content
stringlengths
23
1.05M
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Text.Json; using Azure.Core; namespace Microsoft.Bot.Connector.Client.Models { public partial class OAuthCard : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); if (Optional.IsDefined(ContentType)) { writer.WritePropertyName("contentType"); writer.WriteStringValue(ContentType); } if (Optional.IsDefined(Text)) { writer.WritePropertyName("text"); writer.WriteStringValue(Text); } if (Optional.IsDefined(ConnectionName)) { writer.WritePropertyName("connectionName"); writer.WriteStringValue(ConnectionName); } if (Optional.IsDefined(TokenExchangeResource)) { writer.WritePropertyName("tokenExchangeResource"); writer.WriteObjectValue(TokenExchangeResource); } if (Optional.IsDefined(Buttons)) { writer.WritePropertyName("buttons"); writer.WriteObjectValue(Buttons); } writer.WriteEndObject(); } } }
/*---------------------------------------------------------------- // auth: https://github.com/code-mirage/FolderBrowserDialog // date: // desc: Visual Studio 2017 default FolderBrowserDialog not practical The component will be overridden // mdfy: Windragon //----------------------------------------------------------------*/ using System; namespace WLib.WinCtrls.ExplorerCtrl.FileFolderCtrl { [Flags] public enum FOS { FOS_ALLNONSTORAGEITEMS = 0x80, FOS_ALLOWMULTISELECT = 0x200, FOS_CREATEPROMPT = 0x2000, FOS_DEFAULTNOMINIMODE = 0x20000000, FOS_DONTADDTORECENT = 0x2000000, FOS_FILEMUSTEXIST = 0x1000, FOS_FORCEFILESYSTEM = 0x40, FOS_FORCESHOWHIDDEN = 0x10000000, FOS_HIDEMRUPLACES = 0x20000, FOS_HIDEPINNEDPLACES = 0x40000, FOS_NOCHANGEDIR = 8, FOS_NODEREFERENCELINKS = 0x100000, FOS_NOREADONLYRETURN = 0x8000, FOS_NOTESTFILECREATE = 0x10000, FOS_NOVALIDATE = 0x100, FOS_OVERWRITEPROMPT = 2, FOS_PATHMUSTEXIST = 0x800, FOS_PICKFOLDERS = 0x20, FOS_SHAREAWARE = 0x4000, FOS_STRICTFILETYPES = 4 } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class ItemButtonUI : MonoBehaviour { public Button button = null; public Image image = null; public Text textObj = null; public Text itemCount = null; public Pickable item = null; void Update() { if(item == null) { Destroy(gameObject); return; }//if textObj.text = item.name; itemCount.text = item.count + ""; }//Update }//ItemButtonUI
using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; using UnityEngine.UIElements; using UnityEditor.Experimental.GraphView; using System; using System.Linq; namespace AI.BehaviourTree { public class BehaviourTreeView : GraphView { public Action<NodeView> OnNodeSelected; public new class UxmlFactory : UxmlFactory<BehaviourTreeView, GraphView.UxmlTraits> { } BehaviourTree tree; public BehaviourTreeView() { Insert(0, new GridBackground()); this.AddManipulator(new ContentZoomer()); this.AddManipulator(new ContentDragger()); this.AddManipulator(new SelectionDragger()); this.AddManipulator(new RectangleSelector()); var styleSheet = AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/ZAI/Editor/BehaviourTreeEditor.uss"); styleSheets.Add(styleSheet); Undo.undoRedoPerformed += OnUndoRedo; } private void OnUndoRedo() { PopulateView(tree); AssetDatabase.SaveAssets(); } NodeView FindNodeView(Node node) { return GetNodeByGuid(node.guid) as NodeView; } internal void PopulateView(BehaviourTree tree) { this.tree = tree; graphViewChanged -= OnGraphViewChanged; DeleteElements(graphElements.ToList()); graphViewChanged += OnGraphViewChanged; if (tree.rootNode == null) { tree.rootNode = tree.CreateNode(typeof(RootNode)) as RootNode; EditorUtility.SetDirty(tree); AssetDatabase.SaveAssets(); } // Creates node view tree.nodes.ForEach(n => CreateNodeView(n)); // Create edges tree.nodes.ForEach(n => { var childern = tree.GetChildren(n); childern.ForEach(c => { NodeView parentView = FindNodeView(n); NodeView childView = FindNodeView(c); Edge edge = parentView.output.ConnectTo(childView.input); AddElement(edge); }); }); } public override List<Port> GetCompatiblePorts(Port startPort, NodeAdapter nodeAdapter) { return ports.ToList().Where(endPort => endPort.direction != startPort.direction && endPort.node != startPort.node).ToList(); } private GraphViewChange OnGraphViewChanged(GraphViewChange graphViewChange) { if (graphViewChange.elementsToRemove != null) { graphViewChange.elementsToRemove.ForEach(element => { NodeView nodeView = element as NodeView; if (nodeView != null) { tree.DeleteNode(nodeView.node); } Edge edge = element as Edge; if (edge != null) { NodeView parentView = edge.output.node as NodeView; NodeView childeView = edge.input.node as NodeView; tree.RemoveChild(parentView.node, childeView.node); } }); } if (graphViewChange.edgesToCreate != null) { graphViewChange.edgesToCreate.ForEach(edge => { NodeView parentView = edge.output.node as NodeView; NodeView childeView = edge.input.node as NodeView; tree.AddChild(parentView.node, childeView.node); }); } if (graphViewChange.movedElements != null) { nodes.ForEach((n) => { NodeView view = n as NodeView; view.SortChildren(); }); } return graphViewChange; } public override void BuildContextualMenu(ContextualMenuPopulateEvent evt) { // base.BuildContextualMenu(evt); { var types = TypeCache.GetTypesDerivedFrom<ActionNode>(); foreach (var type in types) { evt.menu.AppendAction($"[{type.BaseType.Name}] {type.Name}", (a) => CreateNode(type)); } } { var types = TypeCache.GetTypesDerivedFrom<CompositeNode>(); foreach (var type in types) { evt.menu.AppendAction($"[{type.BaseType.Name}] {type.Name}", (a) => CreateNode(type)); } } { var types = TypeCache.GetTypesDerivedFrom<DecoratorNode>(); foreach (var type in types) { evt.menu.AppendAction($"[{type.BaseType.Name}] {type.Name}", (a) => CreateNode(type)); } } } private void CreateNode(System.Type type) { Node node = tree.CreateNode(type); CreateNodeView(node); } void CreateNodeView(Node node) { NodeView nodeView = new NodeView(node); nodeView.OnNodeSelected = OnNodeSelected; AddElement(nodeView); } public void UpdateNodeState() { nodes.ForEach(n => { NodeView view = n as NodeView; view.UpdateState(); }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace NWheels.Domains.ECommerce.Tests.Stacks { [TestFixture] public class ManualStackTests { [Test] public void ManualTest_MongoBreezeNancy() { StackTestUtility.RunManualTest( StackName.MongoNancyBreeze, runExecutable: StackTestUtility.TestBoardExeFilePath, browseUrl: "http://localhost:8901/admin"); } } }
class GroupSample2 { // The element type of the data source. public class Student { public string First { get; set; } public string Last { get; set; } public int ID { get; set; } public List<int> Scores; } public static List<Student> GetStudents() { // Use a collection initializer to create the data source. Note that each element // in the list contains an inner sequence of scores. List<Student> students = new List<Student> { new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores= new List<int> {97, 72, 81, 60}}, new Student {First="Claire", Last="O'Donnell", ID=112, Scores= new List<int> {75, 84, 91, 39}}, new Student {First="Sven", Last="Mortensen", ID=113, Scores= new List<int> {99, 89, 91, 95}}, new Student {First="Cesar", Last="Garcia", ID=114, Scores= new List<int> {72, 81, 65, 84}}, new Student {First="Debra", Last="Garcia", ID=115, Scores= new List<int> {97, 89, 85, 82}} }; return students; } // This method groups students into percentile ranges based on their // grade average. The Average method returns a double, so to produce a whole // number it is necessary to cast to int before dividing by 10. static void Main() { // Obtain the data source. List<Student> students = GetStudents(); // Write the query. var studentQuery = from student in students let avg = (int)student.Scores.Average() group student by (avg == 0 ? 0 : avg / 10) into g orderby g.Key select g; // Execute the query. foreach (var studentGroup in studentQuery) { int temp = studentGroup.Key * 10; Console.WriteLine("Students with an average between {0} and {1}", temp, temp + 10); foreach (var student in studentGroup) { Console.WriteLine(" {0}, {1}:{2}", student.Last, student.First, student.Scores.Average()); } } // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } /* Output: Students with an average between 70 and 80 Omelchenko, Svetlana:77.5 O'Donnell, Claire:72.25 Garcia, Cesar:75.5 Students with an average between 80 and 90 Garcia, Debra:88.25 Students with an average between 90 and 100 Mortensen, Sven:93.5 */
using UnityEngine; using System.Collections; using UnityEngine.UI; public class PlatformTimerController : MonoBehaviour { public static PlatformTimerController instance = null; public bool startPlatformTimer; public float platformTimer; public float currentPlatformTimer; public Text platformTimerText; private CanvasRenderer canvasRenderer; void Awake() { if (instance == null) { instance = this; } else if (instance != this) { Destroy(gameObject); } } // Use this for initialization void Start () { platformTimer = 2f; currentPlatformTimer = platformTimer; canvasRenderer = GetComponent<CanvasRenderer>(); } // Update is called once per frame void Update () { if (startPlatformTimer) { currentPlatformTimer -= Time.deltaTime; platformTimerText.text = currentPlatformTimer.ToString("00.00"); if (currentPlatformTimer <= 0) { ResetCounter(); Debug.Log("Game Over"); GameController.instance.ResetGame(); } } } public void ResetCounter() { SwitchVisibility(); startPlatformTimer = false; currentPlatformTimer = platformTimer; platformTimerText.text = "00.00"; } public void SwitchVisibility() { if (canvasRenderer.GetAlpha() != 0) { canvasRenderer.SetAlpha(0); } else { canvasRenderer.SetAlpha(1); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FeindeSpawnen : MonoBehaviour { public GameObject[] feinde; public int maxNum = 5; void Start() { for (int i = 0; i < maxNum; i++) { GameObject go = feinde[Random.Range(0, feinde.Length)]; Instantiate( go, new Vector3( Random.Range(-10.0f, 10.0f), go.transform.position.y, Random.Range(-10.0f, 10.0f) ), Quaternion.identity ); } } private void Update() { if (GameObject.FindGameObjectsWithTag("Feinde").Length < maxNum) { int index = Random.Range(0, feinde.Length); GameObject go = feinde[index]; Debug.Log("index: " + index); Debug.Log("length: " + feinde.Length); Debug.Log("pop"); Instantiate( go, new Vector3( Random.Range(-10.0f, 10.0f), go.transform.position.y, Random.Range(-10.0f, 10.0f) ), Quaternion.identity ); } } }
using System.Text.Json.Serialization; namespace Iot.PnpDashboard.Devices.Dtdl { public class InterfaceSchema { [DTMI] [JsonPropertyName("@id")] public string Id { get; set; } [IRI] [JsonPropertyName("@type")] public string Type { get; set; } [JsonPropertyName("comment")] public string Comment { get; set; } [JsonPropertyName("description")] public string Description { get; set; } [JsonPropertyName("displayName")] public string DisplayName { get; set; } } }
using System; using UnityEngine; public class PanelBackgroundComponent : ComponentBase { public ButtonComponent CloseBtn; public GameObject MaskBackground; public event Action<UIPanelType> CloseEvent; private UIPanelType m_PanelType; private MaskType m_MaskType= MaskType.CloseBtnAndMaskBg_CloseEvent; #region override methods protected override void AddEvent() { base.AddEvent(); UIEventListener.Get(this.MaskBackground).onClick += (go) => this.MaskClosePanel(); this.CloseBtn.ClickEvent += this.BtnClosePanel; } public override void Clear() { base.Clear(); this.CloseEvent = null; } #endregion #region private private void BtnClosePanel() { if (this.m_MaskType == MaskType.CloseBtnAndMaskBg_CloseEvent) this.ClosePanel(); } private void MaskClosePanel() { if (this.m_MaskType == MaskType.OnlyMaskBg_CloseEvent) this.ClosePanel(); } private void ClosePanel() { if (this.CloseEvent != null) { this.CloseEvent(this.m_PanelType); } } private void UpdateState() { TransUtils.EnableCollider(this.MyTransform, true); switch (this.m_MaskType) { case MaskType.OnlyMaskBg: case MaskType.OnlyMaskBg_CloseEvent: this.CloseBtn.Hide(); break; case MaskType.CloseBtnAndMaskBg_CloseEvent: this.CloseBtn.Show(); break; case MaskType.None: this.Hide(); break; } } #endregion #region public methods public void Show(Transform parent,UIPanelType type,MaskType maskType) { this.m_MaskType = maskType; this.m_PanelType = type; this.UpdateState(); this.MyTransform.SetParent(parent); this.MyTransform.localPosition = Vector3.zero; this.MyTransform.localRotation = Quaternion.identity; this.MyTransform.localScale = Vector3.one; this.MyTransform.SetAsFirstSibling(); this.Show(); } #endregion }
using System; namespace CodingMilitia.Grpc.Shared.Attributes { [AttributeUsage(AttributeTargets.Method)] public class GrpcMethodAttribute : Attribute { public string Name { get; set; } public GrpcMethodAttribute(string name) { Name = name; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using Xunit; namespace SharpUV.Tests { public class TimerTests { [Fact] public void Delay() { //delay to test (3 seconds) var delay = new TimeSpan(0, 0, 0, 3 /* seconds */); //tollerance (actual time should be between 2.9 and 3.1 seconds) var tollerance = new TimeSpan(0, 0, 0, 0, 100 /* milliseconds */); Stopwatch stopwatch = new Stopwatch(); Timer timer = new Timer(); Loop.Current.QueueWork(() => { stopwatch.Start(); timer.Start(delay, TimeSpan.Zero, () => { stopwatch.Stop(); timer.Stop(); timer.Close(); }); }); Loop.Current.Run(); Assert.True(stopwatch.Elapsed >= delay.Subtract(tollerance)); Assert.True(stopwatch.Elapsed < delay.Add(tollerance)); } } }
using Castle.Core.Logging; using Eaf.Dependency; using System; namespace Eaf.Web.Security.AntiForgery { public class EafAntiForgeryManager : IEafAntiForgeryManager, IEafAntiForgeryValidator, ITransientDependency { public EafAntiForgeryManager(IEafAntiForgeryConfiguration configuration) { Configuration = configuration; Logger = NullLogger.Instance; } public IEafAntiForgeryConfiguration Configuration { get; } public ILogger Logger { protected get; set; } public virtual string GenerateToken() { return Guid.NewGuid().ToString("D"); } public virtual bool IsValid(string cookieValue, string tokenValue) { return cookieValue == tokenValue; } } }
using System.Collections.Generic; using EES.Entities.Concrete; using EES.Entities.View; namespace EES.Business.Abstract { public interface IEvaluationQuestionService { List<EvaluationQuestion> GetAll(); EvaluationQuestion GetById(int questionId); EvaluationQuestion Insert(EvaluationQuestion evaluationQuestion); EvaluationQuestion Update(EvaluationQuestion evaluationQuestion); void Delete(int questionId); List<EvaluationQuestion> GetQuestionsByRole(int roleId); List<QuestionRoleView> GetQuestionRoleViews(); } }
// Copyright (c) Microsoft Corporation // The Microsoft Corporation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.Plugin.Folder; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Wox.Plugin; namespace Wox.Test.Plugins { [TestClass] public class FolderPluginTest { [TestMethod] public void ContextMenuLoaderReturnContextMenuForFolderWithOpenInConsoleWhenLoadContextMenusIsCalled() { // Arrange var mock = new Mock<IPublicAPI>(); var pluginInitContext = new PluginInitContext() { API = mock.Object }; var contextMenuLoader = new ContextMenuLoader(pluginInitContext); var searchResult = new SearchResult() { Type = ResultType.Folder, FullPath = "C:/DummyFolder" }; var result = new Result() { ContextData = searchResult }; // Act List<ContextMenuResult> contextMenuResults = contextMenuLoader.LoadContextMenus(result); // Assert Assert.AreEqual(2, contextMenuResults.Count); Assert.AreEqual(Microsoft.Plugin.Folder.Properties.Resources.Microsoft_plugin_folder_copy_path, contextMenuResults[0].Title); Assert.AreEqual(Microsoft.Plugin.Folder.Properties.Resources.Microsoft_plugin_folder_open_in_console, contextMenuResults[1].Title); } [TestMethod] public void ContextMenuLoaderReturnContextMenuForFileWithOpenInConsoleWhenLoadContextMenusIsCalled() { // Arrange var mock = new Mock<IPublicAPI>(); var pluginInitContext = new PluginInitContext() { API = mock.Object }; var contextMenuLoader = new ContextMenuLoader(pluginInitContext); var searchResult = new SearchResult() { Type = ResultType.File, FullPath = "C:/DummyFile.cs" }; var result = new Result() { ContextData = searchResult }; // Act List<ContextMenuResult> contextMenuResults = contextMenuLoader.LoadContextMenus(result); // Assert Assert.AreEqual(3, contextMenuResults.Count); Assert.AreEqual(Microsoft.Plugin.Folder.Properties.Resources.Microsoft_plugin_folder_open_containing_folder, contextMenuResults[0].Title); Assert.AreEqual(Microsoft.Plugin.Folder.Properties.Resources.Microsoft_plugin_folder_copy_path, contextMenuResults[1].Title); Assert.AreEqual(Microsoft.Plugin.Folder.Properties.Resources.Microsoft_plugin_folder_open_in_console, contextMenuResults[2].Title); } } }
 namespace Shop.Common.Models { using System; using Newtonsoft.Json; public class TokenResponse { [JsonProperty("token")] public string Token { get; set; } [JsonProperty("expiration")] public DateTime Expiration { get; set; } } }
namespace Secucard.Connect.Auth.Model { public class AnonymousCredentials : OAuthCredentials { public override string Id { get { return "anonymous"; } } } }
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace PlayWebApp.Services.Database.Model { public abstract class BusinessEntity : EntityBase { [Required] [StringLength(128)] [Column(TypeName = "nvarchar")] public virtual string Name { get; set; } [Column(TypeName = "bit")] public virtual bool Active { get; set; } [MaxLength(128)] [Column(TypeName = "nvarchar")] public string DefaultAddressId { get; set; } public Address DefaultAddress { get; set; } } public class Customer : BusinessEntity { public virtual ICollection<Booking> Bookings { get; set; } public virtual ICollection<CustomerAddress> Addresses { get; set; } public string PaymentMethod { get; set; } } public class Supplier : BusinessEntity { public virtual ICollection<SupplierAddress> Addresses { get; set; } public string ExpenseAccount { get; set; } } }
using EFCorePowerTools.Shared.Models; using Microsoft.VisualStudio.Data.Core; using Microsoft.VisualStudio.Data.Services; using RevEng.Shared; using System; using System.Collections.Generic; using System.Data.Common; using System.Data.SqlClient; using System.IO; using System.Windows.Forms; // ReSharper disable once CheckNamespace namespace EFCorePowerTools.Helpers { internal class VsDataHelper { internal Dictionary<string, DatabaseConnectionModel> GetDataConnections(EFCorePowerToolsPackage package) { var credentialStore = new CredentialStore(); // http://www.mztools.com/articles/2007/MZ2007018.aspx Dictionary<string, DatabaseConnectionModel> databaseList = new Dictionary<string, DatabaseConnectionModel>(); var dataExplorerConnectionManager = package.GetService<IVsDataExplorerConnectionManager>(); Guid providerSqLite = new Guid(EFCorePowerTools.Shared.Resources.SQLiteProvider); Guid providerSqlitePrivate = new Guid(EFCorePowerTools.Shared.Resources.SQLitePrivateProvider); Guid providerNpgsql = new Guid(Resources.NpgsqlProvider); Guid providerMysql = new Guid(Resources.MysqlVSProvider); Guid providerOracle = new Guid(Resources.OracleProvider); try { if (dataExplorerConnectionManager?.Connections?.Values != null) { foreach (var connection in dataExplorerConnectionManager.Connections.Values) { try { var sConnectionString = DataProtection.DecryptString(connection.EncryptedConnectionString); var info = new DatabaseConnectionModel() { ConnectionName = connection.DisplayName, DatabaseType = DatabaseType.Undefined, ConnectionString = sConnectionString, DataConnection = connection.Connection, }; var objProviderGuid = connection.Provider; if (objProviderGuid == providerSqLite || objProviderGuid == providerSqlitePrivate) { info.DatabaseType = DatabaseType.SQLite; } if (objProviderGuid == new Guid(Resources.SqlServerDotNetProvider) || objProviderGuid == providerNpgsql) { info.DatabaseType = objProviderGuid == providerNpgsql ? DatabaseType.Npgsql : DatabaseType.SQLServer; } // This provider depends on https://dev.mysql.com/downloads/windows/visualstudio/ if (objProviderGuid == providerMysql) { info.DatabaseType = DatabaseType.Mysql; } if (objProviderGuid == providerOracle) { info.DatabaseType = DatabaseType.Oracle; } if (info.DatabaseType != DatabaseType.Undefined && !databaseList.ContainsKey(sConnectionString)) { databaseList.Add(sConnectionString, info); } } catch (Exception ex) { package.LogError(new List<string> { ex.Message }, ex); } } } } catch (Exception ex) { package.LogError(new List<string> { ex.Message }, ex); } try { foreach (var connection in credentialStore.GetStoredDatabaseConnections()) { databaseList.Add(connection.ConnectionName, connection); } } catch (Exception ex) { package.LogError(new List<string> { ex.Message }, ex); } return databaseList; } internal static DatabaseConnectionModel PromptForInfo(EFCorePowerToolsPackage package) { // Show dialog with SqlClient selected by default var dialogFactory = package.GetService<IVsDataConnectionDialogFactory>(); var dialog = dialogFactory.CreateConnectionDialog(); dialog.AddAllSources(); dialog.SelectedSource = new Guid("067ea0d9-ba62-43f7-9106-34930c60c528"); var dialogResult = dialog.ShowDialog(connect: true); if (dialogResult == null) return new DatabaseConnectionModel {DatabaseType = DatabaseType.Undefined}; var info = GetDatabaseInfo(package, dialogResult.Provider, DataProtection.DecryptString(dialog.EncryptedConnectionString)); if (info.ConnectionName == Guid.Empty.ToString()) return new DatabaseConnectionModel { DatabaseType = DatabaseType.Undefined }; var savedName = SaveDataConnection(package, dialog.EncryptedConnectionString, info.DatabaseType, new Guid(info.ConnectionName)); info.ConnectionName = savedName; info.DataConnection = dialogResult; return info; } internal static string PromptForDacpac() { var ofd = new OpenFileDialog { Filter = "SQL Server Database Project|*.dacpac", CheckFileExists = true, Multiselect = false, ValidateNames = true, Title = "Select .dacpac File" }; if (ofd.ShowDialog() != DialogResult.OK) return null; return ofd.FileName; } internal static string SaveDataConnection(EFCorePowerToolsPackage package, string encryptedConnectionString, DatabaseType dbType, Guid provider) { var dataExplorerConnectionManager = package.GetService<IVsDataExplorerConnectionManager>(); var savedName = GetSavedConnectionName(DataProtection.DecryptString(encryptedConnectionString), dbType); dataExplorerConnectionManager.AddConnection(savedName, provider, encryptedConnectionString, true); return savedName; } internal static void RemoveDataConnection(EFCorePowerToolsPackage package, IVsDataConnection dataConnection) { var dataExplorerConnectionManager = package.GetService<IVsDataExplorerConnectionManager>(); foreach (var connection in dataExplorerConnectionManager.Connections.Values) { if (connection.Connection == dataConnection) { dataExplorerConnectionManager.RemoveConnection(connection); } } } private static DatabaseConnectionModel GetDatabaseInfo(EFCorePowerToolsPackage package, Guid provider, string connectionString) { var dbType = DatabaseType.Undefined; var providerGuid = Guid.Empty.ToString(); // Find provider var providerManager = package.GetService<IVsDataProviderManager>(); IVsDataProvider dp; providerManager.Providers.TryGetValue(provider, out dp); if (dp != null) { var providerInvariant = (string)dp.GetProperty("InvariantName"); dbType = DatabaseType.Undefined; if (providerInvariant == "System.Data.SQLite.EF6") { dbType = DatabaseType.SQLite; providerGuid = EFCorePowerTools.Shared.Resources.SQLitePrivateProvider; } if (providerInvariant == "System.Data.SqlClient") { dbType = DatabaseType.SQLServer; providerGuid = Resources.SqlServerDotNetProvider; } if (providerInvariant == "Npgsql") { dbType = DatabaseType.Npgsql; providerGuid = Resources.NpgsqlProvider; } if (providerInvariant == "Oracle.ManagedDataAccess.Client") { dbType = DatabaseType.Oracle; providerGuid = Resources.OracleProvider; } if (providerInvariant == "Mysql" || providerInvariant == "MySql.Data.MySqlClient") { dbType = DatabaseType.Mysql; providerGuid = Resources.MysqlVSProvider; } } return new DatabaseConnectionModel { DatabaseType = dbType, ConnectionString = connectionString, ConnectionName = providerGuid, }; } public static string GetSavedConnectionName(string connectionString, DatabaseType dbType) { if (dbType == DatabaseType.SQLServer) { return PathFromConnectionString(connectionString); } var builder = new DbConnectionStringBuilder(); builder.ConnectionString = connectionString; var result = string.Empty; if (builder.TryGetValue("Data Source", out object dataSource)) { result += dataSource.ToString(); } if (builder.TryGetValue("DataSource", out object dataSource2)) { result += dataSource2.ToString(); } if (builder.TryGetValue("Database", out object database)) { result+= "." + database.ToString(); } return result; } private static string PathFromConnectionString(string connectionString) { var builder = new SqlConnectionStringBuilder(connectionString); var database = builder.InitialCatalog; if (string.IsNullOrEmpty(database)) { if (!string.IsNullOrEmpty(builder.AttachDBFilename)) { database = Path.GetFileName(builder.AttachDBFilename); } } string server; if (builder.DataSource.StartsWith("(localdb)", StringComparison.OrdinalIgnoreCase)) { server = builder.DataSource; } else { using (var cmd = new SqlCommand(connectionString)) { using (var conn = new SqlConnection(connectionString)) { cmd.Connection = conn; cmd.CommandText = "SELECT SERVERPROPERTY('ServerName')"; conn.Open(); server = (string)cmd.ExecuteScalar(); } } } return server + "." + database; } public static string GetDatabaseName(string connectionString, DatabaseType dbType) { var builder = new DbConnectionStringBuilder(); builder.ConnectionString = connectionString; if (builder.TryGetValue("Initial Catalog", out object catalog)) { return catalog.ToString(); } if (builder.TryGetValue("Database", out object database)) { return database.ToString(); } if (builder.TryGetValue("Data Source", out object dataSource)) { return dataSource.ToString(); } if (builder.TryGetValue("DataSource", out object dataSource2)) { return dataSource2.ToString(); } return dbType.ToString(); } } }
namespace Application.UseCases.Accounts.GetAccount; using FluentValidation; public sealed class GetAccountInputValidator : AbstractValidator<GetAccountInput> { public GetAccountInputValidator() { RuleFor(x => x.AccountId).NotEmpty(); } }
using System; using System.Security.Cryptography; using System.Text; namespace DotneterWhj.ToolKits { /// <summary> /// 加密工具类 /// </summary> public static class EncryptHelper { //默认密钥 private static string AESKey = "[45/*YUIdse..e;]"; private static string DESKey = "[&HdN72]"; /// <summary> /// AES加密 /// </summary> public static string AESEncrypt(string value, string _aeskey = "[45/*YUIdse..e;]") { if (string.IsNullOrEmpty(_aeskey)) { _aeskey = AESKey; } byte[] keyArray = Encoding.UTF8.GetBytes(_aeskey); byte[] toEncryptArray = Encoding.UTF8.GetBytes(value); RijndaelManaged rDel = new RijndaelManaged(); rDel.Key = keyArray; rDel.Mode = CipherMode.ECB; rDel.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = rDel.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } /// <summary> /// AES解密 /// </summary> public static string AESDecrypt(string value, string _aeskey = "[45/*YUIdse..e;]") { try { if (string.IsNullOrEmpty(_aeskey)) { _aeskey = AESKey; } byte[] keyArray = Encoding.UTF8.GetBytes(_aeskey); byte[] toEncryptArray = Convert.FromBase64String(value); RijndaelManaged rDel = new RijndaelManaged(); rDel.Key = keyArray; rDel.Mode = CipherMode.ECB; rDel.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = rDel.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Encoding.UTF8.GetString(resultArray); } catch { return string.Empty; } } /// <summary> /// DES加密 /// </summary> public static string DESEncrypt(string value, string _deskey = "[&HdN72]") { if (string.IsNullOrEmpty(_deskey)) { _deskey = DESKey; } byte[] keyArray = Encoding.UTF8.GetBytes(_deskey); byte[] toEncryptArray = Encoding.UTF8.GetBytes(value); DESCryptoServiceProvider rDel = new DESCryptoServiceProvider(); rDel.Key = keyArray; rDel.Mode = CipherMode.ECB; rDel.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = rDel.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } /// <summary> /// DES解密 /// </summary> public static string DESDecrypt(string value, string _deskey = "[&HdN72]") { try { if (string.IsNullOrEmpty(_deskey)) { _deskey = DESKey; } byte[] keyArray = Encoding.UTF8.GetBytes(_deskey); byte[] toEncryptArray = Convert.FromBase64String(value); DESCryptoServiceProvider rDel = new DESCryptoServiceProvider(); rDel.Key = keyArray; rDel.Mode = CipherMode.ECB; rDel.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = rDel.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Encoding.UTF8.GetString(resultArray); } catch { return string.Empty; } } public static string MD5(string value) { byte[] result = Encoding.UTF8.GetBytes(value); MD5 md5 = new MD5CryptoServiceProvider(); byte[] output = md5.ComputeHash(result); return BitConverter.ToString(output).Replace("-", ""); } public static string HMACMD5(string value, string hmacKey) { HMACSHA1 hmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(hmacKey)); byte[] result = System.Text.Encoding.UTF8.GetBytes(value); byte[] output = hmacsha1.ComputeHash(result); return BitConverter.ToString(output).Replace("-", ""); } /// <summary> /// base64编码 /// </summary> /// <returns></returns> public static string Base64Encode(string value) { string result = Convert.ToBase64String(Encoding.Default.GetBytes(value)); return result; } /// <summary> /// base64解码 /// </summary> /// <returns></returns> public static string Base64Decode(string value) { string result = Encoding.Default.GetString(Convert.FromBase64String(value)); return result; } } }
namespace Test.Radical.Helpers { using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Reflection; using SharpTestsEx; using System.Collections.Generic; using Topics.Radical.Reflection; [TestClass()] public class TypeExtensionTests { [TestMethod] public void typeExtension_toShortString_normal_should_return_valid_type_string() { var expected = "Topics.Radical.Reflection.TypeExtensions, Radical"; var target = typeof( Topics.Radical.Reflection.TypeExtensions ); var actual = Topics.Radical.Reflection.TypeExtensions.ToShortString( target ); actual.Should().Be.EqualTo( expected ); } [TestMethod] [ExpectedException( typeof( ArgumentNullException ) )] public void typeExtension_toShortString_using_null_type_reference_should_raise_ArgumentNullException() { Topics.Radical.Reflection.TypeExtensions.ToShortString( null ); } [TestMethod] public void typeExtension_toShortString_using_mscorelib_type_should_not_add_assemblyName_to_type_string() { var expected = "System.String"; var target = typeof( String ); var actual = Topics.Radical.Reflection.TypeExtensions.ToShortString( target ); actual.Should().Be.EqualTo( expected ); } [TestMethod] public void typeExtension_toString_S_using_mscorelib_type_should_not_add_assemblyName_to_type_string() { var expected = "System.String"; var target = typeof( String ); var actual = Topics.Radical.Reflection.TypeExtensions.ToString( target, "S" ); actual.Should().Be.EqualTo( expected ); } [TestMethod] public void typeextensions_toShortNameString_using_non_generic_type_should_return_type_name() { var expected = "String"; var actual = typeof( String ).ToShortNameString(); actual.Should().Be.EqualTo( expected ); } [TestMethod] public void typeextensions_toShortNameString_using_generic_type_should_return_type_name() { var expected = "List<String>"; var actual = typeof( List<String> ).ToShortNameString(); actual.Should().Be.EqualTo( expected ); } [TestMethod] public void typeextensions_toShortNameString_using_complex_generic_type_should_return_type_name() { var expected = "IDictionary<List<Object>, List<String>>"; var actual = typeof( IDictionary<List<Object>, List<String>> ).ToShortNameString(); actual.Should().Be.EqualTo( expected ); } [TestMethod] public void typeextensions_toString_SN_using_complex_generic_type_should_return_type_name() { var expected = "IDictionary<List<Object>, List<String>>"; var actual = typeof( IDictionary<List<Object>, List<String>> ).ToString( "SN" ); actual.Should().Be.EqualTo( expected ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.ComponentModel; using Microsoft.AspNetCore.DataProtection.Infrastructure; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.DataProtection { /// <summary> /// Data protection extensions for <see cref="IServiceProvider"/>. /// </summary> public static class DataProtectionUtilityExtensions { /// <summary> /// Returns a unique identifier for this application. /// </summary> /// <param name="services">The application-level <see cref="IServiceProvider"/>.</param> /// <returns>A unique application identifier, or null if <paramref name="services"/> is null /// or cannot provide a unique application identifier.</returns> /// <remarks> /// <para> /// The returned identifier should be stable for repeated runs of this same application on /// this machine. Additionally, the identifier is only unique within the scope of a single /// machine, e.g., two different applications on two different machines may return the same /// value. /// </para> /// <para> /// This identifier may contain security-sensitive information such as physical file paths, /// configuration settings, or other machine-specific information. Callers should take /// special care not to disclose this information to untrusted entities. /// </para> /// </remarks> [EditorBrowsable(EditorBrowsableState.Never)] public static string? GetApplicationUniqueIdentifier(this IServiceProvider services) { string? discriminator = null; if (services != null) { discriminator = services.GetService<IApplicationDiscriminator>()?.Discriminator; } // Remove whitespace and homogenize empty -> null discriminator = discriminator?.Trim(); return (string.IsNullOrEmpty(discriminator)) ? null : discriminator; } } }
using System; namespace Ofl.Atlassian.Jira.V3 { public static class JiraClientExtensions { #region Read-ony state. private const string Version = "3"; private static readonly string ApiAbsolutePathBase = $"/rest/api/{ Version }/"; #endregion #region Extensions. internal static string CreateApiUri( this JiraClientConfiguration configuration, string path ) { // Validate parameters. if (configuration == null) throw new ArgumentNullException(nameof(configuration)); if (string.IsNullOrWhiteSpace(path)) throw new ArgumentNullException(nameof(path)); // Construct the URL. Get the base first. string? url = configuration.BaseUrl?.ToString(); // Combine. url = CombineUrls(url, ApiAbsolutePathBase); // Combine with the path passed in. return CombineUrls(url, path); } // TODO: Need to find a URL manipulation library, or have one of our own in Ofl.Core. private static string CombineUrls(string? url1, string? url2) { // Format parameters, trim the ends. url1 = url1?.TrimEnd('/') ?? ""; url2 = url2?.TrimStart('/') ?? ""; // If the right is empty, return the left. Or the other way around. if (url1 == "") return url2; if (url2 == "") return url1; // Combine the two. return $"{ url1 }/{ url2 }"; } #endregion } }
//------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //------------------------------------------------------------------------------ using System; using System.Xml; using static Microsoft.IdentityModel.Logging.LogHelper; namespace Microsoft.IdentityModel.Xml { /// <summary> /// Wraps a <see cref="XmlDictionaryWriter"/> and delegates to InnerWriter. /// </summary> public class DelegatingXmlDictionaryWriter : XmlDictionaryWriter { private XmlDictionaryWriter _innerWriter; private XmlDictionaryWriter _internalWriter; private XmlDictionaryWriter _tracingWriter; /// <summary> /// Initializes a new instance of <see cref="DelegatingXmlDictionaryWriter"/> /// </summary> protected DelegatingXmlDictionaryWriter() { } /// <summary> /// Gets or sets a <see cref="XmlDictionaryWriter"/> for tracing. /// </summary> /// <exception cref="ArgumentNullException"> if 'value' is null.</exception> protected XmlDictionaryWriter TracingWriter { get => _tracingWriter; set => _tracingWriter = value ?? throw LogArgumentNullException(nameof(value)); } /// <summary> /// Gets or sets the InnerWriter. /// </summary> /// <exception cref="ArgumentNullException"> if 'value' is null.</exception> protected XmlDictionaryWriter InnerWriter { get => _innerWriter; set => _innerWriter = value ?? throw LogArgumentNullException(nameof(value)); } /// <summary> /// Gets or sets the InternalWriter. /// </summary> /// <exception cref="ArgumentNullException"> if 'value' is null.</exception> internal XmlDictionaryWriter InternalWriter { get => _internalWriter; set => _internalWriter = value ?? throw LogArgumentNullException(nameof(value)); } #if NET45 /// <summary> /// Closes the underlying stream. /// </summary> public override void Close() { UseInnerWriter.Close(); TracingWriter?.Close(); InternalWriter?.Close(); } #endif /// <summary> /// Flushes the underlying stream. /// </summary> public override void Flush() { UseInnerWriter.Flush(); TracingWriter?.Flush(); InternalWriter?.Flush(); } /// <summary> /// Encodes the specified binary bytes as Base64 and writes out the resulting text. /// </summary> /// <param name="buffer">Byte array to encode.</param> /// <param name="index">The position in the buffer indicating the start of the bytes to write.</param> /// <param name="count">The number of bytes to write.</param> public override void WriteBase64(byte[] buffer, int index, int count) { UseInnerWriter.WriteBase64(buffer, index, count); TracingWriter?.WriteBase64(buffer, index, count); InternalWriter?.WriteBase64(buffer, index, count); } /// <summary> /// Writes out a CDATA block containing the specified text. /// </summary> /// <param name="text">The text to place inside the CDATA block.</param> public override void WriteCData(string text) { UseInnerWriter.WriteCData(text); TracingWriter?.WriteCData(text); InternalWriter?.WriteCData(text); } /// <summary> /// Forces the generation of a character entity for the specified Unicode character value. /// </summary> /// <param name="ch">The Unicode character for which to generate a character entity.</param> public override void WriteCharEntity(char ch) { UseInnerWriter.WriteCharEntity(ch); TracingWriter?.WriteCharEntity(ch); InternalWriter?.WriteCharEntity(ch); } /// <summary> /// When overridden in a derived class, writes text one buffer at a time. /// </summary> /// <param name="buffer">Character array containing the text to write.</param> /// <param name="index">The position in the buffer indicating the start of the text to write.</param> /// <param name="count">The number of characters to write.</param> public override void WriteChars(char[] buffer, int index, int count) { UseInnerWriter.WriteChars(buffer, index, count); TracingWriter?.WriteChars(buffer, index, count); InternalWriter?.WriteChars(buffer, index, count); } /// <summary> /// Writes out a comment containing the specified text. /// </summary> /// <param name="text">Text to place inside the comment.</param> public override void WriteComment(string text) { UseInnerWriter.WriteComment(text); TracingWriter?.WriteComment(text); InternalWriter?.WriteComment(text); } /// <summary> /// Writes the DOCTYPE declaration with the specified name and optional attributes. /// </summary> /// <param name="name">The name of the DOCTYPE. This must be non-empty.</param> /// <param name="pubid">If non-null it also writes PUBLIC "pubid" "sysid" where pubid and sysid are /// replaced with the value of the given arguments.</param> /// <param name="sysid">If pubid is null and sysid is non-null it writes SYSTEM "sysid" where sysid /// is replaced with the value of this argument.</param> /// <param name="subset">If non-null it writes [subset] where subset is replaced with the value of /// this argument.</param> public override void WriteDocType(string name, string pubid, string sysid, string subset) { UseInnerWriter.WriteDocType(name, pubid, sysid, subset); TracingWriter?.WriteDocType(name, pubid, sysid, subset); InternalWriter?.WriteDocType(name, pubid, sysid, subset); } /// <summary> /// Closes the previous System.Xml.XmlWriter.WriteStartAttribute(System.String,System.String) call. /// </summary> public override void WriteEndAttribute() { UseInnerWriter.WriteEndAttribute(); TracingWriter?.WriteEndAttribute(); InternalWriter?.WriteEndAttribute(); } /// <summary> /// Closes any open elements or attributes and puts the writer back in the Start state. /// </summary> public override void WriteEndDocument() { UseInnerWriter.WriteEndDocument(); TracingWriter?.WriteEndDocument(); InternalWriter?.WriteEndDocument(); } /// <summary> /// Closes one element and pops the corresponding namespace scope. /// </summary> public override void WriteEndElement() { UseInnerWriter.WriteEndElement(); TracingWriter?.WriteEndElement(); InternalWriter?.WriteEndElement(); } /// <summary> /// Writes out an entity reference as name. /// </summary> /// <param name="name">The name of the entity reference.</param> public override void WriteEntityRef(string name) { UseInnerWriter.WriteEntityRef(name); TracingWriter?.WriteEntityRef(name); InternalWriter?.WriteEntityRef(name); } /// <summary> /// Closes one element and pops the corresponding namespace scope. /// </summary> public override void WriteFullEndElement() { UseInnerWriter.WriteFullEndElement(); TracingWriter?.WriteFullEndElement(); InternalWriter?.WriteFullEndElement(); } /// <summary> /// Writes out a processing instruction with a space between the name and text as follows: &lt;?name text?>. /// </summary> /// <param name="name">The name of the processing instruction.</param> /// <param name="text">The text to include in the processing instruction.</param> public override void WriteProcessingInstruction(string name, string text) { UseInnerWriter.WriteProcessingInstruction(name, text); TracingWriter?.WriteProcessingInstruction(name, text); InternalWriter?.WriteProcessingInstruction(name, text); } /// <summary> /// When overridden in a derived class, writes raw markup manually from a character buffer. /// </summary> /// <param name="buffer">Character array containing the text to write.</param> /// <param name="index">The position within the buffer indicating the start of the text to write.</param> /// <param name="count">The number of characters to write.</param> public override void WriteRaw(char[] buffer, int index, int count) { UseInnerWriter.WriteRaw(buffer, index, count); TracingWriter?.WriteRaw(buffer, index, count); InternalWriter?.WriteRaw(buffer, index, count); } /// <summary> /// Writes raw markup manually from a string. /// </summary> /// <param name="data">String containing the text to write.</param> public override void WriteRaw(string data) { UseInnerWriter.WriteRaw(data); TracingWriter?.WriteRaw(data); InternalWriter?.WriteRaw(data); } /// <summary> /// Writes the start of an attribute with the specified local name and namespace URI. /// </summary> /// <param name="prefix">The namespace prefix of the attribute.</param> /// <param name="localName">The local name of the attribute.</param> /// <param name="namespace">The namespace URI for the attribute.</param> public override void WriteStartAttribute(string prefix, string localName, string @namespace) { UseInnerWriter.WriteStartAttribute(prefix, localName, @namespace); TracingWriter?.WriteStartAttribute(prefix, localName, @namespace); InternalWriter?.WriteStartAttribute(prefix, localName, @namespace); } /// <summary> /// When overridden in a derived class, writes the XML declaration with the version "1.0". /// </summary> public override void WriteStartDocument() { UseInnerWriter.WriteStartDocument(); TracingWriter?.WriteStartDocument(); InternalWriter?.WriteStartDocument(); } /// <summary> /// When overridden in a derived class, writes the XML declaration with the version /// "1.0" and the standalone attribute. /// </summary> /// <param name="standalone">If true, it writes "standalone=yes"; if false, it writes "standalone=no".</param> public override void WriteStartDocument(bool standalone) { UseInnerWriter.WriteStartDocument(standalone); TracingWriter?.WriteStartDocument(standalone); InternalWriter?.WriteStartDocument(standalone); } /// <summary> /// When overridden in a derived class, writes the specified start tag and associates /// it with the given namespace and prefix. /// </summary> /// <param name="prefix">The namespace prefix of the element.</param> /// <param name="localName">The local name of the element.</param> /// <param name="namespace">The namespace URI to associate with the element.</param> public override void WriteStartElement(string prefix, string localName, string @namespace) { UseInnerWriter.WriteStartElement(prefix, localName, @namespace); TracingWriter?.WriteStartElement(prefix, localName, @namespace); InternalWriter?.WriteStartElement(prefix, localName, @namespace); } /// <summary> /// When overridden in a derived class, gets the state of the writer. /// </summary> public override WriteState WriteState { get { return UseInnerWriter.WriteState; } } /// <summary> /// Writes the given text content. /// </summary> /// <param name="text">The text to write.</param> public override void WriteString(string text) { UseInnerWriter.WriteString(text); TracingWriter?.WriteString(text); InternalWriter?.WriteString(text); } /// <summary> /// Generates and writes the surrogate character entity for the surrogate character pair. /// </summary> /// <param name="lowChar">The low surrogate. This must be a value between 0xDC00 and 0xDFFF.</param> /// <param name="highChar">The high surrogate. This must be a value between 0xD800 and 0xDBFF.</param> public override void WriteSurrogateCharEntity(char lowChar, char highChar) { UseInnerWriter.WriteSurrogateCharEntity(lowChar, highChar); TracingWriter?.WriteSurrogateCharEntity(lowChar, highChar); InternalWriter?.WriteSurrogateCharEntity(lowChar, highChar); } /// <summary> /// Writes out the given white space. /// </summary> /// <param name="ws">The string of white space characters.</param> public override void WriteWhitespace(string ws) { UseInnerWriter.WriteWhitespace(ws); TracingWriter?.WriteWhitespace(ws); InternalWriter?.WriteWhitespace(ws); } /// <summary> /// Writes an attribute as a xml attribute with the prefix 'xml:'. /// </summary> /// <param name="localName">Localname of the attribute.</param> /// <param name="value">Attribute value.</param> public override void WriteXmlAttribute(string localName, string value) { UseInnerWriter.WriteXmlAttribute(localName, value); TracingWriter?.WriteAttributeString(localName, value); InternalWriter?.WriteAttributeString(localName, value); } /// <summary> /// Writes an xmlns namespace declaration. /// </summary> /// <param name="prefix">The prefix of the namespace declaration.</param> /// <param name="namespace">The namespace Uri itself.</param> public override void WriteXmlnsAttribute(string prefix, string @namespace) { UseInnerWriter.WriteXmlnsAttribute(prefix, @namespace); TracingWriter?.WriteAttributeString(prefix, String.Empty, @namespace, String.Empty); InternalWriter?.WriteAttributeString(prefix, String.Empty, @namespace, String.Empty); } /// <summary> /// Returns the closest prefix defined in the current namespace scope for the namespace URI. /// </summary> /// <param name="namespace">The namespace URI whose prefix to find.</param> /// <returns>The matching prefix or null if no matching namespace URI is found in the /// current scope.</returns> public override string LookupPrefix(string @namespace) { return UseInnerWriter.LookupPrefix(@namespace); } /// <summary> /// Gets the <see cref="UseInnerWriter"/> /// </summary> /// <exception cref="InvalidOperationException"> if <see cref="InnerWriter"/> is null.</exception> protected XmlDictionaryWriter UseInnerWriter { get => InnerWriter ?? throw LogExceptionMessage(new InvalidOperationException(LogMessages.IDX30028)); } } }
using System; using DevExpress.ExpressApp.Blazor; using Microsoft.AspNetCore.Components; using Microsoft.Extensions.DependencyInjection; namespace Xenial.FeatureCenter.Module.Blazor { public sealed class HelpAndFeedbackWindowControllerBlazor : HelpAndFeedbackWindowControllerBase { protected override void OpenHelpAndFeedbackLink(string uri) { if (Application is BlazorApplication blazorApplication) { var navigationManager = blazorApplication.ServiceProvider.GetRequiredService<NavigationManager>(); navigationManager.NavigateTo(uri, forceLoad: true); } } } }
namespace Pact.Provider.Wrapper.UrlUtilities { public class NamedRegularExpression { public string Name { get; set; } public string RegEx { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace Turmerik.Core.Reflection { public static partial class ConstantValues { } }
using System; namespace Commitments.Core.Exceptions { public class DomainException: Exception { public int Code { get; set; } = 0; } }
namespace GameCreator.Core { using UnityEngine; using UnityEngine.InputSystem; public class IgniterInputActionReference : Igniter { #if UNITY_EDITOR public new static string NAME = "Input System/Input Action Triggered (Reference)"; public new static string COMMENT = "Check if the referenced Input Action has been triggered (or not). " + "Does not control its enabled state."; #endif public InputActionReference actionRef; public bool negate; public PlayerInput playerInput; private void Update() { bool inputTriggered = negate; if (playerInput != null) { InputAction activeAction = playerInput.currentActionMap.FindAction(actionRef.action.id); if (activeAction != null) { inputTriggered = activeAction.triggered; } } else { inputTriggered = actionRef.action.triggered; } if (negate ^ inputTriggered) { this.ExecuteTrigger(gameObject); } } } }
using System; using System.Collections.Generic; using System.Text; namespace UEditor.Core { internal class AppConsts { internal class Action { public const string Config = "config"; public const string UploadImage = "uploadimage"; public const string UploadScrawl = "uploadscrawl"; public const string UploadVideo = "uploadvideo"; public const string UploadFile = "uploadfile"; public const string ListImage = "listimage"; public const string ListFile = "listfile"; public const string CatchImage = "catchimage"; } } }
namespace Cubizer.Chunk { public delegate void OnChangeDelegate(); public delegate void OnDestroyDelegate(); public delegate void OnUpdate(); }
using System; using BinaryTree; namespace _10._06_FindRootToLeafWithSpecifiedSum { class Program { static void Main(string[] args) { TreeNode root = new TreeNode(314); root.Left = new TreeNode(6); root.Left.Left = new TreeNode(271); root.Left.Left.Left = new TreeNode(28); root.Left.Left.Right = new TreeNode(0); root.Left.Right = new TreeNode(561); root.Left.Right.Right = new TreeNode(3); root.Left.Right.Right.Left = new TreeNode(17); root.Right = new TreeNode(6); root.Right.Left = new TreeNode(2); root.Right.Left.Right = new TreeNode(1); root.Right.Left.Right.Left = new TreeNode(401); root.Right.Left.Right.Left.Right = new TreeNode(641); root.Right.Left.Right.Right = new TreeNode(257); root.Right.Right = new TreeNode(271); root.Right.Right.Right = new TreeNode(28); bool hasPathSum = HasPathSum(root, 591); Console.WriteLine(hasPathSum); } static bool HasPathSum(TreeNode node, int target) { return HasPathSum(node, 0, target); } static bool HasPathSum(TreeNode node, int partialSum, int target) { if (node == null) { return false; } partialSum += node.Value; if (node.Left == null && node.Right == null) { return partialSum == target; } return HasPathSum(node.Left, partialSum, target) || HasPathSum(node.Right, partialSum, target); } } }
using System.Collections; using System.Collections.Generic; [System.Serializable] public class WorldData { public Dictionary<WorldPos, ChunkData> chunks = new Dictionary<WorldPos, ChunkData>(); }
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- #pragma warning disable 618 namespace System.Activities.Presentation { using System.Activities.Presentation.Internal.PropertyEditing; using System.Activities.Presentation.Model; using System.Activities.Presentation.Services; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Runtime; using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Threading; using System.Activities.Presentation.View; using System.Windows.Shapes; // This is similar to the WorkflowItemPresenter , but its an edit box for collections. It supports drag drop, and delete. // it auto refreshes the collection on collection changed events. public class WorkflowItemsPresenter : ContentControl, IMultipleDragEnabledCompositeView { public static readonly DependencyProperty HintTextProperty = DependencyProperty.Register("HintText", typeof(string), typeof(WorkflowItemsPresenter), new UIPropertyMetadata(String.Empty, new PropertyChangedCallback(WorkflowItemsPresenter.OnHintTextChanged))); public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register("Items", typeof(ModelItemCollection), typeof(WorkflowItemsPresenter), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(WorkflowItemsPresenter.OnItemsChanged))); public static readonly DependencyProperty SpacerTemplateProperty = DependencyProperty.Register("SpacerTemplate", typeof(DataTemplate), typeof(WorkflowItemsPresenter), new UIPropertyMetadata(null)); public static readonly DependencyProperty HeaderTemplateProperty = DependencyProperty.Register("HeaderTemplate", typeof(DataTemplate), typeof(WorkflowItemsPresenter), new UIPropertyMetadata(null)); public static readonly DependencyProperty FooterTemplateProperty = DependencyProperty.Register("FooterTemplate", typeof(DataTemplate), typeof(WorkflowItemsPresenter), new UIPropertyMetadata(null)); public static readonly DependencyProperty ItemsPanelProperty = DependencyProperty.Register("ItemsPanel", typeof(ItemsPanelTemplate), typeof(WorkflowItemsPresenter), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(WorkflowItemsPresenter.OnItemsPanelChanged))); public static readonly DependencyProperty IndexProperty = DependencyProperty.RegisterAttached("Index", typeof(int), typeof(WorkflowItemsPresenter), new UIPropertyMetadata(addAtEndMarker)); public static readonly DependencyProperty AllowedItemTypeProperty = DependencyProperty.Register("AllowedItemType", typeof(Type), typeof(WorkflowItemsPresenter), new UIPropertyMetadata(typeof(object))); public static readonly DependencyProperty IsDefaultContainerProperty = DependencyProperty.Register("IsDefaultContainer", typeof(bool), typeof(WorkflowItemsPresenter), new UIPropertyMetadata(false)); public static readonly DependencyProperty DroppingTypeResolvingOptionsProperty = DependencyProperty.Register("DroppingTypeResolvingOptions", typeof(TypeResolvingOptions), typeof(WorkflowItemsPresenter)); const int addAtEndMarker = -2; int selectedSpacerIndex; ItemsControl panel; Grid hintTextGrid; EditingContext context = null; bool isRegisteredWithParent = false; bool populateOnLoad = false; bool handleSpacerGotKeyboardFocus = false; Grid outerGrid; public WorkflowItemsPresenter() { panel = new ItemsControl(); panel.Focusable = false; hintTextGrid = new Grid(); hintTextGrid.Focusable = false; hintTextGrid.Background = Brushes.Transparent; hintTextGrid.DataContext = this; hintTextGrid.SetBinding(Grid.MinHeightProperty, "MinHeight"); hintTextGrid.SetBinding(Grid.MinWidthProperty, "MinWidth"); TextBlock text = new TextBlock(); text.Focusable = false; text.SetBinding(TextBlock.TextProperty, "HintText"); text.HorizontalAlignment = HorizontalAlignment.Center; text.VerticalAlignment = VerticalAlignment.Center; text.DataContext = this; text.Foreground = new SolidColorBrush(SystemColors.GrayTextColor); text.FontStyle = FontStyles.Italic; ((IAddChild)hintTextGrid).AddChild(text); this.outerGrid = new Grid() { RowDefinitions = { new RowDefinition(), new RowDefinition() }, ColumnDefinitions = { new ColumnDefinition() } }; Grid.SetRow(this.panel, 0); Grid.SetColumn(this.panel, 0); Grid.SetRow(this.hintTextGrid, 1); Grid.SetColumn(this.hintTextGrid, 0); this.outerGrid.Children.Add(panel); this.outerGrid.Children.Add(hintTextGrid); } public Type AllowedItemType { get { return (Type)GetValue(AllowedItemTypeProperty); } set { SetValue(AllowedItemTypeProperty, value); } } public string HintText { get { return (string)GetValue(HintTextProperty); } set { SetValue(HintTextProperty, value); } } [Fx.Tag.KnownXamlExternal] public DataTemplate SpacerTemplate { get { return (DataTemplate)GetValue(SpacerTemplateProperty); } set { SetValue(SpacerTemplateProperty, value); } } [Fx.Tag.KnownXamlExternal] public DataTemplate HeaderTemplate { get { return (DataTemplate)GetValue(HeaderTemplateProperty); } set { SetValue(HeaderTemplateProperty, value); } } [Fx.Tag.KnownXamlExternal] public DataTemplate FooterTemplate { get { return (DataTemplate)GetValue(FooterTemplateProperty); } set { SetValue(FooterTemplateProperty, value); } } [Fx.Tag.KnownXamlExternal] public ItemsPanelTemplate ItemsPanel { get { return (ItemsPanelTemplate)GetValue(ItemsPanelProperty); } set { SetValue(ItemsPanelProperty, value); } } [SuppressMessage(FxCop.Category.Usage, FxCop.Rule.CollectionPropertiesShouldBeReadOnly, Justification = "Setter is provided to enable setting this property in code.")] [Fx.Tag.KnownXamlExternal] public ModelItemCollection Items { get { return (ModelItemCollection)GetValue(ItemsProperty); } set { SetValue(ItemsProperty, value); } } EditingContext Context { get { if (context == null) { IModelTreeItem modelTreeItem = this.Items as IModelTreeItem; if (modelTreeItem != null) { this.context = modelTreeItem.ModelTreeManager.Context; } } return context; } } public bool IsDefaultContainer { get { return (bool)GetValue(IsDefaultContainerProperty); } set { SetValue(IsDefaultContainerProperty, value); } } [Fx.Tag.KnownXamlExternal] public TypeResolvingOptions DroppingTypeResolvingOptions { get { return (TypeResolvingOptions)GetValue(DroppingTypeResolvingOptionsProperty); } set { SetValue(DroppingTypeResolvingOptionsProperty, value); } } static void OnHintTextChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { WorkflowItemsPresenter itemsPresenter = (WorkflowItemsPresenter)dependencyObject; itemsPresenter.UpdateHintTextVisibility(e.NewValue as string); } static void OnItemsChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { WorkflowItemsPresenter itemsPresenter = (WorkflowItemsPresenter)dependencyObject; itemsPresenter.OnItemsChanged((ModelItemCollection)e.OldValue, (ModelItemCollection)e.NewValue); } static void OnItemsPanelChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { WorkflowItemsPresenter itemsPresenter = (WorkflowItemsPresenter)dependencyObject; itemsPresenter.panel.ItemsPanel = (ItemsPanelTemplate)e.NewValue; } void OnItemsChanged(ModelItemCollection oldItemsCollection, ModelItemCollection newItemsCollection) { if (oldItemsCollection != null) { oldItemsCollection.CollectionChanged -= this.OnCollectionChanged; } if (newItemsCollection != null) { newItemsCollection.CollectionChanged += this.OnCollectionChanged; } if (!isRegisteredWithParent) { CutCopyPasteHelper.RegisterWithParentViewElement(this); isRegisteredWithParent = true; } populateOnLoad = false; PopulateContent(); } void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { // if this.Items is null, and we are getting a collection changed that // means this event some how happened before this can get the unloaded event // and unsubscribe from this event. if (this.Items == null) { return; } bool fullRepopulateNeeded = true; // when one item is dropped into this items presenter focus on the new view element for it. if (e.Action == NotifyCollectionChangedAction.Add && e.NewItems != null && e.NewItems.Count == 1) { // insert itemview and spacer fullRepopulateNeeded = false; int itemViewIndex = GetViewIndexForItem(e.NewStartingIndex); VirtualizedContainerService containerService = this.Context.Services.GetService<VirtualizedContainerService>(); UIElement itemView = containerService.GetContainer((ModelItem)e.NewItems[0], this); this.panel.Items.Insert(itemViewIndex, itemView as UIElement); // index 2 + i*2 + 1 is spacer i+1 FrameworkElement spacer = CreateSpacer(); this.panel.Items.Insert(itemViewIndex + 1, spacer); ModelItem insertedItem = (ModelItem)e.NewItems[0]; this.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, (Action)(() => { UIElement view = (UIElement)insertedItem.View; if (view != null) { Keyboard.Focus(view); } })); } else if (e.Action == NotifyCollectionChangedAction.Remove) { if (e.OldItems != null && e.OldItems.Count == 1) { fullRepopulateNeeded = false; int itemViewIndex = GetViewIndexForItem(e.OldStartingIndex); this.panel.Items.RemoveAt(itemViewIndex); //remove spacer also this.panel.Items.RemoveAt(itemViewIndex); } if (this.Items.Count == 0) { fullRepopulateNeeded = true; } // deselect removed items if (this.Context != null) { IList<ModelItem> selectedItems = this.Context.Items.GetValue<Selection>().SelectedObjects.ToList(); foreach (ModelItem selectedAndRemovedItem in selectedItems.Intersect(e.OldItems.Cast<ModelItem>())) { Selection.Toggle(this.Context, selectedAndRemovedItem); } } } if (this.Items.Count > 0) { this.hintTextGrid.Visibility = Visibility.Collapsed; } else { this.hintTextGrid.Visibility = Visibility.Visible; } if (fullRepopulateNeeded) { PopulateContent(); } } protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); this.AllowDrop = true; this.Content = outerGrid; if (this.ItemsPanel != null) { this.panel.ItemsPanel = this.ItemsPanel; } ICompositeViewEvents containerEvents = null; bool isDefault = false; this.Loaded += (s, eventArgs) => { isDefault = this.IsDefaultContainer; selectedSpacerIndex = addAtEndMarker; DependencyObject parent = VisualTreeHelper.GetParent(this); while (null != parent && !typeof(ICompositeViewEvents).IsAssignableFrom(parent.GetType())) { parent = VisualTreeHelper.GetParent(parent); } containerEvents = parent as ICompositeViewEvents; if (null != containerEvents) { if (isDefault) { containerEvents.RegisterDefaultCompositeView(this); } else { containerEvents.RegisterCompositeView(this); } } if (this.Items != null) { //UnRegistering because of 137896: Inside tab control multiple Loaded events happen without an Unloaded event. this.Items.CollectionChanged -= new NotifyCollectionChangedEventHandler(OnCollectionChanged); this.Items.CollectionChanged += new NotifyCollectionChangedEventHandler(OnCollectionChanged); } if (populateOnLoad) { this.PopulateContent(); } }; this.Unloaded += (s, eventArgs) => { if (null != containerEvents) { if (isDefault) { containerEvents.UnregisterDefaultCompositeView(this); } else { containerEvents.UnregisterCompositeView(this); } } if (this.Items != null) { this.Items.CollectionChanged -= new NotifyCollectionChangedEventHandler(OnCollectionChanged); } populateOnLoad = true; }; } void PopulateContent() { this.panel.Items.Clear(); if (this.Items != null) { // index 0 is header. ContentControl header = new ContentControl(); header.Focusable = false; header.ContentTemplate = this.HeaderTemplate; header.SetValue(IndexProperty, 0); header.Drop += new DragEventHandler(OnSpacerDrop); this.panel.Items.Add(header); // index 1 is first spacer FrameworkElement startSpacer = CreateSpacer(); this.panel.Items.Add(startSpacer); foreach (ModelItem item in this.Items) { // index 2 + i*2 is itemView i VirtualizedContainerService containerService = this.Context.Services.GetService<VirtualizedContainerService>(); UIElement itemView = containerService.GetContainer(item, this); this.panel.Items.Add(itemView as UIElement); // index 2 + i*2 + 1 is spacer i+1 FrameworkElement spacer = CreateSpacer(); this.panel.Items.Add(spacer); } // index 2 + count*2 is footer ContentControl footer = new ContentControl(); footer.ContentTemplate = this.FooterTemplate; footer.Focusable = true; footer.IsHitTestVisible = true; footer.IsTabStop = true; footer.SetValue(IndexProperty, addAtEndMarker); footer.Drop += new DragEventHandler(OnSpacerDrop); footer.LostFocus += new RoutedEventHandler(OnSpacerLostFocus); footer.GotFocus += new RoutedEventHandler(OnSpacerGotFocus); this.panel.Items.Add(footer); footer.Focusable = false; } UpdateHintTextVisibility(HintText); } int GetViewIndexForItem(int itemIndex) { return 2 + itemIndex * 2; } int GetViewIndexForSpacer(int spacerIndex) { return 2 + spacerIndex * 2 + 1; } int GetSpacerIndex(int viewIndex) { if (viewIndex == 1) { return 0; } else { return (viewIndex - 3) / 2 + 1; } } void UpdateHintTextVisibility(string hintText) { if (this.hintTextGrid != null && this.Items != null) { this.hintTextGrid.Visibility = (this.Items.Count == 0 && !string.IsNullOrEmpty(hintText)) ? Visibility.Visible : Visibility.Collapsed; } } private IList<object> GetOrderMetaData(List<ModelItem> items) { List<ModelItem> sortedList = this.SortSelectedItems(new List<ModelItem>(items)); this.CheckListConsistentAndThrow(items, sortedList); return sortedList.Select((m) => m.GetCurrentValue()).ToList(); } private FrameworkElement CreateSpacer() { FrameworkElement spacer = (this.SpacerTemplate != null) ? (FrameworkElement)this.SpacerTemplate.LoadContent() : new Rectangle(); spacer.IsHitTestVisible = true; Control spacerControl = spacer as Control; if (spacerControl != null) { spacerControl.IsTabStop = true; } spacer.Drop += new DragEventHandler(OnSpacerDrop); spacer.LostFocus += new RoutedEventHandler(OnSpacerLostFocus); spacer.GotFocus += new RoutedEventHandler(OnSpacerGotFocus); spacer.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(OnSpacerGotKeyboardFocus); spacer.MouseDown += new MouseButtonEventHandler(OnSpacerMouseDown); return spacer; } void OnSpacerDrop(object sender, DragEventArgs e) { int index = GetSpacerIndexFromView(sender); OnItemsDropped(e, index); } private int GetSpacerIndexFromView(object sender) { if (((DependencyObject)sender).ReadLocalValue(IndexProperty) != DependencyProperty.UnsetValue) { int index = (int)((DependencyObject)sender).GetValue(IndexProperty); return index; } else { return GetSpacerIndex(this.panel.Items.IndexOf(sender)); } } void OnSpacerGotFocus(object sender, RoutedEventArgs e) { int index = GetSpacerIndexFromView(sender); selectedSpacerIndex = index; } void OnSpacerGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { // Handle the event so that it won't be routed to the containing designer to affect selection if (handleSpacerGotKeyboardFocus) { e.Handled = true; } } void OnSpacerLostFocus(object sender, RoutedEventArgs e) { int index = GetSpacerIndexFromView(sender); selectedSpacerIndex = addAtEndMarker; } void OnSpacerMouseDown(object sender, MouseButtonEventArgs e) { // do not move focus if it's a ctrl right click. if (e.RightButton == MouseButtonState.Pressed) { if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) { return; } } // Schedule the Keyboard.Focus command to let it execute later than WorkflowViewElement.OnMouseDown this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { this.handleSpacerGotKeyboardFocus = true; Keyboard.Focus((FrameworkElement)sender); this.handleSpacerGotKeyboardFocus = false; })); } private bool ShouldMoveItems(List<ModelItem> sortedModelItems, int index) { if (sortedModelItems.Count == 0) { return false; } // Should move if the items are not next to each other if (!AreItemsConsecutive(sortedModelItems)) { return true; } // Should not move if the new position is just before the first item or just after the last item or between them. return index < this.Items.IndexOf(sortedModelItems[0]) || index > this.Items.IndexOf(sortedModelItems.Last()) + 1; } private bool AreItemsConsecutive(List<ModelItem> sortedModelItems) { Fx.Assert(sortedModelItems.Count > 0, "Should have at least one item."); int oldIndex = this.Items.IndexOf(sortedModelItems[0]); foreach (ModelItem item in sortedModelItems) { if (oldIndex != this.Items.IndexOf(item)) { return false; } oldIndex++; } return true; } public List<ModelItem> SortSelectedItems(List<ModelItem> selectedItems) { if (selectedItems == null) { throw FxTrace.Exception.ArgumentNull("selectedItems"); } if (selectedItems.Count < 2) { return selectedItems; } List<ModelItem> list = new List<ModelItem>(); // If the performance here is bad, we can use HashSet for selectedItems // to improve foreach (ModelItem item in this.Items) { int index = selectedItems.IndexOf(item); if (index >= 0) { // use the reference in selectedItems. list.Add(selectedItems[index]); } } // in case passing some items that are not in // my container. if (list.Count != selectedItems.Count) { // throw FxTrace.Exception. throw FxTrace.Exception.AsError(new ArgumentException(SR.Error_CantFindItemInWIsP)); } return list; } public void OnItemsMoved(List<ModelItem> movedItems) { if (movedItems == null) { throw FxTrace.Exception.ArgumentNull("movedItems"); } DragDropHelper.ValidateItemsAreOnView(movedItems, this.Items); this.OnItemsDelete(movedItems); } void OnItemsDropped(DragEventArgs e, int index) { ModelItemHelper.TryCreateImmediateEditingScopeAndExecute(this.Items.GetEditingContext(), System.Activities.Presentation.SR.CollectionAddEditingScopeDescription, (es) => { DragDropHelper.SetDragDropCompletedEffects(e, DragDropEffects.None); List<object> droppedObjects = new List<object>(DragDropHelper.GetDroppedObjects(this, e, Context)); List<WorkflowViewElement> movedViewElements = new List<WorkflowViewElement>(); List<object> externalMoveList = new List<object>(); List<ModelItem> internalMoveList = new List<ModelItem>(); // Step 1: Sort the list List<object> sortedDroppingList = DragDropHelper.SortSelectedObjects(droppedObjects); // Step 2: Categorize dropped objects by their source container. foreach (object droppedObject in sortedDroppingList) { ModelItem modelItem = droppedObject as ModelItem; WorkflowViewElement view = (modelItem == null) ? null : (modelItem.View as WorkflowViewElement); if (view == null) { externalMoveList.Add(droppedObject); continue; } UIElement container = DragDropHelper.GetCompositeView(view); if (container == this) { internalMoveList.Add(modelItem); continue; } movedViewElements.Add(view); externalMoveList.Add(droppedObject); } // Step 3: Internal movement if (this.ShouldMoveItems(internalMoveList, index)) { foreach (ModelItem modelItem in internalMoveList) { int oldIndex = this.Items.IndexOf(modelItem); this.Items.Remove(modelItem); //if element is placed ahead of old location, decrement the index not to include moved object if (oldIndex < index) { this.InsertItem(index - 1, modelItem); } else { this.InsertItem(index, modelItem); index++; } } } // Step 4: External move and drop from toolbox foreach (object droppedObject in externalMoveList) { if (!this.IsDropAllowed(droppedObject)) { continue; } this.InsertItem(index++, droppedObject); DragDropHelper.SetDragDropCompletedEffects(e, DragDropEffects.Move); } DragDropHelper.SetDragDropMovedViewElements(e, movedViewElements); e.Handled = true; if (es != null) { es.Complete(); } }); } private void CheckListConsistentAndThrow(List<ModelItem> src, List<ModelItem> copied) { bool valid = DragDropHelper.AreListsIdenticalExceptOrder(src, copied); if (!valid) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Error_BadOutputFromSortSelectedItems)); } } private bool IsDropAllowed(object droppedObject) { bool isDropAllowed = false; ModelItem modelItem = droppedObject as ModelItem; if (modelItem != null && !IsInParentChain(modelItem)) { if (this.AllowedItemType.IsAssignableFrom(modelItem.ItemType)) { isDropAllowed = true; } } else if (droppedObject is Type && this.AllowedItemType.IsAssignableFrom((Type)droppedObject)) { isDropAllowed = true; } else { if (this.AllowedItemType.IsAssignableFrom(droppedObject.GetType())) { isDropAllowed = true; } } return isDropAllowed; } private bool IsInParentChain(ModelItem droppedModelItem) { bool isInParentChain = false; ModelItem parentModelItem = this.Items; while (parentModelItem != null) { if (parentModelItem == droppedModelItem) { isInParentChain = true; break; } parentModelItem = parentModelItem.Parent; } return isInParentChain; } void InsertItem(int index, object droppedObject) { ModelItem insertedItem = null; if (index == addAtEndMarker) { insertedItem = this.Items.Add(droppedObject); } else { insertedItem = this.Items.Insert(index, droppedObject); } if (insertedItem != null) { Selection.SelectOnly(this.Context, insertedItem); } } protected override void OnDrop(DragEventArgs e) { int index = addAtEndMarker; WorkflowViewElement dropTarget = null; if (e.OriginalSource is WorkflowViewElement) { dropTarget = (WorkflowViewElement)e.OriginalSource; } else { dropTarget = VisualTreeUtils.FindFocusableParent<WorkflowViewElement>((UIElement)e.OriginalSource); } if (null != dropTarget && null != dropTarget.ModelItem) { int targetIndex = this.Items.IndexOf(dropTarget.ModelItem); if (-1 != targetIndex) { index = targetIndex + 1; } } OnItemsDropped(e, index); base.OnDrop(e); } void OnDrag(DragEventArgs e) { if (!e.Handled) { if (!DragDropHelper.AllowDrop(e.Data, this.Context, this.AllowedItemType)) { e.Effects = DragDropEffects.None; } e.Handled = true; } } protected override void OnDragEnter(DragEventArgs e) { this.OnDrag(e); base.OnDragEnter(e); } protected override void OnDragOver(DragEventArgs e) { this.OnDrag(e); base.OnDragOver(e); } public void OnItemMoved(ModelItem modelItem) { if (this.Items.Contains(modelItem)) { this.Items.Remove(modelItem); } } protected override AutomationPeer OnCreateAutomationPeer() { return new WorkflowItemsPresenterAutomationPeer(this); } public object OnItemsCut(List<ModelItem> itemsToCut) { List<object> orderMetaData = GetOrderMetaData(itemsToCut).ToList(); foreach (ModelItem item in itemsToCut) { this.Items.Remove(item); this.Context.Items.SetValue(new Selection(new ArrayList())); } return orderMetaData; } public object OnItemsCopied(List<ModelItem> itemsToCopy) { return this.GetOrderMetaData(itemsToCopy); } public void OnItemsPasted(List<object> itemsToPaste, List<object> metaData, Point pastePoint, WorkflowViewElement pastePointReference) { // first see if a spacer is selected. int index = this.selectedSpacerIndex; // else see if we can paste after a selected child if (index < 0) { Selection currentSelection = this.Context.Items.GetValue<Selection>(); index = this.Items.IndexOf(currentSelection.PrimarySelection); //paste after the selected child if (index >= 0) { index++; } } if (index < 0) { index = addAtEndMarker; } IList<object> mergedItemsToPaste = CutCopyPasteHelper.SortFromMetaData(itemsToPaste, metaData); List<ModelItem> modelItemsToSelect = new List<ModelItem>(); foreach (object itemToPaste in mergedItemsToPaste) { if (IsDropAllowed(itemToPaste)) { if (index == addAtEndMarker) { modelItemsToSelect.Add(this.Items.Add(itemToPaste)); } else { modelItemsToSelect.Add(this.Items.Insert(index, itemToPaste)); } if (index >= 0) { index++; } } } this.Dispatcher.BeginInvoke( new Action(() => { this.Context.Items.SetValue(new Selection(modelItemsToSelect)); }), Windows.Threading.DispatcherPriority.ApplicationIdle, null); } public void OnItemsDelete(List<ModelItem> itemsToDelete) { if (null != itemsToDelete) { itemsToDelete.ForEach(p => { if (null != this.Items && this.Items.Contains(p)) { this.Items.Remove(p); } } ); } } public bool CanPasteItems(List<object> itemsToPaste) { bool result = false; if (null != itemsToPaste && itemsToPaste.Count > 0) { result = itemsToPaste.All(p => this.IsDropAllowed(p)); } return result; } class WorkflowItemsPresenterAutomationPeer : UIElementAutomationPeer { WorkflowItemsPresenter owner; public WorkflowItemsPresenterAutomationPeer(WorkflowItemsPresenter owner) : base(owner) { this.owner = owner; } protected override AutomationControlType GetAutomationControlTypeCore() { return AutomationControlType.Custom; } protected override string GetAutomationIdCore() { string automationId = base.GetAutomationIdCore(); if (string.IsNullOrEmpty(automationId)) { automationId = base.GetNameCore(); if (string.IsNullOrEmpty(automationId)) { automationId = this.owner.GetType().Name; } } return automationId; } protected override string GetNameCore() { // Return an empty string if some activites are dropped on the presenter if (owner.Items.Count > 0) { return string.Empty; } string name = base.GetNameCore(); if (string.IsNullOrEmpty(name)) { name = this.owner.HintText; } return name; } protected override string GetClassNameCore() { return this.owner.GetType().Name; } } } }
#if !NET40 // ReSharper disable once CheckNamespace namespace System.Threading.Tasks { public static partial class TasksLikePromisesExtensions { public static async Task<TResult> Then<T, TResult>(this Task<T> task, Func<T, Task<TResult>> onFulfilled) { task.NotNull(nameof(task)); onFulfilled.NotNull(nameof(onFulfilled)); var t = await task.ConfigureAwait(false); return await onFulfilled(t).ConfigureAwait(false); } public static async Task<TResult> Then<T, TResult>(this Task<T> task, Func<T, TResult> onFulfilled) { task.NotNull(nameof(task)); onFulfilled.NotNull(nameof(onFulfilled)); var t = await task.ConfigureAwait(false); return onFulfilled(t); } public static async Task Then<T>(this Task<T> task, Func<T, Task> onFulfilled) { task.NotNull(nameof(task)); onFulfilled.NotNull(nameof(onFulfilled)); var t = await task.ConfigureAwait(false); await onFulfilled(t).ConfigureAwait(false); } public static async Task Then<T>(this Task<T> task, Action<T> onFulfilled) { task.NotNull(nameof(task)); onFulfilled.NotNull(nameof(onFulfilled)); var t = await task.ConfigureAwait(false); onFulfilled(t); } public static async Task<TResult> Then<TResult>(this Task task, Func<Task<TResult>> onFulfilled) { task.NotNull(nameof(task)); onFulfilled.NotNull(nameof(onFulfilled)); await task.ConfigureAwait(false); return await onFulfilled().ConfigureAwait(false); } public static async Task<TResult> Then<TResult>(this Task task, Func<TResult> onFulfilled) { task.NotNull(nameof(task)); onFulfilled.NotNull(nameof(onFulfilled)); await task.ConfigureAwait(false); return onFulfilled(); } public static async Task Then(this Task task, Func<Task> onFulfilled) { task.NotNull(nameof(task)); onFulfilled.NotNull(nameof(onFulfilled)); await task.ConfigureAwait(false); await onFulfilled().ConfigureAwait(false); } public static async Task Then(this Task task, Action onFulfilled) { task.NotNull(nameof(task)); onFulfilled.NotNull(nameof(onFulfilled)); await task.ConfigureAwait(false); onFulfilled(); } } } #endif
using Sandbox; namespace SandboxRealism { internal class RealismThirdPersonCamera : ThirdPersonCamera { public RealismThirdPersonCamera() { this.ZNear = 5.0f; } } }
using System; using System.Collections.Generic; using System.Text; namespace Abyss.Core.Parsers { public class DiscoverableTypeParserAttribute : Attribute { public bool ReplacingPrimitive { get; } public DiscoverableTypeParserAttribute(bool replacingPrimitive = false) { ReplacingPrimitive = replacingPrimitive; } } }
using System; using System.Collections.Generic; using System.Globalization; using CompropagoSdk.Factory.Models; using CompropagoSdk.Tools; namespace CompropagoSdk { public class Service { private readonly Client _client; /// <summary> /// Initializes a new instance of the <see cref="T:CompropagoSdk.Service"/> class. /// </summary> /// <param name="client">Client.</param> /// <remarks> /// Author: Eduardo Aguilar <dante.aguilar41@gmail.com>. /// </remarks> public Service(Client client) { _client = client; } /// <summary> /// Gets the auth. /// </summary> /// <returns>The auth Dictionary.</returns> /// /// <remarks> /// Author: Eduardo Aguilar <dante.aguilar41@gmail.com>. /// </remarks> private Dictionary<string, string> getAuth() { return new Dictionary<string, string> { { "user", _client.GetUser() }, { "pass", _client.GetPass() } }; } /// <summary> /// Lists the providers available for the account. /// </summary> /// <returns>The providers.</returns> /// <param name="limit">Limit.</param> /// <param name="currency">Currency.</param> /// /// <remarks> /// Author: Eduardo Aguilar <dante.aguilar41@gmail.com>. /// </remarks> public Provider[] ListProviders(double limit = 0, string currency = "MXN") { string url = _client.DeployUri + "providers/"; if (limit > 0) { url += "?order_total=" + limit; } if (limit > 0 && currency != "" && currency != "MXN") { url += "&currency=" + currency; } Console.WriteLine(url); var response = Request.Get(url, getAuth()); return Factory.Factory.ListProviders(response); } /// <summary> /// Verifies the order. /// </summary> /// <returns>The order.</returns> /// <param name="orderId">Order identifier.</param> /// /// <remarks> /// Author: Eduardo Aguilar <dante.aguilar41@gmail.com>. /// </remarks> public CpOrderInfo VerifyOrder(string orderId) { var response = Request.Get(_client.DeployUri + "charges/" + orderId + "/", getAuth()); return Factory.Factory.CpOrderInfo(response); } /// <summary> /// Places the order. /// </summary> /// <returns>The order.</returns> /// <param name="order">Order.</param> /// /// <remarks> /// Author: Eduardo Aguilar <dante.aguilar41@gmail.com>. /// </remarks> public NewOrderInfo PlaceOrder(PlaceOrderInfo order) { var data = new Dictionary<string, object> { {"order_id", order.order_id}, {"order_name", order.order_name}, {"order_price", order.order_price.ToString(CultureInfo.InvariantCulture)}, {"customer_name", order.customer_name}, {"customer_email", order.customer_email}, {"payment_type", order.payment_type}, {"currency", order.currency}, {"expiration_time", order.expiration_time}, {"image_url", order.image_url}, {"app_client_name", order.app_client_name}, {"app_client_version", order.app_client_version} }; var response = Request.Post(_client.DeployUri +"charges/", data, getAuth()); return Factory.Factory.NewOrderInfo(response); } /// <summary> /// Sends the sms instructions. /// </summary> /// <returns>The sms instructions.</returns> /// <param name="phone">Phone.</param> /// <param name="orderId">Order identifier.</param> /// /// <remarks> /// Author: Eduardo Aguilar <dante.aguilar41@gmail.com>. /// </remarks> public SmsInfo SendSmsInstructions(string phone, string orderId) { var data = new Dictionary<string,object> { {"customer_phone", phone} }; var response = Request.Post(_client.DeployUri + "charges/" + orderId + "/sms/", data, getAuth()); return Factory.Factory.SmsInfo(response); } /// <summary> /// Lists the webhooks. /// </summary> /// <returns>The webhooks.</returns> /// /// <remarks> /// Author: Eduardo Aguilar <dante.aguilar41@gmail.com>. /// </remarks> public Webhook[] ListWebhooks() { var response = Request.Get(_client.DeployUri + "webhooks/stores/", getAuth()); return Factory.Factory.ListWebhooks(response); } /// <summary> /// Creates the webhook. /// </summary> /// <returns>The webhook.</returns> /// <param name="url">URL.</param> /// /// <remarks> /// Author: Eduardo Aguilar <dante.aguilar41@gmail.com>. /// </remarks> public Webhook CreateWebhook(string url) { var data = new Dictionary<string, object> { {"url", url} }; var response = Request.Post(_client.DeployUri + "webhooks/stores/", data, getAuth()); return Factory.Factory.Webhook(response); } /// <summary> /// Updates the webhook. /// </summary> /// <returns>The webhook.</returns> /// <param name="webhookId">Webhook identifier.</param> /// <param name="url">URL.</param> /// /// <remarks> /// Author: Eduardo Aguilar <dante.aguilar41@gmail.com>. /// </remarks> public Webhook UpdateWebhook(string webhookId, string url) { var data = new Dictionary<string, object> { {"url", url} }; var response = Request.Put(_client.DeployUri + "webhooks/stores/" + webhookId + "/", data, getAuth()); return Factory.Factory.Webhook(response); } public Webhook DeleteWebhook(string webhookId) { var response = Request.Delete(_client.DeployUri + "webhooks/stores/" + webhookId + "/", null, getAuth()); return Factory.Factory.Webhook(response); } } }
using Newtonsoft.Json; using System; namespace provide.Model.NChain { public class TokenContract: BaseModel { [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public Guid? NetworkId { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public Guid? ContractId { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public Guid? ApplicationId { get; set; } public string Name { get; set; } public string Symbol { get; set; } public string Address { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string AccessedAt { get; set; } public int Decimals { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string SaleAddress { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public Guid? SaleContractId { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; namespace Json.Schema.Generation.Tests { public class PropertyOrderTests { private class SpecifiedOrder { public int Second { get; set; } public int First { get; set; } } [Test] public void PropertiesAsDeclared() { var config = new SchemaGeneratorConfiguration { PropertyOrder = PropertyOrder.AsDeclared }; JsonSchema schema = new JsonSchemaBuilder() .FromType<SpecifiedOrder>(config); var properties = schema.Keywords.OfType<PropertiesKeyword>().Single(); Assert.AreEqual(nameof(SpecifiedOrder.Second), properties.Properties.Keys.First()); Assert.AreEqual(nameof(SpecifiedOrder.First), properties.Properties.Keys.Last()); } [Test] public void PropertiesByName() { var config = new SchemaGeneratorConfiguration { PropertyOrder = PropertyOrder.ByName }; JsonSchema schema = new JsonSchemaBuilder() .FromType<SpecifiedOrder>(config); var properties = schema.Keywords.OfType<PropertiesKeyword>().Single(); Assert.AreEqual(nameof(SpecifiedOrder.First), properties.Properties.Keys.First()); Assert.AreEqual(nameof(SpecifiedOrder.Second), properties.Properties.Keys.Last()); } } }
using System.Reflection.Emit; static class ConstructorDelegateBuilder { public static Func<object> BuildConstructorFunc(Type type) { var constructor = type.GetConstructor(Type.EmptyTypes); if (constructor == null) { throw new($"There is no empty constructor: {type.FullName}"); } var dynamic = new DynamicMethod(string.Empty, type, Type.EmptyTypes, type); var il = dynamic.GetILGenerator(); il.DeclareLocal(type); il.Emit(OpCodes.Newobj, constructor); il.Emit(OpCodes.Stloc_0); il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Ret); return (Func<object>)dynamic.CreateDelegate(typeof(Func<object>)); } }
using System; using System.Numerics; using System.Threading; namespace Benchmark.Engine; internal sealed class Visualiser { private const int Opaque = 0xFF << 24; private readonly Rasteriser _rasteriser; private Model _model; private double _angle; private bool _loaded; public Visualiser(int width, int height) => _rasteriser = new Rasteriser(width, height); public void Blit(in IntPtr dstPtr) => _rasteriser.Blit(dstPtr); public void RenderFrame(double seconds) { if (seconds <= 0) return; _angle += seconds; var aspectRatio = _rasteriser.Width / (float) _rasteriser.Height; _rasteriser.Clear(Opaque | 0x433649); _rasteriser.View = Matrix4x4.CreateLookAt(new Vector3(40, 30, 60), new Vector3(0, 20, 0), Vector3.UnitY); _rasteriser.Projection = Matrix4x4.CreatePerspectiveFieldOfView((float) (Math.PI / 4.0), aspectRatio, 1, 500); _rasteriser.World = Matrix4x4.CreateRotationY((float) _angle) * Matrix4x4.CreateScale(10); if (!_loaded) { _loaded = true; new Thread(() => _model = new Importer().Read("Content/Model.zip")).Start(); } _model?.Render(_rasteriser); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Tilemaps; public class ProceduralMapManager : MonoBehaviour { [SerializeField] private Tilemap map; [SerializeField] private List<TileData> tileDatas; private Dictionary<TileBase, TileData> dataFromTiles; private void Awake() { dataFromTiles = new Dictionary<TileBase, TileData>(); foreach (var tileData in tileDatas) { foreach (var tile in tileData.tiles) { dataFromTiles.Add(tile, tileData); } } } private void Update() { if (Input.GetMouseButtonDown(0)) { Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); Vector3Int gridPosition = map.WorldToCell(mousePosition); // get mouse click's position in 2d plane TileBase clickedTile = map.GetTile(gridPosition); print($"{gridPosition} : {clickedTile} : { dataFromTiles[clickedTile].isWalkable}"); } } }
using System.Collections.Generic; using UnityEngine; using KSP.Localization; namespace KERBALISM { public class ProcessController: PartModule, IModuleInfo, IAnimatedModule, ISpecifics, IConfigurable { // config [KSPField] public string resource = string.Empty; // pseudo-resource to control [KSPField] public string title = string.Empty; // name to show on ui [KSPField] public string desc = string.Empty; // description to show on tooltip [KSPField] public double capacity = 1.0; // amount of associated pseudo-resource [KSPField] public bool toggle = true; // show the enable/disable toggle button // persistence/config // note: the running state doesn't need to be serialized, as it can be deduced from resource flow // but we find useful to set running to true in the cfg node for some processes, and not others [KSPField(isPersistant = true)] public bool running; // index of currently active dump valve [KSPField(isPersistant = true)] public int valve_i = 0; // caching of GetInfo() for automation tooltip public string ModuleInfo { get; private set; } private DumpSpecs dump_specs; private bool broken = false; private bool isConfigurable = false; public override void OnLoad(ConfigNode node) { ModuleInfo = GetInfo(); } public void Start() { // don't break tutorial scenarios if (Lib.DisableScenario(this)) return; // configure on start, must be executed with enabled true on parts first load. Configure(true); // get dump specs for associated process dump_specs = Profile.processes.Find(x => x.modifiers.Contains(resource)).dump; // set dump valve ui button Events["DumpValve"].active = dump_specs.AnyValves; // set active dump valve dump_specs.ValveIndex = valve_i; valve_i = dump_specs.ValveIndex; // set action group ui Actions["Action"].guiName = Lib.BuildString(Local.ProcessController_Start_Stop, " ", title);//"Start/Stop // hide toggle if specified Events["Toggle"].active = toggle; Actions["Action"].active = toggle; // deal with non-togglable processes if (!toggle) running = true; // set processes enabled state Lib.SetProcessEnabledDisabled(part, resource, broken ? false : running, capacity); } ///<summary> Called by Configure.cs. Configures the controller to settings passed from the configure module</summary> public void Configure(bool enable) { if (enable) { // if never set // - this is the case in the editor, the first time, or in flight // in the case the module was added post-launch, or EVA kerbals if (!part.Resources.Contains(resource)) { // add the resource // - always add the specified amount, even in flight Lib.AddResource(part, resource, (!broken && running) ? capacity : 0.0, capacity); } } else Lib.RemoveResource(part, resource, 0.0, capacity); } public void ModuleIsConfigured() => isConfigurable = true; ///<summary> Call this when process controller breaks down or is repaired </summary> public void ReliablityEvent(bool breakdown) { broken = breakdown; Lib.SetProcessEnabledDisabled(part, resource, broken ? false : running, capacity); } public void Update() { // update rmb ui Events["Toggle"].guiName = Lib.StatusToggle(title, broken ? Local.ProcessController_broken : running ? Local.ProcessController_running : Local.ProcessController_stopped);//"broken""running""stopped" Events["DumpValve"].guiName = Lib.StatusToggle(Local.ProcessController_Dump, dump_specs.valves[valve_i]);//"Dump" } [KSPEvent(guiActive = true, guiActiveEditor = true, guiName = "_", active = true, groupName = "Processes", groupDisplayName = "#KERBALISM_Group_Processes")]//Processes public void Toggle() { SetRunning(!running); } [KSPEvent(guiActive = true, guiActiveEditor = true, guiName = "#KERBALISM_ProcessController_Dump", active = true, groupName = "Processes", groupDisplayName = "#KERBALISM_Group_Processes")]//"Dump""Processes" public void DumpValve() { valve_i = dump_specs.NextValve; // refresh VAB/SPH ui if (Lib.IsEditor()) GameEvents.onEditorShipModified.Fire(EditorLogic.fetch.ship); } public void SetRunning(bool value) { if (broken) return; // switch status running = value; Lib.SetProcessEnabledDisabled(part, resource, running, capacity); // refresh VAB/SPH ui if (Lib.IsEditor()) GameEvents.onEditorShipModified.Fire(EditorLogic.fetch.ship); } // action groups [KSPAction("_")] public void Action(KSPActionParam param) { Toggle(); } // part tooltip public override string GetInfo() { return isConfigurable ? string.Empty : Specs().Info(desc); } public bool IsRunning() { return running; } // specifics support public Specifics Specs() { Specifics specs = new Specifics(); Process process = Profile.processes.Find(k => k.modifiers.Contains(resource)); if (process != null) { foreach (KeyValuePair<string, double> pair in process.inputs) { if (!process.modifiers.Contains(pair.Key)) specs.Add(pair.Key, Lib.BuildString("<color=#ffaa00>", Lib.HumanReadableRate(pair.Value * capacity), "</color>")); else specs.Add(Local.ProcessController_info1, Lib.HumanReadableDuration(0.5 / pair.Value));//"Half-life" } foreach (KeyValuePair<string, double> pair in process.outputs) { specs.Add(pair.Key, Lib.BuildString("<color=#00ff00>", Lib.HumanReadableRate(pair.Value * capacity), "</color>")); } } return specs; } // module info support public string GetModuleTitle() { return Lib.BuildString("<size=1><color=#00000000>01</color></size>", title); } // Display after config widget public override string GetModuleDisplayName() { return Lib.BuildString("<size=1><color=#00000000>01</color></size>", title); } // Display after config widget public string GetPrimaryField() { return string.Empty; } public Callback<Rect> GetDrawModulePanelCallback() { return null; } // animation group support public void EnableModule() { } public void DisableModule() { } public bool ModuleIsActive() { return broken ? false : running; } public bool IsSituationValid() { return true; } } } // KERBALISM
using Jc.Data; using MySql.Data.MySqlClient; using System; using System.Data.Common; namespace Jc.Data { public class MySqlDbCreator: IDbCreator { /// <summary> /// 创建连接 /// </summary> /// <returns></returns> public DbConnection CreateDbConnection(string connectString) { DbConnection dbConnection = null; dbConnection = new MySqlConnection(connectString); dbConnection.Open(); return dbConnection; } /// <summary> /// 创建DbCmd /// </summary> /// <returns></returns> public DbCommand CreateDbCommand(string sql = null) { DbCommand dbCommand = new MySqlCommand(); if (!string.IsNullOrEmpty(sql)) { dbCommand.CommandText = sql; } dbCommand.CommandTimeout = 60; return dbCommand; } } }
using Steamworks; using System.Collections; using UnityEngine; public class LoadScene : MonoBehaviour { public SceneField scene; public float delay = 2.0f; public float damp = 0.75f; public bool goToLanguageSelection = false; private void Start() { if (!GameSettings.loaded) GameSettings.Load(); StartCoroutine(LoadLogo()); } private IEnumerator LoadLogo() { yield return new WaitForSeconds(delay); if (goToLanguageSelection && !GameSettings.selectedLanguage) { if (SteamManager.Initialized) { var steamUILanguage = SteamUtils.GetSteamUILanguage(); switch (steamUILanguage) { case "russian": TextManager.Instance.SetLanguage(TextManager.Language.Russian); break; default: case "english": TextManager.Instance.SetLanguage(TextManager.Language.English); break; } Initiate.Fade(scene, Color.black, damp); } else { Initiate.Fade("LanguageSelectionMenu", Color.black, damp); } } else { Initiate.Fade(scene, Color.black, damp); } } }
using System; namespace CodeGraph { [Serializable] public class SerializedEdge { public string SourceNodeGUID; public int SourceNodeIndex; public string TargetNodeGUID; public int TargetNodeIndex; } }
namespace Quill.Delta { public class ListConverter { public static string GetStringValue(ListType? list) => list.HasValue ? GetStringValue(list.Value) : ""; public static string GetStringValue(ListType list) => list == ListType.Ordered ? "ordered" : list == ListType.Bullet ? "bullet" : list == ListType.Checked ? "checked" : list == ListType.Unchecked ? "unchecked" : ""; public static ListType? GetEnumValue(string list) => list == "ordered" ? ListType.Ordered : list == "bullet" ? ListType.Bullet : list == "checked" ? ListType.Checked : list == "unchecked" ? (ListType?)ListType.Unchecked : null; } }
using System.Linq; using AutoMapper; using DatingApp.API.Dtos; using DatingApp.API.Models; namespace DatingApp.API.Helpers { public class AutoMapperProfiles : Profile { public AutoMapperProfiles() { CreateMap<User, ListUsersModel>() .ForMember(dest => dest.PhotoUrl, opt => opt.MapFrom(src => src.Photos.FirstOrDefault(p => p.IsMain).Url)) .ForMember(dest => dest.Age, opt => opt.MapFrom(src => src.DateOfBirth.CalculateAge())); CreateMap<User, DetailedUserModel>() .ForMember(dest => dest.PhotoUrl, opt => opt.MapFrom(src => src.Photos.FirstOrDefault(p => p.IsMain).Url)) .ForMember(dest => dest.Age, opt => opt.MapFrom(src => src.DateOfBirth.CalculateAge())); CreateMap<Photo, PhotoDetailModel>(); CreateMap<Photo, PhotoModeratorViewModel>(); CreateMap<CreatePhotoViewModel, Photo>(); CreateMap<Photo, ReturnPhotoViewModel>(); CreateMap<UpdateUserModel, User>(); CreateMap<RegisterUserModel, User>(); CreateMap<CreateMessageViewModel, Message>().ReverseMap(); CreateMap<Message, MessageToReturnViewModel>() .ForMember(dest => dest.SenderPhotoUrl, opt => opt.MapFrom(src => src.Sender.Photos.FirstOrDefault(p => p.IsMain).Url)) .ForMember(dest => dest.RecipientPhotoUrl, opt => opt.MapFrom(src => src.Recipient.Photos.FirstOrDefault(p => p.IsMain).Url)); } } }
using System.Collections.Generic; using Embark.DataChannel; namespace Embark.Storage { /// <summary> /// Persistence for CRUD operations to a storage medium /// </summary> public interface IDataStore { /// <summary> /// Get all the Collections /// </summary> IEnumerable<string> Collections { get; } /// <summary> /// Insert a new object /// </summary> /// <param name="tag">The collection name to save to</param> /// <param name="id">ID to associate with the object</param> /// <param name="objectToInsert">Json or other text value to save</param> void Insert(string tag, long id, string objectToInsert); /// <summary> /// Update an existing object /// </summary> /// <param name="tag">The collection name the object resides in</param> /// <param name="id">The ID of the object to update</param> /// <param name="objectToUpdate">The Json or other text to replace the old value with</param> /// <returns>TRUE if the object was updated, FALSE if it did not exist.</returns> bool Update(string tag, long id, string objectToUpdate); /// <summary> /// Delete an existing object /// </summary> /// <param name="tag">The collection name the object resides in</param> /// <param name="id">The ID of the object to delete</param> /// <returns>TRUE if deleted, FALSE if it did not exist.</returns> bool Delete(string tag, long id); /// <summary> /// Retrieve the saved text of the object /// </summary> /// <param name="tag">Collection name the object is saved in</param> /// <param name="id">The ID of the object</param> /// <returns>NULL if the object doesn't exist, or a string associated with the object.</returns> string Get(string tag, long id); /// <summary> /// Return all the <see cref="DataEnvelope"/> objects that are saved in the collection /// </summary> /// <param name="tag">Name of the collection to get all objects from</param> /// <returns>All objects as <see cref="DataEnvelope"/> objects.</returns> DataEnvelope[] GetAll(string tag); } }
// Author: Franco (...), retoques por Nacho /* * [Tiempo máximo recomendado: 40 minutos] * * 192. * El formato DBF es el usado por el antiguo gestor de bases de datos dBase, * y soportado como formato de exportación por muchas herramientas actuales, * como Excel o Access. * * Debes crear un programa que muestre la lista * de los campos que hay almacenados en un fichero DBF. * * Los archivos DBF se dividen en dos partes: * una cabecera que almacena información sobre la estructura del archivo * y una zona de datos. * * La zona de cabecera se separa de la zona de datos con el carácter CR * (avance de carro, número 13 del código ASCII). * * A su vez la cabecera se divide en dos partes: * la primera ocupa 32 bytes y contiene información general sobre el archivo, * mientras que la segunda contiene información sobre cada campo * y está formada por tantos bloques de 32 bytes como campos tenga la tabla. * * La cabecera general del archivo es: * Posicion Tamaño (bytes) Descripcion * 1 1 Nro. que identifica el producto con el fue creada la tabla * 2 3 Fecha ultima actualizacion año/mes/dia * 5 4 Nro.total de registros de la tabla (en orden inverso) * 9 2 Longitud total de la cabecera incluido CR * 11 2 Longitud del registro (incluye el caracter de marca de borrado) * 13 2 Reservados * 15 1 Flag de Transaccion activa * 16 1 Flag de encriptacion * 17 12 Indicadores para el uso en red de area local * 29 1 Flag de fichero de indica .MDX * 30 3 Reservados * * La cabecera de cada campo es: * Posicion Tamaño (bytes) Descripcion * 1 11 Nombre de Campo * 12 1 Tipo de campo (C,D,F,L,M,N) * 13 4 Reservados * 17 1 Longitud de campo * 18 1 Numero de decimales si el campo numerico, * tambien usado para campos de caracteres de gran tamaño * 19 2 Reservados * 21 1 Flag de area de trabajo * 22 10 Reservados * 32 1 Flag de inclusion en el indice .MDX * * (Se puede observar que la cantidad de campos no se indica en la cabecera, * pero se puede deducir, * sabiendo la longitud de la cabecera, * que está en las posiciones 9 y 10, * y el tamaño de cada bloque de cabecera, * que es de 32 bytes). */ using System; using System.IO; class ej192 { static void Main() { //Console.WriteLine("¿Nombre del fichero?"); //string nombreFichero = Console.ReadLine(); string nombreFichero = "ficherosEjemplo\\CUSTOMER.DBF"; if (!File.Exists(nombreFichero)) { Console.WriteLine("El fichero no existe."); } else { try { FileStream fichero = File.OpenRead(nombreFichero); fichero.Seek(8, SeekOrigin.Begin); int posicionDatos = fichero.ReadByte(); // Válido para max 7 campos int cantidadCampos = posicionDatos / 32; byte[] datos = new byte[32]; fichero.Seek(32, SeekOrigin.Begin); for (int i = 0; i < cantidadCampos - 1; i++) { fichero.Read(datos, 0, 32); for (int j = 0; j < 11; j++) { char letra = Convert.ToChar((byte)datos[j]); Console.Write(letra); } Console.WriteLine(); } fichero.Close(); } catch (PathTooLongException ptee) { Console.WriteLine("Error en el nombre: " + ptee.Message); } catch (IOException ioe) { Console.WriteLine("Error de lectura/escritura, " + ioe.Message); } catch (Exception e) { Console.WriteLine("Error: " + e.Message); } } } }
namespace Shriek.ServiceProxy.Socket { /// <summary> /// 定义会话请求的上下文 /// </summary> public interface IContenxt { /// <summary> /// 获取当前会话对象 /// </summary> ISession Session { get; } /// <summary> /// 获取当前会话收到的数据读取器 /// </summary> ISessionStreamReader StreamReader { get; } /// <summary> /// 获取所有会话对象 /// </summary> ISessionManager AllSessions { get; } } }
using OnceMi.Framework.Util.Text; using SkiaSharp; using System.Text; namespace OnceMi.Framework.Util.User { public class RandomAvatar { public byte[] Create(string username, int picSize) { if (picSize < 128) { picSize = 128; } string name = GetEncodeChars(username); if (string.IsNullOrWhiteSpace(name)) { name = "WTF"; } SKBitmap bmp = new SKBitmap(picSize, picSize); using (SKCanvas canvas = new SKCanvas(bmp)) { canvas.DrawColor(RandomBackgroundColor(name)); using (SKPaint sKPaint = new SKPaint()) { sKPaint.Color = SKColors.White; sKPaint.TextSize = (int)(picSize / 3); sKPaint.IsAntialias = true; //sKPaint.Typeface = SkiaSharp.SKTypeface.FromFamilyName("微软雅黑", SKTypefaceStyle.Bold);//字体 SKRect size = new SKRect(); //计算文字宽度以及高度 sKPaint.MeasureText(name, ref size); float temp = (picSize - size.Size.Width) / 2; float temp1 = (picSize - size.Size.Height) / 2; canvas.DrawText(name, temp, temp1 - size.Top, sKPaint);//画文字 } //保存成图片文件 using (SKImage img = SKImage.FromBitmap(bmp)) { using (SKData p = img.Encode(SKEncodedImageFormat.Png, 100)) { return p.ToArray(); } } } } private string GetEncodeChars(string username) { if (string.IsNullOrEmpty(username)) { return null; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < (username.Length <= 3 ? username.Length : 3); i++) { if (username[i] > 127) { string zhChar = TextUtil.GetPinyinSpellCode(username[i]); if (string.IsNullOrEmpty(zhChar)) { sb.Append(username[i]); } sb.Append(zhChar); } else { sb.Append(username[i]); } } return sb.ToString().ToUpper(); } private SKColor RandomBackgroundColor(string username) { int multiple = 255 / (int)'1'; byte red = (byte)(username.Length > 0 ? (username[0] * multiple) % 255 : 0); byte green = (byte)(username.Length > 1 ? (username[1] * multiple) % 255 : 0); byte blue = (byte)(username.Length > 2 ? (username[2] * multiple) % 255 : 0); SKColor color = new SKColor(red, green, blue); return color; } } }
namespace FubuMVC.Core.Diagnostics.Packaging { public class PackageDiagnosticsRequestModel { } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IdentityServerHost.Quickstart.UI; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace IdentityServer { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddAuthorization(); var builder = services.AddIdentityServer(options => { options.Events.RaiseErrorEvents = true; options.Events.RaiseInformationEvents = true; options.Events.RaiseFailureEvents = true; options.Events.RaiseSuccessEvents = true; options.EmitStaticAudienceClaim = true; }) .AddTestUsers(TestUsers.Users); // in-memory, code config builder.AddInMemoryIdentityResources(Config.IdentityResources); builder.AddInMemoryApiScopes(Config.ApiScopes); builder.AddInMemoryClients(Config.Clients); services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseIdentityServer(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); } } }
using System; using System.Threading; using System.Threading.Tasks; using Zapto.Mediator; namespace Mediator.DependencyInjection.Tests.Generics; public class GenericNotificationHandler<T> : INotificationHandler<GenericNotification<T>> { private readonly Result _result; public GenericNotificationHandler(Result result) { _result = result; } public ValueTask Handle(IServiceProvider provider, GenericNotification<T> notification, CancellationToken cancellationToken) { _result.Values.Add(notification.Value); return default; } }
namespace LINGYUN.Abp.WeChat.Official { public class AbpWeChatOfficialOptions { /// <summary> /// 公众号服务器消息Url /// </summary> public string Url { get; set; } /// <summary> /// 公众号AppId /// </summary> public string AppId { get; set; } /// <summary> /// 公众号AppSecret /// </summary> public string AppSecret { get; set; } /// <summary> /// 公众号消息解密Token /// </summary> public string Token { get; set; } /// <summary> /// 公众号消息解密AESKey /// </summary> public string EncodingAESKey { get; set; } } }
using Pea.Geometry.General; using System.Collections.Generic; namespace Pea.Geometry2D.Shapes { public interface IShape2D : IDeepCloneable<IShape2D>, ITransformable<IShape2D, Vector2D> { Vector2D Center { get; set; } Rectangle BoundingRectangle { get; } List<Vector2D> Points { get; } double MarginWidth { get; set; } void DoTransform(); void Invalidate(); IShape2D DoOffset(double marginWidth); } }
namespace CoinMonitor.Interfaces.ServiceHolders { public interface IServiceHolder { void Init(); void Stop(); } }
using System.Collections.Generic; namespace Aptiv.DBCFiles { /// <summary> /// An ECU object described by a DBC file. /// </summary> public interface IDBCECU { /// <summary> /// The name of this ECU. /// </summary> string Name { get; } /// <summary> /// The set of messages in this ECU. /// </summary> IReadOnlyDictionary<string, IDBCMessage> Messages { get; } /// <summary> /// The set of messages in this ECU marked as being RX. /// </summary> IReadOnlyDictionary<string, IDBCMessage> RxMessages { get; } } }
using Microsoft.EntityFrameworkCore; using question_weight.infra.Models; using System; using System.Collections.Generic; using System.Text; namespace question_weight.infra { public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { Database.EnsureCreated(); } public virtual DbSet<Answer> Answers { get; set; } public virtual DbSet<TypeAnswer> Candidates { get; set; } public virtual DbSet<TypeAnswer> CandidateAnswers { get; set; } public virtual DbSet<TypeAnswer> Questions { get; set; } public virtual DbSet<TypeAnswer> TypeAnswers { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer(GetStringConnectionConfig()); } } protected override void OnModelCreating(ModelBuilder modelBuilder) { } private string GetStringConnectionConfig() { return "Data Source=localhost;Initial Catalog=QuestionWeight;Integrated Security=True;Pooling=False"; } } }
using System; namespace FastMDX { class ParsingException : Exception { public override string Message => "Parsing error."; } }
using System; using System.Net.Http; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace SpringOff.DNEx { internal sealed class ApiService : IApiService { private const string BaseUrl = "http://www.drivernotes.net/api"; private readonly ILogger _logger; public ApiService(ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger<ApiService>(); } public async Task<LoginResponse> Login(LoginRequest request) { if (request == null) throw new ArgumentNullException(nameof(request)); using var client = new HttpClient(); var dto = new LoginRequestDto { Login = request.Login, Password = request.Password }; var httpContent = new StringContent(JsonConvert.SerializeObject(dto)); HttpResponseMessage responseMessage = await client.PostAsync($"{BaseUrl}/login", httpContent); if (responseMessage.IsSuccessStatusCode) { var response = await responseMessage.Content.ReadAsStringAsync(); var responseDto = JsonConvert.DeserializeObject<LoginResponseDto>(response); if (responseDto.Status == "OK") { return new LoginResponse(responseDto.Data.UserId, responseDto.Data.UserHash); } else { _logger.LogError($"Unacceptable response status: {responseDto.Status}"); } } return null; } public async Task<string> GetData(string userHash) { if (userHash == null) throw new ArgumentNullException(nameof(userHash)); using var client = new HttpClient(); client.DefaultRequestHeaders.Add("deviceID", "42"); client.DefaultRequestHeaders.Add("DeviceType", "android"); client.DefaultRequestHeaders.Add("Authorization", userHash); HttpResponseMessage responseMessage = await client.PostAsync($"{BaseUrl}/sync", null); if (responseMessage.IsSuccessStatusCode) { var responseBytes = await responseMessage.Content.ReadAsByteArrayAsync(); var response = System.Text.Encoding.UTF8.GetString(responseBytes, 0, responseBytes.Length); var jsonObject = JsonConvert.DeserializeObject(response); return jsonObject.ToString(); } return null; } public async Task<string> GetCarData(int carId, int toShow) { using var client = new HttpClient(); var dto = new CarStatsRequestDto { CarId = carId.ToString(), ToShow = toShow.ToString() }; var httpContent = new StringContent(JsonConvert.SerializeObject(dto)); HttpResponseMessage responseMessage = await client.PostAsync($"{BaseUrl}/car_statistics", httpContent); if (responseMessage.IsSuccessStatusCode) { var responseBytes = await responseMessage.Content.ReadAsByteArrayAsync(); var response = System.Text.Encoding.UTF8.GetString(responseBytes, 0, responseBytes.Length); var jsonObject = JsonConvert.DeserializeObject(response); return jsonObject.ToString(); } return null; } } }
using Database.Data; using Database.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Database.BusinessLogic { static class DatabaseBusinessLogic { public static void AddUser(AdaptiveWeather.UserFromInterface user) { var userDB = new User(); userDB.Username = user.Username; userDB.PasswordSalt = "1234"; userDB.PasswordHash = "4321"; var a = new W2WDBContext(); a.Users.Add(userDB); a.SaveChanges(); } } }
using Q42.HueApi.Models.Bridge; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Q42.HueApi.Interfaces { /// <summary> /// Different platforms can make specific implementations of this interface /// </summary> public interface IBridgeLocator { /// <summary> /// Returns list of bridge IPs /// </summary> /// <param name="timeout"></param> /// <returns></returns> Task<IEnumerable<LocatedBridge>> LocateBridgesAsync(TimeSpan timeout); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using DotNetNuke.Entities.Urls; namespace DNN.Modules.NewsArticlesFriendlyUrlProvider { internal class NewsArticlesFriendlyUrlProviderInfo : ExtensionUrlProviderInfo { } }
public class LevelManager3 : LevelManager { public override void Start() { base.Start(); Services.GravityButton.GravitySwitch(); } }
using Microsoft.Extensions.DependencyInjection; //ReSharper disable once CheckNamespace namespace Microsoft.EntityFrameworkCore { public class MySqlTestHelpers : TestHelpers { protected MySqlTestHelpers() { } public static MySqlTestHelpers Instance { get; } = new MySqlTestHelpers(); public override IServiceCollection AddProviderServices(IServiceCollection services) => services.AddEntityFrameworkMySql(); protected override void UseProviderOptions(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseMySql("Database=DummyDatabase"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Infrastructure; namespace Microsoft.EntityFrameworkCore.Metadata { /// <summary> /// Represents an index on a set of properties. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information. /// </remarks> public interface IIndex : IReadOnlyIndex, IAnnotatable { /// <summary> /// Gets the properties that this index is defined on. /// </summary> new IReadOnlyList<IProperty> Properties { get; } /// <summary> /// Gets the entity type the index is defined on. This may be different from the type that <see cref="Properties" /> /// are defined on when the index is defined a derived type in an inheritance hierarchy (since the properties /// may be defined on a base type). /// </summary> new IEntityType DeclaringEntityType { get; } /// <summary> /// <para> /// Gets a factory for key values based on the index key values taken from various forms of entity data. /// </para> /// <para> /// This method is typically used by database providers (and other extensions). It is generally /// not used in application code. /// </para> /// </summary> /// <typeparam name="TKey">The type of the index instance.</typeparam> /// <returns>The factory.</returns> IDependentKeyValueFactory<TKey> GetNullableValueFactory<TKey>(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Archer : Unit, IProduct { public void MakeUnit(int hp, int initiative, int damage, IObservable hero, int armyNumber) { this._isAlive = true; this._hp = hp; this._damage = damage; this._initiative = initiative; this._hero = hero; this._armyNumber = armyNumber; this._id = _counter++; _hero.RegisterObserver(this); } public void SetAttackType(AttackType attackType) { this._attackType = attackType; } }
using System.IO; using BenchmarkDotNet.Extensions; using Xunit; namespace BenchmarkDotNet.Tests { public class StringExtensionsTests { [Fact] public void AsValidFileNameReplacesAllInvalidFileNameCharactersWithTheirRepresentation() { foreach (char invalidPathChar in Path.GetInvalidFileNameChars()) Assert.Equal($"char{(short) invalidPathChar}", invalidPathChar.ToString().AsValidFileName()); } [Fact] public void AsValidFileNameDoesNotChangeValidFileNames() { const string validFileName = "valid_File-Name.exe"; Assert.Equal(validFileName, validFileName.AsValidFileName()); } [Fact] public void HtmlEncodeCharacters() { string expectedHtml = "&lt;&#39;&gt;&quot;&amp;shouldntchange"; string html = "<'>\"&shouldntchange"; Assert.Equal(expectedHtml, html.HtmlEncode()); } } }
using System.Collections.Generic; namespace MongoDB { public record CreatePersonInput( string Name, IReadOnlyList<Address> Addresses, Address MainAddress); }
using Microsoft.DataTransfer.Basics; using Microsoft.DataTransfer.WpfHost.Basics.Commands; using Microsoft.DataTransfer.WpfHost.Extensibility; using Microsoft.DataTransfer.WpfHost.ServiceModel; using Microsoft.DataTransfer.WpfHost.ServiceModel.Configuration; using System; using System.Windows; namespace Microsoft.DataTransfer.WpfHost.Steps.Summary { sealed class GenerateCommandLineCommand : CommandBase { private readonly ICommandLineProvider commandLineProvider; private IInfrastructureConfiguration infrastructureConfiguration; private string sourceName; private IDataAdapterConfigurationProvider sourceConfigurationProvider; private string sinkName; private IDataAdapterConfigurationProvider sinkConfigurationProvider; public IInfrastructureConfiguration InfrastructureConfiguration { get { return infrastructureConfiguration; } set { SetProperty(ref infrastructureConfiguration, value); } } public string SourceName { get { return sourceName; } set { SetProperty(ref sourceName, value); } } public IDataAdapterConfigurationProvider SourceConfigurationProvider { get { return sourceConfigurationProvider; } set { SetProperty(ref sourceConfigurationProvider, value); } } public string SinkName { get { return sinkName; } set { SetProperty(ref sinkName, value); } } public IDataAdapterConfigurationProvider SinkConfigurationProvider { get { return sinkConfigurationProvider; } set { SetProperty(ref sinkConfigurationProvider, value); } } public GenerateCommandLineCommand(ICommandLineProvider commandLineProvider) { Guard.NotNull("commandLineProvider", commandLineProvider); this.commandLineProvider = commandLineProvider; } public override bool CanExecute(object parameter) { return infrastructureConfiguration != null && sourceName != null && sourceConfigurationProvider != null && sinkName != null && sinkConfigurationProvider != null; } public override void Execute(object parameter) { new CommandLinePreviewWindow { DataContext = commandLineProvider.Get( infrastructureConfiguration, sourceName, sourceConfigurationProvider.CommandLineArguments, sinkName, sinkConfigurationProvider.CommandLineArguments), Owner = Application.Current.MainWindow }.ShowDialog(); } private void SetProperty<T>(ref T storage, T value) { if (Object.Equals(storage, value)) return; storage = value; RaiseCanExecuteChanged(); } } }
using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.UI; namespace Battlehub.UIControls.DockPanels { public class DepthMaskingBehavior : MonoBehaviour { [SerializeField] private Material m_depthMaskMaterial = null; private DockPanel m_root; private RectTransform m_depthMasks; [SerializeField] private RectTransform[] m_foregroundLayerObjects = null; private class DepthMask { public RectTransform Transform; public Image Graphic; public int Depth; public DepthMask(RectTransform rt, Image image) { Transform = rt; Graphic = image; } } private Dictionary<Region, DepthMask> m_regionToDepthMask = new Dictionary<Region, DepthMask>(); private DepthMask[] m_dragDepthMasks; private Vector3 m_previousDragPosition; private void Awake() { m_root = GetComponent<DockPanel>(); GameObject depthMasks = new GameObject(); depthMasks.name = "DepthMasks"; RectTransform depthMasksRT = depthMasks.AddComponent<RectTransform>(); depthMasksRT.SetParent(m_root.Free.parent, false); depthMasksRT.SetSiblingIndex(0); depthMasksRT.Stretch(); m_depthMasks = depthMasksRT; Region[] regions = m_root.GetComponentsInChildren<Region>(); for(int i = 0; i < regions.Length; ++i) { Region region = regions[i]; CreateDepthMask(region); } m_root.RegionEnabled += OnRegionEnabled; m_root.RegionDisabled += OnRegionDisabled; m_root.RegionCreated += OnRegionCreated; m_root.RegionDestroyed += OnRegionDestroyed; m_root.RegionBeginResize += OnRegionBeginResize; m_root.RegionResize += OnRegionResize; m_root.RegionEndResize += OnRegionEndResize; m_root.RegionBeginDrag += OnRegionBeginDrag; m_root.RegionDrag += OnRegionDrag; m_root.RegionEndDrag += OnRegionEndDrag; m_root.RegionTranformChanged += OnRegionTransformChanged; m_root.RegionDepthChanged += OnRegionDepthChanged; foreach(RectTransform rt in m_foregroundLayerObjects) { rt.localPosition = -Vector3.forward * 1; } } private void OnDestroy() { if(m_depthMasks != null) { Destroy(m_depthMasks.gameObject); } m_regionToDepthMask = null; if(m_root != null) { m_root.RegionEnabled -= OnRegionEnabled; m_root.RegionDisabled -= OnRegionDisabled; m_root.RegionCreated -= OnRegionCreated; m_root.RegionDestroyed -= OnRegionDestroyed; m_root.RegionBeginResize -= OnRegionBeginResize; m_root.RegionResize -= OnRegionResize; m_root.RegionEndResize -= OnRegionEndResize; m_root.RegionBeginDrag -= OnRegionBeginDrag; m_root.RegionDrag -= OnRegionDrag; m_root.RegionEndDrag -= OnRegionEndDrag; m_root.RegionTranformChanged -= OnRegionTransformChanged; m_root.RegionDepthChanged -= OnRegionDepthChanged; } } private void CreateDepthMask(Region region) { if(m_regionToDepthMask.ContainsKey(region)) { return; } GameObject depthMaskGO = new GameObject(); depthMaskGO.name = "DepthMask"; RectTransform depthMaskRT = depthMaskGO.AddComponent<RectTransform>(); depthMaskRT.SetParent(m_depthMasks); Image image = depthMaskGO.AddComponent<Image>(); image.material = m_depthMaskMaterial; image.enabled = region.GetDragRegion() == region.transform; image.raycastTarget = false; DepthMask depthMask = new DepthMask(depthMaskRT, image); m_regionToDepthMask.Add(region, depthMask); UpdateDepthMaskTransform(region, depthMask); } private void DestroyDepthMask(Region region) { DepthMask depthMask; if(m_regionToDepthMask.TryGetValue(region, out depthMask)) { Destroy(depthMask.Transform.gameObject); m_regionToDepthMask.Remove(region); } } private void UpdateDepthMaskTransform(Region region, DepthMask depthMask) { RectTransform regionRT = (RectTransform)region.transform; depthMask.Transform.pivot = regionRT.pivot; depthMask.Transform.anchorMin = regionRT.anchorMin; depthMask.Transform.anchorMax = regionRT.anchorMax; depthMask.Transform.offsetMin = regionRT.offsetMin; depthMask.Transform.offsetMax = regionRT.offsetMax; depthMask.Transform.position = regionRT.transform.position; depthMask.Transform.localScale = Vector3.one; ApplyDepth(region, depthMask); } private void OnRegionCreated(Region region) { CreateDepthMask(region); } private void OnRegionDestroyed(Region region) { DestroyDepthMask(region); } private void OnRegionEnabled(Region region) { DepthMask depthMask; if (m_regionToDepthMask.TryGetValue(region, out depthMask)) { if (depthMask != null) { depthMask.Transform.gameObject.SetActive(true); } } } private void OnRegionDisabled(Region region) { DepthMask depthMask; if (m_regionToDepthMask.TryGetValue(region, out depthMask)) { if(depthMask != null) { depthMask.Transform.gameObject.SetActive(false); } } } private void OnRegionDepthChanged(Region region, int depth) { DepthMask depthMask = null; if(!m_regionToDepthMask.TryGetValue(region, out depthMask)) { return; } if (depth == 0) { depthMask.Graphic.enabled = false; } else { depthMask.Graphic.enabled = region.GetDragRegion() == region.transform; } depthMask.Depth = depth; ApplyDepth(region, depthMask); } private static void ApplyDepth(Region region, DepthMask depthMask) { Vector3 pos = depthMask.Transform.localPosition; pos.z = -depthMask.Depth * 0.05f; depthMask.Transform.localPosition = pos; if (region.transform.parent.GetComponentInParent<Region>() == null) { pos = region.transform.localPosition; pos.z = -(0.025f + depthMask.Depth * 0.05f); region.transform.localPosition = pos; } else { pos = region.transform.localPosition; pos.z = 0; region.transform.localPosition = pos; } foreach(Transform content in region.ContentPanel) { Vector3 contentPos = content.localPosition; contentPos.z = 0; content.localPosition = contentPos; } } private void OnRegionBeginDrag(Region region) { Transform dragRegion = region.GetDragRegion(); if(dragRegion == null) { m_dragDepthMasks = new[] { m_regionToDepthMask[region] }; } else { Region[] regions = dragRegion.GetComponentsInChildren<Region>(); m_dragDepthMasks = regions.Where(r => r.Root == m_root).Select(r => m_regionToDepthMask[r]).ToArray(); } m_previousDragPosition = region.transform.position; } private void OnRegionDrag(Region region) { for(int i = 0; i < m_dragDepthMasks.Length; ++i) { DepthMask depthMask = m_dragDepthMasks[i]; depthMask.Transform.position += (region.transform.position - m_previousDragPosition); m_previousDragPosition = region.transform.position; ApplyDepth(region, depthMask); } } private void OnRegionEndDrag(Region region) { m_dragDepthMasks = null; } private void OnRegionBeginResize(Resizer resizer, Region region) { m_dragDepthMasks = new[] { m_regionToDepthMask[region] }; } private void OnRegionResize(Resizer resizer, Region region) { UpdateDepthMaskTransform(region, m_dragDepthMasks[0]); } private void OnRegionEndResize(Resizer resizer, Region region) { m_dragDepthMasks = null; } private void OnRegionTransformChanged(Region region) { DepthMask depthMask = m_regionToDepthMask[region]; UpdateDepthMaskTransform(region, depthMask); } } }
using System.Linq; using System.Threading.Tasks; using Domain; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Web.Areas.Admin.ViewModels; namespace Web.Areas.Admin.Controllers { [Authorize(Roles = "admin")] [Area("Admin")] public class AccountController : Controller { public AccountController(UserManager<AppUser> userManager) { _userMgr = userManager; } private readonly UserManager<AppUser> _userMgr; // GET: AccountController public ActionResult Index() { System.Collections.Generic.List<AppUser> users = _userMgr.Users.ToList(); return View(users); } // GET: AccountController/Create public ActionResult Create() { return View(); } // POST: AccountController/Create [HttpPost, ActionName("Create")] [ValidateAntiForgeryToken] public async Task<ActionResult> CreateUser([Bind("User,RoleName,Password")] UserVm userVm) { if (ModelState.IsValid) { userVm.User.EmailConfirmed = true; await _userMgr.CreateAsync(userVm.User, userVm.Password); await _userMgr.AddToRoleAsync(userVm.User, userVm.RoleName); return RedirectToAction(nameof(Index)); } return View(); } [Authorize(Roles = "admin,staff,parent")] // GET: AccountController/Edit/5 public async Task<ActionResult> Edit(string email) { AppUser user = await _userMgr.FindByEmailAsync(email); if (user == null) { return NotFound(); } return View(user); } [Authorize(Roles = "admin,staff,parent")] // POST: AccountController/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> EditAsync([Bind("FirstName,LastName,PhoneNumber,Email")] AppUser user) { if (ModelState.IsValid) { AppUser appUser = await _userMgr.FindByEmailAsync(user.Email); appUser.LastName = user.LastName; appUser.FirstName = user.FirstName; appUser.PhoneNumber = user.PhoneNumber; await _userMgr.UpdateAsync(appUser); if (await _userMgr.IsInRoleAsync(user, "admin")) { return View(nameof(Index)); } if (await _userMgr.IsInRoleAsync(user, "staff")) { RedirectToAction("Dashboard", "Applications"); } if (await _userMgr.IsInRoleAsync(user, "parent")) { RedirectToAction("Index", "Home"); } } return View(nameof(Edit), user); } // GET: AccountController/Delete/5 public ActionResult Delete(int id) { return View(); } // POST: AccountController/Delete/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Delete(int id, IFormCollection collection) { try { return RedirectToAction(nameof(Index)); } catch { return View(); } } } }
using System.Collections.Generic; using System.Threading.Tasks; using Clarifai.API; using Clarifai.API.Responses; using Clarifai.DTOs.Predictions; using Clarifai.UnitTests.Fakes; using Newtonsoft.Json.Linq; using NUnit.Framework; namespace Clarifai.UnitTests { [TestFixture] public class ConceptsUnitTests { [Test] public async Task GetConceptResponseShouldBeCorrect() { var httpClient = new FkClarifaiHttpClient( getResponse: @" { ""status"": { ""code"": 10000, ""description"": ""Ok"" }, ""concept"": { ""id"": ""@conceptID"", ""name"": ""@conceptName"", ""created_at"": ""2017-10-02T11:34:20.419915Z"", ""language"": ""en"", ""app_id"": ""@appID"" } } "); var client = new ClarifaiClient(httpClient); var response = await client.GetConcept("").ExecuteAsync(); Assert.True(response.IsSuccessful); Concept concept = response.Get(); Assert.AreEqual("@conceptID", concept.ID); Assert.AreEqual("@conceptName", concept.Name); Assert.AreEqual("@appID", concept.AppID); } [Test] public async Task GetConceptsResponseShouldBeCorrect() { var httpClient = new FkClarifaiHttpClient( getResponse: @" { ""status"": { ""code"": 10000, ""description"": ""Ok"" }, ""concepts"": [{ ""id"": ""@conceptID1"", ""name"": ""@conceptName1"", ""created_at"": ""2017-10-15T16:28:28.901994Z"", ""language"": ""en"", ""app_id"": ""@appID"" }, { ""id"": ""@conceptID2"", ""name"": ""@conceptName2"", ""created_at"": ""2017-10-15T16:26:46.667104Z"", ""language"": ""en"", ""app_id"": ""@appID"" }] } "); var client = new ClarifaiClient(httpClient); var response = await client.GetConcepts().ExecuteAsync(); Assert.True(response.IsSuccessful); List<Concept> concepts = response.Get(); Assert.AreEqual(2, concepts.Count); Concept concept1 = concepts[0]; Concept concept2 = concepts[1]; Assert.AreEqual("@conceptID1", concept1.ID); Assert.AreEqual("@conceptName1", concept1.Name); Assert.AreEqual("@appID", concept1.AppID); Assert.AreEqual("@conceptID2", concept2.ID); Assert.AreEqual("@conceptName2", concept2.Name); Assert.AreEqual("@appID", concept2.AppID); } [Test] public async Task ModifyConceptRequestAndResponseShouldBeCorrect() { var httpClient = new FkClarifaiHttpClient( patchResponse: @" { ""status"": { ""code"": 10000, ""description"": ""Ok"" }, ""concepts"": [{ ""id"": ""@positiveConcept1"", ""name"": ""@positiveConceptName1"", ""created_at"": ""2017-10-15T16:28:28.901994Z"", ""language"": ""en"", ""app_id"": ""@appID"" }, { ""id"": ""@positiveConcept2"", ""created_at"": ""2017-10-15T16:26:46.667104Z"", ""language"": ""en"", ""app_id"": ""@appID"" }] } "); var client = new ClarifaiClient(httpClient); ClarifaiResponse<List<Concept>> response = await client.ModifyConcepts( new List<Concept> { new Concept("@positiveConcept1", "@positiveConceptName1"), new Concept("@positiveConcept2") } ).ExecuteAsync(); var expectedRequestBody = JObject.Parse(@" { ""action"": ""overwrite"", ""concepts"": [ { ""id"": ""@positiveConcept1"", ""name"": ""@positiveConceptName1"" }, { ""id"": ""@positiveConcept2"", ""name"": null } ] } "); Assert.True(JToken.DeepEquals(expectedRequestBody, httpClient.PatchedBody)); Assert.True(response.IsSuccessful); Assert.AreEqual("Ok", response.Status.Description); Assert.AreEqual(response.Get()[0].ID,"@positiveConcept1"); Assert.AreEqual(response.Get()[0].Name,"@positiveConceptName1"); Assert.AreEqual(response.Get()[1].ID,"@positiveConcept2"); } [Test] public async Task AddConceptRequestAndResponseShouldBeCorrect() { var httpClient = new FkClarifaiHttpClient( postResponse: @" { ""status"": { ""code"": 10000, ""description"": ""Ok"" }, ""concepts"": [{ ""id"": ""@positiveConcept1"", ""name"": ""@positiveConceptName1"", ""created_at"": ""2017-10-15T16:28:28.901994Z"", ""language"": ""en"", ""app_id"": ""@appID"" }, { ""id"": ""@positiveConcept2"", ""created_at"": ""2017-10-15T16:26:46.667104Z"", ""language"": ""en"", ""app_id"": ""@appID"" }] } "); var client = new ClarifaiClient(httpClient); ClarifaiResponse<List<Concept>> response = await client.AddConcepts( new List<Concept> { new Concept("@positiveConcept1", "@positiveConceptName1"), new Concept("@positiveConcept2") } ).ExecuteAsync(); var expectedRequestBody = JObject.Parse(@" { ""concepts"": [ { ""id"": ""@positiveConcept1"", ""name"": ""@positiveConceptName1"" }, { ""id"": ""@positiveConcept2"" } ] } "); Assert.True(JToken.DeepEquals(expectedRequestBody, httpClient.PostedBody)); Assert.True(response.IsSuccessful); Assert.AreEqual("Ok", response.Status.Description); Assert.AreEqual(response.Get()[0].ID,"@positiveConcept1"); Assert.AreEqual(response.Get()[0].Name,"@positiveConceptName1"); Assert.AreEqual(response.Get()[1].ID,"@positiveConcept2"); } } }
using UnityEngine; using System.Collections; public class Health : MonoBehaviour { [Header ("Health")] [SerializeField] private float startingHealth; public float currentHealth { get; private set; } private Animator anim; private bool dead; [Header("iFrames")] [SerializeField] private float iFramesDuration; [SerializeField] private int numberOfFlashes; private SpriteRenderer spriteRend; [Header("Components")] [SerializeField] private Behaviour[] components; private bool invulnerable; [Header("Death Sound")] [SerializeField] private AudioClip deathSound; [SerializeField] private AudioClip hurtSound; private void Awake() { currentHealth = startingHealth; anim = GetComponent<Animator>(); spriteRend = GetComponent<SpriteRenderer>(); } public void TakeDamage(float _damage) { if (invulnerable) return; currentHealth = Mathf.Clamp(currentHealth - _damage, 0, startingHealth); if (currentHealth > 0) { anim.SetTrigger("hurt"); StartCoroutine(Invunerability()); SoundManager.instance.PlaySound(hurtSound); } else { if (!dead) { anim.SetTrigger("die"); //Deactivate all attached component classes foreach (Behaviour component in components) component.enabled = false; dead = true; SoundManager.instance.PlaySound(deathSound); } } } public void AddHealth(float _value) { currentHealth = Mathf.Clamp(currentHealth + _value, 0, startingHealth); } private IEnumerator Invunerability() { invulnerable = true; Physics2D.IgnoreLayerCollision(10, 11, true); for (int i = 0; i < numberOfFlashes; i++) { spriteRend.color = new Color(1, 0, 0, 0.5f); yield return new WaitForSeconds(iFramesDuration / (numberOfFlashes * 2)); spriteRend.color = Color.white; yield return new WaitForSeconds(iFramesDuration / (numberOfFlashes * 2)); } Physics2D.IgnoreLayerCollision(10, 11, false); invulnerable = false; } private void Deactivate() { gameObject.SetActive(false); } }
using System; using System.Collections.Generic; using System.Linq; namespace BarcodeSimulator { public static class Barcode { public static string GetTypeName(string input) { if (IsUpcA(input)) return "UPC-A"; if (IsEan13(input)) return "EAN-13"; if (IsEan8(input)) return "EAN-8"; if (IsCode39(input)) return "Code39"; return "Text"; } public static bool IsUpcA(string input) { if (input.Length != 12) return false; if (!input.ToCharArray().All(char.IsDigit)) return false; var digits = input.ToCharArray(0, 11).Select(CharCodeOfNumberToInt).ToArray(); var odds = Odds(digits).Sum(); var evens = Evens(digits).Sum(); var result = 10 - ((odds*3 + evens) % 10); return CharCodeOfNumberToInt(input[11]) == result; } public static bool IsEan13(string input) { return input.Length == 13 && IsEan(input); } public static bool IsEan8(string input) { return input.Length == 8 && IsEan(input); } public static bool IsCode39(string input) { return input.Length > 2 && input[0] == '*' && input.Last() == '*' && input.ToCharArray().All(IsCode39Char); } private static bool IsCode39Char(char c) { return (c >= 0x41 && c <= 0x5a) // A-Z (uppercase only) || (c >= 0x30 && c <= 0x39) // 0-9 || (new[] {'*', ' ', '-', '$', '%', '.', '/', '+'}.Contains(c)); } private static bool IsEan(string input) { if (!input.ToCharArray().All(char.IsDigit)) return false; // take each character, turn it into an integer, then reverse the list // we reverse it because every odd-numbered (1-based counting) digit counting from the END // is multiplied by 3. var digits = input.ToCharArray(0, input.Length - 1).Select(CharCodeOfNumberToInt).Reverse().ToArray(); var odds = Odds(digits).Sum() * 3; var evens = Evens(digits).Sum(); var total = odds + evens; return 10 - (total % 10) == CharCodeOfNumberToInt(input.Last()); } /// <summary> /// Takes the ASCII character code of a number and converts it to an integer. /// </summary> /// <param name="c"></param> /// <returns></returns> /// <example>>CharCodeOfNumberToInt('8') => 8</example> private static int CharCodeOfNumberToInt(char c) { var code = (int) c; if (code < 48 || code > 57) throw new ArgumentException("This character code is not for a number", "c"); return code - 48; } public static IEnumerable<T> Odds<T>(T[] source) { return Enumerable.Range(0, source.Count()).Where(i => i%2 == 0).Select(i => source[i]); } public static IEnumerable<T> Evens<T>(T[] source) { return Enumerable.Range(0, source.Count()).Where(i => i % 2 != 0).Select(i => source[i]); } } }
using System; using System.Collections.Generic; using System.Text; namespace PandoraSharp { //Encryption key for XmlRpc; corresponds to crypt_key_output.h in the pianobar library internal static class XmlRpcKey { public static readonly uint N = 16; public static readonly UInt32[] P = new UInt32[18] { 0xD8A1A847, 0xBCDA04F4, 0x54684D7B, 0xCDFD2D53, 0xADAD96BA, 0x83F7C7D2, 0x97A48912, 0xA9D594AD, 0x6B4F3733, 0x0657C13E, 0xFCAE0687, 0x700858E4, 0x34601911, 0x2A9DC589, 0xE3D08D11, 0x29B2D6AB, 0xC9657084, 0xFB5B9AF0 }; public static readonly UInt32[,] S = new UInt32[4, 256] { { 0x4EE44D9D, 0xCCEEAB0F, 0xD86488F6, 0x25FDD9B7, 0xB0DE3A97, 0x66EADF2F, 0xC0D3DCA4, 0xEE72A5FA, 0x54074DEC, 0xCBAD83AD, 0x4B1771A3, 0xD92AE545, 0xB5FCE937, 0x26AD96D9, 0x5D615D68, 0xF2994B82, 0xE668D342, 0x61051D4C, 0xCFB29CA4, 0x8B421D38, 0xDA3B4EB9, 0xD92D6A55, 0xF7D940C7, 0x99C4BC83, 0xAB896E79, 0x77C7039B, 0x1215B24A, 0x0C0EBC0D, 0xE9F082B2, 0x6B7DFE9C, 0x4A714E76, 0x91280D88, 0xA422A361, 0x3E674D4A, 0x6EBC2D42, 0x6838580B, 0xBAE461AB, 0xE8FEDD17, 0xEFD6E5E0, 0x690D3E93, 0x32FADEB0, 0x1B99EE04, 0xBE9FA7D9, 0x7997DFC6, 0xFD1B8025, 0x667B35D8, 0x2D909996, 0xFE487FF0, 0x628BCFE1, 0xA534C620, 0x6644DEFE, 0x8BF9236D, 0xE943DD51, 0xF4615657, 0x605D4F80, 0x2E02FC45, 0xD924D2D0, 0xFD4AB9E3, 0x5AEB18F0, 0x7A8D7C92, 0x6CA40CA6, 0xD8AD4139, 0xCA5E7EC2, 0x69BE3C59, 0x554A4DD6, 0xBA474DD1, 0xE113576B, 0xCB89A6BD, 0xF366EC0C, 0x876661AB, 0xD85E5381, 0x79A93327, 0x5A4E5D92, 0xE3301F23, 0xF211DD61, 0x6F0140D0, 0xDBA134BF, 0x3C623008, 0xD5FCE976, 0x6EDE648E, 0x814CF920, 0xB38878E1, 0x6232D49C, 0x2310373B, 0xA8C6EBFC, 0xCD506842, 0x62BEF441, 0x1324C803, 0x69D1F137, 0x3907EE67, 0x47967932, 0xC3C3F280, 0xC4B036B9, 0x5EC264B4, 0x9484AA3C, 0x5FEF9C53, 0xC1B9030F, 0xE86C6BBA, 0x3AE49DAE, 0xBBAC421C, 0x54D06D99, 0xBA13A2B2, 0x3132FA87, 0x2FDDB5E2, 0x4B751219, 0x5B59778F, 0xEFFA2E62, 0x3BD56164, 0xE7EDFC1D, 0xCF4D5FDB, 0xC6310BDA, 0x0CAE8B8F, 0x53196C2F, 0xAC951D1F, 0x32FD1D71, 0x7D9D5956, 0x2EA62C92, 0x9FA4A4C8, 0xE491DC41, 0x7E5F2507, 0x4568300F, 0xF210AAA8, 0xB6980949, 0x017405E7, 0x5EBF3350, 0x44B863F6, 0xDF96854A, 0xFA8A8390, 0x342BDFFA, 0x93096350, 0xCD0F0083, 0xBE295FDD, 0x549AA9C9, 0x8554D31B, 0x2F2FE138, 0x30E8C78D, 0xED603733, 0x4B47F4C2, 0x03D481DC, 0x8BE4479C, 0x9A307E98, 0x73CFC5DC, 0x71DE3DFB, 0x55DA2605, 0x2CC97898, 0x13F0CC6F, 0x5F30FEE1, 0xF65D36D0, 0x99D05438, 0xB6A1DF23, 0x2EA6EF9B, 0x12D3A110, 0xF1C89B1A, 0x522BAA1F, 0xE39AC7B3, 0xAFC153D1, 0x2A565274, 0x51530B46, 0x1291387D, 0x15BC2B63, 0xA73AD01F, 0x13EBC4A7, 0x849583D7, 0x4A9E1AE6, 0x430C9A05, 0xEB2A78FB, 0xFA3A817D, 0x6D1D7AE5, 0xB99588F5, 0x6D2C571B, 0xF975441C, 0x1348927D, 0xB069BDE2, 0x0771A398, 0x4B93EDCC, 0x3C167223, 0xC3BBCFDF, 0x40C406DA, 0x81C867B1, 0xEB20C3D2, 0x2476ED54, 0xB581F042, 0x1160A8B8, 0xBCA1AD0F, 0xD8F18C9F, 0x708BC7C6, 0x0579D83C, 0x29BAA2B8, 0x45B845EE, 0xA57F5579, 0xE52E4A8A, 0x48365478, 0xC6CCBFB4, 0x2F53D280, 0x8E1FF972, 0xF4E02067, 0x3F878869, 0x5879FF3C, 0x1EDFAB0F, 0xD4FE52E3, 0x630AC960, 0xABD69092, 0xFAA3BF43, 0xF1CA3317, 0x9CFF48D2, 0x8FE33F83, 0x260C1DE3, 0x89DB0B0B, 0xF127E1E3, 0x7DA503FF, 0x01C9A821, 0x30573A67, 0x8A567A2E, 0xE47B86CF, 0xB8709ADE, 0xB19ADD3A, 0x46A37074, 0x134CE184, 0x1F73191B, 0xE22B39F6, 0xE9D35D3D, 0x996390AF, 0xADBBCCDB, 0xC9312071, 0xD442107D, 0x0B50C70A, 0xB9B6CC8C, 0x60A51E0E, 0xA1076443, 0x215F1292, 0x5A53C644, 0xEA96EA2E, 0xE9F3B4BC, 0xBA5F45D2, 0x454B65D6, 0x2CF04D9C, 0x05EF1D0F, 0xCD1ABBEE, 0xE86697B0, 0xFB92F164, 0xEBEDADBF, 0x69282B8D, 0x65C91F0D, 0x6215AB51, 0x87E7BDF6, 0xC663D502, 0x6EF4864E, 0xDC3BDCC9, 0x97184DBB, 0xCD315EED, 0x64001E09, 0x6F7DE8CE, 0x38435D03, 0x840B5C82, 0x23CDBC8A, 0x7FA0D4FB }, { 0xEBCBE20D, 0x09FADAEC, 0x98FF9F63, 0x16D0DFE1, 0x54B65FA8, 0x8C58D07C, 0xEAACBEA0, 0xEA8BC5B7, 0xD343B8ED, 0x46D416FC, 0x0247DCBB, 0x527CA3F5, 0x22DAF183, 0x6684CF7F, 0xA2D5D9F6, 0xC507E43B, 0x7B368AE6, 0xFC8179EC, 0x47E959C4, 0xDADF15F2, 0x92E48145, 0xD9CFA8B3, 0x94F209E8, 0x10F93D6D, 0x3BAAF7B5, 0x9E5009B4, 0xE7E66FD8, 0x10F6D58F, 0x1EAFFF4D, 0x0423FCE5, 0xE860C60A, 0x7713B2B4, 0x7C5EEF7E, 0x430801CF, 0x46613A77, 0xFADEC916, 0x58AB09B3, 0xEE05C51F, 0xD4C6331F, 0x9BCA1941, 0x15BF041F, 0xC3B04E8D, 0x6CD037AF, 0x11C81E53, 0xB38393DF, 0xB1D07B52, 0x067D02F7, 0xA9E5798B, 0x4E5C10A6, 0x790DD862, 0xDEA21AD1, 0x3C0C90BF, 0xB05D8240, 0xFEA81F59, 0x832F19FF, 0x17190D1C, 0x03E07FDC, 0x43A6AEAC, 0xFE0C8A2E, 0x216813A6, 0xF0428728, 0xC1D21DCF, 0x54109ACB, 0x68FB51BB, 0x3F5AEE69, 0x557FEA14, 0x07965E16, 0x58E2A204, 0x6E765B0C, 0x3B8D920F, 0xDD712180, 0xDD0F67CA, 0x37F9D475, 0x91815CCF, 0xC31A34BB, 0x8F710EF2, 0xF2DA2F82, 0x2A24931B, 0x41CFF29F, 0x16C9BECF, 0x1AEB93FB, 0x090DF533, 0xC10D27B6, 0xF7EE2303, 0xF82A0ED0, 0x57031132, 0x88AFF451, 0x574A8BFF, 0xF1ACA4F0, 0xDD556F49, 0x90D7CF52, 0x4BCA4AA3, 0xC917557C, 0x4BB6B151, 0x52CD8251, 0x7C7ED836, 0x3488ED59, 0xC50C6A0B, 0x675413ED, 0x6368583D, 0x98B61BAE, 0x1AF59261, 0x46590022, 0xA4C70187, 0x4658F3EB, 0x80A61049, 0x8F120E7A, 0xBEAC09D8, 0x195ACD49, 0x6BE1DE45, 0x6EF1E32D, 0xB8A4B816, 0xC18758B8, 0xCA7AD046, 0xD475BFE1, 0xCC3AB8AF, 0x45AB9AD7, 0xC37C62AC, 0x9AAD7E2E, 0xB9D87862, 0x28F3CD26, 0xA0577A0E, 0x75859ECE, 0x4A6E5B86, 0xE61E36B3, 0xA00E0CA4, 0x3E2CC99C, 0x581DF442, 0xCE40B79B, 0x17BAB635, 0x73F1C282, 0x7C009CE0, 0x1A8BBC5A, 0xBBB87ECD, 0x162ED0AC, 0x8DB76F5A, 0xD5AD1234, 0xD0D7A773, 0x41CBDEFB, 0x7197AFF4, 0x5C60E777, 0x5D9141D4, 0xF43D5211, 0xA4F064D9, 0x40C13CB3, 0xE9DE900D, 0xBF733203, 0xC00F2E89, 0x095D476F, 0x277A825D, 0x4B6A61D3, 0xFF857740, 0xE34705C0, 0x65F8372C, 0x497AC161, 0x1231CA4A, 0xFB385036, 0x24B36150, 0x6CB9FA2D, 0xCBAB3399, 0x3832629E, 0x1BB815EE, 0x6AAA74C7, 0x8FFA22B8, 0x64093F28, 0x973BBA95, 0x831A8195, 0x48B2923D, 0x9680C36E, 0x16BA5344, 0x1F190542, 0xBCB0DFCC, 0xCCC24623, 0xFA503EAD, 0x7189956C, 0x80B3C715, 0xFA9F4685, 0x36CF833E, 0x19A53ADF, 0xA5A4BD79, 0x187ADC8D, 0x8AEFA6B6, 0xF64FF62A, 0x88A590BA, 0xE30C75BE, 0xA3BFBCC7, 0xAC669722, 0xC4AEAFF2, 0x822DC5FA, 0xAA73C1D5, 0x422EFD93, 0x946FE915, 0xEF623E46, 0x24395A31, 0xF28FF488, 0xB4D7CA7E, 0x27703504, 0x9F390B73, 0xA6999558, 0x8AE04A20, 0xDD6FE7DB, 0x55963137, 0xCFEF70BB, 0x708CA677, 0x804CF78B, 0xD5AC1CA2, 0x88D7CCFC, 0x5FE056DF, 0x25B390EA, 0x11550845, 0x15A58C0B, 0x7C3530A3, 0x24550544, 0xD395EDD0, 0xEB046782, 0x7E3CCE71, 0x25A8640C, 0x96A955DE, 0x4BF7614E, 0x3014FD08, 0xE2AC1E2E, 0x7D3AB3C3, 0xB63CB59C, 0x9E92D401, 0x859B2C44, 0x1F893940, 0xEE81B9BB, 0x7F430589, 0xAF2CC2EC, 0x0FA273E2, 0x3E5C6FAA, 0xE580E6A9, 0x64D73FE6, 0xE7C5A28A, 0x99B760BC, 0xC0FCBA71, 0xDB521C76, 0xDBC7C1F8, 0x4968CF63, 0xD4928D17, 0x6DBBCC5F, 0x681EB668, 0xC326CEB9, 0x7C6B0EBB, 0xF071C193, 0x5CC6A08C, 0xFA4B95EB, 0x0BED345D, 0x16854F61, 0x22ECDDA9, 0x77335F2D, 0xCC016EE5, 0x4CE1D7F6, 0x32B1409B, 0x2197B046, 0x73CD94F3 }, { 0x56D997EE, 0x92FA3097, 0xA1AF0D9D, 0x11FCBB9C, 0xA2673993, 0x3860F1CE, 0xB2B70A39, 0x5BC90183, 0xBFA62ADC, 0x58E257F2, 0xD221A704, 0x0A876CE4, 0xD7B0FCA9, 0x80D3D874, 0x696A6CFD, 0xB989EFF1, 0xEAA5F132, 0xA29ECB5D, 0x674B7380, 0x0BAD725F, 0x59D55508, 0x8DB40E2A, 0x003EBD12, 0x871AD00E, 0x7ACE20A9, 0xE670BA85, 0x43D53997, 0x79461049, 0x806C102B, 0xB21337BD, 0x791483E8, 0x6ECA44EA, 0x959CF50D, 0x8D87166D, 0xFA939DF8, 0xB0E519DE, 0x8C069B44, 0x0A47F71A, 0x8D7AD1CA, 0x24E6FEDD, 0xCEF2173E, 0xB46A57F1, 0x9DD9C775, 0x549B2E5D, 0x67A37485, 0x38F7FC18, 0xA269F5A1, 0x1B04F14E, 0x4550E006, 0x8F5E0E14, 0x5EB9992C, 0x88D780A5, 0x334FFA1E, 0x473A75C1, 0x9D96E913, 0x7DB16188, 0xE699B708, 0x88D087FA, 0x06E44D4E, 0xCB29E519, 0x68529AB8, 0xBC74B1FD, 0xDA074140, 0x557B9936, 0x80BB557E, 0x42522D24, 0x909E967F, 0x7D578A28, 0x7F78EBD7, 0xB793DC4B, 0x08498F07, 0x8A77FC08, 0xFFFDA0C1, 0x2ECA4123, 0xB63861DC, 0xD909606E, 0x29A545E4, 0xB37539D6, 0x292FAC93, 0xBDC6C4F3, 0xDAC7CE05, 0x68201C9D, 0xE08DC67A, 0xE0FB0327, 0x17554D62, 0x636D9040, 0x0612D29F, 0xAF250475, 0xB8961740, 0xBE3E4408, 0x3AF166E6, 0x3B16CC87, 0x2DC77141, 0x3C874024, 0x0E409623, 0xC7576B7A, 0x35CAF7DA, 0x0AA9AED6, 0x6C5F2CC0, 0x23AAB90F, 0x74A41C51, 0xDAA1B557, 0x412EC422, 0xD9E55CF0, 0x7F6A804E, 0x9256A133, 0xF3FD2639, 0x42C9A68A, 0xB20588E4, 0x33339C04, 0xCB9B9300, 0xCCA198E9, 0x849A2FFF, 0xF2B71118, 0xD27C41DF, 0xF1453CD9, 0xEB94D640, 0x9CE6A69E, 0x1561C1BD, 0x8A8F7E07, 0x1FA3989C, 0x601C3440, 0x95DE5ED8, 0xB2F2AE94, 0x831BA7C3, 0x6831E3ED, 0x5C5C0BD8, 0x628A0E89, 0x2726D7A3, 0x82B6E434, 0xB729A5C7, 0x5AB563C2, 0xA4119CE6, 0x4459E404, 0x0B3E858A, 0x080C2DF9, 0x6EBE3FFB, 0xC1D64BCE, 0xB2C90336, 0x998AE507, 0xC152879A, 0x31B99F23, 0x37769978, 0xF5C78668, 0x2B954114, 0x54169F1A, 0xBF9E6E7D, 0x41BEBC39, 0x35BC63BD, 0x77E91F12, 0x89909690, 0xCB17B79D, 0xCCBF4A25, 0x3E5E653E, 0x3B4531F1, 0x31AF6109, 0x027DC03F, 0x334AE2A7, 0x8A685A70, 0xD82C335D, 0x7D73C193, 0xF0311C79, 0xE8091EAF, 0x64B12983, 0x85CEB9A6, 0x402AB7C9, 0xA95E4546, 0x85CE4FD7, 0x21968004, 0x0846E117, 0xD290B888, 0xCE2888FC, 0xE2F318F1, 0x89B189DD, 0x7A2D73BA, 0xE28937E5, 0x6D857435, 0x8A2F05FA, 0xA19B966F, 0x37EF297F, 0xC50696F5, 0xA7C3DE1A, 0x988D3850, 0x24007793, 0xB94C792C, 0x4DA98736, 0xA04EB570, 0x4AA44F84, 0x7124E7C6, 0x13B9026E, 0x27AC2D15, 0xFBB9AD93, 0x2F94AA1C, 0x98587A3D, 0x9C9DB996, 0x7E3487D5, 0xA819272C, 0x32AA5E43, 0xE0DB72F5, 0x4DB4853C, 0x7350C7EC, 0xB1626C73, 0x07130A5F, 0xC3DAA529, 0xD6422735, 0x8559200D, 0x1046E85C, 0x326CFB54, 0xAD42DB6A, 0xAE4CC364, 0xA49F5718, 0xF472F8A0, 0x3C002484, 0x013067BE, 0xC88A1317, 0x4C3C209B, 0x7CBB8BB3, 0x41FB8DAF, 0x236591B3, 0xDC974A45, 0x8639E738, 0x97C38B19, 0xD7FF5725, 0xE7094458, 0xF28B223F, 0xF73C878B, 0x7F7502D9, 0x52F7FD09, 0x4A661B36, 0x62814D8E, 0xBBDD1D16, 0x002598D9, 0x56B17A84, 0x87A331B7, 0x6C2898C2, 0xAFCBA795, 0x4EFEE9AE, 0xEAE3A4F1, 0xC3D4D9CD, 0x5EFD7C32, 0xB1B31E64, 0x95245686, 0x21A7DA12, 0x7155E041, 0x7362B475, 0x36486BD5, 0xA97E5D7C, 0x8871303B, 0x93199D52, 0x246F919E, 0x5A581359, 0x6AE746DD, 0x3CA9098C, 0x56DA5714, 0xAA0B674A, 0x08C89A5D }, { 0x7DD47329, 0xF270A704, 0x71BF31DA, 0x3B57772E, 0xFBE90F4B, 0x87FC23F6, 0xCF413D71, 0x4FFEA8EC, 0xEFBA20C2, 0xEB53E0C1, 0xFFE7633E, 0x854E28E8, 0xFBFFE904, 0x8A7841BE, 0x94E99960, 0xA3E69064, 0x365C57AB, 0xBEE976CC, 0x596B94C2, 0x8C5E90E2, 0x074B3C54, 0x89B5E926, 0xDF192C71, 0xAF631D85, 0x67A8EDEC, 0x24BE4919, 0x81EB9C8A, 0xFDB13471, 0xEE61A4A1, 0x1EE368DE, 0x8C55C255, 0xD273A000, 0x12A24DCD, 0x22A6708E, 0x6BB4C19A, 0xF2599FDE, 0xE84B8A95, 0xDD578159, 0x1F666F1E, 0x483BBCE2, 0x46E340BA, 0x8B7D6490, 0xE65BD77D, 0xA50F2282, 0x4B455D23, 0x9B5D486B, 0x95CEA1A3, 0x4B7A484A, 0x2E16BE82, 0x096A8E05, 0x5494AF5E, 0x1EBA1525, 0x84FDB773, 0xD47CE143, 0xC1254007, 0x1CE4CBBE, 0x8049402D, 0x114D7B59, 0x64D760AD, 0x6AEECE49, 0x83DC9867, 0x36FF9C28, 0x6FFB709D, 0xB22F7301, 0x6E6CAD92, 0x0001F394, 0xB560CDE7, 0xEA02FDDA, 0x40609266, 0x7F599B81, 0x1B8FD59A, 0xA562FF5C, 0xA01750C6, 0x78A35114, 0x789F8094, 0xF46594B8, 0xFF3A12BE, 0x29DDEB50, 0xE3CF5A2C, 0x8E440B20, 0xBFBF3DD8, 0x649DB58A, 0xC48A8A51, 0x97F139C3, 0x0BB07943, 0x548C90BD, 0x8153FCF1, 0x13098DEF, 0x812EA492, 0xFC0AC487, 0xC5EAE50A, 0x7A02481B, 0xC75279D7, 0x59CBC149, 0x6AB39416, 0x39331E1A, 0x233BE50B, 0x7F09C1BD, 0xECC11E6E, 0xA6647D03, 0x06BD33AD, 0xD717C795, 0xE07E2D67, 0x2688D40B, 0xE23E349F, 0x8C7F559E, 0x3BA698C2, 0xEB5FCD3C, 0xE94E2DE5, 0x3C0FE4DF, 0x55454456, 0x12731019, 0x21AF58D7, 0x2555CE03, 0x17BBC647, 0xF0C66012, 0xE02D87F8, 0x340DB0CE, 0x72A3766F, 0xE2724C51, 0x3636A5FD, 0xC226C419, 0x1A5F0464, 0xA543817B, 0x0B850A8D, 0xD5A6F88B, 0xCE3715B8, 0xB73918A2, 0x6AC92E61, 0x0FCD43EA, 0xF559EEDE, 0x3482C340, 0x447D9924, 0xF95D6EB2, 0xB22E6C6F, 0x935740D2, 0x7C04B228, 0xB90ABD1A, 0x8D9D01C9, 0x43B63B2D, 0xE0EBEDAC, 0x7C219604, 0x8479756F, 0xB67355FE, 0xA056539B, 0xAF1D5A02, 0x6660BB07, 0xD1A0593C, 0x5AABEF47, 0x73802FC5, 0xAADB5251, 0x92556CFF, 0x5BF44BDC, 0x4DC171CF, 0x1EE4E879, 0x516BC896, 0xCDBB21EA, 0xF513BD04, 0x94267720, 0x6B29DAC1, 0x1D778D67, 0x9625EA42, 0x23946BBC, 0xF23D2E0A, 0x001C2CFB, 0xEF121203, 0x963A0C2B, 0x1AAE960B, 0x13F2D588, 0xAE6BFEAE, 0x77424AC8, 0x1E0B2A9F, 0x9074C626, 0x9BCDE764, 0xF8539561, 0xC14A5B05, 0xD88D9FAE, 0x2C5C4C67, 0x2C63BAE5, 0x99CCF4CB, 0x3563CA53, 0x0CE7A114, 0xCB8938D3, 0x7C61537F, 0xE717A35E, 0xB69D3832, 0xE47931C3, 0xD5C9D409, 0x355E0B97, 0xC60EB27E, 0xB17978F6, 0x77CCBCEA, 0x85AEFA12, 0x59DFA376, 0x36DB61D2, 0x96832915, 0xCC4411F3, 0xB81F1EF9, 0x2C54E5E1, 0xDD3CE944, 0x02D92E29, 0x1D4795B1, 0x27F900B0, 0x97A516CC, 0xA2DB2CC8, 0x3125B863, 0xBF44DC77, 0x211A0226, 0x3A98AB5F, 0x2612396E, 0xA1BEF080, 0x708B7433, 0x5D457230, 0xED03C4EB, 0xA84D73AE, 0x89D5582D, 0x95F0C7FA, 0xEF51B8C9, 0xF9DCA97D, 0xCB2E49FD, 0xC12B4ADD, 0x611C9AD5, 0x35D1D7CE, 0xA77E13BE, 0x207C1B88, 0x0AC289D4, 0x4B553B81, 0x4940991A, 0x23D9F9D5, 0xDFD93925, 0xB924E9D2, 0xBFA61D10, 0x861FDF0F, 0xBBD30811, 0x953CE5DA, 0x92B48334, 0x5E5B44FC, 0x5B949533, 0x31A5D165, 0x99339641, 0x2737671F, 0x512EB25C, 0x54408346, 0xA090A7FE, 0x1D9CA5F9, 0x470C19E4, 0x720F936E, 0xA8628453, 0x364D29CC, 0x42E472DF, 0x54949196, 0x6C7C46EA, 0x12797418, 0x7D775295, 0xC46A7C32, 0x69CE8560 } }; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace ExpanseReportManager.Models { public class RoleViewModels { [Display(Name = "Id Role")] public string Id { get; set; } [Display(Name = "Nom Role")] [Required] [MinLength(2)] public string Name { get; set; } [Display(Name = "Liste des employees")] public ICollection<EmployeeViewModels> Employees { get; set; } } public class RoleIndexModel { [Display(Name = "Nouveau role")] public RoleViewModels NewRole { get; set; } [Display(Name = "Liste des roles")] public ICollection<RoleViewModels> Roles { get; set; } } }
namespace Blog.Viewer.Shell { using IoC.UI.Data; using IoC.UI.Interfaces; public class ShellModuleLoader : IModuleLoader { private readonly MenuItemData[] menuItemDatas; public ShellModuleLoader(MenuItemData[] menuItemDatas) { this.menuItemDatas = menuItemDatas; } public void Initialize(IApplicationContext context, IShellView shell) { shell.AddMenuItems(menuItemDatas); } } }
using System; namespace OsuSongsFolderWatcher { internal class BeatmapLoadFailedException : Exception { } }
using Location.Core.Entities; using Location.Infrastructure.Seed.Seeders.Base; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; namespace Location.Infrastructure.Seed.Seeders; public class CountrySeeder : ISeeder { public int Order => 1; public async Task SeedAsync(LocationContext context, string contentRootPath, ILogger<LocationContext> logger, IServiceProvider serviceProvider) { if (context.Countries.Any()) { return; } logger.LogInformation("CountrySeeder is working"); var countries = LoadCountries(contentRootPath); foreach (var country in countries) { context.Entry(country).State = EntityState.Modified; await context.Countries.AddAsync(country); } } private List<Country> LoadCountries(string contentRootPath) => Load<List<Country>>(contentRootPath, "Seeds/countries.json"); private T Load<T>(string contentRootPath, string fileLocation) { var currencyJson = File.ReadAllText(Path.Combine(contentRootPath, fileLocation)); return System.Text.Json.JsonSerializer.Deserialize<T>(currencyJson); } }
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org) // Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net) // Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp) // See the LICENSE.md file in the project root for full license information. using Stride.Core.Assets; using Stride.Core; using Stride.Core.Annotations; namespace Stride.Assets.Presentation.AssetEditors.AssetCompositeGameEditor.ViewModels { /// <summary> /// An interface for view models that contain a design part in an editor of <see cref="AssetComposite"/>. /// </summary> public interface IEditorDesignPartViewModel<out TAssetPartDesign, TAssetPart> where TAssetPartDesign : IAssetPartDesign<TAssetPart> where TAssetPart : IIdentifiable { /// <summary> /// Gets the part design object associated to the asset-side part. /// </summary> [NotNull] TAssetPartDesign PartDesign { get; } } }
#l "constants.cake" #l "backup.cake" void EmbedApiKeys() { var apiKeysPath = sourceFolder + File("Captura.Core/ApiKeys.cs"); var variables = new [] { "imgur_client_id" }; Information("Embedding Api Keys from Environment Variables ..."); CreateBackup(apiKeysPath, tempFolder + File("ApiKeys.cs")); var content = FileRead(apiKeysPath); foreach (var variable in variables) { if (HasEnvironmentVariable(variable)) { content = content.Replace($"Get(\"{variable}\")", $"\"{EnvironmentVariable(variable)}\""); } } FileWrite(apiKeysPath, content); }
namespace OpenSheets.Core { public enum ThreadFlag { Pin, Locked, Hidden } }
using BlazorComponent; using Microsoft.AspNetCore.Components; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Masa.Blazor { public partial class MTabsBar : MSlideGroup, IThemeable { [Parameter] public string BackgroundColor { get; set; } [Parameter] public string Color { get; set; } protected string ComputedColor { get { if (Color != null) return Color; return IsDark ? "white" : "primary"; } } protected override void SetComponentClass() { base.SetComponentClass(); const string prefix = "m-tabs-bar"; CssProvider .Merge(css => { css.Add(prefix) .AddTheme(IsDark) .AddTextColor(ComputedColor) .AddBackgroundColor(BackgroundColor); }, style => { style.AddTextColor(ComputedColor); style.AddBackgroundColor(BackgroundColor); }) .Merge("content", css => { css.Add($"{prefix}__content"); }); } } }
// 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.Runtime.InteropServices; using static Interop; namespace System.Windows.Forms.Metafiles { /// <summary> /// Record that represents a 16 bit Poly record. /// </summary> /// <remarks> /// Not an actual Win32 define, encapsulates: /// /// - EMRSETTEXTCOLOR /// - EMRSETBKCOLOR /// </remarks> [StructLayout(LayoutKind.Sequential)] internal struct EMRSETCOLOR { public EMR emr; public COLORREF crColor; public override string ToString() { return $"[EMR{emr.iType}] Color: {crColor.ToSystemColorString()}"; } } }
using System; class Nacepin { static void Main(string[] args) { double usPrice = double.Parse(Console.ReadLine()); double usWeight = double.Parse(Console.ReadLine()); double ukPrice = double.Parse(Console.ReadLine()); double ukWeight = double.Parse(Console.ReadLine()); double chPrice = double.Parse(Console.ReadLine()); double chWeight = double.Parse(Console.ReadLine()); double usPriceResult = (usPrice / 0.58d) / usWeight; double ukPriceResult = (ukPrice / 0.41d) / ukWeight; double chPriceResult = (chPrice * 0.27d) / chWeight; double highestPrice = 0d; double lowestPrice = 0d; highestPrice = Math.Max(Math.Max(usPriceResult, ukPriceResult), chPriceResult); lowestPrice = Math.Min(Math.Min(usPriceResult, ukPriceResult), chPriceResult); if (lowestPrice == usPriceResult) { Console.WriteLine("US store. {0:F2} lv/kg", lowestPrice); Console.WriteLine("Difference {0:F2} lv/kg", highestPrice - lowestPrice); } else if (lowestPrice == ukPriceResult) { Console.WriteLine("UK store. {0:F2} lv/kg", lowestPrice); Console.WriteLine("Difference {0:F2} lv/kg", highestPrice - lowestPrice); } else { Console.WriteLine("Chinese store. {0:F2} lv/kg", lowestPrice); Console.WriteLine("Difference {0:F2} lv/kg", highestPrice - lowestPrice); } } }
using System.Linq; using System.Threading.Tasks; using AllReady.Areas.Admin.ViewModels.Itinerary; using AllReady.Models; using MediatR; using Microsoft.EntityFrameworkCore; namespace AllReady.Areas.Admin.Features.TaskSignups { public class VolunteerTaskSignupSummaryQueryHandler : IAsyncRequestHandler<VolunteerTaskSignupSummaryQuery, VolunteerTaskSignupSummaryViewModel> { private readonly AllReadyContext _context; public VolunteerTaskSignupSummaryQueryHandler(AllReadyContext context) { _context = context; } public async Task<VolunteerTaskSignupSummaryViewModel> Handle(VolunteerTaskSignupSummaryQuery message) { return await _context.VolunteerTaskSignups.AsNoTracking() .Include(x => x.User) .Where(x => x.Id == message.VolunteerTaskSignupId) .Select( x => new VolunteerTaskSignupSummaryViewModel { VolunteerTaskSignupId = x.Id, VolunteerName = x.User.Name, VolunteerEmail = x.User.Email }) .FirstOrDefaultAsync(); } } }
using System; using System.Collections.Generic; using System.Xml; namespace Recurly { public class AddOn : RecurlyEntity { public string PlanCode { get; private set; } public string AddOnCode { get; set; } public string Name { get; set; } private Dictionary<string, int> _unitAmountInCents; /// <summary> /// A dictionary of currencies and values for the add-on amount /// </summary> public Dictionary<string, int> UnitAmountInCents { get { return _unitAmountInCents ?? (_unitAmountInCents = new Dictionary<string, int>()); } } public int DefaultQuantity { get; set; } public bool? DisplayQuantityOnHostedPage { get; set; } public DateTime CreatedAt { get; private set; } public string TaxCode { get; set; } private const string UrlPrefix = "/plans/"; private const string UrlPostfix = "/add_ons/"; #region Constructors internal AddOn() { } internal AddOn(XmlTextReader xmlReader) { ReadXml(xmlReader); } internal AddOn(string planCode, string addOnCode, string name) { PlanCode = planCode; AddOnCode = addOnCode; Name = name; } #endregion /// <summary> /// Creates an addon /// </summary> public void Create() { Client.Instance.PerformRequest(Client.HttpRequestMethod.Post, UrlPrefix + Uri.EscapeUriString(PlanCode) + UrlPostfix, WriteXml, ReadXml); } /// <summary> /// Update an existing add on in Recurly /// </summary> public void Update() { Client.Instance.PerformRequest(Client.HttpRequestMethod.Put, UrlPrefix + Uri.EscapeUriString(PlanCode) + UrlPostfix + Uri.EscapeUriString(AddOnCode), WriteXml, ReadXml); } /// <summary> /// Deletes this add on, making it inactive /// </summary> public void Delete() { Client.Instance.PerformRequest(Client.HttpRequestMethod.Delete, UrlPrefix + Uri.EscapeUriString(PlanCode) + UrlPostfix + Uri.EscapeUriString(AddOnCode)); } #region Read and Write XML documents internal void ReadXmlUnitAmount(XmlTextReader reader) { while (reader.Read()) { if (reader.Name == "unit_amount_in_cents" && reader.NodeType == XmlNodeType.EndElement) break; if (reader.NodeType == XmlNodeType.Element) { UnitAmountInCents.Remove(reader.Name); UnitAmountInCents.Add(reader.Name, reader.ReadElementContentAsInt()); } } } internal override void ReadXml(XmlTextReader reader) { while (reader.Read()) { // End of account element, get out of here if (reader.Name == "add_on" && reader.NodeType == XmlNodeType.EndElement) break; if (reader.NodeType != XmlNodeType.Element) continue; switch (reader.Name) { case "add_on_code": AddOnCode = reader.ReadElementContentAsString(); break; case "name": Name = reader.ReadElementContentAsString(); break; case "display_quantity_on_hosted_page": DisplayQuantityOnHostedPage = reader.ReadElementContentAsBoolean(); break; case "default_quantity": DefaultQuantity = reader.ReadElementContentAsInt(); break; case "created_at": CreatedAt = reader.ReadElementContentAsDateTime(); break; case "unit_amount_in_cents": ReadXmlUnitAmount(reader); break; case "tax_code": TaxCode = reader.ReadElementContentAsString(); break; } } } internal override void WriteXml(XmlTextWriter xmlWriter) { xmlWriter.WriteStartElement("add_on"); xmlWriter.WriteElementString("add_on_code", AddOnCode); xmlWriter.WriteElementString("name", Name); xmlWriter.WriteIfCollectionHasAny("unit_amount_in_cents", UnitAmountInCents, pair => pair.Key, pair => pair.Value.AsString()); xmlWriter.WriteEndElement(); } #endregion #region Object Overrides public override string ToString() { return "Recurly Plan: " + PlanCode; } public override bool Equals(object obj) { var plan = obj as Plan; return plan != null && Equals(plan); } public bool Equals(Plan plan) { return PlanCode == plan.PlanCode; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BagOUtils.Guards.Messages; namespace BagOUtils.Guards { /// <summary> /// Extensions methods that allow fluent comparison of numbers. This /// is needed so we can have generic extensions methods that allow /// comparison of numbers. We have to define a type in order for the /// extension methods to be associated with the various numeric /// types. This allows us to use IComparable, to get a whole class /// of types that can have extension methods that do comparisons. /// </summary> public static class GuardExtensions { //------------------------------------------------------------------------- // // Comparison Methods // //------------------------------------------------------------------------- /// <summary> /// Determine if the other value is less than /// the base value. /// </summary> /// <typeparam name="T">Any comparable type</typeparam> /// <param name="baseValue">the extended value</param> /// <param name="otherValue">the value to test</param> /// <returns> /// True if the base value is less than the other value. /// </returns> public static bool LessThan<T>(this T baseValue, T otherValue) where T : IComparable<T> { return baseValue.CompareTo(otherValue) < 0; } /// <summary> /// Determine if the other value is less than /// the base value. /// </summary> /// <typeparam name="T">Any comparable type</typeparam> /// <param name="baseValue">the extended value</param> /// <param name="otherValue">the value to test</param> /// <returns> /// True if the base value is less than the other value. /// </returns> public static bool LessThanOrEqual<T>(this T baseValue, T otherValue) where T : IComparable<T> { return baseValue.CompareTo(otherValue) <= 0; } /// <summary> /// Determine if the other value is less than /// the base value. /// </summary> /// <typeparam name="T">Any comparable type</typeparam> /// <param name="baseValue">the extended value</param> /// <param name="otherValue">the value to test</param> /// <returns> /// True if the base value is less than the other value. /// </returns> public static bool EqualTo<T>(this T baseValue, T otherValue) where T : IComparable<T> { return baseValue.CompareTo(otherValue) == 0; } /// <summary> /// Determine if the other value is less than /// the base value. /// </summary> /// <typeparam name="T">Any comparable type</typeparam> /// <param name="baseValue">the extended value</param> /// <param name="otherValue">the value to test</param> /// <returns> /// True if the base value is less than the other value. /// </returns> public static bool GreaterThanOrEqual<T>(this T baseValue, T otherValue) where T : IComparable<T> { return baseValue.CompareTo(otherValue) >= 0; } /// <summary> /// Determine if the other value is less than /// the base value. /// </summary> /// <typeparam name="T">Any comparable type</typeparam> /// <param name="baseValue">the extended value</param> /// <param name="otherValue">the value to test</param> /// <returns> /// True if the base value is less than the other value. /// </returns> public static bool GreaterThan<T>(this T baseValue, T otherValue) where T : IComparable<T> { return baseValue.CompareTo(otherValue) > 0; } //------------------------------------------------------------------------- // // Internal Extensions // Many of these will likely be implemented in other utility libraries. // //------------------------------------------------------------------------- /// <summary> /// Ensure that a string is not null. /// </summary> /// <returns> /// Original string if it is not null. If it is null, an empty string. /// </returns> internal static string NullToEmpty(this string possibleNullString) { var fixedString = possibleNullString; if (possibleNullString == null) { fixedString = string.Empty; } return fixedString; } /// <summary> /// Ensure that calling ToString() on an object doesn't return a null. /// </summary> /// <returns> /// ToString() of object if it is not null. If it is null, an empty string. /// </returns> internal static string NullToEmpty(this object possibleNullObject) { var objectString = string.Empty; if (possibleNullObject != null) { objectString = possibleNullObject.ToString(); } return objectString; } /// <summary> /// Return a lambda (delegate) that simply returns the /// value. /// </summary> /// <typeparam name="T">Type of value.</typeparam> /// <param name="value">Value to return.</param> /// <returns>Lambda that returns the value.</returns> internal static Func<T> ToLambda<T>(this T value) { return () => value; } } }
using System; using UnityEngine; // Token: 0x02000348 RID: 840 [Serializable] public class BucketWeights : BucketContents { // Token: 0x1700037C RID: 892 // (get) Token: 0x06001784 RID: 6020 RVA: 0x000B9148 File Offset: 0x000B7548 // (set) Token: 0x06001785 RID: 6021 RVA: 0x000B9150 File Offset: 0x000B7550 public int Count { get { return this.count; } set { this.count = ((value >= 0) ? value : 0); } } // Token: 0x1700037D RID: 893 // (get) Token: 0x06001786 RID: 6022 RVA: 0x000B9166 File Offset: 0x000B7566 public override BucketContentsType Type { get { return BucketContentsType.Weights; } } // Token: 0x1700037E RID: 894 // (get) Token: 0x06001787 RID: 6023 RVA: 0x000B9169 File Offset: 0x000B7569 public override bool IsCleaningAgent { get { return false; } } // Token: 0x1700037F RID: 895 // (get) Token: 0x06001788 RID: 6024 RVA: 0x000B916C File Offset: 0x000B756C public override bool IsFlammable { get { return false; } } // Token: 0x06001789 RID: 6025 RVA: 0x000B916F File Offset: 0x000B756F public override bool CanBeLifted(int strength) { return strength > 0; } // Token: 0x04001738 RID: 5944 [SerializeField] private int count; }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace api_pix_net.Models.Pix { public class Horario { [JsonProperty("solicitacao")] public DateTime Solicitacao { get; set; } } }
 using System; namespace WhatsNotReferenced { public class DropAssetsAction { readonly UnreferencedAssets assets; public DropAssetsAction(UnreferencedAssets unreferenced) { assets = unreferenced; } public void Execute() { foreach (var table in assets.Tables) { DropTable(table); } foreach (var column in assets.Columns) { DropColumn(column); } } static void DropTable(UnreferencedTable table) { Console.WriteLine($"DROP TABLE {table.FullName}"); } static void DropColumn(UnreferencedColumn column) { Console.WriteLine($"ALTER TABLE {column.TableName} DROP COLUMN {column.Name}"); } } }
/* ==================================================================== */ using System; using System.Collections; using System.Collections.Specialized; using System.Xml; namespace Oranikle.Report.Engine { ///<summary> /// The sets of data (defined by DataSet) that are retrieved as part of the Report. ///</summary> [Serializable] public class DataSetsDefn : ReportLink { IDictionary _Items; // list of report items public DataSetsDefn(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p) { if (xNode.ChildNodes.Count < 10) _Items = new ListDictionary(); // Hashtable is overkill for small lists else _Items = new Hashtable(xNode.ChildNodes.Count); // Loop thru all the child nodes foreach(XmlNode xNodeLoop in xNode.ChildNodes) { if (xNodeLoop.NodeType != XmlNodeType.Element) continue; if (xNodeLoop.Name == "DataSet") { DataSetDefn ds = new DataSetDefn(r, this, xNodeLoop); if (ds != null && ds.Name != null) _Items.Add(ds.Name.Nm, ds); } } } public DataSetDefn this[string name] { get { return _Items[name] as DataSetDefn; } } override public void FinalPass() { foreach (DataSetDefn ds in _Items.Values) { ds.FinalPass(); } return; } public bool GetData(Report rpt) { bool haveRows = false; foreach (DataSetDefn ds in _Items.Values) { haveRows |= ds.GetData(rpt); } return haveRows; } public IDictionary Items { get { return _Items; } } } }
namespace Shapes2D { using UnityEngine; using System.Collections; public class DragCamera : MonoBehaviour { Vector3 anchor; Vector3 origin; bool dragging; bool zoomed; float lastClick; void LateUpdate () { if (Input.GetMouseButtonDown(0)) { float time = Time.time; if (time - lastClick < 0.3f) { zoomed = !zoomed; if (zoomed) Camera.main.orthographicSize = 1; else Camera.main.orthographicSize = 7.35f; } lastClick = time; dragging = true; anchor = Input.mousePosition; origin = Camera.main.transform.position; } if (Input.GetMouseButtonUp(0)) { dragging = false; } if (dragging) { Vector3 delta = Camera.main.ScreenToWorldPoint(Input.mousePosition - anchor - new Vector3(-Screen.width / 2, -Screen.height / 2, Camera.main.transform.position.z)) - new Vector3(Camera.main.transform.position.x, Camera.main.transform.position.y, 0); Camera.main.transform.position = origin - delta; } } } }
namespace CustomControls.Design { using System; using System.ComponentModel; using System.Linq; using System.Windows.Forms; /// <summary> /// Class for displaying a flags enumeration in the designer. /// </summary> /// <remarks>From CodeProject : http://www.codeproject.com/KB/edit/flagenumeditor.aspx</remarks> [ToolboxItem(false)] internal class FlagCheckedListBox : CheckedListBox { #region fields /// <summary> /// Indicates whether currently updating the check states. /// </summary> private bool isUpdatingCheckStates; /// <summary> /// The type of the enum. /// </summary> private Type enumType; /// <summary> /// The enum value. /// </summary> private Enum enumValue; #endregion #region constructor /// <summary> /// Initializes a new instance of the <see cref="FlagCheckedListBox"/> class. /// </summary> public FlagCheckedListBox() { this.CheckOnClick = true; } #endregion #region properties /// <summary> /// Gets or sets the enum value. /// </summary> [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)] public Enum EnumValue { get { object e = Enum.ToObject(this.enumType, this.GetCurrentValue()); return (Enum)e; } set { Items.Clear(); // Store the current enum value this.enumValue = value; // Store enum type this.enumType = value.GetType(); // Add items for enum members this.FillEnumMembers(); // Check/uncheck items depending on enum value this.ApplyEnumValue(); } } #endregion #region methods /// <summary> /// Handles the raising of the <see cref="CheckedListBox.ItemCheck"/> event. /// </summary> /// <param name="e">An <see cref="ItemCheckEventArgs"/> instance that contains the event data.</param> protected override void OnItemCheck(ItemCheckEventArgs e) { base.OnItemCheck(e); if (this.isUpdatingCheckStates) { return; } // Get the checked/unchecked item FlagCheckedListBoxItem item = Items[e.Index] as FlagCheckedListBoxItem; // Update other items this.UpdateCheckedItems(item, e.NewValue); } /// <summary> /// Adds an integer value and its associated description. /// </summary> /// <param name="v">The value to add.</param> /// <param name="c">The description string to add.</param> /// <returns>The <see cref="FlagCheckedListBoxItem"/> item that was added.</returns> private void Add(int v, string c) { FlagCheckedListBoxItem item = new FlagCheckedListBoxItem(v, c); Items.Add(item); } /// <summary> /// Gets the current bit value corresponding to all checked items. /// </summary> /// <returns>The bit value.</returns> private int GetCurrentValue() { return (from object t in this.Items select t as FlagCheckedListBoxItem) .Where((item, i) => this.GetItemChecked(i) && item != null) .Aggregate(0, (current, item) => current | item.Value); } /// <summary> /// Checks or unchecks items depending on the given bit value. /// </summary> /// <param name="value">The bit value.</param> private void UpdateCheckedItems(int value) { this.isUpdatingCheckStates = true; // Iterate over all items for (int i = 0; i < Items.Count; i++) { FlagCheckedListBoxItem item = Items[i] as FlagCheckedListBoxItem; if (item == null) { continue; } if (item.Value == 0) { SetItemChecked(i, value == 0); } else { SetItemChecked(i, (item.Value & value) == item.Value && item.Value != 0); } } this.isUpdatingCheckStates = false; } /// <summary> /// Updates items in the checklistbox. /// </summary> /// <param name="composite">The item that was checked/unchecked.</param> /// <param name="cs">The check state of that item.</param> private void UpdateCheckedItems(FlagCheckedListBoxItem composite, CheckState cs) { if (composite == null) { return; } // If the value of the item is 0, call directly. if (composite.Value == 0) { this.UpdateCheckedItems(0); } // Get the total value of all checked items int sum = (from object t in this.Items select t as FlagCheckedListBoxItem) .Where((item, i) => item != null && this.GetItemChecked(i)) .Aggregate(0, (current, item) => current | item.Value); // If the item has been unchecked, remove its bits from the sum if (cs == CheckState.Unchecked) { sum = sum & (~composite.Value); } else { // If the item has been checked, combine its bits with the sum sum |= composite.Value; } // Update all items in the checklistbox based on the final bit value this.UpdateCheckedItems(sum); } /// <summary> /// Adds items to the checklistbox based on the members of the enum. /// </summary> private void FillEnumMembers() { foreach (string name in Enum.GetNames(this.enumType)) { object val = Enum.Parse(this.enumType, name); int intVal = (int)Convert.ChangeType(val, typeof(int)); this.Add(intVal, name); } this.Height = this.GetItemHeight(0) * 8; } /// <summary> /// Checks/unchecks items based on the current value of the enum variable. /// </summary> private void ApplyEnumValue() { int intVal = (int)Convert.ChangeType(this.enumValue, typeof(int)); this.UpdateCheckedItems(intVal); } #endregion #region nested classes /// <summary> /// Class that represents an item in the <see cref="FlagCheckedListBox"/>. /// </summary> /// <remarks>From CodeProject.</remarks> private class FlagCheckedListBoxItem { /// <summary> /// Initializes a new instance of the <see cref="FlagCheckedListBoxItem"/> class. /// </summary> /// <param name="value">The value of the item.</param> /// <param name="caption">The caption of the item.</param> public FlagCheckedListBoxItem(int value, string caption) { this.Value = value; this.Caption = caption; } /// <summary> /// Gets or sets the value of the item. /// </summary> public int Value { get; set; } /// <summary> /// Gets or sets the caption of the item. /// </summary> public string Caption { get; set; } /// <summary> /// Returns a string which represents the object. /// </summary> /// <returns>A string which represents the object.</returns> public override string ToString() { return this.Caption; } } #endregion } }
using System; using System.Reactive; using System.Reactive.Linq; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace KanjiReviewer { static class ControlObservable { public static IObservable<EventPattern<RoutedEventArgs>> FromClick(AppBarButton button) { return Observable.FromEventPattern<RoutedEventHandler, RoutedEventArgs>( handler => button.Click += handler, handler => button.Click -= handler); } public static IObservable<TResult> FromClick<TResult>(AppBarButton button, TResult result) { return FromClick(button).Select(evt => result); } } }