content stringlengths 23 1.05M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bonsai.Bpod
{
public class EncoderDataFrame
{
public EncoderDataFrame(byte[] packet)
{
OpCode = (OpCode)packet[0];
Timestamp = BitConverter.ToUInt32(packet, 3);
}
public OpCode OpCode { get; private set; }
public uint Timestamp { get; private set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace WebMVC.Models.BaseTB
{
public class UserModels
{
[Key]
public string UserName { get; set; }
public string UserPwd { get; set; }
//public int Age { get; set; }
public UserModels(string name, string pwd)
{
this.UserName = name;
this.UserPwd = pwd;
}
//定义无参数的构造函数主要是因为在通过DbSet获取对象进行linq查询时会报错
//The class 'EFCodeFirstModels.Student' has no parameterless constructor.
public UserModels() { }
}
} |
using System;
using System.IdentityModel.Tokens;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Microsoft.Owin;
using Owin;
namespace AuthorizationServer
{
public static class VerifyTokenApplication
{
public static void VerifyToken(this IAppBuilder app)
{
app.Run(VerifyToken);
}
private static async Task VerifyToken(IOwinContext context)
{
var query = HttpUtility.ParseQueryString(context.Request.Uri.Query);
var token = query["access_token"];
if (string.IsNullOrEmpty(token))
return;
// check if token is valid
// if token (is valid)
var jwtToken = CreateJwtToken();
var bytes = Encoding.UTF8.GetBytes(jwtToken);
await context.Response.Body.WriteAsync(bytes, 0, bytes.Length);
}
private static string CreateJwtToken()
{
using (var hmac = new HMACSHA256(Convert.FromBase64String("c2hhcmVkIHNlY3JldA==")))
{
const string signatureAlgorithm = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
const string digestAlgorithm = "http://www.w3.org/2001/04/xmlenc#sha256";
var signingCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(hmac.Key),
signatureAlgorithm, digestAlgorithm);
var claims = new[]
{
new Claim(ClaimTypes.Email, "foo@bar.com"),
};
var token = new JwtSecurityToken(
"http://authorizationserver.com/",
"http://resourceserver.com/",
claims,
DateTime.UtcNow,
DateTime.UtcNow.AddMinutes(15),
signingCredentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
}
} |
using System.Collections.Generic;
using LearnWordsFast.DAL.Models;
using LearnWordsFast.ViewModels.WordController;
namespace LearnWordsFast.ViewModels.TrainingController
{
public class ManyRightTrainingViewModel : TrainingViewModel
{
public ManyRightTrainingViewModel(ManyRight type, IList<WordViewModel> words) : base(type)
{
Words = words;
}
public IList<WordViewModel> Words { get; set; }
}
} |
using Services.Models;
namespace Site.Models
{
public class SmtpRequest
{
public SmtpRequest() { }
public SmtpRequest(SiteSetting settings, string htmlBody, string textBody, string toEmail, string subject)
{
if (settings != null)
{
From = settings.SmtpUsername;
Port = settings.SmtpPort ?? 0;
Host = settings.SmtpHost;
Password = settings.SmtpPassword;
UserName = settings.SmtpUsername;
}
HtmlBody = htmlBody;
TextBody = textBody;
Subject = subject;
To = toEmail;
}
public string Host { get; set; }
public int Port { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string From { get; set; }
public string To { get; set; }
public string TextBody { get; set; }
public string HtmlBody { get; set; }
public string Subject { get; set; }
}
} |
using RefactoringEssentials.CSharp.CodeRefactorings;
using Xunit;
namespace RefactoringEssentials.Tests.CSharp.CodeRefactorings
{
public class ConvertAnonymousMethodToLambdaTests : CSharpCodeRefactoringTestBase
{
[Fact]
public void BasicTest()
{
Test<ConvertAnonymousMethodToLambdaCodeRefactoringProvider>(@"
class A
{
void F ()
{
System.Action<int, int> action = delegate$ (int i1, int i2) { System.Console.WriteLine(i1); };
}
}", @"
class A
{
void F ()
{
System.Action<int, int> action = (i1, i2) => System.Console.WriteLine(i1);
}
}");
}
[Fact]
public void VarDeclaration()
{
Test<ConvertAnonymousMethodToLambdaCodeRefactoringProvider>(@"
class A
{
void F ()
{
var action = delegate$ (int i1, int i2) { System.Console.WriteLine(i1); System.Console.WriteLine(i2); };
}
}", @"
class A
{
void F ()
{
var action = (int i1, int i2) => { System.Console.WriteLine(i1); System.Console.WriteLine(i2); };
}
}");
}
[Fact]
public void ParameterLessDelegate()
{
Test<ConvertAnonymousMethodToLambdaCodeRefactoringProvider>(@"
class A
{
void F (int i)
{
System.Action<int> act = $delegate { System.Console.WriteLine(i); };
}
}", @"
class A
{
void F (int i)
{
System.Action<int> act = obj => System.Console.WriteLine(i);
}
}");
}
}
}
|
namespace Api.Services.Interfaces
{
using Api.Models.DeliveryData;
using System.Threading.Tasks;
public interface IDeliveryDataService
{
Task<string> Create(
DeliveryDataCreateModel data);
Task<DeliveryDataDetailsModel> Get(string id);
Task<string> Edit(string deliveryDataId, DeliveryDataCreateModel data);
}
}
|
using System.Collections.Generic;
namespace MPT.CSI.Serialize.Models.Components.ProjectSettings
{
public class ProjectInformation
{
/// <summary>
/// The project information items.
/// </summary>
/// <value>The project information items.</value>
public List<string> ProjectInfoItems { get; internal set; } = new List<string>();
/// <summary>
/// The project information data.
/// </summary>
/// <value>The project information data.</value>
public List<string> ProjectInfoData { get; internal set; } = new List<string>();
/// <summary>
/// The user comment.
/// </summary>
/// <value>The user comment.</value>
public string UserComment { get; internal set; }
}
}
|
using System;
using System.Collections.Generic;
namespace Unclazz.Commons.CLI
{
/// <summary>
/// コマンドラインの定義情報を表わすインターフェースです。
/// </summary>
public interface ICommandLine<T>
{
/// <summary>
/// コマンド名です。
/// </summary>
/// <value>コマンド名</value>
string CommandName { get; }
/// <summary>
/// コマンドの説明です。
/// 説明はヘルプの出力に使用されます。
/// </summary>
/// <value>コマンドの説明</value>
string Description { get; }
/// <summary>
/// コマンドライン引数のパースのとき大文字小文字を区別する場合<c>true</c>を返します。
/// </summary>
/// <value>大文字小文字を区別する場合<c>true</c></value>
bool CaseSensitive { get; }
/// <summary>
/// コマンドライン・オプションの定義情報です。
/// </summary>
/// <value>コマンドライン・オプションの定義情報</value>
OptionCollection<T> Options { get; }
/// <summary>
/// コマンドライン引数のうちコマンドライン・オプションの定義情報に
/// 含まれなかった「残りの引数」を処理するためのデリゲートです。
/// デフォルト値として利用されているデリゲートは受け取った値を単に破棄します。
/// </summary>
/// <value>「残りの引数」のためのデリゲート</value>
Action<T, IEnumerable<string>> SetterDelegate { get; }
/// <summary>
/// コマンドライン引数のうちコマンドライン・オプションの定義情報に
/// 含まれなかった「残りの引数」の名前のシーケンス。
/// これらの名前はヘルプの出力に使用されます。
/// </summary>
/// <value>「残りの引数」の名前のシーケンス</value>
IEnumerable<string> ArgumentNames { get; }
/// <summary>
/// パーサ・インスタンスを取得します。
/// </summary>
/// <returns>パーサ</returns>
/// <param name="valueObject">パース結果が設定されるバリュー・オブジェクト</param>
IParser<T> GetParser(T valueObject);
/// <summary>
/// パーサ・インスタンスを取得します。
/// </summary>
/// <returns>パーサ</returns>
/// <param name="valueObjectSupplier">パース結果が設定されるバリュー・オブジェクトのサプライヤー</param>
IParser<T> GetParser(Func<T> valueObjectSupplier);
/// <summary>
/// パーサ・インスタンスを取得します。
/// </summary>
/// <returns>パーサ</returns>
IParser<T> GetParser();
}
}
|
using System.Text.RegularExpressions;
namespace SoundComposition.Domain
{
public partial class Song
{
public string FileName { get; set; }
public string Instrument { get; set; }
public string Note { get; set; }
public int Octave { get; set; }
public float Tempo { get; set; }
public string Intensity { get; set; }
public string Mode { get; set; }
public double SpeedRatio { get; set; }
public double Balance { get; set; }
public double Volume { get; set; }
public Song(string fileName)
:this(fileName.Split('_'))
{
FileName = fileName;
SpeedRatio = 1.0;
Balance = 50.0;
Volume = 100.0;
}
private Song(string[] parts)
{
Instrument = parts[0];
var re = new Regex(@"(?<note>[a-zA-Z]*)(?<octave>\d{1,3})");
var match = re.Match(parts[1]);
if (match.Success)
{
Note = match.Groups["note"].Value;
Octave = int.Parse(match.Groups["octave"].Value);
}
re = new Regex(@"(?<tempo>\d{1,3})");
match = re.Match(parts[2]);
if (match.Success)
{
Tempo = float.Parse(match.Groups["tempo"].Value);
if (Tempo > 1 && Tempo < 16)
Tempo = Tempo * 0.1F;
else if (Tempo == 25.0F)
Tempo = 0.25F;
}
else {
Tempo = 1.0F;
}
Intensity = parts[3];
Mode = parts[4];
}
public override string ToString()
{
return FileName;
}
}
}
|
using GetEdge;
using System;
using System.Collections.Generic;
using Xunit;
namespace TestGetEdges
{
public class GetEdgesTest
{
[Theory]
[InlineData("New New York", true)]
public void CanGetDirectFlight(string cityName, bool expected)
{
//arrange
//instantiate a new graph
Graph graph = new Graph();
Node node1 = new Node("Seattle");
Node node2 = new Node("Narnia");
Node node3 = new Node("Winterfell");
Node node4 = new Node("North Pole");
Node node5 = new Node("Eden");
Node node6 = new Node("Mesopotamia");
Node node7 = new Node(cityName);
//add edges between nodes
graph.AddEdge(node1, node2, 100);
graph.AddEdge(node1, node3, 50);
graph.AddEdge(node1, node4, 200);
graph.AddEdge(node1, node7, 500);
graph.AddEdge(node4, node5, 10);
graph.AddEdge(node4, node6, 50);
//act
Tuple<bool, decimal> flight = graph.GetEdge(node1, node7);
//assert
Assert.Equal(flight.Item1, expected);
}
[Theory]
[InlineData("Narnia", true)]
public void CanGetAnotherDirectFlight(string cityName, bool expected)
{
//arrange
//instantiate a new graph
Graph graph = new Graph();
Node node1 = new Node("Seattle");
Node node2 = new Node(cityName);
Node node3 = new Node("Winterfell");
Node node4 = new Node("North Pole");
Node node5 = new Node("Eden");
Node node6 = new Node("Mesopotamia");
//add edges between nodes
graph.AddEdge(node1, node2, 100);
graph.AddEdge(node1, node3, 50);
graph.AddEdge(node1, node4, 200);
graph.AddEdge(node4, node5, 10);
graph.AddEdge(node4, node6, 50);
//act
Tuple<bool, decimal> flight = graph.GetEdge(node1, node2);
//assert
Assert.Equal(flight.Item1, expected);
}
[Theory]
[InlineData("Mesopotamia", false)]
public void CannotGetDirectFlight(string cityName, bool expected)
{
//arrange
//instantiate a new graph
Graph graph = new Graph();
Node node1 = new Node("Seattle");
Node node2 = new Node("Narnia");
Node node3 = new Node("Winterfell");
Node node4 = new Node("North Pole");
Node node5 = new Node("Eden");
Node node6 = new Node(cityName);
//add edges between nodes
graph.AddEdge(node1, node2, 100);
graph.AddEdge(node1, node3, 50);
graph.AddEdge(node1, node4, 200);
graph.AddEdge(node4, node5, 10);
graph.AddEdge(node4, node6, 50);
//act
Tuple<bool, decimal> flight = graph.GetEdge(node1, node6);
//assert
Assert.Equal(flight.Item1, expected);
}
}
}
|
using System.Collections.Generic;
using ITGlobal.MarkDocs.Tags.Impl;
using JetBrains.Annotations;
namespace ITGlobal.MarkDocs.Tags
{
/// <summary>
/// Helper methods for tags service
/// </summary>
[PublicAPI]
public static class TagsExtensionMethods
{
/// <summary>
/// Gets an instance of tags extension
/// </summary>
/// <param name="documentation">
/// Documentation
/// </param>
/// <returns>
/// Page tags service
/// </returns>
[NotNull]
public static ITagService GetTagService([NotNull] this IDocumentation documentation)
{
var extension = documentation.Service.GetExtension<TagsExtension>();
return extension;
}
/// <summary>
/// Gets a list of normalized page tags
/// </summary>
/// <param name="documentation">
/// Documentation
/// </param>
/// <returns>
/// List of tags
/// </returns>
[NotNull]
public static IReadOnlyList<string> GetTags([NotNull] this IDocumentation documentation)
{
var extension = documentation.GetTagService();
return extension.GetTags(documentation);
}
/// <summary>
/// Gets a list of normalized page tags
/// </summary>
/// <param name="page">
/// Page
/// </param>
/// <returns>
/// List of tags
/// </returns>
[NotNull]
public static IReadOnlyList<string> GetPageTags([NotNull] this IPage page)
{
var extension = page.Documentation.GetTagService();
return extension.GetPageTags(page);
}
/// <summary>
/// Gets a list of pages with tag
/// </summary>
/// <param name="documentation">
/// Documentation
/// </param>
/// <param name="tag">
/// Tag
/// </param>
/// <returns>
/// List of pages
/// </returns>
[NotNull]
public static IReadOnlyList<IPage> GetPagesByTag(
[NotNull] this IDocumentation documentation,
[NotNull] string tag)
{
var extension = documentation.GetTagService();
return extension.GetPagesByTag(documentation, tag);
}
/// <summary>
/// Gets a list of pages with tags
/// </summary>
/// <param name="documentation">
/// Documentation
/// </param>
/// <param name="includeTags">
/// Include only pages with specified tags
/// </param>
/// <param name="excludeTags">
/// Exclude pages with specified tags
/// </param>
/// <returns>
/// List of pages
/// </returns>
[NotNull]
public static IReadOnlyList<IPage> GetPagesByTags(
[NotNull] this IDocumentation documentation,
[CanBeNull] string[] includeTags = null,
[CanBeNull] string[] excludeTags = null)
{
var extension = documentation.GetTagService();
return extension.GetPagesByTags(documentation, includeTags, excludeTags);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ninject;
using System.ComponentModel;
using System.Windows;
namespace Pvp.App.Composition
{
internal static class DesignTimeComposition
{
internal static void SetUpDependencies()
{
if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
{
var kernel = new StandardKernel();
kernel.Load(typeof(App).Assembly);
var resolver = new NinjectDependencyResolver(kernel);
DependencyResolver.SetResolver(resolver);
}
}
}
}
|
using OMM.Domain;
using OMM.Services.AutoMapper;
namespace OMM.Services.Data.DTOs.Statuses
{
public class StatusListDto : IMapFrom<Status>
{
public int Id { get; set; }
public string Name { get; set; }
}
}
|
using System.IO;
using System.Net;
using System.Xml.Serialization;
using Nuxleus.Core;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
using System;
namespace Nuxleus.Extension.Aws.SimpleDb
{
[XmlRootAttribute(Namespace = "http://sdb.amazonaws.com/doc/2007-11-07/", IsNullable = false)]
public class SelectResponse : IResponse, IXmlSerializable
{
static readonly string m_sdbNamespace = "http://sdb.amazonaws.com/doc/2007-11-07/";
static readonly XName m_nextToken = XName.Get("NextToken", m_sdbNamespace);
static readonly XName m_selectResult = XName.Get("SelectResult", m_sdbNamespace);
static readonly XName m_item = XName.Get("Item", m_sdbNamespace);
static readonly XName m_itemName = XName.Get("Name", m_sdbNamespace);
static readonly XName m_itemAttributes = XName.Get("Attribute", m_sdbNamespace);
static readonly XName m_attributeName = XName.Get("Name", m_sdbNamespace);
static readonly XName m_attributeValue = XName.Get("Value", m_sdbNamespace);
public WebHeaderCollection Headers {
get;
set;
}
[XmlElementAttribute(ElementName = "SelectResult")]
public IResult Result {
get;
set;
}
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema() {
throw new System.NotImplementedException();
}
public void ReadXml(XmlReader reader) {
SelectResult result = new SelectResult();
XElement elements = XElement.Load(reader);
XElement selectResult = elements.Element(m_selectResult);
try {
result.NextToken = selectResult.Element(m_nextToken).Value;
}
catch {
result.NextToken = String.Empty;
}
result.Metadata = Utility.GetSdbResponseMetadata(elements);
result.Item = new List<Item>();
IEnumerable<XElement> items = selectResult.Descendants(m_item);
foreach (XElement item in items) {
IEnumerable<XElement> itemAttributes = item.Elements(m_itemAttributes);
List<SimpleDb.Attribute> attributes = new List<SimpleDb.Attribute>();
foreach (XElement attribute in itemAttributes) {
attributes.Add(new Attribute {
Name = attribute.Element(m_attributeName).Value,
Value = attribute.Element(m_attributeValue).Value
});
}
result.Item.Add(new Item {
ItemName = item.Element(m_itemName).Value,
Attribute = attributes
});
}
Result = result;
}
public void WriteXml(XmlWriter writer) {
throw new System.NotImplementedException();
}
#endregion
}
}
|
using System.Collections.Generic;
using ESFA.DC.ILR.ReportService.Model.ReportModels;
namespace ESFA.DC.ILR.ReportService.Service.Comparer
{
public sealed class TrailblazerEmployerIncentivesModelComparer : IComparer<TrailblazerEmployerIncentivesModel>
{
public int Compare(TrailblazerEmployerIncentivesModel x, TrailblazerEmployerIncentivesModel y)
{
return 0;
}
}
} |
using System;
using Terminals.Configuration;
using Terminals.Data;
namespace Terminals.Forms
{
internal class FavoriteSorting
{
private readonly SortProperties defaultSortProperty;
internal FavoriteSorting()
{
this.defaultSortProperty = Settings.Instance.DefaultSortProperty;
}
internal string GetDefaultSortPropertyName()
{
switch (this.defaultSortProperty)
{
case SortProperties.ServerName:
return "ServerName";
case SortProperties.Protocol:
return "Protocol";
case SortProperties.ConnectionName:
return "Name";
default:
return String.Empty;
}
}
/// <summary>
/// Returns text compare to method values selecting property to compare
/// depending on Settings default sort property value
/// </summary>
/// <param name="target">not null favorite to compare with</param>
/// <returns>result of String CompareTo method</returns>
internal int CompareByDefaultSorting(IFavorite source, IFavorite target)
{
switch (this.defaultSortProperty)
{
case SortProperties.ServerName:
return source.ServerName.CompareTo(target.ServerName);
case SortProperties.Protocol:
return source.Protocol.CompareTo(target.Protocol);
case SortProperties.ConnectionName:
return source.Name.CompareTo(target.Name);
default:
return -1;
}
}
}
} |
namespace Improving.AspNet.Tests.Domain
{
using System.Threading.Tasks;
using global::MediatR;
public class AuthorizeStockHandler
: IAsyncRequestHandler<AuthorizeStock, Unit>
{
public Task<Unit> Handle(AuthorizeStock request)
{
return Task.FromResult(Unit.Value);
}
}
} |
using Stl.Mathematics.Internal;
namespace Stl.Mathematics;
public class TileLayer<T>
where T : notnull
{
private readonly Lazy<TileLayer<T>?> _largerLazy;
private readonly Lazy<TileLayer<T>?> _smallerLazy;
public int Index { get; init; }
public T Zero { get; init; } = default!;
public T TileSize { get; init; } = default!;
public int TileSizeMultiplier { get; init; } = 1;
public TileLayer<T>? Larger => _largerLazy.Value;
public TileLayer<T>? Smaller => _smallerLazy.Value;
public TileStack<T> Stack { get; init; } = default!;
public Arithmetics<T> Arithmetics { get; init; } = Arithmetics<T>.Default;
public TileLayer()
{
_largerLazy = new Lazy<TileLayer<T>?>(() => Index + 1 >= Stack.Layers.Length ? null : Stack.Layers[Index + 1]);
_smallerLazy = new Lazy<TileLayer<T>?>(() => Index <= 0 ? null : Stack.Layers[Index - 1]);
}
public bool TryGetTile(Range<T> range, out Tile<T> tile)
{
var a = Arithmetics;
var size = a.Subtract(range.End, range.Start);
if (EqualityComparer<T>.Default.Equals(size, TileSize)) {
var mod = a.Mod(a.Subtract(range.Start, Zero), TileSize);
if (EqualityComparer<T>.Default.Equals(mod, default!)) {
tile = new(range, this);
return true;
}
}
tile = default;
return false;
}
public Tile<T> GetTile(Range<T> range)
=> TryGetTile(range, out var tile)
? tile
: throw Errors.InvalidTileBoundaries(nameof(range));
public Tile<T> GetTile(T point)
{
var a = Arithmetics;
var tileIndex = a.DivNonNegativeRem(a.Subtract(point, Zero), TileSize, out _);
var start = a.MulAdd(TileSize, tileIndex, Zero);
var end = a.Add(start, TileSize);
return new(start, end, this);
}
public bool IsTile(Range<T> range)
=> TryGetTile(range, out _);
public void AssertIsTile(Range<T> range)
{
if (!TryGetTile(range, out _))
throw Errors.InvalidTileBoundaries(nameof(range));
}
public Tile<T>[] GetCoveringTiles(Range<T> range)
{
var tiles = ArrayBuffer<Tile<T>>.Lease(true);
try {
GetCoveringTiles(range, ref tiles);
return tiles.ToArray();
}
finally {
tiles.Release();
}
}
public Tile<T>[] GetOptimalCoveringTiles(Range<T> range)
{
var tiles = ArrayBuffer<Tile<T>>.Lease(true);
try {
GetOptimalCoveringTiles(range, ref tiles);
return tiles.ToArray();
}
finally {
tiles.Release();
}
}
// Private methods
private void GetCoveringTiles(Range<T> range, ref ArrayBuffer<Tile<T>> appendTo)
{
var c = Comparer<T>.Default;
var tile = GetTile(range.Start);
appendTo.Add(tile);
while (c.Compare(tile.End, range.End) < 0) {
tile = tile.Next();
appendTo.Add(tile);
}
}
private void GetOptimalCoveringTiles(Range<T> range, ref ArrayBuffer<Tile<T>> appendTo)
{
if (Smaller == null) {
GetCoveringTiles(range, ref appendTo);
return;
}
var tiles = ArrayBuffer<Tile<T>>.Lease(true);
try {
GetCoveringTiles(range, ref tiles);
if (tiles.Count == 1) {
var tile = tiles[0];
if (tile.IsLeftSubdivisionUseful(range.Start) || tile.IsRightSubdivisionUseful(range.End))
Smaller.GetOptimalCoveringTiles(range, ref appendTo);
else
appendTo.Add(tile);
}
else {
var midTiles = tiles.Span;
var firstTile = tiles[0];
var lastTile = tiles[^1];
if (firstTile.IsLeftSubdivisionUseful(range.Start)) {
// Left side can be subdivided
var leftRange = new Range<T>(range.Start, firstTile.End);
Smaller.GetOptimalCoveringTiles(leftRange, ref appendTo);
midTiles = midTiles[1..];
}
if (lastTile.IsRightSubdivisionUseful(range.End)) {
// Right side can be subdivided
midTiles = midTiles[..^1];
appendTo.AddSpan(midTiles);
var rightRange = new Range<T>(lastTile.Start, range.End);
Smaller.GetOptimalCoveringTiles(rightRange, ref appendTo);
}
else
appendTo.AddSpan(midTiles);
}
}
finally {
tiles.Release();
}
}
}
|
namespace _03.Parse_Tags
{
using System;
public class ParseTags
{
public static void Main()
{
string input = Console.ReadLine();
string openTag = "<upcase>";
string closeTag = "</upcase>";
int tagStartIndex = input.IndexOf(openTag);
while (tagStartIndex != -1)
{
int tagEndIndex = input.IndexOf(closeTag);
if (tagEndIndex == -1)
{
break;
}
string textForChange = input.Substring(tagStartIndex, tagEndIndex - tagStartIndex + closeTag.Length);
string changed = textForChange.Replace(openTag, "")
.Replace(closeTag, "").ToUpper();
input = input.Replace(textForChange, changed);
tagStartIndex = input.IndexOf(openTag);
}
Console.WriteLine(input);
}
}
}
|
using System;
using Robust.Shared.Serialization;
namespace Content.Shared.Morgue
{
[Serializable, NetSerializable]
public enum MorgueVisuals
{
Open,
HasContents,
HasMob,
HasSoul,
}
[Serializable, NetSerializable]
public enum CrematoriumVisuals
{
Burning,
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication1.Models
{
public class LiveChatModel
{
public string DspMessage { get; set; }
public string DspName{get;set;}
public string ChannelUrl { get; set; }
public string ProfileImageUrl { get; set; }
public DateTime? ChatDateTime { get; set; }
public DateTime? CommentDateRaw { get; set; }
public bool IsEdited { get; set; }
public long? LikeCount { get; set; }
public string ParentId { get; set; }
public string Id { get; set; }
public bool IsChild { get; set; }
}
} |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos.Routing
{
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Common;
using Microsoft.Azure.Cosmos.Tracing;
using Microsoft.Azure.Cosmos.Tracing.TraceData;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Collections;
/// <summary>
/// Caches collection information.
/// </summary>
internal class ClientCollectionCache : CollectionCache
{
private readonly IStoreModel storeModel;
private readonly ICosmosAuthorizationTokenProvider tokenProvider;
private readonly IRetryPolicyFactory retryPolicy;
private readonly ISessionContainer sessionContainer;
public ClientCollectionCache(
ISessionContainer sessionContainer,
IStoreModel storeModel,
ICosmosAuthorizationTokenProvider tokenProvider,
IRetryPolicyFactory retryPolicy)
{
this.storeModel = storeModel ?? throw new ArgumentNullException("storeModel");
this.tokenProvider = tokenProvider;
this.retryPolicy = retryPolicy;
this.sessionContainer = sessionContainer;
}
protected override Task<ContainerProperties> GetByRidAsync(string apiVersion,
string collectionRid,
ITrace trace,
IClientSideRequestStatistics clientSideRequestStatistics,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
IDocumentClientRetryPolicy retryPolicyInstance = new ClearingSessionContainerClientRetryPolicy(
this.sessionContainer, this.retryPolicy.GetRequestPolicy());
return TaskHelper.InlineIfPossible(
() => this.ReadCollectionAsync(
PathsHelper.GeneratePath(ResourceType.Collection, collectionRid, false),
retryPolicyInstance,
trace,
clientSideRequestStatistics,
cancellationToken),
retryPolicyInstance,
cancellationToken);
}
protected override Task<ContainerProperties> GetByNameAsync(string apiVersion,
string resourceAddress,
ITrace trace,
IClientSideRequestStatistics clientSideRequestStatistics,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
IDocumentClientRetryPolicy retryPolicyInstance = new ClearingSessionContainerClientRetryPolicy(
this.sessionContainer, this.retryPolicy.GetRequestPolicy());
return TaskHelper.InlineIfPossible(
() => this.ReadCollectionAsync(
resourceAddress, retryPolicyInstance, trace, clientSideRequestStatistics, cancellationToken),
retryPolicyInstance,
cancellationToken);
}
internal override Task<ContainerProperties> ResolveByNameAsync(
string apiVersion,
string resourceAddress,
bool forceRefesh,
ITrace trace,
IClientSideRequestStatistics clientSideRequestStatistics,
CancellationToken cancellationToken)
{
if (forceRefesh && this.sessionContainer != null)
{
return TaskHelper.InlineIfPossible(
async () =>
{
string oldRid = (await base.ResolveByNameAsync(
apiVersion,
resourceAddress,
forceRefesh: false,
trace,
clientSideRequestStatistics,
cancellationToken))?.ResourceId;
ContainerProperties propertiesAfterRefresh = await base.ResolveByNameAsync(
apiVersion,
resourceAddress,
forceRefesh,
trace,
clientSideRequestStatistics,
cancellationToken);
if (oldRid != null && oldRid != propertiesAfterRefresh?.ResourceId)
{
string resourceFullName = PathsHelper.GetCollectionPath(resourceAddress);
this.sessionContainer.ClearTokenByCollectionFullname(resourceFullName);
}
return propertiesAfterRefresh;
},
retryPolicy: null,
cancellationToken);
}
return TaskHelper.InlineIfPossible(
() => base.ResolveByNameAsync(
apiVersion, resourceAddress, forceRefesh, trace, clientSideRequestStatistics, cancellationToken),
retryPolicy: null,
cancellationToken);
}
public override Task<ContainerProperties> ResolveCollectionAsync(
DocumentServiceRequest request, CancellationToken cancellationToken, ITrace trace)
{
return TaskHelper.InlineIfPossible(
() => this.ResolveCollectionWithSessionContainerCleanupAsync(
request,
() => base.ResolveCollectionAsync(request, cancellationToken, trace)),
retryPolicy: null,
cancellationToken);
}
public override Task<ContainerProperties> ResolveCollectionAsync(
DocumentServiceRequest request, TimeSpan refreshAfter, CancellationToken cancellationToken, ITrace trace)
{
return TaskHelper.InlineIfPossible(
() => this.ResolveCollectionWithSessionContainerCleanupAsync(
request,
() => base.ResolveCollectionAsync(request, refreshAfter, cancellationToken, trace)),
retryPolicy: null,
cancellationToken);
}
private async Task<ContainerProperties> ResolveCollectionWithSessionContainerCleanupAsync(
DocumentServiceRequest request,
Func<Task<ContainerProperties>> resolveContainerProvider)
{
string previouslyResolvedCollectionRid = request?.RequestContext?.ResolvedCollectionRid;
ContainerProperties properties = await resolveContainerProvider();
if (this.sessionContainer != null &&
previouslyResolvedCollectionRid != null &&
previouslyResolvedCollectionRid != properties.ResourceId)
{
this.sessionContainer.ClearTokenByResourceId(previouslyResolvedCollectionRid);
}
return properties;
}
private async Task<ContainerProperties> ReadCollectionAsync(
string collectionLink,
IDocumentClientRetryPolicy retryPolicyInstance,
ITrace trace,
IClientSideRequestStatistics clientSideRequestStatistics,
CancellationToken cancellationToken)
{
using (ITrace childTrace = trace.StartChild("Read Collection", TraceComponent.Transport, TraceLevel.Info))
{
cancellationToken.ThrowIfCancellationRequested();
RequestNameValueCollection headers = new RequestNameValueCollection();
using (DocumentServiceRequest request = DocumentServiceRequest.Create(
OperationType.Read,
ResourceType.Collection,
collectionLink,
AuthorizationTokenType.PrimaryMasterKey,
headers))
{
headers.XDate = DateTime.UtcNow.ToString("r");
request.RequestContext.ClientRequestStatistics =
clientSideRequestStatistics ?? new ClientSideRequestStatisticsTraceDatum(DateTime.UtcNow);
if (clientSideRequestStatistics == null)
{
childTrace.AddDatum(
"Client Side Request Stats",
request.RequestContext.ClientRequestStatistics);
}
string authorizationToken = await this.tokenProvider.GetUserAuthorizationTokenAsync(
request.ResourceAddress,
PathsHelper.GetResourcePath(request.ResourceType),
HttpConstants.HttpMethods.Get,
request.Headers,
AuthorizationTokenType.PrimaryMasterKey,
childTrace);
headers.Authorization = authorizationToken;
using (new ActivityScope(Guid.NewGuid()))
{
retryPolicyInstance?.OnBeforeSendRequest(request);
try
{
using (DocumentServiceResponse response =
await this.storeModel.ProcessMessageAsync(request))
{
return CosmosResource.FromStream<ContainerProperties>(response);
}
}
catch (DocumentClientException ex)
{
childTrace.AddDatum("Exception Message", ex.Message);
throw;
}
}
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Spectre.Console;
namespace Generator.Commands
{
public sealed class AsciiCastInput : IAnsiConsoleInput
{
private readonly Queue<(ConsoleKeyInfo?, int)> _input;
private readonly Random _random = new Random();
public AsciiCastInput()
{
_input = new Queue<(ConsoleKeyInfo?, int)>();
}
public void PushText(string input, int keypressDelayMs)
{
if (input is null)
{
throw new ArgumentNullException(nameof(input));
}
foreach (var character in input)
{
PushCharacter(character, keypressDelayMs);
}
}
public void PushTextWithEnter(string input, int keypressDelayMs)
{
PushText(input, keypressDelayMs);
PushKey(ConsoleKey.Enter, keypressDelayMs);
}
public void PushCharacter(char input, int keypressDelayMs)
{
var delay = keypressDelayMs + _random.Next((int)(keypressDelayMs * -.2), (int)(keypressDelayMs * .2));
switch (input)
{
case '↑':
PushKey(ConsoleKey.UpArrow, keypressDelayMs);
break;
case '↓':
PushKey(ConsoleKey.DownArrow, keypressDelayMs);
break;
case '↲':
PushKey(ConsoleKey.Enter, keypressDelayMs);
break;
case '¦':
_input.Enqueue((null, delay));
break;
default:
var control = char.IsUpper(input);
_input.Enqueue((new ConsoleKeyInfo(input, (ConsoleKey)input, false, false, control), delay));
break;
}
}
public void PushKey(ConsoleKey input, int keypressDelayMs)
{
var delay = keypressDelayMs + _random.Next((int)(keypressDelayMs * -.2), (int)(keypressDelayMs * .2));
_input.Enqueue((new ConsoleKeyInfo((char)input, input, false, false, false), delay));
}
public bool IsKeyAvailable()
{
return _input.Count > 0;
}
public ConsoleKeyInfo? ReadKey(bool intercept)
{
if (_input.Count == 0)
{
throw new InvalidOperationException("No input available.");
}
var result = _input.Dequeue();
Thread.Sleep(result.Item2);
return result.Item1;
}
public Task<ConsoleKeyInfo?> ReadKeyAsync(bool intercept, CancellationToken cancellationToken)
{
return Task.FromResult(ReadKey(intercept));
}
}
}
|
namespace Features.Account.Manage;
public class MfaDisable
{
public class Command : IRequest<Result> { }
public class Result : BaseResult { }
public class CommandHandler : IRequestHandler<Command, Result>
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly ClaimsPrincipal _user;
public CommandHandler(UserManager<ApplicationUser> userManager, IUserAccessor user)
{
_userManager = userManager;
_user = user.User;
}
public async Task<Result> Handle(Command request, CancellationToken cancellationToken)
{
var user = await _userManager.GetUserAsync(_user);
var disableMfaResult = await _userManager.SetTwoFactorEnabledAsync(user, false);
if (!disableMfaResult.Succeeded)
{
return new Result().Error(
$"Unexpected error occurred disabling 2FA for user with ID '{_userManager.GetUserId(_user)}'.");
}
return new Result().Success(
"Mfa has been disabled. You can reenable 2fa when you setup an authenticator app");
}
}
}
|
using System.ComponentModel.DataAnnotations;
namespace Shopper.Web.ViewModel
{
public class RegistrationViewModel
{
[EmailAddress]
[Required(ErrorMessage = "Email is required")]
public string CustomerEmail { get; set; }
[Required(ErrorMessage = "Last name is required")]
public string CustomerLastName { get; set; }
[Required(ErrorMessage = "First name is required")]
public string CustomerFirstName { get; set; }
[Required(ErrorMessage = "Valid Contact number is required")]
public int CustomerContactNumber { get; set; }
[Required(ErrorMessage = "Valid Address Line is required")]
public string AddressLineOne { get; set; }
public string AddressLineTwo { get; set; }
[Required(ErrorMessage = "Valid City is required")]
public string City { get; set; }
[Required(ErrorMessage = "Valid Postal Code is required")]
public int PostalCode { get; set; }
[Required(ErrorMessage = "Valid Password is required")]
[DataType(DataType.Password)]
public string CustomerPassword { get; set; }
[Required(ErrorMessage = "Valid Password confirmation is required")]
[DataType(DataType.Password)]
[Compare("CustomerPassword", ErrorMessage = "Password did not matched")]
public string CustomerRetypedPassword { get; set; }
}
}
|
using System.Collections.Generic;
using System.IO;
namespace Disunity.Store.Storage.InMemory {
public class InMemoryUploadStream : UploadStream {
private readonly InMemoryStorageProvider _storageProvider;
private readonly string _filename;
private readonly Dictionary<string, string> _fileInfo;
private readonly MemoryStream _buffer = new MemoryStream();
private StorageFile _storedFile;
public override bool CanWrite => _storedFile == null;
public InMemoryUploadStream(InMemoryStorageProvider storageProvider, string filename,
Dictionary<string, string> fileInfo) {
_storageProvider = storageProvider;
_filename = filename;
_fileInfo = fileInfo;
}
public override void Flush() { }
public override void Write(byte[] buffer, int offset, int count) {
_buffer.Write(buffer, offset, count);
}
public override void WriteByte(byte value) {
_buffer.WriteByte(value);
}
public override StorageFile FinalizeUpload() {
_buffer.Seek(0, SeekOrigin.Begin);
return _storedFile ?? (_storedFile = _storageProvider.UploadFile(_buffer, _filename, _fileInfo).Result);
}
protected override void Dispose(bool disposing) {
base.Dispose(disposing);
if (!disposing) {
return;
}
FinalizeUpload();
_buffer.Dispose();
}
}
} |
using AzureML.Contract;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace AzureML.PowerShell
{
[Cmdlet(VerbsCommon.Get, "AmlAnnotation")]
public class GetAnnotation : AzureMLPsCmdlet
{
[Parameter(Mandatory = true)]
public string ExperimentId { get; set; }
protected override void ProcessRecord()
{
if (string.IsNullOrEmpty(ExperimentId))
{
WriteWarning("ExperimentId must be specified.");
return;
}
WriteObject(Sdk.GetAnnotation(GetWorkspaceSetting(), ExperimentId), true);
}
}
} |
using System;
using System.IO;
namespace Pathfinding.Ionic.BZip2
{
internal class BitWriter
{
private uint accumulator;
private int nAccumulatedBits;
private Stream output;
private int totalBytesWrittenOut;
public byte RemainingBits
{
get
{
return (byte)(this.accumulator >> 32 - this.nAccumulatedBits & 255u);
}
}
public int NumRemainingBits
{
get
{
return this.nAccumulatedBits;
}
}
public int TotalBytesWrittenOut
{
get
{
return this.totalBytesWrittenOut;
}
}
public BitWriter(Stream s)
{
this.output = s;
}
public void Reset()
{
this.accumulator = 0u;
this.nAccumulatedBits = 0;
this.totalBytesWrittenOut = 0;
this.output.Seek(0L, SeekOrigin.Begin);
this.output.SetLength(0L);
}
public void WriteBits(int nbits, uint value)
{
int i = this.nAccumulatedBits;
uint num = this.accumulator;
while (i >= 8)
{
this.output.WriteByte((byte)(num >> 24 & 255u));
this.totalBytesWrittenOut++;
num <<= 8;
i -= 8;
}
this.accumulator = (num | value << 32 - i - nbits);
this.nAccumulatedBits = i + nbits;
}
public void WriteByte(byte b)
{
this.WriteBits(8, (uint)b);
}
public void WriteInt(uint u)
{
this.WriteBits(8, u >> 24 & 255u);
this.WriteBits(8, u >> 16 & 255u);
this.WriteBits(8, u >> 8 & 255u);
this.WriteBits(8, u & 255u);
}
public void Flush()
{
this.WriteBits(0, 0u);
}
public void FinishAndPad()
{
this.Flush();
if (this.NumRemainingBits > 0)
{
byte value = (byte)(this.accumulator >> 24 & 255u);
this.output.WriteByte(value);
this.totalBytesWrittenOut++;
}
}
}
}
|
abstract public class RifleDecorator : IRifle
{
protected IRifle m_DecoaratedRifle;
public RifleDecorator(IRifle rifle)
{
m_DecoaratedRifle = rifle;
}
public virtual float GetAccuracy()
{
return m_DecoaratedRifle.GetAccuracy();
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Nito.Collections;
namespace AdventOfCode
{
public static class Extensions
{
public static string ReadInput(this string path) =>
File.ReadAllText(path);
public static IEnumerable<string> ReadLines(this string path) =>
File.ReadLines(path);
public static IEnumerable<int> ReadLinesAsInt(this string path) =>
File.ReadLines(path).Select(int.Parse);
public static IEnumerable<int> SplitAsInt(this string input, string separator = ", ") =>
input.Split(separator, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse);
public static IEnumerable<T> Cyclic<T>(this IEnumerable<T> source)
{
var arr = source.ToArray();
var i = 0;
while (true)
{
yield return arr[i % arr.Length];
i++;
}
// ReSharper disable once IteratorNeverReturns
}
public static IEnumerable<(int X, int Y)> Square(int x, int y, int width, int height) =>
x.To(width).Pairs(y.To(height));
public static IEnumerable<(T1 A, T2 B)> Pairs<T1, T2>(this IEnumerable<T1> source, IEnumerable<T2> other) =>
source.SelectMany(x => other.Select(y => (x, y)));
public static IEnumerable<int> To(this int from, int max) =>
Enumerable.Range(from, max);
public static void Rotate<T>(this Deque<T> source, long offset)
{
if (offset < 0)
{
offset = Math.Abs(offset);
for (long i = 0; i < offset; i++)
source.AddToFront(source.RemoveFromBack());
}
else if (offset > 0)
for (long i = 0; i < offset; i++)
source.AddToBack(source.RemoveFromFront());
}
public static IEnumerable<IEnumerable<T1>> PartitionBy<T1>(this IEnumerable<T1> source, int width)
{
var entries = source.LongCount() / width;
for (var i = 0; i < entries; i++)
yield return source.Skip(i * width).Take(width);
}
}
}
|
//------------------------------------------------------------------------------
// <copyright file="XmlDocumentValidator.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">Microsoft</owner>
//------------------------------------------------------------------------------
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Globalization;
using System.Security;
using System.Security.Policy;
using System.Security.Permissions;
using System.Reflection;
using System.Runtime.Versioning;
namespace System.Xml {
internal sealed class DocumentSchemaValidator : IXmlNamespaceResolver {
XmlSchemaValidator validator;
XmlSchemaSet schemas;
XmlNamespaceManager nsManager;
XmlNameTable nameTable;
//Attributes
ArrayList defaultAttributes;
XmlValueGetter nodeValueGetter;
XmlSchemaInfo attributeSchemaInfo;
//Element PSVI
XmlSchemaInfo schemaInfo;
//Event Handler
ValidationEventHandler eventHandler;
ValidationEventHandler internalEventHandler;
//Store nodes
XmlNode startNode;
XmlNode currentNode;
XmlDocument document;
//List of nodes for partial validation tree walk
XmlNode[] nodeSequenceToValidate;
bool isPartialTreeValid;
bool psviAugmentation;
bool isValid;
//To avoid SchemaNames creation
private string NsXmlNs;
private string NsXsi;
private string XsiType;
private string XsiNil;
public DocumentSchemaValidator(XmlDocument ownerDocument, XmlSchemaSet schemas, ValidationEventHandler eventHandler) {
this.schemas = schemas;
this.eventHandler = eventHandler;
document = ownerDocument;
this.internalEventHandler = new ValidationEventHandler(InternalValidationCallBack);
this.nameTable = document.NameTable;
nsManager = new XmlNamespaceManager(nameTable);
Debug.Assert(schemas != null && schemas.Count > 0);
nodeValueGetter = new XmlValueGetter(GetNodeValue);
psviAugmentation = true;
//Add common strings to be compared to NameTable
NsXmlNs = nameTable.Add(XmlReservedNs.NsXmlNs);
NsXsi = nameTable.Add(XmlReservedNs.NsXsi);
XsiType = nameTable.Add("type");
XsiNil = nameTable.Add("nil");
}
public bool PsviAugmentation {
get { return psviAugmentation; }
set { psviAugmentation = value; }
}
public bool Validate(XmlNode nodeToValidate) {
XmlSchemaObject partialValidationType = null;
XmlSchemaValidationFlags validationFlags = XmlSchemaValidationFlags.AllowXmlAttributes;
Debug.Assert(nodeToValidate.SchemaInfo != null);
startNode = nodeToValidate;
switch (nodeToValidate.NodeType) {
case XmlNodeType.Document:
validationFlags |= XmlSchemaValidationFlags.ProcessIdentityConstraints;
break;
case XmlNodeType.DocumentFragment:
break;
case XmlNodeType.Element: //Validate children of this element
IXmlSchemaInfo schemaInfo = nodeToValidate.SchemaInfo;
XmlSchemaElement schemaElement = schemaInfo.SchemaElement;
if (schemaElement != null) {
if (!schemaElement.RefName.IsEmpty) { //If it is element ref,
partialValidationType = schemas.GlobalElements[schemaElement.QualifiedName]; //Get Global element with correct Nillable, Default etc
}
else { //local element
partialValidationType = schemaElement;
}
//Verify that if there was xsi:type, the schemaElement returned has the correct type set
Debug.Assert(schemaElement.ElementSchemaType == schemaInfo.SchemaType);
}
else { //Can be an element that matched xs:any and had xsi:type
partialValidationType = schemaInfo.SchemaType;
if (partialValidationType == null) { //Validated against xs:any with pc= lax or skip or undeclared / not validated element
if (nodeToValidate.ParentNode.NodeType == XmlNodeType.Document) {
//If this is the documentElement and it has not been validated at all
nodeToValidate = nodeToValidate.ParentNode;
}
else {
partialValidationType = FindSchemaInfo(nodeToValidate as XmlElement);
if (partialValidationType == null) {
throw new XmlSchemaValidationException(Res.XmlDocument_NoNodeSchemaInfo, null, nodeToValidate);
}
}
}
}
break;
case XmlNodeType.Attribute:
if (nodeToValidate.XPNodeType == XPathNodeType.Namespace) goto default;
partialValidationType = nodeToValidate.SchemaInfo.SchemaAttribute;
if (partialValidationType == null) { //Validated against xs:anyAttribute with pc = lax or skip / undeclared attribute
partialValidationType = FindSchemaInfo(nodeToValidate as XmlAttribute);
if (partialValidationType == null) {
throw new XmlSchemaValidationException(Res.XmlDocument_NoNodeSchemaInfo, null, nodeToValidate);
}
}
break;
default:
throw new InvalidOperationException(Res.GetString(Res.XmlDocument_ValidateInvalidNodeType, null));
}
isValid = true;
CreateValidator(partialValidationType, validationFlags);
if (psviAugmentation) {
if (schemaInfo == null) { //Might have created it during FindSchemaInfo
schemaInfo = new XmlSchemaInfo();
}
attributeSchemaInfo = new XmlSchemaInfo();
}
ValidateNode(nodeToValidate);
validator.EndValidation();
return isValid;
}
public IDictionary<string,string> GetNamespacesInScope(XmlNamespaceScope scope) {
IDictionary<string,string> dictionary = nsManager.GetNamespacesInScope(scope);
if (scope != XmlNamespaceScope.Local) {
XmlNode node = startNode;
while (node != null) {
switch (node.NodeType) {
case XmlNodeType.Element:
XmlElement elem = (XmlElement)node;
if (elem.HasAttributes) {
XmlAttributeCollection attrs = elem.Attributes;
for (int i = 0; i < attrs.Count; i++) {
XmlAttribute attr = attrs[i];
if (Ref.Equal(attr.NamespaceURI, document.strReservedXmlns)) {
if (attr.Prefix.Length == 0) {
// xmlns='' declaration
if (!dictionary.ContainsKey(string.Empty)) {
dictionary.Add(string.Empty, attr.Value);
}
}
else {
// xmlns:prefix='' declaration
if (!dictionary.ContainsKey(attr.LocalName)) {
dictionary.Add(attr.LocalName, attr.Value);
}
}
}
}
}
node = node.ParentNode;
break;
case XmlNodeType.Attribute:
node = ((XmlAttribute)node).OwnerElement;
break;
default:
node = node.ParentNode;
break;
}
}
}
return dictionary;
}
public string LookupNamespace(string prefix) {
string namespaceName = nsManager.LookupNamespace(prefix);
if (namespaceName == null) {
namespaceName = startNode.GetNamespaceOfPrefixStrict(prefix);
}
return namespaceName;
}
public string LookupPrefix(string namespaceName) {
string prefix = nsManager.LookupPrefix(namespaceName);
if (prefix == null) {
prefix = startNode.GetPrefixOfNamespaceStrict(namespaceName);
}
return prefix;
}
private IXmlNamespaceResolver NamespaceResolver {
get {
if ((object)startNode == (object)document) {
return nsManager;
}
return this;
}
}
private void CreateValidator(XmlSchemaObject partialValidationType, XmlSchemaValidationFlags validationFlags) {
validator = new XmlSchemaValidator(nameTable, schemas, NamespaceResolver, validationFlags);
validator.SourceUri = XmlConvert.ToUri(document.BaseURI);
validator.XmlResolver = null;
validator.ValidationEventHandler += internalEventHandler;
validator.ValidationEventSender = this;
if (partialValidationType != null) {
validator.Initialize(partialValidationType);
}
else {
validator.Initialize();
}
}
private void ValidateNode(XmlNode node) {
currentNode = node;
switch (currentNode.NodeType) {
case XmlNodeType.Document:
XmlElement docElem = ((XmlDocument)node).DocumentElement;
if (docElem == null) {
throw new InvalidOperationException(Res.GetString(Res.Xml_InvalidXmlDocument, Res.GetString(Res.Xdom_NoRootEle)));
}
ValidateNode(docElem);
break;
case XmlNodeType.DocumentFragment:
case XmlNodeType.EntityReference:
for (XmlNode child = node.FirstChild; child != null; child = child.NextSibling) {
ValidateNode(child);
}
break;
case XmlNodeType.Element:
ValidateElement();
break;
case XmlNodeType.Attribute: //Top-level attribute
XmlAttribute attr = currentNode as XmlAttribute;
validator.ValidateAttribute(attr.LocalName, attr.NamespaceURI, nodeValueGetter, attributeSchemaInfo);
if (psviAugmentation) {
attr.XmlName = document.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, attributeSchemaInfo);
}
break;
case XmlNodeType.Text:
validator.ValidateText(nodeValueGetter);
break;
case XmlNodeType.CDATA:
validator.ValidateText(nodeValueGetter);
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
validator.ValidateWhitespace(nodeValueGetter);
break;
case XmlNodeType.Comment:
case XmlNodeType.ProcessingInstruction:
break;
default:
throw new InvalidOperationException( Res.GetString( Res.Xml_UnexpectedNodeType, new string[]{ currentNode.NodeType.ToString() } ) );
}
}
// SxS: This function calls ValidateElement on XmlSchemaValidator which is annotated with ResourceExposure attribute.
// Since the resource names passed to ValidateElement method are null and the function does not expose any resources
// it is fine to suppress the SxS warning.
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
[ResourceExposure(ResourceScope.None)]
private void ValidateElement() {
nsManager.PushScope();
XmlElement elementNode = currentNode as XmlElement;
Debug.Assert(elementNode != null);
XmlAttributeCollection attributes = elementNode.Attributes;
XmlAttribute attr = null;
//Find Xsi attributes that need to be processed before validating the element
string xsiNil = null;
string xsiType = null;
for (int i = 0; i < attributes.Count; i++) {
attr = attributes[i];
string objectNs = attr.NamespaceURI;
string objectName = attr.LocalName;
Debug.Assert(nameTable.Get(attr.NamespaceURI) != null);
Debug.Assert(nameTable.Get(attr.LocalName) != null);
if (Ref.Equal(objectNs, NsXsi)) {
if (Ref.Equal(objectName, XsiType)) {
xsiType = attr.Value;
}
else if (Ref.Equal(objectName, XsiNil)) {
xsiNil = attr.Value;
}
}
else if (Ref.Equal(objectNs,NsXmlNs)) {
nsManager.AddNamespace(attr.Prefix.Length == 0 ? string.Empty : attr.LocalName, attr.Value);
}
}
validator.ValidateElement(elementNode.LocalName, elementNode.NamespaceURI, schemaInfo, xsiType, xsiNil, null, null);
ValidateAttributes(elementNode);
validator.ValidateEndOfAttributes(schemaInfo);
//If element has children, drill down
for (XmlNode child = elementNode.FirstChild; child != null; child = child.NextSibling) {
ValidateNode(child);
}
//Validate end of element
currentNode = elementNode; //Reset current Node for validation call back
validator.ValidateEndElement(schemaInfo);
//Get XmlName, as memberType / validity might be set now
if (psviAugmentation) {
elementNode.XmlName = document.AddXmlName(elementNode.Prefix, elementNode.LocalName, elementNode.NamespaceURI, schemaInfo);
if (schemaInfo.IsDefault) { //the element has a default value
XmlText textNode = document.CreateTextNode(schemaInfo.SchemaElement.ElementDecl.DefaultValueRaw);
elementNode.AppendChild(textNode);
}
}
nsManager.PopScope(); //Pop current namespace scope
}
private void ValidateAttributes(XmlElement elementNode) {
XmlAttributeCollection attributes = elementNode.Attributes;
XmlAttribute attr = null;
for (int i = 0; i < attributes.Count; i++) {
attr = attributes[i];
currentNode = attr; //For nodeValueGetter to pick up the right attribute value
if (Ref.Equal(attr.NamespaceURI,NsXmlNs)) { //Do not validate namespace decls
continue;
}
validator.ValidateAttribute(attr.LocalName, attr.NamespaceURI, nodeValueGetter, attributeSchemaInfo);
if (psviAugmentation) {
attr.XmlName = document.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, attributeSchemaInfo);
}
}
if (psviAugmentation) {
//Add default attributes to the attributes collection
if (defaultAttributes == null) {
defaultAttributes = new ArrayList();
}
else {
defaultAttributes.Clear();
}
validator.GetUnspecifiedDefaultAttributes(defaultAttributes);
XmlSchemaAttribute schemaAttribute = null;
XmlQualifiedName attrQName;
attr = null;
for (int i = 0; i < defaultAttributes.Count; i++) {
schemaAttribute = defaultAttributes[i] as XmlSchemaAttribute;
attrQName = schemaAttribute.QualifiedName;
Debug.Assert(schemaAttribute != null);
attr = document.CreateDefaultAttribute(GetDefaultPrefix(attrQName.Namespace), attrQName.Name, attrQName.Namespace);
SetDefaultAttributeSchemaInfo(schemaAttribute);
attr.XmlName = document.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, attributeSchemaInfo);
attr.AppendChild(document.CreateTextNode(schemaAttribute.AttDef.DefaultValueRaw));
attributes.Append(attr);
XmlUnspecifiedAttribute defAttr = attr as XmlUnspecifiedAttribute;
if (defAttr != null) {
defAttr.SetSpecified(false);
}
}
}
}
private void SetDefaultAttributeSchemaInfo(XmlSchemaAttribute schemaAttribute) {
Debug.Assert(attributeSchemaInfo != null);
attributeSchemaInfo.Clear();
attributeSchemaInfo.IsDefault = true;
attributeSchemaInfo.IsNil = false;
attributeSchemaInfo.SchemaType = schemaAttribute.AttributeSchemaType;
attributeSchemaInfo.SchemaAttribute = schemaAttribute;
//Get memberType for default attribute
SchemaAttDef attributeDef = schemaAttribute.AttDef;
if (attributeDef.Datatype.Variety == XmlSchemaDatatypeVariety.Union) {
XsdSimpleValue simpleValue = attributeDef.DefaultValueTyped as XsdSimpleValue;
Debug.Assert(simpleValue != null);
attributeSchemaInfo.MemberType = simpleValue.XmlType;
}
attributeSchemaInfo.Validity = XmlSchemaValidity.Valid;
}
private string GetDefaultPrefix(string attributeNS) {
IDictionary<string,string> namespaceDecls = NamespaceResolver.GetNamespacesInScope(XmlNamespaceScope.All);
string defaultPrefix = null;
string defaultNS;
attributeNS = nameTable.Add(attributeNS); //atomize ns
foreach (KeyValuePair<string,string> pair in namespaceDecls) {
defaultNS = nameTable.Add(pair.Value);
if (object.ReferenceEquals(defaultNS, attributeNS)) {
defaultPrefix = pair.Key;
if (defaultPrefix.Length != 0) { //Locate first non-empty prefix
return defaultPrefix;
}
}
}
return defaultPrefix;
}
private object GetNodeValue() {
return currentNode.Value;
}
//Code for finding type during partial validation
private XmlSchemaObject FindSchemaInfo(XmlElement elementToValidate) {
isPartialTreeValid = true;
Debug.Assert(elementToValidate.ParentNode.NodeType != XmlNodeType.Document); //Handle if it is the documentElement seperately
//Create nodelist to navigate down again
XmlNode currentNode = elementToValidate;
IXmlSchemaInfo parentSchemaInfo = null;
int nodeIndex = 0;
//Check common case of parent node first
XmlNode parentNode = currentNode.ParentNode;
do {
parentSchemaInfo = parentNode.SchemaInfo;
if (parentSchemaInfo.SchemaElement != null || parentSchemaInfo.SchemaType != null) {
break; //Found ancestor with schemaInfo
}
CheckNodeSequenceCapacity(nodeIndex);
nodeSequenceToValidate[nodeIndex++] = parentNode;
parentNode = parentNode.ParentNode;
} while (parentNode != null);
if (parentNode == null) { //Did not find any type info all the way to the root, currentNode is Document || DocumentFragment
nodeIndex = nodeIndex - 1; //Subtract the one for document and set the node to null
nodeSequenceToValidate[nodeIndex] = null;
return GetTypeFromAncestors(elementToValidate, null, nodeIndex);
}
else {
//Start validating down from the parent or ancestor that has schema info and shallow validate all previous siblings
//to correctly ascertain particle for current node
CheckNodeSequenceCapacity(nodeIndex);
nodeSequenceToValidate[nodeIndex++] = parentNode;
XmlSchemaObject ancestorSchemaObject = parentSchemaInfo.SchemaElement;
if (ancestorSchemaObject == null) {
ancestorSchemaObject = parentSchemaInfo.SchemaType;
}
return GetTypeFromAncestors(elementToValidate, ancestorSchemaObject, nodeIndex);
}
}
/*private XmlSchemaElement GetTypeFromParent(XmlElement elementToValidate, XmlSchemaComplexType parentSchemaType) {
XmlQualifiedName elementName = new XmlQualifiedName(elementToValidate.LocalName, elementToValidate.NamespaceURI);
XmlSchemaElement elem = parentSchemaType.LocalElements[elementName] as XmlSchemaElement;
if (elem == null) { //Element not found as direct child of the content model. It might be invalid at this position or it might be a substitution member
SchemaInfo compiledSchemaInfo = schemas.CompiledInfo;
XmlSchemaElement memberElem = compiledSchemaInfo.GetElement(elementName);
if (memberElem != null) {
}
}
}*/
private void CheckNodeSequenceCapacity(int currentIndex) {
if (nodeSequenceToValidate == null) { //Normally users would call Validate one level down, this allows for 4
nodeSequenceToValidate = new XmlNode[4];
}
else if (currentIndex >= nodeSequenceToValidate.Length -1 ) { //reached capacity of array, Need to increase capacity to twice the initial
XmlNode[] newNodeSequence = new XmlNode[nodeSequenceToValidate.Length * 2];
Array.Copy(nodeSequenceToValidate, 0, newNodeSequence, 0, nodeSequenceToValidate.Length);
nodeSequenceToValidate = newNodeSequence;
}
}
private XmlSchemaAttribute FindSchemaInfo(XmlAttribute attributeToValidate) {
XmlElement parentElement = attributeToValidate.OwnerElement;
XmlSchemaObject schemaObject = FindSchemaInfo(parentElement);
XmlSchemaComplexType elementSchemaType = GetComplexType(schemaObject);
if (elementSchemaType == null) {
return null;
}
XmlQualifiedName attName = new XmlQualifiedName(attributeToValidate.LocalName, attributeToValidate.NamespaceURI);
XmlSchemaAttribute schemaAttribute = elementSchemaType.AttributeUses[attName] as XmlSchemaAttribute;
if (schemaAttribute == null) {
XmlSchemaAnyAttribute anyAttribute = elementSchemaType.AttributeWildcard;
if (anyAttribute != null) {
if (anyAttribute.NamespaceList.Allows(attName)){ //Match wildcard against global attribute
schemaAttribute = schemas.GlobalAttributes[attName] as XmlSchemaAttribute;
}
}
}
return schemaAttribute;
}
private XmlSchemaObject GetTypeFromAncestors(XmlElement elementToValidate, XmlSchemaObject ancestorType, int ancestorsCount) {
//schemaInfo is currentNode's schemaInfo
validator = CreateTypeFinderValidator(ancestorType);
schemaInfo = new XmlSchemaInfo();
//start at the ancestor to start validating
int startIndex = ancestorsCount - 1;
bool ancestorHasWildCard = AncestorTypeHasWildcard(ancestorType);
for (int i = startIndex; i >= 0; i--) {
XmlNode node = nodeSequenceToValidate[i];
XmlElement currentElement = node as XmlElement;
ValidateSingleElement(currentElement, false, schemaInfo);
if (!ancestorHasWildCard) { //store type if ancestor does not have wildcard in its content model
currentElement.XmlName = document.AddXmlName(currentElement.Prefix, currentElement.LocalName, currentElement.NamespaceURI, schemaInfo);
//update wildcard flag
ancestorHasWildCard = AncestorTypeHasWildcard(schemaInfo.SchemaElement);
}
validator.ValidateEndOfAttributes(null);
if (i > 0) {
ValidateChildrenTillNextAncestor(node, nodeSequenceToValidate[i - 1]);
}
else { //i == 0
ValidateChildrenTillNextAncestor(node, elementToValidate);
}
}
Debug.Assert(nodeSequenceToValidate[0] == elementToValidate.ParentNode);
//validate element whose type is needed,
ValidateSingleElement(elementToValidate, false, schemaInfo);
XmlSchemaObject schemaInfoFound = null;
if (schemaInfo.SchemaElement != null) {
schemaInfoFound = schemaInfo.SchemaElement;
}
else {
schemaInfoFound = schemaInfo.SchemaType;
}
if (schemaInfoFound == null) { //Detect if the node was validated lax or skip
if (validator.CurrentProcessContents == XmlSchemaContentProcessing.Skip) {
if (isPartialTreeValid) { //Then node assessed as skip; if there was error we turn processContents to skip as well. But this is not the same as validating as skip.
return XmlSchemaComplexType.AnyTypeSkip;
}
}
else if (validator.CurrentProcessContents == XmlSchemaContentProcessing.Lax) {
return XmlSchemaComplexType.AnyType;
}
}
return schemaInfoFound;
}
private bool AncestorTypeHasWildcard(XmlSchemaObject ancestorType) {
XmlSchemaComplexType ancestorSchemaType = GetComplexType(ancestorType);
if (ancestorType != null) {
return ancestorSchemaType.HasWildCard;
}
return false;
}
private XmlSchemaComplexType GetComplexType(XmlSchemaObject schemaObject) {
if (schemaObject == null) {
return null;
}
XmlSchemaElement schemaElement = schemaObject as XmlSchemaElement;
XmlSchemaComplexType complexType = null;
if (schemaElement != null) {
complexType = schemaElement.ElementSchemaType as XmlSchemaComplexType;
}
else {
complexType = schemaObject as XmlSchemaComplexType;
}
return complexType;
}
// SxS: This function calls ValidateElement on XmlSchemaValidator which is annotated with ResourceExposure attribute.
// Since the resource names passed to ValidateElement method are null and the function does not expose any resources
// it is fine to supress the warning.
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
[ResourceExposure(ResourceScope.None)]
private void ValidateSingleElement(XmlElement elementNode, bool skipToEnd, XmlSchemaInfo newSchemaInfo) {
nsManager.PushScope();
Debug.Assert(elementNode != null);
XmlAttributeCollection attributes = elementNode.Attributes;
XmlAttribute attr = null;
//Find Xsi attributes that need to be processed before validating the element
string xsiNil = null;
string xsiType = null;
for (int i = 0; i < attributes.Count; i++) {
attr = attributes[i];
string objectNs = attr.NamespaceURI;
string objectName = attr.LocalName;
Debug.Assert(nameTable.Get(attr.NamespaceURI) != null);
Debug.Assert(nameTable.Get(attr.LocalName) != null);
if (Ref.Equal(objectNs, NsXsi)) {
if (Ref.Equal(objectName, XsiType)) {
xsiType = attr.Value;
}
else if (Ref.Equal(objectName, XsiNil)) {
xsiNil = attr.Value;
}
}
else if (Ref.Equal(objectNs,NsXmlNs)) {
nsManager.AddNamespace(attr.Prefix.Length == 0 ? string.Empty : attr.LocalName, attr.Value);
}
}
validator.ValidateElement(elementNode.LocalName, elementNode.NamespaceURI, newSchemaInfo, xsiType, xsiNil, null, null);
//Validate end of element
if (skipToEnd) {
validator.ValidateEndOfAttributes(newSchemaInfo);
validator.SkipToEndElement(newSchemaInfo);
nsManager.PopScope(); //Pop current namespace scope
}
}
private void ValidateChildrenTillNextAncestor(XmlNode parentNode, XmlNode childToStopAt) {
XmlNode child;
for (child = parentNode.FirstChild; child != null; child = child.NextSibling) {
if (child == childToStopAt) {
break;
}
switch (child.NodeType) {
case XmlNodeType.EntityReference:
ValidateChildrenTillNextAncestor(child, childToStopAt);
break;
case XmlNodeType.Element: //Flat validation, do not drill down into children
ValidateSingleElement(child as XmlElement, true, null);
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
validator.ValidateText(child.Value);
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
validator.ValidateWhitespace(child.Value);
break;
case XmlNodeType.Comment:
case XmlNodeType.ProcessingInstruction:
break;
default:
throw new InvalidOperationException( Res.GetString( Res.Xml_UnexpectedNodeType, new string[]{ currentNode.NodeType.ToString() } ) );
}
}
Debug.Assert(child == childToStopAt);
}
private XmlSchemaValidator CreateTypeFinderValidator(XmlSchemaObject partialValidationType) {
XmlSchemaValidator findTypeValidator = new XmlSchemaValidator(document.NameTable, document.Schemas, this.nsManager, XmlSchemaValidationFlags.None);
findTypeValidator.ValidationEventHandler += new ValidationEventHandler(TypeFinderCallBack);
if (partialValidationType != null) {
findTypeValidator.Initialize(partialValidationType);
}
else { //If we walked up to the root and no schemaInfo was there, start validating from root
findTypeValidator.Initialize();
}
return findTypeValidator;
}
private void TypeFinderCallBack(object sender, ValidationEventArgs arg) {
if (arg.Severity == XmlSeverityType.Error) {
isPartialTreeValid = false;
}
}
private void InternalValidationCallBack(object sender, ValidationEventArgs arg) {
if (arg.Severity == XmlSeverityType.Error) {
isValid = false;
}
XmlSchemaValidationException ex = arg.Exception as XmlSchemaValidationException;
Debug.Assert(ex != null);
ex.SetSourceObject(currentNode);
if (this.eventHandler != null) { //Invoke user's event handler
eventHandler(sender, arg);
}
else if (arg.Severity == XmlSeverityType.Error) {
throw ex;
}
}
}
}
|
// Copyright (C) 2013 Dmitry Yakimenko (detunized@gmail.com).
// Licensed under the terms of the MIT license. See LICENCE for details.
namespace LastPass
{
public abstract class Ui
{
// TODO: Think about how to deal with the cancellation.
public enum SecondFactorMethod
{
GoogleAuth,
Yubikey,
// TODO: See which other methods should be supported.
}
public enum OutOfBandMethod
{
LastPassAuth,
Toopher,
Duo,
}
// Should always a valid string. Cancellation is not supported yet.
public abstract string ProvideSecondFactorPassword(SecondFactorMethod method);
// Should return immediately to allow the login process to continue. Once the OOB is approved
// or declined by the user the library will return the result or throw an error.
// Cancellation is not supported yet.
public abstract void AskToApproveOutOfBand(OutOfBandMethod method);
}
}
|
namespace Fluid.Roguelike.Dungeon
{
public class DungeonSpawnMeta
{
public DungeonRoomMeta SpawnRoom { get; set; }
}
public class DungeonSpawnNpcMeta : DungeonSpawnMeta
{
public string Race;
public string Name;
public int Count = 1;
}
} |
using MauiReactor.Internals;
namespace MauiReactor
{
public partial interface IToolbarItem
{
ToolbarItemOrder? Order { get; set; }
int? Priority { get; set; }
}
public partial class ToolbarItem<T> : IToolbarItem
{
ToolbarItemOrder? IToolbarItem.Order { get; set; }
int? IToolbarItem.Priority { get; set; }
partial void OnBeginUpdate()
{
Validate.EnsureNotNull(NativeControl);
var thisAsIToolbarItem = (IToolbarItem)this;
if (thisAsIToolbarItem.Order != null)
{
NativeControl.Order = thisAsIToolbarItem.Order.Value;
}
if (thisAsIToolbarItem.Priority != null)
{
NativeControl.Priority = thisAsIToolbarItem.Priority.Value;
}
}
}
public partial class ToolbarItem
{
public ToolbarItem(string text)
=> this.Text(text);
}
public static partial class ToolbarItemExtensions
{
public static T Order<T>(this T toolbarItem, ToolbarItemOrder order) where T : IToolbarItem
{
toolbarItem.Order = order;
return toolbarItem;
}
public static T Priority<T>(this T toolbarItem, int priority) where T : IToolbarItem
{
toolbarItem.Priority = priority;
return toolbarItem;
}
}
}
|
using System;
public class CustomService : ICustomService
{
public string GetTime()
{
return DateTime.UtcNow.ToString();
}
} |
using CompanySales.Model.Entity;
using CompanySales.Model.Parameter;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace CompanySales.DAL
{
public class EFUtility
{
/// <summary>
/// EF 查询 DataTable
/// </summary>
/// <param name="sql"></param>
/// <param name="sqlParams"></param>
/// <returns></returns>
public static DataTable GetDataTableBySql(string sql, SqlParameter[] sqlParams)
{
using (SaleContext db = new SaleContext())
{
IDbCommand cmd = db.Database.Connection.CreateCommand();
cmd.CommandText = sql;
if (sqlParams != null && sqlParams.Length > 0)
{
foreach (var item in sqlParams)
{
cmd.Parameters.Add(item);
}
}
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd as SqlCommand;
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
}
/// <summary>
/// 查询统计数目
/// </summary>
/// <param name="sql"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public static int GetCount(string sql, IEnumerable<SqlParameter> parameters)
{
// clone 为解决 【另一个 SqlParameterCollection 中已包含 SqlParameter。】问题
var paramClone = parameters.Select(t => ((ICloneable)t).Clone());
string sqlCount = ConvertSqlCount(sql);
using (SaleContext db = new SaleContext())
{
int count = db.Database.SqlQuery<int>(sqlCount, paramClone.ToArray())
.First();
return count;
}
}
/// <summary>
/// 执行查询
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public static List<T> GetList<T>(string sql, IEnumerable<SqlParameter> parameters, PageParameter pageInfo)
{
// clone 为解决 【另一个 SqlParameterCollection 中已包含 SqlParameter。】问题
var paramClone = parameters.Select(t => ((ICloneable)t).Clone());
using (SaleContext db = new SaleContext())
{
var query = db.Database
.SqlQuery<T>(sql, paramClone.ToArray())
.AsQueryable();
// 如果开启分页,则进行 skip take
if (pageInfo.IsPage)
{
query = query.Skip(pageInfo.Skip).Take(pageInfo.PageSize);
}
List<T> list = query.ToList();
return list;
}
}
/// 处理sql,将 select a,b,c from xxx 转换为 select count(1) from xxx结构
/// 快速统计数目
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
private static string ConvertSqlCount(string sql)
{
/* 正则替换,忽略大小写
\s空白符,\S非空白符,[\s\S]是任意字符
*/
Regex reg = new Regex(@"select[\s\S]*from", RegexOptions.IgnoreCase);
string sqlCount = reg.Replace(sql, "SELECT COUNT(1) FROM ");
return sqlCount;
}
}
}
|
namespace Microsoft.Bing.Commerce.Connectors.Core
{
/// <summary>
/// Describes the change type that happend to the data. Currently only support update.
/// </summary>
public enum DataOperation
{
/// <summary>
/// Represents an update that happened to the data, whether it's a new record or an update to an existing one.
/// </summary>
Update
}
}
|
using Xunit;
using System;
using System.Linq;
using Xunit.Abstractions;
using AdventOfCode2020.Day5;
namespace AdventOfCode2020.Tests.Day5
{
public class Day5Tests
{
private readonly ITestOutputHelper _testOutputHelper;
public Day5Tests(ITestOutputHelper testOutputHelper)
=> _testOutputHelper = testOutputHelper;
// 128 - rows
// 8 - columns
[InlineData("FBFBBFFRLR", 357)]
[InlineData("BFFFBBFRRR", 567)]
[InlineData("FFFBBBFRRR", 119)]
[InlineData("BBFFBBFRLL", 820)]
[Theory]
public void GivenSeatInput_CorrectSeatIsAssigned(string input, int expectedSeatId)
{
var seat = SeatFinder.FindSeat(input, 128, 8);
Assert.Equal(expectedSeatId, seat.GetSeatId());
}
[Fact]
public void SolvePuzzle1()
{
var puzzleInput = new FileReader()
.GetResource("AdventOfCode2020.Tests.Day5.PuzzleInput.txt");
var seats = puzzleInput.Split(Environment.NewLine)
.Select(line => SeatFinder.FindSeat(line, 128, 8))
.ToList();
var max = seats.Max(s => s.GetSeatId());
_testOutputHelper.WriteLine(max.ToString());
Assert.Equal(906, max);
}
[Fact]
public void SolvePuzzle2()
{
var puzzleInput = new FileReader()
.GetResource("AdventOfCode2020.Tests.Day5.PuzzleInput.txt");
var seats = puzzleInput.Split(Environment.NewLine)
.Select(line => SeatFinder.FindSeat(line, 128, 8))
.Select(seat => seat.GetSeatId())
.OrderBy(s => s)
.ToList();
var seatNumber = seats[0];
foreach (var seatNum in seats)
{
if (seatNum != seatNumber && seatNum != seatNumber + 1)
{
_testOutputHelper.WriteLine((seatNum - 1).ToString());
break;
}
else
{
seatNumber = seatNum;
}
}
}
}
} |
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
namespace SchOOD.Web.Controllers
{
[AllowAnonymous]
[Route("")]
public class HomeController : Controller
{
[AllowAnonymous]
[Route("login")]
public async Task Login(string returnUrl)
{
var props = new AuthenticationProperties { RedirectUri = returnUrl };
await HttpContext.ChallengeAsync("CAS", props);
}
}
}
|
/// <summary>Calculates the difference between 2 dates, and returns it as a formatted string.</summary>
/// <param name="startDate">The start date.</param>
/// <param name="endDate">The end date.</param>
/// <returns>The formatted string that represents the calculated difference.</returns>
public static string DateDifferenceToString(DateTime startDate, DateTime endDate)
{
int years, months, days;
DateDifference(startDate, endDate, out years, out months, out days);
return
((years != 0 ? years.ToString() + "y " : "") +
(months != 0 ? months.ToString() + "m " : "") +
(days != 0 ? days.ToString() + "d" : "")).TrimEnd();
} |
using System.Collections.Generic;
using System.CommandLine;
using System.CommandLine.Binding;
using System.CommandLine.Builder;
using System.CommandLine.Help;
using System.CommandLine.Invocation;
using System.CommandLine.IO;
using System.CommandLine.Parsing;
using System.Linq;
namespace J4JSoftware.CommandLine
{
public interface IRootObjectModel
{
IObjectBinder ObjectBinder { get; }
Command Command { get; }
ObjectModels ChildModels { get; }
ParseResult ParseResult { get; }
ParseStatus ParseStatus { get; }
bool Initialize(string[] args, IConsole console = null);
bool Initialize(string args, IConsole console = null);
bool Initialize(CommandLineBuilder builder, string[] args, IConsole console = null);
}
public interface IObjectModel : IRootObjectModel
{
void DefineBindings();
}
} |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace NPH.Models
{
public class WeatherCurrent
{
[JsonProperty("observation_time")]
public virtual string ObservationTime { get; set; }
[JsonProperty("temperature")]
public virtual float Temperature { get; set; }
[JsonProperty("weather_code")]
public virtual int WeatherCode { get; set; }
[JsonProperty("weather_icons")]
public virtual List<string> WeatherIcons { get; set; }
[JsonProperty("weather_descriptions")]
public virtual List<string> WeatherDescriptions { get; set; }
[JsonProperty("wind_speed")]
public virtual float WindSpeed { get; set; }
[JsonProperty("wind_degree")]
public virtual float WindDegree { get; set; }
[JsonProperty("wind_dir")]
public virtual string WindDir { get; set; }
[JsonProperty("pressure")]
public virtual float Pressure { get; set; }
[JsonProperty("precip")]
public virtual float Precip { get; set; }
[JsonProperty("humidity")]
public virtual float Humidity { get; set; }
[JsonProperty("cloudcover")]
public virtual float CloudCover { get; set; }
[JsonProperty("feelslike")]
public virtual float FeelsLike { get; set; }
[JsonProperty("uv_index")]
public virtual float UvIndex { get; set; }
[JsonProperty("visibility")]
public virtual float Visibility { get; set; }
[JsonProperty("is_day")]
public virtual string IsDay { get; set; }
}
}
|
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using Stride.Core.Mathematics;
using Stride.Engine;
using Stride.Input;
using Stride.Physics;
namespace CSharpIntermediate.Code
{
public class FirstPersonCamera : SyncScript
{
public float MouseSpeed = 0.6f;
public float MaxLookUpAngle = -50;
public float MaxLookDownAngle = 50;
public bool InvertMouseY = false;
private Entity firstPersonCameraPivot;
private Vector3 camRotation;
private bool isActive = false;
private Vector2 maxCameraAnglesRadians;
private CharacterComponent character;
public override void Start()
{
firstPersonCameraPivot = Entity.FindChild("CameraPivot");
// Convert the Max camera angles from Degress to Radions
maxCameraAnglesRadians = new Vector2(MathUtil.DegreesToRadians(MaxLookUpAngle), MathUtil.DegreesToRadians(MaxLookDownAngle));
// Store the initial camera rotation
camRotation = Entity.Transform.RotationEulerXYZ;
// Set the mouse to the middle of the screen
Input.MousePosition = new Vector2(0.5f, 0.5f);
isActive = true;
Game.IsMouseVisible = false;
character = Entity.Get<CharacterComponent>();
}
public override void Update()
{
if (Input.IsKeyPressed(Keys.Escape))
{
isActive = !isActive;
Game.IsMouseVisible = !isActive;
Input.UnlockMousePosition();
}
if (isActive)
{
Input.LockMousePosition();
var mouseMovement = -Input.MouseDelta * MouseSpeed;
// Update camera rotation values
camRotation.Y += mouseMovement.X;
camRotation.X += InvertMouseY ? mouseMovement.Y : -mouseMovement.Y;
camRotation.X = MathUtil.Clamp(camRotation.X, maxCameraAnglesRadians.X, maxCameraAnglesRadians.Y);
// Apply Y rotation to character entity
character.Orientation = Quaternion.RotationY(camRotation.Y);
// Entity.Transform.Rotation = Quaternion.RotationY(camRotation.Y);
// Apply X rptatopmnew camera rotation to the existing camera rotations
firstPersonCameraPivot.Transform.Rotation = Quaternion.RotationX(camRotation.X);
}
}
}
}
|
using System;
using System.Text.Json;
using NSL;
using NSL.Tokenization.General;
namespace CSCommon
{
class ConsoleLogger : ILogger
{
public ILogger End()
{
Console.Write("\n");
SetColor();
return this;
}
public ILogger Message(string source)
{
SetColor();
Console.Write(source + " ");
SetColor();
return this;
}
public ILogger Name(string source)
{
SetColor(ConsoleColor.Green);
Console.Write(source + " ");
SetColor();
return this;
}
public ILogger Pos(Position pos)
{
SetColor(ConsoleColor.DarkGray);
Console.Write("at " + pos.ToString() + " " + "\n");
Console.Write(pos.GetDebugLineArrow(3));
SetColor();
return this;
}
public ILogger Source(string source)
{
SetColor();
Console.Write("[");
SetColor(ConsoleColor.Blue);
Console.Write(source);
SetColor();
Console.Write("] ");
SetColor();
return this;
}
public ILogger Error()
{
SetColor();
Console.Write("[");
SetColor(ConsoleColor.Red);
Console.Write("ERR!");
SetColor();
Console.Write("] ");
SetColor();
return this;
}
public ILogger Object(object text)
{
SetColor(ConsoleColor.DarkYellow);
Console.Write(JsonSerializer.Serialize(text) + " ");
SetColor();
return this;
}
protected void SetColor(ConsoleColor color = ConsoleColor.White)
{
Console.ForegroundColor = color;
}
}
} |
//
// https://github.com/mythz/ServiceStack.Redis
// ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2013 ServiceStack.
//
// Licensed under the same terms of Redis and ServiceStack: new BSD license.
//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net.Sockets;
using System.Text;
using ServiceStack.Common.Web;
using ServiceStack.DesignPatterns.Model;
using ServiceStack.Text;
namespace ServiceStack.Redis
{
internal static class RedisExtensions
{
public static List<RedisEndPoint> ToRedisEndPoints(this IEnumerable<string> hosts)
{
if (hosts == null) return new List<RedisEndPoint>();
var redisEndpoints = new List<RedisEndPoint>();
foreach (var host in hosts)
{
RedisEndPoint endpoint;
string[] hostParts;
if (host.Contains("@"))
{
hostParts = host.SplitOnLast('@');
var password = hostParts[0];
hostParts = hostParts[1].Split(':');
endpoint = GetRedisEndPoint(hostParts);
endpoint.Password = password;
}
else
{
hostParts = host.Split(':');
endpoint = GetRedisEndPoint(hostParts);
}
redisEndpoints.Add(endpoint);
}
return redisEndpoints;
}
private static RedisEndPoint GetRedisEndPoint(string[] hostParts)
{
const int hostOrIpAddressIndex = 0;
const int portIndex = 1;
if (hostParts.Length == 0)
throw new ArgumentException("'{0}' is not a valid Host or IP Address: e.g. '127.0.0.0[:11211]'");
var port = (hostParts.Length == 1)
? RedisNativeClient.DefaultPort
: Int32.Parse(hostParts[portIndex]);
return new RedisEndPoint(hostParts[hostOrIpAddressIndex], port);
}
public static bool IsConnected(this Socket socket)
{
try
{
return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
}
catch (SocketException)
{
return false;
}
}
public static string[] GetIds(this IHasStringId[] itemsWithId)
{
var ids = new string[itemsWithId.Length];
for (var i = 0; i < itemsWithId.Length; i++)
{
ids[i] = itemsWithId[i].Id;
}
return ids;
}
public static List<string> ToStringList(this byte[][] multiDataList)
{
if (multiDataList == null)
return new List<string>();
var results = new List<string>();
foreach (var multiData in multiDataList)
{
results.Add(multiData.FromUtf8Bytes());
}
return results;
}
public static byte[] ToFastUtf8Bytes(this double value)
{
return FastToUtf8Bytes(value.ToString("R", CultureInfo.InvariantCulture));
}
private static byte[] FastToUtf8Bytes(string strVal)
{
var bytes = new byte[strVal.Length];
for (var i = 0; i < strVal.Length; i++)
bytes[i] = (byte) strVal[i];
return bytes;
}
public static byte[][] ToMultiByteArray(this string[] args)
{
var byteArgs = new byte[args.Length][];
for (var i = 0; i < args.Length; ++i)
byteArgs[i] = args[i].ToUtf8Bytes();
return byteArgs;
}
public static byte[][] PrependByteArray(this byte[][] args, byte[] valueToPrepend)
{
var newArgs = new byte[args.Length + 1][];
newArgs[0] = valueToPrepend;
var i = 1;
foreach (var arg in args)
newArgs[i++] = arg;
return newArgs;
}
public static byte[][] PrependInt(this byte[][] args, int valueToPrepend)
{
return args.PrependByteArray(valueToPrepend.ToUtf8Bytes());
}
}
} |
using System;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
namespace PGPNET_Setup
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
async private Task<string> DownloadKeys()
{
var url = "https://www.dropbox.com/s/bhpqzxcht527ruu/PGPNET.asc?dl=1";
var wc = new System.Net.WebClient();
try
{
var data = await wc.DownloadDataTaskAsync(url);
var foo = Encoding.UTF8.GetString(data);
return foo;
}
catch
{
MessageBox.Show("Couldn't download PGPNET files.", "Network error", MessageBoxButton.OK);
this.Close();
return null;
}
}
async private Task<string[]> DownloadIDs()
{
var url = "https://www.dropbox.com/s/j754hlknhot9sk8/Group%20Line.txt?dl=1";
var wc = new System.Net.WebClient();
try
{
var data = await wc.DownloadDataTaskAsync(url);
var rows = (from d in Encoding.UTF8.GetString(data).Split('\n')
where d.StartsWith("group pgpnet@yahoogroups.com=")
select d).ToArray();
if (rows.Length != 1)
{
Console.Error.WriteLine("Corrupt membership file");
Environment.Exit(1);
}
Console.Out.WriteLine("done.");
var ids = rows[0].Split('=')[1].Trim().Split(' ');
var rx = new Regex("^0x[A-F0-9]{16}$", RegexOptions.IgnoreCase);
return (from keyid in ids
where rx.IsMatch(keyid)
select keyid).ToArray();
}
catch
{
MessageBox.Show("Couldn't download PGPNET files.", "Network error", MessageBoxButton.OK);
this.Close();
return null;
}
}
private void ImportKeys(string keys)
{
using (var proc = new System.Diagnostics.Process()
{
StartInfo = new System.Diagnostics.ProcessStartInfo()
{
FileName = Controller.GnuPGPath,
Arguments = "--no-tty --batch --quiet --import",
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true
}
})
{
proc.Start();
proc.StandardInput.Write(keys);
proc.StandardInput.Close();
proc.WaitForExit();
}
}
private void UpdatePGPRules(string[] ids)
{
XDocument xdoc = XDocument.Load(Controller.PRRPath);
var newdoc = new XElement("pgpRuleList",
from pgprule in xdoc.Descendants("pgpRule")
where pgprule.Attribute("email").Value != "{pgpnet@yahoogroups.com}"
select pgprule);
var newrule = new XElement("pgpRule");
newrule.SetAttributeValue("email", "{pgpnet@yahoogroups.com}");
newrule.SetAttributeValue("encrypt", 2);
newrule.SetAttributeValue("sign", 2);
newrule.SetAttributeValue("negateRule", 0);
newrule.SetAttributeValue("pgpMime", 2);
newrule.SetAttributeValue("keyId", String.Join(", ", ids));
newdoc.AddFirst(newrule);
using (var output = System.IO.File.CreateText(Controller.PRRPath))
{
output.Write(newdoc.ToString());
}
}
public MainWindow()
{
InitializeComponent();
actionButton.Focus();
}
private void quitButton_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
async private void actionButton_Click(object sender, RoutedEventArgs e)
{
quitButton.IsEnabled = false;
actionButton.IsEnabled = false;
var gpgPath = Controller.GnuPGPath;
findingGnuPG.Value = 1;
var prrPath = Controller.PRRPath;
findingEnigmail.Value = 1;
Controller.AdjustGPGConf();
configuringGnuPG.Value = 1;
acquiringData.IsIndeterminate = true;
var ids = await DownloadIDs();
var keys = await DownloadKeys();
acquiringData.IsIndeterminate = false;
acquiringData.Value = 1;
ImportKeys(keys);
UpdatePGPRules(ids);
configuringEnigmail.Value = 1;
quitButton.IsEnabled = true;
}
private void fileQuit_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void helpPGPNET_Click(object sender, RoutedEventArgs e)
{
}
private void helpAbout_Click(object sender, RoutedEventArgs e)
{
}
}
}
|
using System.IO;
using System.Xml.Linq;
namespace YJC.Toolkit.Sys
{
internal sealed class XElementData
{
public XElementData()
{
}
public XElementData(XElementData data, XElement element)
{
Root = data.Root;
Current = element;
Stream = data.Stream;
}
public XDocument Root { get; set; }
public XElement Current { get; set; }
public Stream Stream { get; set; }
public static XElement GetCurrent(object reader)
{
return reader.Convert<XElementData>().Current;
}
}
}
|
using System;
namespace ByteLengthSample
{
class Program
{
/// <summary>
/// C#中的int、long、float、double等类型都占多少个字节的内存
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
// sizeof 操作符是用来取得一个类型在内存中会占几个byte。
Console.WriteLine("{0}: {1} byte(s) scope:[{2}-{3}]",
nameof(Byte).PadLeft(8),
sizeof(byte).NumberPad(2),
byte.MinValue.NumberPad(32, true),
byte.MaxValue.NumberPad(32));
Console.WriteLine("{0}: {1} byte(s) scope:[{2}-{3}]",
nameof(SByte).PadLeft(8),
sizeof(sbyte).NumberPad(2),
sbyte.MinValue.NumberPad(32, true),
sbyte.MaxValue.NumberPad(32));
Console.WriteLine("{0}: {1} byte(s) scope:[{2}-{3}]",
nameof(Int16).PadLeft(8),
sizeof(short).NumberPad(2),
short.MinValue.NumberPad(32, true),
short.MaxValue.NumberPad(32));
Console.WriteLine("{0}: {1} byte(s) scope:[{2}-{3}]",
nameof(UInt16).PadLeft(8),
sizeof(ushort).NumberPad(2),
ushort.MinValue.NumberPad(32, true),
ushort.MaxValue.NumberPad(32));
Console.WriteLine("{0}: {1} byte(s) scope:[{2}-{3}]",
nameof(Int32).PadLeft(8),
sizeof(int).NumberPad(2),
int.MinValue.NumberPad(32, true),
int.MaxValue.NumberPad(32));
Console.WriteLine("{0}: {1} byte(s) scope:[{2}-{3}]",
nameof(UInt32).PadLeft(8),
sizeof(uint).NumberPad(2),
uint.MinValue.NumberPad(32, true),
uint.MaxValue.NumberPad(32));
Console.WriteLine("{0}: {1} byte(s) scope:[{2}-{3}]",
nameof(Int64).PadLeft(8),
sizeof(long).NumberPad(2),
long.MinValue.NumberPad(32, true),
long.MaxValue.NumberPad(32));
Console.WriteLine("{0}: {1} byte(s) scope:[{2}-{3}]",
nameof(UInt64).PadLeft(8),
sizeof(ulong).NumberPad(2),
ulong.MinValue.NumberPad(32, true),
ulong.MaxValue.NumberPad(32));
Console.WriteLine("{0}: {1} byte(s) scope:[{2}-{3}]",
nameof(Single).PadLeft(8),
sizeof(float).NumberPad(2),
float.MinValue.NumberPad(32, true),
float.MaxValue.NumberPad(32));
Console.WriteLine("{0}: {1} byte(s) scope:[{2}-{3}]",
nameof(Double).PadLeft(8),
sizeof(double).NumberPad(2),
double.MinValue.NumberPad(32, true),
double.MaxValue.NumberPad(32));
Console.WriteLine("{0}: {1} byte(s) scope:[{2}-{3}]",
nameof(Decimal).PadLeft(8),
sizeof(decimal).NumberPad(2),
decimal.MinValue.NumberPad(32, true),
decimal.MaxValue.NumberPad(32));
Console.WriteLine("{0}: {1} byte(s)",
nameof(Boolean).PadLeft(8), sizeof(bool).NumberPad(2));
Console.WriteLine("{0}: {1} byte(s)",
nameof(Char).PadLeft(8), sizeof(char).NumberPad(2));
Console.WriteLine("{0}: {1} byte(s) ",
nameof(IntPtr).PadLeft(8), IntPtr.Size.NumberPad(2));
Console.ReadLine();
}
// 注意:以上结果需要注意,在32位系统中,IntPtr为4字节,在64位系统中,IntPtr为8字节。
// [C#开发笔记之22-C#中的int、long、float、double等类型都占多少个字节的内存](https://www.byteflying.com/archives/4396)
public static string NumberPad<T>(this T value, int length, bool right = false)
{
if (right)
{
return value.ToString().PadRight(length);
}
else
{
return value.ToString().PadLeft(length);
}
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SafeRoom.Api.Extensions;
using SafeRoom.Business;
using SafeRoom.DAL.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SafeRoom.Api.Controllers
{
// If you want to do versioning: https://www.hanselman.com/blog/ASPNETCoreRESTfulWebAPIVersioningMadeEasy.aspx
[Route("api/chatrooms")]
[ApiController]
public class ChatroomController : Controller
{
private readonly ILogger<ChatroomController> _logger;
private readonly IChatroomRepository _chatroomRepository;
public ChatroomController(IChatroomRepository chatroomRepository, ILogger<ChatroomController> logger)
{
_logger = logger;
_chatroomRepository = chatroomRepository;
}
[HttpGet]
public IActionResult GetChatrooms()
{
var chatrooms = _chatroomRepository.GetChatrooms().Select(c => c.ToDto());
return Ok(chatrooms);
}
// Make sure the {} value matches with parameters
[HttpGet("user/{userId}")]
public IActionResult GetChatroomsOfUser(int userId)
{
var chatrooms = _chatroomRepository.GetChatroomsOfUser(userId).Select(c => c.ToDto());
return Ok(chatrooms);
}
}
}
|
using System.Diagnostics;
using Lurgle.Logging;
namespace Seq.Client.WindowsLogins
{
public static class Extensions
{
public static LurgLevel MapLogLevel(EventLogEntryType type)
{
switch (type)
{
case EventLogEntryType.Information:
return LurgLevel.Information;
case EventLogEntryType.Warning:
return LurgLevel.Warning;
case EventLogEntryType.Error:
return LurgLevel.Error;
case EventLogEntryType.SuccessAudit:
return LurgLevel.Information;
case EventLogEntryType.FailureAudit:
return LurgLevel.Warning;
default:
return LurgLevel.Debug;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Discord;
namespace Modix.Services.Utilities
{
public static class GuildUserExtensions
{
public static bool HasRole(this IGuildUser user, ulong roleId)
{
return user.RoleIds.Contains(roleId);
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using System;
using System.Security.Claims;
using VENTURA_HR.DOMAIN.UsuarioAggregate.Enums;
namespace VENTURA_HR.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public abstract class GenericController : ControllerBase
{
internal Guid GetLoggedUserId()
{
string userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
return new Guid(userId);
}
internal EUsuarioTipo GetLoggedTypeUser()
{
string role = User.FindFirstValue(ClaimTypes.Role);
EUsuarioTipo typeUser = (EUsuarioTipo)Enum.Parse(typeof(EUsuarioTipo), role, false);
return typeUser;
}
internal string GetLoggedUserEmail()
{
return User.FindFirstValue(ClaimTypes.Email);
}
internal string GetLoggedUserRole()
{
return User.FindFirstValue(ClaimTypes.Role);
}
}
}
|
using NUnit.Framework;
namespace UnityEditor.MeshSync.Tests {
internal class MeshSyncServerTest {
[Test]
public void CreateServer()
{
MeshSyncServerEditor.CreateMeshSyncServer();
//[TODO-sin: 2020-2-26] Add test to make sure that the StreamingAssets are populated
Assert.True(true);
}
}
} //end namespace
|
using System;
namespace Wivuu.Sprog
{
public class ParserException : Exception
{
internal ParserException(string assertion, int remaining)
: base(assertion)
{
this.Assertion = assertion;
this.Remaining = remaining;
}
public string Assertion { get; }
public int Remaining { get; }
}
} |
using System;
using System.Reflection;
namespace ClrTest.Reflection {
public interface IILProvider {
Byte[] GetByteArray();
}
public class MethodBaseILProvider : IILProvider {
MethodBase m_method;
byte[] m_byteArray;
public MethodBaseILProvider(MethodBase method) {
m_method = method;
}
public byte[] GetByteArray() {
if (m_byteArray == null) {
MethodBody methodBody = m_method.GetMethodBody();
m_byteArray = (methodBody == null) ? new Byte[0] : methodBody.GetILAsByteArray();
}
return m_byteArray;
}
}
}
|
@addTagHelper ContosoMasks.ServiceHost.CDNTagHelper, ContosoMasks.ServiceHost
@{
ViewData["Title"] = "Home";
Microsoft.Extensions.Primitives.StringValues xForwardedForHeader;
string xForwardedFor = "";
string xAzureFDID = "";
if (Context.Request.Headers.TryGetValue("X-Forwarded-For", out xForwardedForHeader))
{
xForwardedFor = xForwardedForHeader.SafeFirstOrDefault().Replace("104.57.183.10", "104.57.XXX.XXX");
}
if (Context.Request.Headers.TryGetValue("X-Azure-FDID", out xForwardedForHeader))
{
xAzureFDID = xForwardedForHeader.SafeFirstOrDefault().Replace("104.57.183.10", "104.57.XXX.XXX");
}
}
<div class="container">
<h1 class="my-4">
Contoso Masks
<small>Made locally!</small>
<a href="@Url.Action("Message")"><small><span class="badge badge-warning">Stay Safe - Info about these important times</span></small></a>
</h1>
<div class="row">
<div id="carouselExampleIndicators" class="carousel slide col-md-8" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="3"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="4"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="5"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="6"></li>
</ol>
<div class="carousel-inner">
<div class="carousel-item active">
<img class="d-block w-100" src="~/images/homescreen.jpg" cdnify="true">
</div>
<div class="carousel-item">
<img class="d-block w-100" src="~/images/golf.jpg" cdnify="true">
</div>
<div class="carousel-item">
<img class="d-block w-100" src="~/images/matzah.jpg" cdnify="true">
</div>
<div class="carousel-item">
<img class="d-block w-100" src="~/images/minecraft.jpg" cdnify="true">
</div>
<div class="carousel-item">
<img class="d-block w-100" src="~/images/spicey.jpg" cdnify="true">
</div>
<div class="carousel-item">
<img class="d-block w-100" src="~/images/stone.jpg" cdnify="true">
</div>
<div class="carousel-item">
<img class="d-block w-100" src="~/images/usa.jpg" cdnify="true">
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
<div class="col-md-4">
<h3 class="my-3">Homemade Masks!</h3>
<p>Who wants masks that look like a hospital? Why not have FUN!</p>
<h3 class="my-3">Mask Details</h3>
<ul>
<li>Copper Wire Nose</li>
<li>Elastic Earband</li>
<li>Inner Pouch to layer Tissues!</li>
<li>6 different Styles!</li>
<li><strong>Only 10 CREDITS each</strong> (plus S&H)</li>
</ul>
<h3 class="my-3">Diagnostics</h3>
<ul>
<li>Current Server Time: <span>@DateTimeOffset.UtcNow.ToString("ddd, dd MMMM yyyy HH':'mm':'ss 'GMT'")</span></li>
<li>Current Local Time: <span id="localDateTime"></span></li>
<li>Client IP: @Context.Connection.RemoteIpAddress.ToString().Replace("104.57.183.10", "104.57.XXX.XXX")</li>
@if (!string.IsNullOrEmpty(xForwardedFor))
{
<li>X-Forwarded-For: @xForwardedFor</li>
}
@if (!string.IsNullOrEmpty(xAzureFDID))
{
<li>X-Azure-FDID: @xAzureFDID</li>
}
</ul>
</div>
</div>
<h3 class="my-4">Mask Styles</h3>
<div class="row">
<div class="card col-md-3 col-sm-6 mb-4">
<img class="img-fluid" src="~/images/golf-small.jpg" alt="" cdnify="true">
<div class="card-body">
<h5 class="card-title">Golf Clubs</h5>
</div>
</div>
<div class="card col-md-3 col-sm-6 mb-4">
<img class="img-fluid" src="~/images/matzah-small.jpg" alt="" cdnify="true">
<div class="card-body">
<h5 class="card-title">Cardboard Crackers</h5>
</div>
</div>
<div class="card col-md-3 col-sm-6 mb-4">
<img class="img-fluid" src="~/images/minecraft-small.jpg" alt="" cdnify="true">
<div class="card-body">
<h5 class="card-title">Minecraft</h5>
</div>
</div>
<div class="card col-md-3 col-sm-6 mb-4">
<img class="img-fluid" src="~/images/spicey-small.jpg" alt="" cdnify="true">
<div class="card-body">
<h5 class="card-title">Hot Sauces</h5>
</div>
</div>
<div class="card col-md-3 col-sm-6 mb-4">
<img class="img-fluid" src="~/images/stone-small.jpg" alt="" cdnify="true">
<div class="card-body">
<h5 class="card-title">Stone</h5>
</div>
</div>
<div class="card col-md-3 col-sm-6 mb-4">
<img class="img-fluid" src="~/images/usa-small.jpg" alt="" cdnify="true">
<div class="card-body">
<h5 class="card-title">Stars and Stripes</h5>
</div>
</div>
</div>
</div>
@section scripts {
<script>
$(function () {
$('#localDateTime').text(new Date().toUTCString());
});
</script>
}
|
using ChatApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ChatApi
{
public class SignalRContext
{
/// <summary>
/// 用户列表
/// </summary>
public List<ChatUser> Users { get; set; }
/// <summary>
/// 群聊
/// </summary>
public List<ChatGroup> Groups { get; set; }
public SignalRContext()
{
Users = new List<ChatUser>();
Groups = new List<ChatGroup>();
}
}
}
|
#region License
// Copyright 2013 Ken Worst - R.C. Worst & Company 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.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace BigCommerce4Net.Domain
{
public class ProductsDiscountRule : EntityBase
{
/// <summary>
/// The unique ID of this discount rule. The ID is auto generated and can not be changed.
///
/// int
/// </summary>
[JsonProperty("id")]
public virtual int Id { get; set; }
/// <summary>
/// The product id which this bulk discount rule applies to.
///
/// int
/// </summary>
[JsonProperty("product_id")]
public virtual int ProductId { get; set; }
/// <summary>
/// Min quantity of the product in the shopping cart for this rule to apply.
///
/// int
/// </summary>
[JsonProperty("min")]
public virtual int MinQuantity { get; set; }
/// <summary>
/// Max quantity of the product in the shopping cart for this rule to apply.
///
/// int
/// </summary>
[JsonProperty("max")]
public virtual int MaxQuantity { get; set; }
/// <summary>
/// Type of discount to apply, either apply $X off the product, each product costs $X or percentage discount for the product.
///
///price - each product will have the discount applied defined in the type_value field.
///percent - each product will have its cost reduced by the percentage defined in the type_value field.
///fixed - each product will cost a fixed price defined by the type_value field.
///
/// enum
/// </summary>
[JsonProperty("type")]
public virtual ProductsDiscountType DiscountType { get; set; }
/// <summary>
/// The percentage or price value which will be applied based on the discount type.
///
/// decimal(20,4)
/// </summary>
[JsonProperty("type_value")]
public virtual decimal DiscountValue { get; set; }
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace BayatGames.SaveGamePro.Serialization.Types
{
/// <summary>
/// Save Game Type NavMeshObstacle serialization implementation.
/// </summary>
public class SaveGameType_NavMeshObstacle : SaveGameType
{
/// <summary>
/// Gets the associated type for this custom type.
/// </summary>
/// <value>The type of the associated.</value>
public override Type AssociatedType
{
get
{
return typeof ( UnityEngine.AI.NavMeshObstacle );
}
}
/// <summary>
/// Write the specified value using the writer.
/// </summary>
/// <param name="value">Value.</param>
/// <param name="writer">Writer.</param>
public override void Write ( object value, ISaveGameWriter writer )
{
UnityEngine.AI.NavMeshObstacle navMeshObstacle = ( UnityEngine.AI.NavMeshObstacle )value;
writer.WriteProperty ( "height", navMeshObstacle.height );
writer.WriteProperty ( "radius", navMeshObstacle.radius );
writer.WriteProperty ( "velocity", navMeshObstacle.velocity );
writer.WriteProperty ( "carving", navMeshObstacle.carving );
writer.WriteProperty ( "carveOnlyStationary", navMeshObstacle.carveOnlyStationary );
writer.WriteProperty ( "carvingMoveThreshold", navMeshObstacle.carvingMoveThreshold );
writer.WriteProperty ( "carvingTimeToStationary", navMeshObstacle.carvingTimeToStationary );
writer.WriteProperty ( "shape", navMeshObstacle.shape );
writer.WriteProperty ( "center", navMeshObstacle.center );
writer.WriteProperty ( "size", navMeshObstacle.size );
writer.WriteProperty ( "enabled", navMeshObstacle.enabled );
writer.WriteProperty ( "tag", navMeshObstacle.tag );
writer.WriteProperty ( "name", navMeshObstacle.name );
writer.WriteProperty ( "hideFlags", navMeshObstacle.hideFlags );
}
/// <summary>
/// Read the data using the reader.
/// </summary>
/// <param name="reader">Reader.</param>
public override object Read ( ISaveGameReader reader )
{
UnityEngine.AI.NavMeshObstacle navMeshObstacle = SaveGameType.CreateComponent<UnityEngine.AI.NavMeshObstacle> ();
ReadInto ( navMeshObstacle, reader );
return navMeshObstacle;
}
/// <summary>
/// Read the data into the specified value.
/// </summary>
/// <param name="value">Value.</param>
/// <param name="reader">Reader.</param>
public override void ReadInto ( object value, ISaveGameReader reader )
{
UnityEngine.AI.NavMeshObstacle navMeshObstacle = ( UnityEngine.AI.NavMeshObstacle )value;
foreach ( string property in reader.Properties )
{
switch ( property )
{
case "height":
navMeshObstacle.height = reader.ReadProperty<System.Single> ();
break;
case "radius":
navMeshObstacle.radius = reader.ReadProperty<System.Single> ();
break;
case "velocity":
navMeshObstacle.velocity = reader.ReadProperty<UnityEngine.Vector3> ();
break;
case "carving":
navMeshObstacle.carving = reader.ReadProperty<System.Boolean> ();
break;
case "carveOnlyStationary":
navMeshObstacle.carveOnlyStationary = reader.ReadProperty<System.Boolean> ();
break;
case "carvingMoveThreshold":
navMeshObstacle.carvingMoveThreshold = reader.ReadProperty<System.Single> ();
break;
case "carvingTimeToStationary":
navMeshObstacle.carvingTimeToStationary = reader.ReadProperty<System.Single> ();
break;
case "shape":
navMeshObstacle.shape = reader.ReadProperty<UnityEngine.AI.NavMeshObstacleShape> ();
break;
case "center":
navMeshObstacle.center = reader.ReadProperty<UnityEngine.Vector3> ();
break;
case "size":
navMeshObstacle.size = reader.ReadProperty<UnityEngine.Vector3> ();
break;
case "enabled":
navMeshObstacle.enabled = reader.ReadProperty<System.Boolean> ();
break;
case "tag":
navMeshObstacle.tag = reader.ReadProperty<System.String> ();
break;
case "name":
navMeshObstacle.name = reader.ReadProperty<System.String> ();
break;
case "hideFlags":
navMeshObstacle.hideFlags = reader.ReadProperty<UnityEngine.HideFlags> ();
break;
}
}
}
}
} |
using System.Threading.Tasks;
namespace Rlx
{
public static class ResultExtensions
{
public static T UnwrapEither<T>(this Result<T, T> result) =>
result.UnwrapOrElse(error => error);
public static Task<T> UnwrapEitherAsync<T>(this ResultTask<T, T> result) =>
result.UnwrapOrElseAsync(error => error);
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using homeControl.Domain.Events;
using JetBrains.Annotations;
namespace homeControl.Interop.Rabbit
{
[UsedImplicitly]
internal sealed class ExchangeConfiguration
{
private readonly Dictionary<Type, List<(string, string, string)>> _receiveExchangesByType
= new Dictionary<Type, List<(string, string, string)>>();
public IReadOnlyDictionary<Type, List<(string name, string type, string route)>> ReceiveExchangesByType
=> new ReadOnlyDictionary<Type, List<(string, string, string)>>(_receiveExchangesByType);
private readonly Dictionary<Type, List<string>> _sendExchangesByType
= new Dictionary<Type, List<string>>();
public IReadOnlyDictionary<Type, List<string>> SendExchangesByType
=> new ReadOnlyDictionary<Type, List<string>>(_sendExchangesByType);
public void ConfigureEventSender(Type eventType, string exchangeName)
{
Guard.DebugAssertArgumentNotNull(eventType, nameof(eventType));
Guard.DebugAssertArgument(typeof(IEvent).IsAssignableFrom(eventType), nameof(eventType));
Guard.DebugAssertArgumentNotNull(exchangeName, nameof(exchangeName));
if (!_sendExchangesByType.TryGetValue(eventType, out var exchangesByType))
{
exchangesByType = new List<string>();
_sendExchangesByType.Add(eventType, exchangesByType);
}
exchangesByType.Add((exchangeName));
}
public void ConfigureEventReceiver(Type eventType, string exchangeName, string exchangeType, string routingKey)
{
Guard.DebugAssertArgumentNotNull(eventType, nameof(eventType));
Guard.DebugAssertArgument(typeof(IEvent).IsAssignableFrom(eventType), nameof(eventType));
Guard.DebugAssertArgumentNotNull(exchangeName, nameof(exchangeName));
Guard.DebugAssertArgumentNotNull(exchangeType, nameof(exchangeType));
if (!_receiveExchangesByType.TryGetValue(eventType, out var exchangesByType))
{
exchangesByType = new List<(string, string, string)>();
_receiveExchangesByType.Add(eventType, exchangesByType);
}
exchangesByType.Add((exchangeName, exchangeType, routingKey));
}
}
} |
using FV3.Helpers;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace HelpList.Model
{
class TeacherCollection : INotifyPropertyChanged
{
//instance fields
private string _firstName;
private string _lastName;
private string _password;
private string _mail;
private ObservableCollection<Teacher> _tc;
private Teacher _selectedTeacher;
private Teacher _newTeacher;
//Properties
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
OnPropertyChanged();
}
}
public string LastName
{
get { return _lastName; }
set
{
_lastName = value;
OnPropertyChanged();
}
}
public string Password
{
get { return _password; }
set
{
_password = value;
OnPropertyChanged();
}
}
public string Mail
{
get { return _mail; }
set
{
_mail = value;
OnPropertyChanged();
}
}
public Teacher SelectedTeacher
{
get { return _selectedTeacher; }
set
{
_selectedTeacher = value;
OnPropertyChanged();
}
}
public Teacher NewTeacher
{
get { return _newTeacher; }
set
{
_newTeacher = value;
OnPropertyChanged();
}
}
public RelayCommand AddCommand { get; set; }
public RelayCommand DeleteCommand { get; set; }
//create a collection for Teachers.
public ObservableCollection<Teacher> TC
{
get { return _tc; }
set
{
_tc = value;
OnPropertyChanged();
}
}
//constructor
public TeacherCollection()
{
TC = new ObservableCollection<Teacher>
{
new Teacher("Henrik", "Høltzer", "henrikpass","hanrik@gmail.com"),
new Teacher("Jamshid", "Eftekhari", "jamshidpass","jamshid@gmail.com"),
};
TC.Add(new Teacher("Torben", "Heidemann", "torbenpass", "torben@gmail.com"));
_newTeacher = new Teacher();
AddCommand = new RelayCommand(AddTeacherMethod);
DeleteCommand = new RelayCommand(DeleteTeacherMethod);
}
//methods
public void AddTeacherMethod()
{
TC.Add(new Teacher(_firstName, _lastName, _password, _mail));
}
public void DeleteTeacherMethod()
{
if (SelectedTeacher != null)
{
TC.Remove(SelectedTeacher);
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
|
using ProSuite.Commons.Essentials.CodeAnnotations;
namespace ProSuite.DomainModel.Core.QA.Html
{
public interface IHtmlDataQualityCategoryOptionsProvider
{
[CanBeNull]
HtmlDataQualityCategoryOptions GetCategoryOptions([NotNull] string uuid);
}
} |
using System;
namespace Rafty
{
public class BecomeCandidate : Message
{
public BecomeCandidate(Guid lastAppendEntriesMessageIdFromLeader)
{
this.LastAppendEntriesMessageIdFromLeader = lastAppendEntriesMessageIdFromLeader;
}
public Guid LastAppendEntriesMessageIdFromLeader { get; private set; }
}
} |
using Serenity.Services;
using System;
using System.Collections.Generic;
namespace Serenity.Data
{
/// <summary>
/// Contains static extension methods for DbField and Meta objects.</summary>
public static class ServiceRequestExtensions
{
public static TRequest IncludeField<TRequest>(this TRequest request, Field field)
where TRequest : ServiceRequest, IIncludeExcludeColumns
{
request.IncludeColumns ??= new HashSet<string>(StringComparer.OrdinalIgnoreCase);
request.IncludeColumns.Add(field.PropertyName ?? field.Name);
return request;
}
}
} |
namespace TwitchWrapper
{
public class UserClient
{
private readonly TwitchClient _client;
private const string UserResource = "users/{0}";
public UserClient(TwitchClient client)
{
_client = client;
}
public User GetUser(string username)
{
var resource = string.Format(UserResource, username);
var request = new TwitchRequest(resource);
return _client.ExecuteRequest<User>(request);
}
}
} |
// Autor : Juan Parra
// 3Soft
namespace Jen.Eventos
{
using Serializable = System.SerializableAttribute;
using SerializationInfo = System.Runtime.Serialization.SerializationInfo;
using StreamingContext = System.Runtime.Serialization.StreamingContext;
/// <summary>
/// Evento para validar campos requeridos
/// </summary>
[Serializable]
public class ValidarRequerido: Evento<Campo>
{
/// <summary>
/// Constructor por defecto del evento
/// </summary>
public ValidarRequerido()
: base()
{
Id = Clase = Lenguaje.ValidarRequerido;
}
/// <summary>
/// Constructor binario del evento
/// </summary>
/// <param name="info">Lista de propiedades serializadas</param>
/// <param name="context">Contexto del proceso de deserialización</param>
protected ValidarRequerido(SerializationInfo info, StreamingContext context)
: base(info, context)
{
Id = Clase = Lenguaje.ValidarRequerido;
}
/// <summary>
/// Punto de entrada de la validación
/// </summary>
/// <returns></returns>
//public override void Ejecutar(Evento ev)
public override void Ejecutar()
{
// direcciona al campo a validar ddMedioDestino
Campo campo = Contexto;
// obtiene el valor crudo del evento
string valor = campo.ToString();
// si el campo es autonumerico no valida el requerido
if (campo.Autonumerico)
{
return;
}
// si el campo contiene el evento que asigna la hora no valida lo requerido.
if (campo.Existe(Lenguaje.CalcularAhora))
{
return;
}
// si es nulo informa el error
if (string.IsNullOrEmpty(valor) || (valor.ToLower().Equals(Lenguaje.Null)))
{
campo.Consejos = string.IsNullOrEmpty(Consejo) ? string.Concat(Contexto.Articulo, Lenguaje.Espacio,
Contexto.Clase, Lenguaje.Espacio,
Contexto.Etiqueta, Lenguaje.Espacio,
Lenguaje.DebeSerNoNulo) : Consejo;
campo.Estado |= Estado.Error;
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunScript : MonoBehaviour
{
[SerializeField]
private Transform firePoint;
[SerializeField]
private GameObject bulletPrefab;
private GameObject bulletInstance;
private float timeToDestroy = 0.8f;
public void Shoot()
{
bulletInstance = (GameObject) Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Destroy(bulletInstance, timeToDestroy);
}
}
|
@{
Layout = "~/Views/SPRK/Shared/_Layout.cshtml";
ViewBag.Title = "Find";
}
<h2>Find a Log</h2>
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QingShan.CodeGenerator.Dto
{
public class CodegeneratorInputDto
{
/// <summary>
/// 控制器
/// </summary>
public string ControllerNamespace { get; set; }
/// <summary>
/// Dto
/// </summary>
public string DtoNamespace { get; set; }
/// <summary>
/// Service
/// </summary>
public string ServiceNamespace { get; set; }
/// <summary>
/// IContract
/// </summary>
public string IContractNamespace { get; set; }
/// <summary>
/// 实体命名空间
/// </summary>
public string EntityNamespace { get; set; }
/// <summary>
/// 输出目录
/// </summary>
public string Output { get; set; }
/// <summary>
///
/// </summary>
public string DataBase { get; set; }
}
}
|
//----------------------------------------------------------------------
// Gold Parser engine.
// See more details on http://www.devincook.com/goldparser/
//
// Original code is written in VB by Devin Cook (GOLDParser@DevinCook.com)
//
// This translation is done by Vladimir Morozov (vmoroz@hotmail.com)
//
// The translation is based on the other engine translations:
// Delphi engine by Alexandre Rai (riccio@gmx.at)
// C# engine by Marcus Klimstra (klimstra@home.nl)
//----------------------------------------------------------------------
using System;
using System.Collections;
namespace Morozov
{
namespace GoldParser
{
/// <summary>
/// Represents reduced rule.
/// </summary>
/// <remarks>
/// This class is used by the engine to hold a reduced rule. Rather the contain
/// a list of Symbols, a reduction contains a list of Tokens corresponding to the
/// the rule it represents.
/// </remarks>
public class Reduction
{
private Rule m_rule;
private ArrayList m_items = new ArrayList();
private int m_number;
/// <summary>
/// Creates a new instance of the <c>Reduction</c> class.
/// </summary>
/// <param name="rule">The rule on which the reduction is based.</param>
public Reduction(Rule rule)
{
m_rule = rule;
}
/// <summary>
/// Adds a token to thetoken list.
/// </summary>
/// <param name="index">Index to insert the token.</param>
/// <param name="token">Token to insert.</param>
public void InsertToken(int index, Token token)
{
m_items.Insert(index, token);
}
/// <summary>
/// Gets the reduction line number in the source file.
/// </summary>
public int LineNumber
{
get
{
if (m_items.Count > 0)
{
return ((Token)m_items[0]).LineNumber;
}
return -1;
}
}
/// <summary>
/// Gets number of tokens.
/// </summary>
public int Count
{
get { return m_items.Count; }
}
/// <summary>
/// Gets a token by its index.
/// </summary>
public Token this[int index]
{
get { return (Token)m_items[index]; }
}
/// <summary>
/// Gets or sets reduction numebr.
/// </summary>
public int ReductionNumber
{
get { return m_number; }
set { m_number = value; }
}
/// <summary>
/// Gets the reduction rule.
/// </summary>
public Rule Rule
{
get { return m_rule; }
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Salvis.DataLayer.Repositories
{
[Serializable]
public class TypeNotAsExpectedException : Exception, IDataLayerException
{
private readonly object _obj;
public TypeNotAsExpectedException(object obj = null)
: base("The passed type or parameter is not matching")
{
_obj = obj;
}
public TypeNotAsExpectedException(string message, object obj = null)
: base(message)
{
_obj = obj;
}
public object RelatedObject
{
get { return _obj; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace flyingSnow
{
static class ConfigGeneratorSettingsIMGUIRegister
{
[SettingsProvider]
public static SettingsProvider CreateConfigGeneratorSettingsProvider()
{
var provider = new SettingsProvider("Project/ConfigGeneratorSettings", SettingsScope.Project)
{
label = "ConfigGenerator Settings",
guiHandler = (searchContext) =>
{
var settings = ConfigGeneratorSettings.GetInstance();
settings.sourceDir = EditorGUILayout.TextField("Path of Excel Files", settings.sourceDir);
settings.targetDir = EditorGUILayout.TextField("Path of Exported Files", settings.targetDir);
settings.targetFormat = (ConfigGeneratorSettings.TargetFormat)EditorGUILayout.Popup(
"Format",
(int)settings.targetFormat,
ConfigGeneratorSettings.TargetFormatDisplays,
GUILayout.MaxWidth(300)
);
if(GUI.changed)
{
settings.Save();
}
},
keywords = new HashSet<string>(new[] { "Excel", "Export"})
};
return provider;
}
}
} |
// <copyright file="Precedence.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
namespace GWParse.Test.Expressions
{
using Xunit;
public sealed class Precedence
{
[InlineData("1+2*3", "Add(NumL(1), Mult(NumL(2), NumL(3)))")]
[InlineData("1+2/3", "Add(NumL(1), Div(NumL(2), NumL(3)))")]
[InlineData("1-2*3", "Sub(NumL(1), Mult(NumL(2), NumL(3)))")]
[InlineData("1-2/3", "Sub(NumL(1), Div(NumL(2), NumL(3)))")]
[InlineData("(1+2)/3", "Div(Add(NumL(1), NumL(2)), NumL(3))")]
[InlineData("(1-2)/3", "Div(Sub(NumL(1), NumL(2)), NumL(3))")]
[InlineData("(1+2)*3", "Mult(Add(NumL(1), NumL(2)), NumL(3))")]
[InlineData("(1-2)*3", "Mult(Sub(NumL(1), NumL(2)), NumL(3))")]
[InlineData("(1*2)/3", "Div(Mult(NumL(1), NumL(2)), NumL(3))")]
[InlineData("(1*2)+3", "Add(Mult(NumL(1), NumL(2)), NumL(3))")]
[InlineData("(1/2)-3", "Sub(Div(NumL(1), NumL(2)), NumL(3))")]
[InlineData("1*2^3", "Mult(NumL(1), Pow(NumL(2), NumL(3)))")]
[InlineData("1^2/3", "Div(Pow(NumL(1), NumL(2)), NumL(3))")]
[InlineData("1^2+3", "Add(Pow(NumL(1), NumL(2)), NumL(3))")]
[InlineData("1^2-3", "Sub(Pow(NumL(1), NumL(2)), NumL(3))")]
[InlineData("1+2^3", "Add(NumL(1), Pow(NumL(2), NumL(3)))")]
[InlineData("1-2^3", "Sub(NumL(1), Pow(NumL(2), NumL(3)))")]
[InlineData("(-1)^2+3", "Add(Pow(Neg(NumL(1)), NumL(2)), NumL(3))")]
[InlineData("1^-2+3", "Add(Pow(NumL(1), Neg(NumL(2))), NumL(3))")]
[InlineData("1^(-2)+3", "Add(Pow(NumL(1), Neg(NumL(2))), NumL(3))")]
[InlineData("-1^2+3", "Add(Neg(Pow(NumL(1), NumL(2))), NumL(3))")]
[Theory]
public void Arithmetic(string input, string output)
{
Test.Good(input, output);
}
[InlineData("1 AND 2 OR 3", "Or(And(NumL(1), NumL(2)), NumL(3))")]
[InlineData("1 AND (2 OR 3)", "And(NumL(1), Or(NumL(2), NumL(3)))")]
[InlineData("1+2 AND 3", "And(Add(NumL(1), NumL(2)), NumL(3))")]
[InlineData("1*2 AND 3", "And(Mult(NumL(1), NumL(2)), NumL(3))")]
[InlineData("NOT 1 AND 2 OR 3", "Or(And(Not(NumL(1)), NumL(2)), NumL(3))")]
[Theory]
public void LogicaNumL(string input, string output)
{
Test.Good(input, output);
}
[InlineData("1+2 AND 3=4", "And(Add(NumL(1), NumL(2)), Eq(NumL(3), NumL(4)))")]
[InlineData("1*2 OR 3=4", "Or(Mult(NumL(1), NumL(2)), Eq(NumL(3), NumL(4)))")]
[InlineData("1*2 OR 3<>4", "Or(Mult(NumL(1), NumL(2)), Ne(NumL(3), NumL(4)))")]
[InlineData("1>2 AND 3<4", "And(Gt(NumL(1), NumL(2)), Lt(NumL(3), NumL(4)))")]
[InlineData("1>2<3=4<>5", "Ne(Eq(Lt(Gt(NumL(1), NumL(2)), NumL(3)), NumL(4)), NumL(5))")]
[InlineData("1>=2<=3=4<>5", "Ne(Eq(Le(Ge(NumL(1), NumL(2)), NumL(3)), NumL(4)), NumL(5))")]
[InlineData("1>2>=3=4<>5", "Ne(Eq(Ge(Gt(NumL(1), NumL(2)), NumL(3)), NumL(4)), NumL(5))")]
[InlineData("\"1\">\"2\" AND \"3\"<>\"4\"", "And(Gt(StrL(\"1\"), StrL(\"2\")), Ne(StrL(\"3\"), StrL(\"4\")))")]
[Theory]
public void RelationaNumL(string input, string output)
{
Test.Good(input, output);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using DdfGuide.Android;
using Newtonsoft.Json;
namespace DdfGuide.Core
{
public class UserDataImportExport : IUserDataImportExport
{
private readonly ICache<IEnumerable<AudioDramaUserData>> _userDataCache;
private readonly IClipboardService _clipboardService;
private readonly IYesNoDialog _yesNoDialog;
private readonly IUserNotifier _userNotifier;
private readonly IOkDialog _okDialog;
private string _jsonForSavingToClipboard;
private List<AudioDramaUserData> _mergedUserDataForImporting;
public event EventHandler UserDataImported;
public UserDataImportExport(
ICache<IEnumerable<AudioDramaUserData>> userDataCache,
IClipboardService clipboardService,
IYesNoDialog yesNoDialog,
IUserNotifier userNotifier,
IOkDialog okDialog)
{
_userDataCache = userDataCache;
_clipboardService = clipboardService;
_yesNoDialog = yesNoDialog;
_userNotifier = userNotifier;
_okDialog = okDialog;
}
public void ExportUserData()
{
var userData = _userDataCache.Load().ToList();
_jsonForSavingToClipboard = JsonConvert.SerializeObject(userData);
_yesNoDialog.YesClicked += SaveClipboardText();
_yesNoDialog.Show(
"In Zwischenablage exportieren?",
$"Datensätze: {userData.Count}\n" +
$"Als gehört markiert: {userData.Count(x => x.Heard)}\n" +
$"Als Favorit markiert: {userData.Count(x => x.IsFavorite)}\n\n" +
$"Dann kannst du deine Daten zum Sichern z.B. in einer Textdatei oder Email einfügen.");
}
private EventHandler SaveClipboardText()
{
return (sender, args) =>
{
_clipboardService.SetClipboardText(_jsonForSavingToClipboard);
_userNotifier.Notify("Daten erfolgreich in Zwischenablage kopiert.");
_yesNoDialog.YesClicked -= SaveClipboardText();
};
}
public void ImportUserData()
{
var json = _clipboardService.GetTextFromClipboard();
if (string.IsNullOrWhiteSpace(json))
{
_okDialog.Show("Zwischenablage ist leer", "Bitte kopiere zunächst deine exportieren Benutzerdaten.");
return;
}
List<AudioDramaUserData> newUserData;
try
{
newUserData = JsonConvert.DeserializeObject<List<AudioDramaUserData>>(json);
}
catch (JsonException)
{
_okDialog.Show("Zwischenablage fehlerhaft", "Der Text in der Zwischenablage ist nicht valide. " +
"Bitte überprüfe, ob du alles richtig kopiert hast.");
return;
}
if (newUserData.GroupBy(x => x.Id).Any(x => x.Count() > 1))
{
_okDialog.Show("Zwischenablage fehlerhaft", "Der Text in der Zwischenablage enthält Duplikate. " +
"Bitte überprüfe, ob du alles richtig kopiert hast.");
}
var oldUserData = _userDataCache.Load();
_mergedUserDataForImporting = new List<AudioDramaUserData>();
foreach (var old in oldUserData)
{
if (newUserData.All(x => x.Id != old.Id))
{
_mergedUserDataForImporting.Add(old);
}
}
_mergedUserDataForImporting.AddRange(newUserData);
_yesNoDialog.YesClicked += ImportDataFromClipboard();
_yesNoDialog.Show(
"Daten aus Zwischenablage importieren?",
$"Datensätze: {newUserData.Count}\n" +
$"Als gehört markiert: {newUserData.Count(x => x.Heard)}\n" +
$"Als Favorit markiert: {newUserData.Count(x => x.IsFavorite)}");
}
private EventHandler ImportDataFromClipboard()
{
return (sender, args) =>
{
_userDataCache.Save(_mergedUserDataForImporting);
UserDataImported?.Invoke(this, EventArgs.Empty);
_userNotifier.Notify("Benutzerdaten erfolgreich importiert.");
_yesNoDialog.YesClicked -= ImportDataFromClipboard();
};
}
}
} |
using System;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using Awem.Windowing;
using Microsoft.Win32;
namespace Awem.EventNotifiers
{
public class DisplaySettingsChangedNotifier : IDisposable
{
private readonly Subject<EventArgs> _changed = new Subject<EventArgs>();
public IObservable<EventArgs> Changed => _changed.AsObservable();
public DisplaySettingsChangedNotifier() => SystemEvents.DisplaySettingsChanged += this.OnChanged;
public void Dispose() => SystemEvents.DisplaySettingsChanged -= this.OnChanged;
private void OnChanged(object sender, EventArgs e) => this._changed.OnNext(e);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PartialViewOtherToJieLink.JSDSViewModels
{
public class TCacAccountModel
{
/// <summary>
/// 账号GUID
/// </summary>
public string ID { get; set; }
/// <summary>
/// 用户GUID:一个用户一个账号
/// </summary>
public string PERSON_ID { get; set; }
/// <summary>
/// 忽略
/// </summary>
public string ACCOUNT_NAME { get; set; }
/// <summary>
/// 账号状态
/// </summary>
public string STATUS { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public string CREATE_TIME { get; set; }
/// <summary>
/// 更新时间
/// </summary>
public string UPDATE_TIME { get; set; }
/// <summary>
/// 忽略
/// </summary>
public string BALANCE { get; set; }
public string TYPE { get; set; }
public string UNLOCK_TIME { get; set; }
public string ACCOUNT_PWD { get; set; }
public string CREATE_DATE { get; set; }
public string LOCKED_TIME { get; set; }
public string VERIFY_DATA { get; set; }
public string FROM_ID { get; set; }
public string REMARK { get; set; }
public string SYNC_TIME { get; set; }
public string SYNC_FLAG { get; set; }
public string SYNC_FAILS { get; set; }
public string DATA_ORIGIN { get; set; }
}
/// <summary>
/// 账号状态
/// </summary>
public enum AccountStatusEnum
{
CLOSE,
NORMAL,
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PickUp15 : MonoBehaviour
{
[SerializeField]
private Text pickUpText;
private bool pickUpAllowed;
private void Start()
{
pickUpText.gameObject.SetActive(false);
}
private void Update()
{
if (pickUpAllowed && Input.GetKeyDown(KeyCode.F))
PickedUp();
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.name.Equals("PlayerCharacter"))
{
pickUpText.gameObject.SetActive(true);
pickUpAllowed = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.name.Equals("PlayerCharacter"))
{
pickUpAllowed = false;
}
}
void PickedUp()
{
CollectedEndGateLVL3.collValue++;
Destroy(gameObject);
pickUpText.gameObject.SetActive(false);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Used for visualization
/// </summary>
public struct VisualizationInfo
{
/// <summary>
/// Output binary with all the hands found
/// </summary>
public Texture2D binary_image;
/// <summary>
/// Input image that will be processed
/// </summary>
public Texture2D rgb_image;
} |
using System.Linq;
using System.Threading.Tasks;
using MAF.FeaturesFlipping.Extensibility.FeatureContext;
using MAF.FeaturesFlipping.FeatureContext.Delegate;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Xunit;
// ReSharper disable once CheckNamespace
namespace MAF.FeaturesFlipping.Extensions.DependencyInjection.FeatureContext.Delegate
{
public partial class FeaturesFlippingBuilderFeatureContextDelegateExtensionsTests
{
public class AddDelegateFeatureContextPart
{
[Fact]
public void Adding_The_Delegate_Based_Factory_Add_To_The_ServiceCollection()
{
// Arrange
var serviceCollection = new ServiceCollection();
var featuresFlippingBuilderMock = new Mock<IFeaturesFlippingBuilder>();
featuresFlippingBuilderMock.SetupGet(_ => _.Services)
.Returns(serviceCollection);
var expectedLifetime = ServiceLifetime.Singleton;
// Act
var actualFeaturesFlippingBuilder =
featuresFlippingBuilderMock.Object.AddDelegateFeatureContextPart(_ => Task.CompletedTask);
// Assert
Assert.NotNull(actualFeaturesFlippingBuilder);
Assert.Equal(serviceCollection, actualFeaturesFlippingBuilder.Services);
Assert.Equal(1, actualFeaturesFlippingBuilder.Services.Count);
var actualServiceDescriptor = actualFeaturesFlippingBuilder.Services.First();
Assert.Equal(typeof(IFeatureContextPartFactory), actualServiceDescriptor.ServiceType);
Assert.IsType<DelegateFeatureContextPartFactory>(actualServiceDescriptor.ImplementationInstance);
Assert.Equal(expectedLifetime, actualServiceDescriptor.Lifetime);
}
}
}
} |
namespace SharedUI.Shared
{
public partial class MainWindowController
{
private void setup()
{
//
// Do any shared initilaization, here
//
}
//
// Add Shared code here
//
[Notify] public string valueA { get; set; }
[Notify] public string valueB { get; set; }
[Notify] public string result { get; private set; } = "N/A";
[IBAction]
public void calculateResult(id sender)
{
if (length(valueA) == 0 || length(valueB) == 0)
{
result = "(value required)";
}
else
{
var a = Convert.TryToDoubleInvariant(valueA);
var b = Convert.TryToDoubleInvariant(valueB);
if (a != null && b != null)
{
result = Convert.ToString(a+b);
}
else
{
result = valueA+valueB;
}
}
}
}
} |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Numerics;
using Dane;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Logika;
namespace Testy.Logika
{
[TestClass]
public class LogicTest
{
[TestMethod]
public void TestLogicApi()
{
LogicAbstractApi logic = LogicAbstractApi.CreateApi();
Assert.IsTrue(logic.Height == 400);
Assert.IsTrue(logic.Width == 800);
logic.CreateBalls(2);
ObservableCollection<Ball> balls = logic.Balls;
Assert.IsTrue(balls.Count == 2);
Assert.IsTrue(balls[0].X < logic.Width);
Assert.IsTrue(balls[0].Y < logic.Height);
Assert.IsTrue(balls[0].X > 0);
Assert.IsTrue(balls[0].Y > 0);
List<BallLogic> ballsLogic = logic.GetBalls();
Assert.IsTrue(ballsLogic[0].Ball == balls[0]);
logic.StopBalls();
Assert.IsTrue(balls.Count == 0);
}
[TestMethod]
public void TestLogic()
{
LogicAbstractApi logic = LogicAbstractApi.CreateApi();
logic.CreateBalls(1);
Vector2 velocity = new Vector2(1, 1);
Ball ball1 = new Ball(-5, -20, 10, 2, velocity);
Assert.IsTrue(ball1.VX == 1);
logic.Collisions(800, 400, ball1.Radius, ball1);
Assert.IsTrue(ball1.VX == -1);
Vector2 velocity2 = new Vector2(2, 1.5f);
Vector2 velocity3 = new Vector2(-1, -0.3f);
Ball ball2 = new Ball(30, 20, 10, 2, velocity);
Ball ball3 = new Ball(40, 25, 10, 2, velocity);
logic.BallCrash(ball2, ball3);
Assert.IsTrue(ball2.VX != velocity2.X);
Assert.IsTrue(ball2.VY != velocity2.Y);
Assert.IsTrue(ball3.VX != velocity3.X);
Assert.IsTrue(ball3.VY != velocity3.Y);
}
}
} |
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Mixpanel
{
internal sealed class BatchMessageWrapper
{
public List<List<MixpanelMessage>> TrackMessages { get; private set; }
public List<List<MixpanelMessage>> EngageMessages { get; private set; }
internal const int MaxBatchSize = 50;
public BatchMessageWrapper(IEnumerable<MixpanelMessage> messages)
{
if (messages == null)
{
return;
}
foreach (var message in messages)
{
if (message == null || message.Data == null || message.Kind == MessageKind.Batch)
{
continue;
}
bool isTrackMessage =
message.Kind == MessageKind.Track || message.Kind == MessageKind.Alias;
if (isTrackMessage)
{
AddTrackMessage(message);
}
else
{
AddEngageMessage(message);
}
}
}
private void AddTrackMessage(MixpanelMessage message)
{
Debug.Assert(message != null);
if (TrackMessages == null)
{
TrackMessages = new List<List<MixpanelMessage>>();
}
AddBatchMessage(TrackMessages, message);
}
private void AddEngageMessage(MixpanelMessage message)
{
Debug.Assert(message != null);
if (EngageMessages == null)
{
EngageMessages = new List<List<MixpanelMessage>>();
}
AddBatchMessage(EngageMessages, message);
}
private void AddBatchMessage(List<List<MixpanelMessage>> list, MixpanelMessage message)
{
Debug.Assert(list != null);
Debug.Assert(message != null);
var lastInnerList = list.LastOrDefault();
bool newInnerListNeeded = lastInnerList == null || lastInnerList.Count >= MaxBatchSize;
if (newInnerListNeeded)
{
var newInnerList = new List<MixpanelMessage> { message };
list.Add(newInnerList);
}
else
{
lastInnerList.Add(message);
}
}
}
} |
using System;
using System.Linq;
using OpenTK.Audio.OpenAL;
using System.ComponentModel;
using OpenCV.Net;
using System.Reactive.Linq;
using Bonsai.Audio.Configuration;
namespace Bonsai.Audio
{
/// <summary>
/// Represents an operator that plays a sequence of buffered samples to the specified audio device.
/// </summary>
[Description("Plays the sequence of buffered samples to the specified audio device.")]
public class AudioPlayback : Sink<Mat>
{
/// <summary>
/// Gets or sets the name of the audio device used for playback.
/// </summary>
[Description("The name of the audio device used for playback.")]
[TypeConverter(typeof(PlaybackDeviceNameConverter))]
public string DeviceName { get; set; }
/// <summary>
/// Gets or sets the optional name of the source used to playback the audio buffers.
/// </summary>
[TypeConverter(typeof(SourceNameConverter))]
[Description("The optional name of the source used to playback the audio buffers.")]
public string SourceName { get; set; }
/// <summary>
/// Gets or sets the sample rate, in Hz, used to playback the audio buffers.
/// </summary>
[Description("The sample rate, in Hz, used to playback the audio buffers.")]
public int SampleRate { get; set; } = 44100;
/// <summary>
/// Gets or sets the sample rate, in Hz, used to playback the audio buffers.
/// </summary>
[Browsable(false)]
[Obsolete("Use SampleRate instead for consistent wording with signal processing operator properties.")]
public int? Frequency
{
get { return null; }
set
{
if (value != null)
{
SampleRate = value.Value;
}
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="Frequency"/> property should be serialized.
/// </summary>
[Obsolete]
[Browsable(false)]
public bool FrequencySpecified
{
get { return Frequency.HasValue; }
}
/// <summary>
/// Gets or sets a value specifying the state to which the source should be set
/// when queueing audio buffers.
/// </summary>
[Description("Specifies the state to which the source should be set when queueing audio buffers.")]
public ALSourceState? State { get; set; } = ALSourceState.Playing;
/// <summary>
/// Plays an observable sequence of buffered samples to the specified audio device.
/// </summary>
/// <param name="source">
/// A sequence of <see cref="Mat"/> objects representing the buffered audio samples
/// to queue for playback on the specified audio device.
/// </param>
/// <returns>
/// An observable sequence that is identical to the <paramref name="source"/> sequence
/// but where there is an additional side effect of queueing the audio buffers for
/// playback on the specified audio device.
/// </returns>
/// <remarks>
/// This operator only subscribes to the <paramref name="source"/> sequence after
/// initializing the audio context on the specified audio device.
/// </remarks>
public override IObservable<Mat> Process(IObservable<Mat> source)
{
return Observable.Using(
() => AudioManager.ReserveContext(DeviceName),
resource =>
{
var sourceName = SourceName;
if (!string.IsNullOrEmpty(sourceName))
{
var audioSource = resource.Context.ResourceManager.Load<AudioSource>(sourceName);
return Process(source, Observable.Return(audioSource));
}
else
{
var configuration = new SourceConfiguration();
var audioSource = configuration.CreateResource(resource.Context.ResourceManager);
return Process(source, Observable.Return(audioSource)).Finally(audioSource.Dispose);
}
});
}
/// <summary>
/// Plays an observable sequence of buffered samples to all the specified audio sources.
/// </summary>
/// <param name="dataSource">
/// A sequence of <see cref="Mat"/> objects representing the buffered audio samples
/// to queue for playback on all the active audio sources.
/// </param>
/// <param name="audioSource">
/// A sequence of <see cref="AudioSource"/> objects on which to queue the buffered
/// audio samples for playback.
/// </param>
/// <returns>
/// An observable sequence that is identical to the <paramref name="dataSource"/>
/// sequence but where there is an additional side effect of queueing the audio buffers
/// for playback on all the active audio sources.
/// </returns>
/// <remarks>
/// This operator only subscribes to the <paramref name="dataSource"/> sequence
/// after initializing the audio context on the specified audio device.
/// </remarks>
public IObservable<Mat> Process(IObservable<Mat> dataSource, IObservable<AudioSource> audioSource)
{
var playbackState = State;
return Observable.Using(
() => AudioManager.ReserveContext(DeviceName),
resource => audioSource.SelectMany(source => dataSource.Do(input =>
{
var buffer = AL.GenBuffer();
BufferHelper.UpdateBuffer(buffer, input, SampleRate);
var sourceState = source.State;
var targetState = playbackState.GetValueOrDefault(sourceState);
if (targetState != ALSourceState.Playing && sourceState != targetState)
{
source.SetState(playbackState.Value);
}
AL.SourceQueueBuffer(source.Id, buffer);
source.ClearBuffers(0);
if (targetState == ALSourceState.Playing && sourceState != targetState)
{
source.Play();
}
})));
}
/// <summary>
/// Plays an observable sequence of buffered samples to all the specified audio sources.
/// </summary>
/// <param name="audioSource">
/// A sequence of <see cref="AudioSource"/> objects on which to queue the buffered
/// audio samples for playback.
/// </param>
/// <param name="dataSource">
/// A sequence of <see cref="Mat"/> objects representing the buffered audio samples
/// to queue for playback on all the active audio sources.
/// </param>
/// <returns>
/// An observable sequence that is identical to the <paramref name="dataSource"/>
/// sequence but where there is an additional side effect of queueing the audio buffers
/// for playback on all the active audio sources.
/// </returns>
/// <remarks>
/// This operator only subscribes to the <paramref name="dataSource"/> sequence
/// after initializing the audio context on the specified audio device.
/// </remarks>
[Obsolete]
public IObservable<Mat> Process(IObservable<AudioSource> audioSource, IObservable<Mat> dataSource)
{
return Process(dataSource, audioSource);
}
}
}
|
using CryptoExchange.Net;
using CryptoExchange.Net.Objects;
using Newtonsoft.Json;
using Okex.Net.Converters;
using Okex.Net.CoreObjects;
using Okex.Net.Enums;
using Okex.Net.Helpers;
using Okex.Net.RestObjects.Account;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Okex.Net
{
public partial class OkexClient
{
#region Account API Endpoints
/// <summary>
/// Retrieve a list of assets (with non-zero balance), remaining balance, and available amount in the account.
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<OkexAccountBalance> GetAccountBalance(string currency = null, CancellationToken ct = default) => GetAccountBalance_Async(currency, ct).Result;
/// <summary>
/// Retrieve a list of assets (with non-zero balance), remaining balance, and available amount in the account.
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<OkexAccountBalance>> GetAccountBalance_Async(string currency = null, CancellationToken ct = default)
{
var parameters = new Dictionary<string, object>();
parameters.AddOptionalParameter("ccy", currency);
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexAccountBalance>>>(GetUrl(Endpoints_V5_Account_Balance), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<OkexAccountBalance>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<OkexAccountBalance>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<OkexAccountBalance>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data.FirstOrDefault(), null);
}
/// <summary>
/// Retrieve information on your positions. When the account is in net mode, net positions will be displayed, and when the account is in long/short mode, long or short positions will be displayed.
/// </summary>
/// <param name="instrumentType">Instrument Type</param>
/// <param name="instrumentId">Instrument ID</param>
/// <param name="positionId">Position ID</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<IEnumerable<OkexPosition>> GetAccountPositions(
OkexInstrumentType? instrumentType = null,
string instrumentId = null,
string positionId = null,
CancellationToken ct = default) => GetAccountPositions_Async(instrumentType, instrumentId, positionId, ct).Result;
/// <summary>
/// Retrieve information on your positions. When the account is in net mode, net positions will be displayed, and when the account is in long/short mode, long or short positions will be displayed.
/// </summary>
/// <param name="instrumentType">Instrument Type</param>
/// <param name="instrumentId">Instrument ID</param>
/// <param name="positionId">Position ID</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<IEnumerable<OkexPosition>>> GetAccountPositions_Async(
OkexInstrumentType? instrumentType = null,
string instrumentId = null,
string positionId = null,
CancellationToken ct = default)
{
var parameters = new Dictionary<string, object>();
if (instrumentType.HasValue)
parameters.AddOptionalParameter("instType", JsonConvert.SerializeObject(instrumentType, new InstrumentTypeConverter(false)));
parameters.AddOptionalParameter("instId", instrumentId);
parameters.AddOptionalParameter("posId", positionId);
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexPosition>>>(GetUrl(Endpoints_V5_Account_Positions), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<IEnumerable<OkexPosition>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<IEnumerable<OkexPosition>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<IEnumerable<OkexPosition>>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data, null);
}
/// <summary>
/// Get account and position risk
/// </summary>
/// <param name="instrumentType">Instrument Type</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<IEnumerable<OkexPositionRisk>> GetAccountPositionRisk(OkexInstrumentType? instrumentType = null, CancellationToken ct = default) => GetAccountPositionRisk_Async(instrumentType, ct).Result;
/// <summary>
/// Get account and position risk
/// </summary>
/// <param name="instrumentType">Instrument Type</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<IEnumerable<OkexPositionRisk>>> GetAccountPositionRisk_Async(OkexInstrumentType? instrumentType = null, CancellationToken ct = default)
{
var parameters = new Dictionary<string, object>();
if (instrumentType.HasValue)
parameters.AddOptionalParameter("instType", JsonConvert.SerializeObject(instrumentType, new InstrumentTypeConverter(false)));
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexPositionRisk>>>(GetUrl(Endpoints_V5_Account_PositionRisk), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<IEnumerable<OkexPositionRisk>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<IEnumerable<OkexPositionRisk>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<IEnumerable<OkexPositionRisk>>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data, null);
}
/// <summary>
/// Retrieve the bills of the account. The bill refers to all transaction records that result in changing the balance of an account. Pagination is supported, and the response is sorted with the most recent first. This endpoint can retrieve data from the last 7 days.
/// </summary>
/// <param name="instrumentType">Instrument Type</param>
/// <param name="currency">Currency</param>
/// <param name="marginMode">Margin Mode</param>
/// <param name="contractType">Contract Type</param>
/// <param name="billType">Bill Type</param>
/// <param name="billSubType">Bill Sub Type</param>
/// <param name="after">Pagination of data to return records earlier than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="before">Pagination of data to return records newer than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="limit">Number of results per request. The maximum is 100; the default is 100.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<IEnumerable<OkexAccountBill>> GetBillHistory(
OkexInstrumentType? instrumentType = null,
string currency = null,
OkexMarginMode? marginMode = null,
OkexContractType? contractType = null,
OkexAccountBillType? billType = null,
OkexAccountBillSubType? billSubType = null,
long? after = null,
long? before = null,
int limit = 100,
CancellationToken ct = default) => GetBillHistory_Async(
instrumentType,
currency,
marginMode,
contractType,
billType,
billSubType,
after,
before,
limit,
ct).Result;
/// <summary>
/// Retrieve the bills of the account. The bill refers to all transaction records that result in changing the balance of an account. Pagination is supported, and the response is sorted with the most recent first. This endpoint can retrieve data from the last 7 days.
/// </summary>
/// <param name="instrumentType">Instrument Type</param>
/// <param name="currency">Currency</param>
/// <param name="marginMode">Margin Mode</param>
/// <param name="contractType">Contract Type</param>
/// <param name="billType">Bill Type</param>
/// <param name="billSubType">Bill Sub Type</param>
/// <param name="after">Pagination of data to return records earlier than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="before">Pagination of data to return records newer than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="limit">Number of results per request. The maximum is 100; the default is 100.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<IEnumerable<OkexAccountBill>>> GetBillHistory_Async(
OkexInstrumentType? instrumentType = null,
string currency = null,
OkexMarginMode? marginMode = null,
OkexContractType? contractType = null,
OkexAccountBillType? billType = null,
OkexAccountBillSubType? billSubType = null,
long? after = null,
long? before = null,
int limit = 100,
CancellationToken ct = default)
{
if (limit < 1 || limit > 100)
throw new ArgumentException("Limit can be between 1-100.");
var parameters = new Dictionary<string, object>();
parameters.AddOptionalParameter("ccy", currency);
parameters.AddOptionalParameter("after", after?.ToString());
parameters.AddOptionalParameter("before", before?.ToString());
parameters.AddOptionalParameter("limit", limit.ToString());
if (instrumentType.HasValue)
parameters.AddOptionalParameter("instType", JsonConvert.SerializeObject(instrumentType, new InstrumentTypeConverter(false)));
if (marginMode.HasValue)
parameters.AddOptionalParameter("mgnMode", JsonConvert.SerializeObject(marginMode, new MarginModeConverter(false)));
if (contractType.HasValue)
parameters.AddOptionalParameter("ctType", JsonConvert.SerializeObject(contractType, new ContractTypeConverter(false)));
if (billType.HasValue)
parameters.AddOptionalParameter("type", JsonConvert.SerializeObject(billType, new AccountBillTypeConverter(false)));
if (billSubType.HasValue)
parameters.AddOptionalParameter("subType", JsonConvert.SerializeObject(billSubType, new AccountBillSubTypeConverter(false)));
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexAccountBill>>>(GetUrl(Endpoints_V5_Account_Bills), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<IEnumerable<OkexAccountBill>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<IEnumerable<OkexAccountBill>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<IEnumerable<OkexAccountBill>>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data, null);
}
/// <summary>
/// Retrieve the account’s bills. The bill refers to all transaction records that result in changing the balance of an account. Pagination is supported, and the response is sorted with most recent first. This endpoint can retrieve data from the last 3 months.
/// </summary>
/// <param name="instrumentType">Instrument Type</param>
/// <param name="currency">Currency</param>
/// <param name="marginMode">Margin Mode</param>
/// <param name="contractType">Contract Type</param>
/// <param name="billType">Bill Type</param>
/// <param name="billSubType">Bill Sub Type</param>
/// <param name="after">Pagination of data to return records earlier than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="before">Pagination of data to return records newer than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="limit">Number of results per request. The maximum is 100; the default is 100.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<IEnumerable<OkexAccountBill>> GetBillArchive(
OkexInstrumentType? instrumentType = null,
string currency = null,
OkexMarginMode? marginMode = null,
OkexContractType? contractType = null,
OkexAccountBillType? billType = null,
OkexAccountBillSubType? billSubType = null,
long? after = null,
long? before = null,
int limit = 100,
CancellationToken ct = default) => GetBillArchive_Async(
instrumentType,
currency,
marginMode,
contractType,
billType,
billSubType,
after,
before,
limit,
ct).Result;
/// <summary>
/// Retrieve the account’s bills. The bill refers to all transaction records that result in changing the balance of an account. Pagination is supported, and the response is sorted with most recent first. This endpoint can retrieve data from the last 3 months.
/// </summary>
/// <param name="instrumentType">Instrument Type</param>
/// <param name="currency">Currency</param>
/// <param name="marginMode">Margin Mode</param>
/// <param name="contractType">Contract Type</param>
/// <param name="billType">Bill Type</param>
/// <param name="billSubType">Bill Sub Type</param>
/// <param name="after">Pagination of data to return records earlier than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="before">Pagination of data to return records newer than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="limit">Number of results per request. The maximum is 100; the default is 100.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<IEnumerable<OkexAccountBill>>> GetBillArchive_Async(
OkexInstrumentType? instrumentType = null,
string currency = null,
OkexMarginMode? marginMode = null,
OkexContractType? contractType = null,
OkexAccountBillType? billType = null,
OkexAccountBillSubType? billSubType = null,
long? after = null,
long? before = null,
int limit = 100,
CancellationToken ct = default)
{
if (limit < 1 || limit > 100)
throw new ArgumentException("Limit can be between 1-100.");
var parameters = new Dictionary<string, object>();
parameters.AddOptionalParameter("ccy", currency);
parameters.AddOptionalParameter("after", after?.ToString());
parameters.AddOptionalParameter("before", before?.ToString());
parameters.AddOptionalParameter("limit", limit.ToString());
if (instrumentType.HasValue)
parameters.AddOptionalParameter("instType", JsonConvert.SerializeObject(instrumentType, new InstrumentTypeConverter(false)));
if (marginMode.HasValue)
parameters.AddOptionalParameter("mgnMode", JsonConvert.SerializeObject(marginMode, new MarginModeConverter(false)));
if (contractType.HasValue)
parameters.AddOptionalParameter("ctType", JsonConvert.SerializeObject(contractType, new ContractTypeConverter(false)));
if (billType.HasValue)
parameters.AddOptionalParameter("type", JsonConvert.SerializeObject(billType, new AccountBillTypeConverter(false)));
if (billSubType.HasValue)
parameters.AddOptionalParameter("subType", JsonConvert.SerializeObject(billSubType, new AccountBillSubTypeConverter(false)));
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexAccountBill>>>(GetUrl(Endpoints_V5_Account_BillsArchive), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<IEnumerable<OkexAccountBill>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<IEnumerable<OkexAccountBill>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<IEnumerable<OkexAccountBill>>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data, null);
}
/// <summary>
/// Retrieve current account configuration.
/// </summary>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<OkexConfiguration> GetAccountConfiguration(CancellationToken ct = default) => GetAccountConfiguration_Async(ct).Result;
/// <summary>
/// Retrieve current account configuration.
/// </summary>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<OkexConfiguration>> GetAccountConfiguration_Async(CancellationToken ct = default)
{
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexConfiguration>>>(GetUrl(Endpoints_V5_Account_Config), HttpMethod.Get, ct, null, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<OkexConfiguration>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<OkexConfiguration>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<OkexConfiguration>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data.FirstOrDefault(), null);
}
/// <summary>
/// FUTURES and SWAP support both long/short mode and net mode. In net mode, users can only have positions in one direction; In long/short mode, users can hold positions in long and short directions.
/// </summary>
/// <param name="positionMode"></param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<RestObjects.Account.OkexPositionMode> SetAccountPositionMode(Enums.OkexPositionMode positionMode, CancellationToken ct = default) => SetAccountPositionMode_Async(positionMode, ct).Result;
/// <summary>
/// FUTURES and SWAP support both long/short mode and net mode. In net mode, users can only have positions in one direction; In long/short mode, users can hold positions in long and short directions.
/// </summary>
/// <param name="positionMode"></param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<RestObjects.Account.OkexPositionMode>> SetAccountPositionMode_Async(Enums.OkexPositionMode positionMode, CancellationToken ct = default)
{
var parameters = new Dictionary<string, object> {
{"posMode", JsonConvert.SerializeObject(positionMode, new PositionModeConverter(false)) },
};
var result = await base.SendRequestAsync<OkexRestApiResponse<IEnumerable<RestObjects.Account.OkexPositionMode>>>(GetUrl(Endpoints_V5_Account_SetPositionMode), HttpMethod.Post, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<RestObjects.Account.OkexPositionMode>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<RestObjects.Account.OkexPositionMode>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<RestObjects.Account.OkexPositionMode>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data.FirstOrDefault(), null);
}
/// <summary>
/// Get Leverage
/// </summary>
/// <param name="instrumentIds">Single instrument ID or multiple instrument IDs (no more than 20) separated with comma</param>
/// <param name="marginMode">Margin Mode</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<IEnumerable<OkexLeverage>> GetAccountLeverage(
string instrumentIds,
OkexMarginMode marginMode,
CancellationToken ct = default) => GetAccountLeverage_Async(instrumentIds, marginMode, ct).Result;
/// <summary>
/// Get Leverage
/// </summary>
/// <param name="instrumentIds">Single instrument ID or multiple instrument IDs (no more than 20) separated with comma</param>
/// <param name="marginMode">Margin Mode</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<IEnumerable<OkexLeverage>>> GetAccountLeverage_Async(
string instrumentIds,
OkexMarginMode marginMode,
CancellationToken ct = default)
{
var parameters = new Dictionary<string, object> {
{"instId", instrumentIds },
{"mgnMode", JsonConvert.SerializeObject(marginMode, new MarginModeConverter(false)) },
};
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexLeverage>>>(GetUrl(Endpoints_V5_Account_LeverageInfo), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<IEnumerable<OkexLeverage>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<IEnumerable<OkexLeverage>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<IEnumerable<OkexLeverage>>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data, null);
}
/// <summary>
/// The following are the setting leverage cases for an instrument:
/// Set leverage for isolated MARGIN at pairs level.
/// Set leverage for cross MARGIN in Single-currency margin at pairs level.
/// Set leverage for cross MARGIN in Multi-currency margin at currency level.
/// Set leverage for cross/isolated FUTURES/SWAP at underlying/contract level.
/// </summary>
/// <param name="leverage">Leverage</param>
/// <param name="currency">Currency</param>
/// <param name="instrumentId">Instrument ID</param>
/// <param name="marginMode">Margin Mode</param>
/// <param name="positionSide">Position Side</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<IEnumerable<OkexLeverage>> SetAccountLeverage(
int leverage,
string currency = null,
string instrumentId = null,
OkexMarginMode? marginMode = null,
OkexPositionSide? positionSide = null,
CancellationToken ct = default) => SetAccountLeverage_Async(leverage, currency, instrumentId, marginMode, positionSide, ct).Result;
/// <summary>
/// The following are the setting leverage cases for an instrument:
/// Set leverage for isolated MARGIN at pairs level.
/// Set leverage for cross MARGIN in Single-currency margin at pairs level.
/// Set leverage for cross MARGIN in Multi-currency margin at currency level.
/// Set leverage for cross/isolated FUTURES/SWAP at underlying/contract level.
/// </summary>
/// <param name="leverage">Leverage</param>
/// <param name="currency">Currency</param>
/// <param name="instrumentId">Instrument ID</param>
/// <param name="marginMode">Margin Mode</param>
/// <param name="positionSide">Position Side</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<IEnumerable<OkexLeverage>>> SetAccountLeverage_Async(
int leverage,
string currency = null,
string instrumentId = null,
OkexMarginMode? marginMode = null,
OkexPositionSide? positionSide = null,
CancellationToken ct = default)
{
if (leverage < 1)
throw new ArgumentException("Invalid Leverage");
if (string.IsNullOrEmpty(currency) && string.IsNullOrEmpty(instrumentId))
throw new ArgumentException("Either instId or ccy is required; if both are passed, instId will be used by default.");
if (marginMode == null)
throw new ArgumentException("marginMode is required");
var parameters = new Dictionary<string, object> {
{"lever", leverage.ToString() },
{"mgnMode", JsonConvert.SerializeObject(marginMode, new MarginModeConverter(false)) },
};
parameters.AddOptionalParameter("ccy", currency);
parameters.AddOptionalParameter("instId", instrumentId);
if (positionSide.HasValue)
parameters.AddOptionalParameter("posSide", JsonConvert.SerializeObject(positionSide, new PositionSideConverter(false)));
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexLeverage>>>(GetUrl(Endpoints_V5_Account_SetLeverage), HttpMethod.Post, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<IEnumerable<OkexLeverage>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<IEnumerable<OkexLeverage>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<IEnumerable<OkexLeverage>>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data, null);
}
/// <summary>
/// Get maximum buy/sell amount or open amount
/// </summary>
/// <param name="instrumentId">Instrument ID</param>
/// <param name="tradeMode">Trade Mode</param>
/// <param name="currency">Currency</param>
/// <param name="price">Price</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<IEnumerable<OkexMaximumAmount>> GetMaximumAmount(
string instrumentId,
OkexTradeMode tradeMode,
string currency = null,
decimal? price = null,
CancellationToken ct = default) => GetMaximumAmount_Async(instrumentId, tradeMode, currency, price, ct).Result;
/// <summary>
/// Get maximum buy/sell amount or open amount
/// </summary>
/// <param name="instrumentId">Instrument ID</param>
/// <param name="tradeMode">Trade Mode</param>
/// <param name="currency">Currency</param>
/// <param name="price">Price</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<IEnumerable<OkexMaximumAmount>>> GetMaximumAmount_Async(
string instrumentId,
OkexTradeMode tradeMode,
string currency = null,
decimal? price = null,
CancellationToken ct = default)
{
var parameters = new Dictionary<string, object> {
{"instId", instrumentId },
{"tdMode", JsonConvert.SerializeObject(tradeMode, new TradeModeConverter(false)) },
};
parameters.AddOptionalParameter("ccy", currency);
parameters.AddOptionalParameter("px", price?.ToString(OkexGlobals.OkexCultureInfo));
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexMaximumAmount>>>(GetUrl(Endpoints_V5_Account_MaxSize), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<IEnumerable<OkexMaximumAmount>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<IEnumerable<OkexMaximumAmount>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<IEnumerable<OkexMaximumAmount>>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data, null);
}
/// <summary>
/// Get Maximum Available Tradable Amount
/// </summary>
/// <param name="instrumentId">Instrument ID</param>
/// <param name="tradeMode">Trade Mode</param>
/// <param name="currency">Currency</param>
/// <param name="reduceOnly">Reduce Only</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<IEnumerable<OkexMaximumAvailableAmount>> GetMaximumAvailableAmount(
string instrumentId,
OkexTradeMode tradeMode,
string currency = null,
bool? reduceOnly = null,
CancellationToken ct = default) => GetMaximumAvailableAmount_Async(instrumentId, tradeMode, currency, reduceOnly, ct).Result;
/// <summary>
/// Get Maximum Available Tradable Amount
/// </summary>
/// <param name="instrumentId">Instrument ID</param>
/// <param name="tradeMode">Trade Mode</param>
/// <param name="currency">Currency</param>
/// <param name="reduceOnly">Reduce Only</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<IEnumerable<OkexMaximumAvailableAmount>>> GetMaximumAvailableAmount_Async(
string instrumentId,
OkexTradeMode tradeMode,
string currency = null,
bool? reduceOnly = null,
CancellationToken ct = default)
{
var parameters = new Dictionary<string, object> {
{"instId", instrumentId },
{"tdMode", JsonConvert.SerializeObject(tradeMode, new TradeModeConverter(false)) },
};
parameters.AddOptionalParameter("ccy", currency);
parameters.AddOptionalParameter("reduceOnly", reduceOnly);
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexMaximumAvailableAmount>>>(GetUrl(Endpoints_V5_Account_MaxAvailSize), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<IEnumerable<OkexMaximumAvailableAmount>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<IEnumerable<OkexMaximumAvailableAmount>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<IEnumerable<OkexMaximumAvailableAmount>>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data, null);
}
/// <summary>
/// Increase or decrease the margin of the isolated position.
/// </summary>
/// <param name="instrumentId">Instrument ID</param>
/// <param name="positionSide">Position Side</param>
/// <param name="marginAddReduce">Type</param>
/// <param name="amount">Amount</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<IEnumerable<OkexMarginAmount>> SetMarginAmount(
string instrumentId,
OkexPositionSide positionSide,
OkexMarginAddReduce marginAddReduce,
decimal amount,
CancellationToken ct = default) => SetMarginAmount_Async(instrumentId, positionSide, marginAddReduce, amount, ct).Result;
/// <summary>
/// Increase or decrease the margin of the isolated position.
/// </summary>
/// <param name="instrumentId">Instrument ID</param>
/// <param name="positionSide">Position Side</param>
/// <param name="marginAddReduce">Type</param>
/// <param name="amount">Amount</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<IEnumerable<OkexMarginAmount>>> SetMarginAmount_Async(
string instrumentId,
OkexPositionSide positionSide,
OkexMarginAddReduce marginAddReduce,
decimal amount,
CancellationToken ct = default)
{
var parameters = new Dictionary<string, object> {
{"instId", instrumentId },
{"posSide", JsonConvert.SerializeObject(positionSide, new PositionSideConverter(false)) },
{"type", JsonConvert.SerializeObject(marginAddReduce, new MarginAddReduceConverter(false)) },
{"amt", amount.ToString(OkexGlobals.OkexCultureInfo) },
};
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexMarginAmount>>>(GetUrl(Endpoints_V5_Account_PositionMarginBalance), HttpMethod.Post, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<IEnumerable<OkexMarginAmount>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<IEnumerable<OkexMarginAmount>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<IEnumerable<OkexMarginAmount>>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data, null);
}
/// <summary>
/// Get the maximum loan of instrument
/// </summary>
/// <param name="instrumentId">Instrument ID</param>
/// <param name="marginMode">Margin Mode</param>
/// <param name="marginCurrency">Margin Currency</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<IEnumerable<OkexMaximumLoanAmount>> GetMaximumLoanAmount(
string instrumentId,
OkexMarginMode marginMode,
string marginCurrency = null,
CancellationToken ct = default) => GetMaximumLoanAmount_Async(instrumentId, marginMode, marginCurrency, ct).Result;
/// <summary>
/// Get the maximum loan of instrument
/// </summary>
/// <param name="instrumentId">Instrument ID</param>
/// <param name="marginMode">Margin Mode</param>
/// <param name="marginCurrency">Margin Currency</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<IEnumerable<OkexMaximumLoanAmount>>> GetMaximumLoanAmount_Async(
string instrumentId,
OkexMarginMode marginMode,
string marginCurrency = null,
CancellationToken ct = default)
{
var parameters = new Dictionary<string, object> {
{"instId", instrumentId },
{"mgnMode", JsonConvert.SerializeObject(marginMode, new MarginModeConverter(false)) },
};
parameters.AddOptionalParameter("mgnCcy", marginCurrency);
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexMaximumLoanAmount>>>(GetUrl(Endpoints_V5_Account_MaxLoan), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<IEnumerable<OkexMaximumLoanAmount>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<IEnumerable<OkexMaximumLoanAmount>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<IEnumerable<OkexMaximumLoanAmount>>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data, null);
}
/// <summary>
/// Get Fee Rates
/// </summary>
/// <param name="instrumentType">Instrument Type</param>
/// <param name="instrumentId">Instrument ID</param>
/// <param name="underlying">Underlying</param>
/// <param name="category">Category</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<OkexFeeRate> GetFeeRates(
OkexInstrumentType instrumentType,
string instrumentId = null,
string underlying = null,
OkexFeeRateCategory? category = null,
CancellationToken ct = default) => GetFeeRates_Async(instrumentType, instrumentId, underlying, category, ct).Result;
/// <summary>
/// Get Fee Rates
/// </summary>
/// <param name="instrumentType">Instrument Type</param>
/// <param name="instrumentId">Instrument ID</param>
/// <param name="underlying">Underlying</param>
/// <param name="category">Category</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<OkexFeeRate>> GetFeeRates_Async(
OkexInstrumentType instrumentType,
string instrumentId = null,
string underlying = null,
OkexFeeRateCategory? category = null,
CancellationToken ct = default)
{
var parameters = new Dictionary<string, object> {
{"instType", JsonConvert.SerializeObject(instrumentType, new InstrumentTypeConverter(false)) },
};
parameters.AddOptionalParameter("instId", instrumentId);
parameters.AddOptionalParameter("uly", underlying);
parameters.AddOptionalParameter("category", JsonConvert.SerializeObject(category, new FeeRateCategoryConverter(false)));
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexFeeRate>>>(GetUrl(Endpoints_V5_Account_TradeFee), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<OkexFeeRate>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<OkexFeeRate>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<OkexFeeRate>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data.FirstOrDefault(), null);
}
/// <summary>
/// Get interest-accrued
/// </summary>
/// <param name="instrumentId">Instrument ID</param>
/// <param name="currency">Currency</param>
/// <param name="marginMode">Margin Mode</param>
/// <param name="after">Pagination of data to return records earlier than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="before">Pagination of data to return records newer than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="limit">Number of results per request. The maximum is 100; the default is 100.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<IEnumerable<OkexInterestAccrued>> GetInterestAccrued(
string instrumentId = null,
string currency = null,
OkexMarginMode? marginMode = null,
long? after = null,
long? before = null,
int limit = 100,
CancellationToken ct = default) => GetInterestAccrued_Async(
instrumentId,
currency,
marginMode,
after,
before,
limit,
ct).Result;
/// <summary>
/// Get interest-accrued
/// </summary>
/// <param name="instrumentId">Instrument ID</param>
/// <param name="currency">Currency</param>
/// <param name="marginMode">Margin Mode</param>
/// <param name="after">Pagination of data to return records earlier than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="before">Pagination of data to return records newer than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="limit">Number of results per request. The maximum is 100; the default is 100.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<IEnumerable<OkexInterestAccrued>>> GetInterestAccrued_Async(
string instrumentId = null,
string currency = null,
OkexMarginMode? marginMode = null,
long? after = null,
long? before = null,
int limit = 100,
CancellationToken ct = default)
{
if (limit < 1 || limit > 100)
throw new ArgumentException("Limit can be between 1-100.");
var parameters = new Dictionary<string, object>();
parameters.AddOptionalParameter("instId", instrumentId);
parameters.AddOptionalParameter("ccy", currency);
parameters.AddOptionalParameter("after", after?.ToString());
parameters.AddOptionalParameter("before", before?.ToString());
parameters.AddOptionalParameter("limit", limit.ToString());
if (marginMode.HasValue)
parameters.AddOptionalParameter("mgnMode", JsonConvert.SerializeObject(marginMode, new MarginModeConverter(false)));
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexInterestAccrued>>>(GetUrl(Endpoints_V5_Account_InterestAccrued), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<IEnumerable<OkexInterestAccrued>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<IEnumerable<OkexInterestAccrued>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<IEnumerable<OkexInterestAccrued>>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data, null);
}
/// <summary>
/// Get the user's current leveraged currency borrowing interest rate
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<IEnumerable<OkexInterestRate>> GetInterestRate(
string currency = null,
CancellationToken ct = default) => GetInterestRate_Async(
currency,
ct).Result;
/// <summary>
/// Get the user's current leveraged currency borrowing interest rate
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<IEnumerable<OkexInterestRate>>> GetInterestRate_Async(
string currency = null,
CancellationToken ct = default)
{
var parameters = new Dictionary<string, object>();
parameters.AddOptionalParameter("ccy", currency);
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexInterestRate>>>(GetUrl(Endpoints_V5_Account_InterestRate), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<IEnumerable<OkexInterestRate>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<IEnumerable<OkexInterestRate>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<IEnumerable<OkexInterestRate>>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data, null);
}
/// <summary>
/// Set the display type of Greeks.
/// </summary>
/// <param name="greeksType">Display type of Greeks.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<RestObjects.Account.OkexGreeksType> SetGreeks(Enums.OkexGreeksType greeksType, CancellationToken ct = default) => SetGreeks_Async(greeksType, ct).Result;
/// <summary>
/// Set the display type of Greeks.
/// </summary>
/// <param name="greeksType">Display type of Greeks.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<RestObjects.Account.OkexGreeksType>> SetGreeks_Async(Enums.OkexGreeksType greeksType, CancellationToken ct = default)
{
var parameters = new Dictionary<string, object> {
{"greeksType", JsonConvert.SerializeObject(greeksType, new GreeksTypeConverter(false)) },
};
var result = await base.SendRequestAsync<OkexRestApiResponse<IEnumerable<RestObjects.Account.OkexGreeksType>>>(GetUrl(Endpoints_V5_Account_SetGreeks), HttpMethod.Post, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<RestObjects.Account.OkexGreeksType>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<RestObjects.Account.OkexGreeksType>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<RestObjects.Account.OkexGreeksType>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data.FirstOrDefault(), null);
}
/// <summary>
/// Retrieve the maximum transferable amount.
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<IEnumerable<OkexWithdrawalAmount>> GetMaximumWithdrawals(
string currency = null,
CancellationToken ct = default) => GetMaximumWithdrawals_Async(
currency,
ct).Result;
/// <summary>
/// Retrieve the maximum transferable amount.
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<IEnumerable<OkexWithdrawalAmount>>> GetMaximumWithdrawals_Async(
string currency = null,
CancellationToken ct = default)
{
var parameters = new Dictionary<string, object>();
parameters.AddOptionalParameter("ccy", currency);
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexWithdrawalAmount>>>(GetUrl(Endpoints_V5_Account_MaxWithdrawal), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<IEnumerable<OkexWithdrawalAmount>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<IEnumerable<OkexWithdrawalAmount>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<IEnumerable<OkexWithdrawalAmount>>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data, null);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Algorithmica.DataStructures
{
public class Stack<TItem>
{
protected List<TItem> dataStorage;
private int currentIndex = 0;
public Stack()
{
dataStorage = new List<TItem>();
}
public Stack(IEnumerable<TItem> initialData)
{
dataStorage = new List<TItem>(initialData);
currentIndex = dataStorage.Count - 1;
}
public TItem Peek()
{
throw new NotImplementedException();
}
public TItem Pop()
{
if (IsEmpty()) throw new InvalidOperationException();
TItem item = dataStorage[currentIndex];
dataStorage.RemoveAt(currentIndex);
currentIndex--;
return item;
}
public bool TryPop(out TItem item)
{
if (IsEmpty())
{
item = default(TItem);
return false;
}
item = dataStorage[currentIndex];
dataStorage.RemoveAt(currentIndex);
currentIndex--;
return true;
}
public void Push()
{
throw new NotImplementedException();
}
public bool IsEmpty()
{
return dataStorage.Count == 0;
}
}
} |
using System.Reflection;
namespace Framework.DomainDriven.UnitTest.Mock.StubProxy
{
public interface IOverrideMethodInfo
{
MethodInfo MethodBase { get; }
object ReturnValue { get; }
}
} |
using UnityEngine;
namespace RTEditor
{
/// <summary>
/// Monobehaviours can implement this interface so that they can be able to
/// listen to different types of events and take action as needed.
/// </summary>
public interface IRTEditorEventListener
{
/// <summary>
/// Called before an object is about to be selected. Must return true if the
/// object can be selected and false otherwise.
/// </summary>
bool OnCanBeSelected(ObjectSelectEventArgs selectEventArgs);
/// <summary>
/// Called when the object has been selected.
/// </summary>
void OnSelected(ObjectSelectEventArgs selectEventArgs);
/// <summary>
/// Called when the object has been deselected.
/// </summary>
void OnDeselected(ObjectDeselectEventArgs deselectEventArgs);
/// <summary>
/// Called when the object is altered (moved, rotated or scaled) by a transform gizmo.
/// </summary>
/// <param name="gizmo">
/// The transform gzimo which alters the object.
/// </param>
void OnAlteredByTransformGizmo(Gizmo gizmo);
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
namespace SmartDisplay.Controls
{
public sealed partial class TileSettingsControl : SettingsUserControlBase
{
public TileSettingsControlVM ViewModel { get; } = new TileSettingsControlVM();
protected override SettingsBaseViewModel ViewModelImpl => ViewModel;
public TileSettingsControl() : base()
{
InitializeComponent();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Yandex.Maps.StaticAPI;
namespace YandexMapsStaticApiTest
{
[TestFixture]
class PointTest
{
double _lat_min=-84.99;
double _lat_max = 84.99;
double _lon_min=-179.99;
double _lon_max = 179.99;
Point p1 = new Point(56.013076, 92.844363);
Point p2 = new Point(56.012805, 92.860652);
Point p3 = new Point(56.035243, 92.803918);
Point p4 = new Point(56.026938, 92.811484);
Point p1d = new Point(56.013076, 92.844363);
Point p2d = new Point(56.012805, 92.860652);
[Test]
public void PointIntilizationStandart()
{
double lat = 53.1235654456;
double lon = 93.5498495156;
Point Point = new Point(lat, lon);
Assert.AreEqual(lat, Point.Lat);
Assert.AreEqual(lon, Point.Lon);
}
[Test]
public void PointIntilizationNegative()
{
double lat = -90;
double lon = -180;
Point Point = new Point(lat, lon);
Assert.AreEqual(_lat_min, Point.Lat);
Assert.AreEqual(_lon_min, Point.Lon);
}
[Test]
public void PointIntilizationMax()
{
double lat = 90;
double lon = 180;
Point Point = new Point(lat, lon);
Assert.AreEqual(_lat_max, Point.Lat);
Assert.AreEqual(_lon_max, Point.Lon);
}
[Test]
public void PointEquality()
{
Assert.AreEqual(p1,p1d);
Assert.AreEqual(p2, p2d);
}
[Test]
public void PointInequality()
{
Assert.AreNotEqual(p1, p2);
Assert.AreNotEqual(p1, p3);
Assert.AreNotEqual(p1, p4);
Assert.AreNotEqual(p2, p1);
Assert.AreNotEqual(p2, p3);
Assert.AreNotEqual(p2, p4);
Assert.AreNotEqual(p3, p1);
Assert.AreNotEqual(p3, p2);
Assert.AreNotEqual(p3, p4);
Assert.AreNotEqual(p4, p1);
Assert.AreNotEqual(p4, p2);
Assert.AreNotEqual(p4, p3);
}
}
}
|
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;
namespace Microsoft.AspNetCore.SpaServices.Prerendering
{
/// <summary>
/// Describes the prerendering result returned by JavaScript code.
/// </summary>
public class RenderToStringResult
{
/// <summary>
/// If set, specifies JSON-serializable data that should be added as a set of global JavaScript variables in the document.
/// This can be used to transfer arbitrary data from server-side prerendering code to client-side code (for example, to
/// transfer the state of a Redux store).
/// </summary>
public JObject Globals { get; set; }
/// <summary>
/// The HTML generated by the prerendering logic.
/// </summary>
public string Html { get; set; }
/// <summary>
/// If set, specifies that instead of rendering HTML, the response should be an HTTP redirection to this URL.
/// This can be used if the prerendering code determines that the requested URL would lead to a redirection according
/// to the SPA's routing configuration.
/// </summary>
public string RedirectUrl { get; set; }
/// <summary>
/// If set, specifies the HTTP status code that should be sent back with the server response.
/// </summary>
public int? StatusCode { get; set; }
/// <summary>
/// Constructs a block of JavaScript code that assigns data from the
/// <see cref="Globals"/> property to the global namespace.
/// </summary>
/// <returns>A block of JavaScript code.</returns>
public string CreateGlobalsAssignmentScript()
{
if (Globals == null)
{
return string.Empty;
}
var stringBuilder = new StringBuilder();
foreach (var property in Globals.Properties())
{
stringBuilder.AppendFormat("window.{0} = {1};",
property.Name,
property.Value.ToString(Formatting.None));
}
return stringBuilder.ToString();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Upds.Sistemas.ProgWeb2.Tintoreria.MVC.Models
{
public class CorreoModel
{
[Display(Name ="Id Correo")]
public int idCorreo { get; set; }
[Required(ErrorMessage ="El campo Nombre Correo es requerido")]
[Display(Name="Nombre")]
public string Nombre { get; set; }
[Display(Name ="Principal")]
public bool Principal { get; set; }
}
} |
using FluentAssertions;
using Moq;
using SpecificationPattern.Core.Specifications;
using Xunit;
namespace SpecificationPattern.Core.Tests.Specifications
{
public class SpecificationExtenstionsTests
{
[Fact]
public void And_ReturnsAndSpecification()
{
var left = new Mock<ISpecification<object>>();
var right = new Mock<ISpecification<object>>();
var result = left.Object.And(right.Object);
result.Should().BeOfType(typeof(AndSpecification<object>));
}
[Fact]
public void Or_ReturnsOrSpecification()
{
var left = new Mock<ISpecification<object>>();
var right = new Mock<ISpecification<object>>();
var result = left.Object.Or(right.Object);
result.Should().BeOfType(typeof(OrSpecification<object>));
}
[Fact]
public void Not_ReturnsNotSpecification()
{
var SUT = new Mock<ISpecification<object>>();
var result = SUT.Object.Not();
result.Should().BeOfType(typeof(NotSpecification<object>));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
namespace WG.Controllers
{
public class Root
{
public const string Base = "api";
}
public class ApiController : ControllerBase
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Anthurium.Web.Models
{
public class UtilitySettings
{
public const string ApiUrl = "ApiUrl";
public string APP_URL { get; set; }
}
}
|
using Qooba.Framework.Abstractions;
using Qooba.Framework.Bot.Abstractions;
namespace Qooba.Framework.Bot.Azure
{
public class BotAzureModule : IModule
{
public virtual string Name => "BotAzureModule";
public int Priority => 20;
public void Bootstrapp(IFramework framework)
{
framework.AddTransientService<IStateManager, AzureStateManager>();
framework.AddTransientService<IUserProfileService, AzureUserProfileService>();
framework.AddTransientService<IMessageQueue, AzureMessageQueue>();
}
}
}
|
using NaughtyAttributes;
using UnityEngine;
namespace GameplayIngredients.Rigs
{
[AddComponentMenu(ComponentMenu.rigsPath + "Reach Position Rig")]
public class ReachPositionRig : Rig
{
public override int defaultPriority => 0;
public override UpdateMode defaultUpdateMode => UpdateMode.LateUpdate;
public Transform target => m_Target;
[Header("Target")]
[SerializeField]
[InfoBox("Target needs to have the same parent as the current game object", EInfoBoxType.Warning)]
protected Transform m_Target;
[Header("Motion")]
public float Dampen = 1.0f;
public float MaximumVelocity = 1.0f;
public bool inLocalSpace = false;
[Header("On Reach Position")]
public Callable[] OnReachPosition;
public float ReachSnapDistance = 0.01f;
bool m_PositionReached = false;
bool warnLocalParent()
{
return m_Target != null && m_Target.transform.parent != transform.parent;
}
public override void UpdateRig(float deltaTime)
{
if(m_Target != null)
{
var transform = gameObject.transform;
Vector3 position = inLocalSpace ? transform.localPosition : transform.position;
Vector3 targetPosition = inLocalSpace ? m_Target.localPosition : m_Target.position;
if (Vector3.Distance(position, targetPosition) < ReachSnapDistance)
{
if(inLocalSpace)
transform.localPosition = targetPosition;
else
transform.position = targetPosition;
if(!m_PositionReached)
{
Callable.Call(OnReachPosition, this.gameObject);
m_PositionReached = true;
}
}
else
{
var delta = m_Target.position - transform.position;
var speed = deltaTime * Mathf.Min((Dampen * delta.magnitude), MaximumVelocity);
gameObject.transform.position += delta.normalized * speed;
m_PositionReached = false;
}
}
}
public void SetTarget(Transform target)
{
m_Target = target;
}
}
}
|
//Define classes File { string name, int size } and Folder { string name, File[] files, Folder[] childFolders }
//and using them build a tree keeping all files and folders on the hard drive starting from C:\WINDOWS.
//Implement a method that calculates the sum of the file sizes in given subtree of the tree and test it accordingly.
//Use recursive DFS traversal.
namespace _03.FileSystem
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
public class FileSystem
{
public static Folder root = new Folder("root");
public static void Main()
{
string startDir = @"C:\Windows\";
DFS(startDir, root);
var allSize = root.GetSizeFromHere();
Console.WriteLine(allSize);
}
private static void DFS(string dirToSearchIn, Folder currentDir)
{
try
{
//adding all files to current dir
foreach (var file in Directory.GetFiles(dirToSearchIn))
{
currentDir.AddFile(new File(file,new FileInfo(file).Length));
}
//adding all childDirs to current dir
foreach (var dir in Directory.GetDirectories(dirToSearchIn))
{
currentDir.AddSubFolder(new Folder(dir));
DFS(dir, currentDir.ChildFolders[currentDir.ChildFolders.Length - 1]);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
|
// Copyright (c) SDV Code Project. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace SdvCode.Areas.Administration.Services.SiteReports.ShopReports
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using SdvCode.Areas.Administration.ViewModels.SiteReports.ShopReports;
using SdvCode.Data;
public class ShopReport : IShopReport
{
private readonly ApplicationDbContext db;
private readonly List<string> rudeWords = new List<string>
{
"Bitch", "Fuck", "Suck", "Fuck yourself", "Suck balls", "Dick", "Fucker", "Gypsy", "Idiot", "Pedal",
"MotherFucker", "Mother fucker",
};
public ShopReport(ApplicationDbContext db)
{
this.db = db;
}
public ICollection<ShopCommentReportViewModel> GetCommentsData()
{
var comments = this.db.ProductComments.ToList();
var result = new List<ShopCommentReportViewModel>();
foreach (var comment in comments)
{
var contentWithoutTags = Regex.Replace(comment.Content, "<.*?>", string.Empty);
List<string> contentWords = contentWithoutTags.ToLower()
.Split(new[] { " ", ",", "-", "!", "?", ":", ";" }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
var targetModel = new ShopCommentReportViewModel
{
Content = contentWithoutTags,
Email = comment.Email,
FullName = comment.UserFullName,
PhoneNumber = comment.PhoneNumber,
Prediction =
contentWords.Any(x => this.rudeWords.Any(y => y.ToLower() == x)) ? "Rude" : string.Empty,
};
result.Add(targetModel);
}
return result;
}
public ICollection<ShopReviewReportViewModel> GetReviewsData()
{
var reviews = this.db.ProductReviews.ToList();
var result = new List<ShopReviewReportViewModel>();
foreach (var review in reviews)
{
var contentWithoutTags = Regex.Replace(review.Content, "<.*?>", string.Empty);
List<string> contentWords = contentWithoutTags.ToLower()
.Split(new[] { " ", ",", "-", "!", "?", ":", ";" }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
var targetModel = new ShopReviewReportViewModel
{
Content = contentWithoutTags,
Email = review.Email,
Stars = review.Stars,
FullName = review.UserFullName,
PhoneNumber = review.PhoneNumber,
Prediction =
contentWords.Any(x => this.rudeWords.Any(y => y.ToLower() == x)) ? "Rude" : string.Empty,
};
result.Add(targetModel);
}
return result;
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.