content stringlengths 23 1.05M |
|---|
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Serilog.Context;
namespace Trill.APIGateway.Framework
{
internal class LogContextMiddleware : IMiddleware
{
private readonly CorrelationIdFactory _correlationIdFactory;
public LogContextMiddleware(CorrelationIdFactory correlationIdFactory)
{
_correlationIdFactory = correlationIdFactory;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var correlationId = _correlationIdFactory.Create();
using (LogContext.PushProperty("CorrelationId", correlationId))
{
await next(context);
}
}
}
} |
namespace Algorithms
{
using System;
public static class BubbleSort
{
public static void Sort<T>(T[] collection) where T : IComparable<T>
{
bool flag = false;
for (int i = 0; i < collection.Length - 1; i++)
{
for (int j = 0; j < collection.Length - i - 1; j++)
{
if (collection[j].CompareTo(collection[j + 1]) > 0)
{
T swap = collection[j];
collection[j] = collection[j + 1];
collection[j + 1] = swap;
flag = true;
}
}
if (!flag) break;
}
}
}
}
namespace Algorithms.Tests
{
using System;
using System.Diagnostics;
using System.Linq;
static class BubbleSortTest
{
static Random randomGenerator = new Random();
static void Main()
{
TestRunner();
TestForPerformance(10000);
TestForPerformance(20000);
TestForPerformance(30000);
}
static void TestRunner()
{
SortAndPrintResult(new int[] { 1, -2, 3, -4, 5, -6, 7, -8, 9, -10 });
SortAndPrintResult(new double[] { 1.1, -2.2, 3.3, -4.4, 5.5, -6.6, 7.7, -8.8, 9.9, -10.10 });
SortAndPrintResult(new string[] { "b", "d", "c", "a", "f", "w", "z" });
SortAndPrintResult(new char[] { 'z', 'b', 'd', 'c', 'w', 'a', 'f' });
}
static void SortAndPrintResult<T>(T[] collection) where T : IComparable<T>
{
Console.Write(string.Join(" ", collection) + " -> ");
BubbleSort.Sort(collection);
Console.WriteLine(string.Join(" ", collection));
}
static void TestForPerformance(int capacity)
{
Stopwatch sw = new Stopwatch();
var collection = new int[capacity];
for (int i = 0; i < capacity; i++)
collection[i] = randomGenerator.Next(int.MaxValue);
sw.Start();
BubbleSort.Sort(collection);
sw.Stop();
IsSortedCollection(collection);
Console.WriteLine(sw.Elapsed + " -> " + capacity + " elements.");
}
static void IsSortedCollection<T>(T[] collection) where T : IComparable<T>
{
var sortedCollection = new T[collection.Length];
Array.Copy(collection, sortedCollection, collection.Length);
Array.Sort(sortedCollection);
if (!sortedCollection.SequenceEqual(collection))
{
throw new InvalidOperationException();
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RBXAPI
{
public class GroupRole
{
internal uint _gid;
#region Constructors
internal GroupRole(uint gid)
{
_gid = gid;
}
#endregion
#region Properties
public string Name { get; internal set; }
public byte Rank { get; internal set; }
public uint RolesetId { get; internal set; }
#endregion
#region Methods
public static GroupRole ByName(Group tGroup, string Name)
{
List<GroupRole> roles = tGroup.Roles;
try
{
return roles.First(x => x.Name == Name);
}
catch (InvalidOperationException e)
{
throw new InvalidOperationException(String.Format("The role by name `{0}` does not exist.", Name), e);
}
}
public static GroupRole ByRank(Group tGroup, byte Rank)
{
List<GroupRole> roles = tGroup.Roles;
try
{
return roles.First(x => x.Rank == Rank);
}
catch (InvalidOperationException e)
{
throw new InvalidOperationException(String.Format("The role by rank `{0}` does not exist.", Rank), e);
}
}
public static GroupRole ByRoleSetId(Group tGroup, uint RolesetId)
{
List<GroupRole> roles = tGroup.Roles;
try
{
return roles.First(x => x.RolesetId == RolesetId);
}
catch (InvalidOperationException e)
{
throw new InvalidOperationException(String.Format("The role by id `{0}` does not exist.", RolesetId), e);
}
}
#endregion
}
}
|
using System.Net;
using System.Net.Http.Json;
using System.Net.Mime;
using System.Text;
using System.Text.Json;
using CustomerService.Domain.CustomerAggregate;
using CustomerService.Repositories;
using EventDriven.Sagas.Configuration.Abstractions.DTO;
using InventoryService.Domain.InventoryAggregate;
using InventoryService.Repositories;
using OrderService.Domain.OrderAggregate;
using OrderService.Repositories;
using OrderService.Sagas.Specs.Configuration;
using OrderService.Sagas.Specs.Helpers;
using OrderService.Sagas.Specs.Repositories;
using SagaConfigService.Repositories;
using Xunit;
namespace OrderService.Sagas.Specs.Steps;
[Binding]
public class CreateOrderSagaStepDefinitions
{
private HttpResponseMessage Response { get; set; } = null!;
private JsonSerializerOptions JsonSerializerOptions { get; } = new()
{
AllowTrailingCommas = true,
PropertyNameCaseInsensitive = true
};
public ISagaConfigDtoRepository SagaConfigRepository { get; }
public ICustomerRepository CustomerRepository { get; }
public IInventoryRepository InventoryRepository { get; }
public IOrderRepository OrderRepository { get; }
public OrderServiceSpecsSettings ServiceSpecsSettings { get; }
public HttpClient Client { get; }
public JsonFilesRepository JsonFilesRepo { get; }
public SagaConfigurationDto? SagaConfiguration { get; set; }
public Customer? Customer { get; set; }
public Inventory? Inventory { get; set; }
public Order? Order { get; set; }
public CreateOrderSagaStepDefinitions(
OrderServiceSpecsSettings serviceSpecsSettings,
HttpClient httpClient,
ISagaConfigDtoRepository sagaConfigRepository,
ICustomerRepository customerRepository,
IInventoryRepository inventoryRepository,
IOrderRepository orderRepository,
JsonFilesRepository jsonFilesRepo)
{
ServiceSpecsSettings = serviceSpecsSettings;
Client = httpClient;
SagaConfigRepository = sagaConfigRepository;
CustomerRepository = customerRepository;
InventoryRepository = inventoryRepository;
OrderRepository = orderRepository;
JsonFilesRepo = jsonFilesRepo;
}
[Given(@"a saga configuration has been created with '(.*)'")]
public async Task GivenASagaConfigurationHasBeenCreatedWith(string file)
{
var sagaConfigJson = JsonFilesRepo.Files[file];
SagaConfiguration = JsonSerializer.Deserialize<SagaConfigurationDto>(sagaConfigJson, JsonSerializerOptions);
if (SagaConfiguration != null)
await SagaConfigRepository.AddAsync(SagaConfiguration);
}
[Given(@"a customer has been created with '(.*)'")]
public async Task GivenHasBeenCreated(string file)
{
var customerJson = JsonFilesRepo.Files[file];
Customer = JsonSerializer.Deserialize<Customer>(customerJson, JsonSerializerOptions);
if (Customer != null)
await CustomerRepository.AddAsync(Customer);
}
[Given(@"the customer credit is (.*)")]
public async Task GivenTheCustomerCreditIs(decimal amount)
{
if (Customer != null)
{
Customer.CreditAvailable = amount;
await CustomerRepository.UpdateAsync(Customer);
}
}
[Given(@"inventory has been created with '(.*)'")]
public async Task GivenProductsHaveBeenCreatedWith(string file)
{
var inventoryJson = JsonFilesRepo.Files[file];
Inventory = JsonSerializer.Deserialize<Inventory>(inventoryJson, JsonSerializerOptions);
if (Inventory != null)
{
await InventoryRepository.AddAsync(Inventory);
}
}
[Given(@"the inventory quantity is (.*)")]
public async Task GivenTheInventoryQuantityIs(int quantity)
{
if (Inventory != null)
{
Inventory.AmountAvailable = quantity;
await InventoryRepository.UpdateAsync(Inventory);
}
}
[When(@"I make a POST request with '(.*)' to '(.*)'")]
public async Task WhenIMakeApostRequestWithTo(string file, string endpoint)
{
var json = JsonFilesRepo.Files[file];
var content = new StringContent(json, Encoding.UTF8, MediaTypeNames.Application.Json);
Response = await Client.PostAsync(endpoint, content);
}
[Then(@"the response status code is '(.*)'")]
public void ThenTheResponseStatusCodeIs(int statusCode)
{
var expected = (HttpStatusCode)statusCode;
Assert.Equal(expected, Response.StatusCode);
}
[Then(@"the location header is '(.*)'")]
public void ThenTheLocationHeaderIs(string location)
{
var fullLocation = location.Replace("id", ServiceSpecsSettings.OrderId.ToString());
Assert.Equal(new Uri(fullLocation, UriKind.Relative), Response.Headers.Location);
}
[Then(@"the response entity should be '(.*)'")]
public async Task ThenTheResponseEntityShouldBe(string file)
{
var json = JsonFilesRepo.Files[file];
Order = JsonSerializer.Deserialize<Order>(json, JsonSerializerOptions);
var actual = await Response.Content.ReadFromJsonAsync<Order>();
Assert.Equal(Order, actual, new OrderComparer()!);
}
[Then(@"the customer credit should equal (.*)")]
public async Task ThenTheCustomerCreditShouldEqual(decimal creditAvailable)
{
if (Customer == null) return;
await Task.Delay(ServiceSpecsSettings.SagaCompletionTimeout);
var customer = await CustomerRepository.GetAsync(Customer.Id);
Assert.Equal(creditAvailable, customer?.CreditAvailable);
}
[Then(@"the inventory quantity should equal (.*)")]
public async Task ThenTheInventoryLevelShouldBe(int amountAvailable)
{
if (Inventory == null) return;
await Task.Delay(ServiceSpecsSettings.SagaCompletionTimeout);
var inventory = await InventoryRepository.GetAsync(ServiceSpecsSettings.InventoryId);
Assert.Equal(amountAvailable, inventory?.AmountAvailable);
}
[Then(@"the order state should be '(.*)'")]
public async Task ThenTheOrderStateShouldBe(OrderState state)
{
if (Order == null) return;
await Task.Delay(ServiceSpecsSettings.SagaCompletionTimeout);
var orderState = await OrderRepository.GetOrderStateAsync(Order.Id);
Assert.Equal(state, orderState);
}
} |
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Cinemachine.Editor
{
[CustomEditor(typeof(CinemachineTrackedDolly))]
internal sealed class CinemachineTrackedDollyEditor : BaseEditor<CinemachineTrackedDolly>
{
protected override void GetExcludedPropertiesInInspector(List<string> excluded)
{
base.GetExcludedPropertiesInInspector(excluded);
switch (Target.m_CameraUp)
{
default:
break;
case CinemachineTrackedDolly.CameraUpMode.PathNoRoll:
case CinemachineTrackedDolly.CameraUpMode.FollowTargetNoRoll:
excluded.Add(FieldPath(x => x.m_RollDamping));
break;
case CinemachineTrackedDolly.CameraUpMode.Default:
excluded.Add(FieldPath(x => x.m_PitchDamping));
excluded.Add(FieldPath(x => x.m_YawDamping));
excluded.Add(FieldPath(x => x.m_RollDamping));
break;
}
}
public override void OnInspectorGUI()
{
BeginInspector();
if (Target.m_Path == null)
EditorGUILayout.HelpBox("A Path is required", MessageType.Warning);
if (Target.m_AutoDolly.m_Enabled && Target.FollowTarget == null)
EditorGUILayout.HelpBox("AutoDolly requires a Follow Target", MessageType.Warning);
DrawRemainingPropertiesInInspector();
}
/// Process a position drag from the user.
/// Called "magically" by the vcam editor, so don't change the signature.
public void OnVcamPositionDragged(Vector3 delta)
{
Undo.RegisterCompleteObjectUndo(Target, "Camera drag");
Quaternion targetOrientation = Target.m_Path.EvaluateOrientationAtUnit(
Target.m_PathPosition, Target.m_PositionUnits);
Vector3 localOffset = Quaternion.Inverse(targetOrientation) * delta;
Target.m_PathOffset += localOffset;
}
[DrawGizmo(GizmoType.Active | GizmoType.InSelectionHierarchy, typeof(CinemachineTrackedDolly))]
private static void DrawTrackeDollyGizmos(CinemachineTrackedDolly target, GizmoType selectionType)
{
if (target.IsValid)
{
CinemachinePathBase path = target.m_Path;
if (path != null)
{
var isActive = CinemachineCore.Instance.IsLive(target.VirtualCamera);
CinemachinePathEditor.DrawPathGizmo(path, path.m_Appearance.pathColor, isActive);
Vector3 pos = path.EvaluatePositionAtUnit(target.m_PathPosition, target.m_PositionUnits);
Color oldColor = Gizmos.color;
Gizmos.color = isActive
? CinemachineSettings.CinemachineCoreSettings.ActiveGizmoColour
: CinemachineSettings.CinemachineCoreSettings.InactiveGizmoColour;
Gizmos.DrawLine(pos, target.VirtualCamera.State.RawPosition);
Gizmos.color = oldColor;
}
}
}
}
}
|
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Assets.Arthur.Scripts
{
public class IntroManager : MonoBehaviour
{
private float _delayBeforeLoading = 4f;
[SerializeField] private string _sceneToLoad;
private float timeElapsed;
void Update()
{
timeElapsed += Time.deltaTime;
if (timeElapsed > _delayBeforeLoading)
{
SceneManager.LoadScene(_sceneToLoad);
}
}
}
}
|
using System;
using UnityEngine;
public class ColorPreset : BaseLabelStylePreset
{
public Color color;
public ColorPreset(Color col)
{
this.color = col;
}
}
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Known workspace kinds
/// </summary>
public static class WorkspaceKind
{
public const string Host = "Host";
public const string Debugger = "Debugger";
public const string Interactive = "Interactive";
public const string MetadataAsSource = "MetadataAsSource";
public const string MiscellaneousFiles = "MiscellaneousFiles";
public const string Preview = "Preview";
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NAudio.Wave;
using MathNet.Numerics;
using MathNet.Numerics.IntegralTransforms;
using System.Numerics;
namespace AudioLib
{
public class Analyzer
{
static readonly int WindowSize = 512;
static readonly int NoOverlap = 128;
readonly float[] sound;
public readonly int SampleRate;
public double FreqPerIndex { get { return SampleRate / (double)WindowSize; } }
public double[,] Spectrogram;
Complex[][] ComplexSpectrogram;
public double[][] ThresholdMask;
public double[] Pitch;//時間ごと最大成分周波数
public double[] PowerTime;//時間ごとボリューム(デシベル)
readonly long ActualDataLength;
static readonly double[] Hamming;
static Analyzer()
{
Hamming = Window.Hamming(WindowSize);
}
public Analyzer(string fileName)
{
using (var file = new WaveFileReader(fileName))
{
ActualDataLength = file.SampleCount / file.WaveFormat.Channels;
sound = new float[ActualDataLength];
for (int i = 0; i < ActualDataLength; i++)
{
sound[i] = file.ReadNextSampleFrame()[0];
}
SampleRate = file.WaveFormat.SampleRate;
}
}
/// <summary>
/// 最大値が1でない外部音声を正規化する
/// </summary>
public void Normalize()
{
var max = sound.Select(x => Math.Abs(x)).Max();
for (int i = 0; i < sound.Length; i++)
{
sound[i] /= max;
}
}
public Analyzer(float[] data, int sampleRate)
{
sound = data;
ActualDataLength = sound.Length;
SampleRate = sampleRate;
}
IEnumerable<double> GetWindowedData(int from, int length)
{
return Enumerable.Range(from, length)
.Select(x => sound.ElementAtOrDefault(x))
.Select((x, j) => x * Hamming[j]);
}
public void CalcSpectrogram(bool useMask)
{
Spectrogram = new double[ActualDataLength / NoOverlap, WindowSize / 2];
if (useMask)
{
ComplexSpectrogram = new Complex[ActualDataLength / NoOverlap][];
ThresholdMask = new double[ActualDataLength / NoOverlap][];
}
Enumerable.Range(0, Spectrogram.GetLength(0))
//.AsParallel()
.ForAll(i =>
{
var w = GetWindowedData(i * NoOverlap - WindowSize / 2, WindowSize)
.Select(x=>new Complex(x, 0))
.ToArray();
Fourier.Radix2Forward(w, FourierOptions.Matlab);
ComplexSpectrogram[i] = new Complex[WindowSize / 2];
for (int j = 0; j < w.Length / 2; j++)
{
if (useMask)
{
ComplexSpectrogram[i][j] = w[j];
}
Spectrogram[i, j] = w[j].Magnitude;
}
if(useMask)
{
ThresholdMask[i] = new ThresholdMasking(ComplexSpectrogram[i], SampleRate).Calc();
}
});
}
void CalcInner(ref double[] target, Func<int, double> func)
{
var tmp = Enumerable.Range(0, (int)ActualDataLength / NoOverlap)
.Select(i => func(i))
.ToArray();
target = new double[ActualDataLength];
double step;
for (int i = 0; i < tmp.Length - 1; i++)
{
step = (tmp[i + 1] - tmp[i]) / NoOverlap;
for (int j = 0; j < NoOverlap; j++)
{
target[i * NoOverlap + j] = tmp[i] + step * j;
}
}
for (int i = (tmp.Length - 1) * NoOverlap; i < ActualDataLength; i++)
{
target[i] = tmp[tmp.Length - 1];
}
}
/// <summary>
/// 長さActualDataLengthの配列
/// </summary>
public void CalcPower()
{
CalcInner(ref PowerTime, CalcPower);
}
IEnumerable<float> CreateFrame(int from, bool window)
{
var head = from * NoOverlap - WindowSize / 2;
return Enumerable.Range(head, WindowSize)
.SkipWhile(x => x < 0)
.TakeWhile(x => x < ActualDataLength)
.Select(x => sound[x] * (window ? (float) Hamming[x - head] : 1f));
}
double CalcPower(int from)
{
int c = 0;
double s = 0;
foreach (var i in CreateFrame(from, false))
{
s += Math.Abs(i);
c++;
}
if (c == 0)
{
return 0;
}
else
{
return s / c;
}
}
/// <summary>
/// 基本周波数を求める
/// </summary>
public void CalcPitch()
{
if (Pitch != null)
{
return;
}
CalcInner(ref Pitch, CalcPitch);
}
double CalcPitch(int from)
{
const double K = 0.8;
var n = CalcNormalizedSquareDifferenceFunction(CreateFrame(from, false).ToArray());
List<Tuple<double, int>> peaks = new List<Tuple<double, int>>();
bool stat = false;
double m = -1;
int t = -1;
for (int i = 1; i < n.Length; i++)
{
if (n[i] >= 0 && n[i - 1] < 0)
{
stat = true;
}
if (n[i] < 0 && n[i - 1] >= 0 && stat)
{
stat = false;
peaks.Add(Tuple.Create(m, t));
}
if (stat && n[i] > m)
{
m = n[i];
t = i;
}
}
if (!peaks.Any())
{
return 0;
}
var thr = peaks.Max(x => x.Item1) * K;
int time = peaks.First(x => x.Item1 >= thr).Item2;
return SampleRate / time;
}
double[] CalcNormalizedSquareDifferenceFunction(float[] f)
{
double[] n = new double[f.Length];
double m, r;
for (int tau = 0; tau < f.Length; tau++)
{
m = 0;
r = 0;
for (int j = 0; j < f.Length - tau - 1; j++)
{
m += f[j] * f[j] + f[j + tau] * f[j + tau];
r += f[j] * f[j + tau];
}
if(m != 0)
{
n[tau] = 2 * r / m;
}
else
{
n[tau] = 0;
}
}
return n;
}
}
}
|
namespace Moo2U.Services {
using System;
using System.Collections.Generic;
using Moo2U.Model;
using SQLite;
public class CustomerService : ICustomerService {
readonly SQLiteConnection _cn;
public CustomerService(ISQLiteConnectionService sqLiteConnectionService) {
if (sqLiteConnectionService == null) {
throw new ArgumentNullException(nameof(sqLiteConnectionService));
}
_cn = sqLiteConnectionService.GetConnection();
}
public IList<Customer> GetAll() {
return _cn.Query<Customer>("SELECT * FROM [Customer]");
}
public Int32 Insert(Customer customer) {
if (customer == null) {
throw new ArgumentNullException(nameof(customer));
}
return _cn.Insert(customer);
}
}
}
|
using System;
using Microsoft.AspNetCore.Http;
namespace GraphQL.Upload.AspNetCore
{
/// <summary>
/// Options for <see cref="GraphQLUploadMiddleware{TSchema}"/>.
/// </summary>
public class GraphQLUploadOptions
{
/// <summary>
/// The maximum allowed file size in bytes. Null indicates no limit at all.
/// </summary>
public long? MaximumFileSize { get; set; }
/// <summary>
/// The maximum allowed amount of files. Null indicates no limit at all.
/// </summary>
public long? MaximumFileCount { get; set; }
/// <summary>
/// Gets or sets the user context factory.
/// </summary>
public Func<HttpContext, object> UserContextFactory { get; set; }
}
}
|
using System;
using Blumind.Core;
using Blumind.Model;
namespace Blumind.Model.MindMaps
{
delegate void TopicEventHandler(object sender, TopicEventArgs e);
class TopicEventArgs : EventArgs
{
Topic _Topic;
ChangeTypes _Changes;
public TopicEventArgs(Topic topic)
{
Topic = topic;
}
public TopicEventArgs(Topic topic, ChangeTypes changes)
{
Topic = topic;
Changes = changes;
}
public Topic Topic
{
get { return _Topic; }
private set { _Topic = value; }
}
public ChangeTypes Changes
{
get { return _Changes; }
private set { _Changes = value; }
}
}
}
|
using ArcanaErp.Core.Interfaces.Models.BaseErpServices;
namespace ArcanaErp.Core.Models.Erp
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
using Lambda;
public partial class PostalAddress : IPostalAddress
{
public int Id { get; set; }
[StringLength(255)]
public string AddressLine1 { get; set; }
[StringLength(255)]
public string AddressLine2 { get; set; }
[StringLength(255)]
public string City { get; set; }
[StringLength(255)]
public string State { get; set; }
[StringLength(255)]
public string Zip { get; set; }
[StringLength(255)]
public string Country { get; set; }
[StringLength(255)]
public string Description { get; set; }
public int GeoCountryId { get; set; }
public int GeoZoneId { get; set; }
public decimal Latitude { get; set; }
public decimal Longitude { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
}
|
using System;
using System.Drawing;
using Northwoods.Go;
namespace ThreatsManager.Extensions.Panels.Diagram
{
[Serializable]
public sealed class WarningMarker : GoImage
{
public WarningMarker() {
Printable = false;
Resizable = false;
Deletable = false;
Copyable = false;
Selectable = false;
Image = Properties.Resources.report_problem_big;
Size = new SizeF(32.0f, 32.0f);
Visible = false;
}
// can't get any selection handles
public override void AddSelectionHandles(GoSelection sel, GoObject selectedObj) { }
public string Tooltip { get; set; }
public override string GetToolTip(GoView view)
{
return Tooltip;
}
}
} |
@model Redoak.Backoffice.Areas.Customer.Models.CustomerManage.CreateModel
<form asp-controller="CustomerManage"
asp-action="Create"
asp-area="Customer"
data-ajax="true"
data-ajax-method="POST"
data-ajax-success="Edit.CreateCallBack"
data-ajax-failure="Edit.CreateBackError">
<div asp-validation-summary="All" class="text-danger"></div>
@*@Html.TextBoxFor(x => x.Id)
@Html.TextBoxFor(x => x.RegionId)*@
@Html.HiddenFor(x => x.Id)
@Html.HiddenFor(x => x.RegionId)
@* 客戶名稱 *@
<div class="form-row ">
<div class="form-group col-md-2">
<label class="col-form-label" asp-for="Name"></label>
</div>
<div class="form-group col-md-4 input-group">
<input asp-for="Name" class="form-control" />
</div>
</div>
@* 聯繫人員 *@
<div class="form-row">
<div class="form-group col-md-2">
<label class="col-form-label" asp-for="ContactPerson"></label>
</div>
<div class="form-group col-md-4 input-group">
<input asp-for="ContactPerson" class="form-control" />
</div>
</div>
@* 地址 *@
<div class="form-row">
<div class="form-group col-md-2">
<label class="col-form-label" asp-for="Address"></label>
</div>
<div class="form-group col-md-4 input-group">
<input asp-for="Address" class="form-control" />
</div>
</div>
@* Email *@
<div class="form-row">
<div class="form-group col-md-2">
<label class="col-form-label" asp-for="ContactEmail"></label>
</div>
<div class="form-group col-md-4 input-group">
<input asp-for="ContactEmail" class="form-control" />
</div>
</div>
@* 聯繫電話 *@
<div class="form-row">
<div class="form-group col-md-2">
<label class="col-form-label" asp-for="ContactPhone"></label>
</div>
<div class="form-group col-md-4 input-group">
<input asp-for="ContactPhone" class="form-control" />
</div>
</div>
<div class="form-group">
<input type="submit" value="存檔" class="btn btn-dark" />
</div>
</form>
<script type="text/javascript">
var Edit = {
Instance: function () {
var instance = {}, that = this;
instance.InitElement = function () {
};
instance.Init = function () {
instance.InitElement();
};
instance.BindDataById = function (id) {
Base.Get({
data: { id: id },
url: "@(Url.Action("Edit"))",
callback: function(html) {
Index.Edit.html(html);
Index.Edit.removeClass('hidden');
}
});
}
return instance;
},
CreateCallBack: function () {
Index.Result.removeClass('hidden');
Index.Edit.addClass('hidden');
Result.ResultKendoGrid.Refresh();
},
CreateBackError: function (e) {
//Base.Error(e);
}
};
$(function () {
Edit.Instance().Init();
});
</script> |
namespace MyVote.Services.AppServer.Models
{
public sealed class PollResultItem
{
public string OptionText { get; set; }
public int PollOptionID { get; set; }
public int ResponseCount { get; set; }
}
}
|
using Delivery_System_Project.Reportes.CrystalReports;
using DeliverySystem.Libreria.Librerias;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Delivery_System_Project.Reportes.Forms
{
public partial class GFacturas : Form
{
FacturaLibreria facturaLibreria;
public GFacturas()
{
InitializeComponent();
this.facturaLibreria = new FacturaLibreria();
var facturas = this.facturaLibreria.GetAllToReport().ToList();
var source = new BindingSource();
source.DataSource = facturas;
var reporte = new CrystalReporteFacturasG();
reporte.SetDataSource(source);
crystalReportViewer1.ReportSource = reporte;
crystalReportViewer1.RefreshReport();
}
private void crystalReportViewer1_Load(object sender, EventArgs e)
{
}
}
}
|
namespace Root.Coding.Code.Api.E01D.Memory
{
public class CharArrayPoolApi: ArrayPoolApi_I<char>
{
public char[] Rent(int minimumLength)
{
// use System.Buffers shared pool
return System.Buffers.ArrayPool<char>.Shared.Rent(minimumLength);
}
public void Return(char[] array)
{
// use System.Buffers shared pool
System.Buffers.ArrayPool<char>.Shared.Return(array);
}
}
}
|
namespace ShallowDeepCopy
{
class Blog
{
public string URL { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace CypherBot.Core.Models
{
public class Creature
{
public int CreatureId { get; set; }
public string Name { get; set; }
public int Level { get; set; }
public string Motive { get; set; }
public string Environment { get; set; }
public int Health { get; set; }
public int DamageInflicted { get; set; }
public int Armor { get; set; }
public string Movement { get; set; }
public string Modifications { get; set; }
public string Combat { get; set; }
public string Interaction { get; set; }
public string Use { get; set; }
public string GMIntrusions { get; set; }
}
}
|
using System;
using System.Globalization;
using System.Windows.Data;
namespace VirtualBingo.UI.Shared.Converters
{
public class HeightToFontSizeForHeaderConverter : IValueConverter
{
private const double StartFontValue = 16;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is double))
{
return StartFontValue;
}
double height = (double) value,
increment = height / 600 - (height / 600 * 0.2);
if (increment <= 1)
{
increment = 1;
}
else if(increment > 1.5)
{
increment = 1.5;
}
return StartFontValue * increment;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
using FluentValidation;
using NerdBudget.Core.Models;
namespace NerdBudget.Core.Validators
{
/// <summary>
/// Represents a basic validator for Budget
/// </summary>
public class BudgetValidator : AbstractValidator<Budget>
{
public BudgetValidator()
{
CascadeMode = CascadeMode.Continue;
// strings
RuleFor(x => x.AccountId).NotNull().NotEmpty().Length(0, 2);
RuleFor(x => x.Id).NotNull().NotEmpty().Length(0, 2);
RuleFor(x => x.CategoryId).NotNull().NotEmpty().Length(0, 2);
RuleFor(x => x.Name).NotNull().NotEmpty().Length(0, 30);
RuleFor(x => x.Frequency).NotNull().NotEmpty().Length(0, 2);
// unique keys
RuleFor(x => x.AccountId).NotEmpty();
// causes issue with ng-repeat on duplicate messages
// RuleFor(x => x.Name).NotEmpty();
// foreign keys
//RuleFor(x => x.AccountId).NotEmpty();
//RuleFor(x => x.CategoryId).NotEmpty();
// to allow for dummy buckets
RuleFor(x => x.Amount).NotEqual(0).When(x => x.Frequency != BudgetFrequencies.NO.ToString());
RuleFor(x => x.Amount).Equal(0).When(x => x.Frequency == BudgetFrequencies.NO.ToString());
RuleFor(x => x.StartDate).NotNull().When(x => x.Frequency != BudgetFrequencies.NO.ToString());
}
}
} |
using Microsoft.Xna.Framework;
namespace OpenVIII
{
public partial class Module_main_menu_debug
{
#region Classes
public abstract class IGMDataItem//<T>
{
//protected T _data;
protected Rectangle _pos;
public bool Enabled { get; private set; } = true;
public Vector2 Scale { get; set; }
public IGMDataItem(Rectangle? pos = null, Vector2? scale = null)
{
_pos = pos ?? Rectangle.Empty;
Scale = scale ?? Menu.TextScale;
}
public virtual void Show() => Enabled = true;
public virtual void Hide() => Enabled = false;
/// <summary>
/// Where to draw this item.
/// </summary>
public virtual Rectangle Pos { get => _pos; set => _pos = value; }
public Color Color { get; set; } = Color.White;
//public virtual object Data { get; public set; }
//public virtual FF8String Data { get; public set; }
public abstract void Draw();
public static implicit operator Rectangle(IGMDataItem v) => v.Pos;
public static implicit operator Color(IGMDataItem v) => v.Color;
public static implicit operator IGMDataItem(IGMData v)
{
return new IGMDataItem_IGMData(v);
}
public virtual void ReInit()
{ }
public virtual bool Update()
{ return false; }
public virtual bool Inputs()
{ return false; }
}
#endregion Classes
}
} |
using System.Collections.Generic;
using UnityEngine;
namespace Prototype.Utils
{
public static class ObjectPool
{
public static void Release<T>(T obj) where T : new()
=> ObjectPool<T>.Release(obj);
}
public static class ObjectPool<T> where T : new()
{
private static List<T> pool = new List<T>(64);
private static T Allocator()
{
return new T();
}
public static T Get()
{
if (pool.IsEmpty())
return Allocator();
else
return pool.PopBack();
}
public static void Release(T obj)
{
pool.Add(obj);
}
}
} |
namespace Prolliance.Membership.DataTransfer.Models
{
/// <summary>
/// 权限对象操作表模型(唯一条件:AppKey + TargetCode + Code)
/// </summary>
public class OperationInfo : ModelBase
{
public string AppId { get; set; }
/// <summary>
/// TargetCode 用于指定操作属于那个权限对象,必须指定
/// </summary>
public string TargetId { get; set; }
/// <summary>
/// Code 是指操作的编码,在同一个 TargetCode 下必须唯一,必须指定
/// </summary>
public string Code { get; set; }
/// <summary>
/// Name 为操作的名称,可以重复,必须指定
/// </summary>
public string Name { get; set; }
/// <summary>
/// 操作的说明信息,通常可以省略
/// </summary>
public string Summary { get; set; }
public string AppKey { get; set; }
public string TargetCode { get; set; }
}
}
|
using GraphQL.Types;
using Microsoft.Extensions.Localization;
using OrchardCore.Apis.GraphQL.Queries;
using OrchardCore.Lists.Models;
namespace OrchardCore.Lists.GraphQL
{
public class ContainedInputObjectType : WhereInputObjectGraphType<ContainedPart>
{
public ContainedInputObjectType(IStringLocalizer<ContainedPart> S)
{
Name = "ContainedPartInput";
Description = S["the list part of the content item"];
AddScalarFilterFields<IdGraphType>("listContentItemId", S["the content item id of the parent list of the content item to filter"]);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
[RequireComponent(typeof(BoxCollider2D))]
public class CharacterController2D : MonoBehaviour {
// Move player in 2D space
public float maxSpeed = 3.4f;
public float jumpHeight = 6.5f;
public float gravityScale = 1.5f;
public Camera mainCamera;
bool facingRight = true;
float moveDirection = 0;
bool isGrounded = false;
Vector3 cameraPos;
Rigidbody2D r2d;
Collider2D mainCollider;
// Check every collider except Player and Ignore Raycast
LayerMask layerMask = ~(1<<2|1<<8);
Transform t;
// Use this for initialization
void Start() {
t=transform;
r2d=GetComponent<Rigidbody2D>();
mainCollider=GetComponent<Collider2D>();
r2d.freezeRotation=true;
r2d.collisionDetectionMode=CollisionDetectionMode2D.Continuous;
r2d.gravityScale=gravityScale;
facingRight=t.localScale.x>0;
gameObject.layer=0;
if(mainCamera)
cameraPos=mainCamera.transform.position;
}
// Update is called once per frame
void Update() {
// Movement controls
if((Input.GetKey(KeyCode.A)||Input.GetKey(KeyCode.D))&&(isGrounded||r2d.velocity.x>0.01f)) {
moveDirection=Input.GetKey(KeyCode.A) ? -1 : 1;
}
else {
if(isGrounded||r2d.velocity.magnitude<0.01f) {
moveDirection=0;
}
}
// Change facing direction
if(moveDirection!=0) {
if(moveDirection>0&&!facingRight) {
facingRight=true;
t.localScale=new Vector3(Mathf.Abs(t.localScale.x), t.localScale.y, transform.localScale.z);
}
if(moveDirection<0&&facingRight) {
facingRight=false;
t.localScale=new Vector3(-Mathf.Abs(t.localScale.x), t.localScale.y, t.localScale.z);
}
}
// Jumping
if(Input.GetKeyDown(KeyCode.W)&&isGrounded) {
r2d.velocity=new Vector2(r2d.velocity.x, jumpHeight);
}
// Camera follow
if(mainCamera)
mainCamera.transform.position=new Vector3(t.position.x, cameraPos.y, cameraPos.z);
}
void FixedUpdate() {
Bounds colliderBounds = mainCollider.bounds;
Vector3 groundCheckPos = colliderBounds.min+new Vector3(colliderBounds.size.x*0.5f, 0.1f, 0);
// Check if player is grounded
isGrounded=Physics2D.OverlapCircle(groundCheckPos, 0.23f, layerMask);
// Apply movement velocity
r2d.velocity=new Vector2((moveDirection)*maxSpeed, r2d.velocity.y);
// Simple debug
Debug.DrawLine(groundCheckPos, groundCheckPos-new Vector3(0, 0.23f, 0), isGrounded ? Color.green : Color.red);
}
} |
namespace Seq.Api.Model.Monitoring
{
public enum MeasurementDisplayPalette
{
Default,
Reds,
Greens,
Blues
}
}
|
using Depot.Api.Repositories;
using Microsoft.AspNetCore.Mvc;
namespace Depot.Api.Controllers
{
[Route("[controller]")]
public class LogsController : Controller
{
private readonly ILogRepository _repository;
public LogsController(ILogRepository repository)
{
_repository = repository;
}
[HttpGet]
public IActionResult Get() => Json(_repository.Logs);
}
} |
// Copyright (c) 2022, Olaf Kober <olaf.kober@outlook.com>
using System;
namespace Amarok.Contracts;
/// <summary>
/// This type serves the infrastructure and is not intended to be used directly.
/// </summary>
internal static class ExceptionResources
{
/// <summary>
/// Looks up a localized string similar to Empty collections are invalid..
/// </summary>
internal static String ArgumentEmptyCollection => "Empty collections are invalid.";
/// <summary>
/// Looks up a localized string similar to Empty strings are invalid..
/// </summary>
internal static String ArgumentEmptyString => "Empty strings are invalid.";
/// <summary>
/// Looks up a localized string similar to Types not assignable to a specific type are invalid..
/// </summary>
internal static String ArgumentIsAssignableTo =>
"Types not assignable to a specific type are invalid.";
/// <summary>
/// Looks up a localized string similar to Values exceeding the inclusive lower limit are invalid..
/// </summary>
internal static String ArgumentIsGreaterThan =>
"Values exceeding the inclusive lower limit are invalid.";
/// <summary>
/// Looks up a localized string similar to Types representing interface or abstract base classes
/// are invalid..
/// </summary>
internal static String ArgumentIsInstantiable =>
"Types representing interface or abstract base classes are invalid.";
/// <summary>
/// Looks up a localized string similar to Types representing concrete classes or value types are
/// invalid..
/// </summary>
internal static String ArgumentIsInterface =>
"Types representing concrete classes or value types are invalid.";
/// <summary>
/// Looks up a localized string similar to Values exceeding the inclusive upper limit are invalid..
/// </summary>
internal static String ArgumentIsLessThan =>
"Values exceeding the inclusive upper limit are invalid.";
/// <summary>
/// Looks up a localized string similar to Negative values are invalid..
/// </summary>
internal static String ArgumentIsPositive => "Negative values are invalid.";
/// <summary>
/// Looks up a localized string similar to Values exceeding the exclusive lower limit are invalid..
/// </summary>
internal static String ArgumentIsStrictlyGreaterThan =>
"Values exceeding the exclusive lower limit are invalid.";
/// <summary>
/// Looks up a localized string similar to Values exceeding the exclusive upper limit are invalid..
/// </summary>
internal static String ArgumentIsStrictlyLessThan =>
"Values exceeding the exclusive upper limit are invalid.";
/// <summary>
/// Looks up a localized string similar to Zero or negative values are invalid..
/// </summary>
internal static String ArgumentIsStrictlyPositive => "Zero or negative values are invalid.";
/// <summary>
/// Looks up a localized string similar to Types not derived from a specific base class are
/// invalid..
/// </summary>
internal static String ArgumentIsSubclassOf =>
"Types not derived from a specific base class are invalid.";
/// <summary>
/// Looks up a localized string similar to Null values are invalid..
/// </summary>
internal static String ArgumentNull => "Null values are invalid.";
/// <summary>
/// Looks up a localized string similar to Lower limit: .
/// </summary>
internal static String LowerLimit => "Lower limit: ";
/// <summary>
/// Looks up a localized string similar to Upper limit: .
/// </summary>
internal static String UpperLimit => "Upper limit: ";
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using ValidationApplication.Models;
namespace ValidationApplication.Pages
{
public class CreateBookModel : PageModel
{
[BindProperty]
public BookModel Input { get; set; }
public void OnGet()
{
}
public async Task<IActionResult> OnPostBook()
{
if (ModelState.IsValid)
{
return RedirectToPage("Success");
}
return Page();
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using Xunit;
namespace GCTest_selfref_cs
{
public class Test
{
[Fact]
public static int TestEntryPoint()
{
object aref = null;
object[] arr = new object[16];
for (int i = arr.GetLowerBound(0); i <= arr.GetUpperBound(0); i++)
arr[i] = arr;
aref = arr[11];
arr = null; //but keep reference to element
GC.Collect();
Array a2 = (Array)aref;
for (int i = a2.GetLowerBound(0); i <= a2.GetUpperBound(0); i++)
{
if (((Array)a2.GetValue(i)).GetLowerBound(0) != 0 ||
((Array)a2.GetValue(i)).GetUpperBound(0) != 15)
{
Console.WriteLine("TEST FAILED!");
return 1;
}
}
Console.WriteLine("TEST PASSED!");
return 100;
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
internal static partial class Interop
{
internal static partial class Sys
{
[LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_CreateAutoreleasePool")]
internal static partial IntPtr CreateAutoreleasePool();
[LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_DrainAutoreleasePool")]
internal static partial void DrainAutoreleasePool(IntPtr ptr);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.BssOpenApi.Model.V20171214;
namespace Aliyun.Acs.BssOpenApi.Transform.V20171214
{
public class QueryInvoicingCustomerListResponseUnmarshaller
{
public static QueryInvoicingCustomerListResponse Unmarshall(UnmarshallerContext _ctx)
{
QueryInvoicingCustomerListResponse queryInvoicingCustomerListResponse = new QueryInvoicingCustomerListResponse();
queryInvoicingCustomerListResponse.HttpResponse = _ctx.HttpResponse;
queryInvoicingCustomerListResponse.RequestId = _ctx.StringValue("QueryInvoicingCustomerList.RequestId");
queryInvoicingCustomerListResponse.Success = _ctx.BooleanValue("QueryInvoicingCustomerList.Success");
queryInvoicingCustomerListResponse.Code = _ctx.StringValue("QueryInvoicingCustomerList.Code");
queryInvoicingCustomerListResponse.Message = _ctx.StringValue("QueryInvoicingCustomerList.Message");
QueryInvoicingCustomerListResponse.QueryInvoicingCustomerList_Data data = new QueryInvoicingCustomerListResponse.QueryInvoicingCustomerList_Data();
List<QueryInvoicingCustomerListResponse.QueryInvoicingCustomerList_Data.QueryInvoicingCustomerList_CustomerInvoice> data_customerInvoiceList = new List<QueryInvoicingCustomerListResponse.QueryInvoicingCustomerList_Data.QueryInvoicingCustomerList_CustomerInvoice>();
for (int i = 0; i < _ctx.Length("QueryInvoicingCustomerList.Data.CustomerInvoiceList.Length"); i++) {
QueryInvoicingCustomerListResponse.QueryInvoicingCustomerList_Data.QueryInvoicingCustomerList_CustomerInvoice customerInvoice = new QueryInvoicingCustomerListResponse.QueryInvoicingCustomerList_Data.QueryInvoicingCustomerList_CustomerInvoice();
customerInvoice.Id = _ctx.LongValue("QueryInvoicingCustomerList.Data.CustomerInvoiceList["+ i +"].Id");
customerInvoice.UserId = _ctx.LongValue("QueryInvoicingCustomerList.Data.CustomerInvoiceList["+ i +"].UserId");
customerInvoice.UserNick = _ctx.StringValue("QueryInvoicingCustomerList.Data.CustomerInvoiceList["+ i +"].UserNick");
customerInvoice.InvoiceTitle = _ctx.StringValue("QueryInvoicingCustomerList.Data.CustomerInvoiceList["+ i +"].InvoiceTitle");
customerInvoice.CustomerType = _ctx.LongValue("QueryInvoicingCustomerList.Data.CustomerInvoiceList["+ i +"].CustomerType");
customerInvoice.TaxpayerType = _ctx.LongValue("QueryInvoicingCustomerList.Data.CustomerInvoiceList["+ i +"].TaxpayerType");
customerInvoice.Bank = _ctx.StringValue("QueryInvoicingCustomerList.Data.CustomerInvoiceList["+ i +"].Bank");
customerInvoice.BankNo = _ctx.StringValue("QueryInvoicingCustomerList.Data.CustomerInvoiceList["+ i +"].BankNo");
customerInvoice.OperatingLicenseAddress = _ctx.StringValue("QueryInvoicingCustomerList.Data.CustomerInvoiceList["+ i +"].OperatingLicenseAddress");
customerInvoice.OperatingLicensePhone = _ctx.StringValue("QueryInvoicingCustomerList.Data.CustomerInvoiceList["+ i +"].OperatingLicensePhone");
customerInvoice.RegisterNo = _ctx.StringValue("QueryInvoicingCustomerList.Data.CustomerInvoiceList["+ i +"].RegisterNo");
customerInvoice.StartCycle = _ctx.LongValue("QueryInvoicingCustomerList.Data.CustomerInvoiceList["+ i +"].StartCycle");
customerInvoice.Status = _ctx.LongValue("QueryInvoicingCustomerList.Data.CustomerInvoiceList["+ i +"].Status");
customerInvoice.GmtCreate = _ctx.StringValue("QueryInvoicingCustomerList.Data.CustomerInvoiceList["+ i +"].GmtCreate");
customerInvoice.TaxationLicense = _ctx.StringValue("QueryInvoicingCustomerList.Data.CustomerInvoiceList["+ i +"].TaxationLicense");
customerInvoice.AdjustType = _ctx.LongValue("QueryInvoicingCustomerList.Data.CustomerInvoiceList["+ i +"].AdjustType");
customerInvoice.EndCycle = _ctx.LongValue("QueryInvoicingCustomerList.Data.CustomerInvoiceList["+ i +"].EndCycle");
customerInvoice.TitleChangeInstructions = _ctx.StringValue("QueryInvoicingCustomerList.Data.CustomerInvoiceList["+ i +"].TitleChangeInstructions");
customerInvoice.IssueType = _ctx.LongValue("QueryInvoicingCustomerList.Data.CustomerInvoiceList["+ i +"].IssueType");
customerInvoice.Type = _ctx.LongValue("QueryInvoicingCustomerList.Data.CustomerInvoiceList["+ i +"].Type");
customerInvoice.DefaultRemark = _ctx.StringValue("QueryInvoicingCustomerList.Data.CustomerInvoiceList["+ i +"].DefaultRemark");
data_customerInvoiceList.Add(customerInvoice);
}
data.CustomerInvoiceList = data_customerInvoiceList;
queryInvoicingCustomerListResponse.Data = data;
return queryInvoicingCustomerListResponse;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cafeteria
{
class Customer
{
private int customerID;
private decimal customerBalance;
public int CustomerId { get { return customerID; } }
public decimal CustomerBalance { get { return customerBalance; } }
public Customer(int id, decimal balance)
{
customerID = id;
customerBalance = balance;
}
public decimal GetNewBalance(decimal total)
{
return customerBalance -= total;
}
}
}
|
@model Sunkist.FeaturedItemSlider.Models.FeaturedItemSliderWidgetEditViewModel
<div>
<fieldset>
<label for="GroupName">Featured Item Group:</label>
@Html.DropDownList("GroupName", new SelectList(Model.GroupNames, Model.SelectedGroup))
</fieldset>
</div> |
using NUnit.Framework;
using TestStack.White.UIItems;
namespace TestStack.White.UITests.ControlTests.Table
{
[TestFixture(WindowsFramework.WinForms)]
public class TableRowsTests : WhiteUITestBase
{
private UIItems.TableItems.Table table;
public TableRowsTests(WindowsFramework framework)
: base(framework)
{
}
[OneTimeSetUp]
public void Setup()
{
SelectDataGridTab();
table = MainWindow.Get<UIItems.TableItems.Table>("DataGrid");
}
[Test]
public void GetRowTest()
{
var rows = table.Rows;
Assert.That(rows.Get("Name", "Imran").Cells[0].Value, Is.EqualTo("Imran"));
}
[Test]
public void GetMultipleRowsTest()
{
var rows = table.Rows;
rows[1].Cells[0].Value = "Imran";
Assert.That(rows.GetMultipleRows("Name", "Imran")[0].Cells[0].Value, Is.EqualTo("Imran"));
Assert.That(rows.GetMultipleRows("Name", "Imran")[1].Cells[0].Value, Is.EqualTo("Imran"));
}
}
} |
@using TimeTracker.Managers.Models
@model Activity
<a href='@Url.Action("Index", "Logs")'><< Back to Logs</a>
<h1>Edit Activity</h1>
<form action='@Url.Action("Edit")' method="POST">
<div class="form-group">
<input class="form-control" type="text" name="name" placeholder="Activity Name" value="@Model.Name"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Update</button>
</div>
</form> |
using Blobs.Entities;
namespace Blobs.Interfaces
{
public interface IBehavior
{
bool IsTriggered { get; }
void Trigger(Blob source);
void ApplyPostTriggerEffect(Blob source);
}
}
|
@{
Layout="Shared/_Layout";
}
@if(Model["form-type"] == "cuisine-delete")
{
<div class="container">
<h1>Delete Cuisine</h1>
<hr/>
<h2>Are you sure you want to delete this cuisine and all of its restaurants?</h2>
<h4>@Model["cuisine"].GetName()</h4>
<form action='/cuisine/delete/@Model["cuisine"].GetId()' method="post">
<input type="hidden" name="_method" value="DELETE">
<button type="submit">Delete</button>
</form>
</div>
}
@if(Model["form-type"] == "restaurant-delete")
{
<div class="container">
<h1>Delete Restaurant</h1>
<hr/>
<h2>Are you sure you want to delete this restaurant?</h2>
<h4>@Model["restaurant"].GetName()</h4>
<form action='/restaurant/delete/@Model["restaurant"].GetId()' method="post">
<input type="hidden" name="_method" value="DELETE">
<button type="submit">Delete</button>
</form>
</div>
}
<p><a href="/">Back Home</a></p>
|
using System;
using System.Collections.Generic;
using System.Text;
namespace FileAndFolderDialog.Abstractions
{
public interface IFolderDialogService
{
/// <summary>
/// Displays a common dialog box that allows a user to select a folder
/// </summary>
/// <param name="options"></param>
/// <returns>The selected folder location, or null if cancelled</returns>
string ShowSelectFolderDialog(SelectFolderOptions options = null);
}
}
|
using System;
using MicrowaveOvenClasses.Interfaces;
namespace MicrowaveOvenClasses.Controllers
{
public class CookController : ICookController
{
// Since there is a 2-way association, this cannot be set until the UI object has been created
// It also demonstrates property dependency injection
public IUserInterface UI { set; private get; }
private bool isCooking = false;
private IDisplay myDisplay;
private IPowerTube myPowerTube;
private ITimer myTimer;
public CookController(
ITimer timer,
IDisplay display,
IPowerTube powerTube,
IUserInterface ui) : this(timer, display, powerTube)
{
UI = ui;
}
public CookController(
ITimer timer,
IDisplay display,
IPowerTube powerTube)
{
myTimer = timer;
myDisplay = display;
myPowerTube = powerTube;
timer.Expired += new EventHandler(OnTimerExpired);
timer.TimerTick += new EventHandler(OnTimerTick);
}
public void StartCooking(int power, int time)
{
myPowerTube.TurnOn(power);
myTimer.Start(time);
isCooking = true;
}
public void Stop()
{
isCooking = false;
myPowerTube.TurnOff();
myTimer.Stop();
}
public void OnTimerExpired(object sender, EventArgs e)
{
if (isCooking)
{
myPowerTube.TurnOff();
UI.CookingIsDone();
isCooking = false;
}
}
public void OnTimerTick(object sender, EventArgs e)
{
int remaining = myTimer.TimeRemaining;
myDisplay.ShowTime(remaining/60, remaining % 60);
}
}
} |
using UnityEngine;
public class AddPotion : MonoBehaviour
{
public void AddOnePotion(PlayerController playerController)
{
if (playerController.TryGetComponent<HealthPotion>(out var health))
{
health.Add();
var pickupDisplay = health.GetComponentInChildren<PickupDisplay>();
if (pickupDisplay != null)
{
pickupDisplay.PickupConfirmation();
}
}
}
}
|
using SqExpress.StatementSyntax;
namespace SqExpress.Syntax.Internal
{
internal class ExprStatement : IExprExec
{
public ExprStatement(IStatement statement)
{
this.Statement = statement;
}
public IStatement Statement { get; }
public TRes Accept<TRes, TArg>(IExprVisitor<TRes, TArg> visitor, TArg arg)
{
if (visitor is not IExprVisitorInternal<TRes, TArg> vi)
{
throw new SqExpressException($"Only internal visitors can work with \"{nameof(ExprStatement)}\"");
}
return vi.VisitExprStatement(this, arg);
}
}
} |
namespace Northwind.Services.Contracts
{
public interface IConfigurationService
{
string NorthwindApiUrl { get; set; }
}
}
|
using System.Collections.Generic;
namespace RTSFramework.Core.Models
{
public class CSharpFilesProgramModel : CSharpProgramModel
{
public List<CSharpFileElement> Files { get; } = new List<CSharpFileElement>();
}
} |
@{
Layout = "~/Views/Shared/_LayoutAlternate.cshtml";
}
<h2>Angular Basic (New Version)</h2>
<div class="container" ng-controller="mainController as main">
<p> {{main.myMessage}}</p>
<button type="button" data-ng-click="main.changeMessage()">Change Message</button>
</div>
@section scripts
{
<script type="text/javascript">
(function () {
"use strict";
angular.module(APPNAME)
.controller('mainController', MainController);
MainController.$inject = ['$scope', '$baseController'];
function MainController(
$scope
, $baseController) {
var vm = this;
$baseController.merge(vm, $baseController);
vm.$scope = $scope;
vm.myMessage = "Angular is rendering on the page";
vm.changeMessage = _changeMessage;
function _changeMessage() {
vm.myMessage = "Changed my message with a click";
}
}
})();
</script>
}
|
namespace AvoCommLib
{
namespace Enums
{
public enum Models
{
HP_3x1x16 = 8,
Dell_2161DS = 12,
BlackBox_KV121A_E = 15
}
}
} |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using transactions.core.Model;
using transactions.core.Repository;
namespace transactions.fileDB.Repository
{
public class InvoiceRepository : IInvoiceRepository
{
protected readonly string _databaseFileName;
protected List<Invoice> _invoices;
protected ShopTransactionRepository _shopTransactionRepository;
public InvoiceRepository(string invoiceFileName, string transactionFileName)
{
_databaseFileName = invoiceFileName;
_invoices = new List<Invoice>();
_shopTransactionRepository = new ShopTransactionRepository(transactionFileName);
LoadDataFromFile();
}
protected void LoadDataFromFile()
{
if (File.Exists(_databaseFileName))
{
string contents = File.ReadAllText(_databaseFileName);
_invoices = JsonConvert.DeserializeObject<List<Invoice>>(contents) ?? new List<Invoice>();
}
else
{
_invoices = new();
}
}
public void CommitToFile()
{
string contents = JsonConvert.SerializeObject(_invoices);
File.WriteAllText(_databaseFileName, contents);
}
public IEnumerable<Invoice> GetAll()
{
foreach(var invoice in _invoices)
{
invoice.Transactions = _shopTransactionRepository.GetByInvoiceId(invoice.Id);
}
return _invoices;
}
public Invoice? Get(int id)
{
if (id >= _invoices.Count)
{
return null;
}
else
{
Invoice invoice = _invoices[id];
invoice.Transactions = _shopTransactionRepository.GetByInvoiceId(id);
return invoice;
}
}
public int Create(Invoice invoice)
{
invoice.Id = _invoices.Count;
_invoices.Add(invoice);
SaveTransactionsForInvoice(invoice);
return invoice.Id;
}
public void Update(Invoice invoice)
{
_invoices[invoice.Id] = invoice;
SaveTransactionsForInvoice(invoice);
}
protected void SaveTransactionsForInvoice(Invoice invoice)
{
if (invoice.Transactions == null) return;
foreach (var transaction in invoice.Transactions)
{
transaction.InvoiceId = invoice.Id;
if (_shopTransactionRepository.Get(transaction.Id) != null)
{
_shopTransactionRepository.Update(transaction);
}
else
{
_shopTransactionRepository.Create(transaction);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
public sealed class BinaryHeap<T>
: IReadOnlyCollection<T>
{
private readonly List<T> _list;
private readonly Func<T, T, int> _compare;
public BinaryHeap(List<T> list, Func<T, T, int> compare)
{
_list = list;
_compare = compare;
}
public int Count => _list.Count;
public T Peek() => _list[0];
public void Enqueue(T value)
{
_list.Add(value);
var i = _list.Count - 1;
while (i > 0)
{
// Index of the parent.
var p = (i - 1) >> 1;
if (_compare(_list[p], value) <= 0)
break;
_list[i] = _list[p];
i = p;
}
_list[i] = value;
}
public T Dequeue()
{
var min = _list[0];
var item = _list[_list.Count - 1];
var i = 0;
while (true)
{
// Index of children.
var l = (i << 1) + 1;
var r = (i << 1) + 2;
if (l >= _list.Count)
break;
// Index of the smaller child.
var c = r < _list.Count && _compare(_list[r], _list[l]) < 0 ? r : l;
if (_compare(_list[c], item) >= 0)
break;
_list[i] = _list[c];
i = c;
}
_list[i] = item;
_list.RemoveAt(_list.Count - 1);
return min;
}
public IEnumerator<T> GetEnumerator() =>
_list.GetEnumerator();
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
=> GetEnumerator();
}
public static class BinaryHeap
{
public static BinaryHeap<T> Create<T>(Func<T, T, int> compare) =>
new BinaryHeap<T>(new List<T>(), compare);
public static BinaryHeap<T> Create<T>() =>
new BinaryHeap<T>(new List<T>(), Comparer<T>.Default.Compare);
public static BinaryHeap<T> FromEnumerable<T>(IEnumerable<T> source, Func<T, T, int> compare)
{
var list = new List<T>(source);
list.Sort(new Comparison<T>(compare));
return new BinaryHeap<T>(list, compare);
}
public static BinaryHeap<T> FromEnumerable<T>(IEnumerable<T> source) =>
FromEnumerable(source, Comparer<T>.Default.Compare);
}
|
using SimplePhotoViewer.UI;
namespace SimplePhotoViewer
{
public partial class App
{
public App()
{
var b = new AppBootstrapper();
}
}
} |
using Nemerle.Internal;
namespace Nemerle.Core
{
public static class ValueOptionStatic
{
public static ValueOption<T> VSome<T>(T value)
{
return new ValueOption<T>(value);
}
public static ValueOption<T> VNone<T>()
{
return default(ValueOption<T>);
}
}
[ExtensionPatternEncoding("VNone", "", "ValueOption where HasValue = false")]
[ExtensionPatternEncoding("VSome", "value", "ValueOption where (HasValue = true, Value = value)")]
public struct ValueOption<T>
{
private readonly T _value;
public readonly bool HasValue;
public T Value
{
get
{
if (this.HasValue)
{
return this._value;
}
throw new AssertionException("lib\\option.n", 234, "", "try use Value when it not set");
}
}
public bool IsSome
{
get
{
return this.HasValue;
}
}
public bool IsNone
{
get
{
return !this.HasValue;
}
}
public T GetValueOrDefault()
{
return this._value;
}
public T WithDefault(T defaultValue)
{
return (!this.HasValue) ? defaultValue : this.Value;
}
public ValueOption(T value)
{
this._value = value;
this.HasValue = true;
}
public static ValueOption<T> None()
{
return default(ValueOption<T>);
}
public static ValueOption<T> Some(T value)
{
return new ValueOption<T>(value);
}
public static ValueOption<TFrom> op_Implicit<TFrom>(TFrom? value) where TFrom : struct
{
if ((!value.HasValue))
{
return ValueOption<TFrom>.None();
}
else
{
return ValueOption<TFrom>.Some(value.Value);
}
}
}
}
|
namespace BTDB.KVDBLayer
{
interface IChunkStorage
{
IChunkStorageTransaction StartTransaction();
}
} |
using RestSharp.Tests.Integrated.Fixtures;
namespace RestSharp.Tests.Integrated;
[Collection(nameof(TestServerCollection))]
public class UploadFileTests {
readonly RestClient _client;
readonly string _path = AppDomain.CurrentDomain.BaseDirectory;
public UploadFileTests(TestServerFixture fixture) => _client = new RestClient(fixture.Server.Url);
[Fact]
public async Task Should_upload_from_file() {
const string filename = "Koala.jpg";
var path = Path.Combine(_path, "Assets", filename);
var request = new RestRequest("upload").AddFile("file", path);
var response = await _client.PostAsync<UploadResponse>(request);
var expected = new UploadResponse(filename, new FileInfo(path).Length, true);
response.Should().BeEquivalentTo(expected);
}
[Fact]
public async Task Should_upload_from_bytes() {
const string filename = "Koala.jpg";
var path = Path.Combine(_path, "Assets", filename);
var bytes = await File.ReadAllBytesAsync(path);
var request = new RestRequest("upload").AddFile("file", bytes, filename);
var response = await _client.PostAsync<UploadResponse>(request);
var expected = new UploadResponse(filename, new FileInfo(path).Length, true);
response.Should().BeEquivalentTo(expected);
}
[Fact]
public async Task Should_upload_from_stream() {
const string filename = "Koala.jpg";
var path = Path.Combine(_path, "Assets", filename);
var request = new RestRequest("upload").AddFile("file", () => File.OpenRead(path), filename);
var response = await _client.PostAsync<UploadResponse>(request);
var expected = new UploadResponse(filename, new FileInfo(path).Length, true);
response.Should().BeEquivalentTo(expected);
}
} |
using System.Collections.Generic;
namespace CLAP
{
/// <summary>
/// A verb execution context
/// </summary>
public class VerbExecutionContext
{
/// <summary>
/// The method that is executed
/// </summary>
public Method Method { get; private set; }
/// <summary>
/// The target object, if any, that the verb is executed on.
/// If the verb is static, this is null.
/// </summary>
public object Target { get; private set; }
/// <summary>
/// The input arguments
/// </summary>
public Dictionary<string, string> Input { get; set; }
internal VerbExecutionContext(
Method method,
object target,
Dictionary<string, string> input)
{
Method = method;
Target = target;
Input = input;
}
}
} |
using System;
using Xamarin.Forms.Platform.iOS;
using MonoTouch.UIKit;
using OxyPlot;
using OxyPlot.XamarinIOS;
using OxyPlot.Series;
using System.Collections.Generic;
using System.Drawing;
using OxyPlotDemo;
using OxyPlotDemo.iOS;
using Xamarin.Forms;
using System.ComponentModel;
[assembly: ExportRenderer (typeof (OxyPlotView), typeof (OxyPlotViewRenderer))]
namespace OxyPlotDemo.iOS
{
public class OxyPlotViewRenderer : ViewRenderer<OxyPlotView, PlotView>
{
protected override void OnElementChanged (ElementChangedEventArgs<OxyPlotView> e)
{
base.OnElementChanged (e);
var plotView = new PlotView ();
SetNativeControl (plotView);
Element.OnInvalidateDisplay += (s,ea) => {
Control.Model.InvalidatePlot(true);
Control.InvalidatePlot(true);
plotView.SetNeedsDisplay();
};
Control.Model = Element.Model;
}
public override void LayoutSubviews ()
{
base.LayoutSubviews ();
if (Control != null)
Control.Frame = new RectangleF (0, 0, (float) Element.Width, (float) Element.Height);
}
protected override void OnElementPropertyChanged (object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged (sender, e);
if (e.PropertyName == OxyPlotView.ModelProperty.PropertyName) {
Control.Model.InvalidatePlot(true);
Control.InvalidatePlot(true);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ExampleApp.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace ExampleApp.Pages {
public class IndexModel : PageModel {
public string Message { get; set; }
public List<Product> Products { get; set; }
private readonly ILogger<IndexModel> _logger;
private readonly IConfiguration _config;
public IProductRepository _productRepository { get; }
public IndexModel (ILogger<IndexModel> logger,
IProductRepository productRepository,
IConfiguration config) {
_logger = logger;
_productRepository = productRepository;
_config = config;
}
public void OnGet () {
Message = _config["MESSAGE"] ?? "NET Core And Docker";
Products = _productRepository.Products.ToList();
}
}
} |
namespace NextGenSoftware.Holochain.HoloNET.Client.MessagePack
{
public enum DateTimePackingFormat
{
Extension,
String,
Epoch,
}
}
|
/*
********************************************************************
*
* 曹旭升(sheng.c)
* E-mail: cao.silhouette@msn.com
* QQ: 279060597
* https://github.com/iccb1013
* http://shengxunwei.com
*
* © Copyright 2016
*
********************************************************************/
using Sheng.WeixinConstruction.Client.Shell.Models;
using Sheng.WeixinConstruction.Core;
using Sheng.WeixinConstruction.Infrastructure;
using Sheng.WeixinConstruction.Service;
using Sheng.WeixinConstruction.WeixinContract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Sheng.WeixinConstruction.Client.Shell.Controllers
{
public class PointCommodityController : ClientBasalController
{
private static readonly CampaignManager _campaignManager = CampaignManager.Instance;
private static readonly PointCommodityManager _pointCommodityManager = PointCommodityManager.Instance;
private static readonly InformationManager _informationManager = InformationManager.Instance;
private static readonly CustomFormManager _customFormManager = CustomFormManager.Instance;
private static readonly MovieManager _movieManager = MovieManager.Instance;
private static readonly ErrorMessage _errorMessage = ErrorMessage.Instance;
private static readonly PortalTemplatePool _portalTemplatePool = PortalTemplatePool.Instance;
public ActionResult PointCommodity(string domainId)
{
return View();
}
public ActionResult PointCommodityDetail(string domainId)
{
string strId = Request.QueryString["id"];
Guid id = Guid.Empty;
if (String.IsNullOrEmpty(strId) || Guid.TryParse(strId, out id) == false)
{
return RedirectToAction("PointCommodity", new { domainId = domainId });
}
PointCommodityDetailViewModel model = new PointCommodityDetailViewModel();
model.PointCommodity = _pointCommodityManager.GetPointCommodity(id);
if (model.PointCommodity == null)
{
return RedirectToAction("PointCommodity", new { domainId = domainId });
}
model.ShoppingCartPointCommodityCount = _pointCommodityManager.GetShoppingCartPointCommodityCount(
this.DomainContext, MemberContext.Member.Id);
return View(model);
}
public ActionResult OrderList(string domainId)
{
return View();
}
public ActionResult OrderDetail(string domainId)
{
string strId = Request.QueryString["id"];
Guid id = Guid.Empty;
if (String.IsNullOrEmpty(strId) || Guid.TryParse(strId, out id) == false)
{
return RedirectToAction("PointCommodity", new { domainId = domainId });
}
PointCommodityOrderDetailViewModel model = new PointCommodityOrderDetailViewModel();
model.Order = _pointCommodityManager.GetOrder(id);
if (model.Order == null)
{
return RedirectToAction("PointCommodity", new { domainId = domainId });
}
model.ItemList = _pointCommodityManager.GetOrderItemList(id);
model.LogList = _pointCommodityManager.GetOrderLogList(id);
return View(model);
}
/// <summary>
/// 购物车
/// </summary>
/// <returns></returns>
public ActionResult ShoppingCart()
{
return View();
}
/// <summary>
/// 结算
/// </summary>
/// <returns></returns>
public ActionResult Checkout()
{
return View();
}
}
} |
using Abp.Application.Services;
using BriefShop.UserDetails.Dto;
using System.Threading.Tasks;
namespace BriefShop.UserDetails
{
public interface IUserDetailAppService: IApplicationService
{
Task UpdateUserLastVisit(UpdateUserLastVisitInput input);
}
}
|
using Ocelot.Configuration.Creator;
using Shouldly;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class IdentityServerConfigurationCreatorTests
{
[Fact]
public void happy_path_only_exists_for_test_coverage_even_uncle_bob_probably_wouldnt_test_this()
{
var result = IdentityServerConfigurationCreator.GetIdentityServerConfiguration();
result.ApiName.ShouldBe("admin");
}
}
} |
namespace GSMailApi.Model.Files.Tasks
{
class DIFile
{
}
}
|
// Copyright (c) 2012-2015 Sharpex2D - Kevin Scholz (ThuCommix)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Globalization;
using Sharpex2D.Math;
namespace Sharpex2D.Input.Implementation.XInput
{
[Developer("ThuCommix", "developer@sharpex2d.de")]
[TestState(TestState.Tested)]
internal class Gamepad : IGamepad
{
/// <summary>
/// Maximum Controller input.
/// </summary>
internal const int MaxControllerCount = 4;
/// <summary>
/// StartIndex.
/// </summary>
internal const int FirstControllerIndex = 0;
/// <summary>
/// Gets the Available Controllers.
/// </summary>
private static readonly Gamepad[] Controllers;
private readonly int _playerIndex;
private XInputState _gamepadStateCurrent;
private XInputState _gamepadStatePrev = new XInputState();
private bool _isInitilized;
private bool _vibrationStopped = true;
private float _vibrationTime;
/// <summary>
/// Initializes a new Gamepad class.
/// </summary>
static Gamepad()
{
Controllers = new Gamepad[MaxControllerCount];
for (int i = FirstControllerIndex; i < MaxControllerCount; i++)
{
Controllers[i] = new Gamepad(i);
}
}
/// <summary>
/// Initializes a new Gamepad class.
/// </summary>
/// <param name="playerIndex">The Index.</param>
private Gamepad(int playerIndex)
{
_playerIndex = playerIndex;
_gamepadStatePrev.Copy(_gamepadStateCurrent);
}
/// <summary>
/// Gets the Gamepad BatteryInformation.
/// </summary>
public XInputBatteryInformation BatteryInformationGamepad { get; internal set; }
/// <summary>
/// Gets the Headset BatteryInformation.
/// </summary>
public XInputBatteryInformation BatteryInformationHeadset { get; internal set; }
/// <summary>
/// A value indicating whether the Controller is available.
/// </summary>
public bool IsAvailable { get; internal set; }
/// <summary>
/// Gets the BatteryLevel.
/// </summary>
public BatteryLevel BatteryLevel
{
get
{
var xinputBatteryType = (XInputBatteryType) BatteryInformationGamepad.BatteryType;
var xinputBatteryLevel = (XInputBatteryLevel) BatteryInformationGamepad.BatteryLevel;
System.Diagnostics.Debug.WriteLine(xinputBatteryType);
if (xinputBatteryType == XInputBatteryType.Wired)
{
return BatteryLevel.Wired;
}
var level = BatteryLevel.Full;
switch (xinputBatteryLevel)
{
case XInputBatteryLevel.Empty:
level = BatteryLevel.Empty;
break;
case XInputBatteryLevel.Full:
level = BatteryLevel.Full;
break;
case XInputBatteryLevel.Low:
level = BatteryLevel.Low;
break;
case XInputBatteryLevel.Medium:
level = BatteryLevel.Medium;
break;
}
return level;
}
}
/// <summary>
/// Gets the State.
/// </summary>
/// <returns>GamepadState.</returns>
public GamepadState GetState()
{
return
new GamepadState(
_gamepadStateCurrent.Gamepad.IsButtonPressed((int) ButtonFlags.XINPUT_GAMEPAD_DPAD_UP),
_gamepadStateCurrent.Gamepad.IsButtonPressed((int) ButtonFlags.XINPUT_GAMEPAD_DPAD_DOWN),
_gamepadStateCurrent.Gamepad.IsButtonPressed((int) ButtonFlags.XINPUT_GAMEPAD_DPAD_LEFT),
_gamepadStateCurrent.Gamepad.IsButtonPressed((int) ButtonFlags.XINPUT_GAMEPAD_DPAD_RIGHT),
_gamepadStateCurrent.Gamepad.IsButtonPressed((int) ButtonFlags.XINPUT_GAMEPAD_A),
_gamepadStateCurrent.Gamepad.IsButtonPressed((int) ButtonFlags.XINPUT_GAMEPAD_B),
_gamepadStateCurrent.Gamepad.IsButtonPressed((int) ButtonFlags.XINPUT_GAMEPAD_Y),
_gamepadStateCurrent.Gamepad.IsButtonPressed((int) ButtonFlags.XINPUT_GAMEPAD_X),
_gamepadStateCurrent.Gamepad.IsButtonPressed((int) ButtonFlags.XINPUT_GAMEPAD_BACK),
_gamepadStateCurrent.Gamepad.IsButtonPressed((int) ButtonFlags.XINPUT_GAMEPAD_START),
_gamepadStateCurrent.Gamepad.IsButtonPressed((int) ButtonFlags.XINPUT_GAMEPAD_LEFT_SHOULDER),
_gamepadStateCurrent.Gamepad.IsButtonPressed((int) ButtonFlags.XINPUT_GAMEPAD_RIGHT_SHOULDER),
_gamepadStateCurrent.Gamepad.IsButtonPressed((int) ButtonFlags.XINPUT_GAMEPAD_LEFT_THUMB),
_gamepadStateCurrent.Gamepad.IsButtonPressed((int) ButtonFlags.XINPUT_GAMEPAD_RIGHT_THUMB),
_gamepadStateCurrent.Gamepad.IsButtonPressed((int) ButtonFlags.XINPUT_GUIDE),
_gamepadStateCurrent.Gamepad.bLeftTrigger/255f, _gamepadStateCurrent.Gamepad.bRightTrigger/255f,
new Vector2(_gamepadStateCurrent.Gamepad.sThumbLX/32767f,
_gamepadStateCurrent.Gamepad.sThumbLY/32767f),
new Vector2(_gamepadStateCurrent.Gamepad.sThumbRX/32767f,
_gamepadStateCurrent.Gamepad.sThumbRY/32767f));
}
/// <summary>
/// Vibrates the controller.
/// </summary>
/// <param name="leftMotor">The LeftMotor.</param>
/// <param name="rightMotor">The RightMotor.</param>
/// <param name="length">The Length.</param>
public void Vibrate(float leftMotor, float rightMotor, float length)
{
leftMotor = (float) System.Math.Max(0d, System.Math.Min(1d, leftMotor));
rightMotor = (float) System.Math.Max(0d, System.Math.Min(1d, rightMotor));
var vibration = new XInputVibration
{
LeftMotorSpeed = (ushort) (65535d*leftMotor),
RightMotorSpeed = (ushort) (65535d*rightMotor)
};
Vibrate(vibration, length);
}
/// <summary>
/// Updates the object.
/// </summary>
/// <param name="gameTime">The GameTime.</param>
public void Update(GameTime gameTime)
{
int result = XInputInterops.XInputGetState(_playerIndex, ref _gamepadStateCurrent);
IsAvailable = (result == 0);
if (!IsAvailable) return;
UpdateBatteryState();
_gamepadStatePrev.Copy(_gamepadStateCurrent);
if (_vibrationTime > 0)
{
_vibrationTime -= gameTime.ElapsedGameTime;
}
if (_vibrationTime <= 0 && !_vibrationStopped)
{
var stopStrength = new XInputVibration {LeftMotorSpeed = 0, RightMotorSpeed = 0};
XInputInterops.XInputSetState(_playerIndex, ref stopStrength);
_vibrationStopped = true;
}
}
/// <summary>
/// Initializes the Device.
/// </summary>
public void Initialize()
{
if (!_isInitilized)
{
_isInitilized = true;
Update(new GameTime
{
ElapsedGameTime = 0,
IsRunningSlowly = false,
TotalGameTime = TimeSpan.FromSeconds(0)
});
}
}
/// <summary>
/// Retrieves the XBoxController.
/// </summary>
/// <param name="index">The Index.</param>
/// <returns>XboxController.</returns>
public static Gamepad Retrieve(int index)
{
return Controllers[index];
}
/// <summary>
/// Updates the BatteryState.
/// </summary>
internal void UpdateBatteryState()
{
XInputBatteryInformation headset = new XInputBatteryInformation(),
gamepad = new XInputBatteryInformation();
XInputInterops.XInputGetBatteryInformation(_playerIndex, (byte) BatteryDeviceType.BATTERY_DEVTYPE_GAMEPAD,
ref gamepad);
XInputInterops.XInputGetBatteryInformation(_playerIndex, (byte) BatteryDeviceType.BATTERY_DEVTYPE_HEADSET,
ref headset);
BatteryInformationHeadset = headset;
BatteryInformationGamepad = gamepad;
}
/// <summary>
/// Gets the Capabilities.
/// </summary>
/// <returns></returns>
public XInputCapabilities GetCapabilities()
{
var capabilities = new XInputCapabilities();
XInputInterops.XInputGetCapabilities(_playerIndex, XInputConstants.XINPUT_FLAG_GAMEPAD, ref capabilities);
return capabilities;
}
/// <summary>
/// Vibrates the controller.
/// </summary>
/// <param name="strength">The Strength.</param>
/// <param name="length">The Length.</param>
internal void Vibrate(XInputVibration strength, float length)
{
XInputInterops.XInputSetState(_playerIndex, ref strength);
_vibrationStopped = false;
_vibrationTime = length;
}
/// <summary>
/// Converts the object to string.
/// </summary>
/// <returns>String.</returns>
public override string ToString()
{
return _playerIndex.ToString(CultureInfo.InvariantCulture);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Rhino.Mocks;
using StickEmApp.Entities;
using StickEmApp.Windows.Builders;
namespace StickEmApp.Windows.UnitTest.Builders
{
[TestFixture]
public class VendorListItemBuilderTestFixture
{
private VendorListItemBuilder _builder;
[SetUp]
public void SetUp()
{
_builder = new VendorListItemBuilder();
}
[Test]
public void TestBuild()
{
//arrange
var id1 = Guid.NewGuid();
var id2 = Guid.NewGuid();
var working = new TestableVendor
{
Id = id1,
Name = "foo",
Required = new Money(105),
Returned = new Money(99),
Result = new SalesResult {NumberOfStickersReceived = 21, Difference = new Money(6)},
StartedAt = new DateTime(2016, 4, 12, 10, 30, 0)
};
var finished = new TestableVendor
{
Id = id2,
Name = "bar",
Required = new Money(55),
Returned = new Money(55),
Result = new SalesResult {NumberOfStickersReceived = 11, Difference = new Money(0)},
StartedAt = new DateTime(2016, 4, 12, 11, 30, 0)
};
finished.Finish(new DateTime(2016, 4, 12, 21, 30, 0));
var input = new List<Vendor> { working, finished };
//act
var result = _builder.BuildFrom(input);
//assert
Assert.That(result.Count, Is.EqualTo(2));
var resultItem = result.ElementAt(0);
Assert.That(resultItem.Id, Is.EqualTo(id1));
Assert.That(resultItem.Name, Is.EqualTo("foo"));
Assert.That(resultItem.NumberOfStickersReceived, Is.EqualTo(21));
Assert.That(resultItem.AmountRequired, Is.EqualTo(new Money(105)));
Assert.That(resultItem.AmountReturned, Is.EqualTo(new Money(99)));
Assert.That(resultItem.Difference, Is.EqualTo(new Money(6)));
Assert.That(resultItem.Status, Is.EqualTo(VendorStatus.Working));
Assert.That(resultItem.StartedAt, Is.EqualTo(new DateTime(2016, 4, 12, 10, 30, 0)));
Assert.That(resultItem.FinishedAt, Is.Null);
resultItem = result.ElementAt(1);
Assert.That(resultItem.Id, Is.EqualTo(id2));
Assert.That(resultItem.Name, Is.EqualTo("bar"));
Assert.That(resultItem.NumberOfStickersReceived, Is.EqualTo(11));
Assert.That(resultItem.AmountRequired, Is.EqualTo(new Money(55)));
Assert.That(resultItem.AmountReturned, Is.EqualTo(new Money(55)));
Assert.That(resultItem.Difference, Is.EqualTo(new Money(0)));
Assert.That(resultItem.Status, Is.EqualTo(VendorStatus.Finished));
Assert.That(resultItem.StartedAt, Is.EqualTo(new DateTime(2016, 4, 12, 11, 30, 0)));
Assert.That(resultItem.FinishedAt, Is.EqualTo(new DateTime(2016, 4, 12, 21, 30, 0)));
}
private class TestableVendor : Vendor
{
private SalesResult _result;
public SalesResult Result
{
set { _result = value; }
}
private Money _required;
public Money Required
{
set { _required = value; }
}
private Money _returned;
public Money Returned
{
set { _returned = value; }
}
public override Money CalculateTotalAmountRequired()
{
return _required;
}
public override Money CalculateTotalAmountReturned()
{
return _returned;
}
public override SalesResult CalculateSalesResult()
{
return _result;
}
}
}
} |
namespace AcrylicKeyboard.Interaction
{
public enum KeyModifier
{
None,
Shift,
Ctrl,
Alt,
Special
}
} |
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
namespace FancyZonesEditor.Models
{
public class LayoutHotkeysModel : INotifyPropertyChanged
{
public SortedDictionary<string, string> SelectedKeys { get; } = new SortedDictionary<string, string>()
{
{ Properties.Resources.Quick_Key_None, string.Empty },
{ "0", string.Empty },
{ "1", string.Empty },
{ "2", string.Empty },
{ "3", string.Empty },
{ "4", string.Empty },
{ "5", string.Empty },
{ "6", string.Empty },
{ "7", string.Empty },
{ "8", string.Empty },
{ "9", string.Empty },
};
public LayoutHotkeysModel()
{
}
public event PropertyChangedEventHandler PropertyChanged;
public void FreeKey(string key)
{
if (SelectedKeys.ContainsKey(key))
{
SelectedKeys[key] = string.Empty;
FirePropertyChanged();
}
}
public bool SelectKey(string key, string uuid)
{
if (!SelectedKeys.ContainsKey(key))
{
return false;
}
if (SelectedKeys[key] == uuid)
{
return true;
}
// clean previous value
foreach (var pair in SelectedKeys)
{
if (pair.Value == uuid)
{
SelectedKeys[pair.Key] = string.Empty;
break;
}
}
SelectedKeys[key] = uuid;
FirePropertyChanged();
return true;
}
public void CleanUp()
{
var keys = SelectedKeys.Keys.ToList();
foreach (var key in keys)
{
SelectedKeys[key] = string.Empty;
}
FirePropertyChanged();
}
protected virtual void FirePropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Platform.WindowManagement;
using Microsoft.VisualStudio.PlatformUI.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text.Editor;
namespace Vim.VisualStudio.Specific
{
#if VS_SPECIFIC_2012 || VS_SPECIFIC_2013
internal partial class SharedService
{
private void InitPeek() { }
private bool ClosePeekView(ITextView textView) => false;
}
#else
internal partial class SharedService
{
private IPeekBroker _peekBroker;
private void InitPeek()
{
_peekBroker = ExportProvider.GetExportedValue<IPeekBroker>();
}
private bool ClosePeekView(ITextView peekView)
{
if (peekView.TryGetPeekViewHostView(out var hostView))
{
_peekBroker.DismissPeekSession(hostView);
return true;
}
return false;
}
}
#endif
}
|
using System;
using System.Collections;
using System.Data;
using System.Linq;
using AutoFixture;
using Moq;
using Netsoft.Glaucus.Moq.Tests;
using Netsoft.Glaucus.Providers;
using Xunit;
namespace Netsoft.Glaucus.Tests
{
public class DbEngineTest
{
private readonly DbEngine target;
private readonly Fixture fixture = new Fixture();
private readonly Mock<IDbProvider> dbProviderMock = null;
public DbEngineTest()
{
this.dbProviderMock = new Mock<IDbProvider>();
this.target = new DbEngine(
this.dbProviderMock.Object,
"ApplicarionTest");
}
#region HasTable
[Fact]
public void HasTable_Tablename_Exists()
{
// Arranje
var tableName = this.fixture.Create<string>();
this.dbProviderMock
.Setup(x => x.HasTable(It.IsAny<string>()))
.Returns(true);
// Act
var result = this.target.HasTable(tableName);
// Assert
dbProviderMock.Verify(x => x.HasTable(tableName), Times.Once);
Assert.True(result);
}
[Fact]
public void HasTable_Tablename_DoesNotExists()
{
// Arranje
var tableName = this.fixture.Create<string>();
this.dbProviderMock
.Setup(x => x.HasTable(It.IsAny<string>()))
.Returns(false);
// Act
var result = this.target.HasTable(tableName);
// Assert
dbProviderMock.Verify(x => x.HasTable(tableName), Times.Once);
Assert.False(result);
}
[Fact]
public void HasTable_Tablename_NotImplemented()
{
// Arranje
var tableName = this.fixture.Create<string>();
this.dbProviderMock
.Setup(x => x.HasTable(It.IsAny<string>()))
.Throws<NotImplementedException>();
// Act
Action act = () => this.target.HasTable(tableName);
// Assert
Assert.Throws<NotImplementedException>(act);
}
#endregion HasTable
#region HasField
[Fact]
public void HasField_TablenameFieldName_Exists()
{
// Arranje
var tableName = this.fixture.Create<string>();
var fieldName = this.fixture.Create<string>();
this.dbProviderMock
.Setup(x => x.HasField(It.IsAny<string>(), It.IsAny<string>()))
.Returns(true);
// Act
var result = this.target.HasField(tableName, fieldName);
// Assert
dbProviderMock.Verify(x => x.HasField(tableName, fieldName), Times.Once);
Assert.True(result);
}
[Fact]
public void HasField_TablenameFieldName_DoesNotExists()
{
// Arranje
var tableName = this.fixture.Create<string>();
var fieldName = this.fixture.Create<string>();
this.dbProviderMock
.Setup(x => x.HasField(It.IsAny<string>(), It.IsAny<string>()))
.Returns(false);
// Act
var result = this.target.HasField(tableName, fieldName);
// Assert
dbProviderMock.Verify(x => x.HasField(tableName, fieldName), Times.Once);
Assert.False(result);
}
[Fact]
public void HasField_TablenameFieldName_NotImplemented()
{
// Arranje
var tableName = this.fixture.Create<string>();
var fieldName = this.fixture.Create<string>();
this.dbProviderMock
.Setup(x => x.HasField(It.IsAny<string>(), It.IsAny<string>()))
.Throws<NotImplementedException>();
// Act
Action act = () => this.target.HasField(tableName, fieldName);
// Assert
Assert.Throws<NotImplementedException>(act);
}
#endregion HasField
#region GetQuerySchema
[Fact]
public void GetQuerySchema_querySQL_Success()
{
// Arranje
var querySQL = this.fixture.Create<string>();
var expected = this.fixture.Build<DbFields>()
.Do(x =>
{
x.Add(this.fixture.Create<string>(), this.fixture.Create<object>());
x.Add(this.fixture.Create<string>(), this.fixture.Create<object>());
x.Add(this.fixture.Create<string>(), this.fixture.Create<object>());
})
.Create();
this.dbProviderMock
.Setup(x => x.GetQuerySchema(It.IsAny<string>()))
.Returns(expected);
// Act
var result = this.target.GetQuerySchema(querySQL);
// Assert
dbProviderMock.Verify(x => x.GetQuerySchema(querySQL), Times.Once);
Assert.True(result.Count == 3);
Assert.Equal(expected, result);
}
#endregion
#region ExecuteSP
[Fact]
public void ExecuteSP_Parameters_Success()
{
// Arranje
var spName = this.fixture.Create<string>();
var parameters = this.fixture.Create<DbParameters>();
var returnParams = this.fixture.CreateMany<string>().ToArray();
var expected = this.fixture.Create<Hashtable>();
this.dbProviderMock
.Setup(x => x.ExecuteSP(It.IsAny<string>(), It.IsAny<DbParameters>(), It.IsAny<string[]>()))
.Returns(expected);
// Act
var result = this.target.ExecuteSP(spName, parameters, returnParams);
// Assert
dbProviderMock.Verify(x => x.ExecuteSP(spName, parameters, returnParams), Times.Once);
Assert.Equal(expected, result);
}
[Fact]
public void ExecuteSP_ParametersDataTable_Success()
{
// Arranje
var spName = this.fixture.Create<string>();
var parameters = this.fixture.Create<DbParameters>();
this.fixture.Register(() => new DataTable(
this.fixture.Create<string>(),
this.fixture.Create<string>()));
var dataTable = this.fixture.Create<DataTable>();
var returnParams = this.fixture.CreateMany<string>().ToArray();
var expected = this.fixture.Create<Hashtable>();
this.dbProviderMock
.Setup(x => x.ExecuteSP(It.IsAny<string>(), It.IsAny<DbParameters>(), ref dataTable, It.IsAny<string[]>()))
.Returns(expected);
// Act
var result = this.target.ExecuteSP(spName, parameters, ref dataTable, returnParams);
// Assert
dbProviderMock.Verify(x => x.ExecuteSP(spName, parameters, ref dataTable, returnParams), Times.Once);
Assert.NotNull(dataTable);
Assert.Equal(expected, result);
}
#endregion
#region ExecuteNonQuery
[Fact]
public void ExecuteNonQuery_QueryParameters_Success()
{
// Arranje
var query = this.fixture.Create<string>();
var parameters = this.fixture.Create<DbParameters>();
var expected = this.fixture.Create<int>();
this.dbProviderMock
.Setup(x => x.ExecuteNonQuery(It.IsAny<string>(), It.IsAny<DbParameters>()))
.Returns(expected);
// Act
var result = this.target.ExecuteNonQuery(query, parameters);
// Assert
dbProviderMock.Verify(x => x.ExecuteNonQuery(query, parameters), Times.Once);
Assert.Equal(expected, result);
}
#endregion ExecuteNonQuery
#region ExecuteNonQuery
[Fact]
public void ExecuteScalar_QueryParameters_Success()
{
// Arranje
var query = this.fixture.Create<string>();
var parameters = this.fixture.Create<DbParameters>();
var expected = this.fixture.Create<object>();
this.dbProviderMock
.Setup(x => x.ExecuteScalar(It.IsAny<string>(), It.IsAny<DbParameters>()))
.Returns(expected);
// Act
var result = this.target.ExecuteScalar(query, parameters);
// Assert
dbProviderMock.Verify(x => x.ExecuteScalar(query, parameters), Times.Once);
Assert.Equal(expected, result);
}
#endregion ExecuteNonQuery
#region Insert
[Fact]
public void Insert_TableNameDbFields_Success()
{
// Arranje
var tableName = this.fixture.Create<string>();
var values = this.fixture.Build<DbFields>()
.Do(x =>
{
x.Add(this.fixture.Create<string>(), this.fixture.Create<string>());
x.Add(this.fixture.Create<string>(), this.fixture.Create<int>());
x.Add(this.fixture.Create<string>(), this.fixture.Create<double>());
})
.Create();
var expected = this.fixture.Create<object>();
this.dbProviderMock
.Setup(x => x.Insert(It.IsAny<string>(), It.IsAny<DbFields>(), null))
.Returns(expected);
// Act
var result = this.target.Insert(tableName, values);
// Assert
dbProviderMock.Verify(x => x.Insert(tableName, values, null), Times.Once);
Assert.Equal(expected, result);
}
[Fact]
public void Insert_TableNameModelMoq_Success()
{
// Arranje
DbFields dbFields = null;
var tableName = this.fixture.Create<string>();
var value = this.fixture.Create<ModelMoq>();
var fieldCount = typeof(ModelMoq).GetProperties().Count();
var expected = this.fixture.Create<object>();
this.dbProviderMock
.Setup(x => x.Insert(It.IsAny<string>(), It.IsAny<DbFields>(), It.IsAny<string>()))
.Callback<string, DbFields, string>((param1, param2, param3) => dbFields = param2)
.Returns(expected);
// Act
var result = this.target.Insert(tableName, value, string.Empty);
// Assert
dbProviderMock.Verify(x => x.Insert(tableName, It.IsAny<DbFields>(), null), Times.Once);
Assert.True(dbFields.Count == fieldCount);
Assert.Equal(expected, result);
}
[Fact]
public void Insert_TableNameModelMoqIgnoreFields_Success()
{
// Arranje
var idField = "Id";
var ignoreField = new[] { "id", "version" };
DbFields dbFields = null;
var tableName = this.fixture.Create<string>();
var value = this.fixture.Create<ModelMoq>();
var fieldCount = typeof(ModelMoq).GetProperties().Count();
var expected = this.fixture.Create<object>();
this.dbProviderMock
.Setup(x => x.Insert(It.IsAny<string>(), It.IsAny<DbFields>(), It.IsAny<string>()))
.Callback<string, DbFields, string>((param1, param2, param3) => dbFields = param2)
.Returns(expected);
// Act
var result = this.target.Insert(tableName, value, idField, ignoreField);
// Assert
dbProviderMock.Verify(x => x.Insert(tableName, It.IsAny<DbFields>(), idField), Times.Once);
Assert.True(dbFields.Count == fieldCount - ignoreField.Count());
Assert.Equal(expected, result);
}
#endregion Insert
#region Update
[Fact]
public void Update_TableNameModelMoq_Success()
{
// Arranje
var idField = "Id";
DbFields dbFields = null;
DbParameters dbParameters = null;
var tableName = this.fixture.Create<string>();
var value = this.fixture.Create<ModelMoq>();
var propertyCount = typeof(ModelMoq).GetProperties().Count();
var expected = this.fixture.Create<int>();
this.dbProviderMock
.Setup(x => x.Update(It.IsAny<string>(), It.IsAny<DbFields>(), It.IsAny<string>(), It.IsAny<DbParameters>()))
.Callback<string, DbFields, string, DbParameters>((param1, param2, param3, param4) =>
{
dbFields = param2;
dbParameters = param4;
})
.Returns(expected);
// Act
var result = this.target.Update(tableName, value, idField);
// Assert
dbProviderMock.Verify(x => x.Update(tableName, dbFields, It.IsAny<string>(), It.IsAny<DbParameters>()), Times.Once);
Assert.True(dbFields.Count == propertyCount - 1);
Assert.True(dbParameters.Count == 1);
Assert.Equal(expected, result);
}
[Fact]
public void Update_TableNameModelMoqIgnoreFields_Success()
{
// Arranje
var idField = "Id";
var ignoreField = new[] { "version" };
DbFields dbFields = null;
DbParameters dbParameters = null;
var tableName = this.fixture.Create<string>();
var value = this.fixture.Create<ModelMoq>();
var propertyCount = typeof(ModelMoq).GetProperties().Count();
var expected = this.fixture.Create<int>();
this.dbProviderMock
.Setup(x => x.Update(It.IsAny<string>(), It.IsAny<DbFields>(), It.IsAny<string>(), It.IsAny<DbParameters>()))
.Callback<string, DbFields, string, DbParameters>((param1, param2, param3, param4) =>
{
dbFields = param2;
dbParameters = param4;
})
.Returns(expected);
// Act
var result = this.target.Update(tableName, value, idField, ignoreField);
// Assert
dbProviderMock.Verify(x => x.Update(tableName, dbFields, It.IsAny<string>(), It.IsAny<DbParameters>()), Times.Once);
Assert.True(dbFields.Count == propertyCount - ignoreField.Count() - 1);
Assert.True(dbParameters.Count == 1);
Assert.Equal(expected, result);
}
#endregion Insert
#region Transaction
[Fact]
public void WithTransactions_NoParams_Success()
{
// Arranje
var transactionMock = new Mock<IDisposable>();
this.dbProviderMock
.Setup(x => x.WithTransactions())
.Returns(transactionMock.Object);
// Act
var result = this.target.WithTransactions();
// Assert
dbProviderMock.Verify(x => x.WithTransactions(), Times.Once);
Assert.NotNull(result);
}
[Fact]
public void RollbackTransaction_NoParams_Success()
{
// Arranje
// Act
this.target.RollbackTransaction();
// Assert
dbProviderMock.Verify(x => x.RollbackTransaction(), Times.Once);
}
#endregion Transaction
}
}
|
using LH.Dhcp.Serialization;
using LH.Dhcp.UnitTests.Extensions;
using Xunit;
namespace LH.Dhcp.UnitTests.Serialization
{
// ReSharper disable once InconsistentNaming
public class DhcpBinaryReader_CanReadWithLengthShould
{
private static readonly byte[] TestBytes = "00112233445566778899aabbccddeeff".AsHexBytes();
[Fact]
public void ReturnFalse_WhenAtEnd()
{
var reader = new DhcpBinaryReader(TestBytes);
reader.ReadValueToEnd();
Assert.False(reader.CanRead(1));
}
[Fact]
public void ReturnFalse_GivenLengthBeyondLimit()
{
var reader = new DhcpBinaryReader(TestBytes);
reader.ReadValue(10);
Assert.False(reader.CanRead(20));
}
[Fact]
public void ReturnFalse_WhenAtLimit()
{
var reader = new DhcpBinaryReader(TestBytes, 2, 4);
reader.ReadValue(4);
Assert.False(reader.CanRead(1));
}
[Fact]
public void ReturnTrue_WhenInMiddle_GivenOffset()
{
var reader = new DhcpBinaryReader(TestBytes, 2, 10);
reader.ReadValue(4);
Assert.True(reader.CanRead(2));
}
[Fact]
public void ReturnTrue_WhenOnStart_GivenNoOffset()
{
var reader = new DhcpBinaryReader(TestBytes);
Assert.True(reader.CanRead(2));
}
[Fact]
public void ReturnTrue_WhenOnStart_GivenOffset()
{
var reader = new DhcpBinaryReader(TestBytes, 2, 10);
Assert.True(reader.CanRead(2));
}
}
} |
namespace uScoober.Hardware.Boards
{
internal interface IDuinoAnalogChannels
{
AnalogChannel PinA0 { get; }
AnalogChannel PinA1 { get; }
AnalogChannel PinA2 { get; }
AnalogChannel PinA3 { get; }
AnalogChannel PinA4 { get; }
AnalogChannel PinA5 { get; }
}
} |
/*
* Copyright 2013-2018 Guardtime, Inc.
*
* This file is part of the Guardtime client SDK.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES, CONDITIONS, OR OTHER LICENSES OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
* "Guardtime" and "KSI" are trademarks or registered trademarks of
* Guardtime, Inc., and no license to trademarks is granted; Guardtime
* reserves and retains all trademark rights.
*/
using System;
namespace Guardtime.KSI.Utils
{
/// <summary>
/// CRC 32 calculation class.
/// </summary>
public static class Crc32
{
private static readonly uint[] Crc32Table =
{
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba,
0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec,
0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940,
0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116,
0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a,
0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818,
0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c,
0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086,
0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4,
0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe,
0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252,
0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60,
0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04,
0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a,
0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e,
0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0,
0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6,
0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
};
/// <summary>
/// Calculate crc32 from data bytes.
/// </summary>
/// <param name="data">data bytes</param>
/// <param name="ival">start value</param>
/// <returns>crc32 value</returns>
public static ulong Calculate(byte[] data, ulong ival)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
ulong retval = ival ^ 0xffffffff;
for (int i = 0; i < data.Length; i++)
{
retval = Crc32Table[(retval ^ data[i]) & 0xff] ^ (retval >> 8);
}
return retval ^ 0xffffffff;
}
}
} |
using System;
namespace Atata.WebDriverSetup
{
/// <summary>
/// Represents the Chrome driver (<c>chromedriver.exe</c>/<c>chromedriver</c>) setup strategy.
/// </summary>
public class ChromeDriverSetupStrategy :
IDriverSetupStrategy,
IGetsDriverLatestVersion,
IGetsInstalledBrowserVersion,
IGetsDriverVersionCorrespondingToBrowserVersion
{
private const string BaseUrl =
"https://chromedriver.storage.googleapis.com";
private const string DriverLatestVersionUrl =
BaseUrl + "/LATEST_RELEASE";
private const string DriverSpecificVersionUrlFormat =
DriverLatestVersionUrl + "_{0}";
private readonly IHttpRequestExecutor httpRequestExecutor;
/// <summary>
/// Initializes a new instance of the <see cref="ChromeDriverSetupStrategy"/> class.
/// </summary>
/// <param name="httpRequestExecutor">The HTTP request executor.</param>
public ChromeDriverSetupStrategy(IHttpRequestExecutor httpRequestExecutor)
{
this.httpRequestExecutor = httpRequestExecutor;
}
/// <inheritdoc/>
public string DriverBinaryFileName { get; } =
OSInfo.IsWindows
? "chromedriver.exe"
: "chromedriver";
/// <inheritdoc/>
public string GetDriverLatestVersion() =>
httpRequestExecutor.DownloadString(DriverLatestVersionUrl).Trim();
/// <inheritdoc/>
public Uri GetDriverDownloadUrl(string version, Architecture architecture) =>
new Uri($"{BaseUrl}/{version}/{GetDriverDownloadFileName()}");
private static string GetDriverDownloadFileName() =>
OSInfo.IsLinux
? "chromedriver_linux64.zip"
: OSInfo.IsOSX
? "chromedriver_mac64.zip"
: "chromedriver_win32.zip";
/// <inheritdoc/>
public string GetInstalledBrowserVersion() =>
OSInfo.IsWindows
? AppVersionDetector.GetFromProgramFiles(@"Google\Chrome\Application\chrome.exe")
?? AppVersionDetector.GetFromBLBeaconInRegistry(@"Google\Chrome")
?? AppVersionDetector.GetByApplicationPathInRegistry("chrome.exe")
: OSInfo.IsLinux
? AppVersionDetector.GetThroughCli("google-chrome", "--product-version")
: AppVersionDetector.GetThroughOSXApplicationCli("Google Chrome");
/// <inheritdoc/>
public string GetDriverVersionCorrespondingToBrowserVersion(string browserVersion)
{
int browserVersionNumbersCount = VersionUtils.GetNumbersCount(browserVersion);
string browserVersionToUse = browserVersionNumbersCount == 1
? browserVersion
: browserVersionNumbersCount == 2
? VersionUtils.TrimMinor(browserVersion)
: VersionUtils.TrimRevision(browserVersion);
string url = string.Format(DriverSpecificVersionUrlFormat, browserVersionToUse);
return httpRequestExecutor.DownloadString(url);
}
}
}
|
using System;
namespace ShereSoft
{
partial class Zip2City
{
static readonly ulong[] CS11000 =
{
139896848976413822,
124044943029540018,
656365672611880840,
1132984173435555269,
455573430536181318,
510673640216794533,
555252320172732675,
1089192582415829215,
485912748646123741,
273209126867770341,
193909988973051691,
50950756335864302,
510673589383236494,
774374044251239683,
844974964520590334,
530848890511498230,
251794722566143310,
852181692213999794,
851465590100891056,
124044941143561102,
1118615640341882568,
845692853744670278,
525991210048808403,
1118158237585089007,
1151760384893353950,
1151760384893353950,
1151760384893353950,
1151760384893353950,
1151760384893353950,
1151760384893353950,
1151760384893353950,
1151760384893353950,
1151760384893353950,
1151760384893353950,
1151760384893353950,
1151760384893353950,
1151760384893353950,
1151760384893353950,
656321983203737566,
656392438286470885,
649980936288090153,
344769144589427603,
1138764684108648001,
543318479090099782,
496711122631493362,
510179221643951022,
700490244036724243,
292920419233811106,
160064230210843941,
249474755045848683,
656389468097811762,
1115957582900639913,
1116282443349851950,
1116109820355640591,
349702358963551809,
755448531096442252,
558150737815215086,
654484536917222020,
814212076071696883,
833660044680174561,
722211242969627561,
50218974374861816,
424555853141625998,
1115888273224965049,
1151760384893353748,
140143315674709118,
292322284889237129,
249716498491473684,
397835384023503154,
481942204269840605,
665872473317739983,
555119523203548549,
560944045998196959,
736886336324703309,
560943403087216220,
520128148182341262,
560944010384357343,
1049865355006224014,
1133135362905859838,
672255272914248350,
702076627645793799,
560943763677497876,
1073381911717361850,
852193676771348038,
544817140053480880,
320469897703725238,
777114638193270053,
166973561279448713,
656299176719586689,
251499699424743733,
1115921991338698418,
1116494649089817641,
731467942067142062,
1130627327445841964,
415321208717104710,
491542742310656958,
726629529603873769,
359073146198457326,
194087669760334756,
1150936511167034416,
454085307385418206,
759060572759560641,
752548180086749426,
104294073989971666,
1031567365333571973,
249885543162283394,
1114046569782480788,
728960488692128702,
51972699401796047,
658694210724436117,
284438063277806886,
1018820906607851570,
728352911353158956,
1050943327878714748,
325881429928342150,
185387999107648658,
1114604533903131794,
1114604554061577150,
1114604554061577150,
1114604554061577150,
1114604554061577150,
1114604554061577150,
1114604554061577150,
1114604554061577150,
1114604554061577150,
1114604554061577150,
1114604554061577150,
1114604554061577150,
793949534104288190,
464582063342373614,
1062186227528153573,
248885015827870342,
51840192317863828,
339534829341776812,
130936325973686932,
728456103485386920,
533189935231352252,
1046755059960519609,
291709903298818694,
114239952768693638,
1031567354842369637,
44104245284352239,
689685439617847517,
193992218314638799,
550439294186999161,
752812445170913909,
860898822101389039,
1057277469845600545,
111339283727250054,
728385734929461448,
592773362674665212,
1049830125046037409,
730307159337957342,
1114604554061577144,
1114604554061577150,
1114604554061577150,
1114604554061577150,
1114604554061577150,
1114604554061577150,
1114604554061577150,
1114604554061577150,
1114604554061577150,
1114604554061577150,
1114604554061577150,
1114604554061577150,
1114604554061577150,
1114604554061577150,
249913425606441918,
1114407407827115924,
456233506783796158,
456235149398844452,
456234711838716523,
196996352771246252,
1151759359434339295,
1151760384893353950,
189833610628399070,
1116856353875055169,
520715947873369022,
503255335742929913,
359136230678854643,
359131970054585326,
70917811705674732,
764452088243190770,
251499175924416140,
1116662258180018581,
443268650033708303,
734833306547042476,
1073398927407952179,
697447952916265638,
742483949155474932,
1037012695216332239,
672407553638189110,
51322143744702956,
716924440854629998,
244563330322452532,
57019609206097062,
287894580644543789,
344597113674575937,
194045153547603333,
129976726029859982,
1116856422596216799,
1116856353877359614,
511371035981872596,
288194091159768869,
1030382076130989281,
726453102098689068,
520209780352400111,
287971313429946849,
1127517255718058273,
527469231379784743,
52617836725830911,
446197870397267948,
1116856391188866501,
1151760384893352999,
1115765673145892830,
1115765673775070175,
1115765673775070175,
1115765673775070175,
1116191184775019487,
45034862155890157,
730752921676980873,
1115764869210687656,
1115765673775070175,
1115765671627586527,
45012942448854271,
722125426751754284,
433750306261967913,
744505025592613633,
285284969226342868,
1126461727657366913,
1062215072709785918,
287493668577705950,
887615998374909313,
402142113599718655,
654390397041376847,
193698694614880050,
1121922949033055315,
287786139059728702,
285008213828015489,
1116828261929293185,
54552962379545911,
484323191065907167,
1046529645966565353,
433752131069325351,
819428869656690185,
1059981080143463677,
187906139959373863,
61128491377747538,
433750698823143054,
433752620819291180,
49963182086305836,
755460625738119476,
284229942022021112,
433752541593572993,
1079517704490373164,
287619908527075367,
45002340307349889,
445900323644974476,
587029300998355433,
338193558118442383,
857463118215033328,
592569294924062710,
1138757644551495649,
1113883105606119463,
770539122346393303,
1115765673775052240,
1115695302883343325,
194087665858381053,
359128316538781486,
45002047761087468,
431198016579602124,
412629780672847859,
1115758732050234297,
1115765673775070175,
44931983094449407,
62348080715343564,
438304965610431961,
182854555667496747,
654467152265708940,
698490671372434703,
484668648340061325,
70923601474684159,
798443836234759162,
695174197809426825,
824666749031434420,
520209708025557377,
54727134614442629,
565399048194211807,
59265918703194703,
1026864662773276652,
450403933256823085,
443270354614784449,
689685781012065452,
92367740098657500,
649925016815707717,
287143144248264866,
128396482974092865,
287971076503981097,
164425268568560193,
1024749854950471109,
1115765673590313251,
1079699570668127199,
503255335703640030,
520129518141144041,
698022188752719839,
1144652044803439583,
1116856325254331518,
328637605171429013,
44958424401212212,
1103269355997041810,
923558858772251901,
164425296287284860,
1079699570490995141,
510193229378844638,
44958424362700924,
46362542284936338,
1116856422595858399,
288194091160665086,
412397555215929921,
345119594331021299,
56889218179309484,
510193229445113417,
649923268973831772,
1079497642874910884,
164425333711278398,
288194091160634821,
1130444601939890753,
654650479497699998,
1116485853706681517,
51304798000250447,
1130754180851579871,
1116856322133839230,
598492152725765603,
443272697768615905,
236482959794452652,
1115810753063039145,
431200353072936747,
863544852135082995,
319909686853804001,
1079699819397913893,
1013737942466951134,
285942222625394312,
491333130810333761,
550719022902058917,
287577322400292850,
55132997457850945,
698019962885880799,
1151760167964163039,
1151760384893353950,
1151758185870098398,
452655730868020990,
287739775228449217,
1118352185044810305,
285571083033593895,
1145461287562689089,
524713322087417150,
45028786512910917,
604797780133287378,
743285873354701793,
56929688005606515,
743149533914770578,
649925495919879891,
649924780039458994,
1116659575740321970,
201044876295372233,
45005669041468052,
546497194942404178,
916992261175156712,
914193023096731615,
160967898828941279,
196996730208270303,
649925332496569309,
60988133703404850,
690600233493136639,
510859269958270544,
1133128429748878989,
46665182637698558,
1116134198637823231,
359151892889337620,
1116856422596836334,
1116856422596836286,
1133146718152391678,
921030096376009342,
921030073601578067,
417752813026029878,
515438170380214259,
927297742819656959,
287164110425654525,
1116309043055922785,
160069977015099326,
288000185752716541,
685953456990242401,
1061335474608593971,
1137200013368740903,
130568223907793959,
685954054353266655,
1116856393036773876,
742012017967070206,
45002466953320911,
328628221404101812,
917157213333674804,
1133393047949605853,
339902118414502398,
814223587665235340,
1116634287037395337,
288194091160665086,
544899891417814657,
1134243533354042623,
527187962397872167,
287787755533632767,
456033423850859137,
1142477488788697893,
698490527898031143,
913293979763646398,
758011859067110653,
551340484599551284,
1116567012966960180,
320636554330471463,
690626386000777253,
460537020928110902,
520130537132036687,
164923206455111647,
902126891442775763,
200547202580328755,
339902785434463589,
349725004907924876,
443280250303616396,
194083388694613164,
1074150333407820835,
285503194367853735,
184794093958514725,
287536797091598963,
1118597757681179941,
189117531181130919,
196091288186968813,
510313428186453052,
503276123464046181,
201727578707655657,
189126707851203461,
1049865372216511662,
196091288187023678,
440190622607652918,
515626165473773535,
443568775446439903,
155336551385185247,
819619722373305599,
443568614385401823,
544899891616463839,
139663752168160223,
50082935010485897,
1134266731243763349,
349929074036033598,
188675276184786316,
1115828344942720110,
78879144111415230,
130469409617867811,
273001312302808552,
546342677083512709,
304675094503462130,
484963385992516863,
539292997575441377,
503247742237703161,
440191643740142564,
45000380223280095,
515626165474209759,
50629634944350175,
1151760167962478559,
359143514949255134,
188675276170984420,
333951075738934772,
563134206620640688,
273001313276162519,
54611917247920169,
287646685853818866,
1116190306795390533,
1118144126375952013,
654428408421599399,
50178686714121260,
824652878709764407,
51304586900844929,
189117655029176942,
189119795105826226,
1116662316403197362,
528011836502539405,
1116659576728452063,
359137605074253071,
530849094502096876,
488825207306724636,
285929520176550337,
189126354708674117,
888299137195620850,
846275565020845311,
1145560912237681390,
654428339938412711,
694740240259465012,
672254384995040847,
1122098869911389703,
1145538709554024615,
268301199484277927,
735852135278693747,
};
}
} |
using UnityEngine;
using System.Collections;
public class PowerUpScript : MonoBehaviour
{
Sprite p1;
Sprite p2;
Sprite p3;
public int type;
public float lifeSpan = 10.0f;
WeaponTypeScript weaponTypeScript;
void Start ()
{
weaponTypeScript = GameObject.Find("WeaponTypeBoxes").GetComponent<WeaponTypeScript>();
}
void Update ()
{
transform.position = new Vector3(transform.position.x, transform.position.y - .05f, transform.position.z);
lifeSpan -= Time.deltaTime;
if(lifeSpan <= 0)
{
Destroy(gameObject);
}
}
public void SetPowerUp(int powerUpType)
{
type = powerUpType;
if(type == 1)
{
gameObject.GetComponent<SpriteRenderer>().sprite = p1;
}
else if(type == 2)
{
gameObject.GetComponent<SpriteRenderer>().sprite = p2;
}
else if(type == 3)
{
gameObject.GetComponent<SpriteRenderer>().sprite = p3;
}
}
void OnCollisionEnter2D(Collision2D coll)
{
if (coll.gameObject.tag == "PlayersShip")
{
weaponTypeScript.AddPowerUp("MeteorShield");
Destroy(gameObject);
}
}
}
|
namespace EasyCaching.SQLite
{
/// <summary>
/// Const sql.
/// </summary>
public static class ConstSQL
{
/// <summary>
/// The setsql.
/// </summary>
public const string SETSQL = @"
DELETE FROM [easycaching] WHERE [cachekey] = @cachekey AND [name]=@name;
INSERT INTO [easycaching]
([name]
,[cachekey]
,[cachevalue]
,[expiration])
VALUES
(@name
,@cachekey
,@cachevalue
,(select strftime('%s','now')) + @expiration);";
/// <summary>
/// The trysetsql.
/// </summary>
public const string TRYSETSQL = @"
INSERT INTO [easycaching]
([name]
,[cachekey]
,[cachevalue]
,[expiration])
SELECT @name,@cachekey,@cachevalue,(select strftime('%s','now') + @expiration)
WHERE NOT EXISTS (SELECT 1 FROM [easycaching] WHERE [cachekey] = @cachekey AND [name]=@name AND [expiration] > strftime('%s','now'));";
/// <summary>
/// The getsql.
/// </summary>
public const string GETSQL = @"SELECT [cachevalue]
FROM [easycaching]
WHERE [cachekey] = @cachekey AND [name]=@name AND [expiration] > strftime('%s','now')";
/// <summary>
/// The getsql.
/// </summary>
public const string GETEXPIRATIONSQL = @"SELECT [expiration] - strftime('%s','now')
FROM [easycaching]
WHERE [cachekey] = @cachekey AND [name]=@name ";
/// <summary>
/// The getallsql.
/// </summary>
public const string GETALLSQL = @"SELECT [cachekey],[cachevalue]
FROM [easycaching]
WHERE [cachekey] IN @cachekey AND [name]=@name AND [expiration] > strftime('%s','now')";
/// <summary>
/// The getbyprefixsql.
/// </summary>
public const string GETBYPREFIXSQL = @"SELECT [cachekey],[cachevalue]
FROM [easycaching]
WHERE [cachekey] LIKE @cachekey AND [name]=@name AND [expiration] > strftime('%s','now')";
/// <summary>
/// The removesql.
/// </summary>
public const string REMOVESQL = @"DELETE FROM [easycaching] WHERE [cachekey] = @cachekey AND [name] = @name ";
/// <summary>
/// The removebyprefixsql.
/// </summary>
public const string REMOVEBYPREFIXSQL = @"DELETE FROM [easycaching] WHERE [cachekey] like @cachekey AND [name]=@name";
/// <summary>
/// The existssql.
/// </summary>
public const string EXISTSSQL = @"SELECT COUNT(1)
FROM [easycaching]
WHERE [cachekey] = @cachekey AND [name]=@name AND [expiration] > strftime('%s','now')";
/// <summary>
/// The countallsql.
/// </summary>
public const string COUNTALLSQL = @"SELECT COUNT(1)
FROM [easycaching]
WHERE [expiration] > strftime('%s','now') AND [name]=@name";
/// <summary>
/// The countprefixsql.
/// </summary>
public const string COUNTPREFIXSQL = @"SELECT COUNT(1)
FROM [easycaching]
WHERE [cachekey] like @cachekey AND [name]=@name AND [expiration] > strftime('%s','now')";
/// <summary>
/// The flushsql.
/// </summary>
public const string FLUSHSQL = @"DELETE FROM [easycaching] WHERE [name]=@name";
/// <summary>
/// The createsql.
/// </summary>
public const string CREATESQL = @"CREATE TABLE IF NOT EXISTS [easycaching] (
[ID] INTEGER PRIMARY KEY
, [name] TEXT
, [cachekey] TEXT
, [cachevalue] TEXT
, [expiration] INTEGER)";
}
}
|
using System.Collections.Generic;
using Microsoft.IdentityServer.Web.Authentication.External;
namespace AdfsTotpAuthenticationProvider
{
internal class AuthenticationAdapterMetadata : IAuthenticationAdapterMetadata
{
public string AdminName => "AdfsTotpAuthenticationProvider";
public string[] AuthenticationMethods => new[] { "http://schemas.microsoft.com/ws/2012/12/authmethod/otp" };
public int[] AvailableLcids => new[] { 1033 };
public Dictionary<int, string> Descriptions
{
get
{
var result = new Dictionary<int, string>
{
{ 1033, "AdfsTotpAuthenticationProvider" }
};
return result;
}
}
public Dictionary<int, string> FriendlyNames
{
get
{
var result = new Dictionary<int, string>
{
{1033, "AdfsTotpAuthenticationProvider"}
};
return result;
}
}
public string[] IdentityClaims => new[] { "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn" };
public bool RequiresIdentity => true;
}
}
|
using LiteDB;
using Microsoft.AspNet.Identity;
using System;
namespace AspNet.Identity.LiteDB {
public class IdentityRole : IRole<string> {
[BsonId]
public string Id { get; private set; }
public string Name { get; set; }
public IdentityRole() {
this.Id = ObjectId.NewObjectId().ToString();
}
public IdentityRole(string roleName)
: this() {
this.Name = roleName;
}
}
}
|
using Ivvy.Json;
using Newtonsoft.Json;
using System;
namespace Ivvy.Venue.Bookings
{
/// <summary>
/// A daily rate for an accommodation room reservation on an iVvy venue booking.
/// </summary>
public class RoomReservationDayRate : ISerializable
{
[JsonProperty("dayDate")]
public string DayDate { get; set; }
[JsonProperty("barId")]
public int? RatePlanId { get; set; }
[JsonProperty("cost")]
public float? Cost { get; set; }
}
} |
// <copyright>
// Licensed under the MIT license. See the LICENSE.md file in the project root for full license information.
// </copyright>
namespace Geode.Models
{
/// <summary>
/// An email address.
/// </summary>
public class Email : Entity
{
/// <summary>
/// Gets or sets a value indicating whether the email is active.
/// </summary>
/// <value>A <see cref="bool"/> value that indicating whether the email is active.</value>
public bool IsActive { get; set; } = true;
/// <summary>
/// Gets or sets the email value.
/// </summary>
/// <value>A <see cref="string"/> value that contains the email address.</value>
public string Value { get; set; } = string.Empty;
}
}
|
using NakedBank.Shared;
using System.Collections.Generic;
using System.Linq;
namespace NakedBank.Domain
{
public class BaseDomain
{
public bool HasErrors => Errors.Any();
public List<BusinessError> Errors { get; private set; }
public BaseDomain()
{
Errors = new List<BusinessError>();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class SpheresManager : MonoBehaviour {
public int lives;
public float minSpeed;
public float maxSpeed;
public float intervalTime;
public Transform xMax;
public Transform xMin;
public Transform yMax;
public Transform yMin;
public Transform bottomLimit;
public Transform player;
public GameObject sphere;
public Text catchedText;
private List<GameObject> spheres;
private List<float> speeds;
private bool gameOn;
private int catchedSpheres = 0;
private float lastCreationTime = 0;
// Use this for initialization
void Start ()
{
spheres = new List<GameObject>();
speeds = new List<float>();
for (int i = 0; i < 3; i++)
{
CreateSphere();
}
//InvokeRepeating("CreateSphere", intervalTime, intervalTime);
gameOn = true;
}
// Update is called once per frame
void Update ()
{
if (gameOn)
{
MoveSpheres();
}
if (Time.time >= lastCreationTime + intervalTime)
{
CreateSphere();
lastCreationTime = Time.time;
}
}
void CreateSphere ()
{
if (gameOn)
{
spheres.Add(Instantiate(sphere, GetPosWithingBoundaries(), transform.rotation) as GameObject);
speeds.Add(Random.Range(minSpeed, maxSpeed));
}
}
Vector3 GetPosWithingBoundaries ()
{
Vector3 pos = new Vector3(0, 0, 0);
pos.x = Random.Range(xMin.position.x, xMax.position.x);
pos.y = Random.Range(yMin.position.y, yMax.position.y);
return pos;
}
void MoveSpheres ()
{
for (int i=0; i<spheres.Count; i++)
{
Vector3 spherePos = spheres[i].transform.position;
spheres[i].transform.position = new Vector3(spherePos.x, spherePos.y - speeds[i], spherePos.z);
if (checkCollision(player.position, spheres[i].transform.position))
{
catchedSpheres++;
catchedText.text = catchedSpheres.ToString();
if (catchedSpheres >= 20)
{
minSpeed = 0.05f;
maxSpeed = 0.08f;
}
else if (catchedSpheres >= 70)
{
}
else if (catchedSpheres >= 100)
{
}
intervalTime -= 0.005f;
RemoveSphereFromList(i);
}
if (spheres[i].transform.position.y <= bottomLimit.position.y)
{
HandleSpherePassedBottomLimit(i);
}
}
}
void HandleSpherePassedBottomLimit (int index)
{
RemoveSphereFromList(index);
lives--;
if (lives <= 0)
{
gameOn = false;
Invoke("RestartGame", 2f);
}
}
void RemoveSphereFromList (int index)
{
GameObject temp = spheres[index];
spheres.Remove(spheres[index]);
speeds.Remove(speeds[index]);
Destroy(temp);
}
void RestartGame ()
{
SceneManager.LoadScene(0);
}
bool checkCollision(Vector3 x, Vector3 y)
{
if (Mathf.Sqrt((y.x - x.x) * (y.x - x.x) + (y.y - x.y) * (y.y - x.y)) < (0.5f + 0.332f))
{
return true;
}
return false;
}
}
|
/*
| Version 10.1.84
| Copyright 2013 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
using System;
using System.Windows;
using System.Windows.Controls;
using System.Collections.Generic;
using ESRI.ArcLogistics.App.Controls;
using ESRI.ArcLogistics.App.Widgets;
namespace ESRI.ArcLogistics.App
{
internal class TaskPanelContentBuilder
{
#region Public methods
/// <summary>
/// Toggles state of widget in panel.
/// </summary>
/// <param name="stackPanel">Stack panel.</param>
/// <param name="ignoredWidgets">Ignored widget collection</param>
/// <param name="isEnable">Enable state flag.</param>
public void ToggleTaskPanelWidgetsState(StackPanel stackPanel, ICollection<Type> ignoredWidgets,
bool isEnable)
{
foreach (UIElement expanderControl in stackPanel.Children)
{
Type type = expanderControl.GetType();
if (type == typeof(ExpanderControl) && (null != expanderControl))
{
ExpanderControl expander = (ExpanderControl)expanderControl;
Type widgetType = expander.ContentOfExpander.GetType();
if (!ignoredWidgets.Contains(widgetType))
{
PageWidget widget = (PageWidget)expander.ContentOfExpander;
widget.IsEnabled = isEnable;
}
}
}
}
/// <summary>
/// Updates state of each widget in panel.
/// </summary>
/// <param name="stackPanel">Stack panel.</param>
public void UpdateTaskPanelWidgetsState(StackPanel stackPanel)
{
foreach (UIElement expanderControl in stackPanel.Children)
{
Type type = expanderControl.GetType();
if (type == typeof(ExpanderControl) && (null != expanderControl))
{
ExpanderControl expander = (ExpanderControl)expanderControl;
expander.ClickButton += new RoutedEventHandler(TaskPanelContentBuilder_ClickButton);
Type widgetType = expander.ContentOfExpander.GetType();
/// update collapsed state
expander.IsCollapsed = App.Current.MainWindow.CollapsedWidgets.Contains(widgetType);
if (widgetType.Equals(typeof(ESRI.ArcLogistics.App.Widgets.QuickHelpWidget)))
{ // quick help widget - update expander state
expander.Visibility = App.Current.MainWindow.IsHelpVisible ?
Visibility.Visible : Visibility.Collapsed;
}
}
}
}
/// <summary>
/// Builds stack panel with content.
/// </summary>
/// <param name="selectedPage"></param>
/// <returns></returns>
public StackPanel BuildTaskPanelContent(ESRI.ArcLogistics.App.Pages.Page selectedPage)
{
StackPanel contentStackPanel = new StackPanel();
contentStackPanel.VerticalAlignment = VerticalAlignment.Stretch;
contentStackPanel.HorizontalAlignment = HorizontalAlignment.Stretch;
if (0 < selectedPage.Widgets.Count)
{
foreach (PageWidget widget in selectedPage.Widgets)
{
// If widget contains calendar - no need to wrap it to expander, just add to Navigation pane content.
if (widget is CalendarWidget || widget is BarrierCalendarWidget || widget is DateRangeCalendarWidget)
contentStackPanel.Children.Add(widget);
else
{
ExpanderControl expanderControl = new ExpanderControl();
expanderControl.ContentOfExpander = widget;
expanderControl.Header = widget.Title;
contentStackPanel.Children.Add(expanderControl);
}
}
}
return contentStackPanel;
}
#endregion
#region Protected Methods
/// <summary>
/// Method add widget's type to collection of collapsed widgets if it was collapsed
/// ande remove if it was expanded
/// </summary>
/// <param name="widgetType">Widget's type.</param>
/// <param name="isCollapsed">Is widget collapsed.</param>
protected void _UpdateListOfCollapsedWidgets(Type widgetType, bool isCollapsed)
{
// If widget collapsed and such type is not exist in collection - add it.
if (!App.Current.MainWindow.CollapsedWidgets.Contains(widgetType) && isCollapsed)
App.Current.MainWindow.CollapsedWidgets.Add(widgetType);
// If widget is expanded - need to remove it's type from collection of collapsed types.
else if (App.Current.MainWindow.CollapsedWidgets.Contains(widgetType) && !isCollapsed)
App.Current.MainWindow.CollapsedWidgets.Remove(widgetType);
}
#endregion
#region Event Handlers
void TaskPanelContentBuilder_ClickButton(object sender, RoutedEventArgs e)
{
ExpanderControl control = sender as ExpanderControl;
Type type = control.ContentOfExpander.GetType();
_UpdateListOfCollapsedWidgets(type, control.IsCollapsed);
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.AssetImporters;
using System;
using System.Reflection;
[ExcludeFromPreset]
public class CustomizeAssetImporter : AssetImporter
{
} |
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace Prodest.Certificado.ICPBrasil.Certificados
{
internal class Asn1Helper
{
private byte[] rawData;
public readonly List<Tag> TagList;
public Asn1Helper(ref byte[] rawData)
{
this.rawData = rawData;
TagList = new List<Tag>();
LoadTagList();
}
private void LoadTagList()
{
for (var offset = 0; offset < rawData.Length;)
{
TagList.Add(new Tag(ref rawData, ref offset));
}
}
}
#pragma warning disable S1939 // Inheritance list should not be redundant
internal enum TagId
#pragma warning restore S1939 // Inheritance list should not be redundant
{
Rfc822Name = 1,
Integer = 2,
BitString = 3,
OctetString = 4,
Null = 5,
ObjectIdentifier = 6,
Utf8String = 12,
Sequence = 16,
Set = 17,
PrintableString = 19,
T61String = 20,
Ia5String = 22,
UtcTime = 23
}
internal class Tag
{
public TagId TagId { get; }
private int LengthOctets { get; }
private int StartContents { get; }
public Tag(ref byte[] rawdata, ref int offset)
{
LengthOctets = 0;
// pode estar em formato Short ou Long
// se ((rawData[offset] & 0x1f) == 0x1f)
// formato Long não é usado nos certificados da ICP-Brasil
// formato Short
TagId = (TagId)(rawdata[offset] & 0x1f);
offset++;
// Octetos de tamanho
if ((rawdata[offset] & 0x80) == 0x00)
{ // Formato Short: tamanho de até 127 bytes
LengthOctets = (rawdata[offset++] & 0x7f);
}
else
{ // Formato Long: tamanho em 2 até 127 octetos
var lenOctetos = rawdata[offset++] & 0x7f;
LengthOctets = CalculaBase256(rawdata, ref offset, lenOctetos);
}
StartContents = offset;
switch (TagId)
{
case TagId.ObjectIdentifier:
case TagId.PrintableString:
case TagId.OctetString:
case TagId.Utf8String:
case TagId.BitString:
case TagId.Ia5String:
case TagId.Integer:
case TagId.Rfc822Name:
case TagId.T61String:
case TagId.UtcTime:
offset += LengthOctets;
break;
case TagId.Null:
case TagId.Sequence:
case TagId.Set:
break;
}
}
public string Format(byte[] rawdata)
{
switch (TagId)
{
case TagId.ObjectIdentifier:
return CalculaOid(rawdata, StartContents, LengthOctets);
case TagId.Ia5String:
case TagId.T61String:
case TagId.PrintableString:
case TagId.UtcTime:
case TagId.OctetString:
case TagId.Utf8String:
case TagId.Rfc822Name:
return (new ASCIIEncoding()).GetString(rawdata, StartContents, LengthOctets);
default:
return TagId.ToString();
}
}
private static int CalculaBase256(IReadOnlyList<byte> rawdata, ref int offset, int length)
{
if (rawdata == null || rawdata.Count < offset + length) return 0;
var tamanho = rawdata[offset++];
for (var i = 1; i < length; i++)
{
tamanho <<= 8;
tamanho += rawdata[offset++];
}
return tamanho;
}
private static string CalculaOid(IReadOnlyList<byte> rawdata, int offset, int length)
{
var sb = new StringBuilder();
sb.AppendFormat(CultureInfo.CurrentCulture
, "{0}.{1}", rawdata[offset] / 40, rawdata[offset] % 40);
offset++;
length--;
for (var i = offset; i < (offset + length); i++)
{
var auxValue = rawdata[i] & 0x7f;
if (
(rawdata[i] & 0x80) == 0x80
&& i < offset + length)
{
auxValue = (rawdata[i++] & 0x7f) << 7;
var auxValue2 = (rawdata[i] & 0x7f);
while (
(rawdata[i] & 0x80) == 0x80
&& i < offset + length)
{
auxValue += auxValue2;
auxValue <<= 7;
auxValue2 = rawdata[++i] & 0x7f;
}
sb.AppendFormat(CultureInfo.CurrentCulture
, ".{0}", auxValue + auxValue2);
}
else
{
sb.AppendFormat(CultureInfo.CurrentCulture
, ".{0}", auxValue);
}
}
return sb.ToString();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Verivox
{
public class ProductA : Product
{
public ProductA()
{
}
public ProductA (string name) : base(name)
{
}
public override decimal GetFixedAnnualCost()
{
decimal costPerMonth = 5M;
ushort monthCount = 12;
return costPerMonth * monthCount;
}
public override decimal GetVariableAnnualCost(decimal consumption)
{
return consumption * .22M;
}
}
}
|
using UnityEngine;
public class HintEasy : MonoBehaviour
{
public static void ShowHint()
{
var belts = GameObject.FindGameObjectsWithTag("Belt");
foreach (var belt in belts)
{
var correct = belt.gameObject.GetComponent<SwapBelts>().isCorrect;
if (!correct)
{
var animator = belt.gameObject.GetComponent<Animator>();
animator.SetTrigger("Hint");
break;
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CloudManager : MonoBehaviour {
void OnDrawGizmosSelected()
{
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.color = Color.blue;
Gizmos.DrawCube(Vector3.zero, Vector3.one);
Gizmos.DrawLine(Vector3.zero, Vector3.forward);
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
namespace SxGeoReader
{
public class SxGeoUnpack
{
private Dictionary<string, object> RecordData;
private Dictionary<string, Type> RecordTypes;
private Dictionary<string, string> SxTypeCodes;
private Encoding StringsEncoding;
public bool RevBO { get; set; }
public SxGeoUnpack(string Format, SxGeoEncoding dbEncoding)
{
RevBO = !BitConverter.IsLittleEndian;
RecordData = new Dictionary<string, object>();
RecordTypes = new Dictionary<string, Type>();
SxTypeCodes = new Dictionary<string, string>();
// разбираем строку формата
string[] fields = Format.Split('/');
foreach (string field in fields)
{
string[] buf = field.Split(':');
if (buf.Length < 2) break;
string SxTypeCode = buf[0];
string FieldName = buf[1];
// подготавливаем словари
RecordData.Add(FieldName, null);
SxTypeCodes.Add(FieldName, SxTypeCode);
RecordTypes.Add(FieldName, SxTypeToType(SxTypeCode));
}
switch (dbEncoding)
{
case SxGeoEncoding.CP1251:
StringsEncoding = Encoding.GetEncoding(1251);
return;
case SxGeoEncoding.UTF8:
StringsEncoding = Encoding.UTF8;
return;
case SxGeoEncoding.Latin1:
StringsEncoding = Encoding.GetEncoding(1252);
return;
}
throw new ArgumentOutOfRangeException(nameof(dbEncoding));
}
private static Type SxTypeToType(string SxTypeCode)
{
if (string.IsNullOrEmpty(SxTypeCode)) return null;
// mediumint - такого типа в C# нет, приведем к int/uint
switch (SxTypeCode[0])
{
case 't': return typeof(sbyte); //tinyint signed - 1 - > sbyte
case 'T': return typeof(byte); //tinyint unsigned - 1 - > byte
case 's': return typeof(short); //smallint signed - 2 - > short
case 'S': return typeof(ushort); //smallint unsigned - 2 - > ushort
case 'm': return typeof(int); //mediumint signed - 3 - > int
case 'M': return typeof(uint); //mediumint unsigned - 3 - > uint
case 'i': return typeof(int); //integer signed - 4 - > int
case 'I': return typeof(uint); //integer unsigned - 4 - > uint
case 'f': return typeof(float); //float - 4 - > float
case 'd': return typeof(double); //double - 8 - > double
case 'n': //number 16bit - 2
case 'N': return typeof(double); //number 32bit - 4 - > float
case 'c': //char - fixed size string
case 'b': return typeof(string); //blob - string with \0 end
}
return null;
}
public Dictionary<string, object> Unpack(byte[] Record, out int RealLength)
{
int Counter = 0;
object buf;
string signs;
int isigns;
//перебираем сгенерированный ранее словарь с данными
foreach (string SxRecordName in SxTypeCodes.Keys)
{
//вытаскиваем код типа данных
string SxTypeCode = SxTypeCodes[SxRecordName];
//вытаскиваем данные в object buf
switch (SxTypeCode[0])
{
case 't':
buf = GetTinuintSigned(Record, Counter);
Counter++;
break;
case 'T':
buf = GetTinuintUnsigned(Record, Counter);
Counter++;
break;
case 's':
buf = GetSmallintSigned(Record, Counter);
Counter += 2;
break;
case 'S':
buf = GetSmallintUnsigned(Record, Counter);
Counter += 2;
break;
case 'm':
buf = GetMediumintSigned(Record, Counter);
Counter += 3;
break;
case 'M':
buf = GetMediumintUnsigned(Record, Counter);
Counter += 3;
break;
case 'i':
buf = GetIntSigned(Record, Counter);
Counter += 4;
break;
case 'I':
buf = GetIntUnsigned(Record, Counter);
Counter += 4;
break;
case 'f':
buf = GetFloat(Record, Counter);
Counter += 4;
break;
case 'd':
buf = GetDouble(Record, Counter);
Counter += 8;
break;
case 'n':
signs = SxTypeCode.Substring(1);
isigns = Convert.ToInt32(signs);
buf = GetN16(Record, Counter, isigns);
Counter += 2;
break;
case 'N':
signs = SxTypeCode.Substring(1);
isigns = Convert.ToInt32(signs);
buf = GetN32(Record, Counter, isigns);
Counter += 4;
break;
case 'c':
int length = Convert.ToInt32(SxTypeCode.Substring(1));
buf = GetFixedString(Record, Counter, length);
Counter += length;
break;
case 'b':
string result;
Counter = GetBlob(Record, Counter, out result);
buf = result;
break;
default:
buf = null;
break;
}
//записываем полученный объект в соотв. место RecordData
RecordData[SxRecordName] = buf;
}
RealLength = Counter;
return RecordData;
}
public Dictionary<string, object> Unpack(byte[] Record)
{
int tmp = 0;
Unpack(Record, out tmp);
return RecordData;
}
private sbyte GetTinuintSigned(byte[] DataArray, int StartPosition)
{
if (StartPosition >= DataArray.Length)
{
return 0;
}
else return (sbyte)DataArray[StartPosition];
}
private byte GetTinuintUnsigned(byte[] DataArray, int StartPosition)
{
if (StartPosition >= DataArray.Length)
{
return 0;
}
else return DataArray[StartPosition];
}
private short GetSmallintSigned(byte[] DataArray, int StartPosition)
{
if (StartPosition >= DataArray.Length + 1)
{
return 0;
}
byte[] buf = new byte[2];
Array.Copy(DataArray, StartPosition, buf, 0, 2);
if (RevBO)
{
Array.Reverse(buf);
}
return BitConverter.ToInt16(buf, 0);
}
private ushort GetSmallintUnsigned(byte[] DataArray, int StartPosition)
{
if (StartPosition >= DataArray.Length + 1)
{
return 0;
}
byte[] buf = new byte[2];
Array.Copy(DataArray, StartPosition, buf, 0, 2);
if (RevBO)
{
Array.Reverse(buf);
}
return BitConverter.ToUInt16(buf, 0);
}
private int GetMediumintSigned(byte[] DataArray, int StartPosition)
{
if (StartPosition >= DataArray.Length + 2)
{
return 0;
}
byte[] buf = new byte[4];
Array.Copy(DataArray, StartPosition, buf, 0, 3);
if (RevBO)
{
Array.Copy(DataArray, StartPosition, buf, 1, 3);
Array.Reverse(buf);
}
else
{
Array.Copy(DataArray, StartPosition, buf, 0, 3);
}
return BitConverter.ToInt32(buf, 0);
}
private uint GetMediumintUnsigned(byte[] DataArray, int StartPosition)
{
if (StartPosition >= DataArray.Length + 2)
{
return 0;
}
byte[] buf = new byte[4];
if (RevBO)
{
Array.Copy(DataArray, StartPosition, buf, 1, 3);
Array.Reverse(buf);
}
else
{
Array.Copy(DataArray, StartPosition, buf, 0, 3);
}
return BitConverter.ToUInt32(buf, 0);
}
private int GetIntSigned(byte[] DataArray, int StartPosition)
{
if (StartPosition >= DataArray.Length + 3)
{
return 0;
}
byte[] buf = new byte[4];
Array.Copy(DataArray, StartPosition, buf, 0, 4);
if (RevBO)
{
Array.Reverse(buf);
}
return BitConverter.ToInt32(buf, 0);
}
private uint GetIntUnsigned(byte[] DataArray, int StartPosition)
{
if (StartPosition >= DataArray.Length + 3)
{
return 0;
}
byte[] buf = new byte[4];
Array.Copy(DataArray, StartPosition, buf, 0, 4);
if (RevBO)
{
Array.Reverse(buf);
}
return BitConverter.ToUInt32(buf, 0);
}
private float GetFloat(byte[] DataArray, int StartPosition)
{
if (StartPosition >= DataArray.Length + 3)
{
return 0;
}
byte[] buf = new byte[4];
Array.Copy(DataArray, StartPosition, buf, 0, 4);
if (RevBO)
{
Array.Reverse(buf);
}
return BitConverter.ToSingle(buf, 0);
}
private double GetDouble(byte[] DataArray, int StartPosition)
{
if (StartPosition >= DataArray.Length + 7)
{
return 0;
}
byte[] buf = new byte[8];
Array.Copy(DataArray, StartPosition, buf, 0, 8);
if (RevBO)
{
Array.Reverse(buf);
}
return BitConverter.ToDouble(buf, 0);
}
private double GetN16(byte[] DataArray, int StartPosition, int Signs)
{
short tmpShort = GetSmallintSigned(DataArray, StartPosition);
return tmpShort / Math.Pow(10, Signs);
}
private double GetN32(byte[] DataArray, int StartPosition, int Signs)
{
int tmpInt = GetIntSigned(DataArray, StartPosition);
return tmpInt / Math.Pow(10, Signs);
}
private string GetFixedString(byte[] DataArray, int StartPosition, int Count)
{
if (StartPosition >= DataArray.Length + Count - 1)
{
return null;
}
//кириллица UTF8 для строк ограниченной длины не поддерживается
//делаем буфер
byte[] buf = new byte[Count];
//копируем нужное количество байт в буфер
Array.Copy(DataArray, StartPosition, buf, 0, Count);
return StringsEncoding.GetString(buf);
}
private int GetBlob(byte[] DataArray, int StartPosition, out string Result)
{
int i = StartPosition;
List<byte> tmpl = new List<byte>();
while (DataArray[i] != '\0')
{
tmpl.Add(DataArray[i]);
i++;
}
i++;
byte[] buf = tmpl.ToArray();
Result = StringsEncoding.GetString(buf);
return i;
}
/*public static float ConvertToFloat(string Value, string DecimalSeparator)
{
NumberFormatInfo format = new NumberFormatInfo();
format.NumberDecimalSeparator = DecimalSeparator;
return Convert.ToSingle(Value, format);
}*/
//--------------------------------
public Dictionary<string, Type> GetRecordTypes()
{
return RecordTypes;
}
public Dictionary<string, string> GetSxTypeCodes()
{
return SxTypeCodes;
}
public static Dictionary<string, Type> GetRecordTypes(string Format)
{
Dictionary<string, Type> tmpTypes = new Dictionary<string, Type>();
string[] fields = Format.Split('/');
foreach (string field in fields)
{
string[] buf = field.Split(':');
if (buf.Length < 2) break;
string SxTypeCode = buf[0];
string FieldName = buf[1];
//формируем Dictionary
tmpTypes.Add(FieldName, SxTypeToType(SxTypeCode));
}
return tmpTypes;
}
}
} |
namespace Flip
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using FluentAssertions;
using Moq;
using Ploeh.AutoFixture;
using Xunit;
using static Moq.It;
using static Moq.Times;
public class StreamFactory_features
{
public class Model : Model<int>
{
public Model(int id) : base(id)
{
}
}
private readonly IFixture _fixture = new Fixture();
[Fact]
public void sut_inherits_StreamFactoryBase()
{
var sut = typeof(StreamFactory<,>);
sut.BaseType.GetGenericTypeDefinition().Should().Be(
typeof(StreamFactoryBase<,>));
}
[Fact]
public void constructor_sets_Filter_correctly()
{
var filter = Mock.Of<IStreamFilter<Model>>();
var sut = new StreamFactory<int, Model>(filter);
sut.Filter.Should().BeSameAs(filter);
}
[Fact]
public void Connect_returns_connection_instance()
{
var sut = new StreamFactory<int, Model>();
var modelId = _fixture.Create<int>();
IConnection<int, Model> actual = sut.Connect(modelId);
actual.Should().NotBeNull();
actual.ModelId.Should().Be(modelId);
}
[Fact]
public void Connect_returns_new_instances_for_every_call()
{
var sut = new StreamFactory<int, Model>();
var modelId = _fixture.Create<int>();
var actual = new List<IConnection<Model>>(
from _ in Enumerable.Range(0, 3)
select sut.Connect(modelId));
actual.Should().OnlyContain(x => x != null);
actual.ShouldAllBeEquivalentTo(actual.Distinct());
}
[Fact]
public void Connect_returns_connection_instances_connected_to_each_other_for_every_call()
{
// Arrange
var sut = new StreamFactory<int, Model>();
var modelId = _fixture.Create<int>();
// Act
var actual = new List<IConnection<Model>>(
from _ in Enumerable.Range(0, 3)
select sut.Connect(modelId));
// Assert
foreach (IConnection<Model> source in actual)
{
var observers = new List<IObserver<Model>>();
var subscriptions = new List<IDisposable>();
foreach (IConnection<Model> target in actual)
{
var observer = Mock.Of<IObserver<Model>>();
IDisposable subscription = target.Subscribe(observer);
observers.Add(observer);
subscriptions.Add(subscription);
}
var revision = new Model(modelId);
source.Emit(revision);
foreach (IObserver<Model> observer in observers)
Mock.Get(observer).Verify(x => x.OnNext(revision), Once());
}
}
[Fact]
public void ExistsFor_returns_false_for_nonexistent_model_id()
{
var sut = new StreamFactory<int, Model>();
var modelId = _fixture.Create<int>();
bool actual = sut.ExistsFor(modelId);
actual.Should().BeFalse();
}
[Fact]
public void ExistsFor_returns_true_for_model_id_with_which_stream_created()
{
var sut = new StreamFactory<int, Model>();
var modelId = _fixture.Create<int>();
IConnection<Model> connection = sut.Connect(modelId);
bool actual = sut.ExistsFor(modelId);
actual.Should().BeTrue();
}
[Fact]
public void Stream_sends_new_revision_to_filter()
{
// Arrange
int modelId = _fixture.Create<int>();
var revision = new Model(modelId);
var factory = new StreamFactory<int, Model>(
Mock.Of<IStreamFilter<Model>>());
IConnection<Model> connection = factory.Connect(modelId);
// Act
connection.Emit(revision);
// Assert
Mock.Get(factory.Filter).Verify(
x => x.Execute(revision, null), Once());
}
[Fact]
public void Stream_sends_last_revision_to_filter()
{
// Arrange
int modelId = _fixture.Create<int>();
var firstRevision = new Model(modelId);
var secondRevision = new Model(modelId);
var factory = new StreamFactory<int, Model>(
Mock.Of<IStreamFilter<Model>>());
Mock.Get(factory.Filter)
.Setup(x => x.Execute(firstRevision, null))
.Returns(firstRevision);
IConnection<Model> connection = factory.Connect(modelId);
connection.Emit(firstRevision);
// Act
connection.Emit(secondRevision);
// Assert
Mock.Get(factory.Filter).Verify(
x => x.Execute(secondRevision, firstRevision), Once());
}
[Fact]
public void Stream_sends_filter_result_to_connections()
{
// Arrange
int modelId = _fixture.Create<int>();
var revision = new Model(modelId);
var filtered = new Model(modelId);
var factory = new StreamFactory<int, Model>(
Mock.Of<IStreamFilter<Model>>(x =>
x.Execute(revision, null) == filtered));
IConnection<Model> connection = factory.Connect(modelId);
var observer = Mock.Of<IObserver<Model>>();
connection.Subscribe(observer);
// Act
connection.Emit(revision);
// Assert
Mock.Get(observer).Verify(x => x.OnNext(filtered), Once());
}
[Fact]
public void Stream_does_not_send_value_to_connections_if_filter_returns_null()
{
// Arrange
int modelId = _fixture.Create<int>();
var revision = new Model(modelId);
Model filtered = null;
var factory = new StreamFactory<int, Model>(
Mock.Of<IStreamFilter<Model>>(x =>
x.Execute(revision, null) == filtered));
IConnection<Model> connection = factory.Connect(modelId);
var observer = Mock.Of<IObserver<Model>>();
connection.Subscribe(observer);
// Act
connection.Emit(revision);
// Assert
Mock.Get(observer).Verify(x => x.OnNext(IsAny<Model>()), Never());
}
[Fact]
public void Stream_does_not_emit_null_value()
{
// Arrange
int modelId = _fixture.Create<int>();
var factory = new StreamFactory<int, Model>(
Mock.Of<IStreamFilter<Model>>());
IConnection<Model> connection = factory.Connect(modelId);
var observer = Mock.Of<IObserver<Model>>();
connection.Subscribe(observer);
// Act
connection.Emit(Observable.Return(default(Model)));
// Assert
Mock.Get(observer).Verify(
x => x.OnNext(IsAny<Model>()),
Never());
Mock.Get(observer).Verify(
x => x.OnError(IsAny<Exception>()),
Never());
Mock.Get(factory.Filter).Verify(
x => x.Execute(IsAny<Model>(), IsAny<Model>()),
Never());
}
[Fact]
public void Stream_fails_if_model_id_invalid()
{
// Arrange
var idGenerator = new Generator<int>(_fixture);
int modelId = idGenerator.First();
int invalidModelId = idGenerator.First(x => x != modelId);
var factory = new StreamFactory<int, Model>();
IConnection<Model> connection = factory.Connect(modelId);
var observer = Mock.Of<IObserver<Model>>();
connection.Subscribe(observer);
// Act
connection.Emit(new Model(invalidModelId));
// Assert
Mock.Get(observer).Verify(
x => x.OnError(IsAny<InvalidOperationException>()), Once());
}
[Fact]
public void Stream_fails_if_filter_result_id_invalid()
{
// Arrange
var idGenerator = new Generator<int>(_fixture);
int modelId = idGenerator.First();
int invalidModelId = idGenerator.First(x => x != modelId);
var filtered = new Model(invalidModelId);
var factory = new StreamFactory<int, Model>(
Mock.Of<IStreamFilter<Model>>(x =>
x.Execute(IsAny<Model>(), IsAny<Model>()) == filtered));
IConnection<Model> connection = factory.Connect(modelId);
var observer = Mock.Of<IObserver<Model>>();
connection.Subscribe(observer);
// Act
connection.Emit(new Model(modelId));
// Assert
Mock.Get(observer).Verify(
x => x.OnError(IsAny<InvalidOperationException>()), Once());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Vita.Entities.Logging {
public interface ILog {
void AddEntry(LogEntry entry);
}
public interface IBufferedLog : ILog {
IList<LogEntry> GetAll();
int ErrorCount { get; }
}
public interface ILogService : ILog, IObservable<LogEntry> {
void Flush();
}
/// <summary>
/// Listens to ILogService, batches entries and produces batches of entries.
/// </summary>
public interface ILogBatchingService : IObserver<LogEntry>, IObservable<IList<LogEntry>> { }
/// <summary>The last-resort error log facility. <see cref="LastResortErrorLog"/> class is an implementation./> </summary>
public interface ILastResortErrorLog {
/// <summary> Logs a fatal error in logging system. </summary>
void LogFatalError(string logSystemError, string originalError = null);
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Threading.Tasks;
namespace Kartrider.Api.Test.Endpoints.Match
{
[TestClass]
public class GetMatchDetailTests : TestBase
{
[DataTestMethod]
[DataRow("036e0001f656572a", DisplayName = "아이템 팀 배틀모드: 036e0001f656572a")]
[DataRow("036a000ef64df337", DisplayName = "스피드 개인전: 036a000ef64df337")]
[DataRow("0343000ef64d9a4a", DisplayName = "스피드 개인전: 0343000ef64d9a4a")]
[DataRow("03210018f64ff810", DisplayName = "스피드 팀전: 03210018f64ff810")]
[DataRow("02080018f64fe39e", DisplayName = "스피드 팀전: 02080018f64fe39e")]
[DataRow("00d40009f64d9038", DisplayName = "아이템 팀전: 00d40009f64d9038")]
public async Task Get_Match_Detail(string matchId)
{
await kartriderApi.Match.GetMatchDetailAsync(matchId);
}
[TestMethod("존재하지 않은 매치 상세 정보")]
public async Task Get_Match_Detail_NotFound()
{
const string matchId = "1";
Func<Task> action = async () => await kartriderApi.Match.GetMatchDetailAsync(matchId);
await Assert.ThrowsExceptionAsync<KartriderApiException>(action);
}
}
} |
using System;
namespace PCG.Terrain.Core.DataTypes
{
[Flags]
public enum CalculationIndicator : byte
{
Free = 0x00,
Busy = 0x01
}
public static class CalculationIndicators
{
public const CalculationIndicator Default = CalculationIndicator.Free;
}
} |
using Korann.DAL.Contracts;
using Korann.DAL.DTO;
namespace Korann.DAL.Repositories
{
public class CategoryRepository : RepositoryBase<Category>, ICategoryRepository
{
protected override string CollectionName
{
get { return "categories"; }
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _03.Camping
{
class Camping
{
static void Main()
{
Dictionary<string, Dictionary<string, int>> data = new Dictionary<string, Dictionary<string, int>>();
string input = Console.ReadLine();
while (input != "end")
{
string[] tokens = input.Split(' ');
string personName = tokens[0];
string camperModel = tokens[1];
int nightsToStay = int.Parse(tokens[2]);
if (!data.ContainsKey(personName))
{
data.Add(personName, new Dictionary<string, int>());
}
data[personName][camperModel] = nightsToStay;
input = Console.ReadLine();
}
var orderedData =
data
.OrderByDescending(n => n.Value.Values.Count)
.ThenBy(n => n.Key.Length)
.ToDictionary(k => k.Key, v => v.Value);
foreach (KeyValuePair<string, Dictionary<string, int>> details in orderedData)
{
string personName = details.Key;
Dictionary<string, int> camperDetails = details.Value;
Console.WriteLine($"{personName}: {camperDetails.Values.Count}");
int totalNights = 0;
foreach (KeyValuePair<string, int> camper in camperDetails)
{
string camperModel = camper.Key;
int nightsToStay = camper.Value;
totalNights += nightsToStay;
Console.WriteLine($"***{camperModel}");
}
Console.WriteLine($"Total stay: {totalNights} nights");
}
}
}
}
|
using Hydrazoid.Utils;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Hydrazoid
{
public class GameManager : Singleton<GameManager>
{
public PlayerCharacter Player { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Drawing;
namespace KATYA
{
public partial class KATYAFile
{
public StatusObject DrawSomething()
{
StatusObject SO = new StatusObject();
try
{
Bitmap bmp = new Bitmap(100, 100);
Graphics g = Graphics.FromImage(bmp);
g.FillRectangle(Brushes.Green, 0, 0, 50, 50);
g.Dispose();
bmp.Save(this.FilePath, System.Drawing.Imaging.ImageFormat.Png);
bmp.Dispose();
}
catch(Exception e)
{
SO = new StatusObject(e, "FILE_IMAGEPROCESSING_DRAWSOMETHING");
}
return SO;
}
}
}
|
using SSW.DataOnion.CodeGenerator.Exceptions;
using SSW.DataOnion.CodeGenerator.Helpers;
using Xunit;
namespace SSW.DataOnion.CodeGenerator.Tests.Unit
{
public class StringExtensionTests
{
[Fact]
public void Test01_Pluralize_Typical_Input()
{
var input = "test";
var pluralized = input.Pluralize();
Assert.Equal(pluralized, "tests");
}
[Fact]
public void Test02_Pluralize_String_With_Y_At_The_End()
{
var input = "testy";
var pluralized = input.Pluralize();
Assert.Equal(pluralized, "testies");
}
[Fact]
public void Test03_Pluralize_String_With_S_At_The_End()
{
var input = "process";
var pluralized = input.Pluralize();
Assert.Equal(pluralized, "processes");
}
[Fact]
public void Test04_Pluralize_Empty_String()
{
try
{
string.Empty.Pluralize();
Assert.False(true);
}
catch (GenerationException)
{
Assert.True(true);
}
}
}
}
|
using System.Runtime.InteropServices;
namespace Rocksmith2014PsarcLib.Psarc.Models.Sng
{
public struct Chord
{
public uint Mask;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public byte[] Frets;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public byte[] Fingers;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public int[] Notes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string Name;
}
}
|
using System;
public class Geometry_Calculator
{
public static void Main()
{
var figureType = Console.ReadLine();
if (figureType == "triangle")
{
CalculateTriangleArea();
}
else if (figureType == "square")
{
CalculateSquareArea();
}
else if (figureType == "rectangle")
{
CalculateRectangleArea();
}
else if (figureType == "circle")
{
CalculateCircleArea();
}
}
private static void CalculateCircleArea()
{
var radius = decimal.Parse(Console.ReadLine());
var area = Math.PI * (double)(radius * radius);
Console.WriteLine($"{area:f2}");
}
public static void CalculateRectangleArea()
{
var width = decimal.Parse(Console.ReadLine());
var height = decimal.Parse(Console.ReadLine());
var area = width * height;
Console.WriteLine($"{area:f2}");
}
public static void CalculateSquareArea()
{
var side = decimal.Parse(Console.ReadLine());
var area = side * side;
Console.WriteLine($"{area:f2}");
}
public static void CalculateTriangleArea()
{
var side = decimal.Parse(Console.ReadLine());
var height = decimal.Parse(Console.ReadLine());
var area = side * height / 2;
Console.WriteLine($"{area:f2}");
}
} |
using System;
namespace Dialog
{
public class DialogStuba
{
public DialogStuba ()
{
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.