content stringlengths 23 1.05M |
|---|
// 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.Threading.Tasks;
namespace Microsoft.MobileBlazorBindings.Authentication
{
/// <summary>
/// Represents a contract for services that perform authentication operations for a Mobile Blazor Bindings application.
/// </summary>
public interface IAuthenticationService
{
/// <summary>
/// Signs in a user.
/// </summary>
Task SignIn();
/// <summary>
/// Signs in a user, using the specified options.
/// </summary>
/// <param name="signInOptions">The sign in options to use.</param>
Task SignIn(SignInOptions signInOptions);
/// <summary>
/// Signs out a user.
/// </summary>
Task SignOut();
}
}
|
using UnityEngine;
using System;
namespace Yolo
{
public class SizeConfig : MonoBehaviour
{
[HideInInspector]
public event EventHandler<ResizeEventArgs> RaiseResizeEvent;
[SerializeField]
int imageWidth = 416;
Size size;
public Size Initialize()
{
size = new Size(Screen.width, Screen.height, imageWidth);
return size;
}
// void Update()
// {
// print(Screen.width);
// if (size.Screen.x != Screen.width || size.Screen.y != Screen.height)
// {
// size = new Size(Screen.width, Screen.height, imageWidth);
// OnRaiseResizeEvent(new ResizeEventArgs(size));
// }
// }
void OnRaiseResizeEvent(ResizeEventArgs e)
{
EventHandler<ResizeEventArgs> handler = RaiseResizeEvent;
if (handler != null)
{
handler(this, e);
}
}
}
public class Size
{
public Vector2 Screen { get; private set; }
public Vector2Int Image { get; private set; }
public float Factor { get; private set; }
public Size(float screenWidth, float screenHeight, int imageWidth)
{
Screen = new Vector2(screenWidth, screenHeight);
Factor = screenWidth / (float)imageWidth;
Image = new Vector2Int(imageWidth, Mathf.RoundToInt(screenHeight / Factor));
}
public override string ToString()
{
return string.Format("Size Screen:{0} Image:{1} Factor:{2}", Screen, Image, Factor);
}
}
public class ResizeEventArgs : EventArgs
{
public Size Size { get; private set; }
public ResizeEventArgs(Size size)
{
Size = size;
}
}
public interface IResizable
{
void SetSize(Size size);
}
} |
using LanguageExt;
using MediatR;
namespace ErsatzTV.Application.Watermarks.Queries
{
public record GetWatermarkById(int Id) : IRequest<Option<WatermarkViewModel>>;
}
|
namespace DgInitEFCore.Configuration.Startup
{
/// <summary>
/// Used to provide a way to configure modules.
/// Create entension methods to this class to be used over <see cref="IAbpStartupConfiguration.Modules"/> object.
/// </summary>
public interface IModuleConfigurations
{
/// <summary>
/// Gets the ABP configuration object.
/// </summary>
IAbpStartupConfiguration AbpConfiguration { get; }
}
} |
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Advanced.CMS.ExternalReviews.ReviewLinksRepository;
using EPiServer;
using EPiServer.Core;
using EPiServer.Security;
using Microsoft.Extensions.DependencyInjection;
using TestSite.Models;
using Xunit;
namespace Advanced.CMS.AdvancedReviews.IntegrationTests.Tests
{
[Collection(IntegrationTestCollectionWithPinSecurity.Name)]
public class SinglePageWithPinSecurityTests : IClassFixture<CommonFixture>
{
private readonly SiteFixtureWithPinSecurity _siteFixture;
private readonly IContentRepository _contentRepository;
public SinglePageWithPinSecurityTests(SiteFixtureWithPinSecurity siteFixture)
{
_siteFixture = siteFixture;
_contentRepository = siteFixture.Services.GetService<IContentRepository>();
}
[Fact]
public async Task When_PinSecurity_Enabled_Login_Screen_Is_Shown()
{
var page = _contentRepository.GetDefault<StandardPage>(ContentReference.StartPage);
page.PageName = "test page";
var contentLink = _contentRepository.Save(page, AccessLevel.NoAccess);
var reviewLinksRepository =
_siteFixture.Services.GetRequiredService<IExternalReviewLinksRepository>();
reviewLinksRepository.GetLinksForContent(contentLink, null);
var link = reviewLinksRepository.AddLink(contentLink, false, TimeSpan.FromDays(1), null);
reviewLinksRepository.UpdateLink(link.Token, DateTime.Now.AddDays(1), "123", null, null);
var message = new HttpRequestMessage(HttpMethod.Get, link.LinkUrl);
var response = await _siteFixture.Client.SendAsync(message);
var text = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("Go", text);
//TODO: test failing login scenario
//TODO: test success login scenario
}
}
}
|
using System;
using System.Collections;
using UnityEngine;
using DG.Tweening;
public class AudioController : MonoBehaviour
{
public AudioSource BackgroundAudio;
public AudioClip GenericClickSound;
public AudioClip ArrowClickSound;
public AudioClip SmallClickSound;
public AudioClip NotificationSound;
public AudioClip HomeBackgroundAudio;
public AudioClip GameBackgroundAudio;
public bool IsHomeEnvironment = false;
public bool IsGameEnvironment = false;
private VolumeController _VolumeController;
private float _UserPresentDelay = 1.0f;
private bool _IsApplicationQuitting;
private bool _isCurHome = true;
private AudioSource _source;
[HideInInspector]
public enum AudioClips
{
GenericClick,
ArrowClick,
SmallClick,
Notification
}
void Awake()
{
_source = gameObject.AddComponent<AudioSource>();
_source.playOnAwake = false;
_VolumeController = GetComponentInChildren<VolumeController>();
if (BackgroundAudio != null)
{
SetBackgroundPlaying(UserPresenceController.Instance.IsMounted && _VolumeController.IsAudioOn);
}
if (IsGameEnvironment && GameBackgroundAudio)
{
BackgroundAudio.clip = GameBackgroundAudio;
BackgroundAudio.volume = 0.0f;
BackgroundAudio.Play();
BackgroundAudio.DOFade(1.0f, 2.0f);
}
}
void OnEnable()
{
_VolumeController.AudioStatusChanged += VolumeController_AudioStatusChanged;
UserPresenceController.Instance.PresenceChanged += Instance_PresenceChanged;
}
void OnDisable()
{
if (!_IsApplicationQuitting)
{
_VolumeController.AudioStatusChanged -= VolumeController_AudioStatusChanged;
UserPresenceController.Instance.PresenceChanged -= Instance_PresenceChanged;
}
}
/// <summary>
/// check to see if we're in a channel in order to modify the background music
/// </summary>
/// <param name="isHome">If set to <c>true</c> is home.</param>
void OnDrawTilesComplete(bool isHome)
{
if (BackgroundAudio == null)
return;
AudioClip newAudioClip;
//only affect these in the home environ
if (IsHomeEnvironment)
{
newAudioClip = HomeBackgroundAudio;
if (newAudioClip != BackgroundAudio.clip)
{
BackgroundAudio.clip = newAudioClip;
BackgroundAudio.Play();
BackgroundAudio.volume = 0.0f;
BackgroundAudio.DOFade(1.0f, 2.0f);
}
}
}
void EventManager_OnBackgroundAudioTrigger(string audioStr, bool isHome)
{
if (BackgroundAudio == null)
return;
//only play in our home environment
if (IsHomeEnvironment)
{
//if we have a value for our background audio, respect it
if (!String.IsNullOrEmpty(audioStr))
{
string clipName = audioStr + "BackgroundAudio";
try
{
AudioClip newAudioClip = (AudioClip)this.GetType().GetField(clipName).GetValue(this);
NewBackgroundAudio(newAudioClip);
}
catch (Exception ex)
{
Debug.LogWarning("Error playing background audio clip: " + ex.ToString());
}
}
else
{
//no value set for background audio, use defaults
NewBackgroundAudio(HomeBackgroundAudio);
}
}
}
void NewBackgroundAudio(AudioClip newAudioClip)
{
if (newAudioClip != null)
{
//only change our audio clip if it's not already playing
if (newAudioClip != BackgroundAudio.clip)
{
BackgroundAudio.clip = newAudioClip;
BackgroundAudio.Play();
BackgroundAudio.volume = 0.0f;
BackgroundAudio.DOFade(1.0f, 2.0f);
}
}
}
/// <summary>
/// we are switching to consumption, fade out the background audio if available
/// </summary>
void EventManager_OnSwitchToConsumption()
{
if (BackgroundAudio == null)
return;
if (IsHomeEnvironment)
{
BackgroundAudio.DOFade(0.0f, 0.6f);
}
}
private void OnApplicationQuit()
{
_IsApplicationQuitting = true;
}
private void Instance_PresenceChanged(object sender, UserPresenceEventArgs e)
{
if (BackgroundAudio == null)
return;
if (e.IsPresent)
{
StartCoroutine(DelayAudioStart(e.IsPresent));
}
else
{
SetBackgroundPlaying(e.IsPresent);
}
}
private void VolumeController_AudioStatusChanged(object sender, AudioStatusEventArgs e)
{
SetBackgroundPlaying(e.IsAudioOn);
}
IEnumerator DelayAudioStart(bool isAudioOn)
{
yield return new WaitForSeconds(_UserPresentDelay);
SetBackgroundPlaying(isAudioOn);
}
public void SetBackgroundPlaying(bool isAudioOn)
{
if (BackgroundAudio == null)
return;
if (isAudioOn == BackgroundAudio.isPlaying)
return;
if (isAudioOn)
{
BackgroundAudio.Play();
Debug.Log ("play the background audio whatever it is");
}
else
{
BackgroundAudio.Pause();
Debug.Log ("pause backgroudn audio");
}
}
public void PlayAudio(AudioClips curAudioClip)
{
switch (curAudioClip)
{
case AudioClips.GenericClick:
PlayAudioClip(GenericClickSound);
break;
case AudioClips.ArrowClick:
PlayAudioClip(ArrowClickSound);
break;
case AudioClips.SmallClick:
PlayAudioClip(SmallClickSound);
break;
case AudioClips.Notification:
PlayAudioClip(NotificationSound);
break;
}
}
public void PlayAudioClip(AudioClip audioClip)
{
if (audioClip != null)
{
if (_source != null)
{
_source.clip = audioClip;
_source.PlayOneShot(audioClip);
}
}
}
}
|
namespace Peach.Core.Debuggers.DebugEngine.Tlb
{
using System;
public enum __MIDL___MIDL_itf_DbgEng_0001_0064_0030
{
DEBUG_SYMINFO_IMAGEHLP_MODULEW64 = 1
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
using CopterDown.Core;
using CopterDown.Core.Entities;
using CopterDown.Core.Enums;
using CopterDown.Enums;
namespace CopterDown.Core
{
public abstract class ABehavior
{
private static int idCounter;
protected Random rnd = new Random();
protected ABehavior(ElementType elemType, State messageListeners)
{
this.BehState = BehaviorState.ACTIVE_ALL;
this.Id = idCounter++;
this.ElemType = elemType;
this.MessageListeners = messageListeners;
}
public ElementType ElemType { get; private set; }
public int Id { get; protected set; }
public BehaviorState BehState { get; set; }
public State MessageListeners { get; protected set; }
public GameObject GameObject { get; set; }
public abstract void OnMessage(Message msg);
public abstract void Update(TimeSpan delta, TimeSpan absolute);
protected Message SendMessage(State traverse, int action, object data)
{
var msg = new Message(ElemType, traverse, action, SenderType.BEHAVIOR, Id, data);
GameObject.SendMessage(msg);
return msg;
}
protected Message SendMessage(int traverse, int action, object data)
{
var msg = new Message(ElemType, traverse, action, SenderType.BEHAVIOR, Id, data);
GameObject.SendMessage(msg);
return msg;
}
}
}
|
using AutoMocker.PrimitiveFactories.Abstract;
using AutoMocker.Utils;
namespace AutoMocker.PrimitiveFactories
{
public class DecimalFactory : IPrimitiveFactory<decimal>
{
public decimal Create()
{
byte scale = (byte)RandomUtil.Instance.Next(29);
bool sign = RandomUtil.Instance.Next(2) == 1;
return new decimal(GenerateInt32(),
GenerateInt32(),
GenerateInt32(),
sign,
scale);
}
private int GenerateInt32()
{
int firstBits = RandomUtil.Instance.Next(0, 1 << 4) << 28;
int lastBits = RandomUtil.Instance.Next(0, 1 << 28);
return firstBits | lastBits;
}
}
}
|
namespace ValidationsTests
{
class TestClass
{
private readonly int _i;
public TestClass(int i) => _i = i;
public int I { get => _i; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DamageSplasher : MonoBehaviour
{
private Image damageSprite;
private Color spriteColor;
void Start()
{
damageSprite = GetComponent<Image>();
spriteColor = new Color(0, 0, 0, 0);
damageSprite.color = spriteColor;
}
public void SplashDamage(int magnitude)
{
if (magnitude == 100)
{
spriteColor = new Color(1, 1, 1, 1);
damageSprite.color = spriteColor;
return;
}
StartCoroutine(SplashAndFade());
}
private IEnumerator SplashAndFade()
{
yield return null;
}
}
|
namespace CacheConsumer.Controllers
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly IDistributedCache cache;
public ValuesController(IDistributedCache cache)
{
this.cache = cache;
}
// GET api/values
[HttpGet]
public async Task<ActionResult<IEnumerable<string>>> Get()
{
var values = ( await this.cache.GetAsync("Values") ).FromByteArray<List<string>>();
return values ?? new List<string>();
}
// GET api/values/5
[HttpGet("{id}")]
public async Task<ActionResult<string>> Get(int id)
{
var values = ( await this.cache.GetAsync("Values") ).FromByteArray<List<string>>();
if (values?.Count > id+1)
{
return values.ElementAt(id);
}
return NotFound();
}
// POST api/values
[HttpPost]
public async Task Post([FromBody] string value)
{
var values = (await this.cache.GetAsync("Values")).FromByteArray<List<string>>();
if (values == null)
{
values = new List<string>();
}
values.Add(value);
await this.cache.SetAsync("Values", values.ToByteArray());
}
// PUT api/values/5
[HttpPut("{id}")]
public async Task Put(int id, [FromBody] string value)
{
var values = ( await this.cache.GetAsync("Values") ).FromByteArray<List<string>>();
if (values?.Count() > id+1)
{
values[id] = value;
await this.cache.SetAsync("Values", values.ToByteArray());
}
}
// DELETE api/values/5
[HttpDelete("{id}")]
public async Task Delete(int id)
{
var values = ( await this.cache.GetAsync("Values") ).FromByteArray<List<string>>();
if (values?.Count() > id+1)
{
values.RemoveAt(id);
await this.cache.SetAsync("Values", values.ToByteArray());
}
}
}
}
|
using EasyPost;
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace EasyPostTest {
[TestClass]
public class CustomsInfoTest {
[TestInitialize]
public void Initialize() {
ClientManager.SetCurrent("cueqNZUb3ldeWTNX7MU3Mel8UXtaAMUi");
}
[TestMethod]
public void TestCreateAndRetrieve() {
Dictionary<string, object> item = new Dictionary<string, object>() {
{"description", "TShirt"}, {"quantity", 1}, {"weight", 8}, {"origin_country", "US"}
};
CustomsInfo info = CustomsInfo.Create(new Dictionary<string, object>() {
{"customs_certify", true}, {"eel_pfc", "NOEEI 30.37(a)"},
{"customs_items", new List<Dictionary<string, object>>() {item}}
});
CustomsInfo retrieved = CustomsInfo.Retrieve(info.id);
Assert.AreEqual(info.id, retrieved.id);
Assert.IsNotNull(retrieved.customs_items);
}
[TestMethod]
public void TestCreateWithIResource() {
CustomsItem item = new CustomsItem() { description = "description" };
CustomsInfo info = CustomsInfo.Create(
new Dictionary<string, object>() {
{ "customs_certify", true },
{ "eel_pfc", "NOEEI 30.37(a)" },
{ "customs_items", new List<IResource>() { item } }
}
);
Assert.IsNotNull(info.id);
Assert.AreEqual(info.customs_items.Count, 1);
Assert.AreEqual(info.customs_items[0].description, item.description);
}
}
} |
@model FileTypeViewModel
@{
Layout = "_FileTypes.cshtml";
}
<fieldset>
<legend>Edit File Type</legend>
@using (Html.BeginForm())
{
@Html.Partial("_FileType")
}
</fieldset> |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pet : MonoBehaviour
{
[SerializeField] private float spawnRate = 0.10f;
[SerializeField] private float catchRate = 0.10f;
[SerializeField] private int attack = 0;
[SerializeField] private int defense = 0;
[SerializeField] private int hp = 10;
private void Start()
{
DontDestroyOnLoad(this);
}
public float SpawnRate
{
get { return spawnRate; }
}
public float CatchRate
{
get { return catchRate; }
}
public int Attack
{
get { return attack; }
}
public int Defense
{
get { return defense; }
}
public int Hp
{
get { return hp; }
}
private void OnMouseDown()
{
PocketPetsSceneManager[] managers = FindObjectsOfType<PocketPetsSceneManager>();
foreach (PocketPetsSceneManager pocketPetsSceneManager in managers)
{
if (pocketPetsSceneManager.gameObject.activeSelf)
{
pocketPetsSceneManager.petTapped(this.gameObject);
}
}
{
}
}
}
|
using System.Collections.Generic;
namespace CarRental.Domain.Entities
{
public class CarModel : BaseEntity
{
public string Name { get; set; }
public CarBrand Brand { get; set; }
public VehicleType Type { get; set; }
public bool HasAutomaticTransmission { get; set; }
public bool HasAirConditioner { get; set; }
public bool HasGps { get; set; }
public int SitsNumber { get; set; }
public int DoorsNumber { get; set; }
public int SuitcasesNumber { get; set; }
public bool IsPremium { get; set; }
public int CarBrandId { get; set; }
public int VehicleTypeId { get; set; }
public ICollection<Car> Cars { get; set; }
}
}
|
namespace Cloud.Governance.Samples.Sdk
{
#region using directives
using System;
using AvePoint.GA.WebAPI;
#endregion using directives
/// <summary>
/// GaoApiClassFixtrue is a global initial class for GaoApi client context initializaion.
/// </summary>
public class GaoApiClassFixtrue
{
public GaoApiClassFixtrue()
{
this.InitStatus = true;
GaoApi.Init(Region.SoutheastAsia, "baron@baron.space", "baron@baron.space");
this.ExecutionCount++;
}
public Boolean InitStatus { get; }
public Int32 ExecutionCount { get; }
}
} |
using System;
using System.Collections;
using System.Reflection;
namespace Moq.Sdk
{
/// <summary>
/// Matches any argument with a given type
/// including <see langword="null"/> if the type is a reference type
/// or a nullable value type.
/// </summary>
public class AnyMatcher : IArgumentMatcher, IEquatable<AnyMatcher>, IStructuralEquatable
{
TypeInfo info;
bool isValueType;
bool isNullable;
public AnyMatcher(Type argumentType)
{
ArgumentType = argumentType;
info = argumentType.GetValueTypeInfo();
isValueType = info.IsValueType;
isNullable = isValueType && info.IsGenericType &&
argumentType.GetGenericTypeDefinition() == typeof(Nullable<>);
}
/// <summary>
/// Gets the type of the argument this matcher supports.
/// </summary>
public Type ArgumentType { get; }
/// <summary>
/// Evaluates whether the given value matches this instance.
/// </summary>
public bool Matches(object value)
{
// Non-nullable value types never match against a null value.
if (isValueType && !isNullable && value == null)
return false;
return value == null || info.IsAssignableFrom(value.GetType().GetTypeInfo());
}
public override string ToString() => "Any<" + Stringly.ToTypeName(ArgumentType) + ">";
#region Equality
public bool Equals(AnyMatcher other) => Equals(other);
public bool Equals(object other, IEqualityComparer comparer) => Equals(other);
public int GetHashCode(IEqualityComparer comparer) => GetHashCode();
#endregion
}
}
|
using Attributes;
using System;
using System.Collections.Generic;
using System.Threading;
namespace TestProject1
{
public class SimpleTests
{
[Test(Ignore = "ignore")]
public void IgnoredTest()
{
}
public void WithoutAttributeTest()
{
}
[Test]
public void Test()
{
Thread.Sleep(10);
}
[Test(Expected = typeof(IndexOutOfRangeException))]
public void TestWithExpectedException()
{
var array = new int[1];
array[1] = 0;
}
[Test]
public void TestWithException()
{
List<int> list = null;
list.Add(0);
}
[Test(Expected = typeof(ArgumentNullException))]
public void TestWithUnexpectedException()
{
throw new DivideByZeroException();
}
[Test(Expected = typeof(NullReferenceException))]
public void TestNotThrowingException()
{
}
}
}
|
namespace Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.SelfDiagnostics
{
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class MemoryMappedFileHandlerTest
{
public static readonly byte[] MessageOnNewFile = MemoryMappedFileHandler.MessageOnNewFile;
[TestMethod]
public void MemoryMappedFileHandler_Success()
{
string filePath;
var fileSize = 1024;
using (var handler = new MemoryMappedFileHandler())
{
handler.CreateLogFile(".", fileSize);
filePath = handler.CurrentFilePath;
}
var actualBytes = ReadFile(filePath, MessageOnNewFile.Length);
CollectionAssert.AreEqual(MessageOnNewFile, actualBytes);
}
[TestMethod]
public void MemoryMappedFileHandler_Circular_Success()
{
var fileSize = 1024;
var buffer = new byte[1024];
var messageToOverflow = Encoding.UTF8.GetBytes("1234567");
var expectedBytesAtEnd = Encoding.UTF8.GetBytes("1234");
var expectedBytesAtStart = Encoding.UTF8.GetBytes("567cessfully opened file.\n");
string filePath;
using (var handler = new MemoryMappedFileHandler())
{
handler.CreateLogFile(".", fileSize);
handler.Write(buffer, fileSize - MessageOnNewFile.Length - expectedBytesAtEnd.Length);
handler.Write(messageToOverflow, messageToOverflow.Length);
filePath = handler.CurrentFilePath;
}
var actualBytes = ReadFile(filePath, buffer.Length);
CollectionAssert.AreEqual(expectedBytesAtStart, SubArray(actualBytes, 0, expectedBytesAtStart.Length));
CollectionAssert.AreEqual(expectedBytesAtEnd, SubArray(actualBytes, actualBytes.Length - expectedBytesAtEnd.Length, expectedBytesAtEnd.Length));
}
private static byte[] ReadFile(string filePath, int byteCount)
{
byte[] actualBytes = new byte[byteCount];
using (var file = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
file.Read(actualBytes, 0, byteCount);
}
return actualBytes;
}
private static byte[] SubArray(byte[] array, int offset, int length)
{
byte[] result = new byte[length];
Array.Copy(array, offset, result, 0, length);
return result;
}
}
}
|
using System;
using System.Windows.Controls;
namespace MaterialDesignThemes.Wpf
{
internal class ComboBoxAssistManagedOverlayInfo
{
public ComboBoxAssistManagedOverlayInfo(ComboBox owner, TextBox originalTextBox, TextBox cloneTextBox)
{
if (owner == null) throw new ArgumentNullException(nameof(owner));
if (originalTextBox == null) throw new ArgumentNullException(nameof(originalTextBox));
if (cloneTextBox == null) throw new ArgumentNullException(nameof(cloneTextBox));
Owner = owner;
OriginalTextBox = originalTextBox;
CloneTextBox = cloneTextBox;
}
public ComboBox Owner { get; }
public TextBox OriginalTextBox { get; }
public TextBox CloneTextBox { get; }
}
} |
using System.Collections.Generic;
using System.Linq;
using System.Windows.Automation;
using Uial.Contexts.Windows;
namespace Uial.Interactions.Windows
{
public class Resize : AbstractPatternInteraction<TransformPattern>, IInteraction
{
public const string Key = "Resize";
public override string Name => Key;
protected override AutomationPattern AutomationPattern => TransformPattern.Pattern;
private double Width { get; set; }
private double Height { get; set; }
public Resize(IWindowsVisualContext context, double width, double height)
: base(context)
{
Width = width;
Height = height;
}
public override void Do()
{
base.Do();
// TODO: Check that the control can be resized;
Pattern.Resize(Width, Height);
}
public static Resize FromRuntimeValues(IWindowsVisualContext context, IEnumerable<string> paramValues)
{
if (paramValues.Count() != 2)
{
throw new InvalidParameterCountException(2, paramValues.Count());
}
double width = double.Parse(paramValues.ElementAt(0));
double height = double.Parse(paramValues.ElementAt(1));
return new Resize(context, width, height);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using dal.Models.Entities;
using dal.Services.Abstract;
using webapi.Infrastructure.Auth;
using webapi.Models.Data;
namespace webapi.Controllers
{
public class UserController : BaseController
{
readonly IUserService _userService;
public UserController(IUserService userService)
{
_userService = userService;
}
[HttpPost]
[AllowAnonymous]
[Route("api/user/signUp")]
public IHttpActionResult SignUp(SignUp signUp)
{
if (_userService.ExistUserName(signUp.UserName))
{
return Content(HttpStatusCode.BadRequest, "Login is exist.");
}
if (_userService.ExistEmail(signUp.Email))
{
return Content(HttpStatusCode.BadRequest, "Email is exist.");
}
if (signUp.Password != signUp.PasswordConfirm)
{
return Content(HttpStatusCode.BadRequest, "Password is not match");
}
var user = new Infrastructure.Auth.User();
user.UserName = signUp.UserName;
user.Email = signUp.Email;
user.Name = signUp.Name;
user.ListRoles = new List<Common.Enum.Role> { Common.Enum.Role.Customer };
user.Status = Common.Enum.Status.Active;
user.Password = PasswordHash.GetPass(signUp.Password);
user.Id = _userService.Create(user);
var settings = new UserSettings();
settings.UserId = user.Id;
settings.Status = Common.Enum.Status.Active.ToString();
settings.Id = _userService.CreateUserSettings(settings);
return Ok(new { data = "OK" });
}
[HttpPost]
[AllowAnonymous]
[Route("api/user/existData")]
public IHttpActionResult ExistData(UserExists dealerExists)
{
var exist = false;
var message = string.Empty;
var existUserName = _userService.ExistUserName(dealerExists.UserName);
if (existUserName)
{
exist = true;
message += "Login is exist.<br>";
}
var existEmail = _userService.ExistEmail(dealerExists.Email);
if (existEmail)
{
exist = true;
message += "Email is exist.<br>";
}
return Ok(new
{
data = new
{
exist,
message
}
});
}
[HttpPost]
[AllowAnonymous]
[Route("api/user/resetPassword")]
public IHttpActionResult ResetPassword(ResetPassword resetPassword)
{
if (resetPassword.Key != "123")
{
return Content(HttpStatusCode.Forbidden, "Code is wrong");
}
if (resetPassword.Password != resetPassword.PasswordConfirm)
{
return Content(HttpStatusCode.Forbidden, "Password is not matched");
}
var user = _userService.GetByUserNameActive(resetPassword.UserName);
user.Password = PasswordHash.GetPass(resetPassword.Password);
_userService.UpdatePassword(user);
return Ok(new
{
data = "Ok"
});
}
}
}
|
// <copyright file="BufferMetadata.cs" company="Techyian">
// Copyright (c) Ian Auty and contributors. All rights reserved.
// Licensed under the MIT License. Please see LICENSE.txt for License info.
// </copyright>
namespace MMALSharp.Common
{
/// <summary>
/// This class contains metadata for a MMAL Buffer header.
/// </summary>
public class BufferMetadata
{
/// <summary>
/// The buffer represents the end of stream.
/// </summary>
public bool Eos { get; set; }
/// <summary>
/// The buffer contains IFrame data.
/// </summary>
public bool IFrame { get; set; }
}
}
|
namespace Bonsai.Vision.Design
{
public class IplImageOutputQuadrangleEditor : IplImageQuadrangleEditor
{
public IplImageOutputQuadrangleEditor()
: base(DataSource.Output)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Markup;
using System.Windows;
using System.Reflection;
using System.Globalization;
using System.Windows.Data;
using System.ComponentModel;
using System.Threading;
using System.Windows.Threading;
using System.Resources;
namespace More.Net.Windows.Localization
{
/// <summary>
///
/// </summary>
public abstract class LocalizedPropertyBase
{
/// <summary>
/// The convert to use to convert the retrieved resource to a value suitable
/// for the property.
/// </summary>
public IValueConverter Converter { get; set; }
/// <summary>
/// The parameter to pass to the converter.
/// </summary>
public Object ConverterParameter { get; set; }
/// <summary>
/// Indicates if the object to the property belongs has been garbage collected.
/// </summary>
public Boolean IsAlive
{
get
{
return target.IsAlive;
}
}
/// <summary>
/// Indicates if the object is in design mode.
/// </summary>
public Boolean IsInDesignMode
{
get
{
DependencyObject target = Target;
return
target != null &&
DesignerProperties.GetIsInDesignMode(target);
}
}
/// <summary>
/// The object to which the property belongs.
/// </summary>
public DependencyObject Target
{
get
{
return (DependencyObject)target.Target;
}
}
public LocalizedPropertyBase(DependencyObject target)
{
if (target == null)
throw new ArgumentNullException("target");
this.target = new WeakReference(target);
}
public ResourceManager GetResourceManager()
{
DependencyObject target = Target;
if (target == null)
return null;
if (target.CheckAccess() == true)
return LocalizationScope.GetResourceManager(target);
else
return target.Dispatcher.Invoke(() => LocalizationScope.GetResourceManager(target));
}
public CultureInfo GetCulture()
{
DependencyObject target = Target;
if (target == null)
return null;
if (target.CheckAccess() == true)
return LocalizationScope.GetCulture(target);
else
return target.Dispatcher.Invoke(() => LocalizationScope.GetCulture(target));
}
public CultureInfo GetDesignCulture()
{
DependencyObject target = Target;
if (target == null)
return null;
if (target.CheckAccess() == true)
return LocalizationScope.GetDesignCulture(target);
else
return target.Dispatcher.Invoke(() => LocalizationScope.GetDesignCulture(target));
}
public abstract Object GetValue();
public abstract void SetValue(Object value);
public abstract Type GetValueType();
private readonly WeakReference target;
}
public class LocalizedDependencyProperty : LocalizedPropertyBase
{
public override Object GetValue()
{
DependencyObject target = Target;
if (target == null)
return null;
if (target.CheckAccess() == true)
return target.GetValue(property);
else
return target.Dispatcher.Invoke(() => target.GetValue(property));
}
public override void SetValue(Object value)
{
DependencyObject target = Target;
if (target == null)
return;
if (target.CheckAccess() == true)
target.SetValue(property, value);
else
target.Dispatcher.Invoke(() => target.SetValue(property, value));
}
/// <summary>
/// Gets the type of the value of the property.
/// </summary>
/// <returns>
/// The type of the value of the property.
/// </returns>
public override Type GetValueType()
{
return property.PropertyType;
}
public LocalizedDependencyProperty(DependencyObject target, DependencyProperty property) :
base(target)
{
this.property = property;
}
private readonly DependencyProperty property;
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
namespace ConsoleApp1
{
public class TwoDimArrayInts
{
public static void TwoDimArrayIntsT()
{
int e = 10;
int ex0 = 3;
int ex1 = 5;
int[,] b = new int[ex0, ex1];
for (int i = 0; i < ex0; ++i)
for (int j = 0; j < ex1; ++j)
b[i, j] = (i + 1) * (j + 1);
Campy.Parallel.For(5, d =>
{
b[d % 3, d] = 33 + d;
});
if (b[0, 0] != 33) throw new Exception();
if (b[1, 1] != 34) throw new Exception();
if (b[2, 2] != 35) throw new Exception();
if (b[0, 3] != 36) throw new Exception();
if (b[1, 4] != 37) throw new Exception();
}
}
class Program
{
static void StartDebugging()
{
Campy.Utils.Options.Set("graph_trace");
Campy.Utils.Options.Set("name_trace");
Campy.Utils.Options.Set("cfg_construction_trace");
Campy.Utils.Options.Set("dot_graph");
Campy.Utils.Options.Set("jit_trace");
Campy.Utils.Options.Set("memory_trace");
Campy.Utils.Options.Set("ptx_trace");
Campy.Utils.Options.Set("state_computation_trace");
Campy.Utils.Options.Set("continue_with_no_resolve");
Campy.Utils.Options.Set("copy_trace");
Campy.Utils.Options.Set("runtime_trace");
}
static void Main(string[] args)
{
StartDebugging();
TwoDimArrayInts.TwoDimArrayIntsT();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TreeViewDemo.DataModel;
using System.Collections.ObjectModel;
namespace TreeViewDemo.LoadOnDemand.ViewModel
{
class CountryViewModel
{
readonly ReadOnlyCollection<RegionViewModel> _regions;
public CountryViewModel(Region[] regions)
{
_regions = new ReadOnlyCollection<RegionViewModel>(
(from region in regions
select new RegionViewModel(region))
.ToList());
}
public ReadOnlyCollection<RegionViewModel> Regions
{
get { return _regions; }
}
}
}
|
using Newtonsoft.Json;
using System.Collections.Generic;
namespace RaskulPool.Models
{
public partial class Payments
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("pending")]
public Pending Pending { get; set; }
[JsonProperty("payments")]
public List<object> PaymentPayments { get; set; }
}
} |
// 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 Microsoft.AspNetCore.Components;
using System.Runtime.ExceptionServices;
using System.Threading.Tasks;
using WindowsDispatcher = System.Windows.Threading.Dispatcher;
namespace PeakSWC.RemoteBlazorWebView.Wpf
{
internal sealed class WpfDispatcher : Dispatcher
{
private readonly WindowsDispatcher _windowsDispatcher;
public WpfDispatcher(WindowsDispatcher windowsDispatcher)
{
_windowsDispatcher = windowsDispatcher ?? throw new ArgumentNullException(nameof(windowsDispatcher));
}
private static Action<Exception> RethrowException = exception =>
ExceptionDispatchInfo.Capture(exception).Throw();
public override bool CheckAccess()
=> _windowsDispatcher.CheckAccess();
public override async Task InvokeAsync(Action workItem)
{
try
{
if (_windowsDispatcher.CheckAccess())
{
workItem();
}
else
{
await _windowsDispatcher.InvokeAsync(workItem);
}
}
catch (Exception ex)
{
// TODO: Determine whether this is the right kind of rethrowing pattern
// You do have to do something like this otherwise unhandled exceptions
// throw from inside Dispatcher.InvokeAsync are simply lost.
_ = _windowsDispatcher.BeginInvoke(RethrowException, ex);
throw;
}
}
public override async Task InvokeAsync(Func<Task> workItem)
{
try
{
if (_windowsDispatcher.CheckAccess())
{
await workItem();
}
else
{
await _windowsDispatcher.InvokeAsync(workItem);
}
}
catch (Exception ex)
{
// TODO: Determine whether this is the right kind of rethrowing pattern
// You do have to do something like this otherwise unhandled exceptions
// throw from inside Dispatcher.InvokeAsync are simply lost.
_ = _windowsDispatcher.BeginInvoke(RethrowException, ex);
throw;
}
}
public override async Task<TResult> InvokeAsync<TResult>(Func<TResult> workItem)
{
try
{
if (_windowsDispatcher.CheckAccess())
{
return workItem();
}
else
{
return await _windowsDispatcher.InvokeAsync(workItem);
}
}
catch (Exception ex)
{
// TODO: Determine whether this is the right kind of rethrowing pattern
// You do have to do something like this otherwise unhandled exceptions
// throw from inside Dispatcher.InvokeAsync are simply lost.
_ = _windowsDispatcher.BeginInvoke(RethrowException, ex);
throw;
}
}
public override async Task<TResult> InvokeAsync<TResult>(Func<Task<TResult>> workItem)
{
try
{
if (_windowsDispatcher.CheckAccess())
{
return await workItem();
}
else
{
return await _windowsDispatcher.InvokeAsync(workItem).Task.Unwrap();
}
}
catch (Exception ex)
{
// TODO: Determine whether this is the right kind of rethrowing pattern
// You do have to do something like this otherwise unhandled exceptions
// throw from inside Dispatcher.InvokeAsync are simply lost.
_ = _windowsDispatcher.BeginInvoke(RethrowException, ex);
throw;
}
}
}
}
|
/*
작성자: 박용준
타이틀: 닷넷세일 - 카테고리 리포지토리 클래스
코멘트: 닷넷세일 - 카테고리 리포지토리 클래스
수정일: 2020-11-01
*/
using Dapper;
using Microsoft.Data.SqlClient;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
namespace DotNetSale.Models
{
public class CategoryRepository : ICategoryRepository
{
private IDbConnection db;
public CategoryRepository()
{
db = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
}
/// <summary>
/// 카테고리(대분류) 등록
/// </summary>
/// <param name="categoryName">카테고리 이름</param>
public void AddCategory(string categoryName)
{
string sql = "Insert Into Categories (CategoryName) Values (@CategoryName);";
db.Execute(sql, new { CategoryName = categoryName });
}
/// <summary>
/// 전체 카테고리 리스트 출력
/// </summary>
/// <returns>전체 카테고리 리스트 출력</returns>
public List<Category> GetAll()
{
string sql = "Select CategoryId, CategoryName From Categories Order By CategoryId Desc";
return db.Query<Category>(sql).ToList();
}
/// <summary>
/// 전체 카테고리 리스트 출력
/// </summary>
/// <returns>전체 카테고리 리스트 출력</returns>
public List<Category> GetCategories()
{
string sql = "Select CategoryId, CategoryName From Categories Order By CategoryId Desc";
return db.Query<Category>(sql).ToList();
}
/// <summary>
/// 전체 카테고리 리스트
/// CategoryListUserControl.ascx에서 사용
/// </summary>
/// <returns>카테고리 리스트</returns>
public SqlDataReader GetProductCategories()
{
#region ADO.NET 클래스 사용
SqlConnection objCon =
new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
objCon.Open();
SqlCommand objCmd = new SqlCommand("ProductCategoryList", objCon);
objCmd.CommandType = CommandType.StoredProcedure;
SqlDataReader result = objCmd.ExecuteReader(CommandBehavior.CloseConnection);
return result;
#endregion
}
}
}
|
using System.Collections.Generic;
namespace MK6.AutomatedTesting.Runner
{
public static class Extensions
{
public static void AddRange<T>(this IList<T> list, IEnumerable<T> newItems)
{
foreach (var newItem in newItems)
{
list.Add(newItem);
}
}
public static IDictionary<TKey, TValue> AddRange<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary,
IEnumerable<KeyValuePair<TKey, TValue>> keyValuePairs)
{
foreach (var keyValuePair in keyValuePairs)
{
dictionary.Add(keyValuePair.Key, keyValuePair.Value);
}
return dictionary;
}
public static IDictionary<TKey, TValue> Add<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary,
KeyValuePair<TKey, TValue> keyValue)
{
dictionary.Add(keyValue);
return dictionary;
}
}
}
|
// 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.IO;
using System.Linq;
using FluentAssertions;
using NuGet.Test.Utility;
using Xunit;
namespace NuGet.Configuration.Test
{
public class CertificateItemTests
{
[Fact]
public void CertificateItem_WithoutFingerprint_Throws()
{
// Arrange
var config = @"
<configuration>
<SectionName>
<certificate hashAlgorithm=""SHA256"" allowUntrustedRoot=""true"" />
</SectionName>
</configuration>";
var nugetConfigPath = "NuGet.Config";
using (var mockBaseDirectory = TestDirectory.Create())
{
SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);
// Act and Assert
var ex = Record.Exception(() => new SettingsFile(mockBaseDirectory));
ex.Should().NotBeNull();
ex.Should().BeOfType<NuGetConfigurationException>();
ex.Message.Should().Be(string.Format("Unable to parse config file because: Missing required attribute 'fingerprint' in element 'certificate'. Path: '{0}'.", Path.Combine(mockBaseDirectory, nugetConfigPath)));
}
}
[Fact]
public void CertificateItem_WithoutHashAlgorithm_Throws()
{
// Arrange
var config = @"
<configuration>
<SectionName>
<certificate fingerprint=""abcdefg"" allowUntrustedRoot=""true"" />
</SectionName>
</configuration>";
var nugetConfigPath = "NuGet.Config";
using (var mockBaseDirectory = TestDirectory.Create())
{
SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);
// Act and Assert
var ex = Record.Exception(() => new SettingsFile(mockBaseDirectory));
ex.Should().NotBeNull();
ex.Should().BeOfType<NuGetConfigurationException>();
ex.Message.Should().Be(string.Format("Unable to parse config file because: Missing required attribute 'hashAlgorithm' in element 'certificate'. Path: '{0}'.", Path.Combine(mockBaseDirectory, nugetConfigPath)));
}
}
[Fact]
public void CertificateItem_WithUnsupportedHashAlgorithm_Throws()
{
// Arrange
var config = @"
<configuration>
<SectionName>
<certificate fingerprint=""abcdefg"" hashAlgorithm=""SHA32"" allowUntrustedRoot=""true"" />
</SectionName>
</configuration>";
var nugetConfigPath = "NuGet.Config";
using (var mockBaseDirectory = TestDirectory.Create())
{
SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);
// Act and Assert
var ex = Record.Exception(() => new SettingsFile(mockBaseDirectory));
ex.Should().NotBeNull();
ex.Should().BeOfType<NuGetConfigurationException>();
ex.Message.Should().Be(string.Format("Unable to parse config file because: Certificate entry has an unsupported hash algorithm: 'SHA32'. Path: '{0}'.", Path.Combine(mockBaseDirectory, nugetConfigPath)));
}
}
[Fact]
public void CertificateItem_WithoutAllowUntrustedRoot_Throws()
{
// Arrange
var config = @"
<configuration>
<SectionName>
<certificate fingerprint=""abcdefg"" hashAlgorithm=""SHA256"" />
</SectionName>
</configuration>";
var nugetConfigPath = "NuGet.Config";
using (var mockBaseDirectory = TestDirectory.Create())
{
SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);
// Act and Assert
var ex = Record.Exception(() => new SettingsFile(mockBaseDirectory));
ex.Should().NotBeNull();
ex.Should().BeOfType<NuGetConfigurationException>();
ex.Message.Should().Be(string.Format("Unable to parse config file because: Missing required attribute 'allowUntrustedRoot' in element 'certificate'. Path: '{0}'.", Path.Combine(mockBaseDirectory, nugetConfigPath)));
}
}
[Fact]
public void CertificateItem_WithChildren_Throws()
{
// Arrange
var config = @"
<configuration>
<SectionName>
<certificate fingerprint=""abcdefg"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""true"">
<add key=""key"" value=""val"" />
</certificate>
</SectionName>
</configuration>";
var nugetConfigPath = "NuGet.Config";
using (var mockBaseDirectory = TestDirectory.Create())
{
SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);
// Act and Assert
var ex = Record.Exception(() => new SettingsFile(mockBaseDirectory));
ex.Should().NotBeNull();
ex.Should().BeOfType<NuGetConfigurationException>();
ex.Message.Should().Be(string.Format("Error parsing NuGet.Config. Element 'certificate' cannot have descendant elements. Path: '{0}'.", Path.Combine(mockBaseDirectory, nugetConfigPath)));
}
}
[Fact]
public void CertificateItem_ParsedCorrectly()
{
// Arrange
var config = @"
<configuration>
<SectionName>
<certificate fingerprint=""abcdefg"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""true"" />
</SectionName>
</configuration>";
var nugetConfigPath = "NuGet.Config";
using (var mockBaseDirectory = TestDirectory.Create())
{
SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);
// Act and Assert
var settingsFile = new SettingsFile(mockBaseDirectory);
var section = settingsFile.GetSection("SectionName");
section.Should().NotBeNull();
section.Items.Count.Should().Be(1);
var item = section.Items.First() as CertificateItem;
var expectedItem = new CertificateItem("abcdefg", Common.HashAlgorithmName.SHA256, allowUntrustedRoot: true);
SettingsTestUtils.DeepEquals(item, expectedItem).Should().BeTrue();
}
}
[Fact]
public void CertificateItem_Update_UpdatesHashAlgorithmCorrectly()
{
// Arrange
var config = @"
<configuration>
<SectionName>
<certificate fingerprint=""abcdefg"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""true"" />
</SectionName>
</configuration>";
var nugetConfigPath = "NuGet.Config";
using (var mockBaseDirectory = TestDirectory.Create())
{
SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);
// Act and Assert
var settingsFile = new SettingsFile(mockBaseDirectory);
settingsFile.TryGetSection("SectionName", out var section).Should().BeTrue();
section.Should().NotBeNull();
section.Items.Count.Should().Be(1);
var item = section.Items.First() as CertificateItem;
var updatedItem = item.Clone() as CertificateItem;
updatedItem.HashAlgorithm = Common.HashAlgorithmName.SHA512;
item.Update(updatedItem);
SettingsTestUtils.DeepEquals(item, updatedItem).Should().BeTrue();
settingsFile.SaveToDisk();
// Assert
var result = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<certificate fingerprint=""abcdefg"" hashAlgorithm=""SHA512"" allowUntrustedRoot=""true"" />
</SectionName>
</configuration>";
Assert.Equal(result.Replace("\r\n", "\n"), File.ReadAllText(Path.Combine(mockBaseDirectory, nugetConfigPath)).Replace("\r\n", "\n"));
}
}
[Fact]
public void CertificateItem_Update_UpdatesAllowUntrustedRootCorrectly()
{
// Arrange
var config = @"
<configuration>
<SectionName>
<certificate fingerprint=""abcdefg"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""true"" />
</SectionName>
</configuration>";
var nugetConfigPath = "NuGet.Config";
using (var mockBaseDirectory = TestDirectory.Create())
{
SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);
// Act and Assert
var settingsFile = new SettingsFile(mockBaseDirectory);
settingsFile.TryGetSection("SectionName", out var section).Should().BeTrue();
section.Should().NotBeNull();
section.Items.Count.Should().Be(1);
var item = section.Items.First() as CertificateItem;
var updatedItem = item.Clone() as CertificateItem;
updatedItem.AllowUntrustedRoot = false;
item.Update(updatedItem);
SettingsTestUtils.DeepEquals(item, updatedItem).Should().BeTrue();
settingsFile.SaveToDisk();
// Assert
var result = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<SectionName>
<certificate fingerprint=""abcdefg"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""false"" />
</SectionName>
</configuration>";
Assert.Equal(result.Replace("\r\n", "\n"), File.ReadAllText(Path.Combine(mockBaseDirectory, nugetConfigPath)).Replace("\r\n", "\n"));
}
}
[Fact]
public void CertificateItem_Equals_WithSameFingerprint_ReturnsTrue()
{
var certificate1 = new CertificateItem("abcdefg", Common.HashAlgorithmName.SHA512);
var certificate2 = new CertificateItem("abcdefg", Common.HashAlgorithmName.SHA256);
certificate1.Equals(certificate2).Should().BeTrue();
}
[Fact]
public void CertificateItem_Equals_WithDifferentFingerprint_ReturnsFalse()
{
var certificate1 = new CertificateItem("abcdefg", Common.HashAlgorithmName.SHA512);
var certificate2 = new CertificateItem("stuvxyz", Common.HashAlgorithmName.SHA512);
certificate1.Equals(certificate2).Should().BeFalse();
}
[Fact]
public void CertificateItem_ElementName_IsCorrect()
{
var certificateItem = new CertificateItem("abcdefg", Common.HashAlgorithmName.SHA512);
certificateItem.ElementName.Should().Be("certificate");
}
[Fact]
public void CertificateItem_Clone_CopiesTheSameItem()
{
// Arrange
var config = @"
<configuration>
<SectionName>
<certificate fingerprint=""abcdefg"" hashAlgorithm=""Sha256"" allowUntrustedRoot=""true"" />
</SectionName>
</configuration>";
var nugetConfigPath = "NuGet.Config";
using (var mockBaseDirectory = TestDirectory.Create())
{
SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);
// Act and Assert
var settingsFile = new SettingsFile(mockBaseDirectory);
settingsFile.TryGetSection("SectionName", out var section).Should().BeTrue();
section.Should().NotBeNull();
section.Items.Count.Should().Be(1);
var item = section.Items.First();
item.IsCopy().Should().BeFalse();
item.Origin.Should().NotBeNull();
var clone = item.Clone();
clone.IsCopy().Should().BeTrue();
clone.Origin.Should().NotBeNull();
SettingsTestUtils.DeepEquals(clone, item).Should().BeTrue();
}
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace GraphQL.Types
{
public class QueryArguments : List<QueryArgument>
{
public QueryArguments(params QueryArgument[] args)
{
AddRange(args);
}
public QueryArguments(IEnumerable<QueryArgument> list)
: base(list)
{
}
public QueryArgument Find(string name)
{
return this.FirstOrDefault(x => x.Name == name);
}
}
}
|
namespace MyWebApp_BikeShop.Services.Buyers
{
using MyWebApp_BikeShop.Services.Buyers.Model;
public interface IBuyerService
{
public bool IsBuyer(string userId);
public void Become(BecomeABuyerServiceModel model);
}
} |
using System.Collections.Generic;
namespace BinBuff.Test
{
class Player : ISerializable
{
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Player) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = playerNum;
hashCode = (hashCode * 397) ^ isAlive.GetHashCode();
hashCode = (hashCode * 397) ^ health.GetHashCode();
hashCode = (hashCode * 397) ^ strength;
return hashCode;
}
}
public int playerNum;
private bool isAlive;
private float health;
private int strength;
public Player()
{
this.playerNum = 0;
this.isAlive = false;
this.health = 0;
this.strength = 0;
}
public Player(int playerNum)
{
this.playerNum = playerNum;
this.isAlive = true;
this.health = 100 * playerNum;
this.strength = 10 * playerNum;
}
public static bool operator ==(Player p1, Player p2)
{
return p1.playerNum == p2.playerNum && p1.isAlive == p2.isAlive && p1.health == p2.health &&
p1.strength == p2.strength;
}
protected bool Equals(Player other)
{
return this == other;
}
public static bool operator !=(Player p1, Player p2)
{
return !(p1 == p2);
}
public void Serialize(BinBuffer binBuffer)
{
binBuffer.Write(playerNum, isAlive, health, strength);
}
public void Deserialize(BinBuffer binBuffer)
{
binBuffer.Read(out playerNum);
binBuffer.Read(out isAlive);
binBuffer.Read(out health);
binBuffer.Read(out strength);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ClickToOpenColorBar : MonoBehaviour {
private GameObject ColorBar;
private HorizontalLayoutGroup layoutGroup;
private bool isColorBarShow = false;
public float minSpacing = -1.83f;
public float smooth = 1;
public float maxSpacing = 0;
private float targetSpacing = 0;
private bool isChanging = false;
public float Unusetime = 0.1f;
private float timer = 0;
// Use this for initialization
void Start () {
ColorBar = transform.Find("ColorBar").gameObject;
ColorBar.SetActive(isColorBarShow);
layoutGroup = ColorBar.GetComponent<HorizontalLayoutGroup>();
}
// Update is called once per frame
private void OnMouseDown()
{
if(timer>Unusetime)
{
isColorBarShow = !isColorBarShow;
if (isColorBarShow)
{
ColorBar.SetActive(true);
targetSpacing = maxSpacing;
}
else
targetSpacing = minSpacing;
isChanging = true;
timer = 0;
}
}
private void Update()
{
timer += Time.deltaTime;
if(isChanging)
{
float spacing;
if (isColorBarShow)
spacing = layoutGroup.spacing + smooth * Time.deltaTime;
else
spacing = layoutGroup.spacing - smooth * Time.deltaTime;
if ((isColorBarShow&&spacing>targetSpacing)||(!isColorBarShow && spacing < targetSpacing))
{
layoutGroup.spacing = targetSpacing;
isChanging = false;
if(!isColorBarShow)
ColorBar.SetActive(false);
return;
}
layoutGroup.spacing = spacing;
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using Steeltoe.Messaging;
using System;
using System.Collections.Concurrent;
namespace Steeltoe.Stream.TestBinder
{
public class OutputDestination : AbstractDestination
{
private BlockingCollection<IMessage> _messages;
public IMessage Receive(long timeout)
{
try
{
_messages.TryTake(out var result, TimeSpan.FromMilliseconds(timeout));
return result;
}
catch (Exception)
{
// Log
}
return null;
}
public IMessage Receive()
{
return Receive(0);
}
protected internal override void AfterChannelIsSet()
{
_messages = new BlockingCollection<IMessage>();
Channel.Subscribe(new MessageHandler(this));
}
private class MessageHandler : IMessageHandler
{
private readonly OutputDestination _outputDestination;
public virtual string ServiceName { get; set; }
public MessageHandler(OutputDestination thiz)
{
_outputDestination = thiz;
ServiceName = GetType().Name + "@" + GetHashCode();
}
public void HandleMessage(IMessage message)
{
_outputDestination._messages.Add(message);
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class PlaySoundOnFirstCollisionWith : MonoBehaviour {
private bool played = false;
public GameObject with;
void Start () {
}
void OnCollisionEnter(Collision collInfo) {
if(played) return;
if(collInfo.collider == null) return;
if(collInfo.collider.gameObject != with) return;
GetComponent<AudioSource>().Play();
played=true;
}
}
|
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
namespace SimpleQA
{
public interface ICommand<TResult>
{
}
public interface ICommandExecuter<TCommand, TResult>
where TCommand : ICommand<TResult>
{
Task<TResult> ExecuteAsync(TCommand command, SimpleQAIdentity user, CancellationToken cancel);
}
}
|
using AutoMapper;
using Store.Domain.DomainModel;
using Store.Infra.MongoDB.DataModels;
namespace Store.Infra.CrossCutting.Mappers;
public class AddressProfile : Profile
{
public AddressProfile()
{
CreateMap<AddressDomain, AddressData>();
CreateMap<AddressData, AddressDomain>();
}
} |
#region
using OStimAnimationTool.Core.Models;
using Prism.Events;
#endregion
namespace OStimAnimationTool.Core.Events
{
public class OpenDatabaseEvent : PubSubEvent<AnimationDatabase>
{
}
}
|
using System.Web.Mvc;
using MaterialCMS.Helpers;
using MaterialCMS.Website.Binders;
using Ninject;
namespace MaterialCMS.Web.Areas.Admin.ModelBinders
{
public class GetUrlGeneratorOptionsTypeModelBinder:MaterialCMSDefaultModelBinder
{
public GetUrlGeneratorOptionsTypeModelBinder(IKernel kernel) : base(kernel)
{
}
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var typeName = GetValueFromContext(controllerContext, "type");
return TypeHelper.GetTypeByName(typeName);
}
}
} |
using AutoMapper;
using EventBus.Messages.Events;
using Ordering.Application.Features.Orders.Commands.CheckoutOrder;
namespace Ordering.Api.Mapping
{
public class OrderMappingProfile:Profile
{
public OrderMappingProfile()
{
CreateMap<BasketCheckoutEvent, CheckoutOrderCommand>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Engine.Application
{
public class Group
{
private readonly Dictionary<object, List<object>> _data = new Dictionary<object, List<object>>();
public void Add(object key, object item)
{
if (!_data.TryGetValue(key, out var lst))
{
lst = new List<object>();
_data[key] = lst;
}
lst.Add(item);
}
public object[] Flatten()
{
return _data.SelectMany(l => l.Value).ToArray();
}
public static Group Create() => new Group();
public static void Add(Group grp, object key, object val)
{
if (grp == null || key == null || val == null)
return;
grp.Add(key, val);
}
public static void AddMany(Group grp, object key, object val)
{
if (grp == null || key == null || val == null)
return;
if (val is IEnumerable<object> arr)
foreach (var a in arr)
grp.Add(key, a);
}
public static object[] Flatten(Group grp)
{
if (grp == null)
return Array.Empty<object>();
return grp.Flatten();
}
public static object[] ToKvArray(Group grp)
{
if (grp == null)
return Array.Empty<object>();
return grp._data.Select(
kv => (object) new Dictionary<string, object>
{
["key"] = kv.Key,
["values"] = (object) kv.Value.ToArray()
}
).ToArray();
}
}
}
|
using Confuser.Core;
using dnlib.DotNet;
using System.Linq;
namespace Confuser.Protections
{
public class AntiWatermarkProtection : Protection
{
public override string Name => "反水印保护(Anti Watermark)";
public override string Description => "此保护去除ProtectedBy水印,使查壳工具无法识别。";
public override string Id => "反水印保护";
public override string FullId => "HoLLy.AntiWatermark";
public override ProtectionPreset Preset => ProtectionPreset.正常保护;
protected override void Initialize(ConfuserContext context) { }
protected override void PopulatePipeline(ProtectionPipeline pipeline)
{
//watermark is added in the inspection stage, this executes right after
pipeline.InsertPostStage(PipelineStage.Inspection, new AntiWatermarkPhase(this));
}
public class AntiWatermarkPhase : ProtectionPhase
{
public override ProtectionTargets Targets => ProtectionTargets.Modules;
public override string Name => "ProtectedBy attribute removal";
public AntiWatermarkPhase(ConfuserComponent parent) : base(parent) { }
protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
{
foreach (var m in parameters.Targets.Cast<ModuleDef>().WithProgress(context.Logger))
{
//look for watermark and remove it
var attr = m.CustomAttributes.Find("ProtectedByAttribute");
if (attr != null)
{
m.CustomAttributes.Remove(attr);
m.Types.Remove((TypeDef)attr.AttributeType);
}
}
}
}
}
}
|
using EPlast.Resources;
using System;
namespace EPlast.BLL.DTO.ActiveMembership
{
public class EntryAndOathDatesDTO
{
private DateTime _dateOath;
private DateTime _dateEntry;
public string UserId { get; set; }
public int Id { get; set; }
public DateTime DateOath
{
get => _dateOath;
set
{
if (value == default)
{
_dateOath = value;
return;
}
if (value < AllowedDates.LowLimitDate)
throw new ArgumentException($"The oath date cannot be earlier than {AllowedDates.LowLimitDate}");
_dateOath = value;
}
}
public DateTime DateEntry
{
get => _dateEntry;
set
{
if (value == default)
{
_dateEntry = value;
return;
}
if (value < AllowedDates.LowLimitDate)
throw new ArgumentException($"The entry date cannot be earlier than {AllowedDates.LowLimitDate}");
_dateEntry = value;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace BlazorDevToAnalytics.Shared
{
public class StatsArticles
{
public double TotalArticles { get; set; }
public double TotalViews { get; set; }
public double TotalReactions { get; set; }
public double TotalComments { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace P04_AddVAT
{
class AddVAT
{
static void Main(string[] args)
{
Func<double, double> addVAT = n => n += n * 0.2;
var prices = Console.ReadLine()
.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries)
.Select(double.Parse)
.Select(addVAT)
.ToList();
foreach (var item in prices)
{
Console.WriteLine($"{item:f2}");
}
}
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PngDecoder.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
// Implements support for decoding png images.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace OxyPlot
{
using System;
using System.IO;
/// <summary>
/// Implements support for decoding png images.
/// </summary>
public class PngDecoder : IImageDecoder
{
/// <summary>
/// Gets information about the image in the specified byte array.
/// </summary>
/// <param name="bytes">The image data.</param>
/// <returns>An <see cref="OxyImageInfo" /> structure.</returns>
/// <exception cref="System.FormatException">Wrong length of pHYs chunk.</exception>
public OxyImageInfo GetImageInfo(byte[] bytes)
{
var ms = new MemoryStream(bytes);
var inputReader = new BinaryReader(ms);
inputReader.ReadBytes(8); // signature
inputReader.ReadBigEndianUInt32(); // headerLength
inputReader.ReadString(4); // headerType
var width = (int)inputReader.ReadBigEndianUInt32();
var height = (int)inputReader.ReadBigEndianUInt32();
var bitDepth = inputReader.ReadByte();
inputReader.ReadByte(); // colorType
inputReader.ReadByte(); // compressionMethod
inputReader.ReadByte(); // filterMethod
inputReader.ReadByte();
inputReader.ReadBigEndianUInt32(); // headerCRC
double dpix = 96;
double dpiy = 96;
while (true)
{
var length = (int)inputReader.ReadBigEndianUInt32();
var type = inputReader.ReadString(4);
if (type == "IEND")
{
break;
}
switch (type)
{
case "pHYs":
{
if (length != 9)
{
throw new FormatException("Wrong length of pHYs chunk.");
}
var ppux = inputReader.ReadBigEndianUInt32();
var ppuy = inputReader.ReadBigEndianUInt32();
inputReader.ReadByte(); // unit
dpix = ppux * 0.0254;
dpiy = ppuy * 0.0254;
break;
}
default:
{
ms.Position += length;
break;
}
}
// Read CRC
inputReader.ReadBigEndianUInt32();
}
return new OxyImageInfo { Width = width, Height = height, DpiX = dpix, DpiY = dpiy, BitsPerPixel = bitDepth };
}
/// <summary>
/// Decodes an image from the specified byte array.
/// </summary>
/// <param name="bytes">The image data.</param>
/// <returns>The 32-bit pixel data, indexed as [x,y].</returns>
public OxyColor[,] Decode(byte[] bytes)
{
// http://www.w3.org/TR/PNG/
// http://en.wikipedia.org/wiki/Portable_Network_Graphics
var s = new MemoryStream(bytes);
var inputReader = new BinaryReader(s);
var signature = inputReader.ReadBytes(8);
if (signature[0] != 0x89 || signature[1] != 0x50 || signature[2] != 0x4E || signature[3] != 0x47
|| signature[4] != 0x0D || signature[5] != 0x0A || signature[6] != 0x1A || signature[7] != 0x0A)
{
throw new FormatException("Invalid signature.");
}
var headerLength = inputReader.ReadBigEndianUInt32();
if (headerLength != 13)
{
throw new FormatException("Header not supported.");
}
var headerType = inputReader.ReadString(4);
if (headerType != "IHDR")
{
throw new FormatException("Invalid header.");
}
var width = (int)inputReader.ReadBigEndianUInt32();
var height = (int)inputReader.ReadBigEndianUInt32();
var bitDepth = inputReader.ReadByte();
var colorType = (ColorType)inputReader.ReadByte();
var compressionMethod = (CompressionMethod)inputReader.ReadByte();
var filterMethod = (FilterMethod)inputReader.ReadByte();
var interlaceMethod = (InterlaceMethod)inputReader.ReadByte();
inputReader.ReadBigEndianUInt32(); // headerCRC
if (bitDepth != 8)
{
throw new NotImplementedException();
}
if (colorType != ColorType.TrueColorWithAlpha)
{
throw new NotImplementedException();
}
if (compressionMethod != CompressionMethod.Deflate)
{
throw new NotImplementedException();
}
if (filterMethod != FilterMethod.None)
{
throw new NotImplementedException();
}
if (interlaceMethod != InterlaceMethod.None)
{
throw new NotImplementedException();
}
var ms = new MemoryStream();
while (true)
{
var length = (int)inputReader.ReadBigEndianUInt32();
var type = inputReader.ReadString(4);
if (type == "IEND")
{
break;
}
switch (type)
{
case "PLTE":
throw new NotImplementedException();
case "IDAT":
{
inputReader.ReadByte(); // method
inputReader.ReadByte(); // check
var chunkBytes = inputReader.ReadBytes(length - 6);
var expectedCheckSum = inputReader.ReadBigEndianUInt32();
var deflatedBytes = Deflate(chunkBytes);
var actualCheckSum = PngEncoder.Adler32(deflatedBytes);
if (actualCheckSum != expectedCheckSum)
{
throw new FormatException("Invalid checksum.");
}
ms.Write(deflatedBytes, 0, deflatedBytes.Length);
break;
}
default:
{
inputReader.ReadBytes(length);
break;
}
}
inputReader.ReadBigEndianUInt32(); // crc
}
var pixels = new OxyColor[width, height];
ms.Position = 0;
for (int y = height - 1; y >= 0; y--)
{
ms.ReadByte();
for (int x = 0; x < width; x++)
{
var red = (byte)ms.ReadByte();
var green = (byte)ms.ReadByte();
var blue = (byte)ms.ReadByte();
var alpha = (byte)ms.ReadByte();
pixels[x, y] = OxyColor.FromArgb(alpha, red, green, blue);
}
}
/*
var bitReader = new ByteBitReader(ms);
for (int y = 0; y < height; y++)
{
var filterType = bitReader.readByte();
for (int x = 0; x < width; x++)
{
var red = (byte)bitReader.ReadBits(bitDepth);
var green = (byte)bitReader.ReadBits(bitDepth);
var blue = (byte)bitReader.ReadBits(bitDepth);
var alpha = (byte)bitReader.ReadBits(bitDepth);
pixels[x, y] = OxyColor.FromArgb(alpha, red, green, blue);
}
}*/
if (ms.Position != ms.Length)
{
throw new InvalidOperationException();
}
return pixels;
}
/// <summary>
/// Deflates the specified bytes.
/// </summary>
/// <param name="bytes">The bytes.</param>
/// <returns>The deflated bytes.</returns>
private static byte[] Deflate(byte[] bytes)
{
//// http://en.wikipedia.org/wiki/DEFLATE
//// http://www.nuget.org/packages/Microsoft.Bcl.Compression/
#if NET
var inputStream = new MemoryStream(bytes);
var deflateStream = new DeflateStream(inputStream, CompressionMode.Decompress);
var buffer = new byte[4096];
var outputStream = new MemoryStream();
while (true)
{
var l = deflateStream.Read(buffer, 0, buffer.Length);
outputStream.Write(buffer, 0, l);
if (l < buffer.Length)
{
break;
}
}
return outputStream.ToArray();
#elif BCL_COMPRESSION
// TODO: use Microsoft.Bcl.Compression
#else
return OxyPlot.Deflate.Decompress(bytes);
#endif
}
}
} |
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CodeConnections.Presentation;
using Microsoft.VisualStudio.Shell.Interop;
namespace CodeConnections.Services
{
internal class OutputWindowOutputService : IOutputService
{
IVsOutputWindowPane? _outputPane;
/// <summary>
/// Have we already created (or tried and failed to create) the output pane?
/// </summary>
private bool _hasCreatedOutputPane;
private readonly string _guidString;
private readonly IVsOutputWindow _outputWindow;
private readonly string _outputPaneName;
public OutputLevel CurrentOutputLevel { get; set; }
public OutputWindowOutputService(string guidString, IVsOutputWindow outputWindow, string outputPaneName)
{
_guidString = guidString;
_outputWindow = outputWindow;
_outputPaneName = outputPaneName;
}
private void TryCreateOutputPane()
{
if (_hasCreatedOutputPane)
{
return;
}
_hasCreatedOutputPane = true;
Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
var guid = new Guid(_guidString);
_outputWindow.CreatePane(guid, _outputPaneName, 1, 1);
_outputWindow.GetPane(guid, out _outputPane);
if (_outputPane == null)
{
throw new InvalidOperationException("Failed to create output pane");
}
}
public void WriteLine(string output)
{
Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
TryCreateOutputPane();
_outputPane?.OutputString($"{output}{Environment.NewLine}");
}
public void FocusOutput()
{
Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
TryCreateOutputPane();
_outputPane?.Activate();
}
public bool IsEnabled(OutputLevel outputLevel) => outputLevel <= CurrentOutputLevel;
}
}
|
using System;
using UnityEngine;
public class DeepPlaneScript : MonoBehaviour
{
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Player")
{
Player player = collision.gameObject.GetComponent<Player>();
player.Respawn();
}
}
}
|
using MovieMeter.Model.Contracts;
using MovieMeter.WebHarvester.Contracts;
using MovieMeter.WebHarvester.Harvester;
using MovieMeter.WebHarvester.Parsers;
using SimpleInjector;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MovieMeter.WebHarvester.DependencyInjection
{
public static class ContainerExtensions
{
public static void RegisterHarvester(this Container container)
{
container.Register<IParser, TMNParser>();
container.Register<IHarvester, Harvester.Harvester>();
container.Register<IRatingProvider, OmdbRatingProvider>();
container.Register<IProgramProvider, ProgramProvider>();
}
}
}
|
using System;
public class About
{
public About()
{
}
public void OutputShort()
{
Console.WriteLine("LordOfMoney v0.1");
}
public void OutputLong()
{
Console.WriteLine("LordOfMoney v0.1\nПерсональный менеджер финансов");
}
}
|
using System.ComponentModel.DataAnnotations;
namespace VirtualGroupEx.Server.Data
{
public class RegisteredQid
{
public int Id { get; set; }
[Required]
public long Qid { get; set; }
public bool Used { get; set; } = false;
}
}
|
namespace IRunes.Services.Tracks
{
using IRunes.ViewModels.Tracks;
public interface ITracksService
{
void CreateTrack(string albumId, string name, string link, decimal price);
DetailsViewModel GetDetails(string trackId);
}
}
|
//---------------------------------------------------------------------
// <copyright file="TestDataServiceActionProvider.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
namespace Microsoft.Test.OData.Framework.TestProviders.OptionalProviders
{
using System.Collections.Generic;
using System.Linq;
#if TESTPROVIDERS
using Microsoft.OData;
#else
using Microsoft.Data.OData;
#endif
using Microsoft.OData.Service;
using Microsoft.OData.Service.Providers;
using Microsoft.Test.OData.Framework.TestProviders.Common;
using Microsoft.Test.OData.Framework.TestProviders.Contracts;
/// <summary>
/// Implementation of an test DataService Action Provider
/// </summary>
public abstract class TestDataServiceActionProvider : IDataServiceActionProvider
{
private object dataServiceInstance;
private IEnumerable<ServiceAction> dataServiceActions;
/// <summary>
/// Initializes a new instance of the TestDataServiceActionProvider class
/// </summary>
/// <param name="dataServiceInstance">Data Service Instance</param>
protected TestDataServiceActionProvider(object dataServiceInstance)
{
this.dataServiceInstance = dataServiceInstance;
}
/// <summary>
/// Returns all service actions in the provider.
/// </summary>
/// <param name="operationContext">operation Context</param>
/// <returns>An enumeration of all service actions.</returns>
public IEnumerable<ServiceAction> GetServiceActions(DataServiceOperationContext operationContext)
{
if (DataServiceOverrides.ActionProvider.GetServiceActionsFunc != null)
{
return DataServiceOverrides.ActionProvider.GetServiceActionsFunc(operationContext);
}
return this.GetServiceActionsInternal(operationContext);
}
/// <summary>
/// Tries to find the <see cref="ServiceAction"/> for the given <paramref name="sericeActionName"/>.
/// </summary>
/// <param name="operationContext">operation Context</param>
/// <param name="serviceActionName">The name of the service action to resolve.</param>
/// <param name="serviceAction">Returns the service action instance if the resolution is successful; null otherwise.</param>
/// <returns>true if the resolution is successful; false otherwise.</returns>
public bool TryResolveServiceAction(DataServiceOperationContext operationContext, string serviceActionName, out ServiceAction serviceAction)
{
if (DataServiceOverrides.ActionProvider.TryResolveServiceActionFunc != null)
{
DataServiceOverrides.ActionProvider.TryResolveServiceActionFunc(operationContext, serviceActionName);
serviceAction = DataServiceOverrides.ActionProvider.OutServiceActionTryResolveServiceActionFunc();
return DataServiceOverrides.ActionProvider.OutReturnTryResolveServiceActionFunc();
}
serviceAction = this.GetServiceActionsInternal(operationContext).SingleOrDefault(sa => sa.Name == serviceActionName);
return serviceAction != null;
}
/// <summary>
/// Builds up an instance oz <see cref="IDataServiceInvokable"/> for the given <paramref name="serviceAction"/> with the provided <paramref name="parameterTokens"/>.
/// </summary>
/// <param name="operationContext">The data service operation context instance.</param>
/// <param name="serviceAction">The service action to invoke.</param>
/// <param name="parameterTokens">The parameter tokens required to invoke the service action.</param>
/// <returns>An instance of <see cref="IDataServiceInvokable"/> to invoke the action with.</returns>
public IDataServiceInvokable CreateInvokable(DataServiceOperationContext operationContext, ServiceAction serviceAction, object[] parameterTokens)
{
if (DataServiceOverrides.ActionProvider.CreateInvokableFunc != null)
{
return DataServiceOverrides.ActionProvider.CreateInvokableFunc(operationContext, serviceAction, parameterTokens);
}
return new TestDataServiceInvokable(this.dataServiceInstance, operationContext, serviceAction, parameterTokens);
}
/// <summary>
/// Gets a collection of actions having <paramref name="bindingParameterType"/> as the binding parameter type.
/// </summary>
/// <param name="operationContext">The data service operation context instance.</param>
/// <param name="bindingParameterType">Instance of the binding parameter resource type (<see cref="ResourceType"/>) in question.</param>
/// <returns>A list of actions having <paramref name="bindingParameterType"/> as the binding parameter type.</returns>
public IEnumerable<ServiceAction> GetServiceActionsByBindingParameterType(DataServiceOperationContext operationContext, ResourceType bindingParameterType)
{
if (DataServiceOverrides.ActionProvider.GetServiceActionsByBindingParameterTypeFunc != null)
{
return DataServiceOverrides.ActionProvider.GetServiceActionsByBindingParameterTypeFunc(operationContext, bindingParameterType);
}
return this.GetServiceActionsInternal(operationContext).Where(sa => sa.BindingParameter != null && sa.BindingParameter.ParameterType.FullName == bindingParameterType.FullName);
}
/// <summary>
/// Determines whether a given <paramref name="serviceAction"/> should be advertised as bindable to the given <paramref name="resourceInstance"/>.
/// </summary>
/// <param name="operationContext">The data service operation context instance.</param>
/// <param name="serviceAction">Service action to be advertised.</param>
/// <param name="resourceInstance">Instance of the resource to which the service action is bound.</param>
/// <param name="resourceInstanceInFeed">true if the resource instance to be serialized is inside a feed; false otherwise. The value true
/// suggests that this method might be called many times during serialization since it will get called once for every resource instance inside
/// the feed. If it is an expensive operation to determine whether to advertise the service action for the <paramref name="resourceInstance"/>,
/// the provider may choose to always advertise in order to optimize for performance.</param>
/// <param name="actionToSerialize">The <see cref="ODataAction"/> to be serialized. The server constructs
/// the version passed into this call, which may be replaced by an implementation of this interface.
/// This should never be set to null unless returning false.</param>
/// <returns>true if the service action should be advertised; false otherwise.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "operationContext", Justification = "parameter is required")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "serviceAction", Justification = "parameter is required")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "resourceInstance", Justification = "parameter is required")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "actionToSerialize", Justification = "parameter is required")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:AvoidRefParameters", Justification = "ref parameter required")]
public bool AdvertiseServiceAction(DataServiceOperationContext operationContext, ServiceAction serviceAction, object resourceInstance, bool resourceInstanceInFeed, ref ODataAction actionToSerialize)
{
if (DataServiceOverrides.ActionProvider.AdvertiseServiceActionFunc != null)
{
DataServiceOverrides.ActionProvider.AdvertiseServiceActionFunc(operationContext, serviceAction, resourceInstance, resourceInstanceInFeed, actionToSerialize);
if (DataServiceOverrides.ActionProvider.OutODataActionAdvertiseServiceFunc != null)
{
actionToSerialize = DataServiceOverrides.ActionProvider.OutODataActionAdvertiseServiceFunc();
}
return DataServiceOverrides.ActionProvider.OutReturnAdvertiseServiceFunc();
}
return true;
}
/// <summary>
/// Loads action providers service actions
/// </summary>
/// <param name="operationContext">operation Context</param>
/// <returns>Enumerable of Service Actions</returns>
internal IEnumerable<ServiceAction> GetServiceActionsInternal(DataServiceOperationContext operationContext)
{
if (this.dataServiceActions == null)
{
var metadataProvider = (IDataServiceMetadataProvider)operationContext.GetService(typeof(IDataServiceMetadataProvider));
this.dataServiceActions = this.LoadServiceActions(metadataProvider).ToArray();
}
return this.dataServiceActions;
}
/// <summary>
/// Wrapper methods around metadata provider to get the ResourceType
/// </summary>
/// <param name="metadataProvider">metadata provider</param>
/// <param name="typeName">type name</param>
/// <returns>a resource type or throws</returns>
protected ResourceType GetResourceType(IDataServiceMetadataProvider metadataProvider, string typeName)
{
ResourceType resourceType = null;
ProviderImplementationSettings.Override(
s => s.EnforceMetadataCaching = false,
() => ExceptionUtilities.Assert(metadataProvider.TryResolveResourceType(typeName, out resourceType), "Cannot find a resource type '{0}' in the metadata provider", typeName));
return resourceType;
}
/// <summary>
/// Wrapper methods around metadata provider to get the ResourceSet
/// </summary>
/// <param name="metadataProvider">metadata provider</param>
/// <param name="setName">set name</param>
/// <returns>a resource set or throws</returns>
protected ResourceSet GetResourceSet(IDataServiceMetadataProvider metadataProvider, string setName)
{
ResourceSet resourceSet = null;
ProviderImplementationSettings.Override(
s => s.EnforceMetadataCaching = false,
() => ExceptionUtilities.Assert(metadataProvider.TryResolveResourceSet(setName, out resourceSet), "Cannot find a resource set '{0}' in the metadata provider", setName));
return resourceSet;
}
/// <summary>
/// Loads action providers service actions
/// </summary>
/// <param name="dataServiceMetadataProvider">Data Service Metadata Provider</param>
/// <returns>Enumerable of Service Actions</returns>
protected abstract IEnumerable<ServiceAction> LoadServiceActions(IDataServiceMetadataProvider dataServiceMetadataProvider);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace T7
{
/// <summary>
/// Holds information about the status of the fuel maps while autotuning
/// </summary>
public class FuelMapInformation
{
private FuelMap m_OriginalFuelMap = new FuelMap();
private FuelMap m_AlteredFuelMap = new FuelMap();
private FuelMap m_ChangesFuelMap = new FuelMap();
private FuelMap m_DifferenceFuelMap = new FuelMap();
private double[] m_differenceMapInPercentages = new double[18 * 16];
/// <summary>
/// Gets the percentual differences for each cell in the fuelmap after running autotune
/// </summary>
/// <returns></returns>
public double[] GetDifferencesInPercentages()
{
// fill the array
for (int i = 0; i < (18 * 16); i++)
{
double diff = Convert.ToInt32(m_AlteredFuelMap.GetByteAtPosition(i)) - Convert.ToInt32(m_OriginalFuelMap.GetByteAtPosition(i));
double original = Convert.ToInt32(m_OriginalFuelMap.GetByteAtPosition(i));
m_differenceMapInPercentages[i] = (diff * 100)/ original;
if (m_differenceMapInPercentages[i] == Double.NaN) m_differenceMapInPercentages[i] = 0;
}
return m_differenceMapInPercentages;
}
/// <summary>
/// Sets the initial fuel map information. Should be called before starting autotune
/// </summary>
/// <param name="map"></param>
public void SetOriginalFuelMap(byte[] map)
{
m_OriginalFuelMap.FuelMapData = map;
m_AlteredFuelMap.FuelMapData = map;
m_ChangesFuelMap.Initialize();
m_DifferenceFuelMap.Initialize();
}
public byte[] GetOriginalFuelMap()
{
return m_OriginalFuelMap.FuelMapData;
}
/// <summary>
/// Updates the altered fuelmap and the changes table while running autotune
/// </summary>
/// <param name="x_index"></param>
/// <param name="y_index"></param>
/// <param name="offset"></param>
/// <returns></returns>
public bool UpdateFuelMap(int x_index, int y_index, int offset)
{
// offset is the REAL new value for the fuelmap
bool retval = false;
// first check if the fuelmap has not been changed yet at that point
int numberOfMeasurements = m_ChangesFuelMap.GetByteAtXY(x_index, y_index);
if (numberOfMeasurements < 255) // max 255 measurements
{
// set the altered fuel map at this position with offset given
byte originalValue = m_OriginalFuelMap.GetByteAtXY(x_index, y_index);
//logger.Debug("Update fuelmap: " + originalValue.ToString("D3") + " to " + offset.ToString("D3"));
// calculate new average value
int newAverage = m_AlteredFuelMap.GetByteAtXY(x_index, y_index);
newAverage *= numberOfMeasurements;
newAverage += offset;
newAverage /= (numberOfMeasurements + 1);
m_AlteredFuelMap.SetByteXY(x_index, y_index, /*Convert.ToByte(offset)*/ Convert.ToByte(newAverage));
numberOfMeasurements++;
m_ChangesFuelMap.SetByteXY(x_index, y_index, Convert.ToByte(numberOfMeasurements));
byte newvalue = Convert.ToByte(/*offset*/ newAverage);
newvalue -= originalValue;
m_DifferenceFuelMap.SetByteXY(x_index, y_index, newvalue);
retval = true;
}
return retval;
}
}
}
|
using System;
using System.Threading.Tasks;
using Google.Cloud.Speech.V1;
namespace VoiceScript.VoiceTranscription
{
/// <summary>
/// Provides access to Google Cloud Speech long running operations API.
/// </summary>
public class LongRunningRecognizer
{
readonly RecognitionConfig config;
public LongRunningRecognizer(RecognitionConfig configuration)
{
config = configuration;
}
/// <summary>
/// Performs transcription of the given audio using Google Cloud Speech long running operation.
/// Polls until the operation is completed and triggers the provided callback after that.
/// </summary>
/// <param name="audio">Audio in Google Cloud Speech compatible format.</param>
/// <param name="callback">Function to be called with the individual transcription parts
/// from <see cref="SpeechRecognitionAlternative.Transcript"/>.
/// Typical use case is for writing transcripted words to the stream.</param>
public void LongRunningRecognize(RecognitionAudio audio, Action<string> callback)
{
var speechClient = SpeechClient.Create();
// Send request to the server
var operation = speechClient.LongRunningRecognize(config, audio);
// Wait for long-running operation to finish
var completedOperation = operation.PollUntilCompleted();
var response = completedOperation.Result;
ServerResponseProcessor.ProcessSpeechRecognitionTranscript(response.Results, callback);
}
/// <summary>
/// Performs asynchronous transcription of the given audio using Google Cloud Speech
/// async long running operation. Polls until the operation is completed
/// and triggers the provided callback after that.
/// </summary>
/// <param name="audio"></param>
/// <param name="callback">Function to be called with the individual transcription parts
/// from <see cref="SpeechRecognitionAlternative.Transcript"/>.
/// Typical use case is for writing transcripted words to the stream.</param>
public async void LongRunningRecognizeAsync(RecognitionAudio audio, Action<string> callback)
{
var speechClient = await SpeechClient.CreateAsync();
// Send request to the server
var operation = await speechClient.LongRunningRecognizeAsync(config, audio);
// Wait for long-running operation to finish
var completedOperation = await operation.PollUntilCompletedAsync();
var response = completedOperation.Result;
ServerResponseProcessor.ProcessSpeechRecognitionTranscript(response.Results, callback);
}
}
}
|
using Herald.Notification.Builder;
namespace Herald.Notification.Sns.Configurations
{
public interface ISnsNotificationBuider : INotificationBuilder
{
}
} |
using System.Collections.Generic;
using UnityEngine.SocialPlatforms;
namespace Newtonsoft.Json.UnityConverters.Tests.GameCenter
{
public class RangeTests : ValueTypeTester<Range>
{
public static readonly IReadOnlyCollection<(Range deserialized, object anonymous)> representations = new (Range, object)[] {
(new Range(), new { from = 0, count = 0 }),
(new Range(1, 2), new { from = 1, count = 2 }),
};
}
}
|
using Newtonsoft.Json;
using Okex.Net.Converters;
using System;
namespace Okex.Net.RestObjects.Market
{
public class Okex24HourVolume
{
[JsonProperty("volUsd")]
public decimal VolumeUsd { get; set; }
[JsonProperty("volCny")]
public decimal VolumeCny { get; set; }
[JsonProperty("ts"), JsonConverter(typeof(OkexTimestampConverter))]
public DateTime Time { get; set; }
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
namespace ScoreSpace
{
/// <summary>
/// Edge ratio or E-Ratio
/// Ratio between MFE and MAE to identify if trades have bias towards profit
/// N = Number of observations
/// AvgEdge = ((MFE / MAE) + (MFE / MAE) + ... + (MFE / MAE)) / N
/// </summary>
public class EdgeRatio
{
/// <summary>
/// Input values
/// </summary>
public virtual IEnumerable<InputData> Values { get; set; } = new List<InputData>();
/// <summary>
/// Calculate
/// </summary>
/// <returns></returns>
public virtual double Calculate()
{
var sum = Values.Sum(o =>
{
var maxGain = o.Max - o.Value;
var maxLoss = o.Value - o.Min;
if (maxLoss == 0)
{
return 0.0;
}
return maxGain / maxLoss;
});
return sum / Values.Count();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using Rafy;
using JXC.WPF.Templates;
using Rafy.MetaModel;
using Rafy.MetaModel.View;
using Rafy.WPF;
namespace JXC.WPF
{
public class BillQueryModule : UITemplate
{
public BillQueryModule()
{
this.EntityType = typeof(TimeSpanCriteria);
}
protected override AggtBlocks DefineBlocks()
{
var blocks = new AggtBlocks
{
Layout = new LayoutMeta(typeof(BillQueryLayout)),
MainBlock = new ConditionBlock(this.EntityType),
Surrounders =
{
new SurrounderBlock(typeof(PurchaseOrder), QueryLogicalView.ResultSurrounderType),
new SurrounderBlock(typeof(OrderStorageInBill), QueryLogicalView.ResultSurrounderType),
new SurrounderBlock(typeof(OrderStorageInBill), QueryLogicalView.ResultSurrounderType)
{
KeyLabel = "采购入库单 - 报表",
BlockType = BlockType.Report,
},
new SurrounderBlock(typeof(OtherStorageInBill), QueryLogicalView.ResultSurrounderType),
new SurrounderBlock(typeof(OtherStorageOutBill), QueryLogicalView.ResultSurrounderType),
new SurrounderBlock(typeof(StorageMove), QueryLogicalView.ResultSurrounderType),
}
};
return blocks;
}
protected override void OnBlocksDefined(AggtBlocks blocks)
{
//TimeSpanCriteria 默认是横向排列的,需要修改此数据
blocks.MainBlock.ViewMeta.AsWPFView().UseDetailAsHorizontal(false);
foreach (var sur in blocks.Surrounders)
{
ModuleBase.MakeBlockReadonly(sur);
}
base.OnBlocksDefined(blocks);
}
protected override void OnUIGenerated(ControlResult ui)
{
ui.MainView.CastTo<QueryLogicalView>().TryExecuteQuery();
base.OnUIGenerated(ui);
}
}
} |
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
namespace DevZest.Data.AspNetCore.Primitives
{
/// <summary>
/// Creates <see cref="DataSetModelBinder{T}"/> instance.
/// </summary>
public class DataSetModelBinderProvider : IModelBinderProvider
{
/// <inheritdoc/>
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
var modelType = context.Metadata.ModelType;
if (modelType.IsDataSet())
{
var loggerFactory = context.Services.GetRequiredService<ILoggerFactory>();
return (IModelBinder)Activator.CreateInstance(
typeof(DataSetModelBinder<>).MakeGenericType(modelType.GetGenericArguments()[0]),
loggerFactory);
}
return null;
}
}
}
|
using System;
using System.Windows;
namespace Host
{
/// <summary>
/// A custom entry point method, Main(), is required to use LoaderOptimizationAttribute,
/// which ensures that WPF assemblies are shared between the main application's appdomain
/// and the subsequent appdomains that are created to host isolated add-ins. Using
/// LoaderOptimizationAttribute dramatically improves performance; otherwise, each
/// add-in needs to load a complete set of WPF assemblies.
/// </summary>
public class App : Application
{
[STAThread]
[LoaderOptimization(LoaderOptimization.MultiDomainHost)]
public static void Main()
{
App app = new App();
app.Run();
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
// Show main application window
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
}
}
} |
// CS0246: The type or namespace name `foo' could not be found. Are you missing an assembly reference?
// Line: 5
struct bar {
foo foo;
}
|
using UnityEngine;
namespace WhateverDevs.Core.Runtime.Serialization
{
/// <summary>
/// Scriptable to get a json serializer for editor referencing.
/// </summary>
[CreateAssetMenu(menuName = "WhateverDevs/Serializers/Json", fileName = "JsonSerializer")]
public class JsonSerializerScriptable : SerializerScriptable<JsonSerializer, string>
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class RaceTower
{
private List<Driver> drivers;
private DriverFactory factory;
private Stack<Driver> failiers;
private int currentLap;
private int totalLaps;
private int trackLength;
private string weathe;
public RaceTower()
{
this.drivers = new List<Driver>();
this.factory = new DriverFactory();
this.failiers = new Stack<Driver>();
this.currentLap = 0;
this.totalLaps = 0;
this.trackLength = 0;
weathe = "Sunny";
}
public void SetTrackInfo(int lapsNumber, int trackLength)
{
this.totalLaps = lapsNumber;
this.trackLength = trackLength;
}
void RegisterDriver(List<string> commandArgs)
{
Driver driver = factory.GetDriver(commandArgs.ToArray());
drivers.Add(driver);
}
void DriverBoxes(List<string> commandArgs)
{
//TODO: Add some logic here …
}
string CompleteLaps(List<string> commandArgs)
{
int n = int.Parse(commandArgs[0]);
if (n > totalLaps - currentLap)
{
throw new ArgumentException($"There is no time! On lap {currentLap}.");
}
while (n != 0)
{
foreach (var driver in drivers)
{
driver.TotalTime += 60 / (trackLength / driver.Speed);
driver.Car.FuelAmount -= trackLength * driver.FuelConsumptionPerKm;
driver.Car.Tyre.Degradate();
PossibleFail(driver);
}
}
return null;
}
string GetLeaderboard()
{
StringBuilder builder = new StringBuilder();
int positon = 1;
builder.AppendLine($"Lap {currentLap}/{totalLaps}");
foreach (var driver in drivers.OrderBy(x => x.TotalTime))
{
builder.AppendLine($"{positon++} {driver.Name} {driver.TotalTime}");
}
while (failiers.Count != 0)
{
builder.AppendLine($"{positon++} {failiers.Peek().Name} {failiers.Peek().Status}");
failiers.Pop();
}
return builder.ToString().Trim();
}
void ChangeWeather(List<string> commandArgs)
{
//TODO: Add some logic here …
}
private void PossibleFail(Driver driver)
{
if (driver.Car.Tyre.Degradation < 0)
{
driver.Status = "Blown Tyre";
RemoveDriverFromRace(driver);
}
else if (driver.Car.FuelAmount< 0)
{
driver.Status = "Out of fuel";
RemoveDriverFromRace(driver);
}
}
private void RemoveDriverFromRace(Driver driver)
{
failiers.Push(driver);
drivers.Remove(driver);
}
}
|
namespace TPUM.Shared.Logic.Core
{
public enum Format
{
JSON, YAML, XML
}
}
|
using System;
using System.Diagnostics;
using System.Windows;
using Text_Grab.Properties;
using Text_Grab.Utilities;
using Text_Grab.Views;
namespace Text_Grab
{
/// <summary>
/// Interaction logic for FirstRunWindow.xaml
/// </summary>
public partial class FirstRunWindow : Window
{
public FirstRunWindow()
{
InitializeComponent();
}
private void OkayButton_Click(object sender, RoutedEventArgs e)
{
if (System.Windows.Application.Current.Windows.Count == 1)
{
switch (Settings.Default.DefaultLaunch)
{
case "Fullscreen":
WindowUtilities.LaunchFullScreenGrab(true);
break;
case "GrabFrame":
WindowUtilities.OpenOrActivateWindow<GrabFrame>();
break;
case "EditText":
WindowUtilities.OpenOrActivateWindow<EditTextWindow>();
break;
default:
break;
}
}
this.Close();
}
private void FirstRun_Loaded(object sender, RoutedEventArgs e)
{
// ShowToastCheckBox.IsChecked = Settings.Default.ShowToast;
switch (Settings.Default.DefaultLaunch)
{
case "Fullscreen":
FullScreenRDBTN.IsChecked = true;
break;
case "GrabFrame":
GrabFrameRDBTN.IsChecked = true;
break;
case "EditText":
EditWindowRDBTN.IsChecked = true;
break;
default:
EditWindowRDBTN.IsChecked = true;
break;
}
}
private void ShowToastCheckBox_Click(object sender, RoutedEventArgs e)
{
// Settings.Default.ShowToast = (bool)ShowToastCheckBox.IsChecked;
Settings.Default.Save();
}
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
if (this.IsLoaded != true)
return;
if (GrabFrameRDBTN.IsChecked != null && (bool)GrabFrameRDBTN.IsChecked)
Settings.Default.DefaultLaunch = "GrabFrame";
else if (FullScreenRDBTN.IsChecked != null && (bool)FullScreenRDBTN.IsChecked)
Settings.Default.DefaultLaunch = "Fullscreen";
else
Settings.Default.DefaultLaunch = "EditText";
Settings.Default.Save();
}
private void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
{
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri) { UseShellExecute = true });
e.Handled = true;
}
private void SettingsButton_Click(object sender, RoutedEventArgs e)
{
WindowUtilities.OpenOrActivateWindow<SettingsWindow>();
this.Close();
}
private void TryFullscreen_Click(object sender, RoutedEventArgs e)
{
WindowUtilities.LaunchFullScreenGrab(true);
}
private void TryGrabFrame_Click(object sender, RoutedEventArgs e)
{
WindowUtilities.OpenOrActivateWindow<GrabFrame>();
}
private void TryEditWindow_Click(object sender, RoutedEventArgs e)
{
WindowUtilities.OpenOrActivateWindow<EditTextWindow>();
}
private void Window_Closed(object? sender, EventArgs e)
{
WindowUtilities.ShouldShutDown();
}
}
}
|
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Duck.Cameras.Windows.Controls
{
public static class ControlUtil
{
public static void RunOnUiThread(this Control control, Action action)
{
if (control.InvokeRequired)
{
control.BeginInvoke(action);
}
else
{
action();
}
}
public static void DelayedRun(this Control control, Action action, int milisDelay = 0)
{
Task.Delay(milisDelay).ContinueWith(_ => control.BeginInvoke(action));
}
}
}
|
using NUnit.Framework;
using System;
namespace LogExpert.Tests
{
[TestFixture]
public class LogWindowTest
{
// TODO: Add more tests when DI container is ready.
[TestCase(@".\TestData\JsonColumnizerTest_01.txt", typeof(DefaultLogfileColumnizer))]
public void Instantiate_JsonFile_BuildCorrectColumnizer(string fileName, Type columnizerType)
{
LogTabWindow logTabWindow = new LogTabWindow(null, 0, false);
LogWindow logWindow =
new LogWindow(logTabWindow, fileName, false, false);
Assert.AreEqual(columnizerType, logWindow.CurrentColumnizer.GetType());
}
[TestCase(@".\TestData\XmlTest_01.xml")]
public void Instantiate_AnyFile_NotCrash(string fileName)
{
PluginRegistry.GetInstance().RegisteredColumnizers.Add(new Log4jXmlColumnizer());
LogTabWindow logTabWindow = new LogTabWindow(null, 0, false);
LogWindow logWindow =
new LogWindow(logTabWindow, fileName, false, false);
Assert.True(true);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Bunashibu.Kikan {
[System.Serializable]
public class HitInfo {
public int MaxTargetCount => _maxTargetCount;
public int MaxHitCount => _maxHitCount;
public float Interval => _interval;
[SerializeField] private int _maxTargetCount;
[SerializeField] private int _maxHitCount;
[SerializeField] private float _interval;
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using Toggl.Phoebe.Data.DataObjects;
using XPlatUtils;
namespace Toggl.Phoebe.Data
{
public static class ForeignRelationExtensions
{
public static IEnumerable<ForeignRelation> GetRelations (this CommonData data)
{
var manager = ServiceContainer.Resolve<ForeignRelationManager> ();
return manager.GetRelations (data);
}
public static Task<CommonData> ToListAsync (this ForeignRelation relation)
{
var manager = ServiceContainer.Resolve<ForeignRelationManager> ();
return manager.ToListAsync (relation);
}
}
}
|
@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.SectionName = "Hub";
}
@section menu {
@*<li>@Html.ActionLink("Home", "Index", "Home")</li>*@
@*<li>@Html.ActionLink("Ping", "Ping", "Home")</li>*@
<li><a href="/Legacy/News/ReleaseManagement/Drafts/">News Releases</a></li>
<li><a href="/Legacy/Calendar/">Corporate Calendar</a></li>
<li><a href="/Legacy/Contacts/">Media Contacts</a></li>
<li>@Html.ActionLink("Media Requests", "Index", "MediaRequests")</li>
@*<li><a href="/swagger">Swagger</a></li>*@
}
@RenderBody()
@section scripts
{
@RenderSection("scripts", required: false)
} |
namespace Mogo.RPC
{
using System;
public enum DefCheckResult : byte
{
ENUM_LOGIN_CHECK_ENTITY_DEF_NOMATCH = 1,
ENUM_LOGIN_CHECK_NO_SERVICE = 2,
ENUM_LOGIN_CHECK_SUCCESS = 0
}
}
|
public enum KamereonShaderControl.PlayType // TypeDefIndex: 7900
{
// Fields
public int value__; // 0x0
public const KamereonShaderControl.PlayType Default = 0;
public const KamereonShaderControl.PlayType AlphaLoop = 1;
public const KamereonShaderControl.PlayType Alpha = 2;
public const KamereonShaderControl.PlayType Rainbow = 3;
public const KamereonShaderControl.PlayType RainbowLoop = 4;
}
|
namespace Pliant.Tree
{
public interface ITreeNode
{
TreeNodeType NodeType { get; }
int Origin { get; }
int Location { get; }
void Accept(ITreeNodeVisitor visitor);
}
} |
//-----------------------------------------------------------------------
// <copyright file="ConsoleMethods.cs" company="TelerikAcademy">
// All rights reserved © Telerik Academy 2012-2013
// </copyright>
//----------------------------------------------------------------------
namespace Utilities
{
using System;
/// <summary>
/// Methods which format an input value and print it on the console.
/// </summary>
public class ConsoleMethods
{
public static void PrintNumberWithPrecision(double number, int digits)
{
string format = "{0:F" + digits + "}";
Console.WriteLine(format, number);
}
public static void PrintNumberAsPercentWithPrecision(double number, int digits)
{
string format = "{0:P" + digits + "}";
Console.WriteLine(format, number);
}
public static void PrintObjectAsPaddedString(object value, int length)
{
string format = "{0," + length + "}";
Console.WriteLine(format, value);
}
}
}
|
namespace Societatis.Api.Data
{
using System.Collections.Generic;
using Societatis.Api.Models;
public interface IGroupRepository
{
Group GetGroup(long id);
IEnumerable<Group> GetGroups(long userId);
void AddGroup(Group group);
void AddGroup(Group group, long parentId);
void AddUserToGroup(long userId, long groupId);
}
} |
using OrbintSoft.Yauaa.Analyzer;
namespace OrbintSoft.Yauaa.WebSample.AspNetCore.Utilities
{
public static class YauaaSingleton
{
private static UserAgentAnalyzer.UserAgentAnalyzerBuilder Builder { get; }
private static UserAgentAnalyzer analyzer = null;
public static UserAgentAnalyzer Analyzer
{
get
{
if (analyzer == null)
{
analyzer = Builder.Build();
}
return analyzer;
}
}
static YauaaSingleton()
{
Builder = UserAgentAnalyzer.NewBuilder();
Builder.DropTests();
Builder.DelayInitialization();
Builder.WithCache(100);
Builder.HideMatcherLoadStats();
Builder.WithAllFields();
}
}
}
|
namespace Records
{
public class WithExpression
{
public void Method()
{
Book one = new()
{
Title = "Fahrenheit 451",
Author = "Ray Bradbury"
};
Book two = one with { Title = "Fahrenheit 452" };
}
}
public record Book
{
public string Title { get; set; }
public string Author { get; set; }
public string Genre { get; set; }
}
}
|
namespace LoChip8
{
public interface IDisplay
{
void Clear();
/// <summary>
/// Draws sprite at specified position.
/// Returns True if any set pixels are changed to unset (using XOR), and False otherwise
/// </summary>
/// <param name="sprite"></param>
/// <param name="positionX"></param>
/// <param name="positionY"></param>
/// <returns>True if any set pixels are changed to unset, and False otherwise</returns>
byte DrawSprite(Sprite sprite, int positionX, int positionY);
}
} |
using BinarySerialization;
namespace ublox.Core.Messages
{
public class CfgMsgPoll : PacketPayload
{
[FieldEndianness(Endianness.Big)]
public MessageId MessageId { get; set; }
}
}
|
namespace Activout.RestClient.Test.DomainExceptionTests
{
public enum MyDomainErrorEnum
{
Unknown = 0,
AccessDenied,
Forbidden,
DomainFoo,
DomainBar,
ServerError,
ClientError
}
} |
namespace PostSharp.Engineering.BuildTools.Dependencies.Model;
public record CiLatestBuildOfBranch( string Name ) : ICiBuildSpec; |
namespace CommunityToolkit.Maui.Sample.Pages.Converters
{
public partial class StringToListConverterPage : BasePage
{
public StringToListConverterPage()
{
InitializeComponent();
}
}
} |
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Dersei.Doto.Extensions
{
public static class RandomExtensions
{
public static T RandomItem<T>(this List<T> @this)
{
var index = Random.Range(0, @this.Count);
return @this[index];
}
public static T RandomItem<T>(this List<T> @this, System.Random random)
{
if (@this.Count == 0)
return default;
var index = random.Next(0, @this.Count);
return @this[index];
}
public static T RandomItem<T>(this T[] @this)
{
if (@this.Length == 0)
return default;
var index = Random.Range(0, @this.Length);
return @this[index];
}
public static T RandomItem<T>(this T[] @this, System.Random random)
{
if (@this.Length == 0)
return default;
var index = random.Next(0, @this.Length);
return @this[index];
}
public static T RandomItem<T>(this IEnumerable<T> @this)
{
if (@this is List<T> list)
{
return list.RandomItem();
}
var enumerable = @this.ToList();
var index = Random.Range(0, enumerable.Count);
return enumerable.ElementAt(index);
}
public static T RandomItem<T>(this IEnumerable<T> @this, System.Random random)
{
if (@this is List<T> list)
{
return list.RandomItem();
}
var enumerable = @this.ToList();
var index = random.Next(0, enumerable.Count);
return enumerable.ElementAt(index);
}
public static T2 RandomItem<T1, T2>(this Dictionary<T1, T2> @this)
{
var index = Random.Range(0, @this.Values.Count);
return @this.Values.ElementAt(index);
}
public static T2 RandomItem<T1, T2>(this Dictionary<T1, T2> @this, System.Random random)
{
var index = random.Next(0, @this.Values.Count);
return @this.Values.ElementAt(index);
}
public static float NextFloat(this System.Random @this, float minValue, float maxValue)
{
var value = (float) @this.NextDouble();
return value * (maxValue - minValue) + minValue;
}
public static Vector3 NextVector3(this Random _, Vector3 minValues, Vector3 maxValues)
{
var x = Random.Range(minValues.x, maxValues.x);
var y = Random.Range(minValues.y, maxValues.y);
var z = Random.Range(minValues.z, maxValues.z);
return new Vector3(x, y, z);
}
public static Vector3 NextVector3(this System.Random @this, Vector3 minValues, Vector3 maxValues)
{
var x = (float) @this.NextDouble() * (maxValues.x - minValues.x) + minValues.x;
var y = (float) @this.NextDouble() * (maxValues.y - minValues.y) + minValues.y;
var z = (float) @this.NextDouble() * (maxValues.z - minValues.z) + minValues.z;
return new Vector3(x, y, z);
}
}
} |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AudioManager : MonoBehaviour {
public static AudioManager Instance;
[System.Serializable]
public class SoundClass{
public string soundName;
public AudioClip soundClip;
[HideInInspector]
public float lastPlayed = -1;
}
public List<SoundClass> sounds;
private Dictionary<string, SoundClass> soundDict;
void Awake(){
Instance = this;
//Build Dictionaary
soundDict = new Dictionary<string, SoundClass>();
foreach(SoundClass sound in sounds){
soundDict.Add(sound.soundName, sound);
}
}
public void playSound(string soundname){
SoundClass sound;
bool found = soundDict.TryGetValue(soundname, out sound);
if(found){
gameObject.audio.PlayOneShot(sound.soundClip);
}
else{
Debug.Log (soundname+" is not registered with soundmanager");
}
}
public void playWithMinInterval(string soundname, float interval){
SoundClass sound;
bool found = soundDict.TryGetValue(soundname, out sound);
if(found){
if(sound.lastPlayed < 0){
gameObject.audio.PlayOneShot(sound.soundClip);
sound.lastPlayed = Time.time;
}
else if(Time.time - sound.lastPlayed > interval){
gameObject.audio.PlayOneShot(sound.soundClip);
sound.lastPlayed = Time.time;
}
}
}
public void playSoundAt(string soundname, Vector3 position){
SoundClass sound;
bool found = soundDict.TryGetValue(soundname, out sound);
if(found){
AudioSource.PlayClipAtPoint(sound.soundClip, position);
}
else{
Debug.Log (soundname+" is not registered with soundmanager");
}
}
public void playSoundAtWithMinInterval(string soundname, Vector3 position, float interval){
SoundClass sound;
bool found = soundDict.TryGetValue(soundname, out sound);
if(found){
if(sound.lastPlayed < 0){
AudioSource.PlayClipAtPoint(sound.soundClip, position);
sound.lastPlayed = Time.time;
}
else if(Time.time - sound.lastPlayed > interval){
AudioSource.PlayClipAtPoint(sound.soundClip, position);
sound.lastPlayed = Time.time;
}
}
}
}
|
namespace SqlStreamStore
{
using System.Diagnostics;
using System.Threading.Tasks;
using SqlStreamStore.Streams;
using Xunit;
public partial class StreamStoreAcceptanceTests
{
[Fact]
public async Task Time_to_take_to_read_1000_read_head_positions()
{
using (var fixture = GetFixture())
{
using (var store = await fixture.GetStreamStore())
{
await store.AppendToStream("stream-1", ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3));
var stopwatch = Stopwatch.StartNew();
for(int i = 0; i < 1000; i++)
{
await store.ReadHeadPosition();
}
_testOutputHelper.WriteLine(stopwatch.ElapsedMilliseconds.ToString());
}
}
}
}
} |
using System.Runtime.Serialization;
using MyAnimeList.ResponseObjects.General;
namespace MyAnimeList.ResponseObjects.Anime;
[DataContract]
public class AnimeListNode : Node
{
public AnimeListNode(int id, string title, Picture mainPicture)
: base(id, title, mainPicture)
{
}
[DataMember]
public int Id { get; }
[DataMember]
public string Title { get; }
[DataMember(Name = "main_picture")]
public Picture MainPicture { get; }
public override string ToString()
{
return base.ToString()
+ $""
;
}
} |
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Data.Users
{
public interface IUserRepository
{
Task<IEnumerable<User>> GetAsync();
Task<User> GetByIdAsync(int userId);
}
} |
using GraphLab.Core.Algorithms.Utils;
using System.Collections.Generic;
using System.Linq;
namespace GraphLab.Core.Algorithms.Search
{
/// <summary>
/// Поиск в ширину
/// </summary>
/// <typeparam name="TVertex"></typeparam>
/// <typeparam name="TEdge"></typeparam>
public class BFS<TVertex, TEdge> : ISearchAlgorithm<TVertex, TEdge>
where TVertex : class, IVertex, new()
where TEdge : IEdge<TVertex>, new()
{
public Graph<TVertex, TEdge> Graph { get; private set; }
public TVertex StartVertex { get; private set; }
public StateManager<TVertex, SearchState> States { get; private set; }
public BFS(Graph<TVertex, TEdge> graph, TVertex startVertex)
{
Graph = graph;
StartVertex = startVertex;
States = new StateManager<TVertex, SearchState>(SearchState.None);
}
private Queue<TVertex> _bag;
public AlgorithmStep Begin()
{
_bag = new Queue<TVertex>();
_bag.Enqueue(StartVertex);
return Step();
}
private AlgorithmStep Step()
{
if (!_bag.Any())
return null;
var vertex = _bag.Dequeue();
MakeCurrent(vertex);
foreach (var adj in Graph[vertex])
{
if (States[adj] == SearchState.None && !_bag.Contains(adj))
{
_bag.Enqueue(adj);
}
}
return Step;
}
private void MakeCurrent(TVertex vertex)
{
var currentVertex = Graph.Verticies.SingleOrDefault(
x => States[x] == SearchState.Current);
if (currentVertex != null)
States[currentVertex] = SearchState.Visited;
States[vertex] = SearchState.Current;
}
}
}
|
using System;
namespace Domain.Events
{
public class ShoppingCartCheckedOut
{
public Guid CartId { get; }
public ShoppingCartCheckedOut(Guid cartId)
{
CartId = cartId;
}
}
} |
/// <summary>
/// Interface for damagable object
/// </summary>
public interface IDamagable
{
/// <summary>
/// Take the damage
/// </summary>
/// <param name="damage">Point of damage</param>
void TakeDamage(float damage);
}
|
using System.Collections;
using System.Collections.Generic;
using CGLA;
namespace VLT
{
[System.Serializable]
public class QuadNodeGenerator : System.IDisposable {
class Request
{
QuadNode m_parent;
bool m_static;
/*QuadId*/int m_child_id;
int m_child_no;
public Request(QuadNode parent, bool is_static, int child_id, int child_no)
{
m_parent = parent;
m_static = is_static;
m_child_id = child_id;
m_child_no = child_no;
}
public bool is_static() { return m_static; }
public int get_child_id() { return m_child_id; }
public int get_child_no() { return m_child_no; }
public QuadNode get_parent() { return m_parent; }
};
class Communicator : System.IDisposable
{
// HANDLE m_incoming_mutex;
// HANDLE m_outgoing_mutex;
// HANDLE m_not_empty_mutex;
List<Request> m_incoming_requests = new List<Request>();
List<QuadInfo> m_outgoing_responses = new List<QuadInfo>();
public Communicator()
{
// m_incoming_mutex = CreateMutex(NULL, FALSE, NULL);
// assert(m_incoming_mutex != 0);
//
// m_outgoing_mutex = CreateMutex(NULL, FALSE, NULL);
// assert(m_outgoing_mutex != 0);
//
// m_not_empty_mutex = CreateMutex(NULL, FALSE, NULL);
// assert(m_not_empty_mutex != 0);
}
public void Dispose()
{
// CloseHandle(m_incoming_mutex);
// m_incoming_mutex = 0;
//
// CloseHandle(m_outgoing_mutex);
// m_outgoing_mutex = 0;
//
// CloseHandle(m_not_empty_mutex);
// m_not_empty_mutex = 0;
}
public void add_incoming_request(Request request)
{
// WaitForSingleObject(m_incoming_mutex, INFINITE);
bool was_empty = m_incoming_requests.Count == 0;
m_incoming_requests.Add(request);
// ReleaseMutex(m_incoming_mutex);
if (was_empty)
{
// ReleaseMutex(m_not_empty_mutex);
}
}
public Request get_incoming_request()
{
// WaitForSingleObject(m_incoming_mutex, INFINITE);
// assert(!m_incoming_requests.empty());
Request request = null;
if (m_incoming_requests.Count != 0) {
request = m_incoming_requests [0];
m_incoming_requests.RemoveAt (0);
}
// ReleaseMutex(m_incoming_mutex);
return request;
}
public void wait_for_incoming_request()
{
// while (m_incoming_requests.Count == 0)
{
// WaitForSingleObject(m_not_empty_mutex, INFINITE);
}
}
public void add_outgoing_response(QuadInfo info)
{
// WaitForSingleObject(m_outgoing_mutex, INFINITE);
m_outgoing_responses.Add(info);
// ReleaseMutex(m_outgoing_mutex);
}
public QuadInfo get_outgoing_response()
{
// WaitForSingleObject(m_outgoing_mutex, INFINITE);
QuadInfo info;
if (m_outgoing_responses.Count != 0)
{
info = m_outgoing_responses[0];
m_outgoing_responses.RemoveAt(0);
}
else
{
info = null;
}
// ReleaseMutex(m_outgoing_mutex);
return info;
}
};
Communicator m_communicator = new Communicator();
static QuadNodeGenerator m_instance;
volatile bool m_running;
// HANDLE m_thread_handle;
public static void thread_proc(object parameter)
{
// FIXME: deadlock if no request is ever issued!! :-/
m_instance.m_communicator.wait_for_incoming_request();
Request request = null;
//do
{
request = m_instance.m_communicator.get_incoming_request();
if (request == null)
return;
QuadInfo info = null;
if (request.is_static())
{
info = m_instance.m_reader.create_info(request.get_child_id());
}
else
{
info = m_instance.m_synthesizer.create_info(request.get_parent(), request.get_child_no());
}
m_instance.m_communicator.add_outgoing_response(m_instance.calculate_info(info, request.get_parent()));
m_instance.m_communicator.wait_for_incoming_request();
}// while (request != null);// m_instance.m_running); TODO
// return 0;
}
void create_thread()
{
m_running = true;
// DWORD thread_id;
// m_thread_handle = CreateThread(NULL, 0, thread_proc, 0, 0, &thread_id);
// assert(m_thread_handle != 0);
/* Thread priorities:
THREAD_PRIORITY_TIME_CRITICAL
THREAD_PRIORITY_HIGHEST
THREAD_PRIORITY_ABOVE_NORMAL
THREAD_PRIORITY_NORMAL
THREAD_PRIORITY_BELOW_NORMAL
THREAD_PRIORITY_LOWEST
THREAD_PRIORITY_IDLE
*/
// SetThreadPriority(m_thread_handle, THREAD_PRIORITY_NORMAL);
}
void destroy_thread()
{
m_running = false;
m_communicator.add_incoming_request(null);
// WaitForSingleObject(m_thread_handle, INFINITE);
//
// CloseHandle(m_thread_handle);
// m_thread_handle = 0;
}
[UnityEngine.SerializeField]Render m_render;
[UnityEngine.SerializeField]QuadTreeReader m_reader;
QuadSynthesizer m_synthesizer;
HeightMapMesher m_mesher;
NormalMapGenerator m_normal_map_generator;
RenderState m_texture_render_state;
Dictionary<int, QuadInfo> m_ready_map = new Dictionary<int, QuadInfo>(50);
QuadInfo calculate_info(QuadInfo info, QuadNode parent)
{
info.set_detail_map(m_synthesizer.create_detail_map(info.get_base_map()));
if (info.get_bounding_box() == null)
{
info.set_bounding_box(new BoundingBox(info.get_heightmap()));
}
// calculate "displacements array"
// calculate "light array"
//m_heightmap_mesher->create_vertex_array(heightmap, skirt_depth)
return info;
}
static byte[] light_array = new byte[64000];
QuadNode create_node(QuadInfo info, QuadNode parent)
{
VertexArray vertex_array = m_mesher.create_vertex_array(info.get_heightmap(), info.get_skirt_depth());
TerrainMesh mesh = null;
if (info.get_image() != null)
{
mesh = m_render.create_mesh(vertex_array, info.get_image());
}
else
{
mesh = m_render.create_mesh(vertex_array, parent.get_mesh().get_static_texture());
}
QuadNode node = new QuadNode(parent, info, mesh);
m_normal_map_generator.calculate_light(node.get_heightmap(), light_array);
m_render.set_render_target(Render.RenderTarget.OffscreenBuffer);
m_render.set_state (m_texture_render_state);
// m_texture_render_state.enable();
//
TextureRenderState texture_render_state = m_texture_render_state as TextureRenderState;
float invsize = 1.0f / (node.get_heightmap().get_spacing() * (node.get_heightmap().get_size() - 1));
texture_render_state.set_diffuse_map(node.get_mesh().get_static_texture());
// texture_render_state.set_material_maps (m_synthesizer.get_material());
Vec2f texture_origin = node.get_texture_origin();
Vec3d chunk_origin = node.get_heightmap().get_origin();
texture_origin.x -= (float)(chunk_origin.x);
texture_origin.y -= (float)(chunk_origin.y);
float texture_size = node.get_texture_size() * invsize;
texture_origin = texture_origin * invsize;
texture_render_state.set_texture_origin_and_size(texture_origin, texture_size);
MemoryBlock light_block = m_mesher.create_light_array(light_array);
m_render.draw(node.get_mesh(), light_block);
m_render.copy_texture(node.get_mesh().get_dynamic_texture());
m_render.set_render_target(Render.RenderTarget.FrameBuffer);
// m_texture_render_state.disable();
return node;
}
public QuadNodeGenerator(string filename, Render render)
{
m_render = render;
m_instance = this;
m_synthesizer = new QuadSynthesizer();
m_reader = QuadTreeReader.create_reader(filename);
m_mesher = new HeightMapMesher();
m_normal_map_generator = new NormalMapGenerator(256, 0.0625f);
m_texture_render_state = m_render.create_state(RenderState.State.TextureState);
create_thread();
}
public void Dispose()
{
destroy_thread();
m_mesher.Dispose();
m_reader.Dispose();
m_synthesizer.Dispose();
m_texture_render_state.Dispose();
m_normal_map_generator.Dispose();
m_instance = null;
}
public QuadNode create_root()
{
return create_node(calculate_info(m_reader.create_info(0), null), null);
}
public void request_children(QuadNode parent)
{
for (int c = 0; c < 4; c++)
{
m_communicator.add_incoming_request(new Request(parent, parent.has_static_children(), parent.get_child_id(c), c));
}
}
public void update()
{
QuadInfo info = m_communicator.get_outgoing_response();
while (info != null)
{
m_ready_map.Add(info.get_id(), info);
info = null;//m_communicator.get_outgoing_response();
}
}
public QuadNode get_node(int id, QuadNode parent)
{
if (m_ready_map.Count != 0) {
QuadInfo info;
if (m_ready_map.TryGetValue (id, out info)) {
m_ready_map.Remove(id);
return create_node(info, parent);
}
}
return null;
}
}
} |
using ADHDmail.Config;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace ADHDmail.API
{
/// <summary>
/// The abstract, base class that represents a query used to retrieve messages from an email API.
/// </summary>
public abstract class Query
{
/// <summary>
/// Represents the fully constructed query for filtering use in querying email APIs.
/// </summary>
protected string RawQuery = string.Empty;
/// <summary>
/// Sets the <see cref="RawQuery"/> to <see cref="string.Empty"/> which represents a query
/// with no filtering. This will construct a query that will return all emails.
/// </summary>
protected Query()
{ }
/// <summary>
/// Constructs the <see cref="RawQuery"/> to contain the filters supplied.
/// </summary>
/// <param name="queryFilters">Represents the filters to apply to the query.</param>
[SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")]
protected Query(List<Filter> queryFilters)
{
RawQuery = ConstructQuery(queryFilters);
}
/// <summary>
/// Parses the <see cref="Filter"/>s provided into a query string that is usable
/// in an API query.
/// </summary>
/// <param name="queryFilters">Represents the filters to apply to the query.</param>
/// <returns>Returns the fully constructed query.</returns>
protected abstract string ConstructQuery(List<Filter> queryFilters);
/// <summary>
/// Represents the fully constructed query for use in the <see cref="GmailApi.GetMessage(string)"/>
/// method.
/// <para>If this returns <see cref="string.Empty"/>, then no filtering is applied to the query.</para>
/// </summary>
/// <returns>Returns the fully constructed query.</returns>
public override string ToString() => RawQuery;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using dreamscape;
using LiteNetLib;
using LiteNetLib.Utils;
namespace dreamhost.lua
{
public class Client : NetObject
{
public NetPeer peer;
public int Ping {
get
{
return peer.Ping;
}
}
public long RemoteTime
{
get {
return peer.RemoteTimeDelta;
}
}
public int Mtu
{
get
{
return peer.Mtu;
}
}
public Client(string name, NetPeer peer) : base(name)
{
this.peer = peer;
}
public override void Drop()
{
Drop("Your connection has been dropped.");
}
public void Drop(string reason)
{
NetDataWriter writer = new NetDataWriter();
writer.Put((byte)NetTypes.Goodbye);
writer.Put(reason);
peer.Send(writer, DeliveryMethod.ReliableOrdered);
peer.Disconnect();
}
}
}
|
#region "Imports"
using System;
using PayPal.Payments.Common.Utility;
using PayPal.Payments.Common.Exceptions;
#endregion
namespace PayPal.Payments.DataObjects
{
/// <summary>
/// Used for Magtek related information.
/// </summary>
/// <remarks>Use the MagtekInfo object for the Magtek
/// encrypted card reader related information.</remarks>
/// <example>
/// <para>Following example shows how to use the MagtekInfo object.</para>
/// <code lang="C#" escaped="false">
/// .................
/// // Swipe is the SwipeCard object
/// .................
/// // Set the Magtek Info details.
/// MagtekInfo MT = new MagtekInfo();
/// MT.DeviceSN = "Device Serial Number from reader";
/// MT.EncMP = "ENCMP from reader";
/// MT.EncryptionBlockType = "1";
/// MT.EncTrack1 = "Track 1 data from reader";
/// MT.EncTrack2 = "Track 2 data from reader";
/// MT.EncTrack3 = "";
/// MT.KSN = "KSN from reader";
/// MT.MagtekCardType = "1";
/// MT.MPStatus = "MPStatus from reader";
/// MT.RegisteredBy = "PayPal";
/// MT.SwipedECRHost = "MAGT";
/// // When using Encrypted Card Readers you do not populate the SwipeCard object as the data from the Magtek object
/// // will be used instead.
/// SwipeCard Swipe = new SwipeCard("");
/// Swipe.MagtekInfo = MT;
/// .................
/// </code>
/// <code lang="Visual Basic" escaped="false">
/// .................
/// ' Inv is the Invoice object
/// .................
/// ' Set the Browser Info details.
/// Dim Browser As BrowserInfo = New BrowserInfo
/// Browser.BrowserCountryCode = "USA"
/// Browser.BrowserUserAgent = "IE 6.0"
/// Inv.BrowserInfo = Browser
/// .................
/// </code>
/// </example>
public sealed class MagtekInfo : BaseRequestDataObject
{
#region "Member Variables"
/// <summary>
/// Holds Encrypted MagnePrint Information
/// </summary>
private String mEncMP;
/// <summary>
/// Holds Encryption Block
/// </summary>
private String mEncryptionBlockType;
/// <summary>
/// Holds Encrypted Track 1
/// </summary>
private String mEncTrack1;
/// <summary>
/// Holds Encrypted Track 2
/// </summary>
private String mEncTrack2;
/// <summary>
/// Holds Encrypted Track 3
/// </summary>
private String mEncTrack3;
/// <summary>
/// Holds KSN
/// </summary>
private String mKSN;
/// <summary>
/// Holds Card Type
/// /// </summary>
private String mMagtekCardType;
/// <summary>
/// Holds MP Status
/// </summary>
private String mMPStatus;
/// <summary>
/// Holds Registered By
/// </summary>
private String mRegisteredBy;
/// <summary>
/// Holds Swiped ECR Host
/// </summary>
private String mSwipedECRHost;
/// <summary>
/// Holds Device Serial Number
/// </summary>
private String mDeviceSN;
/// <summary>
/// Holds Merchant Id
/// </summary>
private String mMerchantId;
/// <summary>
/// Holds 4-digit PAN
/// </summary>
private String mPAN4;
/// <summary>
/// Holds Protection Code
/// </summary>
private String mPCode;
/// <summary>
/// Holds Authorization Value 1
/// </summary>
private String mAuthValue1;
/// <summary>
/// Holds Authorization Value 2
/// </summary>
private String mAuthValue2;
/// <summary>
/// Holds Authorization Value 3
/// </summary>
private String mAuthValue3;
/// <summary>
/// Holds Magtek User Name
/// </summary>
private String mMagtekUserName;
/// <summary>
/// Holds Magtek Password
/// </summary>
private String mMagtekPassword;
#endregion
#region "Constructors"
/// <summary>
/// Constructor for BrowserInfo
/// </summary>
/// <remarks>Use the MagtekInfo object for the Magtek
/// encrypted card reader related information.</remarks>
/// <example>
/// <para>Following example shows how to use a
/// Magtek Info object.</para>
/// <code lang="C#" escaped="false">
/// .................
/// // Swipe is the SwipeCard object
/// .................
/// // Set the MagtekInfo object.
/// MagtekInfo MT = new MagtekInfo();
/// MT.DeviceSN = "Device Serial Number from reader";
/// MT.EncMP = "ENCMP from reader";
/// MT.EncryptionBlockType = "1";
/// MT.EncTrack1 = "Track 1 data from reader";
/// // When using Encrypted Card Readers you do not populate the SwipeCard object as the data from the Magtek object
/// // will be used instead.
/// SwipeCard Swipe = new SwipeCard("");
/// Swipe.MagtekInfo = MT;
/// .................
/// .................
/// </code>
/// <code lang="Visual Basic" escaped="false">
/// .................
/// ' Inv is the Invoice object
/// .................
/// ' Set the Browser Info details.
/// Dim Browser As BrowserInfo = New BrowserInfo
/// Browser.BrowserCountryCode = "USA"
/// Browser.BrowserUserAgent = "IE 6.0"
/// Inv.BrowserInfo = Browser
/// .................
/// </code>
/// </example>
public MagtekInfo()
{
}
#endregion
#region "Properties"
/// <summary>
/// Gets, Sets Magtek Encrypted MagnePrint Information.
/// </summary>
/// <remarks>
/// <para>Encrypted MagnePrint Information returned by a MagneSafe device when a card is swiped.</para>
/// <para>Maps to Payflow Parameter:</para>
/// <code>ENCMP</code>
/// </remarks>
public String EncMP
{
get { return mEncMP; }
set { mEncMP = value; }
}
/// <summary>
/// Gets, Sets Magtek Encryption Block.
/// </summary>
/// <remarks>
/// <para>The code which indicates what type of Encryption Block is used.</para>
/// <para>Maps to Payflow Parameter:</para>
/// <code>ENCRYPTIONBLOCKTYPE</code>
/// </remarks>
public String EncryptionBlockType
{
get { return mEncryptionBlockType; }
set { mEncryptionBlockType = value; }
}
/// <summary>
/// Gets, Sets Magtek Encrypted Track 1.
/// </summary>
/// <remarks>
/// <para>Encrypted Track 1 information returned by a MagneSafe device when a card is swiped.</para>
/// <para>Maps to Payflow Parameter:</para>
/// <code>ENCTRACKE1</code>
/// </remarks>
public String EncTrack1
{
get { return mEncTrack1; }
set { mEncTrack1 = value; }
}
/// <summary>
/// Gets, Sets Magtek Encrypted Track 2.
/// </summary>
/// <remarks>
/// <para>Encrypted Track 2 information returned by a MagneSafe device when a card is swiped.</para>
/// <para>Maps to Payflow Parameter:</para>
/// <code>ENCTRACKE2</code>
/// </remarks>
public String EncTrack2
{
get { return mEncTrack2; }
set { mEncTrack2 = value; }
}
/// <summary>
/// Gets, Sets Magtek Encrypted Track 3.
/// </summary>
/// <remarks>
/// <para>Encrypted Track 3 information returned by a MagneSafe device when a card is swiped.</para>
/// <para>Maps to Payflow Parameter:</para>
/// <code>ENCTRACKE2</code>
/// </remarks>
public String EncTrack3
{
get { return mEncTrack3; }
set { mEncTrack3 = value; }
}
/// <summary>
/// Gets or Sets Magtek KSN
/// </summary>
/// <remarks>
/// <para>20 character string returned by a MagneSafe device when a card is swiped.</para>
/// <para>Maps to Payflow Parameter:</para>
/// <code>KSN</code>
/// </remarks>
public String KSN
{
get { return mKSN; }
set { mKSN = value; }
}
/// <summary>
/// Gets or Sets Magtek Card Data Format
/// </summary>
/// <remarks>
/// <para>The code which indicates what type of Card Data Format is being submitted.</para>
/// <para>Maps to Payflow Parameter:</para>
/// <code>MAGTEKCARDTYPE</code>
/// </remarks>
public String MagtekCardType
{
get { return mMagtekCardType; }
set { mMagtekCardType = value; }
}
/// <summary>
/// Gets or Sets Magtek MagnePrint Status
/// </summary>
/// <remarks>
/// <para>MagnePrint Status of Card Swipe. This is an alpha numeric string, returned by a MagneSafe device when a card is swiped.</para>
/// <para>Maps to Payflow Parameter:</para>
/// <code>MPSTATUS</code>
/// </remarks>
public String MPStatus
{
get { return mMPStatus; }
set { mMPStatus = value; }
}
/// <summary>
/// Gets or Sets Magtek Registered By
/// </summary>
/// <remarks>
/// <para>An alpha numeric entry between 1 and 20 characters long.</para>
/// <para>Maps to Payflow Parameter:</para>
/// <code>REGISTEREDBY</code>
/// </remarks>
public String RegisteredBy
{
get { return mRegisteredBy; }
set { mRegisteredBy = value; }
}
/// <summary>
/// Gets or Sets Magtek Swipe ECR Host
/// </summary>
/// <remarks>
/// <para>MAGT is the only value that is accepted in the SWIPEDECRHOST parameter.</para>
/// <para>Maps to Payflow Parameter:</para>
/// <code>SWIPEDECRHOST</code>
/// </remarks>
public String SwipedECRHost
{
get { return mSwipedECRHost; }
set { mSwipedECRHost = value; }
}
/// <summary>
/// Gets or Sets Magtek device serial number
/// </summary>
/// <remarks>
/// <para>The device serial number of the Magtek card reader.</para>
/// <para>Maps to Payflow Parameter:</para>
/// <code>DEVICESN</code>
/// </remarks>
public String DeviceSN
{
get { return mDeviceSN; }
set { mDeviceSN = value; }
}
/// <summary>
/// Gets or Sets Magtek Merchant Id
/// </summary>
/// <remarks>
/// <para>Your Merchant ID or the Merchant ID of the merchant redeeming the Protection Code.</para>
/// <para>Maps to Payflow Parameter:</para>
/// <code>MERCHANTID</code>
/// </remarks>
public String MerchantId
{
get { return mMerchantId; }
set { mMerchantId = value; }
}
/// <summary>
/// Gets or Sets Magtek PAN4
/// </summary>
/// <remarks>
/// <para>The last four digits of the PAN / account number encoded in the card.</para>
/// <para>Maps to Payflow Parameter:</para>
/// <code>PAN4</code>
/// </remarks>
public String PAN4
{
get { return mPAN4; }
set { mPAN4 = value; }
}
/// <summary>
/// Gets or Sets Magtek Protection Code
/// </summary>
/// <remarks>
/// <para>The generated Protection Code.</para>
/// <para>Maps to Payflow Parameter:</para>
/// <code>PCODE</code>
/// </remarks>
public String PCode
{
get { return mPCode; }
set { mPCode = value; }
}
/// <summary>
/// Gets or Sets Magtek Authentication Value 1
/// </summary>
/// <remarks>
/// <para>Authentication Value 1 generated with the PCode.</para>
/// <para>Maps to Payflow Parameter:</para>
/// <code>AUTHVALUE1</code>
/// </remarks>
public String AuthValue1
{
get { return mAuthValue1; }
set { mAuthValue1 = value; }
}
/// <summary>
/// Gets or Sets Magtek Authentication Value 2
/// </summary>
/// <remarks>
/// <para>Authentication Value 2 generated with the PCode.</para>
/// <para>Maps to Payflow Parameter:</para>
/// <code>AUTHVALUE2</code>
/// </remarks>
public String AuthValue2
{
get { return mAuthValue2; }
set { mAuthValue2 = value; }
}
/// <summary>
/// Gets or Sets Magtek Authentication Value 3
/// </summary>
/// <remarks>
/// <para>Authentication Value 3 generated with the PCode.</para>
/// <para>Maps to Payflow Parameter:</para>
/// <code>AUTHVALUE3</code>
/// </remarks>
public String AuthValue3
{
get { return mAuthValue3; }
set { mAuthValue3 = value; }
}
/// <summary>
/// Gets or Sets MagTek User Name
/// </summary>
/// <remarks>
/// <para> MagTek user name.</para>
/// <para>Maps to Payflow Parameter:</para>
/// <code>MAGTEKUSERNAME</code>
/// </remarks>
public String MagtekUserName
{
get { return mMagtekUserName; }
set { mMagtekUserName = value; }
}
/// <summary>
/// Gets or Sets Magtek password
/// </summary>
/// <remarks>
/// <para>Magtek password.</para>
/// <para>Maps to Payflow Parameter:</para>
/// <code>MAGTEKPWD</code>
/// </remarks>
public String MagtekPassword
{
get { return mMagtekPassword; }
set { mMagtekPassword = value; }
}
#endregion
#region "Core functions"
/// <summary>
/// Generates the transaction request.
/// </summary>
internal override void GenerateRequest()
{
try
{
RequestBuffer.Append(PayflowUtility.AppendToRequest(PayflowConstants.MAGTEK_PARAM_ENCMP, mEncMP));
RequestBuffer.Append(PayflowUtility.AppendToRequest(PayflowConstants.MAGTEK_PARAM_ENCRYPTIONBLOCKTYPE, mEncryptionBlockType));
RequestBuffer.Append(PayflowUtility.AppendToRequest(PayflowConstants.MAGTEK_PARAM_ENCTRACK1, mEncTrack1));
RequestBuffer.Append(PayflowUtility.AppendToRequest(PayflowConstants.MAGTEK_PARAM_ENCTRACK2, mEncTrack2));
RequestBuffer.Append(PayflowUtility.AppendToRequest(PayflowConstants.MAGTEK_PARAM_ENCTRACK3, mEncTrack3));
RequestBuffer.Append(PayflowUtility.AppendToRequest(PayflowConstants.MAGTEK_PARAM_KSN, mKSN));
RequestBuffer.Append(PayflowUtility.AppendToRequest(PayflowConstants.MAGTEK_PARAM_MAGTEKCARDTYPE, mMagtekCardType));
RequestBuffer.Append(PayflowUtility.AppendToRequest(PayflowConstants.MAGTEK_PARAM_REGISTEREDBY, mRegisteredBy));
RequestBuffer.Append(PayflowUtility.AppendToRequest(PayflowConstants.MAGTEK_PARAM_SWIPEDECRHOST, mSwipedECRHost));
RequestBuffer.Append(PayflowUtility.AppendToRequest(PayflowConstants.MAGTEK_PARAM_DEVICESN, mDeviceSN));
RequestBuffer.Append(PayflowUtility.AppendToRequest(PayflowConstants.MAGTEK_PARAM_MPSTATUS, mMPStatus));
RequestBuffer.Append(PayflowUtility.AppendToRequest(PayflowConstants.MAGTEK_PARAM_MERCHANTID, mMerchantId));
RequestBuffer.Append(PayflowUtility.AppendToRequest(PayflowConstants.MAGTEK_PARAM_PAN4, mPAN4));
RequestBuffer.Append(PayflowUtility.AppendToRequest(PayflowConstants.MAGTEK_PARAM_PCODE, mPCode));
RequestBuffer.Append(PayflowUtility.AppendToRequest(PayflowConstants.MAGTEK_PARAM_AUTHVALUE1, mAuthValue1));
RequestBuffer.Append(PayflowUtility.AppendToRequest(PayflowConstants.MAGTEK_PARAM_AUTHVALUE2, mAuthValue2));
RequestBuffer.Append(PayflowUtility.AppendToRequest(PayflowConstants.MAGTEK_PARAM_AUTHVALUE3, mAuthValue3));
RequestBuffer.Append(PayflowUtility.AppendToRequest(PayflowConstants.MAGTEK_PARAM_MAGTEKUSERNAME, mMagtekUserName));
RequestBuffer.Append(PayflowUtility.AppendToRequest(PayflowConstants.MAGTEK_PARAM_MAGTEKPWD, mMagtekPassword));
}
catch (BaseException)
{
throw;
}
catch (Exception Ex)
{
DataObjectException DEx = new DataObjectException(Ex);
throw DEx;
}
//catch
//{
// throw new Exception();
//}
}
#endregion
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.