content
stringlengths
23
1.05M
using System.ComponentModel.DataAnnotations; namespace TT.Domain.Models { public class DMRoll { public int Id { get; set; } [StringLength(128)] public string MembershipOwnerId { get; set; } public string Message { get; set; } public string Tags { get; set; } public string ActionType { get; set; } public bool IsLive { get; set; } } }
using UnityEngine; using UnityEngine.UI; namespace Juce.Cheats.Widgets { public class ToggleWidget : MonoBehaviour { [SerializeField] private Button button = default; [SerializeField] private TMPro.TextMeshProUGUI text = default; [SerializeField] private GameObject toggleCheck = default; public Button Button => button; public TMPro.TextMeshProUGUI Text => text; public GameObject ToggleCheck => toggleCheck; } }
using System; using LibSvnSharp.Interop.Svn; namespace LibSvnSharp { [Flags] public enum SvnCommitTypes { None = 0, Added = svn_client_commit_item_enum_t.SVN_CLIENT_COMMIT_ITEM_ADD, Deleted = svn_client_commit_item_enum_t.SVN_CLIENT_COMMIT_ITEM_DELETE, ContentModified = svn_client_commit_item_enum_t.SVN_CLIENT_COMMIT_ITEM_TEXT_MODS, PropertiesModified = svn_client_commit_item_enum_t.SVN_CLIENT_COMMIT_ITEM_PROP_MODS, Copied = svn_client_commit_item_enum_t.SVN_CLIENT_COMMIT_ITEM_IS_COPY, HasLockToken = svn_client_commit_item_enum_t.SVN_CLIENT_COMMIT_ITEM_LOCK_TOKEN, MovedHere = svn_client_commit_item_enum_t.SVN_CLIENT_COMMIT_ITEM_MOVED_HERE, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Collections.Tests { public class PriorityQueue_Generic_Tests_string_string : PriorityQueue_Generic_Tests<string, string> { protected override (string, string) CreateT(int seed) { var element = this.CreateString(seed); var priority = this.CreateString(seed); return (element, priority); } protected string CreateString(int seed) { int stringLength = seed % 10 + 5; Random rand = new Random(seed); byte[] bytes = new byte[stringLength]; rand.NextBytes(bytes); return Convert.ToBase64String(bytes); } } public class PriorityQueue_Generic_Tests_int_int : PriorityQueue_Generic_Tests<int, int> { protected override (int, int) CreateT(int seed) { var element = this.CreateInt(seed); var priority = this.CreateInt(seed); return (element, priority); } protected int CreateInt(int seed) => new Random(seed).Next(); } }
using HVision.Varins.Interfaces.Algorithms; using HVision.Varins.Interfaces.ViewModels; using Microsoft.Practices.Prism.Mvvm; using Microsoft.Practices.Unity; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HVision.Varins.Cores { [JsonObject(MemberSerialization.OptIn)] public class SpecController : BindableBase { private readonly IUnityContainer _container = null; public SpecController(IUnityContainer container, ISpec spec) { _container = container; Spec = spec; } [JsonProperty] public ISpec Spec { get; } = null; } }
#if WORKINPROGRESS using System.Windows; using System; #if MIGRATION namespace System.Windows.Media.Animation #else namespace Windows.UI.Xaml.Media.Animation #endif { public sealed partial class DiscreteDoubleKeyFrame : DoubleKeyFrame { public DiscreteDoubleKeyFrame() { } } } #endif
using LiteNetLib.Utils; namespace MultiplayerARPG { public struct RequestPickupLootBagItemMessage : INetSerializable { public int dataId; public short fromIndex; public short toIndex; public void Deserialize(NetDataReader reader) { dataId = reader.GetPackedInt(); fromIndex = reader.GetPackedShort(); toIndex = reader.GetPackedShort(); } public void Serialize(NetDataWriter writer) { writer.PutPackedInt(dataId); writer.PutPackedShort(fromIndex); writer.PutPackedShort(toIndex); } } public struct RequestPickupAllLootBagItemsMessage : INetSerializable { public int dataId; public void Deserialize(NetDataReader reader) { dataId = reader.GetPackedInt(); } public void Serialize(NetDataWriter writer) { writer.PutPackedInt(dataId); } } public struct ResponsePickupLootBagItemMessage : INetSerializable { public UITextKeys message; public void Deserialize(NetDataReader reader) { message = (UITextKeys)reader.GetPackedUShort(); } public void Serialize(NetDataWriter writer) { writer.PutPackedUShort((ushort)message); } } public struct ResponsePickupAllLootBagItemsMessage : INetSerializable { public UITextKeys message; public void Deserialize(NetDataReader reader) { message = (UITextKeys)reader.GetPackedUShort(); } public void Serialize(NetDataWriter writer) { writer.PutPackedUShort((ushort)message); } } }
namespace Barber.OpenApi.Settings { using Newtonsoft.Json; public class SettingsModel { public SettingsModel() { } /// <summary> /// Which body Media Type is used for setting the Parameter Type /// </summary> /// <remarks> /// Since a API can have multiple allowed request types, /// we need to set which one we what to use for code generation. /// If no match could be find we use the first one in definition. /// </remarks> public string BodyMediaType { get; set; } = "application/json"; /// <summary> /// Is API Versioning used /// </summary> /// <remarks> /// In case you have URI like this /// "api/v{version}/controller/action/{id}" /// you need to set this option true /// </remarks> public bool HasApiVersion { get; set; } = true; /// <summary> /// Which Response Codes are use to set Return Types /// </summary> /// <remarks> /// Codes are matched in given order. First match will win. /// </remarks> public string[] ResponseCodes { get; set; } = new string[] { "200", "201" }; /// <summary> /// Which body Media Type is used for setting the Return Type /// </summary> /// <remarks> /// Since a API can have multiple allowed response types, /// we need to set which one we what to use for code generation. /// If no match could be find we use the first one in definition. /// </remarks> public string ResponseMediaType { get; set; } = "application/json"; /// <summary> /// Schema specific configuration /// </summary> public SchemaItemModel[] SchemaConfig { get; set; } /// <summary> /// Properties which are filtered out /// </summary> public string[] SkipProperties { get; set; } /// <summary> /// Schema's to Skip /// </summary> public string[] SkipSchemas { get; set; } /// <summary> /// Tag to Skip /// </summary> public string[] SkipTags { get; set; } /// <summary> /// Steps /// </summary> public StepModel[] Steps { get; set; } /// <summary> /// I18next /// </summary> public I18nModel[] I18n { get; set; } /// <summary> /// Template Root Path to templates, can be relative from assembly root /// </summary> public string TemplateRoot { get; set; } = "Templates"; /// <summary> /// Typescript Generator Settings /// </summary> public TypescriptSettingsModel Typescript { get; set; } = new TypescriptSettingsModel(); /// <summary> /// URL / Path to OpenAPI 3 File /// </summary> public string Url { get; set; } /// <summary> /// Create model from settings /// </summary> /// <param name="json">JSON Text</param> /// <returns></returns> public static SettingsModel FromJson(string json) => JsonConvert.DeserializeObject<SettingsModel>(json); /// <summary> /// Create JSON Object /// </summary> /// <param name="model">Settings Model</param> /// <returns></returns> public static string ToJson(SettingsModel model) => JsonConvert.SerializeObject(model, Formatting.Indented); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Sandbox; namespace kake { [Library( "trigger_red" )] public partial class TriggerRed : TriggerMultiple { public override void OnTriggered( Entity other ) { if ( other is KakePlayer client ) { client.ToTeamRed(); } base.StartTouch( other ); } } }
using System; using System.IO; using System.Net.Mail; using System.Net.Mime; using System.Web; using CAPPamari.Web.Models; namespace CAPPamari.Web.Helpers { public static class EmailHelper { public static bool EmailToAdvisor(string username, AdvisorModel advisor) { var document = PrintingHelper.PrintCappReport(username); if (document == null) return false; var email = new MailMessage("do-not-reply@iecfusor.com", advisor.Email) { Subject = "CAPPamari - Please review " + username + "'s CAPP report", Body = "Dear " + advisor.Name + ",\n" + "\n" + "Please review my latest plan for fulfulling my graduation requirements.\n" + "\n" + "Sincerely,\n" + username + "\n" + "--\n" + HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) }; using (var pdfStream = new MemoryStream()) { document.SaveToStream(pdfStream); pdfStream.Position = 0; var attachment = new Attachment(pdfStream, new ContentType(MediaTypeNames.Application.Pdf)); attachment.ContentDisposition.FileName = "CAPP Report.pdf"; email.Attachments.Add(attachment); try { var smtpServer = new SmtpClient("localhost"); smtpServer.Send(email); } catch { return false; } return true; } } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using System.Diagnostics; using Devsense.PHP.Syntax; using Peachpie.CodeAnalysis.Symbols; namespace Pchp.CodeAnalysis.Symbols { /// <summary> /// Synthetized routine parameter. /// </summary> class SpecialParameterSymbol : ParameterSymbol { /// <summary> /// Name of special context parameter. /// Is of type <c>Context</c>. /// </summary> public const string ContextName = "<ctx>"; /// <summary> /// Name of special locals parameter. /// Is of type <c>PhpArray</c>. /// </summary> public const string LocalsName = "<locals>"; /// <summary> /// Name of special locals parameter used for temporary variables used by compiler. /// Is of type <c>PhpArray</c>. /// </summary> public const string TemporaryLocalsName = "<tmpLocals>"; /// <summary> /// Synthesized params parameter. /// </summary> public const string ParamsName = "<arguments>"; /// <summary> /// Name of special late-static-bound parameter. /// Is of type <c>PhpTypeInfo</c> /// </summary> public const string StaticTypeName = "<static>"; /// <summary> /// Name of special <c>this</c> parameter. /// </summary> public const string ThisName = "this"; /// <summary> /// Name of special <c>self</c> parameter. /// </summary> public const string SelfName = "<self>"; readonly MethodSymbol _symbol; readonly int _index; readonly string _name; object _type; public SpecialParameterSymbol(MethodSymbol symbol, object type, string name, int index) { Debug.Assert(type is TypeSymbol || type is CoreType); Contract.ThrowIfNull(symbol); Contract.ThrowIfNull(type); _symbol = symbol; _type = type; _name = name; _index = index; } /// <summary> /// Determines whether given parameter is treated as a special Context parameter /// which is always first and of type <c>Pchp.Core.Context</c>. /// </summary> public static bool IsContextParameter(ParameterSymbol p) => p != null && p.DeclaringCompilation != null ? p.Type == p.DeclaringCompilation.CoreTypes.Context.Symbol : p.Type != null ? (p.Type.Name == "Context" && p.Type.ContainingAssembly.IsPeachpieCorLibrary) : false; /// <summary> /// Determines whether given parameter is treated as a special implicitly provided, by the compiler or the runtime. /// </summary> public static bool IsImportValueParameter(ParameterSymbol p) => p.ImportValueAttributeData.IsValid; /// <summary> /// Determines whether given parameter is treated as a special implicitly provided, by the compiler or the runtime. /// </summary> public static bool IsImportValueParameter(ParameterSymbol p, out ImportValueAttributeData.ValueSpec valueEnum) { var data = p.ImportValueAttributeData; valueEnum = data.Value; return data.IsValid; } public static bool IsDummyFieldsOnlyCtorParameter(IParameterSymbol p) => p.Type.Name == "DummyFieldsOnlyCtor"; public static bool IsCallerClassParameter(ParameterSymbol p) => p.ImportValueAttributeData.Value == ImportValueAttributeData.ValueSpec.CallerClass; /// <summary> /// Determines whether given parameter is a special lately static bound parameter. /// This parameter provides late static bound type, of type <c>PhpTypeInfo</c>. /// </summary> public static bool IsLateStaticParameter(ParameterSymbol p) => p != null && p.Type != null && p.Type.MetadataName == "PhpTypeInfo" && !(p is SourceParameterSymbol) && p.Name == StaticTypeName; // TODO: && namespace == Pchp.Core. /// <summary> /// Determines whether given parameter is a special self parameter. /// This parameter provides self type, of type <c>RuntimeTypeHandle</c>. /// </summary> public static bool IsSelfParameter(ParameterSymbol p) => p != null && p.Type != null && p.Type.MetadataName == "RuntimeTypeHandle" && !(p is SourceParameterSymbol) && p.Name == SelfName; public override bool IsImplicitlyDeclared => true; public override Symbol ContainingSymbol => _symbol; internal override ModuleSymbol ContainingModule => _symbol.ContainingModule; public override NamedTypeSymbol ContainingType => _symbol.ContainingType; public override string Name => _name; public override bool IsThis => _index == -1; internal override TypeSymbol Type { get { if (_type is CoreType ctype) { _type = ctype.Symbol; Debug.Assert(_type != null, "ReferenceManager was not bound (probably)"); } if (_type is TypeSymbol t) { return t; } throw new ArgumentException(); } } public override RefKind RefKind => RefKind.None; public override int Ordinal => _index; public override ImmutableArray<Location> Locations { get { throw new NotImplementedException(); } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { throw new NotImplementedException(); } } internal override ConstantValue ExplicitDefaultConstantValue => null; // TODO } }
using Agoda.RateLimiter.Models; using System; using System.Collections.Generic; using System.Text; namespace Agoda.RateLimiter.Extensions { public static class DateTimeExtensions { private const long SecondsPerMinute = 60; private const long SecondsPerHour = 3600; public static long GetEpochTime(this DateTime time) { TimeSpan timespan = time - new DateTime(1970, 1, 1); return (long)timespan.TotalSeconds; } public static long GetTotalSeconds(this TimeInterval interval) { return interval.Unit switch { TimeUnit.Hour => interval.Value * SecondsPerHour, TimeUnit.Minute => interval.Value * SecondsPerMinute, _ => interval.Value, }; } public static TimeSpan ToTimespan(this TimeInterval interval) { return TimeSpan.FromSeconds(interval.GetTotalSeconds()); } } }
#region License /* * Copyright 2002-2012 the original author or authors. * * 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 NUnit.Framework; namespace Spring.Util { /// <summary> /// Unit tests for the UriTemplate class. /// </summary> /// <author>Arjen Poutsma</author> /// <author>Juergen Hoeller</author> /// <author>Bruno Baia (.NET)</author> [TestFixture] public class UriTemplateTests { [Test] public void GetVariableNames() { UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}"); string[] variableNames = template.VariableNames; Assert.AreEqual(new string[] { "hotel", "booking" }, variableNames, "Invalid variable names"); } [Test] public void ExpandVarArgs() { // absolute UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}"); Uri result = template.Expand("1", "42"); Assert.AreEqual(new Uri("http://example.com/hotels/1/bookings/42"), result, "Invalid expanded template"); // relative template = new UriTemplate("/hotels/{hotel}/bookings/{booking}"); result = template.Expand("1", "42"); Assert.AreEqual(new Uri("/hotels/1/bookings/42", UriKind.Relative), result, "Invalid expanded template"); } [Test] public void MultipleExpandVarArgs() { UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}"); Uri result = template.Expand("2", 21); result = template.Expand(1, "42"); Assert.AreEqual(new Uri("http://example.com/hotels/1/bookings/42"), result, "Invalid expanded template"); } [Test] [ExpectedException( typeof(ArgumentException), ExpectedMessage = "Invalid amount of variables values in 'http://example.com/hotels/{hotel}/bookings/{booking}': expected 2; got 3")] public void ExpandVarArgsInvalidAmountVariables() { UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}"); template.Expand("1", "42", 100); } [Test] public void ExpandVarArgsDuplicateVariables() { UriTemplate template = new UriTemplate("http://example.com/order/{c}/{c}/{c}"); Assert.AreEqual(new string[] { "c" }, template.VariableNames, "Invalid variable names"); Uri result = template.Expand("cheeseburger"); Assert.AreEqual(new Uri("http://example.com/order/cheeseburger/cheeseburger/cheeseburger"), result, "Invalid expanded template"); } [Test] public void ExpandDictionary() { IDictionary<string, object> uriVariables = new Dictionary<string, object>(2); uriVariables.Add("booking", "42"); uriVariables.Add("hotel", 1); // absolute UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}"); Uri result = template.Expand(uriVariables); Assert.AreEqual(new Uri("http://example.com/hotels/1/bookings/42"), result, "Invalid expanded template"); // relative template = new UriTemplate("hotels/{hotel}/bookings/{booking}"); result = template.Expand(uriVariables); Assert.AreEqual(new Uri("hotels/1/bookings/42", UriKind.Relative), result, "Invalid expanded template"); } [Test] public void MultipleExpandDictionary() { UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}"); IDictionary<string, object> uriVariables = new Dictionary<string, object>(2); uriVariables.Add("booking", 21); uriVariables.Add("hotel", "2"); Uri result = template.Expand(uriVariables); uriVariables = new Dictionary<string, object>(2); uriVariables.Add("booking", "42"); uriVariables.Add("hotel", "1"); result = template.Expand(uriVariables); Assert.AreEqual(new Uri("http://example.com/hotels/1/bookings/42"), result, "Invalid expanded template"); } [Test] [ExpectedException( typeof(ArgumentException), ExpectedMessage = "Invalid amount of variables values in 'http://example.com/hotels/{hotel}/bookings/{booking}': expected 2; got 1")] public void ExpandDictionaryInvalidAmountVariables() { IDictionary<string, object> uriVariables = new Dictionary<string, object>(2); uriVariables.Add("hotel", 1); UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}"); template.Expand(uriVariables); } [Test] [ExpectedException( typeof(ArgumentException), ExpectedMessage = "'uriVariables' dictionary has no value for 'hotel'")] public void ExpandDictionaryUnboundVariables() { IDictionary<string, object> uriVariables = new Dictionary<string, object>(2); uriVariables.Add("booking", "42"); uriVariables.Add("bar", 1); UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}"); template.Expand(uriVariables); } [Test] public void ExpandEncoded() { UriTemplate template = new UriTemplate("http://example.com/hotel list/{hotel}"); Uri result = template.Expand("Z\u00fcrich"); Assert.AreEqual(new Uri("http://example.com/hotel%20list/Z%C3%BCrich"), result, "Invalid expanded template"); } [Test] public void Matches() { UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}/"); Assert.IsTrue(template.Matches("http://example.com/hotels/1/bookings/42/"), "UriTemplate does not match"); Assert.IsFalse(template.Matches("hhhhttp://example.com/hotels/1/bookings/42/"), "UriTemplate matches"); Assert.IsFalse(template.Matches("http://example.com/hotels/1/bookings/42/blabla"), "UriTemplate matches"); Assert.IsFalse(template.Matches("http://example.com/hotels/bookings/"), "UriTemplate matches"); Assert.IsFalse(template.Matches(""), "UriTemplate matches"); Assert.IsFalse(template.Matches(null), "UriTemplate matches"); } [Test] public void Match() { UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}"); IDictionary<string, string> result = template.Match("http://example.com/hotels/1/bookings/42"); Assert.AreEqual(2, result.Count); Assert.AreEqual("1", result["hotel"]); Assert.AreEqual("42", result["booking"]); result = template.Match("http://example.com/hotels/1/bookings"); Assert.AreEqual(0, result.Count); } [Test] public void matchDuplicate() { UriTemplate template = new UriTemplate("/order/{c}/{c}/{c}"); IDictionary<string, string> result = template.Match("/order/cheeseburger/cheeseburger/cheeseburger"); Assert.AreEqual(1, result.Count); Assert.AreEqual("cheeseburger", result["c"]); } [Test] public void MatchMultipleInOneSegment() { UriTemplate template = new UriTemplate("/{foo}-{bar}"); IDictionary<string, string> result = template.Match("/12-34"); Assert.AreEqual(2, result.Count); Assert.AreEqual("12", result["foo"]); Assert.AreEqual("34", result["bar"]); } [Test] public void MatchesQueryVariables() { UriTemplate template = new UriTemplate("/search?q={query}"); Assert.IsTrue(template.Matches("/search?q=foo")); } [Test] public void MatchesFragments() { UriTemplate template = new UriTemplate("/search#{fragment}"); Assert.IsTrue(template.Matches("/search#foo")); template = new UriTemplate("/search?query={query}#{fragment}"); Assert.IsTrue(template.Matches("/search?query=foo#bar")); } [Test] public void ExpandWithAtSign() { UriTemplate template = new UriTemplate("http://localhost/query={query}"); Uri uri = template.Expand("foo@bar"); Assert.AreEqual("http://localhost/query=foo@bar", uri.ToString()); } } }
using System; using System.Linq; using CommandLine; using CommandLine.Text; using log4net; using CKAN.Versioning; namespace CKAN.CmdLine { public class Cache : ISubCommand { public Cache() { } private class CacheSubOptions : VerbCommandOptions { [VerbOption("list", HelpText = "List the download cache path")] public CommonOptions ListOptions { get; set; } [VerbOption("set", HelpText = "Set the download cache path")] public SetOptions SetOptions { get; set; } [VerbOption("clear", HelpText = "Clear the download cache directory")] public CommonOptions ClearOptions { get; set; } [VerbOption("reset", HelpText = "Set the download cache path to the default")] public CommonOptions ResetOptions { get; set; } [VerbOption("showlimit", HelpText = "Show the cache size limit")] public CommonOptions ShowLimitOptions { get; set; } [VerbOption("setlimit", HelpText = "Set the cache size limit")] public SetLimitOptions SetLimitOptions { get; set; } [HelpVerbOption] public string GetUsage(string verb) { HelpText ht = HelpText.AutoBuild(this, verb); // Add a usage prefix line ht.AddPreOptionsLine(" "); if (string.IsNullOrEmpty(verb)) { ht.AddPreOptionsLine("ckan cache - Manage the download cache path of CKAN"); ht.AddPreOptionsLine($"Usage: ckan cache <command> [options]"); } else { ht.AddPreOptionsLine("cache " + verb + " - " + GetDescription(verb)); switch (verb) { // First the commands with one string argument case "set": ht.AddPreOptionsLine($"Usage: ckan cache {verb} [options] path"); break; case "setlimit": ht.AddPreOptionsLine($"Usage: ckan cache {verb} [options] megabytes"); break; // Now the commands with only --flag type options case "list": case "clear": case "reset": case "showlimit": default: ht.AddPreOptionsLine($"Usage: ckan cache {verb} [options]"); break; } } return ht; } } private class SetOptions : CommonOptions { [ValueOption(0)] public string Path { get; set; } } private class SetLimitOptions : CommonOptions { [ValueOption(0)] public long Megabytes { get; set; } = -1; } /// <summary> /// Execute a cache subcommand /// </summary> /// <param name="mgr">KSPManager object containing our instances and cache</param> /// <param name="opts">Command line options object</param> /// <param name="unparsed">Raw command line options</param> /// <returns> /// Exit code for shell environment /// </returns> public int RunSubCommand(KSPManager mgr, CommonOptions opts, SubCommandOptions unparsed) { string[] args = unparsed.options.ToArray(); int exitCode = Exit.OK; // Parse and process our sub-verbs Parser.Default.ParseArgumentsStrict(args, new CacheSubOptions(), (string option, object suboptions) => { // ParseArgumentsStrict calls us unconditionally, even with bad arguments if (!string.IsNullOrEmpty(option) && suboptions != null) { CommonOptions options = (CommonOptions)suboptions; options.Merge(opts); user = new ConsoleUser(options.Headless); manager = mgr ?? new KSPManager(user); exitCode = options.Handle(manager, user); if (exitCode != Exit.OK) return; switch (option) { case "list": exitCode = ListCacheDirectory((CommonOptions)suboptions); break; case "set": exitCode = SetCacheDirectory((SetOptions)suboptions); break; case "clear": exitCode = ClearCacheDirectory((CommonOptions)suboptions); break; case "reset": exitCode = ResetCacheDirectory((CommonOptions)suboptions); break; case "showlimit": exitCode = ShowCacheSizeLimit((CommonOptions)suboptions); break; case "setlimit": exitCode = SetCacheSizeLimit((SetLimitOptions)suboptions); break; default: user.RaiseMessage("Unknown command: cache {0}", option); exitCode = Exit.BADOPT; break; } } }, () => { exitCode = MainClass.AfterHelp(); }); return exitCode; } private int ListCacheDirectory(CommonOptions options) { IWin32Registry winReg = new Win32Registry(); user.RaiseMessage(winReg.DownloadCacheDir); printCacheInfo(); return Exit.OK; } private int SetCacheDirectory(SetOptions options) { if (string.IsNullOrEmpty(options.Path)) { user.RaiseError("set <path> - argument missing, perhaps you forgot it?"); return Exit.BADOPT; } string failReason; if (manager.TrySetupCache(options.Path, out failReason)) { IWin32Registry winReg = new Win32Registry(); user.RaiseMessage($"Download cache set to {winReg.DownloadCacheDir}"); printCacheInfo(); return Exit.OK; } else { user.RaiseError($"Invalid path: {failReason}"); return Exit.BADOPT; } } private int ClearCacheDirectory(CommonOptions options) { manager.Cache.RemoveAll(); user.RaiseMessage("Download cache cleared."); printCacheInfo(); return Exit.OK; } private int ResetCacheDirectory(CommonOptions options) { string failReason; if (manager.TrySetupCache("", out failReason)) { IWin32Registry winReg = new Win32Registry(); user.RaiseMessage($"Download cache reset to {winReg.DownloadCacheDir}"); printCacheInfo(); } else { user.RaiseError($"Can't reset cache path: {failReason}"); } return Exit.OK; } private int ShowCacheSizeLimit(CommonOptions options) { IWin32Registry winReg = new Win32Registry(); if (winReg.CacheSizeLimit.HasValue) { user.RaiseMessage(CkanModule.FmtSize(winReg.CacheSizeLimit.Value)); } else { user.RaiseMessage("Unlimited"); } return Exit.OK; } private int SetCacheSizeLimit(SetLimitOptions options) { IWin32Registry winReg = new Win32Registry(); if (options.Megabytes < 0) { winReg.CacheSizeLimit = null; } else { winReg.CacheSizeLimit = options.Megabytes * (long)1024 * (long)1024; } return ShowCacheSizeLimit(null); } private void printCacheInfo() { int fileCount; long bytes; manager.Cache.GetSizeInfo(out fileCount, out bytes); user.RaiseMessage($"{fileCount} files, {CkanModule.FmtSize(bytes)}"); } private KSPManager manager; private IUser user; private static readonly ILog log = LogManager.GetLogger(typeof(Cache)); } }
using BL.Ventas; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BL.Ventas { public class DatosdeInicio : CreateDatabaseIfNotExists<Contexto> { protected override void Seed(Contexto contexto) { var usuarioAdmin1 = new Usuario(); usuarioAdmin1.Nombre = "admin"; usuarioAdmin1.Contrasena = "1234"; contexto.Usuarios.Add(usuarioAdmin1); var usuarioAdmin2 = new Usuario(); usuarioAdmin2.Nombre = "admin2"; usuarioAdmin2.Contrasena = "0000"; contexto.Usuarios.Add(usuarioAdmin2); var categoria1 = new Categoria(); categoria1.Descripcion = "Mecanico"; contexto.Categorias.Add(categoria1); var categoria2 = new Categoria(); categoria2.Descripcion = "Automático"; contexto.Categorias.Add(categoria2); var categoria3 = new Categoria(); categoria3.Descripcion = "Tritonico"; contexto.Categorias.Add(categoria3); var categoria4 = new Categoria(); categoria4.Descripcion = "Automatico palanca timon"; contexto.Categorias.Add(categoria4); base.Seed(contexto); } } }
using Newtonsoft.Json; namespace SDroid.SteamTrade.InternalModels.EconomyItemsAPI { internal class SchemaOverviewString { [JsonProperty("index")] public int Index { get; set; } [JsonProperty("string")] public string Value { get; set; } } }
using System; using Xunit; using Microsoft.EntityFrameworkCore; using DL; namespace Test { public class UnitTest1 { private readonly DbContextOptions<Entity.reviewdbContext> options; public TestRepo() { options = new DbContextOptionsBuilder<Entity.reviewdbContext>().UseSqlite("Filename=test.db").Options; Seed(); } [Fact] public void AddAUserShouldAddAUser() { //Arrange using(var testcontext = new Entity.reviewdbContext(options)) { IReviewRepo _repo = new ReviewRepo(testcontext); //Act _repo.AddUser( new Models.User{ Id = 5, Name = "Bob Smith", AcessLvl = 1 } ); } //Assert using(var assertContext = new Entity.reviewdbContext(options)) { Entity.User user = assertContext.users.FirstOrDefault(); } } private void Seed() { using(var context = new Entity.reviewdbContext(options)) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); // wipe the tables context.Users.AddRange( new Models.User{ Id = 1, Name = "Frank Stevens", AcessLvl = 1 } ); } context.SaveChanges; //Does the actual commit } //Given //When //Then } }
 using Newtonsoft.Json; namespace LoESoft.Server.Core.Networking.Data { public struct Stat { public int StatType { get; set; } public object Data { get; set; } public void Write(NetworkWriter writer) { writer.Write(StatType); writer.WriteUTF(JsonConvert.SerializeObject(Data)); } } }
using Microsoft.AspNetCore.Components; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TagEChartsBlazor.Components { public abstract class BaseRichComponent : ComponentBase, IDisposable { [CascadingParameter] protected ComponentBase? Base { get; set; } [Parameter] public RenderFragment? ChildContent { get; set; } [Parameter] public bool? DisableRender { get; set; } protected abstract void LoadSetting(); protected async override Task OnParametersSetAsync() { await base.OnParametersSetAsync(); LoadSetting(); } public void AppendChild(RenderFragment childContent) { ChildContent = childContent; StateHasChanged(); } protected virtual void Dispose(bool disposing) { } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } }
using System; using PlanesRabbitMQ.BL.Models; namespace PlanesRabbitMQ.Contracts.Planes { public interface PlaneBatchAddRequested { public Guid BatchId { get; set; } public Plane Plane { get; set; } } }
using System.Linq; using Elektronik.Containers; using Elektronik.RosPlugin.Ros2.Bag; using Elektronik.RosPlugin.Ros2.Bag.Containers; using NUnit.Framework; namespace Elektronik.Ros.Tests.Rosbag2 { public class ReadingTestsYaml { private readonly Rosbag2ContainerTree _tree = new(""); [SetUp, Platform("Win")] public void Setup() { _tree.Init(new Rosbag2Settings() {FilePath = @"metadata.yaml"}); } [Test, Platform("Win")] public void ActualTimestamps() { var sum = 0; foreach (var timestamps in _tree.Timestamps.Values) { sum += timestamps.Count; } Assert.AreEqual(282, sum); } [Test, Platform("Win")] public void ContainersTree() { Assert.AreEqual(20, _tree.ActualTopics.Count); Assert.AreEqual(16, _tree.Children.Count()); var children = _tree.Children.ToList(); Assert.IsInstanceOf<VirtualContainer>(children[1]); Assert.AreEqual("control", children[1].DisplayName); Assert.AreEqual(2, children[1].Children.Count()); Assert.IsInstanceOf<VisualisationMarkersDBContainer>(children[2]); Assert.AreEqual("visualization_planning", children[2].DisplayName); } } }
using MagicalLifeAPI.Asset; using MagicalLifeAPI.World.Data.Disk; using MagicalLifeAPI.World.Data.Disk.DataStorage; using MagicalLifeGUIWindows.GUI.Reusable; using Microsoft.Xna.Framework; using MonoGame.Extended.Input.InputListeners; namespace MagicalLifeGUIWindows.GUI.Save { public class OverwriteButton : MonoButton { public OverwriteButton() : base(TextureLoader.GUIMenuButton, GetDrawingBounds(), true, "Overwrite Save") { this.ClickEvent += this.OverwriteButton_ClickEvent; } private void OverwriteButton_ClickEvent(object sender, Reusable.Event.ClickEventArgs e) { this.Overwrite(); } private static Rectangle GetDrawingBounds() { int x = SaveGameMenuLayout.OverwriteButtonX; int y = SaveGameMenuLayout.OverwriteButtonY; int width = SaveGameMenuLayout.OverwriteButtonWidth; int height = SaveGameMenuLayout.OverwriteButtonHeight; return new Rectangle(x, y, width, height); } private void Overwrite() { int selected = SaveGameMenu.menu.SavesList.SelectedIndex; if (selected != -1) { RenderableString selectedItem = (RenderableString)SaveGameMenu.menu.SavesList.Items[selected]; WorldStorage.SerializeWorld(selectedItem.Text, new WorldDiskSink()); } MenuHandler.Back(); } } }
using Streamliner.Blocks.Base; using Streamliner.Definitions; namespace Streamliner.Core.Links { public interface IBlockLinkFactory { IBlockLink<T> CreateLink<T>(ISourceBlock<T> from, ITargetBlock<T> to, FlowLinkDefinition<T> link); IBlockLinkReceiver<T> CreateReceiver<T>(FlowLinkDefinition<T> linkDefinition); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class Gpu : Product { public Gpu(double price) : base(price, 0.7) { } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.EntityFrameworkCore.TestUtilities.FakeProvider; using Xunit; #pragma warning disable RCS1102 // Make class static. namespace Microsoft.EntityFrameworkCore { public class CommandConfigurationTests { public class CommandTimeout { [ConditionalFact] public void Default_value_for_CommandTimeout_is_null_and_can_be_changed_including_setting_to_null() { using (var context = new TimeoutContext()) { Assert.Null(context.Database.GetCommandTimeout()); context.Database.SetCommandTimeout(77); Assert.Equal(77, context.Database.GetCommandTimeout()); context.Database.SetCommandTimeout(null); Assert.Null(context.Database.GetCommandTimeout()); context.Database.SetCommandTimeout(TimeSpan.FromSeconds(66)); Assert.Equal(66, context.Database.GetCommandTimeout()); } } [ConditionalFact] public void Setting_CommandTimeout_to_negative_value_throws() { Assert.Throws<InvalidOperationException>( () => new DbContextOptionsBuilder().UseSqlServer( "No=LoveyDovey", b => b.CommandTimeout(-55))); using (var context = new TimeoutContext()) { Assert.Null(context.Database.GetCommandTimeout()); Assert.Throws<ArgumentException>( () => context.Database.SetCommandTimeout(-3)); Assert.Throws<ArgumentException>( () => context.Database.SetCommandTimeout(TimeSpan.FromSeconds(-3))); Assert.Throws<ArgumentException>( () => context.Database.SetCommandTimeout(-99)); Assert.Throws<ArgumentException>( () => context.Database.SetCommandTimeout(TimeSpan.FromSeconds(-99))); Assert.Throws<ArgumentException>( () => context.Database.SetCommandTimeout(TimeSpan.FromSeconds(uint.MaxValue))); } } public class TimeoutContext : DbContext { public TimeoutContext() { } public TimeoutContext(int? commandTimeout) => Database.SetCommandTimeout(commandTimeout); protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder .UseInternalServiceProvider(SqlServerFixture.DefaultServiceProvider) .UseSqlServer(new FakeDbConnection("A=B")); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace AsepriteAnimator { public enum AsepriteAlignment { Center = 0, TopLeft = 1, TopCenter = 2, TopRight = 3, LeftCenter = 4, RightCenter = 5, BottomLeft = 6, BottomCenter = 7, BottomRight = 8 } }
using System; using System.Linq; using Telerik.Sitefinity.Web.UI.Fields.Contracts; namespace Sitefinity.Samples.UserGeneratedContent.Fields.ImageUrlField { public interface IImageUrlFieldControlDefinition : IFieldControlDefinition { /// <summary> /// Gets or sets the sample text. /// </summary> /// <value>The sample text.</value> string SampleText { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Hoops.Core.Models { public partial class Director { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] [Column("ID")] public int DirectorId { get; set; } [Column("CompanyID")] public Nullable<int> CompanyId { get; set; } [Column("PeopleID")] public int PersonId { get; set; } public Nullable<int> Seq { get; set; } public string Title { get; set; } public byte[] Photo { get; set; } public string PhonePref { get; set; } public Nullable<int> EmailPref { get; set; } public Nullable<System.DateTime> CreatedDate { get; set; } public string CreatedUser { get; set; } // [ForeignKey("PeopleID")] // public virtual Person People {get; set;} } }
using Sakuno.KanColle.Amatsukaze.Services; using System.ComponentModel; using System.Windows; namespace Sakuno.KanColle.Amatsukaze.Views { /// <summary> /// Browser.xaml の相互作用ロジック /// </summary> partial class Browser { public static Browser Instance { get; private set; } UIElement r_Bar; public Browser() { Instance = this; if (!DesignerProperties.GetIsInDesignMode(this)) { BrowserService.Instance.Initialize(); ((MainWindow)App.Current.MainWindow).SubscribeBrowserPreferenceChanged(); } InitializeComponent(); } public override void OnApplyTemplate() { base.OnApplyTemplate(); r_Bar = Template.FindName("Bar", this) as UIElement; } public Size GetBarSize() => r_Bar.DesiredSize; } }
namespace AKSaigyouji.HeightMaps { /// <summary> /// Height maps provide a float y for each coordinate pair x,z of floats. MinHeight and MaxHeight /// indicate the lower and upper bounds for the height values. /// </summary> public interface IHeightMap { /// <summary> /// Minimum possible value returned by get height. /// </summary> float MinHeight { get; } /// <summary> /// Highest possible value returned by get height. /// </summary> float MaxHeight { get; } /// <summary> /// Return a height value parametrized by a pair of floats. Identical input will produce identical output. /// </summary> /// <returns>Float between MinHeight and MaxHeight.</returns> float GetHeight(float x, float y); } }
using System; using System.Collections.Generic; using System.Text; namespace Abmes.DataCollector.Vault.Configuration { public class User { public string IdentityUserId { get; set; } public IEnumerable<string> DataCollectionNames { get; set; } public User() { // needed for deserialization } public User(string identityUserId, IEnumerable<string> dataCollectionNames) { IdentityUserId = identityUserId; DataCollectionNames = dataCollectionNames; } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Windows; using Cryptons.Views.Dialogs; namespace Cryptons { class Functionals { private Functionals() { } private static Functionals _Functionals; public static Functionals DB() { if (_Functionals == null) { _Functionals = new Functionals(); } return _Functionals; } public string nameDB = Properties.Settings.Default.MyDatabaseConnectionString; public SqlConnection getConn() { try { SqlConnection conn = new SqlConnection(nameDB); return conn; } catch { new ErrorFrame("Не удалось подключится к файлу Базы Данных. Возможно отстутствует подключение!"); return null; } } public int GetCount(string sqlQuery) { SqlConnection conn = getConn(); conn.Open(); int x = 0; using (SqlCommand myCommand = new SqlCommand(sqlQuery, conn)) { SqlDataReader reader = myCommand.ExecuteReader(); while (reader.Read()) x++; reader.Close(); } conn.Close(); return x; } public int GetMax(string sql, string selectCol) { SqlConnection conn = getConn(); conn.Open(); int max = 0, x; using (SqlCommand myCommand = new SqlCommand(sql, conn)) { SqlDataReader reader = myCommand.ExecuteReader(); while (reader.Read()) { x = reader.GetInt32(reader.GetOrdinal(selectCol)); if (x > max) max = x; }; reader.Close(); } conn.Close(); return max; } public int GetMin(string sql, string selectCol) { SqlConnection conn = getConn(); conn.Open(); int min = int.MaxValue, x; using (SqlCommand myCommand = new SqlCommand(sql, conn)) { SqlDataReader reader = myCommand.ExecuteReader(); while (reader.Read()) { x = reader.GetInt32(reader.GetOrdinal(selectCol)); if (x < min) min = x; }; reader.Close(); } conn.Close(); return min; } public int GetId(string Table = "[User]", string selectCols = "id_user") { SqlConnection conn = getConn(); conn.Open(); int max = 0, x; using (SqlCommand myCommand = new SqlCommand($"select {selectCols} from {Table}", conn)) { SqlDataReader reader = myCommand.ExecuteReader(); while (reader.Read()) { x = reader.GetInt32(reader.GetOrdinal(selectCols)); if (x > max) max = x; }; reader.Close(); } conn.Close(); return max; } public int GetId(string login) { SqlConnection conn = getConn(); conn.Open(); int x = -1; using (SqlCommand myCommand = new SqlCommand($"select id_user from [User] where login = '{login}'", conn)) { SqlDataReader reader = myCommand.ExecuteReader(); while (reader.Read()) { x = reader.GetInt32(0); }; reader.Close(); } conn.Close(); return x; } public string GetString<T>(string Table, string colName, string idCol, T id) { SqlConnection conn = getConn(); conn.Open(); string myValue = ""; string sql = string.Format($"select {colName} from {Table} where {idCol} = '{id}'"); using (SqlCommand cmd = new SqlCommand(sql, conn)) { SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) myValue = reader.GetString(reader.GetOrdinal(colName)); reader.Close(); } conn.Close(); return myValue; } public int GetInt<T>(string Table, string colName, string idCol, T id) { SqlConnection conn = getConn(); conn.Open(); int myValue = 0; string sql = string.Format($"select {colName} from {Table} where {idCol} = '{id}'"); using (SqlCommand cmd = new SqlCommand(sql, conn)) { SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) myValue = reader.GetInt32(reader.GetOrdinal(colName)); reader.Close(); } conn.Close(); return myValue; } public int GetInt(string sql, string colName) { SqlConnection conn = getConn(); conn.Open(); int myValue = 0; using (SqlCommand cmd = new SqlCommand(sql, conn)) { SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) myValue = reader.GetInt32(reader.GetOrdinal(colName)); reader.Close(); } conn.Close(); return myValue; } public DataTable GetQuery(string myQuery) { SqlConnection conDB = new SqlConnection(nameDB);//all conDB.Open(); DataTable tabord = new DataTable(); SqlDataAdapter dazak = new SqlDataAdapter(myQuery, conDB); dazak.Fill(tabord); return tabord; } public DataTable GetTable(string tableName) { SqlConnection conDB = new SqlConnection(nameDB); conDB.Open(); DataTable tabord = new DataTable(); SqlDataAdapter dazak = new SqlDataAdapter("SELECT * FROM " + tableName, conDB); dazak.Fill(tabord); return tabord; } public bool DeleteFrom(int delID, string Table, string colName) { SqlConnection conn = getConn(); conn.Open(); string sql = string.Format($"Delete from {Table} where {colName} = '{delID}'"); using (SqlCommand cmd = new SqlCommand(sql, conn)) { try { cmd.ExecuteNonQuery(); } catch (SqlException ex) { Exception error = new Exception("К сожалению!", ex); throw error; } } conn.Close(); return true; } public bool DeleteFrom<T>(T delID, string Table, string colName) { SqlConnection conn = getConn(); conn.Open(); string sql = string.Format($"Delete from {Table} where {colName} = '{delID}'"); using (SqlCommand cmd = new SqlCommand(sql, conn)) { try { cmd.ExecuteNonQuery(); } catch (SqlException ex) { Exception error = new Exception("К сожалению!", ex); throw error; } } conn.Close(); return true; } public bool Delete(string sql) { SqlConnection conn = getConn(); conn.Open(); using (SqlCommand cmd = new SqlCommand(sql, conn)) { try { cmd.ExecuteNonQuery(); } catch (SqlException ex) { MessageBox.Show("Delete"); } } conn.Close(); return true; } public bool Add(string login, string password, string username, string firstname, string groupes) { SqlConnection conn = getConn(); conn.Open(); string sql = "INSERT INTO [User] (login,password,usertype,username,firstname,groupes) " + "values (@login,@password,@usertype,@username,@firstname,@groupes)"; using (SqlCommand myCommand = new SqlCommand(sql, conn)) { myCommand.Parameters.AddWithValue("@login", login); myCommand.Parameters.AddWithValue("@password", password); myCommand.Parameters.AddWithValue("@usertype", "Student"); myCommand.Parameters.AddWithValue("@username", username); myCommand.Parameters.AddWithValue("@firstname", firstname); myCommand.Parameters.AddWithValue("@groupes", groupes); myCommand.ExecuteNonQuery(); } conn.Close(); return true; } public bool AddAdmin(string login, string password, string username, string firstname) { SqlConnection conn = getConn(); conn.Open(); string sql = "INSERT INTO [User] (login,password,usertype,username,firstname,groupes) " + "values (@login,@password,@usertype,@username,@firstname,@groupes)"; try { using (SqlCommand myCommand = new SqlCommand(sql, conn)) { myCommand.Parameters.AddWithValue("@login", login); myCommand.Parameters.AddWithValue("@password", password); myCommand.Parameters.AddWithValue("@usertype", "Admin"); myCommand.Parameters.AddWithValue("@username", username); myCommand.Parameters.AddWithValue("@firstname", firstname); myCommand.Parameters.AddWithValue("@groupes", "Admin"); myCommand.ExecuteNonQuery(); } } catch { conn.Close(); return false; } conn.Close(); return true; } public bool AddQuestion(List<string> data) { SqlConnection conn = getConn(); conn.Open(); string sql = "INSERT INTO [Question] (quest,answer1,answer2,answer3,answer4,trueAnswer) " + "values (@quest,@answer1,@answer2,@answer3,@answer4,@trueAnswer)"; try { using (SqlCommand myCommand = new SqlCommand(sql, conn)) { myCommand.Parameters.AddWithValue("@quest", data[0]); myCommand.Parameters.AddWithValue("@answer1", data[1]); myCommand.Parameters.AddWithValue("@answer2", data[2]); myCommand.Parameters.AddWithValue("@answer3", (data.Count > 4) ? data[3] : "NULL"); myCommand.Parameters.AddWithValue("@answer4", (data.Count > 5) ? data[4] : "NULL"); myCommand.Parameters.AddWithValue("@trueAnswer", Convert.ToInt32(data[data.Count - 1])); myCommand.ExecuteNonQuery(); } MessageBox.Show("Вопрос успешно добавлен!"); } catch { conn.Close(); return false; } conn.Close(); return true; } public bool UpdateUser(string Col, string value, int id) { SqlConnection conn = getConn(); conn.Open(); string sql = $"UPDATE [User] SET {Col}=@x1 Where id_user=@id_user"; using (SqlCommand myCommand = new SqlCommand(sql, conn)) { myCommand.Parameters.AddWithValue("@id_user", id); myCommand.Parameters.AddWithValue("@x1", value); myCommand.ExecuteNonQuery(); } conn.Close(); return true; } public bool SaveTest(int rating) { SqlConnection conn = getConn(); conn.Open(); string sql = "INSERT INTO [Rating] (id_user,rating) " + "values (@id_user,@rating)"; try { using (SqlCommand myCommand = new SqlCommand(sql, conn)) { myCommand.Parameters.AddWithValue("@id_user", Properties.Settings.Default.UserId); myCommand.Parameters.AddWithValue("@rating", rating); myCommand.ExecuteNonQuery(); } } catch { MessageBox.Show("SaveTest"); conn.Close(); return false; } conn.Close(); return true; } public bool AddInfo(List<string> data) { SqlConnection conn = getConn(); conn.Open(); string sql = "INSERT INTO [Infos] (header,body,icon) " + "values (@header,@body,@icon)"; try { using (SqlCommand myCommand = new SqlCommand(sql, conn)) { myCommand.Parameters.AddWithValue("@header", data[0]); myCommand.Parameters.AddWithValue("@body", data[1]); myCommand.Parameters.AddWithValue("@icon", data[2]); myCommand.ExecuteNonQuery(); } } catch { conn.Close(); return false; } conn.Close(); return true; } public string getPassword(string login) { string myValue = "Error1"; SqlConnection conn = getConn(); conn.Open(); string sql = $"select * from [User] where login = '{login}'"; using (SqlCommand cmd = new SqlCommand(sql, conn)) { SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) myValue = reader.GetString(reader.GetOrdinal("password")); reader.Close(); } conn.Close(); return myValue; try { } catch { MessageBox.Show("getPassword"); return "Error"; } } public int getIdUser(string login) { SqlConnection conn = getConn(); conn.Open(); int myValue = -1; string sql = string.Format($"select id_user from [User] where login = '{login}'"); using (SqlCommand cmd = new SqlCommand(sql, conn)) { SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) myValue = reader.GetInt32(reader.GetOrdinal("id_user")); reader.Close(); } conn.Close(); return myValue; } public List<List<string>> getRating() { List<List<string>> result = new List<List<string>>(); SqlConnection conn = getConn(); conn.Open(); string sql = "select username,firstname,groupes,rating from [User],[Rating] " + "where [User].id_user = [Rating].id_user"; using (SqlCommand myCommand = new SqlCommand(sql, conn)) { SqlDataReader reader = myCommand.ExecuteReader(); while (reader.Read()) { List<string> res = new List<string>(); res.Add(reader.GetString(0)); res.Add(reader.GetString(1)); res.Add(reader.GetString(2)); res.Add(reader.GetInt32(3).ToString()); result.Add(res); }; reader.Close(); } conn.Close(); return result; } public List<List<string>> getQuestions() { List<List<string>> result = new List<List<string>>(); SqlConnection conn = getConn(); conn.Open(); string sql = string.Format($"select * from [Question]"); using (SqlCommand cmd = new SqlCommand(sql, conn)) { SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { List<string> quest = new List<string>(); quest.Add(reader.GetInt32(0).ToString()); quest.Add(reader.GetString(1)); quest.Add(reader.GetString(2)); quest.Add(reader.GetString(3)); quest.Add(reader.GetString(4)); quest.Add(reader.GetString(5)); quest.Add(reader.GetInt32(6).ToString()); result.Add(quest); } reader.Close(); } conn.Close(); return result; } public List<List<string>> getListQuest() { List<List<string>> result = new List<List<string>>(); SqlConnection conn = getConn(); conn.Open(); string sql = "select id_quest,quest from [Question]"; using (SqlCommand myCommand = new SqlCommand(sql, conn)) { SqlDataReader reader = myCommand.ExecuteReader(); while (reader.Read()) { List<string> res = new List<string>(); res.Add(reader.GetInt32(0).ToString()); res.Add(reader.GetString(1)); result.Add(res); } reader.Close(); } conn.Close(); return result; } public List<List<string>> getListInfo(string filter = "%") { List<List<string>> result = new List<List<string>>(); SqlConnection conn = getConn(); conn.Open(); string sql = "select * from [Infos]"; using (SqlCommand myCommand = new SqlCommand(sql, conn)) { myCommand.Parameters.AddWithValue("@filter",filter); SqlDataReader reader = myCommand.ExecuteReader(); while (reader.Read()) { List<string> res = new List<string>(); res.Add(reader.GetString(1)); res.Add(reader.GetString(2)); res.Add(reader.GetString(3)); result.Add(res); } reader.Close(); } conn.Close(); return result; } public void update() { nameDB = Properties.Settings.Default.MyDatabaseConnectionString; } } }
using Site.Models; using System; using System.Collections.Generic; namespace Site.Services { public interface ISitemapModelRepository { public IEnumerable<SitemapModel> Sitemaps { get; } SitemapModel GetPage(uint? pageNumber); SitemapModel GetPageById(Guid? sitemapModelId); uint GetPageNumber(uint? pageNumber); void AddSitemapItem(SitemapModel sitemapItem); void UpdatePage(SitemapModel sitemapItem); void DeletePageById(Guid sitemapModelId); } }
using System.Linq; using StackExchange.Redis; using Broadcast.Storage.Serialization; namespace Broadcast.Storage.Redis { /// <summary> /// Extensions for object /// </summary> public static class SerializerExtensions { /// <summary> /// Serialize objects to HashEntries /// </summary> /// <param name="obj"></param> /// <returns></returns> public static HashEntry[] SerializeToRedis(this object obj) { var hashset = obj.Serialize() .Select(h => new HashEntry(h.Name, h.Value)) .ToArray(); return hashset; } /// <summary> /// Deserialize Redis hashEntries to Objects /// </summary> /// <typeparam name="T"></typeparam> /// <param name="hashEntries"></param> /// <returns></returns> public static T DeserializeRedis<T>(this HashEntry[] hashEntries) { if (!hashEntries.Any()) { return default; } var item = hashEntries.Select(h => new HashValue(h.Name, h.Value)).Deserialize<T>(); return item; } } }
using System.Collections.Generic; namespace GameServer.Data { public sealed class Conversation { public int Id { get; set; } public string Name { get; set; } public int ChatCount { get; set; } public Dictionary<int, Chat> Chats { get; set; } public Conversation() { Name = string.Empty; ChatCount = 1; Chats = new Dictionary<int, Chat> { { 1, new Chat() } }; } } }
namespace SkyApm.Diagnostics.AspNetCore { internal static class TagsExtension { public static string REQUEST = "request"; public static string RESPONSE = "response"; public static string HEADERS = "header"; public static string EXCEPTION = "exception"; } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Reflection; using JetBrains.Annotations; using Microsoft.DotNet.Cli.Utils; using Microsoft.EntityFrameworkCore.Tools.DotNet.Internal; // ReSharper disable ArgumentsStyleNamedExpression namespace Microsoft.EntityFrameworkCore.Tools.DotNet { public class Program { public static int Main([NotNull] string[] args) { DebugHelper.HandleDebugSwitch(ref args); try { var options = CommandLineOptions.Parse(args); if (options.IsHelp) { return 2; } HandleVerboseContext(options); return new DispatchOperationExecutor( new ProjectContextFactory(), new EfConsoleCommandSpecFactory(new EfConsoleCommandResolver()), new DotNetProjectBuilder()) .Execute(options); } catch (Exception ex) { if (ex is TargetInvocationException) { ex = ex.InnerException; } if (!(ex is OperationErrorException)) { Reporter.Error.WriteLine(ex.ToString()); } Reporter.Error.WriteLine(ex.Message.Bold().Red()); return 1; } } private static void HandleVerboseContext(CommandLineOptions options) { bool isVerbose; bool.TryParse(Environment.GetEnvironmentVariable(CommandContext.Variables.Verbose), out isVerbose); options.IsVerbose = options.IsVerbose || isVerbose; if (options.IsVerbose) { Environment.SetEnvironmentVariable(CommandContext.Variables.Verbose, bool.TrueString); } } } }
using System; using SWPCCBilling2.Infrastructure; using System.Runtime.InteropServices; using SWPCCBilling2.Completions; using System.Collections.Generic; using System.Linq; using SWPCCBilling2.Models; using System.Diagnostics; using System.IO; namespace SWPCCBilling2.Controllers { public class InvoiceController : Controller { private readonly InvoiceStore _invoiceStore; private readonly FamilyStore _familyStore; private readonly Ledger _ledger; private readonly UrlFactory _urlFactory; private readonly InvoiceDocumentFactory _invoiceDocFactory; private readonly Mailer _mailer; private readonly ParentStore _parentStore; private readonly DateFactory _dateFactory; public InvoiceController() { _invoiceStore = new InvoiceStore(); _familyStore = new FamilyStore(); _ledger = new Ledger(); _urlFactory = UrlFactory.DefaultUrlFactory; _invoiceDocFactory = new InvoiceDocumentFactory(); _mailer = new Mailer(); _parentStore = new ParentStore(); _dateFactory = DateFactory.DefaultDateFactory; } [Action("open-invoice","family-name date(optional)")] public void OpenInvoice( [CompleteWith(typeof(FamilyCompletion))] string name, [CompleteWith(typeof(DateCompletion))][Optional] DateTime? date) { DateTime invoiceDate = _dateFactory.GetInvoiceDate(date); IList<Family> activeFamilies = _familyStore.LoadActiveFamilesWithName(name).ToList(); foreach (Family family in activeFamilies) { IList<LedgerLine> ledgerLines = _ledger.LoadLinesWithoutInvoiceForFamily(family.Name); if (ledgerLines.Count == 0) { Console.WriteLine("No invoice created for {0} family - no account activity.", family.Name); continue; } Invoice invoice = _invoiceStore.Load(family.Name, invoiceDate); if (invoice == null) { DateTime dueDate = new DateTime(invoiceDate.Year, invoiceDate.Month, family.DueDay); invoice = new Invoice(family.Name, invoiceDate, dueDate); _invoiceStore.Add(invoice); Console.WriteLine("Creating invoice for {0} family on {1:d}", family.Name, invoiceDate); } else Console.WriteLine("Appending to existing opening invoice for {0} on {1:d}", family.Name, invoiceDate); foreach (LedgerLine ledgerLine in ledgerLines) invoice.AddLedgerLine(ledgerLine); Console.WriteLine(" Amount Due: {0:C}", invoice.BalanceDue()); _invoiceStore.Save(invoice); foreach (LedgerLine ledgerLine in ledgerLines) { ledgerLine.InvoiceId = invoice.Id; _ledger.SaveLine(ledgerLine); }; } } [Action("close-invoice","family-name date(optional)")] public void CloseInvoice( [CompleteWith(typeof(FamilyCompletion))] string name, [CompleteWith(typeof(DateCompletion))][Optional] DateTime? date) { DateTime invoiceDate = _dateFactory.GetInvoiceDate(date); IList<Family> activeFamilies = _familyStore.LoadActiveFamilesWithName(name).ToList(); foreach (Family family in activeFamilies) { Invoice invoice = _invoiceStore.Load(family.Name, invoiceDate); if (invoice == null) { Console.WriteLine("No invoice found for {0} family on {1:d}", family.Name, invoiceDate); continue; } if (invoice.BalanceDue() != 0m) { Console.WriteLine("Invoice for {0} family on {1:d} cannot be closed because they owe {2:C}", family.Name, invoiceDate, invoice.BalanceDue()); continue; } invoice.Closed = _dateFactory.Now(); _invoiceStore.Save(invoice, false); Console.WriteLine("Invoice {0} for {1} family on {2:d} has been closed.", invoice.Id, family.Name, invoiceDate); } } [Action("send-invoice","family-name date(optional) invoice-style(optional)")] public void SendInvoice( [CompleteWith(typeof(FamilyCompletion))] string name, [CompleteWith(typeof(DateCompletion))][Optional] DateTime? date, [CompleteWith(typeof(InvoiceStyleCompletion))][Optional]string viewName) { Console.Write("Password? "); string password = Console.ReadLine(); DateTime invoiceDate = _dateFactory.GetInvoiceDate(date); IList<Family> activeFamilies = _familyStore.LoadActiveFamilesWithName(name).ToList(); foreach (Family family in activeFamilies) { Invoice invoice = _invoiceStore.Load(family.Name, invoiceDate); if (invoice == null) { Console.WriteLine("No invoice found for {0} family on {1:d}", family.Name, invoiceDate); continue; } string subject = String.Format("SWPCC {0:MMMM yyyy} Invoice for {1}", invoice.Opened, family.Name); string htmlBody = _invoiceDocFactory.CreateInvoiceHtmlText(invoice.Id, viewName); IList<string> emailAddresses = _parentStore.LoadForFamilyName(family.Name) .Where(p => !String.IsNullOrEmpty(p.Email)) .Select(p => p.Email) .ToList(); if (_mailer.Send(subject, htmlBody, password, emailAddresses)) { Console.WriteLine("Invoice {0} for {1} family on {2:d} has been sent.", invoice.Id, family.Name, invoiceDate); invoice.Sent = _dateFactory.Now(); _invoiceStore.Save(invoice, false); } } } [Action("export-invoice","family-name date(optional) invoice-style(optional)")] public void ExportInvoice( [CompleteWith(typeof(FamilyCompletion))] string name, [CompleteWith(typeof(DateCompletion))][Optional] DateTime? date, [CompleteWith(typeof(InvoiceStyleCompletion))][Optional]string viewName) { DateTime invoiceDate = _dateFactory.GetInvoiceDate(date); IList<Family> activeFamilies = _familyStore.LoadActiveFamilesWithName(name).ToList(); foreach (Family family in activeFamilies) { Invoice invoice = _invoiceStore.Load(family.Name, invoiceDate); if (invoice == null) { Console.WriteLine("No invoice found for {0} family on {1:d}", family.Name, invoiceDate); continue; } string fileName = String.Format("{0}-{1}.htm", family.Name, invoice.Id); string invoiceFilePath = DocumentPath.For("Invoices", invoiceDate.ToString("yyyy MMMM"), fileName); string invoiceFolderPath = Path.GetDirectoryName(invoiceFilePath); Directory.CreateDirectory(invoiceFolderPath); var outStream = new FileStream(invoiceFilePath, FileMode.CreateNew); Stream inStream = _invoiceDocFactory.CreateInvoiceHtmlStream(invoice.Id, viewName); inStream.CopyTo(outStream); inStream.Close(); outStream.Close(); Console.WriteLine("Invoice {0} for {1} family on {2:d} has been written to: {3}.", invoice.Id, family.Name, invoiceDate, invoiceFilePath); } } [Action("show-invoice","family-name date(optional) invoice-style(optional)")] public void ShowInvoice( [CompleteWith(typeof(FamilyCompletion))] string familyName, [CompleteWith(typeof(DateCompletion))][Optional] DateTime? date, [CompleteWith(typeof(InvoiceStyleCompletion))][Optional]string viewName) { DateTime invoiceDate = _dateFactory.GetInvoiceDate(date); Invoice invoice = _invoiceStore.Load(familyName, invoiceDate); if (invoice != null) { string url = _urlFactory.UrlForPath("invoice/{0}/{1}", invoice.Id, viewName); Process.Start(url); } else Console.WriteLine("No invoice for {0} family on {1:d}.", familyName, invoiceDate); } [Action("remove-invoice","family-name date")] public void RemoveInvoice( [CompleteWith(typeof(FamilyCompletion))] string name, [CompleteWith(typeof(DateCompletion))][Optional] DateTime? date) { DateTime invoiceDate = _dateFactory.GetInvoiceDate(date); IList<Family> activeFamilies = _familyStore.LoadActiveFamilesWithName(name).ToList(); foreach (Family family in activeFamilies) { Invoice invoice = _invoiceStore.Load(family.Name, invoiceDate); if (invoice == null) { Console.WriteLine("No invoice found for {0} family on {1:d}", family.Name, invoiceDate); continue; } _ledger.RemoveInvoiceId(invoice.Id); _invoiceStore.Remove(invoice); Console.WriteLine("Invoice {0} for {1} family on {2:d} has been removed.", invoice.Id, family.Name, invoiceDate); } } } }
// Takes a little less than an hour to run using System; using System.Collections.Generic; using System.Diagnostics; using ExcelLibrary.SpreadSheet; // Used for Excel Integration namespace dejonker1._0 { class Program { const int MAX_NODES = 100; const int TRIES = 5; // Amount of tries for each graph. This is to acquire the median static void Main() { //For Excel integration Workbook workbook = new Workbook(); Worksheet worksheetDijkstra = new Worksheet("Dijkstra"); Worksheet worksheetBellmanFord = new Worksheet("Bellman-Ford"); Console.WriteLine("starting..."); for (int nodes = 10; nodes < MAX_NODES; nodes+=1) { for (int edges = nodes-1; edges < nodes*(nodes-1); edges+=1) { Graph graph = new Graph(nodes, edges); double timeD = MeasureRunTimeDijkstra(graph, TRIES); double timeBF = MeasureRunTimeBellmanFord(graph, TRIES); worksheetDijkstra.Cells[edges, nodes] = new Cell(timeD, CellFormat.General); worksheetBellmanFord.Cells[edges, nodes] = new Cell(timeBF, CellFormat.General); } Console.WriteLine($"Node {nodes}"); // Shows progress } workbook.Worksheets.Add(worksheetDijkstra); workbook.Worksheets.Add(worksheetBellmanFord); workbook.Save(@"C:\Users\gusta\Desktop\cba321\dejonker01.xls"); // This will go to MATLAB Console.WriteLine("Worksheet saved"); Console.Beep(500, 3000); // Plays a sound of 500hz for 3000 ms. This is to signal the program is finished. Console.ReadKey(); } static double MeasureRunTimeDijkstra(Graph graph, int tries) { Stopwatch s = new Stopwatch(); List<double> timings = new List<double>(); for (int i = 0; i < tries; i++) { s.Start(); graph.Dijkstra(0); s.Stop(); timings.Add(s.Elapsed.TotalMilliseconds); s.Reset(); } timings.Sort(); return timings[2]; // median } static double MeasureRunTimeBellmanFord(Graph graph, int tries) { Stopwatch s = new Stopwatch(); List<double> timings = new List<double>(); for (int i = 0; i < tries; i++) { s.Start(); graph.BellmanFord(0); s.Stop(); timings.Add(s.Elapsed.TotalMilliseconds); s.Reset(); } timings.Sort(); return timings[2]; // median } } }
using System.Collections.Generic; using Newtonsoft.Json; namespace Particle.Models { public class ParticleGeneralResponse { [JsonProperty("ok")] public bool Ok { get; set; } [JsonProperty("errors")] public List<string> Errors { get; set; } [JsonProperty("code")] public int Code { get; set; } } }
namespace Menees.Windows.Forms { #region Using Directives using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; #endregion public static partial class WindowsUtility { #region Private Methods static partial void SetHighDpiMode() { Application.SetHighDpiMode(HighDpiMode.SystemAware); } #endregion } }
using System; namespace intro { class Program { static void Main(string[] args) { Console.WriteLine("***** Delegates as event enablers *****\n"); // First, make a Car object. Car c1 = new Car("SlugBug", 100, 10); // Register multiple targets for the notifications. c1.RegisterWithCarEngine(new Car.CarEngineHandler(OnCarEngineEvent)); c1.RegisterWithCarEngine(new Car.CarEngineHandler(OnCarEngineEvent2)); // Speed up (this will trigger the events). Console.WriteLine("***** Speeding up *****"); for (int i = 0; i < 6; i++) c1.Accelerate(20); Console.ReadLine(); } // We now have TWO methods that will be called by the Car // when sending notifications. public static void OnCarEngineEvent(string msg) { Console.WriteLine("\n***** Message From Car Object *****"); Console.WriteLine("=> {0}", msg); Console.WriteLine("***********************************\n"); } public static void OnCarEngineEvent2(string msg) { Console.WriteLine("=> {0}", msg.ToUpper()); } } }
using System; using NLog; namespace Daisy.Terminal.Log { public sealed class FileLogger : ILogger { private static readonly Logger _instance; static FileLogger() { LogManager.ReconfigExistingLoggers(); _instance = LogManager.GetCurrentClassLogger(); } public void Error(Exception ex) { _instance.Error(ex); } public void Error(string message, Exception ex) { _instance.Error(ex, message); } public void Error(string message) { _instance.Error(message); } public void Info(string message) { _instance.Info(message); } } }
@model CategoryNameModel @{ ViewData["Title"] = "Delete Category"; } <h2>@ViewData["Title"]</h2> <hr /> <h3>Are you sure you want to delete <font color="red">@Model.Name</font> category?</h3> <div> <form asp-action="Delete"> <input type="submit" value="Delete" class="btn btn-danger" /> | <a asp-action="Index" asp-route-sortType="alphadown" class="btn btn-default">Back to List</a> <input asp-for="Id" type="hidden" value="@Model.Id" /> </form> </div>
using System; using System.Collections.Generic; namespace Foster.Framework { /// <summary> /// A Virtual Input Button that can be mapped to different keyboards and gamepads /// </summary> public class VirtualButton { public interface INode { bool Pressed(float buffer, long lastBufferConsumedTime); bool Down { get; } bool Released { get; } bool Repeated(float delay, float interval); void Update(); } public class KeyNode : INode { public Input Input; public Keys Key; public bool Pressed(float buffer, long lastBufferConsumedTime) { if (Input.Keyboard.Pressed(Key)) return true; var timestamp = Input.Keyboard.Timestamp(Key); var time = Time.Duration.Ticks; if (time - timestamp <= TimeSpan.FromSeconds(buffer).Ticks && timestamp > lastBufferConsumedTime) return true; return false; } public bool Down => Input.Keyboard.Down(Key); public bool Released => Input.Keyboard.Released(Key); public bool Repeated(float delay, float interval) => Input.Keyboard.Repeated(Key, delay, interval); public void Update() { } public KeyNode(Input input, Keys key) { Input = input; Key = key; } } public class MouseButtonNode : INode { public Input Input; public MouseButtons MouseButton; public bool Pressed(float buffer, long lastBufferConsumedTime) { if (Input.Mouse.Pressed(MouseButton)) return true; var timestamp = Input.Mouse.Timestamp(MouseButton); var time = Time.Duration.Ticks; if (time - timestamp <= TimeSpan.FromSeconds(buffer).Ticks && timestamp > lastBufferConsumedTime) return true; return false; } public bool Down => Input.Mouse.Down(MouseButton); public bool Released => Input.Mouse.Released(MouseButton); public bool Repeated(float delay, float interval) => Input.Mouse.Repeated(MouseButton, delay, interval); public void Update() { } public MouseButtonNode(Input input, MouseButtons mouseButton) { Input = input; MouseButton = mouseButton; } } public class ButtonNode : INode { public Input Input; public int Index; public Buttons Button; public bool Pressed(float buffer, long lastBufferConsumedTime) { if (Input.Controllers[Index].Pressed(Button)) return true; var timestamp = Input.Controllers[Index].Timestamp(Button); var time = Time.Duration.Ticks; if (time - timestamp <= TimeSpan.FromSeconds(buffer).Ticks && timestamp > lastBufferConsumedTime) return true; return false; } public bool Down => Input.Controllers[Index].Down(Button); public bool Released => Input.Controllers[Index].Released(Button); public bool Repeated(float delay, float interval) => Input.Controllers[Index].Repeated(Button, delay, interval); public void Update() { } public ButtonNode(Input input, int controller, Buttons button) { Input = input; Index = controller; Button = button; } } public class AxisNode : INode { public Input Input; public int Index; public Axes Axis; public float Threshold; private float pressedTimestamp; private const float AXIS_EPSILON = 0.00001f; public bool Pressed(float buffer, long lastBufferConsumedTime) { if (Pressed()) return true; var time = Time.Duration.Ticks; if (time - pressedTimestamp <= TimeSpan.FromSeconds(buffer).Ticks && pressedTimestamp > lastBufferConsumedTime) return true; return false; } public bool Down { get { if (Math.Abs(Threshold) <= AXIS_EPSILON) return Math.Abs(Input.Controllers[Index].Axis(Axis)) > AXIS_EPSILON; if (Threshold < 0) return Input.Controllers[Index].Axis(Axis) <= Threshold; return Input.Controllers[Index].Axis(Axis) >= Threshold; } } public bool Released { get { if (Math.Abs(Threshold) <= AXIS_EPSILON) return Math.Abs(Input.LastState.Controllers[Index].Axis(Axis)) > AXIS_EPSILON && Math.Abs(Input.Controllers[Index].Axis(Axis)) < AXIS_EPSILON; if (Threshold < 0) return Input.LastState.Controllers[Index].Axis(Axis) <= Threshold && Input.Controllers[Index].Axis(Axis) > Threshold; return Input.LastState.Controllers[Index].Axis(Axis) >= Threshold && Input.Controllers[Index].Axis(Axis) < Threshold; } } public bool Repeated(float delay, float interval) { throw new NotImplementedException(); } private bool Pressed() { if (Math.Abs(Threshold) <= AXIS_EPSILON) return (Math.Abs(Input.LastState.Controllers[Index].Axis(Axis)) < AXIS_EPSILON && Math.Abs(Input.Controllers[Index].Axis(Axis)) > AXIS_EPSILON); if (Threshold < 0) return (Input.LastState.Controllers[Index].Axis(Axis) > Threshold && Input.Controllers[Index].Axis(Axis) <= Threshold); return (Input.LastState.Controllers[Index].Axis(Axis) < Threshold && Input.Controllers[Index].Axis(Axis) >= Threshold); } public void Update() { if (Pressed()) pressedTimestamp = Input.Controllers[Index].Timestamp(Axis); } public AxisNode(Input input, int controller, Axes axis, float threshold) { Input = input; Index = controller; Axis = axis; Threshold = threshold; } } public readonly Input Input; public readonly List<INode> Nodes = new List<INode>(); public float RepeatDelay; public float RepeatInterval; public float Buffer; private long lastBufferConsumeTime; public bool Pressed { get { for (int i = 0; i < Nodes.Count; i++) if (Nodes[i].Pressed(Buffer, lastBufferConsumeTime)) return true; return false; } } public bool Down { get { for (int i = 0; i < Nodes.Count; i++) if (Nodes[i].Down) return true; return false; } } public bool Released { get { for (int i = 0; i < Nodes.Count; i++) if (Nodes[i].Released) return true; return false; } } public bool Repeated { get { for (int i = 0; i < Nodes.Count; i++) if (Nodes[i].Pressed(Buffer, lastBufferConsumeTime) || Nodes[i].Repeated(RepeatDelay, RepeatInterval)) return true; return false; } } public VirtualButton(Input input, float buffer = 0f) { Input = input; // Using a Weak Reference to subscribe this object to Updates // This way it's automatically collected if the user is no longer // using it, and we don't require the user to call a Dispose or // Unsubscribe callback Input.virtualButtons.Add(new WeakReference<VirtualButton>(this)); RepeatDelay = Input.RepeatDelay; RepeatInterval = Input.RepeatInterval; Buffer = buffer; } public void ConsumeBuffer() { lastBufferConsumeTime = Time.Duration.Ticks; } public VirtualButton Add(params Keys[] keys) { foreach (var key in keys) Nodes.Add(new KeyNode(Input, key)); return this; } public VirtualButton Add(params MouseButtons[] buttons) { foreach (var button in buttons) Nodes.Add(new MouseButtonNode(Input, button)); return this; } public VirtualButton Add(int controller, params Buttons[] buttons) { foreach (var button in buttons) Nodes.Add(new ButtonNode(Input, controller, button)); return this; } public VirtualButton Add(int controller, Axes axis, float threshold) { Nodes.Add(new AxisNode(Input, controller, axis, threshold)); return this; } public void Clear() { Nodes.Clear(); } internal void Update() { for (int i = 0; i < Nodes.Count; i ++) Nodes[i].Update(); } } }
using System; using System.Text; using Kinetix.ComponentModel; namespace Kinetix.Reporting { /// <summary> /// Méthodes utilitaires pour l'encodage de fichiers en base 64. /// </summary> public static class FileBase64Utils { /// <summary> /// Calcule la source d'une image HTML pour afficher une image à partir d'un fichier donné. /// </summary> /// <param name="file">Fichier.</param> /// <returns>Source de l'image en base 64.</returns> public static string ComputeHtmlImageSrc(DownloadedFile file) { var sb = new StringBuilder(); sb.Append("data:"); sb.Append(file.ContentType); sb.Append(";base64,"); sb.Append(Convert.ToBase64String(file.Fichier)); return sb.ToString(); } } }
using Plugin.Permissions.Abstractions; using WorkingWithMaps.Views; using Xamarin.Forms; namespace WorkingWithMaps { public class App : Application { public App () { var tabs = new TabbedPage (); tabs.Children.Add (new MapPage {Title = "Map/Zoom", Icon = "glyphish_74_location.png"}); tabs.Children.Add (new MapAppPage {Title = "Map App", Icon = "glyphish_103_map.png"}); MainPage = new MapTabs(); } } }
#region Arx One FTP // Arx One FTP // A simple FTP client // https://github.com/ArxOne/FTP // Released under MIT license http://opensource.org/licenses/MIT #endregion namespace ArxOne.FtpTest { using System; using Ftp; using Ftp.Exceptions; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class SpecialTest { [TestCategory("Platform")] [TestProperty("Platform", "Xlight FTP")] [TestProperty("Protocol", "FTP")] [TestMethod] public void BroadcastTest() { var testHost = TestHost.Get(platform: "xlightftpd", protocol: "ftp"); using (var ftpClient = new FtpClient(testHost.Uri, testHost.Credential)) { for (int i = 0; i < 100; i++) { try { ftpClient.ListEntries("/"); } catch (FtpProtocolException) { } } } } #if DEBUG [TestProperty("Protocol", "FTP")] [TestMethod] public void SpecificBrownEduTest() { //using (var ftpClient = new FtpClient(new Uri("ftp://speedtest.tele2.net"), null, new FtpClientParameters() using (var ftpClient = new FtpClient(new Uri("ftp://ftp.cs.brown.edu"), null, new FtpClientParameters() { Passive = false, })) { var entries = ftpClient.MlsdEntries(""); //.Mlsd(new FtpPath("/")); } } #endif } }
/* LongLongInteger.Relation.cs Copyright (c) 2017 Palmtree Software This software is released under the MIT License. https://opensource.org/licenses/MIT */ using System; // 演算子のオーバーロードに関するガイドライン: // http://msdn.microsoft.com/ja-jp/library/ms229032.aspx namespace Palmtree.Math { partial struct LongLongInteger : IComparable, IComparable<LongLongInteger> { #region 演算子 #if !CONCEAL_OPERATORS #region < のオーバーロード /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより小さいならばtrue、そうではないのならfalseです。 /// </returns> public static bool operator <(long x, LongLongInteger y) { return (Compare(y, x) > 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより小さいならばtrue、そうではないのならfalseです。 /// </returns> [CLSCompliant(false)] public static bool operator <(ulong x, LongLongInteger y) { return (Compare(y, x) > 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより小さいならばtrue、そうではないのならfalseです。 /// </returns> public static bool operator <(UnsignedLongLongInteger x, LongLongInteger y) { return (Compare(y, x) > 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより小さいならばtrue、そうではないのならfalseです。 /// </returns> public static bool operator <(LongLongInteger x, long y) { return (Compare(x, y) < 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより小さいならばtrue、そうではないのならfalseです。 /// </returns> [CLSCompliant(false)] public static bool operator <(LongLongInteger x, ulong y) { return (Compare(x, y) < 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより小さいならばtrue、そうではないのならfalseです。 /// </returns> public static bool operator <(LongLongInteger x, UnsignedLongLongInteger y) { return (Compare(x, y) < 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより小さいならばtrue、そうではないのならfalseです。 /// </returns> public static bool operator <(LongLongInteger x, LongLongInteger y) { return (Compare(x, y) < 0); } #endregion #region <= のオーバーロード /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより小さいまたは等しいならばtrue、そうではないのならfalseです。 /// </returns> public static bool operator <=(long x, LongLongInteger y) { return (Compare(y, x) >= 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより小さいまたは等しいならばtrue、そうではないのならfalseです。 /// </returns> [CLSCompliant(false)] public static bool operator <=(ulong x, LongLongInteger y) { return (Compare(y, x) >= 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより小さいまたは等しいならばtrue、そうではないのならfalseです。 /// </returns> public static bool operator <=(UnsignedLongLongInteger x, LongLongInteger y) { return (Compare(y, x) >= 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより小さいまたは等しいならばtrue、そうではないのならfalseです。 /// </returns> public static bool operator <=(LongLongInteger x, long y) { return (Compare(x, y) <= 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより小さいまたは等しいならばtrue、そうではないのならfalseです。 /// </returns> [CLSCompliant(false)] public static bool operator <=(LongLongInteger x, ulong y) { return (Compare(x, y) <= 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより小さいまたは等しいならばtrue、そうではないのならfalseです。 /// </returns> public static bool operator <=(LongLongInteger x, UnsignedLongLongInteger y) { return (Compare(x, y) <= 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより小さいまたは等しいならばtrue、そうではないのならfalseです。 /// </returns> public static bool operator <=(LongLongInteger x, LongLongInteger y) { return (Compare(x, y) <= 0); } #endregion #region > のオーバーロード /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより大きいならばtrue、そうではないのならfalseです。 /// </returns> public static bool operator >(long x, LongLongInteger y) { return (Compare(y, x) < 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより大きいならばtrue、そうではないのならfalseです。 /// </returns> [CLSCompliant(false)] public static bool operator >(ulong x, LongLongInteger y) { return (Compare(y, x) < 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより大きいならばtrue、そうではないのならfalseです。 /// </returns> public static bool operator >(UnsignedLongLongInteger x, LongLongInteger y) { return (Compare(y, x) < 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより大きいならばtrue、そうではないのならfalseです。 /// </returns> public static bool operator >(LongLongInteger x, long y) { return (Compare(x, y) > 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより大きいならばtrue、そうではないのならfalseです。 /// </returns> [CLSCompliant(false)] public static bool operator >(LongLongInteger x, ulong y) { return (Compare(x, y) > 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより大きいならばtrue、そうではないのならfalseです。 /// </returns> public static bool operator >(LongLongInteger x, UnsignedLongLongInteger y) { return (Compare(x, y) > 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより大きいならばtrue、そうではないのならfalseです。 /// </returns> public static bool operator >(LongLongInteger x, LongLongInteger y) { return (Compare(x, y) > 0); } #endregion #region >= のオーバーロード /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより大きいまたは等しいならばtrue、そうではないのならfalseです。 /// </returns> public static bool operator >=(long x, LongLongInteger y) { return (Compare(y, x) <= 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより大きいまたは等しいならばtrue、そうではないのならfalseです。 /// </returns> [CLSCompliant(false)] public static bool operator >=(ulong x, LongLongInteger y) { return (Compare(y, x) <= 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより大きいまたは等しいならばtrue、そうではないのならfalseです。 /// </returns> public static bool operator >=(UnsignedLongLongInteger x, LongLongInteger y) { return (Compare(y, x) <= 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより大きいまたは等しいならばtrue、そうではないのならfalseです。 /// </returns> public static bool operator >=(LongLongInteger x, long y) { return (Compare(x, y) >= 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより大きいまたは等しいならばtrue、そうではないのならfalseです。 /// </returns> [CLSCompliant(false)] public static bool operator >=(LongLongInteger x, ulong y) { return (Compare(x, y) >= 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより大きいまたは等しいならばtrue、そうではないのならfalseです。 /// </returns> public static bool operator >=(LongLongInteger x, UnsignedLongLongInteger y) { return (Compare(x, y) >= 0); } /// <summary> /// 二つのオブジェクトの大小関係を調べます。 /// </summary> /// <param name="x"> /// 比較対象のオブジェクトです。 /// </param> /// <param name="y"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// xがyより大きいまたは等しいならばtrue、そうではないのならfalseです。 /// </returns> public static bool operator >=(LongLongInteger x, LongLongInteger y) { return (Compare(x, y) >= 0); } #endregion #endif #endregion #region パブリックメソッド #region CompareTo のオーバーロード /// <summary> /// オブジェクトの論理的な大小関係を求めます。 /// </summary> /// <param name="o"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// オブジェクトがoより小さいならば負の数、オブジェクトがoと等しいならば0、オブジェクトがoより大きいならば正の数です。 /// </returns> public int CompareTo(long o) { return (Compare(this, o)); } /// <summary> /// オブジェクトの論理的な大小関係を求めます。 /// </summary> /// <param name="o"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// オブジェクトがoより小さいならば負の数、オブジェクトがoと等しいならば0、オブジェクトがoより大きいならば正の数です。 /// </returns> [CLSCompliant(false)] public int CompareTo(ulong o) { return (Compare(this, new UnsignedLongLongInteger(o))); } /// <summary> /// オブジェクトの論理的な大小関係を求めます。 /// </summary> /// <param name="o"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// オブジェクトがoより小さいならば負の数、オブジェクトがoと等しいならば0、オブジェクトがoより大きいならば正の数です。 /// </returns> public int CompareTo(UnsignedLongLongInteger o) { return (Compare(this, o)); } #endregion #region Compare のオーバーロード /// <summary> /// 二つのオブジェクトの論理的な大小関係を求めます。 /// </summary> /// <param name="x"> /// 比較するオブジェクトです。 /// </param> /// <param name="y"> /// 比較するオブジェクトです。 /// </param> /// <returns> /// xがyより小さいならば負の数、xがyと等しいならば0、xがyより大きいならば正の数です。 /// </returns> public static int Compare(long x, LongLongInteger y) { return (-Compare(y, x)); } /// <summary> /// 二つのオブジェクトの論理的な大小関係を求めます。 /// </summary> /// <param name="x"> /// 比較するオブジェクトです。 /// </param> /// <param name="y"> /// 比較するオブジェクトです。 /// </param> /// <returns> /// xがyより小さいならば負の数、xがyと等しいならば0、xがyより大きいならば正の数です。 /// </returns> [CLSCompliant(false)] public static int Compare(ulong x, LongLongInteger y) { return (-Compare(y, new UnsignedLongLongInteger(x))); } /// <summary> /// 二つのオブジェクトの論理的な大小関係を求めます。 /// </summary> /// <param name="x"> /// 比較するオブジェクトです。 /// </param> /// <param name="y"> /// 比較するオブジェクトです。 /// </param> /// <returns> /// xがyより小さいならば負の数、xがyと等しいならば0、xがyより大きいならば正の数です。 /// </returns> public static int Compare(UnsignedLongLongInteger x, LongLongInteger y) { return (-Compare(y, x)); } /// <summary> /// 二つのオブジェクトの論理的な大小関係を求めます。 /// </summary> /// <param name="x"> /// 比較するオブジェクトです。 /// </param> /// <param name="y"> /// 比較するオブジェクトです。 /// </param> /// <returns> /// xがyより小さいならば負の数、xがyと等しいならば0、xがyより大きいならば正の数です。 /// </returns> public static int Compare(LongLongInteger x, long y) { if (x._sign == SignType.Zero) { if (y > 0) return (-1); else if (y == 0) return (0); else return (1); } else if (y == 0) return ((int)x._sign); else if (x._sign == SignType.Positive) { if (y > 0) return (UnsignedLongLongInteger.Compare(x._abs, (ulong)y)); else return (1); } else { if (y > 0) return (-1); else if (y == long.MinValue) return (UnsignedLongLongInteger.Compare(_nagated_long_min_value, x._abs)); else return (UnsignedLongLongInteger.Compare((ulong)-y, x._abs)); } } /// <summary> /// 二つのオブジェクトの論理的な大小関係を求めます。 /// </summary> /// <param name="x"> /// 比較するオブジェクトです。 /// </param> /// <param name="y"> /// 比較するオブジェクトです。 /// </param> /// <returns> /// xがyより小さいならば負の数、xがyと等しいならば0、xがyより大きいならば正の数です。 /// </returns> [CLSCompliant(false)] public static int Compare(LongLongInteger x, ulong y) { if (x._sign == SignType.Zero) return (y == 0 ? 0 : -1); else if (y == 0) return ((int)x._sign); else if (x._sign == SignType.Positive) return (UnsignedLongLongInteger.Compare(x._abs, y)); else return (-1); } /// <summary> /// 二つのオブジェクトの論理的な大小関係を求めます。 /// </summary> /// <param name="x"> /// 比較するオブジェクトです。 /// </param> /// <param name="y"> /// 比較するオブジェクトです。 /// </param> /// <returns> /// xがyより小さいならば負の数、xがyと等しいならば0、xがyより大きいならば正の数です。 /// </returns> public static int Compare(LongLongInteger x, UnsignedLongLongInteger y) { if (x._sign == SignType.Zero) return (y.IsZero ? 0 : -1); else if (y.IsZero) return ((int)x._sign); else if (x._sign == SignType.Positive) return (UnsignedLongLongInteger.Compare(x._abs, y)); else return (-1); } /// <summary> /// 二つのオブジェクトの論理的な大小関係を求めます。 /// </summary> /// <param name="x"> /// 比較するオブジェクトです。 /// </param> /// <param name="y"> /// 比較するオブジェクトです。 /// </param> /// <returns> /// xがyより小さいならば負の数、xがyと等しいならば0、xがyより大きいならば正の数です。 /// </returns> public static int Compare(LongLongInteger x, LongLongInteger y) { if (x._sign == SignType.Zero) return (-(int)y._sign); else if (y._sign == SignType.Zero) return ((int)x._sign); else if (x._sign == SignType.Positive) { if (y._sign == SignType.Positive) return (UnsignedLongLongInteger.Compare(x._abs, y._abs)); else return (1); } else { if (y._sign == SignType.Positive) return (-1); else return (UnsignedLongLongInteger.Compare(y._abs, x._abs)); } } #endregion #endregion #region IComparable メンバ /// <summary> /// オブジェクトの論理的な大小関係を求めます。 /// </summary> /// <param name="o"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// オブジェクトがoより小さいならば負の数、オブジェクトがoと等しいならば0、オブジェクトがoより大きいならば正の数です。 /// </returns> public int CompareTo(object o) { if (o == null) return (1); else if (o is ulong) return (Compare(this, (ulong)o)); else if (o is long) return (Compare(this, (long)o)); else if (o is UnsignedLongLongInteger) return (Compare(this, (UnsignedLongLongInteger)o)); else if (o is LongLongInteger) return (Compare(this, (LongLongInteger)o)); else throw (new ArgumentException("LongLongIntegerオブジェクトと比較できないオブジェクトが与えられました。", "o")); } #endregion #region IComparable<LongLongInteger> メンバ /// <summary> /// オブジェクトの論理的な大小関係を求めます。 /// </summary> /// <param name="o"> /// 比較対象のオブジェクトです。 /// </param> /// <returns> /// オブジェクトがoより小さいならば負の数、オブジェクトがoと等しいならば0、オブジェクトがoより大きいならば正の数です。 /// </returns> public int CompareTo(LongLongInteger o) { return (Compare(this, o)); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SQLite; namespace Jargon { internal class Jarsql { public SQLiteConnection connection; public Jarsql() { connection = new SQLiteConnection(); } public bool IsConnected() { if(connection.State == System.Data.ConnectionState.Open) { return true; } else { return false; } } } }
namespace AgileObjects.ReadableExpressions.Translations { #if NET35 using Microsoft.Scripting.Ast; #else using System.Linq.Expressions; #endif internal static class RuntimeVariablesTranslation { public static ITranslation For(RuntimeVariablesExpression runtimeVariables, ITranslationContext context) { return ParameterSetTranslation .For(runtimeVariables.Variables, context) .WithTypes(ExpressionType.RuntimeVariables, runtimeVariables.Type); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PortableKnowledge.Controls { /// <summary> /// State of the condition being monitored by the TrafficLightControl /// </summary> public enum TrafficLightControlState { None, Good, Warning, Bad, GoodWarning, BadWarning, GoodBad, All } public partial class TrafficLightControl : UserControl { private List<TrafficLightControl> _SlaveLights = new List<TrafficLightControl>(); private TrafficLightControlState _State; /// <summary> /// Current state to display /// </summary> public TrafficLightControlState State { get { return _State; } set { _State = value; SetImageForState(); foreach (TrafficLightControl light in _SlaveLights) light.State = _State; } } /// <summary> /// Message to display to user on mouse-over /// </summary> public String Message { get { return GetMessage(); } set { SetMessage(value); foreach (TrafficLightControl light in _SlaveLights) light.Message = Message; } } // BlinkTimer is a System.Threading.Timer rather than a Windows.Forms.Timer because we want // to blink properly, even if the main thread is tied up. System.Threading.Timer _blinkTimer; private Boolean _blinkOn = true; private int _blinkRate; /// <summary> /// The rate of blinking of the light, in milliseconds. 0 = no blinking. /// </summary> public int BlinkRate { get { return _blinkRate; } set { _blinkRate = value; _blinkTimer?.Dispose(); _blinkOn = true; if (value > 0) _blinkTimer = new System.Threading.Timer(BlinkTimerCallback, null, _blinkRate, 0); else SetImageForState(false); foreach (TrafficLightControl light in _SlaveLights) light.BlinkRate = _blinkRate; } } private void BlinkTimerCallback(Object state) { if (_blinkRate > 0) { SetImageForState(!_blinkOn); _blinkOn = !_blinkOn; _blinkTimer = new System.Threading.Timer(BlinkTimerCallback, null, _blinkRate, 0); } else { _blinkOn = true; SetImageForState(false); } } /// <summary> /// Update an external control to reflect the state of this control /// </summary> /// <param name="slave">Control to update</param> public void UpdateExternalControl(TrafficLightControl slave) { if (slave != null) { slave.State = _State; slave.Message = GetMessage(); slave.BlinkRate = _blinkRate; } } /// <summary> /// Add a slave control that will always autmatically reflect the state of this /// control, until removed with RemoveSlave(). /// </summary> /// <param name="slave">Slave control to add</param> public void AddSlave(TrafficLightControl slave) { if (slave != null) { _SlaveLights.Add(slave); UpdateExternalControl(slave); } } /// <summary> /// Remove an existing slaved control /// </summary> /// <param name="slave">Control to remove as a slave to this control</param> public void RemoveSlave(TrafficLightControl slave) { _SlaveLights.Remove(slave); } private Bitmap LightImages = null; public TrafficLightControl() { InitializeComponent(); pictureBox1.BackColor = Color.Transparent; toolTip1.OwnerDraw = true; LightImages = global::PortableKnowledge.Controls.Properties.Resources.TrafficLightControlImages; } /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } if (LightImages != null) { BlinkRate = 0; LightImages.Dispose(); LightImages = null; } base.Dispose(disposing); } /// <summary> /// Change the state and message of the traffic light control in one step /// </summary> /// <param name="State">New state to change to</param> /// <param name="Message">New Message, NULL for no message</param> public void ChangeState(TrafficLightControlState State, String Message = null) { this.State = State; this.Message = Message; } private Object ImageLock = new Object(); private void SetImageForState(Boolean ForceOff = false) { Rectangle imageRect; if (LightImages == null) return; Debug.WriteLine("State: " + _State + "(Force Off: " + ForceOff + ")"); switch (ForceOff ? TrafficLightControlState.None : _State) { case TrafficLightControlState.Good: imageRect = new Rectangle(323, 163, 260, 100); if (!ForceOff) toolTip1.BackColor = Color.PaleGreen; break; case TrafficLightControlState.Bad: imageRect = new Rectangle(323, 449, 260, 100); if (!ForceOff) toolTip1.BackColor = Color.IndianRed; break; case TrafficLightControlState.Warning: imageRect = new Rectangle(323, 306, 260, 100); if (!ForceOff) toolTip1.BackColor = Color.Yellow; break; case TrafficLightControlState.GoodWarning: imageRect = new Rectangle(29, 449, 260, 100); if (!ForceOff) toolTip1.BackColor = Color.GreenYellow; break; case TrafficLightControlState.GoodBad: imageRect = new Rectangle(29, 306, 260, 100); if (!ForceOff) toolTip1.BackColor = Color.MediumVioletRed; break; case TrafficLightControlState.BadWarning: imageRect = new Rectangle(29, 163, 260, 100); if (!ForceOff) toolTip1.BackColor = Color.OrangeRed; break; case TrafficLightControlState.All: imageRect = new Rectangle(29, 20, 260, 100); if (!ForceOff) toolTip1.BackColor = Color.WhiteSmoke; break; default: imageRect = new Rectangle(323, 20, 260, 100); toolTip1.BackColor = this.BackColor; break; } SetPictureImage(imageRect); } private void SetPictureImage(Rectangle Frame) { if (pictureBox1.InvokeRequired) { //pictureBox1.BeginInvoke(new MethodInvoker(delegate () { SetPictureImage(Frame); })); pictureBox1.Invoke(new MethodInvoker(delegate () { SetPictureImage(Frame); })); } else { try { pictureBox1.SuspendLayout(); if (pictureBox1.Image != null) pictureBox1.Image.Dispose(); pictureBox1.Image = LightImages.Clone(Frame, LightImages.PixelFormat); pictureBox1.ResumeLayout(); } catch { } } } private void SetMessage(String NewMessage) { if (pictureBox1.InvokeRequired) { pictureBox1.BeginInvoke(new MethodInvoker(delegate () { SetMessage(NewMessage); })); } else toolTip1.SetToolTip(pictureBox1, NewMessage); } private String GetMessage() { return toolTip1.GetToolTip(pictureBox1); } private void toolTip1_Draw(object sender, DrawToolTipEventArgs e) { e.DrawBackground(); e.DrawBorder(); e.DrawText(); } } }
using System; using System.Threading; namespace SharedResources { public class Program { private static bool isCompleted; static readonly object lockCompleted = new object(); public static void Main(string[] args) { Thread thread = new Thread(HelloWorld); thread.Start(); HelloWorld(); } private static void HelloWorld() { lock (lockCompleted) { if (!isCompleted) { isCompleted = true; Console.WriteLine("Hello world should be printed only once"); } } } } }
using System.Collections.Generic; using GreenhousePlusPlus.Core.Vision; using SixLabors.ImageSharp; namespace GreenhousePlusPlus.Core.Models { public class FilterResult { public Image RedImage; public Image GreenImage; public Image LeafImage; public Image EarthImage; public Image EdgeImage; public Image PlantTipImage; public Image BlurImage; public Image PassImage; public Image WholePipeline; public Image HInterpolateImage; public Histogram Histogram; public Histogram LeafHistogram; public Histogram EarthHistogram; } public class FilterFileInfo { public string Element { get; set; } public string Name { get; set; } public string Path { get; set; } } public class ImageProcessResult { public FilterValues FilterValues { get; set; } public List<FilterFileInfo> Files { get; set; } } }
using SitecoreCognitiveServices.Foundation.MSSDK.Speech.Models; using System; using System.IO; using System.Threading.Tasks; namespace SitecoreCognitiveServices.Foundation.MSSDK.Speech { public interface ISpeakerVerificationRepository { Verification Verify(Stream audioStream, Guid id); Task<Verification> VerifyAsync(Stream audioStream, Guid id); CreateProfileResponse CreateProfile(string locale); Task<CreateProfileResponse> CreateProfileAsync(string locale); void DeleteProfile(Guid id); Task DeleteProfileAsync(Guid id); Profile GetProfile(Guid id); Task<Profile> GetProfileAsync(Guid id); Profile[] GetProfiles(); Task<Profile[]> GetProfilesAsync(); VerificationPhrase[] GetPhrases(string locale); Task<VerificationPhrase[]> GetPhrasesAsync(string locale); Enrollment Enroll(Stream audioStream, Guid id); Task<Enrollment> EnrollAsync(Stream audioStream, Guid id); void ResetEnrollments(Guid id); Task ResetEnrollmentsAsync(Guid id); } }
using System; using System.Collections.Generic; using System.Text.RegularExpressions; public static class Kata { public static string Order(string words) { if (words == "") return words; var rx = new Regex("[a-zA-Z]"); var wordsList = new List<string>(words.Split(" ")); string[] orderedArray = new string[wordsList.Count]; foreach (var word in wordsList) { var rep = Convert.ToInt16(rx.Replace(word, "")); orderedArray[rep - 1] = word; } return string.Join(" ", orderedArray); } }
using System.Net; using System.Threading.Tasks; using DotDns.Records; namespace DotDns.Middlewares { public class ExampleMiddleware : IDnsMiddleware { private readonly IDnsMiddleware.MiddlewareDelegate _next; public ExampleMiddleware(IDnsMiddleware.MiddlewareDelegate next) { _next = next; } public async ValueTask ProcessAsync(DnsPacket request, DnsPacket response) { response.Authoritative = true; response.AddAnswer(new ARecord("example.com", 123, IPAddress.Parse("127.5.0.1").MapToIPv4())); await _next(request, response); } } }
using CatFactory.CodeFactory; namespace CatFactory.Tests.CodeBuilders { public class CSharpCodeBuilder : CodeBuilder { public override string FileExtension => "cs"; public override string FileName => ObjectDefinition.Name; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tesseract.Core.Graphics.Accelerated; using Tesseract.Core.Native; namespace Tesseract.Vulkan.Graphics.Impl { public class VulkanBuffer : IBuffer { public VulkanGraphics Graphics { get; } public VKBuffer Buffer { get; } public ulong Size { get; } public BufferUsage Usage { get; } public IVKMemoryBinding MemoryBinding { get; } IMemoryBinding IBuffer.MemoryBinding => MemoryBinding; public MemoryMapFlags SupportedMappings => MemoryBinding.SupportedMapFlags; public void Dispose() { GC.SuppressFinalize(this); MemoryBinding.Dispose(); Buffer.Dispose(); } public void FlushGPUToHost(in MemoryRange range = default) { MemoryRange range2 = range.Constrain(Size); if (range2.Length > 0) MemoryBinding.Invalidate(range2.Offset, range2.Length); } public void FlushHostToGPU(in MemoryRange range = default) { MemoryRange range2 = range.Constrain(Size); if (range2.Length > 0) MemoryBinding.Flush(range2.Offset, range2.Length); } public IPointer<T> Map<T>(MemoryMapFlags flags, in MemoryRange range = default) where T : unmanaged { MemoryRange range2 = range.Constrain(Size); if (range2.Length == 0) throw new ArgumentException("Cannot map a range of 0 length", nameof(range)); IntPtr ptr = MemoryBinding.Map(); unsafe { return new UnmanagedPointer<T>(ptr, (int)(range2.Length / (ulong)sizeof(T))); } } public void Unmap() => MemoryBinding.Unmap(); public VulkanBuffer(VulkanGraphics graphics, VKBuffer buffer, in BufferCreateInfo createInfo) { Graphics = graphics; Buffer = buffer; Size = createInfo.Size; Usage = createInfo.Usage; if (createInfo.MemoryBinding is IVKMemoryBinding vkbinding) MemoryBinding = vkbinding; else MemoryBinding = Graphics.Memory.Allocate(createInfo, buffer); MemoryBinding.Bind(buffer); } } }
using SmartEnergy.Contract.DTO; using SmartEnergy.Contract.Enums; using System; using System.Collections.Generic; using System.Security.Claims; using System.Text; using System.Threading.Tasks; namespace SmartEnergy.Contract.Interfaces { public interface IIncidentService : IGenericService<IncidentDto> { Task RevertIncidentToInitialState(int incidentID); Task<LocationDto> GetIncidentLocationAsync(int incidentId); Task<IncidentDto> AddCrewToIncidentAsync(int incidentId, int crewId); IncidentDto RemoveCrewFromIncidet(int incidentId); List<IncidentDto> GetUnassignedIncidents(); Task AddDeviceToIncidentAsync(int incidentId, int deviceId); void RemoveDeviceFromIncindet(int incidentId, int deviceId); Task<List<IncidentMapDisplayDto>> GetUnresolvedIncidentsForMapAsync(); Task<List<CallDto>> GetIncidentCallsAsync(int incidentId); Task<int> GetNumberOfCallsAsync(int incidentId); Task<int> GetNumberOfAffectedConsumersAsync(int incidentId); Task<List<DeviceDto>> GetIncidentDevicesAsync(int incidentId); void SetIncidentPriority(int incidentId); Task<List<DeviceDto>> GetUnrelatedDevicesAsync(int incidentId); Task<CrewDto> GetIncidentCrewAsync(int incidentId); Task<CallDto> AddIncidentCallAsync(int incidentId, CallDto newCall); void AssignIncidetToUser(int incidentId, int userId); IncidentListDto GetIncidentsPaged(IncidentFields sortBy, SortingDirection direction, int page, int perPage, IncidentFilter filter, OwnerFilter owner, string searchParam, ClaimsPrincipal user); IncidentStatisticsDto GetStatisticsForUser(int userId); } }
using System; namespace MahTweets.Core.Settings { ///// <summary> ///// Declare a UIElement as a feature of a plugin ///// </summary> //[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] //public class ExportFeatureAttribute : Attribute //{ // /// <summary> // /// Default Constructor // /// </summary> // /// <param name="type">Type of UIElement</param> // public ExportFeatureAttribute(Type type) // { // this.Value = type; // } // /// <summary> // /// Type of UIElement // /// </summary> // public Type Value // { // get; // private set; // } // //public bool IsMultiple // //{ // // get; // // set; // //} // } /// <summary> /// Declare a UIElement as a feature of a plugin /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public class SettingsClassAttribute : Attribute { /// <summary> /// Default Constructor /// </summary> /// <param name="type">Type of UIElement</param> public SettingsClassAttribute(Type type) { Value = type; } /// <summary> /// Type of UIElement /// </summary> public Type Value { get; private set; } //public bool IsMultiple //{ // get; // set; //} } }
using IronText.Framework; using IronText.Reflection; namespace CSharpParser { [Vocabulary] public class CsScanner { [Match(@"'//' ~('\r' | '\n' | u0085 | u2028 | u2029)*")] public void LineComment() { } [Match("'/*' (~'*'* | '*' ~'/')* '*/'")] public void MultiLineComment() { } [Match(@"'\r'? '\n' | u0085 | u2028 | u2029")] public void NewLine() { } [Match("(Zs | '\t' | u000B | u000C)+")] public void WhiteSpace() { } [Match(@" '@'? ('_' | Lu | Ll | Lt | Lm | Lo | Nl) (Pc | Lu | Ll | Lt | Lm | Lo | Nl | Nd | Mn | Mc | Cf)* ")] public CsIdentifier Identifier(string text) { return null; } #region Contextual keywords [Literal("assembly", Disambiguation.Contextual)] public CsAssemblyKeyword AssemblyKeyword() { return null; } [Literal("module", Disambiguation.Contextual)] public CsModuleKeyword ModuleKeyword() { return null; } [Literal("field", Disambiguation.Contextual)] public CsFieldKeyword FieldKeyword() { return null; } [Literal("event", Disambiguation.Contextual)] public CsEventKeyword EventKeyword() { return null; } [Literal("method", Disambiguation.Contextual)] public CsMethodKeyword MethodKeyword() { return null; } [Literal("param", Disambiguation.Contextual)] public CsParamKeyword ParamKeyword() { return null; } [Literal("property", Disambiguation.Contextual)] public CsPropertyKeyword PropertyKeyword() { return null; } [Literal("return", Disambiguation.Contextual)] public CsReturnKeyword ReturnKeyword() { return null; } [Literal("type", Disambiguation.Contextual)] public CsTypeKeyword TypeKeyword() { return null; } [Literal("var", Disambiguation.Contextual)] public CsVarKeyword VarKeyword() { return null; } #endregion Contextual keywords [Literal("true")] public CsBoolean BooleanTrue(string text) { return null; } [Literal("false")] public CsBoolean BooleanFalse(string text) { return null; } [Match("digit+ ([Uu] | [Ll] | 'UL' | 'Ul' | 'uL' | 'ul' | 'LU' | 'Lu' | 'lU' | 'lu')?")] public CsInteger DecimalInteger(string text) { return null; } [Match("'0x' hex+ ([Uu] | [Ll] | 'UL' | 'Ul' | 'uL' | 'ul' | 'LU' | 'Lu' | 'lU' | 'lu')?")] public CsInteger HexInteger(string text) { return null; } [Match("digit+ '.' digit+ ([eE] [+-]? digit+)? [FfDdMm]?")] [Match(" '.' digit+ ([eE] [+-]? digit+)? [FfDdMm]?")] [Match("digit+ ([eE] [+-]? digit+) [FfDdMm]?")] [Match("digit+ [FfDdMm]")] public CsReal Real(string text) { return null; } [Match(@"['] ( ~(u0027 | u005c | '\n') | esc ['""\\0abfnrtv] | esc hex {1,4} | esc 'u' hex {4} ) [']")] public CsChar Char(string text) { return null; } [Match(@" quot ( ~(quot | u005c | '\n') | '\\' ['""\\0abfnrtv] | '\\' hex {1,4} | '\\' 'u' hex {4} )* quot ")] public CsString RegularString(string text) { return null; } [Match("'@' quot (~quot | quot quot)* quot")] public CsString VerbatimString(string text) { return null; } [Literal("null")] public CsNull Null() { return null; } [Produce] public CsDimSeparators DimSeparators(CsCommas commas) { return null; } #region Typed keywords [Literal("extern")] public CsExtern Extern() { return null; } [Literal("partial")] public CsPartial Partial() { return null; } [Literal(";")] public CsSemicolon Semicolon() { return null; } [Literal("new")] public CsNew NewKeyword() { return null; } [Literal(".")] public CsDot Dot() { return null; } #endregion } }
// define this for some diagnostics #define LOG_TRACE_VERBOSE // ReSharper disable InconsistentNaming namespace App { /// <summary> /// Global game parameters. /// /// TODO: Make not static so can be tweaked at runtime. /// </summary> public static class Parameters { /// <summary> /// DEfault logging values. /// </summary> #if LOG_TRACE_VERBOSE //public static bool DefaultShowTraceStack = true; public static bool DefaultShowTraceStack = false; public static bool DefaultShowTraceSource = true; public static int DefaultLogVerbosity = 100; #else public static bool DefaultShowTraceStack = false; public static bool DefaultShowTraceSource = true; public static int DefaultLogVerbosity = 4; #endif /// <summary> /// Number of cards to start with (excluding King) /// </summary> public static int StartHandCardCount = 3; public static int MaxCardsInHand = 10; public static int MaxCardsInDeck = 60; public static int MinCardsInDeck = 30; /// <summary> /// The maximum mana a playerAgent can have /// </summary> public static int MaxManaCap = 12; /// <summary> /// How long in seconds a playerAgent has to place King on boardAgent /// </summary> public static float PlaceKingTimer = 10; /// <summary> /// How long in seconds a playerAgent has to form final hand from initial cards /// </summary> public static float MulliganTimer = 20; /// <summary> /// How long a playerAgent has to complete his turn. Note that there can be /// many actions in a turn, and the ordering is important. /// </summary> public static float GameTurnTimer = 99999; /// <summary> /// Minimum distance to enemy king when playing a new card to the boardAgent /// </summary> public static int EnemyKingClosestPlacement = 4; /// <summary> /// How much health a player loses whenever he is forced to draw from an empty deck. /// </summary> public static int CardExhaustionHealthLoss = -2; } }
#region copyright // (C) Copyright 2015 Dinu Marius-Constantin (http://dinu.at) and others. // // 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. // // Contributors: // Dinu Marius-Constantin #endregion using System; using System.Reflection; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using UFO.Commander.Handler; using UFO.Commander.Helper; using UFO.Commander.Proxy; using UFO.Commander.ViewModel.Entities; using UFO.Server.Bll.Common; using UFO.Server.Domain; using GalaSoft.MvvmLight.Messaging; using UFO.Commander.Messages; namespace UFO.Commander.ViewModel { [ViewExceptionHandler("Login Exception")] public class LoginViewModel : ViewModelBase { private readonly IAdminAccessBll _authAccessBll = BllAccessHandler.AdminAccessBll; public event EventHandler LogoutEvent; private bool _isLoggedIn; public bool IsLoggedIn { get { return _isLoggedIn; } set { _isLoggedIn = value; if (!value) { LogoutEvent?.Invoke(this, null); } } } public string Username { get; set; } public string Password { get; set; } public async Task<bool> RequestSessionToken(string textBoxUserName, string password) { if (!DebugHelper.IsReleaseMode) return true; var user = new User { EMail = textBoxUserName, Password = Crypto.EncryptPassword(password) }.ToViewModelObject<UserViewModel>(); BllAccessHandler.SessionToken = await _authAccessBll.RequestSessionTokenAsync(user); return await _authAccessBll.IsValidAdminAsync(BllAccessHandler.SessionToken); } public async Task<bool> Login() { if (!DebugHelper.IsReleaseMode) return true; return IsLoggedIn = await _authAccessBll.LoginAdminAsync(BllAccessHandler.SessionToken); } private ICommand _logoutCommand; public ICommand LogoutCommand { get { return _logoutCommand ?? (_logoutCommand = new RelayCommand(() => { if (BllAccessHandler.SessionToken == null) { Messenger.Default.Send(new ShowDialogMessage(this)); } })); } } private ICommand _loginCommand; public ICommand LoginCommand => _loginCommand ?? (_loginCommand = new RelayCommand(LoginCommandExecute)); private async void LoginCommandExecute() { var username = Username; var password = Password; var validSession = await RequestSessionToken(username, password); if (validSession) { validSession = await Login(); if (!validSession) return; Messenger.Default.Send(new ShowContentMessage(Locator.TabControlViewModel)); Messenger.Default.Send(new HideDialogMessage(this)); } } private ICommand _cancelCommand; public ICommand CancelCommand => _cancelCommand ?? (_cancelCommand = new RelayCommand(() => Application.Current.Shutdown())); public override string ToString() { return "UFO Login"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Framework.G1 { public static class OptionalCreateExtensions { public static Optional<T>.Value ToOptional<T>(this T value) { return new Optional<T>.Value(value); } public static Optional.Class<T> ToOptionalClass<T>(this T value) where T : class { return new Optional.Class<T>(value); } public static Optional.Struct<T> ToOptionalStruct<T>(this T value) where T : struct { return new Optional.Struct<T>(value); } public static Optional<T> ThenCreateOptional<T>( this bool condition, Func<T> create) { return condition ? create().ToOptional().UpCast<Optional<T>>() : Optional<T>.Absent.Value; } public static Optional<T> ThenCreateOptional<T>( this bool condition, T value) { return condition.ThenCreateOptional(() => value); } } }
using System.Collections.Generic; namespace SearchEngine { public static class Sources { public static List<Page> Pages = new List<Page>(); } }
#region License /* Copyright (c) 2018-2020 Wes Hampson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #endregion using Newtonsoft.Json; using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Windows.Forms; namespace WHampson.PigeonLocator { internal static class Program { public const string ConfigRecentFileKey = "recentFile"; public const string ConfigBlipSize = "blipSize"; public const string ConfigShowExterminated = "showExterminated"; public const string ConfigShowRemaining = "showRemaining"; public const string ConfigLastDirectory = "lastDirectory"; [STAThread] public static void Main(string[] args) { FatalExceptionHandler.Initialize(); if (Environment.OSVersion.Version.Major >= 6) { SetProcessDPIAware(); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (args.Length > 0) { Application.Run(new PigeonLocatorForm(args[0])); } else { Application.Run(new PigeonLocatorForm()); } } public static string GetAssemblyName() { Assembly asm = Assembly.GetExecutingAssembly(); if (asm == null) { return "null"; } return asm.GetName().Name; } public static string GetAssemblyTitle() { Assembly asm = Assembly.GetExecutingAssembly(); if (asm == null) { return "null"; } AssemblyTitleAttribute attr = (AssemblyTitleAttribute) Attribute.GetCustomAttribute(asm, typeof(AssemblyTitleAttribute), false); if (attr == null) { return "null"; } return attr.Title; } public static string GetExeName() { Assembly asm = Assembly.GetExecutingAssembly(); if (asm == null) { return "null"; } string path = asm.Location; if (string.IsNullOrWhiteSpace(path)) { return "null"; } return Path.GetFileNameWithoutExtension(path); } public static FileVersionInfo GetVersion() { Assembly asm = Assembly.GetExecutingAssembly(); if (asm == null) { return null; } return FileVersionInfo.GetVersionInfo(asm.Location); } public static string GetCopyrightString() { return "Copyright (C) 2018-2020 Wes Hampson"; } public static IniFile GetConfig() { return new IniFile(GetAssemblyName() + ".ini"); } public static void LogException(LogLevel l, Exception ex) { TextWriter w; switch (l) { case LogLevel.Error: w = Console.Error; break; default: w = Console.Out; break; } w.WriteLine("[{0}]: {1}: {2}", l.ToString(), ex.GetType().FullName, ex.Message); } [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern bool SetProcessDPIAware(); } internal enum LogLevel { Info, Warning, Error } }
using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace RuntimeInspectorNamespace { [RequireComponent( typeof( ScrollRect ) )] public class RecycledListView : MonoBehaviour { // Cached components [SerializeField] private RectTransform viewportTransform; [SerializeField] private RectTransform contentTransform; private float itemHeight, _1OverItemHeight; private float viewportHeight; private Dictionary<int, RecycledListItem> items = new Dictionary<int, RecycledListItem>(); private Stack<RecycledListItem> pooledItems = new Stack<RecycledListItem>(); IListViewAdapter adapter = null; private bool isDirty = false; // Current indices of items shown on screen private int currentTopIndex = -1, currentBottomIndex = -1; void Start() { GetComponent<ScrollRect>().onValueChanged.AddListener( ( pos ) => UpdateItemsInTheList() ); } void Update() { if( isDirty ) { viewportHeight = viewportTransform.rect.height; UpdateItemsInTheList(); isDirty = false; } } public void SetAdapter( IListViewAdapter adapter ) { this.adapter = adapter; itemHeight = adapter.ItemHeight; _1OverItemHeight = 1f / itemHeight; } // Update the list public void UpdateList() { contentTransform.anchoredPosition = Vector2.zero; float newHeight = Mathf.Max( 1f, adapter.Count * itemHeight ); contentTransform.sizeDelta = new Vector2( 0f, newHeight ); viewportHeight = viewportTransform.rect.height; UpdateItemsInTheList( true ); } public void ResetList() { itemHeight = adapter.ItemHeight; _1OverItemHeight = 1f / itemHeight; if( currentTopIndex > -1 && currentBottomIndex > -1 ) { if( currentBottomIndex > adapter.Count - 1 ) currentBottomIndex = adapter.Count - 1; DestroyItemsBetweenIndices( currentTopIndex, currentBottomIndex ); currentTopIndex = -1; currentBottomIndex = -1; } UpdateList(); } // Window is resized, update the list private void OnRectTransformDimensionsChange() { isDirty = true; } // Calculate the indices of items to show private void UpdateItemsInTheList( bool updateAllVisibleItems = false ) { if( adapter == null ) return; // If there is at least one item to show if( adapter.Count > 0 ) { float contentPos = contentTransform.anchoredPosition.y - 1f; int newTopIndex = (int) ( contentPos * _1OverItemHeight ); int newBottomIndex = (int) ( ( contentPos + viewportHeight + 2f ) * _1OverItemHeight ); if( newTopIndex < 0 ) newTopIndex = 0; if( newBottomIndex > adapter.Count - 1 ) newBottomIndex = adapter.Count - 1; if( currentTopIndex == -1 ) { // There are no active items updateAllVisibleItems = true; currentTopIndex = newTopIndex; currentBottomIndex = newBottomIndex; CreateItemsBetweenIndices( newTopIndex, newBottomIndex ); } else { // There are some active items if( newBottomIndex < currentTopIndex || newTopIndex > currentBottomIndex ) { // If user scrolled a lot such that, none of the items are now within // the bounds of the scroll view, pool all the previous items and create // new items for the new list of visible entries updateAllVisibleItems = true; DestroyItemsBetweenIndices( currentTopIndex, currentBottomIndex ); CreateItemsBetweenIndices( newTopIndex, newBottomIndex ); } else { // User did not scroll a lot such that, some items are are still within // the bounds of the scroll view. Don't destroy them but update their content, // if necessary if( newTopIndex > currentTopIndex ) { DestroyItemsBetweenIndices( currentTopIndex, newTopIndex - 1 ); } if( newBottomIndex < currentBottomIndex ) { DestroyItemsBetweenIndices( newBottomIndex + 1, currentBottomIndex ); } if( newTopIndex < currentTopIndex ) { CreateItemsBetweenIndices( newTopIndex, currentTopIndex - 1 ); // If it is not necessary to update all the items, // then just update the newly created items. Otherwise, // wait for the major update if( !updateAllVisibleItems ) { UpdateItemContentsBetweenIndices( newTopIndex, currentTopIndex - 1 ); } } if( newBottomIndex > currentBottomIndex ) { CreateItemsBetweenIndices( currentBottomIndex + 1, newBottomIndex ); // If it is not necessary to update all the items, // then just update the newly created items. Otherwise, // wait for the major update if( !updateAllVisibleItems ) { UpdateItemContentsBetweenIndices( currentBottomIndex + 1, newBottomIndex ); } } } currentTopIndex = newTopIndex; currentBottomIndex = newBottomIndex; } if( updateAllVisibleItems ) { // Update all the items UpdateItemContentsBetweenIndices( currentTopIndex, currentBottomIndex ); } } else if( currentTopIndex != -1 ) { // There is nothing to show but some items are still visible; pool them DestroyItemsBetweenIndices( currentTopIndex, currentBottomIndex ); currentTopIndex = -1; } } private void CreateItemsBetweenIndices( int topIndex, int bottomIndex ) { for( int i = topIndex; i <= bottomIndex; i++ ) { CreateItemAtIndex( i ); } } // Create (or unpool) an item private void CreateItemAtIndex( int index ) { RecycledListItem item; if( pooledItems.Count > 0 ) { item = pooledItems.Pop(); item.gameObject.SetActive( true ); } else { item = adapter.CreateItem( contentTransform ); item.SetAdapter( adapter ); } // Reposition the item ( (RectTransform) item.transform ).anchoredPosition = new Vector2( 0f, -index * itemHeight ); // To access this item easily in the future, add it to the dictionary items[index] = item; } private void DestroyItemsBetweenIndices( int topIndex, int bottomIndex ) { for( int i = topIndex; i <= bottomIndex; i++ ) { RecycledListItem item = items[i]; item.gameObject.SetActive( false ); pooledItems.Push( item ); } } private void UpdateItemContentsBetweenIndices( int topIndex, int bottomIndex ) { for( int i = topIndex; i <= bottomIndex; i++ ) { RecycledListItem item = items[i]; item.Position = i; adapter.SetItemContent( item ); } } } }
using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace IS4.AuthorizationCenter.Models.Entity { /// <summary> /// 自定义用户 /// </summary> public class ApplicationUser : IdentityUser<Guid> { /// <summary> /// 真实姓名 /// </summary> public string RealName { get; set; } /// <summary> /// 性别 0:男 1:女 /// </summary> public byte Sex { get; set; } = 0; /// <summary> /// 年龄 /// </summary> [MaxLength(3)] public int Age { get; set; } /// <summary> /// qq号 /// </summary> [MaxLength(20)] public virtual int Qicq { get; set; } /// <summary> /// 省份 /// </summary> [MaxLength(20)] public string Province { get; set; } /// <summary> /// 城市 /// </summary> [MaxLength(20)] public string City { get; set; } /// <summary> /// 国家 /// </summary> [MaxLength(20)] public string Country { get; set; } /// <summary> /// 头像 /// </summary> [MaxLength(300)] public string Portrait { get; set; } /// <summary> /// 昵称 /// </summary> [MaxLength(20)] public string NickName { get; set; } /// <summary> /// 微信开放id /// </summary> [MaxLength(100)] public string WeChatOpenId { get; set; } /// <summary> /// 是否删除 /// </summary> public bool IsDelete { get; set; } /// <summary> /// 角色用户关系表 /// </summary> public ICollection<ApplicationUserRole> UserRoles { get; set; } } }
using System.Collections.Generic; using System.Drawing; using TRTexture16Importer.Textures.Grouping; namespace TRTexture16Importer.Textures.Target { public class DynamicTextureTarget { public Dictionary<int, List<Rectangle>> DefaultTileTargets { get; set; } public Dictionary<TextureCategory, Dictionary<int, List<Rectangle>>> OptionalTileTargets { get; set; } public DynamicTextureTarget() { DefaultTileTargets = new Dictionary<int, List<Rectangle>>(); OptionalTileTargets = new Dictionary<TextureCategory, Dictionary<int, List<Rectangle>>>(); } } }
using System; using System.Collections.Generic; using System.Linq; using LinqExtender; using Linq.Flickr.Repository; using Linq.Flickr.Repository.Abstraction; namespace Linq.Flickr { public class CommentCollection : Query<Comment> { public CommentCollection(IFlickrElement elementProxy) { this.elementProxy = elementProxy; } protected override bool AddItem() { string photoId = (string)Bucket.Instance.For.Item(CommentColumns.PhotoId).Value; string text = (string)Bucket.Instance.For.Item(CommentColumns.Text).Value; if (string.IsNullOrEmpty(photoId)) { throw new Exception("Must have valid photoId"); } if (string.IsNullOrEmpty(text)) { throw new Exception("Must have some text for the comment"); } using (ICommentRepository commentRepositoryRepo = new CommentRepository(elementProxy)) { string commentId = commentRepositoryRepo.AddComment(photoId, text); // set the id. Bucket.Instance.For.Item(CommentColumns.Id).Value = commentId; return (string.IsNullOrEmpty(commentId) == false); } } protected override bool UpdateItem() { string commentId = (string)Bucket.Instance.For.Item(CommentColumns.Id).Value; string text = (string)Bucket.Instance.For.Item(CommentColumns.Text).Value; if (string.IsNullOrEmpty(commentId)) throw new Exception("Invalid comment Id"); if (string.IsNullOrEmpty(text)) throw new Exception("Blank comment is not allowed"); using (ICommentRepository commentRepositoryRepo = new CommentRepository(elementProxy)) { return commentRepositoryRepo.EditComment(commentId, text); } } protected override bool RemoveItem() { string commentId = (string)Bucket.Instance.For.Item(CommentColumns.Id).Value; if (string.IsNullOrEmpty(commentId)) { throw new Exception("Must provide a comment_id"); } using (ICommentRepository commentRepositoryRepo = new CommentRepository(elementProxy)) { return commentRepositoryRepo.DeleteComment(commentId); } } private static class CommentColumns { public const string Id = "Id"; public const string PhotoId = "PhotoId"; public const string Text = "Text"; } protected override void Process(LinqExtender.Interface.IModify<Comment> items) { using (ICommentRepository commentRepositoryRepo = new CommentRepository(elementProxy)) { string photoId = (string) Bucket.Instance.For.Item(CommentColumns.PhotoId).Value; string commentId = (string)Bucket.Instance.For.Item(CommentColumns.Id).Value; if (string.IsNullOrEmpty(photoId)) { throw new Exception("Must have a valid photoId"); } int index = Bucket.Instance.Entity.ItemsToSkipFromStart; int itemsToTake = int.MaxValue; if (Bucket.Instance.Entity.ItemsToFetch != null) { itemsToTake = Bucket.Instance.Entity.ItemsToFetch.Value; } // get comments IEnumerable<Comment> comments = commentRepositoryRepo.GetComments(photoId); // filter if (!string.IsNullOrEmpty(commentId)) { var query = (from comment in comments where comment.Id == commentId select comment).Skip(index).Take(itemsToTake); comments = query; } else { var query = (from comment in comments select comment).Skip(index).Take(itemsToTake); comments = query; } items.AddRange(comments, true); } } private IFlickrElement elementProxy; } }
namespace ISAAR.MSolve.Solvers.LinearSystems { /// <summary> /// Objects implementing this interface will be notifying before <see cref="ILinearSystem.Matrix"/> is modified. /// Authors: Serafeim Bakalakos /// </summary> public interface ISystemMatrixObserver { /// <summary> /// It will be called before setting <see cref="ILinearSystem.Matrix"/>. /// </summary> void HandleMatrixWillBeSet(); } }
using System.IO; namespace SystemEx { public static class PathEx { public static string Combine(char separator, params string[] paths) => Path.Combine(paths).Replace(Path.DirectorySeparatorChar, separator); } }
namespace Spect.Net.EvalParser.SyntaxTree { /// <summary> /// This class represents a single literal node /// </summary> public sealed class LiteralNode : ExpressionNode { /// <summary> /// The value of the literal node /// </summary> public uint LiteralValue { get; } /// <summary> /// The source of the literal node /// </summary> public string Source { get; } /// <summary> /// Retrieves the value of the expression /// </summary> /// <param name="evalContext">Evaluation context</param> /// <returns>Evaluated expression value</returns> public override ExpressionValue Evaluate(IExpressionEvaluationContext evalContext) { if (LiteralValue <= byte.MaxValue) { SuggestType(ExpressionValueType.Byte); } else if (LiteralValue <= ushort.MaxValue) { SuggestType(ExpressionValueType.Word); } else { SuggestType(ExpressionValueType.DWord); } return new ExpressionValue(LiteralValue); } /// <summary> /// Initialize a double literal value /// </summary> /// <param name="value">Double value</param> /// <param name="source">Source representation</param> public LiteralNode(uint value, string source) { LiteralValue = new ExpressionValue(value); Source = source; } /// <summary>Returns a string that represents the current object.</summary> /// <returns>A string that represents the current object.</returns> public override string ToString() => Source; } }
using System; using Evol.Common.IoC; namespace Evol.Domain.Configuration { public interface IDependencyRegister { //void Register(ServiceLifetime? lifetime = null); //void Register(Type from, Type to, ServiceLifetime? lifetime = null); void Register(); void Register(Type from, Type to, IocLifetime lifetime); } }
using System; using System.Linq; using System.Collections.Generic; using RUSTWebApplication.Core.DomainService; using RUSTWebApplication.Core.Entity.Product; namespace RUSTWebApplication.Core.ApplicationService.Services { public class ProductMetricService : IProductMetricService { private readonly IProductMetricRepository _productMetricRepository; public ProductMetricService(IProductMetricRepository productMetricRepository) { _productMetricRepository = productMetricRepository; } public ProductMetric Create(ProductMetric newProductMetric) { ValidateCreate(newProductMetric); return _productMetricRepository.Create(newProductMetric); } public ProductMetric Read(int productMetricId) { return _productMetricRepository.Read(productMetricId); } public List<ProductMetric> ReadAll() { return _productMetricRepository.ReadAll().ToList(); } public ProductMetric Update(ProductMetric updatedProductMetric) { ValidateUpdate(updatedProductMetric); return _productMetricRepository.Update(updatedProductMetric); } public ProductMetric Delete(int productMetricId) { return _productMetricRepository.Delete(productMetricId); } private void ValidateCreate(ProductMetric productMetric) { ValidateNull(productMetric); if (productMetric.Id != default) { throw new ArgumentException("You are not allowed to specify an ID when creating a ProductMetric."); } ValidateName(productMetric); ValidateMetricXValue(productMetric); } private void ValidateUpdate(ProductMetric productMetric) { ValidateNull(productMetric); ValidateName(productMetric); ValidateMetricXValue(productMetric); if (_productMetricRepository.Read(productMetric.Id) == null) { throw new ArgumentException($"Cannot find a Product Metric with the ID: {productMetric.Id}"); } } private void ValidateNull(ProductMetric productSize) { if (productSize == null) { throw new ArgumentNullException("ProductMetric cannot be null"); } } private void ValidateName(ProductMetric productMetric) { if (string.IsNullOrEmpty(productMetric.Name)) { throw new ArgumentException("You need to specify a Name for the ProductMetric."); } } private void ValidateMetricXValue(ProductMetric productMetric) { if (string.IsNullOrEmpty(productMetric.MetricX)) { throw new ArgumentException("You need to specify a MetricX for the ProductMetric"); } } } }
using System.ComponentModel; using UnityEngine; using UnityEngine.Timeline; namespace Timeline.Samples { // Uses the USS style defined in `Editor/Stylesheets/Extensions/common.uss`. // See `ReadMe-USS-Styles.md` for more details. [CustomStyle("AnnotationStyle")] [DisplayName("Annotation")] public class AnnotationMarker : Marker // Represents the serialized data for a marker. { public string title; public Color color = new Color(1.0f, 1.0f, 1.0f, 0.5f); public bool showLineOverlay = true; [TextArea(10, 15)] public string description; } }
using System; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace WebKit.Tests { [TestClass] public class Cookies { private static TestHarness _testHarness; [ClassInitialize] public static void Initialize(TestContext Context) { _testHarness = new TestHarness(); } [ClassCleanup] public static void Cleanup() { _testHarness.Stop(); } [TestMethod] public void TestCookieAcceptPolicyAlways() { // TODO: WebKit does not allow cookies to be set by file:// origin URLs. _testHarness.InvokeOnBrowser((Browser) => { Browser.CookieAcceptPolicy = CookieAcceptPolicy.Always; }); _testHarness.Test(@"TestContent\CookieAcceptPolicyAlways.html"); } [TestMethod] public void TestCookieAcceptPolicyNever() { _testHarness.InvokeOnBrowser((Browser) => { Browser.CookieAcceptPolicy = CookieAcceptPolicy.Never; }); _testHarness.Test(@"TestContent\CookieAcceptPolicyNever.html"); } } }
namespace EventHorizon.Blazor.TypeScript.Interop.Generator.Tests.GenerateClassStatementStringTests { using EventHorizon.Blazor.TypeScript.Interop.Generator.AstParser.Model; using Xunit; public class TypeAliasGenerationTests : GenerateStringTestBase { [Theory(DisplayName = "TypeAlias")] [Trait("Category", "TypeAlias")] [Trait("AST", "Sdcb")] [InlineData("NullableActionCallbackArgument.ts", "TypeAlias", "NullableActionCallbackArgument.Expected.txt", ASTParserType.Sdcb)] [InlineData("NullableAliasActionCallbackArgument.ts", "TypeAlias", "NullableAliasActionCallbackArgument.Expected.txt", ASTParserType.Sdcb)] [InlineData("NullableNumberArgument.ts", "TypeAlias", "NullableNumberArgument.Expected.txt", ASTParserType.Sdcb)] [InlineData("NullableTypeResponse.ts", "TypeAlias", "NullableTypeResponse.Expected.txt", ASTParserType.Sdcb)] [InlineData("ObjectTypeResponse.ts", "TypeAlias", "ObjectTypeResponse.Expected.txt", ASTParserType.Sdcb)] public void ShouldGenerateTypeAliasStringsUsingSdcb( string sourceFile, string path, string expectedFile, ASTParserType parserType ) => ValidateGenerateStrings( path, sourceFile, expectedFile, parserType: parserType ); [Theory(DisplayName = "TypeAlias")] [Trait("Category", "TypeAlias")] [Trait("AST", "NodeJS")] [InlineData("NullableActionCallbackArgument.ts", "TypeAlias", "NullableActionCallbackArgument.Expected.txt", ASTParserType.NodeJS)] [InlineData("NullableAliasActionCallbackArgument.ts", "TypeAlias", "NullableAliasActionCallbackArgument.Expected.txt", ASTParserType.NodeJS)] [InlineData("NullableNumberArgument.ts", "TypeAlias", "NullableNumberArgument.Expected.txt", ASTParserType.NodeJS)] [InlineData("NullableTypeResponse.ts", "TypeAlias", "NullableTypeResponse.Expected.txt", ASTParserType.NodeJS)] [InlineData("ObjectTypeResponse.ts", "TypeAlias", "ObjectTypeResponse.Expected.txt", ASTParserType.NodeJS)] public void ShouldGenerateTypeAliasStringsUsingNodeJS( string sourceFile, string path, string expectedFile, ASTParserType parserType ) => ValidateGenerateStrings( path, sourceFile, expectedFile, parserType: parserType ); } }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by Entitas.CodeGeneration.Plugins.ComponentsLookupGenerator. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ public static class GameComponentsLookup { public const int AbilityAttack = 0; public const int AbilityDamage = 1; public const int BossPlayer = 2; public const int Id = 3; public const int Local = 4; public const int MainMissionCompleted = 5; public const int MainMission = 6; public const int Owner = 7; public const int PlayerBox = 8; public const int Player = 9; public const int PlayerDeck = 10; public const int PlayerMissionCompleted = 11; public const int PlayerMission = 12; public const int PlayerMissionTarget = 13; public const int Playing = 14; public const int PlayingOrder = 15; public const int Round = 16; public const int RoundIndex = 17; public const int RoundLimit = 18; public const int SkillCardContainer = 19; public const int Turn = 20; public const int TurnNode = 21; public const int View = 22; public const int WeatherAbility = 23; public const int Weather = 24; public const int WeatherCost = 25; public const int WeatherData = 26; public const int WeatherDictionary = 27; public const int WeatherEffect = 28; public const int WeatherResloveFail = 29; public const int Winner = 30; public const int TotalComponents = 31; public static readonly string[] componentNames = { "AbilityAttack", "AbilityDamage", "BossPlayer", "Id", "Local", "MainMissionCompleted", "MainMission", "Owner", "PlayerBox", "Player", "PlayerDeck", "PlayerMissionCompleted", "PlayerMission", "PlayerMissionTarget", "Playing", "PlayingOrder", "Round", "RoundIndex", "RoundLimit", "SkillCardContainer", "Turn", "TurnNode", "View", "WeatherAbility", "Weather", "WeatherCost", "WeatherData", "WeatherDictionary", "WeatherEffect", "WeatherResloveFail", "Winner" }; public static readonly System.Type[] componentTypes = { typeof(AbilityAttackComponent), typeof(AbilityDamageComponent), typeof(BossPlayerComponent), typeof(IdComponent), typeof(LocalComponent), typeof(MainMissionCompletedComponent), typeof(MainMissionComponent), typeof(OwnerComponent), typeof(PlayerBoxComponent), typeof(PlayerComponent), typeof(PlayerDeckComponent), typeof(PlayerMissionCompletedComponent), typeof(PlayerMissionComponent), typeof(PlayerMissionTargetComponent), typeof(PlayingComponent), typeof(PlayingOrderComponent), typeof(RoundComponent), typeof(RoundIndexComponent), typeof(RoundLimitComponent), typeof(SkillCardContainerComponent), typeof(TurnComponent), typeof(TurnNodeComponent), typeof(ViewComponent), typeof(WeatherAbilityComponent), typeof(WeatherComponent), typeof(WeatherCostComponent), typeof(WeatherDataComponent), typeof(WeatherDictionaryComponent), typeof(WeatherEffectComponent), typeof(WeatherResloveFailComponent), typeof(WinnerComponent) }; }
/** * Runtime player settings * scene list */ using System.Collections; using System.Collections.Generic; using UnityEngine; namespace SS { public class RuntimePlayerSettings : DataAsset<RuntimePlayerSettings> { // Scene list in build settings public List<string> scenes = new List<string>(); public string userName; public string buildTime; } }
// Copyright (c) 2019, WebsitePanel-Support.net. // Distributed by websitepanel-support.net // Build and fixed by Key4ce - IT Professionals // https://www.key4ce.com // // Original source: // Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; namespace WebsitePanel.Providers.Mail { [Serializable] public class MailDomain : ServiceProviderItem { #region Smarter Mail 5.x String Constants //Domain Features public const string SMARTERMAIL5_SHOW_DOMAIN_REPORTS = "ShowDomainReports"; public const string SMARTERMAIL5_SHOW_CALENDAR = "ShowCalendar"; public const string SMARTERMAIL5_SHOW_CONTACTS = "ShowContacts"; public const string SMARTERMAIL5_SHOW_TASKS = "ShowTasks"; public const string SMARTERMAIL5_SHOW_NOTES = "ShowNotes"; public const string SMARTERMAIL5_POP_RETRIEVAL = "ShowCalendar"; public const string SMARTERMAIL5_POP_RETREIVAL_ENABLED = "EnablePopRetreival"; public const string SMARTERMAIL5_CATCHALLS_ENABLED = "EnableCatchAlls"; //Domain Throttling public const string SMARTERMAIL5_MESSAGES_PER_HOUR = "MessagesPerHour"; public const string SMARTERMAIL5_MESSAGES_PER_HOUR_ENABLED = "MessagesPerHourEnabled"; public const string SMARTERMAIL5_BANDWIDTH_PER_HOUR = "BandwidthPerHour"; public const string SMARTERMAIL5_BANDWIDTH_PER_HOUR_ENABLED = "BandwidthPerHourEnabled"; public const string SMARTERMAIL5_BOUNCES_PER_HOUR = "BouncesReceivedPerHour"; public const string SMARTERMAIL5_BOUNCES_PER_HOUR_ENABLED = "BouncesPerHourEnabled"; //Domain Limits public const string SMARTERMAIL5_POP_RETREIVAL_ACCOUNTS = "PopRetreivalAccounts"; #endregion #region Smarter Mail 6.x String Constants //Domain Features public const string SMARTERMAIL6_IMAP_RETREIVAL_ENABLED = "EnableImapRetreival"; public const string SMARTERMAIL6_MAIL_SIGNING_ENABLED = "EnableMailSigning"; public const string SMARTERMAIL6_EMAIL_REPORTS_ENABLED = "EnableEmailReports"; public const string SMARTERMAIL6_SYNCML_ENABLED = "EnableSyncML"; #endregion //license type public const string SMARTERMAIL_LICENSE_TYPE = "LicenseType"; private string[] blackList = new string[0]; private string redirectionHosts; private bool redirectionActive; private bool enabled; private string postmasterAccount; private string catchAllAccount; private string abuseAccount; private int maxPopRetrievalAccounts; public string RedirectionHosts { get { return this.redirectionHosts; } set { this.redirectionHosts = value; } } public string[] BlackList { get { return this.blackList; } set { this.blackList = value; } } public string CatchAllAccount { get { return this.catchAllAccount; } set { this.catchAllAccount = value; } } public string AbuseAccount { get { return this.abuseAccount; } set { this.abuseAccount = value; } } public bool RedirectionActive { get { return this.redirectionActive; } set { this.redirectionActive = value; } } public bool Enabled { get { return this.enabled; } set { this.enabled = value; } } public string PostmasterAccount { get { return this.postmasterAccount; } set { this.postmasterAccount = value; } } #region SmarterMail private string primaryDomainAdminUserName; private string primaryDomainAdminPassword; private string primaryDomainAdminFirstName; private string primaryDomainAdminLastName; private string serverIP; private string path; private int imapPort = 143; private int popPort = 110; private int smtpPort = 25; private int smtpPortAlt; private int ldapPort; private int maxAliases; private int maxDomainAliases; private int maxLists; private int maxDomainSizeInMB; private int maxDomainUsers; private int maxMailboxSizeInMB; private int maxMessageSize; private int maxRecipients; private bool requireSmtpAuthentication; private string listCommandAddress = ""; private bool isGlobalAddressList; private bool sharedContacts; private bool sharedNotes; private bool sharedCalendars; private bool sharedFolders; private bool sharedTasks; private bool bypassForwardBlackList; private bool showstatsmenu; private bool showspammenu; private bool showlistmenu; private bool showdomainaliasmenu; private bool showcontentfilteringmenu; public bool ShowsStatsMenu { get { return showstatsmenu; } set { showstatsmenu = value; } } public bool ShowSpamMenu { get { return showspammenu; } set { showspammenu = value; } } public bool ShowListMenu { get { return showlistmenu; } set { showlistmenu = value; } } public bool ShowDomainAliasMenu { get { return showdomainaliasmenu; } set { showdomainaliasmenu = value; } } public bool ShowContentFilteringMenu { get { return showcontentfilteringmenu; } set { showcontentfilteringmenu = value; } } public bool BypassForwardBlackList { get { return bypassForwardBlackList; } set { bypassForwardBlackList = value; } } public bool IsGlobalAddressList { get { return isGlobalAddressList; } set { isGlobalAddressList = value; } } public bool SharedContacts { get { return sharedContacts; } set { sharedContacts = value; } } public bool SharedNotes { get { return sharedNotes; } set { sharedNotes = value; } } public bool SharedCalendars { get { return sharedCalendars; } set { sharedCalendars = value; } } public bool SharedFolders { get { return sharedFolders; } set { sharedFolders = value; } } public bool SharedTasks { get { return sharedTasks; } set { sharedTasks = value; } } public string PrimaryDomainAdminUserName { get { return primaryDomainAdminUserName; } set { primaryDomainAdminUserName = value; } } public string PrimaryDomainAdminPassword { get { return primaryDomainAdminPassword; } set { primaryDomainAdminPassword = value; } } public string PrimaryDomainAdminFirstName { get { return primaryDomainAdminFirstName; } set { primaryDomainAdminFirstName = value; } } public string PrimaryDomainAdminLastName { get { return primaryDomainAdminLastName; } set { primaryDomainAdminLastName = value; } } public string ServerIP { get { return serverIP; } set { serverIP = value; } } public string Path { get { return path; } set { path = value; } } public int SmtpPortAlt { get { return smtpPortAlt; } set { smtpPortAlt = value; } } public int LdapPort { get { return ldapPort; } set { ldapPort = value; } } public int ImapPort { get { return imapPort; } set { imapPort = value; } } public int PopPort { get { return popPort; } set { popPort = value; } } public int SmtpPort { get { return smtpPort; } set { smtpPort = value; } } public int MaxAliases { get { return maxAliases; } set { maxAliases = value; } } public int MaxDomainAliases { get { return maxDomainAliases; } set { maxDomainAliases = value; } } public int MaxLists { get { return maxLists; } set { maxLists = value; } } public int MaxDomainSizeInMB { get { return maxDomainSizeInMB; } set { maxDomainSizeInMB = value; } } public int MaxDomainUsers { get { return maxDomainUsers; } set { maxDomainUsers = value; } } public int MaxMailboxSizeInMB { get { return maxMailboxSizeInMB; } set { maxMailboxSizeInMB = value; } } public int MaxMessageSize { get { return maxMessageSize; } set { maxMessageSize = value; } } public int MaxRecipients { get { return maxRecipients; } set { maxRecipients = value; } } public int MaxPopRetrievalAccounts { get { return maxPopRetrievalAccounts; } set { maxPopRetrievalAccounts = value; } } public bool RequireSmtpAuthentication { get { return requireSmtpAuthentication; } set { requireSmtpAuthentication = value; } } public string ListCommandAddress { get { return listCommandAddress; } set { listCommandAddress = value; } } #endregion #region IceWarp public bool UseDomainDiskQuota { get; set; } public bool UseDomainLimits { get; set; } public bool UseUserLimits { get; set; } public int MegaByteSendLimit { get; set; } public int NumberSendLimit { get; set; } public int DefaultUserQuotaInMB { get; set; } public int DefaultUserMaxMessageSizeMegaByte { get; set; } public int DefaultUserMegaByteSendLimit { get; set; } public int DefaultUserNumberSendLimit { get; set; } #endregion } }
using System; using System.IO; using System.Diagnostics; namespace Tmds.DotnetTrace.Tool { class TraceFolder { private const string IgnorePidExtension = ".ignorepid"; public string Path { get; } public bool Exists => Directory.Exists(Path); public TraceFolder(string path) { Path = path; } public void Clean() { try { Directory.Delete(Path, recursive: true); } catch (DirectoryNotFoundException) { } } public void Create() { if (!Exists) { Directory.CreateDirectory(Path); } } public void AddIgnoreCurrentProcess() { var handle = Process.GetCurrentProcess().Handle; File.WriteAllBytes(System.IO.Path.Combine(Path, $"{handle}{IgnorePidExtension}"), Array.Empty<byte>()); } public void TryAddIgnoreCurrentProcess() { if (Exists) { AddIgnoreCurrentProcess(); } } public int[] IgnorePids { get { if (Exists) { var files = Directory.GetFiles(Path, $"*{IgnorePidExtension}"); var ignorePids = new int[files.Length]; for (int i = 0; i < files.Length; i++) { string fileName = System.IO.Path.GetFileName(files[i]); ignorePids[i] = int.Parse(fileName.Substring(0, fileName.Length - IgnorePidExtension.Length)); } return ignorePids; } else { return Array.Empty<int>(); } } } } }
namespace PinPadLib.Raw { public enum AcknowledgmentResponseInterruption { Acknowledgment, NegativeAcknowledgment, Abort, } }
using Newtonsoft.Json; namespace DancingGoat.Areas.Admin.Models { public class SampleProjectOptions { [JsonProperty("projectName")] public string ProjectName { get; set; } } }
using RetSim.Items; using RetSim.Misc; using RetSim.Units.Player.Static; using System; namespace RetSimWeb { public class AppState { public Equipment Equipment { get; } = new(); public void ChangeItem(int slot, EquippableItem item) { switch (slot) { case Constants.EquipmentSlots.Head: Equipment.Head = item; break; case Constants.EquipmentSlots.Neck: Equipment.Neck = item; break; case Constants.EquipmentSlots.Shoulders: Equipment.Shoulders = item; break; case Constants.EquipmentSlots.Back: Equipment.Back = item; break; case Constants.EquipmentSlots.Chest: Equipment.Chest = item; break; case Constants.EquipmentSlots.Wrists: Equipment.Wrists = item; break; case Constants.EquipmentSlots.Hands: Equipment.Hands = item; break; case Constants.EquipmentSlots.Waist: Equipment.Waist = item; break; case Constants.EquipmentSlots.Legs: Equipment.Legs = item; break; case Constants.EquipmentSlots.Feet: Equipment.Feet = item; break; case Constants.EquipmentSlots.Finger1: Equipment.Finger1 = item; break; case Constants.EquipmentSlots.Finger2: Equipment.Finger2 = item; break; case Constants.EquipmentSlots.Trinket1: Equipment.Trinket1 = item; break; case Constants.EquipmentSlots.Trinket2: Equipment.Trinket2 = item; break; case Constants.EquipmentSlots.Relic: Equipment.Relic = item; break; default: break; } NotifyStateChanged(); } public void GemsUpdated() { NotifyStateChanged(); } public event Action OnChange; private void NotifyStateChanged() => OnChange?.Invoke(); } }
using System.Threading; using System.Threading.Tasks; using AutoFixture.Xunit2; using Reinforce.RestApi; using Xunit; namespace ReinforceTests.RestApiTests { public class ISObjectDescribeTests { [Theory, AutoData] public async Task ISObjectDescribe(string sObjectName) { using var handler = MockHttpMessageHandler.SetupHandler(null); var api = handler.SetupApi<ISObjectDescribe>(); await api.GetAsync(sObjectName, CancellationToken.None, "v44.0"); handler.ConfirmPath($"/services/data/v44.0/sobjects/{sObjectName}/describe"); } } }
using CLRProfiler.Attributes; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using Microsoft.Diagnostics.Runtime; using System.Collections.ObjectModel; using System.Windows.Input; namespace CLRProfiler.ViewModel { [WeaveRaisePropertyChanged] public class ProcessViewViewModel : ViewModelBase { public ObservableCollection<Model.ProcessInfoTab> Tabs { get; set; } public Model.ProcessInfoTab SelectedTab { get; set; } private Model.CLRDataTarget _dataTarget; public ICommand CloseTabCommand { get; private set; } public ProcessViewViewModel(Model.ProcessItem pi) { _dataTarget = new Model.CLRDataTarget(pi); Tabs = new ObservableCollection<Model.ProcessInfoTab>(); AddTab(new Model.ProcessInfoTab() { Name = "Information", Closeable = false, ViewModel = new ViewModel.ProcessInformationViewModel(_dataTarget) }); SelectedTab = Tabs[0]; MessengerInstance.Register<Messages.OpenDetailMessage>(this, HandleOpenDetailMessage); MessengerInstance.Register<Messages.OpenObjectMessage>(this, HandleOpenObjectMessage); MessengerInstance.Register<Messages.OpenListMessage>(this, HandleOpenListMessage); MessengerInstance.Register<Messages.OpenArrayMessage>(this, HandleOpenArrayMessage); CloseTabCommand = new RelayCommand<Model.ProcessInfoTab>(pit => Tabs.Remove(pit)); } public void HandleOpenDetailMessage(Messages.OpenDetailMessage openMessage) { if (openMessage.DetailsRequest == typeof(ClrAppDomain)) { AddTab(new Model.ProcessInfoTab() { Name = "App Domains", Closeable = true, ViewModel = new ViewModel.AppDomainListViewModel(_dataTarget, openMessage.AutoSelectFirst) }); } else if (openMessage.DetailsRequest == typeof(ClrThread)) { AddTab(new Model.ProcessInfoTab() { Name = "Threads", Closeable = true, ViewModel = new ViewModel.ThreadsListViewModel(_dataTarget) }); } } public void HandleOpenObjectMessage(Messages.OpenObjectMessage openMessage) { AddTab(new Model.ProcessInfoTab() { Name = openMessage.Title, Closeable = true, ViewModel = new ViewModel.PropertyViewViewModel(openMessage.Object) }); } public void HandleOpenListMessage(Messages.OpenListMessage openMessage) { AddTab(new Model.ProcessInfoTab() { Name = openMessage.Title, Closeable = true, ViewModel = new ViewModel.ListViewViewModel(openMessage.Object) }); } public void HandleOpenArrayMessage(Messages.OpenArrayMessage openMessage) { AddTab(new Model.ProcessInfoTab() { Name = openMessage.Title, Closeable = true, ViewModel = new ViewModel.ListViewViewModel(openMessage.Object) }); } private void AddTab(Model.ProcessInfoTab tab) { Tabs.Add(tab); SelectedTab = Tabs[Tabs.Count - 1]; } public override void Cleanup() { foreach (var tab in Tabs) { tab.ViewModel.Cleanup(); } _dataTarget.Dispose(); base.Cleanup(); } } }
using System; namespace Gimela.Data.Mapping { public interface ITypeMapFactory { TypeMap CreateTypeMap(Type sourceType, Type destinationType, IMappingOptions mappingOptions, MemberList memberList); } }
using System; using System.Web; using System.Web.Mvc; namespace Sandbox.Delivery.Web.Views.Shared.ViewHelpers { public static class UrlHelperExtensions { public static string AbsoluteUrl(this UrlHelper urlHelper, string relativeContentPath) { var url = new Uri(HttpContext.Current.Request.Url, urlHelper.Content(relativeContentPath)); return url.AbsoluteUri; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading.Tasks; namespace ReactiveTests { class TestTaskScheduler : TaskScheduler { protected override void QueueTask(Task task) { TryExecuteTaskInline(task, false); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { return TryExecuteTask(task); } protected override IEnumerable<Task> GetScheduledTasks() { return null; } } }
using System.Collections.Generic; using System.ComponentModel; using System.Linq; using MiniC.Compiler.Demo.Annotations; using MiniC.Compiler.Demo.TreeItems; namespace MiniC.Compiler.Demo { public class MainWindowViewModel : INotifyPropertyChanged { private string _sourceCode; public string SourceCode { get { return _sourceCode; } set { _sourceCode = value; Recompile(); OnPropertyChanged("SourceCode"); } } private string _compilerErrors; public string CompilerErrors { get { return _compilerErrors; } set { _compilerErrors = value; OnPropertyChanged("CompilerErrors"); } } private IEnumerable<TreeItemBase> _abstractSyntaxTree; public IEnumerable<TreeItemBase> AbstractSyntaxTree { get { return _abstractSyntaxTree; } private set { _abstractSyntaxTree = value; OnPropertyChanged("AbstractSyntaxTree"); } } private IL.ILClass _intermediateLanguage; public IL.ILClass IntermediateLanguage { get { return _intermediateLanguage; } set { _intermediateLanguage = value; OnPropertyChanged("IntermediateLanguage"); } } public MainWindowViewModel() { _sourceCode = @"int fib(int n) { if (n == 0) return 0; if (n == 1) return 1; return fib(n - 1) + fib(n - 2); } int main(void) { return fib(10); }"; Recompile(); } private void Recompile() { AbstractSyntaxTree = null; IntermediateLanguage = null; CompilerErrors = string.Empty; try { var program = Parser.parse(_sourceCode); AbstractSyntaxTree = program.Select(x => new DeclarationItem(x)); var semanticAnalysisResult = SemanticAnalysis.analyze(program); IntermediateLanguage = new ILBuilder(semanticAnalysisResult).BuildClass(program); } catch (CompilerException ex) { CompilerErrors = ex.Message; } } #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } #endregion } }
@{ ViewBag.Title = "Contacts"; } <h2>@ViewBag.Title</h2> <div class="error" style="display: none; color: red;"> <p> It looks like your session has timed out. Click <a href="/users/logout">here</a> to log back in. </p> </div> <p> <button data-bind="click: refresh">Refresh</button> </p> <table> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Email</th> <th></th> </tr> </thead> <tbody data-bind="template: { name: displayMode, foreach: contacts }"> </tbody> </table> <h4>Add a new contact</h4> <form data-bind="with: newContact, submit: addContact"> <p> <label>First Name</label>: <input type="text" data-bind="value: firstName" required/> </p> <p> <label>Last Name</label>: <input type="text" data-bind="value: lastName" required/> </p> <p> <label>Email</label>: <input type="email" data-bind="value: email" required/> </p> <button type="submit" data-bind="enable: isValid()">Add Contact</button> </form> <script type="text/html" id="tmplView"> <tr> <td data-bind="text: firstName"></td> <td data-bind="text: lastName"></td> <td data-bind="text: email"></td> <td> <button type="submit" data-bind="click: $parent.updateContact">Update</button> <button type="submit" data-bind="click: $parent.deleteContact">Delete</button> </td> </tr> </script> <script type="text/html" id="tmplEdit"> <tr> <td><input type="text" data-bind="value: firstName" required/></td> <td><input type="text" data-bind="value: lastName" required/></td> <td data-bind="text: email"></td> <td> <button type="submit" data-bind="click: $parent.saveContact, enable: isValid()">Save</button> <button type="submit" data-bind="click: $parent.cancelEdit">Cancel</button> </td> </tr> </script> @section scripts { <script> (function () { var apiClient = new my.ApiClient({ baseUri: my.baseUri, authToken: my.authToken, onAuthFail: function () { $(".error").show(); } }); var vm = new my.ContactsViewModel(apiClient); ko.applyBindings(vm); vm.refresh(); })(); </script> }
namespace GtkSharp.Hosting { public class GtkHostBuilderOptions { public bool SuppressEnvironmentConfiguration { get; set; } = false; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DSO.Interfaces { public interface IParameter<T> { string ParameterName { get; } string ParameterValue { get; } string ParameterUnit { get; } bool IsReadOnly { get; } T GetParameter { get; } } }
namespace Borda.UnitOfWork { public class EventBase { } }
using System; using System.Collections.Generic; using System.IO; using Lumina.Extensions; // ReSharper disable InconsistentNaming // ReSharper disable UnassignedField.Global #pragma warning disable 649 #pragma warning disable 169 namespace Lumina.Data.Parsing { public static class MdlStructs { [Flags] public enum ModelFlags1 : byte { DustOcclusionEnabled = 0x80, SnowOcclusionEnabled = 0x40, RainOcclusionEnabled = 0x20, Unknown1 = 0x10, LightingReflectionEnabled = 0x08, WavingAnimationDisabled = 0x04, LightShadowDisabled = 0x02, ShadowDisabled = 0x01, } [Flags] public enum ModelFlags2 : byte { Unknown2 = 0x80, BgUvScrollEnabled = 0x40, EnableForceNonResident = 0x20, ExtraLodEnabled = 0x10, ShadowMaskEnabled = 0x08, ForceLodRangeEnabled = 0x04, EdgeGeometryEnabled = 0x02, Unknown3 = 0x01 } public struct ModelFileHeader { public uint Version; public uint StackSize; public uint RuntimeSize; public ushort VertexDeclarationCount; public ushort MaterialCount; public uint[] VertexOffset; public uint[] IndexOffset; public uint[] VertexBufferSize; public uint[] IndexBufferSize; public byte LodCount; public bool EnableIndexBufferStreaming; public bool EnableEdgeGeometry; private byte Padding; public static ModelFileHeader Read( BinaryReader br ) { ModelFileHeader ret = new ModelFileHeader(); ret.Version = br.ReadUInt32(); ret.StackSize = br.ReadUInt32(); ret.RuntimeSize = br.ReadUInt32(); ret.VertexDeclarationCount = br.ReadUInt16(); ret.MaterialCount = br.ReadUInt16(); ret.VertexOffset = br.ReadStructures< UInt32 >( 3 ).ToArray(); ret.IndexOffset = br.ReadStructures< UInt32 >( 3 ).ToArray(); ret.VertexBufferSize = br.ReadStructures< UInt32 >( 3 ).ToArray(); ret.IndexBufferSize = br.ReadStructures< UInt32 >( 3 ).ToArray(); ret.LodCount = br.ReadByte(); ret.EnableIndexBufferStreaming = br.ReadBoolean(); ret.EnableEdgeGeometry = br.ReadBoolean(); ret.Padding = br.ReadByte(); if( ret.EnableEdgeGeometry ) Console.WriteLine( "Win32 file with EdgeGeometry enabled?" ); return ret; } } public struct VertexDeclarationStruct { // There are always 17, but stop when stream = -1 public VertexElement[] VertexElements; public static VertexDeclarationStruct Read( BinaryReader br ) { VertexDeclarationStruct ret = new VertexDeclarationStruct(); var elems = new List< VertexElement >(); // Read the vertex elements that we need var thisElem = br.ReadStructure< VertexElement >(); do { elems.Add( thisElem ); thisElem = br.ReadStructure< VertexElement >(); } while( thisElem.Stream != 255 ); // Skip the number of bytes that we don't need to read // We skip elems.Count * 9 because we had to read the invalid element int toSeek = 17 * 8 - ( elems.Count + 1 ) * 8; br.Seek( br.BaseStream.Position + toSeek ); ret.VertexElements = elems.ToArray(); return ret; } } public unsafe struct VertexElement { public byte Stream; public byte Offset; public byte Type; public byte Usage; public byte UsageIndex; // D3D9 remnant? private fixed byte Padding[3]; } public unsafe struct ModelHeader { // MeshHeader public float Radius; public ushort MeshCount; public ushort AttributeCount; public ushort SubmeshCount; public ushort MaterialCount; public ushort BoneCount; public ushort BoneTableCount; public ushort ShapeCount; public ushort ShapeMeshCount; public ushort ShapeValueCount; public byte LodCount; private ModelFlags1 Flags1; public bool DustOcclusionEnabled => Flags1.HasFlag( ModelFlags1.DustOcclusionEnabled ); public bool SnowOcclusionEnabled => Flags1.HasFlag( ModelFlags1.SnowOcclusionEnabled ); public bool RainOcclusionEnabled => Flags1.HasFlag( ModelFlags1.RainOcclusionEnabled ); public bool Unknown1 => Flags1.HasFlag( ModelFlags1.Unknown1 ); public bool BgLightingReflectionEnabled => Flags1.HasFlag( ModelFlags1.LightingReflectionEnabled ); public bool WavingAnimationDisabled => Flags1.HasFlag( ModelFlags1.WavingAnimationDisabled ); public bool LightShadowDisabled => Flags1.HasFlag( ModelFlags1.LightShadowDisabled ); public bool ShadowDisabled => Flags1.HasFlag( ModelFlags1.ShadowDisabled ); public ushort ElementIdCount; public byte TerrainShadowMeshCount; private ModelFlags2 Flags2; public bool Unknown2 => Flags2.HasFlag( ModelFlags2.Unknown2 ); public bool BgUvScrollEnabled => Flags2.HasFlag( ModelFlags2.BgUvScrollEnabled ); public bool EnableForceNonResident => Flags2.HasFlag( ModelFlags2.EnableForceNonResident ); public bool ExtraLodEnabled => Flags2.HasFlag( ModelFlags2.ExtraLodEnabled ); public bool ShadowMaskEnabled => Flags2.HasFlag( ModelFlags2.ShadowMaskEnabled ); public bool ForceLodRangeEnabled => Flags2.HasFlag( ModelFlags2.ForceLodRangeEnabled ); public bool EdgeGeometryEnabled => Flags2.HasFlag( ModelFlags2.EdgeGeometryEnabled ); public bool Unknown3 => Flags2.HasFlag( ModelFlags2.Unknown3 ); public float ModelClipOutDistance; public float ShadowClipOutDistance; public ushort Unknown4; public ushort TerrainShadowSubmeshCount; private byte Unknown5; public byte BGChangeMaterialIndex; public byte BGCrestChangeMaterialIndex; public byte Unknown6; public ushort Unknown7; public ushort Unknown8; public ushort Unknown9; private fixed byte Padding[6]; } public struct ElementIdStruct { public uint ElementId; public uint ParentBoneName; public float[] Translate; public float[] Rotate; public static ElementIdStruct Read( BinaryReader br ) { ElementIdStruct ret = new ElementIdStruct(); ret.ElementId = br.ReadUInt32(); ret.ParentBoneName = br.ReadUInt32(); ret.Translate = br.ReadStructures< Single >( 3 ).ToArray(); ret.Rotate = br.ReadStructures< Single >( 3 ).ToArray(); return ret; } } public struct LodStruct { public ushort MeshIndex; public ushort MeshCount; public float ModelLodRange; public float TextureLodRange; public ushort WaterMeshIndex; public ushort WaterMeshCount; public ushort ShadowMeshIndex; public ushort ShadowMeshCount; public ushort TerrainShadowMeshIndex; public ushort TerrainShadowMeshCount; public ushort VerticalFogMeshIndex; public ushort VerticalFogMeshCount; // Yell at me if this ever exists on Win32 public uint EdgeGeometrySize; public uint EdgeGeometryDataOffset; public uint PolygonCount; public uint Unknown1; public uint VertexBufferSize; public uint IndexBufferSize; public uint VertexDataOffset; public uint IndexDataOffset; } public struct ExtraLodStruct { public ushort LightShaftMeshIndex; public ushort LightShaftMeshCount; public ushort GlassMeshIndex; public ushort GlassMeshCount; public ushort MaterialChangeMeshIndex; public ushort MaterialChangeMeshCount; public ushort CrestChangeMeshIndex; public ushort CrestChangeMeshCount; public ushort Unknown1; public ushort Unknown2; public ushort Unknown3; public ushort Unknown4; public ushort Unknown5; public ushort Unknown6; public ushort Unknown7; public ushort Unknown8; public ushort Unknown9; public ushort Unknown10; public ushort Unknown11; public ushort Unknown12; } public struct MeshStruct { public ushort VertexCount; private ushort Padding; public uint IndexCount; public ushort MaterialIndex; public ushort SubMeshIndex; public ushort SubMeshCount; public ushort BoneTableIndex; public uint StartIndex; public uint[] VertexBufferOffset; public byte[] VertexBufferStride; public byte VertexStreamCount; public static MeshStruct Read( BinaryReader br ) { MeshStruct ret = new MeshStruct(); ret.VertexCount = br.ReadUInt16(); ret.Padding = br.ReadUInt16(); ret.IndexCount = br.ReadUInt32(); ret.MaterialIndex = br.ReadUInt16(); ret.SubMeshIndex = br.ReadUInt16(); ret.SubMeshCount = br.ReadUInt16(); ret.BoneTableIndex = br.ReadUInt16(); ret.StartIndex = br.ReadUInt32(); ret.VertexBufferOffset = br.ReadStructures< UInt32 >( 3 ).ToArray(); ret.VertexBufferStride = br.ReadBytes( 3 ); ret.VertexStreamCount = br.ReadByte(); return ret; } } public struct SubmeshStruct { public uint IndexOffset; public uint IndexCount; public uint AttributeIndexMask; public ushort BoneStartIndex; public ushort BoneCount; } public struct TerrainShadowMeshStruct { public uint IndexCount; public uint StartIndex; public uint VertexBufferOffset; public ushort VertexCount; public ushort SubMeshIndex; public ushort SubMeshCount; public byte VertexBufferStride; private byte Padding; } public struct TerrainShadowSubmeshStruct { public uint IndexOffset; public uint IndexCount; public ushort Unknown1; public ushort Unknown2; } public struct BoneTableStruct { public ushort[] BoneIndex; public byte BoneCount; private byte[] Padding; public static BoneTableStruct Read( BinaryReader br ) { BoneTableStruct ret = new BoneTableStruct(); ret.BoneIndex = br.ReadStructures< UInt16 >( 64 ).ToArray(); ret.BoneCount = br.ReadByte(); ret.Padding = br.ReadBytes( 3 ); return ret; } } public struct ShapeStruct { public uint StringOffset; public ushort[] ShapeMeshStartIndex; public ushort[] ShapeMeshCount; public static ShapeStruct Read( BinaryReader br ) { ShapeStruct ret = new ShapeStruct(); ret.StringOffset = br.ReadUInt32(); ret.ShapeMeshStartIndex = br.ReadStructures< UInt16 >( 3 ).ToArray(); ret.ShapeMeshCount = br.ReadStructures< UInt16 >( 3 ).ToArray(); return ret; } } public struct ShapeMeshStruct { public uint StartIndex; public uint ShapeValueCount; public uint ShapeValueOffset; } public struct ShapeValueStruct { public ushort Offset; public ushort Value; } public struct BoundingBoxStruct { public float[] Min; public float[] Max; public static BoundingBoxStruct Read( BinaryReader br ) { BoundingBoxStruct ret = new BoundingBoxStruct(); ret.Min = br.ReadStructures< Single >( 4 ).ToArray(); ret.Max = br.ReadStructures< Single >( 4 ).ToArray(); return ret; } } } }
// file: Supervised\Perceptron\PerceptronModel.cs // // summary: Implements the perceptron model class using System; using System.Linq; using numl.Math.LinearAlgebra; using System.Collections.Generic; namespace numl.Supervised.Perceptron { /// <summary>A data Model for the perceptron.</summary> public class PerceptronModel : Model { /// <summary>Gets or sets the w.</summary> /// <value>The w.</value> public Vector W { get; set; } /// <summary>Gets or sets the b.</summary> /// <value>The b.</value> public double B { get; set; } /// <summary>Gets or sets a value indicating whether the normalized.</summary> /// <value>true if normalized, false if not.</value> public bool Normalized { get; set; } /// <summary>Predicts the given o.</summary> /// <param name="y">The Vector to process.</param> /// <returns>An object.</returns> public override double Predict(Vector y) { this.Preprocess(y); if (Normalized) y = y / y.Norm(); return W.Dot(y) + B; } } }
#tool nuget:?package=vswhere ////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); ////////////////////////////////////////////////////////////////////// // DEFINE RUN CONSTANTS ////////////////////////////////////////////////////////////////////// // Directories var PROJECT_DIR = Context.Environment.WorkingDirectory.FullPath + "/"; var VS2015_DIR = PROJECT_DIR + "solutions/vs2015/"; var VS2017_DIR = PROJECT_DIR + "solutions/vs2017/"; var TOOLS_DIR = PROJECT_DIR + "tools/"; var NET35_ADAPTER_PATH = TOOLS_DIR + "NUnit3TestAdapter/build/net35/"; // Version of the Adapter to Use var ADAPTER_VERSION = "3.9.0"; // Get path to VSTest var VSTEST_CONSOLE = VSWhereLatest()?.CombineWithFilePath( "./Common7/IDE/CommonExtensions/Microsoft/TestWindow/vstest.console.exe"); // Specify all the demo projects var DemoProjects = new DemoProject[] { new DemoProject() { Path = VS2015_DIR + "CSharpTestDemo/CSharpTestDemo.csproj", OutputDir = VS2015_DIR + "CSharpTestDemo/bin/" + configuration + "/", ExpectedResult = "Total tests: 107. Passed: 59. Failed: 24. Skipped: 15." }, new DemoProject() { Path = VS2015_DIR + "VbTestDemo/VbTestDemo.vbproj", OutputDir = VS2015_DIR + "VbTestDemo/bin/" + configuration + "/", ExpectedResult = "Total tests: 107. Passed: 59. Failed: 24. Skipped: 15." }, new DemoProject() { Path = VS2015_DIR + "CppTestDemo/CppTestDemo.vcxproj", OutputDir = VS2015_DIR + "CppTestDemo/" + configuration + "/", ExpectedResult = "Total tests: 29. Passed: 14. Failed: 5. Skipped: 8." }, new DemoProject() { Path = VS2017_DIR + "CSharpTestDemo/CSharpTestDemo.csproj", OutputDir = VS2017_DIR + "CSharpTestDemo/bin/" + configuration + "/", ExpectedResult = "Total tests: 107. Passed: 59. Failed: 24. Skipped: 15." }, new DemoProject() { Path = VS2017_DIR + "NUnit3CoreTestDemo/NUnit3CoreTestDemo.csproj", OutputDir = VS2017_DIR + "NUnit3CoreTestDemo/bin/" + configuration + "/", ExpectedResult = "Total tests: 107. Passed: 59. Failed: 24. Skipped: 15." } }; ////////////////////////////////////////////////////////////////////// // CLEAN ////////////////////////////////////////////////////////////////////// Task("Clean") .Does(() => { foreach(var proj in DemoProjects) CleanDirectory(proj.OutputDir); }); ////////////////////////////////////////////////////////////////////// // NUGET RESTORE ////////////////////////////////////////////////////////////////////// Task("NuGetRestore") .Does(() => { foreach (var proj in DemoProjects) { if (proj.SupportsRestore) { Information("Restoring NuGet Packages for " + proj.Name); if (proj.Name.Contains("Core")) DotNetCoreRestore(proj.Path); else { NuGetRestore(proj.Path, new NuGetRestoreSettings { PackagesDirectory = System.IO.Path.GetDirectoryName(proj.Path) + "/packages" }); } } } }); ////////////////////////////////////////////////////////////////////// // BUILD ////////////////////////////////////////////////////////////////////// Task("Build") .IsDependentOn("NugetRestore") .Does(() => { foreach (var proj in DemoProjects) { MSBuild(proj.Path, new MSBuildSettings { Configuration = configuration, EnvironmentVariables = new Dictionary<string, string>(), NodeReuse = false, PlatformTarget = PlatformTarget.MSIL, ToolVersion = proj.ToolVersion }); } }); ////////////////////////////////////////////////////////////////////// // INSTALL ADAPTER ////////////////////////////////////////////////////////////////////// Task("InstallAdapter") .Does(() => { Information("Installing NUnit3TestAdapter"); NuGetInstall("NUnit3TestAdapter", new NuGetInstallSettings() { OutputDirectory = TOOLS_DIR, Version = ADAPTER_VERSION, ExcludeVersion = true }); }); ////////////////////////////////////////////////////////////////////// // RUN DEMOS ////////////////////////////////////////////////////////////////////// Task("RunDemos") .IsDependentOn("Build") .IsDependentOn("InstallAdapter") .Does(() => { foreach(var proj in DemoProjects) { Information(""); Information("********************************************************************************************"); Information("Demo: " + proj.TestAssembly); Information("********************************************************************************************"); Information(""); if (!proj.Name.Contains("Core")) { IEnumerable<string> redirectedStandardOutput; IEnumerable<string> redirectedErrorOutput; int result = StartProcess( VSTEST_CONSOLE, new ProcessSettings() { Arguments = $"{proj.TestAssembly} /TestAdapterPath:{NET35_ADAPTER_PATH}", RedirectStandardOutput = true }, out redirectedStandardOutput, out redirectedErrorOutput); foreach(string line in redirectedStandardOutput) { Information(line); if (line.StartsWith("Total tests")) proj.ActualResult = line; } } else { Information("Skipping .NET Core demo for now"); proj.SkipReason = ".NET Core Project"; } } Information(""); Information("******************************"); Information("* Test Demo Summary Report *"); Information("******************************"); Information(""); foreach (var proj in DemoProjects) { Information(proj.Path); if (proj.SkipReason != null) { Information(" Skipped: " + proj.SkipReason); } else if (proj.ActualResult == proj.ExpectedResult) { Information(" Passed: " + proj.ExpectedResult); } else { Information("Expected: " + proj.ExpectedResult); Information(" But was: " + proj.ActualResult ?? "<null>"); } Information(""); } }); public class DemoProject { public string Path { get; set; } public string OutputDir { get; set; } public string ExpectedResult { get; set; } public string ActualResult { get; set; } public string SkipReason { get; set; } public string Name { get { return System.IO.Path.GetFileNameWithoutExtension(Path); } } public string Type { get { return System.IO.Path.GetExtension(Path); } } public string TestAssembly { get { return OutputDir + Name + ".dll"; } } public bool SupportsRestore { get { return Type != ".vcxproj"; } } public MSBuildToolVersion ToolVersion { get { return Path.Contains("vs2015") ? MSBuildToolVersion.VS2015 : MSBuildToolVersion.VS2017; } } } ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Appveyor") .IsDependentOn("RunDemos"); Task("Default") .IsDependentOn("Build"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace TIBCO.LABS.EFTL { public interface IDataHandler { void OnData (JsonObject message); void Publish(JsonObject message); } }