content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Text; using NLog.Filters; using NLog.Targets; /// <summary> /// Represents a logging rule. An equivalent of &lt;logger /&gt; configuration element. /// </summary> [NLogConfigurationItem] public class LoggingRule { private readonly bool[] logLevels = new bool[LogLevel.MaxLevel.Ordinal + 1]; private string loggerNamePattern; private MatchMode loggerNameMatchMode; private string loggerNameMatchArgument; /// <summary> /// Create an empty <see cref="LoggingRule" />. /// </summary> public LoggingRule() { this.Filters = new List<Filter>(); this.ChildRules = new List<LoggingRule>(); this.Targets = new List<Target>(); } /// <summary> /// Create a new <see cref="LoggingRule" /> with a <paramref name="minLevel"/> and <paramref name="maxLevel"/> which writes to <paramref name="target"/>. /// </summary> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> /// <param name="minLevel">Minimum log level needed to trigger this rule.</param> /// <param name="maxLevel">Maximum log level needed to trigger this rule.</param> /// <param name="target">Target to be written to when the rule matches.</param> public LoggingRule(string loggerNamePattern, LogLevel minLevel, LogLevel maxLevel, Target target) : this() { this.LoggerNamePattern = loggerNamePattern; this.Targets.Add(target); EnableLoggingForLevels(minLevel, maxLevel); } /// <summary> /// Create a new <see cref="LoggingRule" /> with a <paramref name="minLevel"/> which writes to <paramref name="target"/>. /// </summary> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> /// <param name="minLevel">Minimum log level needed to trigger this rule.</param> /// <param name="target">Target to be written to when the rule matches.</param> public LoggingRule(string loggerNamePattern, LogLevel minLevel, Target target) : this() { this.LoggerNamePattern = loggerNamePattern; this.Targets.Add(target); EnableLoggingForLevels(minLevel, LogLevel.MaxLevel); } /// <summary> /// Create a (disabled) <see cref="LoggingRule" />. You should call <see cref="EnableLoggingForLevel"/> or see cref="EnableLoggingForLevels"/> to enable logging. /// </summary> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> /// <param name="target">Target to be written to when the rule matches.</param> public LoggingRule(string loggerNamePattern, Target target) : this() { this.LoggerNamePattern = loggerNamePattern; this.Targets.Add(target); } internal enum MatchMode { All, None, Equals, StartsWith, EndsWith, Contains, } /// <summary> /// Gets a collection of targets that should be written to when this rule matches. /// </summary> public IList<Target> Targets { get; private set; } /// <summary> /// Gets a collection of child rules to be evaluated when this rule matches. /// </summary> public IList<LoggingRule> ChildRules { get; private set; } /// <summary> /// Gets a collection of filters to be checked before writing to targets. /// </summary> public IList<Filter> Filters { get; private set; } /// <summary> /// Gets or sets a value indicating whether to quit processing any further rule when this one matches. /// </summary> public bool Final { get; set; } /// <summary> /// Gets or sets logger name pattern. /// </summary> /// <remarks> /// Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends but not anywhere else. /// </remarks> public string LoggerNamePattern { get { return this.loggerNamePattern; } set { this.loggerNamePattern = value; int firstPos = this.loggerNamePattern.IndexOf('*'); int lastPos = this.loggerNamePattern.LastIndexOf('*'); if (firstPos < 0) { this.loggerNameMatchMode = MatchMode.Equals; this.loggerNameMatchArgument = value; return; } if (firstPos == lastPos) { string before = this.LoggerNamePattern.Substring(0, firstPos); string after = this.LoggerNamePattern.Substring(firstPos + 1); if (before.Length > 0) { this.loggerNameMatchMode = MatchMode.StartsWith; this.loggerNameMatchArgument = before; return; } if (after.Length > 0) { this.loggerNameMatchMode = MatchMode.EndsWith; this.loggerNameMatchArgument = after; return; } return; } // *text* if (firstPos == 0 && lastPos == this.LoggerNamePattern.Length - 1) { string text = this.LoggerNamePattern.Substring(1, this.LoggerNamePattern.Length - 2); this.loggerNameMatchMode = MatchMode.Contains; this.loggerNameMatchArgument = text; return; } this.loggerNameMatchMode = MatchMode.None; this.loggerNameMatchArgument = string.Empty; } } /// <summary> /// Gets the collection of log levels enabled by this rule. /// </summary> public ReadOnlyCollection<LogLevel> Levels { get { var levels = new List<LogLevel>(); for (int i = LogLevel.MinLevel.Ordinal; i <= LogLevel.MaxLevel.Ordinal; ++i) { if (this.logLevels[i]) { levels.Add(LogLevel.FromOrdinal(i)); } } return levels.AsReadOnly(); } } /// <summary> /// Enables logging for a particular level. /// </summary> /// <param name="level">Level to be enabled.</param> public void EnableLoggingForLevel(LogLevel level) { if (level == LogLevel.Off) { return; } this.logLevels[level.Ordinal] = true; } /// <summary> /// Enables logging for a particular levels between (included) <paramref name="minLevel"/> and <paramref name="maxLevel"/>. /// </summary> /// <param name="minLevel">Minimum log level needed to trigger this rule.</param> /// <param name="maxLevel">Maximum log level needed to trigger this rule.</param> public void EnableLoggingForLevels(LogLevel minLevel, LogLevel maxLevel) { for (int i = minLevel.Ordinal; i <= maxLevel.Ordinal; ++i) { this.EnableLoggingForLevel(LogLevel.FromOrdinal(i)); } } /// <summary> /// Disables logging for a particular level. /// </summary> /// <param name="level">Level to be disabled.</param> public void DisableLoggingForLevel(LogLevel level) { if (level == LogLevel.Off) { return; } this.logLevels[level.Ordinal] = false; } /// <summary> /// Returns a string representation of <see cref="LoggingRule"/>. Used for debugging. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override string ToString() { var sb = new StringBuilder(); sb.AppendFormat(CultureInfo.InvariantCulture, "logNamePattern: ({0}:{1})", this.loggerNameMatchArgument, this.loggerNameMatchMode); sb.Append(" levels: [ "); for (int i = 0; i < this.logLevels.Length; ++i) { if (this.logLevels[i]) { sb.AppendFormat(CultureInfo.InvariantCulture, "{0} ", LogLevel.FromOrdinal(i).ToString()); } } sb.Append("] appendTo: [ "); foreach (Target app in this.Targets) { sb.AppendFormat(CultureInfo.InvariantCulture, "{0} ", app.Name); } sb.Append("]"); return sb.ToString(); } /// <summary> /// Checks whether te particular log level is enabled for this rule. /// </summary> /// <param name="level">Level to be checked.</param> /// <returns>A value of <see langword="true"/> when the log level is enabled, <see langword="false" /> otherwise.</returns> public bool IsLoggingEnabledForLevel(LogLevel level) { if (level == LogLevel.Off) { return false; } return this.logLevels[level.Ordinal]; } /// <summary> /// Checks whether given name matches the logger name pattern. /// </summary> /// <param name="loggerName">String to be matched.</param> /// <returns>A value of <see langword="true"/> when the name matches, <see langword="false" /> otherwise.</returns> public bool NameMatches(string loggerName) { switch (this.loggerNameMatchMode) { case MatchMode.All: return true; default: case MatchMode.None: return false; case MatchMode.Equals: return loggerName.Equals(this.loggerNameMatchArgument, StringComparison.Ordinal); case MatchMode.StartsWith: return loggerName.StartsWith(this.loggerNameMatchArgument, StringComparison.Ordinal); case MatchMode.EndsWith: return loggerName.EndsWith(this.loggerNameMatchArgument, StringComparison.Ordinal); case MatchMode.Contains: return loggerName.IndexOf(this.loggerNameMatchArgument, StringComparison.Ordinal) >= 0; } } } }
38.079179
169
0.567655
[ "BSD-3-Clause" ]
0xC057A/NLog
src/NLog/Config/LoggingRule.cs
12,985
C#
/******************************************************************************* * Copyright (C) Git Corporation. All rights reserved. * * Author: 代码工具自动生成 * Create Date: 2014/05/09 22:48:45 * Blog: http://www.cnblogs.com/qingyuan/ * Copyright: 太数智能科技(上海)有限公司 * Description: Git.Framework * * Revision History: * Date Author Description * 2014/05/09 22:48:45 *********************************************************************************/ using System; using System.Text; using System.Data; namespace Git.Storage.RoseEntity { [Serializable] public partial class SysResource_CE { public SysResource_CE() { } private Int32 _ID; public Int32 ID { set { this._ID = value; } get { return this._ID;} } private string _ResNum; public string ResNum { set { this._ResNum = value; } get { return this._ResNum;} } private string _ResName; public string ResName { set { this._ResName = value; } get { return this._ResName;} } private string _ParentNum; public string ParentNum { set { this._ParentNum = value; } get { return this._ParentNum;} } private Int32 _Depth; public Int32 Depth { set { this._Depth = value; } get { return this._Depth;} } private string _ParentPath; public string ParentPath { set { this._ParentPath = value; } get { return this._ParentPath;} } private Int32 _ChildCount; public Int32 ChildCount { set { this._ChildCount = value; } get { return this._ChildCount;} } private Int32 _Sort; public Int32 Sort { set { this._Sort = value; } get { return this._Sort;} } private Int16 _IsHide; public Int16 IsHide { set { this._IsHide = value; } get { return this._IsHide;} } private Int16 _IsDelete; public Int16 IsDelete { set { this._IsDelete = value; } get { return this._IsDelete;} } private string _Url; public string Url { set { this._Url = value; } get { return this._Url;} } private string _CssName; public string CssName { set { this._CssName = value; } get { return this._CssName;} } private DateTime _CreateTime; public DateTime CreateTime { set { this._CreateTime = value; } get { return this._CreateTime;} } private Int16 _Depart; public Int16 Depart { set { this._Depart = value; } get { return this._Depart;} } private Int16 _ResType; public Int16 ResType { set { this._ResType = value; } get { return this._ResType;} } private DateTime _UpdateTime; public DateTime UpdateTime { set { this._UpdateTime = value; } get { return this._UpdateTime;} } private string _CreateUser; public string CreateUser { set { this._CreateUser = value; } get { return this._CreateUser;} } private string _UpdateUser; public string UpdateUser { set { this._UpdateUser = value; } get { return this._UpdateUser;} } private string _CreateIp; public string CreateIp { set { this._CreateIp = value; } get { return this._CreateIp;} } private string _UpdateIp; public string UpdateIp { set { this._UpdateIp = value; } get { return this._UpdateIp;} } private string _Remark; public string Remark { set { this._Remark = value; } get { return this._Remark;} } } }
18.762712
82
0.616983
[ "MIT" ]
KittenCN/WMS
Git.Storage.RoseEntity/SysResource_CE.cs
3,365
C#
using System.Net; using System.Text.Json; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.Functions.Worker; using Microsoft.Azure.Functions.Worker.Http; using Microsoft.Extensions.Logging; using MyChess.Backend.Handlers; using MyChess.Functions.Internal; using MyChess.Interfaces; namespace MyChess.Functions; public class GamesMoveFunction { private readonly ILogger<GamesMoveFunction> _log; private readonly IGamesHandler _gamesHandler; private readonly ISecurityValidator _securityValidator; public GamesMoveFunction( ILogger<GamesMoveFunction> log, IGamesHandler gamesHandler, ISecurityValidator securityValidator) { _log = log; _gamesHandler = gamesHandler; _securityValidator = securityValidator; } [Function("GamesMove")] //[SignalROutput(HubName = "GameHub")] public async Task<HttpResponseData> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "games/{id}/moves")] HttpRequestData req, // Use following references to migrate to isolated worker: // https://docs.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide#multiple-output-bindings // https://github.com/aspnet/AzureSignalR-samples/blob/main/samples/DotnetIsolated-BidirectionChat/Functions.cs // https://github.com/Azure/azure-functions-dotnet-worker/issues/294 //[Microsoft.Azure.Functions.Worker.(HubName = "GameHub")] IAsyncCollector<SignalRMessage> signalRMessages, string id) { using var _ = _log.FuncGamesMoveScope(); _log.FuncGamesMoveStarted(); var principal = await _securityValidator.GetClaimsPrincipalAsync(req); if (principal == null) { return req.CreateResponse(HttpStatusCode.Unauthorized); } if (!principal.HasPermission(PermissionConstants.GamesReadWrite)) { _log.FuncGamesMoveUserDoesNotHavePermission(principal.Identity?.Name, PermissionConstants.GamesReadWrite); return req.CreateResponse(HttpStatusCode.Unauthorized); } var authenticatedUser = principal.ToAuthenticatedUser(); _log.FuncGamesMoveProcessingMethod(req.Method); var moveToAdd = await JsonSerializer.DeserializeAsync<MyChessGameMove>(req.Body); ArgumentNullException.ThrowIfNull(moveToAdd); var error = await _gamesHandler.AddMoveAsync(authenticatedUser, id, moveToAdd); if (error == null) { //var payload = JsonSerializer.Serialize(moveToAdd); //await signalRMessages.AddAsync(new SignalRMessage() //{ // GroupName = id, // Target = "MoveUpdate", // Arguments = new[] { id, payload } //}); return req.CreateResponse(HttpStatusCode.OK); } else { var problemDetail = new ProblemDetails { Detail = error.Detail, Instance = error.Instance, Status = error.Status, Title = error.Title }; var response = req.CreateResponse((HttpStatusCode)problemDetail.Status); await response.WriteAsJsonAsync(problemDetail); return response; } } }
37.406593
121
0.646298
[ "MIT" ]
JanneMattila/chess
src/MyChess.Functions/GamesMoveFunction.cs
3,406
C#
using System.Runtime.Serialization; namespace NetCoreStack.Contracts { [DataContract] public class ServiceException { [DataMember] public string Message { get; set; } [DataMember] public long ErrorCode { get; set; } public ServiceException(string message, long errorCode = 0) { Message = message; ErrorCode = errorCode; } } }
20.285714
67
0.589202
[ "Apache-2.0" ]
NetCoreStack/Contracts
src/NetCoreStack.Contracts/Types/ServiceException.cs
428
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Input; using System; using System.IO; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Examples.Demos.EyeTracking.Logging { [AddComponentMenu("Scripts/MRTK/Examples/UserInputRecorder")] public class UserInputRecorder : CustomInputLogger { public string FilenameToUse = $"test{Path.DirectorySeparatorChar}folder"; [SerializeField] private LogStructure logStructure = null; private bool automaticLogging = true; #region Singleton private static UserInputRecorder instance; public static UserInputRecorder Instance { get { if (instance == null) { instance = FindObjectOfType<UserInputRecorder>(); } return instance; } } #endregion EyeTrackingTarget prevTarget = null; public override string GetHeader() { if (logStructure != null) { string[] header_columns = logStructure.GetHeaderColumns(); string header_format = GetStringFormat(header_columns); return String.Format(header_format, header_columns); } else return ""; } // Todo: Put into BasicLogger? protected object[] GetData_Part1() { object[] data = new object[] { // UserId UserName, // SessionType sessionDescr, // Timestamp (DateTime.UtcNow - TimerStart).TotalMilliseconds }; return data; } // Todo: Put into generic utils class? public object[] MergeObjArrays(object[] part1, object[] part2) { object[] data = new object[part1.Length + part2.Length]; part1.CopyTo(data, 0); part2.CopyTo(data, part1.Length); return data; } protected override string GetFileName() { if (!string.IsNullOrEmpty(FilenameToUse)) { return FilenameToUse; } return String.Format("{0}-{1}", sessionDescr, UserName); } private string LimitStringLength(string str, int maxLength) { if (str.Length < maxLength) return str; else { return str.Substring(0, maxLength); } } public static string GetStringFormat(object[] data) { string strFormat = ""; for (int i = 0; i < data.Length - 1; i++) { strFormat += ("{" + i + "}" + System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator + " "); } strFormat += ("{" + (data.Length - 1) + "}"); return strFormat; } public void UpdateLog(string inputType, string inputStatus, EyeTrackingTarget intendedTarget) { if ((Instance != null) && (isLogging)) { if (logStructure != null) { object[] data = MergeObjArrays(GetData_Part1(), logStructure.GetData(inputType, inputStatus, intendedTarget)); string data_format = GetStringFormat(data); Instance.CustomAppend(String.Format(data_format, data)); prevTarget = intendedTarget; } } } #region Remains the same across different loggers protected override void CustomAppend(string msg) { base.CustomAppend(msg); } #endregion public void UpdateLog() { UpdateLog("", "", null); } void Update() { if (automaticLogging) { UpdateLog(); } } public override void OnDestroy() { // Disable listening to user input if (UserInputRecorder.Instance != null) { UserInputRecorder.Instance.StopLoggingAndSave(); } base.OnDestroy(); } } }
29.675497
130
0.515287
[ "MIT" ]
AMUZA668/MixedRealityToolkit-Unity
Assets/MRTK/Examples/Demos/EyeTracking/DemoVisualizer/Scripts/UserInputRecorder.cs
4,483
C#
using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; namespace ILNET.Elements { public enum VariableLevel { Local, Intermediate, Global }; public class Variable : Element { private Process m_ParentProcess; private VariableLevel m_Level; private string m_Type; private string m_Value; private bool m_IsInput; private bool m_IsOutput; public Variable() { m_Level = VariableLevel.Local; m_Type = ""; m_Value = ""; m_IsInput = false; m_IsOutput = false; } [XmlIgnoreAttribute] public Process ParentProcess { get { return m_ParentProcess; } set { m_ParentProcess = value; } } public String ScopeVar() { switch (m_Level) { case VariableLevel.Global: return "g"; case VariableLevel.Intermediate: return "i"; case VariableLevel.Local: return "l"; default: return ""; } } public String Compile(String shell) { String value = m_Value; if (value == "") { if (m_Type == "") return ""; if (m_Type == "string") value = "\"\""; else if (!m_Type.Contains("[") && !m_Type.Contains("]")) value = "new " + m_Type + "()"; else return ""; } shell = Utils.Replace(shell, "cvarname", m_Name); shell = Utils.Replace(shell, "cvarscope", ScopeVar()); shell = Utils.Replace(shell, "cvarvalue", value); return shell; } public String CompileResult(String shell) { if (!m_IsOutput) return ""; shell = Utils.Replace(shell, "cvarname", m_Name); String scope; switch (m_Level) { case VariableLevel.Global: scope = "g"; break; case VariableLevel.Intermediate: scope = "i"; break; case VariableLevel.Local: scope = "l"; break; default: return ""; } shell = Utils.Replace(shell, "cvarscope", scope); return shell; } [XmlAttribute("level")] public VariableLevel Level { get { return m_Level; } set { m_Level = value; } } [XmlElement("type")] public string Type { get { return m_Type; } set { m_Type = value; } } [XmlElement("value")] public string Value { get { return m_Value; } set { m_Value = value; } } [XmlAttribute("isInput")] public bool IsInput { get { return m_IsInput; } set { m_IsInput = value; } } [XmlAttribute("isOutput")] public bool IsOutput { get { return m_IsOutput; } set { m_IsOutput = value; } } } }
25.14966
106
0.409521
[ "MIT" ]
Gefix/Ilnet
Model/ILNET/Elements/Variable.cs
3,699
C#
using HMI.Vehicles.Behaviours.Base; using HMI.Vehicles.Services; using UnityEngine; namespace HMI.UI.Cluster { /// <summary> /// Progress bar that shows the current charge level of a battery /// </summary> [RequireComponent(typeof(SpriteRenderer))] public class ClusterBatteryLevel : MonoBehaviour { /// <summary> /// Battery that this progress bar is attached to /// </summary> private BatteryBase BatteryDataSource; /// <summary> /// Renderer of the progress bar /// </summary> private SpriteRenderer SpriteRenderer; /// <summary> /// Unity Awake callback /// </summary> private void Awake() { BatteryDataSource = VehicleService.GetBattery(); SpriteRenderer = GetComponent<SpriteRenderer>(); } /// <summary> /// Unity Update callback /// </summary> private void LateUpdate() { var batteryLevel = Mathf.Clamp01(BatteryDataSource.CurrentRelativeBatteryLevel); SpriteRenderer.material.SetFloat("Fill", batteryLevel); } } }
27.690476
92
0.597592
[ "MIT" ]
sunrui19941128/CarHMI
Assets/UnityTechnologies/HMITemplate/Scripts/HMI/UI/Cluster/ClusterBatteryLevel.cs
1,165
C#
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT //no silverlight for xunit InlineData using System; using System.Collections.Generic; using System.Linq; using NLog.Internal; using Xunit; using Xunit.Extensions; namespace NLog.UnitTests.Internal { public class UrlHelperTests { [Theory] [InlineData("", true, "")] [InlineData("", false, "")] [InlineData(null, false, "")] [InlineData(null, true, "")] [InlineData("ab cd", true,"ab+cd")] [InlineData("ab cd", false, "ab%20cd")] [InlineData("ab cd", false, "ab%20cd")] [InlineData(" €;✈ Ĕ ßß ßß ", true, "+%u20ac%3b%u2708+%u0114++%df%df+%df%df+")] //current implementation, not sure if correct [InlineData(" €;✈ Ĕ ßß ßß ", false, "%20%u20ac%3b%u2708%20%u0114%20%20%df%df%20%df%df%20")] //current implementation, not sure if correct [InlineData(".()*-_!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", true, ".()*-_!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")] [InlineData(".()*-_!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", false, ".()*-_!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")] [InlineData("《∠∠⊙⌒∈∽》`````", true, "%u300a%u2220%u2220%u2299%u2312%u2208%u223d%u300b%60%60%60%60%60")] //current implementation, not sure if correct public void UrlEncodeTest(string input, bool spaceAsPlus, string result) { Assert.Equal(result, UrlHelper.UrlEncode(input, spaceAsPlus)); } } } #endif
46.5
156
0.708096
[ "BSD-3-Clause" ]
0xC057A/NLog
tests/NLog.UnitTests/Internal/UrlHelperTests.cs
3,198
C#
using Newtonsoft.Json; namespace PekoBot.Entities.GraphQL { public class ChannelObject { [JsonProperty("name", NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Populate)] public string Name { get; set; } [JsonProperty("en_name", NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Populate)] public string EnglishName { get; set; } [JsonProperty("id", NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Populate)] public string Id { get; set; } [JsonProperty("image", NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Populate)] public string Image { get; set; } [JsonProperty("platform", NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Populate)] public string Platform { get; set; } [JsonProperty("group", NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Populate)] public string Group { get; set; } [JsonProperty("statistics", NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Populate)] public StatisticsObject Statistics { get; set; } } }
45.107143
130
0.788599
[ "MIT" ]
Mikyan0207/PekoBot
PekoBot.Entities/GraphQL/ChannelObject.cs
1,265
C#
namespace Gecko.WebIDL { using System; internal class HTMLObjectElement : WebIDLBase { public HTMLObjectElement(nsIDOMWindow globalWindow, nsISupports thisObject) : base(globalWindow, thisObject) { } public string Data { get { return this.GetProperty<string>("data"); } set { this.SetProperty("data", value); } } public string Type { get { return this.GetProperty<string>("type"); } set { this.SetProperty("type", value); } } public bool TypeMustMatch { get { return this.GetProperty<bool>("typeMustMatch"); } set { this.SetProperty("typeMustMatch", value); } } public string Name { get { return this.GetProperty<string>("name"); } set { this.SetProperty("name", value); } } public string UseMap { get { return this.GetProperty<string>("useMap"); } set { this.SetProperty("useMap", value); } } public nsISupports Form { get { return this.GetProperty<nsISupports>("form"); } } public string Width { get { return this.GetProperty<string>("width"); } set { this.SetProperty("width", value); } } public string Height { get { return this.GetProperty<string>("height"); } set { this.SetProperty("height", value); } } public nsIDOMDocument ContentDocument { get { return this.GetProperty<nsIDOMDocument>("contentDocument"); } } public nsIDOMWindow ContentWindow { get { return this.GetProperty<nsIDOMWindow>("contentWindow"); } } public bool WillValidate { get { return this.GetProperty<bool>("willValidate"); } } public nsISupports Validity { get { return this.GetProperty<nsISupports>("validity"); } } public string ValidationMessage { get { return this.GetProperty<string>("validationMessage"); } } public bool CheckValidity() { return this.CallMethod<bool>("checkValidity"); } public void SetCustomValidity(string error) { this.CallVoidMethod("setCustomValidity", error); } public string Align { get { return this.GetProperty<string>("align"); } set { this.SetProperty("align", value); } } public string Archive { get { return this.GetProperty<string>("archive"); } set { this.SetProperty("archive", value); } } public string Code { get { return this.GetProperty<string>("code"); } set { this.SetProperty("code", value); } } public bool Declare { get { return this.GetProperty<bool>("declare"); } set { this.SetProperty("declare", value); } } public uint Hspace { get { return this.GetProperty<uint>("hspace"); } set { this.SetProperty("hspace", value); } } public string Standby { get { return this.GetProperty<string>("standby"); } set { this.SetProperty("standby", value); } } public uint Vspace { get { return this.GetProperty<uint>("vspace"); } set { this.SetProperty("vspace", value); } } public string CodeBase { get { return this.GetProperty<string>("codeBase"); } set { this.SetProperty("codeBase", value); } } public string CodeType { get { return this.GetProperty<string>("codeType"); } set { this.SetProperty("codeType", value); } } public string Border { get { return this.GetProperty<string>("border"); } set { this.SetProperty("border", value); } } } }
21.552347
86
0.359129
[ "MIT" ]
haga-rak/Freezer
Freezer/GeckoFX/__Core/WebIDL/Generated/HTMLObjectElement.cs
5,970
C#
using System.Globalization; using imSSOUtils.adapters; namespace imSSOUtils.cache.visual { /// <summary> /// Viewport-based functions /// </summary> internal readonly struct Viewport { /// <summary> /// Toggle filters (LUT) on and off. /// </summary> /// <param name="enabled"></param> public static void toggle_filters(bool enabled) => MemoryAdapter.direct_call($"Game->PostEffectHandler::SetEnableLUT({(enabled ? 1 : 0)});"); /// <summary> /// Changes the current filter intensity. /// </summary> /// <param name="intensity">The intensity (max 1)</param> public static void set_intensity(float intensity) => MemoryAdapter.direct_call( $"Game->PostEffectHandler::SetFilterFade({intensity.ToString(CultureInfo.InvariantCulture).Replace(".", "::")});"); /// <summary> /// Changes the filter. /// </summary> /// <param name="index">The filter index</param> public static void set_filter(int index) => MemoryAdapter.direct_call($"Game->PostEffectHandler::SetFilter({index});"); /// <summary> /// Draws the current location. /// </summary> /// <returns></returns> public static void draw_current_location() { const string code = "if (Game->GlobalTempStringData::GetDataString() != Game->LocationNameMiniMap::GetViewText()) >>\n" + "Game->InfoTextWindow3::SetViewText(Game->LocationNameMiniMap::GetViewText());\n" + "Game->InfoTextWindow3::SetViewTextColor(1, 1, 1, 1);\n" + // Float RGBA: White "Game->InfoTextWindow3::Start();\n<<\n" + "Game->GlobalTempStringData::SetDataString(Game->LocationNameMiniMap::GetViewText());"; MemoryAdapter.direct_call(code); } } }
40
131
0.584896
[ "CC0-1.0" ]
qqtc0/imSSOUtils
imSSOUtils/cache/visual/Viewport.cs
1,922
C#
using System; namespace AspNetCoreIdentity { public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); public string Summary { get; set; } } }
18.6875
69
0.61204
[ "MIT" ]
ANgajasinghe/aspnet-core-identity
AspNetCoreIdentity/WeatherForecast.cs
299
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v8/errors/policy_violation_error.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Ads.GoogleAds.V8.Errors { /// <summary>Holder for reflection information generated from google/ads/googleads/v8/errors/policy_violation_error.proto</summary> public static partial class PolicyViolationErrorReflection { #region Descriptor /// <summary>File descriptor for google/ads/googleads/v8/errors/policy_violation_error.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static PolicyViolationErrorReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cjtnb29nbGUvYWRzL2dvb2dsZWFkcy92OC9lcnJvcnMvcG9saWN5X3Zpb2xh", "dGlvbl9lcnJvci5wcm90bxIeZ29vZ2xlLmFkcy5nb29nbGVhZHMudjguZXJy", "b3JzGhxnb29nbGUvYXBpL2Fubm90YXRpb25zLnByb3RvImIKGFBvbGljeVZp", "b2xhdGlvbkVycm9yRW51bSJGChRQb2xpY3lWaW9sYXRpb25FcnJvchIPCgtV", "TlNQRUNJRklFRBAAEgsKB1VOS05PV04QARIQCgxQT0xJQ1lfRVJST1IQAkL0", "AQoiY29tLmdvb2dsZS5hZHMuZ29vZ2xlYWRzLnY4LmVycm9yc0IZUG9saWN5", "VmlvbGF0aW9uRXJyb3JQcm90b1ABWkRnb29nbGUuZ29sYW5nLm9yZy9nZW5w", "cm90by9nb29nbGVhcGlzL2Fkcy9nb29nbGVhZHMvdjgvZXJyb3JzO2Vycm9y", "c6ICA0dBQaoCHkdvb2dsZS5BZHMuR29vZ2xlQWRzLlY4LkVycm9yc8oCHkdv", "b2dsZVxBZHNcR29vZ2xlQWRzXFY4XEVycm9yc+oCIkdvb2dsZTo6QWRzOjpH", "b29nbGVBZHM6OlY4OjpFcnJvcnNiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V8.Errors.PolicyViolationErrorEnum), global::Google.Ads.GoogleAds.V8.Errors.PolicyViolationErrorEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V8.Errors.PolicyViolationErrorEnum.Types.PolicyViolationError) }, null, null) })); } #endregion } #region Messages /// <summary> /// Container for enum describing possible policy violation errors. /// </summary> public sealed partial class PolicyViolationErrorEnum : pb::IMessage<PolicyViolationErrorEnum> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<PolicyViolationErrorEnum> _parser = new pb::MessageParser<PolicyViolationErrorEnum>(() => new PolicyViolationErrorEnum()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<PolicyViolationErrorEnum> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V8.Errors.PolicyViolationErrorReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PolicyViolationErrorEnum() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PolicyViolationErrorEnum(PolicyViolationErrorEnum other) : this() { _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PolicyViolationErrorEnum Clone() { return new PolicyViolationErrorEnum(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as PolicyViolationErrorEnum); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(PolicyViolationErrorEnum other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(PolicyViolationErrorEnum other) { if (other == null) { return; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; } } } #endif #region Nested types /// <summary>Container for nested types declared in the PolicyViolationErrorEnum message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// Enum describing possible policy violation errors. /// </summary> public enum PolicyViolationError { /// <summary> /// Enum unspecified. /// </summary> [pbr::OriginalName("UNSPECIFIED")] Unspecified = 0, /// <summary> /// The received error code is not known in this version. /// </summary> [pbr::OriginalName("UNKNOWN")] Unknown = 1, /// <summary> /// A policy was violated. See PolicyViolationDetails for more detail. /// </summary> [pbr::OriginalName("POLICY_ERROR")] PolicyError = 2, } } #endregion } #endregion } #endregion Designer generated code
37.041475
319
0.705026
[ "Apache-2.0" ]
deni-skaraudio/google-ads-dotnet
src/V8/Types/PolicyViolationError.g.cs
8,038
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GamesPortal.Client.Interfaces { public static class WellKnownModules { public const string Models = "ModelsModule"; public const string ViewModels = "ViewModelsModule"; public const string Views = "ViewsModule"; } }
23.333333
60
0.714286
[ "MIT" ]
jackobo/jackobs-code
Portal/Client/Head/src/Interfaces/WellKnownModules.cs
352
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.OpenApi.Models; namespace Swashbuckle.AspNetCore.SwaggerGen { public class SchemaGenerator : ISchemaGenerator { private readonly SchemaGeneratorOptions _generatorOptions; private readonly ISerializerMetadataResolver _serializerMetadataResolver; public SchemaGenerator(SchemaGeneratorOptions generatorOptions, ISerializerMetadataResolver serializerMetadataResolver) { _generatorOptions = generatorOptions; _serializerMetadataResolver = serializerMetadataResolver; } public OpenApiSchema GenerateSchema( Type type, SchemaRepository schemaRepository, MemberInfo memberInfo = null, ParameterInfo parameterInfo = null) { var schema = GenerateSchemaForType(type, schemaRepository); if (memberInfo != null) { ApplyMemberMetadata(schema, type, memberInfo); } else if (parameterInfo != null) { ApplyParameterMetadata(schema, type, parameterInfo); } if (schema.Reference == null) { ApplyFilters(schema, type, schemaRepository, memberInfo, parameterInfo); } return schema; } private OpenApiSchema GenerateSchemaForType(Type type, SchemaRepository schemaRepository) { if (_generatorOptions.CustomTypeMappings.ContainsKey(type)) { return _generatorOptions.CustomTypeMappings[type](); } if (type.IsAssignableToOneOf(typeof(IFormFile), typeof(FileResult))) { return new OpenApiSchema { Type = "string", Format = "binary" }; } if (_generatorOptions.GeneratePolymorphicSchemas) { var knownSubTypes = _generatorOptions.SubTypesResolver(type); if (knownSubTypes.Any()) { return GeneratePolymorphicSchema(knownSubTypes, schemaRepository); } } var serializerMetadata = _serializerMetadataResolver.GetSerializerMetadataForType(type); var shouldBeReferened = (serializerMetadata.EnumValues != null && !_generatorOptions.UseInlineDefinitionsForEnums) || (serializerMetadata.IsDictionary && serializerMetadata.Type == serializerMetadata.DictionaryValueType) || (serializerMetadata.IsArray && serializerMetadata.Type == serializerMetadata.ArrayItemType) || (serializerMetadata.IsObject && serializerMetadata.Properties != null); return (shouldBeReferened) ? GenerateReferencedSchema(serializerMetadata, schemaRepository) : GenerateInlineSchema(serializerMetadata, schemaRepository); } private OpenApiSchema GeneratePolymorphicSchema(IEnumerable<Type> knownSubTypes, SchemaRepository schemaRepository) { return new OpenApiSchema { OneOf = knownSubTypes .Select(subType => GenerateSchema(subType, schemaRepository)) .ToList() }; } private OpenApiSchema GenerateReferencedSchema(SerializerMetadata serializerMetadata, SchemaRepository schemaRepository) { return schemaRepository.GetOrAdd( serializerMetadata.Type, _generatorOptions.SchemaIdSelector(serializerMetadata.Type), () => { var schema = GenerateInlineSchema(serializerMetadata, schemaRepository); ApplyFilters(schema, serializerMetadata.Type, schemaRepository); return schema; }); } private OpenApiSchema GenerateInlineSchema(SerializerMetadata serializerMetadata, SchemaRepository schemaRepository) { if (serializerMetadata.IsPrimitive) return GeneratePrimitiveSchema(serializerMetadata); if (serializerMetadata.IsDictionary) return GenerateDictionarySchema(serializerMetadata, schemaRepository); if (serializerMetadata.IsArray) return GenerateArraySchema(serializerMetadata, schemaRepository); if (serializerMetadata.IsObject) return GenerateObjectSchema(serializerMetadata, schemaRepository); return new OpenApiSchema(); } private OpenApiSchema GeneratePrimitiveSchema(SerializerMetadata serializerMetadata) { var schema = new OpenApiSchema { Type = serializerMetadata.DataType, Format = serializerMetadata.DataFormat }; if (serializerMetadata.EnumValues != null) { schema.Enum = serializerMetadata.EnumValues .Select(value => OpenApiAnyFactory.CreateFor(schema, value)) .ToList(); } return schema; } private OpenApiSchema GenerateDictionarySchema(SerializerMetadata serializerMetadata, SchemaRepository schemaRepository) { if (serializerMetadata.DictionaryKeyType.IsEnum) { // This is a special case where we can include named properties based on the enum values return new OpenApiSchema { Type = "object", Properties = serializerMetadata.DictionaryKeyType.GetEnumNames() .ToDictionary( name => name, name => GenerateSchema(serializerMetadata.DictionaryValueType, schemaRepository) ) }; } return new OpenApiSchema { Type = "object", AdditionalPropertiesAllowed = true, AdditionalProperties = GenerateSchema(serializerMetadata.DictionaryValueType, schemaRepository) }; } private OpenApiSchema GenerateArraySchema(SerializerMetadata serializerMetadata, SchemaRepository schemaRepository) { return new OpenApiSchema { Type = "array", Items = GenerateSchema(serializerMetadata.ArrayItemType, schemaRepository), UniqueItems = serializerMetadata.Type.IsSet() ? (bool?)true : null }; } private OpenApiSchema GenerateObjectSchema(SerializerMetadata serializerMetadata, SchemaRepository schemaRepository) { if (serializerMetadata.Properties == null) { return new OpenApiSchema { Type = "object" }; } var schema = new OpenApiSchema { Type = "object", Properties = new Dictionary<string, OpenApiSchema>(), Required = new SortedSet<string>() }; // If it's a baseType with known subTypes, add the discriminator property if (_generatorOptions.GeneratePolymorphicSchemas && _generatorOptions.SubTypesResolver(serializerMetadata.Type).Any()) { var discriminatorName = _generatorOptions.DiscriminatorSelector(serializerMetadata.Type); schema.Properties.Add(discriminatorName, new OpenApiSchema { Type = "string" }); schema.Required.Add(discriminatorName); schema.Discriminator = new OpenApiDiscriminator { PropertyName = discriminatorName }; } foreach (var serializerPropertyMetadata in serializerMetadata.Properties) { var customAttributes = serializerPropertyMetadata.MemberInfo.GetInlineOrMetadataTypeAttributes(); if (_generatorOptions.IgnoreObsoleteProperties && customAttributes.OfType<ObsoleteAttribute>().Any()) continue; var propertySchema = GenerateSchema(serializerPropertyMetadata.MemberType, schemaRepository, memberInfo: serializerPropertyMetadata.MemberInfo); if (propertySchema.Reference == null) { propertySchema.Nullable = serializerPropertyMetadata.IsNullable; } schema.Properties.Add(serializerPropertyMetadata.Name, propertySchema); if (serializerPropertyMetadata.IsRequired || customAttributes.OfType<RequiredAttribute>().Any()) schema.Required.Add(serializerPropertyMetadata.Name); } if (serializerMetadata.ExtensionDataValueType != null) { schema.AdditionalProperties = GenerateSchema(serializerMetadata.ExtensionDataValueType, schemaRepository); } // If it's a known subType, reference the baseType for inheritied properties if (_generatorOptions.GeneratePolymorphicSchemas && (serializerMetadata.Type.BaseType != null) && _generatorOptions.SubTypesResolver(serializerMetadata.Type.BaseType).Contains(serializerMetadata.Type)) { var baseSerializerContract = _serializerMetadataResolver.GetSerializerMetadataForType(serializerMetadata.Type.BaseType); var baseSchemaReference = GenerateReferencedSchema(baseSerializerContract, schemaRepository); schema.AllOf = new[] { baseSchemaReference }; var baseSchema = schemaRepository.Schemas[baseSchemaReference.Reference.Id]; foreach (var basePropertyName in baseSchema.Properties.Keys) { schema.Properties.Remove(basePropertyName); } } return schema; } private void ApplyMemberMetadata(OpenApiSchema schema, Type type, MemberInfo memberInfo) { if (schema.Reference != null) { schema.AllOf = new[] { new OpenApiSchema { Reference = schema.Reference } }; schema.Reference = null; } if (schema.Reference == null) { schema.Nullable = type.IsReferenceOrNullableType(); schema.ApplyCustomAttributes(memberInfo.GetInlineOrMetadataTypeAttributes()); if (memberInfo is PropertyInfo propertyInfo) { schema.ReadOnly = (propertyInfo.IsPubliclyReadable() && !propertyInfo.IsPubliclyWritable()); schema.WriteOnly = (!propertyInfo.IsPubliclyReadable() && propertyInfo.IsPubliclyWritable()); } } } private void ApplyParameterMetadata(OpenApiSchema schema, Type type, ParameterInfo parameterInfo) { if (schema.Reference != null) { schema.AllOf = new[] { new OpenApiSchema { Reference = schema.Reference } }; schema.Reference = null; } if (schema.Reference == null) { schema.Nullable = type.IsReferenceOrNullableType(); schema.ApplyCustomAttributes(parameterInfo.GetCustomAttributes()); if (parameterInfo.HasDefaultValue) { schema.Default = OpenApiAnyFactory.CreateFor(schema, parameterInfo.DefaultValue); } } } private void ApplyFilters( OpenApiSchema schema, Type type, SchemaRepository schemaRepository, MemberInfo memberInfo = null, ParameterInfo parameterInfo = null) { var filterContext = new SchemaFilterContext( type: type, schemaGenerator: this, schemaRepository: schemaRepository, memberInfo: memberInfo, parameterInfo: parameterInfo); foreach (var filter in _generatorOptions.SchemaFilters) { filter.Apply(schema, filterContext); } } } }
40.481967
160
0.606625
[ "MIT" ]
ybeauchamph/Swashbuckle.AspNetCore
src/Swashbuckle.AspNetCore.SwaggerGen/SchemaGenerator/SchemaGenerator.cs
12,349
C#
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.IO; using Avalonia.Platform; using Avalonia.Skia.Helpers; using SkiaSharp; namespace Avalonia.Skia { /// <summary> /// Immutable Skia bitmap. /// </summary> public class ImmutableBitmap : IDrawableBitmapImpl { private readonly SKImage _image; /// <summary> /// Create immutable bitmap from given stream. /// </summary> /// <param name="stream">Stream containing encoded data.</param> public ImmutableBitmap(Stream stream) { using (var skiaStream = new SKManagedStream(stream)) { using (var data = SKData.Create(skiaStream)) _image = SKImage.FromEncodedData(data); if (_image == null) { throw new ArgumentException("Unable to load bitmap from provided data"); } PixelSize = new PixelSize(_image.Width, _image.Height); // TODO: Skia doesn't have an API for DPI. Dpi = new Vector(96, 96); } } /// <summary> /// Create immutable bitmap from given pixel data copy. /// </summary> /// <param name="size">Size of the bitmap.</param> /// <param name="dpi">DPI of the bitmap.</param> /// <param name="stride">Stride of data pixels.</param> /// <param name="format">Format of data pixels.</param> /// <param name="data">Data pixels.</param> public ImmutableBitmap(PixelSize size, Vector dpi, int stride, PixelFormat format, IntPtr data) { var imageInfo = new SKImageInfo(size.Width, size.Height, format.ToSkColorType(), SKAlphaType.Premul); _image = SKImage.FromPixelCopy(imageInfo, data, stride); if (_image == null) { throw new ArgumentException("Unable to create bitmap from provided data"); } PixelSize = size; Dpi = dpi; } public Vector Dpi { get; } public PixelSize PixelSize { get; } public int Version { get; } = 1; /// <inheritdoc /> public void Dispose() { _image.Dispose(); } /// <inheritdoc /> public void Save(string fileName) { ImageSavingHelper.SaveImage(_image, fileName); } /// <inheritdoc /> public void Save(Stream stream) { ImageSavingHelper.SaveImage(_image, stream); } /// <inheritdoc /> public void Draw(DrawingContextImpl context, SKRect sourceRect, SKRect destRect, SKPaint paint) { context.Canvas.DrawImage(_image, sourceRect, destRect, paint); } } }
30.936842
113
0.563797
[ "MIT" ]
Karlyshev/Avalonia
src/Skia/Avalonia.Skia/ImmutableBitmap.cs
2,939
C#
using System; using System.Collections.Generic; namespace MatchingBrackets { public class MatchingBrackets { public static void Main() { var input = Console.ReadLine(); var stack = new Stack<int>(); for (int i = 0; i < input.Length; i++) { if (input[i] == '(') { stack.Push(i); } if (input[i] == ')') { var startIndex = stack.Pop(); string output = input.Substring(startIndex, i - startIndex + 1); Console.WriteLine(output); } } } } }
23.7
84
0.410689
[ "MIT" ]
varbanov88/C-Advanced
StacksAndQueues/MatchingBrackets/MatchingBrackets.cs
713
C#
#region License & Metadata // The MIT License (MIT) // // 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. // // // Created On: 2018/05/19 14:02 // Modified On: 2019/01/24 14:09 // Modified By: Alexis #endregion using System.Runtime.InteropServices; namespace SuperMemoAssistant.SuperMemo.SuperMemo17.Files { internal class InfElementsElemContainer17 { #region Constructors public InfElementsElemContainer17(InfElementsElem17 e) { _elem = e; } #endregion #region Properties & Fields - Public public InfElementsElem17 _elem; #endregion } [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 118)] internal unsafe struct InfElementsElem17 { [FieldOffset(0)] /* 0x00 */ public byte elementType; // (00: Topic/Deleted, 01: Item, 02: ?, 03: ?, 04: Concept) [FieldOffset(1)] /* 0x01 */ public byte unknownbyte1; [FieldOffset(2)] /* 0x02 */ public int titleTextId; // id / -1 if deleted [FieldOffset(6)] /* 0x06 */ public int componPos; // FF FF FF FF if none [FieldOffset(10)] /* 0x0A */ public int unknownId; [FieldOffset(14)] /* 0x0E */ public int unknown3; [FieldOffset(18)] /* 0x12 */ public int unknown4; [FieldOffset(22)] /* 0x16 */ public int unknown5; [FieldOffset(26)] /* 0x1A */ public byte unknownbyte14; [FieldOffset(27)] /* 0x1B */ public byte unknownbyte15; [FieldOffset(28)] /* 0x1C */ public fixed byte AF[6]; // Real48 [FieldOffset(34)] /* 0x22 */ public int unknown8; [FieldOffset(38)] /* 0x26 */ public int unknown9; [FieldOffset(42)] /* 0x2A */ public int unknown10; [FieldOffset(46)] /* 0x2E */ public int unknown11; [FieldOffset(50)] /* 0x32 */ public int unknown12; [FieldOffset(54)] /* 0x36 */ public byte unknownbyte16; [FieldOffset(55)] /* 0x37 */ public byte unknownbyte17; [FieldOffset(56)] /* 0x38 */ public byte unknownbyte18; [FieldOffset(57)] /* 0x39 */ public int commentId; [FieldOffset(61)] /* 0x3D */ public int templateId; [FieldOffset(65)] /* 0x41 */ public int conceptId; [FieldOffset(69)] /* 0x45 */ public byte unknownbyte19; [FieldOffset(70)] /* 0x46 */ public int unknown17; [FieldOffset(74)] /* 0x4A */ public int unknown18; [FieldOffset(78)] /* 0x4E */ public int unknown19; [FieldOffset(82)] /* 0x52 */ public int unknown20; [FieldOffset(86)] /* 0x56 */ public int unknown21; [FieldOffset(90)] /* 0x5A */ public int unknown22; [FieldOffset(94)] /* 0x5E */ public int unknown23; [FieldOffset(98)] /* 0x62 */ public int unknown24; [FieldOffset(102)] /* 0x66 */ public byte unknownbyte20; [FieldOffset(103)] /* 0x67 */ public fixed byte ordinal[5]; [FieldOffset(108)] /* 0x6C */ public byte unknownbyte21; [FieldOffset(109)] /* 0x6D */ public byte unknownbyte22; [FieldOffset(110)] /* 0x6E */ public int ElementNumber; [FieldOffset(114)] /* 0x72 */ public int unknown28; public static readonly int SizeOfElementsElem = Marshal.SizeOf(typeof(InfElementsElem17)); } }
29.858156
99
0.660333
[ "MIT" ]
kpence/SuperMemoAssistant
src/Core/SuperMemoAssistant.Core/SuperMemo/SuperMemo17/Files/InfElementsElem17.cs
4,212
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Day_18 { //Solves Advanced Math according ot AoC 2020 Day 18 part2. //Which is not actually how to do math. adjust operator priority to sensible values if resuing public static class AdvancedMath { public static double DoMath(string input) { var problem = StringToProblem(input); //Resolve the Parenthesis deepest first one at a time. while (DeepestNestedProblem(problem).Success) { var (_, start, length) = DeepestNestedProblem(problem); var result = ResolveProblem(problem.GetRange(start + 1, length - 1)); problem[start] = new MathElement(result); // replace the ( of the nested statement with the result of the problem problem.RemoveRange(start + 1, length);//remove everything past the opening ( from the list } //Resolve the final unparenthesized problem return ResolveProblem(problem); } //Resolve a problem in two steps first + and - then * and / //These are Advanced Math rules which does not obey real life math rules //Adjust these if re-using this code for other math problems public static double ResolveProblem(List<MathElement> problem) { problem = ResolveOperators(problem, new string[] { "+", "-" }); problem = ResolveOperators(problem, new string[] { "*", "/" }); if (problem.Count == 1) return problem[0].Value; throw new Exception("Symbols remaining after resolution."); } //Resolves only the provided operators private static List<MathElement> ResolveOperators(List<MathElement> problem, string[] operators) { for (var i = 0; i < problem.Count; i++) { var element = problem[i]; if (element.IsOperator && operators.Contains(element.Operator)) { var result = OperateOperators(problem[i - 1], element, problem[i + 1]); problem[i - 1] = new MathElement(result); problem.RemoveRange(i, 2); i--; } } return problem; } private static double OperateOperators(MathElement valA, MathElement op, MathElement valB) { return OperateOperators(valA.Value, op.Operator, valB.Value); } //Actually Do Math To Numbers private static double OperateOperators(double valA, string op, double valB) { switch (op) { case "+": return valA + valB; case "-": return valA - valB; case "*": return valA * valB; case "/": return valA / valB; default: throw new Exception($"Unknown operator {op}"); } } private static List<MathElement> StringToProblem(string input) { var problem = new List<MathElement>(); var number = ""; for (var i = 0; i < input.Length; i++) { //is it a digit or a ., remember it var symbol = input[i]; if (IsDigit(symbol) || symbol == '.') { number += symbol; } //is not a digit or a . then add any remember digits and. to the problem as a number and clear the remembered ones if (!(IsDigit(symbol) || symbol == '.') && !string.IsNullOrWhiteSpace(number)) { var element = new MathElement(number); problem.Add(element); number = ""; } //its not a digit or a . so it must be a symbol to add to the problem if (!(IsDigit(symbol) || symbol == '.') && !string.IsNullOrWhiteSpace(symbol.ToString())) { var element = new MathElement(symbol); problem.Add(element); } } //Trailing number if (!string.IsNullOrWhiteSpace(number)) { var element = new MathElement(number); problem.Add(element); } return problem; } public static string ProblemToString(List<MathElement> Problem) { var sb = new StringBuilder(); foreach (var element in Problem) { sb.Append(element); } return sb.ToString(); } private static (bool Success, int Start, int Length) DeepestNestedProblem(List<MathElement> Problem) { //empty problems don't have nesting if (Problem.Count == 0) { return (false, 0, 0); } var lastOpen = 0; for (int i = 0; i < Problem.Count; ++i) { var c = Problem[i]; if (c == '(') { lastOpen = i; } else if (c == ')') { return (true, lastOpen, i - lastOpen); } } //didn't find any, must not have any return (false, 0, 0); } private static bool IsDigit(char c) { return double.TryParse(c.ToString(), out _); } private static bool IsDigit(string s) { return double.TryParse(s, out _); } } }
32.446927
130
0.493457
[ "BSD-3-Clause" ]
Tzarnal/Advent-of-Code
2020 All Days, Every Day/Day 18/AdvancedMath.cs
5,810
C#
using EFCore.BulkExtensions.SqlAdapters; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace EFCore.BulkExtensions.Tests.IncludeGraph { public class RootEntity { public int Id { get; set; } public OwnedType Owned { get; set; } public OwnedInSeparateTable OwnedInSeparateTable { get; set; } } public class OwnedType { public int? ChildId { get; set; } public ChildEntity Child { get; set; } public string Field1 { get; set; } } public class OwnedInSeparateTable { public string Flowers { get; set; } } public class ChildEntity { public int Id { get; set; } public string Name { get; set; } } public class Issue547DbContext : DbContext { public Issue547DbContext([NotNullAttribute] DbContextOptions options) : base(options) { } public DbSet<RootEntity> RootEntities { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<RootEntity>(cfg => { cfg.HasKey(y => y.Id); cfg.OwnsOne(y => y.Owned, own => { own.HasOne(y => y.Child).WithMany().HasForeignKey(y => y.ChildId).IsRequired(false); own.Property(y => y.Field1).HasMaxLength(50); }); cfg.OwnsOne(y => y.OwnedInSeparateTable, own => { own.ToTable(nameof(OwnedInSeparateTable)); }); }); modelBuilder.Entity<ChildEntity>(cfg => { cfg.Property(y => y.Id).ValueGeneratedNever(); cfg.Property(y => y.Name); }); } } public class Issue547 : IDisposable { [Theory] [InlineData(DbServer.SqlServer)] public async Task Test(DbServer dbServer) { ContextUtil.DbServer = dbServer; using var db = new Issue547DbContext(ContextUtil.GetOptions<Issue547DbContext>(databaseName: $"{nameof(EFCoreBulkTest)}_Issue547")); await db.Database.EnsureCreatedAsync(); var tranches = new List<RootEntity> { new RootEntity { Id = 1, Owned = new OwnedType { Field1 = "F1", Child = new ChildEntity { Id = 1388, Name = "F1C1" } }, OwnedInSeparateTable = new OwnedInSeparateTable { Flowers = "Roses" } }, new RootEntity { Id = 2, Owned = new OwnedType { Field1 = "F2", Child = new ChildEntity { Id = 1234, Name = "F2C2" } }, OwnedInSeparateTable = new OwnedInSeparateTable { Flowers = "Tulips" } } }; await db.BulkInsertOrUpdateAsync(tranches, new BulkConfig { IncludeGraph = true }); foreach (var a in tranches) { Assert.True(a.Owned.ChildId.HasValue); } var rootEntities = await db.RootEntities .Include(y => y.OwnedInSeparateTable) .Include(y => y.Owned.Child) .ToListAsync(); foreach (var re in rootEntities) { Assert.NotNull(re.Owned); Assert.NotEmpty(re.Owned.Field1); Assert.NotNull(re.Owned.ChildId); Assert.NotNull(re.Owned.Child); Assert.NotEmpty(re.Owned.Child.Name); Assert.NotNull(re.OwnedInSeparateTable); Assert.NotEmpty(re.OwnedInSeparateTable.Flowers); } } public void Dispose() { using var db = new Issue547DbContext(ContextUtil.GetOptions<Issue547DbContext>(databaseName: $"{nameof(EFCoreBulkTest)}_Issue547")); db.Database.EnsureDeleted(); } } }
30.486486
144
0.505541
[ "MIT" ]
AKonyshev/EFCore.BulkExtensions
EFCore.BulkExtensions.Tests/IncludeGraph/Issue547.cs
4,514
C#
using FluentValidation; using luxclusif.order.application.UseCases.Order.CreateOrder; using luxclusif.order.domain.Validation; namespace luxclusif.order.webapi.Validators { public class CreateOrderInputValidator : AbstractValidator<CreateOrderInput> { public CreateOrderInputValidator() { RuleFor(x => x.Name) .NotEmpty() .WithMessage(ValidationConstant.RequiredParameter); RuleFor(x => x.Name) .Length(3,100) .WithMessage(ValidationConstant.RequiredParameter); } } }
28.333333
80
0.647059
[ "MIT" ]
lucashigor/luxclusif.order
luxclusif.order.webapi/Validators/CreateOrderInputValidator.cs
597
C#
using NeoCA.Application.Models.Cache; using NeoCA.Infrastructure.Cache; using NeoCA.Infrastructure.UnitTests.Mocks; using Microsoft.Extensions.Options; using Shouldly; using Xunit; namespace NeoCA.Infrastructure.UnitTests.Cache { public class MemoryCacheServiceTests { private readonly IOptions<CacheConfiguration> _cacheOptions; public MemoryCacheServiceTests() { _cacheOptions = Options.Create(new CacheConfiguration() { AbsoluteExpirationInHours = 1, SlidingExpirationInMinutes = 30 }); } [Fact] public void TryGet_Null_Value() { object expectedValue = null; var mockMemoryCahe = MemoryCacheMocks.GetMemoryCache(expectedValue); var service = new MemoryCacheService(mockMemoryCahe.Object, _cacheOptions); var result = service.TryGet("key", out expectedValue); result.ShouldBeOfType<bool>(); result.ShouldBe(false); } [Fact] public void TryGet_NotNull_Value() { object expectedValue = "value"; var mockMemoryCahe = MemoryCacheMocks.GetMemoryCache(expectedValue); var service = new MemoryCacheService(mockMemoryCahe.Object, _cacheOptions); var result = service.TryGet("key", out expectedValue); result.ShouldBeOfType<bool>(); result.ShouldBe(true); } [Fact] public void Set() { object expectedValue = "value"; var mockMemoryCahe = MemoryCacheMocks.GetMemoryCache(expectedValue); var service = new MemoryCacheService(mockMemoryCahe.Object, _cacheOptions); var result = service.Set("key", expectedValue); result.ShouldNotBeNull(); result.ShouldBeOfType<string>(); } [Fact] public void Remove() { object expectedValue = "value"; var mockMemoryCahe = MemoryCacheMocks.GetMemoryCache(expectedValue); var service = new MemoryCacheService(mockMemoryCahe.Object, _cacheOptions); Should.NotThrow(() => service.Remove("key")); } } }
31.111111
87
0.618304
[ "Apache-2.0" ]
NeoSOFT-Technologies/netcore-template
Content/test/NeoCA.Infrastructure.UnitTests/Cache/MemoryCacheServiceTests.cs
2,242
C#
using Xunit; namespace RomanNumerals.Tests { public class RomanNumeralsConverterTest { [Theory] [InlineData(1, "I")] [InlineData(2, "II")] [InlineData(3, "III")] [InlineData(4, "IV")] [InlineData(5, "V")] [InlineData(6, "VI")] [InlineData(7, "VII")] [InlineData(8, "VIII")] [InlineData(9, "IX")] [InlineData(10, "X")] [InlineData(39, "XXXIX")] [InlineData(50, "L")] [InlineData(100, "C")] [InlineData(207, "CCVII")] [InlineData(246, "CCXLVI")] [InlineData(1066, "MLXVI")] [InlineData(1776, "MDCCLXXVI")] [InlineData(1954, "MCMLIV")] [InlineData(1990, "MCMXC")] [InlineData(2014, "MMXIV")] [InlineData(2018, "MMXVIII")] public void WhenConvertingNumber_ShouldReturnRomanNumeral(int number, string expected) { var actual = RomanNumeralsConverter.Convert(number); Assert.Equal(expected, actual); } } }
27.944444
94
0.557654
[ "MIT" ]
amiyaaloke/roman-numerals
RomanNumerals.Tests/RomanNumeralsConverterTest.cs
1,006
C#
namespace System.Windows.Input { /// <summary> /// The delegate to use for handlers that receive StylusEventArgs. /// </summary> public delegate void StylusSystemGestureEventHandler(object sender, StylusSystemGestureEventArgs e); }
28.111111
104
0.727273
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/wpf/src/Core/CSharp/System/Windows/Input/Stylus/StylusSystemGestureEventHandler.cs
253
C#
using System; using System.Collections; using System.Diagnostics; namespace TypeLitePlus.TsModels { /// <summary> /// Represents a collection in the code model. /// </summary> [DebuggerDisplay("TsCollection - ItemsType={ItemsType}")] public class TsCollection : TsType { /// <summary> /// Gets or sets type of the items in the collection. /// </summary> /// <remarks> /// If the collection isn't strongly typed, the ItemsType property is initialized to TsType.Any. /// </remarks> public TsType ItemsType { get; set; } /// <summary> /// Gets or sets the dimension of the collection. /// </summary> public int Dimension { get; set; } /// <summary> /// Initializes a new instance of the TsCollection class with the specific CLR type. /// </summary> /// <param name="type">The CLR collection represented by this instance of the TsCollection.</param> public TsCollection(Type type) : base(type) { var enumerableType = TsType.GetEnumerableType(this.Type); if (enumerableType == this.Type) { this.ItemsType = TsType.Any; } else if (enumerableType != null) { this.ItemsType = TsType.Create(enumerableType); } else if (typeof(IEnumerable).IsAssignableFrom(this.Type)) { this.ItemsType = TsType.Any; } else { throw new ArgumentException(string.Format("The type '{0}' is not collection.", this.Type.FullName)); } this.Dimension = GetCollectionDimension(type); } private static int GetCollectionDimension(Type t) { Type enumerableUnderlying = null; if (t.IsArray) { return GetCollectionDimension(t.GetElementType()) + 1; } else if (t != typeof(string) && (enumerableUnderlying = GetEnumerableType(t)) != null) { if (enumerableUnderlying == t) { return 0; } return GetCollectionDimension(enumerableUnderlying) + 1; } else { return 0; } } } }
30.935897
116
0.523829
[ "MIT" ]
CloudNimble/TypeLitePlus
TypeLitePlus.Core/TsModels/TsCollection.cs
2,415
C#
using System; using System.Data; using System.Data.Common; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace LinqToDB.Data { #if !NOASYNC public partial class DataConnection { internal async Task InitCommandAsync(CommandType commandType, string sql, DataParameter[] parameters, CancellationToken cancellationToken) { if (_connection == null) _connection = DataProvider.CreateConnection(ConnectionString); if (_connection.State == ConnectionState.Closed) { await ((DbConnection)_connection).OpenAsync(cancellationToken); _closeConnection = true; } InitCommand(commandType, sql, parameters, null); } internal async Task<int> ExecuteNonQueryAsync(CancellationToken cancellationToken) { if (TraceSwitch.Level == TraceLevel.Off || OnTraceConnection == null) return await ((DbCommand)Command).ExecuteNonQueryAsync(cancellationToken); if (TraceSwitch.TraceInfo) { OnTraceConnection(new TraceInfo { BeforeExecute = true, TraceLevel = TraceLevel.Info, DataConnection = this, Command = Command, }); } try { var now = DateTime.Now; var ret = await ((DbCommand)Command).ExecuteNonQueryAsync(cancellationToken); if (TraceSwitch.TraceInfo) { OnTraceConnection(new TraceInfo { TraceLevel = TraceLevel.Info, DataConnection = this, Command = Command, ExecutionTime = DateTime.Now - now, RecordsAffected = ret, }); } return ret; } catch (Exception ex) { if (TraceSwitch.TraceError) { OnTraceConnection(new TraceInfo { TraceLevel = TraceLevel.Error, DataConnection = this, Command = Command, Exception = ex, }); } throw; } } internal async Task<DbDataReader> ExecuteReaderAsync(CommandBehavior commandBehavior, CancellationToken cancellationToken) { if (TraceSwitch.Level == TraceLevel.Off || OnTraceConnection == null) return await ((DbCommand)Command).ExecuteReaderAsync(commandBehavior, cancellationToken); if (TraceSwitch.TraceInfo) { OnTraceConnection(new TraceInfo { BeforeExecute = true, TraceLevel = TraceLevel.Info, DataConnection = this, Command = Command, }); } var now = DateTime.Now; try { var ret = await ((DbCommand)Command).ExecuteReaderAsync(cancellationToken); if (TraceSwitch.TraceInfo) { OnTraceConnection(new TraceInfo { TraceLevel = TraceLevel.Info, DataConnection = this, Command = Command, ExecutionTime = DateTime.Now - now, }); } return ret; } catch (Exception ex) { if (TraceSwitch.TraceError) { OnTraceConnection(new TraceInfo { TraceLevel = TraceLevel.Error, DataConnection = this, Command = Command, ExecutionTime = DateTime.Now - now, Exception = ex, }); } throw; } } } #endif }
23.507353
141
0.620269
[ "MIT" ]
codefox42/linq2db
Source/Data/DataConnection.Async.cs
3,199
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Rigidbody), typeof(SphereCollider))] public class Velcro : MonoBehaviour { [SerializeField] private Transform _partner; [SerializeField] private float _distance; [SerializeField] private float _distForLoose = 2.5f; [SerializeField] private float _speed = 4; public event Action<Transform> OnHoking; private Rigidbody _rb; private SphereCollider _sc; private Vector3 _newPosition; private bool _isDrag; void Start() { _rb = GetComponent<Rigidbody>(); _sc = GetComponent<SphereCollider>(); } private void Update() { transform.position = new Vector3(transform.position.x, transform.position.y, 0); if (_isDrag) { //back to the future is dedicated (-time != past) is zero transform.position = Vector3.Lerp(transform.position, _newPosition, Time.deltaTime * (_speed - _distance)); } } private void StartFalling() { _sc.enabled = false; } public void Hooking() { OnHoking?.Invoke(transform); _newPosition = transform.position; _isDrag = true; _rb.velocity = Vector3.zero; _rb.isKinematic = true; } public void DragShifting(Vector3 newPos) { _distance = (transform.position - _partner.position).magnitude; _distance += transform.localScale.x; //Size matters if (_distance > _distForLoose) StartFalling(); _newPosition = newPos; } public void Uncoupling() { _isDrag = false; _rb.isKinematic = false; } #if UNITY_EDITOR private void OnValidate() { gameObject.layer = 12; } #endif }
24.863014
119
0.63416
[ "MIT" ]
Dream-Wood/Climb-Up
Assets/Scripts/Velcro.cs
1,815
C#
namespace TidalUSDK.Constants { public class TidalNonces { public static string TokenAndroid = "kgsOOmYk3zShYrNP"; public static string ClientKey = "vjknfvjbnjhbgjhbbg"; } }
25.125
63
0.696517
[ "MIT" ]
SacredSkull/dotnet-tidal-usdk
TidalUSDK/Constants/TidalNonces.cs
201
C#
using System; using Eto.Gl; using Eto.Gl.Mac; using Ninject; using OpenTK; using SharpFlame.Infrastructure; namespace SharpFlame.Gui.Mac { public static class Startup { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] public static void Main(string[] args) { Toolkit.Init(); var p = Eto.Platform.Detect; p.Add<GLSurface.IHandler>( () => new MacGLSurfaceHandler() ); var kernel = Bootstrap.KernelWith(Eto.Platform.Instance); var app = new SharpFlameApplication(); app.Run(); } } }
22
70
0.557185
[ "MIT" ]
Warzone2100/SharpFlame
source/SharpFlame.Gui.Mac/Startup.cs
684
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Reactive; namespace Microsoft.Reactive.Testing { /// <summary> /// Observable sequence that records subscription lifetimes and timestamped notification messages sent to observers. /// </summary> /// <typeparam name="T">The type of the elements in the sequence.</typeparam> public interface ITestableObservable<T> : IObservable<T> { /// <summary> /// Gets a list of all the subscriptions to the observable sequence, including their lifetimes. /// </summary> IList<Subscription> Subscriptions { get; } /// <summary> /// Gets the recorded timestamped notification messages that were sent by the observable sequence to its observers. /// </summary> IList<Recorded<Notification<T>>> Messages { get; } } }
37.892857
123
0.690858
[ "MIT" ]
00mjk/reactive
Rx.NET/Source/src/Microsoft.Reactive.Testing/ITestObservable.cs
1,063
C#
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace SuperWorkerService { public class Worker : BackgroundService { private readonly ILogger<Worker> log; private readonly IHostApplicationLifetime appLifetime; private readonly IConfiguration config; private readonly ExtendedMethods exMethods; private readonly Tasks tasks; public Worker(ILogger<Worker> logger, IHostApplicationLifetime applicationLifetime, IConfiguration configuration, ExtendedMethods extendedMethods, Tasks tasks) { log = logger; appLifetime = applicationLifetime; config = configuration; exMethods = extendedMethods; this.tasks = tasks; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { Stopwatch runtime = new Stopwatch(); try { while (!stoppingToken.IsCancellationRequested) { await exMethods.ItIsTimeAsync().ConfigureAwait(false); log.LogDebug("Worker starts"); runtime.Restart(); await tasks.Task1().ConfigureAwait(false); runtime.Stop(); log.LogInformation("Worker completed, time of execution (s): {runetime}", runtime.Elapsed.TotalSeconds); } } catch (Exception ex) { log.LogCritical(ex, "Error in main worker."); } finally { appLifetime.StopApplication(); } } } /// /// To support database you need Dapper and some database connector like MySqlConnector /// Requirement: Dapper /// https://github.com/StackExchange/Dapper /// https://mysqlconnector.net/ /// /* public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null, bool buffered = true); public static IEnumerable<dynamic> Query (this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null, bool buffered = true); public static int Execute(this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null); var count = connection.Execute(@"insert MyTable(colA, colB) values (@a, @b)", new[] { new { a=1, b=1 }, new { a=2, b=2 }, new { a=3, b=3 } } ); */ }
35.413333
167
0.620105
[ "MIT" ]
m4rcelpl/SuperWorkerService
Worker.cs
2,656
C#
using UnrealBuildTool; using System.IO; public class OpenCV : ModuleRules { private string ThirdPartyPath { get { return Path.GetFullPath(Path.Combine(ModuleDirectory, "../../../../ThirdParty/")); } } public OpenCV(ReadOnlyTargetRules Target): base (Target) { PrivatePCHHeaderFile = "Private/OpenCVPrivatePCH.h"; // Startard Module Dependencies PublicDependencyModuleNames.AddRange(new string[] { "Core", "RHI", "RenderCore" }); PrivateDependencyModuleNames.AddRange(new string[] { "CoreUObject", "Engine", "Slate", "SlateCore" }); // Start OpenCV linking here! bool isLibrarySupported = false; // Create OpenCV Path string OpenCVPath = Path.Combine(ThirdPartyPath, "OpenCV"); // Get Library Path string LibPath = ""; bool isdebug = Target.Configuration == UnrealTargetConfiguration.Debug; // && BuildConfiguration.bDebugBuildsActuallyUseDebugCRT; if (Target.Platform == UnrealTargetPlatform.Win64) { LibPath = Path.Combine(OpenCVPath, "Libraries", "Win64"); isLibrarySupported = true; } else if (Target.Platform == UnrealTargetPlatform.Win32) { // TODO: add OpenCV binaries for Win32 } else if (Target.Platform == UnrealTargetPlatform.Mac) { // TODO: add OpenCV binaries for Mac } else if (Target.Platform == UnrealTargetPlatform.Linux) { // TODO: add OpenCV binaries for Linux } else { string Err = string.Format("{0} dedicated server is made to depend on {1}. We want to avoid this, please correct module dependencies.", Target.Platform.ToString(), this.ToString()); System.Console.WriteLine(Err); } if (isLibrarySupported) { //Add Include path PublicIncludePaths.AddRange(new string[] { Path.Combine(OpenCVPath, "Includes") }); // Add Library Path PublicLibraryPaths.Add(LibPath); //Add Static Libraries PublicAdditionalLibraries.Add("opencv_world411.lib"); //Add Dynamic Libraries PublicDelayLoadDLLs.Add("opencv_world411.dll"); PublicDelayLoadDLLs.Add("opencv_videoio_ffmpeg411_64.dll"); } PublicDefinitions.Add(string.Format("WITH_OPENCV_BINDING={0}", isLibrarySupported ? 1 : 0)); } }
34.942857
224
0.623467
[ "MIT" ]
alloy-city/AViS
Plugins/OpenCV/Source/OpenCV/OpenCV.Build.cs
2,446
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace MiniORM.App.Data.Entities { public class EmployeeProject { [Key] [ForeignKey(nameof(Employee))] public int EmployeeId { get; set; } [Key] [ForeignKey(nameof(Project))] public int ProjectId { get; set; } public Employee Employee {get; set;} public Project Project { get; set; } } }
21.8
51
0.649541
[ "MIT" ]
StefanLB/Databases-Advanced---Entity-Framework---February-2019
02. DB-Advanced-ORM-Fundamentals/MiniORM.App/Data/Entities/EmployeeProject.cs
547
C#
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DynamicObjectTracking")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ESRI")] [assembly: AssemblyProduct("DynamicObjectTracking")] [assembly: AssemblyCopyright("Copyright ESRI 2006")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(true)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5b193f0e-5858-43e3-aab2-d75e92509ef1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
36.37037
84
0.750509
[ "Apache-2.0" ]
Esri/arcobjects-sdk-community-samples
Net/GraphicsPipeline/DynamicObjectTracking/CSharp/Properties/AssemblyInfo.cs
1,964
C#
using System; namespace StrongBeaver.Core.Exceptions { public class CoreException : Exception { public CoreException() : base() { // No operation } public CoreException(string message) : base(message) { // No operation } public CoreException(string message, Exception innerException) : base(message, innerException) { // No operation } } }
19.96
70
0.517034
[ "MIT" ]
akobr/strong-beaver
StrongBeaver.Core/Exceptions/CoreException.cs
501
C#
namespace NeuralNet.NeuralNet { public class Dendrite { public double Weight { get; set; } public Dendrite() { CryptoRandom n = new CryptoRandom(); this.Weight = n.RandomValue; } } }
16.933333
48
0.527559
[ "MIT" ]
BBlum16/NNC
C#/NeuralNetwork/NeuralNet/Dendrite.cs
256
C#
using CinemaDirector.Helpers; using System.Collections.Generic; #if UNITY_EDITOR using UnityEditor; #endif using UnityEngine.UI; using UnityEngine; namespace CinemaDirector { [CutsceneItemAttribute("uGUI", "Text Remover", CutsceneItemGenre.ActorItem)] public class TextDegenerationEvent : CinemaActorAction, IRevertable { string textValue; // Options for reverting in editor. [SerializeField] private RevertMode editorRevertMode = RevertMode.Revert; // Options for reverting during runtime. [SerializeField] private RevertMode runtimeRevertMode = RevertMode.Revert; /// <summary> /// Cache the state of all actors related to this event. /// </summary> /// <returns></returns> public RevertInfo[] CacheState() { List<Transform> actors = new List<Transform>(GetActors()); List<RevertInfo> reverts = new List<RevertInfo>(); for (int i = 0; i < actors.Count; i++) { Transform go = actors[i]; if (go != null) { Text txt = go.GetComponentInChildren<Text>(); if (txt != null) { reverts.Add(new RevertInfo(this, txt, "text", txt.text)); } } } return reverts.ToArray(); } public override void Trigger(GameObject actor) { textValue= actor.GetComponentInChildren<Text>().text; } public override void SetTime(GameObject actor, float time, float deltaTime) { if (actor != null) if (time > 0 && time <= Duration) UpdateTime(actor, time, deltaTime); } public override void UpdateTime(GameObject actor, float runningTime, float deltaTime) { float transition = runningTime / Duration; int numericalValue; if (textValue!=null) { numericalValue = (int)Mathf.Round(Mathf.Lerp(textValue.Length,0, transition)); actor.GetComponentInChildren<Text>().text = textValue.Substring(0, numericalValue); #if UNITY_EDITOR EditorUtility.SetDirty(actor.GetComponentInChildren<Text>()); #endif } } public override void End(GameObject actor) { actor.GetComponentInChildren<Text>().text = ""; #if UNITY_EDITOR EditorUtility.SetDirty(actor.GetComponentInChildren<Text>()); #endif } /// <summary> /// Option for choosing when this Event will Revert to initial state in Editor. /// </summary> public RevertMode EditorRevertMode { get { return editorRevertMode; } set { editorRevertMode = value; } } /// <summary> /// Option for choosing when this Event will Revert to initial state in Runtime. /// </summary> public RevertMode RuntimeRevertMode { get { return runtimeRevertMode; } set { runtimeRevertMode = value; } } } }
31.882353
99
0.555043
[ "MIT" ]
Bennef/BIP
Assets/3rd Party Assets/Cinema Suite/Cinema Director/Cutscene Items/Actor Items/uGUI/TextDegenerationEvent.cs
3,254
C#
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; using MonoTouch.NUnit.UI; namespace Couchbase.Lite.iOS.Tests { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("UnitTestAppDelegate")] public partial class UnitTestAppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; TouchRunner runner; // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching (UIApplication app, NSDictionary options) { //Couchbase.Lite.Storage.SystemSQLite.Dummy.DoDummy(); // create a new window instance based on the screen size window = new UIWindow (UIScreen.MainScreen.Bounds); runner = new TouchRunner (window); // register every tests included in the main application/assembly runner.Add (System.Reflection.Assembly.GetExecutingAssembly ()); window.RootViewController = new UINavigationController (runner.GetViewController ()); // make the window visible window.MakeKeyAndVisible (); return true; } } }
34.55102
98
0.658004
[ "Apache-2.0" ]
APXLabs/couchbase-lite-net
src/Couchbase.Lite.iOS.Tests/UnitTestAppDelegate.cs
1,695
C#
using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Bitbucket.Cloud.Net.Common.Models; using Bitbucket.Cloud.Net.Models.v2; using Flurl.Http; // ReSharper disable once CheckNamespace namespace Bitbucket.Cloud.Net { public partial class BitbucketCloudClient { private IFlurlRequest GetDownloadsUrl(string workspaceId, string repositorySlug) => GetBaseUrl($"2.0/repositories/{workspaceId}/{repositorySlug}/downloads"); private IFlurlRequest GetDownloadsUrl(string workspaceId, string repositorySlug, string path) => GetDownloadsUrl(workspaceId, repositorySlug) .AppendPathSegment(path); public async Task<bool> CreateRepositoryDownloadAsync(string workspaceId, string repositorySlug, string fileName) { var response = await GetDownloadsUrl(workspaceId, repositorySlug) .PostMultipartAsync(content => content.AddFile(Path.GetFileName(fileName), fileName)) .ConfigureAwait(false); return await HandleResponseAsync(response).ConfigureAwait(false); } public async Task<IEnumerable<Download>> GetRepositoryDownloadsAsync(string workspaceId, string repositorySlug, int? maxPages = null) { var queryParamValues = new Dictionary<string, object>(); return await GetPagedResultsAsync(maxPages, queryParamValues, async qpv => await GetDownloadsUrl(workspaceId, repositorySlug) .SetQueryParams(qpv) .GetJsonAsync<PagedResults<Download>>() .ConfigureAwait(false)) .ConfigureAwait(false); } public async Task<string> GetRepositoryDownloadAsync(string workspaceId, string repositorySlug, string fileName, string localFolderPath) { return await GetDownloadsUrl(workspaceId, repositorySlug, fileName) .DownloadFileAsync(localFolderPath) .ConfigureAwait(false); } public async Task<bool> DeleteRepositoryDownloadAsync(string workspaceId, string repositorySlug, string fileName) { var response = await GetDownloadsUrl(workspaceId, repositorySlug, fileName) .DeleteAsync() .ConfigureAwait(false); return await HandleResponseAsync(response).ConfigureAwait(false); } } }
37.553571
159
0.783642
[ "MIT" ]
Bob343/Bitbucket.Cloud.Net
src/Bitbucket.Cloud.Net/v2/Repositories/Downloads/BitbucketCloudClient.cs
2,105
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Localization.Internal { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using DotNetNuke.Common; using DotNetNuke.Entities.Portals; internal class LocalizationImpl : ILocalization { /// <inheritdoc/> public string BestCultureCodeBasedOnBrowserLanguages(IEnumerable<string> cultureCodes, string fallback) { if (cultureCodes == null) { throw new ArgumentException("cultureCodes cannot be null"); } if (fallback == null) { throw new ArgumentException("fallback cannot be null"); } var values = cultureCodes.ToList(); foreach (string langHeader in HttpContextSource.Current.Request.UserLanguages ?? new string[0]) { string lang = langHeader; // strip any ;q=xx lang = lang.Split(';')[0]; // check for exact match e.g. de-DE == de-DE if (lang.Contains('-')) { var match = values.FirstOrDefault(x => x == lang); if (match != null) { return match; } } // only keep the initial language value if (lang.Length > 1) { lang = lang.Substring(0, 2); // check for language match e.g. en-GB == en-US because en == en var match = values.FirstOrDefault(x => x.StartsWith(lang)); if (match != null) { return match; } } } return fallback; } /// <inheritdoc/> public string BestCultureCodeBasedOnBrowserLanguages(IEnumerable<string> cultureCodes) { return this.BestCultureCodeBasedOnBrowserLanguages(cultureCodes, Localization.SystemLocale); } /// <inheritdoc/> public CultureInfo GetPageLocale(PortalSettings portalSettings) { return Localization.GetPageLocale(portalSettings); } /// <inheritdoc/> public void SetThreadCultures(CultureInfo cultureInfo, PortalSettings portalSettings) { Localization.SetThreadCultures(cultureInfo, portalSettings); } } }
31.952941
111
0.539396
[ "MIT" ]
Mariusz11711/DNN
DNN Platform/Library/Services/Localization/Internal/LocalizationImpl.cs
2,718
C#
using System; using System.Collections.Generic; using System.Text; using Timereporter.Core.Models; namespace Timereporter.Core.Collections { public interface ITimes : IDictionary<string, ITime> { } }
18
54
0.74537
[ "MIT" ]
SpellarBot/TimeReporter
Timereporter.Core/Collections/ITimes.cs
218
C#
using System; using System.Collections.Generic; using System.Numerics; using System.Threading.Tasks; using Uno.Disposables; using Uno.Extensions; using Uno.UI.Helpers.WinUI; using Windows.Devices.Input; using Windows.Foundation; using Windows.System; using Windows.System.Threading; using Windows.UI; using Windows.UI.Core; using Windows.UI.Input; using Windows.UI.Xaml; using Windows.UI.Xaml.Automation.Peers; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Shapes; namespace Microsoft.UI.Xaml.Controls.Primitives { public partial class ColorSpectrum : Control { private bool m_updatingColor; private bool m_updatingHsvColor; private bool m_isPointerOver; private bool m_isPointerPressed; private bool m_shouldShowLargeSelection; private List<Hsv> m_hsvValues = new List<Hsv>(); // Uno Doc: Set an instance unlike WinUI // XAML elements private Grid m_layoutRoot; private Grid m_sizingGrid; private Rectangle m_spectrumRectangle; private Ellipse m_spectrumEllipse; private Rectangle m_spectrumOverlayRectangle; private Ellipse m_spectrumOverlayEllipse; private FrameworkElement m_inputTarget; private Panel m_selectionEllipsePanel; private ToolTip m_colorNameToolTip; private IAsyncAction m_createImageBitmapAction; // On RS1 and before, we put the spectrum images in a bitmap, // which we then give to an ImageBrush. private WriteableBitmap m_hueRedBitmap; private WriteableBitmap m_hueYellowBitmap; private WriteableBitmap m_hueGreenBitmap; private WriteableBitmap m_hueCyanBitmap; private WriteableBitmap m_hueBlueBitmap; private WriteableBitmap m_huePurpleBitmap; private WriteableBitmap m_saturationMinimumBitmap; private WriteableBitmap m_saturationMaximumBitmap; private WriteableBitmap m_valueBitmap; // On RS2 and later, we put the spectrum images in a loaded image surface, // which we then put into a SpectrumBrush. // Uno Doc: SpectrumBrush is disabled for now //private LoadedImageSurface m_hueRedSurface; //private LoadedImageSurface m_hueYellowSurface; //private LoadedImageSurface m_hueGreenSurface; //private LoadedImageSurface m_hueCyanSurface; //private LoadedImageSurface m_hueBlueSurface; //private LoadedImageSurface m_huePurpleSurface; //private LoadedImageSurface m_saturationMinimumSurface; //private LoadedImageSurface m_saturationMaximumSurface; //private LoadedImageSurface m_valueSurface; // Fields used by UpdateEllipse() to ensure that it's using the data // associated with the last call to CreateBitmapsAndColorMap(), // in order to function properly while the asynchronous bitmap creation // is in progress. private ColorSpectrumShape m_shapeFromLastBitmapCreation = ColorSpectrumShape.Box; private ColorSpectrumComponents m_componentsFromLastBitmapCreation = ColorSpectrumComponents.HueSaturation; private double m_imageWidthFromLastBitmapCreation = 0.0; private double m_imageHeightFromLastBitmapCreation = 0.0; private int m_minHueFromLastBitmapCreation = 0; private int m_maxHueFromLastBitmapCreation = 0; private int m_minSaturationFromLastBitmapCreation = 0; private int m_maxSaturationFromLastBitmapCreation = 0; private int m_minValueFromLastBitmapCreation = 0; private int m_maxValueFromLastBitmapCreation = 0; private Color m_oldColor = Color.FromArgb(255, 255, 255, 255); private Vector4 m_oldHsvColor = new Vector4(0.0f, 0.0f, 1.0f, 1.0f); // Uno Doc: Added to dispose event handlers private SerialDisposable _eventSubscriptions = new SerialDisposable(); public ColorSpectrum() { SetDefaultStyleKey(this); m_updatingColor = false; m_updatingHsvColor = false; m_isPointerOver = false; m_isPointerPressed = false; m_shouldShowLargeSelection = false; m_shapeFromLastBitmapCreation = this.Shape; m_componentsFromLastBitmapCreation = this.Components; m_imageWidthFromLastBitmapCreation = 0; m_imageHeightFromLastBitmapCreation = 0; m_minHueFromLastBitmapCreation = this.MinHue; m_maxHueFromLastBitmapCreation = this.MaxHue; m_minSaturationFromLastBitmapCreation = this.MinSaturation; m_maxSaturationFromLastBitmapCreation = this.MaxSaturation; m_minValueFromLastBitmapCreation = this.MinValue; m_maxValueFromLastBitmapCreation = this.MaxValue; Unloaded += OnUnloaded; if (SharedHelpers.IsRS1OrHigher()) { IsFocusEngagementEnabled = true; } } // IUIElementOverridesHelper overrides protected override AutomationPeer OnCreateAutomationPeer() { return new ColorSpectrumAutomationPeer(this); } // IFrameworkElementOverrides overrides protected override void OnApplyTemplate() { // Uno Doc: Added to dispose event handlers _eventSubscriptions.Disposable = null; var registrations = new CompositeDisposable(); m_layoutRoot = GetTemplateChild<Grid>("LayoutRoot"); m_sizingGrid = GetTemplateChild<Grid>("SizingGrid"); m_spectrumRectangle = GetTemplateChild<Rectangle>("SpectrumRectangle"); m_spectrumEllipse = GetTemplateChild<Ellipse>("SpectrumEllipse"); m_spectrumOverlayRectangle = GetTemplateChild<Rectangle>("SpectrumOverlayRectangle"); m_spectrumOverlayEllipse = GetTemplateChild<Ellipse>("SpectrumOverlayEllipse"); m_inputTarget = GetTemplateChild<FrameworkElement>("InputTarget"); m_selectionEllipsePanel = GetTemplateChild<Panel>("SelectionEllipsePanel"); m_colorNameToolTip = GetTemplateChild<ToolTip>("ColorNameToolTip"); if (m_layoutRoot is Grid layoutRoot) { layoutRoot.SizeChanged += OnLayoutRootSizeChanged; registrations.Add(() => layoutRoot.SizeChanged -= OnLayoutRootSizeChanged); } if (m_inputTarget is FrameworkElement inputTarget) { inputTarget.PointerEntered += OnInputTargetPointerEntered; inputTarget.PointerExited += OnInputTargetPointerExited; inputTarget.PointerPressed += OnInputTargetPointerPressed; inputTarget.PointerMoved += OnInputTargetPointerMoved; inputTarget.PointerReleased += OnInputTargetPointerReleased; registrations.Add(() => inputTarget.PointerEntered -= OnInputTargetPointerEntered); registrations.Add(() => inputTarget.PointerExited -= OnInputTargetPointerExited); registrations.Add(() => inputTarget.PointerPressed -= OnInputTargetPointerPressed); registrations.Add(() => inputTarget.PointerMoved -= OnInputTargetPointerMoved); registrations.Add(() => inputTarget.PointerReleased -= OnInputTargetPointerReleased); } if (DownlevelHelper.ToDisplayNameExists()) { if (m_colorNameToolTip is ToolTip colorNameToolTip) { colorNameToolTip.Content = ColorHelper.ToDisplayName(this.Color); } } if (m_selectionEllipsePanel is Panel selectionEllipsePanel) { selectionEllipsePanel.RegisterPropertyChangedCallback(FrameworkElement.FlowDirectionProperty, OnSelectionEllipseFlowDirectionChanged); } // If we haven't yet created our bitmaps, do so now. if (m_hsvValues.Count == 0) { CreateBitmapsAndColorMap(); } UpdateEllipse(); UpdateVisualState(useTransitions: false); // Uno Doc: Added to dispose event handlers _eventSubscriptions.Disposable = registrations; } // IControlOverrides overrides protected override void OnKeyDown(KeyRoutedEventArgs args) { if (args.Key != VirtualKey.Left && args.Key != VirtualKey.Right && args.Key != VirtualKey.Up && args.Key != VirtualKey.Down) { base.OnKeyDown(args); return; } // Uno Doc: Window must be fully qualified for iOS/macOS where NSWindow maps to Window bool isControlDown = (Windows.UI.Xaml.Window.Current.CoreWindow.GetKeyState(VirtualKey.Control) & CoreVirtualKeyStates.Down) == CoreVirtualKeyStates.Down; ColorPickerHsvChannel incrementChannel = ColorPickerHsvChannel.Hue; if (args.Key == VirtualKey.Left || args.Key == VirtualKey.Right) { switch (this.Components) { case ColorSpectrumComponents.HueSaturation: case ColorSpectrumComponents.HueValue: incrementChannel = ColorPickerHsvChannel.Hue; break; case ColorSpectrumComponents.SaturationHue: case ColorSpectrumComponents.SaturationValue: incrementChannel = ColorPickerHsvChannel.Saturation; break; case ColorSpectrumComponents.ValueHue: case ColorSpectrumComponents.ValueSaturation: incrementChannel = ColorPickerHsvChannel.Value; break; } } else if (args.Key == VirtualKey.Up || args.Key == VirtualKey.Down) { switch (this.Components) { case ColorSpectrumComponents.SaturationHue: case ColorSpectrumComponents.ValueHue: incrementChannel = ColorPickerHsvChannel.Hue; break; case ColorSpectrumComponents.HueSaturation: case ColorSpectrumComponents.ValueSaturation: incrementChannel = ColorPickerHsvChannel.Saturation; break; case ColorSpectrumComponents.HueValue: case ColorSpectrumComponents.SaturationValue: incrementChannel = ColorPickerHsvChannel.Value; break; } } double minBound = 0.0; double maxBound = 0.0; switch (incrementChannel) { case ColorPickerHsvChannel.Hue: minBound = this.MinHue; maxBound = this.MaxHue; break; case ColorPickerHsvChannel.Saturation: minBound = this.MinSaturation; maxBound = this.MaxSaturation; break; case ColorPickerHsvChannel.Value: minBound = this.MinValue; maxBound = this.MaxValue; break; } // The order of saturation and value in the spectrum is reversed - the max value is at the bottom while the min value is at the top - // so we want left and up to be lower for hue, but higher for saturation and value. // This will ensure that the icon always moves in the direction of the key press. ColorHelpers.IncrementDirection direction = (incrementChannel == ColorPickerHsvChannel.Hue && (args.Key == VirtualKey.Left || args.Key == VirtualKey.Up)) || (incrementChannel != ColorPickerHsvChannel.Hue && (args.Key == VirtualKey.Right || args.Key == VirtualKey.Down)) ? ColorHelpers.IncrementDirection.Lower : ColorHelpers.IncrementDirection.Higher; ColorHelpers.IncrementAmount amount = isControlDown ? ColorHelpers.IncrementAmount.Large : ColorHelpers.IncrementAmount.Small; Vector4 hsvColor = this.HsvColor; UpdateColor(ColorHelpers.IncrementColorChannel(new Hsv(Hsv.GetHue(hsvColor), Hsv.GetSaturation(hsvColor), Hsv.GetValue(hsvColor)), incrementChannel, direction, amount, true /* shouldWrap */, minBound, maxBound)); args.Handled = true; } protected override void OnGotFocus(RoutedEventArgs e) { // We only want to bother with the color name tool tip if we can provide color names. if (m_colorNameToolTip is ToolTip colorNameToolTip) { if (DownlevelHelper.ToDisplayNameExists()) { colorNameToolTip.IsOpen = true; } } UpdateVisualState(useTransitions: true); } protected override void OnLostFocus(RoutedEventArgs e) { // We only want to bother with the color name tool tip if we can provide color names. if (m_colorNameToolTip is ToolTip colorNameToolTip) { if (DownlevelHelper.ToDisplayNameExists()) { colorNameToolTip.IsOpen = false; } } UpdateVisualState(useTransitions: true); } // Property changed handler. private void OnPropertyChanged(DependencyPropertyChangedEventArgs args) { DependencyProperty property = args.Property; if (property == ColorProperty) { OnColorChanged(args); } else if (property == HsvColorProperty) { OnHsvColorChanged(args); } else if ( property == MinHueProperty || property == MaxHueProperty) { OnMinMaxHueChanged(args); } else if ( property == MinSaturationProperty || property == MaxSaturationProperty) { OnMinMaxSaturationChanged(args); } else if ( property == MinValueProperty || property == MaxValueProperty) { OnMinMaxValueChanged(args); } else if (property == ShapeProperty) { OnShapeChanged(args); } else if (property == ComponentsProperty) { OnComponentsChanged(args); } } // DependencyProperty changed event handlers private void OnColorChanged(DependencyPropertyChangedEventArgs args) { // If we're in the process of internally updating the color, then we don't want to respond to the Color property changing. if (!m_updatingColor) { Color color = this.Color; m_updatingHsvColor = true; Hsv newHsv = ColorConversion.RgbToHsv(new Rgb(color.R / 255.0, color.G / 255.0, color.B / 255.0)); this.HsvColor = new Vector4((float)newHsv.H, (float)newHsv.S, (float)newHsv.V, (float)(color.A / 255.0)); m_updatingHsvColor = false; UpdateEllipse(); UpdateBitmapSources(); } m_oldColor = (Color)args.OldValue; } private void OnHsvColorChanged(DependencyPropertyChangedEventArgs args) { // If we're in the process of internally updating the HSV color, then we don't want to respond to the HsvColor property changing. if (!m_updatingHsvColor) { SetColor(); } m_oldHsvColor = (Vector4)args.OldValue; } private void SetColor() { Vector4 hsvColor = this.HsvColor; m_updatingColor = true; Rgb newRgb = ColorConversion.HsvToRgb(new Hsv(Hsv.GetHue(hsvColor), Hsv.GetSaturation(hsvColor), Hsv.GetValue(hsvColor))); this.Color = ColorConversion.ColorFromRgba(newRgb, Hsv.GetAlpha(hsvColor)); m_updatingColor = false; UpdateEllipse(); UpdateBitmapSources(); RaiseColorChanged(); } public void RaiseColorChanged() { Color newColor = this.Color; if (m_oldColor.A != newColor.A || m_oldColor.R != newColor.R || m_oldColor.G != newColor.G || m_oldColor.B != newColor.B) { var colorChangedEventArgs = new ColorChangedEventArgs(); colorChangedEventArgs.OldColor = m_oldColor; colorChangedEventArgs.NewColor = newColor; this.ColorChanged?.Invoke(this, colorChangedEventArgs); if (DownlevelHelper.ToDisplayNameExists()) { if (m_colorNameToolTip is ToolTip colorNameToolTip) { colorNameToolTip.Content = ColorHelper.ToDisplayName(newColor); } } var peer = FrameworkElementAutomationPeer.FromElement(this); if (peer != null) { ColorSpectrumAutomationPeer colorSpectrumPeer = peer as ColorSpectrumAutomationPeer; colorSpectrumPeer.RaisePropertyChangedEvent(m_oldColor, newColor, m_oldHsvColor, this.HsvColor); } } } protected void OnMinMaxHueChanged(DependencyPropertyChangedEventArgs args) { int minHue = this.MinHue; int maxHue = this.MaxHue; if (minHue < 0 || minHue > 359) { throw new ArgumentException("MinHue must be between 0 and 359."); } else if (maxHue < 0 || maxHue > 359) { throw new ArgumentException("MaxHue must be between 0 and 359."); } ColorSpectrumComponents components = this.Components; // If hue is one of the axes in the spectrum bitmap, then we'll need to regenerate it // if the maximum or minimum value has changed. if (components != ColorSpectrumComponents.SaturationValue && components != ColorSpectrumComponents.ValueSaturation) { CreateBitmapsAndColorMap(); } } protected void OnMinMaxSaturationChanged(DependencyPropertyChangedEventArgs args) { int minSaturation = this.MinSaturation; int maxSaturation = this.MaxSaturation; if (minSaturation < 0 || minSaturation > 100) { throw new ArgumentException("MinSaturation must be between 0 and 100."); } else if (maxSaturation < 0 || maxSaturation > 100) { throw new ArgumentException("MaxSaturation must be between 0 and 100."); } ColorSpectrumComponents components = this.Components; // If value is one of the axes in the spectrum bitmap, then we'll need to regenerate it // if the maximum or minimum value has changed. if (components != ColorSpectrumComponents.HueValue && components != ColorSpectrumComponents.ValueHue) { CreateBitmapsAndColorMap(); } } private void OnMinMaxValueChanged(DependencyPropertyChangedEventArgs args) { int minValue = this.MinValue; int maxValue = this.MaxValue; if (minValue < 0 || minValue > 100) { throw new ArgumentException("MinValue must be between 0 and 100."); } else if (maxValue < 0 || maxValue > 100) { throw new ArgumentException("MaxValue must be between 0 and 100."); } ColorSpectrumComponents components = this.Components; // If value is one of the axes in the spectrum bitmap, then we'll need to regenerate it // if the maximum or minimum value has changed. if (components != ColorSpectrumComponents.HueSaturation && components != ColorSpectrumComponents.SaturationHue) { CreateBitmapsAndColorMap(); } } private void OnShapeChanged(DependencyPropertyChangedEventArgs args) { CreateBitmapsAndColorMap(); } private void OnComponentsChanged(DependencyPropertyChangedEventArgs args) { CreateBitmapsAndColorMap(); } private void OnUnloaded(object sender, RoutedEventArgs args) { // If we're in the middle of creating an image bitmap while being unloaded, // we'll want to synchronously cancel it so we don't have any asynchronous actions // lingering beyond our lifetime. ColorHelpers.CancelAsyncAction(m_createImageBitmapAction); // Uno Doc: Added to dispose event handlers _eventSubscriptions.Disposable = null; } public Rect GetBoundingRectangle() { Rect localRect = new Rect(0, 0, 0, 0); if (m_inputTarget is FrameworkElement inputTarget) { localRect.Width = inputTarget.ActualWidth; localRect.Height = inputTarget.ActualHeight; } var globalBounds = TransformToVisual(null).TransformBounds(localRect); return SharedHelpers.ConvertDipsToPhysical(this, globalBounds); } new private void UpdateVisualState(bool useTransitions) { if (m_isPointerPressed) { VisualStateManager.GoToState(this, m_shouldShowLargeSelection ? "PressedLarge" : "Pressed", useTransitions); } else if (m_isPointerOver) { VisualStateManager.GoToState(this, "PointerOver", useTransitions); } else { VisualStateManager.GoToState(this, "Normal", useTransitions); } VisualStateManager.GoToState(this, m_shapeFromLastBitmapCreation == ColorSpectrumShape.Box ? "BoxSelected" : "RingSelected", useTransitions); VisualStateManager.GoToState(this, SelectionEllipseShouldBeLight() ? "SelectionEllipseLight" : "SelectionEllipseDark", useTransitions); if (this.IsEnabled && this.FocusState != FocusState.Unfocused) { if (this.FocusState == FocusState.Pointer) { VisualStateManager.GoToState(this, "PointerFocused", useTransitions); } else { VisualStateManager.GoToState(this, "Focused", useTransitions); } } else { VisualStateManager.GoToState(this, "Unfocused", useTransitions); } } private void UpdateColor(Hsv newHsv) { m_updatingColor = true; m_updatingHsvColor = true; Rgb newRgb = ColorConversion.HsvToRgb(newHsv); float alpha = Hsv.GetAlpha(this.HsvColor); this.Color = ColorConversion.ColorFromRgba(newRgb, alpha); this.HsvColor = new Vector4((float)newHsv.H, (float)newHsv.S, (float)newHsv.V, alpha); UpdateEllipse(); UpdateVisualState(useTransitions: true); m_updatingHsvColor = false; m_updatingColor = false; RaiseColorChanged(); } private void UpdateColorFromPoint(PointerPoint point) { // If we haven't initialized our HSV value array yet, then we should just ignore any user input - // we don't yet know what to do with it. if (m_hsvValues.Count == 0) { return; } double xPosition = point.Position.X; double yPosition = point.Position.Y; double radius = Math.Min(m_imageWidthFromLastBitmapCreation, m_imageHeightFromLastBitmapCreation) / 2; double distanceFromRadius = Math.Sqrt(Math.Pow(xPosition - radius, 2) + Math.Pow(yPosition - radius, 2)); var shape = this.Shape; // If the point is outside the circle, we should bring it back into the circle. if (distanceFromRadius > radius && shape == ColorSpectrumShape.Ring) { xPosition = (radius / distanceFromRadius) * (xPosition - radius) + radius; yPosition = (radius / distanceFromRadius) * (yPosition - radius) + radius; } // Now we need to find the index into the array of HSL values at each point in the spectrum m_image. int x = (int)Math.Round(xPosition); int y = (int)Math.Round(yPosition); int width = (int)Math.Round(m_imageWidthFromLastBitmapCreation); if (x < 0) { x = 0; } else if (x >= m_imageWidthFromLastBitmapCreation) { x = (int)Math.Round(m_imageWidthFromLastBitmapCreation) - 1; } if (y < 0) { y = 0; } else if (y >= m_imageHeightFromLastBitmapCreation) { y = (int)Math.Round(m_imageHeightFromLastBitmapCreation) - 1; } // The gradient image contains two dimensions of HSL information, but not the third. // We should keep the third where it already was. // Uno Doc: This can sometimes cause a crash -- possibly due to differences in c# rounding. Therefore, index is now clamped. Hsv hsvAtPoint = m_hsvValues[MathEx.Clamp((y * width + x), 0, m_hsvValues.Count - 1)]; var components = this.Components; var hsvColor = this.HsvColor; switch (components) { case ColorSpectrumComponents.HueValue: case ColorSpectrumComponents.ValueHue: hsvAtPoint.S = Hsv.GetSaturation(hsvColor); break; case ColorSpectrumComponents.HueSaturation: case ColorSpectrumComponents.SaturationHue: hsvAtPoint.V = Hsv.GetValue(hsvColor); break; case ColorSpectrumComponents.ValueSaturation: case ColorSpectrumComponents.SaturationValue: hsvAtPoint.H = Hsv.GetHue(hsvColor); break; } UpdateColor(hsvAtPoint); } private void UpdateEllipse() { var selectionEllipsePanel = m_selectionEllipsePanel; if (selectionEllipsePanel == null) { return; } // If we don't have an image size yet, we shouldn't be showing the ellipse. if (m_imageWidthFromLastBitmapCreation == 0 || m_imageHeightFromLastBitmapCreation == 0) { selectionEllipsePanel.Visibility = Visibility.Collapsed; return; } else { selectionEllipsePanel.Visibility = Visibility.Visible; } double xPosition; double yPosition; Vector4 hsvColor = this.HsvColor; Hsv.SetHue(hsvColor, MathEx.Clamp(Hsv.GetHue(hsvColor), (float)m_minHueFromLastBitmapCreation, (float)m_maxHueFromLastBitmapCreation)); Hsv.SetSaturation(hsvColor, MathEx.Clamp(Hsv.GetSaturation(hsvColor), m_minSaturationFromLastBitmapCreation / 100.0f, m_maxSaturationFromLastBitmapCreation / 100.0f)); Hsv.SetValue(hsvColor, MathEx.Clamp(Hsv.GetValue(hsvColor), m_minValueFromLastBitmapCreation / 100.0f, m_maxValueFromLastBitmapCreation / 100.0f)); if (m_shapeFromLastBitmapCreation == ColorSpectrumShape.Box) { double xPercent = 0; double yPercent = 0; double hPercent = (Hsv.GetHue(hsvColor) - m_minHueFromLastBitmapCreation) / (m_maxHueFromLastBitmapCreation - m_minHueFromLastBitmapCreation); double sPercent = (Hsv.GetSaturation(hsvColor) * 100.0 - m_minSaturationFromLastBitmapCreation) / (m_maxSaturationFromLastBitmapCreation - m_minSaturationFromLastBitmapCreation); double vPercent = (Hsv.GetValue(hsvColor) * 100.0 - m_minValueFromLastBitmapCreation) / (m_maxValueFromLastBitmapCreation - m_minValueFromLastBitmapCreation); // In the case where saturation was an axis in the spectrum with hue, or value is an axis, full stop, // we inverted the direction of that axis in order to put more hue on the outside of the ring, // so we need to do similarly here when positioning the ellipse. if (m_componentsFromLastBitmapCreation == ColorSpectrumComponents.HueSaturation || m_componentsFromLastBitmapCreation == ColorSpectrumComponents.SaturationHue) { sPercent = 1 - sPercent; } else { vPercent = 1 - vPercent; } switch (m_componentsFromLastBitmapCreation) { case ColorSpectrumComponents.HueValue: xPercent = hPercent; yPercent = vPercent; break; case ColorSpectrumComponents.HueSaturation: xPercent = hPercent; yPercent = sPercent; break; case ColorSpectrumComponents.ValueHue: xPercent = vPercent; yPercent = hPercent; break; case ColorSpectrumComponents.ValueSaturation: xPercent = vPercent; yPercent = sPercent; break; case ColorSpectrumComponents.SaturationHue: xPercent = sPercent; yPercent = hPercent; break; case ColorSpectrumComponents.SaturationValue: xPercent = sPercent; yPercent = vPercent; break; } xPosition = m_imageWidthFromLastBitmapCreation * xPercent; yPosition = m_imageHeightFromLastBitmapCreation * yPercent; } else { double thetaValue = 0; double rValue = 0; double hThetaValue = m_maxHueFromLastBitmapCreation != m_minHueFromLastBitmapCreation ? 360 * (Hsv.GetHue(hsvColor) - m_minHueFromLastBitmapCreation) / (m_maxHueFromLastBitmapCreation - m_minHueFromLastBitmapCreation) : 0; double sThetaValue = m_maxSaturationFromLastBitmapCreation != m_minSaturationFromLastBitmapCreation ? 360 * (Hsv.GetSaturation(hsvColor) * 100.0 - m_minSaturationFromLastBitmapCreation) / (m_maxSaturationFromLastBitmapCreation - m_minSaturationFromLastBitmapCreation) : 0; double vThetaValue = m_maxValueFromLastBitmapCreation != m_minValueFromLastBitmapCreation ? 360 * (Hsv.GetValue(hsvColor) * 100.0 - m_minValueFromLastBitmapCreation) / (m_maxValueFromLastBitmapCreation - m_minValueFromLastBitmapCreation) : 0; double hRValue = m_maxHueFromLastBitmapCreation != m_minHueFromLastBitmapCreation ? (Hsv.GetHue(hsvColor) - m_minHueFromLastBitmapCreation) / (m_maxHueFromLastBitmapCreation - m_minHueFromLastBitmapCreation) - 1 : 0; double sRValue = m_maxSaturationFromLastBitmapCreation != m_minSaturationFromLastBitmapCreation ? (Hsv.GetSaturation(hsvColor) * 100.0 - m_minSaturationFromLastBitmapCreation) / (m_maxSaturationFromLastBitmapCreation - m_minSaturationFromLastBitmapCreation) - 1 : 0; double vRValue = m_maxValueFromLastBitmapCreation != m_minValueFromLastBitmapCreation ? (Hsv.GetValue(hsvColor) * 100.0 - m_minValueFromLastBitmapCreation) / (m_maxValueFromLastBitmapCreation - m_minValueFromLastBitmapCreation) - 1 : 0; // In the case where saturation was an axis in the spectrum with hue, or value is an axis, full stop, // we inverted the direction of that axis in order to put more hue on the outside of the ring, // so we need to do similarly here when positioning the ellipse. if (m_componentsFromLastBitmapCreation == ColorSpectrumComponents.HueSaturation || m_componentsFromLastBitmapCreation == ColorSpectrumComponents.ValueHue) { sThetaValue = 360 - sThetaValue; sRValue = -sRValue - 1; } else { vThetaValue = 360 - vThetaValue; vRValue = -vRValue - 1; } switch (m_componentsFromLastBitmapCreation) { case ColorSpectrumComponents.HueValue: thetaValue = hThetaValue; rValue = vRValue; break; case ColorSpectrumComponents.HueSaturation: thetaValue = hThetaValue; rValue = sRValue; break; case ColorSpectrumComponents.ValueHue: thetaValue = vThetaValue; rValue = hRValue; break; case ColorSpectrumComponents.ValueSaturation: thetaValue = vThetaValue; rValue = sRValue; break; case ColorSpectrumComponents.SaturationHue: thetaValue = sThetaValue; rValue = hRValue; break; case ColorSpectrumComponents.SaturationValue: thetaValue = sThetaValue; rValue = vRValue; break; } double radius = Math.Min(m_imageWidthFromLastBitmapCreation, m_imageHeightFromLastBitmapCreation) / 2; xPosition = (Math.Cos((thetaValue * Math.PI / 180.0) + Math.PI) * radius * rValue) + radius; yPosition = (Math.Sin((thetaValue * Math.PI / 180.0) + Math.PI) * radius * rValue) + radius; } Canvas.SetLeft(selectionEllipsePanel, xPosition - (selectionEllipsePanel.Width / 2)); Canvas.SetTop(selectionEllipsePanel, yPosition - (selectionEllipsePanel.Height / 2)); // We only want to bother with the color name tool tip if we can provide color names. if (DownlevelHelper.ToDisplayNameExists()) { if (m_colorNameToolTip is ToolTip colorNameToolTip) { // ToolTip doesn't currently provide any way to re-run its placement logic if its placement target moves, // so toggling IsEnabled induces it to do that without incurring any visual glitches. colorNameToolTip.IsEnabled = false; colorNameToolTip.IsEnabled = true; } } UpdateVisualState(useTransitions: true); } private void OnLayoutRootSizeChanged(object sender, SizeChangedEventArgs args) { // We want ColorSpectrum to always be a square, so we'll take the smaller of the dimensions // and size the sizing grid to that. CreateBitmapsAndColorMap(); } private void OnInputTargetPointerEntered(object sender, PointerRoutedEventArgs args) { m_isPointerOver = true; UpdateVisualState(useTransitions: true); args.Handled = true; } private void OnInputTargetPointerExited(object sender, PointerRoutedEventArgs args) { m_isPointerOver = false; UpdateVisualState(useTransitions: true); args.Handled = true; } private void OnInputTargetPointerPressed(object sender, PointerRoutedEventArgs args) { var inputTarget = m_inputTarget; Focus(FocusState.Pointer); m_isPointerPressed = true; m_shouldShowLargeSelection = args.Pointer.PointerDeviceType == PointerDeviceType.Pen || args.Pointer.PointerDeviceType == PointerDeviceType.Touch; inputTarget.CapturePointer(args.Pointer); UpdateColorFromPoint(args.GetCurrentPoint(inputTarget)); UpdateVisualState(useTransitions: true); UpdateEllipse(); args.Handled = true; } private void OnInputTargetPointerMoved(object sender, PointerRoutedEventArgs args) { if (!m_isPointerPressed) { return; } UpdateColorFromPoint(args.GetCurrentPoint(m_inputTarget)); args.Handled = true; } private void OnInputTargetPointerReleased(object sender, PointerRoutedEventArgs args) { m_isPointerPressed = false; m_shouldShowLargeSelection = false; m_inputTarget.ReleasePointerCapture(args.Pointer); UpdateVisualState(useTransitions: true); UpdateEllipse(); args.Handled = true; } private void OnSelectionEllipseFlowDirectionChanged(DependencyObject o, DependencyProperty p) { UpdateEllipse(); } private async void CreateBitmapsAndColorMap() { var layoutRoot = m_layoutRoot; var sizingGrid = m_sizingGrid; var inputTarget = m_inputTarget; var spectrumRectangle = m_spectrumRectangle; var spectrumEllipse = m_spectrumEllipse; var spectrumOverlayRectangle = m_spectrumOverlayRectangle; var spectrumOverlayEllipse = m_spectrumOverlayEllipse; if (m_layoutRoot == null || m_sizingGrid == null || m_inputTarget == null || m_spectrumRectangle == null || m_spectrumEllipse == null || m_spectrumOverlayRectangle == null || m_spectrumOverlayEllipse == null || SharedHelpers.IsInDesignMode()) { return; } double minDimension = Math.Min(layoutRoot.ActualWidth, layoutRoot.ActualHeight); if (minDimension == 0) { return; } sizingGrid.Width = minDimension; sizingGrid.Height = minDimension; // Uno Doc: Slightly modified from WinUI if (sizingGrid.Clip is RectangleGeometry clip) { clip.Rect = new Rect(0, 0, minDimension, minDimension); } inputTarget.Width = minDimension; inputTarget.Height = minDimension; spectrumRectangle.Width = minDimension; spectrumRectangle.Height = minDimension; spectrumEllipse.Width = minDimension; spectrumEllipse.Height = minDimension; spectrumOverlayRectangle.Width = minDimension; spectrumOverlayRectangle.Height = minDimension; spectrumOverlayEllipse.Width = minDimension; spectrumOverlayEllipse.Height = minDimension; Vector4 hsvColor = this.HsvColor; int minHue = this.MinHue; int maxHue = this.MaxHue; int minSaturation = this.MinSaturation; int maxSaturation = this.MaxSaturation; int minValue = this.MinValue; int maxValue = this.MaxValue; ColorSpectrumShape shape = this.Shape; ColorSpectrumComponents components = this.Components; // If min >= max, then by convention, min is the only number that a property can have. if (minHue >= maxHue) { maxHue = minHue; } if (minSaturation >= maxSaturation) { maxSaturation = minSaturation; } if (minValue >= maxValue) { maxValue = minValue; } Hsv hsv = new Hsv(Hsv.GetHue(hsvColor), Hsv.GetSaturation(hsvColor), Hsv.GetValue(hsvColor)); // The middle 4 are only needed and used in the case of hue as the third dimension. // Saturation and luminosity need only a min and max. ArrayList<byte> bgraMinPixelData = new ArrayList<byte>(); ArrayList<byte> bgraMiddle1PixelData = new ArrayList<byte>(); ArrayList<byte> bgraMiddle2PixelData = new ArrayList<byte>(); ArrayList<byte> bgraMiddle3PixelData = new ArrayList<byte>(); ArrayList<byte> bgraMiddle4PixelData = new ArrayList<byte>(); ArrayList<byte> bgraMaxPixelData = new ArrayList<byte>(); List<Hsv> newHsvValues = new List<Hsv>(); // Uno Docs: size_t not available in C# so types were changed var pixelCount = (int)(Math.Round(minDimension) * Math.Round(minDimension)); var pixelDataSize = pixelCount * 4; bgraMinPixelData.Capacity = pixelDataSize; // We'll only save pixel data for the middle bitmaps if our third dimension is hue. if (components == ColorSpectrumComponents.ValueSaturation || components == ColorSpectrumComponents.SaturationValue) { bgraMiddle1PixelData.Capacity = pixelDataSize; bgraMiddle2PixelData.Capacity = pixelDataSize; bgraMiddle3PixelData.Capacity = pixelDataSize; bgraMiddle4PixelData.Capacity = pixelDataSize; } bgraMaxPixelData.Capacity = pixelDataSize; newHsvValues.Capacity = pixelCount; int minDimensionInt = (int)Math.Round(minDimension); //WorkItemHandler workItemHandler = //(IAsyncAction workItem) => await Task.Run(() => { // As the user perceives it, every time the third dimension not represented in the ColorSpectrum changes, // the ColorSpectrum will visually change to accommodate that value. For example, if the ColorSpectrum handles hue and luminosity, // and the saturation externally goes from 1.0 to 0.5, then the ColorSpectrum will visually change to look more washed out // to represent that third dimension's new value. // Internally, however, we don't want to regenerate the ColorSpectrum bitmap every single time this happens, since that's very expensive. // In order to make it so that we don't have to, we implement an optimization where, rather than having only one bitmap, // we instead have multiple that we blend together using opacity to create the effect that we want. // In the case where the third dimension is saturation or luminosity, we only need two: one bitmap at the minimum value // of the third dimension, and one bitmap at the maximum. Then we set the second's opacity at whatever the value of // the third dimension is - e.g., a saturation of 0.5 implies an opacity of 50%. // In the case where the third dimension is hue, we need six: one bitmap corresponding to red, yellow, green, cyan, blue, and purple. // We'll then blend between whichever colors our hue exists between - e.g., an orange color would use red and yellow with an opacity of 50%. // This optimization does incur slightly more startup time initially since we have to generate multiple bitmaps at once instead of only one, // but the running time savings after that are *huge* when we can just set an opacity instead of generating a brand new bitmap. if (shape == ColorSpectrumShape.Box) { for (int x = minDimensionInt - 1; x >= 0; --x) { for (int y = minDimensionInt - 1; y >= 0; --y) { //if (workItem.Status == AsyncStatus.Canceled) //{ // break; //} FillPixelForBox( x, y, hsv, minDimensionInt, components, minHue, maxHue, minSaturation, maxSaturation, minValue, maxValue, bgraMinPixelData, bgraMiddle1PixelData, bgraMiddle2PixelData, bgraMiddle3PixelData, bgraMiddle4PixelData, bgraMaxPixelData, newHsvValues); } } } else { for (int y = 0; y < minDimensionInt; ++y) { for (int x = 0; x < minDimensionInt; ++x) { //if (workItem.Status == AsyncStatus.Canceled) //{ // break; //} FillPixelForRing( x, y, minDimensionInt / 2.0, hsv, components, minHue, maxHue, minSaturation, maxSaturation, minValue, maxValue, bgraMinPixelData, bgraMiddle1PixelData, bgraMiddle2PixelData, bgraMiddle3PixelData, bgraMiddle4PixelData, bgraMaxPixelData, newHsvValues); } } } }); //if (m_createImageBitmapAction != null) //{ // m_createImageBitmapAction.Cancel(); //} //m_createImageBitmapAction = ThreadPool.RunAsync(workItemHandler); var strongThis = this; //m_createImageBitmapAction.Completed = new AsyncActionCompletedHandler( //(IAsyncAction asyncInfo, AsyncStatus asyncStatus) => //{ // if (asyncStatus != AsyncStatus.Completed) // { // return; // } strongThis.m_createImageBitmapAction = null; // Uno Doc: Assumed normal priority is acceptable _ = strongThis.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { int pixelWidth = (int)Math.Round(minDimension); int pixelHeight = (int)Math.Round(minDimension); // Uno Doc: In C# (unlike C++) the existing 'components' var is captured by the lambda so it must be renamed here ColorSpectrumComponents components2 = strongThis.Components; // UNO TODO //if (SharedHelpers.IsRS2OrHigher) //{ // LoadedImageSurface minSurface = CreateSurfaceFromPixelData(pixelWidth, pixelHeight, bgraMinPixelData); // LoadedImageSurface maxSurface = CreateSurfaceFromPixelData(pixelWidth, pixelHeight, bgraMaxPixelData); // switch (components2) // { // case ColorSpectrumComponents.HueValue: // case ColorSpectrumComponents.ValueHue: // strongThis.m_saturationMinimumSurface = minSurface; // strongThis.m_saturationMaximumSurface = maxSurface; // break; // case ColorSpectrumComponents.HueSaturation: // case ColorSpectrumComponents.SaturationHue: // strongThis.m_valueSurface = maxSurface; // break; // case ColorSpectrumComponents.ValueSaturation: // case ColorSpectrumComponents.SaturationValue: // strongThis.m_hueRedSurface = minSurface; // strongThis.m_hueYellowSurface = CreateSurfaceFromPixelData(pixelWidth, pixelHeight, bgraMiddle1PixelData); // strongThis.m_hueGreenSurface = CreateSurfaceFromPixelData(pixelWidth, pixelHeight, bgraMiddle2PixelData); // strongThis.m_hueCyanSurface = CreateSurfaceFromPixelData(pixelWidth, pixelHeight, bgraMiddle3PixelData); // strongThis.m_hueBlueSurface = CreateSurfaceFromPixelData(pixelWidth, pixelHeight, bgraMiddle4PixelData); // strongThis.m_huePurpleSurface = maxSurface; // break; // } //} //else { WriteableBitmap minBitmap = ColorHelpers.CreateBitmapFromPixelData(pixelWidth, pixelHeight, bgraMinPixelData); WriteableBitmap maxBitmap = ColorHelpers.CreateBitmapFromPixelData(pixelWidth, pixelHeight, bgraMaxPixelData); switch (components2) { case ColorSpectrumComponents.HueValue: case ColorSpectrumComponents.ValueHue: strongThis.m_saturationMinimumBitmap = minBitmap; strongThis.m_saturationMaximumBitmap = maxBitmap; break; case ColorSpectrumComponents.HueSaturation: case ColorSpectrumComponents.SaturationHue: strongThis.m_valueBitmap = maxBitmap; break; case ColorSpectrumComponents.ValueSaturation: case ColorSpectrumComponents.SaturationValue: strongThis.m_hueRedBitmap = minBitmap; strongThis.m_hueYellowBitmap = ColorHelpers.CreateBitmapFromPixelData(pixelWidth, pixelHeight, bgraMiddle1PixelData); strongThis.m_hueGreenBitmap = ColorHelpers.CreateBitmapFromPixelData(pixelWidth, pixelHeight, bgraMiddle2PixelData); strongThis.m_hueCyanBitmap = ColorHelpers.CreateBitmapFromPixelData(pixelWidth, pixelHeight, bgraMiddle3PixelData); strongThis.m_hueBlueBitmap = ColorHelpers.CreateBitmapFromPixelData(pixelWidth, pixelHeight, bgraMiddle4PixelData); strongThis.m_huePurpleBitmap = maxBitmap; break; } } strongThis.m_shapeFromLastBitmapCreation = strongThis.Shape; strongThis.m_componentsFromLastBitmapCreation = strongThis.Components; strongThis.m_imageWidthFromLastBitmapCreation = minDimension; strongThis.m_imageHeightFromLastBitmapCreation = minDimension; strongThis.m_minHueFromLastBitmapCreation = strongThis.MinHue; strongThis.m_maxHueFromLastBitmapCreation = strongThis.MaxHue; strongThis.m_minSaturationFromLastBitmapCreation = strongThis.MinSaturation; strongThis.m_maxSaturationFromLastBitmapCreation = strongThis.MaxSaturation; strongThis.m_minValueFromLastBitmapCreation = strongThis.MinValue; strongThis.m_maxValueFromLastBitmapCreation = strongThis.MaxValue; strongThis.m_hsvValues = newHsvValues; strongThis.UpdateBitmapSources(); strongThis.UpdateEllipse(); }); //}); } private void FillPixelForBox( double x, double y, Hsv baseHsv, double minDimension, ColorSpectrumComponents components, double minHue, double maxHue, double minSaturation, double maxSaturation, double minValue, double maxValue, ArrayList<byte> bgraMinPixelData, ArrayList<byte> bgraMiddle1PixelData, ArrayList<byte> bgraMiddle2PixelData, ArrayList<byte> bgraMiddle3PixelData, ArrayList<byte> bgraMiddle4PixelData, ArrayList<byte> bgraMaxPixelData, List<Hsv> newHsvValues) { double hMin = minHue; double hMax = maxHue; double sMin = minSaturation / 100.0; double sMax = maxSaturation / 100.0; double vMin = minValue / 100.0; double vMax = maxValue / 100.0; Hsv hsvMin = baseHsv; Hsv hsvMiddle1 = baseHsv; Hsv hsvMiddle2 = baseHsv; Hsv hsvMiddle3 = baseHsv; Hsv hsvMiddle4 = baseHsv; Hsv hsvMax = baseHsv; double xPercent = (minDimension - 1 - x) / (minDimension - 1); double yPercent = (minDimension - 1 - y) / (minDimension - 1); switch (components) { case ColorSpectrumComponents.HueValue: hsvMin.H = hsvMiddle1.H = hsvMiddle2.H = hsvMiddle3.H = hsvMiddle4.H = hsvMax.H = hMin + yPercent * (hMax - hMin); hsvMin.V = hsvMiddle1.V = hsvMiddle2.V = hsvMiddle3.V = hsvMiddle4.V = hsvMax.V = vMin + xPercent * (vMax - vMin); hsvMin.S = 0; hsvMax.S = 1; break; case ColorSpectrumComponents.HueSaturation: hsvMin.H = hsvMiddle1.H = hsvMiddle2.H = hsvMiddle3.H = hsvMiddle4.H = hsvMax.H = hMin + yPercent * (hMax - hMin); hsvMin.S = hsvMiddle1.S = hsvMiddle2.S = hsvMiddle3.S = hsvMiddle4.S = hsvMax.S = sMin + xPercent * (sMax - sMin); hsvMin.V = 0; hsvMax.V = 1; break; case ColorSpectrumComponents.ValueHue: hsvMin.V = hsvMiddle1.V = hsvMiddle2.V = hsvMiddle3.V = hsvMiddle4.V = hsvMax.V = vMin + yPercent * (vMax - vMin); hsvMin.H = hsvMiddle1.H = hsvMiddle2.H = hsvMiddle3.H = hsvMiddle4.H = hsvMax.H = hMin + xPercent * (hMax - hMin); hsvMin.S = 0; hsvMax.S = 1; break; case ColorSpectrumComponents.ValueSaturation: hsvMin.V = hsvMiddle1.V = hsvMiddle2.V = hsvMiddle3.V = hsvMiddle4.V = hsvMax.V = vMin + yPercent * (vMax - vMin); hsvMin.S = hsvMiddle1.S = hsvMiddle2.S = hsvMiddle3.S = hsvMiddle4.S = hsvMax.S = sMin + xPercent * (sMax - sMin); hsvMin.H = 0; hsvMiddle1.H = 60; hsvMiddle2.H = 120; hsvMiddle3.H = 180; hsvMiddle4.H = 240; hsvMax.H = 300; break; case ColorSpectrumComponents.SaturationHue: hsvMin.S = hsvMiddle1.S = hsvMiddle2.S = hsvMiddle3.S = hsvMiddle4.S = hsvMax.S = sMin + yPercent * (sMax - sMin); hsvMin.H = hsvMiddle1.H = hsvMiddle2.H = hsvMiddle3.H = hsvMiddle4.H = hsvMax.H = hMin + xPercent * (hMax - hMin); hsvMin.V = 0; hsvMax.V = 1; break; case ColorSpectrumComponents.SaturationValue: hsvMin.S = hsvMiddle1.S = hsvMiddle2.S = hsvMiddle3.S = hsvMiddle4.S = hsvMax.S = sMin + yPercent * (sMax - sMin); hsvMin.V = hsvMiddle1.V = hsvMiddle2.V = hsvMiddle3.V = hsvMiddle4.V = hsvMax.V = vMin + xPercent * (vMax - vMin); hsvMin.H = 0; hsvMiddle1.H = 60; hsvMiddle2.H = 120; hsvMiddle3.H = 180; hsvMiddle4.H = 240; hsvMax.H = 300; break; } // If saturation is an axis in the spectrum with hue, or value is an axis, then we want // that axis to go from maximum at the top to minimum at the bottom, // or maximum at the outside to minimum at the inside in the case of the ring configuration, // so we'll invert the number before assigning the HSL value to the array. // Otherwise, we'll have a very narrow section in the middle that actually has meaningful hue // in the case of the ring configuration. if (components == ColorSpectrumComponents.HueSaturation || components == ColorSpectrumComponents.SaturationHue) { hsvMin.S = sMax - hsvMin.S + sMin; hsvMiddle1.S = sMax - hsvMiddle1.S + sMin; hsvMiddle2.S = sMax - hsvMiddle2.S + sMin; hsvMiddle3.S = sMax - hsvMiddle3.S + sMin; hsvMiddle4.S = sMax - hsvMiddle4.S + sMin; hsvMax.S = sMax - hsvMax.S + sMin; } else { hsvMin.V = vMax - hsvMin.V + vMin; hsvMiddle1.V = vMax - hsvMiddle1.V + vMin; hsvMiddle2.V = vMax - hsvMiddle2.V + vMin; hsvMiddle3.V = vMax - hsvMiddle3.V + vMin; hsvMiddle4.V = vMax - hsvMiddle4.V + vMin; hsvMax.V = vMax - hsvMax.V + vMin; } newHsvValues.Add(hsvMin); Rgb rgbMin = ColorConversion.HsvToRgb(hsvMin); bgraMinPixelData.Add((byte)Math.Round(rgbMin.B * 255.0)); // b bgraMinPixelData.Add((byte)Math.Round(rgbMin.G * 255.0)); // g bgraMinPixelData.Add((byte)Math.Round(rgbMin.R * 255.0)); // r bgraMinPixelData.Add(255); // a - ignored // We'll only save pixel data for the middle bitmaps if our third dimension is hue. if (components == ColorSpectrumComponents.ValueSaturation || components == ColorSpectrumComponents.SaturationValue) { Rgb rgbMiddle1 = ColorConversion.HsvToRgb(hsvMiddle1); bgraMiddle1PixelData.Add((byte)Math.Round(rgbMiddle1.B * 255.0)); // b bgraMiddle1PixelData.Add((byte)Math.Round(rgbMiddle1.G * 255.0)); // g bgraMiddle1PixelData.Add((byte)Math.Round(rgbMiddle1.R * 255.0)); // r bgraMiddle1PixelData.Add(255); // a - ignored Rgb rgbMiddle2 = ColorConversion.HsvToRgb(hsvMiddle2); bgraMiddle2PixelData.Add((byte)Math.Round(rgbMiddle2.B * 255.0)); // b bgraMiddle2PixelData.Add((byte)Math.Round(rgbMiddle2.G * 255.0)); // g bgraMiddle2PixelData.Add((byte)Math.Round(rgbMiddle2.R * 255.0)); // r bgraMiddle2PixelData.Add(255); // a - ignored Rgb rgbMiddle3 = ColorConversion.HsvToRgb(hsvMiddle3); bgraMiddle3PixelData.Add((byte)Math.Round(rgbMiddle3.B * 255.0)); // b bgraMiddle3PixelData.Add((byte)Math.Round(rgbMiddle3.G * 255.0)); // g bgraMiddle3PixelData.Add((byte)Math.Round(rgbMiddle3.R * 255.0)); // r bgraMiddle3PixelData.Add(255); // a - ignored Rgb rgbMiddle4 = ColorConversion.HsvToRgb(hsvMiddle4); bgraMiddle4PixelData.Add((byte)Math.Round(rgbMiddle4.B * 255.0)); // b bgraMiddle4PixelData.Add((byte)Math.Round(rgbMiddle4.G * 255.0)); // g bgraMiddle4PixelData.Add((byte)Math.Round(rgbMiddle4.R * 255.0)); // r bgraMiddle4PixelData.Add(255); // a - ignored } Rgb rgbMax = ColorConversion.HsvToRgb(hsvMax); bgraMaxPixelData.Add((byte)Math.Round(rgbMax.B * 255.0)); // b bgraMaxPixelData.Add((byte)Math.Round(rgbMax.G * 255.0)); // g bgraMaxPixelData.Add((byte)Math.Round(rgbMax.R * 255.0)); // r bgraMaxPixelData.Add(255); // a - ignored } private void FillPixelForRing( double x, double y, double radius, Hsv baseHsv, ColorSpectrumComponents components, double minHue, double maxHue, double minSaturation, double maxSaturation, double minValue, double maxValue, ArrayList<byte> bgraMinPixelData, ArrayList<byte> bgraMiddle1PixelData, ArrayList<byte> bgraMiddle2PixelData, ArrayList<byte> bgraMiddle3PixelData, ArrayList<byte> bgraMiddle4PixelData, ArrayList<byte> bgraMaxPixelData, List<Hsv> newHsvValues) { double hMin = minHue; double hMax = maxHue; double sMin = minSaturation / 100.0; double sMax = maxSaturation / 100.0; double vMin = minValue / 100.0; double vMax = maxValue / 100.0; double distanceFromRadius = Math.Sqrt(Math.Pow(x - radius, 2) + Math.Pow(y - radius, 2)); double xToUse = x; double yToUse = y; // If we're outside the ring, then we want the pixel to appear as blank. // However, to avoid issues with rounding errors, we'll act as though this point // is on the edge of the ring for the purposes of returning an HSL value. // That way, hittesting on the edges will always return the correct value. if (distanceFromRadius > radius) { xToUse = (radius / distanceFromRadius) * (x - radius) + radius; yToUse = (radius / distanceFromRadius) * (y - radius) + radius; distanceFromRadius = radius; } Hsv hsvMin = baseHsv; Hsv hsvMiddle1 = baseHsv; Hsv hsvMiddle2 = baseHsv; Hsv hsvMiddle3 = baseHsv; Hsv hsvMiddle4 = baseHsv; Hsv hsvMax = baseHsv; double r = 1 - distanceFromRadius / radius; double theta = Math.Atan2((radius - yToUse), (radius - xToUse)) * 180.0 / Math.PI; theta += 180.0; theta = Math.Floor(theta); while (theta > 360) { theta -= 360; } double thetaPercent = theta / 360; switch (components) { case ColorSpectrumComponents.HueValue: hsvMin.H = hsvMiddle1.H = hsvMiddle2.H = hsvMiddle3.H = hsvMiddle4.H = hsvMax.H = hMin + thetaPercent * (hMax - hMin); hsvMin.V = hsvMiddle1.V = hsvMiddle2.V = hsvMiddle3.V = hsvMiddle4.V = hsvMax.V = vMin + r * (vMax - vMin); hsvMin.S = 0; hsvMax.S = 1; break; case ColorSpectrumComponents.HueSaturation: hsvMin.H = hsvMiddle1.H = hsvMiddle2.H = hsvMiddle3.H = hsvMiddle4.H = hsvMax.H = hMin + thetaPercent * (hMax - hMin); hsvMin.S = hsvMiddle1.S = hsvMiddle2.S = hsvMiddle3.S = hsvMiddle4.S = hsvMax.S = sMin + r * (sMax - sMin); hsvMin.V = 0; hsvMax.V = 1; break; case ColorSpectrumComponents.ValueHue: hsvMin.V = hsvMiddle1.V = hsvMiddle2.V = hsvMiddle3.V = hsvMiddle4.V = hsvMax.V = vMin + thetaPercent * (vMax - vMin); hsvMin.H = hsvMiddle1.H = hsvMiddle2.H = hsvMiddle3.H = hsvMiddle4.H = hsvMax.H = hMin + r * (hMax - hMin); hsvMin.S = 0; hsvMax.S = 1; break; case ColorSpectrumComponents.ValueSaturation: hsvMin.V = hsvMiddle1.V = hsvMiddle2.V = hsvMiddle3.V = hsvMiddle4.V = hsvMax.V = vMin + thetaPercent * (vMax - vMin); hsvMin.S = hsvMiddle1.S = hsvMiddle2.S = hsvMiddle3.S = hsvMiddle4.S = hsvMax.S = sMin + r * (sMax - sMin); hsvMin.H = 0; hsvMiddle1.H = 60; hsvMiddle2.H = 120; hsvMiddle3.H = 180; hsvMiddle4.H = 240; hsvMax.H = 300; break; case ColorSpectrumComponents.SaturationHue: hsvMin.S = hsvMiddle1.S = hsvMiddle2.S = hsvMiddle3.S = hsvMiddle4.S = hsvMax.S = sMin + thetaPercent * (sMax - sMin); hsvMin.H = hsvMiddle1.H = hsvMiddle2.H = hsvMiddle3.H = hsvMiddle4.H = hsvMax.H = hMin + r * (hMax - hMin); hsvMin.V = 0; hsvMax.V = 1; break; case ColorSpectrumComponents.SaturationValue: hsvMin.S = hsvMiddle1.S = hsvMiddle2.S = hsvMiddle3.S = hsvMiddle4.S = hsvMax.S = sMin + thetaPercent * (sMax - sMin); hsvMin.V = hsvMiddle1.V = hsvMiddle2.V = hsvMiddle3.V = hsvMiddle4.V = hsvMax.V = vMin + r * (vMax - vMin); hsvMin.H = 0; hsvMiddle1.H = 60; hsvMiddle2.H = 120; hsvMiddle3.H = 180; hsvMiddle4.H = 240; hsvMax.H = 300; break; } // If saturation is an axis in the spectrum with hue, or value is an axis, then we want // that axis to go from maximum at the top to minimum at the bottom, // or maximum at the outside to minimum at the inside in the case of the ring configuration, // so we'll invert the number before assigning the HSL value to the array. // Otherwise, we'll have a very narrow section in the middle that actually has meaningful hue // in the case of the ring configuration. if (components == ColorSpectrumComponents.HueSaturation || components == ColorSpectrumComponents.SaturationHue) { hsvMin.S = sMax - hsvMin.S + sMin; hsvMiddle1.S = sMax - hsvMiddle1.S + sMin; hsvMiddle2.S = sMax - hsvMiddle2.S + sMin; hsvMiddle3.S = sMax - hsvMiddle3.S + sMin; hsvMiddle4.S = sMax - hsvMiddle4.S + sMin; hsvMax.S = sMax - hsvMax.S + sMin; } else { hsvMin.V = vMax - hsvMin.V + vMin; hsvMiddle1.V = vMax - hsvMiddle1.V + vMin; hsvMiddle2.V = vMax - hsvMiddle2.V + vMin; hsvMiddle3.V = vMax - hsvMiddle3.V + vMin; hsvMiddle4.V = vMax - hsvMiddle4.V + vMin; hsvMax.V = vMax - hsvMax.V + vMin; } newHsvValues.Add(hsvMin); Rgb rgbMin = ColorConversion.HsvToRgb(hsvMin); bgraMinPixelData.Add((byte)Math.Round(rgbMin.B * 255)); // b bgraMinPixelData.Add((byte)Math.Round(rgbMin.G * 255)); // g bgraMinPixelData.Add((byte)Math.Round(rgbMin.R * 255)); // r bgraMinPixelData.Add(255); // a // We'll only save pixel data for the middle bitmaps if our third dimension is hue. if (components == ColorSpectrumComponents.ValueSaturation || components == ColorSpectrumComponents.SaturationValue) { Rgb rgbMiddle1 = ColorConversion.HsvToRgb(hsvMiddle1); bgraMiddle1PixelData.Add((byte)Math.Round(rgbMiddle1.B * 255)); // b bgraMiddle1PixelData.Add((byte)Math.Round(rgbMiddle1.G * 255)); // g bgraMiddle1PixelData.Add((byte)Math.Round(rgbMiddle1.R * 255)); // r bgraMiddle1PixelData.Add(255); // a Rgb rgbMiddle2 = ColorConversion.HsvToRgb(hsvMiddle2); bgraMiddle2PixelData.Add((byte)Math.Round(rgbMiddle2.B * 255)); // b bgraMiddle2PixelData.Add((byte)Math.Round(rgbMiddle2.G * 255)); // g bgraMiddle2PixelData.Add((byte)Math.Round(rgbMiddle2.R * 255)); // r bgraMiddle2PixelData.Add(255); // a Rgb rgbMiddle3 = ColorConversion.HsvToRgb(hsvMiddle3); bgraMiddle3PixelData.Add((byte)Math.Round(rgbMiddle3.B * 255)); // b bgraMiddle3PixelData.Add((byte)Math.Round(rgbMiddle3.G * 255)); // g bgraMiddle3PixelData.Add((byte)Math.Round(rgbMiddle3.R * 255)); // r bgraMiddle3PixelData.Add(255); // a Rgb rgbMiddle4 = ColorConversion.HsvToRgb(hsvMiddle4); bgraMiddle4PixelData.Add((byte)Math.Round(rgbMiddle4.B * 255)); // b bgraMiddle4PixelData.Add((byte)Math.Round(rgbMiddle4.G * 255)); // g bgraMiddle4PixelData.Add((byte)Math.Round(rgbMiddle4.R * 255)); // r bgraMiddle4PixelData.Add(255); // a } Rgb rgbMax = ColorConversion.HsvToRgb(hsvMax); bgraMaxPixelData.Add((byte)Math.Round(rgbMax.B * 255)); // b bgraMaxPixelData.Add((byte)Math.Round(rgbMax.G * 255)); // g bgraMaxPixelData.Add((byte)Math.Round(rgbMax.R * 255)); // r bgraMaxPixelData.Add(255); // a } private void UpdateBitmapSources() { var spectrumOverlayRectangle = m_spectrumOverlayRectangle; var spectrumOverlayEllipse = m_spectrumOverlayEllipse; if (spectrumOverlayRectangle == null || spectrumOverlayEllipse == null) { return; } var spectrumRectangle = m_spectrumRectangle; var spectrumEllipse = m_spectrumEllipse; Vector4 hsvColor = this.HsvColor; ColorSpectrumComponents components = this.Components; // We'll set the base image and the overlay image based on which component is our third dimension. // If it's saturation or luminosity, then the base image is that dimension at its minimum value, // while the overlay image is that dimension at its maximum value. // If it's hue, then we'll figure out where in the color wheel we are, and then use the two // colors on either side of our position as our base image and overlay image. // For example, if our hue is orange, then the base image would be red and the overlay image yellow. switch (components) { case ColorSpectrumComponents.HueValue: case ColorSpectrumComponents.ValueHue: // UNO TODO //if (SharedHelpers.IsRS2OrHigher) //{ // if (m_saturationMinimumSurface == null || // m_saturationMaximumSurface == null) // { // return; // } // winrt::SpectrumBrush spectrumBrush{ winrt::make<SpectrumBrush>() }; // spectrumBrush.MinSurface(m_saturationMinimumSurface); // spectrumBrush.MaxSurface(m_saturationMaximumSurface); // spectrumBrush.MaxSurfaceOpacity(Hsv.GetSaturation(hsvColor)); // spectrumRectangle.Fill = spectrumBrush; // spectrumEllipse.Fill = spectrumBrush; //} //else { if (m_saturationMinimumBitmap == null || m_saturationMaximumBitmap == null) { return; } ImageBrush spectrumBrush = new ImageBrush(); ImageBrush spectrumOverlayBrush = new ImageBrush(); spectrumBrush.ImageSource = m_saturationMinimumBitmap; spectrumOverlayBrush.ImageSource = m_saturationMaximumBitmap; spectrumOverlayRectangle.Opacity = Hsv.GetSaturation(hsvColor); spectrumOverlayEllipse.Opacity = Hsv.GetSaturation(hsvColor); spectrumRectangle.Fill = spectrumBrush; spectrumEllipse.Fill = spectrumBrush; spectrumOverlayRectangle.Fill = spectrumOverlayBrush; spectrumOverlayRectangle.Fill = spectrumOverlayBrush; } break; case ColorSpectrumComponents.HueSaturation: case ColorSpectrumComponents.SaturationHue: // UNO TODO //if (SharedHelpers.IsRS2OrHigher) //{ // if (m_valueSurface == null) // { // return; // } // SpectrumBrush spectrumBrush{ winrt::make<SpectrumBrush>() }; // spectrumBrush.MinSurface(m_valueSurface); // spectrumBrush.MaxSurface(m_valueSurface); // spectrumBrush.MaxSurfaceOpacity(1); // spectrumRectangle.Fill = spectrumBrush; // spectrumEllipse.Fill = spectrumBrush; //} //else { if (m_valueBitmap == null) { return; } ImageBrush spectrumBrush = new ImageBrush(); ImageBrush spectrumOverlayBrush = new ImageBrush(); spectrumBrush.ImageSource = m_valueBitmap; spectrumOverlayBrush.ImageSource = m_valueBitmap; spectrumOverlayRectangle.Opacity = 1.0; spectrumOverlayEllipse.Opacity = 1.0; spectrumRectangle.Fill = spectrumBrush; spectrumEllipse.Fill = spectrumBrush; spectrumOverlayRectangle.Fill = spectrumOverlayBrush; spectrumOverlayRectangle.Fill = spectrumOverlayBrush; } break; case ColorSpectrumComponents.ValueSaturation: case ColorSpectrumComponents.SaturationValue: // UNO TODO //if (SharedHelpers.IsRS2OrHigher) //{ // if (m_hueRedSurface == null || // m_hueYellowSurface == null || // m_hueGreenSurface == null || // m_hueCyanSurface == null || // m_hueBlueSurface == null || // m_huePurpleSurface == null) // { // return; // } // SpectrumBrush spectrumBrush{ winrt::make<SpectrumBrush>() }; // double sextant = Hsv.GetHue(hsvColor) / 60.0; // if (sextant < 1) // { // spectrumBrush.MinSurface(m_hueRedSurface); // spectrumBrush.MaxSurface(m_hueYellowSurface); // } // else if (sextant >= 1 && sextant < 2) // { // spectrumBrush.MinSurface(m_hueYellowSurface); // spectrumBrush.MaxSurface(m_hueGreenSurface); // } // else if (sextant >= 2 && sextant < 3) // { // spectrumBrush.MinSurface(m_hueGreenSurface); // spectrumBrush.MaxSurface(m_hueCyanSurface); // } // else if (sextant >= 3 && sextant < 4) // { // spectrumBrush.MinSurface(m_hueCyanSurface); // spectrumBrush.MaxSurface(m_hueBlueSurface); // } // else if (sextant >= 4 && sextant < 5) // { // spectrumBrush.MinSurface(m_hueBlueSurface); // spectrumBrush.MaxSurface(m_huePurpleSurface); // } // else // { // spectrumBrush.MinSurface(m_huePurpleSurface); // spectrumBrush.MaxSurface(m_hueRedSurface); // } // spectrumBrush.MaxSurfaceOpacity(sextant - (int)sextant); // spectrumRectangle.Fill = spectrumBrush; // spectrumEllipse.Fill = spectrumBrush; //} //else { if (m_hueRedBitmap == null || m_hueYellowBitmap == null || m_hueGreenBitmap == null || m_hueCyanBitmap == null || m_hueBlueBitmap == null || m_huePurpleBitmap == null) { return; } ImageBrush spectrumBrush = new ImageBrush(); ImageBrush spectrumOverlayBrush = new ImageBrush(); double sextant = Hsv.GetHue(hsvColor) / 60.0; if (sextant < 1) { spectrumBrush.ImageSource = m_hueRedBitmap; spectrumOverlayBrush.ImageSource = m_hueYellowBitmap; } else if (sextant >= 1 && sextant < 2) { spectrumBrush.ImageSource = m_hueYellowBitmap; spectrumOverlayBrush.ImageSource = m_hueGreenBitmap; } else if (sextant >= 2 && sextant < 3) { spectrumBrush.ImageSource = m_hueGreenBitmap; spectrumOverlayBrush.ImageSource = m_hueCyanBitmap; } else if (sextant >= 3 && sextant < 4) { spectrumBrush.ImageSource = m_hueCyanBitmap; spectrumOverlayBrush.ImageSource = m_hueBlueBitmap; } else if (sextant >= 4 && sextant < 5) { spectrumBrush.ImageSource = m_hueBlueBitmap; spectrumOverlayBrush.ImageSource = m_huePurpleBitmap; } else { spectrumBrush.ImageSource = m_huePurpleBitmap; spectrumOverlayBrush.ImageSource = m_hueRedBitmap; } spectrumOverlayRectangle.Opacity = sextant - (int)sextant; spectrumOverlayEllipse.Opacity = sextant - (int)sextant; spectrumRectangle.Fill = spectrumBrush; spectrumEllipse.Fill = spectrumBrush; spectrumOverlayRectangle.Fill = spectrumOverlayBrush; spectrumOverlayRectangle.Fill = spectrumOverlayBrush; } break; } } private bool SelectionEllipseShouldBeLight() { // The selection ellipse should be light if and only if the chosen color // contrasts more with black than it does with white. // To find how much something contrasts with white, we use the equation // for relative luminance, which is given by // // L = 0.2126 * Rg + 0.7152 * Gg + 0.0722 * Bg // // where Xg = { X/3294 if X <= 10, (R/269 + 0.0513)^2.4 otherwise } // // If L is closer to 1, then the color is closer to white; if it is closer to 0, // then the color is closer to black. This is based on the fact that the human // eye perceives green to be much brighter than red, which in turn is perceived to be // brighter than blue. // // If the third dimension is value, then we won't be updating the spectrum's displayed colors, // so in that case we should use a value of 1 when considering the backdrop // for the selection ellipse. Color displayedColor; if (this.Components == ColorSpectrumComponents.HueSaturation || this.Components == ColorSpectrumComponents.SaturationHue) { Vector4 hsvColor = this.HsvColor; Rgb color = ColorConversion.HsvToRgb(new Hsv(Hsv.GetHue(hsvColor), Hsv.GetSaturation(hsvColor), 1.0)); displayedColor = ColorConversion.ColorFromRgba(color, Hsv.GetAlpha(hsvColor)); } else { displayedColor = this.Color; } double rg = displayedColor.R <= 10 ? displayedColor.R / 3294.0 : Math.Pow(displayedColor.R / 269.0 + 0.0513, 2.4); double gg = displayedColor.G <= 10 ? displayedColor.G / 3294.0 : Math.Pow(displayedColor.G / 269.0 + 0.0513, 2.4); double bg = displayedColor.B <= 10 ? displayedColor.B / 3294.0 : Math.Pow(displayedColor.B / 269.0 + 0.0513, 2.4); return 0.2126 * rg + 0.7152 * gg + 0.0722 * bg <= 0.5; } } }
35.884403
215
0.709582
[ "Apache-2.0" ]
AnshSSonkhia/uno
src/Uno.UI/Microsoft/UI/Xaml/Controls/ColorPicker/ColorSpectrum.cs
64,881
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.ApiManagement.V20170301 { public static class GetApiOperation { /// <summary> /// Api Operation details. /// </summary> public static Task<GetApiOperationResult> InvokeAsync(GetApiOperationArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetApiOperationResult>("azure-native:apimanagement/v20170301:getApiOperation", args ?? new GetApiOperationArgs(), options.WithVersion()); } public sealed class GetApiOperationArgs : Pulumi.InvokeArgs { /// <summary> /// API revision identifier. Must be unique in the current API Management service instance. Non-current revision has ;rev=n as a suffix where n is the revision number. /// </summary> [Input("apiId", required: true)] public string ApiId { get; set; } = null!; /// <summary> /// Operation identifier within an API. Must be unique in the current API Management service instance. /// </summary> [Input("operationId", required: true)] public string OperationId { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the API Management service. /// </summary> [Input("serviceName", required: true)] public string ServiceName { get; set; } = null!; public GetApiOperationArgs() { } } [OutputType] public sealed class GetApiOperationResult { /// <summary> /// Description of the operation. May include HTML formatting tags. /// </summary> public readonly string? Description; /// <summary> /// Operation Name. /// </summary> public readonly string DisplayName; /// <summary> /// Resource ID. /// </summary> public readonly string Id; /// <summary> /// A Valid HTTP Operation Method. Typical Http Methods like GET, PUT, POST but not limited by only them. /// </summary> public readonly string Method; /// <summary> /// Resource name. /// </summary> public readonly string Name; /// <summary> /// Operation Policies /// </summary> public readonly string? Policies; /// <summary> /// An entity containing request details. /// </summary> public readonly Outputs.RequestContractResponse? Request; /// <summary> /// Array of Operation responses. /// </summary> public readonly ImmutableArray<Outputs.ResponseContractResponse> Responses; /// <summary> /// Collection of URL template parameters. /// </summary> public readonly ImmutableArray<Outputs.ParameterContractResponse> TemplateParameters; /// <summary> /// Resource type for API Management resource. /// </summary> public readonly string Type; /// <summary> /// Relative URL template identifying the target resource for this operation. May include parameters. Example: /customers/{cid}/orders/{oid}/?date={date} /// </summary> public readonly string UrlTemplate; [OutputConstructor] private GetApiOperationResult( string? description, string displayName, string id, string method, string name, string? policies, Outputs.RequestContractResponse? request, ImmutableArray<Outputs.ResponseContractResponse> responses, ImmutableArray<Outputs.ParameterContractResponse> templateParameters, string type, string urlTemplate) { Description = description; DisplayName = displayName; Id = id; Method = method; Name = name; Policies = policies; Request = request; Responses = responses; TemplateParameters = templateParameters; Type = type; UrlTemplate = urlTemplate; } } }
32.992857
191
0.597965
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/ApiManagement/V20170301/GetApiOperation.cs
4,619
C#
using System; using System.Threading.Tasks; using SettingX.Core.Models; using SettingX.Repositories.Common.Client; using Xunit; using Xunit.Priority; namespace SettingX.Repositories.Tests.Rest.RepositoryTests { [DefaultPriority(0)] [TestCaseOrderer(PriorityOrderer.Name, PriorityOrderer.Assembly)] public class ServiceTokenTest : IClassFixture<ClientFixture> { private readonly IClient _client; public ServiceTokenTest(ClientFixture fixture) { _client = fixture.Client; } [Fact] public async Task Write_Read_Update_Read() { var token1 = new ServiceToken { SecurityKeyOne = Guid.NewGuid().ToString(), SecurityKeyTwo = Guid.NewGuid().ToString(), Token = Guid.NewGuid().ToString() }; var token2 = new ServiceToken { SecurityKeyOne = Guid.NewGuid().ToString(), SecurityKeyTwo = Guid.NewGuid().ToString(), Token = Guid.NewGuid().ToString() }; await _client.ServiceTokensApi.SaveOrUpdateAsync(token1); await _client.ServiceTokensApi.SaveOrUpdateAsync(token2); token1.SecurityKeyOne = Guid.NewGuid().ToString(); token1.SecurityKeyTwo = Guid.NewGuid().ToString(); await _client.ServiceTokensApi.SaveOrUpdateAsync(token1); var token1FromDb = await _client.ServiceTokensApi.GetAsync(token1.Token); var token2FromDb = await _client.ServiceTokensApi.GetAsync(token2.Token); Assert.Equal(token1.SecurityKeyOne, token1FromDb.SecurityKeyOne); Assert.Equal(token1.SecurityKeyTwo, token1FromDb.SecurityKeyTwo); Assert.Equal(token2.SecurityKeyOne, token2FromDb.SecurityKeyOne); Assert.Equal(token2.SecurityKeyTwo, token2FromDb.SecurityKeyTwo); } [Fact] public async Task Write_Remove_Read() { var token = new ServiceToken { SecurityKeyOne = Guid.NewGuid().ToString(), SecurityKeyTwo = Guid.NewGuid().ToString(), Token = Guid.NewGuid().ToString() }; await _client.ServiceTokensApi.SaveOrUpdateAsync(token); await _client.ServiceTokensApi.RemoveAsync(token.Token); await _client.ServiceTokensApi.RemoveAsync(token.Token); var token1FromDb = await _client.ServiceTokensApi.GetAsync(token.Token); Assert.Null(token1FromDb); } [FactConditional, Priority(1)] public async Task Read_All() { var all = await _client.ServiceTokensApi.GetAllAsync(); Assert.Equal(2, all.Count); } } }
34.082353
85
0.599931
[ "MIT" ]
SettingX/SettingX.Repositories.Tests
SettingX.Repositories.Tests.Rest/RepositoryTests/ServiceTokenTest.cs
2,897
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Labs_authentification")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HP Inc.")] [assembly: AssemblyProduct("Labs_authentification")] [assembly: AssemblyCopyright("Copyright © HP Inc. 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("89f6d42f-1fe6-46bd-8360-3ee17426bf6d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.444444
84
0.754335
[ "MIT" ]
SebastianTrifa/c-
Labs_authentification/Properties/AssemblyInfo.cs
1,387
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the pinpoint-email-2018-07-26.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.PinpointEmail.Model { /// <summary> /// Represents the body of the email message. /// </summary> public partial class Body { private Content _html; private Content _text; /// <summary> /// Gets and sets the property Html. /// <para> /// An object that represents the version of the message that is displayed in email clients /// that support HTML. HTML messages can include formatted text, hyperlinks, images, and /// more. /// </para> /// </summary> public Content Html { get { return this._html; } set { this._html = value; } } // Check to see if Html property is set internal bool IsSetHtml() { return this._html != null; } /// <summary> /// Gets and sets the property Text. /// <para> /// An object that represents the version of the message that is displayed in email clients /// that don't support HTML, or clients where the recipient has disabled HTML rendering. /// </para> /// </summary> public Content Text { get { return this._text; } set { this._text = value; } } // Check to see if Text property is set internal bool IsSetText() { return this._text != null; } } }
29.658228
112
0.613316
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/PinpointEmail/Generated/Model/Body.cs
2,343
C#
/* * The MIT License (MIT) * Copyright (c) StarX 2017 */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.ComponentModel; using CrazyStorm.Core; using System.Windows.Resources; using System.Threading.Tasks; using System.Threading; namespace CrazyStorm { public partial class Main : Window { #region Private Members Config config; File file; List<ParticleType> defaultParticleTypes; Dictionary<ParticleSystem, CommandStack> commandStacks; List<Core.Component> clipBoard; #endregion #region Constructor public Main() { defaultParticleTypes = new List<ParticleType>(); commandStacks = new Dictionary<ParticleSystem, CommandStack>(); clipBoard = new List<Core.Component>(); InitializeComponent(); } #endregion #region Private Methods void InitializeConfig() { config = new Config("Config.ini"); ParticleTabControl.DataContext = config; } void LoadDefaultParticleTypes() { StreamResourceInfo info = Application.GetResourceStream(new Uri("set.txt", UriKind.Relative)); using (System.IO.StreamReader reader = new System.IO.StreamReader(info.Stream)) { ParticleType.LoadDefaultTypes(reader, defaultParticleTypes); } } void InitializeSystem() { InitializeFile(); InitializeParticle(); InitializeEdit(); InitializeScreen(); } void InitializeFile() { Title = VersionInfo.AppTitle + " - " + fileName; ImageList.ItemsSource = file.Images; SoundList.ItemsSource = file.Sounds; VariableGrid.ItemsSource = file.Globals; DeleteVariable.IsEnabled = file.Globals.Count > 0 ? true : false; } void InitializeParticle() { DeleteAllParticle(); selectedSystem = file.ParticleSystems.First(); foreach (var item in file.ParticleSystems) { InitializeCommandStack(item); AddNewParticleTab(item); } } void InitializeCommandStack(ParticleSystem particle) { commandStacks[particle] = new CommandStack(); commandStacks[particle].StackChanged += () => { UpdateCommandStackStatus(); saved = false; }; } void InitializeEdit() { CutItem.IsEnabled = false; CopyItem.IsEnabled = false; PasteItem.IsEnabled = false; UndoItem.IsEnabled = false; RedoItem.IsEnabled = false; DelItem.IsEnabled = false; CutButton.IsEnabled = false; CopyButton.IsEnabled = false; PasteButton.IsEnabled = false; UndoButton.IsEnabled = false; RedoButton.IsEnabled = false; } void InitializeLayerAndComponent() { selectedLayer = selectedSystem.Layers.First(); LayerTree.ItemsSource = selectedSystem.Layers; LayerAxis.ItemsSource = selectedSystem.Layers; ComponentTree.ItemsSource = selectedSystem.ComponentTree; BindComponentItem.IsEnabled = false; UnbindComponentItem.IsEnabled = false; } void InitializeScreen() { aimRect = null; aimComponent = null; } void UpdateSelectedStatus() { //Be careful that UpdateScreen() needs to update first, //because it will refresh selectedComponents set. UpdateScreen(); UpdateComponentPanels(); UpdateSelectedGroup(); UpdateComponentMenu(); UpdateEditStatus(); } #endregion #region Public Methods public void Initailize() { LoadDefaultParticleTypes(); InitializeConfig(); } public void StartNewFile() { saved = true; New(); } public void OpenFile(string openPath) { Open(openPath); } #endregion #region Window EventHandlers private void Window_Loaded(object sender, RoutedEventArgs e) { //Highlight selected layer. TreeViewItem item = (TreeViewItem)LayerTree.ItemContainerGenerator.ContainerFromItem(selectedLayer); if (item != null) { item.IsSelected = true; } } #endregion } }
30.823171
112
0.576459
[ "MIT" ]
Langzaigg/CrazyStorm2.0
Main.xaml.cs
5,057
C#
namespace CASC.CodeParser.Binding { internal enum BoundBinaryOperatorKind { Addition, Subtraction, Multiplication, Division, BitwiseXOR, LogicalAND, BitwiseAND, LogicalOR, BitwiseOR, Equals, NotEquals, Greater, GreaterEquals, Less, LessEquals } }
18
41
0.537037
[ "MIT" ]
CASC-Lang/CASC-JIT
src/CASC-Interpreter/CodeParser/Binding/BoundBinaryOperatorKind.cs
378
C#
using assignment6.Repository.Entity; using assignment6.Repository.Infrastructure; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace assignment6.Repository.Repository { public class EmployeeRepository : RepositoryBase<Emp1>, IEmployeeRepository { public EmployeeRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) { } } public interface IEmployeeRepository : IRepository<Emp1> { } }
24.863636
92
0.723949
[ "MIT" ]
medhajoshi27/AllProjectmedha
assignment6/Assignment6.Repository/Repository/EmployeeRepository.cs
549
C#
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace StyleCop.Analyzers.Test.Verifiers { using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Testing; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Testing; using Microsoft.CodeAnalysis.Testing.Verifiers; internal static class StyleCopDiagnosticVerifier<TAnalyzer> where TAnalyzer : DiagnosticAnalyzer, new() { internal static DiagnosticResult Diagnostic() => CSharpCodeFixVerifier<TAnalyzer, EmptyCodeFixProvider, XUnitVerifier>.Diagnostic(); internal static DiagnosticResult Diagnostic(string diagnosticId) => CSharpCodeFixVerifier<TAnalyzer, EmptyCodeFixProvider, XUnitVerifier>.Diagnostic(diagnosticId); internal static DiagnosticResult Diagnostic(DiagnosticDescriptor descriptor) => new DiagnosticResult(descriptor); internal static Task VerifyCSharpDiagnosticAsync(string source, DiagnosticResult expected, CancellationToken cancellationToken) => VerifyCSharpDiagnosticAsync(source, new[] { expected }, cancellationToken); internal static Task VerifyCSharpDiagnosticAsync(string source, DiagnosticResult[] expected, CancellationToken cancellationToken) { var test = new CSharpTest { TestCode = source, }; test.ExpectedDiagnostics.AddRange(expected); return test.RunAsync(cancellationToken); } internal static Task VerifyCSharpDiagnosticAsync(LanguageVersion? languageVersion, string source, DiagnosticResult expected, CancellationToken cancellationToken) => VerifyCSharpDiagnosticAsync(languageVersion, source, new[] { expected }, cancellationToken); internal static Task VerifyCSharpDiagnosticAsync(LanguageVersion? languageVersion, string source, DiagnosticResult[] expected, CancellationToken cancellationToken) { var test = new CSharpTest(languageVersion) { TestCode = source, }; test.ExpectedDiagnostics.AddRange(expected); return test.RunAsync(cancellationToken); } internal class CSharpTest : StyleCopCodeFixVerifier<TAnalyzer, EmptyCodeFixProvider>.CSharpTest { public CSharpTest() : this(languageVersion: null) { } public CSharpTest(LanguageVersion? languageVersion) { if (languageVersion != null) { this.SolutionTransforms.Add((solution, projectId) => { var parseOptions = (CSharpParseOptions)solution.GetProject(projectId).ParseOptions; return solution.WithProjectParseOptions(projectId, parseOptions.WithLanguageVersion(languageVersion.Value)); }); } } } } }
42.421053
171
0.671836
[ "Apache-2.0" ]
yyefimov/StyleCopAnalyzers
StyleCop.Analyzers/StyleCop.Analyzers.Test/Verifiers/StyleCopDiagnosticVerifier`1.cs
3,226
C#
// T4 code generation is enabled for model 'C:\Users\erik.aberg\Source\Repos\effective-adventure\CreateCookiesSolutionMVC\CreateCookies\CreateCookiesModel.edmx'. // To enable legacy code generation, change the value of the 'Code Generation Strategy' designer // property to 'Legacy ObjectContext'. This property is available in the Properties Window when the model // is open in the designer. // If no context and entity classes have been generated, it may be because you created an empty model but // have not yet chosen which version of Entity Framework to use. To generate a context class and entity // classes for your model, open the model in the designer, right-click on the designer surface, and // select 'Update Model from Database...', 'Generate Database from Model...', or 'Add Code Generation // Item...'.
82
163
0.77561
[ "MIT" ]
spikk/effective-adventure
CreateCookiesSolutionMVC/CreateCookies/CreateCookiesModel.Designer.cs
822
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Dfe.Spi.Common.Logging.Definitions; using Dfe.Spi.GiasAdapter.Domain.Cache; using Dfe.Spi.GiasAdapter.Domain.Configuration; using Microsoft.Azure.Cosmos.Table; using Newtonsoft.Json; namespace Dfe.Spi.GiasAdapter.Infrastructure.AzureStorage.Cache { public class TableEstablishmentRepository : TableCacheRepository<PointInTimeEstablishment, EstablishmentEntity>, IEstablishmentRepository { public TableEstablishmentRepository(CacheConfiguration configuration, ILoggerWrapper logger) : base(configuration.TableStorageConnectionString, configuration.EstablishmentTableName, logger, "establishments") { } public async Task StoreAsync(PointInTimeEstablishment establishment, CancellationToken cancellationToken) { await StoreAsync(new[] {establishment}, cancellationToken); } public async Task StoreAsync(PointInTimeEstablishment[] establishments, CancellationToken cancellationToken) { await InsertOrUpdateAsync(establishments, cancellationToken); } public async Task StoreInStagingAsync(PointInTimeEstablishment[] establishments, CancellationToken cancellationToken) { await InsertOrUpdateStagingAsync(establishments, cancellationToken); } public async Task<PointInTimeEstablishment> GetEstablishmentAsync(long urn, CancellationToken cancellationToken) { return await GetEstablishmentAsync(urn, null, cancellationToken); } public async Task<PointInTimeEstablishment> GetEstablishmentAsync(long urn, DateTime? pointInTime, CancellationToken cancellationToken) { if (!pointInTime.HasValue) { return await RetrieveAsync(urn.ToString(), "current", cancellationToken); } var query = new TableQuery<EstablishmentEntity>() .Where(TableQuery.CombineFilters( TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, urn.ToString()), TableOperators.And, TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.LessThanOrEqual, pointInTime.Value.ToString("yyyyMMdd")))) .OrderByDesc("RowKey") .Take(1); var results = await QueryAsync(query, cancellationToken); // Appears to be a bug in the library that does not honor the order or the take. // Will reprocess here return results .OrderByDescending(r => r.PointInTime) .FirstOrDefault(); } public async Task<PointInTimeEstablishment> GetEstablishmentFromStagingAsync(long urn, DateTime pointInTime, CancellationToken cancellationToken) { return await RetrieveAsync(GetStagingPartitionKey(pointInTime), urn.ToString(), cancellationToken); } public async Task<int> ClearStagingDataForDateAsync(DateTime date, CancellationToken cancellationToken) { var partitionKey = GetStagingPartitionKey(date); return await DeleteAllRowsInPartitionAsync(partitionKey, cancellationToken); } protected override EstablishmentEntity ModelToEntity(PointInTimeEstablishment model) { return ModelToEntity(model.Urn.ToString(), model.PointInTime.ToString("yyyyMMdd"), model); } protected override EstablishmentEntity ModelToEntityForStaging(PointInTimeEstablishment model) { return ModelToEntity(GetStagingPartitionKey(model.PointInTime), model.Urn.ToString(), model); } private EstablishmentEntity ModelToEntity(string partitionKey, string rowKey, PointInTimeEstablishment establishment) { return new EstablishmentEntity { PartitionKey = partitionKey, RowKey = rowKey, Establishment = JsonConvert.SerializeObject(establishment), PointInTime = establishment.PointInTime, IsCurrent = establishment.IsCurrent, }; } protected override PointInTimeEstablishment EntityToModel(EstablishmentEntity entity) { return JsonConvert.DeserializeObject<PointInTimeEstablishment>( entity.Establishment); } protected override EstablishmentEntity[] ProcessEntitiesBeforeStoring(EstablishmentEntity[] entities) { var processedEntities = new List<EstablishmentEntity>(); foreach (var entity in entities) { if (entity.IsCurrent) { processedEntities.Add(new EstablishmentEntity { PartitionKey = entity.PartitionKey, RowKey = "current", Establishment = entity.Establishment, PointInTime = entity.PointInTime, IsCurrent = entity.IsCurrent, }); } processedEntities.Add(entity); } return processedEntities.ToArray(); } private string GetStagingPartitionKey(DateTime pointInTime) { return $"staging{pointInTime:yyyyMMdd}"; } } }
40.558824
153
0.649746
[ "MIT" ]
DFE-Digital/spi-gias-adapter
src/Dfe.Spi.GiasAdapter.Infrastructure.AzureStorage/Cache/TableEstablishmentRepository.cs
5,516
C#
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; namespace JsonTransformation { public class ParametersTransform : ICanTransformJson { public bool TransformJson(TransformJsonArgs args) { if (!(args.Source is JObject jSource)) return false; if (jSource["$setParameters"] is JObject jSetParameters) return SetParameters(args, jSetParameters); else if (jSource["$useParameter"] is JToken jUseParameter) return UseParameter(args, jUseParameter); return false; } bool UseParameter(TransformJsonArgs args, JToken jUseParameter) { var parName = jUseParameter.Value<string>(); if (args.Context.TryGetValue("paramByName", out object paramByNameObj) && paramByNameObj is Dictionary<string, JToken> paramByName) { if (paramByName.TryGetValue(parName, out var parValue)) { var newNode = parValue.DeepClone(); args.Source.Replace(newNode); args.Source = newNode; return true; } } return false; } bool SetParameters(TransformJsonArgs args, JObject jSetParameters) { if (!(args.Context.TryGetValue("paramByName", out object paramByNameObj) && paramByNameObj is Dictionary<string, JToken> paramByName)) { paramByName = new Dictionary<string, JToken>(); args.Context["paramByName"] = paramByName; } foreach (var jProp in jSetParameters.Properties()) { paramByName[jProp.Name] = jProp.Value; } (args.Source as JObject).Remove("$setParameters"); //args.Source.Remove(); //args.Source = null; return false; } } }
34.232143
146
0.57903
[ "MIT" ]
pmunin/JsonTransformation
src/JsonTransformation/ParametersTransform.cs
1,919
C#
using ColossalFramework.UI; using UnityEngine; using System; namespace Shicho.GUI { using Core; using Extension; public static class Helper { public static RectOffset ZeroOffset { get => new RectOffset(0, 0, 0, 0); } public static Vector2 ScreenResolution { get => UIView.GetAView().GetScreenResolution(); } public static Rect ScreenRectAsScreen { get { //Log.Debug($"{v.GetScreenResolution()}, {v.scale}, {v.ratio}, {v.inputScale}"); var res = ScreenResolution; return new Rect( x: 0, y: 0, width: res.x, height: res.y ); } } public static Rect ScreenRectAsUI { get => ScreenToUI(ScreenRectAsScreen); } // UI coordinates = same axis as Screen, center point at "center" public static Rect ScreenToUI(Rect r) { var res = ScreenResolution; return new Rect( x: r.x - res.x / 2, y: r.y - res.y / 2, width: r.width, height: r.height ); } public static Color32 RGB(byte r, byte g, byte b) { return new Color32(r, g, b, 255); } public static Color32 RGBA(byte r, byte g, byte b, byte a) { return new Color32(r, g, b, a); } // CSS-like padding specifiers public static RectOffset Padding(int top, int? right = null, int? bottom = null, int? left = null) { if (!right.HasValue) { return new RectOffset(top: top, bottom: top, left: 0, right: 0); } if (!bottom.HasValue) { return new RectOffset(top: top, bottom: top, left: right.Value, right: right.Value); } if (!left.HasValue) { return new RectOffset(top: top, right: right.Value, bottom: bottom.Value, left: 0); } return new RectOffset(top: top, right: right.Value, bottom: bottom.Value, left: left.Value); } public static UILabel AddLabel(ref UIPanel parent, string label, string tooltip = "", UIFont font = null, RectOffset padding = null, Color32? color = null, string bullet = null) { var obj = parent.AddUIComponent<UILabel>(); obj.text = label; obj.tooltip = tooltip; if (color.HasValue) { obj.textColor = color.Value; } if (font != null) { obj.font = font; } else { obj.font = FontStore.Get(11); } if (padding != null) { obj.padding = padding; } var bulletSize = obj.font.size + 4; obj.padding.left += bulletSize + 3; if (bullet != null) { obj.padding.left += 3; var sp = obj.AddUIComponent<UISprite>(); sp.spriteName = bullet; sp.width = sp.height = bulletSize; sp.relativePosition = new Vector2(2, 0); } return obj; } public static UIPanel AddIconLabel(ref UIPanel parent, string icon, string label, string tooltip = "", UIFont font = null, Color32? color = null, float? wrapperWidth = null, bool isInverted = false) { var wrapper = parent.AddUIComponent<UIPanel>(); wrapper.anchor = UIAnchorStyle.Top | UIAnchorStyle.Left | UIAnchorStyle.Right; wrapper.autoSize = true; //wrapper.SetAutoLayout(LayoutDirection.Horizontal); if (wrapperWidth.HasValue) { wrapper.width = wrapperWidth.Value; } var iconObj = Helper.AddIcon(ref wrapper, icon, 16); var labelObj = wrapper.AddUIComponent<UILabel>(); labelObj.font = font; labelObj.text = label; labelObj.tooltip = tooltip; if (color.HasValue) labelObj.textColor = color.Value; if (isInverted) { //wrapper.autoLayoutStart = LayoutStart.TopRight; //iconObj.relativePosition = new Vector2(wrapper.width, 0); //labelObj.relativePosition = new Vector2(wrapper.width - iconObj.width, 0); //labelObj.textAlignment = UIHorizontalAlignment.Right; iconObj.relativePosition = new Vector2(wrapper.width - iconObj.width, 0); labelObj.relativePosition = new Vector2(iconObj.relativePosition.x - labelObj.width - 4, 0); } else { iconObj.relativePosition = Vector2.zero; labelObj.relativePosition = new Vector2(iconObj.width, 0); labelObj.padding.left = 4; } return wrapper; } public static UICheckBox AddCheckBox(ref UIPanel parent, string label, string tooltip, bool initialValue, PropertyChangedEventHandler<bool> onCheckChanged, UIFont font = null, int? indentPadding = null) { var box = parent.AddUIComponent<UICheckBox>(); box.anchor = UIAnchorStyle.Top | UIAnchorStyle.Left | UIAnchorStyle.Right; box.label = box.AddUIComponent<UILabel>(); box.label.anchor = UIAnchorStyle.Top | UIAnchorStyle.Left | UIAnchorStyle.Right; box.label.text = label; if (tooltip == null) { // box.label.tooltip = $"default: {initialValue}"; } else { box.label.tooltip = tooltip; } if (font != null) { box.label.font = font; } box.label.padding.left = box.label.font.size + 6; if (indentPadding.HasValue) { box.label.padding.left += indentPadding.Value; } box.label.relativePosition = new Vector2(0, -(box.label.font.size - 10)); box.label.FitTo(parent); box.height = box.label.height; var uncheckedSprite = box.AddUIComponent<UISprite>() as UISprite; uncheckedSprite.spriteName = "AchievementCheckedFalse"; uncheckedSprite.relativePosition = new Vector2(indentPadding.HasValue ? indentPadding.Value : 0, 2.5f); uncheckedSprite.anchor = UIAnchorStyle.Top | UIAnchorStyle.Left; uncheckedSprite.width = uncheckedSprite.height = box.label.font.size; var checkedSprite = uncheckedSprite.AddUIComponent<UISprite>() as UISprite; checkedSprite.spriteName = "AchievementCheckedTrue"; checkedSprite.relativePosition = Vector2.zero; checkedSprite.anchor = uncheckedSprite.anchor; checkedSprite.size = uncheckedSprite.size; box.checkedBoxObject = checkedSprite; box.eventCheckChanged += onCheckChanged; box.isChecked = initialValue; // box.isChecked = initialValue; //if (initialValue) box.SimulateClick(); return box; } public static UIDropDown AddDropDown(ref UIPanel parent, string name, string[] options, string initialValue, PropertyChangedEventHandler<int> onSelectedIndexChanged, UIFont font = null) { if (font == null) { font = FontStore.Get(11); } var panel = parent.AttachUIComponent(UITemplateManager.GetAsGameObject("OptionsDropdownTemplate")) as UIPanel; panel.clipChildren = false; panel.SetAutoLayout(LayoutDirection.Horizontal); panel.autoFitChildrenVertically = true; var label = panel.Find<UILabel>("Label"); label.text = name; label.textScale = 1; label.font = font; label.textColor = RGB(160, 160, 160); label.padding = Padding(0, 14, 0, 18); var dd = panel.Find<UIDropDown>("Dropdown"); dd.font = FontStore.Get(11); dd.textScale = 1; dd.width = 98; dd.name = name; dd.autoSize = false; dd.height = dd.font.size + dd.spritePadding.vertical + dd.textFieldPadding.vertical + dd.outlineSize * 2; //dd.autoListWidth = false; //dd.itemHeight = font.size; //dd.listHeight = font.size; dd.listPosition = UIDropDown.PopupListPosition.Below; dd.textFieldPadding = Padding(2, 0, 2, 8); dd.spritePadding = Padding(5, 8, 3, 8); dd.listPadding = Padding(0, 0); dd.itemPadding = Padding(3, 0, 0, 6); //dd.foregroundSpriteMode = UIForegroundSpriteMode.Stretch; dd.items = options; dd.selectedIndex = 0; //dd.eventDropdownOpen += (UIDropDown self, UIListBox popup, ref bool overridden) => { // Log.Debug($"popup: {popup.position}, {popup.size}"); // Log.Debug($"popup.p: {popup.parent}"); // overridden = true; //}; dd.eventDropdownClose += (UIDropDown self, UIListBox popup, ref bool overridden) => { self.Unfocus(); }; dd.eventSelectedIndexChanged += onSelectedIndexChanged; dd.selectedValue = initialValue; return dd; } public static UITextureSprite AddIcon(ref UIPanel parent, string name, uint size) { var icon = parent.AddUIComponent<UITextureSprite>(); icon.texture = Shicho.Resources.icons[name]; icon.width = icon.height = size; return icon; } public static SliderPane AddSliderPane<T>(ref UIPanel parent, SliderOption<T> opts, UIFont font = null) { var pane = new SliderPane() { wrapper = parent.AddUIComponent<UIPanel>(), }; pane.wrapper.padding.top = 4; pane.wrapper.width = pane.wrapper.parent.width - parent.padding.horizontal; pane.wrapper.autoSize = false; //panel.SetAutoLayout(LayoutDirection.Horizontal); //panel.backgroundSprite = "Menubar"; pane.wrapper.pivot = UIPivotPoint.MiddleLeft; pane.slider = pane.wrapper.AddUIComponent<UISlider>(); pane.slider.autoSize = true; pane.slider.relativePosition = new Vector2(font.size * 1.5f, 0); pane.slider.pivot = UIPivotPoint.MiddleLeft; pane.slider.anchor = UIAnchorStyle.Left | UIAnchorStyle.CenterVertical; pane.slider.minValue = opts.minValue; pane.slider.maxValue = opts.maxValue; pane.slider.stepSize = opts.stepSize; pane.slider.scrollWheelAmount = pane.slider.stepSize * 2 + float.Epsilon; pane.slider.backgroundSprite = "BudgetSlider"; { var thumb = pane.slider.AddUIComponent<UISprite>(); pane.slider.thumbObject = thumb; thumb.spriteName = "SliderBudget"; pane.slider.height = thumb.height + 8; pane.slider.thumbOffset = new Vector2(1, 1); } pane.slider.width = pane.wrapper.width - 24; pane.wrapper.height = pane.slider.height + 10; pane.slider.eventValueChanged += (c, value) => { if (pane.field != null) { pane.field.text = value.ToString(); } opts.onValueChanged.Invoke(c, value); }; if (opts.hasField) { pane.slider.width -= 48; pane.field = pane.wrapper.AddUIComponent<UITextField>(); pane.field.autoSize = false; pane.field.width = parent.width - pane.slider.width - parent.padding.horizontal - 20 - 6; pane.field.relativePosition = new Vector2(pane.field.parent.width - pane.field.width, 0); pane.field.anchor = UIAnchorStyle.CenterVertical | UIAnchorStyle.Right; pane.field.height -= 4; pane.field.readOnly = false; pane.field.builtinKeyNavigation = true; pane.field.numericalOnly = true; pane.field.allowFloats = true; pane.field.canFocus = true; pane.field.selectOnFocus = true; pane.field.submitOnFocusLost = true; pane.field.cursorBlinkTime = 0.5f; pane.field.cursorWidth = 1; pane.field.selectionSprite = "EmptySprite"; pane.field.normalBgSprite = "TextFieldPanel"; //field.hoveredBgSprite = "TextFieldPanelHovered"; pane.field.focusedBgSprite = "TextFieldPanel"; pane.field.clipChildren = true; pane.field.colorizeSprites = true; pane.field.color = Helper.RGB(30, 30, 30); pane.field.textColor = Helper.RGB(250, 250, 250); pane.field.font = FontStore.Get(11); pane.field.horizontalAlignment = UIHorizontalAlignment.Left; pane.field.padding = Helper.Padding(0, 6); //field.padding.top -= 5; //Log.Debug($"Page: {page.position}, {page.size}"); //Log.Debug($"Panel: {panel.position}, {panel.size}"); //Log.Debug($"Slider: {slider.position}, {slider.size}"); //Log.Debug($"Field: {field.position}, {field.size}"); pane.field.eventTextSubmitted += (c, text) => { if (text == "") return; try { pane.slider.value = float.Parse(text); } catch (Exception e) { Log.Error($"failed to set new value \"{text}\": {e}"); pane.field.text = ""; } }; } // hasField pane.slider.value = opts.initialValue; //pane.wrapper.height = pane.slider.height + (pane.field?.height).GetValueOrDefault(0); return pane; } public static void DeepDestroy(UIComponent component) { if (component == null) return; var children = component.GetComponentsInChildren<UIComponent>(); if (children != null && children.Length > 0) { for (int i = 0; i < children.Length; ++i) { if (children[i].parent == component) { DeepDestroy(children[i]); } } } UnityEngine.Object.Destroy(component); component = null; } } }
39.342246
210
0.546894
[ "MIT" ]
SETNAHQ/Shicho
Shicho/GUI/Helper.cs
14,716
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.EBS")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Elastic Block Store. This release introduces the EBS direct APIs for Snapshots: 1. ListSnapshotBlocks, which lists the block indexes and block tokens for blocks in an Amazon EBS snapshot. 2. ListChangedBlocks, which lists the block indexes and block tokens for blocks that are different between two snapshots of the same volume/snapshot lineage. 3. GetSnapshotBlock, which returns the data in a block of an Amazon EBS snapshot.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.3.100.15")]
55.71875
514
0.761077
[ "Apache-2.0" ]
tmlife485/myawskendra
sdk/code-analysis/ServiceAnalysis/EBS/Properties/AssemblyInfo.cs
1,783
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Cache.V20180301 { /// <summary> /// Response to put/get linked server (with properties) for Redis cache. /// </summary> [AzureNativeResourceType("azure-native:cache/v20180301:LinkedServer")] public partial class LinkedServer : Pulumi.CustomResource { /// <summary> /// Fully qualified resourceId of the linked redis cache. /// </summary> [Output("linkedRedisCacheId")] public Output<string> LinkedRedisCacheId { get; private set; } = null!; /// <summary> /// Location of the linked redis cache. /// </summary> [Output("linkedRedisCacheLocation")] public Output<string> LinkedRedisCacheLocation { get; private set; } = null!; /// <summary> /// Resource name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Terminal state of the link between primary and secondary redis cache. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// Role of the linked server. /// </summary> [Output("serverRole")] public Output<string> ServerRole { get; private set; } = null!; /// <summary> /// Resource type. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a LinkedServer resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public LinkedServer(string name, LinkedServerArgs args, CustomResourceOptions? options = null) : base("azure-native:cache/v20180301:LinkedServer", name, args ?? new LinkedServerArgs(), MakeResourceOptions(options, "")) { } private LinkedServer(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:cache/v20180301:LinkedServer", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:cache/v20180301:LinkedServer"}, new Pulumi.Alias { Type = "azure-native:cache:LinkedServer"}, new Pulumi.Alias { Type = "azure-nextgen:cache:LinkedServer"}, new Pulumi.Alias { Type = "azure-native:cache/v20170201:LinkedServer"}, new Pulumi.Alias { Type = "azure-nextgen:cache/v20170201:LinkedServer"}, new Pulumi.Alias { Type = "azure-native:cache/v20171001:LinkedServer"}, new Pulumi.Alias { Type = "azure-nextgen:cache/v20171001:LinkedServer"}, new Pulumi.Alias { Type = "azure-native:cache/v20190701:LinkedServer"}, new Pulumi.Alias { Type = "azure-nextgen:cache/v20190701:LinkedServer"}, new Pulumi.Alias { Type = "azure-native:cache/v20200601:LinkedServer"}, new Pulumi.Alias { Type = "azure-nextgen:cache/v20200601:LinkedServer"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing LinkedServer resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static LinkedServer Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new LinkedServer(name, id, options); } } public sealed class LinkedServerArgs : Pulumi.ResourceArgs { /// <summary> /// Fully qualified resourceId of the linked redis cache. /// </summary> [Input("linkedRedisCacheId", required: true)] public Input<string> LinkedRedisCacheId { get; set; } = null!; /// <summary> /// Location of the linked redis cache. /// </summary> [Input("linkedRedisCacheLocation", required: true)] public Input<string> LinkedRedisCacheLocation { get; set; } = null!; /// <summary> /// The name of the linked server that is being added to the Redis cache. /// </summary> [Input("linkedServerName")] public Input<string>? LinkedServerName { get; set; } /// <summary> /// The name of the Redis cache. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// Role of the linked server. /// </summary> [Input("serverRole", required: true)] public Input<Pulumi.AzureNative.Cache.V20180301.ReplicationRole> ServerRole { get; set; } = null!; public LinkedServerArgs() { } } }
41.727273
135
0.595705
[ "Apache-2.0" ]
sebtelko/pulumi-azure-native
sdk/dotnet/Cache/V20180301/LinkedServer.cs
6,426
C#
// Part of FemtoCraft | Copyright 2012-2013 Matvei Stefarov <me@matvei.org> | See LICENSE.txt // Based on fCraft.MapConversion.MapDAT - fCraft is Copyright 2009-2012 Matvei Stefarov <me@matvei.org> | See LICENSE.fCraft.txt using System; using System.IO; using System.IO.Compression; using System.Net; using JetBrains.Annotations; namespace Testosterone { static class DatMapConverter { static readonly byte[] Mapping = new byte[256]; static DatMapConverter() { Mapping[50] = (byte)Block.Air; // torch Mapping[51] = (byte)Block.Lava; // fire Mapping[52] = (byte)Block.Glass; // spawner Mapping[53] = (byte)Block.Slab; // wood stairs Mapping[54] = (byte)Block.Wood; // chest Mapping[55] = (byte)Block.Air; // redstone wire Mapping[56] = (byte)Block.IronOre; // diamond ore Mapping[57] = (byte)Block.Aqua; // diamond block Mapping[58] = (byte)Block.Log; // workbench Mapping[59] = (byte)Block.Leaves; // crops Mapping[60] = (byte)Block.Dirt; // soil Mapping[61] = (byte)Block.Stone; // furnace Mapping[62] = (byte)Block.Stone; // burning furnace Mapping[63] = (byte)Block.Air; // sign post Mapping[64] = (byte)Block.Air; // wooden door Mapping[65] = (byte)Block.Air; // ladder Mapping[66] = (byte)Block.Air; // rails Mapping[67] = (byte)Block.Slab; // cobblestone stairs Mapping[68] = (byte)Block.Air; // wall sign Mapping[69] = (byte)Block.Air; // lever Mapping[70] = (byte)Block.Air; // pressure plate Mapping[71] = (byte)Block.Air; // iron door Mapping[72] = (byte)Block.Air; // wooden pressure plate Mapping[73] = (byte)Block.IronOre; // redstone ore Mapping[74] = (byte)Block.IronOre; // glowing redstone ore Mapping[75] = (byte)Block.Air; // redstone torch (off) Mapping[76] = (byte)Block.Air; // redstone torch (on) Mapping[77] = (byte)Block.Air; // stone button Mapping[78] = (byte)Block.Air; // snow Mapping[79] = (byte)Block.Glass; // ice Mapping[80] = (byte)Block.White; // snow block Mapping[81] = (byte)Block.Leaves; // cactus Mapping[82] = (byte)Block.Gray; // clay Mapping[83] = (byte)Block.Leaves; // reed Mapping[84] = (byte)Block.Log; // jukebox Mapping[85] = (byte)Block.Wood; // fence Mapping[86] = (byte)Block.Orange; // pumpkin Mapping[87] = (byte)Block.Dirt; // netherstone Mapping[88] = (byte)Block.Gravel; // slow sand Mapping[89] = (byte)Block.Sand; // lightstone Mapping[90] = (byte)Block.Violet; // portal Mapping[91] = (byte)Block.Orange; // jack-o-lantern // all others default to 0/air } [NotNull] public static Map Load( [NotNull] string fileName ) { if( fileName == null ) throw new ArgumentNullException( "fileName" ); using( FileStream mapStream = File.OpenRead( fileName ) ) { byte[] temp = new byte[8]; Map map = null; mapStream.Seek( -4, SeekOrigin.End ); mapStream.Read( temp, 0, 4 ); mapStream.Seek( 0, SeekOrigin.Begin ); int uncompressedLength = BitConverter.ToInt32( temp, 0 ); byte[] data = new byte[uncompressedLength]; using( GZipStream reader = new GZipStream( mapStream, CompressionMode.Decompress, true ) ) { reader.Read( data, 0, uncompressedLength ); } for( int i = 0; i < uncompressedLength - 1; i++ ) { if( data[i] != 0xAC || data[i + 1] != 0xED ) continue; // bypassing the header crap int pointer = i + 6; Array.Copy( data, pointer, temp, 0, 2 ); pointer += IPAddress.HostToNetworkOrder( BitConverter.ToInt16( temp, 0 ) ); pointer += 13; int headerEnd; // find the end of serialization listing for( headerEnd = pointer; headerEnd < data.Length - 1; headerEnd++ ) { if( data[headerEnd] == 0x78 && data[headerEnd + 1] == 0x70 ) { headerEnd += 2; break; } } // start parsing serialization listing int offset = 0; int width = 0, length = 0, height = 0; Position spawn = new Position(); while( pointer < headerEnd ) { switch( (char)data[pointer] ) { case 'Z': offset++; break; case 'F': case 'I': offset += 4; break; case 'J': offset += 8; break; } pointer += 1; Array.Copy( data, pointer, temp, 0, 2 ); short skip = IPAddress.HostToNetworkOrder( BitConverter.ToInt16( temp, 0 ) ); pointer += 2; // look for relevant variables Array.Copy( data, headerEnd + offset - 4, temp, 0, 4 ); if( MemCmp( data, pointer, "width" ) ) { width = (ushort)IPAddress.HostToNetworkOrder( BitConverter.ToInt32( temp, 0 ) ); } else if( MemCmp( data, pointer, "depth" ) ) { height = (ushort)IPAddress.HostToNetworkOrder( BitConverter.ToInt32( temp, 0 ) ); } else if( MemCmp( data, pointer, "height" ) ) { length = (ushort)IPAddress.HostToNetworkOrder( BitConverter.ToInt32( temp, 0 ) ); } else if( MemCmp( data, pointer, "xSpawn" ) ) { spawn.X = (short)(IPAddress.HostToNetworkOrder( BitConverter.ToInt32( temp, 0 ) )*32 + 16); } else if( MemCmp( data, pointer, "ySpawn" ) ) { spawn.Z = (short)(IPAddress.HostToNetworkOrder( BitConverter.ToInt32( temp, 0 ) )*32 + 16); } else if( MemCmp( data, pointer, "zSpawn" ) ) { spawn.Y = (short)(IPAddress.HostToNetworkOrder( BitConverter.ToInt32( temp, 0 ) )*32 + 16); } pointer += skip; } map = new Map( width, length, height ) { Spawn = spawn }; // find the start of the block array bool foundBlockArray = false; offset = Array.IndexOf<byte>( data, 0x00, headerEnd ); while( offset != -1 && offset < data.Length - 2 ) { if( data[offset] == 0x00 && data[offset + 1] == 0x78 && data[offset + 2] == 0x70 ) { foundBlockArray = true; pointer = offset + 7; } offset = Array.IndexOf<byte>( data, 0x00, offset + 1 ); } // copy the block array... or fail if( !foundBlockArray ) { throw new Exception( "DatMapConverter: Could not locate block array." ); } Array.Copy( data, pointer, map.Blocks, 0, map.Blocks.Length ); // Map survivaltest/indev blocktypes to standard/presentation blocktypes map.ConvertBlockTypes( Mapping ); if( Config.Physics ) map.EnablePhysics(); break; } if( map == null ) { throw new Exception( "DatMapConverter: Error loading map." ); } return map; } } static bool MemCmp( [NotNull] byte[] data, int offset, [NotNull] string value ) { if( data == null ) throw new ArgumentNullException( "data" ); if( value == null ) throw new ArgumentNullException( "value" ); if( offset < 0 || offset > data.Length ) throw new ArgumentOutOfRangeException( "offset" ); for( int i = 0; i < value.Length; i++ ) { if( offset + i >= data.Length || data[offset + i] != value[i] ) return false; } return true; } } }
49.076503
128
0.472999
[ "BSD-3-Clause" ]
MCClassicServerArchive/Testosterone
Testosterone/DATMapConverter.cs
8,983
C#
using CodeWars; using NUnit.Framework; using Interval = System.ValueTuple<int, int>; namespace CodeWarsTests { [TestFixture] public class IntervalsTests { [Test] public void ShouldHandleEmptyIntervals() { Assert.AreEqual(0, Intervals.SumIntervals(new Interval[] { })); Assert.AreEqual(0, Intervals.SumIntervals(new Interval[] { (4, 4), (6, 6), (8, 8) })); } [Test] public void ShouldAddDisjoinedIntervals() { Assert.AreEqual(9, Intervals.SumIntervals(new Interval[] { (1, 2), (6, 10), (11, 15) })); Assert.AreEqual(11, Intervals.SumIntervals(new Interval[] { (4, 8), (9, 10), (15, 21) })); Assert.AreEqual(7, Intervals.SumIntervals(new Interval[] { (-1, 4), (-5, -3) })); Assert.AreEqual(78, Intervals.SumIntervals(new Interval[] { (-245, -218), (-194, -179), (-155, -119) })); } [Test] public void ShouldAddAdjacentIntervals() { Assert.AreEqual(54, Intervals.SumIntervals(new Interval[] { (1, 2), (2, 6), (6, 55) })); Assert.AreEqual(23, Intervals.SumIntervals(new Interval[] { (-2, -1), (-1, 0), (0, 21) })); } [Test] public void ShouldAddOverlappingIntervals() { Assert.AreEqual(7, Intervals.SumIntervals(new Interval[] { (1, 4), (7, 10), (3, 5) })); Assert.AreEqual(6, Intervals.SumIntervals(new Interval[] { (5, 8), (3, 6), (1, 2) })); Assert.AreEqual(19, Intervals.SumIntervals(new Interval[] { (1, 5), (10, 20), (1, 6), (16, 19), (5, 11) })); } [Test] public void ShouldHandleMixedIntervals() { Assert.AreEqual(13, Intervals.SumIntervals(new Interval[] { (2, 5), (-1, 2), (-40, -35), (6, 8) })); Assert.AreEqual(1234, Intervals.SumIntervals(new Interval[] { (-7, 8), (-2, 10), (5, 15), (2000, 3150), (-5400, -5338) })); Assert.AreEqual(158, Intervals.SumIntervals(new Interval[] { (-101, 24), (-35, 27), (27, 53), (-105, 20), (-36, 26) })); } } }
42.897959
135
0.543292
[ "MIT" ]
soylegendario/codewars
src/CodeWarsTests/IntervalsTests.cs
2,102
C#
/* * Copyright (c) 2006-2014, openmetaverse.org * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Net; using System.Text; using System.Threading; using OpenMetaverse.Packets; using OpenMetaverse.StructuredData; using OpenMetaverse.Interfaces; using OpenMetaverse.Http; namespace OpenMetaverse { /// <summary> /// Capabilities is the name of the bi-directional HTTP REST protocol /// used to communicate non real-time transactions such as teleporting or /// group messaging /// </summary> public partial class Caps { /// <summary> /// Triggered when an event is received via the EventQueueGet /// capability /// </summary> /// <param name="capsKey">Event name</param> /// <param name="message">Decoded event data</param> /// <param name="simulator">The simulator that generated the event</param> //public delegate void EventQueueCallback(string message, StructuredData.OSD body, Simulator simulator); public delegate void EventQueueCallback(string capsKey, IMessage message, Simulator simulator); /// <summary>Reference to the simulator this system is connected to</summary> public Simulator Simulator; internal string _SeedCapsURI; internal Dictionary<string, Uri> _Caps = new Dictionary<string, Uri>(); private CapsClient _SeedRequest; private EventQueueClient _EventQueueCap = null; /// <summary>Capabilities URI this system was initialized with</summary> public string SeedCapsURI { get { return _SeedCapsURI; } } /// <summary>Whether the capabilities event queue is connected and /// listening for incoming events</summary> public bool IsEventQueueRunning { get { if (_EventQueueCap != null) return _EventQueueCap.Running; else return false; } } /// <summary> /// Default constructor /// </summary> /// <param name="simulator"></param> /// <param name="seedcaps"></param> internal Caps(Simulator simulator, string seedcaps) { Simulator = simulator; _SeedCapsURI = seedcaps; MakeSeedRequest(); } public void Disconnect(bool immediate) { Logger.Log(String.Format("Caps system for {0} is {1}", Simulator, (immediate ? "aborting" : "disconnecting")), Helpers.LogLevel.Info, Simulator.Client); if (_SeedRequest != null) _SeedRequest.Cancel(); if (_EventQueueCap != null) _EventQueueCap.Stop(immediate); } /// <summary> /// Request the URI of a named capability /// </summary> /// <param name="capability">Name of the capability to request</param> /// <returns>The URI of the requested capability, or String.Empty if /// the capability does not exist</returns> public Uri CapabilityURI(string capability) { Uri cap; if (_Caps.TryGetValue(capability, out cap)) return cap; else return null; } private void MakeSeedRequest() { if (Simulator == null || !Simulator.Client.Network.Connected) return; // Create a request list OSDArray req = new OSDArray(); // This list can be updated by using the following command to obtain a current list of capabilities the official linden viewer supports: // wget -q -O - https://bitbucket.org/lindenlab/viewer-development/raw/default/indra/newview/llviewerregion.cpp | grep 'capabilityNames.append' | sed 's/^[ \t]*//;s/capabilityNames.append("/req.Add("/' req.Add("AgentState"); req.Add("AttachmentResources"); req.Add("AvatarPickerSearch"); req.Add("CharacterProperties"); req.Add("ChatSessionRequest"); req.Add("CopyInventoryFromNotecard"); req.Add("CreateInventoryCategory"); req.Add("DispatchRegionInfo"); req.Add("EnvironmentSettings"); req.Add("EstateChangeInfo"); req.Add("EventQueueGet"); req.Add("FetchInventory2"); req.Add("FetchInventoryDescendents2"); req.Add("FetchLib2"); req.Add("FetchLibDescendents2"); req.Add("GetDisplayNames"); req.Add("GetMesh"); req.Add("GetObjectCost"); req.Add("GetObjectPhysicsData"); req.Add("GetTexture"); req.Add("GroupAPIv1"); req.Add("GroupMemberData"); req.Add("GroupProposalBallot"); req.Add("HomeLocation"); req.Add("IncrementCOFVersion"); req.Add("LandResources"); req.Add("MapLayer"); req.Add("MapLayerGod"); req.Add("MeshUploadFlag"); req.Add("NavMeshGenerationStatus"); req.Add("NewFileAgentInventory"); req.Add("ObjectMedia"); req.Add("ObjectMediaNavigate"); req.Add("ObjectNavMeshProperties"); req.Add("ParcelPropertiesUpdate"); req.Add("ParcelVoiceInfoRequest"); req.Add("ProductInfoRequest"); req.Add("ProvisionVoiceAccountRequest"); req.Add("RemoteParcelRequest"); req.Add("RenderMaterials"); req.Add("RequestTextureDownload"); req.Add("ResourceCostSelected"); req.Add("RetrieveNavMeshSrc"); req.Add("SearchStatRequest"); req.Add("SearchStatTracking"); req.Add("SendPostcard"); req.Add("SendUserReport"); req.Add("SendUserReportWithScreenshot"); req.Add("ServerReleaseNotes"); req.Add("SetDisplayName"); req.Add("SimConsoleAsync"); req.Add("SimulatorFeatures"); req.Add("StartGroupProposal"); req.Add("TerrainNavMeshProperties"); req.Add("TextureStats"); req.Add("UntrustedSimulatorMessage"); req.Add("UpdateAgentInformation"); req.Add("UpdateAgentLanguage"); req.Add("UpdateAvatarAppearance"); req.Add("UpdateGestureAgentInventory"); req.Add("UpdateGestureTaskInventory"); req.Add("UpdateNotecardAgentInventory"); req.Add("UpdateNotecardTaskInventory"); req.Add("UpdateScriptAgent"); req.Add("UpdateScriptTask"); req.Add("UploadBakedTexture"); req.Add("ViewerMetrics"); req.Add("ViewerStartAuction"); req.Add("ViewerStats"); _SeedRequest = new CapsClient(new Uri(_SeedCapsURI)); _SeedRequest.OnComplete += new CapsClient.CompleteCallback(SeedRequestCompleteHandler); _SeedRequest.BeginGetResponse(req, OSDFormat.Xml, Simulator.Client.Settings.CAPS_TIMEOUT); } private void SeedRequestCompleteHandler(CapsClient client, OSD result, Exception error) { if (result != null && result.Type == OSDType.Map) { OSDMap respTable = (OSDMap)result; foreach (string cap in respTable.Keys) { _Caps[cap] = respTable[cap].AsUri(); } if (_Caps.ContainsKey("EventQueueGet")) { Logger.DebugLog("Starting event queue for " + Simulator.ToString(), Simulator.Client); _EventQueueCap = new EventQueueClient(_Caps["EventQueueGet"]); _EventQueueCap.OnConnected += EventQueueConnectedHandler; _EventQueueCap.OnEvent += EventQueueEventHandler; _EventQueueCap.Start(); } } else if ( error != null && error is WebException && ((WebException)error).Response != null && ((HttpWebResponse)((WebException)error).Response).StatusCode == HttpStatusCode.NotFound) { // 404 error Logger.Log("Seed capability returned a 404, capability system is aborting", Helpers.LogLevel.Error); } else { // The initial CAPS connection failed, try again MakeSeedRequest(); } } private void EventQueueConnectedHandler() { Simulator.Client.Network.RaiseConnectedEvent(Simulator); } /// <summary> /// Process any incoming events, check to see if we have a message created for the event, /// </summary> /// <param name="eventName"></param> /// <param name="body"></param> private void EventQueueEventHandler(string eventName, OSDMap body) { IMessage message = Messages.MessageUtils.DecodeEvent(eventName, body); if (message != null) { Simulator.Client.Network.CapsEvents.BeginRaiseEvent(eventName, message, Simulator); #region Stats Tracking if (Simulator.Client.Settings.TRACK_UTILIZATION) { Simulator.Client.Stats.Update(eventName, OpenMetaverse.Stats.Type.Message, 0, body.ToString().Length); } #endregion } else { Logger.Log("No Message handler exists for event " + eventName + ". Unable to decode. Will try Generic Handler next", Helpers.LogLevel.Warning); Logger.Log("Please report this information to http://jira.openmetaverse.org/: \n" + body, Helpers.LogLevel.Debug); // try generic decoder next which takes a caps event and tries to match it to an existing packet if (body.Type == OSDType.Map) { OSDMap map = (OSDMap)body; Packet packet = Packet.BuildPacket(eventName, map); if (packet != null) { NetworkManager.IncomingPacket incomingPacket; incomingPacket.Simulator = Simulator; incomingPacket.Packet = packet; Logger.DebugLog("Serializing " + packet.Type.ToString() + " capability with generic handler", Simulator.Client); Simulator.Client.Network.PacketInbox.Enqueue(incomingPacket); } else { Logger.Log("No Packet or Message handler exists for " + eventName, Helpers.LogLevel.Warning); } } } } } }
42.23569
215
0.573501
[ "BSD-3-Clause" ]
CasperTech/libopenmetaverse
OpenMetaverse/Caps.cs
12,544
C#
// // DO NOT MODIFY. THIS IS AUTOMATICALLY GENERATED FILE. // #nullable enable #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. using System; using System.Collections.Generic; namespace CefNet.DevTools.Protocol.Database { /// <summary>Database error.</summary> public sealed class Error { /// <summary>Error message.</summary> public string Message { get; set; } /// <summary>Error code.</summary> public int Code { get; set; } } }
27.333333
140
0.684669
[ "MIT" ]
CefNet/CefNet.DevTools.Protocol
CefNet.DevTools.Protocol/Generated/Database/Error.g.cs
574
C#
/******************************************************************************* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * API Version: 2006-03-01 * */ using System; using System.IO; #if AWS_ASYNC_API using System.Threading; using System.Threading.Tasks; #endif namespace Amazon.Runtime.Internal.Util { /// <summary> /// A wrapper stream that calculates a hash of the base stream as it /// is being read. /// The calculated hash is only available after the stream is closed or /// CalculateHash is called. After calling CalculateHash, any further reads /// on the streams will not change the CalculatedHash. /// If an ExpectedHash is specified and is not equal to the calculated hash, /// Close or CalculateHash methods will throw an AmazonClientException. /// If CalculatedHash is calculated for only the portion of the stream that /// is read. /// </summary> /// <exception cref="Amazon.Runtime.AmazonClientException"> /// Exception thrown during Close() or CalculateHash(), if ExpectedHash is set and /// is different from CalculateHash that the stream calculates, provided that /// CalculatedHash is not a zero-length byte array. /// </exception> public abstract class HashStream : WrapperStream { #region Properties /// <summary> /// Algorithm to use to calculate hash. /// </summary> protected IHashingWrapper Algorithm { get; set; } /// <summary> /// True if hashing is finished and no more hashing should be done; /// otherwise false. /// </summary> protected bool FinishedHashing { get { return CalculatedHash != null; } } /// <summary> /// Current position in the stream. /// </summary> protected long CurrentPosition { get; private set; } /// <summary> /// Calculated hash for the stream. /// This value is set only after the stream is closed. /// </summary> public byte[] CalculatedHash { get; protected set; } /// <summary> /// Expected hash value. Compared against CalculatedHash upon Close(). /// If the hashes are different, an AmazonClientException is thrown. /// </summary> public byte[] ExpectedHash { get; private set; } /// <summary> /// Expected length of stream. /// </summary> public long ExpectedLength { get; protected set; } #endregion #region Constructors ///// <summary> ///// Initializes an HashStream with a hash algorithm and a base stream. ///// </summary> ///// <param name="baseStream">Stream to calculate hash for.</param> //protected HashStream(Stream baseStream) // : this(baseStream, null) { } /// <summary> /// Initializes an HashStream with a hash algorithm and a base stream. /// </summary> /// <param name="baseStream">Stream to calculate hash for.</param> /// <param name="expectedHash"> /// Expected hash. Will be compared against calculated hash on stream close. /// Pass in null to disable check. /// </param> /// <param name="expectedLength"> /// Expected length of the stream. If the reading stops before reaching this /// position, CalculatedHash will be set to empty array. /// </param> protected HashStream(Stream baseStream, byte[] expectedHash, long expectedLength) : base(baseStream) { ExpectedHash = expectedHash; ExpectedLength = expectedLength; ValidateBaseStream(); Reset(); } #endregion #region Stream overrides /// <summary> /// Reads a sequence of bytes from the current stream and advances the position /// within the stream by the number of bytes read. /// </summary> /// <param name="buffer"> /// An array of bytes. When this method returns, the buffer contains the specified /// byte array with the values between offset and (offset + count - 1) replaced /// by the bytes read from the current source. /// </param> /// <param name="offset"> /// The zero-based byte offset in buffer at which to begin storing the data read /// from the current stream. /// </param> /// <param name="count"> /// The maximum number of bytes to be read from the current stream. /// </param> /// <returns> /// The total number of bytes read into the buffer. This can be less than the /// number of bytes requested if that many bytes are not currently available, /// or zero (0) if the end of the stream has been reached. /// </returns> public override int Read(byte[] buffer, int offset, int count) { int result = base.Read(buffer, offset, count); CurrentPosition += result; if (!FinishedHashing) { Algorithm.AppendBlock(buffer, offset, result); } return result; } #if AWS_ASYNC_API /// <summary> /// Asynchronously reads a sequence of bytes from the current stream, advances /// the position within the stream by the number of bytes read, and monitors /// cancellation requests. /// </summary> /// <param name="buffer"> /// An array of bytes. When this method returns, the buffer contains the specified /// byte array with the values between offset and (offset + count - 1) replaced /// by the bytes read from the current source. /// </param> /// <param name="offset"> /// The zero-based byte offset in buffer at which to begin storing the data read /// from the current stream. /// </param> /// <param name="count"> /// The maximum number of bytes to be read from the current stream. /// </param> /// <param name="cancellationToken"> /// The token to monitor for cancellation requests. The default value is /// System.Threading.CancellationToken.None. /// </param> /// <returns> /// A task that represents the asynchronous read operation. The value of the TResult /// parameter contains the total number of bytes read into the buffer. This can be /// less than the number of bytes requested if that many bytes are not currently /// available, or zero (0) if the end of the stream has been reached. /// </returns> public async override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { int result = await base.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false); CurrentPosition += result; if (!FinishedHashing) { Algorithm.AppendBlock(buffer, offset, result); } return result; } #endif #if !NETSTANDARD /// <summary> /// Closes the underlying stream and finishes calculating the hash. /// If an ExpectedHash is specified and is not equal to the calculated hash, /// this method will throw an AmazonClientException. /// </summary> /// <exception cref="Amazon.Runtime.AmazonClientException"> /// If ExpectedHash is set and is different from CalculateHash that the stream calculates. /// </exception> public override void Close() { CalculateHash(); base.Close(); } #endif protected override void Dispose(bool disposing) { try { CalculateHash(); if (disposing && Algorithm != null) { Algorithm.Dispose(); Algorithm = null; } } finally { base.Dispose(disposing); } } /// <summary> /// Gets a value indicating whether the current stream supports seeking. /// HashStream does not support seeking, this will always be false. /// </summary> public override bool CanSeek { get { // Restrict random access, as this will break hashing. return false; } } /// <summary> /// Gets or sets the position within the current stream. /// HashStream does not support seeking, attempting to set Position /// will throw NotSupportedException. /// </summary> public override long Position { get { throw new NotSupportedException("HashStream does not support seeking"); } set { // Restrict random access, as this will break hashing. throw new NotSupportedException("HashStream does not support seeking"); } } /// <summary> /// Sets the position within the current stream. /// HashStream does not support seeking, attempting to call Seek /// will throw NotSupportedException. /// </summary> /// <param name="offset">A byte offset relative to the origin parameter.</param> /// <param name="origin"> /// A value of type System.IO.SeekOrigin indicating the reference point used /// to obtain the new position.</param> /// <returns>The new position within the current stream.</returns> public override long Seek(long offset, SeekOrigin origin) { // Restrict random access, as this will break hashing. throw new NotSupportedException("HashStream does not support seeking"); } /// <summary> /// Gets the overridden length used to construct the HashStream /// </summary> public override long Length { get { return this.ExpectedLength; } } #endregion #region Public methods /// <summary> /// Calculates the hash for the stream so far and disables any further /// hashing. /// </summary> public virtual void CalculateHash() { if (!FinishedHashing) { if (ExpectedLength < 0 || CurrentPosition == ExpectedLength) { CalculatedHash = Algorithm.AppendLastBlock(new byte[0]); } else CalculatedHash = new byte[0]; if (CalculatedHash.Length > 0 && ExpectedHash != null && ExpectedHash.Length > 0) { if (!CompareHashes(ExpectedHash, CalculatedHash)) throw new AmazonClientException("Expected hash not equal to calculated hash"); } } } /// <summary> /// Resets the hash stream to starting state. /// Use this if the underlying stream has been modified and needs /// to be rehashed without reconstructing the hierarchy. /// </summary> public void Reset() { CurrentPosition = 0; CalculatedHash = null; if (Algorithm != null) Algorithm.Clear(); var baseHashStream = BaseStream as HashStream; if (baseHashStream != null) { baseHashStream.Reset(); } } #endregion #region Private methods /// <summary> /// Validates the underlying stream. /// </summary> private void ValidateBaseStream() { // Fast-fail on unusable streams if (!BaseStream.CanRead && !BaseStream.CanWrite) throw new InvalidDataException("HashStream does not support base streams that are not capable of reading or writing"); } /// <summary> /// Compares two hashes (arrays of bytes). /// </summary> /// <param name="expected">Expected hash.</param> /// <param name="actual">Actual hash.</param> /// <returns> /// True if the hashes are identical; otherwise false. /// </returns> protected static bool CompareHashes(byte[] expected, byte[] actual) { if (ReferenceEquals(expected, actual)) return true; if (expected == null || actual == null) return (expected == actual); if (expected.Length != actual.Length) return false; for (int i = 0; i < expected.Length; i++) { if (expected[i] != actual[i]) return false; } return true; } #endregion } /// <summary> /// A wrapper stream that calculates a hash of the base stream as it /// is being read or written. /// The calculated hash is only available after the stream is closed or /// CalculateHash is called. After calling CalculateHash, any further reads /// on the streams will not change the CalculatedHash. /// If an ExpectedHash is specified and is not equal to the calculated hash, /// Close or CalculateHash methods will throw an AmazonClientException. /// If base stream's position is not 0 or HashOnReads is true and the entire stream is /// not read, the CalculatedHash will be set to an empty byte array and /// comparison to ExpectedHash will not be made. /// </summary> /// <exception cref="Amazon.Runtime.AmazonClientException"> /// Exception thrown during Close() or CalculateHash(), if ExpectedHash is set and /// is different from CalculateHash that the stream calculates, provided that /// CalculatedHash is not a zero-length byte array. /// </exception> public class HashStream<T> : HashStream where T : IHashingWrapper, new() { #region Constructors /// <summary> /// Initializes an HashStream with a hash algorithm and a base stream. /// </summary> /// <param name="baseStream">Stream to calculate hash for.</param> /// <param name="expectedHash"> /// Expected hash. Will be compared against calculated hash on stream close. /// Pass in null to disable check. /// </param> /// <param name="expectedLength"> /// Expected length of the stream. If the reading stops before reaching this /// position, CalculatedHash will be set to empty array. /// </param> public HashStream(Stream baseStream, byte[] expectedHash, long expectedLength) : base(baseStream, expectedHash, expectedLength) { Algorithm = new T(); } #endregion } /// <summary> /// A wrapper stream that calculates an MD5 hash of the base stream as it /// is being read or written. /// The calculated hash is only available after the stream is closed or /// CalculateHash is called. After calling CalculateHash, any further reads /// on the streams will not change the CalculatedHash. /// If an ExpectedHash is specified and is not equal to the calculated hash, /// Close or CalculateHash methods will throw an AmazonClientException. /// If base stream's position is not 0 or HashOnReads is true and the entire stream is /// not read, the CalculatedHash will be set to an empty byte array and /// comparison to ExpectedHash will not be made. /// </summary> /// <exception cref="Amazon.Runtime.AmazonClientException"> /// Exception thrown during Close() or CalculateHash(), if ExpectedHash is set and /// is different from CalculateHash that the stream calculates, provided that /// CalculatedHash is not a zero-length byte array. /// </exception> public class MD5Stream : HashStream<HashingWrapperMD5> { private Logger _logger; #region Constructors /// <summary> /// Initializes an MD5Stream with a base stream. /// </summary> /// <param name="baseStream">Stream to calculate hash for.</param> /// <param name="expectedHash"> /// Expected hash. Will be compared against calculated hash on stream close. /// Pass in null to disable check. /// </param> /// <param name="expectedLength"> /// Expected length of the stream. If the reading stops before reaching this /// position, CalculatedHash will be set to empty array. /// </param> public MD5Stream(Stream baseStream, byte[] expectedHash, long expectedLength) : base(baseStream, expectedHash, expectedLength) { _logger = Logger.GetLogger(this.GetType()); } #endregion } }
39.113978
135
0.567902
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Core/Amazon.Runtime/Internal/Util/HashStream.cs
18,190
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Network.Latest { /// <summary> /// Route resource. /// Latest API Version: 2020-08-01. /// </summary> [Obsolete(@"The 'latest' version is deprecated. Please migrate to the resource in the top-level module: 'azure-nextgen:network:Route'.")] [AzureNextGenResourceType("azure-nextgen:network/latest:Route")] public partial class Route : Pulumi.CustomResource { /// <summary> /// The destination CIDR to which the route applies. /// </summary> [Output("addressPrefix")] public Output<string?> AddressPrefix { get; private set; } = null!; /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> [Output("etag")] public Output<string> Etag { get; private set; } = null!; /// <summary> /// A value indicating whether this route overrides overlapping BGP routes regardless of LPM. /// </summary> [Output("hasBgpOverride")] public Output<bool?> HasBgpOverride { get; private set; } = null!; /// <summary> /// The name of the resource that is unique within a resource group. This name can be used to access the resource. /// </summary> [Output("name")] public Output<string?> Name { get; private set; } = null!; /// <summary> /// The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is VirtualAppliance. /// </summary> [Output("nextHopIpAddress")] public Output<string?> NextHopIpAddress { get; private set; } = null!; /// <summary> /// The type of Azure hop the packet should be sent to. /// </summary> [Output("nextHopType")] public Output<string> NextHopType { get; private set; } = null!; /// <summary> /// The provisioning state of the route resource. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// The type of the resource. /// </summary> [Output("type")] public Output<string?> Type { get; private set; } = null!; /// <summary> /// Create a Route resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public Route(string name, RouteArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:network/latest:Route", name, args ?? new RouteArgs(), MakeResourceOptions(options, "")) { } private Route(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:network/latest:Route", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:network:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20150501preview:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20150615:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20160330:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20160601:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20160901:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20161201:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20170301:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20170601:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20170801:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20170901:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20171001:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20171101:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180101:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180201:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180401:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180601:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180701:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:Route"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:Route"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing Route resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static Route Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new Route(name, id, options); } } public sealed class RouteArgs : Pulumi.ResourceArgs { /// <summary> /// The destination CIDR to which the route applies. /// </summary> [Input("addressPrefix")] public Input<string>? AddressPrefix { get; set; } /// <summary> /// A value indicating whether this route overrides overlapping BGP routes regardless of LPM. /// </summary> [Input("hasBgpOverride")] public Input<bool>? HasBgpOverride { get; set; } /// <summary> /// Resource ID. /// </summary> [Input("id")] public Input<string>? Id { get; set; } /// <summary> /// The name of the resource that is unique within a resource group. This name can be used to access the resource. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is VirtualAppliance. /// </summary> [Input("nextHopIpAddress")] public Input<string>? NextHopIpAddress { get; set; } /// <summary> /// The type of Azure hop the packet should be sent to. /// </summary> [Input("nextHopType", required: true)] public InputUnion<string, Pulumi.AzureNextGen.Network.Latest.RouteNextHopType> NextHopType { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the route. /// </summary> [Input("routeName")] public Input<string>? RouteName { get; set; } /// <summary> /// The name of the route table. /// </summary> [Input("routeTableName", required: true)] public Input<string> RouteTableName { get; set; } = null!; /// <summary> /// The type of the resource. /// </summary> [Input("type")] public Input<string>? Type { get; set; } public RouteArgs() { } } }
46.474654
146
0.585126
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Network/Latest/Route.cs
10,085
C#
// Java Genetic Algorithm Library. // Copyright (c) 2017 Franz Wilhelmstötter // // 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. // // Author: // Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at) using System; using System.Linq; using Jenetics.Util; using Xunit; namespace Jenetics { public class PopulationTest : ObjectTesterBase<Population<DoubleGene, double>> { private static readonly Func<Genotype<DoubleGene>, double> Ff = gt => gt.Gene.Allele; private static readonly Func<double, double> Fs = d => d; private static Phenotype<DoubleGene, double> Pt(double value) { return Phenotype.Of(Genotype.Of(DoubleChromosome.Of(DoubleGene.Of(value, 0, 10))), 0, Ff, Fs); } protected override Factory<Population<DoubleGene, double>> Factory() { return () => { var gt = Genotype.Of(DoubleChromosome.Of(0, 1)); return new Population<DoubleGene, double>(100) .Fill(() => Phenotype.Of(gt.NewInstance(), 1, Ff, Fs), 100); }; } [Fact] public void Empty() { var genotype = Genotype.Of( Enumerable.Range(0, 10) .Select(i => DoubleChromosome.Of(0, 10, 10)) .ToImmutableSeq() ); var pop = Population.Empty<DoubleGene, bool>(); Assert.True(0 == pop.Count); Assert.True(pop.IsEmpty); pop.Add(Phenotype.Of(genotype, 1, chromosomes => true)); Assert.True(1 == pop.Count); Assert.False(pop.IsEmpty); } [Fact] public void Sort() { var population = new Population<DoubleGene, double>(); var random = RandomRegistry.GetRandom(); for (var i = 0; i < 100; ++i) population.Add(Pt(random.Next() * 9.0)); population.PopulationSort(); for (var i = 0; i < population.Count - 1; ++i) { var first = Ff(population[i].GetGenotype()); var second = Ff(population[i + 1].GetGenotype()); Assert.True(first.CompareTo(second) >= 0); } Lists.Shuffle(population); population.SortWith(Optimize.Maximum.Descending<double>()); for (var i = 0; i < population.Count - 1; ++i) { var first = Ff(population[i].GetGenotype()); var second = Ff(population[i + 1].GetGenotype()); Assert.True(first.CompareTo(second) >= 0, first + "<" + second); } Lists.Shuffle(population); population.SortWith(Optimize.Minimum.Descending<double>()); for (var i = 0; i < population.Count - 1; ++i) { var first = Ff(population[i].GetGenotype()); var second = Ff(population[i + 1].GetGenotype()); Assert.True(first.CompareTo(second) <= 0, first + ">" + second); } } } }
33.820755
106
0.560112
[ "Apache-2.0" ]
TiZott/jenetics.net
src/core/Jenetics.Tests~/PopulationTest.cs
3,589
C#
using System; using Akka.Configuration; using Akka.Persistence.Sql.Linq2Db.Config; using Akka.Persistence.Sql.Linq2Db.Db; using Akka.Persistence.Sql.Linq2Db.Journal; using Akka.Persistence.Sql.Linq2Db.Journal.Types; using Akka.Persistence.TCK.Journal; using LinqToDB; using Xunit.Abstractions; namespace Akka.Persistence.Sql.Linq2Db.Tests { public class SQLServerJournalSpec : JournalSpec { private static readonly Configuration.Config conf = SQLServerJournalSpecConfig.Create(ConnectionString.Instance,"journalSpec"); public SQLServerJournalSpec(ITestOutputHelper outputHelper) : base(conf, "SQLServer", outputHelper) { var connFactory = new AkkaPersistenceDataConnectionFactory(new JournalConfig(conf.GetConfig("akka.persistence.journal.linq2db"))); using (var conn = connFactory.GetConnection()) { try { conn.GetTable<JournalRow>().Delete(); } catch (Exception e) { } try { conn.GetTable<JournalMetaData>().Delete(); } catch (Exception e) { } } Initialize(); } // TODO: hack. Replace when https://github.com/akkadotnet/akka.net/issues/3811 protected override bool SupportsSerialization => false; } }
32.847826
142
0.583719
[ "Apache-2.0" ]
to11mtm/Akka.Persistence.Linq2Db
src/Akka.Persistence.Sql.Linq2Db.Tests/SQLServerJournalSpec.cs
1,513
C#
namespace System.Collections.Generic { public record ChunkResultItem<T> : ChunkResult<T>{ public T Item { get; init; } public ChunkResultItem(T item) { this.Item = item; } } }
17.923077
54
0.553648
[ "MIT" ]
MediatedCommunications/Extensions
System.Extensions/System/Collections/Generic/ChunkResultItem.cs
235
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/winioctl.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop.Windows; public static partial class DeviceDsmAction { [NativeTypeName("#define DeviceDsmAction_None (0x00000000u)")] public const uint DeviceDsmAction_None = (0x00000000U); [NativeTypeName("#define DeviceDsmAction_Trim (0x00000001u)")] public const uint DeviceDsmAction_Trim = (0x00000001U); [NativeTypeName("#define DeviceDsmAction_Notification (0x00000002u | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_Notification = (0x00000002U | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_OffloadRead (0x00000003u | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_OffloadRead = (0x00000003U | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_OffloadWrite (0x00000004u)")] public const uint DeviceDsmAction_OffloadWrite = (0x00000004U); [NativeTypeName("#define DeviceDsmAction_Allocation (0x00000005u | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_Allocation = (0x00000005U | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_Repair (0x00000006u | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_Repair = (0x00000006U | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_Scrub (0x00000007u | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_Scrub = (0x00000007U | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_DrtQuery (0x00000008u | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_DrtQuery = (0x00000008U | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_DrtClear (0x00000009u | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_DrtClear = (0x00000009U | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_DrtDisable (0x0000000Au | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_DrtDisable = (0x0000000AU | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_TieringQuery (0x0000000Bu | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_TieringQuery = (0x0000000BU | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_Map (0x0000000Cu | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_Map = (0x0000000CU | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_RegenerateParity (0x0000000Du | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_RegenerateParity = (0x0000000DU | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_NvCache_Change_Priority (0x0000000Eu | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_NvCache_Change_Priority = (0x0000000EU | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_NvCache_Evict (0x0000000Fu | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_NvCache_Evict = (0x0000000FU | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_TopologyIdQuery (0x00000010u | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_TopologyIdQuery = (0x00000010U | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_GetPhysicalAddresses (0x00000011u | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_GetPhysicalAddresses = (0x00000011U | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_ScopeRegen (0x00000012u | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_ScopeRegen = (0x00000012U | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_ReportZones (0x00000013u | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_ReportZones = (0x00000013U | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_OpenZone (0x00000014u | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_OpenZone = (0x00000014U | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_FinishZone (0x00000015u | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_FinishZone = (0x00000015U | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_CloseZone (0x00000016u | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_CloseZone = (0x00000016U | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_ResetWritePointer (0x00000017u)")] public const uint DeviceDsmAction_ResetWritePointer = (0x00000017U); [NativeTypeName("#define DeviceDsmAction_GetRangeErrorInfo (0x00000018u | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_GetRangeErrorInfo = (0x00000018U | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_WriteZeroes (0x00000019u)")] public const uint DeviceDsmAction_WriteZeroes = (0x00000019U); [NativeTypeName("#define DeviceDsmAction_LostQuery (0x0000001Au | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_LostQuery = (0x0000001AU | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_GetFreeSpace (0x0000001Bu | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_GetFreeSpace = (0x0000001BU | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_ConversionQuery (0x0000001Cu | DeviceDsmActionFlag_NonDestructive)")] public const uint DeviceDsmAction_ConversionQuery = (0x0000001CU | (0x80000000)); [NativeTypeName("#define DeviceDsmAction_VdtSet (0x0000001Du)")] public const uint DeviceDsmAction_VdtSet = (0x0000001DU); }
58.72
145
0.7953
[ "MIT" ]
reflectronic/terrafx.interop.windows
sources/Interop/Windows/Windows/um/winioctl/DeviceDsmAction.cs
5,874
C#
/* The MIT License (MIT) Copyright (c) 2015 Calvin Baart Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections.Generic; using UnityEngine; public class AudioChannel { public static int NumChannels = 2; public static int SampleRate = 44100; public int ChannelId; public List<ClipInfo> Clips; //State Info public Instrument instrument; public int coarseVolume; public int coarseExpression; public int coarsePan; public int fineVolume; public int fineExpression; public int finePan; public bool sustain; public float volume; public float[] data; public float pitchBend; public float rvt; public bool changed; public AudioChannel(int channelID) { SampleRate = AudioSettings.outputSampleRate; this.ChannelId = channelID; this.Clips = new List<ClipInfo>(); Reset(); } public void Reset() { this.instrument = Instrument.AcousticGrandPiano; this.volume = 1.0f; this.coarseVolume = 127; // int(0.5 * 0xFE) this.coarseExpression = 127; this.coarsePan = 63; //int(0.5 * 0x7F) this.finePan = 63; this.fineExpression = 127; //int(0x7F) this.fineVolume = 127; this.data = new float[2048]; this.sustain = false; this.pitchBend = 0.5f; this.changed = false; SetReverb(0.0f); } public void ResetData() { for (var i = 0; i < data.Length; i++) { data[i] = 0.0f; } changed = true; } public void SetReverb(float rvt) { Debug.Log("Setting reverb: '" + rvt + "'."); this.rvt = rvt; } public void Apply() { if (!changed) return; //todo: implement filters and apply them here (for reverb etc.) changed = false; var targetSampleRate = (SampleRate - 18000) + (36000 * pitchBend); if (!Mathf.Approximately(targetSampleRate, SampleRate)) Debug.LogWarning("TODO: Implement pitch bend. Target sample rate = '" + targetSampleRate + "'."); } };
28.086207
110
0.633824
[ "MIT" ]
calsmurf2904/unity_synthesizer
Assets/Scripts/Internal/AudioChannel.cs
3,260
C#
using System; using System.Reflection.Emit; public static partial class Extensions { /// <summary> /// Pops an integer value from the evaluation stack and branches to the given label if it interprets as true /// </summary> /// <param name="il">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param> public static ILGenerator IfTrue(this BranchILGenerator il) { if (il == null) throw new ArgumentNullException(nameof(il)); return il.IL.FluentEmit(il.ShortForm ? OpCodes.Brtrue_S : OpCodes.Brtrue, il.Label); } }
38.375
114
0.672638
[ "MIT" ]
edwardmeng/FluentMethods
src/Core/System.Reflection.Emit.ILGenerator/Branch/IfTrue.cs
616
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the comprehend-2017-11-27.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Comprehend.Model { /// <summary> /// This is the response object from the ListEntityRecognizerSummaries operation. /// </summary> public partial class ListEntityRecognizerSummariesResponse : AmazonWebServiceResponse { private List<EntityRecognizerSummary> _entityRecognizerSummariesList = new List<EntityRecognizerSummary>(); private string _nextToken; /// <summary> /// Gets and sets the property EntityRecognizerSummariesList. /// <para> /// The list entity recognizer summaries. /// </para> /// </summary> public List<EntityRecognizerSummary> EntityRecognizerSummariesList { get { return this._entityRecognizerSummariesList; } set { this._entityRecognizerSummariesList = value; } } // Check to see if EntityRecognizerSummariesList property is set internal bool IsSetEntityRecognizerSummariesList() { return this._entityRecognizerSummariesList != null && this._entityRecognizerSummariesList.Count > 0; } /// <summary> /// Gets and sets the property NextToken. /// <para> /// The list entity recognizer summaries. /// </para> /// </summary> [AWSProperty(Min=1)] public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } } }
32.571429
115
0.659091
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/Comprehend/Generated/Model/ListEntityRecognizerSummariesResponse.cs
2,508
C#
using System.Web.Http; namespace Items.Web.App_Start { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
25
62
0.549474
[ "Apache-2.0" ]
davgit/angularjs-crudgrid
Items.Web/App_Start/WebApiConfig.cs
477
C#
using ArucoUnity.Utilities; using System; namespace ArucoUnity.Cameras { /// <summary> /// Generic configurable controller using a <see cref="ArucoCamera"/> as starting dependency. /// </summary> public abstract class ArucoCameraController : Controller, IArucoCameraController { // IArucoCameraController properties public IArucoCamera ArucoCamera { get; set; } // ConfigurableController methods /// <summary> /// Adds <see cref="ArucoCamera"/> as dependency. /// </summary> protected override void Configuring() { base.Configuring(); if (ArucoCamera == null) { throw new ArgumentNullException("ArucoCamera", "This property needs to be set for the configuration."); } AddDependency(ArucoCamera); } } }
28.354839
119
0.608646
[ "BSD-3-Clause" ]
NormandErwan/ArucoUnity
Assets/ArucoUnity/Scripts/Cameras/ArucoCameraController.cs
881
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.AspNetCore.Mvc.Internal; using Microsoft.AspNetCore.Mvc.ModelBinding.Internal; namespace Microsoft.AspNetCore.Mvc.ModelBinding.Validation { /// <summary> /// A visitor implementation that interprets <see cref="ValidationStateDictionary"/> to traverse /// a model object graph and perform validation. /// </summary> public class ValidationVisitor { /// <summary> /// Creates a new <see cref="ValidationVisitor"/>. /// </summary> /// <param name="actionContext">The <see cref="ActionContext"/> associated with the current request.</param> /// <param name="validatorProvider">The <see cref="IModelValidatorProvider"/>.</param> /// <param name="validatorCache">The <see cref="ValidatorCache"/> that provides a list of <see cref="IModelValidator"/>s.</param> /// <param name="metadataProvider">The provider used for reading metadata for the model type.</param> /// <param name="validationState">The <see cref="ValidationStateDictionary"/>.</param> public ValidationVisitor( ActionContext actionContext, IModelValidatorProvider validatorProvider, ValidatorCache validatorCache, IModelMetadataProvider metadataProvider, ValidationStateDictionary validationState) { if (actionContext == null) { throw new ArgumentNullException(nameof(actionContext)); } if (validatorProvider == null) { throw new ArgumentNullException(nameof(validatorProvider)); } if (validatorCache == null) { throw new ArgumentNullException(nameof(validatorCache)); } Context = actionContext; ValidatorProvider = validatorProvider; Cache = validatorCache; MetadataProvider = metadataProvider; ValidationState = validationState; ModelState = actionContext.ModelState; CurrentPath = new ValidationStack(); } protected IModelValidatorProvider ValidatorProvider { get; } protected IModelMetadataProvider MetadataProvider { get; } protected ValidatorCache Cache { get; } protected ActionContext Context { get; } protected ModelStateDictionary ModelState { get; } protected ValidationStateDictionary ValidationState { get; } protected ValidationStack CurrentPath { get; } protected object Container { get; set; } protected string Key { get; set; } protected object Model { get; set; } protected ModelMetadata Metadata { get; set; } protected IValidationStrategy Strategy { get; set; } /// <summary> /// Indicates whether validation of a complex type should be performed if validation fails for any of its children. The default behavior is false. /// </summary> public bool ValidateComplexTypesIfChildValidationFails { get; set; } /// <summary> /// Validates a object. /// </summary> /// <param name="metadata">The <see cref="ModelMetadata"/> associated with the model.</param> /// <param name="key">The model prefix key.</param> /// <param name="model">The model object.</param> /// <returns><c>true</c> if the object is valid, otherwise <c>false</c>.</returns> public bool Validate(ModelMetadata metadata, string key, object model) { return Validate(metadata, key, model, alwaysValidateAtTopLevel: false); } /// <summary> /// Validates a object. /// </summary> /// <param name="metadata">The <see cref="ModelMetadata"/> associated with the model.</param> /// <param name="key">The model prefix key.</param> /// <param name="model">The model object.</param> /// <param name="alwaysValidateAtTopLevel">If <c>true</c>, applies validation rules even if the top-level value is <c>null</c>.</param> /// <returns><c>true</c> if the object is valid, otherwise <c>false</c>.</returns> public virtual bool Validate(ModelMetadata metadata, string key, object model, bool alwaysValidateAtTopLevel) { if (model == null && key != null && !alwaysValidateAtTopLevel) { var entry = ModelState[key]; if (entry != null && entry.ValidationState != ModelValidationState.Valid) { entry.ValidationState = ModelValidationState.Valid; } return true; } return Visit(metadata, key, model); } /// <summary> /// Validates a single node in a model object graph. /// </summary> /// <returns><c>true</c> if the node is valid, otherwise <c>false</c>.</returns> protected virtual bool ValidateNode() { var state = ModelState.GetValidationState(Key); // Rationale: we might see the same model state key used for two different objects. // We want to run validation unless it's already known that this key is invalid. if (state != ModelValidationState.Invalid) { var validators = Cache.GetValidators(Metadata, ValidatorProvider); var count = validators.Count; if (count > 0) { var context = new ModelValidationContext( Context, Metadata, MetadataProvider, Container, Model); var results = new List<ModelValidationResult>(); for (var i = 0; i < count; i++) { results.AddRange(validators[i].Validate(context)); } var resultsCount = results.Count; for (var i = 0; i < resultsCount; i++) { var result = results[i]; var key = ModelNames.CreatePropertyModelName(Key, result.MemberName); // It's OK for key to be the empty string here. This can happen when a top // level object implements IValidatableObject. ModelState.TryAddModelError(key, result.Message); } } } state = ModelState.GetFieldValidationState(Key); if (state == ModelValidationState.Invalid) { return false; } else { // If the field has an entry in ModelState, then record it as valid. Don't create // extra entries if they don't exist already. var entry = ModelState[Key]; if (entry != null) { entry.ValidationState = ModelValidationState.Valid; } return true; } } protected virtual bool Visit(ModelMetadata metadata, string key, object model) { RuntimeHelpers.EnsureSufficientExecutionStack(); if (model != null && !CurrentPath.Push(model)) { // This is a cycle, bail. return true; } var entry = GetValidationEntry(model); key = entry?.Key ?? key ?? string.Empty; metadata = entry?.Metadata ?? metadata; var strategy = entry?.Strategy; if (ModelState.HasReachedMaxErrors) { SuppressValidation(key); return false; } else if (entry != null && entry.SuppressValidation) { // Use the key on the entry, because we might not have entries in model state. SuppressValidation(entry.Key); CurrentPath.Pop(model); return true; } using (StateManager.Recurse(this, key ?? string.Empty, metadata, model, strategy)) { if (Metadata.IsEnumerableType) { return VisitComplexType(DefaultCollectionValidationStrategy.Instance); } if (Metadata.IsComplexType) { return VisitComplexType(DefaultComplexObjectValidationStrategy.Instance); } return VisitSimpleType(); } } // Covers everything VisitSimpleType does not i.e. both enumerations and complex types. protected virtual bool VisitComplexType(IValidationStrategy defaultStrategy) { var isValid = true; if (Model != null && Metadata.ValidateChildren) { var strategy = Strategy ?? defaultStrategy; isValid = VisitChildren(strategy); } else if (Model != null) { // Suppress validation for the entries matching this prefix. This will temporarily set // the current node to 'skipped' but we're going to visit it right away, so subsequent // code will set it to 'valid' or 'invalid' SuppressValidation(Key); } // Double-checking HasReachedMaxErrors just in case this model has no properties. // If validation has failed for any children, only validate the parent if ValidateComplexTypesIfChildValidationFails is true. if ((isValid || ValidateComplexTypesIfChildValidationFails) && !ModelState.HasReachedMaxErrors) { isValid &= ValidateNode(); } return isValid; } protected virtual bool VisitSimpleType() { if (ModelState.HasReachedMaxErrors) { SuppressValidation(Key); return false; } return ValidateNode(); } protected virtual bool VisitChildren(IValidationStrategy strategy) { var isValid = true; var enumerator = strategy.GetChildren(Metadata, Key, Model); var parentEntry = new ValidationEntry(Metadata, Key, Model); while (enumerator.MoveNext()) { var entry = enumerator.Current; var metadata = entry.Metadata; var key = entry.Key; if (metadata.PropertyValidationFilter?.ShouldValidateEntry(entry, parentEntry) == false) { SuppressValidation(key); continue; } isValid &= Visit(metadata, key, entry.Model); } return isValid; } protected virtual void SuppressValidation(string key) { if (key == null) { // If the key is null, that means that we shouldn't expect any entries in ModelState for // this value, so there's nothing to do. return; } var entries = ModelState.FindKeysWithPrefix(key); foreach (var entry in entries) { entry.Value.ValidationState = ModelValidationState.Skipped; } } protected virtual ValidationStateEntry GetValidationEntry(object model) { if (model == null || ValidationState == null) { return null; } ValidationState.TryGetValue(model, out var entry); return entry; } protected struct StateManager : IDisposable { private readonly ValidationVisitor _visitor; private readonly object _container; private readonly string _key; private readonly ModelMetadata _metadata; private readonly object _model; private readonly object _newModel; private readonly IValidationStrategy _strategy; public static StateManager Recurse( ValidationVisitor visitor, string key, ModelMetadata metadata, object model, IValidationStrategy strategy) { var recursifier = new StateManager(visitor, model); visitor.Container = visitor.Model; visitor.Key = key; visitor.Metadata = metadata; visitor.Model = model; visitor.Strategy = strategy; return recursifier; } public StateManager(ValidationVisitor visitor, object newModel) { _visitor = visitor; _newModel = newModel; _container = _visitor.Container; _key = _visitor.Key; _metadata = _visitor.Metadata; _model = _visitor.Model; _strategy = _visitor.Strategy; } public void Dispose() { _visitor.Container = _container; _visitor.Key = _key; _visitor.Metadata = _metadata; _visitor.Model = _model; _visitor.Strategy = _strategy; _visitor.CurrentPath.Pop(_newModel); } } } }
38.132964
154
0.552884
[ "Apache-2.0" ]
nisha-kaushik/Mvc
src/Microsoft.AspNetCore.Mvc.Core/ModelBinding/Validation/ValidationVisitor.cs
13,766
C#
using System; using System.Linq.Expressions; namespace AutoMapper.Internal.Mappers { using static Expression; public class ConvertMapper : IObjectMapper { public static bool IsPrimitive(Type type) => type.IsPrimitive || type == typeof(string) || type == typeof(decimal); public bool IsMatch(in TypePair types) => (types.SourceType == typeof(string) && types.DestinationType == typeof(DateTime)) || (IsPrimitive(types.SourceType) && IsPrimitive(types.DestinationType)); public Expression MapExpression(IGlobalConfiguration configurationProvider, ProfileMap profileMap, MemberMap memberMap, Expression sourceExpression, Expression destExpression) { var convertMethod = typeof(Convert).GetMethod("To" + destExpression.Type.Name, new[] { sourceExpression.Type }); return Call(convertMethod, sourceExpression); } } }
50.944444
135
0.70229
[ "MIT" ]
AutoMapper/AutoMapper
src/AutoMapper/Mappers/ConvertMapper.cs
919
C#
using System; using System.IO.Ports; using System.Web; namespace Asv.Mavlink { public class SerialPortConfig { public int DataBits { get; set; } = 8; public int BoundRate { get; set; } = 115200; public Parity Parity { get; set; } = Parity.None; public StopBits StopBits { get; set; } = StopBits.One; public string PortName { get; set; } public int WriteTimeout { get; set; } = 200; public int WriteBufferSize { get; set; } = 40960; public static bool TryParseFromUri(Uri uri, out SerialPortConfig opt) { if (!"serial".Equals(uri.Scheme, StringComparison.InvariantCultureIgnoreCase)) { opt = null; return false; } var coll = HttpUtility.ParseQueryString(uri.Query); opt = new SerialPortConfig { PortName = uri.LocalPath, WriteTimeout = int.Parse(coll["wrt"] ?? "1000"), BoundRate = int.Parse(coll["br"] ?? "57600"), WriteBufferSize = int.Parse(coll["ws"] ?? "40960"), Parity = (Parity)Enum.Parse(typeof(Parity), coll["parity"] ?? Parity.None.ToString()), DataBits = int.Parse(coll["dataBits"] ?? "8"), StopBits = (StopBits)Enum.Parse(typeof(StopBits), coll["stopBits"] ?? StopBits.One.ToString()), }; return true; } public override string ToString() { return $"Serial {PortName} ({BoundRate})"; //return $"serial:{PortName}?br={BoundRate}&wrt={WriteTimeout}&parity={Parity}&dataBits={DataBits}&stopBits={StopBits}"; } } }
37.065217
132
0.553079
[ "MIT" ]
asvol/mavlink.net
src/Asv.Mavlink/Gcs/PortManager/Port/Serial/SerialPortConfig.cs
1,705
C#
using System; using SharpTest; namespace Tests { class Tests : TestRunner { public static void Main(string[] args) { TestRunner.Start<Tests>(); } } }
11
40
0.660606
[ "MIT" ]
bigbearstudios/sharp-commander
Tests/Program.cs
167
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NetworkedPlanet.BrightStar.Samples { /// <summary> /// This class contains a number of static methods that exercise and demonstrate different aspects of the Proxy interface. /// </summary> public class ProxyObjectsExample { /// <summary> /// This sample code shows how to check if a named store already exists and if not create one. /// </summary> public static void CreateStoreExample() { } } }
26.318182
126
0.647668
[ "MIT" ]
smkgeekfreak/BrightstarDB
src/core/BrightstarDB.Samples/ProxyObjectsExample.cs
581
C#
namespace Sylvester.Compiler { public interface IDeviceBuffer { DeviceType DeviceType { get; } IShape Shape { get; } } }
18.625
38
0.610738
[ "MIT" ]
allisterb/Sylvester
src/Base/Sylvester.Compiler/Compiler/IDeviceBuffer.cs
151
C#
using System; using System.Linq; using System.Collections.Generic; using UnityEditor.Experimental.Rendering.HDPipeline.Drawing; using UnityEditor.Graphing; using UnityEditor.ShaderGraph; using UnityEditor.ShaderGraph.Drawing; using UnityEditor.ShaderGraph.Drawing.Controls; using UnityEngine; using UnityEngine.UIElements; using UnityEngine.Experimental.Rendering.HDPipeline; namespace UnityEditor.Experimental.Rendering.HDPipeline { [Serializable] [Title("Master", "HDRP/Hair")] class HairMasterNode : MasterNode<IHairSubShader>, IMayRequirePosition, IMayRequireNormal, IMayRequireTangent { public const string PositionSlotName = "Position"; public const int PositionSlotId = 0; public const string AlbedoSlotName = "Albedo"; public const string AlbedoDisplaySlotName = "DiffuseColor"; public const int AlbedoSlotId = 1; public const string NormalSlotName = "Normal"; public const int NormalSlotId = 2; public const string SpecularOcclusionSlotName = "SpecularOcclusion"; public const int SpecularOcclusionSlotId = 3; public const string BentNormalSlotName = "BentNormal"; public const int BentNormalSlotId = 4; public const string HairStrandDirectionSlotName = "HairStrandDirection"; public const int HairStrandDirectionSlotId = 5; public const string SubsurfaceMaskSlotName = "SubsurfaceMask"; public const int SubsurfaceMaskSlotId = 6; public const string ThicknessSlotName = "Thickness"; public const int ThicknessSlotId = 7; public const string DiffusionProfileHashSlotName = "DiffusionProfileHash"; public const int DiffusionProfileHashSlotId = 8; public const string SmoothnessSlotName = "Smoothness"; public const int SmoothnessSlotId = 9; public const string AmbientOcclusionSlotName = "Occlusion"; public const string AmbientOcclusionDisplaySlotName = "AmbientOcclusion"; public const int AmbientOcclusionSlotId = 10; public const string EmissionSlotName = "Emission"; public const int EmissionSlotId = 11; public const string AlphaSlotName = "Alpha"; public const int AlphaSlotId = 12; public const string AlphaClipThresholdSlotName = "AlphaClipThreshold"; public const int AlphaClipThresholdSlotId = 13; public const string AlphaClipThresholdDepthPrepassSlotName = "AlphaClipThresholdDepthPrepass"; public const int AlphaClipThresholdDepthPrepassSlotId = 14; public const string AlphaClipThresholdDepthPostpassSlotName = "AlphaClipThresholdDepthPostpass"; public const int AlphaClipThresholdDepthPostpassSlotId = 15; public const string SpecularAAScreenSpaceVarianceSlotName = "SpecularAAScreenSpaceVariance"; public const int SpecularAAScreenSpaceVarianceSlotId = 16; public const string SpecularAAThresholdSlotName = "SpecularAAThreshold"; public const int SpecularAAThresholdSlotId = 17; //Hair Specific public const string SpecularTintSlotName = "SpecularTint"; public const int SpecularTintSlotId = 18; public const string SpecularShiftSlotName = "SpecularShift"; public const int SpecularShiftSlotId = 19; public const string SecondarySpecularTintSlotName = "SecondarySpecularTint"; public const int SecondarySpecularTintSlotId = 20; public const string SecondarySmoothnessSlotName = "SecondarySmoothness"; public const int SecondarySmoothnessSlotId = 21; public const string SecondarySpecularShiftSlotName = "SecondarySpecularShift"; public const int SecondarySpecularShiftSlotId = 22; public const string AlphaClipThresholdShadowSlotName = "AlphaClipThresholdShadow"; public const int AlphaClipThresholdShadowSlotId = 23; public const string BakedGISlotName = "BakedGI"; public const int LightingSlotId = 24; public const string BakedBackGISlotName = "BakedBackGI"; public const int BackLightingSlotId = 25; public const string DepthOffsetSlotName = "DepthOffset"; public const int DepthOffsetSlotId = 26; public enum MaterialType { KajiyaKay } // Don't support Multiply public enum AlphaModeLit { Alpha, Premultiply, Additive, } // Just for convenience of doing simple masks. We could run out of bits of course. [Flags] enum SlotMask { None = 0, Position = 1 << PositionSlotId, Albedo = 1 << AlbedoSlotId, Normal = 1 << NormalSlotId, SpecularOcclusion = 1 << SpecularOcclusionSlotId, BentNormal = 1 << BentNormalSlotId, HairStrandDirection = 1 << HairStrandDirectionSlotId, SubsurfaceMask = 1 << SubsurfaceMaskSlotId, Thickness = 1 << ThicknessSlotId, DiffusionProfile = 1 << DiffusionProfileHashSlotId, Smoothness = 1 << SmoothnessSlotId, Occlusion = 1 << AmbientOcclusionSlotId, Emission = 1 << EmissionSlotId, Alpha = 1 << AlphaSlotId, AlphaClipThreshold = 1 << AlphaClipThresholdSlotId, AlphaClipThresholdDepthPrepass = 1 << AlphaClipThresholdDepthPrepassSlotId, AlphaClipThresholdDepthPostpass = 1 << AlphaClipThresholdDepthPostpassSlotId, SpecularTint = 1 << SpecularTintSlotId, SpecularShift = 1 << SpecularShiftSlotId, SecondarySpecularTint = 1 << SecondarySpecularTintSlotId, SecondarySmoothness = 1 << SecondarySmoothnessSlotId, SecondarySpecularShift = 1 << SecondarySpecularShiftSlotId, AlphaClipThresholdShadow = 1 << AlphaClipThresholdShadowSlotId, BakedGI = 1 << LightingSlotId, BakedBackGI = 1 << BackLightingSlotId, DepthOffset = 1 << DepthOffsetSlotId, } const SlotMask KajiyaKaySlotMask = SlotMask.Position | SlotMask.Albedo | SlotMask.Normal | SlotMask.SpecularOcclusion | SlotMask.BentNormal | SlotMask.HairStrandDirection | SlotMask.SubsurfaceMask | SlotMask.Thickness | SlotMask.DiffusionProfile | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.Alpha | SlotMask.AlphaClipThreshold | SlotMask.AlphaClipThresholdDepthPrepass | SlotMask.AlphaClipThresholdDepthPostpass | SlotMask.SpecularTint | SlotMask.SpecularShift | SlotMask.SecondarySpecularTint | SlotMask.SecondarySmoothness | SlotMask.SecondarySpecularShift | SlotMask.AlphaClipThresholdShadow | SlotMask.BakedGI | SlotMask.DepthOffset; // This could also be a simple array. For now, catch any mismatched data. SlotMask GetActiveSlotMask() { switch (materialType) { case MaterialType.KajiyaKay: return KajiyaKaySlotMask; default: return KajiyaKaySlotMask; } } bool MaterialTypeUsesSlotMask(SlotMask mask) { SlotMask activeMask = GetActiveSlotMask(); return (activeMask & mask) != 0; } [SerializeField] SurfaceType m_SurfaceType; public SurfaceType surfaceType { get { return m_SurfaceType; } set { if (m_SurfaceType == value) return; m_SurfaceType = value; UpdateNodeAfterDeserialization(); Dirty(ModificationScope.Topological); } } [SerializeField] AlphaMode m_AlphaMode; public AlphaMode alphaMode { get { return m_AlphaMode; } set { if (m_AlphaMode == value) return; m_AlphaMode = value; Dirty(ModificationScope.Graph); } } [SerializeField] bool m_BlendPreserveSpecular = true; public ToggleData blendPreserveSpecular { get { return new ToggleData(m_BlendPreserveSpecular); } set { if (m_BlendPreserveSpecular == value.isOn) return; m_BlendPreserveSpecular = value.isOn; Dirty(ModificationScope.Graph); } } [SerializeField] bool m_TransparencyFog = true; public ToggleData transparencyFog { get { return new ToggleData(m_TransparencyFog); } set { if (m_TransparencyFog == value.isOn) return; m_TransparencyFog = value.isOn; Dirty(ModificationScope.Graph); } } [SerializeField] bool m_AlphaTest; public ToggleData alphaTest { get { return new ToggleData(m_AlphaTest); } set { if (m_AlphaTest == value.isOn) return; m_AlphaTest = value.isOn; UpdateNodeAfterDeserialization(); Dirty(ModificationScope.Topological); } } [SerializeField] bool m_AlphaTestDepthPrepass; public ToggleData alphaTestDepthPrepass { get { return new ToggleData(m_AlphaTestDepthPrepass); } set { if (m_AlphaTestDepthPrepass == value.isOn) return; m_AlphaTestDepthPrepass = value.isOn; UpdateNodeAfterDeserialization(); Dirty(ModificationScope.Topological); } } [SerializeField] bool m_AlphaTestDepthPostpass; public ToggleData alphaTestDepthPostpass { get { return new ToggleData(m_AlphaTestDepthPostpass); } set { if (m_AlphaTestDepthPostpass == value.isOn) return; m_AlphaTestDepthPostpass = value.isOn; UpdateNodeAfterDeserialization(); Dirty(ModificationScope.Topological); } } [SerializeField] bool m_TransparentWritesVelocity; public ToggleData transparentWritesVelocity { get { return new ToggleData(m_TransparentWritesVelocity); } set { if (m_TransparentWritesVelocity == value.isOn) return; m_TransparentWritesVelocity = value.isOn; UpdateNodeAfterDeserialization(); Dirty(ModificationScope.Topological); } } [SerializeField] bool m_AlphaTestShadow; public ToggleData alphaTestShadow { get { return new ToggleData(m_AlphaTestShadow); } set { if (m_AlphaTestShadow == value.isOn) return; m_AlphaTestShadow = value.isOn; UpdateNodeAfterDeserialization(); Dirty(ModificationScope.Topological); } } [SerializeField] bool m_BackThenFrontRendering; public ToggleData backThenFrontRendering { get { return new ToggleData(m_BackThenFrontRendering); } set { if (m_BackThenFrontRendering == value.isOn) return; m_BackThenFrontRendering = value.isOn; Dirty(ModificationScope.Graph); } } [SerializeField] int m_SortPriority; public int sortPriority { get { return m_SortPriority; } set { if (m_SortPriority == value) return; m_SortPriority = value; Dirty(ModificationScope.Graph); } } [SerializeField] DoubleSidedMode m_DoubleSidedMode; public DoubleSidedMode doubleSidedMode { get { return m_DoubleSidedMode; } set { if (m_DoubleSidedMode == value) return; m_DoubleSidedMode = value; Dirty(ModificationScope.Graph); } } [SerializeField] MaterialType m_MaterialType; public MaterialType materialType { get { return m_MaterialType; } set { if (m_MaterialType == value) return; m_MaterialType = value; UpdateNodeAfterDeserialization(); Dirty(ModificationScope.Topological); } } [SerializeField] bool m_ReceiveDecals = true; public ToggleData receiveDecals { get { return new ToggleData(m_ReceiveDecals); } set { if (m_ReceiveDecals == value.isOn) return; m_ReceiveDecals = value.isOn; Dirty(ModificationScope.Graph); } } [SerializeField] bool m_ReceivesSSR = true; public ToggleData receiveSSR { get { return new ToggleData(m_ReceivesSSR); } set { if (m_ReceivesSSR == value.isOn) return; m_ReceivesSSR = value.isOn; Dirty(ModificationScope.Graph); } } [SerializeField] bool m_SpecularAA; public ToggleData specularAA { get { return new ToggleData(m_SpecularAA); } set { if (m_SpecularAA == value.isOn) return; m_SpecularAA = value.isOn; UpdateNodeAfterDeserialization(); Dirty(ModificationScope.Topological); } } [SerializeField] float m_SpecularAAScreenSpaceVariance; public float specularAAScreenSpaceVariance { get { return m_SpecularAAScreenSpaceVariance; } set { if (m_SpecularAAScreenSpaceVariance == value) return; m_SpecularAAScreenSpaceVariance = value; Dirty(ModificationScope.Graph); } } [SerializeField] float m_SpecularAAThreshold; public float specularAAThreshold { get { return m_SpecularAAThreshold; } set { if (m_SpecularAAThreshold == value) return; m_SpecularAAThreshold = value; Dirty(ModificationScope.Graph); } } [SerializeField] bool m_Transmission = false; public ToggleData transmission { get { return new ToggleData(m_Transmission); } set { if (m_Transmission == value.isOn) return; m_Transmission = value.isOn; UpdateNodeAfterDeserialization(); Dirty(ModificationScope.Graph); } } [SerializeField] bool m_SubsurfaceScattering = false; public ToggleData subsurfaceScattering { get { return new ToggleData(m_SubsurfaceScattering); } set { if (m_SubsurfaceScattering == value.isOn) return; m_SubsurfaceScattering = value.isOn; UpdateNodeAfterDeserialization(); Dirty(ModificationScope.Graph); } } [SerializeField] SpecularOcclusionMode m_SpecularOcclusionMode; public SpecularOcclusionMode specularOcclusionMode { get { return m_SpecularOcclusionMode; } set { if (m_SpecularOcclusionMode == value) return; m_SpecularOcclusionMode = value; UpdateNodeAfterDeserialization(); Dirty(ModificationScope.Graph); } } [SerializeField] int m_DiffusionProfile; public int diffusionProfile { get { return m_DiffusionProfile; } set { if (m_DiffusionProfile == value) return; m_DiffusionProfile = value; Dirty(ModificationScope.Graph); } } [SerializeField] bool m_overrideBakedGI; public ToggleData overrideBakedGI { get { return new ToggleData(m_overrideBakedGI); } set { if (m_overrideBakedGI == value.isOn) return; m_overrideBakedGI = value.isOn; UpdateNodeAfterDeserialization(); Dirty(ModificationScope.Topological); } } [SerializeField] bool m_depthOffset; public ToggleData depthOffset { get { return new ToggleData(m_depthOffset); } set { if (m_depthOffset == value.isOn) return; m_depthOffset = value.isOn; UpdateNodeAfterDeserialization(); Dirty(ModificationScope.Topological); } } public HairMasterNode() { UpdateNodeAfterDeserialization(); } public override string documentationURL { get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/Hair-Master-Node"; } } public sealed override void UpdateNodeAfterDeserialization() { base.UpdateNodeAfterDeserialization(); name = "Hair Master"; List<int> validSlots = new List<int>(); if (MaterialTypeUsesSlotMask(SlotMask.Position)) { AddSlot(new PositionMaterialSlot(PositionSlotId, PositionSlotName, PositionSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); validSlots.Add(PositionSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.Albedo)) { AddSlot(new ColorRGBMaterialSlot(AlbedoSlotId, AlbedoDisplaySlotName, AlbedoSlotName, SlotType.Input, Color.grey.gamma, ColorMode.Default, ShaderStageCapability.Fragment)); validSlots.Add(AlbedoSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.SpecularOcclusion) && specularOcclusionMode == SpecularOcclusionMode.Custom) { AddSlot(new Vector1MaterialSlot(SpecularOcclusionSlotId, SpecularOcclusionSlotName, SpecularOcclusionSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); validSlots.Add(SpecularOcclusionSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.Normal)) { AddSlot(new NormalMaterialSlot(NormalSlotId, NormalSlotName, NormalSlotName, CoordinateSpace.Tangent, ShaderStageCapability.Fragment)); validSlots.Add(NormalSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.BentNormal)) { AddSlot(new NormalMaterialSlot(BentNormalSlotId, BentNormalSlotName, BentNormalSlotName, CoordinateSpace.Tangent, ShaderStageCapability.Fragment)); validSlots.Add(BentNormalSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.Smoothness)) { AddSlot(new Vector1MaterialSlot(SmoothnessSlotId, SmoothnessSlotName, SmoothnessSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); validSlots.Add(SmoothnessSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.Occlusion)) { AddSlot(new Vector1MaterialSlot(AmbientOcclusionSlotId, AmbientOcclusionDisplaySlotName, AmbientOcclusionSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); validSlots.Add(AmbientOcclusionSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.DiffusionProfile) && (subsurfaceScattering.isOn || transmission.isOn)) { AddSlot(new DiffusionProfileInputMaterialSlot(DiffusionProfileHashSlotId, DiffusionProfileHashSlotName, DiffusionProfileHashSlotName, ShaderStageCapability.Fragment)); validSlots.Add(DiffusionProfileHashSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.SubsurfaceMask) && subsurfaceScattering.isOn) { AddSlot(new Vector1MaterialSlot(SubsurfaceMaskSlotId, SubsurfaceMaskSlotName, SubsurfaceMaskSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); validSlots.Add(SubsurfaceMaskSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.Thickness) && transmission.isOn) { AddSlot(new Vector1MaterialSlot(ThicknessSlotId, ThicknessSlotName, ThicknessSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); validSlots.Add(ThicknessSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.HairStrandDirection)) { AddSlot(new Vector3MaterialSlot(HairStrandDirectionSlotId, HairStrandDirectionSlotName, HairStrandDirectionSlotName, SlotType.Input, new Vector3(0, -1, 0), ShaderStageCapability.Fragment)); validSlots.Add(HairStrandDirectionSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.Emission)) { AddSlot(new ColorRGBMaterialSlot(EmissionSlotId, EmissionSlotName, EmissionSlotName, SlotType.Input, Color.black, ColorMode.HDR, ShaderStageCapability.Fragment)); validSlots.Add(EmissionSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.Alpha)) { AddSlot(new Vector1MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); validSlots.Add(AlphaSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.AlphaClipThreshold) && alphaTest.isOn) { AddSlot(new Vector1MaterialSlot(AlphaClipThresholdSlotId, AlphaClipThresholdSlotName, AlphaClipThresholdSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); validSlots.Add(AlphaClipThresholdSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.AlphaClipThresholdDepthPrepass) && surfaceType == SurfaceType.Transparent && alphaTest.isOn && alphaTestDepthPrepass.isOn) { AddSlot(new Vector1MaterialSlot(AlphaClipThresholdDepthPrepassSlotId, AlphaClipThresholdDepthPrepassSlotName, AlphaClipThresholdDepthPrepassSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); validSlots.Add(AlphaClipThresholdDepthPrepassSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.AlphaClipThresholdDepthPostpass) && surfaceType == SurfaceType.Transparent && alphaTest.isOn && alphaTestDepthPostpass.isOn) { AddSlot(new Vector1MaterialSlot(AlphaClipThresholdDepthPostpassSlotId, AlphaClipThresholdDepthPostpassSlotName, AlphaClipThresholdDepthPostpassSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); validSlots.Add(AlphaClipThresholdDepthPostpassSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.AlphaClipThresholdShadow) && alphaTest.isOn && alphaTestShadow.isOn) { AddSlot(new Vector1MaterialSlot(AlphaClipThresholdShadowSlotId, AlphaClipThresholdShadowSlotName, AlphaClipThresholdShadowSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); validSlots.Add(AlphaClipThresholdShadowSlotId); } if (specularAA.isOn) { AddSlot(new Vector1MaterialSlot(SpecularAAScreenSpaceVarianceSlotId, SpecularAAScreenSpaceVarianceSlotName, SpecularAAScreenSpaceVarianceSlotName, SlotType.Input, 0.1f, ShaderStageCapability.Fragment)); validSlots.Add(SpecularAAScreenSpaceVarianceSlotId); AddSlot(new Vector1MaterialSlot(SpecularAAThresholdSlotId, SpecularAAThresholdSlotName, SpecularAAThresholdSlotName, SlotType.Input, 0.2f, ShaderStageCapability.Fragment)); validSlots.Add(SpecularAAThresholdSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.SpecularTint)) { AddSlot(new ColorRGBMaterialSlot(SpecularTintSlotId, SpecularTintSlotName, SpecularTintSlotName, SlotType.Input, Color.white, ColorMode.Default, ShaderStageCapability.Fragment)); validSlots.Add(SpecularTintSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.SpecularShift)) { AddSlot(new Vector1MaterialSlot(SpecularShiftSlotId, SpecularShiftSlotName, SpecularShiftSlotName, SlotType.Input, 0.1f, ShaderStageCapability.Fragment)); validSlots.Add(SpecularShiftSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.SecondarySpecularTint)) { AddSlot(new ColorRGBMaterialSlot(SecondarySpecularTintSlotId, SecondarySpecularTintSlotName, SecondarySpecularTintSlotName, SlotType.Input, Color.grey, ColorMode.Default, ShaderStageCapability.Fragment)); validSlots.Add(SecondarySpecularTintSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.SecondarySmoothness)) { AddSlot(new Vector1MaterialSlot(SecondarySmoothnessSlotId, SecondarySmoothnessSlotName, SecondarySmoothnessSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); validSlots.Add(SecondarySmoothnessSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.SecondarySpecularShift)) { AddSlot(new Vector1MaterialSlot(SecondarySpecularShiftSlotId, SecondarySpecularShiftSlotName, SecondarySpecularShiftSlotName, SlotType.Input, -0.1f, ShaderStageCapability.Fragment)); validSlots.Add(SecondarySpecularShiftSlotId); } if (MaterialTypeUsesSlotMask(SlotMask.BakedGI) && overrideBakedGI.isOn) { AddSlot(new DefaultMaterialSlot(LightingSlotId, BakedGISlotName, BakedGISlotName, ShaderStageCapability.Fragment)); validSlots.Add(LightingSlotId); AddSlot(new DefaultMaterialSlot(BackLightingSlotId, BakedBackGISlotName, BakedBackGISlotName, ShaderStageCapability.Fragment)); validSlots.Add(BackLightingSlotId); } if (depthOffset.isOn) { AddSlot(new Vector1MaterialSlot(DepthOffsetSlotId, DepthOffsetSlotName, DepthOffsetSlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); validSlots.Add(DepthOffsetSlotId); } RemoveSlotsNameNotMatching(validSlots, true); } protected override VisualElement CreateCommonSettingsElement() { return new HairSettingsView(this); } public NeededCoordinateSpace RequiresNormal(ShaderStageCapability stageCapability) { List<MaterialSlot> slots = new List<MaterialSlot>(); GetSlots(slots); List<MaterialSlot> validSlots = new List<MaterialSlot>(); for (int i = 0; i < slots.Count; i++) { if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) continue; validSlots.Add(slots[i]); } return validSlots.OfType<IMayRequireNormal>().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresNormal(stageCapability)); } public NeededCoordinateSpace RequiresTangent(ShaderStageCapability stageCapability) { List<MaterialSlot> slots = new List<MaterialSlot>(); GetSlots(slots); List<MaterialSlot> validSlots = new List<MaterialSlot>(); for (int i = 0; i < slots.Count; i++) { if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) continue; validSlots.Add(slots[i]); } return validSlots.OfType<IMayRequireTangent>().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresTangent(stageCapability)); } public NeededCoordinateSpace RequiresPosition(ShaderStageCapability stageCapability) { List<MaterialSlot> slots = new List<MaterialSlot>(); GetSlots(slots); List<MaterialSlot> validSlots = new List<MaterialSlot>(); for (int i = 0; i < slots.Count; i++) { if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) continue; validSlots.Add(slots[i]); } return validSlots.OfType<IMayRequirePosition>().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresPosition(stageCapability)); } public bool RequiresSplitLighting() { return subsurfaceScattering.isOn; } public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) { // Trunk currently relies on checking material property "_EmissionColor" to allow emissive GI. If it doesn't find that property, or it is black, GI is forced off. // ShaderGraph doesn't use this property, so currently it inserts a dummy color (white). This dummy color may be removed entirely once the following PR has been merged in trunk: Pull request #74105 // The user will then need to explicitly disable emissive GI if it is not needed. // To be able to automatically disable emission based on the ShaderGraph config when emission is black, // we will need a more general way to communicate this to the engine (not directly tied to a material property). collector.AddShaderProperty(new ColorShaderProperty() { overrideReferenceName = "_EmissionColor", hidden = true, value = new Color(1.0f, 1.0f, 1.0f, 1.0f) }); base.CollectShaderProperties(collector, generationMode); } } }
39.93565
233
0.613986
[ "MIT" ]
ToadsworthLP/Millenium
Library/PackageCache/com.unity.render-pipelines.high-definition@5.10.0-preview/Editor/Material/Hair/ShaderGraph/HairMasterNode.cs
31,030
C#
using System; namespace EnTTSharp.Serialization.Xml.AutoRegistration { [AttributeUsage(AttributeTargets.Method)] public sealed class EntityXmlWriterAttribute : Attribute { } }
19.4
60
0.757732
[ "MIT" ]
RabbitStewDio/EnTTSharp
src/EnTTSharp.Serialization.Xml/AutoRegistration/EntityXmlWriterAttribute.cs
196
C#
using UnityEngine; using System.Collections; public class _TEST : MonoBehaviour { [SerializeField] MaskType _type = MaskType.None; [SerializeField] Color _color = Color.black; [SerializeField, Range(0.01f, 5f)] float _duration = 1f; IEnumerator Start() { MaskBehaviour.Open( _type, _color, _duration ); yield return new WaitWhile( () => MaskBehaviour.isPlaying ); yield return new WaitForSeconds( 1f ); MaskBehaviour.Close( _type, _color, _duration ); } }
19.84
64
0.701613
[ "Apache-2.0" ]
tom10987/Unity.Sample.ScreenSequencer
Assets/_TEST/_TEST.cs
496
C#
using Microsoft.AspNetCore.Mvc.RazorPages; namespace Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic.Demo.Pages; public class IndexModel : PageModel { public void OnGet() { } }
15.333333
60
0.717391
[ "Apache-2.0" ]
daridakr/ProgGuru
modules/Volo.BasicTheme/test/Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic.Demo/Pages/Index.cshtml.cs
186
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace Mosaic.Base { public static class WinAPI { public const int GwlExstyle = -20; public const int GwlStyle = -16; public const uint WM_SETICON = 0x0080; public const uint WM_CLOSE = 0x0010; public const int WS_EX_DLGMODALFRAME = 0x0001; public const int SWP_NOSIZE = 0x0001; public const int SWP_NOMOVE = 0x0002; public const int SWP_NOZORDER = 0x0004; public const int SWP_FRAMECHANGED = 0x0020; public const int SWP_NOACTIVATE = 0x0010; public const int WM_KEYDOWN = 0x0100; public const int WM_KEYUP = 0x0101; public const int WM_CHAR = 0x0102; public const int WsExToolwindow = 0x00000080; public const int Flip3D = 8; [StructLayout(LayoutKind.Sequential)] public struct Margins { public int cxLeftWidth; // width of left border that retains its size public int cxRightWidth; // width of right border that retains its size public int cyTopHeight; // height of top border that retains its size public int cyBottomHeight; // height of bottom border that retains its size }; public struct BbStruct //Blur Behind Structure { public BbFlags Flags; public bool Enable; public IntPtr Region; public bool TransitionOnMaximized; } [Flags] public enum BbFlags : byte //Blur Behind Flags { DwmBbEnable = 1, DwmBbBlurregion = 2, DwmBbTransitiononmaximized = 4, }; public enum Flip3DPolicy { Default = 0, ExcludeBelow, ExcludeAbove } [StructLayout(LayoutKind.Sequential)] public struct SHFILEINFO { public IntPtr hIcon; public int iIcon; public uint dwAttributes; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szDisplayName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string szTypeName; } public const uint SHGFI_ICON = 0x000000100; // get icon public const uint SHGFI_DISPLAYNAME = 0x000000200; // get display name public const uint SHGFI_LARGEICON = 0x000000000; // get large icon public const uint SHGFI_SMALLICON = 0x000000001; // get small icon [DllImport("DwmApi.dll")] public static extern int DwmExtendFrameIntoClientArea(IntPtr hwnd, ref Margins pMarInset); [DllImport("dwmapi.dll")] public static extern int DwmEnableBlurBehindWindow(IntPtr hWnd, ref BbStruct blurBehind); [DllImport("dwmapi.dll")] public static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize); [DllImport("dwmapi.dll")] public static extern int DwmIsCompositionEnabled(out bool enabled); [DllImport("user32.dll")] public static extern int GetWindowLong(IntPtr window, int index); [DllImport("user32.dll")] public static extern int SetWindowLong(IntPtr window, int index, uint value); [DllImport("gdi32.dll")] public static extern IntPtr CreateRoundRectRgn(int x1, int y1, int x2, int y2, int xradius, int yradius); [DllImport("gdi32.dll")] public static extern IntPtr CreateEllipticRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect); [DllImport("kernel32")] public static extern bool AllocConsole(); [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] public static extern bool FreeConsole(); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); [DllImport("shell32.dll")] public static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd); [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter, int x, int y, int width, int height, uint flags); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam); [DllImport("shell32")] public static extern int SHGetFileInfo(string pszPath, uint dwFileAttributes, out SHFILEINFO psfi, uint cbFileInfo, uint flags); [DllImport("user32.dll", SetLastError = false)] public static extern IntPtr GetDesktopWindow(); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsIconic(IntPtr hWnd); public static void RemoveWindowIcon(IntPtr hwnd) { // Change the extended window style to not show a window icon int extendedStyle = GetWindowLong(hwnd, GwlExstyle); SetWindowLong(hwnd, GwlExstyle, (uint)extendedStyle | WS_EX_DLGMODALFRAME); // Update the window's non-client area to reflect the changes SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); } [DllImport("user32.dll", EntryPoint = "GetWindowPlacement")] private static extern bool InternalGetWindowPlacement(IntPtr hWnd, ref WindowPlacement lpwndpl); public static bool GetWindowPlacement(IntPtr hWnd, out WindowPlacement placement) { placement = new WindowPlacement(); placement.Length = Marshal.SizeOf(typeof(WindowPlacement)); return InternalGetWindowPlacement(hWnd, ref placement); } [DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr hWnd, GetWindowCmd uCmd); [DllImport("user32.dll")] public static extern IntPtr FindWindow(string classname, string title); [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, out Rect lpRect); [DllImport("dwmapi.dll")] public static extern int DwmRegisterThumbnail(IntPtr dest, IntPtr source, out IntPtr hthumbnail); [DllImport("dwmapi.dll")] public static extern int DwmUnregisterThumbnail(IntPtr HThumbnail); [DllImport("dwmapi.dll")] public static extern int DwmUpdateThumbnailProperties(IntPtr HThumbnail, ref ThumbnailProperties props); [DllImport("dwmapi.dll")] public static extern int DwmQueryThumbnailSourceSize(IntPtr HThumbnail, out Size size); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] static extern int GetWindowTextLength(IntPtr hWnd); public static string GetText(IntPtr hWnd) { // Allocate correct string length first int length = GetWindowTextLength(hWnd); StringBuilder sb = new StringBuilder(length + 1); GetWindowText(hWnd, sb, sb.Capacity); return sb.ToString(); } public enum WindowShowStyle : uint { Hide = 0, ShowNormal = 1, ShowMinimized = 2, ShowMaximized = 3, Maximize = 3, ShowNormalNoActivate = 4, Show = 5, Minimize = 6, ShowMinNoActivate = 7, ShowNoActivate = 8, Restore = 9, ShowDefault = 10, ForceMinimized = 11 } public struct Point { public int x; public int y; } public struct Size { public int Width, Height; } public struct WindowPlacement { public int Length; public int Flags; public int ShowCmd; public Point MinPosition; public Point MaxPosition; public Rect NormalPosition; } public struct ThumbnailProperties { public ThumbnailFlags Flags; public Rect Destination; public Rect Source; public Byte Opacity; public bool Visible; public bool SourceClientAreaOnly; } public struct Rect { public Rect(int x, int y, int x1, int y1) { this.Left = x; this.Top = y; this.Right = x1; this.Bottom = y1; } public int Left, Top, Right, Bottom; } [Flags] public enum ThumbnailFlags : int { RectDetination = 1, RectSource = 2, Opacity = 4, Visible = 8, SourceClientAreaOnly = 16 } public enum GetWindowCmd : uint { First = 0, Last = 1, Next = 2, Prev = 3, Owner = 4, Child = 5, EnabledPopup = 6 } [Flags] public enum WindowStyles : uint { WS_OVERLAPPED = 0x00000000, WS_POPUP = 0x80000000, WS_CHILD = 0x40000000, WS_MINIMIZE = 0x20000000, WS_VISIBLE = 0x10000000, WS_DISABLED = 0x08000000, WS_CLIPSIBLINGS = 0x04000000, WS_CLIPCHILDREN = 0x02000000, WS_MAXIMIZE = 0x01000000, WS_BORDER = 0x00800000, WS_DLGFRAME = 0x00400000, WS_VSCROLL = 0x00200000, WS_HSCROLL = 0x00100000, WS_SYSMENU = 0x00080000, WS_THICKFRAME = 0x00040000, WS_GROUP = 0x00020000, WS_TABSTOP = 0x00010000, WS_MINIMIZEBOX = 0x00020000, WS_MAXIMIZEBOX = 0x00010000, WS_CAPTION = WS_BORDER | WS_DLGFRAME, WS_TILED = WS_OVERLAPPED, WS_ICONIC = WS_MINIMIZE, WS_SIZEBOX = WS_THICKFRAME, WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW, WS_OVERLAPPEDWINDOW = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX, WS_POPUPWINDOW = WS_POPUP | WS_BORDER | WS_SYSMENU, WS_CHILDWINDOW = WS_CHILD, } public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1); public static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2); public static readonly IntPtr HWND_TOP = new IntPtr(0); public static readonly IntPtr HWND_BOTTOM = new IntPtr(1); } }
34.996914
152
0.608784
[ "MIT" ]
mediaexplorer74/Mosaic2022
Mosaic.Base/WinAPI.cs
11,341
C#
#region Copyright (c) 2011 Atif Aziz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // ReSharper disable once CheckNamespace namespace Elmah.Fabmail { using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using MoreLinq; partial class StackTraceHtmlFragments : IStackTraceFormatter<string> { public string BeforeType { get; set; } public string AfterType { get; set; } public string BeforeMethod { get; set; } public string AfterMethod { get; set; } public string BeforeParameterType { get; set; } public string AfterParameterType { get; set; } public string BeforeParameterName { get; set; } public string AfterParameterName { get; set; } public string BeforeFile { get; set; } public string AfterFile { get; set; } public string BeforeLine { get; set; } public string AfterLine { get; set; } public string BeforeFrame { get; set; } public string AfterFrame { get; set; } public string BeforeParameters { get; set; } public string AfterParameters { get; set; } string IStackTraceFormatter<string>.Text(string text) => string.IsNullOrEmpty(text) ? string.Empty : WebUtility.HtmlEncode(text); string IStackTraceFormatter<string>.Type(string markup) => BeforeType + markup + AfterType; string IStackTraceFormatter<string>.Method(string markup) => BeforeMethod + markup + AfterMethod; string IStackTraceFormatter<string>.ParameterType(string markup) => BeforeParameterType + markup + AfterParameterType; string IStackTraceFormatter<string>.ParameterName(string markup) => BeforeParameterName + markup + AfterParameterName; string IStackTraceFormatter<string>.File(string markup) => BeforeFile + markup + AfterFile; string IStackTraceFormatter<string>.Line(string markup) => BeforeLine + markup + AfterLine; string IStackTraceFormatter<string>.BeforeFrame => BeforeFrame ?? string.Empty; string IStackTraceFormatter<string>.AfterFrame => AfterFrame ?? string.Empty; string IStackTraceFormatter<string>.BeforeParameters => BeforeParameters ?? string.Empty; string IStackTraceFormatter<string>.AfterParameters => AfterParameters ?? string.Empty; } partial interface IStackTraceFormatter<T> { T Text (string text); T Type (T markup); T Method (T markup); T ParameterType (T markup); T ParameterName (T markup); T File (T markup); T Line (T markup); T BeforeFrame { get; } T AfterFrame { get; } T BeforeParameters { get; } T AfterParameters { get; } } static partial class StackTraceFormatter { static readonly StackTraceHtmlFragments DefaultStackTraceHtmlFragments = new StackTraceHtmlFragments(); public static string FormatHtml(string text, IStackTraceFormatter<string> formatter) { return string.Concat(Format(text, formatter ?? DefaultStackTraceHtmlFragments)); } public static IEnumerable<T> Format<T>(string text, IStackTraceFormatter<T> formatter) { Debug.Assert(text != null); var frames = StackTraceParser.Parse ( text, (idx, len, txt) => new { Index = idx, End = idx + len, Text = txt, Markup = formatter.Text(txt), }, (t, m) => new { Type = new { t.Index, t.End, Markup = formatter.Type(t.Markup) }, Method = new { m.Index, m.End, Markup = formatter.Method(m.Markup) } }, (t, n) => new { Type = new { t.Index, t.End, Markup = formatter.ParameterType(t.Markup) }, Name = new { n.Index, n.End, Markup = formatter.ParameterName(n.Markup) } }, (p, ps) => new { List = p, Parameters = ps.ToArray() }, (f, l) => new { File = f.Text.Length > 0 ? new { f.Index, f.End, Markup = formatter.File(f.Markup) } : null, Line = l.Text.Length > 0 ? new { l.Index, l.End, Markup = formatter.Line(l.Markup) } : null, }, (f, tm, p, fl) => from tokens in new[] { new[] { new { f.Index, End = f.Index, Markup = formatter.BeforeFrame }, tm.Type, tm.Method, new { p.List.Index, End = p.List.Index, Markup = formatter.BeforeParameters }, }, from pe in p.Parameters from e in new[] { pe.Type, pe.Name } select e, new[] { new { Index = p.List.End, p.List.End, Markup = formatter.AfterParameters }, fl.File, fl.Line, new { Index = f.End, f.End, Markup = formatter.AfterFrame }, }, } from token in tokens where token != null select token ); return from token in Enumerable.Repeat(new { Index = 0, End = 0, Markup = default(T) }, 1) .Concat(from tokens in frames from token in tokens select token) .Pairwise((prev, curr) => new { Previous = prev, Current = curr }) from m in new[] { formatter.Text(text.Substring(token.Previous.End, token.Current.Index - token.Previous.End)), token.Current.Markup, } select m; } } }
47.00641
148
0.501296
[ "Apache-2.0" ]
elmah/Fabmail
src/App_Packages/StackTraceFormatter/StackTraceFormatter.cs
7,333
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the pinpoint-2016-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.Pinpoint.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Pinpoint.Model.Internal.MarshallTransformations { /// <summary> /// CreatePushTemplate Request Marshaller /// </summary> public class CreatePushTemplateRequestMarshaller : IMarshaller<IRequest, CreatePushTemplateRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((CreatePushTemplateRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(CreatePushTemplateRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Pinpoint"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-12-01"; request.HttpMethod = "POST"; if (!publicRequest.IsSetTemplateName()) throw new AmazonPinpointException("Request object does not have required field TemplateName set"); request.AddPathResource("{template-name}", StringUtils.FromString(publicRequest.TemplateName)); request.ResourcePath = "/v1/templates/{template-name}/push"; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); var context = new JsonMarshallerContext(request, writer); context.Writer.WriteObjectStart(); var marshaller = PushNotificationTemplateRequestMarshaller.Instance; marshaller.Marshall(publicRequest.PushNotificationTemplateRequest, context); context.Writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static CreatePushTemplateRequestMarshaller _instance = new CreatePushTemplateRequestMarshaller(); internal static CreatePushTemplateRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreatePushTemplateRequestMarshaller Instance { get { return _instance; } } } }
37.362745
151
0.655733
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Pinpoint/Generated/Model/Internal/MarshallTransformations/CreatePushTemplateRequestMarshaller.cs
3,811
C#
// *********************************************************************** // Assembly : IronyModManager // Author : Mario // Created : 01-11-2020 // // Last Modified By : Mario // Last Modified On : 01-29-2021 // *********************************************************************** // <copyright file="DIPackage.Avalonia.cs" company="Mario"> // Mario // </copyright> // <summary></summary> // *********************************************************************** using System.Collections.Generic; using System; using Avalonia.ReactiveUI; using IronyModManager.Log; using ReactiveUI; using Splat; using Container = SimpleInjector.Container; namespace IronyModManager.DI { /// <summary> /// Class DIPackage. /// Implements the <see cref="SimpleInjector.Packaging.IPackage" /> /// </summary> /// <seealso cref="SimpleInjector.Packaging.IPackage" /> public partial class DIPackage { /// <summary> /// Registers the avalonia services. /// </summary> /// <param name="container">The container.</param> #pragma warning disable CA1822 // Mark members as static #region Methods private void RegisterAvaloniaServices(Container container) #pragma warning restore CA1822 // Mark members as static { var viewFetcher = new AvaloniaActivationForViewFetcher(); var dataTemplate = new AutoDataTemplateBindingHook(); Locator.CurrentMutable.RegisterConstant(viewFetcher, typeof(IActivationForViewFetcher)); Locator.CurrentMutable.RegisterConstant(dataTemplate, typeof(IPropertyBindingHook)); container.RegisterInstance<IActivationForViewFetcher>(viewFetcher); container.RegisterInstance<IPropertyBindingHook>(dataTemplate); Avalonia.Logging.Logger.Sink = new AvaloniaLogger(); } #endregion Methods } }
34.8
100
0.596134
[ "MIT" ]
LunarTraveller/IronyModManager
src/IronyModManager/DI/DIPackage.Avalonia.cs
1,916
C#
#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using XLua; using System.Collections.Generic; namespace XLua.CSObjectWrap { using Utils = XLua.Utils; public class XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapPathfindingRadiusModifierWrapWrapWrapWrap { public static void __Register(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Type type = typeof(XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapPathfindingRadiusModifierWrapWrapWrap); Utils.BeginObjectRegister(type, L, translator, 0, 0, 0, 0); Utils.EndObjectRegister(type, L, translator, null, null, null, null, null); Utils.BeginClassRegister(type, L, __CreateInstance, 2, 0, 0); Utils.RegisterFunc(L, Utils.CLS_IDX, "__Register", _m___Register_xlua_st_); Utils.EndClassRegister(type, L, translator); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __CreateInstance(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); if(LuaAPI.lua_gettop(L) == 1) { XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapPathfindingRadiusModifierWrapWrapWrap gen_ret = new XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapPathfindingRadiusModifierWrapWrapWrap(); translator.Push(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapPathfindingRadiusModifierWrapWrapWrap constructor!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m___Register_xlua_st_(RealStatePtr L) { try { { System.IntPtr _L = LuaAPI.lua_touserdata(L, 1); XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapPathfindingRadiusModifierWrapWrapWrap.__Register( _L ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } } }
26.081818
197
0.598815
[ "MIT" ]
zxsean/DCET
Unity/Assets/Model/XLua/Gen/XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapPathfindingRadiusModifierWrapWrapWrapWrap.cs
2,871
C#
/* Copyright 2010-2013 10gen 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.IO; using MongoDB.Bson.IO; namespace MongoDB.Bson.Serialization.Serializers { /// <summary> /// Represents a serializer for BsonBooleans. /// </summary> public class BsonBooleanSerializer : BsonBaseSerializer { // private static fields private static BsonBooleanSerializer __instance = new BsonBooleanSerializer(); // constructors /// <summary> /// Initializes a new instance of the BsonBooleanSerializer class. /// </summary> public BsonBooleanSerializer() { } // public static properties /// <summary> /// Gets an instance of the BsonBooleanSerializer class. /// </summary> public static BsonBooleanSerializer Instance { get { return __instance; } } // public methods /// <summary> /// Deserializes an object from a BsonReader. /// </summary> /// <param name="bsonReader">The BsonReader.</param> /// <param name="nominalType">The nominal type of the object.</param> /// <param name="actualType">The actual type of the object.</param> /// <param name="options">The serialization options.</param> /// <returns>An object.</returns> public override object Deserialize( BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) { VerifyTypes(nominalType, actualType, typeof(BsonBoolean)); var bsonType = bsonReader.GetCurrentBsonType(); switch (bsonType) { case BsonType.Boolean: return (BsonBoolean)bsonReader.ReadBoolean(); default: var message = string.Format("Cannot deserialize BsonBoolean from BsonType {0}.", bsonType); throw new FileFormatException(message); } } /// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { throw new ArgumentNullException("value"); } var bsonBoolean = (BsonBoolean)value; bsonWriter.WriteBoolean(bsonBoolean.Value); } } }
34.122449
111
0.603768
[ "Apache-2.0" ]
ExM/mongo-csharp-driver
MongoDB.Bson/Serialization/Serializers/BsonBooleanSerializer.cs
3,346
C#
using Microsoft.AspNetCore.Mvc; using ReyNenePalace.Models; using ReyNenePalace.ViewModels; namespace ReyNenePalace.Components { public class ShoppingCartSummary: ViewComponent { private readonly ShoppingCart _shoppingCart; public ShoppingCartSummary(ShoppingCart shoppingCart) { _shoppingCart = shoppingCart; } public IViewComponentResult Invoke() { var items = _shoppingCart.GetShoppingCartItems(); _shoppingCart.ShoppingCartItems = items; var shoppingCartViewModel = new ShoppingCartViewModel { ShoppingCart = _shoppingCart, ShoppingCartTotal = _shoppingCart.GetShoppingCartTotal() }; return View(shoppingCartViewModel); } } }
25.65625
72
0.645554
[ "MIT" ]
foloNene/ReyNenePalace
ReyNenePalace/Components/ShoppingCartSummary.cs
823
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the forecast-2018-06-26.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.ForecastService.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.ForecastService.Model.Internal.MarshallTransformations { /// <summary> /// DescribePredictorBacktestExportJob Request Marshaller /// </summary> public class DescribePredictorBacktestExportJobRequestMarshaller : IMarshaller<IRequest, DescribePredictorBacktestExportJobRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DescribePredictorBacktestExportJobRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DescribePredictorBacktestExportJobRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.ForecastService"); string target = "AmazonForecast.DescribePredictorBacktestExportJob"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2018-06-26"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetPredictorBacktestExportJobArn()) { context.Writer.WritePropertyName("PredictorBacktestExportJobArn"); context.Writer.Write(publicRequest.PredictorBacktestExportJobArn); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static DescribePredictorBacktestExportJobRequestMarshaller _instance = new DescribePredictorBacktestExportJobRequestMarshaller(); internal static DescribePredictorBacktestExportJobRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DescribePredictorBacktestExportJobRequestMarshaller Instance { get { return _instance; } } } }
37.628571
183
0.654518
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/ForecastService/Generated/Model/Internal/MarshallTransformations/DescribePredictorBacktestExportJobRequestMarshaller.cs
3,951
C#
using TMPro; using UnityEngine; public class GameLogic : MonoBehaviour { [SerializeField] private int MinNumber = 1; [SerializeField] private int MaxNumber = 1000; [SerializeField] private TextMeshProUGUI label; private int CurrentMin; private int CurrentMax; private int CurrentGuess; private System.Random rand; void Start() { rand = new System.Random(); MinNumber = 1; MaxNumber = 1000; CurrentMin = MinNumber; CurrentMax = MaxNumber + 1; UpdateGuess(); } void Update() { } public void Higher() { if(CurrentMax != CurrentMin) { CurrentMin = CurrentGuess == MaxNumber ? MaxNumber : CurrentGuess + 1; UpdateGuess(); } } public void Lower() { if (CurrentMax != CurrentMin) { CurrentMax = CurrentGuess == MinNumber ? MinNumber : CurrentGuess - 1; UpdateGuess(); } } void UpdateGuess() { if (CurrentMin > CurrentMax) CurrentMax = CurrentMin; CurrentGuess = rand.Next(CurrentMin, CurrentMax); label.SetText(CurrentGuess.ToString()); } }
22.081967
58
0.518931
[ "MIT" ]
yottaawesome/unity-playground
src/2D/Number Wizard UI/Assets/Scripts/GameLogic.cs
1,347
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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 Microsoft.Azure.Commands.Blueprint.Models; using Microsoft.Azure.Commands.Common.Authentication.Abstractions; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Azure.Management.Blueprint.Models; namespace Microsoft.Azure.Commands.Blueprint.Common { public interface IBlueprintClient { IAzureSubscription Subscription { get; } IEnumerable<PSBlueprint> ListBlueprints(IEnumerable<string> mgList); PSBlueprint GetBlueprint(string mgName, string blueprintName); PSPublishedBlueprint GetPublishedBlueprint(string mgName, string blueprintName, string version); PSPublishedBlueprint GetLatestPublishedBlueprint(string mgName, string blueprintName); IEnumerable<PSBlueprintAssignment> ListBlueprintAssignments(string subscriptionId); PSBlueprintAssignment GetBlueprintAssignment(string subscriptionId, string blueprintAssignmentName); PSBlueprintAssignment DeleteBlueprintAssignment(string subscriptionId, string blueprintAssignmentName); PSBlueprintAssignment CreateOrUpdateBlueprintAssignment(string subscriptionId, string assignmentName, Assignment assignment); } }
45.227273
134
0.707035
[ "MIT" ]
haitch/azure-powershell
src/ResourceManager/Blueprint/Commands.Blueprint/Common/IBlueprintClient.cs
1,949
C#
using System; using System.Threading.Tasks; namespace FunK { public partial class F { public static Operation<T, T> Begin<T>(T value) => Operation<T, T>.Of(value); public static Operation<T, T> Begin<T>(Result<T> value) => Operation<T, T>.Of(value); public static Operation<(T,R), (T,R)> Begin<T, R>((T,R) value) => Operation<(T,R), (T,Random)>.Of(value); public static Operation<T, TR> Begin<T, TR>(T value, Func<object, TR> func) => Operation<T, TR>.Of(value, func); public static Operation<T, TR> Begin<T, TR>(Result<T> value, Func<object, TR> func) => Operation<T, TR>.Of(value, func); } public partial class Operation<T, FR> { internal Result<T> value; internal Func<object, Result<FR>> λ; internal Operation(T value, Func<object, FR> func) { this.value = F.Result(value); λ = x => func(x); } internal Operation(Result<T> value, Func<object, FR> func) { this.value = value; λ = x => func(x); } internal Operation(T value, Func<object, Result<FR>> func) { this.value = F.Result(value); λ = func; } internal Operation(Result<T> value, Func<object, Result<FR>> func) { this.value = value; λ = func; } public static Operation<T, T> Of(T value) => new Operation<T, T>(value, x => (T)x); public static Operation<T, FR> Of(Result<T> value) => new Operation<T, FR>(value, x => (FR)x); public static Operation<T, TR> Of<TR>(T value, Func<object, TR> func) => new Operation<T, TR>(value, func); public static Operation<T, TR> Of<TR>(Result<T> value, Func<object, TR> func) => new Operation<T, TR>(value, func); } public static partial class OperationExtensions { /// <summary> /// Creates a new <see cref="Operation{T, FR}"/> with the set of λ from the original but with an starting value of <paramref name="value"/> /// </summary> public static Operation<T, TR> Using<T, TR>(this Operation<T, TR> operation, T value) => new Operation<T, TR>(value, operation.λ); /// <summary> /// Creates a new <see cref="Operation{T, FR}"/> with the set of λ from the original but with an starting value of <paramref name="value"/> /// </summary> public static Operation<T, TR> Using<T, TR>(this Operation<T, TR> operation, Result<T> value) => new Operation<T, TR>(value, operation.λ); /// <summary> /// Creates a new async <see cref="Operation{T, FR}"/> with the set of λ from the original but with an starting value of <paramref name="value"/> once it resolves /// </summary> public static Task<Operation<T, TR>> Using<T, TR>(this Operation<T, TR> operation, Task<Result<T>> task) => task.Map(value => new Operation<T, TR>(value, operation.λ)); /// <summary> /// Joins two <see cref="Operation{T, FR}"/> into one, by applying all the λ from <paramref name="operation2"/> to <paramref name="operation"/> /// </summary> public static Operation<T, FR> Apply<T, R, FR>(this Operation<T, R> operation, Operation<T, FR> operation2) => new Operation<T, FR>(operation.value, x => operation.λ(x).Bind(r => operation2.λ(r))); } }
34.940594
170
0.562766
[ "MIT" ]
juanpablocruz/FunK
FunK/Operation/Operation.cs
3,545
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a the Phase Extern Generator // Changes to this file will be lost if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using Phase; using Phase.Attributes; namespace Haxe.Crypto { }
29.5
80
0.438257
[ "MIT" ]
CoderLine/Phase
Phase.Haxe/generated/std/Haxe/Crypto/HashMethod.cs
413
C#
using System; using System.Windows; using System.Windows.Media.Animation; using EasyNews.Models; using EasyNews.ViewModels; namespace EasyNews.Views { /// <summary> /// Interaction logic for RssScroller.xaml /// </summary> public partial class RssScroller { /// <summary> /// The expandAnimation used by the Scroller /// </summary> private DoubleAnimation _expandAnimation; /// <summary> /// The collapseAnimation used by the Scroller /// </summary> private DoubleAnimation _collapseAnimation; /// <summary> /// The Storyboard for the expandAnimation /// </summary> private Storyboard _expandArticleListStoryboard; /// <summary> /// The Storyboard for the collapseAnimation /// </summary> private Storyboard _collapseArticleListStoryboard; /// <summary> /// The EventHandler, that is called when the collapseAnimation starts /// </summary> private EventHandler _collapseAnimationStarted; /// <summary> /// Action, that is executed when an Article is selected. Parent class sets this variable. /// </summary> public Action<EasyNewsFeedItem> ArticleSelected { private get; set; } /// <summary> /// Constructor /// Initializes the animations /// </summary> public RssScroller() { InitializeComponent(); var halfSecondDuration = new Duration(TimeSpan.FromMilliseconds(500)); _expandAnimation = new DoubleAnimation(200, 400, halfSecondDuration); _collapseAnimation = new DoubleAnimation(400, 200, halfSecondDuration); } /// <summary> /// Sets the event handlers for started/completed of the animations /// Also initializes the animations and connects them with their Storyboards /// </summary> /// <param name="completed">The EventHandler to be called when the animations are completed</param> /// <param name="started">The EventHandler to be called when the animations are started</param> public void InitAnimations(EventHandler completed, EventHandler started) { _collapseAnimationStarted = started; _collapseAnimation.Completed += completed; _expandAnimation.Completed += completed; _expandArticleListStoryboard = new Storyboard(); _expandArticleListStoryboard.Children.Add(_expandAnimation); _collapseArticleListStoryboard = new Storyboard(); _collapseArticleListStoryboard.Children.Add(_collapseAnimation); Storyboard.SetTargetName(_expandAnimation, ArticleList.Name); Storyboard.SetTargetName(_collapseAnimation, ArticleList.Name); Storyboard.SetTargetProperty(_expandAnimation, new PropertyPath(WidthProperty)); Storyboard.SetTargetProperty(_collapseAnimation, new PropertyPath(WidthProperty)); } /// <summary> /// Called when ArticleList is loaded. /// Sets the DataContext of the ScrollViewer. /// </summary> /// <param name="sender">EventSender</param> /// <param name="args">EventArgs</param> private void OnArticleListLoaded(object sender, RoutedEventArgs args) { var context = DataContext as ArticleViewModel; ScrollViewer.DataContext = context; } /// <summary> /// Called when an article is selected. Calls the EventHandler ArticleSelected with the selected FeedItem /// </summary> /// <param name="sender">EventSender (the Button that was clicked)</param> /// <param name="args">EventArgs</param> private void OnArticleSelected(object sender, RoutedEventArgs args) { var b = (FrameworkElement)sender; var item = (EasyNewsFeedItem) b.DataContext; ArticleSelected(item); } /// <summary> /// Called when the user hovers over the Scroller. /// Starts the expandAnimation. /// </summary> /// <param name="sender">EventSender</param> /// <param name="args">EventArgs</param> private void OnArticleListHover(object sender, RoutedEventArgs args) { if (_collapseAnimationStarted == null) { return; } _collapseAnimationStarted(sender,args); _expandArticleListStoryboard.Begin(this); } /// <summary> /// Called when the user hovers out of the Scroller. /// Starts the collapseAnimation. /// </summary> /// <param name="sender">EventSender</param> /// <param name="args">EventArgs</param> private void OnArticleListHoverOut(object sender, RoutedEventArgs args) { if (_collapseAnimationStarted == null) { return; } _collapseAnimationStarted(sender,args); _collapseArticleListStoryboard.Begin(this); } } }
37.035971
113
0.619075
[ "MIT" ]
shutdownr/easy-news
EasyNews/Views/RssScroller.xaml.cs
5,150
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Compute.V20210401 { public static class GetVirtualMachineScaleSet { /// <summary> /// Describes a Virtual Machine Scale Set. /// </summary> public static Task<GetVirtualMachineScaleSetResult> InvokeAsync(GetVirtualMachineScaleSetArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetVirtualMachineScaleSetResult>("azure-native:compute/v20210401:getVirtualMachineScaleSet", args ?? new GetVirtualMachineScaleSetArgs(), options.WithVersion()); } public sealed class GetVirtualMachineScaleSetArgs : Pulumi.InvokeArgs { /// <summary> /// The expand expression to apply on the operation. 'UserData' retrieves the UserData property of the VM scale set that was provided by the user during the VM scale set Create/Update operation /// </summary> [Input("expand")] public string? Expand { get; set; } /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the VM scale set. /// </summary> [Input("vmScaleSetName", required: true)] public string VmScaleSetName { get; set; } = null!; public GetVirtualMachineScaleSetArgs() { } } [OutputType] public sealed class GetVirtualMachineScaleSetResult { /// <summary> /// Specifies additional capabilities enabled or disabled on the Virtual Machines in the Virtual Machine Scale Set. For instance: whether the Virtual Machines have the capability to support attaching managed data disks with UltraSSD_LRS storage account type. /// </summary> public readonly Outputs.AdditionalCapabilitiesResponse? AdditionalCapabilities; /// <summary> /// Policy for automatic repairs. /// </summary> public readonly Outputs.AutomaticRepairsPolicyResponse? AutomaticRepairsPolicy; /// <summary> /// When Overprovision is enabled, extensions are launched only on the requested number of VMs which are finally kept. This property will hence ensure that the extensions do not run on the extra overprovisioned VMs. /// </summary> public readonly bool? DoNotRunExtensionsOnOverprovisionedVMs; /// <summary> /// The extended location of the Virtual Machine Scale Set. /// </summary> public readonly Outputs.ExtendedLocationResponse? ExtendedLocation; /// <summary> /// Specifies information about the dedicated host group that the virtual machine scale set resides in. &lt;br&gt;&lt;br&gt;Minimum api-version: 2020-06-01. /// </summary> public readonly Outputs.SubResourceResponse? HostGroup; /// <summary> /// Resource Id /// </summary> public readonly string Id; /// <summary> /// The identity of the virtual machine scale set, if configured. /// </summary> public readonly Outputs.VirtualMachineScaleSetIdentityResponse? Identity; /// <summary> /// Resource location /// </summary> public readonly string Location; /// <summary> /// Resource name /// </summary> public readonly string Name; /// <summary> /// Specifies the orchestration mode for the virtual machine scale set. /// </summary> public readonly string? OrchestrationMode; /// <summary> /// Specifies whether the Virtual Machine Scale Set should be overprovisioned. /// </summary> public readonly bool? Overprovision; /// <summary> /// Specifies information about the marketplace image used to create the virtual machine. This element is only used for marketplace images. Before you can use a marketplace image from an API, you must enable the image for programmatic use. In the Azure portal, find the marketplace image that you want to use and then click **Want to deploy programmatically, Get Started -&gt;**. Enter any required information and then click **Save**. /// </summary> public readonly Outputs.PlanResponse? Plan; /// <summary> /// Fault Domain count for each placement group. /// </summary> public readonly int? PlatformFaultDomainCount; /// <summary> /// The provisioning state, which only appears in the response. /// </summary> public readonly string ProvisioningState; /// <summary> /// Specifies information about the proximity placement group that the virtual machine scale set should be assigned to. &lt;br&gt;&lt;br&gt;Minimum api-version: 2018-04-01. /// </summary> public readonly Outputs.SubResourceResponse? ProximityPlacementGroup; /// <summary> /// Specifies the scale-in policy that decides which virtual machines are chosen for removal when a Virtual Machine Scale Set is scaled-in. /// </summary> public readonly Outputs.ScaleInPolicyResponse? ScaleInPolicy; /// <summary> /// When true this limits the scale set to a single placement group, of max size 100 virtual machines. NOTE: If singlePlacementGroup is true, it may be modified to false. However, if singlePlacementGroup is false, it may not be modified to true. /// </summary> public readonly bool? SinglePlacementGroup; /// <summary> /// The virtual machine scale set sku. /// </summary> public readonly Outputs.SkuResponse? Sku; /// <summary> /// Specifies the Spot Restore properties for the virtual machine scale set. /// </summary> public readonly Outputs.SpotRestorePolicyResponse? SpotRestorePolicy; /// <summary> /// Resource tags /// </summary> public readonly ImmutableDictionary<string, string>? Tags; /// <summary> /// Resource type /// </summary> public readonly string Type; /// <summary> /// Specifies the ID which uniquely identifies a Virtual Machine Scale Set. /// </summary> public readonly string UniqueId; /// <summary> /// The upgrade policy. /// </summary> public readonly Outputs.UpgradePolicyResponse? UpgradePolicy; /// <summary> /// The virtual machine profile. /// </summary> public readonly Outputs.VirtualMachineScaleSetVMProfileResponse? VirtualMachineProfile; /// <summary> /// Whether to force strictly even Virtual Machine distribution cross x-zones in case there is zone outage. zoneBalance property can only be set if the zones property of the scale set contains more than one zone. If there are no zones or only one zone specified, then zoneBalance property should not be set. /// </summary> public readonly bool? ZoneBalance; /// <summary> /// The virtual machine scale set zones. NOTE: Availability zones can only be set when you create the scale set /// </summary> public readonly ImmutableArray<string> Zones; [OutputConstructor] private GetVirtualMachineScaleSetResult( Outputs.AdditionalCapabilitiesResponse? additionalCapabilities, Outputs.AutomaticRepairsPolicyResponse? automaticRepairsPolicy, bool? doNotRunExtensionsOnOverprovisionedVMs, Outputs.ExtendedLocationResponse? extendedLocation, Outputs.SubResourceResponse? hostGroup, string id, Outputs.VirtualMachineScaleSetIdentityResponse? identity, string location, string name, string? orchestrationMode, bool? overprovision, Outputs.PlanResponse? plan, int? platformFaultDomainCount, string provisioningState, Outputs.SubResourceResponse? proximityPlacementGroup, Outputs.ScaleInPolicyResponse? scaleInPolicy, bool? singlePlacementGroup, Outputs.SkuResponse? sku, Outputs.SpotRestorePolicyResponse? spotRestorePolicy, ImmutableDictionary<string, string>? tags, string type, string uniqueId, Outputs.UpgradePolicyResponse? upgradePolicy, Outputs.VirtualMachineScaleSetVMProfileResponse? virtualMachineProfile, bool? zoneBalance, ImmutableArray<string> zones) { AdditionalCapabilities = additionalCapabilities; AutomaticRepairsPolicy = automaticRepairsPolicy; DoNotRunExtensionsOnOverprovisionedVMs = doNotRunExtensionsOnOverprovisionedVMs; ExtendedLocation = extendedLocation; HostGroup = hostGroup; Id = id; Identity = identity; Location = location; Name = name; OrchestrationMode = orchestrationMode; Overprovision = overprovision; Plan = plan; PlatformFaultDomainCount = platformFaultDomainCount; ProvisioningState = provisioningState; ProximityPlacementGroup = proximityPlacementGroup; ScaleInPolicy = scaleInPolicy; SinglePlacementGroup = singlePlacementGroup; Sku = sku; SpotRestorePolicy = spotRestorePolicy; Tags = tags; Type = type; UniqueId = uniqueId; UpgradePolicy = upgradePolicy; VirtualMachineProfile = virtualMachineProfile; ZoneBalance = zoneBalance; Zones = zones; } } }
42.271967
444
0.64951
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Compute/V20210401/GetVirtualMachineScaleSet.cs
10,103
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace PullRequestMonitor.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.1.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("30")] public int PollIntervalSeconds { get { return ((int)(this["PollIntervalSeconds"])); } set { this["PollIntervalSeconds"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("")] public string VstsAccount { get { return ((string)(this["VstsAccount"])); } set { this["VstsAccount"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("00000000-0000-0000-0000-000000000000")] public global::System.Guid ProjectId { get { return ((global::System.Guid)(this["ProjectId"])); } set { this["ProjectId"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute(".*")] public string RepoNamePattern { get { return ((string)(this["RepoNamePattern"])); } set { this["RepoNamePattern"] = value; } } } }
38.333333
151
0.566609
[ "MIT" ]
jornletnes/pull-request-monitor
PullRequestMonitor/Properties/Settings.Designer.cs
2,877
C#
using System; using System.Linq; using QueryEncapsulation.Web.Data; using QueryEncapsulation.Web.Domain; namespace QueryEncapsulation.Web { public static class SeedData { public static void Init() { using (var context = new AppDbContext()) { if (!context.Posts.Any()) { context.Posts.Add(new Post{PostDate=DateTime.Parse("6/1/2015"), Title = "New Tech Roundup", Body = "", Comments = {new Comment{Email = "zune@microsoft.com"}, new Comment{Email = "dart@google.com"}}}); context.Posts.Add(new Post{PostDate=DateTime.Parse("6/2/2015"), Title = "Hipsters, and how to spot them", Body = "", Comments = {new Comment{Email = "clippy@microsoft.com"}, new Comment{Email = "polymer@google.com"}, new Comment{Email = "silverlight@microsoft.com"}}}); context.Posts.Add(new Post{PostDate=DateTime.Parse("6/3/2015"), Title = "Bug or feature?", Body = "", Comments = {new Comment{Email = "vista@microsoft.com"}, new Comment{Email = "angularjs@google.com"}, new Comment{Email = "vs2015@microsoft.com"}}}); context.Posts.Add(new Post{PostDate=DateTime.Parse("6/4/2015"), Title = "Hot Tech Features", Body = "", Comments = {new Comment{Email = "aurelia@awesome.com"}, new Comment{Email = "angularjs@google.com"}, new Comment{Email = "ps@sony.com"}}}); context.SaveChanges(); } } } } }
51.923077
275
0.67037
[ "Apache-2.0" ]
MattHoneycutt/asp.net-samples
QueryEncapsulation/QueryEncapsulation.Web/App_Start/SeedData.cs
1,350
C#
using GW2Api.NET.V2; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace GW2Api.NET.IntegrationTests.V2.Commerce { [TestClass, TestCategory("Large"), TestCategory("V2"), TestCategory("V2 Commerce")] public class CommerceTests { private IGw2ApiV2 _api; [TestInitialize] public void Setup() => _api = new Gw2ApiV2(new HttpClient()); [DataTestMethod] [DynamicData(nameof(TestData.DefaultTestData), typeof(TestData), DynamicDataSourceType.Method)] public async Task GetCoinsToGemsExchangeInfoAsync_AnyParams_ReturnsTheInfo(Func<CancellationTokenSource> ctsFactory) { using var cts = ctsFactory(); var quantity = 100_000; var result = await _api.GetCoinsToGemsExchangeInfoAsync(quantity, cts.GetTokenOrDefault()); Assert.IsTrue(result.CoinsPerGem > 0); Assert.IsTrue(result.Quantity > 0); } [DataTestMethod] [DynamicData(nameof(TestData.DefaultTestData), typeof(TestData), DynamicDataSourceType.Method)] public async Task GetGemsToCoinsExchangeInfoAsync_AnyParams_ReturnsTheInfo(Func<CancellationTokenSource> ctsFactory) { using var cts = ctsFactory(); var quantity = 100; var result = await _api.GetGemsToCoinsExchangeInfoAsync(quantity, cts.GetTokenOrDefault()); Assert.IsTrue(result.CoinsPerGem > 0); Assert.IsTrue(result.Quantity > 0); } [DataTestMethod] [DynamicData(nameof(TestData.DefaultTestData), typeof(TestData), DynamicDataSourceType.Method)] public async Task GetAllItemListingIdsAsync_AnyParams_ReturnsAllIds(Func<CancellationTokenSource> ctsFactory) { using var cts = ctsFactory(); var result = await _api.GetAllItemListingIdsAsync(cts.GetTokenOrDefault()); Assert.IsTrue(result.Any()); } [DataTestMethod] [DynamicData(nameof(TestData.DefaultTestData), typeof(TestData), DynamicDataSourceType.Method)] public async Task GetItemListingAsync_ValidId_ReturnsThatListing(Func<CancellationTokenSource> ctsFactory) { using var cts = ctsFactory(); var id = 24; var result = await _api.GetItemListingAsync(id, cts.GetTokenOrDefault()); Assert.AreEqual(id, result.Id); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] [DynamicData(nameof(TestData.DefaultTestData), typeof(TestData), DynamicDataSourceType.Method)] public async Task GetItemListingsAsync_NullIds_ThrowsArgumentNullException(Func<CancellationTokenSource> ctsFactory) { using var cts = ctsFactory(); await _api.GetItemListingsAsync(ids: null, cts.GetTokenOrDefault()); } [DataTestMethod] [DynamicData(nameof(TestData.DefaultTestData), typeof(TestData), DynamicDataSourceType.Method)] public async Task GetItemListingsAsync_ValidIds_ReturnsThoseListings(Func<CancellationTokenSource> ctsFactory) { using var cts = ctsFactory(); var ids = new List<int> { 24, 68, 69 }; var result = await _api.GetItemListingsAsync(ids, cts.GetTokenOrDefault()); CollectionAssert.AreEquivalent(ids, result.Select(x => x.Id).ToList()); } [DataTestMethod] [DynamicData(nameof(TestData.DefaultTestData), typeof(TestData), DynamicDataSourceType.Method)] public async Task GetItemListingsAsync_NoIds_ReturnsAPage(Func<CancellationTokenSource> ctsFactory) { using var cts = ctsFactory(); var result = await _api.GetItemListingsAsync(token: cts.GetTokenOrDefault()); Assert.IsTrue(result.Data.Any()); } [DataTestMethod] [DynamicData(nameof(TestData.DefaultTestData), typeof(TestData), DynamicDataSourceType.Method)] public async Task GetAllMarketPriceIdsAsync_AnyParams_ReturnsAllIds(Func<CancellationTokenSource> ctsFactory) { using var cts = ctsFactory(); var result = await _api.GetAllMarketPriceIdsAsync(cts.GetTokenOrDefault()); Assert.IsTrue(result.Any()); } [DataTestMethod] [DynamicData(nameof(TestData.DefaultTestData), typeof(TestData), DynamicDataSourceType.Method)] public async Task GetMarketPriceAsync_ValidId_ReturnsThatListing(Func<CancellationTokenSource> ctsFactory) { using var cts = ctsFactory(); var id = 24; var result = await _api.GetMarketPriceAsync(id, cts.GetTokenOrDefault()); Assert.AreEqual(id, result.Id); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] [DynamicData(nameof(TestData.DefaultTestData), typeof(TestData), DynamicDataSourceType.Method)] public async Task GetMarketPricesAsync_NullIds_ThrowsArgumentNullException(Func<CancellationTokenSource> ctsFactory) { using var cts = ctsFactory(); await _api.GetMarketPricesAsync(ids: null, cts.GetTokenOrDefault()); } [DataTestMethod] [DynamicData(nameof(TestData.DefaultTestData), typeof(TestData), DynamicDataSourceType.Method)] public async Task GetMarketPricesAsync_ValidIds_ReturnsThoseListings(Func<CancellationTokenSource> ctsFactory) { using var cts = ctsFactory(); var ids = new List<int> { 24, 68, 69 }; var result = await _api.GetMarketPricesAsync(ids, cts.GetTokenOrDefault()); CollectionAssert.AreEquivalent(ids, result.Select(x => x.Id).ToList()); } [DataTestMethod] [DynamicData(nameof(TestData.DefaultTestData), typeof(TestData), DynamicDataSourceType.Method)] public async Task GetMarketPricesAsync_NoIds_ReturnsAPage(Func<CancellationTokenSource> ctsFactory) { using var cts = ctsFactory(); var result = await _api.GetMarketPricesAsync(token: cts.GetTokenOrDefault()); Assert.IsTrue(result.Data.Any()); } } }
40.279503
125
0.660756
[ "MIT" ]
RyanClementsHax/GW2Api.NET
GW2Api.NET.IntegrationTests/V2/Commerce/CommerceTests.cs
6,487
C#
using Accord.IO; using Accord.Neuro; using BLL.Services.Interfaces; using Deedle; namespace BLL.Services.Implementations { public class DataService : IDataService { private const string ValidationDataFileName = "validation.csv"; private const string TrainigDataFileName = "training.csv"; private const string NetworkStateFileName = "trained_network.state"; private readonly IFileService _fileService; public DataService(IFileService fileService) { _fileService = fileService; } public Frame<int, string> GetValidationData() { return _fileService.GetDataFromFile(ValidationDataFileName); } public Frame<int, string> GetTrainingData() { return _fileService.GetDataFromFile(TrainigDataFileName); } public void SaveNetworkState(ActivationNetwork network) { string fileName = _fileService.CreateFilePath(NetworkStateFileName); Serializer.Save(network, fileName); } } }
28.918919
80
0.66729
[ "MIT" ]
dkiryanov/voenmeh-machine-learning-backpropagation
BLL/Services/Implementations/DataService.cs
1,072
C#
namespace Lexepars { public interface INamed { string Name { get; } } }
11.625
28
0.548387
[ "MIT" ]
DNemtsov/Lexepars
src/Lexepars/Grammar/INamed.cs
95
C#