content
stringlengths
23
1.05M
#region License // Pomona is open source software released under the terms of the LICENSE specified in the // project's repository, or alternatively at http://pomona.io/ #endregion using System.Collections.Generic; using System.Linq; using System.Text; namespace Pomona.Common { public static class NameUtils { public static string CapitalizeFirstLetter(this string word) { if (word.Length == 0) return word; return word.Substring(0, 1).ToUpper() + word.Substring(1); } public static string ConvertCamelCaseToUri(string word) { var parts = GetCamelCaseParts(word).ToArray(); return string.Join("-", parts.Select(x => x.ToLower())); } public static string ConvetUriSegmentToCamelCase(string uriSegment) { var sb = new StringBuilder(); var nextCharToUpper = true; foreach (var c in uriSegment) { if (c == '-') nextCharToUpper = true; else { sb.Append(nextCharToUpper ? char.ToUpperInvariant(c) : c); nextCharToUpper = false; } } return sb.ToString(); } public static IEnumerable<string> GetCamelCaseParts(string camelCaseWord) { var startOfPart = 0; for (var i = 0; i < camelCaseWord.Length; i++) { if (i > 0 && char.IsUpper(camelCaseWord[i])) { yield return camelCaseWord.Substring(startOfPart, i - startOfPart); startOfPart = i; } } if (startOfPart < camelCaseWord.Length) yield return camelCaseWord.Substring(startOfPart); } public static string LowercaseFirstLetter(this string word) { if (word.Length == 0) return word; return word.Substring(0, 1).ToLower() + word.Substring(1); } } }
using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime.Serialization; namespace CS.Mmg { /// <summary> /// What is the type of the guide either guide or template /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum GuideType { /// <summary> /// Guide /// </summary> [EnumMember(Value = "Guide")] Guide, /// <summary> /// Template /// </summary> [EnumMember(Value = "Template")] Template, } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall.Math; using FlatRedBall.Gui; using FlatRedBall; namespace EditorObjects { public static class PositionedObjectRotator { #region Fields private static PositionedObjectList<PositionedObject> mObjectsToIgnore = new PositionedObjectList<PositionedObject>(); #endregion #region Properties public static PositionedObjectList<PositionedObject> ObjectsToIgnore { get { return mObjectsToIgnore; } } #endregion #region Methods public static void MouseRotateObject<T>(T objectToMove, MovementStyle movementStyle) where T : IRotatable { Cursor cursor = GuiManager.Cursor; if (cursor.YVelocity != 0) cursor.StaticPosition = true; float movementAmount = cursor.YVelocity / 8.0f; switch (movementStyle) { case MovementStyle.Group: objectToMove.RotationZ += movementAmount; break; case MovementStyle.Hierarchy: objectToMove.RotationZ += movementAmount; if (objectToMove is PositionedObject && (objectToMove as PositionedObject).Parent != null) { (objectToMove as PositionedObject).SetRelativeFromAbsolute(); } break; case MovementStyle.IgnoreAttachments: objectToMove.RotationZ += movementAmount; if (objectToMove is PositionedObject) { PositionedObject asPositionedObject = objectToMove as PositionedObject; if (asPositionedObject.Parent != null) { asPositionedObject.SetRelativeFromAbsolute(); } foreach (PositionedObject child in asPositionedObject.Children) { //child.Position -= movementVector; if (mObjectsToIgnore.Contains(child) == false) { child.SetRelativeFromAbsolute(); } } } break; } } public static void MouseRotateObjects<T>(PositionedObjectList<T> listToMove, MovementStyle movementStyle) where T : PositionedObject { if (movementStyle == MovementStyle.Group) { PositionedObjectList<T> topParents = listToMove.GetTopParents(); foreach (T positionedObject in topParents) { MouseRotateObject(positionedObject, movementStyle); } } else { foreach (PositionedObject positionedObject in listToMove) { MouseRotateObject(positionedObject, movementStyle); } } } #endregion } }
using System; using System.Collections.Generic; using System.Text; namespace MediumProxy { public class CachePolicy { public int CachedItemsCountHardLimit { get; set; } = 50; public TimeSpan MonitoringThreadInterval { get; set; } = TimeSpan.FromSeconds(12); public TimeSpan CacheLifecycleTimeSpan { get; set; } = TimeSpan.FromSeconds(720); public double CacheLifecycleSpeculativeExecutionRate { get; set; } = 0.8; } }
// <copyright file="TintColor.cs" company="VoxelGame"> // MIT License // For full license see the repository. // </copyright> // <author>pershingthesecond</author> using System; namespace VoxelGame.Core.Visuals { /// <summary> /// A tint that can be applied to blocks. /// </summary> public readonly struct TintColor : IEquatable<TintColor> { private readonly float r; private readonly float g; private readonly float b; public bool IsNeutral { get; } public TintColor(float r, float g, float b) { this.r = r; this.g = g; this.b = b; IsNeutral = false; } public TintColor(float r, float g, float b, bool isNeutral) { this.r = r; this.g = g; this.b = b; IsNeutral = isNeutral; } public static TintColor None => new(r: 1f, g: 1f, b: 1f); public static TintColor Neutral => new(r: 0f, g: 0f, b: 0f, isNeutral: true); #region PREDEFINED COLORS /// <summary> /// Gets a white color: <c>(1|1|1)</c> /// </summary> public static TintColor White => new(r: 1f, g: 1f, b: 1f); /// <summary> /// Gets a red color: <c>(1|0|0)</c> /// </summary> public static TintColor Red => new(r: 1f, g: 0f, b: 0f); /// <summary> /// Gets a green color: <c>(0|1|0)</c> /// </summary> public static TintColor Green => new(r: 0f, g: 1f, b: 0f); /// <summary> /// Gets a blue color: <c>(0|0|1)</c> /// </summary> public static TintColor Blue => new(r: 0f, g: 0f, b: 1f); /// <summary> /// Gets a yellow color: <c>(1|1|0)</c> /// </summary> public static TintColor Yellow => new(r: 1f, g: 1f, b: 0f); /// <summary> /// Gets a cyan color: <c>(0|1|1)</c> /// </summary> public static TintColor Cyan => new(r: 0f, g: 1f, b: 1f); /// <summary> /// Gets a magenta color: <c>(1|0|1)</c> /// </summary> public static TintColor Magenta => new(r: 1f, g: 0f, b: 1f); /// <summary> /// Gets an orange color: <c>(1|0.5|0)</c> /// </summary> public static TintColor Orange => new(r: 1f, g: 0.5f, b: 0f); /// <summary> /// Gets a dark green color: <c>(0|0.5|0)</c> /// </summary> public static TintColor DarkGreen => new(r: 0f, g: 0.5f, b: 0f); /// <summary> /// Gets a lime color: <c>(0.75|1|0)</c> /// </summary> public static TintColor Lime => new(r: 0.75f, g: 1f, b: 0f); /// <summary> /// Gets a gray color: <c>(0.15|0.15|0.15)</c> /// </summary> public static TintColor Gray => new(r: 0.15f, g: 0.15f, b: 0.15f); /// <summary> /// Gets a light color: <c>(0.8|0.8|0.8)</c> /// </summary> public static TintColor LightGray => new(r: 0.8f, g: 0.8f, b: 0.8f); /// <summary> /// Gets an indigo color: <c>(0.5|1|0)</c> /// </summary> public static TintColor Indigo => new(r: 0.5f, g: 1f, b: 0f); /// <summary> /// Gets a maroon color: <c>(0.5|0|0)</c> /// </summary> public static TintColor Maroon => new(r: 0.5f, g: 0f, b: 0f); /// <summary> /// Gets an olive color: <c>(0.5|0.5|0)</c> /// </summary> public static TintColor Olive => new(r: 0.5f, g: 0.5f, b: 0f); /// <summary> /// Gets a brown color: <c>(0.5|0.25|0)</c> /// </summary> public static TintColor Brown => new(r: 0.5f, g: 0.25f, b: 0f); /// <summary> /// Gets a navy color: <c>(0|0|0.5)</c> /// </summary> public static TintColor Navy => new(r: 0f, g: 0f, b: 0.5f); /// <summary> /// Gets an amaranth color: <c>(0.9|0.2|0.3)</c> /// </summary> public static TintColor Amaranth => new(r: 0.9f, g: 0.2f, b: 0.3f); /// <summary> /// Gets an amber color: <c>(1|0.75|0)</c> /// </summary> public static TintColor Amber => new(r: 1f, g: 0.75f, b: 0f); /// <summary> /// Gets an apricot color: <c>(1|0.8|0.65)</c> /// </summary> public static TintColor Apricot => new(r: 1f, g: 0.8f, b: 0.65f); /// <summary> /// Gets an aquamarine color: <c>(0.5|1|0.85)</c> /// </summary> public static TintColor Aquamarine => new(r: 0.5f, g: 1f, b: 0.85f); /// <summary> /// Gets a beige color: <c>(0.9|0.9|0.8)</c> /// </summary> public static TintColor Beige => new(r: 0.9f, g: 0.9f, b: 0.8f); /// <summary> /// Gets a coffee color: <c>(0.45|0.3|0.2)</c> /// </summary> public static TintColor Coffee => new(r: 0.45f, g: 0.3f, b: 0.2f); /// <summary> /// Gets a coral color: <c>(1|0.5|0.3)</c> /// </summary> public static TintColor Coral => new(r: 1f, g: 0.5f, b: 0.3f); /// <summary> /// Gets a crimson color: <c>(0.9|0.15|0.3)</c> /// </summary> public static TintColor Crimson => new(r: 0.9f, g: 0.15f, b: 0.3f); /// <summary> /// Gets an emerald color: <c>(0.3|0.8|0.5)</c> /// </summary> public static TintColor Emerald => new(r: 0.3f, g: 0.8f, b: 0.5f); /// <summary> /// Gets a lilac color: <c>(0.8|0.6|0.8)</c> /// </summary> public static TintColor Lilac => new(r: 0.8f, g: 0.6f, b: 0.8f); /// <summary> /// Gets a mauve color: <c>(0.9|0.7|1)</c> /// </summary> public static TintColor Mauve => new(r: 0.9f, g: 0.7f, b: 1f); /// <summary> /// Gets a periwinkle color: <c>(0.8|0.8|1)</c> /// </summary> public static TintColor Periwinkle => new(r: 0.8f, g: 0.8f, b: 1f); /// <summary> /// Gets a Prussian blue color: <c>(0|0.2|0.32)</c> /// </summary> public static TintColor PrussianBlue => new(r: 0f, g: 0.2f, b: 0.32f); /// <summary> /// Gets a slate gray color: <c>(0.5|0.5|0.6)</c> /// </summary> public static TintColor SlateGray => new(r: 0.5f, g: 0.5f, b: 0.6f); /// <summary> /// Gets a taupe color: <c>(0.3|0.2|0.2)</c> /// </summary> public static TintColor Taupe => new(r: 0.3f, g: 0.2f, b: 0.2f); /// <summary> /// Gets a viridian color: <c>(0.3|0.5|0.45)</c> /// </summary> public static TintColor Viridian => new(r: 0.3f, g: 0.5f, b: 0.45f); #endregion PREDEFINED COLORS public int ToBits => ((int) (r * 7f) << 6) | ((int) (g * 7f) << 3) | (int) (b * 7f); public int GetBits(TintColor neutral) { return IsNeutral ? neutral.ToBits : ToBits; } public override bool Equals(object? obj) { if (obj is TintColor other) return Equals(other); return false; } public bool Equals(TintColor other) { return ToBits == other.ToBits && other.IsNeutral == IsNeutral; } public override int GetHashCode() { return (IsNeutral ? 1 : 0 << 9) | ((int) (r * 7f) << 6) | ((int) (g * 7f) << 3) | (int) (b * 7f); } public static bool operator ==(TintColor left, TintColor right) { return left.Equals(right); } public static bool operator !=(TintColor left, TintColor right) { return !(left == right); } } }
using System; using System.IO; namespace TML.Patcher.CLI.Common { /// <summary> /// Miscellaneous utilities. /// </summary> public static class Utilities { /// <summary> /// Get mod name from file path with prompt. /// </summary> public static string GetModName(string path, string promptText, bool isDirectory = false) { while (true) { Patcher window = Program.Patcher; window.WriteAndClear(promptText, ConsoleColor.Yellow); string? modName = Console.ReadLine(); if (modName == null) { window.WriteAndClear("Specified mod name somehow returned null."); continue; } if (!modName.EndsWith(".tmod")) modName += ".tmod"; if (isDirectory && Directory.Exists(Path.Combine(path, modName))) return modName; if (File.Exists(Path.Combine(path, modName))) return modName; window.WriteAndClear("Specified mod could not be located!"); } } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; using System; public class SampleScript : MonoBehaviour { public WheelDatePicker datePicker; public WheelTimePicker timePicker; public WheelDatePicker datePicker2; public WheelTimePicker timePicker2; public InfiniWheel otherWheel; public Text dateLabel; public Text timeLabel; void Start() { otherWheel.Init(new string[] { "0", "1", "2", "3", "4", "5" }); datePicker.ValueChange += () => { dateLabel.text = datePicker.date.ToLongDateString(); if(datePicker2.date != datePicker.date) datePicker2.date = datePicker.date; }; timePicker.ValueChange += () => { timeLabel.text = timePicker.time.ToString(); if(timePicker2.time != timePicker.time) timePicker2.time = timePicker.time; }; datePicker2.ValueChange += () => { dateLabel.text = datePicker2.date.ToLongDateString(); if(datePicker2.date != datePicker.date) datePicker.date = datePicker2.date; }; timePicker2.ValueChange += () => { timeLabel.text = timePicker2.time.ToString(); if(timePicker2.time != timePicker.time) timePicker.time = timePicker2.time; }; datePicker.date = DateTime.Now; timePicker.time = DateTime.Now.TimeOfDay; } }
using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using SmhiNet.Interfaces; using UnitTestForSmhiNet.FakesRepositories; namespace UnitTestForSmhiNet.ObservationUnitTests { [TestClass] public class ObservationWithNullValues { [TestMethod] public void GetDate_Has_Null() { var weatherObservation = new FakeWeatherObservationRepository(); var data = weatherObservation.GetNulls(); Assert.IsNotNull(data); } [TestMethod] public void GetDate_Has_Null_Check_Model() { var weatherObservation = new FakeWeatherObservationRepository(); var data = weatherObservation.GetNulls(); Assert.IsNotNull(data); } } }
using System.Runtime.InteropServices; using AltV.Net.CApi.ClientEvents; using AltV.Net.Shared.Utils; namespace AltV.Net.Client { public class Discord { private readonly ICore core; public Discord(ICore core) { this.core = core; } public async Task<string> RequestOAuth2Token(string appId) { GCHandle handle; bool resultSuccess = false; string data = null; var semaphore = new SemaphoreSlim(0, 1); unsafe { void ResolveTask(bool success, string token) { resultSuccess = success; data = token; semaphore.Release(); } DiscordOAuth2TokenResultModuleDelegate resolveTask = ResolveTask; handle = GCHandle.Alloc(resolveTask); var appIdPtr = MemoryUtils.StringToHGlobalUtf8(appId); core.Library.Client.Core_Discord_GetOAuth2Token(core.NativePointer, appIdPtr, resolveTask); Marshal.FreeHGlobal(appIdPtr); } await semaphore.WaitAsync(); handle.Free(); semaphore.Dispose(); if (!resultSuccess) throw new Exception("Failed to request OAuth2 token"); return data; } } }
using System; namespace Neutronium.Core.Navigation { /// <summary> /// interface used to build navigation beetween ViewModels /// based on ViewModel type /// </summary> public interface INavigationBuilder { /// <summary> /// Register a file relative path to HTML file corresponding to a viewmodel type /// </summary> /// <param name="type"> /// Type of view model to register /// </param> /// <param name="path"> /// relative file path to HTML file /// </param> /// <param name="id"> /// Optional id information, can be used if same type can resolve to different /// view depending on context /// <returns> /// the navigation builder instance /// </returns> INavigationBuilder Register(Type type, string path, string id = null); /// <summary> /// Register a file relative path to HTML file corresponding to a viewmodel type /// </summary> /// <param name="path"> /// relative file path to HTML file /// </param> /// <param name="id"> /// Optional id information, can be used if same type can resolve to different /// view depending on context /// </param> /// <typeparam name="T"> /// Type of view model to register /// </typeparam> /// <returns> /// the navigation builder instance /// </returns> INavigationBuilder Register<T>(string path, string id=null); /// <summary> /// Register a file absolute path to HTML file corresponding to a viewmodel type /// </summary> /// <param name="path"> /// absolute file path to HTML file /// </param> /// <param name="id"> /// Optional id information, can be used if same type can resolve to different /// view depending on context /// </param> /// <typeparam name="T"> /// Type of view model to register /// </typeparam> /// <returns> /// the navigation builder instance /// </returns> INavigationBuilder RegisterAbsolute<T>(string path, string id = null); /// <summary> /// Register an Uri to HTML resource corresponding to a viewmodel type /// </summary> /// <param name="path"> /// Uri to HTML resource /// </param> /// <param name="id"> /// Optional id information, can be used if same type can resolve to different /// view depending on context /// </param> /// <typeparam name="T"> /// Type of view model to register /// </typeparam> /// <returns> /// the navigation builder instance /// </returns> INavigationBuilder Register<T>(Uri path, string id = null); } }
using System; using System.Collections.Generic; using System.Globalization; using Yoti.Auth.Constants; namespace Yoti.Auth.Sandbox.Profile.Request.Attribute.Derivation { public class SandboxAgeVerificationBuilder { private DateTime _dateOfBirth; private string _derivation; private List<SandboxAnchor> _anchors; public SandboxAgeVerificationBuilder WithDateOfBirth(string value) { bool success = DateTime.TryParseExact( s: value, format: "yyyy-MM-dd", provider: CultureInfo.InvariantCulture, style: DateTimeStyles.None, result: out DateTime parsedDate); if (success) { WithDateOfBirth(parsedDate); return this; } throw new InvalidCastException($"Error when converting string value '{value}' to a DateTime"); } public SandboxAgeVerificationBuilder WithDateOfBirth(DateTime value) { Validation.NotNull(value, nameof(value)); _dateOfBirth = value; return this; } public SandboxAgeVerificationBuilder WithAgeOver(int value) { return WithDerivation($"{UserProfile.AgeOverAttribute}:{value}"); } public SandboxAgeVerificationBuilder WithAgeUnder(int value) { return WithDerivation($"{UserProfile.AgeUnderAttribute}:{value}"); } public SandboxAgeVerificationBuilder WithDerivation(string value) { Validation.NotNullOrEmpty(value, nameof(value)); _derivation = value; return this; } public SandboxAgeVerificationBuilder WithAnchors(List<SandboxAnchor> anchors) { Validation.NotNull(anchors, nameof(anchors)); Validation.CollectionNotEmpty(anchors, nameof(anchors)); _anchors = anchors; return this; } public SandboxAgeVerification Build() { return new SandboxAgeVerification(_dateOfBirth, _derivation, _anchors); } } }
namespace BackEnd.Dtos { public class MachForUpdateDto { public string CurrentJob { get; set; } public string CurrentOp { get; set; } } }
// *********************************************************************** // Assembly : XLabs.Forms.WP8 // Author : XLabs Team // Created : 12-27-2015 // // Last Modified By : XLabs Team // Last Modified On : 01-04-2016 // *********************************************************************** // <copyright file="RadioButtonRenderer.cs" company="XLabs Team"> // Copyright (c) XLabs Team. All rights reserved. // </copyright> // <summary> // This project is licensed under the Apache 2.0 license // https://github.com/XLabs/Xamarin-Forms-Labs/blob/master/LICENSE // // XLabs is a open source project that aims to provide a powerfull and cross // platform set of controls tailored to work with Xamarin Forms. // </summary> // *********************************************************************** // using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using Xamarin.Forms; using Xamarin.Forms.Platform.WinPhone; using XLabs.Forms.Controls; using NativeCheckBox = System.Windows.Controls.RadioButton; [assembly: ExportRenderer(typeof (CustomRadioButton), typeof (RadioButtonRenderer))] namespace XLabs.Forms.Controls { /// <summary> /// Class RadioButtonRenderer. /// </summary> public class RadioButtonRenderer : ViewRenderer<CustomRadioButton, NativeCheckBox> { /// <summary> /// Called when [element changed]. /// </summary> /// <param name="e">The e.</param> protected override void OnElementChanged(ElementChangedEventArgs<CustomRadioButton> e) { base.OnElementChanged(e); if (e.OldElement != null) { e.OldElement.CheckedChanged -= CheckedChanged; } if (Control == null) { var checkBox = new NativeCheckBox(); checkBox.Checked += (s, args) => Element.Checked = true; checkBox.Unchecked += (s, args) => Element.Checked = false; SetNativeControl(checkBox); } UpdateText(); Control.IsChecked = e.NewElement.Checked; UpdateFont(); Control.Foreground = Element.TextColor.ToBrush(); Element.CheckedChanged += CheckedChanged; Element.PropertyChanged += ElementOnPropertyChanged; } private void ElementOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs) { switch (propertyChangedEventArgs.PropertyName) { case "Checked": Control.IsChecked = Element.Checked; break; case "TextColor": Control.Foreground = Element.TextColor.ToBrush(); break; case "FontName": case "FontSize": UpdateFont(); break; case "Text": UpdateText(); break; default: Debug.WriteLine("Property change for {0} has not been implemented.", propertyChangedEventArgs.PropertyName); break; } } private void CheckedChanged(object sender, EventArgs<bool> eventArgs) { Device.BeginInvokeOnMainThread(() => { UpdateText(); Control.IsChecked = eventArgs.Value; }); } /// <summary> /// Updates radio button text content. /// </summary> private void UpdateText() { Control.Content = new TextBlock() { Text = Element.Text, TextWrapping = TextWrapping.Wrap }; } /// <summary> /// Updates the font. /// </summary> private void UpdateFont() { if (!string.IsNullOrEmpty(Element.FontName)) { Control.FontFamily = new FontFamily(Element.FontName); } Control.FontSize = (Element.FontSize > 0) ? (float)Element.FontSize : 12.0f; } } }
using System; using System.Collections.Generic; namespace CarDealership.Models { public class Car { private string _makeModel; private int _price; private int _miles; private string _details; private static List<Car> _instances = new List<Car> {}; // public Car (string makeModel, int price, int miles, string details) // { // _makeModel = makeModel; // _price = price; // _miles = miles; // _details = details; // } public void SetMakeModel(string newMakeModel) { _makeModel = newMakeModel; } public string GetMakeModel() { return _makeModel; } public void SetPrice(int newPrice) { if (newPrice >= 0) { _price = newPrice; } else { Console.WriteLine("The price for this item is not valid."); } } public int GetPrice() { return _price; } public void SetMiles(int newMiles) { _miles = newMiles; } public int GetMiles() { return _miles; } public void SetDetails(string newDetails) { _details = newDetails; } public string GetDetails() { return _details; } public static List<Car> GetAll() { return _instances; } public void Save() { _instances.Add(this); } public static void ClearAll() { _instances.Clear(); } } // public class Program // { // public static void Main() // { // Car porsche = new Car(); // porsche.SetMakeModel("2014 Porsche 911"); // porsche.SetPrice(114991); // porsche.SetMiles(7864); // porsche.SetDetails("This car goes fast!"); // // Car ford = new Car(); // ford.SetMakeModel("2011 Ford F450"); // ford.SetPrice(55995); // ford.SetMiles(14241); // ford.SetDetails("This car is more affordable."); // // Car lexus = new Car(); // lexus.SetMakeModel("2013 Lexus RX 350"); // lexus.SetPrice(44700); // lexus.SetMiles(20000); // lexus.SetDetails("This car is luxurious."); // // Car mercedes = new Car(); // mercedes.SetMakeModel("Merceded Benz CLS550"); // mercedes.SetPrice(39900); // mercedes.SetMiles(37979); // mercedes.SetDetails("This car is not as expensive as the others."); // // List<Car> Cars = new List<Car>() {porsche, ford, lexus, mercedes}; // // // foreach(Car automobile in Cars) // { // Console.WriteLine(automobile.GetMakeModel()); // } // // Console.WriteLine("Enter maximum price: "); // string stringMaxPrice = Console.ReadLine(); // int maxPrice = int.Parse(stringMaxPrice); // // Console.WriteLine("Enter maximum mileage: "); // string stringMaxMileage = Console.ReadLine(); // int maxMileage = int.Parse(stringMaxMileage); // // List<Car> CarsMatchingSearch = new List<Car>(); // // foreach (Car automobile in Cars) // { // if (automobile.GetPrice() < maxPrice && automobile.GetMiles() < maxMileage) // { // CarsMatchingSearch.Add(automobile); // } // } // Console.WriteLine("here are the cars that match your search: "); // foreach (Car automobile in CarsMatchingSearch) // { // Console.WriteLine(automobile.GetMakeModel()); // Console.WriteLine(automobile.GetDetails()); // } // } }
namespace Conic.Wormhole { public struct ReadResult { public ReadResult(int imputLength, string value) { Value = value; ImputLength = imputLength; } public string Value { get; set; } public int ImputLength { get; set; } } }
using System.IO; using System; using Lab_22_Serialization; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; namespace Lab_24_Serialise_Binary { class Program { static void Main(string[] args) { var customer = new Customer(1, "simon", "NRDEH32"); var customer2 = new Customer(2, "Mary", "CB35468"); var customer3 = new Customer(3, "John", "dhrhe45"); var customers = new List<Customer>() { customer, customer2, customer3 }; // formatter : allow us to serialise to binary var formatter = new BinaryFormatter(); // stream to FILE using(var stream = new FileStream("data.bin", FileMode.Create, FileAccess.Write, FileShare.None)) { formatter.Serialize(stream, customers); } // read back var customersBinary = new List<Customer>(); using (var reader = File.OpenRead("data.bin")) { //deserialise customersBinary = formatter.Deserialize(reader) as List<Customer>; } // print customersBinary.ForEach(c => Console.WriteLine($"{c.CustomerID},{c.CustomerName}")); } } }
namespace NLib.Linq.Extensions { using System.Linq.Expressions; /// <summary> /// Defines extensions methods for <see cref="Expression"/>. /// </summary> public static class ExpressionExtensions { /// <summary> /// Gets the name of the parameter. /// </summary> /// <param name="reference">The reference.</param> /// <returns>The name of the parameter.</returns> public static string GetParameterName(this Expression reference) { var lambda = (LambdaExpression)reference; var body = (MemberExpression)lambda.Body; return body.Member.Name; } } }
using NUnit.Framework; using System; using Core.Either; namespace Core.Maybe.Tests; [TestFixture] public class EitherTests { private readonly Either<int, string> _eitherResult; private readonly Either<int, string> _eitherError; private const int EitherLeftValue = 5; private const string EitherRightValue = "Five"; public EitherTests() { _eitherResult = EitherLeftValue.ToResult<int, string>(); _eitherError = EitherRightValue.ToError<int, string>(); } #pragma warning disable 219 [Test] public void NullCheckingTests() { Action<int>? nullActionInt = null; void MockActionInt(int x) { var y = 5; } Action<string>? nullActionString = null; void MockActionString(string x) { var y = 5; } Action? nullAction = null; void MockAction() { var a = 1; } // ReSharper disable ExpressionIsAlwaysNull AssertExtension.Throws<ArgumentNullException>(() => _eitherResult.Match(nullAction!, MockAction)); AssertExtension.Throws<ArgumentNullException>(() => _eitherResult.Match(MockAction, nullAction!)); _eitherResult.Match(MockAction, MockAction); AssertExtension.Throws<ArgumentNullException>(() => _eitherError.Match(nullAction!, MockAction)); AssertExtension.Throws<ArgumentNullException>(() => _eitherError.Match(MockAction, nullAction!)); _eitherError.Match(MockAction, MockAction); AssertExtension.Throws<ArgumentNullException>(() => _eitherError.Match(nullActionInt!, MockActionString)); AssertExtension.Throws<ArgumentNullException>(() => _eitherError.Match(MockActionInt, nullActionString!)); _eitherResult.Match(MockActionInt, MockActionString); } [Test] public void MatchActionTests() { var bool1 = false; var bool2 = false; var testInt = 0; var testString = null as string; void ResetTestValues() { bool1 = false; bool2 = false; testInt = 0; testString = null; } void SetBool1Action() => bool1 = true; void SetBool2Action() => bool2 = true; void SetTestInt(int value) => testInt = value; void SetTestString(string value) => testString = value; _eitherResult.Match(SetBool1Action, SetBool2Action); Assert.IsTrue(bool1); Assert.IsFalse(bool2); ResetTestValues(); _eitherError.Match(SetBool1Action, SetBool2Action); Assert.IsFalse(bool1); Assert.IsTrue(bool2); ResetTestValues(); _eitherResult.Match(SetTestInt, SetTestString); Assert.AreEqual(EitherLeftValue, testInt); Assert.AreEqual(null, testString); ResetTestValues(); _eitherError.Match(SetTestInt, SetTestString); Assert.AreEqual(0, testInt); Assert.AreEqual(EitherRightValue, testString); ResetTestValues(); } [Test] public void MatchFunctionTests() { var testInt = 0; var testString = null as string; void ResetTestValues() { testInt = 0; testString = null; } bool FuncTlt(int x) { testInt = x; return true; } bool FuncTrt(string x) { testString = x; return false; } Assert.IsTrue(_eitherResult.Match(FuncTlt, FuncTrt)); Assert.AreEqual(EitherLeftValue, testInt); Assert.AreEqual(null, testString); ResetTestValues(); Assert.IsFalse(_eitherError.Match(FuncTlt, FuncTrt)); Assert.AreEqual(EitherRightValue, testString); Assert.AreEqual(0, testInt); ResetTestValues(); Assert.IsTrue(_eitherResult.Match(() => true, () => false)); Assert.IsFalse(_eitherError.Match(() => true, () => false)); } [Test] public void OrDefaultFunctionsTests() { Assert.AreEqual(EitherLeftValue, _eitherResult.ResultOrDefault()); Assert.AreEqual(EitherRightValue, _eitherError.ErrorOrDefault()); Assert.AreEqual(0, _eitherError.ResultOrDefault()); Assert.AreEqual(default, _eitherResult.ErrorOrDefault()); Assert.AreEqual(29, _eitherError.ResultOrDefault(29)); Assert.AreEqual("Twenty nine", _eitherResult.ErrorOrDefault("Twenty nine")); } [Test] public void SameTResultTErrorTests() { var eitherResult = Either<string, string>.Result("Left defined"); var eitherError = Either<string, string>.Error("Right defined"); Assert.AreEqual("Left defined", eitherResult.ResultOrDefault()); Assert.AreEqual("Right defined", eitherError.ErrorOrDefault()); Assert.AreEqual(null, eitherError.ResultOrDefault()); Assert.AreEqual(null, eitherResult.ErrorOrDefault()); } [Test] public void ExtensionMethodTests() { var eitherResult = 29.ToResult<int, string>(); var eitherError = "Twenty nine".ToError<int, string>(); Assert.AreEqual(29, eitherResult.ResultOrDefault()); Assert.AreEqual(null, eitherResult.ErrorOrDefault()); Assert.AreEqual("Twenty nine", eitherError.ErrorOrDefault()); Assert.AreEqual(0, eitherError.ResultOrDefault()); } } internal static class AssertExtension { public static void Throws<T>(Action action) where T : Exception { var exceptionThrown = false; try { action.Invoke(); } catch (T) { exceptionThrown = true; } if (!exceptionThrown) { throw new Exception( $"An exception of type {typeof(T)} was expected, but not thrown" ); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine; namespace ShuHai.Unity { public struct LogInfo { public string Log; public string StackTrack; public LogType LotType; } public static class Root { #region Life Cycle public static event Action FixedUpdate; public static event Action Update; public static event Action LateUpdate; public static bool ApplicationQuiting { get; internal set; } internal static void _Initialize() { InitializeLog(); CreateComponents(); } internal static void _Deinitialize() { DestroyComponents(); DeinitializeLog(); } internal static void _FixedUpdate() { FixedUpdate?.Invoke(); } internal static void _Update() { Update?.Invoke(); } internal static void _LateUpdate() { LateUpdate?.Invoke(); LogLateUpdate(); } #if UNITY_EDITOR public static event Action EditorUpdate; internal static void EditorRootUpdate() { EditorUpdate?.Invoke(); } #endif // UNITY_EDITOR public static Coroutine StartCoroutine(IEnumerator routine) { return RootBehaviour.Instance.StartCoroutine(routine); } public static void StopCoroutine(IEnumerator routine) { RootBehaviour.Instance.StopCoroutine(routine); } #endregion Life Cycle #region Components public static IReadOnlyList<MonoBehaviour> Components => _components; public static T GetComponent<T>() where T : MonoBehaviour { return (T)_componentsByType.GetValue(typeof(T)); } public static MonoBehaviour GetComponent(Type type) { Ensure.Argument.NotNull(type, nameof(type)); Ensure.Argument.Is<IRootComponent>(type, nameof(type)); return _componentsByType.GetValue(type); } private static readonly List<MonoBehaviour> _components = new List<MonoBehaviour>(); private static readonly Dictionary<Type, MonoBehaviour> _componentsByType = new Dictionary<Type, MonoBehaviour>(); #region Initialization private static void CreateComponents() { var types = ShuHai.AssemblyCache.Assemblies .SelectMany(a => a.GetTypes()) .Where(IsComponentType) .ToArray(); _components.AddRange(types.Select(CreateComponent)); _components.Sort(CompareComponent); foreach (var component in _components) _componentsByType.Add(component.GetType(), component); } private static MonoBehaviour CreateComponent(Type type) { return (MonoBehaviour)RootBehaviour.Instance.gameObject.AddComponent(type); } private static bool IsComponentType(Type type) { if (!typeof(IRootComponent).IsAssignableFrom(type)) return false; if (!type.IsSubclassOf(typeof(Component))) return false; if (type.IsAbstract) return false; if (type.IsGenericType && type.ContainsGenericParameters) return false; return true; } private static int CompareComponent(MonoBehaviour l, MonoBehaviour r) { Type lt = l.GetType(), rt = r.GetType(); var la = lt.GetCustomAttribute<RootComponentAttribute>(); var ra = rt.GetCustomAttribute<RootComponentAttribute>(); int lp = la?.Priority ?? 0, rp = ra?.Priority ?? 0; int c = -lp.CompareTo(rp); if (c != 0) return c; // Make sure the invocation order keeps the same when priority is the same. return string.Compare(lt.FullName, rt.FullName, StringComparison.Ordinal); } #endregion Initialization private static void DestroyComponents() { } #endregion Components #region Log /// <summary> /// Log information of last unity's <see cref="LogType.Error" />, <see cref="LogType.Assert" /> or /// <see cref="LogType.Exception" /> message. /// </summary> public static LogInfo? LastErrorLog { get; set; } /// <summary> /// Similar to <see cref="LastErrorLog" /> but clear at end of each frame. /// </summary> public static LogInfo? LastErrorLogInFrame { get; set; } private static void InitializeLog() { Application.logMessageReceived += OnLogMessageReceived; } private static void DeinitializeLog() { Application.logMessageReceived -= OnLogMessageReceived; } private static void LogLateUpdate() { LastErrorLogInFrame = null; } private static void OnLogMessageReceived(string log, string stackTrace, LogType type) { switch (type) { case LogType.Exception: case LogType.Error: case LogType.Assert: LastErrorLog = new LogInfo { Log = log, StackTrack = stackTrace, LotType = type }; LastErrorLogInFrame = LastErrorLog; break; case LogType.Warning: break; case LogType.Log: break; default: throw new ArgumentOutOfRangeException(nameof(type), type, null); } } #endregion Log } }
using System.Collections; using UnityEngine; public class NetworkObject : MonoBehaviour { public Renderer _renderer; public Rigidbody rb; public Vector3 positionError = Vector3.zero; public Quaternion rotationError = Quaternion.identity; Vector3 previousPosition; Color defaultColour; public int netId; public int clientAuthority = -1; [SerializeField] float _priority; public float priority { get { return _priority; } set { if (!hasLocalAuthority) return; _priority = value; } } Coroutine resetAuthorityRoutine; public bool isLocal { get { if (Client.getInstance != null) return netId == Client.getInstance.localId; return false; } } public bool hasLocalAuthority { get { if (Client.getInstance != null) return clientAuthority == Client.getInstance.localId; return false; } } public virtual void Init(int netId) { this.netId = netId; previousPosition = transform.position; defaultColour = _renderer.materials[0].color; } void Update() { if (Vector3.Distance(transform.position, previousPosition) > .1f) priority++; } public void setPriority(int priority) { this.priority = priority; } public void Interact(int remoteNetId) { if (this is Player) return; if (remoteNetId == -1) { clientAuthority = -1; _renderer.materials[0].color = defaultColour; } else { if (clientAuthority != -1) return; clientAuthority = remoteNetId; _renderer.materials[0].color = new Color(remoteNetId * 100, remoteNetId * 100, remoteNetId * 100); priority += 100; if (resetAuthorityRoutine != null) StopCoroutine(resetAuthorityRoutine); resetAuthorityRoutine = StartCoroutine(resetClientAuthority()); } } IEnumerator resetClientAuthority() { yield return new WaitForSeconds(5f - (Client.getInstance.getPing() + (1f / 60f))); Interact(-1); } private void OnCollisionEnter(Collision collision) { if (!hasLocalAuthority) return; NetworkObject obj = collision.collider.GetComponent<NetworkObject>(); if (obj == null || obj is Player) return; priority += 50; obj.Interact(this is Player ? netId : clientAuthority); } public void moveWithSmoothing(Vector3 pos, Quaternion rot) { if (moveSmoothlyRoutine != null) StopCoroutine(moveSmoothlyRoutine); if (rotateSmoothlyRoutine != null) StopCoroutine(rotateSmoothlyRoutine); moveSmoothlyRoutine = StartCoroutine(moveSmoothly(pos)); rotateSmoothlyRoutine = StartCoroutine(rotateSmoothly(rot.normalized)); } Coroutine moveSmoothlyRoutine; Coroutine rotateSmoothlyRoutine; IEnumerator moveSmoothly(Vector3 toPos) { while (transform.position != toPos) { transform.position = Vector3.MoveTowards(transform.position, toPos, 5f * Time.deltaTime); yield return null; } } IEnumerator rotateSmoothly(Quaternion toRot) { while (transform.rotation != toRot) { transform.rotation = Quaternion.Lerp(transform.rotation, toRot, 5f * Time.deltaTime); yield return null; } } }
#region File Description //----------------------------------------------------------------------------- // FuzzyLogicGame.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System.Collections.Generic; using Microsoft.Xna.Framework.Input.Touch; #endregion namespace FuzzyLogic { /// <summary> /// This sample shows how an AI can use fuzzy logic to make decisions. It also /// demonstrates a method for organizing different AI behaviors, similar to a state /// machine. /// </summary> public class FuzzyLogicGame : Microsoft.Xna.Framework.Game { #region Constants // This value controls the number of mice that will be in the game. Try // increasing this value! Lots of mice can be fun to watch. const int NumberOfMice = 15; #endregion #region Fields GraphicsDeviceManager graphics; SpriteBatch spriteBatch; SpriteFont font; KeyboardState currentKeyboardState; GamePadState currentGamePadState; KeyboardState lastKeyboardState; GamePadState lastGamePadState; // The game will keep track of a tank and some mice, which are represented // by these two variables. Tank tank; List<Mouse> mice = new List<Mouse>(); // This texture is a 1x1 white dot, just like the name suggests. by stretching // it, we can use it to draw the bar graph that will show the tank's fuzzy // weights. Texture2D onePixelWhite; // Tells us which of the three fuzzy weights the user is currently modifying. // the currently selected weight will have a pulsing red tint. int currentlySelectedWeight; // Definte the dimensions of the fuzzy logic bars Rectangle barDistance = new Rectangle(105, 45, 85, 40); Rectangle barAngle = new Rectangle(105, 125, 85, 40); Rectangle barTime = new Rectangle(105, 205, 85, 40); Rectangle levelBoundary; Vector2 lastTouchPoint; bool isDragging; #endregion #region Initialization public FuzzyLogicGame() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.PreferredBackBufferWidth = 800; graphics.PreferredBackBufferHeight = 480; #if WINDOWS_PHONE // Frame rate is 30 fps by default for Windows Phone. TargetElapsedTime = TimeSpan.FromTicks(333333); graphics.IsFullScreen = true; #endif } protected override void Initialize() { // The level boundary is the viewable area but slightly // smaller to prevent the Entities from drawing off-screen levelBoundary = GraphicsDevice.Viewport.TitleSafeArea; levelBoundary.X += 20; levelBoundary.Y += 20; levelBoundary.Width -= 40; levelBoundary.Height -= 40; // Now that we've created the graphics device, we can use its title // safe area to create the tank. tank = new Tank(levelBoundary, mice); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); tank.LoadContent(Content); onePixelWhite = new Texture2D(GraphicsDevice, 1, 1, false, SurfaceFormat.Color); onePixelWhite.SetData<Color>(new Color[] { Color.White }); font = Content.Load<SpriteFont>("hudFont"); } #endregion #region Update and Draw /// <summary> /// Allows the game to run logic. /// </summary> protected override void Update(GameTime gameTime) { HandleInput(); tank.Update(gameTime); // Update all of the mice int i = 0; while (i < mice.Count) { mice[i].Update(gameTime); // If the tank has caught any of the mice, remove them from the list. // who knows what happen to the mice after they're caught? Whatever it // is, it probably isn't pretty. if (Vector2.Distance(tank.Position, mice[i].Position) < Tank.CaughtDistance) { mice.RemoveAt(i); } else { i++; } } // Now, if the tank has caught any mice, we'll have fewer than our desired // number, and we have to repopulate. while (mice.Count < NumberOfMice) { Mouse mouse = new Mouse(levelBoundary, tank); mouse.LoadContent(Content); mice.Add(mouse); } base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.DarkGray); spriteBatch.Begin(); foreach (Mouse mouse in mice) { mouse.Draw(spriteBatch, gameTime); } tank.Draw(spriteBatch, gameTime); // Draw the three bars showing the tank's internal state. DrawBar(barDistance, tank.FuzzyDistanceWeight, "Distance", gameTime, currentlySelectedWeight == 0); DrawBar(barAngle, tank.FuzzyAngleWeight, "Angle", gameTime, currentlySelectedWeight == 1); DrawBar(barTime, tank.FuzzyTimeWeight, "Time", gameTime, currentlySelectedWeight == 2); spriteBatch.End(); base.Draw(gameTime); } /// <summary> /// DrawBar is a helper function used by Draw. It is used to draw the three /// bars which display the tank's fuzzy weights. /// </summary> private void DrawBar(Rectangle bar, float barWidthNormalized, string label, GameTime gameTime, bool highlighted) { Color tintColor = Color.White; // if the bar is highlighted, we want to make it pulse with a red tint. if (highlighted) { // to do this, we'll first generate a value t, which we'll use to // determine how much tint to have. float t = (float)Math.Sin(10 * gameTime.TotalGameTime.TotalSeconds); // Sin varies from -1 to 1, and we want t to go from 0 to 1, so we'll // scale it now. t = .5f + .5f * t; // finally, we'll calculate our tint color by using Lerp to generate // a color in between Red and White. tintColor = new Color(Vector4.Lerp( Color.Red.ToVector4(), Color.White.ToVector4(), t)); } // calculate how wide the bar should be, and then draw it. bar.Width = (int)(bar.Width * barWidthNormalized); spriteBatch.Draw(onePixelWhite, bar, tintColor); // finally, draw the label to the left of the bar. Vector2 labelSize = font.MeasureString(label); Vector2 labelPosition = new Vector2(bar.X - 5 - labelSize.X, bar.Y); spriteBatch.DrawString(font, label, labelPosition, tintColor); } #endregion #region Handle Input bool IsPressed(Keys key) { return (currentKeyboardState.IsKeyUp(key) && lastKeyboardState.IsKeyDown(key)); } bool IsPressed(Buttons button) { return (currentGamePadState.IsButtonUp(button) && lastGamePadState.IsButtonDown(button)); } /// <summary> /// Handles input for quitting the game. /// </summary> void HandleInput() { currentKeyboardState = Keyboard.GetState(); currentGamePadState = GamePad.GetState(PlayerIndex.One); // Check for exit. if (currentKeyboardState.IsKeyDown(Keys.Escape) || currentGamePadState.Buttons.Back == ButtonState.Pressed) { Exit(); } // Check to see whether the user wants to modify their currently selected // weight. if (IsPressed(Keys.Up) || IsPressed(Buttons.DPadUp) || IsPressed(Buttons.LeftThumbstickUp)) { currentlySelectedWeight--; if (currentlySelectedWeight < 0) currentlySelectedWeight = 2; } if (IsPressed(Keys.Down) || IsPressed(Buttons.DPadDown) || IsPressed(Buttons.LeftThumbstickDown)) { currentlySelectedWeight = (currentlySelectedWeight + 1) % 3; } // Figure out how much the user wants to change the current weight, if at // all. the input thumbsticks vary from -1 to 1, which is too much all at // once, so we'll scale it down a bit. float changeAmount = currentGamePadState.ThumbSticks.Left.X; TouchCollection touchState = TouchPanel.GetState(); // Interpert touch screen presses - get only the first one for this specific case if (touchState.Count > 0) { TouchLocation location = touchState[0]; switch (location.State) { case TouchLocationState.Pressed: // Save first touch coordinates lastTouchPoint = location.Position; isDragging = true; // Create a rectangle for the touch point Rectangle touch = new Rectangle((int)lastTouchPoint.X, (int)lastTouchPoint.Y, 20, 20); // Check for collision with the bars if (barDistance.Intersects(touch)) currentlySelectedWeight = 0; else if (barAngle.Intersects(touch)) currentlySelectedWeight = 1; else if (barTime.Intersects(touch)) currentlySelectedWeight = 2; changeAmount = 0; break; case TouchLocationState.Moved: if (isDragging && currentlySelectedWeight > -1) { float DragDelta = location.Position.X - lastTouchPoint.X; if (DragDelta > 0) changeAmount = 1; else if (DragDelta < 0) changeAmount = -1.0f; } break; case TouchLocationState.Released: // Make coordinates irrelevant if (isDragging) { lastTouchPoint.X = -1; lastTouchPoint.Y = -1; isDragging = false; } break; } } if (currentKeyboardState.IsKeyDown(Keys.Right) || currentGamePadState.IsButtonDown(Buttons.DPadRight)) { changeAmount = 1; } if (currentKeyboardState.IsKeyDown(Keys.Left) || currentGamePadState.IsButtonDown(Buttons.DPadLeft)) { changeAmount = -1f; } changeAmount *= .025f; // Apply to the changeAmount to the currentlySelectedWeight switch (currentlySelectedWeight) { case 0: tank.FuzzyDistanceWeight += changeAmount; break; case 1: tank.FuzzyAngleWeight += changeAmount; break; case 2: tank.FuzzyTimeWeight += changeAmount; break; default: break; } lastKeyboardState = currentKeyboardState; lastGamePadState = currentGamePadState; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Comun_Controles_Merror2 : System.Web.UI.UserControl { internal String _mensajeError; #region Propiedades public String MensajeError { get { return _mensajeError; } set { _mensajeError = value; lblDetalleErrores.Text = value; pnlMasterErrores.Style.Value = (!String.IsNullOrEmpty(this.MensajeError) ? "" : "display:none;"); } } #endregion Propiedades //public string Text //{ // get { return lblMValidacion.Text; } // set // { // if (!string.IsNullOrEmpty(value)) // Visible = true; // else // Visible = false; // lblMValidacion.Text = value; // } //} //public string Value //{ // get { return lblMValidacion.Text; } // set // { // if (!string.IsNullOrEmpty(value)) // Visible = true; // else // Visible = false; // lblMValidacion.Text = value; // } //} //public bool Visible //{ // get { return divMValidacion.Visible; } // set { divMValidacion.Visible = value; } //} //protected void Page_Load(object sender, EventArgs e) //{ // imgMValidacion.ImageUrl = "../App_Themes/Imagenes/atencion_gde_ani.gif"; //} }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace QuestionsApp.Web.DB { public class QuestionsContext : DbContext { public QuestionsContext(DbContextOptions options) : base(options) { } public DbSet<QuestionDB> Questions { get; set; } public DbSet<VoteDB> Votes { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace NDash.Tests { public class ShuffleTests { [Fact] public void should_not_mutate_original_collection() { var ascending = Enumerable.Range(0, 100); ascending.Shuffle(); Assert.Equal(Enumerable.Range(0, 100), ascending); } public class given_default_RNG { [Fact] public void should_shuffle_randomly() { var ascending = Enumerable.Range(0, 100); var shuffled = ascending.Shuffle(); // if this somehow fails, it's an act of god Assert.NotEqual(shuffled, ascending); should_have_same_elements(shuffled, ascending); } } public class given_custom_RNG { class ReverseRandom : Random { readonly int[] order = new[] { 4, 3, 2, 3, 4 }; int curr = 0; public override int Next(int maxValue) => order[curr++]; } [Fact] public void should_shuffle_with_RNG() { var ascending = new[] { 1, 2, 3, 4, 5 }; var descending = ascending.Shuffle(new ReverseRandom()); Assert.Equal(new[] { 5, 4, 3, 2, 1 }, descending.ToArray()); should_have_same_elements(ascending, descending); } } static void should_have_same_elements<T>(IEnumerable<T> expected, IEnumerable<T> actual) { Assert.Empty(expected.DisjunctiveUnion(actual)); } } }
using System.Collections.Generic; using System.Linq; using System.Text; using AttributeRouting.Helpers; namespace AttributeRouting.Framework { /// <summary> /// Strategy ensuring that every route has a unique name. /// Preferably, it generates routes names like "Area_Controller_Action". /// In case of duplicates, it will append the HTTP method (if not a GET route) and/or a unique index to the route. /// So the most heinous possible form is "Area_Controller_Action_Method_Index". /// </summary> public class UniqueRouteNameBuilder : IRouteNameBuilder { private readonly HashSet<string> _registeredRouteNames = new HashSet<string>(); public string Execute(RouteSpecification routeSpec) { var routeNameBuilder = new StringBuilder(); if (routeSpec.AreaName.HasValue()) routeNameBuilder.AppendFormat("{0}_", routeSpec.AreaName); routeNameBuilder.Append(routeSpec.ControllerName); routeNameBuilder.AppendFormat("_{0}", routeSpec.ActionName); // Ensure route names are unique. var routeName = routeNameBuilder.ToString(); var routeNameIsRegistered = _registeredRouteNames.Contains(routeName); if (routeNameIsRegistered) { // Prefix with the first verb (assuming this is the primary verb) if not a GET route. if (routeSpec.HttpMethods.Length > 0 && !routeSpec.HttpMethods.Contains("GET")) { routeNameBuilder.AppendFormat("_{0}", routeSpec.HttpMethods.FirstOrDefault()); } // Suffixing with an index if necessary to disambiguate. routeName = routeNameBuilder.ToString(); var count = _registeredRouteNames.Count(n => n == routeName || n.StartsWith(routeName + "_")); if (count > 0) { routeNameBuilder.AppendFormat("_{0}", count); } } routeName = routeNameBuilder.ToString(); _registeredRouteNames.Add(routeName); return routeName; } } }
using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Platform; using osu.Game.Tests.Visual; namespace osu.Game.Rulesets.Tau.Tests { public class TestSceneOsuGame : OsuTestScene { [BackgroundDependencyLoader] private void load(GameHost host, OsuGameBase gameBase) { OsuGame game = new OsuGame(); game.SetHost(host); Children = new Drawable[] { game }; } } }
using WebGL; namespace THREE { public class Clock { public bool autoStart; public double startTime; public double oldTime; public double elapsedTime; public bool running; public Clock(dynamic autoStart = null) { this.autoStart = autoStart ?? true; startTime = 0; oldTime = 0; elapsedTime = 0; running = false; } public void start() { startTime = JSDate.now(); oldTime = startTime; running = true; } public void stop() { getElapsedTime(); running = false; } public dynamic getElapsedTime() { getDelta(); return elapsedTime; } public dynamic getDelta() { var diff = 0.0; if (autoStart && ! running) { start(); } if (running) { var newTime = JSDate.now(); diff = 0.001 * (newTime - oldTime); oldTime = newTime; elapsedTime += diff; } return diff; } } }
/* * This is a .NET port of the original Java version, which was written by * Gil Tene as described in * https://github.com/HdrHistogram/HdrHistogram * and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ */ using System; using System.Collections; using System.Collections.Generic; namespace Cassandra.AppMetrics.HdrHistogram.Iteration { /// <summary> /// Provide functionality for enumerating over histogram counts. /// </summary> internal abstract class AbstractHistogramEnumerator : IEnumerator<HistogramIterationValue> { private readonly long _savedHistogramTotalRawCount; private readonly HistogramIterationValue _currentIterationValue; private int _nextBucketIndex; private int _nextSubBucketIndex; private long _prevValueIteratedTo; private long _totalCountToPrevIndex; private long _totalValueToCurrentIndex; private bool _freshSubBucket; private long _currentValueAtIndex; private long _nextValueAtIndex; protected HistogramBase SourceHistogram { get; } protected long ArrayTotalCount { get; } protected int CurrentBucketIndex { get; private set; } protected int CurrentSubBucketIndex { get; private set; } protected long TotalCountToCurrentIndex { get; private set; } protected long CountAtThisValue { get; private set; } public HistogramIterationValue Current { get; private set; } protected AbstractHistogramEnumerator(HistogramBase histogram) { SourceHistogram = histogram; _savedHistogramTotalRawCount = histogram.TotalCount; ArrayTotalCount = histogram.TotalCount; CurrentBucketIndex = 0; CurrentSubBucketIndex = 0; _currentValueAtIndex = 0; _nextBucketIndex = 0; _nextSubBucketIndex = 1; _nextValueAtIndex = 1; _prevValueIteratedTo = 0; _totalCountToPrevIndex = 0; TotalCountToCurrentIndex = 0; _totalValueToCurrentIndex = 0; CountAtThisValue = 0; _freshSubBucket = true; _currentIterationValue = new HistogramIterationValue(); } /// <summary> /// Returns <c>true</c> if the iteration has more elements. (In other words, returns true if next would return an element rather than throwing an exception.) /// </summary> /// <returns><c>true</c> if the iterator has more elements.</returns> protected virtual bool HasNext() { if (SourceHistogram.TotalCount != _savedHistogramTotalRawCount) { throw new InvalidOperationException("Source has been modified during enumeration."); } return (TotalCountToCurrentIndex < ArrayTotalCount); } protected abstract void IncrementIterationLevel(); protected abstract bool ReachedIterationLevel(); protected virtual double GetPercentileIteratedTo() { return (100.0 * TotalCountToCurrentIndex) / ArrayTotalCount; } protected virtual long GetValueIteratedTo() { return SourceHistogram.HighestEquivalentValue(_currentValueAtIndex); } /// <summary> /// Returns the next element in the iteration. /// </summary> /// <returns>the <see cref="HistogramIterationValue"/> associated with the next element in the iteration.</returns> private HistogramIterationValue Next() { // Move through the sub buckets and buckets until we hit the next reporting level: while (!ExhaustedSubBuckets()) { CountAtThisValue = SourceHistogram.GetCountAt(CurrentBucketIndex, CurrentSubBucketIndex); if (_freshSubBucket) { // Don't add unless we've incremented since last bucket... TotalCountToCurrentIndex += CountAtThisValue; _totalValueToCurrentIndex += CountAtThisValue * SourceHistogram.MedianEquivalentValue(_currentValueAtIndex); _freshSubBucket = false; } if (ReachedIterationLevel()) { var valueIteratedTo = GetValueIteratedTo(); _currentIterationValue.Set( valueIteratedTo, _prevValueIteratedTo, CountAtThisValue, (TotalCountToCurrentIndex - _totalCountToPrevIndex), TotalCountToCurrentIndex, _totalValueToCurrentIndex, ((100.0 * TotalCountToCurrentIndex) / ArrayTotalCount), GetPercentileIteratedTo()); _prevValueIteratedTo = valueIteratedTo; _totalCountToPrevIndex = TotalCountToCurrentIndex; // move the next iteration level forward: IncrementIterationLevel(); if (SourceHistogram.TotalCount != _savedHistogramTotalRawCount) { throw new InvalidOperationException("Source has been modified during enumeration."); } return _currentIterationValue; } IncrementSubBucket(); } // Should not reach here. But possible for overflowed histograms under certain conditions throw new ArgumentOutOfRangeException(); } private bool ExhaustedSubBuckets() { return (CurrentBucketIndex >= SourceHistogram.BucketCount); } private void IncrementSubBucket() { _freshSubBucket = true; // Take on the next index: CurrentBucketIndex = _nextBucketIndex; CurrentSubBucketIndex = _nextSubBucketIndex; _currentValueAtIndex = _nextValueAtIndex; // Figure out the next next index: _nextSubBucketIndex++; if (_nextSubBucketIndex >= SourceHistogram.SubBucketCount) { _nextSubBucketIndex = SourceHistogram.SubBucketHalfCount; _nextBucketIndex++; } _nextValueAtIndex = SourceHistogram.ValueFromIndex(_nextBucketIndex, _nextSubBucketIndex); } #region IEnumerator explicit implementation object IEnumerator.Current => Current; bool IEnumerator.MoveNext() { var canMove = HasNext(); if (canMove) { Current = Next(); } return canMove; } void IEnumerator.Reset() { //throw new NotImplementedException(); } void IDisposable.Dispose() { //throw new NotImplementedException(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; namespace BadRabbit.Carrot { public class BasicSprite : Basic2DObject { public Texture2DValue Sprite; public BoolValue Additive; public override void Create() { Sprite = new Texture2DValue("Sprite"); Additive = new BoolValue("Additive", AdditiveChange); AddTag(GameObjectTag._2DForward); base.Create(); } private void AdditiveChange() { if (Additive.get()) { RemoveTag(GameObjectTag._2DForward); AddTag(GameObjectTag._2DForward); } else { RemoveTag(GameObjectTag._2DForward); AddTag(GameObjectTag._2DForward); } } public override void Draw2D(GameObjectTag DrawTag) { Render.DrawSprite(Sprite.get(), Position, Size, Rotation); base.Draw2D(DrawTag); } } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; namespace SharpGLTF.Schema2.LoadAndSave { [TestFixture] [Category("Model Load and Save")] public class LoadInvalidTests { [Test] public void LoadInvalidJsonModel() { var path = System.IO.Path.Combine(TestContext.CurrentContext.TestDirectory, "Assets", "Invalid_Json.gltf"); Assert.Throws<Validation.SchemaException>(() => ModelRoot.Load(path)); var validation = ModelRoot.Validate(path); Assert.IsTrue(validation.HasErrors); } } }
using System.Linq; using System.Reflection; using Hermit.Injection; using UnityEditor; namespace Hermit.Common { [CustomEditor(typeof(MonoServiceRegistry), true)] public class MonoServiceProviderEditor : Editor { private void OnEnable() { var serviceProvider = target as MonoServiceRegistry; if (serviceProvider == null) { return; } var sceneContext = serviceProvider.GetComponentInParent<SceneContext>(); if (sceneContext == null) { return; } var type = sceneContext.GetType(); var field = type.GetField("ServiceProviders", BindingFlags.NonPublic | BindingFlags.Instance); if (field == null) { return; } var providers = field.GetValue(sceneContext) as MonoServiceRegistry[]; for (var i = 0; i < providers?.Length; i++) { var provider = providers[i]; if (provider == serviceProvider) { return; } } if (providers == null) { return; } var list = providers.ToList(); list.Add(serviceProvider); field.SetValue(sceneContext, list.ToArray()); } } }
using System; using System.Collections.Generic; using System.Text; namespace CrimsonForthCompiler.Visitors.CrimsonForthVisitor { class LabelGenerator { private int internalCount; private int internalIfCount; private int internalWhileCount; private string internalCurrentFunction; public LabelGenerator() { this.internalCount = 0; this.internalIfCount = 0; this.internalWhileCount = 0; } public void IncrementIfCount() { this.internalIfCount++; } public void IncrementWhileCount() { this.internalWhileCount++; } public string GenerateGenericLabel() { return $"LBL_GENERIC_{this.internalCount++}"; } public string GenerateIfLabel() { return $"LBL_IF_{this.internalIfCount}"; } public string GenerateElseLabel() { return $"LBL_IF_ELSE_{this.internalIfCount}"; } public string GenerateWhileLabel() { return $"LBL_WHILE_{this.internalWhileCount}"; } public string GenerateWhileConditionLabel() { return $"LBL_WHILECOND_{this.internalWhileCount}"; } public string GenerateFunctionLabel(string functionName) { this.internalCurrentFunction = functionName; return $"LBL_FN_{functionName}"; } public string FunctionReturnLabel() { return $"LBL_RETURN_{this.internalCurrentFunction}"; } } }
using System; using System.Linq; class GetLargestNumber { static void Main() { //input int size = 3; int[] numbers = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); //logic int maxNumber = numbers[0]; for (int i = 1; i < size; i++) { maxNumber = GetMax(maxNumber, numbers[i]); } //output Console.WriteLine(maxNumber); } public static int GetMax(int a,int b) { if (a>=b) { return a; } else { return b; } } }
using System.Text.Json.Serialization; namespace Essensoft.Paylink.Alipay.Domain { /// <summary> /// OpenApiProvisioningBundle Data Structure. /// </summary> public class OpenApiProvisioningBundle : AlipayObject { /// <summary> /// 加密后的数据 /// </summary> [JsonPropertyName("data")] public string Data { get; set; } /// <summary> /// 一次性公密钥 /// </summary> [JsonPropertyName("ephemeral_public_key")] public string EphemeralPublicKey { get; set; } /// <summary> /// 公钥hash /// </summary> [JsonPropertyName("public_key_hash")] public string PublicKeyHash { get; set; } /// <summary> /// EC_v2 /// </summary> [JsonPropertyName("version")] public string Version { get; set; } } }
using AutoMapper; using Media.Api.Core.BookAggregate; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Media.Api.Web.Features.Books.Create { public class BookCreateProfile : Profile { public BookCreateProfile() { CreateMap<BookCreateCommand, Book>(); CreateMap<Book, BookCreateResponse>(); } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace DragControlNamespace { public sealed partial class DragControl { //save last control location for 'MoveToLastlocation' function private Point point; private Control control_to_drag; private Form Owner; private bool alowdrag = true; private MyControls mycontrols; public bool AllowDrag { get => this.alowdrag; set { this.alowdrag = value; this.control_to_drag.DragAble(value); } } public string GetStopControlName { get => mycontrols.getStopedControlName; } public delegate void EndEventHandled(object sender, EventArgs e); public event EndEventHandled Finished; public delegate void FreeEventHandled(object sender, EventArgs e); public event FreeEventHandled Free; } }
using Maturnik.WebUI.Shared.Models; using MediatR; namespace Maturnik.Application.SchoolSubjects.Queries.All { public class AllSchoolSubjectsQuery : IRequest<ApiResponse<AllSchoolSubjectsViewModel>> { } }
using System; namespace UltraSFV.Core { /// <summary> /// UpdateStatus: Enumerated type used to indicate the status of updates. /// ApplyUpdate means that an update is available to be applied /// </summary> public enum UpdateStatus { ContinueExecution, ApplyUpdate } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Loksim3D.WetterEdit.Win32Wrapper { public class Win32Exception : Exception { public Win32Exception(string msg, int errorCode) : base(msg) { ErrorCode = errorCode; } public int ErrorCode { get; set; } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using WordCounter.Models; namespace WordCounter.Tests { [TestClass] public class SentenceTests { [TestMethod] public void SentenceConstructor_ConstructsASentence_Sentence() { Sentence newSentence = new Sentence ("Bad Bunny isn't really a bunny."); Assert.AreEqual(typeof(Sentence), newSentence.GetType()); } [TestMethod] public void FormatSentence_ToLowerCase_String() { //Arrange Sentence newSentence = new Sentence ("Bad Bunny isn't really a bunny."); //Act string result = newSentence.FormatSentence(); //Assert Assert.AreEqual(result, "bad bunny isn't really a bunny."); } [TestMethod] public void SplitSentence_SplitOnSpaces_StringArray() { //Arrange Sentence newSentence = new Sentence ("Bad Bunny isn't really a bunny."); string [] target = new string [6] {"bad", "bunny", "isnt", "really", "a", "bunny"}; //Act string [] result = newSentence.SplitSentence(newSentence.InputSentence); //Assert CollectionAssert.AreEqual(result, target); } [TestMethod] public void SplitSentence_RemoveNonAlphas_StringArray() { //Arrange Sentence newSentence = new Sentence ("Bad Bunny isn't really a bunny."); string [] target = new string [6] {"bad", "bunny", "isnt", "really", "a", "bunny"}; //Act string [] result = newSentence.SplitSentence(newSentence.InputSentence); foreach(string word in result) { Console.WriteLine("word"); Console.WriteLine(word); } //Assert CollectionAssert.AreEqual(result, target); } } }
using System; using System.Threading.Tasks; namespace MudBlazor { internal static class TaskExtensions { public static void FireAndForget(this Task task) { task.FireAndForget(ex => Console.WriteLine(ex)); } public static async void FireAndForget(this Task task, Action<Exception> handler) { try { await task; } catch(Exception ex) { handler(ex); } } public static void FireAndForget(this ValueTask task) { task.FireAndForget(ex => Console.WriteLine(ex)); } public static async void FireAndForget(this ValueTask task, Action<Exception> handler) { try { await task; } catch (Exception ex) { handler(ex); } } } }
// Copyright 2021 Bob "Wombat" Hogg // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Globalization; using Godot; /** * Utilities for working with the configuration file */ public static class ConfigFileUtils { // on Windows, this corresponds to ~/AppData/Roaming/Godot/app_userdata/<Game Name>/WhatTheHex.cfg private const string ConfigFileLocation = "user://WhatTheHex.cfg"; private static ConfigFile LoadedConfigFile; /** * Get the currently defined culture (i.e. locale setting). * Defaults to en-US. */ public static CultureInfo GetCulture() { var configFile = GetConfigFile(); string cultureName = (string)configFile.GetValue("settings", "culture", "en-US"); return new CultureInfo(cultureName); // Yes, I prefer en-US over en-CA. Sorry to all the other Canucks reading this. } /** * Loads and returns the current high score. * Note, the score should always be rendered as "Hiscore" or "HISCORE" * (in English, anyhow) for aesthetic consistency. * @return The value of the current high score, or 0 if there isn't one yet. */ public static int LoadHiscore() { var configFile = GetConfigFile(); return (int)configFile.GetValue("progress", "hiscore", 0); } /** * Saves the specified score as the new high score. * @param newHiscore The score to set as the new high score. */ public static void SaveHiscore(int newHiscore) { var configFile = GetConfigFile(); configFile.SetValue("progress", "hiscore", newHiscore); SaveConfigFile(configFile); } /** * Checks if we should play music (during the main game) or not. * Defaults to true in release mode and false in debug mode. * @return true if we should play music; false otherwise. */ public static bool ShouldPlayMusic() { var configFile = GetConfigFile(); var defaultValue = !OS.IsDebugBuild(); return (bool)configFile.GetValue("music", "enabled", defaultValue); } /** * Set if we should or should not play music * @param should True if we should play music and false if we should not */ public static void SetShouldPlayMusic(bool should) { var configFile = GetConfigFile(); configFile.SetValue("music", "enabled", should); SaveConfigFile(configFile); } /** * Set the thickness of the hexagons * @param thickness Edge thickness */ public static void SetEdgeThickness(int thickness) { var configFile = GetConfigFile(); configFile.SetValue("hexagons", "edge_thickness", thickness); SaveConfigFile(configFile); } /** * Retrieve the currently configured edge thickness * @return The currently configured edge thickness */ public static int GetEdgeThickness() { var configFile = GetConfigFile(); return (int)configFile.GetValue("hexagons", "edge_thickness", 6); } private static ConfigFile GetConfigFile() { if(LoadedConfigFile != null) { return LoadedConfigFile; } ConfigFile configFile = new ConfigFile(); configFile.Load(ConfigFileLocation); LoadedConfigFile = configFile; return configFile; } private static void SaveConfigFile(ConfigFile configFile) { Error result = configFile.Save(ConfigFileLocation); if(result != Error.Ok) { GD.Print("Saving config file failed! Error is " + result); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(menuName = "PluggableAI/Actions/Die")] public class DieAction : Action { public override void Enter(StateController controller) { //call die function in state controller controller.Die(); } public override void Act(StateController controller) { //can not act in death } public override void Exit(StateController controller) { //can not exit death } }
using System; using Newtonsoft.Json.Linq; using VkLib.Extensions; namespace VkLib.Core.Photos { public class VkPhoto { public string Id { get; set; } public long Pid { get; set; } public int Aid { get; set; } public long OwnerId { get; set; } public string Src { get; set; } public string SrcBig { get; set; } public string SrcSmall { get; set; } public int Width { get; set; } public int Height { get; set; } public string Text { get; set; } public DateTime Created { get; set; } public static VkPhoto FromJson(JToken json) { if (json == null) throw new ArgumentNullException("json"); var result = new VkPhoto(); result.Id = (string)json["id"]; result.Pid = (long)json["pid"]; result.Aid = (int)json["aid"]; result.OwnerId = (long)json["owner_id"]; result.Src = (string)json["src"]; result.SrcBig = (string)json["src_big"]; result.SrcSmall = (string)json["src_small"]; result.Width = (int)json["width"]; result.Height = (int)json["height"]; result.Text = (string)json["text"]; result.Created = DateTimeExtensions.UnixTimeStampToDateTime((long)json["created"]); return result; } } }
using _31_ValidateAppInput.Models; using System; namespace _31_ValidateAppInput { public static class ManageDataIntegrity { public static void GetExample() { var student = new Student("l", 5); var entityErrors = Validator<Student>.Validate(student); Console.WriteLine($"Errors: {string.Join(", ", entityErrors)}"); Console.ReadLine(); } } }
using Framework.Async; using Framework.Core; namespace Framework.ServiceModel.Async { public interface IAsyncRemoveService<in TIdentityObject> { IAsyncProcessFunc<TIdentityObject, Ignore> RemoveAction { get; } } }
namespace PrtgAPI.Linq.Expressions { internal interface ICountLimitLinqExpression { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; namespace Nest { [JsonObject] public class IndexingStats { [JsonProperty(PropertyName = "index_total")] public long Total { get; set; } [JsonProperty(PropertyName = "index_time")] public string Time { get; set; } [JsonProperty(PropertyName = "index_time_in_millis")] public double TimeInMilliseconds { get; set; } [JsonProperty(PropertyName = "index_current")] public long Current { get; set; } [JsonProperty(PropertyName = "delete_total")] public long DeleteTotal { get; set; } [JsonProperty(PropertyName = "delete_time")] public string DeleteTime { get; set; } [JsonProperty(PropertyName = "delete_time_in_millis")] public double DeleteTimeInMilliseconds { get; set; } [JsonProperty(PropertyName = "delete_current")] public long DeleteCurrent { get; set; } [JsonProperty(PropertyName = "types")] [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public Dictionary<string, TypeStats> Types { get; set; } } }
#region Copyright // <<<<<<< HEAD <<<<<<< HEAD ======= ======= >>>>>>> update form orginal repo // DotNetNuke® - https://www.dnnsoftware.com // Copyright (c) 2002-2018 // by DotNetNuke Corporation // // 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 <<<<<<< HEAD >>>>>>> Merges latest changes from release/9.4.x into development (#3178) ======= >>>>>>> update form orginal repo #region Usings using System; using System.Collections.Generic; using System.Data; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Content.Common; using DotNetNuke.Entities.Modules; using DotNetNuke.Security; #endregion namespace DotNetNuke.Entities.Content.Taxonomy { /// <summary> /// Class of Vocabulary. /// </summary> /// <seealso cref="TermController"/> [Serializable] public class Vocabulary : BaseEntityInfo, IHydratable { private static readonly PortalSecurity Security = PortalSecurity.Instance; private string _Description; private bool _IsSystem; private string _Name; private int _ScopeId; private ScopeType _ScopeType; private int _ScopeTypeId; private List<Term> _Terms; private VocabularyType _Type; private int _VocabularyId; private int _Weight; #region "Constructors" public Vocabulary() : this(Null.NullString, Null.NullString, VocabularyType.Simple) { } public Vocabulary(string name) : this(name, Null.NullString, VocabularyType.Simple) { } public Vocabulary(string name, string description) : this(name, description, VocabularyType.Simple) { } public Vocabulary(VocabularyType type) : this(Null.NullString, Null.NullString, type) { } public Vocabulary(string name, string description, VocabularyType type) { Description = description; Name = name; Type = type; ScopeId = Null.NullInteger; ScopeTypeId = Null.NullInteger; VocabularyId = Null.NullInteger; Weight = 0; } #endregion #region "Public Properties" public string Description { get { return _Description; } set { _Description = Security.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); } } public bool IsHeirarchical { get { return (Type == VocabularyType.Hierarchy); } } public bool IsSystem { get { return _IsSystem; } set { _IsSystem = value; } } public string Name { get { return _Name; } set { if (HtmlUtils.ContainsEntity(value)) value = System.Net.WebUtility.HtmlDecode(value); _Name = Security.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); } } public int ScopeId { get { return _ScopeId; } set { _ScopeId = value; } } public ScopeType ScopeType { get { if (_ScopeType == null) { _ScopeType = this.GetScopeType(_ScopeTypeId); } return _ScopeType; } } public int ScopeTypeId { get { return _ScopeTypeId; } set { _ScopeTypeId = value; } } public List<Term> Terms { get { if (_Terms == null) { _Terms = this.GetTerms(_VocabularyId); } return _Terms; } } public VocabularyType Type { get { return _Type; } set { _Type = value; } } public int VocabularyId { get { return _VocabularyId; } set { _VocabularyId = value; } } public int Weight { get { return _Weight; } set { _Weight = value; } } #endregion #region "IHydratable Implementation" public virtual void Fill(IDataReader dr) { VocabularyId = Null.SetNullInteger(dr["VocabularyID"]); switch (Convert.ToInt16(dr["VocabularyTypeID"])) { case 1: Type = VocabularyType.Simple; break; case 2: Type = VocabularyType.Hierarchy; break; } IsSystem = Null.SetNullBoolean(dr["IsSystem"]); Name = Null.SetNullString(dr["Name"]); Description = Null.SetNullString(dr["Description"]); ScopeId = Null.SetNullInteger(dr["ScopeID"]); ScopeTypeId = Null.SetNullInteger(dr["ScopeTypeID"]); Weight = Null.SetNullInteger(dr["Weight"]); //Fill base class properties FillInternal(dr); } public virtual int KeyID { get { return VocabularyId; } set { VocabularyId = value; } } #endregion } }
using Dalamud.CrystalTower.UI; namespace Dalamud.CrystalTower.Tests.Mocks { public class WindowMock : ImmediateModeWindow { public bool DrawCalled { get; private set; } public override void Draw(ref bool visible) { DrawCalled = true; } public void RequestWindowOpen() { OpenWindow<AltWindowMock>(); } public void RequestWindowClose() { CloseWindow<AltWindowMock>(); } } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; namespace Cassandra.IntegrationTests.SimulacronAPI.PrimeBuilder.Then { public class RowsResult : IRowsResult { private readonly string[] _columnNames; private (string, string)[] _columnNamesToTypes; private readonly List<(string, object)[]> _rows = new List<(string, object)[]>(); public RowsResult(params string[] columnNames) { _columnNames = columnNames; } public RowsResult(params (string, DataType)[] columnNamesToTypes) { _columnNamesToTypes = columnNamesToTypes.Select(tuple => (tuple.Item1, tuple.Item2.AdaptForSimulacron().Value)).ToArray(); } public IRowsResult WithRows(params object[][] columnNamesToValues) { var result = this as IRowsResult; return columnNamesToValues.Aggregate(result, (current, elem) => current.WithRow(elem)); } public IRowsResult WithRow(params object[] values) { if (_columnNamesToTypes == null || _columnNamesToTypes.Length == 0) { _columnNamesToTypes = _columnNames.Zip(values, (name, val) => (name, DataType.GetDataType(val).AdaptForSimulacron().Value)).ToArray(); } if (values.Length != _columnNamesToTypes.Length) { throw new ArgumentException("Number of values don't match columns."); } _rows.Add(_columnNamesToTypes.Zip(values, (val1, val2) => (val1.Item1, DataType.AdaptValueForSimulacronPrime(val2))).ToArray()); return this; } public object RenderRows() { return _rows.Select(row => row.ToDictionary(tuple => tuple.Item1, tuple => tuple.Item2)); } public object RenderColumnTypes() { return _columnNamesToTypes.ToDictionary(tuple => tuple.Item1, tuple => tuple.Item2); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public static class Constants { public enum Worlds { RealWorld, SoulsWorld } public static int experienceToLevelUp = 10; }
using System.Data.Entity.ModelConfiguration; using Twilio.OwlFinance.Domain.Model.Data; namespace Twilio.OwlFinance.Infrastructure.DataAccess.Configuration { public class DocuSignLogModelConfiguration : EntityTypeConfiguration<DocuSignLog> { public DocuSignLogModelConfiguration() { ToTable("DocuSignLog"); HasKey(e => e.ID); Property(e => e.CaseID).IsRequired(); Property(e => e.EnvelopeID).IsRequired(); Property(e => e.DocumentID).IsRequired(); Property(e => e.CreatedDate) .IsRequired() .HasColumnType("datetime2"); } } }
namespace codingfreaks.AspNetIdentity.Data.Core { using System; using System.Diagnostics; using System.Linq; public static class ContextUtil { #region properties public static IdentityEntities Context { get { var context = new IdentityEntities(); context.Configuration.LazyLoadingEnabled = true; context.Database.Log = msg => Trace.TraceInformation(msg); return context; } } #endregion } }
using System; using System.IO; namespace Terraria.IO { public class FileMetadata { public const ulong MAGIC_NUMBER = 27981915666277746uL; public const int SIZE = 20; public FileType Type; public uint Revision; public bool IsFavorite; private FileMetadata() { } public void Write(BinaryWriter writer) { writer.Write(27981915666277746uL | (ulong)this.Type << 56); writer.Write(this.Revision); writer.Write((ulong)((long)(this.IsFavorite.ToInt() & 1))); } public void IncrementAndWrite(BinaryWriter writer) { this.Revision += 1u; this.Write(writer); } public static FileMetadata FromCurrentSettings(FileType type) { return new FileMetadata { Type = type, Revision = 0u, IsFavorite = false }; } public static FileMetadata Read(BinaryReader reader, FileType expectedType) { FileMetadata fileMetadata = new FileMetadata(); fileMetadata.Read(reader); if (fileMetadata.Type != expectedType) { throw new FileFormatException(string.Concat(new string[] { "Expected type \"", Enum.GetName(typeof(FileType), expectedType), "\" but found \"", Enum.GetName(typeof(FileType), fileMetadata.Type), "\"." })); } return fileMetadata; } private void Read(BinaryReader reader) { ulong num = reader.ReadUInt64(); if ((num & 72057594037927935uL) != 27981915666277746uL) { throw new FileFormatException("Expected Re-Logic file format."); } byte b = (byte)(num >> 56 & 255uL); FileType fileType = FileType.None; FileType[] array = (FileType[])Enum.GetValues(typeof(FileType)); for (int i = 0; i < array.Length; i++) { if (array[i] == (FileType)b) { fileType = array[i]; break; } } if (fileType == FileType.None) { throw new FileFormatException("Found invalid file type."); } this.Type = fileType; this.Revision = reader.ReadUInt32(); ulong num2 = reader.ReadUInt64(); this.IsFavorite = ((num2 & 1uL) == 1uL); } } }
using HJM.Chip8.CPU.Changes; using System; using System.Collections.Generic; using System.Text; namespace HJM.Chip8.CPU.Instructions.Chip8 { /// <summary> /// 3xkk - SE Vx, byte /// Skip next instruction if Vx = kk. /// The interpreter compares register Vx to kk, and if they are equal, increments the program counter by 2. /// </summary> public class InsSe3xkk : Instruction { public override string Description { get; set; } = "Skip next instruction if Vx = kk."; public override ushort OpCode { get; set; } = 0x3000; public override CPUStateChange Execute(in CPUState state) { CPUStateChange stateChange = new CPUStateChange(); byte x = (byte)((state.OpCode & 0x0F00) >> 8); byte kk = (byte)(state.OpCode & 0x00FF); stateChange.ProgramCounterChange = new Change<ushort>(); if (state.Registers[x] == kk) { stateChange.SkipNextInstruction(state.ProgramCounter); } else { stateChange.IncrementProgramCounter(state.ProgramCounter); } return stateChange; } } }
namespace application.jsmrg.ytils.com.lib.Engine { public static class JsMrgCommand { public const string Include = "include"; public const string HtmlVar = "htmlvar"; } }
using AutoMapper; using MediatR; using System; using System.Threading; using System.Threading.Tasks; using Template.Application.Contracts.Persistance; using Template.Domain.Entities; namespace Template.Application.Features.Dummies.Commands.CreateDummy { public class CreateDummyCommandHandler : IRequestHandler<CreateDummyCommand, int> { private readonly IDummyRepository _dummyRepository; private readonly IMapper _mapper; public CreateDummyCommandHandler(IDummyRepository dummyRepository, IMapper mapper) { _dummyRepository = dummyRepository ?? throw new ArgumentNullException(nameof(dummyRepository)); _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); } public async Task<int> Handle(CreateDummyCommand request, CancellationToken cancellationToken) { if (request == null) throw new NullReferenceException("Create dummy request is null"); Dummy dummy = _mapper.Map<Dummy>(request); Dummy createdDummy = await _dummyRepository.Create(dummy); return createdDummy.Id; } } }
using System.Text; namespace Toe.Scripting.Defines { public class TreeExpressionItem { public static readonly TreeExpressionItem Never = new TreeExpressionItem(TreeExpressionItemType.Never, 0); public static readonly TreeExpressionItem Always = new TreeExpressionItem(TreeExpressionItemType.Always, 0); private TreeExpressionItem(TreeExpressionItemType type, int index) { Type = type; Index = index; } public TreeExpressionItem(int index, TreeExpressionItem ifDefined, TreeExpressionItem ifNotDefined) { IfDefined = ifDefined; IfNotDefined = ifNotDefined; Type = TreeExpressionItemType.Or; Index = index; } public TreeExpressionItemType Type { get; } public int Index { get; } public TreeExpressionItem IfDefined { get; } public TreeExpressionItem IfNotDefined { get; } public bool? AsBool() { if (Type == TreeExpressionItemType.Always) return true; if (Type == TreeExpressionItemType.Never) return false; return null; } public string ToString(Operands operands) { if (Type == TreeExpressionItemType.Always) return PreprocessorExpression.True; if (Type == TreeExpressionItemType.Never) return PreprocessorExpression.False; var ifDef = IfDefined.AsBool(); var ifNotDef = IfNotDefined.AsBool(); var sb = new StringBuilder(); if (ifDef != false) { if (ifNotDef != false) sb.Append("("); { if (ifDef != true) sb.Append("("); sb.Append("defined("); sb.Append(operands[Index]); sb.Append(")"); if (ifDef != true) { sb.Append(" && "); sb.Append(IfDefined.ToString(operands)); sb.Append(")"); } } if (ifNotDef != false) { sb.Append(" || "); if (ifNotDef != true) sb.Append("("); sb.Append("!defined("); sb.Append(operands[Index]); sb.Append(")"); if (ifNotDef != true) { sb.Append(" && "); sb.Append(IfNotDefined.ToString(operands)); sb.Append(")"); } sb.Append(")"); } } else { if (ifNotDef != true) sb.Append("("); sb.Append("!defined("); sb.Append(operands[Index]); sb.Append(")"); if (ifNotDef != true) { sb.Append(" && "); sb.Append(IfNotDefined.ToString(operands)); sb.Append(")"); } } return sb.ToString(); } } }
/* This source file is a part of the project YAGL. Copyright (c) 2020 Pavel Melnikov. Distributed under the MIT License (http://opensource.org/licenses/MIT). See LICENSE.txt for the full license text. */ // ReSharper disable UnusedType.Global using System.IO; namespace Yagl.Graphics.Imaging.Formats { public partial class Yaf { private static class EndChunk { public const uint Code = 0x21444E45; // END!. private const uint Size = 0; //public static void Read(BinaryReader reader) //{ // // Intentionally left blank. //} public static void Write(BinaryWriter writer) { writer.Write(Code); // Code. writer.Write(Size); // Size. writer.Write(0u); // Reserved. } } } }
using System; using System.IO; using FluentBuild.Utilities; using ICSharpCode.SharpZipLib.Zip; using NUnit.Framework; using Rhino.Mocks; namespace FluentBuild.Runners.Zip { [TestFixture] public class ZipDecompressTests { private ZipDecompress _subject; private IFileSystemHelper _fileSystemHelper; [Test] public void PathShouldBeSet() { _subject.Path("temp"); Assert.That(_subject._pathToArchive, Is.EqualTo("temp")); } [Test] public void ConstructorShouldCreate() { var x = new ZipDecompress(); Assert.That(x._fileSystemHelper, Is.TypeOf<FileSystemHelper>()); } [Test] public void PasswordShouldBeSet() { _subject.UsingPassword("temp"); Assert.That(_subject._password, Is.EqualTo("temp")); } [Test] public void Extract() { string inputFile = "c:\\temp\test.zip"; var memoryStream = new MemoryStream(); var inMemoryStream = new ZipOutputStream(memoryStream); var entry = new ZipEntry("name"); var data = new byte[5] {0, 0, 0, 0, 0}; entry.Size = data.Length; entry.DateTime = DateTime.Now; inMemoryStream.PutNextEntry(entry); inMemoryStream.Write(data, 0, data.Length); inMemoryStream.Finish(); // inMemoryStream.Close(); memoryStream.Seek(0, SeekOrigin.Begin); _fileSystemHelper.Stub(x => x.ReadFile(inputFile)).Return(memoryStream); _fileSystemHelper.Stub(x => x.CreateFile(Arg<string>.Is.Anything)).Return(new MemoryStream()); _subject.Path(inputFile).To("c:\\temp").InternalExecute(); } [SetUp] public void SetUp() { _fileSystemHelper = MockRepository.GenerateStub<IFileSystemHelper>(); _subject = new ZipDecompress(_fileSystemHelper); } } }
using System; using System.Diagnostics; using System.Xml.Serialization; namespace Esha.Genesis.Services.Client { /// <remarks /> [XmlInclude(typeof(AdditionalItemIngredientStatementSettingsDto))] [Serializable] [DebuggerStepThrough] [XmlType(Namespace = "http://ns.esha.com/2013/exlx")] public class IngredientStatementSettingsDto : StatementSettingsBaseDto { private AdditionalItemIngredientStatementSettingsDto[] _additionalItemsField; private IngredientStatementCompositionBehavior _compositionBehaviorField; private GlobalString[] _itemsOverrideTextField; private GlobalString[] _statementNameOverrideField; /// <remarks /> [XmlArray] public AdditionalItemIngredientStatementSettingsDto[] AdditionalItems { get => _additionalItemsField; set => _additionalItemsField = value; } /// <remarks /> [XmlElement] public IngredientStatementCompositionBehavior CompositionBehavior { get => _compositionBehaviorField; set => _compositionBehaviorField = value; } /// <remarks /> [XmlArray] [XmlArrayItem("Value", Namespace = "http://ns.esha.com/2013/types", IsNullable = false)] public GlobalString[] ItemsOverrideText { get => _itemsOverrideTextField; set => _itemsOverrideTextField = value; } /// <remarks /> [XmlArray] [XmlArrayItem("Value", Namespace = "http://ns.esha.com/2013/types", IsNullable = false)] public GlobalString[] StatementNameOverride { get => _statementNameOverrideField; set => _statementNameOverrideField = value; } } }
using System; using System.Collections.Generic; using System.Text; using Serilog; namespace SerilogConsoleApp.StructuredData { /// <summary> /// There are many places where, given the capability, it makes sense to /// serialise a log event property as a structured object. /// DTOs (data transfer objects), messages, events and models are /// often best logged by breaking them down into properties with values. /// For this task, Serilog provides the @ destructuring operator. /// </summary> class PreservingObjectStructureExample { public static void Run() { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Console() .CreateLogger(); var sensorInput = new { Latitude = 25, Longitude = 134, Country = new { FlagColor = "red", Capital = "Washington DC" } }; Log.Information("Processing {SensorInput}", sensorInput); Log.Information("Processing Destructuring {@SensorInput}", sensorInput); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Sismuni.Agente.Servicio.Dto.Tramite; namespace Sismuni.Service.Web.TramiteDocumentario.Response { public class ResponseMessage { public HeadMessage _HeadMessage { get; set; } public List<TramiteDto> _BodyMessage { get; set; } } }
using System; using System.Collections.Generic; namespace Solid.IdentityModel.Tokens.Saml2.Metadata { public class RoleDescriptor : DescriptorBase { public Organization Organization { get; set; } public ICollection<ContactPerson> ContactPerson { get; } = new List<ContactPerson>(); public ICollection<KeyDescriptor> KeyDescriptors { get; } = new List<KeyDescriptor>(); public ICollection<Uri> ProtocolsSupported { get; internal set; } = new List<Uri>(); public Uri ErrorUrl { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Felbook.Models; namespace Felbook.Tests.Fakes { class MockStatusService : AbstractMockService, IStatusService { public MockStatusService(MockModel model) : base(model) { } #region Interface methods public Status FindStatusById(int id) { throw new NotImplementedException(); } public void AddCommentToStatus(User author, Status commentedStatus, string text) { throw new NotImplementedException(); } public void AddStatus(User user, Group group, Event ev, StatusFormModel formModel) { throw new NotImplementedException(); } public void AddStatus(User user, Event ev, StatusFormModel formModel) { throw new NotImplementedException(); } public void AddStatus(User user, Group group, StatusFormModel formModel) { throw new NotImplementedException(); } public void AddStatus(User user, StatusFormModel formModel) { throw new NotImplementedException(); } #endregion } }
using backend.Interfaces.Database; using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Threading.Tasks; namespace backend.Services.Database { public class Compressor : ICompressor { public byte[] Compress(byte[] bytes) { byte[] compressedBytes; using (var output = new MemoryStream()) { using (var uncompressed = new MemoryStream(bytes)) using (var zipStream = new GZipStream(output, CompressionLevel.Optimal)) { uncompressed.CopyTo(zipStream); } compressedBytes = output.ToArray(); } return compressedBytes; } public byte[] Decompress(byte[] bytes) { byte[] decompressedBinary; using (var output = new MemoryStream()) { using (var inputstream = new MemoryStream(bytes)) using (var unzipStream = new GZipStream(inputstream, CompressionMode.Decompress)) { unzipStream.CopyTo(output); } decompressedBinary = output.ToArray(); } return decompressedBinary; } } }
// --------------------------------------------------------------------------------------- // ILGPU // Copyright (c) 2020-2021 ILGPU Project // www.ilgpu.net // // File: LocalMemoryIntrinsic.cs // // This file is part of ILGPU and is distributed under the University of Illinois Open // Source License. See LICENSE.txt for details. // --------------------------------------------------------------------------------------- using ILGPU.IR; using ILGPU.IR.Values; using ILGPU.Resources; using System; namespace ILGPU.Frontend.Intrinsic { enum LocalMemoryIntrinsicKind { Allocate, } /// <summary> /// Marks local-memory methods that are built in. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] sealed class LocalMemoryIntrinsicAttribute : IntrinsicAttribute { public LocalMemoryIntrinsicAttribute(LocalMemoryIntrinsicKind intrinsicKind) { IntrinsicKind = intrinsicKind; } public override IntrinsicType Type => IntrinsicType.LocalMemory; /// <summary> /// Returns the assigned intrinsic kind. /// </summary> public LocalMemoryIntrinsicKind IntrinsicKind { get; } } partial class Intrinsics { /// <summary> /// Handles local operations. /// </summary> /// <param name="context">The current invocation context.</param> /// <param name="attribute">The intrinsic attribute.</param> /// <returns>The resulting value.</returns> private static ValueReference HandleLocalMemoryOperation( ref InvocationContext context, LocalMemoryIntrinsicAttribute attribute) { var builder = context.Builder; var location = context.Location; var genericArgs = context.GetMethodGenericArguments(); var allocationType = builder.CreateType(genericArgs[0]); return attribute.IntrinsicKind == LocalMemoryIntrinsicKind.Allocate ? builder.CreateNewView( location, builder.CreateAlloca( location, allocationType, MemoryAddressSpace.Local, context[0]), context[0]) : throw context.Location.GetNotSupportedException( ErrorMessages.NotSupportedLocalMemoryIntrinsic, attribute.IntrinsicKind.ToString()); } } }
using UnityEngine; namespace Prototypes.TrainSystems { public class BeginDragEvent { public object Item { get; } public object Parent { get; } public BeginDragEvent(object item, object parent) { Item = item; Parent = parent; } } }
using FluentValidation; using SFA.DAS.AdminService.Web.ViewModels.Register; namespace SFA.DAS.AdminService.Web.Validators { public class RegisterViewModelValidator : AbstractValidator<RegisterViewModel> { public RegisterViewModelValidator() { RuleFor(vm => vm.SearchString).NotEmpty().WithMessage("Enter 2 or more characters") .Must(x => x?.Trim().Length > 1) .WithMessage("Enter 2 or more characters"); } } }
using System.Collections.Generic; using Cytoid.Storyboard; using Cytoid.Storyboard.Controllers; namespace Storyboard.Controllers { public class ControllerEaser : StoryboardRendererEaser<ControllerState> { private List<StoryboardRendererEaser<ControllerState>> children; public ControllerEaser(StoryboardRenderer renderer) : base(renderer) { children = new List<StoryboardRendererEaser<ControllerState>> { new StoryboardOpacityEaser(renderer), new UiOpacityEaser(renderer), new ScannerOpacityEaser(renderer), new BackgroundDimEaser(renderer), new NoteOpacityEaser(renderer), new ScannerColorEaser(renderer), new ScannerSmoothingEaser(renderer), new ScannerPositionEaser(renderer), new GlobalNoteRingColorEaser(renderer), new GlobalNoteFillColorEaser(renderer), new RadialBlurEaser(renderer), new ColorAdjustmentEaser(renderer), new GrayScaleEaser(renderer), new NoiseEaser(renderer), new ColorFilterEaser(renderer), new SepiaEaser(renderer), new DreamEaser(renderer), new FisheyeEaser(renderer), new ShockwaveEaser(renderer), new FocusEaser(renderer), new GlitchEaser(renderer), new ArtifactEaser(renderer), new ArcadeEaser(renderer), new ChromaticalEaser(renderer), new TapeEaser(renderer), new BloomEaser(renderer), new CameraEaser(renderer) }; } public override void OnUpdate() { children.ForEach(it => { it.From = From; it.To = To; it.Ease = Ease; it.Time = Time; it.OnUpdate(); }); } } }
using NUnit.Framework; using System; using UniGLTF; using UnityEngine; using VRM; public class VRMTest { static GameObject CreateSimpelScene() { var root = new GameObject("gltfRoot").transform; var scene = new GameObject("scene0").transform; scene.SetParent(root, false); scene.localPosition = new Vector3(1, 2, 3); return root.gameObject; } void AssertAreEqual(Transform go, Transform other) { var lt = go.Traverse().GetEnumerator(); var rt = go.Traverse().GetEnumerator(); while (lt.MoveNext()) { if (!rt.MoveNext()) { throw new Exception("rt shorter"); } MonoBehaviourComparator. AssertAreEquals(lt.Current.gameObject, rt.Current.gameObject); VRMMonoBehaviourComparator. AssertAreEquals(lt.Current.gameObject, rt.Current.gameObject); } if (rt.MoveNext()) { throw new Exception("rt longer"); } } [Test] public void VRMSimpleSceneTest() { var go = CreateSimpelScene(); var context = new VRMImporterContext(null); try { // export var gltf = VRMExporter.Export(go); using (var exporter = new gltfExporter(gltf)) { exporter.Prepare(go); exporter.Export(); // import context.Json = gltf.ToJson(); Debug.LogFormat("{0}", context.Json); gltfImporter.Import<glTF>(context); AssertAreEqual(go.transform, context.Root.transform); } } finally { //Debug.LogFormat("Destory, {0}", go.name); GameObject.DestroyImmediate(go); context.Destroy(true); } } }
using CloudBackup.Database.Enum; using System; using System.Collections.Generic; using System.Text; namespace CloudBackup.Database.Entity { public class Device { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public string CpuId { get; set; } public string DiskSeriNo { get; set; } public string MacAddress { get; set; } public string ApiAccessKey { get; set; } public string ApiSecretKey { get; set; } public string BakcupJobId { get; set; } public string FileListJobId { get; set; } public string CheckOnlineJobId { get; set; } public int OrganizationId { get; set; } public DateTime? CreatedDate { get; set; } public ActiveStatus ActiveStatus { get; set; } public DeviceStatus DeviceStatus { get; set; } } }
using HomeSeerAPI; using Hspi.Devices; using NullGuard; using System.Collections.Generic; namespace Hspi.DeviceData { [NullGuard(ValidationFlags.Arguments | ValidationFlags.NonPublic)] internal class MediaStateFeedbackDeviceData : DoubleFeedbackDeviceDataBase { public MediaStateFeedbackDeviceData(int? refId) : base(refId) { } public override IList<VSVGPairs.VSPair> StatusPairs { get { var pairs = new List<VSVGPairs.VSPair> { new VSVGPairs.VSPair(HomeSeerAPI.ePairStatusControl.Status) { PairType = VSVGPairs.VSVGPairType.SingleValue, Value = (int)MediaStateDeviceFeedback.State.Stopped, Status = "Stopped", }, new VSVGPairs.VSPair(HomeSeerAPI.ePairStatusControl.Status) { PairType = VSVGPairs.VSVGPairType.SingleValue, Value = (int)MediaStateDeviceFeedback.State.Playing, Status = "Playing", }, new VSVGPairs.VSPair(HomeSeerAPI.ePairStatusControl.Status) { PairType = VSVGPairs.VSVGPairType.SingleValue, Value = (int)MediaStateDeviceFeedback.State.Paused, Status = "Paused", }, new VSVGPairs.VSPair(HomeSeerAPI.ePairStatusControl.Status) { PairType = VSVGPairs.VSVGPairType.SingleValue, Value = (int)MediaStateDeviceFeedback.State.Unknown, Status = "Unknown", } }; return pairs; } } public override bool StatusDevice => true; }; }
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AlibabaCloud.SDK.Dataworks_public20200518.Models { public class ListCalcEnginesResponse : TeaModel { [NameInMap("HttpStatusCode")] [Validation(Required=true)] public int? HttpStatusCode { get; set; } [NameInMap("Success")] [Validation(Required=true)] public bool? Success { get; set; } [NameInMap("RequestId")] [Validation(Required=true)] public string RequestId { get; set; } [NameInMap("Data")] [Validation(Required=true)] public ListCalcEnginesResponseData Data { get; set; } public class ListCalcEnginesResponseData : TeaModel { [NameInMap("PageNumber")] [Validation(Required=true)] public int? PageNumber { get; set; } [NameInMap("PageSize")] [Validation(Required=true)] public int? PageSize { get; set; } [NameInMap("TotalCount")] [Validation(Required=true)] public int? TotalCount { get; set; } [NameInMap("CalcEngines")] [Validation(Required=true)] public List<ListCalcEnginesResponseDataCalcEngines> CalcEngines { get; set; } public class ListCalcEnginesResponseDataCalcEngines : TeaModel { public string CalcEngineType { get; set; } public string GmtCreate { get; set; } public string DwRegion { get; set; } public bool? IsDefault { get; set; } public int? BindingProjectId { get; set; } public string EnvType { get; set; } public long TenantId { get; set; } public string Name { get; set; } public string BindingProjectName { get; set; } public string Region { get; set; } public int? EngineId { get; set; } public Dictionary<string, string> EngineInfo { get; set; } public string TaskAuthType { get; set; } } }; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using DNMOFT.RNC.Context; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace DNMOFT.RNC.Controllers { [Route("api/[controller]")] public class Contribuyente : ControllerBase { private readonly DNMOFT.RNC.Context.AppContext _context; public Contribuyente(DNMOFT.RNC.Context.AppContext context) { _context = context; } // GET: api/<controller> [HttpGet] public mContribuyente GetByRnc(string rnc) { var result = _context.mContribuyentes.Where(x => x.RNC == rnc).FirstOrDefault(); return result; } } }
using IntegrationTool.SDK; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IntegrationTool.Module.WriteToEventLog { public enum EventLogLevel { Information, Warning, Error } public class WriteToEventLogConfiguration : StepConfiguration { public string Message { get; set; } public EventLogLevel Level { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using lfeigl.cleanr.Library; namespace lfeigl.cleanr.CLI { public static class Utils { public static void PrintBaseObject(Base baseObject) { List<string> print = new List<string>(); print.Add($"=== {baseObject.ID} ==="); foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(baseObject)) { string key = descriptor.Name; object value = descriptor.GetValue(baseObject); print.Add($"{key}: {value}"); } print.Add(""); Console.WriteLine(string.Join("\n", print)); } public static void PrintListOfBaseObjects(List<Base> list) { foreach (Base baseObject in list) { PrintBaseObject(baseObject); } } } }
using System; using System.Globalization; using Oddin.OddsFeedSdk.API.Entities.Abstractions; namespace Oddin.OddsFeedSdk.API.Entities { internal class TvChannel : ITvChannel { public string Name { get; } public string StreamUrl { get; } public DateTime? StartTime { get; } public CultureInfo Language { get; } public TvChannel(string name, DateTime? startTime, string streamUrl, CultureInfo cultureInfo) { Name = name; StreamUrl = streamUrl; StartTime = startTime; Language = cultureInfo; } } }
namespace Terraria.ID { public static class BuffID { public const int ObsidianSkin = 1; public const int Regeneration = 2; public const int Swiftness = 3; public const int Gills = 4; public const int Ironskin = 5; public const int ManaRegeneration = 6; public const int MagicPower = 7; public const int Featherfall = 8; public const int Spelunker = 9; public const int Invisibility = 10; public const int Shine = 11; public const int NightOwl = 12; public const int Battle = 13; public const int Thorns = 14; public const int WaterWalking = 15; public const int Archery = 16; public const int Hunter = 17; public const int Gravitation = 18; public const int ShadowOrb = 19; public const int Poisoned = 20; public const int PotionSickness = 21; public const int Darkness = 22; public const int Cursed = 23; public const int OnFire = 24; public const int Tipsy = 25; public const int WellFed = 26; public const int FairyBlue = 27; public const int Werewolf = 28; public const int Clairvoyance = 29; public const int Bleeding = 30; public const int Confused = 31; public const int Slow = 32; public const int Weak = 33; public const int Merfolk = 34; public const int Silenced = 35; public const int BrokenArmor = 36; public const int Horrified = 37; public const int TheTongue = 38; public const int CursedInferno = 39; public const int PetBunny = 40; public const int BabyPenguin = 41; public const int PetTurtle = 42; public const int PaladinsShield = 43; public const int Frostburn = 44; public const int BabyEater = 45; public const int Chilled = 46; public const int Frozen = 47; public const int Honey = 48; public const int Pygmies = 49; public const int BabySkeletronHead = 50; public const int BabyHornet = 51; public const int TikiSpirit = 52; public const int PetLizard = 53; public const int PetParrot = 54; public const int BabyTruffle = 55; public const int PetSapling = 56; public const int Wisp = 57; public const int RapidHealing = 58; public const int ShadowDodge = 59; public const int LeafCrystal = 60; public const int BabyDinosaur = 61; public const int IceBarrier = 62; public const int Panic = 63; public const int BabySlime = 64; public const int EyeballSpring = 65; public const int BabySnowman = 66; public const int Burning = 67; public const int Suffocation = 68; public const int Ichor = 69; public const int Venom = 70; public const int WeaponImbueVenom = 71; public const int Midas = 72; public const int WeaponImbueCursedFlames = 73; public const int WeaponImbueFire = 74; public const int WeaponImbueGold = 75; public const int WeaponImbueIchor = 76; public const int WeaponImbueNanites = 77; public const int WeaponImbueConfetti = 78; public const int WeaponImbuePoison = 79; public const int Blackout = 80; public const int PetSpider = 81; public const int Squashling = 82; public const int Ravens = 83; public const int BlackCat = 84; public const int CursedSapling = 85; public const int WaterCandle = 86; public const int Campfire = 87; public const int ChaosState = 88; public const int HeartLamp = 89; public const int Rudolph = 90; public const int Puppy = 91; public const int BabyGrinch = 92; public const int AmmoBox = 93; public const int ManaSickness = 94; public const int BeetleEndurance1 = 95; public const int BeetleEndurance2 = 96; public const int BeetleEndurance3 = 97; public const int BeetleMight1 = 98; public const int BeetleMight2 = 99; public const int BeetleMight3 = 100; public const int FairyRed = 101; public const int FairyGreen = 102; public const int Wet = 103; public const int Mining = 104; public const int Heartreach = 105; public const int Calm = 106; public const int Builder = 107; public const int Titan = 108; public const int Flipper = 109; public const int Summoning = 110; public const int Dangersense = 111; public const int AmmoReservation = 112; public const int Lifeforce = 113; public const int Endurance = 114; public const int Rage = 115; public const int Inferno = 116; public const int Wrath = 117; public const int MinecartLeft = 118; public const int Lovestruck = 119; public const int Stinky = 120; public const int Fishing = 121; public const int Sonar = 122; public const int Crate = 123; public const int Warmth = 124; public const int HornetMinion = 125; public const int ImpMinion = 126; public const int BunnyMount = 128; public const int PigronMount = 129; public const int SlimeMount = 130; public const int TurtleMount = 131; public const int BeeMount = 132; public const int SpiderMinion = 133; public const int TwinEyesMinion = 134; public const int PirateMinion = 135; public const int MiniMinotaur = 136; public const int Slimed = 137; public const int MinecartRight = 138; public const int SharknadoMinion = 139; public const int UFOMinion = 140; public const int UFOMount = 141; public const int DrillMount = 142; public const int ScutlixMount = 143; public const int Electrified = 144; public const int MoonLeech = 145; public const int Sunflower = 146; public const int MonsterBanner = 147; public const int Rabies = 148; public const int Webbed = 149; public const int Bewitched = 150; public const int SoulDrain = 151; public const int MagicLantern = 152; public const int ShadowFlame = 153; public const int BabyFaceMonster = 154; public const int CrimsonHeart = 155; public const int Stoned = 156; public const int PeaceCandle = 157; public const int StarInBottle = 158; public const int Sharpened = 159; public const int Dazed = 160; public const int DeadlySphere = 161; public const int UnicornMount = 162; public const int Obstructed = 163; public const int VortexDebuff = 164; public const int DryadsWard = 165; public const int MinecartRightMech = 166; public const int MinecartLeftMech = 167; public const int CuteFishronMount = 168; public const int BoneJavelin = 169; public const int SolarShield1 = 170; public const int SolarShield2 = 171; public const int SolarShield3 = 172; public const int NebulaUpLife1 = 173; public const int NebulaUpLife2 = 174; public const int NebulaUpLife3 = 175; public const int NebulaUpMana1 = 176; public const int NebulaUpMana2 = 177; public const int NebulaUpMana3 = 178; public const int NebulaUpDmg1 = 179; public const int NebulaUpDmg2 = 180; public const int NebulaUpDmg3 = 181; public const int StardustMinion = 182; public const int StardustMinionBleed = 183; public const int MinecartLeftWood = 184; public const int MinecartRightWood = 185; public const int DryadsWardDebuff = 186; public const int StardustGuardianMinion = 187; public const int StardustDragonMinion = 188; public const int Daybreak = 189; public const int SuspiciousTentacle = 190; public const int CompanionCube = 191; public const int SugarRush = 192; public const int BasiliskMount = 193; public const int WindPushed = 194; public const int Count = 195; } }
using System.Collections.Generic; using System.Linq; using EtlGate.Extensions; using FluentAssert; using JetBrains.Annotations; using NUnit.Framework; namespace EtlGate.Tests.Extensions { [UsedImplicitly] public class IEnumerableTExtensionsTests { [UsedImplicitly] public class When_asked_to_convert_a_List_to_a_LinkedList { [TestFixture] public class Given_an_empty_list { [Test] public void Should_return_and_empty_result() { var input = new int[] { }; var result = input.ToLinkedList().ToList(); result.Count.ShouldBeEqualTo(0); } } [TestFixture] public class Given_list_containing_1_item { [Test] public void Should_return_1_item() { var input = new[] { 1 }; var result = input.ToLinkedList().ToList(); result.Count.ShouldBeEqualTo(1); } } [TestFixture] public class Given_list_containing_2_items { private IList<int> _input; private List<LinkedListNode<int>> _result; #pragma warning disable 618 [TestFixtureSetUp] #pragma warning restore 618 public void Before_first_test() { _input = new[] { 1, 2 }; _result = _input.ToLinkedList().ToList(); } [Test] public void Should_link_first_result_Next_to_second_result() { var linkedListNode = _result.First().Next; linkedListNode.ShouldNotBeNull(); // ReSharper disable once PossibleNullReferenceException linkedListNode.Value.ShouldBeEqualTo(_input.Last()); } [Test] public void Should_link_second_result_Previous_to_first_result() { var linkedListNode = _result.Last().Previous; linkedListNode.ShouldNotBeNull(); // ReSharper disable once PossibleNullReferenceException linkedListNode.Value.ShouldBeEqualTo(_input.First()); } [Test] public void Should_return_2_items() { _result.Count.ShouldBeEqualTo(2); } [Test] public void Should_return_the_first_input_first() { _result.First().Value.ShouldBeEqualTo(_input.First()); } [Test] public void Should_return_the_second_input_second() { _result.Last().Value.ShouldBeEqualTo(_input.Last()); } } } } }
using SadConsole; using System; namespace Highbyte.DotNet6502.SadConsoleHost { public class SadConsoleEmulatorInput { private readonly Memory _emulatorMem; private readonly EmulatorInputConfig _emulatorInputConfig; public SadConsoleEmulatorInput( Memory emulatorMem, EmulatorInputConfig emulatorInputConfig) { _emulatorMem = emulatorMem; _emulatorInputConfig = emulatorInputConfig; } public void CaptureInput() { CaptureKeyboard(); CaptureRandomNumber(); } private void CaptureKeyboard() { var keyboard = GameHost.Instance.Keyboard; if(keyboard.KeysPressed.Count > 0) _emulatorMem[_emulatorInputConfig.KeyPressedAddress] = (byte)keyboard.KeysPressed[0].Character; else _emulatorMem[_emulatorInputConfig.KeyPressedAddress] = 0x00; if(keyboard.KeysDown.Count > 0) _emulatorMem[_emulatorInputConfig.KeyDownAddress] = (byte)keyboard.KeysDown[0].Character; else _emulatorMem[_emulatorInputConfig.KeyDownAddress] = 0x00; if(keyboard.KeysReleased.Count > 0) _emulatorMem[_emulatorInputConfig.KeyReleasedAddress] = (byte)keyboard.KeysReleased[0].Character; else _emulatorMem[_emulatorInputConfig.KeyReleasedAddress] = 0x00; } private void CaptureRandomNumber() { byte rnd = (byte)new Random().Next(0, 255); _emulatorMem[_emulatorInputConfig.RandomValueAddress] = rnd; } } }
using eShopData.DTOs; namespace Admin.eShopDemo.Models { public class UserViewModel { public IEnumerable<UserModel> ListUsers { get; set; } = new List<UserModel>(); } }
namespace DbMigrator.Helpers.Interfaces { public interface IConfigurationHelper { string GetConnectionString(string connectionString, string connectionStringName); string GetProvider(string provider, string connectionStringName); void SetAppConfig(string configPath); } }
namespace Spectre.Console.Cli.Internal { internal sealed class TemplateToken { public Kind TokenKind { get; } public int Position { get; } public string Value { get; } public string Representation { get; } public TemplateToken(Kind kind, int position, string value, string representation) { TokenKind = kind; Position = position; Value = value; Representation = representation; } public enum Kind { Unknown = 0, LongName, ShortName, RequiredValue, OptionalValue, } } }
using Newtonsoft.Json; namespace PoissonSoft.KrakenApi.Contracts.UserData { /// <summary> /// Retrieve a summary of collateral balances, margin position valuations, equity and margin level. /// </summary> public class TradeBalance { [JsonProperty("error")] public string[] Error { get; set; } [JsonProperty("result")] public TradeBalanceInfo Result { get; set; } } /// <summary> /// /// </summary> public class TradeBalanceInfo { /// <summary> /// Equivalent balance (combined balance of all currencies) /// </summary> [JsonProperty("eb")] public string EquivalentBalance { get; set; } /// <summary> /// Trade balance (combined balance of all equity currencies) /// </summary> [JsonProperty("tb")] public string TradeBalance { get; set; } /// <summary> /// Margin amount of open positions /// </summary> [JsonProperty("m")] public string MarginAmountOpenPositions { get; set; } /// <summary> /// Unrealized net profit/loss of open positions /// </summary> [JsonProperty("n")] public string UnrealizedProfit { get; set; } /// <summary> /// Cost basis of open positions /// </summary> [JsonProperty("c")] public string CostBasisOpenPositions { get; set; } /// <summary> /// Current floating valuation of open positions /// </summary> [JsonProperty("v")] public string CurrentFloatingValuationOpenPositions { get; set; } /// <summary> /// Equity: trade balance + unrealized net profit/loss /// </summary> [JsonProperty("e")] public string Equity { get; set; } /// <summary> /// Free margin: Equity - initial margin (maximum margin available to open new positions) /// </summary> [JsonProperty("mf")] public string FreeMargin { get; set; } /// <summary> /// Margin level: (equity / initial margin) * 100 /// </summary> [JsonProperty("ml")] public string MarginLevel { get; set; } } }
using MasterDevs.ChromeDevTools; using Newtonsoft.Json; using System.Collections.Generic; namespace MasterDevs.ChromeDevTools.Protocol.Chrome.Debugger { /// <summary> /// Fired when virtual machine parses script. This event is also fired for all known and uncollected /// scripts upon enabling debugger. /// </summary> [Event(ProtocolName.Debugger.ScriptParsed)] [SupportedBy("Chrome")] public class ScriptParsedEvent { /// <summary> /// Gets or sets Identifier of the script parsed. /// </summary> public string ScriptId { get; set; } /// <summary> /// Gets or sets URL or name of the script parsed (if any). /// </summary> public string Url { get; set; } /// <summary> /// Gets or sets Line offset of the script within the resource with given URL (for script tags). /// </summary> public long StartLine { get; set; } /// <summary> /// Gets or sets Column offset of the script within the resource with given URL. /// </summary> public long StartColumn { get; set; } /// <summary> /// Gets or sets Last line of the script. /// </summary> public long EndLine { get; set; } /// <summary> /// Gets or sets Length of the last line of the script. /// </summary> public long EndColumn { get; set; } /// <summary> /// Gets or sets Specifies script creation context. /// </summary> public long ExecutionContextId { get; set; } /// <summary> /// Gets or sets Content hash of the script. /// </summary> public string Hash { get; set; } /// <summary> /// Gets or sets Embedder-specific auxiliary data. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public object ExecutionContextAuxData { get; set; } /// <summary> /// Gets or sets True, if this script is generated as a result of the live edit operation. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public bool? IsLiveEdit { get; set; } /// <summary> /// Gets or sets URL of source map associated with script (if any). /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string SourceMapURL { get; set; } /// <summary> /// Gets or sets True, if this script has sourceURL. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public bool? HasSourceURL { get; set; } /// <summary> /// Gets or sets True, if this script is ES6 module. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public bool? IsModule { get; set; } /// <summary> /// Gets or sets This script length. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public long? Length { get; set; } /// <summary> /// Gets or sets JavaScript top stack frame of where the script parsed event was triggered if available. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public Runtime.StackTrace StackTrace { get; set; } /// <summary> /// Gets or sets If the scriptLanguage is WebAssembly, the code section offset in the module. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public long? CodeOffset { get; set; } /// <summary> /// Gets or sets The language of the script. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public Debugger.ScriptLanguage ScriptLanguage { get; set; } } }
namespace TermoThis { class Acessar { string senha /*a_senha*/ = "xyz"; public bool Login(string senha /*p_senha*/) { // return a_senha == p_senha; return this.senha == senha; // this.senha: Instância da classe / senha: Parâmetro do método } } }
using System; using System.IO; using System.Collections; using CSCore.Tags.ID3; using NVorbis; using JAudioTags; namespace aplicacion_musica { public class LectorMetadatos { private readonly VorbisReader _vorbisReader = null; private readonly FLACFile _FLACfile; private readonly ID3v2QuickInfo _mp3iD3 = null; public string Artista { get; private set; } public string Titulo { get; private set; } public LectorMetadatos(string s) { switch (Path.GetExtension(s)) { case ".mp3": ID3v2 mp3tag = ID3v2.FromFile(s); _mp3iD3 = new ID3v2QuickInfo(mp3tag); Artista = _mp3iD3.LeadPerformers; Titulo = _mp3iD3.Title; break; case ".flac": _FLACfile = new FLACFile(s, true); Artista = _FLACfile.ARTIST; Titulo = _FLACfile.TITLE; break; case ".ogg": _vorbisReader = new VorbisReader(s); foreach (String meta in _vorbisReader.Comments) { if (meta.Contains("TITLE=")) Titulo=meta.Replace("TITLE=", ""); else if (meta.Contains("TITLE=".ToLower())) Titulo=meta.Replace("title=", ""); } foreach (String meta in _vorbisReader.Comments) { if (meta.Contains("ARTIST=")) Artista = meta.Replace("ARTIST=", ""); else if (meta.Contains("ARTIST=".ToLower())) Artista = meta.Replace("artist=", ""); } Cerrar(); break; default: break; } } private void Cerrar() { if (_vorbisReader != null) _vorbisReader.Dispose(); } public bool Evaluable() { return ((Artista != null) && (Titulo != null)) ? true : false; } } }
using System; namespace EfsTools.Attributes { public class ElementsCountAttribute : Attribute { public ElementsCountAttribute(int val) { Value = val; } public int Value { get; } } }
using System; using System.Windows; #if WinRT using Windows.UI.Xaml; using Windows.UI.Xaml.Data; using CultureInfo = System.String; #else using System.Windows.Data; using System.Globalization; #endif namespace LogoFX.Client.Mvvm.View.Infra.Converters { public class BoolToVisibilityConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { bool bValue = false; if (value is bool) bValue = (bool)value; else if (value is string) Boolean.TryParse((string) value, out bValue); else return Visibility.Visible; bool result; if (!Boolean.TryParse((string)parameter, out result)) result = true; if (result) return bValue ? Visibility.Visible : Visibility.Collapsed; else return bValue ? Visibility.Collapsed : Visibility.Visible; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new Exception("The method or operation is not implemented."); } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ToolBrush : Tool { Color[] colors = new Color[]{ Color.blue, Color.red, Color.yellow, Color.green, Color.black }; int currentColor = 0; Selector sel; // Use this for initialization void Start () { sel = new Selector(this); } public override void handUpdate(GameObject handOb, bool pinch, bool startButton) { int colorMod = 0; if (startButton) colorMod = 1; if (colorMod != 0) { int totalColors = colors.Length; currentColor += colorMod; while (currentColor >= totalColors) currentColor -= totalColors; while (currentColor < 0) currentColor += totalColors; Renderer rend = GetComponent<Renderer>(); if (rend != null) { rend.material.color = colors[currentColor]; } } sel.select(handOb); Color color = Color.gray; if (sel.getSelected() != null && sel.getHitObect().GetComponent<Renderer>() != null) { if(colors[currentColor] != Color.black) color = colors[currentColor]; if (pinch) sel.getSelected().paintObject(sel.getHitObect(), colors[currentColor], true, true); } sel.drawLine(color); } public override string getName() { return "Brush"; } }
using System.ComponentModel.DataAnnotations; namespace GlobalLib.Models.VieShowDB { public class tblDistributor { [Key] public string Distrib_strCode { get; set; } public string Distrib_strName { get; set; } } }
// ----------------------------------------------------------------------- // <copyright file="ReadinessStatus.cs" company="Petabridge, LLC"> // Copyright (C) 2015 - 2019 Petabridge, LLC <https://petabridge.com> // </copyright> // ----------------------------------------------------------------------- namespace Akka.HealthCheck.Readiness { /// <summary> /// Used to signal changes in readiness status to the downstream consumers. /// </summary> public sealed class ReadinessStatus { public ReadinessStatus(bool isReady, string statusMessage = null) { IsReady = isReady; StatusMessage = statusMessage ?? string.Empty; } /// <summary> /// If <c>true</c>, the current node is ready to begin accepting requests. /// </summary> public bool IsReady { get; } /// <summary> /// An optional status message that will be written out to the /// target (if it supports text) as part of the readiness check. /// </summary> public string StatusMessage { get; } } }
namespace JT808.Protocol.Metadata { /// <summary> /// 分包属性 /// </summary> public struct JT808SplitPackageProperty { /// <summary> /// 当前页 /// </summary> public int PackgeIndex { get; set; } /// <summary> /// 分页总数 /// </summary> public int PackgeCount { get; set; } /// <summary> /// 分包数据 /// </summary> public byte[] Data { get; set; } } }
/* * Author: Shon Verch * File Name: ScriptableObjectHelper.cs * Project Name: TheDungeonMaster * Creation Date: 01/08/18 * Modified Date: 01/08/18 * Description: Extensions functionality regard scriptable objects. */ using UnityEngine; using UnityEditor; using System.IO; /// <summary> /// Extensions functionality regard scriptable objects. /// </summary> public static class ScriptableObjectHelper { /// <summary> /// Creates a unique <see cref="ScriptableObject"/> of type <typeparamref name="T"/> at the specified file path. /// </summary> public static T CreateAsset<T>(string filePath) where T : ScriptableObject { // If we don't have a file path provided or the directory is invalid. if (filePath == string.Empty || !Directory.Exists(Path.GetDirectoryName(filePath))) return default(T); T asset = ScriptableObject.CreateInstance<T>(); AssetDatabase.CreateAsset(asset, filePath); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); return asset; } }
namespace DesktopApp { partial class DebugForm { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.urlStrip = new System.Windows.Forms.ToolStripStatusLabel(); this.toolBtnShowCode = new System.Windows.Forms.ToolStripStatusLabel(); this.toolBtnDebut = new System.Windows.Forms.ToolStripStatusLabel(); this.statusStrip1.SuspendLayout(); this.SuspendLayout(); // // statusStrip1 // this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.urlStrip, this.toolBtnShowCode, this.toolBtnDebut}); this.statusStrip1.Location = new System.Drawing.Point(0, 540); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new System.Drawing.Size(984, 22); this.statusStrip1.TabIndex = 0; this.statusStrip1.Text = "statusStrip1"; // // urlStrip // this.urlStrip.Name = "urlStrip"; this.urlStrip.Size = new System.Drawing.Size(874, 17); this.urlStrip.Spring = true; this.urlStrip.Text = "toolStripStatusLabel1"; this.urlStrip.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // toolBtnShowCode // this.toolBtnShowCode.Name = "toolBtnShowCode"; this.toolBtnShowCode.Size = new System.Drawing.Size(32, 17); this.toolBtnShowCode.Text = "源码"; this.toolBtnShowCode.ToolTipText = "网页Html代码"; this.toolBtnShowCode.Click += new System.EventHandler(this.toolBtnShowCode_Click); // // toolBtnDebut // this.toolBtnDebut.Name = "toolBtnDebut"; this.toolBtnDebut.Size = new System.Drawing.Size(32, 17); this.toolBtnDebut.Text = "调试"; this.toolBtnDebut.Click += new System.EventHandler(this.toolBtnDebut_Click); // // DebugForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(984, 562); this.Controls.Add(this.statusStrip1); this.Name = "DebugForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "DebugForm"; this.Load += new System.EventHandler(this.DebugForm_Load); this.Shown += new System.EventHandler(this.DebugForm_Shown); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.ToolStripStatusLabel urlStrip; private System.Windows.Forms.ToolStripStatusLabel toolBtnShowCode; private System.Windows.Forms.ToolStripStatusLabel toolBtnDebut; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ConferenceScheduler.Entities; namespace HybridConferenceScheduler { public class EventHandler { public IEnumerable<Assignment> Assignments { get; private set; } public void EngineUpdateEventHandler(ProcessUpdateEventArgs args) { var assignments = args.Assignments; this.Assignments = assignments; this.Assignments.WriteSchedule(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; namespace PhotoChannelWebAPI.Middleware.MemoryCache { public static class MemoryCacheMiddlewareExtension { public static IApplicationBuilder UseCacheMiddleware(this IApplicationBuilder builder) { return builder.UseMiddleware<CacheMiddleware>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Basil.Util.Event; using Basil.Util.Event.Messages; using DotNetCore.CAP; using Microsoft.AspNetCore.Mvc; namespace WebApp2.Controllers { /// <summary> /// 事件总线演示,实际项目中应该和业务控制器混用,这里只做演示用 /// </summary> public class EventBusTestController : BaseController { private readonly IEventBus eventBus; /// <summary> /// /// </summary> /// <param name="eventBus"></param> public EventBusTestController(IEventBus eventBus) { this.eventBus = eventBus; } /// <summary> /// 分布式事务eventBus实现,在RecMsg中设置断点,程序将执行RecMsg,得不到RecMsg的返回结果,因为执行过程是异步的 /// </summary> /// <param name="p"></param> /// <returns></returns> [HttpGet("{p}")] public string SendMsg(string p) { MessageEvent me = new MessageEvent() { Target = "nds.tools.user.msgtest", Data = p }; eventBus.Publish(me); return p; } /// <summary> /// 接收SendMsg中的信息, 实际场景是在其他服务发送消息,也可单独执行测试 /// </summary> /// <param name="p"></param> /// <returns></returns> [CapSubscribe("nds.tools.user.msgtest", Group = "t1")] [HttpGet("{p}")] public string RecMsg(string p) { return p; } /// <summary> /// 接收SendMsg中的信息, 实际场景是在其他服务发送消息,也可单独执行测试 /// </summary> /// <param name="p"></param> /// <returns></returns> [CapSubscribe("nds.tools.user.msgtest", Group = "t2")] [HttpGet("{p}")] public string RecMsg2(string p) { return p; } /// <summary> /// 测试网关需要 /// 随便弄个接口 /// </summary> /// <returns></returns> [HttpGet] public string Test() { return "OK"; } } }