content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the iam-2010-05-08.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.IdentityManagement.Model { /// <summary> /// Contains the response to a successful <a>UploadSSHPublicKey</a> request. /// </summary> public partial class UploadSSHPublicKeyResponse : AmazonWebServiceResponse { private SSHPublicKey _sshPublicKey; /// <summary> /// Gets and sets the property SSHPublicKey. /// <para> /// Contains information about the SSH public key. /// </para> /// </summary> public SSHPublicKey SSHPublicKey { get { return this._sshPublicKey; } set { this._sshPublicKey = value; } } // Check to see if SSHPublicKey property is set internal bool IsSetSSHPublicKey() { return this._sshPublicKey != null; } } }
30.142857
101
0.667062
[ "Apache-2.0" ]
AltairMartinez/aws-sdk-unity-net
src/Services/IdentityManagement/Generated/Model/UploadSSHPublicKeyResponse.cs
1,688
C#
using LazyBot.Area.Detection; using LazyBot.Area.Searching; using UnityEngine; [CreateAssetMenu(menuName = "Validator/Mask")] public class MaskValidatorSO : DetectionValidatorSO { public override bool Validate(SearchingArea searchingArea, DetectionArea detectionArea) { return !(((1 << detectionArea.Collider.gameObject.layer) & searchingArea.Data.TargetMask) == 0); } }
30.230769
104
0.755725
[ "MIT" ]
Seaqqull/lazy-bot
LazyBot/Assets/Scripts/Searching/Validator/MaskValidatorSO.cs
395
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Windows.UI.Xaml; using OpenCvSharp; namespace SDKTemplate { public class AlgorithmProperty : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; // This method is called by the Set accessor of each property. // The CallerMemberName attribute that is applied to the optional propertyName // parameter causes the property name of the caller to be substituted as an argument. private void NotifyPropertyChanged([CallerMemberName] string propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } // Name of the parameter. private string parameterName; public string ParameterName { get { return parameterName; } set { parameterName = value; NotifyPropertyChanged("ParameterName"); } } // Description of the parameter. private string description; public string Description { get { return description; } set { description = value; NotifyPropertyChanged("Description"); } } // Value setting panel visibility private Visibility sliderVisibility; public Visibility SliderVisibility { get { return sliderVisibility; } set { sliderVisibility = value; NotifyPropertyChanged("SliderVisibility"); } } // Value setting panel visibility private Visibility comboBoxVisibility; public Visibility ComboBoxVisibility { get { return comboBoxVisibility; } set { comboBoxVisibility = value; NotifyPropertyChanged("ComboBoxVisibility"); } } // Value setting panel visibility private Visibility detailsVisibility; public Visibility DetailsVisibility { get { return detailsVisibility; } set { detailsVisibility = value; NotifyPropertyChanged("DetailsVisibility"); } } // Current value of the parameter private double currentValue; public object CurrentValue { get { if (ParamType == typeof(int)) { return (int)currentValue; } if (ParamType == typeof(double)) { return currentValue; } if (ParamType == typeof(OpenCvSharp.Size)) { var res = new OpenCvSharp.Size((int)currentValue, (int)currentValue); return res; } //else if (ParamType == typeof(LineTypes)) //{ // if ((int)currentValue == 0) // { // return LineTypes.Link4; // } // else if ((int)currentValue == 1) // { // return LineTypes.Link8; // } // else if ((int)currentValue == 2) // { // return LineTypes.AntiAlias; // } // else // { // return LineTypes.Link4; // } //} //else if (ParamType == typeof(BorderTypes)) //{ // if ((int)currentValue == 0) // { // return BorderTypes.Constant; // } // else if ((int)currentValue == 1) // { // return BorderTypes.Replicate; // } // else if ((int)currentValue == 2) // { // return BorderTypes.Reflect; // } // else if ((int)currentValue == 3) // { // return BorderTypes.Wrap; // } // else if ((int)currentValue == 4) // { // return BorderTypes.Reflect101; // } // else if ((int)currentValue == 5) // { // return BorderTypes.Transparent; // } // else if ((int)currentValue == 6) // { // return BorderTypes.Isolated; // } // else // { // return BorderTypes.Default; // } //} if (ParamType == typeof(Scalar)) { return (Scalar)currentValue; } if (ParamType == typeof(OpenCvSharp.Point)) { var res = new OpenCvSharp.Point(currentValue, currentValue); return res; } if (ParamType?.BaseType == typeof(Enum)) { return ParamList[CurrentIntValue]; } return currentValue; } set { currentValue = (double)value; CurrentDoubleValue = (double)value; CurrentStringValue = CurrentValue.ToString(); if (ParamType?.BaseType == typeof(Enum)) { CurrentIntValue = Convert.ToInt32(value); } else { CurrentIntValue = 0; } NotifyPropertyChanged("CurrentValue"); } } private double currentDoubleValue; public double CurrentDoubleValue { get { return (double)currentDoubleValue; } set { currentDoubleValue = value; NotifyPropertyChanged("CurrentDoubleValue"); } } private string currentStringValue; public string CurrentStringValue { set { currentStringValue = "Current Value = " + value.ToString(); NotifyPropertyChanged("CurrentStringValue"); } get { return currentStringValue; } } private int currentIntValue; public int CurrentIntValue { get { return currentIntValue; } set { currentIntValue = value; NotifyPropertyChanged("CurrentIntValue"); } } // Maximum value of the parameter private double maxValue; public double MaxValue { get { return maxValue; } set { maxValue = value; NotifyPropertyChanged("MaxValue"); } } // Minimum value of the parameter private double minValue; public double MinValue { get { return minValue; } set { minValue = value; NotifyPropertyChanged("MinValue"); } } private bool isSliderEnable; public bool IsSliderEnable { get { return isSliderEnable; } set { isSliderEnable = value; NotifyPropertyChanged("IsSliderEnable"); } } private bool isComboBoxEnable; public bool IsComboBoxEnable { get { return isComboBoxEnable; } set { isComboBoxEnable = value; NotifyPropertyChanged("IsComboBoxEnable"); } } private string tag; public string Tag { get { return tag; } set { tag = value; NotifyPropertyChanged("Tag"); } } private List<object> comboList; public List<object> ComboList { get { return comboList; } set { comboList = value; NotifyPropertyChanged("ComboList"); } } private Type paramType; public Type ParamType { get { return paramType; } set { paramType = value; NotifyPropertyChanged("ParamType"); } } private List<object> paramList; public List<object> ParamList { get { return paramList; } set { paramList = value; NotifyPropertyChanged("ParamList"); } } // Converter // enum val public List<string> Selections; public int selectIndex; public bool isInitialize; public AlgorithmProperty(int index, Type type, string name, string description = "The default property description.", double max = 255, double min = 0, double cur = 0) { ParameterName = name; Description = description; MaxValue = max; MinValue = min; CurrentValue = cur > max ? max : cur < min ? min : cur; ParamType = type; if (type.BaseType != typeof(Enum)) { ParamList = null; IsComboBoxEnable = false; isSliderEnable = true; } else { var _enumval = Enum.GetValues(type).Cast<object>(); ParamList = _enumval.ToList(); IsComboBoxEnable = true; isSliderEnable = false; } selectIndex = index; SliderVisibility = Visibility.Collapsed; ComboBoxVisibility = Visibility.Collapsed; DetailsVisibility = Visibility.Collapsed; isInitialize = false; Tag = name; } public AlgorithmProperty(string name, List<string> selections, string description = "The default property description.") { parameterName = name; this.description = description; Selections = selections; selectIndex = 0; } public void updateSelectIndex(int idx) { selectIndex = idx; } public void resetCurrentValue() { currentValue = (maxValue + minValue) / 2; } } }
29.579787
175
0.44893
[ "BSD-3-Clause" ]
SSteve/opencvsharp_samples
CameraOpenCV/AlgorithmProperty.cs
11,124
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Text; using System.Windows.Forms; namespace SpeedTestClient { public partial class Form1 : Form { public Form1() { InitializeComponent(); comboBox1.SelectedIndex = 0; } private void button2_Click(object sender, EventArgs e) { int seqChan; Int32.TryParse(textBox3.Text, out seqChan); int port; Int32.TryParse(textBox2.Text, out port); Program.Connect(textBox1.Text, port, comboBox1.SelectedItem.ToString(), seqChan); } private void button1_Click(object sender, EventArgs e) { Program.DisplaySettings(); } } }
21.242424
85
0.697575
[ "MIT" ]
AntonyChurch/lidgren-network-gen3
OldSamples/LibraryTestSamples/SpeedSample/SpeedClient/Form1.cs
703
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Text.Json; using Azure.Core; namespace Azure.ResourceManager.Compute.Models { public partial class PirSharedGalleryResource { internal static PirSharedGalleryResource DeserializePirSharedGalleryResource(JsonElement element) { Optional<string> name = default; Optional<string> location = default; Optional<string> uniqueId = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("name")) { name = property.Value.GetString(); continue; } if (property.NameEquals("location")) { location = property.Value.GetString(); continue; } if (property.NameEquals("identifier")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } foreach (var property0 in property.Value.EnumerateObject()) { if (property0.NameEquals("uniqueId")) { uniqueId = property0.Value.GetString(); continue; } } continue; } } return new PirSharedGalleryResource(name.Value, location.Value, uniqueId.Value); } } }
32.925926
105
0.488189
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/compute/Azure.ResourceManager.Compute/src/Generated/Models/PirSharedGalleryResource.Serialization.cs
1,778
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace MS2Lib.Tests { [TestClass] [DeploymentItem("TestData")] public class MultiArrayFileTests { [TestMethod] public void Indexer_IndexSmallerThanSize_ExpectedResult() { var maf = new MultiArrayFile("fileArray.bin", 16, 16); var expected = new byte[] { 0x73, 0x9A, 0x8C, 0xA1, 0x16, 0x52, 0x42, 0xE1, 0xBA, 0x2F, 0xD0, 0xC9, 0x0E, 0x1B, 0xC6, 0x94 }; var actual = maf[12]; CollectionAssert.AreEquivalent(expected, actual); } [TestMethod] public void Indexer_IndexHigherThanSize_ExpectedResult() { var maf = new MultiArrayFile("fileArray.bin", 16, 16); var expected = new byte[] { 0xDE, 0x04, 0x58, 0xEB, 0xE4, 0x3A, 0xD7, 0xC6, 0x63, 0xDB, 0xF9, 0x4F, 0xEB, 0x87, 0x2D, 0xA2 }; var actual = maf[20]; CollectionAssert.AreEquivalent(expected, actual); } [TestMethod] public void Indexer_ArraySizeMatchesGivenSize_ExpectedResult() { var expected = 6; var maf = new MultiArrayFile("fileArray.bin", 10, expected); var actual = maf[20].Length; Assert.AreEqual(expected, actual); } } }
30.348837
137
0.598467
[ "MIT" ]
Miyuyami/MS2Lib
MS2Lib.Tests/MultiArrayFileTests.cs
1,307
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DS4WinWPF.DS4Control { public abstract class DS4ControlSettings { } }
16.153846
44
0.761905
[ "MIT" ]
midwan/DS4Windows
DS4Windows/DS4Control/DS4ControlSettings.cs
212
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace Checklist { static class Program { /// <summary> /// Punto di ingresso principale dell'applicazione. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
22.347826
65
0.616732
[ "MIT" ]
HarlockOfficial/awesome-hacktoberfest
Sasso Carta Forbice Lizard Spock/Checklist/Program.cs
516
C#
/************************************************************************** * MIT License * * Copyright (C) 2015 Frederic Chaxel <fchaxel@free.fr> * * 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.Collections.Generic; using System.Linq; using System.Text; using System.IO.BACnet; namespace BaCSharp { public abstract class BinaryObject : BaCSharpObject { [BaCSharpType(BacnetApplicationTags.BACNET_APPLICATION_TAG_ENUMERATED)] public virtual uint PROP_POLARITY { get { return 0; } } [BaCSharpType(BacnetApplicationTags.BACNET_APPLICATION_TAG_ENUMERATED)] public virtual uint PROP_EVENT_STATE { get { return 0; } } BacnetBitString m_PROP_STATUS_FLAGS = new BacnetBitString(); [BaCSharpType(BacnetApplicationTags.BACNET_APPLICATION_TAG_BIT_STRING)] public virtual BacnetBitString PROP_STATUS_FLAGS { get { return m_PROP_STATUS_FLAGS; } } public bool m_PROP_OUT_OF_SERVICE = false; [BaCSharpType(BacnetApplicationTags.BACNET_APPLICATION_TAG_BOOLEAN)] public virtual bool PROP_OUT_OF_SERVICE { get { return m_PROP_OUT_OF_SERVICE; } set { m_PROP_OUT_OF_SERVICE = value; m_PROP_STATUS_FLAGS.SetBit((byte)3, value); ExternalCOVManagement(BacnetPropertyIds.PROP_OUT_OF_SERVICE); } } public bool m_PRESENT_VALUE_ReadOnly = false; public uint m_PROP_PRESENT_VALUE; [BaCSharpType(BacnetApplicationTags.BACNET_APPLICATION_TAG_ENUMERATED)] public virtual uint PROP_PRESENT_VALUE { get { return m_PROP_PRESENT_VALUE; } set { if (m_PRESENT_VALUE_ReadOnly == false) { if (((value == 0) || (value == 1))) { if (value != m_PROP_PRESENT_VALUE) { m_PROP_PRESENT_VALUE = value; ExternalCOVManagement(BacnetPropertyIds.PROP_PRESENT_VALUE); } } else ErrorCode_PropertyWrite = ErrorCodes.OutOfRange; } else ErrorCode_PropertyWrite = ErrorCodes.WriteAccessDenied; } } // This property shows the same attribut as the previous, but without restriction // for internal usage, not for network callbacks public virtual uint internal_PROP_PRESENT_VALUE { get { return m_PROP_PRESENT_VALUE; } set { if (value != m_PROP_PRESENT_VALUE) { m_PROP_PRESENT_VALUE = value; ExternalCOVManagement(BacnetPropertyIds.PROP_PRESENT_VALUE); } } } public BinaryObject(BacnetObjectId ObjId, String ObjName, String Description, bool InitialValue) : base(ObjId, ObjName, Description) { m_PROP_STATUS_FLAGS.SetBit((byte)0, false); m_PROP_STATUS_FLAGS.SetBit((byte)1, false); m_PROP_STATUS_FLAGS.SetBit((byte)2, false); m_PROP_STATUS_FLAGS.SetBit((byte)3, false); m_PROP_PRESENT_VALUE = InitialValue==true ? (uint)1 : 0; } public BinaryObject() { } } }
38.082645
110
0.601997
[ "MIT" ]
DHSERVICE56/DH-SERVICRES
BacnetExplore/CodeExamples/AnotherStorageImplementation/BacnetObjects/BinaryObject.cs
4,610
C#
using System; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Abp.Authorization; using Abp.Authorization.Roles; using Abp.Authorization.Users; using Abp.Configuration; using Abp.Dependency; using Abp.Domain.Uow; using Abp.Extensions; using Abp.MultiTenancy; using Abp.Runtime.Security; using Abp.Zero.Configuration; using Microsoft.AspNet.Identity; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Authentication; namespace Abp.Zero.AspNetCore { public abstract class AbpSignInManager<TTenant, TRole, TUser> : ITransientDependency where TTenant : AbpTenant<TUser> where TRole : AbpRole<TUser>, new() where TUser : AbpUser<TUser> { public AbpUserManager<TRole, TUser> UserManager { get; set; } public AuthenticationManager AuthenticationManager => _contextAccessor.HttpContext.Authentication; private readonly IHttpContextAccessor _contextAccessor; private readonly ISettingManager _settingManager; private readonly IUnitOfWorkManager _unitOfWorkManager; private readonly IAbpZeroAspNetCoreConfiguration _configuration; protected AbpSignInManager( AbpUserManager<TRole, TUser> userManager, IHttpContextAccessor contextAccessor, ISettingManager settingManager, IUnitOfWorkManager unitOfWorkManager, IAbpZeroAspNetCoreConfiguration configuration) { UserManager = userManager; _contextAccessor = contextAccessor; _settingManager = settingManager; _unitOfWorkManager = unitOfWorkManager; _configuration = configuration; } /// <summary> /// This method can return two results: /// <see cref="SignInStatus.Success"/> indicates that user has successfully signed in. /// <see cref="SignInStatus.RequiresVerification"/> indicates that user has successfully signed in. /// </summary> /// <param name="loginResult">The login result received from <see cref="AbpLogInManager{TTenant,TRole,TUser}"/> Should be Success.</param> /// <param name="isPersistent">True to use persistent cookie.</param> /// <param name="rememberBrowser">Remember user's browser (and not use two factor auth again) or not.</param> /// <returns></returns> /// <exception cref="System.ArgumentException">loginResult.Result should be success in order to sign in!</exception> [UnitOfWork] public virtual async Task<SignInStatus> SignInOrTwoFactorAsync(AbpLoginResult<TTenant, TUser> loginResult, bool isPersistent, bool? rememberBrowser = null) { if (loginResult.Result != AbpLoginResultType.Success) { throw new ArgumentException("loginResult.Result should be success in order to sign in!"); } using (_unitOfWorkManager.Current.SetTenantId(loginResult.Tenant?.Id)) { if (IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEnabled, loginResult.Tenant?.Id)) { UserManager.As<AbpUserManager<TRole, TUser>>().RegisterTwoFactorProviders(loginResult.Tenant?.Id); if (await UserManager.GetTwoFactorEnabledAsync(loginResult.User.Id)) { if ((await UserManager.GetValidTwoFactorProvidersAsync(loginResult.User.Id)).Count > 0) { if (!await TwoFactorBrowserRememberedAsync(loginResult.User.Id.ToString(), loginResult.User.TenantId) || rememberBrowser == false) { var claimsIdentity = new ClaimsIdentity(_configuration.TwoFactorAuthenticationScheme); claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, loginResult.User.Id.ToString())); if (loginResult.Tenant != null) { claimsIdentity.AddClaim(new Claim(AbpClaimTypes.TenantId, loginResult.Tenant.Id.ToString())); } await AuthenticationManager.SignInAsync( _configuration.TwoFactorAuthenticationScheme, CreateIdentityForTwoFactor( loginResult.User, _configuration.TwoFactorAuthenticationScheme ) ); return SignInStatus.RequiresVerification; } } } } await SignInAsync(loginResult, isPersistent, rememberBrowser); return SignInStatus.Success; } } /// <param name="loginResult">The login result received from <see cref="AbpLogInManager{TTenant,TRole,TUser}"/> Should be Success.</param> /// <param name="isPersistent">True to use persistent cookie.</param> /// <param name="rememberBrowser">Remember user's browser (and not use two factor auth again) or not.</param> [UnitOfWork] public virtual async Task SignInAsync(AbpLoginResult<TTenant, TUser> loginResult, bool isPersistent, bool? rememberBrowser = null) { if (loginResult.Result != AbpLoginResultType.Success) { throw new ArgumentException("loginResult.Result should be success in order to sign in!"); } using (_unitOfWorkManager.Current.SetTenantId(loginResult.Tenant?.Id)) { await SignOutAllAsync(); if (rememberBrowser == null) { rememberBrowser = IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsRememberBrowserEnabled, loginResult.Tenant?.Id); } if (rememberBrowser == true) { await SignOutAllAndSignInAsync(loginResult.Identity, isPersistent); await AuthenticationManager.SignInAsync( _configuration.TwoFactorRememberBrowserAuthenticationScheme, CreateIdentityForTwoFactor( loginResult.User, _configuration.TwoFactorRememberBrowserAuthenticationScheme ) ); } else { await SignOutAllAndSignInAsync(loginResult.Identity, isPersistent); } } } private static ClaimsPrincipal CreateIdentityForTwoFactor(TUser user, string authType) { var claimsIdentity = new ClaimsIdentity(authType); claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())); if (user.TenantId.HasValue) { claimsIdentity.AddClaim(new Claim(AbpClaimTypes.TenantId, user.TenantId.Value.ToString())); } return new ClaimsPrincipal(claimsIdentity); } public virtual async Task SignInAsync(TUser user, bool isPersistent, bool? rememberBrowser = null) { using (_unitOfWorkManager.Current.SetTenantId(user.TenantId)) { var userIdentity = await UserManager.CreateIdentityAsync(user, _configuration.AuthenticationScheme); await SignOutAllAsync(); if (rememberBrowser == null) { rememberBrowser = IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsRememberBrowserEnabled, user.TenantId); } if (rememberBrowser == true) { await SignOutAllAndSignInAsync(userIdentity, isPersistent); await AuthenticationManager.SignInAsync( _configuration.TwoFactorRememberBrowserAuthenticationScheme, CreateIdentityForTwoFactor( user, _configuration.TwoFactorRememberBrowserAuthenticationScheme ) ); } else { await SignOutAllAndSignInAsync(userIdentity, isPersistent); } } } public virtual async Task<SignInStatus> TwoFactorSignInAsync(string provider, string code, bool isPersistent, bool rememberBrowser) { var userId = await GetVerifiedUserIdAsync(); if (userId == Guid.Empty) { return SignInStatus.Failure; } var user = await UserManager.FindByIdAsync(userId); if (user == null) { return SignInStatus.Failure; } if (await UserManager.IsLockedOutAsync(user.Id)) { return SignInStatus.LockedOut; } if (await UserManager.VerifyTwoFactorTokenAsync(user.Id, provider, code)) { await UserManager.ResetAccessFailedCountAsync(user.Id); await SignInAsync(user, isPersistent, rememberBrowser); return SignInStatus.Success; } await UserManager.AccessFailedAsync(user.Id); return SignInStatus.Failure; } public virtual async Task<bool> SendTwoFactorCodeAsync(string provider) { var userId = await GetVerifiedUserIdAsync(); if (userId == Guid.Empty) { return false; } var token = await UserManager.GenerateTwoFactorTokenAsync(userId, provider); var identityResult = await UserManager.NotifyTwoFactorTokenAsync(userId, provider, token); return identityResult == IdentityResult.Success; } public async Task<Guid> GetVerifiedUserIdAsync() { var authenticateResult = await AuthenticationManager.AuthenticateAsync(_configuration.TwoFactorAuthenticationScheme); var identUserId = IdentityExtensions.GetUserId(authenticateResult.Identity); if (!string.IsNullOrWhiteSpace(identUserId)) { return Guid.Parse(identUserId); } return Guid.Empty; } public virtual async Task<Guid?> GetVerifiedTenantIdAsync() { var authenticateResult = await AuthenticationManager.AuthenticateAsync(_configuration.TwoFactorAuthenticationScheme); return AbpZeroClaimsIdentityHelper.GetTenantId(authenticateResult?.Identity); } public async Task<bool> TwoFactorBrowserRememberedAsync(string userId, Guid? tenantId) { var result = await AuthenticationManager.AuthenticateAsync(_configuration.TwoFactorRememberBrowserAuthenticationScheme); if (result?.Identity == null) { return false; } if (IdentityExtensions.GetUserId(result.Identity) != userId) { return false; } if (AbpZeroClaimsIdentityHelper.GetTenantId(result.Identity) != tenantId) { return false; } return true; } public async Task<bool> HasBeenVerifiedAsync() { return await GetVerifiedUserIdAsync() != Guid.Empty; } private bool IsTrue(string settingName, Guid? tenantId) { return tenantId == null ? _settingManager.GetSettingValueForApplication<bool>(settingName) : _settingManager.GetSettingValueForTenant<bool>(settingName, tenantId.Value); } public async Task SignOutAllAsync() { await AuthenticationManager.SignOutAsync(_configuration.AuthenticationScheme); await AuthenticationManager.SignOutAsync(_configuration.TwoFactorAuthenticationScheme); } public async Task SignOutAllAndSignInAsync(ClaimsIdentity identity, bool rememberMe = false) { await SignOutAllAsync(); await AuthenticationManager.SignInAsync( _configuration.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties { IsPersistent = rememberMe } ); } public async Task<ExternalLoginUserInfo> GetExternalLoginUserInfo(string authSchema) { var authInfo = await AuthenticationManager.GetAuthenticateInfoAsync(authSchema); if (authInfo == null) { return null; } var claims = authInfo.Principal.Claims.ToList(); var userInfo = new ExternalLoginUserInfo { LoginInfo = new UserLoginInfo( authInfo.Properties.Items["LoginProvider"], authInfo.Principal.FindFirst(ClaimTypes.NameIdentifier)?.Value ) }; var givennameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName); if (givennameClaim != null && !givennameClaim.Value.IsNullOrEmpty()) { userInfo.Name = givennameClaim.Value; } var surnameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.Surname); if (surnameClaim != null && !surnameClaim.Value.IsNullOrEmpty()) { userInfo.Surname = surnameClaim.Value; } if (userInfo.Name == null || userInfo.Surname == null) { var nameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.Name); if (nameClaim != null) { var nameSurName = nameClaim.Value; if (!nameSurName.IsNullOrEmpty()) { var lastSpaceIndex = nameSurName.LastIndexOf(' '); if (lastSpaceIndex < 1 || lastSpaceIndex > (nameSurName.Length - 2)) { userInfo.Name = userInfo.Surname = nameSurName; } else { userInfo.Name = nameSurName.Substring(0, lastSpaceIndex); userInfo.Surname = nameSurName.Substring(lastSpaceIndex); } } } } var emailClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.Email); if (emailClaim != null) { userInfo.EmailAddress = emailClaim.Value; } return userInfo; } } }
41.142077
163
0.576438
[ "MIT" ]
aprognimak/aspnetboilerplate
src/Abp.Zero.AspNetCore/AbpSignInManager.cs
15,060
C#
using System; using System.Collections.Generic; using CommonServiceLocator; namespace LessonsSamples.Lesson6.SL { class MovieLister { private readonly IServiceLocator serviceLocator; public MovieLister() { serviceLocator = ServiceLocator.Current; } public MovieLister(IServiceLocator serviceLocator) { this.serviceLocator = serviceLocator; } public Movie[] GetMoviesDirectedBy(string director) { IMovieProvider movieProvider = serviceLocator.GetInstance<IMovieProvider>(); IEnumerable<Movie> allMovies = movieProvider.GetAll(); List<Movie> resultList = new List<Movie>(); foreach (var movie in allMovies) { if (IsDirectedBy(movie, director)) resultList.Add(movie); } return resultList.ToArray(); } private bool IsDirectedBy(Movie movie, string director) { throw new NotImplementedException(); } } }
26.268293
88
0.597957
[ "MIT" ]
iQuarc/Code-Design-Training
LessonsSamples/LessonsSamples/Lesson6/MovieLister_SL.cs
1,077
C#
/******************************************************************************* * Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.EC2; using Amazon.EC2.Model; namespace Amazon.PowerShell.Cmdlets.EC2 { /// <summary> /// Reports the current modification status of EBS volumes. /// /// /// <para> /// Current-generation EBS volumes support modification of attributes including type, /// size, and (for <code>io1</code> volumes) IOPS provisioning while either attached to /// or detached from an instance. Following an action from the API or the console to modify /// a volume, the status of the modification may be <code>modifying</code>, <code>optimizing</code>, /// <code>completed</code>, or <code>failed</code>. If a volume has never been modified, /// then certain elements of the returned <code>VolumeModification</code> objects are /// null. /// </para><para> /// You can also use CloudWatch Events to check the status of a modification to an EBS /// volume. For information about CloudWatch Events, see the <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/">Amazon /// CloudWatch Events User Guide</a>. For more information, see <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-expand-volume.html#monitoring_mods">Monitoring /// Volume Modifications"</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// </para><br/><br/>This cmdlet automatically pages all available results to the pipeline - parameters related to iteration are only needed if you want to manually control the paginated output. To disable autopagination, use -NoAutoIteration. /// </summary> [Cmdlet("Get", "EC2VolumeModification")] [OutputType("Amazon.EC2.Model.VolumeModification")] [AWSCmdlet("Calls the Amazon Elastic Compute Cloud (EC2) DescribeVolumesModifications API operation.", Operation = new[] {"DescribeVolumesModifications"}, SelectReturnType = typeof(Amazon.EC2.Model.DescribeVolumesModificationsResponse))] [AWSCmdletOutput("Amazon.EC2.Model.VolumeModification or Amazon.EC2.Model.DescribeVolumesModificationsResponse", "This cmdlet returns a collection of Amazon.EC2.Model.VolumeModification objects.", "The service call response (type Amazon.EC2.Model.DescribeVolumesModificationsResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class GetEC2VolumeModificationCmdlet : AmazonEC2ClientCmdlet, IExecutor { #region Parameter Filter /// <summary> /// <para> /// <para>The filters. Supported filters: <code>volume-id</code>, <code>modification-state</code>, /// <code>target-size</code>, <code>target-iops</code>, <code>target-volume-type</code>, /// <code>original-size</code>, <code>original-iops</code>, <code>original-volume-type</code>, /// <code>start-time</code>. </para> /// </para> /// </summary> [System.Management.Automation.Parameter(Position = 1, ValueFromPipelineByPropertyName = true)] [Alias("Filters")] public Amazon.EC2.Model.Filter[] Filter { get; set; } #endregion #region Parameter VolumeId /// <summary> /// <para> /// <para>The IDs of the volumes for which in-progress modifications will be described.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] [Alias("VolumeIds")] public System.String[] VolumeId { get; set; } #endregion #region Parameter MaxResult /// <summary> /// <para> /// <para>The maximum number of results (up to a limit of 500) to be returned in a paginated /// request.</para> /// </para> /// <para> /// <br/><b>Note:</b> In AWSPowerShell and AWSPowerShell.NetCore this parameter is used to limit the total number of items returned by the cmdlet. /// <br/>In AWS.Tools this parameter is simply passed to the service to specify how many items should be returned by each service call. /// <br/>Pipe the output of this cmdlet into Select-Object -First to terminate retrieving data pages early and control the number of items returned. /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("MaxItems","MaxResults")] public int? MaxResult { get; set; } #endregion #region Parameter NextToken /// <summary> /// <para> /// <para>The <code>nextToken</code> value returned by a previous paginated request.</para> /// </para> /// <para> /// <br/><b>Note:</b> This parameter is only used if you are manually controlling output pagination of the service API call. /// <br/>In order to manually control output pagination, use '-NextToken $null' for the first call and '-NextToken $AWSHistory.LastServiceResponse.NextToken' for subsequent calls. /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String NextToken { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'VolumesModifications'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.EC2.Model.DescribeVolumesModificationsResponse). /// Specifying the name of a property of type Amazon.EC2.Model.DescribeVolumesModificationsResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "VolumesModifications"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the VolumeId parameter. /// The -PassThru parameter is deprecated, use -Select '^VolumeId' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^VolumeId' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter NoAutoIteration /// <summary> /// By default the cmdlet will auto-iterate and retrieve all results to the pipeline by performing multiple /// service calls. If set, the cmdlet will retrieve only the next 'page' of results using the value of NextToken /// as the start point. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter NoAutoIteration { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.EC2.Model.DescribeVolumesModificationsResponse, GetEC2VolumeModificationCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.VolumeId; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute if (this.Filter != null) { context.Filter = new List<Amazon.EC2.Model.Filter>(this.Filter); } context.MaxResult = this.MaxResult; #if !MODULAR if (ParameterWasBound(nameof(this.MaxResult)) && this.MaxResult.HasValue) { WriteWarning("AWSPowerShell and AWSPowerShell.NetCore use the MaxResult parameter to limit the total number of items returned by the cmdlet." + " This behavior is obsolete and will be removed in a future version of these modules. Pipe the output of this cmdlet into Select-Object -First to terminate" + " retrieving data pages early and control the number of items returned. AWS.Tools already implements the new behavior of simply passing MaxResult" + " to the service to specify how many items should be returned by each service call."); } #endif context.NextToken = this.NextToken; if (this.VolumeId != null) { context.VolumeId = new List<System.String>(this.VolumeId); } // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members #if MODULAR public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent; #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute // create request and set iteration invariants var request = new Amazon.EC2.Model.DescribeVolumesModificationsRequest(); if (cmdletContext.Filter != null) { request.Filters = cmdletContext.Filter; } if (cmdletContext.MaxResult != null) { request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToServiceTypeInt32(cmdletContext.MaxResult.Value); } if (cmdletContext.VolumeId != null) { request.VolumeIds = cmdletContext.VolumeId; } // Initialize loop variant and commence piping var _nextToken = cmdletContext.NextToken; var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken)); var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); do { request.NextToken = _nextToken; CmdletOutput output; try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; if (!useParameterSelect) { pipelineOutput = cmdletContext.Select(response, this); } output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; _nextToken = response.NextToken; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } ProcessOutput(output); } while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken)); if (useParameterSelect) { WriteObject(cmdletContext.Select(null, this)); } return null; } #else public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent; // create request and set iteration invariants var request = new Amazon.EC2.Model.DescribeVolumesModificationsRequest(); if (cmdletContext.Filter != null) { request.Filters = cmdletContext.Filter; } if (cmdletContext.VolumeId != null) { request.VolumeIds = cmdletContext.VolumeId; } // Initialize loop variants and commence piping System.String _nextToken = null; int? _emitLimit = null; int _retrievedSoFar = 0; if (AutoIterationHelpers.HasValue(cmdletContext.NextToken)) { _nextToken = cmdletContext.NextToken; } if (AutoIterationHelpers.HasValue(cmdletContext.MaxResult)) { _emitLimit = cmdletContext.MaxResult; } var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken)); var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); do { request.NextToken = _nextToken; if (_emitLimit.HasValue) { request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToInt32(_emitLimit.Value); } CmdletOutput output; try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; if (!useParameterSelect) { pipelineOutput = cmdletContext.Select(response, this); } output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; int _receivedThisCall = response.VolumesModifications.Count; _nextToken = response.NextToken; _retrievedSoFar += _receivedThisCall; if (_emitLimit.HasValue) { _emitLimit -= _receivedThisCall; } } catch (Exception e) { if (_retrievedSoFar == 0 || !_emitLimit.HasValue) { output = new CmdletOutput { ErrorResponse = e }; } else { break; } } ProcessOutput(output); } while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken) && (!_emitLimit.HasValue || _emitLimit.Value >= 1)); if (useParameterSelect) { WriteObject(cmdletContext.Select(null, this)); } return null; } #endif public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.EC2.Model.DescribeVolumesModificationsResponse CallAWSServiceOperation(IAmazonEC2 client, Amazon.EC2.Model.DescribeVolumesModificationsRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Elastic Compute Cloud (EC2)", "DescribeVolumesModifications"); try { #if DESKTOP return client.DescribeVolumesModifications(request); #elif CORECLR return client.DescribeVolumesModificationsAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public List<Amazon.EC2.Model.Filter> Filter { get; set; } public int? MaxResult { get; set; } public System.String NextToken { get; set; } public List<System.String> VolumeId { get; set; } public System.Func<Amazon.EC2.Model.DescribeVolumesModificationsResponse, GetEC2VolumeModificationCmdlet, object> Select { get; set; } = (response, cmdlet) => response.VolumesModifications; } } }
46.683047
247
0.584158
[ "Apache-2.0" ]
5u5hma/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/EC2/Basic/Get-EC2VolumeModification-Cmdlet.cs
19,000
C#
/**** Git Credential Manager for Windows **** * * Copyright (c) Microsoft Corporation * All rights reserved. * * 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." **/ namespace Microsoft.Alm.Authentication { public interface ICredentialStore { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Namespace")] string Namespace { get; } Secret.UriNameConversion UriNameConversion { get; } void DeleteCredentials(TargetUri targetUri); Credential ReadCredentials(TargetUri targetUri); void WriteCredentials(TargetUri targetUri, Credential credentials); } }
41.404762
146
0.745831
[ "MIT" ]
lift766/Mercurial-Credential-Manager-for-Windows
Microsoft.Alm.Authentication/ICredentialStore.cs
1,741
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; namespace SpaceInvaders { /// <summary> /// This class represents the entire game, it implements the singleton pattern /// </summary> class Game { #region GameObjects management /// <summary> /// Set of all game objects currently in the game /// </summary> public HashSet<GameObject> gameObjects = new HashSet<GameObject>(); /// <summary> /// Set of new game objects scheduled for addition to the game /// </summary> private HashSet<GameObject> pendingNewGameObjects = new HashSet<GameObject>(); /// <summary> /// Schedule a new object for addition in the game. /// The new object will be added at the beginning of the next update loop /// </summary> /// <param name="gameObject">object to add</param> public void AddNewGameObject(GameObject gameObject) { pendingNewGameObjects.Add(gameObject); } #endregion #region game technical elements /// <summary> /// Size of the game area /// </summary> public Size gameSize; /// <summary> /// State of the keyboard /// </summary> public HashSet<Keys> keyPressed = new HashSet<Keys>(); #endregion #region static fields (helpers) /// <summary> /// Singleton for easy access /// </summary> public static Game game { get; private set; } /// <summary> /// A shared black brush /// </summary> private static Brush blackBrush = new SolidBrush(Color.Black); /// <summary> /// A shared simple font /// </summary> private static Font defaultFont = new Font("Times New Roman", 24, FontStyle.Bold, GraphicsUnit.Pixel); #endregion #region constructors /// <summary> /// Singleton constructor /// </summary> /// <param name="gameSize">Size of the game area</param> /// /// <returns></returns> public static Game CreateGame(Size gameSize) { if (game == null) game = new Game(gameSize); return game; } /// <summary> /// Private constructor /// </summary> /// <param name="gameSize">Size of the game area</param> private Game(Size gameSize) { this.gameSize = gameSize; } #endregion #region methods /// <summary> /// Force a given key to be ignored in following updates until the user /// explicitily retype it or the system autofires it again. /// </summary> /// <param name="key">key to ignore</param> public void ReleaseKey(Keys key) { keyPressed.Remove(key); } /// <summary> /// Draw the whole game /// </summary> /// <param name="g">Graphics to draw in</param> public void Draw(Graphics g) { foreach (GameObject gameObject in gameObjects) gameObject.Draw(this, g); } /// <summary> /// Update game /// </summary> public void Update(double deltaT) { // add new game objects gameObjects.UnionWith(pendingNewGameObjects); pendingNewGameObjects.Clear(); // if space is pressed if (keyPressed.Contains(Keys.Space)) { // create new BalleQuiTombe GameObject newObject = new BalleQuiTombe(gameSize.Width / 2, 0); // add it to the game AddNewGameObject(newObject); // release key space (no autofire) ReleaseKey(Keys.Space); } // update each game object foreach (GameObject gameObject in gameObjects) { gameObject.Update(this, deltaT); } // remove dead objects gameObjects.RemoveWhere(gameObject => !gameObject.IsAlive()); } #endregion } }
28.375
110
0.540923
[ "MIT" ]
PerretB/SpaceInvaders
SpaceInvaders/Game.cs
4,315
C#
using System; using System.Threading.Tasks; using DevUniverse.Pipelines.Core.Conditions; using DevUniverse.Pipelines.Core.Steps; namespace DevUniverse.Pipelines.Core.Builders { /// <summary> /// The pipeline builder with 1 parameter which returns the result asynchronously. /// </summary> /// <typeparam name="TParam0">The type of the 1st parameter.</typeparam> /// <typeparam name="TResult">The type of the result.</typeparam> public interface IPipelineBuilderAsync<TParam0, TResult> : IPipelineBuilderAsync, Shared.IPipelineBuilder < Func<TParam0, TResult>, IPipelineStep<TParam0, TResult>, Func<TParam0, Task<bool>>, IPipelineConditionAsync<TParam0>, IPipelineBuilderAsync<TParam0, TResult> > where TResult : Task { } }
33.68
86
0.675772
[ "MIT" ]
RomanDoskoch/Pipelines
DevUniverse.Pipelines/Sources/Core/DevUniverse.Pipelines.Core/Builders/IPipelineBuilderAsync1.cs
844
C#
namespace Arquitetura.Service.Api.Areas.HelpPage.ModelDescriptions { public class KeyValuePairModelDescription : ModelDescription { public ModelDescription KeyModelDescription { get; set; } public ModelDescription ValueModelDescription { get; set; } } }
31.333333
67
0.748227
[ "MIT" ]
willyamsann/Architecture---DDD-Net-FrameWork-4.7.2
src/Arquitetura.Service.Api/Arquitetura.Service.Api/Areas/HelpPage/ModelDescriptions/KeyValuePairModelDescription.cs
282
C#
#region License /* Copyright © 2014-2018 European Support Limited Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using Amdocs.Ginger.Repository; using Amdocs.Ginger.Common; using Amdocs.Ginger.Common.Repository; using System; using System.Collections.Generic; using System.IO; using System.Windows.Controls; using Ginger.Reports; using GingerCore; using GingerCore.Repository; namespace Ginger.Run.RunSetActions { public class RunSetActionGenerateTestNGReport : RunSetActionBase { public new static class Fields { public static string SaveResultstoFolderName = "SaveResultstoFolderName"; public static string OpenExecutionResultsFolder = "OpenExecutionResultsFolder"; public static string SaveResultsInSolutionFolderName = "SaveResultsInSolutionFolderName"; public static string SaveindividualBFReport = "SaveindividualBFReport"; public static string IsStatusByActivitiesGroup = "IsStatusByActivitiesGroup"; public static string IsStatusByActivity = "IsStatusByActivity"; } public override List<RunSetActionBase.eRunAt> GetRunOptions() { List<RunSetActionBase.eRunAt> list = new List<RunSetActionBase.eRunAt>(); list.Add(RunSetActionBase.eRunAt.ExecutionEnd); return list; } public override bool SupportRunOnConfig { get { return true; } } [IsSerializedForLocalRepository] public string SaveResultsInSolutionFolderName { get; set; } [IsSerializedForLocalRepository] public string SaveResultstoFolderName { get; set; } [IsSerializedForLocalRepository] public bool OpenExecutionResultsFolder { get; set; } [IsSerializedForLocalRepository] public bool SaveindividualBFReport { get; set; } [IsSerializedForLocalRepository] public bool IsStatusByActivitiesGroup { get; set; } private bool isStatusByActivity = true; [IsSerializedForLocalRepository] public bool IsStatusByActivity { get { return isStatusByActivity; } set { isStatusByActivity = value; } } public override void Execute(ReportInfo RI) { try { if (!string.IsNullOrEmpty(SaveResultsInSolutionFolderName)) { Reporter.ToGingerHelper(eGingerHelperMsgKey.SaveItem, null, SaveResultsInSolutionFolderName, "Execution Summary"); if (!Directory.Exists(SaveResultsInSolutionFolderName)) { Directory.CreateDirectory(SaveResultsInSolutionFolderName); } SaveBFResults(RI, SaveResultsInSolutionFolderName, IsStatusByActivitiesGroup); Reporter.CloseGingerHelper(); } else { Errors = "Folder path not provided."; Status = eRunSetActionStatus.Failed; } } catch(Exception ex) { Errors = ex.Message.ToString(); Status = eRunSetActionStatus.Failed; } } //TODO: move to Run SetAction private void SaveBFResults(ReportInfo RI, string folder, bool statusByGroupActivity) { TestNGResultReport TNGReport = new TestNGResultReport(); string xml=TNGReport.CreateReport(RI, statusByGroupActivity); System.IO.File.WriteAllLines(folder + @"\testng-results.xml", new string[] { xml } ); //TODO: let the user select file prefix } public override Page GetEditPage() { RunSetActionGenerateTestNGReportEditPage p = new RunSetActionGenerateTestNGReportEditPage(this); return p; } public override void PrepareDuringExecAction(ObservableList<GingerRunner> Gingers) { throw new NotImplementedException(); } public override string Type { get { return "Generate TestNG Report"; } } } }
36.232558
134
0.6457
[ "Apache-2.0" ]
DebasmitaGhosh/Ginger
Ginger/Ginger/Run/RunSetActions/RunSetActionGenerateTestNGReport.cs
4,675
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the sagemaker-2017-07-24.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SageMaker.Model { /// <summary> /// Container for the parameters to the CreateNotebookInstance operation. /// Creates an Amazon SageMaker notebook instance. A notebook instance is a machine learning /// (ML) compute instance running on a Jupyter notebook. /// /// /// <para> /// In a <code>CreateNotebookInstance</code> request, specify the type of ML compute instance /// that you want to run. Amazon SageMaker launches the instance, installs common libraries /// that you can use to explore datasets for model training, and attaches an ML storage /// volume to the notebook instance. /// </para> /// /// <para> /// Amazon SageMaker also provides a set of example notebooks. Each notebook demonstrates /// how to use Amazon SageMaker with a specific algorithm or with a machine learning framework. /// /// </para> /// /// <para> /// After receiving the request, Amazon SageMaker does the following: /// </para> /// <ol> <li> /// <para> /// Creates a network interface in the Amazon SageMaker VPC. /// </para> /// </li> <li> /// <para> /// (Option) If you specified <code>SubnetId</code>, Amazon SageMaker creates a network /// interface in your own VPC, which is inferred from the subnet ID that you provide in /// the input. When creating this network interface, Amazon SageMaker attaches the security /// group that you specified in the request to the network interface that it creates in /// your VPC. /// </para> /// </li> <li> /// <para> /// Launches an EC2 instance of the type specified in the request in the Amazon SageMaker /// VPC. If you specified <code>SubnetId</code> of your VPC, Amazon SageMaker specifies /// both network interfaces when launching this instance. This enables inbound traffic /// from your own VPC to the notebook instance, assuming that the security groups allow /// it. /// </para> /// </li> </ol> /// <para> /// After creating the notebook instance, Amazon SageMaker returns its Amazon Resource /// Name (ARN). You can't change the name of a notebook instance after you create it. /// </para> /// /// <para> /// After Amazon SageMaker creates the notebook instance, you can connect to the Jupyter /// server and work in Jupyter notebooks. For example, you can write code to explore a /// dataset that you can use for model training, train a model, host models by creating /// Amazon SageMaker endpoints, and validate hosted models. /// </para> /// /// <para> /// For more information, see <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works.html">How /// It Works</a>. /// </para> /// </summary> public partial class CreateNotebookInstanceRequest : AmazonSageMakerRequest { private List<string> _acceleratorTypes = new List<string>(); private List<string> _additionalCodeRepositories = new List<string>(); private string _defaultCodeRepository; private DirectInternetAccess _directInternetAccess; private InstanceType _instanceType; private string _kmsKeyId; private string _lifecycleConfigName; private string _notebookInstanceName; private string _roleArn; private RootAccess _rootAccess; private List<string> _securityGroupIds = new List<string>(); private string _subnetId; private List<Tag> _tags = new List<Tag>(); private int? _volumeSizeInGB; /// <summary> /// Gets and sets the property AcceleratorTypes. /// <para> /// A list of Elastic Inference (EI) instance types to associate with this notebook instance. /// Currently, only one instance type can be associated with a notebook instance. For /// more information, see <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/ei.html">Using /// Elastic Inference in Amazon SageMaker</a>. /// </para> /// </summary> public List<string> AcceleratorTypes { get { return this._acceleratorTypes; } set { this._acceleratorTypes = value; } } // Check to see if AcceleratorTypes property is set internal bool IsSetAcceleratorTypes() { return this._acceleratorTypes != null && this._acceleratorTypes.Count > 0; } /// <summary> /// Gets and sets the property AdditionalCodeRepositories. /// <para> /// An array of up to three Git repositories to associate with the notebook instance. /// These can be either the names of Git repositories stored as resources in your account, /// or the URL of Git repositories in <a href="https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html">AWS /// CodeCommit</a> or in any other Git repository. These repositories are cloned at the /// same level as the default repository of your notebook instance. For more information, /// see <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/nbi-git-repo.html">Associating /// Git Repositories with Amazon SageMaker Notebook Instances</a>. /// </para> /// </summary> [AWSProperty(Max=3)] public List<string> AdditionalCodeRepositories { get { return this._additionalCodeRepositories; } set { this._additionalCodeRepositories = value; } } // Check to see if AdditionalCodeRepositories property is set internal bool IsSetAdditionalCodeRepositories() { return this._additionalCodeRepositories != null && this._additionalCodeRepositories.Count > 0; } /// <summary> /// Gets and sets the property DefaultCodeRepository. /// <para> /// A Git repository to associate with the notebook instance as its default code repository. /// This can be either the name of a Git repository stored as a resource in your account, /// or the URL of a Git repository in <a href="https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html">AWS /// CodeCommit</a> or in any other Git repository. When you open a notebook instance, /// it opens in the directory that contains this repository. For more information, see /// <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/nbi-git-repo.html">Associating /// Git Repositories with Amazon SageMaker Notebook Instances</a>. /// </para> /// </summary> [AWSProperty(Min=1, Max=1024)] public string DefaultCodeRepository { get { return this._defaultCodeRepository; } set { this._defaultCodeRepository = value; } } // Check to see if DefaultCodeRepository property is set internal bool IsSetDefaultCodeRepository() { return this._defaultCodeRepository != null; } /// <summary> /// Gets and sets the property DirectInternetAccess. /// <para> /// Sets whether Amazon SageMaker provides internet access to the notebook instance. If /// you set this to <code>Disabled</code> this notebook instance will be able to access /// resources only in your VPC, and will not be able to connect to Amazon SageMaker training /// and endpoint services unless your configure a NAT Gateway in your VPC. /// </para> /// /// <para> /// For more information, see <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/appendix-additional-considerations.html#appendix-notebook-and-internet-access">Notebook /// Instances Are Internet-Enabled by Default</a>. You can set the value of this parameter /// to <code>Disabled</code> only if you set a value for the <code>SubnetId</code> parameter. /// </para> /// </summary> public DirectInternetAccess DirectInternetAccess { get { return this._directInternetAccess; } set { this._directInternetAccess = value; } } // Check to see if DirectInternetAccess property is set internal bool IsSetDirectInternetAccess() { return this._directInternetAccess != null; } /// <summary> /// Gets and sets the property InstanceType. /// <para> /// The type of ML compute instance to launch for the notebook instance. /// </para> /// </summary> [AWSProperty(Required=true)] public InstanceType InstanceType { get { return this._instanceType; } set { this._instanceType = value; } } // Check to see if InstanceType property is set internal bool IsSetInstanceType() { return this._instanceType != null; } /// <summary> /// Gets and sets the property KmsKeyId. /// <para> /// The Amazon Resource Name (ARN) of a AWS Key Management Service key that Amazon SageMaker /// uses to encrypt data on the storage volume attached to your notebook instance. The /// KMS key you provide must be enabled. For information, see <a href="https://docs.aws.amazon.com/kms/latest/developerguide/enabling-keys.html">Enabling /// and Disabling Keys</a> in the <i>AWS Key Management Service Developer Guide</i>. /// </para> /// </summary> [AWSProperty(Max=2048)] public string KmsKeyId { get { return this._kmsKeyId; } set { this._kmsKeyId = value; } } // Check to see if KmsKeyId property is set internal bool IsSetKmsKeyId() { return this._kmsKeyId != null; } /// <summary> /// Gets and sets the property LifecycleConfigName. /// <para> /// The name of a lifecycle configuration to associate with the notebook instance. For /// information about lifestyle configurations, see <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/notebook-lifecycle-config.html">Step /// 2.1: (Optional) Customize a Notebook Instance</a>. /// </para> /// </summary> [AWSProperty(Max=63)] public string LifecycleConfigName { get { return this._lifecycleConfigName; } set { this._lifecycleConfigName = value; } } // Check to see if LifecycleConfigName property is set internal bool IsSetLifecycleConfigName() { return this._lifecycleConfigName != null; } /// <summary> /// Gets and sets the property NotebookInstanceName. /// <para> /// The name of the new notebook instance. /// </para> /// </summary> [AWSProperty(Required=true, Max=63)] public string NotebookInstanceName { get { return this._notebookInstanceName; } set { this._notebookInstanceName = value; } } // Check to see if NotebookInstanceName property is set internal bool IsSetNotebookInstanceName() { return this._notebookInstanceName != null; } /// <summary> /// Gets and sets the property RoleArn. /// <para> /// When you send any requests to AWS resources from the notebook instance, Amazon SageMaker /// assumes this role to perform tasks on your behalf. You must grant this role necessary /// permissions so Amazon SageMaker can perform these tasks. The policy must allow the /// Amazon SageMaker service principal (sagemaker.amazonaws.com) permissions to assume /// this role. For more information, see <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html">Amazon /// SageMaker Roles</a>. /// </para> /// <note> /// <para> /// To be able to pass this role to Amazon SageMaker, the caller of this API must have /// the <code>iam:PassRole</code> permission. /// </para> /// </note> /// </summary> [AWSProperty(Required=true, Min=20, Max=2048)] public string RoleArn { get { return this._roleArn; } set { this._roleArn = value; } } // Check to see if RoleArn property is set internal bool IsSetRoleArn() { return this._roleArn != null; } /// <summary> /// Gets and sets the property RootAccess. /// <para> /// Whether root access is enabled or disabled for users of the notebook instance. The /// default value is <code>Enabled</code>. /// </para> /// <note> /// <para> /// Lifecycle configurations need root access to be able to set up a notebook instance. /// Because of this, lifecycle configurations associated with a notebook instance always /// run with root access even if you disable root access for users. /// </para> /// </note> /// </summary> public RootAccess RootAccess { get { return this._rootAccess; } set { this._rootAccess = value; } } // Check to see if RootAccess property is set internal bool IsSetRootAccess() { return this._rootAccess != null; } /// <summary> /// Gets and sets the property SecurityGroupIds. /// <para> /// The VPC security group IDs, in the form sg-xxxxxxxx. The security groups must be for /// the same VPC as specified in the subnet. /// </para> /// </summary> [AWSProperty(Max=5)] public List<string> SecurityGroupIds { get { return this._securityGroupIds; } set { this._securityGroupIds = value; } } // Check to see if SecurityGroupIds property is set internal bool IsSetSecurityGroupIds() { return this._securityGroupIds != null && this._securityGroupIds.Count > 0; } /// <summary> /// Gets and sets the property SubnetId. /// <para> /// The ID of the subnet in a VPC to which you would like to have a connectivity from /// your ML compute instance. /// </para> /// </summary> [AWSProperty(Max=32)] public string SubnetId { get { return this._subnetId; } set { this._subnetId = value; } } // Check to see if SubnetId property is set internal bool IsSetSubnetId() { return this._subnetId != null; } /// <summary> /// Gets and sets the property Tags. /// <para> /// An array of key-value pairs. You can use tags to categorize your AWS resources in /// different ways, for example, by purpose, owner, or environment. For more information, /// see <a href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging /// AWS Resources</a>. /// </para> /// </summary> [AWSProperty(Min=0, Max=50)] public List<Tag> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } /// <summary> /// Gets and sets the property VolumeSizeInGB. /// <para> /// The size, in GB, of the ML storage volume to attach to the notebook instance. The /// default value is 5 GB. /// </para> /// </summary> [AWSProperty(Min=5, Max=16384)] public int VolumeSizeInGB { get { return this._volumeSizeInGB.GetValueOrDefault(); } set { this._volumeSizeInGB = value; } } // Check to see if VolumeSizeInGB property is set internal bool IsSetVolumeSizeInGB() { return this._volumeSizeInGB.HasValue; } } }
41.328638
183
0.596104
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/SageMaker/Generated/Model/CreateNotebookInstanceRequest.cs
17,606
C#
using UnityEngine; using Unity.Collections; using Unity.Mathematics; using Unity.Jobs; using Unity.Burst; using System.Collections.Generic; using System; namespace MeshBuilder { using TopCellInfo = MarchingSquaresMesher.TopCellMesher.CellInfo; using CellVerts = MarchingSquaresMesher.TopCellMesher.CellVertices; using IndexSpan = MarchingSquaresMesher.TopCellMesher.IndexSpan; public partial class MarchingSquaresMesher : Builder { /// <summary> /// Generates an XZ aligned flat mesh. The filled center cells are merged according to different triangulation methods. /// </summary> /// TODO: This needed a prepass before the corner info generation and also a bit different triangle generation /// so there is a lot of code duplication in StartGeneration because it can't be handled like the other ICellMeshers /// I should refactor them after I added chunk support public struct OptimizedTopCellMesher : ICellMesher<OptimizedTopCellMesher.OptimizationCornerInfo> { public struct OptimizationCornerInfo { public TopCellMesher.TopCellInfo info; public MergedTriInfo mergedInfo; } public float lerpToExactEdge; public float heightOffset; public OptimizationMode optimizationMode; public struct OptimizationCellInfo { public bool wasChecked; public bool isFull; public bool needsVertex; public MergedTriInfo mergedInfo; } public struct MergedTriInfo { public byte triangleCount; // these are not vertex indices, but the indicies of the // corner info which holds the vertex index public int triA0Cell, triA1Cell, triA2Cell; public int triB0Cell, triB1Cell, triB2Cell; public MergedTriInfo(byte triCount, int a0, int a1, int a2, int b0, int b1, int b2) { triangleCount = triCount; triA0Cell = a0; triA1Cell = a1; triA2Cell = a2; triB0Cell = b0; triB1Cell = b1; triB2Cell = b2; } } public OptimizationCornerInfo GenerateInfo(float cornerDistance, float rightDistance, float topRightDistance, float topDistance, ref int nextVertices, ref int nextTriIndex, bool hasCellTriangles) { Debug.LogError("Not implemented!"); return default; } public OptimizationCornerInfo GenerateInfo(OptimizationCellInfo cell, float cornerDistance, float rightDistance, float topRightDistance, float topDistance, ref int nextVertex, ref int nextTriIndex, bool hasCellTriangles) { byte config = CalcConfiguration(cornerDistance, rightDistance, topRightDistance, topDistance); var info = new TopCellMesher.TopCellInfo { info = new TopCellInfo(config, cornerDistance, rightDistance, topDistance), verts = new CellVerts(-1, -1, -1), tris = new IndexSpan(nextTriIndex, 0) }; if (config == MaskFull) { if (hasCellTriangles) { nextTriIndex += cell.mergedInfo.triangleCount * 3; } if (cell.needsVertex) { info.verts.corner = nextVertex; ++nextVertex; } } else { info = TopCellMesher.GenerateInfoSimple(cornerDistance, rightDistance, topRightDistance, topDistance, ref nextVertex, ref nextTriIndex, hasCellTriangles); } return new OptimizationCornerInfo { info = info, mergedInfo = cell.mergedInfo }; } public void CalculateVertices(int x, int y, float cellSize, OptimizationCornerInfo corner, float height, NativeArray<float3> vertices) => TopCellMesher.CalculateVerticesFull(x, y, cellSize, corner.info.verts, corner.info.info, height, vertices, heightOffset, lerpToExactEdge); public void CalculateIndices(OptimizationCornerInfo bl, OptimizationCornerInfo br, OptimizationCornerInfo tr, OptimizationCornerInfo tl, NativeArray<int> triangles) => Debug.LogError("Not impemented!"); public void CalculateIndices(OptimizationCornerInfo bl, OptimizationCornerInfo br, OptimizationCornerInfo tr, OptimizationCornerInfo tl, NativeArray<int> triangles, NativeArray<OptimizationCornerInfo> corners) { int triangleIndex = bl.info.tris.start; byte config = bl.info.info.config; if (config == MaskFull) { if (bl.mergedInfo.triangleCount == 1) { triangles[triangleIndex] = Vertex(bl.mergedInfo.triA0Cell, corners); ++triangleIndex; triangles[triangleIndex] = Vertex(bl.mergedInfo.triA1Cell, corners); ++triangleIndex; triangles[triangleIndex] = Vertex(bl.mergedInfo.triA2Cell, corners); } else if (bl.mergedInfo.triangleCount == 2) { triangles[triangleIndex] = Vertex(bl.mergedInfo.triA0Cell, corners); ++triangleIndex; triangles[triangleIndex] = Vertex(bl.mergedInfo.triA1Cell, corners); ++triangleIndex; triangles[triangleIndex] = Vertex(bl.mergedInfo.triA2Cell, corners); ++triangleIndex; triangles[triangleIndex] = Vertex(bl.mergedInfo.triB0Cell, corners); ++triangleIndex; triangles[triangleIndex] = Vertex(bl.mergedInfo.triB1Cell, corners); ++triangleIndex; triangles[triangleIndex] = Vertex(bl.mergedInfo.triB2Cell, corners); } } else { TopCellMesher.CalculateIndicesSimple(config, bl.info.tris, bl.info.verts, br.info.verts, tr.info.verts, tl.info.verts, triangles); } } public bool NeedUpdateInfo => false; public void UpdateInfo(int x, int y, int cellColNum, int cellRowNum, ref OptimizationCornerInfo cell, ref OptimizationCornerInfo top, ref OptimizationCornerInfo right) { // do nothing } private static int Vertex(int index, NativeArray<OptimizationCornerInfo> corners) => corners[index].info.verts.corner; public bool CanGenerateUvs => true; public void CalculateUvs(int x, int y, int cellColNum, int cellRowNum, float cellSize, OptimizationCornerInfo corner, float uvScale, NativeArray<float3> vertices, NativeArray<float2> uvs) => TopCellMesher.TopCalculateUvs(x, y, cellColNum, cellRowNum, cellSize, corner.info.verts, uvScale, vertices, uvs); public bool CanGenerateNormals => true; public void CalculateNormals(OptimizationCornerInfo corner, OptimizationCornerInfo right, OptimizationCornerInfo top, NativeArray<float3> vertices, NativeArray<float3> normals) => TopCellMesher.SetNormals(corner.info.verts, normals, new float3(0, 1, 0)); public JobHandle StartGeneration(JobHandle lastHandle, MarchingSquaresMesher mesher) { int colNum = mesher.ColNum; int rowNum = mesher.RowNum; NativeArray<OptimizationCellInfo> optimizationCells = new NativeArray<OptimizationCellInfo>(colNum * rowNum, Allocator.TempJob); mesher.AddTemp(optimizationCells); NativeArray<OptimizationCornerInfo> corners = new NativeArray<OptimizationCornerInfo>(colNum * rowNum, Allocator.TempJob); mesher.AddTemp(corners); mesher.vertices = new NativeList<float3>(Allocator.TempJob); mesher.AddTemp(mesher.vertices); mesher.triangles = new NativeList<int>(Allocator.TempJob); mesher.AddTemp(mesher.triangles); mesher.uvs = new NativeList<float2>(Allocator.TempJob); mesher.AddTemp(mesher.uvs); mesher.normals = new NativeList<float3>(Allocator.TempJob); mesher.AddTemp(mesher.normals); bool generateUVs = mesher.ShouldGenerateUV && CanGenerateUvs; lastHandle = GenerateOptimizationData.Schedule(colNum, rowNum, optimizationMode, optimizationCells, mesher.DistanceData.RawData); lastHandle = GenerateOptimizedCorners.Schedule(colNum, rowNum, this, optimizationCells, mesher.DistanceData.RawData, corners, mesher.vertices, mesher.triangles, generateUVs, mesher.uvs, mesher.normals, lastHandle); var vertexHandle = CalculateVertices<OptimizationCornerInfo, OptimizedTopCellMesher>.Schedule(colNum, mesher.CellSize, this, corners, mesher.vertices, lastHandle); var uvHandle = vertexHandle; if (generateUVs) { uvHandle = CalculateUvs<OptimizationCornerInfo, OptimizedTopCellMesher>.Schedule(colNum, rowNum, mesher.CellSize, mesher.uvScale, this, corners, mesher.vertices, mesher.uvs, vertexHandle); } var normalHandle = CalculateNormals<OptimizationCornerInfo, OptimizedTopCellMesher>.Schedule(colNum, rowNum, this, corners, mesher.vertices, mesher.normals, vertexHandle); vertexHandle = JobHandle.CombineDependencies(vertexHandle, uvHandle, normalHandle); var trianglesHandle = CalculateOptimizedTriangles.Schedule(colNum, rowNum, this, corners, mesher.triangles, lastHandle); return JobHandle.CombineDependencies(vertexHandle, trianglesHandle); } private struct GenerateOptimizationData : IJob { public int distanceColNum; public int distanceRowNum; public OptimizationMode mode; [ReadOnly] public NativeArray<float> distances; public NativeArray<OptimizationCellInfo> cells; public void Execute() { for (int y = 0; y < distanceRowNum; ++y) { for (int x = 0; x < distanceColNum; ++x) { int index = y * distanceColNum + x; float corner = distances[index]; float right = CanStepRight(x) ? distances[index + 1] : -1; float topRight = CanStepRight(x) && CanStepUp(y) ? distances[index + 1 + distanceColNum] : -1; float top = CanStepUp(y) ? distances[index + distanceColNum] : -1; cells[index] = CreateCellInfo(corner, right, topRight, top); } } if (mode == OptimizationMode.GreedyRect) { GreedyRect.Fill(distanceColNum, distanceRowNum, cells); } else if (mode == OptimizationMode.NextLargestRect) { NextLargest.Fill(distanceColNum, distanceRowNum, cells); } else { GreedyRect.Fill(distanceColNum, distanceRowNum, cells); Debug.LogError("Unhandled optimization mode!"); } } static public JobHandle Schedule(int colNum, int rowNum, OptimizationMode optimizationMode, NativeArray<OptimizationCellInfo> optimizationCells, NativeArray<float> distances, JobHandle dependOn = default) { var optimizationJob = new GenerateOptimizationData { distanceColNum = colNum, distanceRowNum = rowNum, mode = optimizationMode, cells = optimizationCells, distances = distances }; return optimizationJob.Schedule(dependOn); } private OptimizationCellInfo CreateCellInfo(float corner, float right, float topRight, float top) => new OptimizationCellInfo { isFull = CalcConfiguration(corner, right, topRight, top) == MaskFull, wasChecked = false, needsVertex = false, mergedInfo = new MergedTriInfo(0, -1, -1, -1, -1, -1, -1) }; private bool CanStepRight(int x) => x < distanceColNum - 1; private bool CanStepUp(int y) => y < distanceRowNum - 1; struct Area { public int startX, endX, startY, endY; } private class GreedyRect { public static void Fill(int cornerColNum, int cornerRowNum, NativeArray<OptimizationCellInfo> cells) { for (int y = 0; y < cornerRowNum; ++y) { for (int x = 0; x < cornerColNum; ++x) { int index = y * cornerColNum + x; var cell = cells[index]; if (!cell.wasChecked) { if (cell.isFull) { Area area = FindFullArea(x, y, cornerColNum, cornerRowNum, cells); TriangulateArea(area, cornerColNum, cells); CheckEdgeVertices(area, cornerColNum, cells); MarkChecked(area, cornerColNum, cells); } else { MarkChecked(x, y, cornerColNum, cells); } } } } } static Area FindFullArea(int x, int y, int colNum, int rowNum, NativeArray<OptimizationCellInfo> cells) { int width = 0; int height = 0; int maxWidth = colNum - x - 1; int maxHeight = rowNum - y - 1; bool growWidth = true; bool growHeight = true; while (width < maxWidth && height < maxHeight && (growWidth || growHeight)) { if (growWidth) { int testWidth = width + 1; bool allow = true; for (int testY = y; testY <= y + height; ++testY) { if (!IsValid(x + testWidth, testY)) { allow = false; break; } } if (allow) { width = testWidth; } else { growWidth = false; } } if (growHeight) { int testHeight = height + 1; bool allow = true; for (int testX = x; testX <= x + width; ++testX) { if (!IsValid(testX, y + testHeight)) { allow = false; break; } } if (allow) { height = testHeight; } else { growHeight = false; } } } bool IsValid(int xc, int yc) { int i = yc * colNum + xc; return cells[i].isFull && !cells[i].wasChecked; } return new Area { startX = x, endX = x + width, startY = y, endY = y + height }; } } private class NextLargest { private class CellDist { public int index; public int x; public int y; public int dist; } public static void Fill(int cornerColNum, int cornerRowNum, NativeArray<OptimizationCellInfo> cells) { Queue<int> candidates = new Queue<int>(); CellDist[] cellDist = new CellDist[cells.Length]; for (int i = 0; i < cellDist.Length; ++i) { var cell = new CellDist { dist = 0, index = i, x = i % cornerColNum, y = i / cornerColNum }; if (cells[i].isFull) { cell.dist = Mathf.Min(cell.x, cell.y, cornerColNum - cell.x - 1, cornerRowNum - cell.y - 1); if (IsOnEdge(i, cell.x, cell.y)) { cell.dist = 1; candidates.Enqueue(i); } } cellDist[i] = cell; } while (candidates.Count > 0) { int i = candidates.Dequeue(); var cell = cellDist[i]; int curVal = cell.dist + 1; if (cell.x > 0) ProcessAdjacent(i - 1, curVal); if (cell.x < cornerColNum - 1) ProcessAdjacent(i + 1, curVal); if (cell.y > 0) ProcessAdjacent(i - cornerColNum, curVal); if (cell.y < cornerRowNum - 1) ProcessAdjacent(i + cornerColNum, curVal); } Array.Sort(cellDist, (CellDist a, CellDist b) => { return b.dist.CompareTo(a.dist); }); for (int i = 0; i < cellDist.Length; ++i) { CellDist distInfo = cellDist[i]; if (cells[distInfo.index].isFull && !cells[distInfo.index].wasChecked) { Area area = FindFullAreaAround(distInfo.x, distInfo.y, cornerColNum, cornerRowNum, cells); TriangulateArea(area, cornerColNum, cells); CheckEdgeVertices(area, cornerColNum, cells); MarkChecked(area, cornerColNum, cells); } } bool IsOnEdge(int i, int x, int y) { return (x > 0 && !cells[i - 1].isFull) || (x < cornerColNum - 1 && !cells[i + 1].isFull) || (y > 0 && !cells[i - cornerColNum].isFull) || (y < cornerRowNum - 1 && !cells[i + cornerColNum].isFull); } void ProcessAdjacent(int adj, int curVal) { if (cells[adj].isFull && cellDist[adj].dist > curVal) { cellDist[adj].dist = curVal; candidates.Enqueue(adj); } } } static Area FindFullAreaAround(int x, int y, int colNum, int rowNum, NativeArray<OptimizationCellInfo> cells) { int startX = x; int startY = y; int endX = x; int endY = y; bool growLeft = true; bool growRight = true; bool growUp = true; bool growDown = true; while (growLeft || growRight || growUp || growDown) { GrowHorizontal(ref growRight, ref endX, 1, startY, endY); GrowVertical(ref growUp, ref endY, 1, startX, endX); GrowHorizontal(ref growLeft, ref startX, -1, startY, endY); GrowVertical(ref growDown, ref startY, -1, startX, endX); } void GrowHorizontal(ref bool canGrow, ref int posX, int dir, int fromY, int toY) { if (canGrow) { int testX = posX + dir; canGrow = testX >= 0 && testX <= colNum - 1 && IsValidVertical(testX, fromY, toY); posX = canGrow ? testX : posX; } } void GrowVertical(ref bool canGrow, ref int posY, int dir, int fromX, int toX) { if (canGrow) { int testY = posY + dir; canGrow = testY >= 0 && testY <= rowNum - 1 && IsValidHorizontal(testY, fromX, toX); posY = canGrow ? testY : posY; } } bool IsValidVertical(int testX, int fromY, int toY) { for (int testY = fromY; testY <= toY; ++testY) { if (!IsValid(testX, testY)) { return false; } } return true; } bool IsValidHorizontal(int testY, int fromX, int toX) { for (int testX = fromX; testX <= toX; ++testX) { if (!IsValid(testX, testY)) { return false; } } return true; } bool IsValid(int xc, int yc) { int i = yc * colNum + xc; return cells[i].isFull && !cells[i].wasChecked; } return new Area { startX = startX, endX = endX, startY = startY, endY = endY }; } } static void TriangulateArea(Area area, int colNum, NativeArray<OptimizationCellInfo> cells) { ApplySimpleFullTriangles(area, colNum, cells); } static void MarkChecked(Area area, int colNum, NativeArray<OptimizationCellInfo> cells) { for (int y = area.startY; y <= area.endY; ++y) { for (int x = area.startX; x <= area.endX; ++x) { MarkChecked(x, y, colNum, cells); } } } static void CheckEdgeVertices(Area area, int colNum, NativeArray<OptimizationCellInfo> cells) { if (area.startY > 0) { for (int x = Mathf.Max(area.startX, 1); x <= area.endX; ++x) { int index = ToIndex(x, area.startY, colNum); if (NeedVertex(index)) { UpdateCell(index, cells, true); } } } if (area.startX > 0) { for (int y = Mathf.Max(area.startY, 1); y <= area.endY; ++y) { int index = ToIndex(area.startX, y, colNum); if (NeedVertex(index)) { UpdateCell(index, cells, true); } } } bool NeedVertex(int index) { int left = index - 1; int bottom = index - colNum; int bottomLeft = index - colNum - 1; return !cells[left].isFull || !cells[bottom].isFull || !cells[bottomLeft].isFull; } } static void MarkChecked(int x, int y, int colNum, NativeArray<OptimizationCellInfo> cells) { int index = ToIndex(x, y, colNum); var cell = cells[index]; cell.wasChecked = true; cells[index] = cell; } static private int ToIndex(int x, int y, int colNum) => y * colNum + x; static void ApplySimpleFullTriangles(Area area, int colNum, NativeArray<OptimizationCellInfo> cells) { int blIndex = ToIndex(area.startX, area.startY, colNum); int brIndex = ToIndex(area.endX + 1, area.startY, colNum); int tlIndex = ToIndex(area.startX, area.endY + 1, colNum); int trIndex = ToIndex(area.endX + 1, area.endY + 1, colNum); UpdateCell(blIndex, cells, true, 2, blIndex, tlIndex, trIndex, blIndex, trIndex, brIndex); UpdateCell(brIndex, cells, true); UpdateCell(tlIndex, cells, true); UpdateCell(trIndex, cells, true); } static private void UpdateCell(int index, NativeArray<OptimizationCellInfo> cells, bool needsVertex) { var cell = cells[index]; cell.needsVertex = needsVertex; cells[index] = cell; } static private void UpdateCell(int index, NativeArray<OptimizationCellInfo> cells, bool needsVertex, byte triangleCount, int a0, int a1, int a2, int b0, int b1, int b2) { var cell = cells[index]; cell.needsVertex = needsVertex; cell.mergedInfo = new MergedTriInfo(triangleCount, a0, a1, a2, b0, b1, b2); cells[index] = cell; } } [BurstCompile] private struct GenerateOptimizedCorners : IJob { private const bool HasCellTriangles = true; private const bool NoCellTriangles = false; public int distanceColNum; public int distanceRowNum; public OptimizedTopCellMesher cellMesher; [ReadOnly] public NativeArray<OptimizationCellInfo> optimizationCells; [ReadOnly] public NativeArray<float> distances; [WriteOnly] public NativeArray<OptimizationCornerInfo> corners; public NativeList<float3> vertices; public NativeList<int> indices; public bool generateUVs; public NativeList<float2> uvs; public NativeList<float3> normals; public void Execute() { int nextVertex = 0; int nextTriangleIndex = 0; // the border cases are separated to avoid boundary checking // not sure if it's worth it... // inner for (int y = 0; y < distanceRowNum - 1; ++y) { for (int x = 0; x < distanceColNum - 1; ++x) { int index = y * distanceColNum + x; float corner = distances[index]; float right = distances[index + 1]; float topRight = distances[index + 1 + distanceColNum]; float top = distances[index + distanceColNum]; var cell = optimizationCells[index]; corners[index] = cellMesher.GenerateInfo(cell, corner, right, topRight, top, ref nextVertex, ref nextTriangleIndex, HasCellTriangles); } } // top border for (int x = 0, y = distanceRowNum - 1; x < distanceColNum - 1; ++x) { int index = y * distanceColNum + x; float corner = distances[index]; float right = distances[index + 1]; var cell = optimizationCells[index]; corners[index] = cellMesher.GenerateInfo(cell, corner, right, -1, -1, ref nextVertex, ref nextTriangleIndex, NoCellTriangles); } // right border for (int x = distanceColNum - 1, y = 0; y < distanceRowNum - 1; ++y) { int index = y * distanceColNum + x; float corner = distances[index]; float top = distances[index + distanceColNum]; var cell = optimizationCells[index]; corners[index] = cellMesher.GenerateInfo(cell, corner, -1, -1, top, ref nextVertex, ref nextTriangleIndex, NoCellTriangles); } // top right corner int last = distanceColNum * distanceRowNum - 1; corners[last] = cellMesher.GenerateInfo(optimizationCells[last], distances[last], -1, -1, -1, ref nextVertex, ref nextTriangleIndex, NoCellTriangles); vertices.ResizeUninitialized(nextVertex); indices.ResizeUninitialized(nextTriangleIndex); normals.ResizeUninitialized(nextVertex); if (generateUVs) { uvs.ResizeUninitialized(nextVertex); } } static public JobHandle Schedule(int colNum, int rowNum, OptimizedTopCellMesher cellMesher, NativeArray<OptimizationCellInfo> optimizationCells, NativeArray<float> distances, NativeArray<OptimizationCornerInfo> corners, NativeList<float3> vertices, NativeList<int> triangles, bool generateUVs, NativeList<float2> uvs, NativeList<float3> normals, JobHandle dependOn) { var cornerJob = new GenerateOptimizedCorners { distanceColNum = colNum, distanceRowNum = rowNum, cellMesher = cellMesher, optimizationCells = optimizationCells, distances = distances, corners = corners, vertices = vertices, indices = triangles, generateUVs = generateUVs, uvs = uvs, normals = normals }; return cornerJob.Schedule(dependOn); } } [BurstCompile] private struct CalculateOptimizedTriangles : IJobParallelFor { public int cornerColNum; public OptimizedTopCellMesher cellMesher; [NativeDisableParallelForRestriction] [ReadOnly] public NativeArray<OptimizationCornerInfo> cornerInfos; [NativeDisableParallelForRestriction] [WriteOnly] public NativeArray<int> triangles; public void Execute(int index) { int cellColNum = cornerColNum - 1; int x = index % cellColNum; int y = index / cellColNum; index = y * cornerColNum + x; var bl = cornerInfos[index]; var br = cornerInfos[index + 1]; var tr = cornerInfos[index + 1 + cornerColNum]; var tl = cornerInfos[index + cornerColNum]; cellMesher.CalculateIndices(bl, br, tr, tl, triangles, cornerInfos); } public static JobHandle Schedule(int colNum, int rowNum, OptimizedTopCellMesher cellMesher, NativeArray<OptimizationCornerInfo> corners, NativeList<int> triangles, JobHandle dependOn) { var trianglesJob = new CalculateOptimizedTriangles { cornerColNum = colNum, cellMesher = cellMesher, cornerInfos = corners, triangles = triangles.AsDeferredJobArray() }; int cellCount = (colNum - 1) * (rowNum - 1); return trianglesJob.Schedule(cellCount, MeshTriangleBatchNum, dependOn); } } } } }
47.483039
264
0.464695
[ "MIT" ]
hbence/MeshBuilder
builders/marching_squares/OptimizedTopCellMesher.cs
34,997
C#
// Copyright (c) Gurmit Teotia. Please see the LICENSE file in the project root for license information. using System.Collections.Generic; using Amazon.SimpleWorkflow.Model; namespace Guflow.Decider { /// <summary> /// Represent activity started event. /// </summary> public class ActivityStartedEvent : ActivityEvent { internal ActivityStartedEvent(HistoryEvent activityStartedEvent, IEnumerable<HistoryEvent> allHistoryEvents) : base(activityStartedEvent) { PopulateAttributes(allHistoryEvents,activityStartedEvent.EventId,activityStartedEvent.ActivityTaskStartedEventAttributes.ScheduledEventId); IsActive = true; } } }
38.263158
152
0.709766
[ "Apache-2.0" ]
Seekatar/guflow
Guflow/Decider/Activity/ActivityStartedEvent.cs
729
C#
// <auto-generated /> using System; using System.Collections.Generic; using MarketingBox.Redistribution.Service.Postgres; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; #nullable disable namespace MarketingBox.Redistribution.Service.Postgres.Migrations { [DbContext(typeof(PgContext))] [Migration("20220504083810_updateFreq2")] partial class updateFreq2 { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasDefaultSchema("redistribution-service") .HasAnnotation("ProductVersion", "6.0.4") .HasAnnotation("Relational:MaxIdentifierLength", 63); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); modelBuilder.Entity("MarketingBox.Redistribution.Service.Domain.Models.RedistributionEntity", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id")); b.Property<long>("AffiliateId") .HasColumnType("bigint"); b.Property<long>("CampaignId") .HasColumnType("bigint"); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property<long>("CreatedBy") .HasColumnType("bigint"); b.Property<int>("DayLimit") .HasColumnType("integer"); b.Property<List<long>>("FilesIds") .HasColumnType("bigint[]"); b.Property<int>("Frequency") .HasColumnType("integer"); b.Property<string>("Metadata") .HasColumnType("text"); b.Property<int>("PortionLimit") .HasColumnType("integer"); b.Property<List<long>>("RegistrationsIds") .HasColumnType("bigint[]"); b.Property<int>("Status") .HasColumnType("integer"); b.Property<bool>("UseAutologin") .HasColumnType("boolean"); b.HasKey("Id"); b.HasIndex("CreatedBy"); b.ToTable("redistribution", "redistribution-service"); }); modelBuilder.Entity("MarketingBox.Redistribution.Service.Domain.Models.RedistributionLog", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id")); b.Property<int?>("AutologinResult") .HasColumnType("integer"); b.Property<string>("EntityId") .IsRequired() .HasColumnType("text"); b.Property<string>("Metadata") .HasColumnType("text"); b.Property<long>("RedistributionId") .HasColumnType("bigint"); b.Property<int>("Result") .HasColumnType("integer"); b.Property<DateTime?>("SendDate") .HasColumnType("timestamp with time zone"); b.Property<int>("Storage") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("RedistributionId"); b.HasIndex("Result"); b.HasIndex("SendDate"); b.HasIndex("RedistributionId", "Storage", "EntityId") .IsUnique(); b.ToTable("redistribution-log", "redistribution-service"); }); modelBuilder.Entity("MarketingBox.Redistribution.Service.Domain.Models.RegistrationsFile", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id")); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property<long>("CreatedBy") .HasColumnType("bigint"); b.Property<byte[]>("File") .IsRequired() .HasColumnType("bytea"); b.HasKey("Id"); b.HasIndex("CreatedBy"); b.ToTable("registrations-file", "redistribution-service"); }); #pragma warning restore 612, 618 } } }
34.953947
110
0.509317
[ "MIT" ]
MyJetMarketingBox/MarketingBox.Redistribution.Service
src/MarketingBox.Redistribution.Service.Postgres/Migrations/20220504083810_updateFreq2.Designer.cs
5,315
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SalesTaxApp.Data.Models { public class OrderDetail { public int OrderDetailId { get; set; } public int OrderId { get; set; } public int ProductId { get; set; } public decimal Price { get; set; } public int Amount { get; set; } public decimal Tax { get; set; } public virtual Product Product { get; set; } public virtual Order Order { get; set; } } }
18.758621
52
0.615809
[ "MIT" ]
mickfo/SalesTaxApp
Data/Models/OrderDetail.cs
546
C#
namespace p13._01.FamilyTree { using System.Collections.Generic; using System.Text; public class Person { private string name; private string birthday; private List<Person> parents; private List<Person> children; public Person(string name, string birthday) { this.Name = name; this.Birthday = birthday; this.Parents = new List<Person>(); this.Children = new List<Person>(); } public string Name { get => this.name; set => this.name = value; } public string Birthday { get => this.birthday; set => this.birthday = value; } public List<Person> Parents { get => this.parents; set => this.parents = value; } public List<Person> Children { get => this.children; set => this.children = value; } public void AddChild(Person parent) { children.Add(parent); } public void AddParent(Person child) { parents.Add(child); } public override string ToString() { StringBuilder builder = new StringBuilder(); builder .AppendLine($"{this.Name} {this.Birthday}"); return builder.ToString().TrimEnd(); } } }
21.865672
60
0.494198
[ "MIT" ]
vesy53/SoftUni
C# Advanced/C#Adanced/LabEndExercises/12.DefiningClassesExercise/p13.01.FamilyTree/Person.cs
1,467
C#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Screens.Play; namespace osu.Game.Tests.Visual { internal class TestCaseSkipButton : OsuTestCase { public override string Description => @"Skip skip skippediskip"; protected override void LoadComplete() { base.LoadComplete(); Add(new SkipButton(Clock.CurrentTime + 5000)); } } }
26.75
93
0.635514
[ "MIT" ]
akmvihfan/osu-RP
osu.Game.Tests/Visual/TestCaseSkipButton.cs
537
C#
using Zaabee.FastDfs.Common; namespace Zaabee.FastDfs.Storage { /// <summary> /// set metat data from storage server /// Reqeust /// Cmd: STORAGE_PROTO_CMD_SET_METADATA 13 /// Body: /// @ FDFS_PROTO_PKG_LEN_SIZE bytes: filename length /// @ FDFS_PROTO_PKG_LEN_SIZE bytes: meta data size /// @ 1 bytes: operation flag, /// 'O' for overwrite all old metadata /// 'M' for merge, insert when the meta item not exist, otherwise update it /// @ FDFS_GROUP_NAME_MAX_LEN bytes: group name /// @ filename bytes: filename /// @ meta data bytes: each meta data seperated by \x01, /// name and value seperated by \x02 /// Response /// Cmd: STORAGE_PROTO_CMD_RESP /// Status: 0 right other wrong /// Body: /// </summary> internal class SetMetadata : FdfsRequest { private SetMetadata() { } } }
29.8
79
0.626398
[ "MIT" ]
Mutuduxf/Zaabee.FastDFS
src/Zaabee.FastDfs/Storage/SetMetadata.cs
896
C#
using System; using System.Linq; using System.Threading.Tasks; using IdentityModel.Client; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Protocols.OpenIdConnect; namespace IdentityModel.AspNetCore.AccessTokenManagement { /// <summary> /// Options-based configuration service for token clients /// </summary> public class DefaultTokenClientConfigurationService : ITokenClientConfigurationService { private readonly AccessTokenManagementOptions _accessTokenManagementOptions; private readonly IOptionsMonitor<OpenIdConnectOptions> _oidcOptions; private readonly IAuthenticationSchemeProvider _schemeProvider; /// <summary> /// ctor /// </summary> /// <param name="accessTokenManagementOptions"></param> /// <param name="oidcOptions"></param> /// <param name="schemeProvider"></param> public DefaultTokenClientConfigurationService( IOptions<AccessTokenManagementOptions> accessTokenManagementOptions, IOptionsMonitor<OpenIdConnectOptions> oidcOptions, IAuthenticationSchemeProvider schemeProvider) { _accessTokenManagementOptions = accessTokenManagementOptions.Value; _oidcOptions = oidcOptions; _schemeProvider = schemeProvider; } /// <inheritdoc /> public virtual async Task<ClientCredentialsTokenRequest> GetClientCredentialsRequestAsync(string clientName) { ClientCredentialsTokenRequest requestDetails; // if a named client configuration was passed in, try to load it if (string.Equals(clientName, AccessTokenManagementDefaults.DefaultTokenClientName)) { // if only one client configuration exists, load that if (_accessTokenManagementOptions.Client.Clients.Count == 1) { requestDetails = _accessTokenManagementOptions.Client.Clients.First().Value; } // otherwise fall back to the scheme configuration else { var (options, configuration) = await GetOpenIdConnectSettingsAsync(_accessTokenManagementOptions.User.Scheme); requestDetails = new ClientCredentialsTokenRequest() { Address = configuration.TokenEndpoint, ClientId = options.ClientId, ClientSecret = options.ClientSecret }; if (!string.IsNullOrWhiteSpace(_accessTokenManagementOptions.Client.Scope)) { requestDetails.Scope = _accessTokenManagementOptions.Client.Scope; } var assertion = await CreateAssertionAsync(clientName); if (assertion != null) { requestDetails.ClientAssertion = assertion; } } } else { if (!_accessTokenManagementOptions.Client.Clients.TryGetValue(clientName, out requestDetails)) { throw new InvalidOperationException($"No access token client configuration found for client: {clientName}"); } } return requestDetails; } /// <inheritdoc /> public virtual async Task<RefreshTokenRequest> GetRefreshTokenRequestAsync() { var (options, configuration) = await GetOpenIdConnectSettingsAsync(_accessTokenManagementOptions.User.Scheme); var requestDetails = new RefreshTokenRequest { Address = configuration.TokenEndpoint, ClientId = options.ClientId, ClientSecret = options.ClientSecret }; var assertion = await CreateAssertionAsync(); if (assertion != null) { requestDetails.ClientAssertion = assertion; } return requestDetails; } /// <inheritdoc /> public virtual async Task<TokenRevocationRequest> GetTokenRevocationRequestAsync() { var (options, configuration) = await GetOpenIdConnectSettingsAsync(_accessTokenManagementOptions.User.Scheme); var requestDetails = new TokenRevocationRequest { Address = configuration.AdditionalData[OidcConstants.Discovery.RevocationEndpoint].ToString(), ClientId = options.ClientId, ClientSecret = options.ClientSecret }; var assertion = await CreateAssertionAsync(); if (assertion != null) { requestDetails.ClientAssertion = assertion; } return requestDetails; } /// <summary> /// Retrieves configuration from a named OpenID Connect handler /// </summary> /// <param name="schemeName"></param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public virtual async Task<(OpenIdConnectOptions options, OpenIdConnectConfiguration configuration)> GetOpenIdConnectSettingsAsync(string schemeName) { OpenIdConnectOptions options; if (string.IsNullOrWhiteSpace(schemeName)) { var scheme = await _schemeProvider.GetDefaultChallengeSchemeAsync(); if (scheme is null) { throw new InvalidOperationException("No OpenID Connect authentication scheme configured for getting client configuration. Either set the scheme name explicitly or set the default challenge scheme"); } options = _oidcOptions.Get(scheme.Name); } else { options = _oidcOptions.Get(schemeName); } OpenIdConnectConfiguration configuration; try { configuration = await options.ConfigurationManager.GetConfigurationAsync(default); } catch (Exception e) { throw new InvalidOperationException($"Unable to load OpenID configuration for configured scheme: {e.Message}"); } return (options, configuration); } /// <inheritdoc /> public virtual async Task<PasswordTokenRequest> GetPasswordGrantRequestAsync(string clientName) { PasswordTokenRequest requestDetails; // if a named client configuration was passed in, try to load it if (string.Equals(clientName, AccessTokenManagementDefaults.DefaultTokenClientName)) { // if only one client configuration exists, load that if (_accessTokenManagementOptions.Password.Clients.Count == 1) { requestDetails = _accessTokenManagementOptions.Password.Clients.First().Value; } // otherwise fall back to the scheme configuration else { var (options, configuration) = await GetOpenIdConnectSettingsAsync(_accessTokenManagementOptions.Password.Scheme); requestDetails = new PasswordTokenRequest() { Address = configuration.TokenEndpoint, ClientId = options.ClientId, ClientSecret = options.ClientSecret }; if (!string.IsNullOrWhiteSpace(_accessTokenManagementOptions.Password.Scope)) { requestDetails.Scope = _accessTokenManagementOptions.Password.Scope; } var assertion = await CreateAssertionAsync(clientName); if (assertion != null) { requestDetails.ClientAssertion = assertion; } } } else { if (!_accessTokenManagementOptions.Password.Clients.TryGetValue(clientName, out requestDetails)) { throw new InvalidOperationException($"No access token client configuration found for client: {clientName}"); } } return requestDetails; } /// <inheritdoc /> public virtual async Task<RefreshTokenRequest> GetRefreshPasswordTokenRequestAsync(string clientName) { PasswordTokenRequest configuration = await GetPasswordGrantRequestAsync(clientName); var requestDetails = new RefreshTokenRequest { Address = configuration.Address, ClientId = configuration.ClientId, ClientSecret = configuration.ClientSecret }; var assertion = await CreateAssertionAsync(); if (assertion != null) { requestDetails.ClientAssertion = assertion; } return requestDetails; } /// <summary> /// Allows injecting a client assertion into outgoing requests /// </summary> /// <param name="clientName">Name of client (if present)</param> /// <returns></returns> protected virtual Task<ClientAssertion> CreateAssertionAsync(string clientName = default) { return Task.FromResult<ClientAssertion>(null); } } }
33.738956
208
0.683014
[ "Apache-2.0" ]
gonzo-coder/IdentityModel.AspNetCore
src/AccessTokenManagement/DefaultTokenClientConfigurationService.cs
8,401
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("CleaningRobot.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CleaningRobot.Test")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("eded577f-eaef-431c-bf58-2dd9598dcc67")] // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
30.285714
56
0.756289
[ "MIT" ]
andrii-katolyk/CleaningRobot
CleaningRobot.Test/Properties/AssemblyInfo.cs
637
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.EHPC; using Aliyun.Acs.EHPC.Transform; using Aliyun.Acs.EHPC.Transform.V20180412; namespace Aliyun.Acs.EHPC.Model.V20180412 { public class ListNodesNoPagingRequest : RpcAcsRequest<ListNodesNoPagingResponse> { public ListNodesNoPagingRequest() : base("EHPC", "2018-04-12", "ListNodesNoPaging") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.EHPC.Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.EHPC.Endpoint.endpointRegionalType, null); } } private string role; private string clusterId; private string sequence; private string hostName; private bool? onlyDetached; public string Role { get { return role; } set { role = value; DictionaryUtil.Add(QueryParameters, "Role", value); } } public string ClusterId { get { return clusterId; } set { clusterId = value; DictionaryUtil.Add(QueryParameters, "ClusterId", value); } } public string Sequence { get { return sequence; } set { sequence = value; DictionaryUtil.Add(QueryParameters, "Sequence", value); } } public string HostName { get { return hostName; } set { hostName = value; DictionaryUtil.Add(QueryParameters, "HostName", value); } } public bool? OnlyDetached { get { return onlyDetached; } set { onlyDetached = value; DictionaryUtil.Add(QueryParameters, "OnlyDetached", value.ToString()); } } public override ListNodesNoPagingResponse GetResponse(UnmarshallerContext unmarshallerContext) { return ListNodesNoPagingResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
24.604839
134
0.662078
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-ehpc/EHPC/Model/V20180412/ListNodesNoPagingRequest.cs
3,051
C#
using System.Collections.Generic; namespace FiM_Compiler.CodeGeneration.GenerationData.KeywordTokenRules.UserInteractions { public class Output : TokenRule { public Output() { returnType = TokenType.UserOutput; rule = new TokenType[] { TokenType.Keyword, TokenType.Whitespace, TokenType.Value, TokenType.Punctuation }; variations = null; CheckVariations(); } public override bool IsStackMatch(List<Token> stack) { if (DefaultStackCheck(stack, rule)) { if (KeywordsDictionary.IsKeyword(KeywordType.UserOutput, stack[stack.Count - 4].Value)) { PerformRuleTransform(stack); return true; } } return false; } protected override void PerformRuleTransform(List<Token> stack) { var childsInput = new List<Token>(); childsInput.Add(stack[stack.Count - 2]); ConvertTokens(ref stack, rule.Length, returnType, childsInput); } } }
30.368421
103
0.558059
[ "MIT" ]
pavvlik777/FIM_Compiler
FiM_Compiler/FiM_Compiler/CodeGeneration/GenerationData/KeywordTokenRules/UserInteractions/Output.cs
1,156
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using System.Text.Json; using Azure.Core; using Azure.ResourceManager.Models; namespace Azure.ResourceManager.KeyVault.Models { public partial class PrivateLinkResourceData : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); writer.WritePropertyName("properties"); writer.WriteStartObject(); if (Optional.IsCollectionDefined(RequiredZoneNames)) { writer.WritePropertyName("requiredZoneNames"); writer.WriteStartArray(); foreach (var item in RequiredZoneNames) { writer.WriteStringValue(item); } writer.WriteEndArray(); } writer.WriteEndObject(); writer.WriteEndObject(); } internal static PrivateLinkResourceData DeserializePrivateLinkResourceData(JsonElement element) { Optional<AzureLocation> location = default; Optional<IReadOnlyDictionary<string, string>> tags = default; ResourceIdentifier id = default; string name = default; ResourceType type = default; SystemData systemData = default; Optional<string> groupId = default; Optional<IReadOnlyList<string>> requiredMembers = default; Optional<IList<string>> requiredZoneNames = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("location")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } location = new AzureLocation(property.Value.GetString()); continue; } if (property.NameEquals("tags")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } Dictionary<string, string> dictionary = new Dictionary<string, string>(); foreach (var property0 in property.Value.EnumerateObject()) { dictionary.Add(property0.Name, property0.Value.GetString()); } tags = dictionary; continue; } if (property.NameEquals("id")) { id = new ResourceIdentifier(property.Value.GetString()); continue; } if (property.NameEquals("name")) { name = property.Value.GetString(); continue; } if (property.NameEquals("type")) { type = new ResourceType(property.Value.GetString()); continue; } if (property.NameEquals("systemData")) { systemData = JsonSerializer.Deserialize<SystemData>(property.Value.ToString()); continue; } if (property.NameEquals("properties")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } foreach (var property0 in property.Value.EnumerateObject()) { if (property0.NameEquals("groupId")) { groupId = property0.Value.GetString(); continue; } if (property0.NameEquals("requiredMembers")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } List<string> array = new List<string>(); foreach (var item in property0.Value.EnumerateArray()) { array.Add(item.GetString()); } requiredMembers = array; continue; } if (property0.NameEquals("requiredZoneNames")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } List<string> array = new List<string>(); foreach (var item in property0.Value.EnumerateArray()) { array.Add(item.GetString()); } requiredZoneNames = array; continue; } } continue; } } return new PrivateLinkResourceData(id, name, type, systemData, Optional.ToNullable(location), Optional.ToDictionary(tags), groupId.Value, Optional.ToList(requiredMembers), Optional.ToList(requiredZoneNames)); } } }
41.123288
220
0.459527
[ "MIT" ]
damodaravadhani/azure-sdk-for-net
sdk/keyvault/Azure.ResourceManager.KeyVault/src/Generated/Models/PrivateLinkResourceData.Serialization.cs
6,004
C#
using System.Collections.Generic; namespace InterviewPreparation.MicrosoftExcercises.Easy { class ValidParentheses { public bool IsValid(string s) { var stack = new Stack<char>(); for (int i = 0; i < s.Length; i++) { switch (s[i]) { case '(': stack.Push('('); break; case '{': stack.Push('{'); break; case '[': stack.Push('['); break; case ')': if (stack.Count == 0 || stack.Pop() != '(') { return false; } break; case '}': if (stack.Count == 0 || stack.Pop() != '{') { return false; } break; case ']': if (stack.Count == 0 || stack.Pop() != '[') { return false; } break; } } return stack.Count == 0; } public bool IsValidOptimized(string s) { var mapping = new Dictionary<char, char>() { {'}', '{'}, {')', '('}, {']', '['} }; var stack = new Stack<char>(); foreach (var c in s) { if (!mapping.ContainsKey(c)) { stack.Push(c); } else { if (stack.Count == 0 || stack.Pop() != mapping[c]) { return false; } } } return stack.Count == 0; } } }
26.871795
70
0.26479
[ "Unlicense" ]
joch0a/coding-exercises
InterviewPreparation/MicrosoftExcercises/Easy/ValidParentheses.cs
2,098
C#
namespace Furion.Extras.Admin.NET.Service { /// <summary> /// OAuth用户参数 /// </summary> public class AuthUserInput { public string Uuid { get; set; } public string Username { get; set; } public string Nickname { get; set; } public string Avatar { get; set; } public string Blog { get; set; } public string Company { get; set; } public string Location { get; set; } public string Email { get; set; } public string Eemark { get; set; } public Gender Gender { get; set; } public string Source { get; set; } public AuthToken Token { get; set; } public string RawUserInfo { get; set; } } }
32.363636
47
0.567416
[ "Apache-2.0" ]
364988343/AKStreamUI
backend/Furion.Extras.Admin.NET/Service/User/Dto/AuthUserInput.cs
722
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace SharpNes { class EmulatorConfiguration { public static EmulatorConfiguration Instance { get { return instance; } } public string this[string key] { get { string value = ConfigurationManager.AppSettings[key]; return value == null ? "" : value; } set { try { var configurationFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var settings = configurationFile.AppSettings.Settings; if (settings[key] == null) settings.Add(key, value); else settings[key].Value = value; configurationFile.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection(configurationFile.AppSettings.SectionInformation.Name); } catch (ConfigurationErrorsException) { MessageBox.Show("Unabled to update application configuration", "Recently Used Files", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private EmulatorConfiguration() { } private static EmulatorConfiguration instance = new EmulatorConfiguration(); } }
29.482143
111
0.548153
[ "MIT" ]
colinvella/EmuNes
EmuNES/EmulatorConfiguration.cs
1,653
C#
namespace Turtle.Actions { public class Move : IAction { } }
12
31
0.611111
[ "MIT" ]
Meldow/TurtleSimple
Turtle/Actions/Move.cs
72
C#
namespace IssueTrackingSystem2.Web.InputModels.Issue { using AutoMapper; using IssueTrackingSystem2.Common.Enums; using IssueTrackingSystem2.Services.Mapping; using IssueTrackingSystem2.Services.Models; using IssueTrackingSystem2.Web.Infrastructure.Attributes; using IssueTrackingSystem2.Web.InputModels.Milestone; using System; using System.ComponentModel.DataAnnotations; public class IssueCreateInputModel : IMapTo<IssueServiceModel>, IHaveCustomMappings { [Required] public string Title { get; set; } [Required] public string Description { get; set; } [Display(Name = "Due Date")] [DateTimeValidation(nameof(DueDate))] public DateTime DueDate { get; set; } [Required] public string Priority { get; set; } [Required] [EnumValidation(typeof(IssueStatuses))] public string Status { get; set; } [Required] [Display(Name = "Issue Assignee")] public string AssigneeId { get; set; } public string Comment { get; set; } public MilestoneConciseInputModel Milestone { get; set; } public void CreateMappings(IProfileExpression configuration) { configuration.CreateMap<IssueCreateInputModel, IssueServiceModel>() .ForMember(dest => dest.Status, mapper => mapper.MapFrom(src => new StatusServiceModel() { Name = src.Status, Type = StatusTypes.Issue.ToString(), })); } } }
31.54
104
0.634115
[ "MIT" ]
r-petrov/Issue-Tracking-System-2
src/Web/IssueTrackingSystem2.Web.InputModels/Issue/IssueCreateInputModel.cs
1,579
C#
using CMS.Core; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Web.Mvc; namespace HBS.LocalizedValidationAttributes.Kentico.MVC { /// <summary> /// Localized version of the RequiredAttribute, Error Message can contain resolve {$ localizedstring.key $}'s, and the resolved string can contain a {0} for the Property Name /// </summary> public class LocalizedRequiredAttribute : RequiredAttribute, IClientValidatable { public override string FormatErrorMessage(string name) { ILocalizationService _LocalizationService = DependencyResolver.Current.GetService<ILocalizationService>(); return String.Format(CultureInfo.CurrentCulture, _LocalizationService.LocalizeString(ErrorMessageString, CultureInfo.CurrentCulture.Name), name); } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { yield return new ModelClientValidationRequiredRule(FormatErrorMessage(metadata.GetDisplayName())); } } }
44.384615
178
0.758232
[ "MIT" ]
KenticoDevTrev/KenticoLocalizedValidationAttributes
LocalizedValidationAttributes/LocalizedAttributes/LocalizedRequiredAttribute.cs
1,156
C#
using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Records; using System.Linq; using System.Threading.Tasks; using YesSql; namespace Lombiq.HelpfulLibraries.Libraries.Contents { public class ContentVersionNumberService : IContentVersionNumberService { private readonly ISession _session; public ContentVersionNumberService(ISession session) => _session = session; public Task<int> GetLatestVersionNumberAsync(string contentItemId) => _session.Query<ContentItem, ContentItemIndex>() .Where(index => index.ContentItemId == contentItemId) .CountAsync(); public async Task<int> GetCurrentVersionNumberAsync(string contentItemId, string contentItemVersionId) { var versions = (await _session.Query<ContentItem, ContentItemIndex>() .Where(index => index.ContentItemId == contentItemId) .OrderByDescending(index => index.CreatedUtc) .ListAsync()) .ToList(); return versions.FindLastIndex(version => version.ContentItemVersionId == contentItemVersionId) + 1; } } }
38.125
112
0.659016
[ "BSD-3-Clause" ]
CityofSantaMonica/Helpful-Libraries
Lombiq.HelpfulLibraries/Libraries/Contents/ContentVersionNumberService.cs
1,222
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Csla; using Csla.DiffGram; namespace Test.Library { [Serializable] public class LineItemEdit : DiffBase<LineItemEdit> { public static readonly PropertyInfo<int> IdProperty = RegisterProperty<int>(c => c.Id); public int Id { get { return GetProperty(IdProperty); } set { SetProperty(IdProperty, value); } } public static readonly PropertyInfo<string> ProductNameProperty = RegisterProperty<string>(c => c.ProductName); public string ProductName { get { return GetProperty(ProductNameProperty); } set { SetProperty(ProductNameProperty, value); } } private void Child_Fetch(int id, int line) { using (BypassPropertyChecks) { Id = line; ProductName = "Product " + id + line; } } protected override void ExportTo(Csla.DiffGram.DataItem dto) { dto.DataFields.Add(new Csla.DiffGram.DataField { Name="Id", Value=Id }); dto.DataFields.Add(new Csla.DiffGram.DataField { Name = "ProductName", Value = ProductName }); } protected override void ImportFrom(Csla.DiffGram.DataItem dto) { // update changed values here } } }
26.229167
115
0.669579
[ "MIT" ]
Crown0815/csla
Samples/NET/cs/Csla.DiffGram/Test.Library/LineItemEdit.cs
1,261
C#
using Imagin.Common.Linq; using System; using System.Globalization; using System.Windows.Data; namespace Imagin.Common.Converters { /// <summary> /// /// </summary> [ValueConversion(typeof(string), typeof(string))] public class FileExtensionConverter : IValueConverter { /// <summary> /// /// </summary> /// <param name="value"></param> /// <param name="targetType"></param> /// <param name="parameter"></param> /// <param name="culture"></param> /// <returns></returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) return string.Empty; var Value = (string)value; if (Value.IsNullOrEmpty()) return string.Empty; return Value.GetExtension(); } /// <summary> /// /// </summary> /// <param name="value"></param> /// <param name="targetType"></param> /// <param name="parameter"></param> /// <param name="culture"></param> /// <returns></returns> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } }
29.5
103
0.550847
[ "BSD-2-Clause" ]
OkumaScott/Imagin.NET
Imagin.Common.WPF/_Converters/FileExtensionConverter.cs
1,300
C#
namespace Security.HMAC { using System; public class HmacMiddlewareOptions { public TimeSpan ClockSkew { get; set; } public string RequestProtocol { get; set; } public string Host { get; set; } } }
21.727273
51
0.619247
[ "MIT" ]
ifbaltics/hmac-security
src/NetCore/HmacMiddlewareOptions.cs
241
C#
namespace Oyooni.Server.Data.BusinessModels.Interfaces { /// <summary> /// Represents a base entity contract /// </summary> public interface IBaseEntity { /// <summary> /// The identifier of the entity /// </summary> string Id { get; set; } } }
21.571429
55
0.562914
[ "MIT" ]
Oyooni5245/Oyooni
Source/Oyooni/Oyooni.Server/Data/BusinessModels/Interfaces/IBaseEntity.cs
304
C#
using System.Collections.Generic; using System.Collections.ObjectModel; using Newtonsoft.Json; using Nuka.Core.Middlewares.InfoSelf.Providers; namespace Nuka.Core.Models { public class InfoSelfResponse { public IEnumerable<string> Tags { get; set; } public string ClusterServiceName { get; set; } public string ClusterServiceVersion { get; set; } public string ClusterServiceType { get; set; } public IEnumerable<string> ApiVersions { get; set; } public IDictionary<string, string> Context { get; set; } public ReadOnlyDictionary<string, double> Metrics { get; set; } } }
35.555556
71
0.698438
[ "MIT" ]
Nuka-World/Nuka.Alpha
Nuka.Core/Models/InfoSelfResponse.cs
640
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Mim.V6301 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(TypeName="PORX_IN090101UK31.Message", Namespace="urn:hl7-org:v3")] [System.Xml.Serialization.XmlRootAttribute("PORX_IN090101UK31", Namespace="urn:hl7-org:v3", IsNullable=false)] public partial class PORX_IN090101UK31Message { private II idField; private TS creationTimeField; private CS versionCodeField; private II interactionIdField; private CS processingCodeField; private CS processingModeCodeField; private CS acceptAckCodeField; private MCCI_MT010101UK12CommunicationFunctionRcv[] communicationFunctionRcvField; private MCCI_MT010101UK12CommunicationFunctionSnd communicationFunctionSndField; private PORX_IN090101UK31ControlActEvent controlActEventField; private string typeField; private string[] typeIDField; private string[] realmCodeField; private string nullFlavorField; private static System.Xml.Serialization.XmlSerializer serializer; public PORX_IN090101UK31Message() { this.typeField = "Message"; } public II id { get { return this.idField; } set { this.idField = value; } } public TS creationTime { get { return this.creationTimeField; } set { this.creationTimeField = value; } } public CS versionCode { get { return this.versionCodeField; } set { this.versionCodeField = value; } } public II interactionId { get { return this.interactionIdField; } set { this.interactionIdField = value; } } public CS processingCode { get { return this.processingCodeField; } set { this.processingCodeField = value; } } public CS processingModeCode { get { return this.processingModeCodeField; } set { this.processingModeCodeField = value; } } public CS acceptAckCode { get { return this.acceptAckCodeField; } set { this.acceptAckCodeField = value; } } [System.Xml.Serialization.XmlElementAttribute("communicationFunctionRcv")] public MCCI_MT010101UK12CommunicationFunctionRcv[] communicationFunctionRcv { get { return this.communicationFunctionRcvField; } set { this.communicationFunctionRcvField = value; } } public MCCI_MT010101UK12CommunicationFunctionSnd communicationFunctionSnd { get { return this.communicationFunctionSndField; } set { this.communicationFunctionSndField = value; } } public PORX_IN090101UK31ControlActEvent ControlActEvent { get { return this.controlActEventField; } set { this.controlActEventField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string type { get { return this.typeField; } set { this.typeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string[] typeID { get { return this.typeIDField; } set { this.typeIDField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string[] realmCode { get { return this.realmCodeField; } set { this.realmCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string nullFlavor { get { return this.nullFlavorField; } set { this.nullFlavorField = value; } } private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(PORX_IN090101UK31Message)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current PORX_IN090101UK31Message object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an PORX_IN090101UK31Message object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output PORX_IN090101UK31Message object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out PORX_IN090101UK31Message obj, out System.Exception exception) { exception = null; obj = default(PORX_IN090101UK31Message); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out PORX_IN090101UK31Message obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static PORX_IN090101UK31Message Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((PORX_IN090101UK31Message)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current PORX_IN090101UK31Message object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an PORX_IN090101UK31Message object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output PORX_IN090101UK31Message object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out PORX_IN090101UK31Message obj, out System.Exception exception) { exception = null; obj = default(PORX_IN090101UK31Message); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out PORX_IN090101UK31Message obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static PORX_IN090101UK31Message LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this PORX_IN090101UK31Message object /// </summary> public virtual PORX_IN090101UK31Message Clone() { return ((PORX_IN090101UK31Message)(this.MemberwiseClone())); } #endregion } }
37.657224
1,358
0.556233
[ "MIT" ]
Kusnaditjung/MimDms
src/Mim.V6301/Generated/PORX_IN090101UK31Message.cs
13,293
C#
// <auto-generated /> using BusinessContacts.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace BusinessContacts.Migrations { [DbContext(typeof(BusinessContactsContext))] [Migration("20210130170008_InitialContactDataMigration")] partial class InitialContactDataMigration { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .UseIdentityColumns() .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.2"); modelBuilder.Entity("BusinessContacts.Models.ContactDataModel", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("Address") .IsRequired() .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.Property<string>("BussinessTaxNumber") .IsRequired() .HasMaxLength(11) .HasColumnType("nvarchar(11)"); b.Property<string>("City") .IsRequired() .HasMaxLength(30) .HasColumnType("nvarchar(30)"); b.Property<string>("CompanyName") .IsRequired() .HasMaxLength(30) .HasColumnType("nvarchar(30)"); b.Property<string>("ContactPerson") .HasMaxLength(40) .HasColumnType("nvarchar(40)"); b.Property<string>("Email") .HasColumnType("nvarchar(max)"); b.Property<string>("MobilePhone") .HasMaxLength(30) .HasColumnType("nvarchar(30)"); b.HasKey("Id"); b.ToTable("ContactDataModel"); }); #pragma warning restore 612, 618 } } }
35.15942
80
0.5169
[ "MIT" ]
kbratkovic/BusinessContacts
BusinessContacts/Migrations/20210130170008_InitialContactDataMigration.Designer.cs
2,428
C#
namespace P08_CondenseArrayToNumber { using System; using System.Linq; public class Program { public static void Main() { int[] nums = Console.ReadLine().Split().Select(int.Parse).ToArray(); int firstLength = nums.Length - 1; int finalResult = 0; if (nums.Length == 1) { Console.WriteLine(nums[0]); return; } for (int i = 0; i < firstLength; i++) { int[] condensed = new int[nums.Length - 1]; for (int j = 0; j < condensed.Length; j++) { condensed[j] = nums[j] + nums[j + 1]; } nums = condensed; finalResult = condensed[0]; } Console.WriteLine(finalResult); } } }
23.864865
80
0.433749
[ "MIT" ]
MertYumer/Tech-Module-2018
03. Arrays/P08-CondenseArrayToNumber/Program.cs
885
C#
 namespace DocsToolset { partial class Ui { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Ui)); this.pbxSpinner = new System.Windows.Forms.PictureBox(); this.btnRun = new System.Windows.Forms.Button(); this.btnBrowseDocPath = new System.Windows.Forms.Button(); this.txtDocFilePath = new DocsToolset.TextBoxX(); this.btnFocus = new System.Windows.Forms.Button(); this.tabReplace = new System.Windows.Forms.TabPage(); this.label1 = new System.Windows.Forms.Label(); this.cmbReplaceOptions = new System.Windows.Forms.ComboBox(); this.tabFindOptions = new System.Windows.Forms.TabPage(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.txtPhraseFilePath = new DocsToolset.TextBoxX(); this.btnOpenPhraseFile = new System.Windows.Forms.Button(); this.btnBrowsePhraseFile = new System.Windows.Forms.Button(); this.tabFind = new System.Windows.Forms.TabPage(); this.dgv = new System.Windows.Forms.DataGridView(); this.tabControl = new System.Windows.Forms.TabControl(); ((System.ComponentModel.ISupportInitialize)(this.pbxSpinner)).BeginInit(); this.tabReplace.SuspendLayout(); this.tabFindOptions.SuspendLayout(); this.groupBox1.SuspendLayout(); this.tabFind.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dgv)).BeginInit(); this.tabControl.SuspendLayout(); this.SuspendLayout(); // // pbxSpinner // this.pbxSpinner.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.pbxSpinner.Image = global::DocsToolset.Properties.Resources.spinner; this.pbxSpinner.Location = new System.Drawing.Point(794, 340); this.pbxSpinner.Name = "pbxSpinner"; this.pbxSpinner.Size = new System.Drawing.Size(31, 31); this.pbxSpinner.TabIndex = 19; this.pbxSpinner.TabStop = false; this.pbxSpinner.Visible = false; // // btnRun // this.btnRun.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnRun.Location = new System.Drawing.Point(781, 339); this.btnRun.Name = "btnRun"; this.btnRun.Size = new System.Drawing.Size(57, 33); this.btnRun.TabIndex = 18; this.btnRun.Text = "Run"; this.btnRun.UseVisualStyleBackColor = true; // // btnBrowseDocPath // this.btnBrowseDocPath.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnBrowseDocPath.BackgroundImage = global::DocsToolset.Properties.Resources.folder; this.btnBrowseDocPath.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center; this.btnBrowseDocPath.FlatAppearance.BorderColor = System.Drawing.Color.DimGray; this.btnBrowseDocPath.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnBrowseDocPath.Location = new System.Drawing.Point(744, 341); this.btnBrowseDocPath.Name = "btnBrowseDocPath"; this.btnBrowseDocPath.Size = new System.Drawing.Size(29, 29); this.btnBrowseDocPath.TabIndex = 17; this.btnBrowseDocPath.UseVisualStyleBackColor = true; // // txtDocFilePath // this.txtDocFilePath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtDocFilePath.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.None; this.txtDocFilePath.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.None; this.txtDocFilePath.BackColor = System.Drawing.SystemColors.Window; this.txtDocFilePath.BorderColor = System.Drawing.SystemColors.Window; this.txtDocFilePath.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtDocFilePath.CharacterCasing = System.Windows.Forms.CharacterCasing.Normal; this.txtDocFilePath.Hint = "Document path"; this.txtDocFilePath.Location = new System.Drawing.Point(14, 341); this.txtDocFilePath.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.txtDocFilePath.MaxLength = 32767; this.txtDocFilePath.Multiline = false; this.txtDocFilePath.Name = "txtDocFilePath"; this.txtDocFilePath.Padding = new System.Windows.Forms.Padding(4, 6, 0, 0); this.txtDocFilePath.Password = false; this.txtDocFilePath.ReadOnly = false; this.txtDocFilePath.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtDocFilePath.SelectedText = ""; this.txtDocFilePath.SelectionLength = 0; this.txtDocFilePath.SelectionStart = 0; this.txtDocFilePath.Size = new System.Drawing.Size(731, 29); this.txtDocFilePath.TabIndex = 20; this.txtDocFilePath.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtDocFilePath.WordWrap = false; // // btnFocus // this.btnFocus.Location = new System.Drawing.Point(10, 10); this.btnFocus.Name = "btnFocus"; this.btnFocus.Size = new System.Drawing.Size(1, 1); this.btnFocus.TabIndex = 21; this.btnFocus.UseVisualStyleBackColor = true; // // tabReplace // this.tabReplace.Controls.Add(this.label1); this.tabReplace.Controls.Add(this.cmbReplaceOptions); this.tabReplace.Location = new System.Drawing.Point(4, 29); this.tabReplace.Name = "tabReplace"; this.tabReplace.Padding = new System.Windows.Forms.Padding(3); this.tabReplace.Size = new System.Drawing.Size(844, 303); this.tabReplace.TabIndex = 2; this.tabReplace.Text = "Replace"; this.tabReplace.UseVisualStyleBackColor = true; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(26, 25); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(107, 20); this.label1.TabIndex = 1; this.label1.Text = "Replace action"; // // cmbReplaceOptions // this.cmbReplaceOptions.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbReplaceOptions.FormattingEnabled = true; this.cmbReplaceOptions.Location = new System.Drawing.Point(30, 49); this.cmbReplaceOptions.Name = "cmbReplaceOptions"; this.cmbReplaceOptions.Size = new System.Drawing.Size(491, 28); this.cmbReplaceOptions.TabIndex = 0; // // tabFindOptions // this.tabFindOptions.Controls.Add(this.groupBox1); this.tabFindOptions.Location = new System.Drawing.Point(4, 29); this.tabFindOptions.Name = "tabFindOptions"; this.tabFindOptions.Padding = new System.Windows.Forms.Padding(3); this.tabFindOptions.Size = new System.Drawing.Size(844, 303); this.tabFindOptions.TabIndex = 1; this.tabFindOptions.Text = "Find options"; this.tabFindOptions.UseVisualStyleBackColor = true; // // groupBox1 // this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox1.Controls.Add(this.txtPhraseFilePath); this.groupBox1.Controls.Add(this.btnOpenPhraseFile); this.groupBox1.Controls.Add(this.btnBrowsePhraseFile); this.groupBox1.Location = new System.Drawing.Point(21, 19); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(803, 115); this.groupBox1.TabIndex = 1; this.groupBox1.TabStop = false; this.groupBox1.Text = "Edit phrase file"; // // txtPhraseFilePath // this.txtPhraseFilePath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtPhraseFilePath.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.None; this.txtPhraseFilePath.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.None; this.txtPhraseFilePath.BackColor = System.Drawing.SystemColors.Window; this.txtPhraseFilePath.BorderColor = System.Drawing.SystemColors.Window; this.txtPhraseFilePath.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtPhraseFilePath.CharacterCasing = System.Windows.Forms.CharacterCasing.Normal; this.txtPhraseFilePath.Hint = "Phrase file path"; this.txtPhraseFilePath.Location = new System.Drawing.Point(19, 35); this.txtPhraseFilePath.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.txtPhraseFilePath.MaxLength = 32767; this.txtPhraseFilePath.Multiline = false; this.txtPhraseFilePath.Name = "txtPhraseFilePath"; this.txtPhraseFilePath.Padding = new System.Windows.Forms.Padding(4, 6, 0, 0); this.txtPhraseFilePath.Password = false; this.txtPhraseFilePath.ReadOnly = false; this.txtPhraseFilePath.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtPhraseFilePath.SelectedText = ""; this.txtPhraseFilePath.SelectionLength = 0; this.txtPhraseFilePath.SelectionStart = 0; this.txtPhraseFilePath.Size = new System.Drawing.Size(739, 29); this.txtPhraseFilePath.TabIndex = 23; this.txtPhraseFilePath.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtPhraseFilePath.WordWrap = false; // // btnOpenPhraseFile // this.btnOpenPhraseFile.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); this.btnOpenPhraseFile.Location = new System.Drawing.Point(18, 71); this.btnOpenPhraseFile.Name = "btnOpenPhraseFile"; this.btnOpenPhraseFile.Size = new System.Drawing.Size(58, 32); this.btnOpenPhraseFile.TabIndex = 9; this.btnOpenPhraseFile.Text = "Open"; this.btnOpenPhraseFile.UseVisualStyleBackColor = true; // // btnBrowsePhraseFile // this.btnBrowsePhraseFile.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnBrowsePhraseFile.BackgroundImage = global::DocsToolset.Properties.Resources.folder; this.btnBrowsePhraseFile.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center; this.btnBrowsePhraseFile.FlatAppearance.BorderColor = System.Drawing.Color.Gray; this.btnBrowsePhraseFile.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnBrowsePhraseFile.Location = new System.Drawing.Point(757, 35); this.btnBrowsePhraseFile.Name = "btnBrowsePhraseFile"; this.btnBrowsePhraseFile.Size = new System.Drawing.Size(29, 29); this.btnBrowsePhraseFile.TabIndex = 8; this.btnBrowsePhraseFile.UseVisualStyleBackColor = true; // // tabFind // this.tabFind.Controls.Add(this.dgv); this.tabFind.Location = new System.Drawing.Point(4, 29); this.tabFind.Name = "tabFind"; this.tabFind.Padding = new System.Windows.Forms.Padding(3); this.tabFind.Size = new System.Drawing.Size(844, 303); this.tabFind.TabIndex = 0; this.tabFind.Text = "Find"; this.tabFind.UseVisualStyleBackColor = true; // // dgv // this.dgv.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dgv.BackgroundColor = System.Drawing.Color.White; this.dgv.Location = new System.Drawing.Point(11, 12); this.dgv.Name = "dgv"; this.dgv.RowTemplate.Height = 25; this.dgv.Size = new System.Drawing.Size(822, 284); this.dgv.TabIndex = 11; // // tabControl // this.tabControl.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tabControl.Controls.Add(this.tabFind); this.tabControl.Controls.Add(this.tabFindOptions); this.tabControl.Controls.Add(this.tabReplace); this.tabControl.HotTrack = true; this.tabControl.Location = new System.Drawing.Point(0, 0); this.tabControl.Name = "tabControl"; this.tabControl.SelectedIndex = 0; this.tabControl.Size = new System.Drawing.Size(852, 336); this.tabControl.TabIndex = 0; // // Ui // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(852, 377); this.Controls.Add(this.txtDocFilePath); this.Controls.Add(this.pbxSpinner); this.Controls.Add(this.btnRun); this.Controls.Add(this.btnBrowseDocPath); this.Controls.Add(this.btnFocus); this.Controls.Add(this.tabControl); this.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.MinimumSize = new System.Drawing.Size(700, 300); this.Name = "Ui"; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show; this.Text = "Docs toolset"; ((System.ComponentModel.ISupportInitialize)(this.pbxSpinner)).EndInit(); this.tabReplace.ResumeLayout(false); this.tabReplace.PerformLayout(); this.tabFindOptions.ResumeLayout(false); this.groupBox1.ResumeLayout(false); this.tabFind.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dgv)).EndInit(); this.tabControl.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.PictureBox pbxSpinner; private System.Windows.Forms.Button btnRun; private System.Windows.Forms.Button btnBrowseDocPath; private DocsToolset.TextBoxX txtDocFilePath; private System.Windows.Forms.Button btnFocus; private System.Windows.Forms.TabPage tabReplace; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox cmbReplaceOptions; private System.Windows.Forms.TabPage tabFindOptions; private System.Windows.Forms.GroupBox groupBox1; private DocsToolset.TextBoxX txtPhraseFilePath; private System.Windows.Forms.Button btnOpenPhraseFile; private System.Windows.Forms.Button btnBrowsePhraseFile; private System.Windows.Forms.TabPage tabFind; private System.Windows.Forms.DataGridView dgv; private System.Windows.Forms.TabControl tabControl; } }
54.965839
167
0.634047
[ "MIT" ]
trishores/docs-toolset
code/docs-toolset-proj/Classes/Ui.Designer.cs
17,701
C#
using System.Collections.Generic; using PANDA.Data.Models; namespace PANDA.Services { public interface IUserService { User GetUserLogin(string username, string password); List<string> GetAllUsernames(); bool CreateUser(User user); } }
24.636364
60
0.697417
[ "MIT" ]
RosenDev/SoftuniLearning
C#Web/SIS/PANDA.Services/IUserService.cs
273
C#
// Copyright 2007-2019 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Registration { public class ConsumerEndpointRegistrationConfigurator<TConsumer> : EndpointRegistrationConfigurator<TConsumer>, IConsumerEndpointRegistrationConfigurator<TConsumer> where TConsumer : class, IConsumer { } }
41.318182
82
0.751375
[ "ECL-2.0", "Apache-2.0" ]
AOrlov/MassTransit
src/MassTransit/Configuration/Registration/ConsumerEndpointRegistrationConfigurator.cs
909
C#
namespace ClearHl7.Codes.V270 { /// <summary> /// HL7 Version 2 Table 0261 - Location Equipment. /// </summary> /// <remarks>https://www.hl7.org/fhir/v2/0261</remarks> public enum CodeLocationEquipment { /// <summary> /// EEG - Electro-Encephalogram. /// </summary> ElectroEncephalogram, /// <summary> /// EKG - Electro-Cardiogram. /// </summary> ElectroCardiogram, /// <summary> /// INF - Infusion pump. /// </summary> InfusionPump, /// <summary> /// IVP - IV pump. /// </summary> IvPump, /// <summary> /// OXY - Oxygen. /// </summary> Oxygen, /// <summary> /// SUC - Suction. /// </summary> Suction, /// <summary> /// VEN - Ventilator. /// </summary> Ventilator, /// <summary> /// VIT - Vital signs monitor. /// </summary> VitalSignsMonitor } }
20.78
59
0.454283
[ "MIT" ]
kamlesh-microsoft/clear-hl7-net
src/ClearHl7.Codes/V270/CodeLocationEquipment.cs
1,041
C#
using System.Reflection; using System.Runtime.InteropServices; using System.Resources; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TrackMe.WinPhoneNative")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TrackMe.WinPhoneNative")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e7a2f712-3100-48e2-b047-f9413efa0a04")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: NeutralResourcesLanguageAttribute("en-US")]
38.297297
84
0.751588
[ "MIT" ]
PGSSoft/TrackMe-Mobile
TrackMe.WinPhoneNative/Properties/AssemblyInfo.cs
1,420
C#
namespace Microsoft.eShopWeb; public class CatalogSettings { public string CatalogBaseUrl { get; set; } public string ServiceBusConnectionString { get; set; } public string DeliverReserveFunctionUrl { get; set; } }
25.444444
58
0.746725
[ "MIT" ]
Eduard-Zhyzneuski-Epam/eShopOnWeb
src/ApplicationCore/CatalogSettings.cs
231
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Diagnostics; using System.Threading; using StarkPlatform.CodeAnalysis.Stark.Extensions; using StarkPlatform.CodeAnalysis.Stark.Syntax; using StarkPlatform.CodeAnalysis.Editor.Implementation.Highlighting; using StarkPlatform.CodeAnalysis.Text; namespace StarkPlatform.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters { [ExportHighlighter(LanguageNames.Stark)] internal class LoopHighlighter : AbstractKeywordHighlighter { protected override bool IsHighlightableNode(SyntaxNode node) => node.IsContinuableConstruct(); protected override IEnumerable<TextSpan> GetHighlightsForNode( SyntaxNode node, CancellationToken cancellationToken) { var spans = new List<TextSpan>(); switch (node) { case DoStatementSyntax doStatement: HighlightDoStatement(doStatement, spans); break; case ForStatementSyntax2 forStatement: HighlightForStatement(forStatement, spans); break; case ForStatementSyntax forEachStatement: HighlightForEachStatement(forEachStatement, spans); break; case WhileStatementSyntax whileStatement: HighlightWhileStatement(whileStatement, spans); break; } HighlightRelatedKeywords(node, spans, highlightBreaks: true, highlightContinues: true); return spans; } private void HighlightDoStatement(DoStatementSyntax statement, List<TextSpan> spans) { spans.Add(statement.DoKeyword.Span); spans.Add(statement.WhileKeyword.Span); spans.Add(EmptySpan(statement.EosToken.Span.End)); } private void HighlightForStatement(ForStatementSyntax2 statement, List<TextSpan> spans) { spans.Add(statement.ForKeyword.Span); } private void HighlightForEachStatement(ForStatementSyntax statement, List<TextSpan> spans) { spans.Add(statement.ForEachKeyword.Span); } private void HighlightWhileStatement(WhileStatementSyntax statement, List<TextSpan> spans) { spans.Add(statement.WhileKeyword.Span); } /// <summary> /// Finds all breaks and continues that are a child of this node, and adds the appropriate spans to the spans list. /// </summary> private void HighlightRelatedKeywords(SyntaxNode node, List<TextSpan> spans, bool highlightBreaks, bool highlightContinues) { Debug.Assert(highlightBreaks || highlightContinues); if (highlightBreaks && node is BreakStatementSyntax breakStatement) { spans.Add(breakStatement.BreakKeyword.Span); spans.Add(EmptySpan(breakStatement.EosToken.Span.End)); } else if (highlightContinues && node is ContinueStatementSyntax continueStatement) { spans.Add(continueStatement.ContinueKeyword.Span); spans.Add(EmptySpan(continueStatement.EosToken.Span.End)); } else { foreach (var child in node.ChildNodes()) { var highlightBreaksForChild = highlightBreaks && !child.IsBreakableConstruct(); var highlightContinuesForChild = highlightContinues && !child.IsContinuableConstruct(); // Only recurse if we have anything to do if (highlightBreaksForChild || highlightContinuesForChild) { HighlightRelatedKeywords(child, spans, highlightBreaksForChild, highlightContinuesForChild); } } } } } }
40.333333
161
0.629315
[ "Apache-2.0" ]
stark-lang/stark-roslyn
src/EditorFeatures/Stark/Highlighting/KeywordHighlighters/LoopHighlighter.cs
4,116
C#
/* This software known as 'Distrib' is under the GNU GPL v2. License This license can be found at: http://www.gnu.org/licenses/gpl-2.0.html Unless this software has been made available to you under the terms of an alternative license by Clint Pearson, your use of this software is dependent upon compliance with the GNU GPL v2. license. This software is the sole copyright of Clint Pearson Contact: clintkpearson@gmail.com This software is provided with NO WARRANTY at all, explicit or implied. If you wish to contact me about the software / licensing you can reach me at distribgrid@gmail.com */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Distrib.Data.Transport { /// <summary> /// Data transport point attribute for properties /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public sealed class DataTransportPointAttribute : Attribute { private readonly DataTransportPointDirection _direction = DataTransportPointDirection.Both; private readonly IReadOnlyList<string> _keywords = null; public DataTransportPointAttribute( DataTransportPointDirection direction, string[] keywords) { _direction = direction; _keywords = keywords.ToList().AsReadOnly(); } /// <summary> /// Gets the direction for the data point /// </summary> public DataTransportPointDirection Direction { get { return _direction; } } /// <summary> /// Gets the keywords for the data point /// </summary> public IReadOnlyList<string> Keywords { get { return _keywords; } } } }
30.71875
101
0.623601
[ "MIT" ]
ckpearson/Distrib
Distrib/Distrib/Data/Transport/DataTransportPointAttribute.cs
1,968
C#
/* Write a program that reads a text file and inserts line numbers in front of each of its lines. The result should be written to another text file.*/ using System; using System.IO; namespace _03.LineNumbers { class LineNumbers { static void Main(string[] args) { String fileName = @"..\..\FreeFile.txt"; String fileSource1 = @"..\..\Test1.txt"; StreamWriter writer = new StreamWriter(fileName); using (writer) { StreamReader reader = new StreamReader(fileSource1); using (reader) { int lineNumber = 1; String line = reader.ReadLine(); while (line != null) { writer.Write(lineNumber + " "); writer.WriteLine(line); line = reader.ReadLine(); lineNumber++; } } } StreamReader reader3 = new StreamReader(fileName); using (reader3) { String line = reader3.ReadLine(); while (line != null) { Console.WriteLine(line); line = reader3.ReadLine(); } } } } }
29.234043
98
0.443959
[ "MIT" ]
IvanGrigorov/CSharp-2
TextFiles/03. LineNumbers/LineNumbers.cs
1,376
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Controls; using System.IO; namespace PWPlanner.TileTypes { public class Special : Tile { public override int ZIndex { get { return 10; } } public Special() { } public Special(Image image) { Image = image; } public static SpecialName GetSpecialNameByString(string fileName) { fileName = Path.GetFileNameWithoutExtension(fileName); if (Enum.TryParse(fileName, out SpecialName name)) { return name; } else { return SpecialName.NONE; } } public override Tile Clone(Image image) { var fg = new Special(); fg.Image = image; fg.TileName = this.TileName; return fg; } public enum SpecialName { Acid, Acidalt, DarkFog, DarkFogalt, DarkRiverWater, DarkRiverWateralt, FakeBlood, FakeBloodalt, Fog, Fogalt, Quicksand, Quicksandalt, Water, Wateralt, Acidfall1, Acidfall2, Acidfall3, Bloodfall, Bloodfall1, Bloodfall2, Bloodfall3, DarkRiverWaterfall, DarkRiverWaterfall1, DarkRiverWaterfall2, DarkRiverWaterfall3, Waterfall, Waterfall1, Waterfall2, Waterfall3, ClearWater, ClearWateralt, ClearWaterfall, ClearWaterfall1, ClearWaterfall2, ClearWaterfall3, Oil, Oilalt, OilFall, OilFall1, OilFall2, OilFall3, NONE } } }
21.915789
73
0.472622
[ "MIT" ]
ColdUnwanted/PWPlanner
PWPlanner/TileTypes/Special.cs
2,084
C#
namespace QuizEMI.Data.Models { using System; using System.Collections.Generic; using QuizEMI.Data.Common.Enumerations; using QuizEMI.Data.Common.Models; public class Event : BaseDeletableModel<string> { public Event() { this.Id = Guid.NewGuid().ToString(); this.Results = new HashSet<Result>(); this.EventsGroups = new HashSet<EventGroup>(); this.ScheduledJobs = new HashSet<ScheduledJob>(); } public string Name { get; set; } public string CreatorId { get; set; } public Status Status { get; set; } public virtual ApplicationUser Creator { get; set; } public DateTime ActivationDateAndTime { get; set; } public TimeSpan DurationOfActivity { get; set; } public string QuizId { get; set; } public virtual Quiz Quiz { get; set; } public string QuizName { get; set; } public virtual ICollection<Result> Results { get; set; } public virtual ICollection<EventGroup> EventsGroups { get; set; } public virtual ICollection<ScheduledJob> ScheduledJobs { get; set; } } }
26.659091
76
0.618926
[ "MIT" ]
BENALIsalahEDDINE/QuizEMI
Data/QuizEMI.Data.Models/Event.cs
1,175
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Daisy.SaveAsDAISY { public partial class ConversionProgress : Form { public ConversionProgress() { InitializeComponent(); } public void addMessage(string message) { this.MessageTextArea.Text = this.MessageTextArea.Text + ( message.EndsWith("\n") ? message : message + "\r\n"); this.MessageTextArea.Refresh(); } public delegate void CancelClickListener(); private event CancelClickListener cancelButtonClicked; public void setCancelClickListener(CancelClickListener cancelAction) { cancelButtonClicked = cancelAction; } private void CancelButton_Click(object sender, EventArgs e) { if (cancelButtonClicked != null) cancelButtonClicked(); this.Close(); } private void ConversionProgress_FormClosing(Object sender, FormClosingEventArgs e) { if (cancelButtonClicked != null) cancelButtonClicked(); } } }
28.404762
123
0.66974
[ "BSD-3-Clause" ]
daisy/word-save-as-daisy
Common/DaisyAddinLib/ConversionProgress.cs
1,195
C#
using System; using System.Runtime.Serialization; namespace Xtrimmer.SqlDatabaseBuilder { [Serializable] public class InvalidDatabaseIdentifierException : ArgumentException { public InvalidDatabaseIdentifierException() { } public InvalidDatabaseIdentifierException(string message) : base(message) { } public InvalidDatabaseIdentifierException(string message, Exception inner) : base(message, inner) { } protected InvalidDatabaseIdentifierException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
23.482759
102
0.646109
[ "Apache-2.0" ]
Xtrimmer/SqlDatabaseBuilder
src/SqlDatabaseBuilder/Exceptions/InvalidDatabaseIdentifierException.cs
683
C#
using System; using System.Collections.Generic; using Umbraco.Core.Models; using Umbraco.Core.Models.ContentEditing; using Umbraco.Core.Models.Membership; namespace Umbraco.Web.ContentApps { public class ContentInfoContentAppFactory : IContentAppFactory { // see note on ContentApp private const int Weight = +100; private ContentApp _contentApp; private ContentApp _mediaApp; public ContentApp GetContentAppFor(object o, IEnumerable<IReadOnlyUserGroup> userGroups) { switch (o) { case IContent _: return _contentApp ?? (_contentApp = new ContentApp { Alias = "umbInfo", Name = "Info", Icon = "icon-info", View = "views/content/apps/info/info.html", Weight = Weight }); case IMedia _: return _mediaApp ?? (_mediaApp = new ContentApp { Alias = "umbInfo", Name = "Info", Icon = "icon-info", View = "views/media/apps/info/info.html", Weight = Weight }); default: throw new NotSupportedException($"Object type {o.GetType()} is not supported here."); } } } }
31.744681
105
0.484584
[ "MIT" ]
0Neji/Umbraco-CMS
src/Umbraco.Web/ContentApps/ContentInfoContentAppFactory.cs
1,494
C#
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using JetBrains.Annotations; using Nuke.Common.OutputSinks; using Nuke.Common.Utilities; namespace Nuke.Common.CI.TravisCI { [UsedImplicitly] [ExcludeFromCodeCoverage] internal class TravisCIOutputSink : AnsiColorOutputSink { public TravisCIOutputSink() : base( traceCode: "37", informationCode: "36;1", warningCode: "33;1", errorCode: "31;1", successCode: "32;1") { } public override IDisposable WriteBlock(string text) { return DelegateDisposable.CreateBracket( () => Console.WriteLine($"travis_fold:start:{text}"), () => Console.WriteLine($"travis_fold:end:{text}")); } } }
27.527778
69
0.608476
[ "MIT" ]
Janek91/common
source/Nuke.Common/CI/TravisCI/TravisCIOutputSink.cs
991
C#
namespace NetFusion.Bootstrap.Plugins { /// <summary> /// Marker interface used to identify interfaces implemented by modules that /// provide access to information it manages. All, modules implementing an /// interface derived from this type will be added to the dependency-injection /// container as singletons of the derived interface type. /// </summary> public interface IPluginModuleService { } }
33.923077
82
0.712018
[ "MIT" ]
grecosoft/NetFusion
netfusion/src/Core/NetFusion.Bootstrap/Plugins/IPluginModuleService.cs
443
C#
using Dfc.ProviderPortal.TribalExporter.Interfaces; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Dfc.ProviderPortal.TribalExporter.Helpers { public static class DelimitedFileHelper { public static IEnumerable<IDelimitedLine> ReadLines(TextReader reader, IDelimitedFileSettings settings) { if (reader == null) throw new ArgumentNullException(nameof(reader)); if (settings == null) throw new ArgumentNullException(nameof(settings)); try { var number = settings.IsFirstRowHeaders ? 0 : -1; while (reader.Peek() > -1) { number++; yield return ReadLine(number, reader.ReadLine(), settings); } } finally { if (reader != null) reader.Close(); } } public static IEnumerable<IDelimitedLine> ReadLines(string path, IDelimitedFileSettings settings) { if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("Cannot be null, empty or only whitespace.", nameof(path)); if (settings == null) throw new ArgumentNullException(nameof(settings)); if (!File.Exists(path)) throw new FileNotFoundException(nameof(path)); using (var streamReader = new StreamReader(path)) { return ReadLines(streamReader, settings); } } internal static IDelimitedLine ReadLine(int number, string line, IDelimitedFileSettings settings) { if (number < 0) throw new ArgumentOutOfRangeException(nameof(number), "Must be greater then 0."); if (settings == null) throw new ArgumentNullException(nameof(settings)); var fields = new List<IDelimitedField>(); var fieldCount = 0; var chars = line == null ? new char[] { } : line.ToCharArray(); var buffer = new StringBuilder(); var inQuotes = false; for (var i = 0; i < chars.Length; i++) { if (inQuotes) { var nextChar = (i + 1) == chars.Length ? chars[i] : chars[i + 1]; if (chars[i] == '"' && nextChar == settings.DelimitingCharacter || chars[i] == '"' && nextChar == chars[i] && (i + 1) == chars.Length || chars[i] == '"' && Environment.NewLine.Contains(nextChar.ToString())) { fieldCount++; fields.Add(new DelimitedField(fieldCount, buffer.ToString(), inQuotes)); buffer = new StringBuilder(); inQuotes = false; } else { buffer.Append(chars[i]); } } else { if (chars[i] == settings.DelimitingCharacter) { var prevChar = i == 0 ? chars[i] : chars[i - 1]; if (buffer.Length > 0 || prevChar == settings.DelimitingCharacter) { fieldCount++; fields.Add(new DelimitedField(fieldCount, buffer.ToString())); buffer = new StringBuilder(); } continue; } else if (Environment.NewLine.Contains(chars[i].ToString())) { break; } else if (chars[i] == '"' && buffer.Length == 0) { inQuotes = true; } else { buffer.Append(chars[i]); } } } var lastChar = chars.Length == 0 ? default(char) : chars[chars.Length - 1]; if (buffer.Length > 0 || lastChar == settings.DelimitingCharacter) { fieldCount++; fields.Add(new DelimitedField(fieldCount, buffer.ToString())); } return new DelimitedLine(number, fields); } } }
37.862069
136
0.472222
[ "MIT" ]
SkillsFundingAgency/dfc-providerportal-tribalexporter
src/Dfc.ProviderPortal.TribalExporter/Helpers/DelimitedFileHelper.cs
4,394
C#
namespace Perpetuum { public class GlobalConfiguration { public string ListenerIP { get; set; } public int ListenerPort { get; set; } public string GameRoot { get; set; } public string WebServiceIP { get; set; } public string PersonalConfig { get; set; } public string ConnectionString { get; set; } public string RelayName => "relay"; public bool EnableUpnp { get; set; } public int SteamAppID { get; set; } public byte[] SteamKey { get; set; } public string ResourceServerURL { get; set; } public bool EnableDev { get; set; } public CorporationConfiguration Corporation { get; set; } public bool StartServerInAdminOnlyMode { get; set; } } }
28.62963
65
0.614489
[ "MIT" ]
OpenPerpetuum/PerpetuumServer
src/Perpetuum/GlobalConfiguration.cs
773
C#
/* Copyright 2010-present MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace MongoDB.Driver { /// <summary> /// Flags used with the Eval method in MongoDatabase. /// </summary> [Flags] public enum EvalFlags { /// <summary> /// No flags. /// </summary> None = 0, /// <summary> /// Do not take a write lock. /// </summary> NoLock = 1 } }
26.694444
74
0.649324
[ "Apache-2.0" ]
591094733/mongo-csharp-driver
src/MongoDB.Driver.Legacy/EvalFlags.cs
961
C#
using System; using LionFire.Persistence; namespace LionFire.Serialization { //public interface IDeserializerScorer : ISerializerScorerBase<DeserializePersistenceOperation, DeserializePersistenceContext> //{ // //float ScoreForStrategy(SerializationStrategyPreference preference, Lazy<DeserializationPersistenceOperation> operation = null, DeserializationPersistenceContext context = null); //} //public static class ISerializationProviderExtensions //{ // // FUTURE? // //public static ISerializationStrategy ResolveStrategy(this IHasSerializationStrategies serializationProvider, SerializerSelectionContext context) => serializationProvider.GetStrategies(context).FirstOrDefault().Strategy; //} }
41.555556
231
0.78877
[ "MIT" ]
LionFire/Core
src/LionFire.Persistence/Serialization/Scorers/delete-IDeserializerScorer.cs
750
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using SmartHunter.Game.Helpers; namespace SmartHunter.Core.Helpers { public static class MemoryHelper { static List<PointerTrace> s_UniquePointerTraces = new List<PointerTrace>(); static WindowsApi.RegionPageProtection[] ProtectionExclusions { get { return new WindowsApi.RegionPageProtection[] { WindowsApi.RegionPageProtection.PAGE_GUARD, WindowsApi.RegionPageProtection.PAGE_NOACCESS }; } } static bool CheckProtection(uint flags) { var protectionFlags = (WindowsApi.RegionPageProtection)flags; foreach (var protectionExclusion in ProtectionExclusions) { if (protectionFlags.HasFlag(protectionExclusion)) { return false; } } return true; } public static List<ulong> FindPatternAddresses(Process process, AddressRange addressRange, BytePattern pattern, bool stopAfterFirst) { List<ulong> matchAddresses = new List<ulong>(); ulong currentAddress = addressRange.Start; while (currentAddress < addressRange.End && !process.HasExited) { WindowsApi.MEMORY_BASIC_INFORMATION64 memoryRegion; if (WindowsApi.VirtualQueryEx(process.Handle, (IntPtr)currentAddress, out memoryRegion, (uint)Marshal.SizeOf(typeof(WindowsApi.MEMORY_BASIC_INFORMATION64))) > 0 && memoryRegion.RegionSize > 0 && memoryRegion.State == (uint)WindowsApi.RegionPageState.MEM_COMMIT && CheckProtection(memoryRegion.Protect)) { var regionStartAddress = memoryRegion.BaseAddress; if (addressRange.Start > regionStartAddress) { regionStartAddress = addressRange.Start; } var regionEndAddress = memoryRegion.BaseAddress + memoryRegion.RegionSize; if (addressRange.End < regionEndAddress) { regionEndAddress = addressRange.End; } if (regionEndAddress <= regionStartAddress) { regionEndAddress = regionStartAddress + addressRange.Size; } ulong regionBytesToRead = regionEndAddress - regionStartAddress; byte[] regionBytes = new byte[regionBytesToRead]; if (process.HasExited) { break; } int lpNumberOfBytesRead = 0; WindowsApi.ReadProcessMemory(process.Handle, (IntPtr)regionStartAddress, regionBytes, regionBytes.Length, ref lpNumberOfBytesRead); var matchIndices = FindPatternMatchIndices(regionBytes, pattern, stopAfterFirst); foreach (var matchIndex in matchIndices) { var matchAddress = regionStartAddress + (ulong)matchIndex; matchAddresses.Add(matchAddress); pattern.Config.LastResultAddress = matchAddress.ToString("X8"); Log.WriteLine($"Found '{pattern.Config.Name}' at address 0x{matchAddress.ToString("X8")}"); //TODO: Rimetti } if (matchAddresses.Any() && stopAfterFirst) { break; } } currentAddress = memoryRegion.BaseAddress + memoryRegion.RegionSize; } return matchAddresses; } // KMP algorithm modified to search bytes with a nullable/wildcard search static List<int> FindPatternMatchIndices(byte[] bytes, BytePattern pattern, bool stopAfterFirst) { List<int> matchedIndices = new List<int>(); int textLength = bytes.Length; int patternLength = pattern.Bytes.Length; if (textLength == 0 || patternLength == 0 || textLength < patternLength) { return matchedIndices; } int[] longestPrefixSuffices = new int[patternLength]; GetLongestPrefixSuffices(pattern, ref longestPrefixSuffices); int textIndex = 0; int patternIndex = 0; while (textIndex < textLength) { if (!pattern.Bytes[patternIndex].HasValue // Ignore compare if the pattern index is nullable - this treats it like a * wildcard || bytes[textIndex] == pattern.Bytes[patternIndex]) { textIndex++; patternIndex++; } if (patternIndex == patternLength) { matchedIndices.Add(textIndex - patternIndex); patternIndex = longestPrefixSuffices[patternIndex - 1]; if (stopAfterFirst) { break; } } else if (textIndex < textLength && (pattern.Bytes[patternIndex].HasValue // Only compare disparity if the pattern byte isn't a null wildcard && bytes[textIndex] != pattern.Bytes[patternIndex])) { if (patternIndex != 0) { patternIndex = longestPrefixSuffices[patternIndex - 1]; } else { textIndex++; } } } return matchedIndices; } static void GetLongestPrefixSuffices(BytePattern pattern, ref int[] longestPrefixSuffices) { int patternLength = pattern.Bytes.Length; int length = 0; int patternIndex = 1; longestPrefixSuffices[0] = 0; while (patternIndex < patternLength) { if (pattern.Bytes[patternIndex] == pattern.Bytes[length]) { length++; longestPrefixSuffices[patternIndex] = length; patternIndex++; } else { if (length == 0) { longestPrefixSuffices[patternIndex] = 0; patternIndex++; } else { length = longestPrefixSuffices[length - 1]; } } } } public static List<AddressRange> DivideAddressRange(AddressRange addressRange, int divisionCount) { List<AddressRange> addressRangeDivisions = new List<AddressRange>(); ulong start = addressRange.Start; ulong end = addressRange.End; ulong range = end - start; float rangePerDivision = range / (float)divisionCount; end = start + (ulong)Math.Ceiling(rangePerDivision); for (int index = 0; index < divisionCount; ++index) { ulong startAddress = start; ulong endAddress = end; if (index + 1 == divisionCount) { endAddress = addressRange.End; } addressRangeDivisions.Add(new AddressRange(startAddress, endAddress - startAddress)); start = end; end += (ulong)Math.Floor(rangePerDivision); } return addressRangeDivisions; } public static T Read<T>(Process process, ulong address) where T : struct { byte[] bytes = new byte[Marshal.SizeOf(typeof(T))]; int lpNumberOfBytesRead = 0; WindowsApi.ReadProcessMemory(process.Handle, (IntPtr)address, bytes, bytes.Length, ref lpNumberOfBytesRead); T result; GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); } finally { handle.Free(); } return result; } public static string ReadString(Process process, ulong address, uint length) { byte[] bytes = new byte[length]; int lpNumberOfBytesRead = 0; WindowsApi.ReadProcessMemory(process.Handle, (IntPtr)address, bytes, bytes.Length, ref lpNumberOfBytesRead); int nullTerminatorIndex = Array.FindIndex(bytes, (byte b) => b == 0); if (nullTerminatorIndex >= 0) { Array.Resize(ref bytes, nullTerminatorIndex); return Encoding.UTF8.GetString(bytes); } return null; } public static ulong ReadMultiLevelPointer(bool traceUniquePointers, Process process, ulong address, params long[] offsets) { PointerTrace trace = new PointerTrace(); ulong result = address; foreach (var offset in offsets) { var readResult = Read<ulong>(process, address); result = (ulong)((long)readResult + offset); trace.Levels.Add(new PointerTraceLevel(address, readResult, offset, result)); address = result; } if (traceUniquePointers && !s_UniquePointerTraces.Contains(trace)) { s_UniquePointerTraces.Add(trace); Log.WriteLine($"Unique Pointer Trace:\r\n{trace}"); } return result; } public static ulong LoadEffectiveAddressRelative(Process process, ulong address) { const uint opcodeLength = 3; const uint paramLength = 4; const uint instructionLength = opcodeLength + paramLength; uint operand = Read<uint>(process, address + opcodeLength); ulong operand64 = operand; // 64 bit relative addressing if (operand64 > Int32.MaxValue) { operand64 = 0xffffffff00000000 | operand64; } return address + operand64 + instructionLength; } public static uint ReadStaticOffset(Process process, ulong address) { const uint opcodeLength = 3; return Read<uint>(process, address + opcodeLength); } } }
35.491909
176
0.525212
[ "MIT" ]
1342293181/SmartHunter
SmartHunter/Core/Helpers/MemoryHelper.cs
10,967
C#
using UnityEngine; using UnityEngine.EventSystems; using System.Collections.Generic; namespace Unicessing { /** @class UGraphics @lang_en -------- Base class for drawing by Unicessing @end_lang @lang_jp -------- Unicessingによる描画の基本クラス @end_lang */ public class UGraphics : UResource { #region Settings [SerializeField] private float DefaultDepthStep = 0.003f; public float width = 1.0f; public float height = 1.0f; #endregion #region System Variables public class UStyle { public Color fillColor; public Color strokeColor; public ColorMode colorMode; public Vector4 colorScale; public Vector4 invColorScale; public int layer; public int layerMask; public float depth; public float depthStep; public Texture texture; public float textSize; public float textScale; public float textQuality; public int textAlignX; public int textAlignY; public int rectMode; public int ellipseMode; public int imageMode; public int sphereDetailKey; public const int sphereDetailKeyDefault = (30 << 16) | 30; public Font font; public UMaterials.BlendMode blendMode; public Material customMaterial; public bool isLighting; public bool isStroke; public bool isFill; public UStyle(UGraphics g) { init(g); } public UStyle Clone() { return (UStyle)MemberwiseClone(); } public void init(UGraphics g) { fillColor = Color.white; strokeColor = Color.white; colorMode = ColorMode.RGB; const float inv255 = 1.0f / 255.0f; colorScale = new Vector4(255, 255, 255, 255); invColorScale = new Vector4(inv255, inv255, inv255, inv255); layer = (g != null) ? g.gameObject.layer : -1; layerMask = 1 << layer; depth = 0.0f; depthStep = (g != null) ? g.DefaultDepthStep : 0.003f; texture = null; textSize = 13; textScale = 1.0f; textQuality = 1.0f; textAlignX = LEFT; textAlignY = BASELINE; rectMode = CORNER; ellipseMode = CENTER; imageMode = CORNER; sphereDetailKey = sphereDetailKeyDefault; font = null; blendMode = UMaterials.BlendMode.Opaque; customMaterial = null; isLighting = true; isStroke = false; isFill = true; } } private bool isLoop = true; private bool isRotateRadians = true; private bool isSphereRadius = true; protected struct SystemObject { public Transform transform; public Vector3 axis; public Vector3 translateScale; public UStyle style; public UShape pointShape; public UShape lineShape; public UShape curveShape; public UShape customShape; public GameObject imageBox; public GameObject objBox; } protected SystemObject system; private Stack<UTransform> matrixStack = new Stack<UTransform>(); private Stack<UStyle> styleStack = new Stack<UStyle>(); private Stack<int> layerStack = new Stack<int>(); private Stack<int> layerMaskStack = new Stack<int>(); private List<GameObject> tempGameObjs = new List<GameObject>(); private List<GameObject> keepGameObjs = new List<GameObject>(); class BasicShapes { public UShape point = null; public UShape rect = null; public UShape ellipse = null; public UShape box = null; public UShape sphere = null; public Dictionary<int, UShape> detailSpheres = null; public GameObject text = null; } private BasicShapes basicShapes = new BasicShapes(); private List<UShape> shapes = new List<UShape>(); private List<Mesh> destroyMeshes = new List<Mesh>(); public void disposeMesh(Mesh mesh) { destroyMeshes.Add(mesh); } #endregion #region System Functions protected virtual void Awake() { InitMath(); InitInput(); InitGraphics(); } protected virtual void Start() { Setup(); } protected virtual void OnDestroy() { foreach (Mesh mesh in destroyMeshes) { Destroy(mesh); } destroyMeshes.Clear(); Resources.UnloadUnusedAssets(); } void InitGraphics() { UMaterials.Init(); InitCamera(); system.style = new UStyle(this); GameObject sysTransObj = new GameObject("SystemTrans"); sysTransObj.transform.SetParent(gameObject.transform); sysTransObj.transform.localPosition = Vector3.zero; sysTransObj.transform.localRotation = Quaternion.identity; system.transform = sysTransObj.transform; system.axis = Vector3.one; system.imageBox = new GameObject("ImageBox"); system.imageBox.transform.SetParent(gameObject.transform); system.objBox = new GameObject(gameObject.name + " Objects"); system.pointShape = new UShape(this); system.lineShape = new UShape(this); system.curveShape = new UShape(this); system.customShape = null; basicShapes.point = createPoint(0, 0, 0); basicShapes.rect = createRect(0, 0, 1, 1); basicShapes.ellipse = createEllipse(0, 0, 1, 1); basicShapes.box = createBox(1, 1, 1); basicShapes.sphere = createSphere(1, 1, 1); basicShapes.detailSpheres = new Dictionary<int, UShape>(); basicShapes.text = loadPrefab("Unicessing/Prefabs/Text"); } void RecreateBasicFillShapes() { basicShapes.rect = createRect(0, 0, 1, 1); basicShapes.ellipse = createEllipse(0, 0, 1, 1); basicShapes.box = createBox(1, 1, 1); basicShapes.sphere = createSphere(1, 1, 1); basicShapes.detailSpheres.Clear(); } private void UpdateTranslateScale() { var ts = transform.localScale; system.translateScale.x = ts.x < 0.0f ? -1 : 1; system.translateScale.y = ts.y < 0.0f ? -1 : 1; system.translateScale.z = ts.z < 0.0f ? -1 : 1; } private void PreDraw() { clear(); UpdateTranslateScale(); noDepthStep(); UpdateInput(); BeginSystemShapes(); push(); depthStep(); } protected override Vector3 OnUpdateMouse3D(Vector3 pos) { return isP5 ? new Vector3(pos.x + width * 0.5f, pos.y + height * 0.5f, pos.z) : pos; } private void PostDraw() { DrawShapes(); pop(); EndSystemShapes(); } private void DrawShapes() { foreach (UShape shape in shapes) draw(shape); } private void FlushSystemShapes() { EndSystemShapes(); BeginSystemShapes(); } private void DrawSubGraphics() { foreach (USubGraphics sg in subGraphics) sg.SetupDraw(); } private void BeginSystemShapes(UShape.VertexType vertexType = UShape.VertexType.NONE) { system.pointShape.beginShape(UShape.VertexType.POINTS); system.lineShape.beginShape(UShape.VertexType.LINES); system.curveShape.beginShape(UShape.VertexType.CURVE_LINES); } private void EndSystemShapes(UShape.VertexType vertexType = UShape.VertexType.NONE) { if (system.pointShape != null) { system.pointShape.endShape(); drawShape(system.pointShape, Matrix4x4.identity); } if (system.lineShape != null) { system.lineShape.endShape(); drawShape(system.lineShape, Matrix4x4.identity); } if (system.curveShape != null) { system.curveShape.endShape(); drawShape(system.curveShape, Matrix4x4.identity); } } protected virtual void Update() { if (!isLoop) return; PreDraw(); push(); Draw(); pop(); DrawSubGraphics(); PostDraw(); } #if false // UNITY_EDITOR void OnDrawGizmosSelected() { if (!targetCamera) return; Transform trans = (mousePlane) ? mousePlane : transform; Gizmos.matrix = trans.localToWorldMatrix; } #endif private Vector2 GetModePos(int mode, float x, float y, float w, float h) { switch (mode) { case CORNER: return new Vector2(x, y); case CORNER_P5: return new Vector2(x, y - h); case CENTER: default: return new Vector2(x - (w * 0.5f), y - (h * 0.5f)); } } private float rotVal(float angle) { return isRotateRadians ? degrees(angle) : angle; } // for Unicessing #endregion #region Processing Events protected virtual void Setup() { } protected virtual void Draw() { } #endregion #region Processing Members /// @i{Specify width and height sizes\, coordinate system mode\, overall scale,widthとheightの大きさ、座標系モード、全体のスケールを指定} /** @lang_en -------- Unicessing uses Camera in the scene, so you do not need to use size (). @param width The value to return when referencing width. It does not affect the camera @param height The value to return when referencing height. It does not affect the camera @param mode The default is U3D. When it is set to P2D or P3D, it becomes the coordinate system of processing (y and z are opposite to each other). P2D starts with noLights() @param scale Scale value for various objects to draw with Unicessing @sa AxisMode @end_lang @lang_jp -------- UnicessingではCameraを自分でシーンに配置して使うため、size()を省略できる。 @param width widthを参照したときに返したい値。カメラには影響しない @param height heightを参照したときに返したい値。カメラには影響しない @param mode デフォルトはU3D。P2D、P3DにするとProcessingの座標系(yとzが逆方向)になる。P2DはnoLights()でスタートする @param scale Unicessingで描画する各種オブジェクトにかかるスケール値 @sa AxisMode @end_lang */ public void size(float width, float height, AxisMode mode = U3D, float scale = 1.0f) { this.width = width; this.height = height; if (mode == P2D || mode == P3D) { axis(scale, -scale, -scale); translate(-width / 2, -height / 2); if(mode == P2D) { noLights(); } } else { axis(scale, scale, scale); } } /// @i{start Draw() loop,描画ループを許可} public void loop() { isLoop = true; } /// @i{stop Draw() loop,描画ループを止める} public void noLoop() { isLoop = false; } /// @i{delete temporary objects,一時オブジェクトを消す} public void clear() { foreach (GameObject obj in keepGameObjs) { obj.SetActive(false); } foreach (GameObject obj in tempGameObjs) { Destroy(obj); } tempGameObjs.Clear(); foreach (Mesh mesh in destroyMeshes) { Destroy(mesh); } destroyMeshes.Clear(); } /// @i{Changes the way Unicessing interprets color data. mode : Either RGB or HSB\, corresponding to Red/Green/Blue and Hue/Saturation/Brightness,Unicessingでの色の解釈modeをRGB、HSBで切り替える。値の範囲のスケールも可能。} public void colorMode(ColorMode mode, float max = 255) { colorMode(mode, max, max, max, max); } public void colorMode(ColorMode mode, float maxR, float maxG, float maxB, float maxA) { system.style.colorMode = mode; system.style.colorScale = new Vector4(maxR, maxG, maxB, maxA); system.style.invColorScale = new Vector4(1 / maxR, 1 / maxG, 1 / maxB, 1 / maxA); } /// @i{Convert color according to color space mode,色空間モードにあわせて色を変換する} protected override Color convertColorSpace(float r, float g, float b, float a) { r = r * system.style.invColorScale.x; g = g * system.style.invColorScale.y; b = b * system.style.invColorScale.z; a = a * system.style.invColorScale.w; if (system.style.colorMode == ColorMode.HSB) { Color col = Color.HSVToRGB(r, g, b); col.a = a; return col; } else { return new Color(r, g, b, a); } } /// @i{Extracts the red value from a color,色の赤色成分を返す} public float red(Color col) { return col.r * system.style.colorScale.x; } /// @i{Extracts the green value from a color,色の緑色成分を返す} public float green(Color col) { return col.g * system.style.colorScale.y; } /// @i{Extracts the blue value from a color,色の青色成分を返す} public float blue(Color col) { return col.b * system.style.colorScale.z; } /// @i{Extracts the alpha value from a color,色の透明色成分を返す} public float alpha(Color col) { return col.a * system.style.colorScale.w; } /// @i{Extracts the gray scale value from a color,色のグレイスケール成分を返す} public float gray(Color col) { return col.grayscale * system.style.colorScale.w; } /// @i{Extracts the hue value from a color,色の色相を返す} public float hue(Color col) { float h = 0, s = 0, v = 0; Color.RGBToHSV(col, out h, out s, out v); return h * system.style.colorScale.x; } /// @i{Extracts the saturation value from a color,色の彩度を返す} public float saturation(Color col) { float h = 0, s = 0, v = 0; Color.RGBToHSV(col, out h, out s, out v); return s * system.style.colorScale.y; } /// @i{Extracts the brightness value from a color,色の明度を返す} public float brightness(Color col) { float h = 0, s = 0, v = 0; Color.RGBToHSV(col, out h, out s, out v); return v * system.style.colorScale.z; } /// @i{Calculates a color or colors between two color at a specific increment,2つの色の補間した色を返す} public Color lerpColor(Color c1, Color c2, float amt) { return Color.Lerp(c1, c2, amt); } /// @i{Enable fill,塗りつぶす} public void fill() { system.style.isFill = true; } /// @i{Sets the color used to fill shapes,塗りつぶし色を指定} public void fill(float gray, float alpha = 255) { fill(gray, gray, gray, alpha); } public void fill(float r, float g, float b, float a = 255) { fill(color(r, g, b, a)); } public void fill(Color col) { system.style.fillColor = col; system.style.isFill = true; } /// @i{Disable fill,塗りつぶさない} public void noFill() { system.style.isFill = false; } /// @i{Enable stroke,線を描く} public void stroke() { system.style.isStroke = true; } /// @i{Sets the color used to draw lines and borders around shape\, wireframes,線の色を指定} public void stroke(float gray, float alpha = 255) { stroke(gray, gray, gray, alpha); } public void stroke(float r, float g, float b, float a = 255) { stroke(color(r, g, b, a)); } public void stroke(Color col) { system.style.strokeColor = col; system.style.isStroke = true; } /// @i{Disable stroke,線を描かない} public void noStroke() { system.style.isStroke = false; } /// @i{Sets a texture to be applied to vertex points,塗りつぶしにテクスチャーを使うように指定} public void texture(UImage img) { system.style.texture = img.texture; } public void texture(Texture tex) { system.style.texture = tex; } /// @i{Disable texture,塗りつぶしにテクスチャーを使わない} public void noTexture() { system.style.texture = null; } /// @i{Blends the pixels in the display window according to a defined mode OPAQUE\, TRANSPARENT\, ADD,合成モードを指定。デフォルトは不透明のOPAQUEで、半透明のTRANSPARENT、加算のADDなどがある} public void blendMode(UMaterials.BlendMode mode) { system.style.blendMode = mode; } /// @i{Loads a shader into the Material object,シェーダー/マテリアルをロードし、マテリアルとして返す} public Material loadShader(string name) { return UMaterials.load(name); } /// @i{Applies the custom shader / material specified. but not with the default renderer,指定された独自シェーダー、マテリアルを使用} public void shader(Shader shader) { this.shader(new Material(shader)); } public void shader(Material material) { system.style.customMaterial = material; } /// @i{Restores the default shaders,独自シェーダー/マテリアルの使用をやめて通常のシェーダーに戻す} public void resetShader() { system.style.customMaterial = null; } /// @i{The pushStyle() function saves the current style settings and popStyle() restores the prior settings,現在のスタイルをスタックに積んで保存} public void pushStyle() { styleStack.Push(system.style.Clone()); } /// @i{The pushStyle() function saves the current style settings and popStyle() restores the prior settings restores the prior settings,保存したスタイルをスタックから降ろして反映} public void popStyle() { system.style = styleStack.Pop(); } /// @i{Get style,現在のスタイルクラスを直接参照する} public UStyle getStyle() { return system.style; } /// @i{Set style,現在のスタイルクラスを変更する} public void setStyle(UStyle style) { this.style(style); } public void style(UStyle style) { Debug.Assert(style != null); int layer = system.style.layer; int layerMask = system.style.layerMask; bool isFlush = (style.layer != layer || style.layerMask != layerMask); system.style = style.Clone(); if (style.layer < 0) { this.layer(layer); this.layerMask(layerMask); } if (isFlush) { FlushSystemShapes(); } } /// @i{Pushes the current transformation matrix onto the matrix stack,現在の行列(姿勢、位置、スケール)をスタックに積んで保存} public void pushMatrix() { matrixStack.Push(new UTransform(system.transform)); } /// @i{Pops the current transformation matrix off the matrix stack,現在の行列(姿勢、位置、スケール)をスタックから降ろして反映} public void popMatrix() { if (matrixStack.Count > 0) { system.transform.Set(matrixStack.Pop()); } } /// @i{pushStyle() and pushMatrix(),現在のスタイルと行列(姿勢、位置、スケール)をスタックに積んで保存} public void push() { pushStyle(); pushMatrix(); } /// @i{popStyle() and popMatrix(),現在のスタイルと行列(姿勢、位置、スケール)をスタックから降ろして反映} public void pop() { popMatrix(); popStyle(); } /// @i{Get the current local matrix,現在のローカル行列(姿勢、位置、スケール)を取得する} public UMatrix getMatrix() { return new UMatrix(system.transform.worldToLocalMatrix); } /// @i{Get the current world matrix,現在のワールド行列(姿勢、位置、スケール)を取得する} public Matrix4x4 getWorldMatrix() { return system.transform.localToWorldMatrix; } /// @i{Get the current local matrix,現在のローカル行列(姿勢、位置、スケール)を取得する} public Matrix4x4 getLocalMatrix() { return system.transform.worldToLocalMatrix; } /// @i{Overwrite the current local matrix,現在のローカル行列(姿勢、位置、スケール)を上書きする} public void applyMatrix(UMatrix matrix) { system.transform.setLocal(matrix); } /// @i{Overwrite the current world matrix,現在のワールド行列(姿勢、位置、スケール)を上書きする} public void applyWorldMatrix(Matrix4x4 matrix) { system.transform.setWorld(new UMatrix(matrix)); } /// @i{Overwrite the current local matrix,現在のローカル行列(姿勢、位置、スケール)を上書きする} public void applyLocalMatrix(Matrix4x4 matrix) { system.transform.setLocal(new UMatrix(matrix)); } //public void translateNoScale(float x, float y, float z = 0.0f) { translateNoScale(new Vector3(x, y, z)); } //public void translateNoScale(Vector3 pos) { system.transform.Translate(pos); } /// @i{Move position,位置を移動する} public void translate(float x, float y, float z = 0.0f) { translate(new Vector3(x, y, z)); } public void translate(Vector3 pos) { var s = system.transform.lossyScale; pos.x *= s.x * system.translateScale.x; pos.y *= s.y * system.translateScale.y; pos.z *= s.z * system.translateScale.z; system.transform.Translate(pos, Space.Self); } /// @i{Rotate orientation (Z),姿勢を回転させる(Z軸)} public void rotate(float angle) { rotateZ(angle); } /// @i{Rotate orientation (3 axis),姿勢を回転させる(3軸)} public void rotate(float xAngle, float yAngle, float zAngle) { system.transform.Rotate(new Vector3(rotVal(xAngle), rotVal(yAngle), rotVal(zAngle))); } public void rotate(Vector3 angles) { rotate(angles.x, angles.y, angles.z); } /// @i{Rotate orientation (Quaternion),姿勢を回転させる(Quaternion)} public void rotate(Quaternion quat) { system.transform.localRotation = quat; } /// @i{Rotate orientation (any axis),姿勢を回転させる(指定の軸)} public void rotate(float angle, float x, float y, float z) { system.transform.RotateAround(Vector3.zero, new Vector3(x, y, z), rotVal(angle)); } /// @i{Rotate orientation (X),姿勢を回転させる(X軸)} public void rotateX(float angle) { system.transform.Rotate(rotVal(angle), 0.0f, 0.0f); } /// @i{Rotate orientation (Y),姿勢を回転させる(Y軸)} public void rotateY(float angle) { system.transform.Rotate(0.0f, rotVal(angle), 0.0f); } /// @i{Rotate orientation (Z),姿勢を回転させる(Z軸)} public void rotateZ(float angle) { system.transform.Rotate(0.0f, 0.0f, rotVal(angle)); } /// @i{Rotate orientation (Regardless of the current rotateMode\, rotate the 3 axis Euler angles in degrees),姿勢を回転させる(現在のrotateModeに関係なく、3軸オイラー角を度単位で回転)} /// @i{Scale the size,大きさをスケール倍する)} public void scale(float s) { scale(s, s, s); } public void scale(float x, float y, float z = 1.0f) { Vector3 s = system.transform.localScale; s.x *= x; s.y *= y; s.z *= z; system.transform.localScale = s; } public void scale(Vector3 s) { scale(s.x, s.y, s.z); } /// @i{Return the X coordinate of the current world position,現在ワールド位置のX座標を返す} public float modelX() { return system.transform.position.x; } /// @i{Return the Y coordinate of the current world position,現在ワールド位置のY座標を返す} public float modelY() { return system.transform.position.y; } /// @i{Return the Z coordinate of the current world position,現在ワールド位置のZ座標を返す} public float modelZ() { return system.transform.position.z; } /// @i{The createShape() function is used to define a new shape,新しいシェイプを作成する} public UShape createShape() { return new UShape(this); } /// @i{The createShape() function is used to define a new basic shape,基本形状のシェイプを作成する} /** @lang_en -------- Create the basic shape specified by kind. @param kind Either POINT, LINE, RECT, ELLIPSE, BOX, SPHERE @param p ScaleVertex position of shape @sa UShape.ShapeKind @end_lang @lang_jp -------- kindで指定した基本形状のシェイプを作成する。 @param kind UShape.ShapeKindのPOINT、LINE、RECT、ELLIPSE、BOX、SPHEREいずれかのシェイプ種別 @param p シェイプの頂点位置 @sa UShape.ShapeKind @end_lang */ public UShape createShape(UShape.ShapeKind kind, params float[] p) { UShape shape = new UShape(this); switch (kind) { case UShape.ShapeKind.POINT: shape.createPoint(p[0], p[1], p[2]); break; case UShape.ShapeKind.LINE: shape.createLine(p[0], p[1], p[2], p[3], p[4], p[5]); break; case UShape.ShapeKind.RECT: shape.createRect(p[0], p[1], p[2], p[3]); break; case UShape.ShapeKind.ELLIPSE: shape.createEllipse(p[0], p[1], p[2], p[3]); break; case UShape.ShapeKind.BOX: shape.createBox(p[0], p[1], p[2]); break; case UShape.ShapeKind.SPHERE: shape.createSphere(p[0], p[1], p[2], (int)p[3], (int)p[4]); break; } return shape; } /// @i{Create a point shape,点のシェイプを作成する} public UShape createPoint(float x, float y, float z) { return createShape(UShape.ShapeKind.POINT, x, y, z); } /// @i{Create a line shape,線のシェイプを作成する} public UShape createLine(float x1, float y1, float x2, float y2) { return createShape(UShape.ShapeKind.LINE, x1, y1, 0, x2, y2, 0); } public UShape createLine(float x1, float y1, float z1, float x2, float y2, float z2) { return createShape(UShape.ShapeKind.LINE, x1, y1, z1, x2, y2, z2); } /// @i{Create a rect shape,四角のシェイプを作成する} public UShape createRect(float x, float y, float w, float h) { return createShape(UShape.ShapeKind.RECT, x, y, w, h); } /// @i{Create a ellipse shape,円のシェイプを作成する} public UShape createEllipse(float x, float y, float w, float h, int res = 48) { return createShape(UShape.ShapeKind.ELLIPSE, x, y, w, h, res); } /// @i{Create a box shape,箱のシェイプを作成する} public UShape createBox(float w, float h, float d) { return createShape(UShape.ShapeKind.BOX, w, h, d); } /// @i{Create a sphere shape,球のシェイプを作成する} public UShape createSphere(float w, float h, float d, int ures = 30, int vres = 30) { return createShape(UShape.ShapeKind.SPHERE, w, h, d, ures, vres); } /// @i{Draw a point,点を描く} public void point(float x, float y, float z = 0.0f) { point(new Vector3(x, y, z)); } public void point(Vector3 pos) { #if true Vector3 v = system.transform.TransformPoint(pos); system.pointShape.vertex(v.x, v.y, v.z); if (system.pointShape.vertexCount >= 1024 * 60) { system.pointShape.endShape(); drawShape(system.pointShape, Matrix4x4.identity); system.pointShape.beginShape(UShape.VertexType.POINTS); } #else draw(basicShapes.point, pos.x, pos.y, pos.z); #endif } /// @i{Draw a line,線を描く} public void line(float x1, float y1, float x2, float y2) { line(x1, y1, 0, x2, y2, 0); } public void line(float x1, float y1, float z1, float x2, float y2, float z2) { line(new Vector3(x1, y1, z1), new Vector3(x2, y2, z2)); } public void line(Vector3 v1, Vector3 v2) { #if true v1 = system.transform.TransformPoint(v1); v2 = system.transform.TransformPoint(v2); system.lineShape.vertex(v1.x, v1.y, v1.z); system.lineShape.vertex(v2.x, v2.y, v2.z); if(system.lineShape.vertexCount >= 1024 * 60) { system.lineShape.endShape(); drawShape(system.lineShape, Matrix4x4.identity); system.lineShape.beginShape(UShape.VertexType.LINES); } #else UShape shape = new UShape(this); shape.createLine(v1.x, v1.y, v1.z, v2.x, v2.y, v2.z); draw(shape); #endif } /// @i{Draw a curve,曲線を描く} public void curve(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { curve(new Vector3(x1, y1, 0.0f), new Vector3(x2, y2, 0.0f), new Vector3(x3, y3, 0.0f), new Vector3(x4, y4, 0.0f)); } public void curve(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { curve(new Vector3(x1, y1, z1), new Vector3(x2, y2, z2), new Vector3(x3, y3, z3), new Vector3(x4, y4, z4)); } public void curve(Vector3 v1, Vector3 v2, Vector3 v3, Vector3 v4) { v1 = system.transform.TransformPoint(v1); v2 = system.transform.TransformPoint(v2); v3 = system.transform.TransformPoint(v3); v4 = system.transform.TransformPoint(v4); system.curveShape.vertex(v1); system.curveShape.vertex(v2); system.curveShape.vertex(v3); system.curveShape.vertex(v4); if (system.curveShape.vertexCount >= 1024 * (60 / system.curveShape.curveDivision)) { system.curveShape.endShape(); drawShape(system.curveShape, Matrix4x4.identity); system.curveShape.beginShape(UShape.VertexType.CURVE_LINES); } } /// @i{Modifies the location from which rectangles are drawn by changing the way in which parameters given to rect() are intepreted. CORNER\, CENTER\, CORNER_P5,rect()で四角形を描くときの基準位置を設定する。CORNER、CENTER、CORNER_P5} public void rectMode(int mode) // CORNER or CENTER { Debug.Assert(mode == CORNER || mode == CENTER || mode == CORNER_P5); system.style.rectMode = mode; } /// @i{Draw a rect,四角を描く} public void rect(float x, float y, float w, float h) { Vector2 pos = GetModePos(system.style.rectMode, x, y, w, h); draw(basicShapes.rect, pos.x, pos.y, w, h); } /// @i{Modifies the location from which rectangles are drawn by changing the way in which parameters given to ellipse() are intepreted. CORNER\, CENTER\, CORNER_P5,ellipse()で円を描くときの基準位置を設定する。CORNER、CENTER、CORNER_P5} public void ellipseMode(int mode) // CORNER or CENTER { Debug.Assert(mode == CORNER || mode == CENTER || mode == CORNER_P5); system.style.ellipseMode = mode; } /// @i{Draw a ellipse,円を描く} public void ellipse(float x, float y, float w, float h) { Vector2 pos = GetModePos(system.style.ellipseMode, x + w * 0.5f, y + h * 0.5f, w, h); draw(basicShapes.ellipse, pos.x, pos.y, w, h); } /// @i{Draw a triangle,三角を描く} public void triangle(float x1, float y1, float x2, float y2, float x3, float y3) { beginShape(UShape.VertexType.TRIANGLES); vertex(x1, y1); vertex(x2, y2); vertex(x3, y3); endShape(); } /// @i{Draw a box,箱を描く} public void box(float whd) { box(whd, whd, whd); } public void box(float w, float h, float d) { box(0.0f, 0.0f, 0.0f, w, h, d); } public void box(float x, float y, float z, float w, float h, float d) { draw(basicShapes.box, x, y, z, w, h, d); } public void box(Vector3 pos, Vector3 scale) { box(pos.x, pos.y, pos.z, scale.x, scale.y, scale.z); } public void box(Vector3 scale) { box(0.0f, 0.0f, 0.0f, scale.x, scale.y, scale.z); } /// @i{Draw a sphere,球を描く} public void sphere(float r) { sphere(r, r, r); } public void sphere(float w, float h, float d) { sphere(0.0f, 0.0f, 0.0f, w, h, d); } public void sphere(float x, float y, float z, float w, float h, float d) { if(isSphereRadius) { w *= 2.0f; h *= 2.0f; d *= 2.0f; } UShape shape = basicShapes.sphere; if (system.style.sphereDetailKey != UStyle.sphereDetailKeyDefault) { if (basicShapes.detailSpheres.ContainsKey(system.style.sphereDetailKey)) { shape = basicShapes.detailSpheres[system.style.sphereDetailKey]; } } draw(shape, x, y, z, w, h, d); } public void sphere(Vector3 pos, Vector3 scale) { sphere(pos.x, pos.y, pos.z, scale.x, scale.y, scale.z); } public void sphere(Vector3 scale) { sphere(0.0f, 0.0f, 0.0f, scale.x, scale.y, scale.z); } /// @i{Set the number of divisions of the surface of the sphere when drawing with sphere(),sphere()で描くときの球の面の分割数を設定する} public void sphereDetail(int res) { sphereDetail(res, res); } public void sphereDetail(int ures, int vres) { int key = (ures << 16) | vres; if (!basicShapes.detailSpheres.ContainsKey(key)) { basicShapes.detailSpheres[key] = createSphere(1.0f, 1.0f, 1.0f, ures, vres); } system.style.sphereDetailKey = key; } /// @i{Start designating the customized shape with beginShape() and draw it with endShape(),独自のシェイプをbeginShape()で作成開始し、endShape()で描く} /** @lang_en -------- Between beginShape() and endShape(), you can specify a vertex using vertex() or curveVertex() and draw a customized shape. @param type Either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, or QUAD_STRIP @sa UShape.VertexType @end_lang @lang_jp -------- beginShape()からendShape()の間に、vertex()またはcurveVertex()を使って頂点を指定し、独自のシェイプを描ける。 @param kind UShape.ShapeKindのPOINT、LINE、RECT、ELLIPSE、BOX、SPHEREいずれかのシェイプ種別 @sa UShape.ShapeKind @end_lang */ public void beginShape(UShape.VertexType type = UShape.VertexType.LINE_STRIP) { if (system.customShape == null) { system.customShape = new UShape(this); } system.customShape.beginShape(type); } /// @i{The endShape() function is the companion to beginShape() and may only be called after beginShape(). Close shape with CLOSE,endShape()はbeginShape()のあとに使い、その間で指定した頂点の図形を描く。CLOSEで図形を最初の頂点につなげて閉じる} public void endShape(UShape.CloseType closeType = UShape.CloseType.NONE) { if (system.customShape==null) { debuglogError("endShape: <Not beginShape>"); return; } system.customShape.endShape(closeType); draw(system.customShape); system.customShape.Dispose(); system.customShape = null; } public void endShape(int closeType) { endShape((UShape.CloseType)closeType); } public void endShapeClose() { endShape(UShape.CloseType.CLOSE); } /// @i{Add a vertex. Use between beginShape() and endShape(),頂点を追加する。beginShape()とendShape()の間で使うこと} public void vertex(float x, float y, float z = 0.0f) { vertex(x, y, z, 0.0f, 0.0f); } public void vertex(float x, float y, float u, float v) { vertex(x, y, 0.0f, u, v); } public void vertex(float x, float y, float z, float u, float v) { vertex(new Vector3(x, y, z), new Vector2(u, v)); } public void vertex(Vector3 pos) { vertex(pos, Vector2.zero); } public void vertex(Vector3 pos, Vector3 uv) { if (system.customShape == null) { debuglogError("vertex: <Not beginShape>"); return; } system.customShape.vertex(pos, uv); } /// @i{Add a vertex. Use between beginShape() and endShape(). Available only when CURVE_LINES\, CURVE_LINE_STRIP,曲線の頂点を追加する。beginShape()とendShape()の間で使うこと。CURVE_LINES、CURVE_LINE_STRIPのときのみ使用可能} public void curveVertex(float x, float y, float z = 0.0f) { curveVertex(new Vector3(x, y, z)); } public void curveVertex(Vector3 pos) { if (system.customShape == null) { debuglogError("curveVertex: <Not beginShape>"); return; } system.customShape.curveVertex(pos); } /// @i{Draw a shape,シェイプを描く} public void draw(UShape shape, float x, float y) { draw(shape, x, y, 0.0f); } public void draw(UShape shape, float x, float y, float w, float h) { draw(shape, x, y, 0.0f, w, h, 1.0f); } public void draw(UShape shape, float x, float y, float z) { pushMatrix(); translate(x, y, z); drawShape(shape); popMatrix(); } public void draw(UShape shape, float x, float y, float z, float w, float h, float d) { pushMatrix(); translate(x, y, z); scale(w, h, d); drawShape(shape); popMatrix(); } public void draw(UShape shape) { pushMatrix(); drawShape(shape); popMatrix(); } private void drawShape(UShape shape) { if (shape == null) return; applyDepth(); #if UNITY_EDITOR Camera drawCam = null; // targetCamera; シーンビューに出なくなるのでひとまずnull #else Camera drawCam = targetCamera; #endif shape.draw(system.transform.localToWorldMatrix, drawCam); if (shape.isFillShape && shape.is2DShape) addDepthStep(); } private void drawShape(UShape shape, Matrix4x4 matrix) { if (shape == null) return; #if UNITY_EDITOR Camera drawCam = null; // targetCamera; シーンビューに出なくなるのでひとまずnull #else Camera drawCam = targetCamera; #endif shape.draw(matrix, drawCam); if (shape.isFillShape && shape.is2DShape) addDepthStep(); } /* public void drawNow(UShape shape) { if (shape == null) return; shape.drawNow(system.transform.localToWorldMatrix, shape.nowColor); } */ /// @i{Make image area,画像領域を作る} public UImage createImage(float width, float height, TextureFormat texFormat = TextureFormat.ARGB32) { return createImage((int)width, (int)height, texFormat); } public UImage createImage(int width, int height, TextureFormat texFormat = TextureFormat.ARGB32) { return createImage(system.imageBox, width, height, texFormat); } public UImage createImage(GameObject obj, int width, int height, TextureFormat texFormat = TextureFormat.ARGB32) { UImage img = obj.AddComponent<UImage>(); img.create(width, height, texFormat); img.gameObject.SetActive(false); return img; } /// @i{Load image. Resources folder\, local file\, URL can be specified,画像を読み込む。リソースフォルダ内、ローカルファイル、URLを指定可能} public UImage loadImage(string path, int width = 0, int height = 0) { return loadImage(system.imageBox, path, width, height); } public UImage loadImage(GameObject obj, string path, int width = 0, int height = 0) { UImage img = obj.AddComponent<UImage>(); img.width = width; img.height = height; img.load(this, path); return img; } /// @i{Remove image,画像を破棄する} public void removeImage(UImage img) { Debug.Assert(img); Destroy(img); } /// @i{Modifies the location from which images are drawn by changing the way in which parameters given to image() are intepreted. CORNER\, CENTER\, CORNER_P5,image()で画像を描くときの基準位置を設定する。CORNER、CENTER、CORNER_P5} public void imageMode(int mode) // CORNER or CENTER { Debug.Assert(mode == CORNER || mode == CENTER || mode == CORNER_P5); system.style.imageMode = mode; } /// @i{Draw a image,画像を描く} public void image(Texture tex, float x, float y) { assert(tex != null); image(tex, x, y, tex.width * 0.01f, tex.height * 0.01f); } public void image(UImage img, float x, float y) { assert(img != null); image(img, x, y, img.width * 0.01f, img.height * 0.01f); } public void image(UImage img, float x, float y, float w, float h) { assert(img != null); image(img.texture, x, y, w, h); } public void image(Texture tex, float x, float y, float w, float h) { //Debug.Assert(tex != null); Texture ptex = system.style.texture; system.style.texture = tex; Vector2 pos = GetModePos(system.style.imageMode, x, y, w, h); draw(basicShapes.rect, pos.x, pos.y, w, h); system.style.texture = ptex; } /// @i{Sets the current text size,テキストの大きさを設定する} public void textSize(float size) { system.style.textSize = size; } /// @i{Sets the current text size,テキストの縦横の基準位置を設定する} /** @lang_en -------- @param alignX Either LEFT, CENTER, RIGHT @param alignY Either BASELINE, TOP, CENTER, BOTTOM @end_lang @lang_jp -------- @param alignX 横の基準位置 LEFT, CENTER, RIGHT @param alignY 縦の基準位置 BASELINE, TOP, CENTER, BOTTOM @end_lang */ public void textAlign(int alignX, int alignY = BASELINE) { Debug.Assert(alignX == LEFT || alignX == CENTER || alignX == RIGHT); Debug.Assert(alignY == TOP || alignY == CENTER || alignY == BOTTOM || alignY == BASELINE); system.style.textAlignX = alignX; // LEFT, CENTER, RIGHT system.style.textAlignY = alignY; // TOP, CENTER, BTOTTOM, BASELINE } /// @i{Load font. If it is not in the resource folder\, search for the same name font from the system font of the OS,フォントを読み込む。リソースフォルダにない場合、OSのシステムフォントから同名フォントを探す} public Font loadFont(string fontname) { string fontPath = getResourceName(fontname); Font font = Resources.Load(fontPath, typeof(Font)) as Font; if (font == null) { font = Font.CreateDynamicFontFromOSFont(fontname, (int)(system.style.textScale)); if (font == null) { debuglogWaring("loadFont <NotFound> " + fontPath); } } else { debuglog("loadFont " + fontPath); } return font; } /// @i{Return a list of system font names,OSのシステムフォント名一覧を取得する} public string[] fontList() { string[] fonts = Font.GetOSInstalledFontNames(); string s = ""; for (int i=0; i<fonts.Length; i++) { s += fonts[i]; } println(s); return fonts; } /// @i{Sets the current font that will be drawn with the text() function,テキスト描画に使うフォントを設定する} public void textFont(Font font) { system.style.font = font; } public void textFont(string fontname) { textFont(loadFont(fontname)); } /// @i{Create a text shape,テキストのシェイプを作成する} public GameObject createText(string str, float x, float y, float z = 0.0f) { GameObject obj = createObj(basicShapes.text); createText(obj, str, x, y, z); return obj; } private void createText(GameObject obj, string str, float x, float y, float z = 0.0f) { if (!basicShapes.text) return; TextMesh tm = obj.GetComponent<TextMesh>(); if (tm) { Debug.Assert(system.style.textSize > 0); float textQuality = 100.0f * system.style.textScale; if (textQuality < 1.0f) textQuality = 1.0f; tm.color = system.style.fillColor; tm.characterSize = system.style.textSize * 10 / textQuality; tm.fontSize = (int)(textQuality); if (system.style.font != null) { tm.font = system.style.font; obj.GetComponent<Renderer>().material = system.style.font.material; } tm.text = str; tm.anchor = TextAnchor.MiddleCenter; if (system.style.textAlignX == LEFT) { switch (system.style.textAlignY) { case TOP: tm.anchor = TextAnchor.UpperLeft; break; case CENTER: tm.anchor = TextAnchor.MiddleLeft; break; case BASELINE: tm.anchor = TextAnchor.MiddleLeft; break; case BOTTOM: tm.anchor = TextAnchor.LowerLeft; break; } } else if (system.style.textAlignX == RIGHT) { switch (system.style.textAlignY) { case TOP: tm.anchor = TextAnchor.UpperRight; break; case CENTER: tm.anchor = TextAnchor.MiddleRight; break; case BASELINE: tm.anchor = TextAnchor.MiddleRight; break; case BOTTOM: tm.anchor = TextAnchor.LowerRight; break; } } else { switch (system.style.textAlignY) { case TOP: tm.anchor = TextAnchor.UpperCenter; break; case CENTER: tm.anchor = TextAnchor.MiddleCenter; break; case BASELINE: tm.anchor = TextAnchor.MiddleCenter; break; case BOTTOM: tm.anchor = TextAnchor.LowerCenter; break; } } if (system.style.textAlignY == BASELINE) { if (system.axis.y < 0) y -= system.style.textSize * 0.3f; else y += system.style.textSize * 0.3f; } } Vector3 s = Vector3.one; if (system.axis.x < 0) { s.x = -1; } if (system.axis.y < 0) { s.y = -1; } SetTransformObj(obj, new Vector3(x, y, z), s); } /// @i{Draw a text,テキストを描く} public void text(string str, float x = 0.0f, float y = 0.0f, float z = 0.0f) { GameObject obj = instantiateObj(basicShapes.text); if (obj) tempGameObjs.Add(obj); createText(obj, str, x, y, z); } /// @i{Do not use lights. unlit shader,ライトを使わないようにする(unlitシェーダー)} public void noLights() { system.style.isLighting = false; } /// @i{Use lights. normal shader. NOTE: Separately lights arrangement and setting are necessary,ライトを使うようにする(通常のシェーダー)※別途Lightの配置や設定は必要 } public void lights() { system.style.isLighting = true; } /// @i{Set ambient light (whole scene),環境光を設定する(シーン全体)} public void ambientLight(int r, int g, int b) { RenderSettings.ambientLight = color(r, g, b); } /// @i{Create a directional light,ディレクショナルライトを作る} public Light createDirectionalLight(int r, int g, int b, float nx, float ny, float nz) { return directionalLight(null, r, g, b, nx, ny, nz); } /// @i{Set the directional light. If lights is null\, add it to the scene newly,ディレクショナルライトを設定する。lightがnullの場合はシーンに新しく追加する} public Light directionalLight(Light light, int r, int g, int b, float nx, float ny, float nz) { if(!light) { GameObject obj = new GameObject("DirectionalLight"); light = obj.AddComponent<Light>(); obj.transform.SetParent(system.objBox.transform); } light.enabled = true; light.color = color(r, g, b); light.type = LightType.Directional; light.cullingMask = system.style.layerMask; light.gameObject.transform.localRotation = light.gameObject.transform.localRotation * Quaternion.LookRotation(new Vector3(nx, ny, nz)); return light; } #endregion #region Processing Extra Members private void axisP5(float scale = 1.0f) { axis(scale, -scale, -scale); } private void axis(float x, float y, float z) { axis(new Vector3(x, y, z)); } private void axis(Vector3 axis) { bool isChangeY = (axis.y < 0 && system.axis.y > 0) || (axis.y > 0 && system.axis.y < 0); system.axis = axis; transform.localScale = axis; if(isChangeY) RecreateBasicFillShapes(); UpdateTranslateScale(); } /// @i{Return the axis and scale of the current coordinate system mode,現在の座標系モードの軸、スケール} public Vector2 axis2D { get { return new Vector2(system.axis.x, system.axis.y); } } public Vector3 axis3D { get { return system.axis; } } /// @i{Is it currently in Processing's coordinate system mode?,Processingの座標系モードか?} public bool isP5 { get { return system.axis.y < 0.0f; } } /// @i{Add shape to drawing list,描画リストにシェイプを追加} public void add(UShape shape) { if(shape!=null) shapes.Add(shape); } /// @i{Remove shape to drawing list,描画リストからシェイプを削除} public void remove(UShape shape, bool isDispose = false) { if (shape == null) return; shapes.Remove(shape); if (isDispose) shape.Dispose(); } /// @i{Set rotation mode of rotate() to radians,rotate()の回転モードをラジアン単位にする} public void rotateRadians() { isRotateRadians = true; } /// @i{Set rotation mode of rotate() to degrees,rotate()の回転モードを度単位にする} public void rotateDegrees() { isRotateRadians = false; } public void rotateDegrees(float xAngle, float yAngle, float zAngle) { system.transform.Rotate(new Vector3(xAngle, yAngle, zAngle)); } public void rotateDegrees(Vector3 eulerAngles) { system.transform.Rotate(eulerAngles); } /// @i{Interpret the value specified by sphere()\, where on is the radius and off is the diameter,sphere()で指定した値をonで半径、offで直径と解釈する} public void sphereRadius(bool on) { isSphereRadius = on; } /// @i{Sets the current font scale,テキストのスケールを設定する} public void textScale(float s) { system.style.textScale = s; } /// @i{Sets the current font quality,テキストの品質を設定する} public void textQuality(float level) { system.style.textQuality = level; } /// @i{The current transform in Unicessing,Unicessing内で座標変換した現在のTransform} public Transform uniTransfrom { get { return system.transform; } } /// @i{Returns the current transform in Unicessing,Unicessing内で座標変換した現在のTransformを返す} public Transform getTransform() { return system.transform; } /// @i{Returns world position,現在のワールド位置を返す(getWorldPos()の別名)} public Vector3 modelPos() { return getWorldPos(); } /// @i{Returns world position,ワールド座標系での位置を返す} public Vector3 getWorldPos() { return system.transform.position; } /// @i{Returns local position,ローカル座標系での位置を返す} public Vector3 getLocalPos() { return system.transform.localPosition; } /// @i{Returns Set world position,ワールド座標系で位置を設定する} public void setWorldPos(float x, float y, float z) { setWorldPos(new Vector3(x, y, z)); } public void setWorldPos(Vector3 pos) { system.transform.position = pos; } /// @i{Returns Set local position,ローカル座標系で位置を設定する} public void setLocalPos(float x, float y, float z) { setLocalPos(new Vector3(x, y, z)); } public void setLocalPos(Vector3 pos) { system.transform.localPosition = pos; } /// @i{Convert the position in the local coordinate system to the position in the world coordinate system,ローカル座標系での位置を、ワールド座標系での位置に変換する} public Vector3 localToWorldPos(float x, float y, float z = 0.0f) { return localToWorldPos(new Vector3(x, y, z)); } public Vector3 localToWorldPos(Vector3 localPos) { return system.transform.TransformPoint(localPos); } /// @i{Convert the position in the world coordinate system to the position in the local coordinate system,ワールド座標系での位置を、ローカル座標系での位置に変換する} public Vector3 wordlToLocalPos(float x, float y, float z = 0.0f) { return wordlToLocalPos(new Vector3(x, y, z)); } public Vector3 wordlToLocalPos(Vector3 worldPos) { return system.transform.InverseTransformPoint(worldPos); } /// @i{Convert the direction in the local coordinate system to the world coordinate system,ローカル座標系での方向をワールド座標系に変換する} public Vector3 localToWorldDir(Vector3 localDir) { return system.transform.TransformDirection(localDir); } /// @i{Convert the direction in the world coordinate system to the local coordinate system,ワールド座標系での方向をローカル座標系に変換する} public Vector3 worldToLocalDir(Vector3 woldDir) { return system.transform.InverseTransformDirection(woldDir); } /// @i{Returns Set world rotation,ワールド座標系で姿勢を設定する} public void setWorldRot(float xAngle, float yAngle, float zAngle) { setWorldRot(Quaternion.Euler(rotVal(xAngle), rotVal(yAngle), rotVal(zAngle))); } public void setWorldRot(Quaternion quat) { system.transform.localRotation = quat; } /// @i{Returns Set local rotation,ローカル座標系で姿勢を設定する} public void setLocalRot(float xAngle, float yAngle, float zAngle) { setLocalRot(Quaternion.Euler(rotVal(xAngle), rotVal(yAngle), rotVal(zAngle))); } public void setLocalRot(Quaternion quat) { system.transform.localRotation = quat; } /// @i{Returns SetLook at the camera,カメラの方を向かせる} public void lookAtCamera() { system.transform.LookAt(targetCamera.transform); system.transform.Rotate(0.0f, 180.0f, 0.0f); } /// @i{Returns SetLook at the camera,任意の点の方を向かせる} public void lookAt(float x, float y, float z) { lookAt(new Vector3(x, y, z)); } public void lookAt(Vector3 worldPosition) { lookAt(worldPosition, transform.up); } public void lookAt(Vector3 worldPosition, Vector3 worldUp) { system.transform.LookAt(worldPosition, worldUp); system.transform.Rotate(0.0f, 180.0f, 0.0f); } /// @i{Set specified layer and layer mask,指定のレイヤーとレイヤーマスクを設定} public void layerAndMask(int layerIndex) { layer(layerIndex); layerMask(1 << layerIndex); } public void layerAndMask(string layerName) { layer(layerName); layerMask(layerName); } /// @i{Set layer,レイヤーを設定} public void layer(int layerIndex) { if (system.style.layer != layerIndex) FlushSystemShapes(); system.style.layer = layerIndex; } public void layer(string layerName) { layer(LayerMask.NameToLayer(layerName)); } /// @i{Begin setting layer. Restore with endLayer(),レイヤーを設定を開始。endLayer()で元に戻す} public void beginLayer(string layerName) { beginLayer(LayerMask.NameToLayer(layerName)); } public void beginLayer(int layerIndex) { layerStack.Push(system.style.layer); layerMaskStack.Push(system.style.layerMask); layer(layerIndex); } /// @i{Restore layer settings,レイヤーを設定を元に戻す} public void endLayer() { layerMask(layerMaskStack.Pop()); layer(layerStack.Pop()); } /// @i{Set layer mask,レイヤーマスクを設定} public void layerMask(int layerBits) { system.style.layerMask = layerBits; if (targetCamera) { targetCamera.cullingMask = system.style.layerMask; } } public void layerMask(string layerName) { layerMask(1 << LayerMask.NameToLayer(layerName)); } public void layerMaskEverything() { layerMask(-1); } /// @i{Set layer to add to layer mask,レイヤーマスクに追加するレイヤーを設定} public void addLayerMask(int layerIndex) { layer(system.style.layerMask | 1 << layerIndex); } public void addLayerMask(string layerName) { layer(system.style.layerMask | 1 << LayerMask.NameToLayer(layerName)); } /// @i{Set layer to remove to layer mask,レイヤーマスクから削除するレイヤーを設定} public void removeLayerMask(int layerIndex) { layer(system.style.layerMask & ~(1 << layerIndex)); } public void removeLayerMask(string layerName) { layer(system.style.layerMask & ~(1 << LayerMask.NameToLayer(layerName))); } /// @i{Enable scene lights,シーンのライトをEnableにする} public void sceneLights() { Light[] lights = GetComponentsInChildren<Light>(); foreach (Light light in lights) { if (light.gameObject.layer == system.style.layer) { light.enabled = true; } } if (lights == null) createDirectionalLight(128, 128, 128, 0, 0, -1); } /// @i{Disable scene lights,シーンのライトをDisableにする} public void noSceneLights() { Light[] lights = GetComponentsInChildren<Light>(); foreach (Light light in lights) { if (light.gameObject.layer == system.style.layer) { light.enabled = false; } } } /// @i{Restore DepthStep to default value,DepthStepをデフォルト値に戻す} public void depthStep() { depthStep(DefaultDepthStep); } /// @i{Set DepthStep,DepthStepを設定する} public void depthStep(float step) { system.style.depthStep = step; addDepthStep(); } /// @i{Set DepthStep to 0 so as not to automatically change the overlap depth of drawing,DepthStepを0にして、描画の重ねあわせの深さを自動的に変えないようにする} public void noDepthStep() { system.style.depthStep = 0.0f; } private void addDepthStep() { system.style.depth += system.style.depthStep; } private void applyDepth() { if (targetCamera != null) { Vector3 dir = targetCamera.transform.forward; float d = -system.style.depth * system.axis.z; Vector3 depth = dir * d; system.transform.Translate(depth); } } /// @i{Load prefab from Resources folder,プレハブをリソースフォルダから読み込む} public GameObject loadPrefab(string path) { GameObject prefabObj = Resources.Load(path) as GameObject; if (!prefabObj) { debuglogWaring("loadPrefab <NotFound> " + path); return null; } return prefabObj; } /// @i{Create (Instantiate) GameObject from prefab and deactivate once,プレハブからGameObjectを作成(Instantiate)し、いったん非アクティブにする} public GameObject createObj(GameObject prefabObj) { GameObject obj = instantiateObj(prefabObj); if (!obj) { debuglogError("createObj <Failed> " + prefabObj); return null; } obj.SetActive(false); if (obj) keepGameObjs.Add(obj); return obj; } /// @i{Activate and display the GameObject that was being createdObj(),createObj()していたGameObjectをアクティブにして表示する} public void dispObj(GameObject createdObj) { dispObj(createdObj, Vector3.zero, Vector3.one); } public void dispObj(GameObject createdObj, float x, float y, float z = 0.0f, float sx = 1.0f, float sy = 1.0f, float sz = 1.0f) { dispObj(createdObj, new Vector3(x, y, z), new Vector3(sx, sy, sz)); } public void dispObj(GameObject createdObj, Vector3 pos, Vector3 scale) { Debug.Assert(createdObj); if (!createdObj.activeSelf /*&& keepGameObjs.Contains(createdObj)*/) // createObjectで作成したオブジェクトなら { createdObj.SetActive(true); } SetTransformObj(createdObj, pos, scale); } /// @i{Create and draw an object temporarily for this frame from prefab,プレハブからこのフレームだけ一時的にオブジェクトを作成して描く} public GameObject entryObj(GameObject prefabObj) { return entryObj(prefabObj, Vector3.zero, Vector3.one); } public GameObject entryObj(GameObject prefabObj, float x, float y, float z = 0.0f, float sx = 1.0f, float sy = 1.0f, float sz = 1.0f) { return entryObj(prefabObj, new Vector3(x, y, z), new Vector3(sx, sy, sz)); } public GameObject entryObj(GameObject prefabObj, Vector3 pos, Vector3 scale) { Debug.Assert(prefabObj); GameObject obj = instantiateObj(prefabObj); if (obj) tempGameObjs.Add(obj); SetTransformObj(obj, pos, scale); return obj; } /// @i{Draw GameObject. Call dipsObj() if the object is inactive\, call entryObj() if it is active,GameObjectを描く。渡したオブジェクトが非アクティブならdipsObj()を、アクティブならentryObj()を呼ぶ} public GameObject draw(GameObject obj) { return draw(obj, Vector3.zero, Vector3.one); } public GameObject draw(GameObject obj, float x, float y, float z = 0.0f, float sx = 1.0f, float sy = 1.0f, float sz = 1.0f) { return draw(obj, new Vector3(x, y, z), new Vector3(sx, sy, sz)); } public GameObject draw(GameObject obj, Vector3 pos, Vector3 scale) { Debug.Assert(obj); GameObject dispObj = null; if (!obj.activeSelf /*&& keepGameObjs.Contains(obj)*/) // createObjectで作成したオブジェクトなら { dispObj = obj; dispObj.SetActive(true); } else { dispObj = instantiateObj(obj); if (dispObj) tempGameObjs.Add(dispObj); } SetTransformObj(dispObj, pos, scale); return obj; } private GameObject instantiateObj(GameObject prefabObj) { if (!prefabObj) { debuglogWaring("prefab <Null Resource>"); return null; } GameObject obj = null; if (!obj) { obj = Instantiate(prefabObj) as GameObject; if (!obj) { debuglogWaring("prefab <Instantiate Failed>"); return null; } else { obj.transform.SetParent(system.objBox.transform); } } return obj; } private void SetTransformObj(GameObject obj, Vector3 pos, Vector3 scale) { obj.transform.position = system.transform.TransformPoint(pos); obj.transform.localScale = Vector3.Scale(system.transform.lossyScale, scale); obj.transform.rotation = system.transform.rotation; obj.gameObject.layer = system.style.layer; } /// @i{Destroy GameObject,GameObjectを破棄する} public void destroyObj(GameObject obj) { if (keepGameObjs.Contains(obj)) { keepGameObjs.Remove(obj); } else if (tempGameObjs.Contains(obj)) { tempGameObjs.Remove(obj); } Destroy(obj); } /// @i{Draw a mesh,メッシュを描く} public void mesh(Mesh mesh, float x, float y, float z = 0.0f, float sx = 1.0f, float sy = 1.0f, float sz = 1.0f, bool enableMaterial = true) { this.mesh(mesh, new Vector3(x, y, z), new Vector3(sx, sy, sz), enableMaterial); } public void mesh(Mesh mesh, Vector3 pos, Vector3 scale, bool enableMaterial = true) { this.mesh(mesh, null, pos, scale, enableMaterial); } private void mesh(Mesh mesh, Mesh wireMesh, Vector3 pos, Vector3 scale, bool enableMaterial = true) { pushMatrix(); translate(pos); system.transform.localScale = Vector3.Scale(system.transform.localScale, scale); Material material; if (system.style.isLighting) material = UMaterials.getFillMaterial(system.style.blendMode); else material = UMaterials.getFillUnlitMaterial(system.style.blendMode); MaterialPropertyBlock materialPB = null; if (enableMaterial) { materialPB = new MaterialPropertyBlock(); materialPB.SetColor("_Color", system.style.fillColor); if (system.style.texture != null) { materialPB.SetTexture("_MainTex", system.style.texture); } } Camera drawCam = null; // targetCamera; シーンビューに出なくなるのでひとまずnull Matrix4x4 matrix = system.transform.localToWorldMatrix; if (system.style.isFill) { for (int i = 0; i < mesh.subMeshCount; i++) { Graphics.DrawMesh(mesh, matrix, material, system.style.layer, drawCam, i, materialPB); } } if (system.style.isStroke && wireMesh != null) { material = UMaterials.getFillUnlitMaterial(system.style.blendMode); if (enableMaterial) { materialPB.SetColor("_Color", system.style.strokeColor); } for (int i = 0; i < wireMesh.subMeshCount; i++) { Graphics.DrawMesh(wireMesh, matrix, material, system.style.layer, drawCam, i, materialPB); } } popMatrix(); } /// @i{Draw a mesh held by GameObject,GameObjectが持つメッシュを描く} public void mesh(GameObject inMeshObj, float x, float y, float z = 0.0f, float sx = 1.0f, float sy = 1.0f, float sz = 1.0f, bool enableMaterial = true) { this.mesh(inMeshObj, new Vector3(x, y, z), new Vector3(sx, sy, sz), enableMaterial); } public void mesh(GameObject inMeshObj, Vector3 pos, Vector3 scale, bool enableMaterial = true) { Debug.Assert(inMeshObj); if (inMeshObj == null) { return; } MeshFilter meshFilter = inMeshObj.GetComponent<MeshFilter>(); if (meshFilter) { Mesh m = meshFilter.sharedMesh; Mesh wm = null; if (system.style.isStroke) { UWireframe wire = inMeshObj.GetComponent<UWireframe>(); if (!wire) { wire = inMeshObj.AddComponent<UWireframe>(); } if (!wire.mesh) { wire.RemakeMesh(m); } wm = wire.mesh; } if (m) { mesh(m, wm, pos, scale, enableMaterial); } } } /// @i{Draw a connected shape in the system,システムでまとめているシェイプを描き出す} public void flushSystemShapes() { FlushSystemShapes(); } #endregion #region USubGraphics private List<USubGraphics> subGraphics = new List<USubGraphics>(); /// @i{Add USubGraphics to the list. NOTE: USubGraphics automatically add() at the time of Start()\, so you do not need to call it yourself,USubGraphicsをリストに追加する。※USubGraphicsはStart()時に自動的にこの処理を行うので、独自に呼ぶ必要はない} public void add(USubGraphics sg) { if (sg != null && !subGraphics.Contains(sg)) subGraphics.Add(sg); } /// @i{Remove USubGraphics from the list. NOTE: USubGraphics automatically remove() on OnDestroy()\, so you do not need to call it yourself,USubGraphicsをリストから削除する。※USubGraphicsはOnDestroy()時に自動的にこの処理を行うので、独自に呼ぶ必要はない} public void remove(USubGraphics sg) { subGraphics.Remove(sg); } /// @i{Create USubGraphics that can be drawn by sharing UGprahics,UGprahicsを共有して描画できるUSubGraphicsを作成する} public USubGraphics createSubGraphics(System.Action<UGraphics> customDraw = null) { return createSubGraphics<USubGraphics>(name, null, null, customDraw); } public USubGraphics createSubGraphics(string name = "SubGraphics", System.Action<GameObject> preInit = null, System.Action<USubGraphics> postInit = null, System.Action<UGraphics> customDraw = null) { return createSubGraphics<USubGraphics>(name, preInit, postInit, customDraw); } /// @i{Create USubGraphics that can be drawn by sharing UGprahics,UGprahicsを共有して描画できるUSubGraphicsを作成する} /** @lang_en -------- @tparam T Subclass of USubGraphics or USubGraphics @param name Name of GameObject @param preInit Process to be done when creating GameObject @param postInit Process to be done after USubGraphics component creation @param customDraw Process to be done at drawing @end_lang @lang_jp -------- @tparam T USubGraphicsまたはその派生クラス @param name GameObjectの名前 @param preInit GameObject生成時に行いたい処理 @param postInit USubGraphicsコンポーネント生成後に行いたい処理 @param customDraw USubGraphics描画時に行いたい処理 @end_lang @code // Unicessing/Scripts/Samples/UnicessingMenu.cs addButton() createSubGraphics<UnicessingMenuButton>(name, obj => { BoxCollider collider = obj.AddComponent<BoxCollider>(); collider.center = new Vector3(x, y, 0); collider.size = new Vector3(8, 0.9f, 0.1f); }, button => { button.buttonName = name; button.buttonColor = buttonColor; button.fontColor = fontColor; buttonList.Add(button); } ); @endcode @sa USubGraphics */ public T createSubGraphics<T>(string name = "SubGraphics", System.Action<GameObject> preInit = null, System.Action<T> postInit = null, System.Action<UGraphics> customDraw = null) where T : USubGraphics { GameObject obj = new GameObject(name); obj.transform.SetParent(transform); //obj.transform.SetParent(system.objBox.transform); if (preInit != null) preInit(obj); T subGraphics = obj.AddComponent<T>(); subGraphics.g = this; if (postInit != null) postInit(subGraphics); if (customDraw != null) subGraphics.customDraw = customDraw; return subGraphics; } #endregion } }
44.793457
223
0.587831
[ "MIT" ]
ioio-creative/CityGallery_UnicessingDemo
Unicessing_Test/Assets/Unicessing/Scripts/System/Core/UGraphics.cs
75,237
C#
using System.Windows.Input; using Xamarin.Forms; namespace CoffeeChain.App.ViewModels { public class TokenTransferViewModel : BaseViewModel { private string _recipient; public string Recipient { get { return _recipient; } set { SetProperty(ref _recipient, value); } } private int _tokens; public int Tokens { get { return _tokens; } set { SetProperty(ref _tokens, value); } } public ICommand ExecuteTransactionCommand { get; private set; } public TokenTransferViewModel() { Title = "Kaffee Token übertragen"; ExecuteTransactionCommand = new Command(ExecuteTransaction); } private async void ExecuteTransaction() { System.Console.WriteLine($"Recipient: {Recipient}, Tokens: {Tokens}"); System.Console.WriteLine($"Sender: {_web3.TransactionManager.Account.Address}"); if (Recipient.IsNullOrEmpty() || Tokens <= 0) { System.Console.WriteLine("Invalid input for transaction. Aborting."); return; } IsBusy = true; var transactionId = await _coffeeEconomyService.TransfareTokensAsync(Recipient, Tokens); System.Console.WriteLine($"TransactionId: {transactionId}"); Recipient = null; Tokens = 0; IsBusy = false; } } }
29.615385
101
0.558442
[ "MIT" ]
illwerkevkw-innovationlab/CoffeeChain
CoffeeChain.App/CoffeeChain.App/ViewModels/TokenTransferViewModel.cs
1,543
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.Security.Authentication.Identity.Provider { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] #endif public enum SecondaryAuthenticationFactorAuthenticationStage { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ NotStarted, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ WaitingForUserConfirmation, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ CollectingCredential, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ SuspendingAuthentication, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ CredentialCollected, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ CredentialAuthenticated, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ StoppingAuthentication, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ ReadyForLock, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ CheckingDevicePresence, #endif } #endif }
31.170732
64
0.719092
[ "Apache-2.0" ]
06needhamt/uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Security.Authentication.Identity.Provider/SecondaryAuthenticationFactorAuthenticationStage.cs
1,278
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class Handsome : Trait { public override int GetSelfToAllySentimentGain(EnumSentiment sentiment, int baseSentiment) { return baseSentiment; } public override int GetAllyToSelfSentimentGain(EnumSentiment sentiment, int baseSentiment) { if (sentiment == EnumSentiment.Trust && baseSentiment > 0) { return (int) (baseSentiment*1.5); } return baseSentiment; } public override string GetName() { return "Handsome"; } public override string GetDescription() { return "Their beauty makes them strangely easy to trust."; } }
24.096774
94
0.665328
[ "MIT", "Unlicense" ]
Malan-Tai/SynCOM
Assets/Scripts/Characters/Traits/Handsome.cs
747
C#
/******************************************/ /* */ /* Copyright (c) 2020 monitor1394 */ /* https://github.com/monitor1394 */ /* */ /******************************************/ using System.Collections.Generic; using UnityEngine; namespace XUGL { public static class UGLHelper { public static bool IsValueEqualsColor(Color32 color1, Color32 color2) { return color1.a == color2.a && color1.b == color2.b && color1.g == color2.g && color1.r == color2.r; } public static bool IsValueEqualsColor(Color color1, Color color2) { return color1.a == color2.a && color1.b == color2.b && color1.g == color2.g && color1.r == color2.r; } public static bool IsValueEqualsString(string str1, string str2) { if (str1 == null && str2 == null) return true; else if (str1 != null && str2 != null) return str1.Equals(str2); else return false; } public static bool IsValueEqualsVector2(Vector2 v1, Vector2 v2) { return v1.x == v2.x && v1.y == v2.y; } public static bool IsValueEqualsVector3(Vector3 v1, Vector3 v2) { return v1.x == v2.x && v1.y == v2.y && v1.z == v2.z; } public static bool IsValueEqualsList<T>(List<T> list1, List<T> list2) { if (list1 == null || list2 == null) return false; if (list1.Count != list2.Count) return false; for (int i = 0; i < list1.Count; i++) { if (list1[i] == null && list2[i] == null) { } else { if (list1[i] != null) { if (!list1[i].Equals(list2[i])) return false; } else { if (!list2[i].Equals(list1[i])) return false; } } } return true; } public static bool IsClearColor(Color32 color) { return color.a == 0 && color.b == 0 && color.g == 0 && color.r == 0; } public static bool IsClearColor(Color color) { return color.a == 0 && color.b == 0 && color.g == 0 && color.r == 0; } public static bool IsZeroVector(Vector3 pos) { return pos.x == 0 && pos.y == 0 && pos.z == 0; } public static Vector3 RotateRound(Vector3 position, Vector3 center, Vector3 axis, float angle) { Vector3 point = Quaternion.AngleAxis(angle, axis) * (position - center); Vector3 resultVec3 = center + point; return resultVec3; } public static void GetBezierList(ref List<Vector3> posList, Vector3 sp, Vector3 ep, Vector3 lsp, Vector3 nep, float smoothness = 2f, float k = 2.0f) { float dist = Mathf.Abs(sp.x - ep.x); Vector3 cp1, cp2; var dir = (ep - sp).normalized; var diff = dist / k; if (lsp == sp) { cp1 = sp + dist / k * dir * 1; cp1.y = sp.y; cp1 = sp; } else { cp1 = sp + (ep - lsp).normalized * diff; } if (nep == ep) cp2 = ep; else cp2 = ep - (nep - sp).normalized * diff; dist = Vector3.Distance(sp, ep); int segment = (int)(dist / (smoothness <= 0 ? 2f : smoothness)); if (segment < 1) segment = (int)(dist / 0.5f); if (segment < 4) segment = 4; GetBezierList2(ref posList, sp, ep, segment, cp1, cp2); } public static void GetBezierListVertical(ref List<Vector3> posList, Vector3 sp, Vector3 ep, float smoothness = 2f, float k = 2.0f) { Vector3 dir = (ep - sp).normalized; float dist = Vector3.Distance(sp, ep); Vector3 cp1 = sp + dist / k * dir * 1; Vector3 cp2 = sp + dist / k * dir * (k - 1); cp1.x = sp.x; cp2.x = ep.x; int segment = (int)(dist / (smoothness <= 0 ? 2f : smoothness)); GetBezierList2(ref posList, sp, ep, segment, cp1, cp2); } public static List<Vector3> GetBezierList(Vector3 sp, Vector3 ep, int segment, Vector3 cp) { List<Vector3> list = new List<Vector3>(); for (int i = 0; i < segment; i++) { list.Add(GetBezier(i / (float)segment, sp, cp, ep)); } list.Add(ep); return list; } public static void GetBezierList2(ref List<Vector3> posList, Vector3 sp, Vector3 ep, int segment, Vector3 cp, Vector3 cp2) { posList.Clear(); if (posList.Capacity < segment + 1) { posList.Capacity = segment + 1; } for (int i = 0; i < segment; i++) { posList.Add((GetBezier2(i / (float)segment, sp, cp, cp2, ep))); } posList.Add(ep); } public static Vector3 GetBezier(float t, Vector3 sp, Vector3 cp, Vector3 ep) { Vector3 aa = sp + (cp - sp) * t; Vector3 bb = cp + (ep - cp) * t; return aa + (bb - aa) * t; } public static Vector3 GetBezier2(float t, Vector3 sp, Vector3 p1, Vector3 p2, Vector3 ep) { t = Mathf.Clamp01(t); var oneMinusT = 1f - t; return oneMinusT * oneMinusT * oneMinusT * sp + 3f * oneMinusT * oneMinusT * t * p1 + 3f * oneMinusT * t * t * p2 + t * t * t * ep; } public static Vector3 GetDire(float angle, bool isDegree = false) { angle = isDegree ? angle * Mathf.Deg2Rad : angle; return new Vector3(Mathf.Sin(angle), Mathf.Cos(angle)); } public static Vector3 GetVertialDire(Vector3 dire) { if (dire.x == 0) { return new Vector3(-1, 0, 0); } if (dire.y == 0) { return new Vector3(0, -1, 0); } else { return new Vector3(-dire.y / dire.x, 1, 0).normalized; } } /// <summary> /// 获得0-360的角度(12点钟方向为0度) /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <returns></returns> public static float GetAngle360(Vector2 from, Vector2 to) { float angle; Vector3 cross = Vector3.Cross(from, to); angle = Vector2.Angle(from, to); angle = cross.z > 0 ? -angle : angle; angle = (angle + 360) % 360; return angle; } public static Vector3 GetPos(Vector3 center, float radius, float angle, bool isDegree = false) { angle = isDegree ? angle * Mathf.Deg2Rad : angle; return new Vector3(center.x + radius * Mathf.Sin(angle), center.y + radius * Mathf.Cos(angle)); } } }
33.899543
117
0.45757
[ "MIT" ]
Amblion/unity-ugui-XCharts
Assets/XCharts/Runtime/XUGL/UGLHelper.cs
7,450
C#
namespace PanGu.Lucene.ImportTool { partial class FormImport { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormImport)); this.labelProgress = new System.Windows.Forms.Label(); this.progressBar = new System.Windows.Forms.ProgressBar(); this.buttonCreateIndex = new System.Windows.Forms.Button(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.linkLabel1 = new System.Windows.Forms.LinkLabel(); this.label1 = new System.Windows.Forms.Label(); this.buttonTestSpeed = new System.Windows.Forms.Button(); this.checkBoxDoubleThread = new System.Windows.Forms.CheckBox(); this.SuspendLayout(); // // labelProgress // this.labelProgress.AutoSize = true; this.labelProgress.Location = new System.Drawing.Point(421, 27); this.labelProgress.Name = "labelProgress"; this.labelProgress.Size = new System.Drawing.Size(21, 13); this.labelProgress.TabIndex = 3; this.labelProgress.Text = "0%"; // // progressBar // this.progressBar.Location = new System.Drawing.Point(24, 21); this.progressBar.Name = "progressBar"; this.progressBar.Size = new System.Drawing.Size(391, 26); this.progressBar.TabIndex = 2; // // buttonCreateIndex // this.buttonCreateIndex.Location = new System.Drawing.Point(24, 95); this.buttonCreateIndex.Name = "buttonCreateIndex"; this.buttonCreateIndex.Size = new System.Drawing.Size(75, 23); this.buttonCreateIndex.TabIndex = 4; this.buttonCreateIndex.Text = "创建索引"; this.buttonCreateIndex.UseVisualStyleBackColor = true; this.buttonCreateIndex.Click += new System.EventHandler(this.buttonCreateIndex_Click); // // openFileDialog // this.openFileDialog.DefaultExt = "xml"; this.openFileDialog.FileName = "news.xml"; this.openFileDialog.Filter = "xml|*.xml"; this.openFileDialog.RestoreDirectory = true; // // linkLabel1 // this.linkLabel1.AutoSize = true; this.linkLabel1.Location = new System.Drawing.Point(24, 69); this.linkLabel1.Name = "linkLabel1"; this.linkLabel1.Size = new System.Drawing.Size(418, 13); this.linkLabel1.TabIndex = 5; this.linkLabel1.TabStop = true; this.linkLabel1.Text = "http://pangusegment.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=31482"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(24, 53); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(115, 13); this.label1.TabIndex = 6; this.label1.Text = "News.xml 下载地址:"; // // buttonTestSpeed // this.buttonTestSpeed.Location = new System.Drawing.Point(119, 95); this.buttonTestSpeed.Name = "buttonTestSpeed"; this.buttonTestSpeed.Size = new System.Drawing.Size(93, 23); this.buttonTestSpeed.TabIndex = 7; this.buttonTestSpeed.Text = "测试分词速度"; this.buttonTestSpeed.UseVisualStyleBackColor = true; this.buttonTestSpeed.Click += new System.EventHandler(this.buttonTestSpeed_Click); // // checkBoxDoubleThread // this.checkBoxDoubleThread.AutoSize = true; this.checkBoxDoubleThread.Location = new System.Drawing.Point(229, 99); this.checkBoxDoubleThread.Name = "checkBoxDoubleThread"; this.checkBoxDoubleThread.Size = new System.Drawing.Size(134, 17); this.checkBoxDoubleThread.TabIndex = 8; this.checkBoxDoubleThread.Text = "双线程同时分词测试"; this.checkBoxDoubleThread.UseVisualStyleBackColor = true; // // FormImport // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(469, 130); this.Controls.Add(this.checkBoxDoubleThread); this.Controls.Add(this.buttonTestSpeed); this.Controls.Add(this.label1); this.Controls.Add(this.linkLabel1); this.Controls.Add(this.buttonCreateIndex); this.Controls.Add(this.labelProgress); this.Controls.Add(this.progressBar); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "FormImport"; this.Text = "Import tool"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label labelProgress; private System.Windows.Forms.ProgressBar progressBar; private System.Windows.Forms.Button buttonCreateIndex; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.LinkLabel linkLabel1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button buttonTestSpeed; private System.Windows.Forms.CheckBox checkBoxDoubleThread; } }
45.29932
143
0.585373
[ "Apache-2.0" ]
eaglet2006/pangu
PanGu4Lucene/PanGu.Lucene.ImportTool/FormImport.Designer.cs
6,709
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SitecoreCognitiveServices.Foundation.MSSDK.Speech.Models { public class OperationLocation { public string Url { get; set; } } }
22.666667
68
0.753676
[ "MIT" ]
markstiles/SitecoreCognitiveServices.Core
src/Foundation/MSSDK/code/Speech/Models/OperationLocation.cs
274
C#
// // Copyright (c) 2017 The nanoFramework project contributors // See LICENSE file in the project root for full license information. namespace Windows.Devices.WiFi { /// <summary> /// Describes whether to automatically reconnect to this network. /// </summary> public enum WiFiReconnectionKind { /// <summary> /// Reconnect automatically. /// </summary> Automatic, /// <summary> /// Allow user to reconnect manually. /// </summary> Manual } }
22.333333
69
0.598881
[ "Apache-2.0" ]
haeberle/lib-Windows.Devices.WiFi
source/Windows.Devices.WiFi/WiFiReconnectionKind.cs
538
C#
using CookPopularCSharpToolkit.Communal; using CookPopularCSharpToolkit.Windows; using System; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; /* * Copyright (c) 2021 All Rights Reserved. * Description:DataGridAssistant * Author: Chance_写代码的厨子 * Create Time:2021-04-02 17:03:39 */ namespace CookPopularControl.Controls { /// <summary> /// 提供<see cref="DataGrid"/>的附加属性基类 /// </summary> [TemplatePart(Name = ElementScrollViewer, Type = typeof(ScrollViewer))] [TemplatePart(Name = SelectAllButton, Type = typeof(System.Windows.Controls.Button))] [TemplatePart(Name = RowHeader, Type = typeof(DataGridRowHeader))] [TemplatePart(Name = RowHeaderCheckBox, Type = typeof(System.Windows.Controls.CheckBox))] public class DataGridAssistant { private const string ElementScrollViewer = "PART_ScrollViewer"; private const string SelectAllButton = "PART_SelectAllButton"; private const string RowHeader = "PART_DataGridRowHeader"; private const string RowHeaderCheckBox = "PART_RowCheckBox"; private const string ElementText = nameof(ElementText); private const string ElementComboBox = nameof(ElementComboBox); private const string ElementCheckBox = nameof(ElementCheckBox); #region IsApplyDefaultStyle public static bool GetIsApplyDefaultStyle(DependencyObject obj) => (bool)obj.GetValue(IsApplyDefaultStyleProperty); public static void SetIsApplyDefaultStyle(DependencyObject obj, bool value) => obj.SetValue(IsApplyDefaultStyleProperty, ValueBoxes.BooleanBox(value)); /// <summary> /// <see cref="IsApplyDefaultStyleProperty"/>标识<see cref="DataGridCell"/>是否引用CookPopularControl的默认样式 /// </summary> public static readonly DependencyProperty IsApplyDefaultStyleProperty = DependencyProperty.RegisterAttached("IsApplyDefaultStyle", typeof(bool), typeof(DataGridAssistant), new PropertyMetadata(ValueBoxes.FalseBox, OnIsApplyDefaultStyleChanged)); private static void OnIsApplyDefaultStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is DataGrid dg) { if ((bool)e.NewValue) { if (dg.AutoGenerateColumns) { dg.AutoGeneratingColumn += Dg_AutoGeneratingColumn; return; } dg.Loaded += (s, e) => SetDataGridCellDefaultStyle(dg); } else { dg.AutoGeneratingColumn += Dg_AutoGeneratingColumn; } } } private static void Dg_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) { if (sender is DataGrid dg) { SetDataGridCellDefaultStyle(dg); } } private static void SetDataGridCellDefaultStyle(DataGrid dg) { foreach (var column in dg.Columns.OfType<DataGridColumn>()) { if (column.GetType() == typeof(DataGridTextColumn)) { SetDataGridCellElementStyle(column, dg, ElementText); SetDataGridCellEditingElementStyle(column, dg, ElementText); } else if (column.GetType() == typeof(DataGridComboBoxColumn)) { SetDataGridCellElementStyle(column, dg, ElementComboBox); SetDataGridCellEditingElementStyle(column, dg, ElementComboBox); } else if (column.GetType() == typeof(DataGridCheckBoxColumn)) { SetDataGridCellElementStyle(column, dg, ElementCheckBox); SetDataGridCellEditingElementStyle(column, dg, ElementCheckBox); } } } #endregion #region IsRegisterSelectAll public static bool GetIsRegisterSelectAll(DependencyObject obj) => (bool)obj.GetValue(IsRegisterSelectAllProperty); public static void SetIsRegisterSelectAll(DependencyObject obj, bool value) => obj.SetValue(IsRegisterSelectAllProperty, value); /// <summary> /// <see cref="IsRegisterSelectAllProperty"/>标识注册全选与取消全选事件 /// </summary> public static readonly DependencyProperty IsRegisterSelectAllProperty = DependencyProperty.RegisterAttached("IsRegisterSelectAll", typeof(bool), typeof(DataGridAssistant), new PropertyMetadata(ValueBoxes.FalseBox, OnIsRegisterSelectAllChanged)); private static void OnIsRegisterSelectAllChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is DataGrid dataGrid) { dataGrid.Loaded += (s, arg) => { var scrollViewer = dataGrid.Template.FindName(ElementScrollViewer, dataGrid) as ScrollViewer; var selectedAllButton = scrollViewer.Template.FindName(SelectAllButton, scrollViewer) as System.Windows.Controls.Button; /** * 如果注册事件, * 则禁用PART_SelectAllButton控件模板中的Button的SelectAllCommand命令, * 否则将达不到取消全选的效果 */ var btnButton = selectedAllButton.Template.FindName("SelectAllButton", selectedAllButton) as System.Windows.Controls.Button; btnButton.Command = null; if ((bool)e.NewValue) { selectedAllButton.Click += (s, e) => SetSelectedAllButton(dataGrid); } else { selectedAllButton.Click -= (s, e) => SetSelectedAllButton(dataGrid); } }; } } private static void SetSelectedAllButton(DataGrid dg) { if (dg.SelectedItems.Count < dg.Items.Count) { dg.SelectAll(); } else { dg.UnselectAll(); } } #endregion #region IsShowSerialNumber public static bool GetIsShowSerialNumber(DependencyObject obj) => (bool)obj.GetValue(IsShowSerialNumberProperty); public static void SetIsShowSerialNumber(DependencyObject obj, bool value) => obj.SetValue(IsShowSerialNumberProperty, ValueBoxes.BooleanBox(value)); /// <summary> /// <see cref="IsShowSerialNumberProperty"/>是否显示排序 /// </summary> public static readonly DependencyProperty IsShowSerialNumberProperty = DependencyProperty.RegisterAttached("IsShowSerialNumber", typeof(bool), typeof(DataGridAssistant), new PropertyMetadata(ValueBoxes.FalseBox, OnIsShowSerialNumberChanged)); private static void OnIsShowSerialNumberChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is DataGrid dg) { if ((bool)e.NewValue) { dg.LoadingRow += Gd_LoadingRow; } else { dg.LoadingRow -= Gd_LoadingRow; } } } private static void Gd_LoadingRow(object sender, DataGridRowEventArgs e) { var dg = sender as DataGrid; var dgr = e.Row; if (dg != null && dgr != null) { if (dgr.IsLoaded) DataGridRowLoaded(dg, dgr); else dgr.Loaded += (s, e) => DataGridRowLoaded(dg, dgr); } } private static void DataGridRowLoaded(DataGrid dg, DataGridRow dgr) { var rowHeader = dgr.Template.FindName(RowHeader, dgr) as DataGridRowHeader; var checkBox = rowHeader.Template.FindName(RowHeaderCheckBox, rowHeader) as System.Windows.Controls.CheckBox; if (checkBox == null) return; if (GetIsShowSerialNumber(dg)) checkBox.Content = (dgr.GetIndex() + 1).ToString(); else checkBox.Content = null; } #endregion #region IsShowThickness public static bool GetIsShowThickness(DependencyObject obj) => (bool)obj.GetValue(IsShowThicknessProperty); public static void SetIsShowThickness(DependencyObject obj, bool value) => obj.SetValue(IsShowThicknessProperty, ValueBoxes.BooleanBox(value)); /// <summary> /// <see cref="IsShowThicknessProperty"/>标识是否显示线框 /// </summary> public static readonly DependencyProperty IsShowThicknessProperty = DependencyProperty.RegisterAttached("IsShowThickness", typeof(bool), typeof(DataGridAssistant), new PropertyMetadata(ValueBoxes.FalseBox)); #endregion #region IsEnableEditWithoutFocused public static bool GetIsEnableEditWithoutFocused(DependencyObject obj) => (bool)obj.GetValue(IsEnableEditWithoutFocusedProperty); public static void SetIsEnableEditWithoutFocused(DependencyObject obj, bool value) => obj.SetValue(IsEnableEditWithoutFocusedProperty, ValueBoxes.BooleanBox(value)); /// <summary> /// <see cref="IsEnableEditWithoutFocusedProperty"/>标识允许使用单击后在<see cref="DataGrid"/>的<see cref="DataGridCell"/>内部编辑组件。 /// </summary> /// <remarks>不需要先获取单元格焦点</remarks> public static readonly DependencyProperty IsEnableEditWithoutFocusedProperty = DependencyProperty.RegisterAttached("IsEnableEditWithoutFocused", typeof(bool), typeof(DataGridAssistant), new PropertyMetadata(ValueBoxes.FalseBox, OnIsEnableEditWithoutFocusedChanged)); private static void OnIsEnableEditWithoutFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is DataGrid dg) { if ((bool)e.NewValue) { dg.PreviewMouseLeftButtonDown += Dg_PreviewMouseLeftButtonDown; dg.KeyDown += Dg_KeyDown; } else { dg.PreviewMouseLeftButtonDown -= Dg_PreviewMouseLeftButtonDown; dg.KeyDown -= Dg_KeyDown; } } } private static void Dg_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { var originalSource = (DependencyObject)e.OriginalSource; var dataGridCell = originalSource.GetVisualAncestry().OfType<DataGridCell>().FirstOrDefault(); if (dataGridCell?.IsReadOnly ?? true) return; if (dataGridCell?.Content is UIElement element) { var dataGrid = (DataGrid)sender; var mousePosition = e.GetPosition(element); var elementHitBox = new Rect(element.RenderSize); if (elementHitBox.Contains(mousePosition)) { if (dataGridCell.Column.GetType() == typeof(DataGridTemplateColumn)) { return; } dataGrid.CurrentCell = new DataGridCellInfo(dataGridCell); dataGrid.BeginEdit(); switch (dataGridCell?.Content) { case ToggleButton toggleButton: { var newMouseEvent = new MouseButtonEventArgs(e.MouseDevice, 0, MouseButton.Left) { RoutedEvent = Mouse.MouseDownEvent, Source = dataGrid }; toggleButton.RaiseEvent(newMouseEvent); break; } case System.Windows.Controls.ComboBox comboBox: { comboBox.IsDropDownOpen = !comboBox.IsDropDownOpen; e.Handled = true; break; } default: break; } } } } private static void Dg_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) { if (sender is DataGrid dg) { if (e.Key == System.Windows.Input.Key.Space && e.OriginalSource is DataGridCell cell && !cell.IsReadOnly && cell.Column is DataGridComboBoxColumn) dg.BeginEdit(); } } #endregion #region DataGridCell public static Style GetTextColumnStyle(DependencyObject obj) => (Style)obj.GetValue(TextColumnStyleProperty); public static void SetTextColumnStyle(DependencyObject obj, Style value) => obj.SetValue(TextColumnStyleProperty, value); /// <summary> /// <see cref="TextColumnStyleProperty"/>标识<see cref="DataGridCell"/>默认文本样式 /// </summary> public static readonly DependencyProperty TextColumnStyleProperty = DependencyProperty.RegisterAttached("TextColumnStyle", typeof(Style), typeof(DataGridAssistant), new PropertyMetadata(default(Style), OnTextColumnStyleChanged)); private static void OnTextColumnStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is DataGrid dg && e.NewValue != null) { dg.AutoGeneratingColumn += (s, e) => SetDataGridCellElementStyle(e.Column, dg, ElementText); dg.AutoGeneratingColumn -= (s, e) => SetDataGridCellElementStyle(e.Column, dg, ElementText); } } public static Style GetTextColumnEditingStyle(DependencyObject obj) => (Style)obj.GetValue(TextColumnEditingStyleProperty); public static void SetTextColumnEditingStyle(DependencyObject obj, Style value) => obj.SetValue(TextColumnEditingStyleProperty, value); /// <summary> /// <see cref="TextColumnStyleProperty"/>标识<see cref="DataGridCell"/>编辑时文本样式 /// </summary> public static readonly DependencyProperty TextColumnEditingStyleProperty = DependencyProperty.RegisterAttached("TextColumnEditingStyle", typeof(Style), typeof(DataGridAssistant), new PropertyMetadata(default(Style), OnTextColumnEditingStyleChanged)); private static void OnTextColumnEditingStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is DataGrid dg && e.NewValue != null) { dg.AutoGeneratingColumn += (s, e) => SetDataGridCellEditingElementStyle(e.Column, dg, ElementText); dg.AutoGeneratingColumn -= (s, e) => SetDataGridCellEditingElementStyle(e.Column, dg, ElementText); } } public static Style GetComboBoxColumnStyle(DependencyObject obj) => (Style)obj.GetValue(ComboBoxColumnStyleProperty); public static void SetComboBoxColumnStyle(DependencyObject obj, Style value) => obj.SetValue(ComboBoxColumnStyleProperty, value); public static readonly DependencyProperty ComboBoxColumnStyleProperty = DependencyProperty.RegisterAttached("ComboBoxColumnStyle", typeof(Style), typeof(DataGridAssistant), new PropertyMetadata(default(Style), OnComboBoxColumnStyleChanged)); private static void OnComboBoxColumnStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is DataGrid dg && e.NewValue != null) { dg.AutoGeneratingColumn += (s, e) => SetDataGridCellElementStyle(e.Column, dg, ElementComboBox); dg.AutoGeneratingColumn -= (s, e) => SetDataGridCellElementStyle(e.Column, dg, ElementComboBox); } } public static Style GetComboBoxColumnEditingStyle(DependencyObject obj) => (Style)obj.GetValue(ComboBoxColumnEditingStyleProperty); public static void SetComboBoxColumnEditingStyle(DependencyObject obj, Style value) => obj.SetValue(ComboBoxColumnEditingStyleProperty, value); public static readonly DependencyProperty ComboBoxColumnEditingStyleProperty = DependencyProperty.RegisterAttached("ComboBoxColumnEditingStyle", typeof(Style), typeof(DataGridAssistant), new PropertyMetadata(default(Style), OnComboBoxColumnEditingStyleChanged)); private static void OnComboBoxColumnEditingStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is DataGrid dg && e.NewValue != null) { dg.AutoGeneratingColumn += (s, e) => SetDataGridCellEditingElementStyle(e.Column, dg, ElementComboBox); dg.AutoGeneratingColumn -= (s, e) => SetDataGridCellEditingElementStyle(e.Column, dg, ElementComboBox); } } public static Style GetCheckBoxColumnStyle(DependencyObject obj) => (Style)obj.GetValue(CheckBoxColumnStyleProperty); public static void SetCheckBoxColumnStyle(DependencyObject obj, Style value) => obj.SetValue(CheckBoxColumnStyleProperty, value); public static readonly DependencyProperty CheckBoxColumnStyleProperty = DependencyProperty.RegisterAttached("CheckBoxColumnStyle", typeof(Style), typeof(DataGridAssistant), new PropertyMetadata(default(Style), OnCheckBoxColumnStyleChanged)); private static void OnCheckBoxColumnStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is DataGrid dg && e.NewValue != null) { dg.AutoGeneratingColumn += (s, e) => SetDataGridCellElementStyle(e.Column, dg, ElementCheckBox); dg.AutoGeneratingColumn -= (s, e) => SetDataGridCellElementStyle(e.Column, dg, ElementCheckBox); } } public static Style GetCheckBoxColumnEditingStyle(DependencyObject obj) => (Style)obj.GetValue(CheckBoxColumnEditingStyleProperty); public static void SetCheckBoxColumnEditingStyle(DependencyObject obj, Style value) => obj.SetValue(CheckBoxColumnEditingStyleProperty, value); public static readonly DependencyProperty CheckBoxColumnEditingStyleProperty = DependencyProperty.RegisterAttached("CheckBoxColumnEditingStyle", typeof(Style), typeof(DataGridAssistant), new PropertyMetadata(default(Style), OnCheckBoxColumnEditingStyleChanged)); private static void OnCheckBoxColumnEditingStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is DataGrid dg && e.NewValue != null) { dg.AutoGeneratingColumn += (s, e) => SetDataGridCellEditingElementStyle(e.Column, dg, ElementCheckBox); dg.AutoGeneratingColumn -= (s, e) => SetDataGridCellEditingElementStyle(e.Column, dg, ElementCheckBox); } } private static void SetDataGridCellElementStyle(DataGridColumn column, DataGrid dg, string elementName) { object o = elementName switch { ElementText => (column as DataGridTextColumn).ElementStyle = GetTextColumnStyle(dg), ElementCheckBox => (column as DataGridCheckBoxColumn).ElementStyle = GetCheckBoxColumnStyle(dg), ElementComboBox => (column as DataGridComboBoxColumn).ElementStyle = GetComboBoxColumnStyle(dg), _ => throw new NotImplementedException(), }; } private static void SetDataGridCellEditingElementStyle(DataGridColumn column, DataGrid dg, string elementName) { object o = elementName switch { ElementText => (column as DataGridTextColumn).EditingElementStyle = GetTextColumnEditingStyle(dg), ElementCheckBox => (column as DataGridCheckBoxColumn).EditingElementStyle = GetCheckBoxColumnEditingStyle(dg), ElementComboBox => (column as DataGridComboBoxColumn).EditingElementStyle = GetComboBoxColumnEditingStyle(dg), _ => throw new NotImplementedException(), }; } #endregion } }
47.689252
199
0.628289
[ "Apache-2.0" ]
Muzsor/CookPopularControl
CookPopularControl/Controls/Grid/DataGridAssistant.cs
20,683
C#
#region License // Copyright 2004-2010 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion namespace Castle.Facilities.NHibernateIntegration.Tests.Issues { public class IssueTestCase : AbstractNHibernateTestCase { protected virtual string BugNumber { get { string ns = GetType().Namespace; return ns.Substring(ns.LastIndexOf('.') + 1); } } protected override string ConfigurationFile { get { return "Issues/" + BugNumber + "/facility.xml"; } } } }
29.131579
77
0.688347
[ "Apache-2.0" ]
ByteDecoder/Castle.Facilities.NHibernateIntegration
src/Castle.Facilities.NHibernateIntegration.Tests/Issues/IssueTestCase.cs
1,070
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TestFDM")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("TestFDM")] [assembly: AssemblyCopyright("Copyright © Microsoft 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("085f4c39-e4d0-4ab7-981a-d567744ca6aa")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.945946
85
0.727967
[ "MIT" ]
jdm7dv/financial
windows/CsForFinancialMarkets/CsForFinancialMarkets/BookExamples/Ch10/TestFDM/Properties/AssemblyInfo.cs
1,444
C#
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ /* ================================================================ * About NPOI * Author: Tony Qu * Author's email: tonyqus (at) gmail.com * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn) * HomePage: http://www.codeplex.com/npoi * Contributors: * * ==============================================================*/ using Npoi.Core.POIFS.EventFileSystem; using Npoi.Core.Util; using System; using System.Collections.Generic; using System.IO; namespace Npoi.Core.POIFS.FileSystem { /// <summary> /// This interface defines methods specific to Directory objects /// managed by a Filesystem instance. /// @author Marc Johnson (mjohnson at apache dot org) /// </summary> public interface DirectoryEntry : Entry, IEnumerable<Entry> { /// <summary> /// get an iterator of the Entry instances contained directly in /// this instance (in other words, children only; no grandchildren /// etc.) /// </summary> /// <value>The entries.never null, but hasNext() may return false /// immediately (i.e., this DirectoryEntry is empty). All /// objects retrieved by next() are guaranteed to be /// implementations of Entry.</value> IEnumerator<Entry> Entries { get; } /// <summary> /// get the names of all the Entries contained directly in this /// instance (in other words, names of children only; no grandchildren etc). /// </summary> /// <value>the names of all the entries that may be retrieved with /// getEntry(string), which may be empty (if this DirectoryEntry is empty /// </value> List<string> EntryNames { get; } /// <summary> ///is this DirectoryEntry empty? /// </summary> /// <value><c>true</c> if this instance contains no Entry instances; otherwise, <c>false</c>.</value> bool IsEmpty { get; } /// <summary> /// find out how many Entry instances are contained directly within /// this DirectoryEntry /// </summary> /// <value>number of immediately (no grandchildren etc.) contained /// Entry instances</value> int EntryCount { get; } /// <summary> /// get a specified Entry by name /// </summary> /// <param name="name">the name of the Entry to obtain.</param> /// <returns>the specified Entry, if it is directly contained in /// this DirectoryEntry</returns> Entry GetEntry(string name); /// <summary> /// Create a new DocumentEntry /// </summary> /// <param name="name">the name of the new DocumentEntry</param> /// <param name="stream">the Stream from which to Create the new DocumentEntry</param> /// <returns>the new DocumentEntry</returns> DocumentEntry CreateDocument(string name, Stream stream); // <summary> // Create a new DocumentEntry; the data will be provided later // </summary> // <param name="name">the name of the new DocumentEntry</param> // <param name="size">the size of the new DocumentEntry</param> // <returns>the new DocumentEntry</returns> //DocumentEntry CreateDocument(string name, int size); /// <summary> /// Create a new DocumentEntry; the data will be provided later /// </summary> /// <param name="name">the name of the new DocumentEntry</param> /// <param name="size">the size of the new DocumentEntry</param> /// <param name="writer">BeforeWriting event handler</param> /// <returns>the new DocumentEntry</returns> DocumentEntry CreateDocument(string name, int size, POIFSWriterListener writer); /// <summary> /// Create a new DirectoryEntry /// </summary> /// <param name="name">the name of the new DirectoryEntry</param> /// <returns>the name of the new DirectoryEntry</returns> DirectoryEntry CreateDirectory(string name); /// <summary> /// Gets or sets the storage ClassID. /// </summary> /// <value>The storage ClassID.</value> ClassID StorageClsid { get; set; } /// <summary> /// Checks if entry with specified name present /// </summary> /// <param name="name">entry name</param> /// <returns>true if have</returns> bool HasEntry(string name); } }
41.51145
109
0.595072
[ "Apache-2.0" ]
Arch/Npoi.Core
src/Npoi.Core/POIFS/FileSystem/DirectoryEntry.cs
5,440
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Properties; using System.Collections.Generic; namespace Microsoft.OpenApi.Validations.Rules { /// <summary> /// The validation rules for <see cref="OpenApiSchema"/>. /// </summary> [OpenApiRule] public static class OpenApiSchemaRules { /// <summary> /// Validate the data matches with the given data type. /// </summary> public static ValidationRule<OpenApiSchema> SchemaMismatchedDataType => new ValidationRule<OpenApiSchema>( (context, schema) => { // default context.Enter("default"); if (schema.Default != null) { RuleHelpers.ValidateDataTypeMismatch(context, nameof(SchemaMismatchedDataType), schema.Default, schema); } context.Exit(); // example context.Enter("example"); if (schema.Example != null) { RuleHelpers.ValidateDataTypeMismatch(context, nameof(SchemaMismatchedDataType), schema.Example, schema); } context.Exit(); // enum context.Enter("enum"); if (schema.Enum != null) { for (int i = 0; i < schema.Enum.Count; i++) { context.Enter(i.ToString()); RuleHelpers.ValidateDataTypeMismatch(context, nameof(SchemaMismatchedDataType), schema.Enum[i], schema); context.Exit(); } } context.Exit(); }); /// <summary> /// Validates Schema Discriminator /// </summary> public static ValidationRule<OpenApiSchema> ValidateSchemaDiscriminator => new ValidationRule<OpenApiSchema>( (context, schema) => { // discriminator context.Enter("discriminator"); if(schema.Reference != null && schema.Discriminator != null) { if (!schema.Required.Contains(schema.Discriminator?.PropertyName)) { context.CreateError(nameof(ValidateSchemaDiscriminator), string.Format(SRResource.Validation_SchemaRequiredFieldListMustContainThePropertySpecifiedInTheDiscriminator, schema.Reference.Id, schema.Discriminator.PropertyName)); } } context.Exit(); }); /// <summary> /// Validates OneOf Discriminator /// </summary> public static ValidationRule<OpenApiSchema> ValidateOneOfDiscriminator => new ValidationRule<OpenApiSchema>( (context, schema) => { // oneOf context.Enter("oneOf"); if (schema.OneOf != null && schema.Discriminator != null) { ValidateSchemaListDiscriminator(context, nameof(ValidateOneOfDiscriminator), schema.OneOf, schema.Discriminator); } context.Exit(); }); // <summary> /// Validates AnyOf Discriminator /// </summary> public static ValidationRule<OpenApiSchema> ValidateAnyOfDiscriminator => new ValidationRule<OpenApiSchema>( (context, schema) => { // oneOf context.Enter("anyOf"); if (schema.AnyOf != null && schema.Discriminator != null) { ValidateSchemaListDiscriminator(context, nameof(ValidateAnyOfDiscriminator), schema.AnyOf, schema.Discriminator); } context.Exit(); }); // add more rule. /// <summary> /// Checks if the schemas in the list contain a property with the property name specified by the discriminator. /// </summary> private static void ValidateSchemaListDiscriminator(IValidationContext context, string ruleName, IList<OpenApiSchema> schemas, OpenApiDiscriminator discriminator) { foreach (var schema in schemas) { if (schema.Reference != null && !schema.Properties.ContainsKey(discriminator.PropertyName)) { context.CreateError(ruleName, string.Format(SRResource.Validation_CompositeSchemaMustContainPropertySpecifiedInTheDiscriminator, schema.Reference.Id, discriminator.PropertyName)); } if (schema.Reference != null && !schema.Required.Contains(discriminator.PropertyName)) { context.CreateError(ruleName, string.Format(SRResource.Validation_CompositeSchemaRequiredFieldListMustContainThePropertySpecifiedInTheDiscriminator, schema.Reference.Id, discriminator.PropertyName)); } } } } }
39.094595
157
0.499654
[ "MIT" ]
senthilkumarmohan/OpenAPI.NET
src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs
5,788
C#
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. #if STRIDE_GRAPHICS_API_DIRECT3D11 // Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // 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.Collections.Generic; using SharpDX.Direct3D; using SharpDX.Direct3D11; using SharpDX.DXGI; using Stride.Core; using Stride.Core.Mathematics; using ResultCode = SharpDX.DXGI.ResultCode; namespace Stride.Graphics { /// <summary> /// Provides methods to retrieve and manipulate an graphics output (a monitor), it is equivalent to <see cref="Output"/>. /// </summary> /// <msdn-id>bb174546</msdn-id> /// <unmanaged>IDXGIOutput</unmanaged> /// <unmanaged-short>IDXGIOutput</unmanaged-short> public partial class GraphicsOutput { private readonly int outputIndex; private readonly Output output; private readonly OutputDescription outputDescription; /// <summary> /// Initializes a new instance of <see cref="GraphicsOutput" />. /// </summary> /// <param name="adapter">The adapter.</param> /// <param name="outputIndex">Index of the output.</param> /// <exception cref="System.ArgumentNullException">output</exception> /// <exception cref="ArgumentOutOfRangeException">output</exception> internal GraphicsOutput(GraphicsAdapter adapter, int outputIndex) { if (adapter == null) throw new ArgumentNullException("adapter"); this.outputIndex = outputIndex; this.adapter = adapter; this.output = adapter.NativeAdapter.GetOutput(outputIndex).DisposeBy(this); outputDescription = output.Description; unsafe { var rectangle = outputDescription.DesktopBounds; desktopBounds = *(Rectangle*)&rectangle; } } /// <summary> /// Find the display mode that most closely matches the requested display mode. /// </summary> /// <param name="targetProfiles">The target profile, as available formats are different depending on the feature level..</param> /// <param name="mode">The mode.</param> /// <returns>Returns the closes display mode.</returns> /// <unmanaged>HRESULT IDXGIOutput::FindClosestMatchingMode([In] const DXGI_MODE_DESC* pModeToMatch,[Out] DXGI_MODE_DESC* pClosestMatch,[In, Optional] IUnknown* pConcernedDevice)</unmanaged> /// <remarks>Direct3D devices require UNORM formats. This method finds the closest matching available display mode to the mode specified in pModeToMatch. Similarly ranked fields (i.e. all specified, or all unspecified, etc) are resolved in the following order. ScanlineOrdering Scaling Format Resolution RefreshRate When determining the closest value for a particular field, previously matched fields are used to filter the display mode list choices, and other fields are ignored. For example, when matching Resolution, the display mode list will have already been filtered by a certain ScanlineOrdering, Scaling, and Format, while RefreshRate is ignored. This ordering doesn't define the absolute ordering for every usage scenario of FindClosestMatchingMode, because the application can choose some values initially, effectively changing the order that fields are chosen. Fields of the display mode are matched one at a time, generally in a specified order. If a field is unspecified, FindClosestMatchingMode gravitates toward the values for the desktop related to this output. If this output is not part of the desktop, then the default desktop output is used to find values. If an application uses a fully unspecified display mode, FindClosestMatchingMode will typically return a display mode that matches the desktop settings for this output. Unspecified fields are lower priority than specified fields and will be resolved later than specified fields.</remarks> public DisplayMode FindClosestMatchingDisplayMode(GraphicsProfile[] targetProfiles, DisplayMode mode) { if (targetProfiles == null) throw new ArgumentNullException("targetProfiles"); ModeDescription closestDescription; SharpDX.Direct3D11.Device deviceTemp = null; try { var features = new SharpDX.Direct3D.FeatureLevel[targetProfiles.Length]; for (int i = 0; i < targetProfiles.Length; i++) { features[i] = (FeatureLevel)targetProfiles[i]; } deviceTemp = new SharpDX.Direct3D11.Device(adapter.NativeAdapter, SharpDX.Direct3D11.DeviceCreationFlags.None, features); } catch (Exception) { } var description = new SharpDX.DXGI.ModeDescription() { Width = mode.Width, Height = mode.Height, RefreshRate = mode.RefreshRate.ToSharpDX(), Format = (SharpDX.DXGI.Format)mode.Format, Scaling = DisplayModeScaling.Unspecified, ScanlineOrdering = DisplayModeScanlineOrder.Unspecified, }; using (var device = deviceTemp) output.GetClosestMatchingMode(device, description, out closestDescription); return DisplayMode.FromDescription(closestDescription); } /// <summary> /// Retrieves the handle of the monitor associated with this <see cref="GraphicsOutput"/>. /// </summary> /// <msdn-id>bb173068</msdn-id> /// <unmanaged>HMONITOR Monitor</unmanaged> /// <unmanaged-short>HMONITOR Monitor</unmanaged-short> public IntPtr MonitorHandle { get { return outputDescription.MonitorHandle; } } /// <summary> /// Gets the native output. /// </summary> /// <value>The native output.</value> internal Output NativeOutput { get { return output; } } /// <summary> /// Enumerates all available display modes for this output and stores them in <see cref="SupportedDisplayModes"/>. /// </summary> private void InitializeSupportedDisplayModes() { var modesAvailable = new List<DisplayMode>(); var modesMap = new Dictionary<string, DisplayMode>(); #if DIRECTX11_1 var output1 = output.QueryInterface<Output1>(); #endif try { const DisplayModeEnumerationFlags displayModeEnumerationFlags = DisplayModeEnumerationFlags.Interlaced | DisplayModeEnumerationFlags.Scaling; foreach (var format in Enum.GetValues(typeof(SharpDX.DXGI.Format))) { var dxgiFormat = (Format)format; #if DIRECTX11_1 var modes = output1.GetDisplayModeList1(dxgiFormat, displayModeEnumerationFlags); #else var modes = output.GetDisplayModeList(dxgiFormat, displayModeEnumerationFlags); #endif foreach (var mode in modes) { if (mode.Scaling == DisplayModeScaling.Unspecified) { var key = format + ";" + mode.Width + ";" + mode.Height + ";" + mode.RefreshRate.Numerator + ";" + mode.RefreshRate.Denominator; DisplayMode oldMode; if (!modesMap.TryGetValue(key, out oldMode)) { var displayMode = DisplayMode.FromDescription(mode); modesMap.Add(key, displayMode); modesAvailable.Add(displayMode); } } } } } catch (SharpDX.SharpDXException dxgiException) { if (dxgiException.ResultCode != ResultCode.NotCurrentlyAvailable) throw; } #if DIRECTX11_1 output1.Dispose(); #endif supportedDisplayModes = modesAvailable.ToArray(); } /// <summary> /// Initializes <see cref="CurrentDisplayMode"/> with the most appropiate mode from <see cref="SupportedDisplayModes"/>. /// </summary> /// <remarks>It checks first for a mode with <see cref="Format.R8G8B8A8_UNorm"/>, /// if it is not found - it checks for <see cref="Format.B8G8R8A8_UNorm"/>.</remarks> private void InitializeCurrentDisplayMode() { currentDisplayMode = TryFindMatchingDisplayMode(Format.R8G8B8A8_UNorm) ?? TryFindMatchingDisplayMode(Format.B8G8R8A8_UNorm); } /// <summary> /// Tries to find a display mode that has the same size as the current <see cref="OutputDescription"/> associated with this instance /// of the specified format. /// </summary> /// <param name="format">The format to match with.</param> /// <returns>A matched <see cref="DisplayMode"/> or null if nothing is found.</returns> private DisplayMode TryFindMatchingDisplayMode(Format format) { var desktopBounds = outputDescription.DesktopBounds; foreach (var supportedDisplayMode in SupportedDisplayModes) { var width = desktopBounds.Right - desktopBounds.Left; var height = desktopBounds.Bottom - desktopBounds.Top; if (supportedDisplayMode.Width == width && supportedDisplayMode.Height == height && (Format)supportedDisplayMode.Format == format) { // Stupid DXGI, there is no way to get the DXGI.Format, nor the refresh rate. return new DisplayMode((PixelFormat)format, width, height, supportedDisplayMode.RefreshRate); } } return null; } } } #endif
49.235808
1,483
0.640532
[ "MIT" ]
Alan-love/xenko
sources/engine/Stride.Graphics/Direct3D/GraphicsOutput.Direct3D.cs
11,275
C#
/* _BEGIN_TEMPLATE_ { "id": "EX1_316", "name": [ "力量的代价", "Power Overwhelming" ], "text": [ "使一个友方随从获得+4/+4,该随从会在回合结束时死亡。", "Give a friendly minion +4/+4 until end of turn. Then, it dies. Horribly." ], "cardClass": "WARLOCK", "type": "SPELL", "cost": 1, "rarity": "COMMON", "set": "HOF", "collectible": true, "dbfId": 846 } _END_TEMPLATE_ */ namespace HREngine.Bots { class Sim_EX1_316 : SimTemplate //poweroverwhelming { //Give a friendly minion +4/+4 until end of turn. Then, it dies. Horribly. public override void onCardPlay(Playfield p, bool ownplay, Minion target, int choice) { p.minionGetBuffed(target, 4, 4); if (ownplay) { target.destroyOnOwnTurnEnd = true; } else { target.destroyOnEnemyTurnEnd = true; } } } }
21.511628
93
0.541622
[ "MIT" ]
chi-rei-den/Silverfish
cards/HOF/EX1/Sim_EX1_316.cs
981
C#
namespace UblTr.Common { [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] [System.Xml.Serialization.XmlRootAttribute("TrainID", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", IsNullable = false)] public partial class TrainIDType : IdentifierType1 { } }
51.416667
162
0.768233
[ "MIT" ]
canyener/Ubl-Tr
Ubl-Tr/Common/CommonBasicComponents/TrainIDType.cs
617
C#
#pragma warning disable CS1591 /* * * * * * A simple JSON Parser / builder * ------------------------------ * * It mainly has been written as a simple JSON parser. It can build a JSON string * from the node-tree, or generate a node tree from any valid JSON string. * * If you want to use compression when saving to file / stream / B64 you have to include * SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ ) in your project and * define "USE_SharpZipLib" at the top of the file * * Written by Bunny83 * 2012-06-09 * * [2012-06-09 First Version] * - provides strongly typed node classes and lists / dictionaries * - provides easy access to class members / array items / data values * - the parser now properly identifies types. So generating JSON with this framework should work. * - only double quotes (") are used for quoting strings. * - provides "casting" properties to easily convert to / from those types: * int / float / double / bool * - provides a common interface for each node so no explicit casting is required. * - the parser tries to avoid errors, but if malformed JSON is parsed the result is more or less undefined * - It can serialize/deserialize a node tree into/from an experimental compact binary format. It might * be handy if you want to store things in a file and don't want it to be easily modifiable * * [2012-12-17 Update] * - Added internal JSONLazyCreator class which simplifies the construction of a JSON tree * Now you can simple reference any item that doesn't exist yet and it will return a JSONLazyCreator * The class determines the required type by it's further use, creates the type and removes itself. * - Added binary serialization / deserialization. * - Added support for BZip2 zipped binary format. Requires the SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ ) * The usage of the SharpZipLib library can be disabled by removing or commenting out the USE_SharpZipLib define at the top * - The serializer uses different types when it comes to store the values. Since my data values * are all of type string, the serializer will "try" which format fits best. The order is: int, float, double, bool, string. * It's not the most efficient way but for a moderate amount of data it should work on all platforms. * * [2017-03-08 Update] * - Optimised parsing by using a StringBuilder for token. This prevents performance issues when large * string data fields are contained in the json data. * - Finally refactored the badly named JSONClass into JSONObject. * - Replaced the old JSONData class by distict typed classes ( JSONString, JSONNumber, JSONBool, JSONNull ) this * allows to propertly convert the node tree back to json without type information loss. The actual value * parsing now happens at parsing time and not when you actually access one of the casting properties. * * [2017-04-11 Update] * - Fixed parsing bug where empty string values have been ignored. * - Optimised "ToString" by using a StringBuilder internally. This should heavily improve performance for large files * - Changed the overload of "ToString(string aIndent)" to "ToString(int aIndent)" * * [2017-11-29 Update] * - Removed the IEnumerator implementations on JSONArray & JSONObject and replaced it with a common * struct Enumerator in JSONNode that should avoid garbage generation. The enumerator always works * on KeyValuePair<string, JSONNode>, even for JSONArray. * - Added two wrapper Enumerators that allows for easy key or value enumeration. A JSONNode now has * a "Keys" and a "Values" enumerable property. Those are also struct enumerators / enumerables * - A KeyValuePair<string, JSONNode> can now be implicitly converted into a JSONNode. This allows * a foreach loop over a JSONNode to directly access the values only. Since KeyValuePair as well as * all the Enumerators are structs, no garbage is allocated. * - To add Linq support another "LinqEnumerator" is available through the "Linq" property. This * enumerator does implement the generic IEnumerable interface so most Linq extensions can be used * on this enumerable object. This one does allocate memory as it's a wrapper class. * - The Escape method now escapes all control characters (# < 32) in strings as uncode characters * (\uXXXX) and if the static bool JSONNode.forceASCII is set to true it will also escape all * characters # > 127. This might be useful if you require an ASCII output. Though keep in mind * when your strings contain many non-ascii characters the strings become much longer (x6) and are * no longer human readable. * - The node types JSONObject and JSONArray now have an "Inline" boolean switch which will default to * false. It can be used to serialize this element inline even you serialize with an indented format * This is useful for arrays containing numbers so it doesn't place every number on a new line * - Extracted the binary serialization code into a seperate extension file. All classes are now declared * as "partial" so an extension file can even add a new virtual or abstract method / interface to * JSONNode and override it in the concrete type classes. It's of course a hacky approach which is * generally not recommended, but i wanted to keep everything tightly packed. * - Added a static CreateOrGet method to the JSONNull class. Since this class is immutable it could * be reused without major problems. If you have a lot null fields in your data it will help reduce * the memory / garbage overhead. I also added a static setting (reuseSameInstance) to JSONNull * (default is true) which will change the behaviour of "CreateOrGet". If you set this to false * CreateOrGet will not reuse the cached instance but instead create a new JSONNull instance each time. * I made the JSONNull constructor private so if you need to create an instance manually use * JSONNull.CreateOrGet() * * [2018-01-09 Update] * - Changed all double.TryParse and double.ToString uses to use the invariant culture to avoid problems * on systems with a culture that uses a comma as decimal point. * * [2018-01-26 Update] * - Added AsLong. Note that a JSONNumber is stored as double and can't represent all long values. However * storing it as string would work. * - Added static setting "JSONNode.longAsString" which controls the default type that is used by the * LazyCreator when using AsLong * * [2018-04-25 Update] * - Added support for parsing single values (JSONBool, JSONString, JSONNumber, JSONNull) as top level value. * * The MIT License (MIT) * * Copyright (c) 2012-2017 Markus Göbel (Bunny83) * * 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.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace BitArmory.ReCaptcha.Utils { public enum JsonNodeType { Array = 1, Object = 2, String = 3, Number = 4, NullValue = 5, Boolean = 6, None = 7, Custom = 0xFF, } public enum JsonTextMode { Compact, Indent } public abstract partial class JsonNode { #region Enumerators public struct Enumerator { private enum Type { None, Array, Object } private Type type; private Dictionary<string, JsonNode>.Enumerator m_Object; private List<JsonNode>.Enumerator m_Array; public bool IsValid { get { return type != Type.None; } } public Enumerator(List<JsonNode>.Enumerator aArrayEnum) { type = Type.Array; m_Object = default(Dictionary<string, JsonNode>.Enumerator); m_Array = aArrayEnum; } public Enumerator(Dictionary<string, JsonNode>.Enumerator aDictEnum) { type = Type.Object; m_Object = aDictEnum; m_Array = default(List<JsonNode>.Enumerator); } public KeyValuePair<string, JsonNode> Current { get { if (type == Type.Array) return new KeyValuePair<string, JsonNode>(string.Empty, m_Array.Current); else if (type == Type.Object) return m_Object.Current; return new KeyValuePair<string, JsonNode>(string.Empty, null); } } public bool MoveNext() { if (type == Type.Array) return m_Array.MoveNext(); else if (type == Type.Object) return m_Object.MoveNext(); return false; } } public struct ValueEnumerator { private Enumerator m_Enumerator; public ValueEnumerator(List<JsonNode>.Enumerator aArrayEnum) : this(new Enumerator(aArrayEnum)) { } public ValueEnumerator(Dictionary<string, JsonNode>.Enumerator aDictEnum) : this(new Enumerator(aDictEnum)) { } public ValueEnumerator(Enumerator aEnumerator) { m_Enumerator = aEnumerator; } public JsonNode Current { get { return m_Enumerator.Current.Value; } } public bool MoveNext() { return m_Enumerator.MoveNext(); } public ValueEnumerator GetEnumerator() { return this; } } public struct KeyEnumerator { private Enumerator m_Enumerator; public KeyEnumerator(List<JsonNode>.Enumerator aArrayEnum) : this(new Enumerator(aArrayEnum)) { } public KeyEnumerator(Dictionary<string, JsonNode>.Enumerator aDictEnum) : this(new Enumerator(aDictEnum)) { } public KeyEnumerator(Enumerator aEnumerator) { m_Enumerator = aEnumerator; } public string Current { get { return m_Enumerator.Current.Key; } } public bool MoveNext() { return m_Enumerator.MoveNext(); } public KeyEnumerator GetEnumerator() { return this; } } public class LinqEnumerator : IEnumerator<KeyValuePair<string, JsonNode>>, IEnumerable<KeyValuePair<string, JsonNode>> { private JsonNode m_Node; private Enumerator m_Enumerator; internal LinqEnumerator(JsonNode aNode) { m_Node = aNode; if (m_Node != null) m_Enumerator = m_Node.GetEnumerator(); } public KeyValuePair<string, JsonNode> Current { get { return m_Enumerator.Current; } } object IEnumerator.Current { get { return m_Enumerator.Current; } } public bool MoveNext() { return m_Enumerator.MoveNext(); } public void Dispose() { m_Node = null; m_Enumerator = new Enumerator(); } public IEnumerator<KeyValuePair<string, JsonNode>> GetEnumerator() { return new LinqEnumerator(m_Node); } public void Reset() { if (m_Node != null) m_Enumerator = m_Node.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return new LinqEnumerator(m_Node); } } #endregion Enumerators #region common interface public static bool forceASCII = false; // Use Unicode by default public static bool longAsString = false; // lazy creator creates a JSONString instead of JSONNumber public abstract JsonNodeType Tag { get; } public virtual JsonNode this[int aIndex] { get { return null; } set { } } public virtual JsonNode this[string aKey] { get { return null; } set { } } public virtual string Value { get { return ""; } set { } } public virtual int Count { get { return 0; } } public virtual bool IsNumber { get { return false; } } public virtual bool IsString { get { return false; } } public virtual bool IsBoolean { get { return false; } } public virtual bool IsNull { get { return false; } } public virtual bool IsArray { get { return false; } } public virtual bool IsObject { get { return false; } } public virtual bool Inline { get { return false; } set { } } public virtual void Add(string aKey, JsonNode aItem) { } public virtual void Add(JsonNode aItem) { Add("", aItem); } public virtual JsonNode Remove(string aKey) { return null; } public virtual JsonNode Remove(int aIndex) { return null; } public virtual JsonNode Remove(JsonNode aNode) { return aNode; } public virtual IEnumerable<JsonNode> Children { get { yield break; } } public IEnumerable<JsonNode> DeepChildren { get { foreach (var C in this.Children) foreach (var D in C.DeepChildren) yield return D; } } public override string ToString() { StringBuilder sb = new StringBuilder(); WriteToStringBuilder(sb, 0, 0, JsonTextMode.Compact); return sb.ToString(); } public virtual string ToString(int aIndent) { StringBuilder sb = new StringBuilder(); WriteToStringBuilder(sb, 0, aIndent, JsonTextMode.Indent); return sb.ToString(); } internal abstract void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JsonTextMode aMode); public abstract Enumerator GetEnumerator(); public IEnumerable<KeyValuePair<string, JsonNode>> Linq { get { return new LinqEnumerator(this); } } public KeyEnumerator Keys { get { return new KeyEnumerator(GetEnumerator()); } } public ValueEnumerator Values { get { return new ValueEnumerator(GetEnumerator()); } } #endregion common interface #region typecasting properties public virtual double AsDouble { get { double v = 0.0; if (double.TryParse(this.Value,NumberStyles.Float, CultureInfo.InvariantCulture, out v)) return v; return 0.0; } set { this.Value = value.ToString(CultureInfo.InvariantCulture); } } public virtual int AsInt { get { return (int)this.AsDouble; } set { this.AsDouble = value; } } public virtual float AsFloat { get { return (float)this.AsDouble; } set { this.AsDouble = value; } } public virtual bool AsBool { get { bool v = false; if (bool.TryParse(this.Value, out v)) return v; return !string.IsNullOrEmpty(this.Value); } set { this.Value = (value) ? "true" : "false"; } } public virtual long AsLong { get { long val = 0; if (long.TryParse(this.Value, out val)) return val; return 0L; } set { this.Value = value.ToString(); } } public virtual JsonArray AsArray { get { return this as JsonArray; } } public virtual JsonObject AsObject { get { return this as JsonObject; } } #endregion typecasting properties #region operators public static implicit operator JsonNode(string s) { return new JsonString(s); } public static implicit operator string(JsonNode d) { return (d == null) ? null : d.Value; } public static implicit operator JsonNode(double n) { return new JsonNumber(n); } public static implicit operator double(JsonNode d) { return (d == null) ? 0 : d.AsDouble; } public static implicit operator JsonNode(float n) { return new JsonNumber(n); } public static implicit operator float(JsonNode d) { return (d == null) ? 0 : d.AsFloat; } public static implicit operator JsonNode(int n) { return new JsonNumber(n); } public static implicit operator int(JsonNode d) { return (d == null) ? 0 : d.AsInt; } public static implicit operator JsonNode(long n) { if (longAsString) return new JsonString(n.ToString()); return new JsonNumber(n); } public static implicit operator long(JsonNode d) { return (d == null) ? 0L : d.AsLong; } public static implicit operator JsonNode(bool b) { return new JsonBool(b); } public static implicit operator bool(JsonNode d) { return (d == null) ? false : d.AsBool; } public static implicit operator JsonNode(KeyValuePair<string, JsonNode> aKeyValue) { return aKeyValue.Value; } public static bool operator ==(JsonNode a, object b) { if (ReferenceEquals(a, b)) return true; bool aIsNull = a is JsonNull || ReferenceEquals(a, null) || a is JsonLazyCreator; bool bIsNull = b is JsonNull || ReferenceEquals(b, null) || b is JsonLazyCreator; if (aIsNull && bIsNull) return true; return !aIsNull && a.Equals(b); } public static bool operator !=(JsonNode a, object b) { return !(a == b); } public override bool Equals(object obj) { return ReferenceEquals(this, obj); } public override int GetHashCode() { return base.GetHashCode(); } #endregion operators [ThreadStatic] private static StringBuilder m_EscapeBuilder; internal static StringBuilder EscapeBuilder { get { if (m_EscapeBuilder == null) m_EscapeBuilder = new StringBuilder(); return m_EscapeBuilder; } } internal static string Escape(string aText) { var sb = EscapeBuilder; sb.Length = 0; if (sb.Capacity < aText.Length + aText.Length / 10) sb.Capacity = aText.Length + aText.Length / 10; foreach (char c in aText) { switch (c) { case '\\': sb.Append("\\\\"); break; case '\"': sb.Append("\\\""); break; case '\n': sb.Append("\\n"); break; case '\r': sb.Append("\\r"); break; case '\t': sb.Append("\\t"); break; case '\b': sb.Append("\\b"); break; case '\f': sb.Append("\\f"); break; default: if (c < ' ' || (forceASCII && c > 127)) { ushort val = c; sb.Append("\\u").Append(val.ToString("X4")); } else sb.Append(c); break; } } string result = sb.ToString(); sb.Length = 0; return result; } private static JsonNode ParseElement(string token, bool quoted) { if (quoted) return token; string tmp = token.ToLower(); if (tmp == "false" || tmp == "true") return tmp == "true"; if (tmp == "null") return JsonNull.CreateOrGet(); double val; if (double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out val)) return val; else return token; } public static JsonNode Parse(string aJSON) { Stack<JsonNode> stack = new Stack<JsonNode>(); JsonNode ctx = null; int i = 0; StringBuilder Token = new StringBuilder(); string TokenName = ""; bool QuoteMode = false; bool TokenIsQuoted = false; while (i < aJSON.Length) { switch (aJSON[i]) { case '{': if (QuoteMode) { Token.Append(aJSON[i]); break; } stack.Push(new JsonObject()); if (ctx != null) { ctx.Add(TokenName, stack.Peek()); } TokenName = ""; Token.Length = 0; ctx = stack.Peek(); break; case '[': if (QuoteMode) { Token.Append(aJSON[i]); break; } stack.Push(new JsonArray()); if (ctx != null) { ctx.Add(TokenName, stack.Peek()); } TokenName = ""; Token.Length = 0; ctx = stack.Peek(); break; case '}': case ']': if (QuoteMode) { Token.Append(aJSON[i]); break; } if (stack.Count == 0) throw new Exception("JSON Parse: Too many closing brackets"); stack.Pop(); if (Token.Length > 0 || TokenIsQuoted) ctx.Add(TokenName, ParseElement(Token.ToString(), TokenIsQuoted)); TokenIsQuoted = false; TokenName = ""; Token.Length = 0; if (stack.Count > 0) ctx = stack.Peek(); break; case ':': if (QuoteMode) { Token.Append(aJSON[i]); break; } TokenName = Token.ToString(); Token.Length = 0; TokenIsQuoted = false; break; case '"': QuoteMode ^= true; TokenIsQuoted |= QuoteMode; break; case ',': if (QuoteMode) { Token.Append(aJSON[i]); break; } if (Token.Length > 0 || TokenIsQuoted) ctx.Add(TokenName, ParseElement(Token.ToString(), TokenIsQuoted)); TokenIsQuoted = false; TokenName = ""; Token.Length = 0; TokenIsQuoted = false; break; case '\r': case '\n': break; case ' ': case '\t': if (QuoteMode) Token.Append(aJSON[i]); break; case '\\': ++i; if (QuoteMode) { char C = aJSON[i]; switch (C) { case 't': Token.Append('\t'); break; case 'r': Token.Append('\r'); break; case 'n': Token.Append('\n'); break; case 'b': Token.Append('\b'); break; case 'f': Token.Append('\f'); break; case 'u': { string s = aJSON.Substring(i + 1, 4); Token.Append((char)int.Parse( s, System.Globalization.NumberStyles.AllowHexSpecifier)); i += 4; break; } default: Token.Append(C); break; } } break; default: Token.Append(aJSON[i]); break; } ++i; } if (QuoteMode) { throw new Exception("JSON Parse: Quotation marks seems to be messed up."); } if (ctx == null) return ParseElement(Token.ToString(), TokenIsQuoted); return ctx; } } // End of JSONNode public partial class JsonArray : JsonNode { private List<JsonNode> m_List = new List<JsonNode>(); private bool inline = false; public override bool Inline { get { return inline; } set { inline = value; } } public override JsonNodeType Tag { get { return JsonNodeType.Array; } } public override bool IsArray { get { return true; } } public override Enumerator GetEnumerator() { return new Enumerator(m_List.GetEnumerator()); } public override JsonNode this[int aIndex] { get { if (aIndex < 0 || aIndex >= m_List.Count) return new JsonLazyCreator(this); return m_List[aIndex]; } set { if (value == null) value = JsonNull.CreateOrGet(); if (aIndex < 0 || aIndex >= m_List.Count) m_List.Add(value); else m_List[aIndex] = value; } } public override JsonNode this[string aKey] { get { return new JsonLazyCreator(this); } set { if (value == null) value = JsonNull.CreateOrGet(); m_List.Add(value); } } public override int Count { get { return m_List.Count; } } public override void Add(string aKey, JsonNode aItem) { if (aItem == null) aItem = JsonNull.CreateOrGet(); m_List.Add(aItem); } public override JsonNode Remove(int aIndex) { if (aIndex < 0 || aIndex >= m_List.Count) return null; JsonNode tmp = m_List[aIndex]; m_List.RemoveAt(aIndex); return tmp; } public override JsonNode Remove(JsonNode aNode) { m_List.Remove(aNode); return aNode; } public override IEnumerable<JsonNode> Children { get { foreach (JsonNode N in m_List) yield return N; } } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JsonTextMode aMode) { aSB.Append('['); int count = m_List.Count; if (inline) aMode = JsonTextMode.Compact; for (int i = 0; i < count; i++) { if (i > 0) aSB.Append(','); if (aMode == JsonTextMode.Indent) aSB.AppendLine(); if (aMode == JsonTextMode.Indent) aSB.Append(' ', aIndent + aIndentInc); m_List[i].WriteToStringBuilder(aSB, aIndent + aIndentInc, aIndentInc, aMode); } if (aMode == JsonTextMode.Indent) aSB.AppendLine().Append(' ', aIndent); aSB.Append(']'); } } // End of JSONArray public partial class JsonObject : JsonNode { private Dictionary<string, JsonNode> m_Dict = new Dictionary<string, JsonNode>(); private bool inline = false; public override bool Inline { get { return inline; } set { inline = value; } } public override JsonNodeType Tag { get { return JsonNodeType.Object; } } public override bool IsObject { get { return true; } } public override Enumerator GetEnumerator() { return new Enumerator(m_Dict.GetEnumerator()); } public override JsonNode this[string aKey] { get { if (m_Dict.ContainsKey(aKey)) return m_Dict[aKey]; else return new JsonLazyCreator(this, aKey); } set { if (value == null) value = JsonNull.CreateOrGet(); if (m_Dict.ContainsKey(aKey)) m_Dict[aKey] = value; else m_Dict.Add(aKey, value); } } public override JsonNode this[int aIndex] { get { if (aIndex < 0 || aIndex >= m_Dict.Count) return null; return m_Dict.ElementAt(aIndex).Value; } set { if (value == null) value = JsonNull.CreateOrGet(); if (aIndex < 0 || aIndex >= m_Dict.Count) return; string key = m_Dict.ElementAt(aIndex).Key; m_Dict[key] = value; } } public override int Count { get { return m_Dict.Count; } } public override void Add(string aKey, JsonNode aItem) { if (aItem == null) aItem = JsonNull.CreateOrGet(); if (!string.IsNullOrEmpty(aKey)) { if (m_Dict.ContainsKey(aKey)) m_Dict[aKey] = aItem; else m_Dict.Add(aKey, aItem); } else m_Dict.Add(Guid.NewGuid().ToString(), aItem); } public override JsonNode Remove(string aKey) { if (!m_Dict.ContainsKey(aKey)) return null; JsonNode tmp = m_Dict[aKey]; m_Dict.Remove(aKey); return tmp; } public override JsonNode Remove(int aIndex) { if (aIndex < 0 || aIndex >= m_Dict.Count) return null; var item = m_Dict.ElementAt(aIndex); m_Dict.Remove(item.Key); return item.Value; } public override JsonNode Remove(JsonNode aNode) { try { var item = m_Dict.Where(k => k.Value == aNode).First(); m_Dict.Remove(item.Key); return aNode; } catch { return null; } } public override IEnumerable<JsonNode> Children { get { foreach (KeyValuePair<string, JsonNode> N in m_Dict) yield return N.Value; } } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JsonTextMode aMode) { aSB.Append('{'); bool first = true; if (inline) aMode = JsonTextMode.Compact; foreach (var k in m_Dict) { if (!first) aSB.Append(','); first = false; if (aMode == JsonTextMode.Indent) aSB.AppendLine(); if (aMode == JsonTextMode.Indent) aSB.Append(' ', aIndent + aIndentInc); aSB.Append('\"').Append(Escape(k.Key)).Append('\"'); if (aMode == JsonTextMode.Compact) aSB.Append(':'); else aSB.Append(" : "); k.Value.WriteToStringBuilder(aSB, aIndent + aIndentInc, aIndentInc, aMode); } if (aMode == JsonTextMode.Indent) aSB.AppendLine().Append(' ', aIndent); aSB.Append('}'); } } // End of JSONObject public partial class JsonString : JsonNode { private string m_Data; public override JsonNodeType Tag { get { return JsonNodeType.String; } } public override bool IsString { get { return true; } } public override Enumerator GetEnumerator() { return new Enumerator(); } public override string Value { get { return m_Data; } set { m_Data = value; } } public JsonString(string aData) { m_Data = aData; } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JsonTextMode aMode) { aSB.Append('\"').Append(Escape(m_Data)).Append('\"'); } public override bool Equals(object obj) { if (base.Equals(obj)) return true; string s = obj as string; if (s != null) return m_Data == s; JsonString s2 = obj as JsonString; if (s2 != null) return m_Data == s2.m_Data; return false; } public override int GetHashCode() { return m_Data.GetHashCode(); } } // End of JSONString public partial class JsonNumber : JsonNode { private double m_Data; public override JsonNodeType Tag { get { return JsonNodeType.Number; } } public override bool IsNumber { get { return true; } } public override Enumerator GetEnumerator() { return new Enumerator(); } public override string Value { get { return m_Data.ToString(CultureInfo.InvariantCulture); } set { double v; if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out v)) m_Data = v; } } public override double AsDouble { get { return m_Data; } set { m_Data = value; } } public override long AsLong { get { return (long)m_Data; } set { m_Data = value; } } public JsonNumber(double aData) { m_Data = aData; } public JsonNumber(string aData) { this.Value = aData; } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JsonTextMode aMode) { aSB.Append(this.Value); } private static bool IsNumeric(object value) { return value is int || value is uint || value is float || value is double || value is decimal || value is long || value is ulong || value is short || value is ushort || value is sbyte || value is byte; } public override bool Equals(object obj) { if (obj == null) return false; if (base.Equals(obj)) return true; JsonNumber s2 = obj as JsonNumber; if (s2 != null) return m_Data == s2.m_Data; if (IsNumeric(obj)) return Convert.ToDouble(obj) == m_Data; return false; } public override int GetHashCode() { return m_Data.GetHashCode(); } } // End of JSONNumber public partial class JsonBool : JsonNode { private bool m_Data; public override JsonNodeType Tag { get { return JsonNodeType.Boolean; } } public override bool IsBoolean { get { return true; } } public override Enumerator GetEnumerator() { return new Enumerator(); } public override string Value { get { return m_Data.ToString(); } set { bool v; if (bool.TryParse(value, out v)) m_Data = v; } } public override bool AsBool { get { return m_Data; } set { m_Data = value; } } public JsonBool(bool aData) { m_Data = aData; } public JsonBool(string aData) { this.Value = aData; } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JsonTextMode aMode) { aSB.Append((m_Data) ? "true" : "false"); } public override bool Equals(object obj) { if (obj == null) return false; if (obj is bool) return m_Data == (bool)obj; return false; } public override int GetHashCode() { return m_Data.GetHashCode(); } } // End of JSONBool public partial class JsonNull : JsonNode { static JsonNull m_StaticInstance = new JsonNull(); public static bool reuseSameInstance = true; public static JsonNull CreateOrGet() { if (reuseSameInstance) return m_StaticInstance; return new JsonNull(); } private JsonNull() { } public override JsonNodeType Tag { get { return JsonNodeType.NullValue; } } public override bool IsNull { get { return true; } } public override Enumerator GetEnumerator() { return new Enumerator(); } public override string Value { get { return "null"; } set { } } public override bool AsBool { get { return false; } set { } } public override bool Equals(object obj) { if (object.ReferenceEquals(this, obj)) return true; return (obj is JsonNull); } public override int GetHashCode() { return 0; } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JsonTextMode aMode) { aSB.Append("null"); } } // End of JSONNull internal partial class JsonLazyCreator : JsonNode { private JsonNode m_Node = null; private string m_Key = null; public override JsonNodeType Tag { get { return JsonNodeType.None; } } public override Enumerator GetEnumerator() { return new Enumerator(); } public JsonLazyCreator(JsonNode aNode) { m_Node = aNode; m_Key = null; } public JsonLazyCreator(JsonNode aNode, string aKey) { m_Node = aNode; m_Key = aKey; } private T Set<T>(T aVal) where T : JsonNode { if (m_Key == null) m_Node.Add(aVal); else m_Node.Add(m_Key, aVal); m_Node = null; // Be GC friendly. return aVal; } public override JsonNode this[int aIndex] { get { return new JsonLazyCreator(this); } set { Set(new JsonArray()).Add(value); } } public override JsonNode this[string aKey] { get { return new JsonLazyCreator(this, aKey); } set { Set(new JsonObject()).Add(aKey, value); } } public override void Add(JsonNode aItem) { Set(new JsonArray()).Add(aItem); } public override void Add(string aKey, JsonNode aItem) { Set(new JsonObject()).Add(aKey, aItem); } public static bool operator ==(JsonLazyCreator a, object b) { if (b == null) return true; return System.Object.ReferenceEquals(a, b); } public static bool operator !=(JsonLazyCreator a, object b) { return !(a == b); } public override bool Equals(object obj) { if (obj == null) return true; return System.Object.ReferenceEquals(this, obj); } public override int GetHashCode() { return 0; } public override int AsInt { get { Set(new JsonNumber(0)); return 0; } set { Set(new JsonNumber(value)); } } public override float AsFloat { get { Set(new JsonNumber(0.0f)); return 0.0f; } set { Set(new JsonNumber(value)); } } public override double AsDouble { get { Set(new JsonNumber(0.0)); return 0.0; } set { Set(new JsonNumber(value)); } } public override long AsLong { get { if (longAsString) Set(new JsonString("0")); else Set(new JsonNumber(0.0)); return 0L; } set { if (longAsString) Set(new JsonString(value.ToString())); else Set(new JsonNumber(value)); } } public override bool AsBool { get { Set(new JsonBool(false)); return false; } set { Set(new JsonBool(value)); } } public override JsonArray AsArray { get { return Set(new JsonArray()); } } public override JsonObject AsObject { get { return Set(new JsonObject()); } } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JsonTextMode aMode) { aSB.Append("null"); } } // End of JSONLazyCreator public static class Json { public static JsonNode Parse(string aJSON) { return JsonNode.Parse(aJSON); } } }
33.664207
130
0.502817
[ "MIT" ]
BitArmory/ReCaptcha
BitArmory.ReCaptcha/Utils/SimpleJson.cs
45,616
C#
namespace Discord { /// <summary> /// Modify the current user with the specified arguments /// </summary> /// <example> /// <code language="c#"> /// await Context.Client.CurrentUser.ModifyAsync(x => /// { /// x.Avatar = new Image(File.OpenRead("avatar.jpg")); /// }); /// </code> /// </example> /// <seealso cref="ISelfUser"/> public class SelfUserProperties { /// <summary> /// Your username /// </summary> public Optional<string> Username { get; set; } /// <summary> /// Your avatar /// </summary> public Optional<Image?> Avatar { get; set; } } }
26.074074
63
0.492898
[ "Unlicense" ]
Lelouch99/bot_cc
Discord.Net/src/Discord.Net.Core/Entities/Users/SelfUserProperties.cs
706
C#
using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Application.Common.Interfaces; using Application.Common.Repositories; using Domain.Entities; using Microsoft.EntityFrameworkCore; namespace Persistence.Common { public class ChatUserRepository : BaseRepository<ChatUser>, IChatUserRepository { public ChatUserRepository(ITwitterDbContext context) : base(context) { } public Task<List<string>> FindUserIdsInChat(string exceptUserId, long chatId, CancellationToken token) => Query.Where(f => f.ChatId == chatId && f.UserId != exceptUserId) .Select(f => f.UserId) .ToListAsync(token); public Task<ChatUser> FindByUserAndChat(string userId, long chatId, CancellationToken token) => Query.FirstOrDefaultAsync(f => f.UserId == userId && f.ChatId == chatId, token); public Task<AppUser> FindUserInChat(long chatId, string userId, CancellationToken token) => Query.Include(f => f.User) .Where(f => f.ChatId == chatId && f.UserId != userId) .Select(f => f.User) .FirstOrDefaultAsync(token); } }
37.242424
113
0.665582
[ "MIT" ]
destbg/TwitterRecreated
src/Persistence/Common/ChatUserRepository.cs
1,231
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using FluentScheduler; using Twitter.Data.UnitOfWork; namespace ScheduledJob { public class Program { static void Main(string[] args) { JobManager.AddJob(() => { //Do something... string content; try { var data = new QQmgsData(); var userNumber = data.Users.All().Count(); var tweetNumber = data.Tweets.All().Count(); content = $"[{DateTime.Now.ToString("O")}] <br/>主人好睡觉了... 我也很困了<br/><br/>现在我们有{userNumber}位用户哦~<br/>不仅如此我们现在一共有{tweetNumber}条发言在我们的全球某工商平台哦~"; //content = $"[{DateTime.Now.ToString("O")}] <br/><br/> 主人天天好心情,今天是 {DateTime.Today.DayOfWeek}, 可以起床了哦~"; MailJob.SendMailAsync(content).Wait(); } catch (Exception e) { content = e.Message; } //var sw = new StreamWriter(@"C:\Users\Administrator\Desktop\test\qqmgs.txt", true); //sw.WriteLine(content); //sw.Close(); Console.WriteLine(content, DateTime.Now); }, t => { //从程序启动开始执行,然后每秒钟执行一次 //t.ToRunNow().AndEvery(1).Minutes(); var time = new DateTime(2016, 7, 26, 6, 30, 0); t.ToRunOnceAt(time).AndEvery(1).Days(); ////带有任务名称的任务定时器 //t.WithName("TimerTask").ToRunOnceAt(DateTime.Now.AddSeconds(5)); }); Console.ReadKey(); } } }
31.017544
162
0.493778
[ "Apache-2.0" ]
ZJGSU-Open-Source/QQmgs
ScheduledJob/Program.cs
1,958
C#
using System; using System.Collections.Specialized; using System.Data.Entity; using System.Linq; using System.Web.Mvc; using NewGenFramework.Core.Aspects.Postsharp.AuthorizationAspects; using NewGenFramework.Core.DataAccess; using NewGenFramework.Core.Utilities.Mappings; using NonFactors.Mvc.Grid; using BayiPuan.Business.Abstract; using BayiPuan.Entities.ComplexTypes; using BayiPuan.Entities.Concrete; using BayiPuan.MvcWebUi.GenericVM; using BayiPuan.MvcWebUi.Filters; using BayiPuan.MvcWebUi.HtmlHelpers; using BayiPuan.MvcWebUi.Infrastructure; using BayiPuan.MvcWebUi.Models.ViewModels; using NewGenFramework.Core.Utilities.Common; namespace BayiPuan.MvcWebUi.Controllers { [AuthorizationFilter] public class BuyController : BaseController { private readonly IBuyService _buyService; private readonly IQueryableRepository<Buy> _queryableRepository; private readonly IQueryableRepository<vwRP_StockCount> _totalRowsRepository; private readonly IQueryableRepository<Gift> _giftQueryableRepository; private readonly IQueryableRepository<User> _userQueryableRepository; public BuyController(IBuyService buyService, IQueryableRepository<Buy> queryableRepository, IQueryableRepository<vwRP_StockCount> totalRowsRepository, IQueryableRepository<Gift> giftQueryableRepository, IQueryableRepository<User> userQueryableRepository) { _buyService = buyService; _queryableRepository = queryableRepository; _totalRowsRepository = totalRowsRepository; _giftQueryableRepository = giftQueryableRepository; _userQueryableRepository = userQueryableRepository; } // GET: List [SecuredOperation(Roles = "SystemAdmin,Admin,User")] public ActionResult BuyIndex(Int32? page, Int32? rows) { var getUserId =Convert.ToInt32(GeneralHelpers.GetUserId()); IGrid<Buy> col = new Grid<Buy>(_queryableRepository.Table.Include("Gift").Include("User").Include("Brand").Where(x=>x.UserId==getUserId).OrderByDescending(x => x.BuyId).Skip((page - 1 ?? 0) * (rows ?? 10)).Take(rows ?? 10).AsNoTracking()); col.Query = new NameValueCollection(Request.QueryString); if (col.Query != null) { col = new Grid<Buy>(_queryableRepository.Table.Include("Gift").Include("User").Include("Brand").Where(x => x.UserId == getUserId).OrderByDescending(x => x.BuyId).AsNoTracking()); } col.Columns.Add(x => x.Brand.BrandName).Titled("Marka"); col.Columns.Add(x => x.Gift.Description).Titled("Hediye"); col.Columns.Add(x => x.UserId).RenderedAs(x => x.User.FirstName + " " + x.User.LastName).Titled("Kullanıcı"); col.Columns.Add(x => x.BuyAmount).Titled("Alınan Miktar"); col.Columns.Add(x => x.BuyDate).Titled("İstek Tarihi"); col.Columns.Add(x => x.IsApproved).Titled("Durumu").RenderedAs(x => x.IsApproved == true ? "İstek Yapıldı" : "Puan İadesi Yapıldı"); col.Columns.Add(x => x.BuyState).Titled("Hediye Durumu").RenderedAs(x => x.BuyState == BuyState.IncelemeBekliyor ? "İnceleme Bekliyor" : x.BuyState == BuyState.OnaylandiGonderimBekliyor ? "Onaylandı, Gönderim Bekleniyor." :x.BuyState==BuyState.HediyeKarsilanamiyor? "Hediye Firmadan Karşılanamıyor" : "Gönderildi."); col.Pager = new GridPager<Buy>(col); col.Processors.Add(col.Pager); col.Pager.RowsPerPage = 10; col.EmptyText = "Gösterilecek Kayıt Yok :("; foreach (IGridColumn column in col.Columns) { column.IsFilterable = true; column.IsSortable = true; } var total = _totalRowsRepository.Table.Where(x => x.TableName == "Buys").AsNoTracking().Select(x => x.TableRows).First(); ViewBag.totalRows = Convert.ToInt32(total); return View(col); } [SecuredOperation(Roles = "SystemAdmin,Admin")] public ActionResult ApprovedBuyIndex(Int32? page, Int32? rows) { IGrid<Buy> col = new Grid<Buy>(_queryableRepository.Table.Include("Gift").Include("User").Include("Brand").AsNoTracking().Where(x => x.BuyState != BuyState.Gonderildi && x.BuyState!=BuyState.HediyeKarsilanamiyor).OrderByDescending(x => x.BuyId).Skip((page - 1 ?? 0) * (rows ?? 10)).Take(rows ?? 10)); col.Query = new NameValueCollection(Request.QueryString); if (col.Query != null) { col = new Grid<Buy>(_queryableRepository.Table.Include("Gift").Include("User").Include("Brand").AsNoTracking().Where(x => x.BuyState != BuyState.Gonderildi && x.BuyState != BuyState.HediyeKarsilanamiyor).OrderByDescending(x => x.BuyId)); } col.Columns.Add(x => "<a class=' fas fa-edit btn btn-warning btn-sm' title='Güncelle' href='Edit/" + x.BuyId + "'> </a>") // "<a class='actions fas fa-trash-alt btn btn-danger btn-sm' title='Sil' href='Delete/" + x.BuyId + "'> </a>") .Encoded(false).Titled("işlemler").Filterable(false); //Görüntülenecek kolonları buraya yazacaksanız //col.Columns.Add(x => x.BuyId).Titled("BuyId").MultiFilterable(true); col.Columns.Add(x => x.Brand.BrandName).Titled("Marka"); col.Columns.Add(x => x.Gift.Description).Titled("Hediye"); col.Columns.Add(x => x.UserId).RenderedAs(x => x.User.FirstName + " " + x.User.LastName).Titled("Kullanıcı"); col.Columns.Add(x => x.BuyAmount).Titled("Alınan Miktar"); col.Columns.Add(x => x.BuyDate).Titled("İstek Tarihi"); col.Columns.Add(x => x.IsApproved).Titled("Durumu").RenderedAs(x => x.IsApproved == true ? "İstek Yapıldı" : "Puan İadesi Yapıldı"); col.Columns.Add(x => x.BuyState).Titled("Hediye Durumu").RenderedAs(x => x.BuyState == BuyState.IncelemeBekliyor ? "İnceleme Bekliyor" : x.BuyState == BuyState.OnaylandiGonderimBekliyor ? "Onaylandı, Gönderim Bekleniyor." : x.BuyState == BuyState.HediyeKarsilanamiyor ? "Hediye Firmadan Karşılanamıyor" : "Gönderildi."); col.Pager = new GridPager<Buy>(col); col.Processors.Add(col.Pager); col.Pager.RowsPerPage = 10; col.EmptyText = "Gösterilecek Kayıt Yok :("; foreach (IGridColumn column in col.Columns) { column.IsFilterable = true; column.IsSortable = true; } var total = _totalRowsRepository.Table.Where(x => x.TableName == "Buys").AsNoTracking().Select(x => x.TableRows).First(); ViewBag.totalRows = Convert.ToInt32(total); return View(col); } // GET: Create [SecuredOperation(Roles = "SystemAdmin")] public ActionResult Create() { var empty = new BuyViewModel(); var data = empty.ToVM(); return View(data); } // POST: Brand/Create [HttpPost] public ActionResult Create(BuyViewModel buy) { if (!ModelState.IsValid) { ErrorNotification("Kayıt Eklenemedi!"); return RedirectToAction("Create"); } _buyService.Add(new Buy { //Alanlar buraya yazılacak //Örn:BrandName = brand.BrandName, }); SuccessNotification("Kayıt Eklendi."); return RedirectToAction("BuyIndex"); } // GET: Edit [SecuredOperation(Roles = "SystemAdmin,Admin")] public ActionResult Edit(int id) { var data = AutoMapperHelper.MapToSameViewModel<Buy, BuyViewModel>(_buyService.GetById(id)); return View(data.ToVM()); } // POST: Edit [HttpPost] public ActionResult Edit(BuyViewModel buy) { var brand = _giftQueryableRepository.Table.AsNoTracking().FirstOrDefault(x => x.GiftId == buy.GiftId); var userMail = _userQueryableRepository.Table.AsNoTracking().FirstOrDefault(x => x.UserId == buy.UserId); if (!ModelState.IsValid) { ErrorNotification("Bir Hata Oluştu"); return RedirectToAction("BuyIndex"); } try { if (buy.BuyState == BuyState.IncelemeBekliyor) { ErrorNotification("Hediye Talebini İnceleme Bekliyor Durumunda Bıraktınız! Başka Bir İşlem Yapmak İster misiniz?"); return RedirectToAction("BuyIndex"); } if (buy.BuyState == BuyState.HediyeKarsilanamiyor) { // TODO: Add update logic here _buyService.Update(new Buy { UserId = buy.UserId, ApprovedDate = DateTime.Now, BuyAmount = buy.BuyAmount, BuyDate = buy.BuyDate, EditUserId = Convert.ToInt32(GeneralHelpers.GetUserId()), GiftId = buy.GiftId, IsApproved = false, BuyState = buy.BuyState, NotApproved = true, NotApprovedDate = DateTime.Now, BrandId = brand.BrandId, Reason = "Hediye İsteği Firmadan Karşılanamıyor.Puanlar iade Edildi.", BuyId = buy.BuyId }); var mailEnable = System.Configuration.ConfigurationManager.AppSettings["MailEnable"]; if (mailEnable=="true") { var mail = MailHelper.SendMail($"Hediye İsteğiniz Karşılanamıyor, Harcadığınız Puanların İadesi Gerçekleştirildi.<br/>Durum için gerçekten çok üzgünüz. Lütfen bayipuan.com üzerinde takip ediniz.", $"{userMail.Email}", "Hediye İsteğinizle İlgili Üzücü Bir Gelişme Oldu!", true); if (mail) { SuccessNotification("Mail Gönderildi"); } else { ErrorNotification("Mail Gönderilemedi!"); } } ErrorNotification("Hediye Talebi Karşılanamıyor. Talep Reddedildi!!! <br/> Harcanan Puanların İadesi Gerçekleştirildi."); return RedirectToAction("BuyIndex"); } _buyService.Update(new Buy { UserId = buy.UserId, ApprovedDate = DateTime.Now, BuyAmount = buy.BuyAmount, BuyDate = buy.BuyDate, EditUserId = Convert.ToInt32(GeneralHelpers.GetUserId()), GiftId = buy.GiftId, IsApproved = true, BuyState = buy.BuyState, BrandId = brand.BrandId, BuyId = buy.BuyId }); var mailEnablex = System.Configuration.ConfigurationManager.AppSettings["MailEnable"]; if (mailEnablex == "true") { var Onaymail = MailHelper.SendMail($"Tebrikler Hediye İsteğiniz Onaylandı. Lütfen bayipuan.com üzerinde takip ediniz.", $"{userMail.Email}", "Tebrikler Hediye İsteğiniz Onaylandı!", true); if (Onaymail) { SuccessNotification("Mail Gönderildi"); } else { ErrorNotification("Mail Gönderilemedi!"); } } SuccessNotification("Seçilen Hediye Onaylandı."); return RedirectToAction("BuyIndex"); } catch (Exception ex) { return View(ex.ToString()); } } // GET: Delete [SecuredOperation(Roles = "SystemAdmin")] public ActionResult Delete(int id, Buy buy) { var data = AutoMapperHelper.MapToSameViewModel<Buy, BuyViewModel>(_buyService.GetById(id)); return View(data.ToVM()); } // POST: Delete [HttpPost] public ActionResult Delete(int id) { try { _buyService.Delete(_buyService.GetById(id)); SuccessNotification("Kayıt Silindi"); return RedirectToAction("BuyIndex"); } catch { return View(); } } } }
43.392308
326
0.651658
[ "MIT" ]
keremvaris/NewGenFramework
BayiPuan.MvcWebUi/Controllers/BuyController.cs
11,397
C#
/*! * \file Evaporation.cs * * \brief Implements the models for the calculation of evaporation as described in FAO paper 56. * * \author Hunstock * \date 15.08.2015 */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using atbApi; using atbApi.data; using local; namespace atbApi { /*! * \brief Encapsulates the result of an evaporation calculation. * */ public class EvaporationResult { /*! kcMin, unit: "none", description: crop coefficient minimal value */ public double kcMin { get; set; } /*! kcMax, unit: "none", description: crop coefficient maximal value */ public double kcMax { get; set; } /*! kcb, unit: "none", description: basal crop coefficient */ public double kcb { get; set; } /*! fc, unit: "none", description: fraction of soil surface covered by vegetation */ public double fc { get; set; } /*! few, unit: "none", description: fraction of soil that is exposed and wetted in the event */ public double few { get; set; } /*! tew, unit: "mm", description: totally evaporable water */ public double tew { get; set; } /*! rew, unit: "mm", description: readily evaporable water */ public double rew { get; set; } /*! kr, unit: "none", description: evaporation reduction coefficient */ public double kr { get; set; } /*! ke, unit: "mm", description: soil evaporation coefficient */ public double ke { get; set; } /*! de, unit: "mm", description: drainage in evaporation layer */ public double de { get; set; } /*! dpe, unit: "mm", description: percolation from evaporation layer to deeper soil layers */ public double dpe { get; set; } /*! e, unit: "mm", description: Calculated evaporation value. */ public double e { get; set; } } /*! * \brief static class that holds all static functions for the evaporation calculation. * */ public static class Evaporation { /*! * \brief calculate evaporation. * * \param [in,out] lastConditions The last soil conditions. * \param plantSet Set the plant values. * \param climateSet Set the climate values. * \param irrigationType Type of the irrigation. * \param et0 The reference evapotranspiration. * \param eFactor The factor e is reduced by. May be used to consider mulching etc. * \param tew The totally evaporable water. * \param irrigationFw The fraction of wetted surface depending on irrigation type. * \param autoIrrigationFw The fraction of wetted surface depending on automatic irrigation type. * \param netIrrigation The netto irrigation. * \param autoNetIrrigation The automatic netto irrigation. * \param interception The interception. * \param interceptionIrr The interception of the irrigated water. * \param interceptionAutoIrr The interception of the automatic irrigated water. * \param [in,out] eResult The result of the calculation. * * \return true if it succeeds, false if it fails. */ public static bool ECalculation( ref SoilConditions lastConditions, PlantValues plantSet, ClimateValues climateSet, String irrigationType, double et0, double eFactor, double tew, double irrigationFw, double autoIrrigationFw, double netIrrigation, double autoNetIrrigation, double interception, double interceptionIrr, double interceptionAutoIrr, ref EvaporationResult eResult ) { if (eResult == null) eResult = new EvaporationResult(); var rewFactor = 2.2926; var kcMax = 1.2; var kcMin = 0.0; var kcb = 0.0; var fc = 0.0; if (!(plantSet.isFallow == true)) { kcb = (double)plantSet.Kcb; kcMax = 1.2 + (0.04 * ((double)climateSet.windspeed - 2) - 0.004 * ((double)climateSet.humidity - 45)) * Math.Pow(((double)plantSet.height / 3), 0.3); kcMax = Math.Max(kcMax, kcb + 0.05); kcMax = Math.Min(kcMax, 1.3); kcMax = Math.Max(kcMax, 1.05); kcMin = 0.175; fc = Math.Pow(Math.Max((kcb - kcMin), 0.01) / (kcMax - kcMin), 1 + 0.5 * (double)plantSet.height); fc = Math.Min(0.99, fc); } eResult.kcMin = kcMin; eResult.kcMax = kcMax; eResult.kcb = kcb; eResult.fc = fc; var few = Math.Min(1 - fc, Math.Min(irrigationFw, autoIrrigationFw)); if ((netIrrigation > 0 || autoNetIrrigation > 0) && (irrigationType == "drip")) { few = Math.Min(1 - fc, (1 - (2 / 3) * fc) * Math.Min(irrigationFw, autoIrrigationFw)); } eResult.few = few; eResult.tew = tew; var rew = tew / rewFactor; eResult.rew = rew; var kr = 1.0; if (lastConditions.de > rew) { kr = (tew - lastConditions.de) / (tew - rew); kr = Math.Max(0, kr); } if (rew == 0) kr = 0; eResult.kr = kr; var ke = Math.Min(kr * (kcMax - kcb), few * kcMax); eResult.ke = ke; var e = ke * et0; e = e * eFactor; eResult.e = e; var rpPrecipitation = climateSet.rpPrecipitation != null ? (double)climateSet.rpPrecipitation : (double)climateSet.precipitation; var netPrecititationTc = rpPrecipitation - interception + netIrrigation - interceptionIrr + autoNetIrrigation - interceptionAutoIrr; var dpe = netPrecititationTc - lastConditions.de; dpe = Math.Max(0, dpe); var de = lastConditions.de - netPrecititationTc + e / few + dpe; de = Math.Max(0, de); de = Math.Min(tew, de); lastConditions.de = de; lastConditions.dpe = dpe; eResult.de = de; eResult.dpe = dpe; return true; } } }
41.876543
167
0.533756
[ "Apache-2.0" ]
ATB-Potsdam/IDM
ATB_Irrigation-Module_cs/Evaporation.cs
6,786
C#
namespace Kenc.Cloudflare.Core.IntegrationTests { using System.Collections.Generic; using System.Threading.Tasks; using Kenc.Cloudflare.Core.Clients; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] [TestCategory("IntegrationTests")] public class DNSScenarioTests : IntegrationTestBase { [TestMethod] public async Task GetDomain() { var domainId = TestContextSetting("domainId"); var domainName = TestContextSetting("domainName"); ICloudflareClient client = CreateClient(); IList<Entities.Zone> domain = await client.Zones.ListAsync(domainName, Clients.Enums.ZoneStatus.Active); Assert.IsNotNull(domain); Assert.AreEqual(domainId, domain[0].Id); } [TestMethod] public async Task ListTxtRecords() { var domainId = TestContextSetting("domainId"); ICloudflareClient client = CreateClient(); Entities.EntityList<Entities.DNSRecord> dnsRecords = await client.Zones.DNSSettings.ListAsync(domainId, Clients.Enums.DNSRecordType.TXT); Assert.IsNotNull(dnsRecords); Assert.AreNotEqual(0, dnsRecords.Count); } [TestMethod] public async Task CreateTextRecord() { var recordIdentifier = $"_intTest{System.DateTime.UtcNow:yyyymmddhhMMss}"; var domainId = TestContextSetting("domainId"); ICloudflareClient client = CreateClient(); Entities.DNSRecord record = await client.Zones.DNSSettings.CreateRecordAsync(domainId, recordIdentifier, Clients.Enums.DNSRecordType.TXT, recordIdentifier); Assert.IsNotNull(record); Assert.AreEqual(recordIdentifier, record.Content); // delete the record again await client.Zones.DNSSettings.DeleteRecordAsync(record); } } }
37.705882
168
0.660426
[ "MIT" ]
Kencdk/Kenc.Cloudflare
src/Libraries/Kenc.Cloudflare.Core.IntegrationTests/DNSScenarioTests.cs
1,923
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace RobotServer.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("RobotServer.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
43.515625
177
0.613285
[ "MIT" ]
B13K/opc-ua-samples
RobotServer/Properties/Resources.Designer.cs
2,787
C#
using System; using System.Collections.Generic; namespace SKIT.FlurlHttpClient.Wechat.Api.Models { /// <summary> /// <para>表示 [POST] /cgi-bin/guide/getguideacctconfig 接口的请求。</para> /// </summary> public class CgibinGuideGetGuideAccountConfigRequest : WechatApiRequest { } }
23.076923
75
0.703333
[ "MIT" ]
KimMeng2015/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat.Api/Models/CgibinGuide/Config/CgibinGuideGetGuideAccountConfigRequest.cs
318
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.17379 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace DiscountMe.Languages.Idiomas { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class Texts { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Texts() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DiscountMe.Languages.Idiomas.Texts", typeof(Texts).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to login. /// </summary> public static string LoginTitle { get { return ResourceManager.GetString("LoginTitle", resourceCulture); } } /// <summary> /// Looks up a localized string similar to DiscountMe. /// </summary> public static string NombreAplicacion { get { return ResourceManager.GetString("NombreAplicacion", resourceCulture); } } /// <summary> /// Looks up a localized string similar to acerca de. /// </summary> public static string TextoAcercaDe { get { return ResourceManager.GetString("TextoAcercaDe", resourceCulture); } } /// <summary> /// Looks up a localized string similar to actualizar. /// </summary> public static string TextoActualizar { get { return ResourceManager.GetString("TextoActualizar", resourceCulture); } } /// <summary> /// Looks up a localized string similar to ajustes. /// </summary> public static string TextoAjustes { get { return ResourceManager.GetString("TextoAjustes", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Atención. /// </summary> public static string TextoAtencion { get { return ResourceManager.GetString("TextoAtencion", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Autores:. /// </summary> public static string TextoAutores { get { return ResourceManager.GetString("TextoAutores", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Bienvenido.. /// </summary> public static string TextoBienvenida { get { return ResourceManager.GetString("TextoBienvenida", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Buscar. /// </summary> public static string TextoBotonBuscar { get { return ResourceManager.GetString("TextoBotonBuscar", resourceCulture); } } /// <summary> /// Looks up a localized string similar to cerrar sesión. /// </summary> public static string TextoBotonCerrarSession { get { return ResourceManager.GetString("TextoBotonCerrarSession", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Guardar. /// </summary> public static string TextoBotonGuardarAjustes { get { return ResourceManager.GetString("TextoBotonGuardarAjustes", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Login. /// </summary> public static string TextoBotonLogin { get { return ResourceManager.GetString("TextoBotonLogin", resourceCulture); } } /// <summary> /// Looks up a localized string similar to buscar. /// </summary> public static string TextoBuscar { get { return ResourceManager.GetString("TextoBuscar", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Ajustes. /// </summary> public static string TextoCategoriaAjustes { get { return ResourceManager.GetString("TextoCategoriaAjustes", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Categoría de búsqueda:. /// </summary> public static string TextoCategoriaBusqueda { get { return ResourceManager.GetString("TextoCategoriaBusqueda", resourceCulture); } } /// <summary> /// Looks up a localized string similar to categorías. /// </summary> public static string TextoCategorias { get { return ResourceManager.GetString("TextoCategorias", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Contacto:. /// </summary> public static string TextoContacto { get { return ResourceManager.GetString("TextoContacto", resourceCulture); } } /// <summary> /// Looks up a localized string similar to IberaSoft. /// </summary> public static string TextoContenidoAutores { get { return ResourceManager.GetString("TextoContenidoAutores", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Correcto. /// </summary> public static string TextoCorrecto { get { return ResourceManager.GetString("TextoCorrecto", resourceCulture); } } /// <summary> /// Looks up a localized string similar to contact@iberasoft.com. /// </summary> public static string TextoDireccionContacto { get { return ResourceManager.GetString("TextoDireccionContacto", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Error. /// </summary> public static string TextoError { get { return ResourceManager.GetString("TextoError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to El GPS está desacitado. Active la recepción GPS en la configuración del teléfono móvil.. /// </summary> public static string TextoGPSDesactivado { get { return ResourceManager.GetString("TextoGPSDesactivado", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Parámetros de búsqueda:. /// </summary> public static string TextoLabelBuscar { get { return ResourceManager.GetString("TextoLabelBuscar", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Email:. /// </summary> public static string TextoLabelEmailUsuario { get { return ResourceManager.GetString("TextoLabelEmailUsuario", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Unidades de medida:. /// </summary> public static string TextoLabelMedidaDeBusqueda { get { return ResourceManager.GetString("TextoLabelMedidaDeBusqueda", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Nombre:. /// </summary> public static string TextoLabelNombreUsuario { get { return ResourceManager.GetString("TextoLabelNombreUsuario", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Rango de búsqueda:. /// </summary> public static string TextoLabelRangoDeBusqueda { get { return ResourceManager.GetString("TextoLabelRangoDeBusqueda", resourceCulture); } } /// <summary> /// Looks up a localized string similar to mapa de descuentos. /// </summary> public static string TextoMapaDescuentos { get { return ResourceManager.GetString("TextoMapaDescuentos", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 1.0.0. /// </summary> public static string TextoNumeroVersion { get { return ResourceManager.GetString("TextoNumeroVersion", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Contraseña:. /// </summary> public static string TextoPassword { get { return ResourceManager.GetString("TextoPassword", resourceCulture); } } /// <summary> /// Looks up a localized string similar to perfil. /// </summary> public static string TextoPerfil { get { return ResourceManager.GetString("TextoPerfil", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Recordarme:. /// </summary> public static string TextoRecordarme { get { return ResourceManager.GetString("TextoRecordarme", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Nombre del usuario:. /// </summary> public static string TextoUsuario { get { return ResourceManager.GetString("TextoUsuario", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Los datos correspondientes al usuario no son correctos.. /// </summary> public static string TextoUsuarioIncorrecto { get { return ResourceManager.GetString("TextoUsuarioIncorrecto", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Versión:. /// </summary> public static string TextoVersion { get { return ResourceManager.GetString("TextoVersion", resourceCulture); } } } }
35.155673
175
0.541954
[ "MIT" ]
IberaSoft/discount-me
DiscountMeWP7/DiscountMe.Languages/Idiomas/Texts.Designer.cs
13,341
C#
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace Voximplant.API.Response { /// <summary> /// The [GetContractorInfo] function result. /// </summary> public class ContractorInfoType { /// <summary> /// Russian-specific ID for tax purposes. /// </summary> [JsonProperty("inn")] public string Inn { get; private set; } /// <summary> /// Additional Russian-specific ID for tax purposes for businesses; there is no KPP for individual entrepreneurs. /// </summary> [JsonProperty("kpp")] public string Kpp { get; private set; } /// <summary> /// The full company name. /// </summary> [JsonProperty("company_name")] public string CompanyName { get; private set; } /// <summary> /// The full company address with a postcode. /// </summary> [JsonProperty("company_address")] public string CompanyAddress { get; private set; } /// <summary> /// The company phone. /// </summary> [JsonProperty("company_phone")] public string CompanyPhone { get; private set; } /// <summary> /// The correspondence address. /// </summary> [JsonProperty("correspondence_address")] public string CorrespondenceAddress { get; private set; } /// <summary> /// The correspondence email. /// </summary> [JsonProperty("correspondence_email")] public string CorrespondenceEmail { get; private set; } /// <summary> /// The correspondence to. /// </summary> [JsonProperty("correspondence_to")] public string CorrespondenceTo { get; private set; } /// <summary> /// The contract info. /// </summary> [JsonProperty("contract")] public ContractInfoType Contract { get; private set; } } }
29.432836
121
0.570487
[ "MIT" ]
voximplant/apiclient-dotnet
apiclient/Response/ContractorInfoType.cs
1,972
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class StaticData : MonoBehaviour { public static string playerName = "player11"; }
20.333333
50
0.748634
[ "MIT" ]
Papyrustaro/UnityFishingGame
Assets/Scripts/StaticData.cs
185
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.Cors; using System.Web.Http.Cors; namespace WebAPITemplate.Util { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] public class CorsPolicyAttribute : Attribute, ICorsPolicyProvider { private const string keyCorsHeaders = "cors:headers"; private const string keyCorsMethods = "cors:methods"; private const string keyCorsOrigins = "cors:origins"; private CorsPolicy _policy; public CorsPolicyAttribute() { // Create a CORS policy. _policy = new CorsPolicy(); #region Headers var headers = ConfigurationManager.AppSettings[keyCorsHeaders]; if (headers == "*") _policy.AllowAnyHeader = true; else headers.Split(';').ToList().ForEach(i => _policy.Headers.Add(i)); #endregion #region Methods var methods = ConfigurationManager.AppSettings[keyCorsMethods]; if (methods == "*") _policy.AllowAnyMethod = true; else methods.Split(';').ToList().ForEach(i => _policy.Methods.Add(i)); #endregion #region Origins var origins = ConfigurationManager.AppSettings[keyCorsOrigins]; if (origins == "*") _policy.AllowAnyOrigin = true; else origins.Split(';').ToList().ForEach(i => _policy.Methods.Add(i)); #endregion } public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken) { return Task.FromResult(_policy); } } }
32.948276
115
0.613291
[ "MIT" ]
aniketphadte/Web-API-Template
WebAPITemplate/WebAPITemplate/Util/CorsPolicyAttribute.cs
1,913
C#
using System; using System.Collections.Generic; using System.Linq; using ljepotaservis.Infrastructure.DataTransferObjects.ServicesDtos; using ljepotaservis.Infrastructure.DataTransferObjects.StoreDtos; using ljepotaservis.Infrastructure.DataTransferObjects.UserDtos; using Newtonsoft.Json.Linq; namespace ljepotaservis.Infrastructure.DataTransferObjects.ReservationDtos { public class CreateReservationDto { public CreateReservationDto() {} public CreateReservationDto(JObject reservationServiceJObject) { StoreId = int.Parse(reservationServiceJObject["storeId"].ToString()); Client = reservationServiceJObject["user"].ToObject<UserDto>(); Employee = reservationServiceJObject["employee"].ToObject<EmployeeDto>(); DateTimeOfReservation = reservationServiceJObject["date"].ToObject<DateTime>().AddHours(2); var services = reservationServiceJObject["services"].Select(serviceToken => new ServiceDto(serviceToken)).ToList(); Services = services; } public int StoreId { get; set; } public UserDto Client { get; set; } public EmployeeDto Employee { get; set; } public ICollection<ServiceDto> Services { get; set; } public DateTime DateTimeOfReservation { get; set; } } }
40.424242
127
0.715142
[ "MIT" ]
AnteVuletic/ljepotaservis
ljepotaservis/ljepotaservis.Infrastructure/DataTransferObjects/ReservationDtos/CreateReservationDto.cs
1,336
C#
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Nez; using Nez.Sprites; using System; class Bumper : WorldObject, ITriggerListener { protected const float minBumpVelocity = 600f; protected readonly Vector2 bumpDirection = Vector2.Normalize(new Vector2(0f, -1)); protected SpriteAnimator animator; protected SoundEffect bounceSound; public override void OnAddedToEntity() { var collider = Entity.AddComponent(new BoxCollider(-110, -10, 220, 80)); collider.IsTrigger = true; animator = Entity.AddComponent(new SpriteAnimator() { LayerDepth = .5f }); animator.AddAnimation("idle", new[] { Game.Atlas.GetSprite("champi1") }); animator.AddAnimation("bump", Game.Atlas.GetAnimation("champi")); bounceSound = Core.Content.Load<SoundEffect>("bounce"); base.OnAddedToEntity(); } public void OnTriggerEnter(Collider other, Collider local) { var player = other.GetComponent<Player>(); player.Velocity += Math.Max(2 * Vector2.Dot(-player.Velocity, bumpDirection), minBumpVelocity) * bumpDirection; bounceSound.Play(); if (!player.IsThrowing()) { Debug.Log("Bumper bounced player : dino detected : " + player.DinoCount().ToString()); if (player.DinoCount() == 1) player.fsm.ChangeState<Flying_1State>(); else if (player.DinoCount() == 2) player.fsm.ChangeState<Flying_2State>(); else if (player.DinoCount() == 3) player.fsm.ChangeState<Flying_3State>(); } animator.Play("bump", SpriteAnimator.LoopMode.Once); } public void OnTriggerExit(Collider other, Collider local) { } }
34.54902
119
0.645857
[ "MIT" ]
Rouli-M/OpenJam2020
Components/Bumper.cs
1,764
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Framework.DomainDriven.ServiceModel.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.7.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("")] public string ServiceEnvironmentFactoryType { get { return ((string)(this["ServiceEnvironmentFactoryType"])); } } } }
42.194444
152
0.587887
[ "MIT" ]
Luxoft/BSSFramework
src/_DomainDriven/Framework.DomainDriven.ServiceModel/Properties/Settings.Designer.cs
1,486
C#
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // 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. // File System.Web.UI.BaseParser.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI { public partial class BaseParser { #region Methods and constructors public BaseParser () { } #endregion } }
42.75
463
0.768519
[ "MIT" ]
Acidburn0zzz/CodeContracts
Microsoft.Research/Contracts/System.Web/System.Web.UI.BaseParser.cs
2,052
C#
// *** WARNING: this file was generated by crd2pulumi. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Kubernetes.Types.Inputs.Argoproj.V1Alpha1 { /// <summary> /// ResourceStatus holds the current sync and health status of a resource /// </summary> public class ApplicationStatusResourcesArgs : Pulumi.ResourceArgs { [Input("group")] public Input<string>? Group { get; set; } [Input("health")] public Input<Pulumi.Kubernetes.Types.Inputs.Argoproj.V1Alpha1.ApplicationStatusResourcesHealthArgs>? Health { get; set; } [Input("hook")] public Input<bool>? Hook { get; set; } [Input("kind")] public Input<string>? Kind { get; set; } [Input("name")] public Input<string>? Name { get; set; } [Input("namespace")] public Input<string>? Namespace { get; set; } [Input("requiresPruning")] public Input<bool>? RequiresPruning { get; set; } /// <summary> /// SyncStatusCode is a type which represents possible comparison results /// </summary> [Input("status")] public Input<string>? Status { get; set; } [Input("version")] public Input<string>? Version { get; set; } public ApplicationStatusResourcesArgs() { } } }
28.867925
129
0.620915
[ "Apache-2.0" ]
pulumi/pulumi-kubernetes-crds
operators/argocd-operator/dotnet/Kubernetes/Crds/Operators/ArgocdOperator/Argoproj/V1Alpha1/Inputs/ApplicationStatusResourcesArgs.cs
1,530
C#