content stringlengths 23 1.05M |
|---|
using UnityEngine;
using System.Collections;
public class FollowPlayer : MonoBehaviour {
Vector3 offset;
void Start () {
offset = transform.position - GameObject.FindGameObjectWithTag ("Player").transform.position;
}
void LateUpdate () {
Vector3 _targetCamPos = GameObject.FindGameObjectWithTag ("Player").transform.position + offset;
transform.position = Vector3.Lerp (transform.position, _targetCamPos, 10f * Time.deltaTime);
}
}
|
namespace WildFarm.Animals
{
using System;
using WildFarm.Animals.Creators;
public class AnimalFactory
{
public AnimalFactory()
{
}
public Animal CreateAnimal (string [] args)
{
Type anType = Type.GetType($"WildFarm.Animals.Creators.{args[0]}Creator");
if (anType != null)
{
var animalCreator = (IAnimalCreator)Activator.CreateInstance(anType);
return animalCreator.Create(args);
}
throw new ArgumentException($"Animal {args[0]} doesn't exists!");
}
}
}
|
using Newtonsoft.Json;
namespace Nest
{
/// <summary>
/// Limits the number of tokens that are indexed per document and field.
/// </summary>
public class LimitTokenCountTokenFilter : TokenFilterBase
{
public LimitTokenCountTokenFilter()
: base("limit")
{
}
/// <summary>
/// The maximum number of tokens that should be indexed per document and field.
/// </summary>
[JsonProperty("max_token_count")]
public int? MaxTokenCount { get; set; }
/// <summary>
/// If set to true the filter exhaust the stream even if max_token_count tokens have been consumed already.
/// </summary>
[JsonProperty("consume_all_tokens")]
public bool? ConsumeAllTokens { get; set; }
}
} |
namespace DotNet.Status.Web.Models
{
public class IssuesHookData
{
public string Action { get; set; }
public Octokit.Issue Issue { get; set; }
public IssuesHookUser Sender { get; set; }
public IssuesHookRepository Repository { get; set; }
public IssuesHookLabel Label { get; set; }
public IssuesHookChanges Changes { get; set; }
}
} |
using Lyn.Protocol.Common.Messages;
using Lyn.Types.Bitcoin;
using Lyn.Types.Fundamental;
namespace Lyn.Protocol.Bolt2.MessageRetransmission.Messages
{
public class ChannelReestablish : MessagePayload
{
public ChannelReestablish(UInt256 channelId, ulong nextCommitmentNumber, ulong nextRevocationNumber,
PublicKey myCurrentPerCommitmentPoint, Secret yourLastPerCommitmentSecret)
{
ChannelId = channelId;
NextCommitmentNumber = nextCommitmentNumber;
NextRevocationNumber = nextRevocationNumber;
YourLastPerCommitmentSecret = yourLastPerCommitmentSecret;
MyCurrentPerCommitmentPoint = myCurrentPerCommitmentPoint;
}
public override MessageType MessageType => MessageType.ChannelReestablish;
public UInt256 ChannelId { get; set; }
public ulong NextCommitmentNumber { get; set; }
public ulong NextRevocationNumber { get; set; }
public Secret YourLastPerCommitmentSecret { get; set; }
public PublicKey MyCurrentPerCommitmentPoint { get; set; }
}
} |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Llilum = Microsoft.Llilum.Devices.Spi;
namespace Windows.Devices.Spi
{
public sealed class SpiDevice : IDisposable
{
// Connection
private bool m_disposed;
private readonly Llilum.SpiDevice m_channel;
private readonly SpiConnectionSettings m_connectionSettings;
private readonly String m_deviceId;
/// <summary>
/// Private SpiDevice constructor
/// </summary>
internal SpiDevice(string busId, SpiConnectionSettings settings, Llilum.SpiDevice channel)
{
m_deviceId = busId;
m_connectionSettings = settings;
m_channel = channel;
}
~SpiDevice()
{
Dispose(false);
}
/// <summary>
/// Closes resources associated with this SPI device
/// </summary>
public void Dispose()
{
if (!m_disposed)
{
Dispose(true);
GC.SuppressFinalize(this);
m_disposed = true;
}
}
/// <summary>
/// Disposes of all resources associated with this SPI device
/// </summary>
/// <param name="disposing">True if called from Dispose, false if called from the finalizer.</param>
private void Dispose(bool disposing)
{
if (disposing)
{
m_channel.Dispose();
}
}
/// <summary>
/// Opens a device with the connection settings provided.
/// </summary>
/// <param name="busId">The id of the bus.</param>
/// <param name="settings">The connection settings.</param>
/// <returns>The SPI device requested.</returns>
/// [RemoteAsync]
public static SpiDevice FromIdAsync(string busId, SpiConnectionSettings settings)
{
Llilum.ISpiChannelInfoUwp channelInfoUwp = GetSpiChannelInfo(busId);
if (channelInfoUwp == null)
{
throw new InvalidOperationException();
}
Llilum.ISpiChannelInfo channelInfo = channelInfoUwp.ChannelInfo;
if (channelInfo == null)
{
throw new InvalidOperationException();
}
// This will throw if it fails
Llilum.SpiDevice spiChannel = new Llilum.SpiDevice(channelInfo, settings.ChipSelectLine, false);
spiChannel.ClockFrequency = settings.ClockFrequency;
spiChannel.DataBitLength = settings.DataBitLength;
spiChannel.Mode = (Llilum.SpiMode)settings.Mode;
spiChannel.Open();
return new SpiDevice(busId, settings, spiChannel);
}
/// <summary>
/// Gets the connection settings for the device.
/// </summary>
/// <value>The connection settings.</value>
public SpiConnectionSettings ConnectionSettings
{
get
{
return m_connectionSettings;
}
}
/// <summary>
/// Gets the unique ID associated with the device.
/// </summary>
/// <value>The ID.</value>
public string DeviceId
{
get
{
return m_deviceId;
}
}
/// <summary>
/// Retrieves the info about a certain bus.
/// </summary>
/// <param name="busId">The id of the bus.</param>
/// <returns>The bus info requested.</returns>
public static SpiBusInfo GetBusInfo(string busId)
{
Llilum.ISpiChannelInfoUwp channelInfo = GetSpiChannelInfo(busId);
if (channelInfo == null)
{
return null;
}
var supportedDataBitLengths = new List<int>()
{
8,
};
if (channelInfo.Supports16)
{
supportedDataBitLengths.Add(16);
}
return new SpiBusInfo()
{
ChipSelectLineCount = channelInfo.ChipSelectLines,
MaxClockFrequency = channelInfo.MaxFreq,
MinClockFrequency = channelInfo.MinFreq,
SupportedDataBitLengths = supportedDataBitLengths,
};
}
/// <summary>
/// Gets all the SPI buses found on the system.
/// </summary>
/// <returns>String containing all the buses found on the system.</returns>
/// [Overload("GetDeviceSelector")]
public static string GetDeviceSelector()
{
string[] channels = GetSpiChannels();
string allChannels = "";
if (channels != null)
{
foreach (string channel in channels)
{
allChannels += (channel + ";");
}
}
return allChannels;
}
/// <summary>
/// Gets all the SPI buses found on the system that match the input parameter.
/// </summary>
/// <param name="friendlyName">Input parameter specifying an identifying name for the desired bus. This usually corresponds to a name on the schematic.</param>
/// <returns>String containing all the buses that have the input in the name.</returns>
public static string GetDeviceSelector(string friendlyName)
{
// UWP prescribes returning the channels as one single string that looks like the following: "CH1;CH2;"
string[] channels = GetSpiChannels();
foreach (string channel in channels)
{
if (channel.Equals(friendlyName))
{
return friendlyName;
}
}
return null;
}
/// <summary>
/// Reads from the connected device.
/// </summary>
/// <param name="buffer">Array containing data read from the device</param>
public void Read(byte[] buffer)
{
// Read sends buffer.Length 0s, and places read values into buffer
if (buffer != null && buffer.Length > 0)
{
m_channel.Read(buffer, 0, buffer.Length);
}
}
/// <summary>
/// Transfer data using a full duplex communication system.
/// </summary>
/// <param name="writeBuffer">Array containing data to write to the device.</param>
/// <param name="readBuffer">Array containing data read from the device.</param>
public void TransferFullDuplex(byte[] writeBuffer, byte[] readBuffer)
{
if (writeBuffer != null && writeBuffer.Length > 0)
{
int readOffset = writeBuffer.Length;
if (readBuffer != null)
{
// If the read buffer is smaller than the write buffer, we want to read
// the last part of the transmission. Otherwise, read from the start
readOffset = writeBuffer.Length - readBuffer.Length;
if (readOffset < 0)
{
readOffset = 0;
}
}
m_channel.WriteRead(writeBuffer, 0, writeBuffer.Length, readBuffer, 0, readBuffer.Length, readOffset);
}
}
/// <summary>
/// Transfer data sequentially to the device.
/// </summary>
/// <param name="writeBuffer">Array containing data to write to the device.</param>
/// <param name="readBuffer">Array containing data read from the device.</param>
public void TransferSequential(byte[] writeBuffer, byte[] readBuffer)
{
Write(writeBuffer);
Read(readBuffer);
}
/// <summary>
/// Writes to the connected device.
/// </summary>
/// <param name="buffer">Array containing the data to write to the device.</param>
public void Write(byte[] buffer)
{
if (buffer != null && buffer.Length > 0)
{
m_channel.Write(buffer, 0, buffer.Length);
}
}
//--//
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern Llilum.ISpiChannelInfoUwp GetSpiChannelInfo(string busId);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern string[] GetSpiChannels();
}
}
|
using ProtoBuf;
namespace Woof.Net;
/// <summary>
/// Messge metadata header part.
/// </summary>
[ProtoContract]
public class MessageMetadata {
/// <summary>
/// Message type identifier.
/// </summary>
[ProtoMember(1)]
public int TypeId { get; set; }
/// <summary>
/// Message identifier.
/// </summary>
[ProtoMember(2)]
public Guid Id { get; set; }
/// <summary>
/// Message payload length.
/// </summary>
[ProtoMember(3)]
public int PayloadLength { get; set; }
/// <summary>
/// Optional message signature.
/// </summary>
[ProtoMember(4)]
public byte[]? Signature { get; set; }
}
|
using System;
namespace GitHub.Commands
{
/// <summary>
/// Supplies parameters to <see cref="INextInlineCommentCommand"/> and
/// <see cref="IPreviousInlineCommentCommand"/>.
/// </summary>
public class InlineCommentNavigationParams
{
/// <summary>
/// Gets or sets the line that should be used as the start point for navigation.
/// </summary>
/// <remarks>
/// If null, the current line will be used. If -1 then the absolute first or last
/// comment in the file will be navigated to.
/// </remarks>
public int? FromLine { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the cursor will be moved to the newly opened
/// comment.
/// </summary>
public bool MoveCursor { get; set; } = true;
}
}
|
@page
@model webapp.Pages.ProfileModel
@{
ViewData["Title"] = "Profile";
}
<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>
<form>
<p>
UPN: <input type="text" asp-for="SearchString" />
<input type="submit" value="Filter" />
</p>
</form>
<table class="table table-striped table-condensed" style="font-family: monospace">
<tr>
<th>Property</th>
<th>Value</th>
</tr>
@{
if (Model.GraphUser != null)
{
<tr>
<td>photo</td>
<td>
@{
if (!string.IsNullOrEmpty(Model.Photo))
{
<img style="margin: 5px 0; width: 150px" src="data:image/jpeg;base64, @Model.Photo" />
}
else
{
<h3>NO PHOTO</h3>
<p>Check user profile in Azure Active Directory to add a photo.</p>
}
}
</td>
</tr>
<tr>
<td> Display name </td>
<td> @Html.DisplayFor(model => model.GraphUser.DisplayName) </td>
</tr>
<tr>
<td> Mail </td>
<td> @Html.DisplayFor(model => model.GraphUser.Mail) </td>
</tr>
<tr>
<td> UPN </td>
<td> @Html.DisplayFor(model => model.GraphUser.UserPrincipalName) </td>
</tr>
}
}
</table> |
namespace Expanse.Serialization
{
/// <summary>
/// Interface capable of serializing and deserializing objects.
/// </summary>
public interface ISerializer<TData>
{
/// <summary>
/// Serializes a source object.
/// </summary>
/// <typeparam name="TSource">Type of source object.</typeparam>
/// <param name="obj">Source object instance.</param>
/// <returns>Returns serialized data.</returns>
TData Serialize<TSource>(TSource obj);
/// <summary>
/// Deserializes data into a target object.
/// </summary>
/// <typeparam name="TTarget">Type of the target object.</typeparam>
/// <param name="data">Serialized object data.</param>
/// <returns>Returns a deserialized instance object.</returns>
TTarget Deserialize<TTarget>(TData data);
}
/// <summary>
/// Interface capable of serializing and deserializing objects to and from strings.
/// </summary>
public interface IStringSerializer : ISerializer<string> { }
/// <summary>
/// Interface capable of serializing and deserializing objects to and from byte arrays.
/// </summary>
public interface IByteSerializer : ISerializer<byte[]>
{
/// <summary>
/// Serializes a source object into a buffer.
/// </summary>
/// <typeparam name="TSource">Type of source object.</typeparam>
/// <param name="obj">Source object instance.</param>
/// <param name="buffer">Byte array to serialize into.</param>
/// <returns>Returns the length of the serialized data.</returns>
int Serialize<TSource>(TSource obj, ref byte[] buffer);
/// <summary>
/// Serializes a source object into a buffer.
/// </summary>
/// <typeparam name="TSource">Type of source object.</typeparam>
/// <param name="obj">Source object instance.</param>
/// <param name="buffer">Byte array to serialize into.</param>
/// <param name="offset">Offset to write into the buffer.</param>
/// <returns>Returns the length of the serialized data plus the offset.</returns>
int Serialize<TSource>(TSource obj, ref byte[] buffer, int offset);
/// <summary>
/// Deserializes data into a target object.
/// </summary>
/// <typeparam name="TTarget">Type of the target object.</typeparam>
/// <param name="data">Serialized object data.</param>
/// <param name="offset">Offset at which the target data is.</param>
/// <returns>Returns a deserialized instance object.</returns>
TTarget Deserialize<TTarget>(byte[] data, int offset);
}
}
|
using EstimatorX.Shared.Models;
namespace EstimatorX.Shared.Definitions;
public interface IHaveEstimate
{
// user entered
ClarityScale? Clarity { get; set; }
ConfidenceScale? Confidence { get; set; }
Criticality? Criticality { get; set; }
int? Estimate { get; set; }
// computed
double? Multiplier { get; set; }
int? WeightedEstimate { get; set; }
int? EstimatedTotal { get; set; }
int? WeightedTotal { get; set; }
string RiskLevel { get; set; }
string EffortLevel { get; set; }
double? EstimatedCost { get; set; }
double? WeightedCost { get; set; }
}
|
namespace Qsi.Debugger.Models
{
public class QsiSplitTreeItem
{
}
}
|
using System;
using Ludiq;
using Bolt;
namespace Lasm.BoltAddons.BinaryEncryption
{
[UnitSurtitle("Binary Encryption")]
[UnitShortTitle("Create Variable")]
public class NewBinaryVariable : BinaryEncryptionBaseUnit
{
[Inspectable]
[UnitHeaderInspectable("Type"), InspectorLabel("Type")]
public Type type = typeof(int);
[DoNotSerialize]
public ValueInput name;
[AllowsNull]
[DoNotSerialize]
public ValueInput value;
[DoNotSerialize]
public ValueInput valueNull;
[DoNotSerialize]
public ValueOutput variable;
protected override void Definition()
{
name = ValueInput<string>("name", string.Empty);
if (type.IsValueType)
{
value = ValueInput(type, "value");
value.SetDefaultValue(Activator.CreateInstance(type));
}
else
{
valueNull = ValueInput(type, "valueNull");
valueNull.SetDefaultValue(null);
}
Func<Recursion, BinaryVariable> binaryVariable = getBinaryVariable => GetBinaryVariable();
variable = ValueOutput<BinaryVariable>("variable", binaryVariable);
}
private BinaryVariable GetBinaryVariable()
{
BinaryVariable _variable = new BinaryVariable();
_variable.name = name.GetValue<string>();
_variable.variable = value.GetValue(type);
return _variable;
}
}
}
|
using System;
namespace Chatter.MessageBrokers
{
public interface IBrokeredMessageBodyConverter
{
string ContentType { get; }
TBody Convert<TBody>(byte[] body);
byte[] Convert(object body);
string Stringify(byte[] body);
string Stringify(object body);
}
}
|
using System;
using System.Globalization;
using System.Linq;
using Scrummy.Application.Web.MVC.Extensions.Entities;
using Scrummy.Application.Web.MVC.Presenters.Team;
using Scrummy.Application.Web.MVC.Utility;
using Scrummy.Application.Web.MVC.ViewModels.Team;
using Scrummy.Domain.Repositories;
using Scrummy.Domain.UseCases.Interfaces.Team;
namespace Scrummy.Application.Web.MVC.Presenters.Implementation.Team
{
internal class ViewProjectHistoryPresenter : Presenter, IViewProjectHistoryPresenter
{
public ViewProjectHistoryPresenter(
Action<MessageType, string> messageHandler,
Action<string, string> errorHandler,
IRepositoryProvider repositoryProvider)
: base(messageHandler, errorHandler, repositoryProvider)
{
}
public ViewProjectHistoryViewModel Present(ViewProjectHistoryResponse response)
{
return new ViewProjectHistoryViewModel
{
Team = response.Team.ToViewModel(),
Projects = response.Projects.Select(x =>
{
var project = RepositoryProvider.Project.Read(x.Id);
return new ViewProjectHistoryViewModel.Project
{
Id = project.Id.ToPresentationIdentity(),
Text = project.Name,
To = x.To.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
From = x.From.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
};
}),
};
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class HUDCraftingProgressMeter : MonoBehaviour {
public Camp playerCamp; // inspector set
Image progressBar;
Image progressBarFrame;
Image itemIcon;
Text percentageText;
// Use this for initialization
void Start () {
Image[] childImages = GetComponentsInChildren<Image>();
progressBar = childImages[1];
itemIcon = childImages[2];
progressBarFrame = GetComponent<Image>();
percentageText = GetComponentInChildren<Text>();
}
// Update is called once per frame
void Update () {
if (playerCamp.isCrafting)
{
percentageText.text = (int)(playerCamp.craftingProgress * 100) + "%";
progressBar.fillAmount = playerCamp.craftingProgress;
}
}
public void Enabled(bool flip)
{
percentageText.enabled = flip;
progressBar.enabled = flip;
progressBarFrame.enabled = flip;
itemIcon.enabled = flip;
if (flip)
{
itemIcon.sprite = playerCamp.currentlyCraftingItem.icon;
}
}
}
|
//===================================================
//作 者:边涯 http://www.u3dol.com QQ群:87481002
//创建时间:2015-11-29 17:07:00
//备 注:场景UI的基类
//===================================================
using UnityEngine;
using System.Collections;
/// <summary>
/// 场景UI的基类
/// </summary>
public class UISceneBase: UIBase
{
/// <summary>
/// 容器_居中
/// </summary>
[SerializeField]
public Transform Container_Center;
} |
using System;
using System.Threading.Tasks;
namespace MicroObjectsLib.Cache
{
public sealed class ClassCache<T> : ICache<T> where T : class
{
private T _cache;
public async Task<T> Retrieve(Func<Task<T>> func) => _cache ?? (_cache = await func());
public Task Clear() => Task.Run(() => _cache = null);
}
} |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace Ex08_Pr06_BookLibraryModification
{
class Ex08_Pr05_BookLibrary
{
// 100/100
static void Main()
{
int n = int.Parse(Console.ReadLine());
Dictionary<string, decimal> moneyMade = new Dictionary<string, decimal>();
for (int i = 0; i < n; i++)
{
string[] input = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string nameofAuthor = input[1];
decimal money = decimal.Parse(input[5]);
if (moneyMade.ContainsKey(nameofAuthor) == false)
{
moneyMade.Add(nameofAuthor, 0);
}
moneyMade[nameofAuthor] += money;
}
foreach (var item in moneyMade.OrderByDescending(x => x.Value).ThenBy(x => x.Key))
{
Console.WriteLine(item.Key + " -> " + string.Format("{0:F2}", item.Value));
}
}
}
} |
using System;
using System.Text;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace HttpMultipartParserUnitTest
{
using System.IO;
using HttpMultipartParser;
using System.Threading.Tasks;
/// <summary>
/// Summary description for RebufferableBinaryReaderUnitTest
/// </summary>
[TestClass]
public class RebufferableBinaryReaderUnitTest
{
public RebufferableBinaryReaderUnitTest()
{
//
// TODO: Add constructor logic here
//
}
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
// You can use the following additional attributes as you write your tests:
//
// Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
//
// Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
// public static void MyClassCleanup() { }
//
// Use TestInitialize to run code before running each test
// [TestInitialize()]
// public void MyTestInitialize() { }
//
// Use TestCleanup to run code after each test has run
// [TestCleanup()]
// public void MyTestCleanup() { }
//
#endregion
#region Read() Tests
[TestMethod]
public async Task CanReadSingleCharacterBuffer()
{
var stream = new InputStreamImpl(TestUtil.StringToStreamNoBom("abc"));
var reader = new RebufferableBinaryReader(stream, Encoding.UTF8);
Assert.AreEqual(await reader.ReadAsync(), 'a');
Assert.AreEqual(await reader.ReadAsync(), 'b');
Assert.AreEqual(await reader.ReadAsync(), 'c');
}
[TestMethod]
public async Task CanReadSingleCharacterOverBuffers()
{
var stream = new InputStreamImpl(TestUtil.StringToStreamNoBom("def"));
var reader = new RebufferableBinaryReader(stream, Encoding.UTF8);
reader.Buffer(TestUtil.StringToByteNoBom("abc"));
Assert.AreEqual(await reader.ReadAsync(), 'a');
Assert.AreEqual(await reader.ReadAsync(), 'b');
Assert.AreEqual(await reader.ReadAsync(), 'c');
Assert.AreEqual(await reader.ReadAsync(), 'd');
Assert.AreEqual(await reader.ReadAsync(), 'e');
Assert.AreEqual(await reader.ReadAsync(), 'f');
}
[TestMethod]
public async Task CanReadMixedAsciiAndUTFCharacters()
{
var stream = new InputStreamImpl(TestUtil.StringToStreamNoBom("abcdèfg"));
var reader = new RebufferableBinaryReader(stream, Encoding.UTF8);
Assert.AreEqual(await reader.ReadAsync(), 'a');
Assert.AreEqual(await reader.ReadAsync(), 'b');
Assert.AreEqual(await reader.ReadAsync(), 'c');
Assert.AreEqual(await reader.ReadAsync(), 'd');
Assert.AreEqual(await reader.ReadAsync(), 'è');
Assert.AreEqual(await reader.ReadAsync(), 'f');
Assert.AreEqual(await reader.ReadAsync(), 'g');
}
[TestMethod]
public async Task CanReadMixedAsciiAndUTFCharactersOverBuffers()
{
var stream = new InputStreamImpl(TestUtil.StringToStreamNoBom("dèfg"));
var reader = new RebufferableBinaryReader(stream, Encoding.UTF8);
reader.Buffer(TestUtil.StringToByteNoBom("abc"));
Assert.AreEqual(await reader.ReadAsync(), 'a');
Assert.AreEqual(await reader.ReadAsync(), 'b');
Assert.AreEqual(await reader.ReadAsync(), 'c');
Assert.AreEqual(await reader.ReadAsync(), 'd');
Assert.AreEqual(await reader.ReadAsync(), 'è');
Assert.AreEqual(await reader.ReadAsync(), 'f');
Assert.AreEqual(await reader.ReadAsync(), 'g');
}
#endregion
#region Read(buffer, index, count) Tests
[TestMethod]
public async Task CanReadSingleBuffer()
{
var stream = new InputStreamImpl(TestUtil.StringToStreamNoBom("6chars"));
var reader = new RebufferableBinaryReader(stream, Encoding.UTF8);
var buffer = new byte[Encoding.UTF8.GetByteCount("6chars")];
await reader.ReadAsync(buffer, 0, buffer.Length);
var result = Encoding.UTF8.GetString(buffer);
Assert.AreEqual(result, "6chars");
}
[TestMethod]
public async Task CanReadAcrossMultipleBuffers()
{
var stream = new InputStreamImpl(TestUtil.StringToStreamNoBom("ars"));
var reader = new RebufferableBinaryReader(stream, Encoding.UTF8);
reader.Buffer(TestUtil.StringToByteNoBom("6ch"));
var buffer = new byte[6];
await reader.ReadAsync(buffer, 0, buffer.Length);
Assert.AreEqual(Encoding.UTF8.GetString(buffer), "6chars");
}
[TestMethod]
public async Task CanReadMixedAsciiAndUTF8()
{
var stream = new InputStreamImpl(TestUtil.StringToStreamNoBom("5èats"));
var reader = new RebufferableBinaryReader(stream, Encoding.UTF8);
var buffer = new byte[Encoding.UTF8.GetByteCount("5èats")];
await reader.ReadAsync(buffer, 0, buffer.Length);
var result = Encoding.UTF8.GetString(buffer);
Assert.AreEqual(result, "5èats");
}
[TestMethod]
public async Task CanReadMixedAsciiAndUTF8AcrossMultipleBuffers()
{
var stream = new InputStreamImpl(TestUtil.StringToStreamNoBom("ts"));
var reader = new RebufferableBinaryReader(stream, Encoding.UTF8);
reader.Buffer(TestUtil.StringToByteNoBom(("5èa")));
var buffer = new byte[Encoding.UTF8.GetByteCount("5èats")];
await reader.ReadAsync(buffer, 0, buffer.Length);
var result = Encoding.UTF8.GetString(buffer);
Assert.AreEqual(result, "5èats");
}
[TestMethod]
public async Task ReadCorrectlyHandlesSmallerBufferThenStream()
{
var stream = new InputStreamImpl(TestUtil.StringToStreamNoBom("6chars"));
var reader = new RebufferableBinaryReader(stream, Encoding.UTF8);
var buffer = new byte[4];
await reader.ReadAsync(buffer, 0, buffer.Length);
Assert.AreEqual(Encoding.UTF8.GetString(buffer), "6cha");
buffer = new byte[2];
await reader.ReadAsync(buffer, 0, buffer.Length);
Assert.AreEqual(Encoding.UTF8.GetString(buffer), "rs");
}
[TestMethod]
public async Task ReadCorrectlyHandlesLargerBufferThenStream()
{
var stream = new InputStreamImpl(TestUtil.StringToStreamNoBom("6chars"));
var reader = new RebufferableBinaryReader(stream, Encoding.UTF8);
var buffer = new byte[10];
int amountRead = await reader.ReadAsync(buffer, 0, buffer.Length);
Assert.AreEqual(Encoding.UTF8.GetString(buffer), "6chars\0\0\0\0");
Assert.AreEqual(amountRead, 6);
}
[TestMethod]
public async Task ReadReturnsZeroOnNoData()
{
var stream = new InputStreamImpl(new MemoryStream());
var reader = new RebufferableBinaryReader(stream, Encoding.UTF8);
var buffer = new byte[6];
int amountRead = await reader.ReadAsync(buffer, 0, buffer.Length);
Assert.AreEqual(Encoding.UTF8.GetString(buffer), "\0\0\0\0\0\0");
Assert.AreEqual(amountRead, 0);
}
[TestMethod]
public async Task ReadCanResumeInterruptedStream()
{
var stream = new InputStreamImpl(TestUtil.StringToStreamNoBom("6chars"));
var reader = new RebufferableBinaryReader(stream, Encoding.UTF8);
var buffer = new byte[4];
int amountRead = await reader.ReadAsync(buffer, 0, buffer.Length);
Assert.AreEqual(Encoding.UTF8.GetString(buffer), "6cha");
Assert.AreEqual(amountRead, 4);
reader.Buffer(TestUtil.StringToByteNoBom("14intermission"));
buffer = new byte[14];
amountRead = await reader.ReadAsync(buffer, 0, buffer.Length);
Assert.AreEqual(Encoding.UTF8.GetString(buffer), "14intermission");
Assert.AreEqual(amountRead, 14);
buffer = new byte[2];
amountRead = await reader.ReadAsync(buffer, 0, buffer.Length);
Assert.AreEqual(Encoding.UTF8.GetString(buffer), "rs");
Assert.AreEqual(amountRead, 2);
}
#endregion
#region ReadByteLine() Tests
[TestMethod]
public async Task CanReadByteLineOnMixedAsciiAndUTF8Text()
{
var stream = new InputStreamImpl(TestUtil.StringToStreamNoBom("Bonjour poignée"));
var reader = new RebufferableBinaryReader(stream, Encoding.UTF8);
var bytes = await reader.ReadByteLine();
var expected = new byte[] {66, 111, 110, 106, 111, 117, 114, 32, 112, 111, 105, 103, 110, 195, 169, 101};
foreach (var pair in expected.Zip(bytes, Tuple.Create))
{
Assert.AreEqual(pair.Item1, pair.Item2);
}
}
#endregion
}
}
|
namespace IE.MobileStorage.Models
{
public class PackmanScores
{
public int Key { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AudioController : MonoBehaviour
{
public static AudioController Instance;
public List<AudioBundle> maleSFXLibrary;
public List<AudioBundle> femaleSFXLibrary;
public List<AudioBundle> SFXLibrary;
public List<AudioBundle> IntroLibrary;
public List<AudioBundle> AnnouncerLibrary;
private AudioClip currentSong;
private AudioSource ownAudioSource;
public AudioSource SFXAudioSource;
public float SFXVolume;
public float OSTVolume;
void Awake()
{
DontDestroyOnLoad(transform.gameObject);
Instance = this;
ownAudioSource = GetComponent<AudioSource>();
if (ownAudioSource.clip == null)
{
// ChangeBackgroundMusic("Main Menu");
}
}
void Update()
{
if (MainMenu.Instance != null) {
SFXVolume = float.Parse(MainMenu.Instance.SfxVolumeString) / 10;
ownAudioSource.volume = float.Parse(MainMenu.Instance.musicVolumeString) / 10;
}
}
public void CallMaleSound(string targetTrack)
{
for (int i = 0; i < maleSFXLibrary.Count; i++)
{
if (maleSFXLibrary[i].nameOfTrack == targetTrack)
{
SFXAudioSource.PlayOneShot(maleSFXLibrary[i].track, SFXVolume);
}
}
}
public void CallFemaleSound(string targetTrack)
{
for (int i = 0; i < femaleSFXLibrary.Count; i++)
{
if (femaleSFXLibrary[i].nameOfTrack == targetTrack)
{
SFXAudioSource.PlayOneShot(femaleSFXLibrary[i].track, SFXVolume);
}
}
}
public void CallAnnouncerSound(string targetTrack)
{
for (int i = 0; i < AnnouncerLibrary.Count; i++)
{
if (AnnouncerLibrary[i].nameOfTrack == targetTrack)
{
SFXAudioSource.PlayOneShot(AnnouncerLibrary[i].track, SFXVolume);
}
}
}
public void ChangeBackgroundMusic(string targetTrack)
{
for (int i = 0; i < IntroLibrary.Count; i++)
{
if (IntroLibrary[i].nameOfTrack == targetTrack)
{
ownAudioSource.clip = IntroLibrary[i].track;
ownAudioSource.Play();
}
}
}
public void CallSFXSound(string targetTrack)
{
for (int i = 0; i < SFXLibrary.Count; i++)
{
if (SFXLibrary[i].nameOfTrack == targetTrack)
{
SFXAudioSource.PlayOneShot(SFXLibrary[i].track, SFXVolume);
}
}
}
public void PlaySound(Gender targetGender, SoundEffect targetEffect)
{
if (targetGender == Gender.FEMALE)
{
switch (targetEffect)
{
case SoundEffect.ATTACK:
CallFemaleSound("Attack " + Random.Range(0, 8));
break;
case SoundEffect.BLOCK:
CallFemaleSound("Block " + Random.Range(0, 8));
break;
case SoundEffect.DEATH:
CallFemaleSound("Death " + Random.Range(0, 6));
break;
case SoundEffect.HIT:
CallFemaleSound("Hit " + Random.Range(0, 7));
break;
}
}
else if (targetGender == Gender.MALE)
{
switch (targetEffect)
{
case SoundEffect.ATTACK:
CallMaleSound("Attack " + Random.Range(0, 9));
break;
case SoundEffect.BLOCK:
CallMaleSound("Block " + Random.Range(0, 9));
break;
case SoundEffect.DEATH:
CallMaleSound("Death " + Random.Range(0, 6));
break;
case SoundEffect.HIT:
CallMaleSound("Hit " + Random.Range(0, 8));
break;
}
}
}
public void PlaySound(AnnouncerSounds targetSound)
{
switch (targetSound)
{
case AnnouncerSounds.CENA:
CallAnnouncerSound("Cena");
break;
case AnnouncerSounds.JOHN:
CallAnnouncerSound("John");
break;
case AnnouncerSounds.CHOOSEYOURCHARACTER:
CallAnnouncerSound("Choose Your Character");
break;
case AnnouncerSounds.FIGHT:
CallAnnouncerSound("Fight");
break;
case AnnouncerSounds.LOSE:
CallAnnouncerSound("Lose");
break;
case AnnouncerSounds.ROUND1:
CallAnnouncerSound("Round 1");
break;
case AnnouncerSounds.ROUND2:
CallAnnouncerSound("Round 2");
break;
case AnnouncerSounds.ROUND3:
CallAnnouncerSound("Round 3");
break;
case AnnouncerSounds.TIMEUP:
CallAnnouncerSound("Time up");
break;
case AnnouncerSounds.WIN:
CallAnnouncerSound("Win");
break;
case AnnouncerSounds.WINNER:
CallAnnouncerSound("Winner");
break;
case AnnouncerSounds.TEN:
CallAnnouncerSound("10");
break;
case AnnouncerSounds.NINE:
CallAnnouncerSound("9");
break;
case AnnouncerSounds.EIGHT:
CallAnnouncerSound("8");
break;
case AnnouncerSounds.SEVEN:
CallAnnouncerSound("7");
break;
case AnnouncerSounds.SIX:
CallAnnouncerSound("6");
break;
case AnnouncerSounds.FIVE:
CallAnnouncerSound("5");
break;
case AnnouncerSounds.FOUR:
CallAnnouncerSound("4");
break;
case AnnouncerSounds.THREE:
CallAnnouncerSound("3");
break;
case AnnouncerSounds.TWO:
CallAnnouncerSound("2");
break;
case AnnouncerSounds.ONE:
CallAnnouncerSound("1");
break;
}
}
public void PlaySound(SFXSounds targetSound)
{
switch (targetSound)
{
case SFXSounds.BLOODSPLATTER:
CallSFXSound("Blood Splatter " + Random.Range(0, 3));
break;
case SFXSounds.BUTTON:
CallSFXSound("Button");
break;
}
}
}
[System.Serializable]
public class AudioBundle
{
public string nameOfTrack;
public AudioClip track;
public AudioBundle(string NameOfTrack, AudioClip Track)
{
this.nameOfTrack = NameOfTrack;
this.track = Track;
}
}
public enum SoundType
{
ANNOUNCEMENT,
SFX,
CHARACTERSFX
}
public enum SoundEffect
{
BLOCK,
DEATH,
HIT,
ATTACK
}
public enum AnnouncerSounds
{
CENA,
JOHN,
CHOOSEYOURCHARACTER,
FIGHT,
LOSE,
ROUND1,
ROUND2,
ROUND3,
TIMEUP,
WIN,
WINNER,
TEN,
NINE,
EIGHT,
SEVEN,
SIX,
FIVE,
FOUR,
THREE,
TWO,
ONE
}
public enum SFXSounds
{
BLOODSPLATTER,
BUTTON
} |
namespace Mapbox.Unity.MeshGeneration.Modifiers
{
using Mapbox.Unity.MeshGeneration.Data;
public enum ModifierType
{
Preprocess,
Postprocess
}
/// <summary>
/// Mesh Data class and Mesh Modifier
/// MeshData class is used to keep data required for a mesh.Mesh modifiers recieve raw feature data and a mesh modifier,
/// generate their data and keep it inside MeshData. i.e.PolygonMeshModifier is responsible for triangulating the polygon,
/// so it calculates the triangle indices using the vertices and save it into MeshData.Triangles list.There's no control
/// over which field a mesh modifier fills or overrides but some of the basic mesh modifier goes like this;
/// Polygon mesh modifier - Vertices and triangles
/// Line Mesh modifier - Vertices, triangles and uvs
/// UV modifier - uvs(only used with polygon mesh modifier)
/// height modifier - vertices(adds new points), triangles(for side walls), uvs(for side walls)
/// After running all mesh modifiers, mesh data is expected to have at least vertices and triangles set as
/// they are the bare minimum to create a unity mesh object.
/// So the main purpose of the mesh modifiers is to fill up the mesh data class but they aren't limited to that either.
/// You can always create gameobjects and debug lines/spheres inside them for debugging purposes whenever you have a problem.
/// MeshData class also has some extra fields inside for data transfer purposes(between modifiers). i.e.Edges list
/// inside mesh data isn't used for mesh itself, but it's calculated by PolygonMeshModifier and used by HeightModifier
/// so to avoid calculating it twice, we're keeping it in the mesh data object. You can also extend mesh data like this
/// if you ever need to save data or share information between mesh modifiers.
/// We fully expect developers to create their own mesh modifiers to customize the look of their world.It would probably
/// take a little experience with mesh generation to be able to do this but it's the suggested way to create
/// custom world objects, like blobly toonish buildings, or wobbly roads.
/// </summary>
public class MeshModifier : ModifierBase
{
public virtual ModifierType Type { get { return ModifierType.Preprocess; } }
public virtual void Run(VectorFeatureUnity feature, MeshData md, float scale)
{
Run(feature, md);
}
public virtual void Run(VectorFeatureUnity feature, MeshData md, UnityTile tile = null)
{
}
}
} |
using System;
using System.Threading.Tasks;
using OmmaLicenseValidator;
using OmmaLicenseValidator.Responses;
namespace ValidatorSample
{
class Program
{
static void Main(string[] args)
{
var exit = false;
var validator = new ValidatorChecker();
Console.WriteLine("Enter a license number to check");
var license = Console.ReadLine();
while (!exit)
{
validator.GetLicenseDetails(license).Wait();
Console.WriteLine("Enter another license number or enter 'N' to exit");
license = Console.ReadLine() ?? "n";
if (license.Equals("n", StringComparison.InvariantCultureIgnoreCase))
exit = true;
}
}
}
public class ValidatorChecker
{
private readonly LicenseValidator _licenseValidator;
public ValidatorChecker()
{
_licenseValidator = new LicenseValidator();
}
public async Task GetLicenseDetails(string license)
{
Console.WriteLine("Fetching...");
var result = await _licenseValidator.GetValidatorResponseAsync(license);
Console.WriteLine("License Details ---");
Console.WriteLine($"County Issued: {result.CountyIssued}");
Console.WriteLine($"Expiration Date: {result.ExpirationDate.ToShortDateString()}");
Console.WriteLine($"Approved: {result.Approved}");
Console.WriteLine();
}
}
}
|
namespace SeudoBuild.Pipeline
{
/// <inheritdoc />
/// <summary>
/// Results from creating an archive from a build product.
/// </summary>
public class ArchiveStepResults : PipelineStepResults
{
public string ArchiveFileName { get; set; }
}
}
|
using System.Collections.Generic;
using GeoAPI.Geometries;
using NetTopologySuite.Algorithm;
using NetTopologySuite.Noding;
namespace NetTopologySuite.Geometries.Prepared
{
///<summary>
/// A base class containing the logic for computes the <i>contains</i>
/// and <i>covers</i> spatial relationship predicates
/// for a <see cref="PreparedPolygon"/> relative to all other <see cref="IGeometry"/> classes.
/// Uses short-circuit tests and indexing to improve performance.
///</summary>
/// <remarks>
/// <para>
/// Contains and covers are very similar, and differ only in how certain
/// cases along the boundary are handled. These cases require
/// full topological evaluation to handle, so all the code in
/// this class is common to both predicates.
/// </para>
/// <para>
/// It is not possible to short-circuit in all cases, in particular
/// in the case where line segments of the test geometry touches the polygon linework.
/// In this case full topology must be computed.
/// (However, if the test geometry consists of only points, this
/// <i>can</i> be evaluated in an optimized fashion.
/// </para>
/// </remarks>
/// <author>Martin Davis</author>
internal abstract class AbstractPreparedPolygonContains : PreparedPolygonPredicate
{
/**
* This flag controls a difference between contains and covers.
*
* For contains the value is true.
* For covers the value is false.
*/
protected bool RequireSomePointInInterior = true;
// information about geometric situation
private bool _hasSegmentIntersection;
private bool _hasProperIntersection;
private bool _hasNonProperIntersection;
///<summary>
/// Creates an instance of this operation.
/// </summary>
/// <param name="prepPoly">The PreparedPolygon to evaluate</param>
protected AbstractPreparedPolygonContains(PreparedPolygon prepPoly)
: base(prepPoly)
{
}
///<summary>
/// Evaluate the <i>contains</i> or <i>covers</i> relationship
/// for the given geometry.
///</summary>
/// <param name="geom">the test geometry</param>
/// <returns>true if the test geometry is contained</returns>
protected bool Eval(IGeometry geom)
{
/*
* Do point-in-poly tests first, since they are cheaper and may result
* in a quick negative result.
*
* If a point of any test components does not lie in target, result is false
*/
bool isAllInTargetArea = IsAllTestComponentsInTarget(geom);
if (!isAllInTargetArea) return false;
/*
* If the test geometry consists of only Points,
* then it is now sufficient to test if any of those
* points lie in the interior of the target geometry.
* If so, the test is contained.
* If not, all points are on the boundary of the area,
* which implies not contained.
*/
if (RequireSomePointInInterior
&& geom.Dimension == 0)
{
bool isAnyInTargetInterior = IsAnyTestComponentInTargetInterior(geom);
return isAnyInTargetInterior;
}
/*
* Check if there is any intersection between the line segments
* in target and test.
* In some important cases, finding a proper intersection implies that the
* test geometry is NOT contained.
* These cases are:
* <ul>
* <li>If the test geometry is polygonal
* <li>If the target geometry is a single polygon with no holes
* <ul>
* In both of these cases, a proper intersection implies that there
* is some portion of the interior of the test geometry lying outside
* the target, which means that the test is not contained.
*/
bool properIntersectionImpliesNotContained = IsProperIntersectionImpliesNotContainedSituation(geom);
// MD - testing only
// properIntersectionImpliesNotContained = true;
// find all intersection types which exist
FindAndClassifyIntersections(geom);
if (properIntersectionImpliesNotContained && _hasProperIntersection)
return false;
/*
* If all intersections are proper
* (i.e. no non-proper intersections occur)
* we can conclude that the test geometry is not contained in the target area,
* by the Epsilon-Neighbourhood Exterior Intersection condition.
* In real-world data this is likely to be by far the most common situation,
* since natural data is unlikely to have many exact vertex segment intersections.
* Thus this check is very worthwhile, since it avoid having to perform
* a full topological check.
*
* (If non-proper (vertex) intersections ARE found, this may indicate
* a situation where two shells touch at a single vertex, which admits
* the case where a line could cross between the shells and still be wholely contained in them.
*/
if (_hasSegmentIntersection && !_hasNonProperIntersection)
return false;
/*
* If there is a segment intersection and the situation is not one
* of the ones above, the only choice is to compute the full topological
* relationship. This is because contains/covers is very sensitive
* to the situation along the boundary of the target.
*/
if (_hasSegmentIntersection)
{
return FullTopologicalPredicate(geom);
// System.out.println(geom);
}
/*
* This tests for the case where a ring of the target lies inside
* a test polygon - which implies the exterior of the Target
* intersects the interior of the Test, and hence the result is false
*/
if (geom is IPolygonal)
{
// TODO: generalize this to handle GeometryCollections
bool isTargetInTestArea = IsAnyTargetComponentInAreaTest(geom, prepPoly.RepresentativePoints);
if (isTargetInTestArea) return false;
}
return true;
}
private bool IsProperIntersectionImpliesNotContainedSituation(IGeometry testGeom)
{
/*
* If the test geometry is polygonal we have the A/A situation.
* In this case, a proper intersection indicates that
* the Epsilon-Neighbourhood Exterior Intersection condition exists.
* This condition means that in some small
* area around the intersection point, there must exist a situation
* where the interior of the test intersects the exterior of the target.
* This implies the test is NOT contained in the target.
*/
if (testGeom is IPolygonal) return true;
/*
* A single shell with no holes allows concluding that
* a proper intersection implies not contained
* (due to the Epsilon-Neighbourhood Exterior Intersection condition)
*/
if (IsSingleShell(prepPoly.Geometry)) return true;
return false;
}
/// <summary>
/// Tests whether a geometry consists of a single polygon with no holes.
/// </summary>
/// <returns>True if the geometry is a single polygon with no holes</returns>
private static bool IsSingleShell(IGeometry geom)
{
// handles single-element MultiPolygons, as well as Polygons
if (geom.NumGeometries != 1) return false;
var poly = (IPolygon)geom.GetGeometryN(0);
int numHoles = poly.NumInteriorRings;
if (numHoles == 0) return true;
return false;
}
private void FindAndClassifyIntersections(IGeometry geom)
{
var lineSegStr = SegmentStringUtil.ExtractSegmentStrings(geom);
var intDetector = new SegmentIntersectionDetector();
intDetector.FindAllIntersectionTypes = true;
prepPoly.IntersectionFinder.Intersects(lineSegStr, intDetector);
_hasSegmentIntersection = intDetector.HasIntersection;
_hasProperIntersection = intDetector.HasProperIntersection;
_hasNonProperIntersection = intDetector.HasNonProperIntersection;
}
///<summary>
/// Computes the full topological predicate.
/// Used when short-circuit tests are not conclusive.
///</summary>
/// <param name="geom">The test geometry</param>
/// <returns>true if this prepared polygon has the relationship with the test geometry</returns>
protected abstract bool FullTopologicalPredicate(IGeometry geom);
}
}
|
using Newtonsoft.Json;
using Assets.Scripts.GameLogic.Enums;
namespace Assets.Scripts.Data.Entities
{
public class QuestModel : IEntity
{
[JsonProperty("quest_id")]
public int QuestId { get; set; }
[JsonProperty("quest_title")]
public string QuestTitle { get; set; }
[JsonProperty("completed")]
public bool Completed { get; set; }
[JsonProperty("quest_description")]
public string QuestDescription { get; set; }
[JsonProperty("quest_type")]
public QuestType QuestType { get; set; }
}
}
|
using Microsoft.EntityFrameworkCore;
namespace COVIDScreeningApi.Data
{
public class DataContext : DbContext
{
public DbSet<PortOfEntry> Ports { get; set; }
public DbSet<Representative> Representatives { get; set; }
public DbSet<Screening> Screenings { get; set; }
public DataContext(DbContextOptions<DataContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<PortOfEntry>()
.ToContainer("PortsOfEntry")
.HasNoDiscriminator()
.HasPartitionKey(x => x.PartitionKey);
modelBuilder
.Entity<Representative>()
.ToContainer("Representatives")
.HasNoDiscriminator()
.HasPartitionKey(x => x.PartitionKey);
modelBuilder
.Entity<Screening>()
.ToContainer("Screenings")
.HasNoDiscriminator()
.HasPartitionKey(x => x.PartitionKey);
}
}
} |
using System;
using System.ComponentModel.Composition;
namespace PA.Plugin
{
public interface IPluginCategory
{
string Category { get; }
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface), MetadataAttribute]
public class PluginCategoryAttribute : Attribute, IPluginCategory
{
public string Category { get; private set; }
public PluginCategoryAttribute(string Category)
:base()
{
this.Category = Category;
}
public PluginCategoryAttribute()
: base()
{
this.Category = "";
}
}
}
|
using Microsoft.AspNetCore.Mvc;
namespace Kahla.Home.Views.Shared.Components.KahlaNav
{
public class KahlaNav : ViewComponent
{
public IViewComponentResult Invoke(bool isProduction)
{
var model = new KahlaNavViewModel
{
IsProduction = isProduction
};
return View(model);
}
}
}
|
using System;
using System.Security.Claims;
using System.Security.Principal;
namespace MyExpenses.Web.Common
{
public static class PrincipalExtensions
{
public static MyExpensesUserIdentity GetAppIdentity(this IPrincipal principal)
{
Guid? userId=null;
string userName=string.Empty;
bool isAuthenticated = false;
var identity = principal!=null? principal.Identity as ClaimsIdentity : null;
if (identity != null)
{
isAuthenticated = true;
var nameClaim = identity.FindFirst(x => x.Type == "userName");
userName = nameClaim != null ? nameClaim.Value : null;
var idClaim = identity.FindFirst(x => x.Type == "userId");
Guid parsedGuid;
if (idClaim != null) if(Guid.TryParse(idClaim.Value, out parsedGuid)) userId=parsedGuid;
}
return new MyExpensesUserIdentity(userId,userName,isAuthenticated);
}
}
} |
using TNO.DAL.Models;
using TNO.Entities;
using TNO.Entities.Models;
namespace TNO.DAL.Services;
public interface IContentService : IBaseService<Content, long>
{
IPaged<Content> Find(ContentFilter filter);
}
|
using Helpdesk_Ticketing.Models;
using static Helpdesk_Ticketing.Models.TicketTypes;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Helpdesk_Ticketing.Models.ViewModels;
namespace Helpdesk_Ticketing.Data
{
public class TicketsDbContext : DbContext
{
public TicketsDbContext(DbContextOptions<TicketsDbContext> options): base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<TicketTypes>().HasData(
new TicketTypes
{
ID = 1,
NameTicket = "Problem 1",
//Importance = Priority.Low,
Comments = "details: "
},
new TicketTypes
{
ID = 2,
NameTicket = "Problem 2",
Comments = "details: "
},
new TicketTypes
{
ID = 3,
NameTicket = "Problem 3",
Comments = "details: "
},
new TicketTypes
{
ID = 4,
NameTicket = "Problem 4",
Comments = "details: "
},
new TicketTypes
{
ID = 5,
NameTicket = "Problem 5",
Comments = "details: "
}
);
}
public DbSet<TicketTypes> TicketTypes { get; set; }
public DbSet<CartTickets> CartTickets { get; set; }
public DbSet<Cart> Carts { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace GradingSystem
{
public interface IBook
{
void AddGrade(params double[] grade);
Statistics GetStatistics();
string Name { get; }
List<double> Grades { get; set; }
event GradeAddedDelegate GradeAdded;
}
}
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Unity.Collections;
using UnityEngine;
namespace DefenceFactory.Game.World
{
public enum ChunkFlag
{
None = 0x000,
Load = 0x001,
Redraw = 0x002,
Destroy = 0x004,
Generate = 0x010,
Updating = 0x020,
Update = 0x040,
Loaded = 0x100,
}
public static class ChunkFlagExtension
{
public static ref ChunkFlag Add(this ref ChunkFlag flag, ChunkFlag value)
{
flag |= value;
return ref flag;
}
public static ref ChunkFlag Remove(this ref ChunkFlag flag, ChunkFlag value)
{
flag &= ~value;
return ref flag;
}
}
}
|
// Copyright 2020 EPAM Systems, Inc.
//
// 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.
namespace HCA.Foundation.Commerce.Infrastructure.Pipelines
{
using System.Linq;
using Base.Providers.SiteDefinitions;
using Connect.Context.Storefront;
using Connect.Services.Search;
using Context;
using DependencyInjection;
using Providers;
using Sitecore;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
[Service(typeof(ICatalogItemResolver))]
public class CatalogItemResolver : ICatalogItemResolver
{
private readonly IPageTypeProvider pageTypeProvider;
private readonly ISearchService searchService;
private readonly ISiteContext siteContext;
private readonly ISiteDefinitionsProvider siteDefinitionsProvider;
private readonly IStorefrontContext storefrontContext;
public CatalogItemResolver(
ISearchService searchService,
IPageTypeProvider pageTypeProvider,
IStorefrontContext storefrontContext,
ISiteDefinitionsProvider siteDefinitionsProvider,
ISiteContext siteContext)
{
this.searchService = searchService;
this.pageTypeProvider = pageTypeProvider;
this.storefrontContext = storefrontContext;
this.siteDefinitionsProvider = siteDefinitionsProvider;
this.siteContext = siteContext;
}
public void ProcessItemAndApplyContext(Item contextItem, string[] urlSegments)
{
Assert.ArgumentNotNull(contextItem, nameof(contextItem));
if (urlSegments == null)
{
return;
}
var rootItem = this.siteDefinitionsProvider.GetCurrentSiteDefinition()?.RootItem;
if (rootItem == null)
{
return;
}
if (this.siteContext.CurrentItem != null)
{
return;
}
var currentItem = Context.Item;
while (currentItem != null && currentItem.ID != rootItem.ID)
{
var urlSegment = urlSegments.LastOrDefault()?.TrimEnd('/');
this.ProcessItem(currentItem, urlSegment);
if (urlSegments.Length > 0)
{
urlSegments = urlSegments.Take(urlSegments.Length - 1).ToArray();
}
currentItem = currentItem.Parent;
}
}
private void ProcessItem(Item item, string urlSegment)
{
var contextItemType = this.pageTypeProvider.ResolveByItem(item);
if (contextItemType == Commerce.Constants.ItemType.Unknown)
{
return;
}
var itemName = item.Name != "*" ? item.Name : urlSegment;
if (string.IsNullOrEmpty(itemName))
{
return;
}
Item currentItem;
switch (contextItemType)
{
case Commerce.Constants.ItemType.Category:
currentItem = this.searchService.GetCategoryItem(itemName);
this.siteContext.CurrentCategoryItem = currentItem;
break;
case Commerce.Constants.ItemType.Product:
currentItem = this.searchService.GetProductItem(itemName);
this.siteContext.CurrentProductItem = currentItem;
break;
default:
return;
}
if (this.siteContext.CurrentItem == null)
{
this.siteContext.CurrentItem = currentItem;
}
}
}
} |
// Copyright (c) 2015–Present Scott McDonald. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.md in the project root for license information.
using System.Diagnostics.Contracts;
namespace ApiFramework.Schema.Internal
{
/// <summary>
/// This API supports the API Framework infrastructure and is not intended to be used directly from your code.
/// This API may change or be removed in future releases.
/// </summary>
internal class ApiSchemaProxy : IApiSchemaProxy
{
// PUBLIC PROPERTIES ////////////////////////////////////////////////
#region Properties
public IApiSchema Subject { get; private set; }
#endregion
// INTERNAL METHODS /////////////////////////////////////////////////
#region Methods
internal void Initialize(IApiSchema subject)
{
Contract.Requires(subject != null);
this.Subject = subject;
}
#endregion
// PRIVATE METHODS //////////////////////////////////////////////////
#region Invariant Methods
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.Subject != null);
}
#endregion
}
} |
// Copyright (c) 2021 EPAM Systems
//
// 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 Epam.FixAntenna.NetCore.Common.Logging;
using Epam.FixAntenna.NetCore.Configuration;
namespace Epam.FixAntenna.NetCore.FixEngine.Storage.File
{
internal class SlicedFileMessageStorage : FlatFileMessageStorage
{
/// <summary>
/// The default maximum file size is 100MB.
/// </summary>
internal const long DefaultMaxFileSize = 100 * 1024 * 1024;
private static readonly ILog Log = LogFactory.GetLog(typeof(SlicedFileMessageStorage));
protected internal SlicedFileManager FileManager;
protected internal long MaxFileSize;
public SlicedFileMessageStorage(Config config) : base(config)
{
MaxFileSize = Configuration.GetPropertyAsBytesLength(Config.MaxStorageSliceSize);
if (MaxFileSize <= 0)
{
Log.Warn("Parameter \"" + Config.MaxStorageSliceSize +
"\" must be integer and greater than zero.");
MaxFileSize = DefaultMaxFileSize;
}
}
/// <inheritdoc />
public override long Initialize()
{
FileManager = new SlicedFileManager(FileName);
FileManager.Initialize();
FileName = FileManager.GetFileName();
return base.Initialize();
}
public virtual long GetMaxFileSize()
{
return MaxFileSize;
}
public virtual void SetMaxFileSize(long maxFileSize)
{
MaxFileSize = maxFileSize;
}
/// <inheritdoc />
protected internal override long AppendMessageInternal(long timestamp, byte[] message, int offset, int length)
{
if (ChannelPosition > MaxFileSize)
{
NextChunk();
}
return base.AppendMessageInternal(timestamp, message, offset, length);
}
public virtual void NextChunk()
{
Close();
FileName = FileManager.GetNextFileName();
OpenStorageFile();
}
/// <inheritdoc />
public override void BackupStorageFile(string fullPathToStorageFile, string fullPathToDestinationBackupFile)
{
var backupFileManager = new SlicedFileManager(fullPathToDestinationBackupFile);
backupFileManager.Initialize();
var last = FileManager.GetChunkId();
for (var i = 1; i <= last; i++)
{
BackupFile(FileManager.GetFileName(i), backupFileManager.GetFileName(i));
}
}
/// <inheritdoc />
public override void DeleteStorageFile(string fullPathToStorageFile)
{
var last = FileManager.GetChunkId();
for (var i = 1; i <= last; i++)
{
DeleteFile(FileManager.GetFileName(i));
}
}
}
} |
using System;
namespace Reddit.Inputs
{
[Serializable]
public class CategorizedSrListingInput : SrListingInput
{
/// <summary>
/// boolean value
/// </summary>
public bool include_categories;
/// <summary>
/// Input data for a categorized SR listing.
/// </summary>
/// <param name="after">fullname of a thing</param>
/// <param name="before">fullname of a thing</param>
/// <param name="count">a positive integer (default: 0)</param>
/// <param name="limit">the maximum number of items desired (default: 25, maximum: 100)</param>
/// <param name="show">(optional) the string all</param>
/// <param name="srDetail">(optional) expand subreddits</param>
/// <param name="includeCategories">boolean value</param>
public CategorizedSrListingInput(string after = null, string before = null, int count = 0, int limit = 25, string show = "all",
bool srDetail = false, bool includeCategories = false)
{
this.after = after;
this.before = before;
this.count = count;
this.limit = limit;
this.show = show;
sr_detail = srDetail;
include_categories = includeCategories;
}
}
}
|
using CleanArchitecture.Domain.Models;
using CleanArchitecture.Infrastructure.Data.Context;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CleanArchitecture.WebUI.Controllers
{
public class TagController : Controller
{
private readonly CA_BlogDbContext _context;
public TagController(CA_BlogDbContext context)
{
_context = context;
}
public IActionResult TagAdd()
{
return View();
}
[HttpPost]
public async Task<IActionResult> TagAdd(Tag tag)
{
await _context.Tags.AddAsync(tag);
await _context.SaveChangesAsync();
return RedirectToAction("Add", "Blog");
}
}
}
|
using BencodeNET.Parsing;
using BencodeNET.Torrents;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TorrentChain.Data.Models
{
public class BlockData
{
public BlockData(IEnumerable<byte> data)
{
Data = data.ToArray();
}
public IEnumerable<byte> Data { get; }
}
}
|
using Bridge.Test.NUnit;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Bridge.ClientTest.Batch3.BridgeIssues
{
/// <summary>
/// Ensures an external, template-driven constructor works on Bridge.
/// </summary>
/// <remarks>
/// It is required for the class to be marked as [Reflectable] and
/// Bridge's metadata generation rule should be enabled for this scenario
/// to work at all.
/// </remarks>
[TestFixture(TestNameFormat = "#3540 - {0}")]
public class Bridge3540
{
/// <summary>
/// This class should be marked as reflectable, so that the custom
/// constructor's template can be handled by Bridge.
/// </summary>
[Reflectable]
public class Test
{
public int a;
/// <summary>
/// An extern, template-driven constructor.
/// </summary>
[Template("{a: 1}")]
public extern Test();
}
/// <summary>
/// A generics parameter-driven method, necessary to reproduce the issue.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
static T TemplateMethod<T>() where T : class, new()
{
return new T();
}
/// <summary>
/// To test, we'd just call the template method specifying the Test
/// class as its generics' specialized type, and expect the custom
/// constructor to be executed.
/// </summary>
[Test]
public static void TestTemplateCtor()
{
var test = TemplateMethod<Test>();
Assert.AreEqual(1, test.a, "Custom, template-driven constructor is correctly called.");
}
}
} |
using Terraria;
using Terraria.Audio;
using Terraria.ModLoader;
using Terraria.ModLoader.Core;
namespace TerrariaOverhaul.Common.Hooks.Items
{
public interface IModifyItemNPCHitSound
{
public delegate void Delegate(Item item, Player player, NPC target, ref SoundStyle customHitSound, ref bool playNPCHitSound);
public static readonly HookList<GlobalItem, Delegate> Hook = ItemLoader.AddModHook(new HookList<GlobalItem, Delegate>(
//Method reference
typeof(IModifyItemNPCHitSound).GetMethod(nameof(IModifyItemNPCHitSound.ModifyItemNPCHitSound)),
//Invocation
e => (Item item, Player player, NPC target, ref SoundStyle customHitSound, ref bool playNPCHitSound) => {
foreach(IModifyItemNPCHitSound g in e.Enumerate(item)) {
g.ModifyItemNPCHitSound(item, player, target, ref customHitSound, ref playNPCHitSound);
}
}
));
void ModifyItemNPCHitSound(Item item, Player player, NPC target, ref SoundStyle customHitSound, ref bool playNPCHitSound);
}
}
|
namespace MSToolKit.Core.Authentication.Abstraction
{
/// <summary>
/// Provides an abstraction for validating passwords.
/// </summary>
public interface IPasswordValidator
{
/// <summary>
/// Validates the given password.
/// </summary>
/// <param name="password">The password in plain text.</param>
/// <returns>MSToolKit.Core.Authentication.AuthenticationResult</returns>
AuthenticationResult Validate(string password);
}
} |
using HospitalManagement.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace HospitalManagement.Services
{
public interface Departament
{
public Doctor makeAppointment(Patient Client, DateTime date);
}
}
|
// Copyright (c) Dapplo and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Reactive.Linq;
using System.Threading.Tasks;
using Dapplo.Log;
using Dapplo.Log.XUnit;
using Dapplo.Windows.Input.Mouse;
using Dapplo.Windows.Messages;
using Dapplo.Windows.Messages.Enumerations;
using Xunit.Abstractions;
namespace Dapplo.Windows.Tests
{
/// <summary>
/// Test mouse hooking
/// </summary>
public class MouseHookTests
{
public MouseHookTests(ITestOutputHelper testOutputHelper)
{
LogSettings.RegisterDefaultLogger<XUnitLogger>(LogLevels.Verbose, testOutputHelper);
}
//[StaFact]
private async Task Test_LeftMouseDownAsync()
{
// This takes care of having a WinProc handler, to make sure the messages arrive
// ReSharper disable once UnusedVariable
var winProcHandler = WinProcHandler.Instance;
await MouseHook.MouseEvents.Where(args => args.WindowsMessage == WindowsMessages.WM_LBUTTONDOWN).FirstAsync();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
using MvvmCross.iOS.Platform;
using MvvmCross.Platform;
using MvvmCross.Core.ViewModels;
using MvvmCross.Forms.iOS;
using PageRendererExample.UI.iOS;
namespace pagerenderexample.iOS
{
[Register("AppDelegate")]
public partial class AppDelegate : MvxFormsApplicationDelegate
{
private UIWindow _window;
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
_window = new UIWindow(UIScreen.MainScreen.Bounds);
var setup = new MvvmSetup(this, _window);
setup.Initialize();
_window.MakeKeyAndVisible();
LoadApplication(setup.MvxFormsApp);
return base.FinishedLaunching(app, options);
}
}
}
|
using AutoVersionsDB.NotificationableEngine;
namespace AutoVersionsDB.Core.ConfigProjects.Processes
{
public abstract class ProjectConfigProcessDefinition : ProcessDefinition
{
public ProjectConfigProcessDefinition()
: base(null)
{
}
}
}
|
using OpenTK;
using System;
using System.Diagnostics;
using System.Threading;
namespace GameCore
{
/// <summary>
/// Handle rendering on a separate thread.
/// </summary>
public class BackgroundRenderer : IDisposable
{
#region Events
public event EventHandler<EventArgs> Initialize;
public event EventHandler<EventArgs> DisposeResources;
/// <summary>
/// Add your game rendering code here.
/// </summary>
/// <param name="e">Contains timing information.</param>
public event EventHandler<FrameEventArgs> RenderFrame;
#endregion
#region Fields
private bool _disposed;
private GameWindow _game;
private Thread _renderTask;
private bool _exitRequested;
#endregion
#region Constructors
public BackgroundRenderer(GameWindow game)
{
_disposed = false;
_game = game;
_renderTask = new Thread(RenderLoop);
_exitRequested = false;
}
#endregion
#region Properties
public GameWindow Game
{
get
{
return _game;
}
}
#endregion
#region Methods
/// <summary>
/// Start the renderer thread running in the background.
/// </summary>
public void Start()
{
// Release the OpenGL context so it can be used on the rendering thread.
_game.Context.MakeCurrent(null);
_renderTask.Start();
}
public void Exit()
{
_exitRequested = true;
_renderTask.Join();
}
private void RenderLoop()
{
// We will dispose of this ourself.
GC.SuppressFinalize(this);
// The OpenGL context now belongs to the rendering thread. No other thread may use it!
_game.MakeCurrent();
if (Initialize != null)
{
Initialize(this, EventArgs.Empty);
}
var renderTimer = Stopwatch.StartNew();
var frameTime = TimeSpan.Zero;
while (!_exitRequested)
{
HandleRender(frameTime);
frameTime = renderTimer.Elapsed;
renderTimer.Restart();
}
Dispose();
}
private void HandleRender(TimeSpan elapsed)
{
if (RenderFrame != null)
{
RenderFrame(this, new FrameEventArgs(elapsed));
}
_game.SwapBuffers();
}
public void Dispose()
{
Dispose(true);
}
void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (DisposeResources != null)
{
DisposeResources(this, EventArgs.Empty);
}
}
_game.Context.MakeCurrent(null);
_disposed = true;
}
}
~BackgroundRenderer()
{
Dispose(false);
}
#endregion
}
}
|
using System.Linq;
using Microsoft.Extensions.Logging;
using TheFlow.CoreConcepts;
using TheFlow.Elements.Activities;
using TheFlow.Infrastructure.Parallel;
namespace TheFlow.Elements.Gateways
{
public class ParallelGateway : Activity
{
// TODO: Support multiple input connections and multiple output connections
public override void Run(ExecutionContext context)
{
var processMonitor = context.ServiceProvider
.GetService<IProcessMonitor>();
var logger = context.ServiceProvider?
.GetService<ILogger<ParallelGateway>>();
var incomingConnections = context.Model
.GetIncomingConnections(context.Token.ExecutionPoint)
.ToArray();
if (incomingConnections.Length <= 1)
{
context.Instance
.HandleActivityCompletion(context.WithRunningElement(null), null);
}
else
{
var parentToken = context.Instance.Token.FindById(context.Token.ParentId);
var key = $"{context.Token.ParentId}/{context.Token.ExecutionPoint}";
var pending = 0;
using (processMonitor?.Lock(key))
{
context.Token.Release();
var childrenCount = parentToken.Children.Count();
var actionableChildrenCount = parentToken.Children
.SelectMany(c => c.GetActionableTokens())
.Count();
pending = actionableChildrenCount + (incomingConnections.Length - childrenCount);
}
if (pending == 0)
{
logger?.LogInformation($"({context.Token.ExecutionPoint}) All tokens are done. Moving on...");
parentToken.ExecutionPoint = context.Token.ExecutionPoint;
context.Instance
.HandleActivityCompletion(
context
.WithRunningElement(null)
.WithToken(parentToken),
null);
}
}
}
}
} |
using UnityEngine;
[AddComponentMenu("")]
public class Test01_DebugLog : MonoBehaviour
{
void Start()
{
Debug.Log("Hello, World! - From, Udon#");
}
}
|
using HyperMap.Converters.Collections;
using HyperMap.Integration.Tests.Sources;
using HyperMap.Integration.Tests.Targets;
using HyperMap.Mapping;
namespace HyperMap.Integration.Tests.Maps
{
public sealed class CustomerToCustomerListViewMap : MapBase<Customer, CustomerListView>
{
public CustomerToCustomerListViewMap()
{
For(p => p.Orders).MapTo(p => p.Orders).Using<EnumerableToListTypeConverter<Order, OrderView>>();
}
}
}
|
@section styles
{
<link href="~/App/Main/styles/main.css" rel="stylesheet" />
}
@section scripts
{
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/angular-animate.min.js"></script>
<script src="~/Scripts/angular-route.min.js"></script>
<script src="~/Scripts/angular-sanitize.min.js"></script>
<script src="~/Scripts/angular-ui/ui-bootstrap.min.js"></script>
<script src="~/Scripts/angular-ui/ui-bootstrap-tpls.min.js"></script>
<script src="~/Scripts/angular-ui/ui-utils.min.js"></script>
<script src="~/Abp/Framework/scripts/libs/angularjs/abp.ng.js"></script>
<script src="~/api/AbpServiceProxies/GetAll?type=angular"></script>
<script src="~/App/Main/app.js"></script>
<script src="~/App/Main/views/layout/layout.js"></script>
<script src="~/App/Main/views/home/home.js"></script>
<script src="~/App/Main/views/about/about.js"></script>
}
<div ng-app="app">
@Html.Partial("~/App/Main/views/layout/layout.cshtml")
</div> |
using System.Collections.Generic;
namespace CompositeC1Contrib.FormBuilder
{
public interface IModelsProvider
{
IEnumerable<ProviderModelContainer> GetModels();
}
}
|
using System;
using Microsoft.Extensions.Caching.Memory;
namespace PidPlugin.Cache
{
public class MemoryCacheAccessor : ICacheAccessor
{
private readonly IMemoryCache memoryCache;
public MemoryCacheAccessor(IMemoryCache memoryCache)
{
this.memoryCache = memoryCache ??
throw new ArgumentNullException(nameof(memoryCache));
}
public bool TryGetValue(string key, out object value)
{
return this.memoryCache.TryGetValue(key, out value);
}
public void Set(string key, object value, TimeSpan expirationTime)
{
System.Diagnostics.Debug.WriteLine("SETTING");
this.memoryCache.Set(key, value, expirationTime);
}
}
}
|
using System.Threading.Tasks;
using Microsoft.ServiceBus.Messaging;
namespace Nimbus.Infrastructure
{
internal interface IQueueManager
{
Task<MessageSender> CreateMessageSender(string queuePath);
Task<MessageReceiver> CreateMessageReceiver(string queuePath);
Task<TopicClient> CreateTopicSender(string topicPath);
Task<SubscriptionClient> CreateSubscriptionReceiver(string topicPath, string subscriptionName);
Task<QueueClient> CreateDeadLetterQueueClient<T>();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace Mimick
{
/// <summary>
/// A class containing extension methods for common array operations.
/// </summary>
public static partial class Extensions
{
/// <summary>
/// Create a copy of the array.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <param name="array">The array.</param>
/// <returns>The new array instance containing the copied values.</returns>
public static T[] Copy<T>(this T[] array) => Copy(array, 0, array.Length);
/// <summary>
/// Create a copy of the array.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <param name="array">The array.</param>
/// <param name="index">The zero-based array index to begin copying from.</param>
/// <returns>The new array instance containing the copied values.</returns>
public static T[] Copy<T>(this T[] array, int index) => Copy(array, index, array.Length - index);
/// <summary>
/// Create a copy of the array.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <param name="array">The array.</param>
/// <param name="index">The zero-based array index to begin copying from.</param>
/// <param name="count">The number of elements to copy.</param>
/// <returns>The new array instance containing the copied values.</returns>
public static T[] Copy<T>(this T[] array, int index, int count)
{
T[] target = new T[count];
Array.Copy(array, index, target, 0, count);
return target;
}
/// <summary>
/// Fills all elements of the array with the provided value.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <param name="array">The array.</param>
/// <param name="value">The array fill value.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Fill<T>(this T[] array, T value) => Fill(array, value, 0, array.Length);
/// <summary>
/// Fills all elements of the array with the provided value.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <param name="array">The array.</param>
/// <param name="value">The array fill value.</param>
/// <param name="index">The zero-based array index to begin filling from.</param>
/// <param name="count">The number of elements to fill.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Fill<T>(this T[] array, T value, int index, int count)
{
for (int i = 0; i < count; i++)
array[i + index] = value;
}
/// <summary>
/// Slices the array at the provided index, returning a new array containing the sliced elements.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <param name="array">The array.</param>
/// <param name="index">The zero-based index of the array to slice from.</param>
/// <returns>A new array containing the sliced elements.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T[] Slice<T>(this T[] array, int index) => Copy(array, index);
/// <summary>
/// Slices the array at the provided index, returning a new array containing the sliced elements.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <param name="array">The array.</param>
/// <param name="index">The zero-based index of the array to slice from.</param>
/// <param name="count">The number of elements to slice.</param>
/// <returns>A new array containing the sliced elements.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T[] Slice<T>(this T[] array, int index, int count) => Copy(array, index, count);
}
}
|
using UnityEngine;
public interface IEDroneState
{
void UpdateState();
void GoToAttackState();
void GoToAlertState();
void GoToPatrolState();
void OnTriggerEnter(Collider other);
void OnTriggerStay(Collider other);
void OnTriggerExit(Collider other);
void Impact();
}
|
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using Ultraviolet.Core;
using Ultraviolet.Core.Text;
using Ultraviolet.FreeType2.Native;
using Ultraviolet.Graphics;
using Ultraviolet.Graphics.Graphics2D;
using Ultraviolet.Graphics.Graphics2D.Text;
using static Ultraviolet.FreeType2.Native.FreeTypeNative;
using static Ultraviolet.FreeType2.Native.FT_Error;
using static Ultraviolet.FreeType2.Native.FT_Kerning_Mode;
using static Ultraviolet.FreeType2.Native.FT_Pixel_Mode;
using static Ultraviolet.FreeType2.Native.FT_Render_Mode;
using static Ultraviolet.FreeType2.Native.FT_Stroker_LineCap;
using static Ultraviolet.FreeType2.Native.FT_Stroker_LineJoin;
namespace Ultraviolet.FreeType2
{
/// <summary>
/// Represents one of a FreeType font's font faces.
/// </summary>
public unsafe class FreeTypeFontFace : UltravioletFontFace
{
/// <summary>
/// Initializes a new instance of the <see cref="FreeTypeFontFace"/> class.
/// </summary>
/// <param name="uv">The Ultraviolet context.</param>
/// <param name="face">The FreeType2 face which this instance represents.</param>
/// <param name="metadata">The processor metadata with which this font face was loaded.</param>
internal FreeTypeFontFace(UltravioletContext uv, IntPtr face, FreeTypeFontProcessorMetadata metadata)
: base(uv)
{
Contract.Require(face, nameof(face));
this.face = face;
this.facade = new FT_FaceRecFacade(face);
this.stroker = CreateStroker(face, metadata);
if (metadata.AtlasWidth < 1 || metadata.AtlasHeight < 1 || metadata.AtlasSpacing < 0)
throw new InvalidOperationException(FreeTypeStrings.InvalidAtlasParameters);
this.AtlasWidth = metadata.AtlasWidth;
this.AtlasHeight = metadata.AtlasHeight;
this.AtlasSpacing = metadata.AtlasSpacing;
this.scale = metadata.Scale;
this.offsetXAdjustment = metadata.AdjustOffsetX;
this.offsetYAdjustment = metadata.AdjustOffsetY;
this.hAdvanceAdjustment = metadata.AdjustHorizontalAdvance;
this.vAdvanceAdjustment = metadata.AdjustVerticalAdvance;
this.glyphWidthAdjustment = (metadata.StrokeRadius * 2);
this.glyphHeightAdjustment = (metadata.StrokeRadius * 2);
this.HasColorStrikes = facade.HasColorFlag;
this.HasKerningInfo = facade.HasKerningFlag;
this.FamilyName = facade.MarshalFamilyName();
this.StyleName = facade.MarshalStyleName();
if (scale != 1f)
{
this.Ascender = (Int32)Math.Floor(scale * facade.Ascender) + metadata.AdjustAscender;
this.Descender = (Int32)Math.Floor(scale * facade.Descender) + metadata.AdjustDescender;
this.LineSpacing = (Int32)Math.Floor(scale * facade.LineSpacing) + metadata.AdjustLineSpacing;
}
else
{
this.Ascender = facade.Ascender + metadata.AdjustAscender;
this.Descender = facade.Descender + metadata.AdjustDescender;
this.LineSpacing = facade.LineSpacing + metadata.AdjustLineSpacing;
}
if (GetGlyphInfo(' ', false, out var spaceGlyphInfo))
this.SpaceWidth = spaceGlyphInfo.Width;
this.SizeInPoints = metadata.SizeInPoints;
this.SizeInPixels = SizeInPixels;
this.TabWidth = SpaceWidth * 4;
this.totalDesignHeight = Ascender - Descender;
this.SubstitutionCharacter = metadata.Substitution ??
facade.GetCharIfDefined('�') ?? facade.GetCharIfDefined('□') ?? '?';
PopulateGlyph(SubstitutionCharacter);
}
/// <inheritdoc/>
public override String ToString() => String.Format("{0} {1} {2}pt", FamilyName, StyleName, SizeInPoints);
/// <inheritdoc/>
public override Int32 GetGlyphIndex(Int32 codePoint) =>
(Int32)facade.GetCharIndex((UInt32)codePoint);
/// <inheritdoc/>
public override void GetCodePointRenderInfo(Int32 codePoint, out GlyphRenderInfo info) =>
info = GetGlyphInfo((UInt32)codePoint, false, out var ginfo) ? ginfo.ToGlyphRenderInfo() : default(GlyphRenderInfo);
/// <inheritdoc/>
public override void GetGlyphIndexRenderInfo(Int32 glyphIndex, out GlyphRenderInfo info) =>
info = GetGlyphInfo((UInt32)glyphIndex, true, out var ginfo) ? ginfo.ToGlyphRenderInfo() : default(GlyphRenderInfo);
/// <inheritdoc/>
public override Size2 MeasureString(String text)
{
var source = new StringSource(text);
return MeasureString(ref source, 0, text.Length);
}
/// <inheritdoc/>
public override Size2 MeasureString(String text, Int32 start, Int32 count)
{
var source = new StringSource(text);
return MeasureString(ref source, start, count);
}
/// <inheritdoc/>
public override Size2 MeasureString(StringBuilder text)
{
var source = new StringBuilderSource(text);
return MeasureString(ref source, 0, text.Length);
}
/// <inheritdoc/>
public override Size2 MeasureString(StringBuilder text, Int32 start, Int32 count)
{
var source = new StringBuilderSource(text);
return MeasureString(ref source, start, count);
}
/// <inheritdoc/>
public override Size2 MeasureString(ref StringSegment text)
{
var source = new StringSegmentSource(text);
return MeasureString(ref source, 0, text.Length);
}
/// <inheritdoc/>
public override Size2 MeasureString(ref StringSegment text, Int32 start, Int32 count)
{
var source = new StringSegmentSource(text);
return MeasureString(ref source, start, count);
}
/// <inheritdoc/>
public override Size2 MeasureString<TSource>(ref TSource text)
{
return MeasureString(ref text, 0, text.Length);
}
/// <inheritdoc/>
public override Size2 MeasureString<TSource>(ref TSource text, Int32 start, Int32 count)
{
if (count == 0)
return Size2.Zero;
Contract.EnsureRange(start >= 0 && start < text.Length, nameof(start));
Contract.EnsureRange(count >= 0 && start + count <= text.Length, nameof(count));
var cx = 0;
var cy = 0;
var maxLineWidth = 0;
for (var i = 0; i < count; i++)
{
var ix = start + i;
var ixNext = ix + 1;
var character = text[ix];
if (ixNext < count && Char.IsSurrogatePair(text[ix], text[ixNext]))
i++;
switch (character)
{
case '\r':
continue;
case '\n':
maxLineWidth = Math.Max(maxLineWidth, cx);
cx = 0;
cy = cy + LineSpacing;
continue;
case '\t':
cx = cx + TabWidth;
continue;
}
cx += MeasureGlyph(ref text, ix).Width;
}
maxLineWidth = Math.Max(maxLineWidth, cx);
return new Size2(maxLineWidth, cy + totalDesignHeight);
}
/// <inheritdoc/>
public override Size2 MeasureShapedString(ShapedString text, Boolean rtl = false) =>
MeasureShapedString(ref text, 0, text.Length, rtl);
/// <inheritdoc/>
public override Size2 MeasureShapedString(ShapedString text, Int32 start, Int32 count, Boolean rtl = false) =>
MeasureShapedString(ref text, start, count, rtl);
/// <inheritdoc/>
public override Size2 MeasureShapedString(ShapedStringBuilder text, Boolean rtl = false) =>
MeasureShapedString(ref text, 0, text.Length, rtl);
/// <inheritdoc/>
public override Size2 MeasureShapedString(ShapedStringBuilder text, Int32 start, Int32 count, Boolean rtl = false) =>
MeasureShapedString(ref text, start, count, rtl);
/// <inheritdoc/>
public override Size2 MeasureShapedString<TSource>(ref TSource text, Boolean rtl = false) =>
MeasureShapedString(ref text, 0, text.Length, rtl);
/// <inheritdoc/>
public override Size2 MeasureShapedString<TSource>(ref TSource text, Int32 start, Int32 count, Boolean rtl = false)
{
if (count == 0)
return Size2.Zero;
Contract.EnsureRange(start >= 0 && start < text.Length, nameof(start));
Contract.EnsureRange(count >= 0 && start + count <= text.Length, nameof(count));
var cx = 0;
var cy = 0;
var maxLineWidth = 0;
for (var i = 0; i < count; i++)
{
var sc = text[rtl ? (text.Length - 1) - i : i];
switch (sc.GetSpecialCharacter())
{
case '\n':
maxLineWidth = Math.Max(maxLineWidth, cx);
cx = 0;
cy = cy + LineSpacing;
break;
case '\t':
cx = cx + TabWidth;
break;
default:
cx = cx + sc.Advance;
break;
}
}
maxLineWidth = Math.Max(maxLineWidth, cx);
return new Size2(maxLineWidth, totalDesignHeight);
}
/// <inheritdoc/>
public override Size2 MeasureGlyph(Int32 c1, Int32? c2 = null)
{
if (!GetGlyphInfo((UInt32)c1, false, out var c1Info))
return Size2.Zero;
return new Size2(c1Info.Advance, totalDesignHeight);
}
/// <inheritdoc/>
public override Size2 MeasureGlyphByGlyphIndex(Int32 glyphIndex1, Int32? glyphIndex2 = null)
{
if (!GetGlyphInfo((UInt32)glyphIndex1, true, out var info))
return Size2.Zero;
return new Size2(info.Advance, totalDesignHeight);
}
/// <inheritdoc/>
public override Size2 MeasureGlyph(String text, Int32 ix)
{
var source = new StringSource(text);
return MeasureGlyph(ref source, ix);
}
/// <inheritdoc/>
public override Size2 MeasureGlyph(StringBuilder text, Int32 ix)
{
var source = new StringBuilderSource(text);
return MeasureGlyph(ref source, ix);
}
/// <inheritdoc/>
public override Size2 MeasureGlyph(ref StringSegment text, Int32 ix)
{
var source = new StringSegmentSource(text);
return MeasureGlyph(ref source, ix);
}
/// <inheritdoc/>
public override Size2 MeasureGlyph<TSource>(ref TSource text, Int32 ix)
{
GetUtf32CodePointFromString(ref text, ix, out var c1, out var c1length);
if (!GetGlyphInfo(c1, false, out var cinfo))
return Size2.Zero;
var c2 = (ix + c1length < text.Length) ? text[ix + c1length] : (Char?)null;
var offset = c2.HasValue ? GetKerningInfo((Int32)c1, c2.GetValueOrDefault()) : Size2.Zero;
return new Size2(cinfo.Advance, totalDesignHeight) + offset;
}
/// <inheritdoc/>
public override Size2 MeasureShapedGlyph(ShapedString text, Int32 ix, Boolean rtl = false) =>
MeasureShapedGlyph(ref text, ix, rtl);
/// <inheritdoc/>
public override Size2 MeasureShapedGlyph(ShapedStringBuilder text, Int32 ix, Boolean rtl = false) =>
MeasureShapedGlyph(ref text, ix, rtl);
/// <inheritdoc/>
public override Size2 MeasureShapedGlyph<TSource>(ref TSource source, Int32 ix, Boolean rtl = false)
{
var sc = source[rtl ? (source.Length - 1) - ix : ix];
switch (sc.GetSpecialCharacter())
{
case '\n':
return Size2.Zero;
case '\t':
return new Size2(TabWidth, totalDesignHeight);
default:
return new Size2(sc.Advance, totalDesignHeight);
}
}
/// <inheritdoc/>
public override Size2 MeasureGlyphWithHypotheticalKerning(ref StringSegment text, Int32 ix, Int32 c2)
{
var source = new StringSegmentSource(text);
return MeasureGlyphWithHypotheticalKerning(ref source, ix, c2);
}
/// <inheritdoc/>
public override Size2 MeasureGlyphWithHypotheticalKerning<TSource>(ref TSource text, Int32 ix, Int32 c2)
{
GetUtf32CodePointFromString(ref text, ix, out var c1, out _);
if (!GetGlyphInfo(c1, false, out var cinfo))
return Size2.Zero;
var offset = GetKerningInfo((Int32)c1, c2);
return new Size2(cinfo.Advance, totalDesignHeight) + offset;
}
/// <inheritdoc/>
public override Size2 MeasureShapedGlyphWithHypotheticalKerning<TSource>(ref TSource text, Int32 ix, Int32 glyphIndex2, Boolean rtl = false) =>
new Size2(text[rtl ? (text.Length - 1) - ix : ix].Advance, totalDesignHeight);
/// <inheritdoc/>
public override Size2 MeasureGlyphWithoutKerning(ref StringSegment text, Int32 ix)
{
var source = new StringSegmentSource(text);
return MeasureGlyphWithoutKerning(ref source, ix);
}
/// <inheritdoc/>
public override Size2 MeasureGlyphWithoutKerning<TSource>(ref TSource text, Int32 ix)
{
GetUtf32CodePointFromString(ref text, ix, out var c1, out _);
if (!GetGlyphInfo(c1, false, out var cinfo))
return Size2.Zero;
return new Size2(cinfo.Advance, totalDesignHeight);
}
/// <inheritdoc/>
public override Size2 MeasureShapedGlyphWithoutKerning<TSource>(ref TSource text, Int32 ix, Boolean rtl = false) =>
new Size2(text[rtl ? (text.Length - 1) - ix : ix].Advance, totalDesignHeight);
/// <inheritdoc/>
public override Size2 GetKerningInfoByGlyphIndex(Int32 glyphIndex1, Int32 glyphIndex2)
{
if (face == IntPtr.Zero || !HasKerningInfo)
return Size2.Zero;
if (Use64BitInterface)
{
var kerning = default(FT_Vector64);
var err = FT_Get_Kerning(face, (UInt32)glyphIndex1, (UInt32)glyphIndex2, (UInt32)FT_KERNING_DEFAULT, (IntPtr)(&kerning));
if (err != FT_Err_Ok)
throw new FreeTypeException(err);
var x = FreeTypeCalc.F26Dot6ToInt32(kerning.x);
var y = FreeTypeCalc.F26Dot6ToInt32(kerning.y);
return new Size2(x, y);
}
else
{
var kerning = default(FT_Vector32);
var err = FT_Get_Kerning(face, (UInt32)glyphIndex1, (UInt32)glyphIndex2, (UInt32)FT_KERNING_DEFAULT, (IntPtr)(&kerning));
if (err != FT_Err_Ok)
throw new FreeTypeException(err);
var x = FreeTypeCalc.F26Dot6ToInt32(kerning.x);
var y = FreeTypeCalc.F26Dot6ToInt32(kerning.y);
return new Size2(x, y);
}
}
/// <inheritdoc/>
public override Size2 GetKerningInfo(Int32 c1, Int32 c2)
{
if (face == IntPtr.Zero || !HasKerningInfo)
return Size2.Zero;
var c1Index = facade.GetCharIndex((UInt32)c1);
if (c1Index == 0)
return Size2.Zero;
var c2Index = facade.GetCharIndex((UInt32)c2);
if (c2Index == 0)
return Size2.Zero;
if (Use64BitInterface)
{
var kerning = default(FT_Vector64);
var err = FT_Get_Kerning(face, c1Index, c2Index, (UInt32)FT_KERNING_DEFAULT, (IntPtr)(&kerning));
if (err != FT_Err_Ok)
throw new FreeTypeException(err);
var x = FreeTypeCalc.F26Dot6ToInt32(kerning.x);
var y = FreeTypeCalc.F26Dot6ToInt32(kerning.y);
return new Size2(x, y);
}
else
{
var kerning = default(FT_Vector32);
var err = FT_Get_Kerning(face, c1Index, c2Index, (UInt32)FT_KERNING_DEFAULT, (IntPtr)(&kerning));
if (err != FT_Err_Ok)
throw new FreeTypeException(err);
var x = FreeTypeCalc.F26Dot6ToInt32(kerning.x);
var y = FreeTypeCalc.F26Dot6ToInt32(kerning.y);
return new Size2(x, y);
}
}
/// <inheritdoc/>
public override Size2 GetKerningInfo(ref StringSegment text, Int32 ix)
{
var source = new StringSegmentSource(text);
return GetKerningInfo(ref source, ix);
}
/// <inheritdoc/>
public override Size2 GetKerningInfo(ref StringSegment text1, Int32 ix1, ref StringSegment text2, Int32 ix2)
{
var source1 = new StringSegmentSource(text1);
var source2 = new StringSegmentSource(text2);
return GetKerningInfo(ref source1, ix1, ref source2, ix2);
}
/// <inheritdoc/>
public override Size2 GetKerningInfo<TSource>(ref TSource text, Int32 ix)
{
if (ix + 1 >= text.Length)
return Size2.Zero;
var pos = ix;
GetUtf32CodePointFromString(ref text, pos, out var c1, out var c1length);
pos += c1length;
if (pos >= text.Length)
return Size2.Zero;
GetUtf32CodePointFromString(ref text, pos, out var c2, out _);
return GetKerningInfo((Int32)c1, (Int32)c2);
}
/// <inheritdoc/>
public override Size2 GetKerningInfo<TSource1, TSource2>(ref TSource1 text1, Int32 ix1, ref TSource2 text2, Int32 ix2)
{
var c1 = text1[ix1];
var c2 = text2[ix2];
return GetKerningInfo(c1, c2);
}
/// <inheritdoc/>
public override Size2 GetShapedKerningInfo<TSource>(ref TSource text, Int32 ix) => Size2.Zero;
/// <inheritdoc/>
public override Size2 GetShapedKerningInfo<TSource1, TSource2>(ref TSource1 text1, Int32 ix1, ref TSource2 text2, Int32 ix2, Boolean rtl = false) => Size2.Zero;
/// <inheritdoc/>
public override Size2 GetHypotheticalKerningInfo(ref StringSegment text, Int32 ix, Int32 c2)
{
var source = new StringSegmentSource(text);
return GetHypotheticalKerningInfo(ref source, ix, c2);
}
/// <inheritdoc/>
public override Size2 GetHypotheticalKerningInfo<TSource>(ref TSource text, Int32 ix, Int32 c2)
{
var c1 = text[ix];
return GetKerningInfo(c1, c2);
}
/// <inheritdoc/>
public override Size2 GetHypotheticalShapedKerningInfo<TSource>(ref TSource text, Int32 ix, Int32 glyphIndex2, Boolean rtl = false) => Size2.Zero;
/// <inheritdoc/>
public override Boolean ContainsGlyph(Int32 c) =>
facade.GetCharIndex((UInt32)c) > 0;
/// <summary>
/// Ensures that the specified character's associated glyph has been added to the font's texture atlases.
/// </summary>
/// <param name="c">The character for which to ensure that a glyph has been populated.</param>
public void PopulateGlyph(Char c) =>
GetGlyphInfo(c, false, out var info);
/// <summary>
/// Gets the font's family name.
/// </summary>
public String FamilyName { get; }
/// <summary>
/// Gets the font's style name.
/// </summary>
public String StyleName { get; }
/// <summary>
/// Gets the width of the texture atlases used by FreeType2 font faces.
/// </summary>
public Int32 AtlasWidth { get; } = 1024;
/// <summary>
/// Gets the height of the texture atlases used by FreeType2 font faces.
/// </summary>
public Int32 AtlasHeight { get; } = 1024;
/// <summary>
/// Gets the spacing between cells on the atlases used by FreeType2 font faces.
/// </summary>
public Int32 AtlasSpacing { get; } = 4;
/// <summary>
/// Gets the font's size in points.
/// </summary>
public Int32 SizeInPoints { get; }
/// <summary>
/// Gets the font's size in pixels.
/// </summary>
public Int32 SizeInPixels { get; }
/// <summary>
/// Gets a value indicating whether this font has colored strikes.
/// </summary>
public Boolean HasColorStrikes { get; }
/// <summary>
/// Gets a value indicating whether this font has kerning information.
/// </summary>
public Boolean HasKerningInfo { get; }
/// <summary>
/// Gets a value indicating whether this font face is stroked.
/// </summary>
public Boolean IsStroked => stroker != IntPtr.Zero;
/// <inheritdoc/>
public override Boolean SupportsGlyphIndices => true;
/// <inheritdoc/>
public override Boolean SupportsShapedText => true;
/// <inheritdoc/>
public override Int32 Glyphs => glyphInfoCache.Count;
/// <inheritdoc/>
public override Int32 SpaceWidth { get; }
/// <inheritdoc/>
public override Int32 TabWidth { get; }
/// <inheritdoc/>
public override Int32 Ascender { get; }
/// <inheritdoc/>
public override Int32 Descender { get; }
/// <inheritdoc/>
public override Int32 LineSpacing { get; }
/// <inheritdoc/>
public override Char SubstitutionCharacter { get; }
/// <summary>
/// Gets a pointer to the native font object.
/// </summary>
internal IntPtr NativePointer => face;
/// <inheritdoc/>
protected override void Dispose(Boolean disposing)
{
if (Disposed)
return;
if (disposing)
{
SafeDispose.DisposeRef(ref resamplingSurface1);
SafeDispose.DisposeRef(ref resamplingSurface2);
if (stroker != IntPtr.Zero)
{
FT_Stroker_Done(stroker);
stroker = IntPtr.Zero;
}
var err = FT_Done_Face(face);
if (err != FT_Err_Ok)
throw new FreeTypeException(err);
face = IntPtr.Zero;
}
base.Dispose(disposing);
}
/// <summary>
/// Creates a stroker if this font face requires one.
/// </summary>
private static IntPtr CreateStroker(IntPtr face, FreeTypeFontProcessorMetadata metadata)
{
var err = default(FT_Error);
var pstroker = IntPtr.Zero;
if (metadata.StrokeRadius <= 0)
return pstroker;
err = FT_Stroker_New(FreeTypeFontPlugin.Library, (IntPtr)(&pstroker));
if (err != FT_Err_Ok)
throw new FreeTypeException(err);
var lineCapMode = FT_STROKER_LINECAP_BUTT;
switch (metadata.StrokeLineCap)
{
case FreeTypeLineCapMode.Round:
lineCapMode = FT_STROKER_LINECAP_ROUND;
break;
case FreeTypeLineCapMode.Square:
lineCapMode = FT_STROKER_LINECAP_SQUARE;
break;
}
var lineJoinMode = FT_STROKER_LINEJOIN_ROUND;
switch (metadata.StrokeLineJoin)
{
case FreeTypeLineJoinMode.Bevel:
lineJoinMode = FT_STROKER_LINEJOIN_BEVEL;
break;
case FreeTypeLineJoinMode.Miter:
lineJoinMode = FT_STROKER_LINEJOIN_MITER;
break;
case FreeTypeLineJoinMode.MiterFixed:
lineJoinMode = FT_STROKER_LINEJOIN_MITER_FIXED;
break;
}
var fixedRadius = FreeTypeCalc.Int32ToF26Dot6(metadata.StrokeRadius);
var fixedMiterLimit = FreeTypeCalc.Int32ToF26Dot6(metadata.StrokeMiterLimit);
if (Use64BitInterface)
FT_Stroker_Set64(pstroker, fixedRadius, lineCapMode, lineJoinMode, fixedMiterLimit);
else
FT_Stroker_Set32(pstroker, fixedRadius, lineCapMode, lineJoinMode, fixedMiterLimit);
return pstroker;
}
/// <summary>
/// Performs alpha blending between two colors.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Color AlphaBlend(Color src, Color dst, Boolean srgb)
{
if (srgb)
{
src = Color.ConvertSrgbColorToLinear(src);
dst = Color.ConvertSrgbColorToLinear(dst);
}
var srcA = src.A / 255f;
var srcR = src.R / 255f;
var srcG = src.G / 255f;
var srcB = src.B / 255f;
var dstA = dst.A / 255f;
var dstR = dst.R / 255f;
var dstG = dst.G / 255f;
var dstB = dst.B / 255f;
var invSrcA = (1f - srcA);
var outA = srcA + (dstA * invSrcA);
var outR = srcR + (dstR * invSrcA);
var outG = srcG + (dstG * invSrcA);
var outB = srcB + (dstB * invSrcA);
var outColor = new Color(outR, outG, outB, outA);
return srgb ? Color.ConvertLinearColorToSrgb(outColor) : outColor;
}
/// <summary>
/// Ensures that the specified scratch surface exists and has at least the specified size.
/// </summary>
private static void CreateResamplingSurface(UltravioletContext uv, ref Surface2D srf, Int32 w, Int32 h)
{
if (srf == null)
{
var srgb = uv.GetGraphics().Capabilities.SrgbEncodingEnabled;
var opts = srgb ? SurfaceOptions.SrgbColor : SurfaceOptions.LinearColor;
srf?.Dispose();
srf = Surface2D.Create(w, h, opts);
}
srf.Clear(Color.Transparent);
}
/// <summary>
/// Calculates the weights used during a resampling operation.
/// </summary>
private static void CreateResamplingWeights(ref Single[] weights, Int32 srcSize, Int32 dstSize, Single ratio, Single radius)
{
Single TriangleKernel(Single x)
{
if (x < 0f) x = -x;
if (x < 1f) return 1f - x;
return 0f;
};
var scale = ratio;
if (scale < 1.0f)
scale = 1.0f;
var weightCountPerPixel = (Int32)Math.Floor(radius) - (Int32)Math.Ceiling(-radius);
var weightOffset = 0;
var resultSize = dstSize * weightCountPerPixel;
if (weights == null || weights.Length < resultSize)
weights = new Single[resultSize];
for (int i = 0; i < dstSize; i++)
{
var pos = ((i + 0.5f) * ratio) - 0.5f;
var min = (Int32)Math.Ceiling(pos - radius);
var max = min + weightCountPerPixel;
var sum = 0.0f;
for (var j = min; j < max; j++)
{
var weight = TriangleKernel((j - pos) / scale);
sum += weight;
weights[weightOffset + (j - min)] = weight;
}
if (sum > 0)
{
for (var j = 0; j < weightCountPerPixel; j++)
weights[weightOffset + j] /= sum;
}
weightOffset += weightCountPerPixel;
}
}
/// <summary>
/// Blits the specified bitmap onto a texture atlas.
/// </summary>
private void BlitBitmap(ref FT_Bitmap bmp, Int32 adjustX, Int32 adjustY,
Color color, FreeTypeBlendMode blendMode, ref DynamicTextureAtlas.Reservation reservation)
{
var width = (Int32)bmp.width;
if (width == 0)
return;
var height = (Int32)bmp.rows;
if (height == 0)
return;
var resampleRatio = 0f;
var resampleRadius = 0f;
var scaledWidth = width;
var scaledHeight = height;
// Prepare for scaling the glyph if required.
var scaled = (scale != 1f);
if (scaled)
{
// Calculate resampling parameters.
scaledWidth = (Int32)Math.Floor(width * scale);
scaledHeight = (Int32)Math.Floor(height * scale);
resampleRatio = 1f / scale;
resampleRadius = resampleRatio;
if (resampleRadius < 1f)
resampleRadius = 1f;
// Ensure that our scratch surfaces exist with enough space.
CreateResamplingSurface(Ultraviolet, ref resamplingSurface1, width, height);
CreateResamplingSurface(Ultraviolet, ref resamplingSurface2, scaledWidth, height);
// Precalculate pixel weights.
CreateResamplingWeights(ref resamplingWeightsX, width, reservation.Width, resampleRatio, resampleRadius);
CreateResamplingWeights(ref resamplingWeightsY, height, reservation.Height, resampleRatio, resampleRadius);
}
// Blit the glyph to the specified reservation.
switch ((FT_Pixel_Mode)bmp.pixel_mode)
{
case FT_PIXEL_MODE_MONO:
if (scaled)
{
BlitGlyphBitmapMono(resamplingSurface1, 0, 0, ref bmp, width, height, bmp.pitch, color, blendMode, reservation.Atlas.IsFlipped);
BlitResampledX(resamplingSurface1, new Rectangle(0, 0, width, height), resamplingSurface2, new Rectangle(0, 0, scaledWidth, height), resamplingWeightsX);
BlitResampledY(resamplingSurface2, new Rectangle(0, 0, scaledWidth, height), reservation.Atlas.Surface,
new Rectangle(reservation.X + adjustX, reservation.Y + adjustY, scaledWidth, scaledHeight), resamplingWeightsY);
}
else
{
BlitGlyphBitmapMono(reservation.Atlas.Surface, reservation.X + adjustX, reservation.Y + adjustY,
ref bmp, width, height, bmp.pitch, color, blendMode, reservation.Atlas.IsFlipped);
}
break;
case FT_PIXEL_MODE_GRAY:
if (scaled)
{
BlitGlyphBitmapGray(resamplingSurface1, 0, 0, ref bmp, width, height, bmp.pitch, color, blendMode, reservation.Atlas.IsFlipped);
BlitResampledX(resamplingSurface1, new Rectangle(0, 0, width, height), resamplingSurface2, new Rectangle(0, 0, scaledWidth, height), resamplingWeightsX);
BlitResampledY(resamplingSurface2, new Rectangle(0, 0, scaledWidth, height), reservation.Atlas.Surface,
new Rectangle(reservation.X + adjustX, reservation.Y + adjustY, scaledWidth, scaledHeight), resamplingWeightsY);
}
else
{
BlitGlyphBitmapGray(reservation.Atlas.Surface, reservation.X + adjustX, reservation.Y + adjustY,
ref bmp, width, height, bmp.pitch, color, blendMode, reservation.Atlas.IsFlipped);
}
break;
case FT_PIXEL_MODE_BGRA:
if (scaled)
{
BlitGlyphBitmapBgra(resamplingSurface1, 0, 0, ref bmp, width, height, bmp.pitch, blendMode, reservation.Atlas.IsFlipped);
BlitResampledX(resamplingSurface1, new Rectangle(0, 0, width, height), resamplingSurface2, new Rectangle(0, 0, scaledWidth, height), resamplingWeightsX);
BlitResampledY(resamplingSurface2, new Rectangle(0, 0, scaledWidth, height), reservation.Atlas.Surface,
new Rectangle(reservation.X + adjustX, reservation.Y + adjustY, scaledWidth, scaledHeight), resamplingWeightsY);
}
else
{
BlitGlyphBitmapBgra(reservation.Atlas.Surface, reservation.X + adjustX, reservation.Y + adjustY,
ref bmp, width, height, bmp.pitch, blendMode, reservation.Atlas.IsFlipped);
}
break;
default:
throw new NotSupportedException(FreeTypeStrings.PixelFormatNotSupported);
}
reservation.Atlas.Invalidate();
}
/// <summary>
/// Converts the specified index of a string to a UTF-32 codepoint.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private Boolean GetUtf32CodePointFromString(ref StringSegment text, Int32 ix, out UInt32 utf32, out Int32 length)
{
var ixNext = ix + 1;
if (ixNext < text.Length)
{
var c1 = text[ix];
var c2 = text[ixNext];
if (Char.IsSurrogatePair(c1, c2))
{
utf32 = (UInt32)Char.ConvertToUtf32(c1, c2);
length = 2;
return true;
}
}
length = 1;
if (Char.IsSurrogate(text[ix]))
{
utf32 = SubstitutionCharacter;
return false;
}
utf32 = text[ix];
return false;
}
/// <summary>
/// Converts the specified index of a string to a UTF-32 codepoint.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private Boolean GetUtf32CodePointFromString<TSource>(ref TSource text, Int32 ix, out UInt32 utf32, out Int32 length)
where TSource : IStringSource<Char>
{
var ixNext = ix + 1;
if (ixNext < text.Length)
{
var c1 = text[ix];
var c2 = text[ixNext];
if (Char.IsSurrogatePair(c1, c2))
{
utf32 = (UInt32)Char.ConvertToUtf32(c1, c2);
length = 2;
return true;
}
}
length = 1;
if (Char.IsSurrogate(text[ix]))
{
utf32 = SubstitutionCharacter;
return false;
}
utf32 = text[ix];
return false;
}
/// <summary>
/// Blits a mono glyph bitmap to the specified atlas' surface.
/// </summary>
private static void BlitGlyphBitmapMono(Surface2D dstSurface, Int32 dstX, Int32 dstY,
ref FT_Bitmap bmp, Int32 bmpWidth, Int32 bmpHeight, Int32 bmpPitch, Color color, FreeTypeBlendMode blendMode, Boolean flip)
{
var srgb = dstSurface.SrgbEncoded;
for (int y = 0; y < bmpHeight; y++)
{
var pSrcY = flip ? (bmpHeight - 1) - y : y;
var pSrc = (Byte*)bmp.buffer + (pSrcY * bmpPitch);
var pDst = (Color*)dstSurface.Pixels + ((dstY + y) * dstSurface.Width) + dstX;
if (blendMode == FreeTypeBlendMode.Opaque)
{
for (int x = 0; x < bmpWidth; x += 8)
{
var bits = *pSrc++;
for (int b = 0; b < 8; b++)
{
var srcColor = ((bits >> (7 - b)) & 1) == 0 ? Color.Transparent : color;
if (srgb)
srcColor = Color.ConvertLinearColorToSrgb(srcColor);
*pDst++ = srcColor;
}
}
}
else
{
for (int x = 0; x < bmpWidth; x += 8)
{
var bits = *pSrc++;
for (int b = 0; b < 8; b++)
{
var srcColor = ((bits >> (7 - b)) & 1) == 0 ? Color.Transparent : color;
var dstColor = *pDst;
if (srgb)
srcColor = Color.ConvertLinearColorToSrgb(srcColor);
*pDst++ = AlphaBlend(srcColor, dstColor, srgb);
}
}
}
}
}
/// <summary>
/// Blits a grayscale glyph bitmap to the specified atlas' surface.
/// </summary>
private static void BlitGlyphBitmapGray(Surface2D dstSurface, Int32 dstX, Int32 dstY,
ref FT_Bitmap bmp, Int32 bmpWidth, Int32 bmpHeight, Int32 bmpPitch, Color color, FreeTypeBlendMode blendMode, Boolean flip)
{
var srgb = dstSurface.SrgbEncoded;
for (int y = 0; y < bmpHeight; y++)
{
var pSrcY = flip ? (bmpHeight - 1) - y : y;
var pSrc = (Byte*)bmp.buffer + (pSrcY * bmpPitch);
var pDst = (Color*)dstSurface.Pixels + ((dstY + y) * dstSurface.Width) + dstX;
if (blendMode == FreeTypeBlendMode.Opaque)
{
for (int x = 0; x < bmpWidth; x++)
{
var srcColor = color * (*pSrc++ / 255f);
if (srgb)
srcColor = Color.ConvertLinearColorToSrgb(srcColor);
*pDst++ = srcColor;
}
}
else
{
for (int x = 0; x < bmpWidth; x++)
{
var srcColor = color * (*pSrc++ / 255f);
var dstColor = *pDst;
if (srgb)
srcColor = Color.ConvertLinearColorToSrgb(srcColor);
*pDst++ = AlphaBlend(srcColor, dstColor, srgb);
}
}
}
}
/// <summary>
/// Blits a BGRA color glyph bitmap to the specified atlas' surface.
/// </summary>
private static void BlitGlyphBitmapBgra(Surface2D dstSurface, Int32 dstX, Int32 dstY,
ref FT_Bitmap bmp, Int32 bmpWidth, Int32 bmpHeight, Int32 bmpPitch, FreeTypeBlendMode blendMode, Boolean flip)
{
var srgb = dstSurface.SrgbEncoded;
for (int y = 0; y < bmpHeight; y++)
{
var pSrcY = flip ? (bmpHeight - 1) - y : y;
var pSrc = (Color*)((Byte*)bmp.buffer + (pSrcY * bmpPitch));
var pDst = (Color*)dstSurface.Pixels + ((dstY + y) * dstSurface.Width) + dstX;
if (blendMode == FreeTypeBlendMode.Opaque)
{
for (int x = 0; x < bmpWidth; x++)
{
var srcColor = *pSrc++;
var dstColor = new Color(srcColor.B, srcColor.G, srcColor.R, srcColor.A);
*pDst++ = dstColor;
}
}
else
{
for (int x = 0; x < bmpWidth; x++)
{
var srcColor = *pSrc++;
var dstColor = *pDst;
*pDst++ = AlphaBlend(srcColor, dstColor, srgb);
}
}
}
}
/// <summary>
/// Blits from one surface to another surface, performing bilinear resampling along the x-axis.
/// </summary>
private static void BlitResampledX(Surface2D srcSurface, Rectangle srcRect, Surface2D dstSurface, Rectangle dstRect, Single[] weights)
{
var scale = dstRect.Width / (Single)srcRect.Width;
var ratio = 1f / scale;
var radius = ratio;
if (radius < 1f)
radius = 1f;
var weightCount = (Int32)Math.Floor(radius) - (Int32)Math.Ceiling(-radius);
var weightOffset = 0;
for (var y = 0; y < srcRect.Height; y++)
{
weightOffset = 0;
var pSrc = (Color*)((Byte*)srcSurface.Pixels + ((srcRect.Y + y) * srcSurface.Pitch)) + srcRect.X;
var pDst = (Color*)((Byte*)dstSurface.Pixels + ((dstRect.Y + y) * dstSurface.Pitch)) + dstRect.X;
for (var x = 0; x < dstRect.Width; x++)
{
var pos = ((x + 0.5f) * ratio) - 0.5f;
var min = (Int32)Math.Ceiling(pos - radius);
var totalR = 0f;
var totalG = 0f;
var totalB = 0f;
var totalA = 0f;
for (int i = 0; i < weightCount; i++)
{
var pixOffset = min + i;
if (pixOffset < 0)
pixOffset = 0;
else if (pixOffset >= srcRect.Width)
pixOffset = srcRect.Width - 1;
var pixWeight = weights[weightOffset + i];
var pixColor = pSrc[srcRect.X + pixOffset];
var weight = weights[weightOffset + i];
totalR += weight * pixColor.R;
totalG += weight * pixColor.G;
totalB += weight * pixColor.B;
totalA += weight * pixColor.A;
}
*pDst++ = new Color((Byte)totalR, (Byte)totalG, (Byte)totalB, (Byte)totalA);
weightOffset += weightCount;
}
}
}
/// <summary>
/// Blits from one surface to another surface, performing bilinear resampling along the y-axis.
/// </summary>
private static void BlitResampledY(Surface2D srcSurface, Rectangle srcRect, Surface2D dstSurface, Rectangle dstRect, Single[] weights)
{
var scale = dstRect.Height / (Single)srcRect.Height;
var ratio = 1f / scale;
var radius = ratio;
if (radius < 1f)
radius = 1f;
var weightCount = (Int32)Math.Floor(radius) - (Int32)Math.Ceiling(-radius);
var weightOffset = 0;
var bytesPerPixel = sizeof(Color);
for (var x = 0; x < dstRect.Width; x++)
{
var pSrc = (Byte*)srcSurface.Pixels + (srcRect.Y * srcSurface.Pitch) + ((srcRect.X + x) * bytesPerPixel);
var pDst = (Byte*)dstSurface.Pixels + (dstRect.Y * dstSurface.Pitch) + ((dstRect.X + x) * bytesPerPixel);
weightOffset = 0;
for (var y = 0; y < dstRect.Height; y++)
{
var pos = ((y + 0.5f) * ratio) - 0.5f;
var min = (Int32)Math.Ceiling(pos - radius);
var totalR = 0f;
var totalG = 0f;
var totalB = 0f;
var totalA = 0f;
var pPix = pSrc + (min * srcSurface.Pitch);
for (int i = 0; i < weightCount; i++)
{
var pixOffset = min + i;
if (pixOffset < 0)
pixOffset = 0;
else if (pixOffset >= srcRect.Height)
pixOffset = srcRect.Height - 1;
var pixWeight = weights[weightOffset + i];
var pixColor = *(Color*)(pSrc + (pixOffset * srcSurface.Pitch));
var weight = weights[weightOffset + i];
totalR += weight * pixColor.R;
totalG += weight * pixColor.G;
totalB += weight * pixColor.B;
totalA += weight * pixColor.A;
}
*(Color*)pDst = new Color((Byte)totalR, (Byte)totalG, (Byte)totalB, (Byte)totalA);
pDst += dstSurface.Pitch;
weightOffset += weightCount;
}
}
}
/// <summary>
/// Gets the font face's metadata for the specified code point or glyph index.
/// </summary>
private Boolean GetGlyphInfo(UInt32 glyphIndexOrCodePoint, Boolean isGlyphIndex, out FreeTypeGlyphInfo info)
{
var glyphIndex = isGlyphIndex ? glyphIndexOrCodePoint : facade.GetCharIndex(glyphIndexOrCodePoint);
if (glyphIndex == 0)
{
if (!isGlyphIndex)
{
var cu16 = (glyphIndexOrCodePoint <= Char.MaxValue) ? (Char?)glyphIndexOrCodePoint : null;
if (cu16 != SubstitutionCharacter)
return GetGlyphInfo(SubstitutionCharacter, false, out info);
}
info = default(FreeTypeGlyphInfo);
return false;
}
else
{
if (glyphInfoCache.TryGetValue(glyphIndex, out var cached))
{
info = cached;
}
else
{
LoadGlyphTexture(glyphIndex, out info);
glyphInfoCache[glyphIndex] = info;
}
}
return true;
}
/// <summary>
/// Loads the texture data for the specified glyph.
/// </summary>
private void LoadGlyphTexture(UInt32 glyphIndex, out FreeTypeGlyphInfo info)
{
var err = default(FT_Error);
// Load the glyph into the face's glyph slot.
var flags = IsStroked ? FT_LOAD_NO_BITMAP : FT_LOAD_COLOR;
err = FT_Load_Glyph(face, glyphIndex, flags);
if (err != FT_Err_Ok)
throw new FreeTypeException(err);
var glyphOffsetX = 0;
var glyphOffsetY = 0;
var glyphAscent = 0;
var glyphAdvance = facade.GlyphMetricHorizontalAdvance + hAdvanceAdjustment;
var reservation = default(DynamicTextureAtlas.Reservation);
var reservationFound = false;
// Stroke the glyph.
StrokeGlyph(out var strokeGlyph, out var strokeBmp,
out var strokeOffsetX, out var strokeOffsetY);
// Render the glyph.
err = FT_Render_Glyph(facade.GlyphSlot, FT_RENDER_MODE_NORMAL);
if (err != FT_Err_Ok)
throw new FreeTypeException(err);
var glyphBmp = facade.GlyphBitmap;
if (glyphBmp.rows > 0 && glyphBmp.width > 0)
{
var glyphBmpHeightScaled = (Int32)glyphBmp.rows;
var glyphAdjustX = 0;
var glyphAdjustY = 0;
var reservationWidth = 0;
var reservationHeight = 0;
if (strokeGlyph == IntPtr.Zero)
{
reservationWidth = (Int32)glyphBmp.width;
reservationHeight = (Int32)glyphBmp.rows;
glyphAscent = facade.GlyphBitmapTop;
}
else
{
reservationWidth = Math.Max((Int32)strokeBmp.width, (Int32)glyphBmp.width);
reservationHeight = Math.Max((Int32)strokeBmp.rows, (Int32)glyphBmp.rows);
glyphAscent = Math.Max(facade.GlyphBitmapTop, strokeOffsetY);
glyphAdjustX = -(strokeOffsetX - facade.GlyphBitmapLeft);
glyphAdjustY = +(strokeOffsetY - facade.GlyphBitmapTop);
}
// Apply scaling to metrics.
if (scale != 1f)
{
glyphBmpHeightScaled = (Int32)Math.Floor(glyphBmpHeightScaled * scale);
glyphAdvance = (Int32)Math.Floor(glyphAdvance * scale);
glyphAscent = (Int32)Math.Floor(glyphAscent * scale);
reservationWidth = (Int32)Math.Floor(reservationWidth * scale);
reservationHeight = (Int32)Math.Floor(reservationHeight * scale);
}
// Attempt to reserve space on one of the font's existing atlases.
if (reservationWidth > 0 && reservationHeight > 0)
{
foreach (var atlas in atlases)
{
if (atlas.TryReserveCell(reservationWidth, reservationHeight, out reservation))
{
reservationFound = true;
break;
}
}
// Attempt to create a new atlas if we weren't able to make a reservation.
if (!reservationFound)
{
var srgb = Ultraviolet.GetGraphics().Capabilities.SrgbEncodingEnabled;
var opts = TextureOptions.ImmutableStorage | (srgb ? TextureOptions.SrgbColor : TextureOptions.LinearColor);
var atlas = DynamicTextureAtlas.Create(AtlasWidth, AtlasHeight, AtlasSpacing, opts);
atlas.Surface.Clear(Color.Transparent);
atlases.Add(atlas);
if (!atlas.TryReserveCell(reservationWidth, reservationHeight, out reservation))
throw new InvalidOperationException(FreeTypeStrings.GlyphTooBigForAtlas.Format());
}
// If we're using flipped textures, we need to modify our y-adjust...
if (reservation.Atlas.IsFlipped)
glyphAdjustY = (reservationHeight - glyphBmpHeightScaled) - glyphAdjustY;
// Update the atlas surface.
var blendMode = FreeTypeBlendMode.Opaque;
if (strokeGlyph != IntPtr.Zero)
{
BlitBitmap(ref strokeBmp, 0, 0, Color.Black, blendMode, ref reservation);
blendMode = FreeTypeBlendMode.Blend;
FT_Done_Glyph(strokeGlyph);
}
BlitBitmap(ref glyphBmp, glyphAdjustX, glyphAdjustY, Color.White, blendMode, ref reservation);
}
}
// Calculate the glyph's metrics and apply scaling.
var glyphWidth = facade.GlyphMetricWidth + glyphWidthAdjustment;
var glyphHeight = facade.GlyphMetricHeight + glyphHeightAdjustment;
if (scale != 1f)
{
glyphWidth = (Int32)Math.Floor(glyphWidth * scale);
glyphHeight = (Int32)Math.Floor(glyphHeight * scale);
glyphOffsetX = (Int32)Math.Floor(facade.GlyphBitmapLeft * scale) + offsetXAdjustment;
glyphOffsetY = (Ascender - glyphAscent) + offsetYAdjustment;
}
else
{
glyphOffsetX = facade.GlyphBitmapLeft + offsetXAdjustment;
glyphOffsetY = (Ascender - glyphAscent) + offsetYAdjustment;
}
// Create the glyph info structure for the glyph cache.
info = new FreeTypeGlyphInfo
{
Advance = glyphAdvance,
Width = glyphWidth,
Height = glyphHeight,
OffsetX = glyphOffsetX,
OffsetY = glyphOffsetY,
Texture = reservation.Atlas,
TextureRegion = reservation.Atlas == null ? Rectangle.Empty : reservation.Atlas.IsFlipped ?
new Rectangle(reservation.X, reservation.Atlas.Height - (reservation.Y + reservation.Height), reservation.Width, reservation.Height) :
new Rectangle(reservation.X, reservation.Y, reservation.Width, reservation.Height),
};
}
/// <summary>
/// Strokes the currently loaded glyph, if a stroker exists.
/// </summary>
private void StrokeGlyph(out IntPtr glyph, out FT_Bitmap strokeBmp, out Int32 strokeOffsetX, out Int32 strokeOffsetY)
{
var err = default(FT_Error);
var strokeGlyph = IntPtr.Zero;
if (stroker == IntPtr.Zero)
{
glyph = IntPtr.Zero;
strokeBmp = default(FT_Bitmap);
strokeOffsetX = 0;
strokeOffsetY = 0;
return;
}
err = FT_Get_Glyph(facade.GlyphSlot, (IntPtr)(&strokeGlyph));
if (err != FT_Err_Ok)
throw new FreeTypeException(err);
err = FT_Glyph_StrokeBorder((IntPtr)(&strokeGlyph), stroker, false, true);
if (err != FT_Err_Ok)
{
FT_Done_Glyph(strokeGlyph);
throw new FreeTypeException(err);
}
err = FT_Glyph_To_Bitmap((IntPtr)(&strokeGlyph), FT_RENDER_MODE_NORMAL, IntPtr.Zero, true);
if (err != FT_Err_Ok)
{
FT_Done_Glyph(strokeGlyph);
throw new FreeTypeException(err);
}
if (Use64BitInterface)
{
var bmp64 = (FT_BitmapGlyphRec64*)strokeGlyph;
strokeBmp = bmp64->bitmap;
strokeOffsetX = bmp64->left;
strokeOffsetY = bmp64->top;
}
else
{
var bmp32 = (FT_BitmapGlyphRec32*)strokeGlyph;
strokeBmp = bmp32->bitmap;
strokeOffsetX = bmp32->left;
strokeOffsetY = bmp32->top;
}
glyph = strokeGlyph;
}
// The FreeType2 face which this instance represents.
private readonly FT_FaceRecFacade facade;
private IntPtr face;
private IntPtr stroker;
// Metric adjustments.
private readonly Single scale;
private readonly Int32 totalDesignHeight;
private readonly Int32 offsetXAdjustment;
private readonly Int32 offsetYAdjustment;
private readonly Int32 hAdvanceAdjustment;
private readonly Int32 vAdvanceAdjustment;
private readonly Int32 glyphWidthAdjustment;
private readonly Int32 glyphHeightAdjustment;
// Surfaces and buffers used for resizing glyphs.
private Single[] resamplingWeightsX;
private Single[] resamplingWeightsY;
private Surface2D resamplingSurface1;
private Surface2D resamplingSurface2;
// Cache of atlases used to store glyph images.
private readonly List<DynamicTextureAtlas> atlases =
new List<DynamicTextureAtlas>();
// Cache of metadata for loaded glyphs.
private readonly Dictionary<UInt32, FreeTypeGlyphInfo> glyphInfoCache =
new Dictionary<UInt32, FreeTypeGlyphInfo>();
}
}
|
using System;
using System.Reflection;
namespace Sigil.NonGeneric
{
public partial class Emit
{
/// <summary>
/// <para>Calls the given method virtually. Pops its arguments in reverse order (left-most deepest in the stack), and pushes the return value if it is non-void.</para>
/// <para>The `this` reference should appear before any arguments (deepest in the stack).</para>
/// <para>The method invoked at runtime is determined by the type of the `this` reference.</para>
/// <para>If the method invoked shouldn't vary (or if the method is static), use Call instead.</para>
/// </summary>
public Emit CallVirtual(MethodInfo method, Type constrained = null, Type[] arglist = null)
{
InnerEmit.CallVirtual(method, constrained, arglist);
return this;
}
}
}
|
#region Copyright Notice
/*
* ConnectSdk.Windows
* ILauncher.cs
*
* Copyright (c) 2015, https://github.com/sdaemon
* Created by Sorin S. Serban on 22-4-2015,
*
* 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.
*/
#endregion
using System;
using ConnectSdk.Windows.Core;
using ConnectSdk.Windows.Service.Capability.Listeners;
using ConnectSdk.Windows.Service.Command;
using ConnectSdk.Windows.Service.Sessions;
namespace ConnectSdk.Windows.Service.Capability
{
public interface ILauncher : ICapabilityMethod
{
ILauncher GetLauncher();
CapabilityPriorityLevel GetLauncherCapabilityLevel();
void LaunchAppWithInfo(AppInfo appInfo, ResponseListener listener);
void LaunchAppWithInfo(AppInfo appInfo, Object ps, ResponseListener listener);
void LaunchApp(string appId, ResponseListener listener);
void CloseApp(LaunchSession launchSession, ResponseListener listener);
void GetAppList(ResponseListener listener);
void GetRunningApp(ResponseListener listener);
IServiceSubscription SubscribeRunningApp(ResponseListener listener);
void GetAppState(LaunchSession launchSession, ResponseListener listener);
IServiceSubscription SubscribeAppState(LaunchSession launchSession, ResponseListener listener);
void LaunchBrowser(string url, ResponseListener listener);
void LaunchYouTube(string contentId, ResponseListener listener);
void LaunchNetflix(string contentId, ResponseListener listener);
void LaunchHulu(string contentId, ResponseListener listener);
void LaunchAppStore(string appId, ResponseListener listener);
}
} |
using System;
using System.Collections.Generic;
using System.Reflection;
using HotChocolate.Types;
using HotChocolate.Types.Descriptors;
using Snapshooter.Xunit;
using Xunit;
namespace HotChocolate.Data.Sorting
{
public class SortAttributeTests
{
[Fact]
public void Create_Schema_With_SortType()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType<Query1>()
.AddSorting()
.Create();
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void Create_Schema_With_SortType_With_Fluent_API()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType<Query2>()
.AddSorting()
.Create();
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void Create_Schema_With_SortType_With_Fluent_API_Ctor_Param()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType<Query3>()
.AddSorting()
.Create();
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void Create_Schema_With_SortAttributes()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType<Query4>()
.AddSorting()
.Create();
// assert
schema.ToString().MatchSnapshot();
}
public class Query1
{
[UseSorting]
public IEnumerable<Foo> Foos { get; } = new[]
{
new Foo {Bar = "aa", Baz = 1, Qux = 1},
new Foo {Bar = "ba", Baz = 1},
new Foo {Bar = "ca", Baz = 2},
new Foo {Bar = "ab", Baz = 2},
new Foo {Bar = "ac", Baz = 2},
new Foo {Bar = "ad", Baz = 2},
new Foo {Bar = null!, Baz = 0}
};
}
public class Query2
{
[UseSorting(Type = typeof(FooSortType))]
public IEnumerable<Foo> Foos { get; } = new[]
{
new Foo {Bar = "aa", Baz = 1, Qux = 1},
new Foo {Bar = "ba", Baz = 1},
new Foo {Bar = "ca", Baz = 2},
new Foo {Bar = "ab", Baz = 2},
new Foo {Bar = "ac", Baz = 2},
new Foo {Bar = "ad", Baz = 2},
new Foo {Bar = null!, Baz = 0}
};
}
public class Query3
{
[UseSorting(typeof(FooSortType))]
public IEnumerable<Foo> Foos { get; } = new[]
{
new Foo {Bar = "aa", Baz = 1, Qux = 1},
new Foo {Bar = "ba", Baz = 1},
new Foo {Bar = "ca", Baz = 2},
new Foo {Bar = "ab", Baz = 2},
new Foo {Bar = "ac", Baz = 2},
new Foo {Bar = "ad", Baz = 2},
new Foo {Bar = null!, Baz = 0}
};
}
public class Query4
{
[UseSorting]
public IEnumerable<Bar> Bars { get; } = new[]
{
new Bar { Baz = 1 },
new Bar { Baz = 2 },
new Bar { Baz = 2 },
new Bar { Baz = 2 },
new Bar { Baz = 2 },
};
}
public class FooSortType : SortInputType<Foo>
{
protected override void Configure(ISortInputTypeDescriptor<Foo> descriptor)
{
descriptor.BindFieldsExplicitly().Field(m => m.Bar);
}
}
public class Foo
{
public string Bar { get; set; } = default!;
[GraphQLType(typeof(NonNullType<IntType>))]
public long Baz { get; set; }
[GraphQLType(typeof(IntType))] public int? Qux { get; set; }
}
[SortTest]
public class Bar
{
public long Baz { get; set; }
[IgnoreSortField]
public int? ShouldNotBeVisible { get; set; }
}
public class SortTestAttribute : SortInputTypeDescriptorAttribute
{
public override void OnConfigure(
IDescriptorContext context,
ISortInputTypeDescriptor descriptor,
Type type)
{
descriptor.Name("ItWorks");
}
}
public class IgnoreSortFieldAttribute : SortFieldDescriptorAttribute
{
public override void OnConfigure(
IDescriptorContext context,
ISortFieldDescriptor descriptor,
MemberInfo member)
{
descriptor.Ignore();
}
}
}
}
|
using System.Collections.Generic;
using XtraUpload.Domain;
namespace XtraUpload.WebApi
{
internal class DeleteFolderResultDto
{
public IEnumerable<FolderItem> Folders { get; set; }
public IEnumerable<FileItemHeaderDto> Files { get; set; }
}
}
|
using FubuMVC.Core.Registration;
namespace FubuMVC.Core.Security.Authorization
{
public class SecurityServicesRegistry : ServiceRegistry
{
public SecurityServicesRegistry()
{
SetServiceIfNone<IAuthorizationFailureHandler, DefaultAuthorizationFailureHandler>();
SetServiceIfNone<ISecurityContext, WebSecurityContext>();
SetServiceIfNone<IAuthenticationContext, WebAuthenticationContext>();
SetServiceIfNone<IAuthorizationPreviewService, AuthorizationPreviewService>();
SetServiceIfNone<IAuthorizationPolicyExecutor, AuthorizationPolicyExecutor>();
SetServiceIfNone<IChainAuthorizor, ChainAuthorizor>();
}
}
} |
namespace BladesOfSteelCP.Data;
public enum EnumFirstStep
{
ThrowAwayAllCards = 0,
PlayAttack = 1,
PlayDefense = 2
} |
using Xunit;
using static MySQLCLRFunctions.StringTransform;
namespace MySQLCLRFunctions.Tests
{
public class StringTransformTests
{
[Fact]
public void ReplaceMatchXTest()
{
const string input = "ThisIsIt";
const string validoutput = "Th!sIsI!";
var output = ReplaceMatchX(input, "[it]", "!");
Assert.Equal(expected: validoutput, output);
}
[Fact]
public void ReplaceRecursiveSTest()
{
const string input = "This is a test of the emergency ";
const string validoutput = "This is a test of the emergency ";
var output = ReplaceRecursiveS(input, " ", " ");
Assert.Equal(expected: validoutput, output);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace DD4T.Examples.Helpers
{
public static class ImageHelper
{
public static string ResizeToWidth(this string url, int width)
{
return ResizeToDimension(url, width, "w");
}
public static string ResizeToHeight(this string url, int height)
{
return ResizeToDimension(url, height, "h");
}
private static string ResizeToDimension(string url, int val, string dimension)
{
Regex re = new Regex(@"(\.[a-zA-Z]+$)");
if (re.IsMatch(url))
{
string ext = re.Match(url).Groups[1].ToString();
return re.Replace(url, "_" + dimension + Convert.ToString(val) + ext);
}
return url;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace RA.Models.Json
{
public class Place
{
public Place()
{
Type = "ceterms:Place";
ContactPoint = new List<Json.ContactPoint>();
}
[JsonProperty( "@type" )]
public string Type { get; set; }
[JsonProperty( "ceterms:geoURI" )]
public string GeoURI { get; set; }
[JsonProperty( PropertyName = "ceterms:name" )]
public string Name { get; set; }
[JsonProperty( PropertyName = "ceterms:description" )]
public string Description { get; set; }
[JsonProperty( "ceterms:streetAddress" )]
public string StreetAddress { get; set; }
[JsonProperty( "ceterms:postOfficeBoxNumber" )]
public string PostOfficeBoxNumber { get; set; }
[JsonProperty( "ceterms:addressLocality" )]
public string City { get; set; }
[JsonProperty( "ceterms:addressRegion" )]
public string AddressRegion { get; set; }
[JsonProperty( "ceterms:postalCode" )]
public string PostalCode { get; set; }
[JsonProperty( "ceterms:addressCountry" )]
public string Country { get; set; }
[JsonProperty( PropertyName = "ceterms:latitude" )]
public double Latitude { get; set; }
[JsonProperty( PropertyName = "ceterms:longitude" )]
public double Longitude { get; set; }
[JsonProperty( "ceterms:targetContactPoint" )]
public List<ContactPoint> ContactPoint { get; set; }
}
}
|
using Core.Base;
using MailKit.Net.Smtp;
using Microsoft.Extensions.Options;
using MimeKit;
using MimeKit.Text;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Core.Mail
{
public class PostaciKit: IEmailSender
{
private readonly EpostaHesapBilgileri postaHesabi;
public PostaciKit(IOptions<EpostaHesapBilgileri> postaHesabi)
{
this.postaHesabi = postaHesabi.Value;
}
public async Task SendEmailAsync(string aliciEposta, string konu, string mesaj)
{
var emailMessage = new MimeMessage();
string[] adresler = aliciEposta.Split(';');
if (adresler.Length == 0)
throw new ArgumentException("Göndermek istediğiniz eposta adresi yok!");
else
{
foreach (string adres in adresler)
{
emailMessage.To.Add(new MailboxAddress("", adres));
}
}
emailMessage.From.Add(new MailboxAddress("bilgi@drmturhan.com"));
emailMessage.Subject = konu;
emailMessage.Body = new TextPart(TextFormat.Html) { Text = mesaj };
await Task.Run(() =>
{
try
{
using (var client = new SmtpClient())
{
client.Connect("outlook.office365.com", 587, MailKit.Security.SecureSocketOptions.StartTls);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
// Note: only needed if the SMTP server requires authentication
client.Authenticate("bilgi@drmturhan.com", "!9Kasim2001gozde");
client.Send(emailMessage);
client.Disconnect(true);
}
}
catch (Exception hata)
{
}
});
}
}
}
|
////////PROVISIONAL IMPLEMENTATION////////
////////PROVISIONAL IMPLEMENTATION////////
////////PROVISIONAL IMPLEMENTATION////////
namespace System.IO
{
public abstract class TextReader : IDisposable
{
protected TextReader()
{
}
public virtual void Close()
{
this.Dispose(true);
}
public void Dispose()
{
this.Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
}
public virtual int Peek()
{
return -1;
}
public virtual int Read()
{
return -1;
}
public virtual int Read(char[] buffer, int index, int count)
{
throw new NotImplementedException();
}
public virtual int ReadBlock(char[] buffer, int index, int count)
{
throw new NotImplementedException();
}
public virtual string ReadLine()
{
throw new NotImplementedException();
}
public virtual string ReadToEnd()
{
throw new NotImplementedException();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace office365.PORTAL.Core
{
public class PORTALUserObjectList
{
public string odatacontext { get; set; }
public PORTALUserObject[] Value { get; set; }
}
}
|
namespace Cmsql.Query
{
public interface ICmsqlQueryResult
{
}
}
|
namespace Gw2Sharp.WebApi.V2.Models
{
/// <summary>
/// Represents a upgrade component item.
/// </summary>
public class ItemUpgradeComponent : Item
{
/// <summary>
/// The upgrade component details.
/// </summary>
public ItemUpgradeComponentDetails Details { get; set; } = new ItemUpgradeComponentDetails();
}
}
|
using System;
class C
{
public static int Main ()
{
if (new C ().Test () != 6)
return 1;
return 0;
}
public delegate void Cmd ();
public delegate int Cmd2 ();
int Test ()
{
int r = Foo2 (delegate () {
int x = 4;
Foo (delegate () {
int y = 6;
Foo (delegate () {
x = y;
});
});
return x;
});
Console.WriteLine (r);
return r;
}
int Foo2 (Cmd2 cmd)
{
return cmd ();
}
void Foo (Cmd cmd)
{
cmd ();
}
} |
using System;
using System.Threading;
using ZedSharp.Utils;
namespace ZedSharp.RateLimit
{
internal class FixedTokenBucket
{
private readonly SemaphoreSlim _sem = new SemaphoreSlim(1, 1);
private readonly int _capacity;
private readonly int _interval;
private long _nextRefillTime;
private int _tokens;
public FixedTokenBucket(int capacity, int interval)
{
_capacity = capacity;
_interval = interval;
}
public bool ShouldThrottle(out TimeSpan waitTime, out bool newPeriod)
{
return ShouldThrottle(1, false, out waitTime, out newPeriod);
}
public bool ShouldThrottle(int n, bool force, out TimeSpan waitTime, out bool newPeriod)
{
using (_sem.Run())
{
var currentTime = DateTime.UtcNow.ToUnixTimeMilliseconds();
newPeriod = UpdateTokens(currentTime);
if (_tokens < n && !force)
{
var timeToIntervalEnd = _nextRefillTime - currentTime;
if (timeToIntervalEnd >= 0)
{
waitTime = TimeSpan.FromMilliseconds(timeToIntervalEnd);
return true;
}
}
_tokens -= n;
waitTime = TimeSpan.Zero;
return false;
}
}
public bool UpdateTokens(long currentTime)
{
if (currentTime < _nextRefillTime)
{
return false;
}
_tokens = _capacity;
_nextRefillTime = DateTime.UtcNow.ToUnixTimeMilliseconds() + _interval;
return true;
}
public int CurrentTokenCount
{
get
{
using (_sem.Run())
{
return _tokens;
}
}
}
public long CurrentIntervalStart
{
get
{
using (_sem.Run())
{
return _nextRefillTime - _interval;
}
}
}
}
}
|
using DigitalRune.Game.UI;
using DigitalRune.Game.UI.Controls;
using DigitalRune.Game.UI.Rendering;
using DigitalRune.Mathematics.Algebra;
namespace Samples.Game.UI
{
// A UIScreen which displays a Window. The Window contains an Image control.
class NormalUIScreen : UIScreen
{
private readonly Window _window;
public Image Image { get; private set; }
public NormalUIScreen(IUIRenderer renderer)
: base("Normal", renderer)
{
Image = new Image
{
Width = 800,
Height = 450,
};
_window = new Window
{
X = 100,
Y = 50,
Title = "3D Scene (Click scene to control camera. Press <Esc> to leave scene.)",
CanResize = true,
CloseButtonStyle = null, // Hide close button.
Content = new ScrollViewer
{
HorizontalAlignment = HorizontalAlignment.Stretch,
VerticalAlignment = VerticalAlignment.Stretch,
Content = Image
},
};
_window.Show(this);
}
protected override void OnLoad()
{
base.OnLoad();
// The window is resizable. Limit the max size.
// Measure() computes the DesiredWidth and DesiredHeight.
_window.Measure(new Vector2F(float.PositiveInfinity));
_window.MaxWidth = _window.DesiredWidth;
_window.MaxHeight = _window.DesiredHeight;
}
}
}
|
using System.Drawing;
namespace WallStreet.Models
{
public class User
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public int AccountId { get; set; }
public decimal Money { get; set; }
public int StockCapacity { get; set; }
public Bitmap ProfilePicture { get; set; }
public User()
{
}
public User(string firstName, string lastName, string email, int accountId)
{
this.FirstName = firstName;
this.LastName = lastName;
this.Email = email;
this.AccountId = accountId;
this.Money = 10000;
this.StockCapacity = 100;
}
}
}
|
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web.Mvc;
namespace Szl.MvcDemo
{
public static class Extensions
{
public static IDictionary<string, object> ToSimpleDictionary(this NameValueCollection nameValueCollection)
{
var simpleDictionary = new Dictionary<string, object>();
nameValueCollection.CopyTo(simpleDictionary);
return simpleDictionary;
}
}
} |
using System.Collections.Generic;
namespace EncoreTickets.SDK.Payment.Models.RequestModels
{
public class UpdateOrderRequest
{
public Address BillingAddress { get; set; }
public Shopper Shopper { get; set; }
public List<OrderItem> Items { get; set; }
public RiskData RiskData { get; set; }
}
}
|
// Copyright (c) MudBlazor 2021
// MudBlazor licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.JSInterop;
namespace MudBlazor
{
public interface IScrollListenerFactory
{
IScrollListener Create(string selector);
}
public class ScrollListenerFactory : IScrollListenerFactory
{
private readonly IServiceProvider _provider;
public ScrollListenerFactory(IServiceProvider provider)
{
_provider = provider;
}
public IScrollListener Create(string selector) =>
new ScrollListener(selector, _provider.GetRequiredService<IJSRuntime>());
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AniWrap
{
public class SolvedCaptcha
{
public string ChallengeField { get; private set; }
public string ResponseField { get; private set; }
public SolvedCaptcha(string challenge, string response)
{
this.ChallengeField = challenge;
this.ResponseField = response;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Crunch.NET.Request.Type
{
public interface IRequestTypeConverter
{
bool CanConvert(string requestType);
Request Convert(string requestType);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
ConsoleColor[] Colors =
{
ConsoleColor.DarkBlue,
ConsoleColor.DarkGreen,
ConsoleColor.DarkCyan,
ConsoleColor.DarkRed,
ConsoleColor.DarkMagenta,
ConsoleColor.DarkYellow,
ConsoleColor.Blue,
ConsoleColor.Red,
ConsoleColor.Magenta,
};
try
{
Console.CursorVisible = false;
Random random = new Random();
while (true)
{
NewBoard:
Console.Clear();
int?[,] board = new int?[4, 4];
int score = 0;
while (true)
{
// add a 2 or 4 randomly to the board
bool IsNull((int X, int Y) point) => board[point.X, point.Y] is null;
int nullCount = BoardValues(board).Count(IsNull);
if (nullCount == 0)
{
goto GameOver;
}
int index = random.Next(0, nullCount);
var (x, y) = BoardValues(board).Where(IsNull).ElementAt(index);
board[x, y] = random.Next(10) < 9 ? 2 : 4;
score += 2;
// make sure there are still valid moves left
if (!TryUpdate((int?[,])board.Clone(), ref score, Direction.Up) &&
!TryUpdate((int?[,])board.Clone(), ref score, Direction.Down) &&
!TryUpdate((int?[,])board.Clone(), ref score, Direction.Left) &&
!TryUpdate((int?[,])board.Clone(), ref score, Direction.Right))
{
goto GameOver;
}
Render(board, score);
Direction direction;
GetDirection:
switch (Console.ReadKey(true).Key)
{
case ConsoleKey.UpArrow: direction = Direction.Up; break;
case ConsoleKey.DownArrow: direction = Direction.Down; break;
case ConsoleKey.LeftArrow: direction = Direction.Left; break;
case ConsoleKey.RightArrow: direction = Direction.Right; break;
case ConsoleKey.End: goto NewBoard;
case ConsoleKey.Escape: goto Close;
default: goto GetDirection;
}
if (!TryUpdate(board, ref score, direction))
{
goto GetDirection;
}
}
GameOver:
Render(board, score);
Console.WriteLine($"Game Over...");
Console.WriteLine();
Console.WriteLine("Play Again [enter], or quit [escape]?");
GetInput:
switch (Console.ReadKey(true).Key)
{
case ConsoleKey.Enter: goto NewBoard;
case ConsoleKey.Escape: goto Close;
default: goto GetInput;
}
}
Close:
Console.Clear();
Console.Write("2048 was closed.");
}
finally
{
Console.CursorVisible = true;
}
bool TryUpdate(int?[,] board, ref int score, Direction direction)
{
(int X, int Y) Adjacent(int x, int y) =>
direction switch
{
Direction.Up => (x + 1, y),
Direction.Down => (x - 1, y),
Direction.Left => (x, y - 1),
Direction.Right => (x, y + 1),
_ => throw new NotImplementedException(),
};
(int X, int Y) Map(int x, int y) =>
direction switch
{
Direction.Up => (board.GetLength(0) - x - 1, y),
Direction.Down => (x, y),
Direction.Left => (x, y),
Direction.Right => (x, board.GetLength(1) - y - 1),
_ => throw new NotImplementedException(),
};
bool[,] locked = new bool[board.GetLength(0), board.GetLength(1)];
bool update = false;
for (int i = 0; i < board.GetLength(0); i++)
{
for (int j = 0; j < board.GetLength(1); j++)
{
var (tempi, tempj) = Map(i, j);
if (board[tempi, tempj] is null)
{
continue;
}
KeepChecking:
var (adji, adjj) = Adjacent(tempi, tempj);
if (adji < 0 || adji >= board.GetLength(0) ||
adjj < 0 || adjj >= board.GetLength(1) ||
locked[adji, adjj])
{
continue;
}
else if (board[adji, adjj] is null)
{
board[adji, adjj] = board[tempi, tempj];
board[tempi, tempj] = null;
update = true;
tempi = adji;
tempj = adjj;
goto KeepChecking;
}
else if (board[adji, adjj] == board[tempi, tempj])
{
board[adji, adjj] += board[tempi, tempj];
score += board[adji, adjj].Value;
board[tempi, tempj] = null;
update = true;
locked[adji, adjj] = true;
}
}
}
return update;
}
IEnumerable<(int, int)> BoardValues(int?[,] board)
{
for (int i = board.GetLength(0) - 1; i >= 0; i--)
{
for (int j = 0; j < board.GetLength(1); j++)
{
yield return (i, j);
}
}
}
ConsoleColor GetColor(int? value) =>
value is null
? ConsoleColor.DarkGray
: Colors[(value.Value / 2 - 1) % Colors.Length];
void Render(int?[,] board, int score)
{
int horizontal = board.GetLength(0) * 8;
string horizontalBar = new string('═', horizontal);
string horizontalSpace = new string(' ', horizontal);
Console.SetCursorPosition(0, 0);
Console.WriteLine("2048");
Console.WriteLine();
Console.WriteLine($"╔{horizontalBar}╗");
Console.WriteLine($"║{horizontalSpace}║");
for (int i = board.GetLength(1) - 1; i >= 0; i--)
{
Console.Write("║");
for (int j = 0; j < board.GetLength(0); j++)
{
Console.Write(" ");
ConsoleColor background = Console.BackgroundColor;
Console.BackgroundColor = GetColor(board[i, j]);
Console.Write(string.Format("{0,4}", board[i, j]));
Console.BackgroundColor = background;
Console.Write(" ");
}
Console.WriteLine("║");
Console.WriteLine($"║{horizontalSpace}║");
}
Console.WriteLine($"╚{horizontalBar}╝");
Console.WriteLine($"Score: {score}");
}
public enum Direction
{
Up = 1,
Down = 2,
Left = 3,
Right = 4,
}
|
namespace TeamSpark.AzureDay.WebSite.Data.Enum
{
public enum RoomType
{
LectureRoom = 1001,
WorkshopRoom = 2001,
CoffeeRoom = 21001
}
}
|
// Copyright (c) 2015-2017, Saritasa. All rights reserved.
// Licensed under the BSD license. See LICENSE file in the project root for full license information.
using System;
using JetBrains.Annotations;
namespace Saritasa.Tools.Messages.Common.Repositories.QueryProviders
{
/// <summary>
/// Sql query provider for AdoNetMessageRepository.
/// </summary>
internal interface IMessageQueryProvider
{
/// <summary>
/// Create initial table for messages.
/// </summary>
/// <returns>Sql query.</returns>
string GetCreateTableScript();
/// <summary>
/// Returns script to check whether messages table exists.
/// </summary>
/// <returns>Sql query.</returns>
string GetExistsTableScript();
/// <summary>
/// Returns sql script to insert message.
/// </summary>
/// <returns>Sql query.</returns>
string GetInsertMessageScript();
/// <summary>
/// Get filter script.
/// </summary>
/// <param name="messageQuery">Message query to filter by.</param>
/// <returns>Sql query.</returns>
string GetFilterScript([NotNull] MessageQuery messageQuery);
}
}
|
using System;
using System.Linq;
using System.Collections.Generic;
using Android.App;
using Android.OS;
using Android.Views;
using Android.Widget;
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.Views.Animations;
namespace XamarinStore
{
public class ProductListFragment : ListFragment
{
public event Action<Product,int> ProductSelected = delegate {};
BadgeDrawable basketBadge;
int badgeCount;
public override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
RetainInstance = true;
SetHasOptionsMenu (true);
}
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.Inflate (Resource.Layout.XamarinListLayout, container, false);
}
public override void OnViewCreated (View view, Bundle savedInstanceState)
{
base.OnViewCreated (view, savedInstanceState);
ListView.SetDrawSelectorOnTop (true);
ListView.Selector = new ColorDrawable (new Android.Graphics.Color (0x30ffffff));
if (ListAdapter == null) {
ListAdapter = new ProductListViewAdapter (view.Context);
GetData ();
}
}
async void GetData ()
{
var adapter = (ProductListViewAdapter)ListAdapter;
adapter.Products = await WebService.Shared.GetProducts ();
//No need to await the precache, we just need to kick it off
#pragma warning disable 4014
WebService.Shared.PreloadImages (Images.ScreenWidth);
#pragma warning restore 4014
adapter.NotifyDataSetChanged ();
}
public override void OnListItemClick (ListView l, View v, int position, long id)
{
base.OnListItemClick (l, v, position, id);
var adapter = (ProductListViewAdapter) ListView.Adapter;
ProductSelected (adapter.Products [position], v.Top);
}
void AdjustParallax (object sender, View.TouchEventArgs e)
{
e.Handled = false;
}
public override void OnCreateOptionsMenu (IMenu menu, MenuInflater inflater)
{
inflater.Inflate (Resource.Menu.menu, menu);
var cartItem = menu.FindItem (Resource.Id.cart_menu_item);
cartItem.SetIcon ((basketBadge = new BadgeDrawable (cartItem.Icon)));
var order = WebService.Shared.CurrentOrder;
if (badgeCount != order.Products.Count)
basketBadge.SetCountAnimated (order.Products.Count);
else
basketBadge.Count = order.Products.Count;
badgeCount = order.Products.Count;
order.ProductsChanged += (sender, e) => {
basketBadge.SetCountAnimated (order.Products.Count);
};
base.OnCreateOptionsMenu (menu, inflater);
}
class ProductListViewAdapter : BaseAdapter
{
Context context;
IInterpolator appearInterpolator = new DecelerateInterpolator ();
public IReadOnlyList<Product> Products;
long newItems;
public override int Count {
get { return Products == null ? 0 : Products.Count; }
}
public override Java.Lang.Object GetItem (int position)
{
return new Java.Lang.String (Products [position].ToString ());
}
public ProductListViewAdapter (Context context)
{
this.context = context;
}
public override long GetItemId (int position)
{
return Products[position].GetHashCode ();
}
public override View GetView (int position, View convertView, ViewGroup parent)
{
if (convertView == null) {
var inflater = LayoutInflater.FromContext (context);
convertView = inflater.Inflate (Resource.Layout.ProductListItem, parent, false);
convertView.Id = 0x60000000;
}
convertView.Id++;
var imageView = convertView.FindViewById<ImageView> (Resource.Id.productImage);
var nameLabel = convertView.FindViewById<TextView> (Resource.Id.productTitle);
var priceLabel = convertView.FindViewById<TextView> (Resource.Id.productPrice);
var progressView = convertView.FindViewById<ProgressBar> (Resource.Id.productImageSpinner);
var product = Products [position];
nameLabel.Text = product.Name;
priceLabel.Text = product.PriceDescription;
LoadProductImage (convertView, progressView, imageView, product);
if (((newItems >> position) & 1) == 0) {
newItems |= 1L << position;
var density = context.Resources.DisplayMetrics.Density;
convertView.TranslationY = 60 * density;
convertView.RotationX = 12;
convertView.ScaleX = 1.1f;
convertView.PivotY = 180 * density;
convertView.PivotX = parent.Width / 2;
convertView.Animate ()
.TranslationY (0)
.RotationX (0)
.ScaleX (1)
.SetDuration (450)
.SetInterpolator (appearInterpolator)
.Start ();
}
return convertView;
}
async void LoadProductImage (View mainView, ProgressBar progressView, ImageView imageView, Product product)
{
var currentId = mainView.Id;
progressView.Visibility = ViewStates.Visible;
imageView.SetImageResource (Android.Resource.Color.Transparent);
await Images.SetImageFromUrlAsync (imageView,product.ImageForSize (Images.ScreenWidth));
progressView.Visibility = ViewStates.Invisible;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using LiveClinic.Contracts;
using LiveClinic.Pharmacy.Core.Application.Inventory.Commands;
using LiveClinic.Pharmacy.Core.Application.Inventory.Queries;
using LiveClinic.Pharmacy.Core.Application.Orders.Commands;
using LiveClinic.Pharmacy.Core.Domain.Inventory;
using LiveClinic.Pharmacy.Core.Domain.Orders;
using LiveClinic.Pharmacy.Core.Tests.TestArtifacts;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
using Serilog;
namespace LiveClinic.Pharmacy.Core.Tests.Application.Inventory.Commands
{
[TestFixture]
public class DispenseDrugTests
{
private IMediator _mediator;
private Drug _drug;
private PrescriptionOrder _order;
[OneTimeSetUp]
public void Init()
{
_drug = TestData.CreateTestDrugWithStock("YYY", 5);
_order = TestData.CreateTestPrescriptionOrder(new List<Drug>() {_drug},1,1).First();
_order.OrderItems.ForEach(x =>
{
x.DrugId = _drug.Id;
x.Days = 1;
x.Quantity = 1;
});
_order.PaymentId=Guid.NewGuid();
TestInitializer.SeedData(new[] {_drug}, new[] {_order});
}
[SetUp]
public void SetUp()
{
_mediator = TestInitializer.ServiceProvider.GetService<IMediator>();
}
[Test]
public void should_Dispense()
{
var res = _mediator.Send( new DispenseDrugs(_order.OrderId)).Result;
Assert.True(res.IsSuccess);
Assert.That(TestInitializer.TestConsumerOrderFulfilled.Consumed.Any<OrderFulfilled>().Result);
var inventoryQuery = _mediator.Send(new GetInventory(_drug.Id)).Result;
var inventoryDto = inventoryQuery.Value.First();
Assert.AreEqual(4,inventoryDto.QuantityStock);
Log.Debug(inventoryDto.ToString());
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace Noise.Infrastructure.Dto {
public enum eTrackPlayStrategy {
Suggester,
Disqualifier,
BonusSuggester
}
public enum eTrackPlayHandlers {
// Suggesters
Unknown = 0,
Stop = 100,
Replay = 101,
PlayArtist = 102,
PlaySimilar = 103,
PlayFavorites = 104,
PlayGenre = 105,
SeldomPlayedArtists = 106,
PlayUserTags = 107,
RatedTracks = 108,
// Disqualifiers
ShortTracks = 201,
AlreadyQueuedTracks = 202,
BadRatingTracks = 203,
TalkingTracks = 204,
DoNotPlayTracks = 205,
// Bonus handlers
HighlyRatedTracks = 301,
PlayAdjacentTracks = 302
}
public class ExhaustedStrategySpecification {
public IList<eTrackPlayHandlers> TrackSuggesters { get; }
public IList<eTrackPlayHandlers> TrackDisqualifiers { get; }
public IList<eTrackPlayHandlers> TrackBonusSuggesters { get; }
public long SuggesterParameter { get; set; }
public static ExhaustedStrategySpecification Default {
get {
var retValue = new ExhaustedStrategySpecification();
retValue.TrackSuggesters.Add( eTrackPlayHandlers.Stop );
retValue.TrackDisqualifiers.Add( eTrackPlayHandlers.AlreadyQueuedTracks );
retValue.TrackDisqualifiers.Add( eTrackPlayHandlers.ShortTracks );
retValue.TrackDisqualifiers.Add( eTrackPlayHandlers.BadRatingTracks );
retValue.TrackDisqualifiers.Add( eTrackPlayHandlers.TalkingTracks );
retValue.TrackDisqualifiers.Add( eTrackPlayHandlers.DoNotPlayTracks );
// retValue.TrackBonusSuggesters.Add( eTrackPlayHandlers.HighlyRatedTracks );
// retValue.TrackBonusSuggesters.Add( eTrackPlayHandlers.PlayAdjacentTracks );
return retValue;
}
}
public ExhaustedStrategySpecification() {
TrackSuggesters = new List<eTrackPlayHandlers>();
TrackDisqualifiers = new List<eTrackPlayHandlers>();
TrackBonusSuggesters = new List<eTrackPlayHandlers>();
SuggesterParameter = Constants.cDatabaseNullOid;
}
public ExhaustedStrategySpecification( ExhaustedStrategySpecification copy ) {
TrackSuggesters = new List<eTrackPlayHandlers>( copy.TrackSuggesters );
TrackDisqualifiers = new List<eTrackPlayHandlers>( copy.TrackDisqualifiers );
TrackBonusSuggesters = new List<eTrackPlayHandlers>( copy.TrackBonusSuggesters );
SuggesterParameter = copy.SuggesterParameter;
}
public void SetPrimarySuggester( eTrackPlayHandlers suggester ) {
TrackSuggesters.Clear();
TrackSuggesters.Add( suggester );
}
public eTrackPlayHandlers PrimarySuggester() {
var retValue = eTrackPlayHandlers.Unknown;
if( TrackSuggesters.Any()) {
retValue = TrackSuggesters.FirstOrDefault();
}
return retValue;
}
}
}
|
// SPDX-License-Identifier: MIT
// Copyright (C) 2018-present iced project and contributors
#if FAST_FMT
using Iced.Intel;
namespace Iced.UnitTests.Intel.FormatterTests.Fast {
public abstract class FastFormatterTest {
protected void FormatBase(int index, InstructionInfo info, string formattedString, FastFormatter formatter) =>
FormatterTestUtils.FormatTest(info.Bitness, info.HexBytes, info.IP, info.Code, info.Options, formattedString, formatter);
protected void FormatBase(int index, Instruction instruction, string formattedString, FastFormatter formatter) =>
FormatterTestUtils.FormatTest(instruction, formattedString, formatter);
}
}
#endif
|
//
// EmptyClass.cs
//
// Author:
// Thomas GERVAIS <thomas.gervais@gmail.com>
//
// Copyright (c) 2016
//
// 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 PA.TileList.Drawing.Graphics2D;
using PA.TileList.Quantified;
using System.Drawing;
using PA.TileList.Linear;
using System.Linq;
namespace PA.TileList.Drawing.Quantified
{
public class RulersRenderer<T> : AbstractBitmapRenderer<IQuantifiedTile<T>>, IRenderer<IQuantifiedTile<T>, Bitmap>
where T : ICoordinate
{
private float[] _steps;
private enum Direction
{
Vertical,
Horizontal
}
public RulersRenderer(float[] steps)
{
this._steps = steps;
}
public override RectangleD<Bitmap> Render(IQuantifiedTile<T> obj, Bitmap baseImage, ScaleMode mode)
{
return this.Render(obj, baseImage, new RectangleD(obj.GetOrigin(), obj.GetSize()), mode);
}
public override void Draw(IQuantifiedTile<T> obj, RectangleD<Bitmap> portion)
{
using (var g = portion.GetGraphicsD())
{
DrawSteps(g, this._steps, Direction.Vertical);
DrawSteps(g, this._steps, Direction.Horizontal);
}
}
private RectangleD<Bitmap> Render(IQuantifiedTile<T> obj, Bitmap image, RectangleD portion, ScaleMode mode)
{
var r = new RectangleD<Bitmap>(image, portion, mode);
Draw(obj, r);
return r;
}
private static void DrawSteps(GraphicsD g, float[] steps, Direction d)
{
var min = 0f;
var max = 0f;
var scale = 1f;
//g.Graphics.FillRectangle(Brushes.Pink,
// new Rectangle((int)(g.OffsetX + g.Portion.Inner.X), (int)(g.OffsetY + g.Portion.Inner.Y),
// (int)(g.Portion.Inner.Width ), (int)(g.Portion.Inner.Height )));
switch (d)
{
case Direction.Vertical:
min = g.Portion.Inner.Top;
max = g.Portion.Inner.Bottom;
scale = g.ScaleY;
g.Graphics.DrawLine(Pens.Blue, g.OffsetX, min * scale, g.OffsetX, max * scale);
break;
case Direction.Horizontal:
min = g.Portion.Inner.Left;
max = g.Portion.Inner.Right;
scale = g.ScaleX;
g.Graphics.DrawLine(Pens.Blue, min * scale, g.OffsetY, max * scale, g.OffsetY);
break;
}
for (var i = 0; i < steps.Length; i++)
{
var step = steps[i] * scale;
var size = (i + 1f) / scale;
var start = 0f;
while (start < min)
start += step;
while (start > min)
start -= step;
for (var position = start; position < max; position += step)
switch (d)
{
case Direction.Vertical:
if (i == 0)
g.Graphics.DrawString(Math.Round(position / scale).ToString(),
new Font(FontFamily.GenericSansSerif, 20 * g.ScaleY), Brushes.Black,
g.OffsetX - size, position + g.OffsetY);
g.Graphics.DrawLine(Pens.Black, g.OffsetX - 10 * size, position + g.OffsetY, g.OffsetX + 10 * size,
position + g.OffsetY);
break;
case Direction.Horizontal:
if (i == 0)
g.Graphics.DrawString(Math.Round(position / scale).ToString(),
new Font(FontFamily.GenericSansSerif, 20 * g.ScaleY), Brushes.Black,
position + g.OffsetX, g.OffsetY - size);
g.Graphics.DrawLine(Pens.Black, position + g.OffsetX, g.OffsetY - 10 * size, position + g.OffsetX,
g.OffsetY + 10 * size);
break;
}
}
}
}
}
|
public class Spinner : Enemy
{
public override void Start()
{
base.Start();
stateMachine.Initialize(gameObject, Empty);
}
public override void Update()
{
base.Update();
stateMachine.Update();
}
void Empty()
{
}
}
|
using Pomelo.EntityFrameworkCore.MySql.Storage;
namespace Microsoft.EntityFrameworkCore.Tests
{
public class MySqlContextFactory<TContext> : RelationalContextFactoryBase<TContext>
where TContext : DbContext
{
public ServerVersion ServerVersion { get; private set; }
protected override string ScriptSplit => ";\r\n\r\n";
protected override string DropTableCommand => "DROP TABLE IF EXISTS `{0}`";
protected override void Configure(DbContextOptionsBuilder optionsBuilder)
{
var connectionString =
$"Server=localhost;" +
$"Port=3306;" +
$"Database=efcorebulktest{Suffix};" +
$"User=root;" +
$"Password=Password12!;" +
$"Character Set=utf8;" +
$"TreatTinyAsBoolean=true;";
ServerVersion = ServerVersion.AutoDetect(connectionString);
#if EFCORE50 || EFCORE60
optionsBuilder.UseMySql(
connectionString,
ServerVersion,
s => s.UseBulk());
#elif EFCORE31
optionsBuilder.UseMySql(
connectionString,
s => s.UseBulk()
.ServerVersion(ServerVersion));
#endif
}
}
}
|
using System;
using DeltaEngine.Datatypes;
using DeltaEngine.Extensions;
using SlimDX.XInput;
using SlimDXState = SlimDX.XInput.State;
namespace DeltaEngine.Input.SlimDX
{
/// <summary>
/// Native implementation of the GamePad interface using SlimDX
/// </summary>
public class SlimDXGamePad : GamePad
{
public SlimDXGamePad(GamePadNumber number = GamePadNumber.Any)
: base(number)
{
controller = new Controller(GetUserIndexFromNumber());
states = new State[GamePadButton.A.GetCount()];
for (int i = 0; i < states.Length; i++)
states[i] = State.Released;
}
private Controller controller;
private readonly State[] states;
private UserIndex GetUserIndexFromNumber()
{
if (Number == GamePadNumber.Any)
return GetAnyController();
if (Number == GamePadNumber.Two)
return UserIndex.Two;
if (Number == GamePadNumber.Three)
return UserIndex.Three;
return Number == GamePadNumber.Four ? UserIndex.Four : UserIndex.One;
}
private static UserIndex GetAnyController()
{
if (new Controller(UserIndex.Two).IsConnected)
return UserIndex.Two;
if (new Controller(UserIndex.Three).IsConnected)
return UserIndex.Three;
return new Controller(UserIndex.Three).IsConnected ? UserIndex.Four : UserIndex.One;
}
public override bool IsAvailable
{
get { return controller.IsConnected; }
protected set { }
}
protected override void UpdateGamePadStates()
{
var state = controller.GetState();
UpdateValuesFromState(ref state);
}
private void UpdateValuesFromState(ref SlimDXState state)
{
UpdateAllButtons(state.Gamepad.Buttons);
if (lastPacket == state.PacketNumber)
return;
lastPacket = state.PacketNumber;
leftThumbStick = Normalize(state.Gamepad.LeftThumbX, state.Gamepad.LeftThumbY,
Gamepad.GamepadLeftThumbDeadZone);
rightThumbStick = Normalize(state.Gamepad.RightThumbX, state.Gamepad.RightThumbY,
Gamepad.GamepadRightThumbDeadZone);
leftTrigger = state.Gamepad.LeftTrigger / (float)byte.MaxValue;
rightTrigger = state.Gamepad.RightTrigger / (float)byte.MaxValue;
}
private uint lastPacket;
private Vector2D leftThumbStick;
private Vector2D rightThumbStick;
private float leftTrigger;
private float rightTrigger;
private static Vector2D Normalize(short rawX, short rawY, short threshold)
{
var value = new Vector2D(rawX, rawY);
var magnitude = value.DistanceTo(Vector2D.Zero);
var direction = value / (magnitude == 0 ? 1 : magnitude);
var normalizedMagnitude = 0.0f;
if (magnitude - threshold > 0)
normalizedMagnitude = Math.Min((magnitude - threshold) / (short.MaxValue - threshold), 1);
return direction * normalizedMagnitude;
}
private void UpdateAllButtons(GamepadButtonFlags buttons)
{
UpdateNormalButtons(buttons);
UpdateStickAndShoulderButtons(buttons);
UpdateDPadButtons(buttons);
}
private void UpdateNormalButtons(GamepadButtonFlags buttons)
{
UpdateButton(buttons, GamepadButtonFlags.A, GamePadButton.A);
UpdateButton(buttons, GamepadButtonFlags.B, GamePadButton.B);
UpdateButton(buttons, GamepadButtonFlags.X, GamePadButton.X);
UpdateButton(buttons, GamepadButtonFlags.Y, GamePadButton.Y);
UpdateButton(buttons, GamepadButtonFlags.Back, GamePadButton.Back);
UpdateButton(buttons, GamepadButtonFlags.Start, GamePadButton.Start);
}
private void UpdateButton(GamepadButtonFlags buttons, GamepadButtonFlags nativeButton,
GamePadButton button)
{
var buttonIndex = (int)button;
states[buttonIndex] =
states[buttonIndex].UpdateOnNativePressing((buttons & nativeButton) != 0);
}
private void UpdateStickAndShoulderButtons(GamepadButtonFlags buttons)
{
UpdateButton(buttons, GamepadButtonFlags.LeftShoulder, GamePadButton.LeftShoulder);
UpdateButton(buttons, GamepadButtonFlags.LeftThumb, GamePadButton.LeftStick);
UpdateButton(buttons, GamepadButtonFlags.RightShoulder, GamePadButton.RightShoulder);
UpdateButton(buttons, GamepadButtonFlags.RightThumb, GamePadButton.RightStick);
}
private void UpdateDPadButtons(GamepadButtonFlags buttons)
{
UpdateButton(buttons, GamepadButtonFlags.DPadDown, GamePadButton.Down);
UpdateButton(buttons, GamepadButtonFlags.DPadUp, GamePadButton.Up);
UpdateButton(buttons, GamepadButtonFlags.DPadLeft, GamePadButton.Left);
UpdateButton(buttons, GamepadButtonFlags.DPadRight, GamePadButton.Right);
}
public override void Dispose()
{
controller = null;
}
public override Vector2D GetLeftThumbStick()
{
return leftThumbStick;
}
public override Vector2D GetRightThumbStick()
{
return rightThumbStick;
}
public override float GetLeftTrigger()
{
return leftTrigger;
}
public override float GetRightTrigger()
{
return rightTrigger;
}
public override State GetButtonState(GamePadButton button)
{
return states[(int)button];
}
public override void Vibrate(float strength)
{
var motorSpeed = (ushort)(strength * ushort.MaxValue);
controller.SetVibration(new Vibration
{
LeftMotorSpeed = motorSpeed,
RightMotorSpeed = motorSpeed
});
}
}
} |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace MS_PCCRC_TestTool
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Net;
using System.Drawing;
/// <summary>
/// TODO: Update summary.
/// </summary>
public static class Utility
{
/// <summary>
/// Transfer a byte array to a hex string.
/// Example from a byte array { 0x0a, 0x0b, 0x0c },
/// the return is a string 0A0B0C.
/// </summary>
/// <param name="data">The input byte array</param>
/// <param name="start">The start index.</param>
/// <param name="length">The data length of convert to string.</param>
/// <returns>Hex String from the buffer</returns>
public static string ToHexString(byte[] data, int start, int length)
{
StringBuilder oRet = new StringBuilder();
string tempString = string.Empty;
if (data == null)
{
return string.Empty;
}
if (length == 0)
{
length = data.Length;
}
for (int i = start; i < start + length; i++)
{
oRet.Append(data[i].ToString("X2"));
}
return oRet.ToString();
}
/// <summary>
/// Transfer a byte array to a hex string.
/// Example from a byte array { 0x0a, 0x0b, 0x0c },
/// the return is a string 0A0B0C.
/// </summary>
/// <param name="data">The input byte array</param>
/// <returns>Hex String from the byte array</returns>
public static string ToHexString(byte[] data)
{
string hexStr = string.Empty;
if (data != null)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
builder.Append(data[i].ToString("X2"));
}
hexStr = builder.ToString();
}
return hexStr;
}
/// <summary>
/// Show message box.
/// </summary>
/// <param name="msg"></param>
/// <param name="icon"></param>
public static void ShowMessageBox(string msg, MessageBoxIcon icon)
{
switch (icon)
{
case MessageBoxIcon.Error:
MessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
break;
case MessageBoxIcon.Information:
MessageBox.Show(msg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
break;
case MessageBoxIcon.Warning:
MessageBox.Show(msg, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
break;
}
}
public static byte[] DownloadHTTPFile(string server, string file)
{
WebClient client = new WebClient();
return client.DownloadData(string.Format("http://{0}/{1}", server, file));
}
}
}
|
using System;
using UnityEngine;
public class JianzhutishiItem : MonoBehaviour
{
public UILabel name_Client;
public UILabel des;
public UISprite icon;
private void Awake()
{
this.name_Client = base.transform.FindChild("Name").GetComponent<UILabel>();
this.des = base.transform.FindChild("officename_lable").GetComponent<UILabel>();
this.icon = base.transform.FindChild("Sprite").GetComponent<UISprite>();
}
}
|
@model ArtworkListingServiceModel
@inject IArtistService ArtistService
@{
var artist = ArtistService.GetName(ViewBag.ArtistId);
var artworks = Model.Artworks;
var title = artist + "'s Artworks";
ViewData["Title"] = title;
}
<div class="container p-3">
<h1 class="title-margin text-center">@title</h1>
@if (!artworks.Any())
{
<p>No artworks yet</p>
}
<div class="row">
@foreach (var art in artworks)
{
<partial name="_ArtPartial" model="@art" />
}
</div>
</div>
|
using System;
using System.Threading.Tasks;
using EasyConsole;
namespace Langly {
internal sealed class MainMenu : MenuPage {
public MainMenu(Program program) : base("Main Menu", program,
new Option("Collectathon", (_) => Task.Run(() => program.NavigateTo<CollectathonMenu>(_))),
new Option("Quit", (_) => Task.Run(() => Environment.Exit(0)))) { }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GitDeployHub.Web.Engine
{
public interface ILog
{
void Log(string messsage);
void LogNewLine();
}
} |
// To use this example, attach this script to an empty GameObject.
// Create three buttons (Create>UI>Button). Next, select your
// empty GameObject in the Hierarchy and click and drag each of your
// Buttons from the Hierarchy to the Your First Button, Your Second Button
// and Your Third Button fields in the Inspector.
// Click each Button in Play Mode to output their message to the console.
// Note that click means press down and then release.
using UnityEngine;
using UnityEngine.UI;
public class ClickedEvent : MonoBehaviour
{
//Make sure to attach these Buttons in the Inspector
public Button m_YourFirstButton, m_YourSecondButton, m_YourThirdButton;
void Start()
{
//Calls the TaskOnClick/TaskWithParameters/ButtonClicked method when you click the Button
m_YourFirstButton.onClick.AddListener(TaskOnClick);
m_YourSecondButton.onClick.AddListener(delegate { TaskWithParameters("Hello"); });
m_YourThirdButton.onClick.AddListener(() => ButtonClicked(42));
m_YourThirdButton.onClick.AddListener(TaskOnClick);
}
void TaskOnClick()
{
//Output this to console when Button1 or Button3 is clicked
Debug.Log("You have clicked the button!");
}
void TaskWithParameters(string message)
{
//Output this to console when the Button2 is clicked
Debug.Log(message);
}
void ButtonClicked(int buttonNo)
{
//Output this to console when the Button3 is clicked
Debug.Log("Button clicked = " + buttonNo);
}
} |
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Maw.Domain.Videos
{
public interface IVideoService
{
Task<IEnumerable<short>> GetYearsAsync(bool allowPrivate);
Task<IEnumerable<Category>> GetAllCategoriesAsync(bool allowPrivate);
Task<IEnumerable<Category>> GetCategoriesAsync(short year, bool allowPrivate);
Task<IEnumerable<Video>> GetVideosInCategoryAsync(short categoryId, bool allowPrivate);
Task<Video> GetVideoAsync(short id, bool allowPrivate);
Task<Category> GetCategoryAsync(short categoryId, bool allowPrivate);
Task<IEnumerable<Comment>> GetCommentsAsync(short videoId);
Task<GpsDetail> GetGpsDetailAsync(int videoId);
Task<Rating> GetRatingsAsync(short videoId, string username);
Task<int> InsertCommentAsync(short videoId, string username, string comment);
Task<float?> SaveRatingAsync(short videoId, string username, short rating);
Task<float?> RemoveRatingAsync(short videoId, string username);
Task SetGpsOverrideAsync(int videoId, GpsCoordinate gps, string username);
Task SetCategoryTeaserAsync(short categoryId, int videoId);
Task ClearCacheAsync();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.