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
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Grades { public class GradeStatistics { public GradeStatistics() { HighestGrade = 0; LowestGrade = float.MaxValue; } public string Description { get { string result; switch (LetterGrade) { case "A": result = "Excellent"; break; case "B": result = "Good"; break; case "C": result = "Average"; break; case "D": result = "Below average"; break; default: result = "Failing"; break; } return result; } } public string LetterGrade { get { string result; if(AverageGrade >= 90) { result = "A"; } else if(AverageGrade >= 80) { result = "B"; } else if(AverageGrade >= 70) { result = "C"; } else if(AverageGrade >= 60) { result = "D"; } else { result = "F"; } return result; } } public float AverageGrade; public float HighestGrade; public float LowestGrade; } }
25.089744
50
0.314257
[ "Apache-2.0" ]
tarluna/Grades
Grades/GradeStatistics.cs
1,959
C#
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by SpecFlow (http://www.specflow.org/). // SpecFlow Version:2.1.0.0 // SpecFlow Generator Version:2.0.0.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ #region Designer generated code #pragma warning disable namespace CleanArchitecture.Specification.Customers.GetCustomersList { using TechTalk.SpecFlow; [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "2.1.0.0")] [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [NUnit.Framework.TestFixtureAttribute()] [NUnit.Framework.DescriptionAttribute("Get Customers List")] public partial class GetCustomersListFeature { private TechTalk.SpecFlow.ITestRunner testRunner; #line 1 "GetCustomersList.feature" #line hidden [NUnit.Framework.TestFixtureSetUpAttribute()] public virtual void FeatureSetup() { testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner(); TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Get Customers List", "\tAs a sales person\r\n\tI want to get a list of customers\r\n\tSo I can inspect the cus" + "tomers", ProgrammingLanguage.CSharp, ((string[])(null))); testRunner.OnFeatureStart(featureInfo); } [NUnit.Framework.TestFixtureTearDownAttribute()] public virtual void FeatureTearDown() { testRunner.OnFeatureEnd(); testRunner = null; } [NUnit.Framework.SetUpAttribute()] public virtual void TestInitialize() { } [NUnit.Framework.TearDownAttribute()] public virtual void ScenarioTearDown() { testRunner.OnScenarioEnd(); } public virtual void ScenarioSetup(TechTalk.SpecFlow.ScenarioInfo scenarioInfo) { testRunner.OnScenarioStart(scenarioInfo); } public virtual void ScenarioCleanup() { testRunner.CollectScenarioErrors(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Get a List of Customers")] public virtual void GetAListOfCustomers() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Get a List of Customers", ((string[])(null))); #line 6 this.ScenarioSetup(scenarioInfo); #line 7 testRunner.When("I request a list of customers", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line hidden TechTalk.SpecFlow.Table table1 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name"}); table1.AddRow(new string[] { "1", "Martin Fowler"}); table1.AddRow(new string[] { "2", "Uncle Bob"}); table1.AddRow(new string[] { "3", "Kent Beck"}); #line 8 testRunner.Then("the following customers should be returned:", ((string)(null)), table1, "Then "); #line hidden this.ScenarioCleanup(); } } } #pragma warning restore #endregion
37.081633
251
0.578976
[ "BSD-3-Clause" ]
Abaza96/cleanArchitecture
Specification/Customers/GetCustomersList/GetCustomersList.feature.cs
3,636
C#
using System; using System.Collections.Generic; namespace TwilightSparkle.Forum.DomainModel.IdentityServer4 { public class Client { public int Id { get; set; } public bool Enabled { get; set; } = true; public string ClientId { get; set; } public string ProtocolType { get; set; } = "oidc"; public List<ClientSecret> ClientSecrets { get; set; } public bool RequireClientSecret { get; set; } = true; public string ClientName { get; set; } public string Description { get; set; } public string ClientUri { get; set; } public string LogoUri { get; set; } public bool RequireConsent { get; set; } = false; public bool AllowRememberConsent { get; set; } = true; public bool AlwaysIncludeUserClaimsInIdToken { get; set; } public List<ClientGrantType> AllowedGrantTypes { get; set; } public bool RequirePkce { get; set; } = true; public bool AllowPlainTextPkce { get; set; } public bool RequireRequestObject { get; set; } public bool AllowAccessTokensViaBrowser { get; set; } public List<ClientRedirectUri> RedirectUris { get; set; } public List<ClientPostLogoutRedirectUri> PostLogoutRedirectUris { get; set; } public string FrontChannelLogoutUri { get; set; } public bool FrontChannelLogoutSessionRequired { get; set; } = true; public string BackChannelLogoutUri { get; set; } public bool BackChannelLogoutSessionRequired { get; set; } = true; public bool AllowOfflineAccess { get; set; } public List<ClientScope> AllowedScopes { get; set; } public int IdentityTokenLifetime { get; set; } = 300; public string AllowedIdentityTokenSigningAlgorithms { get; set; } public int AccessTokenLifetime { get; set; } = 3600; public int AuthorizationCodeLifetime { get; set; } = 300; public int? ConsentLifetime { get; set; } = null; public int AbsoluteRefreshTokenLifetime { get; set; } = 2592000; public int SlidingRefreshTokenLifetime { get; set; } = 1296000; public int RefreshTokenUsage { get; set; } = 1; // TokenUsage.OneTimeOnly; public bool UpdateAccessTokenClaimsOnRefresh { get; set; } public int RefreshTokenExpiration { get; set; } = 1; // TokenExpiration.Absolute; public int AccessTokenType { get; set; } = 0; // AccessTokenType.Jwt; public bool EnableLocalLogin { get; set; } = true; public List<ClientIdPRestriction> IdentityProviderRestrictions { get; set; } public bool IncludeJwtId { get; set; } public List<ClientClaim> Claims { get; set; } public bool AlwaysSendClientClaims { get; set; } public string ClientClaimsPrefix { get; set; } = "client_"; public string PairWiseSubjectSalt { get; set; } public List<ClientCorsOrigin> AllowedCorsOrigins { get; set; } public List<ClientProperty> Properties { get; set; } public DateTime Created { get; set; } = DateTime.UtcNow; public DateTime? Updated { get; set; } public DateTime? LastAccessed { get; set; } public int? UserSsoLifetime { get; set; } public string UserCodeType { get; set; } public int DeviceCodeLifetime { get; set; } = 300; public bool NonEditable { get; set; } } }
54.403226
89
0.651645
[ "Apache-2.0" ]
pavvlik777/Fluttershy_Barn_Forum
src/TwilightSparkle.Forum.DomainModel/IdentityServer4/Client.cs
3,375
C#
using System; using System.Linq; using System.Reflection; using System.Threading.Tasks; using NUnit.Framework; namespace BotFramework.Tests { // this [Ignore("This is just a proof of concept.")] public class TaskTests { private static Task _task; [Test] public async Task Test() { Func<Task> task1 = async () => { await Task.Delay(100); Console.WriteLine("Delay"); PrintTaskState(); }; Func<Task> task2 = async () => { await Task.Delay(100); Console.WriteLine("Delay"); PrintTaskState(); }; _task = Task.Run(async () => { PrintTaskState(); var someState = 0; await task1.Invoke(); await task2.Invoke(); someState++; Console.WriteLine("Done"); }); await _task; } private static int counter = 0; private static void ResetTaskState() { counter++; if (counter == 5) { throw new Exception(); } var a = _task.GetPrivateValue<Task>(5); var b = a.GetPrivateValue(1); b.SetPublicValue(0, 0); } private static void PrintTaskState() { var a = _task.GetPrivateValue<Task>(5); var b = a.GetPrivateValue(1); Console.WriteLine($"Task state is: {b.GetPrivateValue(0)}"); } } public static class ObjectHelpers { public static object GetPrivateValue<T>(this object o, int index) { return typeof(T).GetFields(BindingFlags.Instance | BindingFlags.NonPublic)[index].GetValue(o); } public static object GetPrivateValue(this object o, int index) { return o.GetType().GetRuntimeFields().ToArray()[index].GetValue(o); } public static void SetPublicValue(this object o, int index, object value) { o.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public)[index].SetValue(o, value); } } }
26.08046
106
0.506831
[ "MIT" ]
AskoldMakaruk/BotFramework
BotFramework.Tests/TaskTests.cs
2,269
C#
using System.Text.Json.Serialization; namespace TechSpace.Web.Models { public class Post { public string Id { get; set; } public string Author { get; set; } public string Title { get; set; } public string Content { get; set; } public string PassthroughUrl { get; set; } [JsonConverter(typeof(JsonStringEnumConverter))] public FeedProvider Provider { get; set; } } }
26.647059
56
0.600442
[ "MIT" ]
LukeBillo/tech-space
TechSpace.Web/Models/Post.cs
455
C#
using System; using System.IO; using System.IO.Compression; using System.Runtime.Serialization; using System.Security.Cryptography; namespace Lokad.Cqrs.StreamingStorage { [DataContract] public sealed class BinaryStreamReference { [DataMember(Order = 1)] public string Container { get; private set; } [DataMember(Order = 2)] public string Name { get; private set; } [DataMember(Order = 3)] public string Sha1 { get; private set; } [DataMember(Order = 4)] public int StorageSize { get; private set; } [DataMember(Order = 5)] public int ActualSize { get; private set; } [DataMember(Order = 6)] public bool Compressed { get; private set; } public BinaryStreamReference() { } public BinaryStreamReference(string container, string name, string sha1, int storageSize, int actualSize, bool compressed) { Container = container; Name = name; Sha1 = sha1; StorageSize = storageSize; ActualSize = actualSize; Compressed = compressed; } } public class BinaryStreamReader : IDisposable { readonly SHA1Managed _sha1 = new SHA1Managed(); readonly Stream _stream; readonly CryptoStream _crypto; public readonly BinaryStreamReference Reference; readonly GZipStream _zip; bool _streamsDisposed; public Stream Stream { get { return _crypto; } } public BinaryStreamReader(Stream stream, BinaryStreamReference reference) { Reference = reference; _stream = stream; if (reference.Compressed) { _zip = new GZipStream(stream, CompressionMode.Decompress); _crypto = new CryptoStream(_zip, _sha1, CryptoStreamMode.Read); } else { _crypto = new CryptoStream(stream, _sha1, CryptoStreamMode.Read); } } byte[] _computedSha1; void DisposeStreamsIfNeeded() { if (_streamsDisposed) return; using (_sha1) { using (_stream) using (_zip) using (_crypto) { _streamsDisposed = true; } _computedSha1 = _sha1.Hash; } } public void ReadRestOfStreamToComputeHashes() { var buffer = new byte[1024 * 10]; while (true) { if (_crypto.Read(buffer, 0, buffer.Length) == 0) return; } } public void CloseAndVerifyHash() { DisposeStreamsIfNeeded(); var exectedSha1 = Reference.Sha1; if (null == exectedSha1) return; var computedSha1 = BitConverter.ToString(_computedSha1).Replace("-", "").ToLowerInvariant(); if (!String.Equals(exectedSha1, computedSha1, StringComparison.InvariantCultureIgnoreCase)) throw new InvalidOperationException(String.Format("Hash mismatch in {2}. Expected '{0}' was '{1}'", exectedSha1, computedSha1, Reference)); } public void Dispose() { DisposeStreamsIfNeeded(); } } public class BinaryStreamWriter : IDisposable { readonly SHA1Managed _sha1 = new SHA1Managed(); readonly string _fileName; readonly string _container; readonly Stream _stream; readonly CryptoStream _crypto; readonly GZipStream _zip; readonly StreamCounter _storageCounter; readonly StreamCounter _actualCounter; readonly bool _compress; public Stream Stream { get { return _actualCounter; } } public BinaryStreamWriter(Stream stream, string container, string fileName, bool compress) { _stream = stream; _container = container; _fileName = fileName; _storageCounter = new StreamCounter(_stream); if (compress) { _zip = new GZipStream(_storageCounter, CompressionMode.Compress, false); _crypto = new CryptoStream(_zip, _sha1, CryptoStreamMode.Write); } else { _crypto = new CryptoStream(_storageCounter, _sha1, CryptoStreamMode.Write); } _actualCounter = new StreamCounter(_crypto); _compress = compress; } bool _streamsDisposed; int _storageSize; int _actualSize; void DisposeStreamsIfNeeded() { if (_streamsDisposed) return; using (_sha1) { using (_storageCounter) using (_stream) using (_zip) using (_crypto) using (_actualCounter) { _streamsDisposed = true; } _computedSha1 = BitConverter.ToString(_sha1.Hash).Replace("-", "").ToUpperInvariant(); _storageSize = _storageCounter.WrittenBytes; _actualSize = _actualCounter.WrittenBytes; } } string _computedSha1; public BinaryStreamReference CloseAndComputeHash() { DisposeStreamsIfNeeded(); return new BinaryStreamReference(_container, _fileName, _computedSha1, _storageSize, _actualSize, _compress); } public void Dispose() { DisposeStreamsIfNeeded(); } } public sealed class StreamCounter : Stream { readonly Stream _stream; public int WrittenBytes { get; private set; } public StreamCounter(Stream stream) { _stream = stream; } public override void Flush() { _stream.Flush(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException("Seeking is not supported"); } public override void SetLength(long value) { _stream.SetLength(value); } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException("Reading is not supported"); } public override void Write(byte[] buffer, int offset, int count) { _stream.Write(buffer, offset, count); WrittenBytes += count; } public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return _stream.CanWrite; } } public override long Length { get { return _stream.Length; } } public override long Position { get { return _stream.Position; } set { throw new NotSupportedException("Stream can't change position"); } } } }
28.268482
130
0.547694
[ "BSD-3-Clause" ]
FlipGitBits/lokad-cqrs
Cqrs.Portable/DataStreams/BinaryStreams.cs
7,265
C#
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using PureCloudPlatform.Client.V2.Client; namespace PureCloudPlatform.Client.V2.Model { /// <summary> /// QueueConversationCobrowseEventTopicScoredAgent /// </summary> [DataContract] public partial class QueueConversationCobrowseEventTopicScoredAgent : IEquatable<QueueConversationCobrowseEventTopicScoredAgent> { /// <summary> /// Initializes a new instance of the <see cref="QueueConversationCobrowseEventTopicScoredAgent" /> class. /// </summary> /// <param name="Agent">Agent.</param> /// <param name="Score">Score.</param> public QueueConversationCobrowseEventTopicScoredAgent(QueueConversationCobrowseEventTopicUriReference Agent = null, int? Score = null) { this.Agent = Agent; this.Score = Score; } /// <summary> /// Gets or Sets Agent /// </summary> [DataMember(Name="agent", EmitDefaultValue=false)] public QueueConversationCobrowseEventTopicUriReference Agent { get; set; } /// <summary> /// Gets or Sets Score /// </summary> [DataMember(Name="score", EmitDefaultValue=false)] public int? Score { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class QueueConversationCobrowseEventTopicScoredAgent {\n"); sb.Append(" Agent: ").Append(Agent).Append("\n"); sb.Append(" Score: ").Append(Score).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as QueueConversationCobrowseEventTopicScoredAgent); } /// <summary> /// Returns true if QueueConversationCobrowseEventTopicScoredAgent instances are equal /// </summary> /// <param name="other">Instance of QueueConversationCobrowseEventTopicScoredAgent to be compared</param> /// <returns>Boolean</returns> public bool Equals(QueueConversationCobrowseEventTopicScoredAgent other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return true && ( this.Agent == other.Agent || this.Agent != null && this.Agent.Equals(other.Agent) ) && ( this.Score == other.Score || this.Score != null && this.Score.Equals(other.Score) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Agent != null) hash = hash * 59 + this.Agent.GetHashCode(); if (this.Score != null) hash = hash * 59 + this.Score.GetHashCode(); return hash; } } } }
31.335616
142
0.535738
[ "MIT" ]
nmusco/platform-client-sdk-dotnet
build/src/PureCloudPlatform.Client.V2/Model/QueueConversationCobrowseEventTopicScoredAgent.cs
4,575
C#
using HarmonyLib; using Kingmaker.UnitLogic; using Kingmaker.UnitLogic.Class.LevelUp.Actions; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace ToyBox.Multiclass { public static class SkillPoint { public static int CalcTotalSkillPointsNonMythic(this ClassData cd) => cd.CharacterClass.IsMythic ? 0 : cd.CalcSkillPoints() * cd.Level; public static int? GetTotalSkillPoints(UnitDescriptor unit, int nextLevel) { var intelligenceSkillPoints = LevelUpHelper.GetTotalIntelligenceSkillPoints(unit, nextLevel); var classes = unit.Progression.Classes; var split = classes.GroupBy(cd => unit.IsClassGestalt(cd.CharacterClass)); var total = 0; var gestaltCount = 0; var baseTotal = 0; var gestaltSumOrMax = 0; foreach (var group in split) { if (group.Key == false) baseTotal += group.ToList().Sum(cd => cd.CalcTotalSkillPointsNonMythic()); else { var gestaltClasses = group.ToList(); gestaltCount = gestaltClasses.Count; if (gestaltCount > 0) { switch (Main.settings.multiclassSkillPointPolicy) { case ProgressionPolicy.Largest: gestaltSumOrMax += gestaltClasses.Max(cl => cl.CalcTotalSkillPointsNonMythic()); break; case ProgressionPolicy.Average: case ProgressionPolicy.Sum: gestaltSumOrMax += gestaltClasses.Sum(cl => cl.CalcTotalSkillPointsNonMythic()); break; default: break; } } } } total = Main.settings.multiclassSkillPointPolicy switch { ProgressionPolicy.Largest => Mathf.Max(baseTotal, gestaltSumOrMax), ProgressionPolicy.Average => (gestaltSumOrMax + baseTotal) / (gestaltCount + 1), ProgressionPolicy.Sum => gestaltSumOrMax + baseTotal, _ => baseTotal, }; return Mathf.Max(intelligenceSkillPoints + total, nextLevel); } [HarmonyPatch(typeof(LevelUpHelper), "GetTotalSkillPoints")] public static class LevelUpHelper_GetTotalSkillPoints_Patch { public static bool Prefix(UnitDescriptor unit, int nextLevel, ref int __result) { if (!MultipleClasses.IsAvailable()) return true; var totalSkillPoints = GetTotalSkillPoints(unit, nextLevel); if (totalSkillPoints.HasValue) { __result = totalSkillPoints.Value; return false; } else return true; } } } }
47.403226
143
0.562436
[ "MIT" ]
AeonBlack/ToyBox
ToyBox/classes/MonkeyPatchin/Multiclass/StatProgression/SkillPoint.cs
2,941
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Microsoft.Azure.IIoT.App.Data { using Microsoft.Azure.IIoT.App.Models; using Microsoft.Azure.IIoT.OpcUa.Api.Registry.Models; using System.Collections.Generic; using System.Linq; /// <summary> /// Handle event /// </summary> public static class DiscovererInfoEx { /// <summary> /// Update a list of discoverers from a received event /// </summary> /// <param name="results"></param> /// <param name="ev"></param> public static void Update(this IList<DiscovererInfo> results, DiscovererEventApiModel ev) { var discoverer = results.FirstOrDefault(e => e.DiscovererModel.Id == ev.Id); if (discoverer == null && ev.EventType != DiscovererEventType.New) { return; } switch (ev.EventType) { case DiscovererEventType.New: if (discoverer == null) { // Add if not already in list results.Add(new DiscovererInfo { DiscovererModel = ev.Discoverer }); } break; case DiscovererEventType.Updated: ev.Discoverer.Patch(discoverer.DiscovererModel); break; case DiscovererEventType.Deleted: results.Remove(discoverer); break; } } } }
37.583333
99
0.494457
[ "MIT" ]
Azure/Industrial-IoT
samples/src/Microsoft.Azure.IIoT.App/src/Extensions/DiscovererInfoEx.cs
1,806
C#
//----------------------------------------------------------------------------- // FILE: ModelGenTestHelper // CONTRIBUTOR: Jeff Lill // COPYRIGHT: Copyright (c) 2005-2022 by neonFORGE LLC. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Loader; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Neon.Common; using Neon.CSharp; using Neon.ModelGen; using Neon.Xunit; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Xunit; namespace TestModelGen { /// <summary> /// Test helpers. /// </summary> internal static class ModelGenTestHelper { /// <summary> /// Adds the assembly references required to compile the generated code. /// </summary> /// <param name="references">The assembly references.</param> public static void ReferenceHandler(MetadataReferences references) { references.Add(typeof(System.Dynamic.CallInfo)); references.Add(typeof(Newtonsoft.Json.JsonToken)); } } }
29.706897
80
0.679629
[ "Apache-2.0" ]
codelastnight/neonKUBE
Test/Test.Neon.ModelGen/ModelGenTestHelper.cs
1,725
C#
using BusinessLayer.Abstract; using DataAccessLayer.Abstract; using EntityLayer.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BusinessLayer.Concrete { public class CommentManager : ICommentService { ICommentDal _commentDal; public CommentManager(ICommentDal commentDal) { _commentDal = commentDal; } public void CommentAdd(Comment comment) { _commentDal.Insert(comment); } public List<Comment> GetList(int id) { return _commentDal.List(x=>x.BlogId==id); } } }
22.7
53
0.653451
[ "MIT" ]
rabianur412/CoreDemo
BusinessLayer/Concrete/CommentManager.cs
683
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================================= ** ** ** ** Purpose: The arrays are of different primitive types. ** ** =============================================================================*/ using System.Runtime.Serialization; namespace System { // The ArrayMismatchException is thrown when an attempt to store // an object of the wrong type within an array occurs. [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ArrayTypeMismatchException : SystemException { // Creates a new ArrayMismatchException with its message string set to // the empty string, its HRESULT set to COR_E_ARRAYTYPEMISMATCH, // and its ExceptionInfo reference set to null. public ArrayTypeMismatchException() : base(SR.Arg_ArrayTypeMismatchException) { HResult = HResults.COR_E_ARRAYTYPEMISMATCH; } // Creates a new ArrayMismatchException with its message string set to // message, its HRESULT set to COR_E_ARRAYTYPEMISMATCH, // and its ExceptionInfo reference set to null. // public ArrayTypeMismatchException(String message) : base(message) { HResult = HResults.COR_E_ARRAYTYPEMISMATCH; } public ArrayTypeMismatchException(String message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_ARRAYTYPEMISMATCH; } protected ArrayTypeMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
36.185185
134
0.626919
[ "MIT" ]
AaronRobinsonMSFT/coreclr
src/System.Private.CoreLib/shared/System/ArrayTypeMismatchException.cs
1,954
C#
using Newtonsoft.Json; using VkApi.Wrapper.Objects; using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Threading.Tasks; namespace VkApi.Wrapper.Responses { public class StoriesGetBannedResponse { ///<summary> /// Stories count ///</summary> [JsonProperty("count")] public int Count { get; set; } [JsonProperty("items")] public int[] Items { get; set; } } }
23.55
41
0.645435
[ "MIT" ]
FrediKats/VkLibrary
VkApi.Wrapper/Responses/Stories/StoriesGetBannedResponse.cs
471
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace Microsoft.Build.Logging.StructuredLogger { /// <summary> /// Base class to represent a log node (e.g. Project, or Target) that can contain child node sub nodes /// and properties defined at that scope. Properties defined will be inherited from the parent if possible. /// </summary> internal abstract class LogProcessNode : ILogNode { /// <summary> /// The child nodes bucketed by their type. This is for performance iterating through the list by /// type as well as to preserve order within the types (List will preserve order). /// </summary> private readonly Dictionary<Type, List<ILogNode>> _childNodes; /// <summary> /// Initializes a new instance of the <see cref="LogProcessNode"/> class. /// </summary> protected LogProcessNode() { Properties = new PropertyBag(); _childNodes = new Dictionary<Type, List<ILogNode>>(); } /// <summary> /// Gets or sets the name of the node (e.g. name of the project). /// </summary> /// <value> /// The name of the node. /// </value> public string Name { get; set; } /// <summary> /// Gets or sets the identifier of the node. /// </summary> /// <value> /// The identifier. /// </value> public int Id { get; protected set; } /// <summary> /// Gets or sets the time at which MSBuild indicated the node started execution. /// </summary> /// <value> /// The start time. /// </value> public DateTime StartTime { get; protected set; } /// <summary> /// Gets or sets the time at which MSBuild indicated the node completed execution. /// </summary> /// <value> /// The end time. /// </value> public DateTime EndTime { get; set; } /// <summary> /// Gets or sets the properties collection for this node. /// </summary> /// <value> /// The properties. /// </value> public PropertyBag Properties { get; protected set; } /// <summary> /// Writes the node to XML XElement representation. /// </summary> /// <param name="parentElement">The parent element.</param> public abstract void SaveToElement(XElement parentElement); /// <summary> /// Adds a generic message type child to the node. /// </summary> /// <param name="message">The message node to add.</param> public void AddMessage(Message message) { AddChildNode(message); } /// <summary> /// Adds the child node. /// </summary> /// <typeparam name="T">Generic ILogNode type to add</typeparam> /// <param name="childNode">The child node.</param> protected void AddChildNode<T>(T childNode) where T : ILogNode { var type = childNode.GetType(); if (_childNodes.ContainsKey(type)) { _childNodes[type].Add(childNode); } else { _childNodes[type] = new List<ILogNode> { childNode }; } } /// <summary> /// Gets the child nodes that are of type T. /// </summary> /// <remarks>Must be exactly of type T, not inherited</remarks> /// <typeparam name="T">Generic ILogNode type</typeparam> /// <returns></returns> protected IEnumerable<T> GetChildrenOfType<T>() where T : ILogNode { var t = typeof(T); return _childNodes.ContainsKey(t) ? _childNodes[t].Cast<T>() : new List<T>(); } /// <summary> /// Writes the properties associated with this node to the XML element. /// </summary> /// <param name="parentElement">The parent element.</param> protected void WriteProperties(XElement parentElement) { if (Properties.Properties.Count > 0) { var propElement = new XElement("Properties"); foreach (var p in Properties.Properties) { propElement.Add(new XElement("Property", new XAttribute("Name", p.Key)) { Value = p.Value }); } parentElement.Add(propElement); } } /// <summary> /// Writes the children of type T to the XML element. /// </summary> /// <typeparam name="T">Generic ILogNode type</typeparam> /// <param name="parentElement">The root.</param> protected void WriteChildren<T>(XElement parentElement) where T : ILogNode { foreach (var child in GetChildrenOfType<T>()) { child.SaveToElement(parentElement); } } /// <summary> /// Writes the children of type T to the XML element and creates a root node if necessary. /// </summary> /// <typeparam name="T">Generic ILogNode type</typeparam> /// <param name="parentElement">The parent element.</param> /// <param name="subNodeFactory">Delegate to create a new element to contain children. Will not be called if /// there are no children of the specified type.</param> protected void WriteChildren<T>(XElement parentElement, Func<XElement> subNodeFactory) where T : ILogNode { if (GetChildrenOfType<T>().Any()) { var node = subNodeFactory(); WriteChildren<T>(node); parentElement.Add(node); } } } }
35.712575
117
0.5555
[ "MIT" ]
0n1zz/main
Samples/XmlFileLogger/LogProcessNode.cs
5,966
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.ML.Probabilistic.Learners.BayesPointMachineClassifierInternal { using System; using System.IO; using Microsoft.ML.Probabilistic.Distributions; using Microsoft.ML.Probabilistic.Serialization; using GaussianArray = Microsoft.ML.Probabilistic.Distributions.DistributionStructArray<Distributions.Gaussian, double>; /// <summary> /// A binary Bayes point machine classifier with <see cref="Gaussian"/> prior distributions over factorized weights. /// <para> /// The factorized weight distributions can be interpreted as a <see cref="VectorGaussian"/> distribution /// with diagonal covariance matrix, which ignores possible correlations between weights. /// </para> /// </summary> [Serializable] internal class GaussianBinaryFactorizedInferenceAlgorithms : BinaryFactorizedInferenceAlgorithms { #region Fields and constructors /// <summary> /// The current custom binary serialization version of the <see cref="GaussianBinaryFactorizedInferenceAlgorithms"/> class. /// </summary> private const int CustomSerializationVersion = 1; /// <summary> /// The prior distributions over weights for the training algorithm. /// </summary> private readonly GaussianArray weightPriorDistributions; /// <summary> /// Initializes a new instance of the <see cref="GaussianBinaryFactorizedInferenceAlgorithms"/> class. /// </summary> /// <param name="computeModelEvidence">If true, the training algorithm computes evidence.</param> /// <param name="useSparseFeatures">If true, the inference algorithms expect features in a sparse representation.</param> /// <param name="featureCount">The number of features that the inference algorithms use.</param> /// <param name="weightPriorVariance">The variance of the prior distributions over weights. Defaults to 1.</param> public GaussianBinaryFactorizedInferenceAlgorithms(bool computeModelEvidence, bool useSparseFeatures, int featureCount, double weightPriorVariance = 1.0) : base(computeModelEvidence, useSparseFeatures, featureCount) { InferenceAlgorithmUtilities.CheckVariance(weightPriorVariance); // Set the prior distributions over weights this.weightPriorDistributions = new GaussianArray(new Gaussian(0.0, weightPriorVariance), featureCount); } /// <summary> /// Initializes a new instance of the <see cref="GaussianBinaryFactorizedInferenceAlgorithms"/> class /// from a reader of a binary stream. /// </summary> /// <param name="reader">The binary reader to read the state of the inference algorithm from.</param> public GaussianBinaryFactorizedInferenceAlgorithms(IReader reader) : base(reader) { int deserializedVersion = reader.ReadSerializationVersion(CustomSerializationVersion); if (deserializedVersion == CustomSerializationVersion) { this.weightPriorDistributions = reader.ReadGaussianArray(); } } #endregion #region ICustomSerializable implementation /// <summary> /// Saves the state of the inference algorithms using the specified writer to a binary stream. /// </summary> /// <param name="writer">The writer to save the state of the inference algorithms to.</param> public override void SaveForwardCompatible(IWriter writer) { base.SaveForwardCompatible(writer); writer.Write(CustomSerializationVersion); writer.Write(this.weightPriorDistributions); } #endregion #region Inference /// <summary> /// Runs the generated training algorithm for the specified features and labels. /// </summary> /// <param name="featureValues">The feature values.</param> /// <param name="featureIndexes">The feature indexes.</param> /// <param name="labels">The labels.</param> /// <param name="iterationCount">The number of iterations to run the training algorithm for.</param> /// <param name="batchNumber"> /// An optional batch number. Defaults to 0 and is used only if the training data is divided into batches. /// </param> protected override void TrainInternal(double[][] featureValues, int[][] featureIndexes, bool[] labels, int iterationCount, int batchNumber = 0) { // Update the prior distributions over weights this.TrainingAlgorithm.SetObservedValue(InferenceQueryVariableNames.WeightPriors, this.weightPriorDistributions); // Run training base.TrainInternal(featureValues, featureIndexes, labels, iterationCount, batchNumber); } #endregion #region Inference algorithm generation /// <summary> /// Creates an Infer.NET inference algorithm which trains the Bayes point machine classifier. /// </summary> /// <param name="computeModelEvidence">If true, the generated training algorithm computes evidence.</param> /// <param name="useSparseFeatures">If true, the generated training algorithm expects features in a sparse representation.</param> /// <returns>The created <see cref="IGeneratedAlgorithm"/> for training.</returns> protected override IGeneratedAlgorithm CreateTrainingAlgorithm(bool computeModelEvidence, bool useSparseFeatures) { return InferenceAlgorithmUtilities.CreateBinaryTrainingAlgorithm( computeModelEvidence, useSparseFeatures, useCompoundWeightPriorDistributions: false); } /// <summary> /// Creates an Infer.NET inference algorithm for making predictions from the Bayes point machine classifier. /// </summary> /// <param name="useSparseFeatures">If true, the generated prediction algorithm expects features in a sparse representation.</param> /// <returns>The created <see cref="IGeneratedAlgorithm"/> for prediction.</returns> protected override IGeneratedAlgorithm CreatePredictionAlgorithm(bool useSparseFeatures) { return InferenceAlgorithmUtilities.CreateBinaryPredictionAlgorithm(useSparseFeatures); } #endregion } }
48.137681
161
0.685684
[ "MIT" ]
ScriptBox99/dotnet-infer
src/Learners/Classifier/BayesPointMachineClassifierInternal/Algorithms/GaussianBinaryFactorizedInferenceAlgorithms.cs
6,643
C#
// 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. namespace Castle.Components.Validator { using System; /// <summary> /// Validate that this date is a valid one. /// </summary> /// <remarks> /// This checks the format of the date /// </remarks> [Serializable, CLSCompliant(false)] [AttributeUsage(AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Parameter, AllowMultiple = true)] public class ValidateDateTimeAttribute : AbstractValidationAttribute { /// <summary> /// Initializes a new instance of the <see cref="ValidateDateTimeAttribute"/> class. /// </summary> public ValidateDateTimeAttribute() { } /// <summary> /// Initializes a new instance of the <see cref="ValidateDateAttribute"/> class. /// </summary> /// <param name="errorMessage">The error message.</param> public ValidateDateTimeAttribute(string errorMessage) : base(errorMessage) { } /// <summary> /// Constructs and configures an <see cref="IValidator"/> /// instance based on the properties set on the attribute instance. /// </summary> /// <returns></returns> public override IValidator Build() { IValidator validator = new DateTimeValidator(); ConfigureValidatorMessage(validator); return validator; } } }
31.457627
126
0.717134
[ "Apache-2.0" ]
hach-que/Castle.Core
src/Castle.Components.Validator/Attributes/ValidateDateTimeAttribute.cs
1,856
C#
using BaoZi.IService; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BaoZi.Service { public class OrderService : IOrderService { public string CreateOrder() { return "下单成功"; } } }
17.166667
45
0.656958
[ "MIT" ]
weixiaolong325/.NetCore5.0AutofacDemo
BaoZi.Service/OrderService.cs
319
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Counselor.Platform.Tests.Core.Repositories { [TestClass] public class DialogsRepositoryTests { [TestMethod] public void CreateOrUpdateDialogSimple() { } } }
15.6
52
0.773504
[ "MIT" ]
AxQE/Counselor.Platform
tests/Counselor.Platform.Tests/Core/Repositories/DialogsRepositoryTests.cs
236
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; using System.Windows.Markup; using MaterialDesignExtensions.Commands.Internal; using MaterialDesignExtensions.Controllers; using MaterialDesignExtensions.Model; namespace MaterialDesignExtensions.Controls { /// <summary> /// A decorator control to add some kind of autocomplete features to a default TextBox. /// </summary> [ContentProperty(nameof(TextBox))] public class TextBoxSuggestions : ControlWithAutocompletePopup { private static readonly string SuggestionItemsControlName = "suggestionItemsControl"; private static readonly string SuggestionItemsPopupName = "suggestionItemsPopup"; /// <summary> /// The TextBox to decorate. /// </summary> public static readonly DependencyProperty TextBoxProperty = DependencyProperty.Register( nameof(TextBox), typeof(TextBox), typeof(TextBoxSuggestions), new PropertyMetadata(null, TextBoxChangedHandler)); /// <summary> /// The TextBox to decorate. /// </summary> public TextBox TextBox { get { return (TextBox)GetValue(TextBoxProperty); } set { SetValue(TextBoxProperty, value); } } /// <summary> /// A source for providing the suggestions. /// </summary> public static readonly DependencyProperty TextBoxSuggestionsSourceProperty = DependencyProperty.Register( nameof(TextBoxSuggestionsSource), typeof(ITextBoxSuggestionsSource), typeof(TextBoxSuggestions), new PropertyMetadata(null, TextBoxSuggestionsSourceChangedHandler)); /// <summary> /// A source for providing the suggestions. /// </summary> public ITextBoxSuggestionsSource TextBoxSuggestionsSource { get { return (ITextBoxSuggestionsSource)GetValue(TextBoxSuggestionsSourceProperty); } set { SetValue(TextBoxSuggestionsSourceProperty, value); } } private ItemsControl m_suggestionItemsControl; private AutocompleteController m_autocompleteController; static TextBoxSuggestions() { DefaultStyleKeyProperty.OverrideMetadata(typeof(TextBoxSuggestions), new FrameworkPropertyMetadata(typeof(TextBoxSuggestions))); } /// <summary> /// Creates a new <see cref="TextBoxSuggestions" />. /// </summary> public TextBoxSuggestions() : base() { m_suggestionItemsControl = null; m_autocompleteController = new AutocompleteController() { AutocompleteSource = TextBoxSuggestionsSource }; CommandBindings.Add(new CommandBinding(TextBoxSuggestionsCommands.SelectSuggestionItemCommand, SelectSuggestionItemCommandHandler)); Loaded += LoadedHandler; Unloaded += UnloadedHandler; } public override void OnApplyTemplate() { base.OnApplyTemplate(); m_popup = Template.FindName(SuggestionItemsPopupName, this) as AutocompletePopup; m_suggestionItemsControl = Template.FindName(SuggestionItemsControlName, this) as ItemsControl; } protected override void LoadedHandler(object sender, RoutedEventArgs args) { base.LoadedHandler(sender, args); if (m_autocompleteController != null) { m_autocompleteController.AutocompleteItemsChanged += AutocompleteItemsChangedHandler; } if (TextBox != null) { // first remove the event handler to prevent multiple registrations TextBox.TextChanged -= TextBoxTextChangedHandler; TextBox.KeyUp -= TextBoxKeyUpHandler; // and then set the event handler TextBox.TextChanged += TextBoxTextChangedHandler; TextBox.KeyUp += TextBoxKeyUpHandler; } } protected override void UnloadedHandler(object sender, RoutedEventArgs args) { base.UnloadedHandler(sender, args); if (m_autocompleteController != null) { m_autocompleteController.AutocompleteItemsChanged -= AutocompleteItemsChangedHandler; } if (TextBox != null) { TextBox.TextChanged -= TextBoxTextChangedHandler; TextBox.KeyUp -= TextBoxKeyUpHandler; } } private void SelectSuggestionItemCommandHandler(object sender, ExecutedRoutedEventArgs args) { if (TextBox != null) { TextBox.Text = args.Parameter as string; } } private static void TextBoxChangedHandler(DependencyObject obj, DependencyPropertyChangedEventArgs args) { (obj as TextBoxSuggestions)?.TextBoxChangedHandler(args.OldValue as TextBox, args.NewValue as TextBox); } private void TextBoxChangedHandler(TextBox oldTextBox, TextBox newTextBox) { if (oldTextBox != null) { oldTextBox.TextChanged -= TextBoxTextChangedHandler; newTextBox.KeyUp -= TextBoxKeyUpHandler; } if (newTextBox != null) { newTextBox.TextChanged += TextBoxTextChangedHandler; newTextBox.KeyUp += TextBoxKeyUpHandler; } } private void TextBoxTextChangedHandler(object sender, TextChangedEventArgs args) { if (sender == TextBox) { m_autocompleteController?.Search(TextBox.Text); } } private void TextBoxKeyUpHandler(object sender, KeyEventArgs args) { if (sender == TextBox && args.Key == Key.Down) { m_suggestionItemsControl.Focus(); } } private static void TextBoxSuggestionsSourceChangedHandler(DependencyObject obj, DependencyPropertyChangedEventArgs args) { (obj as TextBoxSuggestions)?.TextBoxSuggestionsSourceChangedHandler(args.NewValue as ITextBoxSuggestionsSource); } private void TextBoxSuggestionsSourceChangedHandler(ITextBoxSuggestionsSource textBoxSuggestionsSource) { if (m_autocompleteController != null) { m_autocompleteController.AutocompleteSource = textBoxSuggestionsSource; } } private void AutocompleteItemsChangedHandler(object sender, AutocompleteItemsChangedEventArgs args) { Dispatcher.Invoke(() => { SetSuggestionItems(args.Items); }); } private void SetSuggestionItems(IEnumerable suggestionItems) { if (m_suggestionItemsControl != null) { if (suggestionItems != null) { m_suggestionItemsControl.ItemsSource = suggestionItems; } else { m_suggestionItemsControl.ItemsSource = null; } } } } }
33.78125
177
0.61451
[ "MIT" ]
GerHobbelt/MaterialDesignExtensions
MaterialDesignExtensions/Controls/TextBoxSuggestions.cs
7,569
C#
using UnityEngine; namespace Utils { public class DontDestroyOnLoad : MonoBehaviour { private void Start() => DontDestroyOnLoad(gameObject); } }
16.777778
56
0.754967
[ "MIT" ]
sgaumin/TemplateGJ_2D
Assets/Scripts/Utils/Organization/DontDestroyOnLoad.cs
153
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Runtime.Remoting; using System.Threading.Tasks; using Orleans.Runtime; using Orleans.Runtime.Configuration; namespace Orleans.TestingHost { /// <summary> /// Represents a handle to a silo that is deployed inside a remote AppDomain, but in the same process /// </summary> public class AppDomainSiloHandle : SiloHandle { private bool isActive = true; /// <summary> Get or set the AppDomain used by the silo </summary> public AppDomain AppDomain { get; set; } /// <summary>Gets or sets a reference to the silo host that is marshable by reference.</summary> public AppDomainSiloHost SiloHost { get; set; } /// <inheritdoc /> public override bool IsActive => isActive; /// <summary>Creates a new silo in a remote app domain and returns a handle to it.</summary> public static SiloHandle Create( string siloName, Silo.SiloType type, Type siloBuilderFactory, ClusterConfiguration config, NodeConfiguration nodeConfiguration, string applicationBase = null) { AppDomainSetup setup = GetAppDomainSetupInfo(applicationBase); var appDomain = AppDomain.CreateDomain(siloName, null, setup); try { var args = new object[] {siloName, siloBuilderFactory, config}; var siloHost = (AppDomainSiloHost) appDomain.CreateInstanceAndUnwrap( typeof(AppDomainSiloHost).Assembly.FullName, typeof(AppDomainSiloHost).FullName, false, BindingFlags.Default, null, args, CultureInfo.CurrentCulture, new object[] { }); appDomain.UnhandledException += ReportUnobservedException; siloHost.Start(); var retValue = new AppDomainSiloHandle { Name = siloName, SiloHost = siloHost, NodeConfiguration = nodeConfiguration, SiloAddress = siloHost.SiloAddress, Type = type, AppDomain = appDomain, AppDomainTestHook = siloHost.AppDomainTestHook, }; return retValue; } catch (Exception) { UnloadAppDomain(appDomain); throw; } } /// <inheritdoc /> public override void StopSilo(bool stopGracefully) { if (!IsActive) return; if (stopGracefully) { try { this.SiloHost.Shutdown(); } catch (RemotingException re) { WriteLog(re); /* Ignore error */ } catch (Exception exc) { WriteLog(exc); throw; } } this.isActive = false; try { UnloadAppDomain(); } catch (Exception exc) { WriteLog(exc); throw; } this.SiloHost = null; } private void UnloadAppDomain() { UnloadAppDomain(this.AppDomain); this.AppDomain = null; } private static void UnloadAppDomain(AppDomain appDomain) { if (appDomain != null) { appDomain.UnhandledException -= ReportUnobservedException; AppDomain.Unload(appDomain); } } /// <inheritdoc /> protected override void Dispose(bool disposing) { if (!this.IsActive) return; if (disposing) { StopSilo(true); } else { // Do not attempt to unload the AppDomain in the finalizer thread itself, as it is not supported, and also not a lot of work should be done in it var appDomain = this.AppDomain; appDomain.UnhandledException -= ReportUnobservedException; Task.Run(() => AppDomain.Unload(appDomain)).Ignore(); } } private void WriteLog(object value) { // TODO: replace Console.WriteLine(value.ToString()); } internal static AppDomainSetup GetAppDomainSetupInfo(string applicationBase) { var currentAppDomain = AppDomain.CurrentDomain; return new AppDomainSetup { ApplicationBase = string.IsNullOrEmpty(applicationBase) ? Environment.CurrentDirectory : applicationBase, ConfigurationFile = currentAppDomain.SetupInformation.ConfigurationFile, ShadowCopyFiles = currentAppDomain.SetupInformation.ShadowCopyFiles, ShadowCopyDirectories = currentAppDomain.SetupInformation.ShadowCopyDirectories, CachePath = currentAppDomain.SetupInformation.CachePath }; } private static void ReportUnobservedException(object sender, System.UnhandledExceptionEventArgs eventArgs) { Exception exception = (Exception)eventArgs.ExceptionObject; // WriteLog("Unobserved exception: {0}", exception); } } }
32.649425
161
0.534941
[ "MIT" ]
seralexeev/orleans
src/Orleans.TestingHost/AppDomainSiloHandle.cs
5,683
C#
using System; namespace Orleans.Indexing { /// <summary> /// A simple implementation of a partitioned in-memory hash-index /// </summary> /// <typeparam name="K">type of hash-index key</typeparam> /// <typeparam name="V">type of grain that is being indexed</typeparam> [Serializable] public class ActiveHashIndexPartitionedPerKey<K, V> : HashIndexPartitionedPerKey<K, V, IActiveHashIndexPartitionedPerKeyBucket<K, V>> where V : class, IIndexableGrain { public ActiveHashIndexPartitionedPerKey(IServiceProvider serviceProvider, string indexName, bool isUniqueIndex) : base(serviceProvider, indexName, isUniqueIndex) { } } }
38
170
0.71345
[ "MIT" ]
TedHartMS/OrleansV2.Fork.Indexing
src/Orleans.Indexing/Indexes/ActiveIndexes/ActiveHashIndexPartitionedPerKey.cs
684
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.DocumentDB.V20200901.Outputs { [OutputType] public sealed class PeriodicModeBackupPolicyResponse { /// <summary> /// Configuration values for periodic mode backup /// </summary> public readonly Outputs.PeriodicModePropertiesResponse? PeriodicModeProperties; /// <summary> /// Describes the mode of backups. /// </summary> public readonly string Type; [OutputConstructor] private PeriodicModeBackupPolicyResponse( Outputs.PeriodicModePropertiesResponse? periodicModeProperties, string type) { PeriodicModeProperties = periodicModeProperties; Type = type; } } }
29.222222
87
0.669202
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/DocumentDB/V20200901/Outputs/PeriodicModeBackupPolicyResponse.cs
1,052
C#
namespace JGL.Infra.Globals.DbSettings.Definitions { public static class DatabaseProperties { public static class MySQL { public const int MAXLENGTH_DESCRIPTION = 250; public const int MAXLENGTH_GUID = 50; public const int MAXLENGTH_SHORTNAME = 50; public const int MAXLENGTH = 5000; public const int MAXLENGTH_NAME = 100; public const int MAXLENGTH_ENUM = 50; public const int MAXLENGTH_FRACTIONARY = 5; public const string TYPE_DATETIME = "DATETIME"; //public const string TYPE_DATETIME = "datetime2"; } } }
31.285714
62
0.61796
[ "MIT" ]
jagel/meal-planner-api
MealPlanner.Infrastructure/DbSettings/Definitions/DatabaseProperties.cs
659
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("Jabberwocky.Extras.NewRelic.Sc")] [assembly: AssemblyDescription("Jabberwocky Extras New Relic for Sitecore")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Velir")] [assembly: AssemblyProduct("Jabberwock.Extras.NewRelic.Sc")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("51835579-3654-49d4-8b0b-ceb8af41643d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyInformationalVersion("3.0.0.0")]
40.263158
84
0.752288
[ "MIT" ]
MinyieDiaz/Jabberwocky
src/Extras/Jabberwock.Extras.NewRelic.Sc/Properties/AssemblyInfo.cs
1,533
C#
///<remarks>This file is part of the <see cref="https://github.com/enviriot">Enviriot</see> project.<remarks> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace X13.MQTT { /// <summary>The different types of messages defined in the MQTT protocol</summary> internal enum MessageType : byte { NONE = 0, CONNECT = 1, CONNACK = 2, PUBLISH = 3, PUBACK = 4, PUBREC = 5, PUBREL = 6, PUBCOMP = 7, SUBSCRIBE = 8, SUBACK = 9, UNSUBSCRIBE = 10, UNSUBACK = 11, PINGREQ = 12, PINGRESP = 13, DISCONNECT = 14, } internal abstract class MqMessage { protected static UTF8Encoding enc = new UTF8Encoding(); static MqMessage() { } public static MqMessage Parse(byte header, uint len, MemoryStream stream) { MqMessage msg=null; switch((MessageType)((header & 0xf0) >> 4)) { case MessageType.CONNECT: msg=new MqConnect(header, len, stream); break; case MessageType.CONNACK: msg=new MqConnack(header, len, stream); break; case MessageType.DISCONNECT: msg=new MqDisconnect(header, len, stream); break; case MessageType.PINGREQ: msg=new MqPingReq(header, len, stream); break; case MessageType.PINGRESP: msg=new MqPingResp(header, len, stream); break; case MessageType.PUBLISH: msg=new MqPublish(header, len, stream); break; case MessageType.SUBSCRIBE: msg=new MqSubscribe(header, len, stream); break; case MessageType.SUBACK: msg=new MqSuback(header, len, stream); break; case MessageType.UNSUBSCRIBE: msg=new MqUnsubscribe(header, len, stream); break; case MessageType.UNSUBACK: msg=new MqUnsuback(header, len, stream); break; case MessageType.PUBACK: case MessageType.PUBCOMP: case MessageType.PUBREC: case MessageType.PUBREL: msg=new MqMsgAck(header, len, stream); break; } return msg; } protected uint variableHeaderLength = 0; public readonly MessageType MsgType; public bool Duplicate; public QoS QualityOfService; public bool Retained; public ushort MessageID; public MessageType Reason { get; protected set; } protected MqMessage(MessageType msgType) { this.MsgType = msgType; this.Duplicate=false; this.QualityOfService=QoS.AtMostOnce; this.Retained=false; this.MessageID=0; } /// <summary>Creates an MqttMessage from a data stream</summary> /// <param name="header">The first byte of the fixed header of the message</param> /// <param name="len">Variable header length</param> /// <param name="str">Input stream</param> protected MqMessage(byte header, uint len, Stream str) { //-V3117 this.MsgType = (MessageType)((header & 0xf0) >> 4); this.Duplicate = (header & 0x08) != 0; this.QualityOfService = (QoS)((header & 0x06)>>1); this.Retained = (header & 0x01) != 0; variableHeaderLength = len; } /// <summary>Encodes the length of the variable header to the format specified in the MQTT protocol and writes it to the given stream</summary> /// <param name="str">Output Stream</param> public virtual void Serialise(Stream str) { // Write the fixed header to the stream byte header = (byte)(((byte)this.MsgType << 4) | (this.Duplicate?8:0) | ((byte)this.QualityOfService << 1) | (this.Retained?1:0)); str.WriteByte(header); // Add the second byte of the fixed header (The variable header length) WriteToStreamPacked(str, variableHeaderLength); } public override string ToString() { return MsgType.ToString(); } protected static void WriteToStream(Stream str, ushort val) { str.WriteByte((byte)(val >> 8)); str.WriteByte((byte)(val & 0xFF)); } private static void WriteToStreamPacked(Stream str, uint length) { byte digit = 0; do { digit = (byte)(length % 128); length /= 128; if(length > 0) { digit |= 0x80; } str.WriteByte(digit); } while(length > 0); } protected static void WriteToStream(Stream str, string val) { UTF8Encoding enc = new UTF8Encoding(); byte[] bs = enc.GetBytes(val); WriteToStream(str, (ushort)bs.Length); str.Write(bs, 0, bs.Length); } protected static ushort ReadUshortFromStream(Stream str) { // Read two bytes and interpret as ushort in Network Order byte[] data = new byte[2]; ReadCompleteBuffer(str, data); return (ushort)((data[0] << 8) + data[1]); } protected static string ReadStringFromStream(Stream str) { ushort len = ReadUshortFromStream(str); byte[] data = new byte[len]; ReadCompleteBuffer(str, data); return enc.GetString(data, 0, data.Length); } protected static byte[] ReadCompleteBuffer(Stream str, byte[] buffer) { int read = 0; while(read < buffer.Length) { int res = str.Read(buffer, read, buffer.Length - read); if(res <1) { throw new Exception("End of stream reached whilst filling buffer"); } read += res; } return buffer; } } internal class MqConnect : MqMessage { /// <summary>The version of the MQTT protocol we are using</summary> private const byte VERSION = 3; /// <summary>Constant description of the protocol</summary> private static readonly byte[] protocolDesc3 = new byte[] { 0, 6, (byte)'M', (byte)'Q', (byte)'I', (byte)'s', (byte)'d', (byte)'p', 3}; private static readonly byte[] protocolDesc4 = new byte[] { 0, 4, (byte)'M', (byte)'Q', (byte)'T', (byte)'T', 4 }; public ushort keepAlive { get; set; } public string clientId { get; internal set; } public string willTopic { get; set; } public byte[] willPayload { get; set; } public bool willRetained { get; set; } public QoS willQos { get; set; } public bool cleanSession { get; set; } public string userName { get; set; } public string userPassword { get; set; } public byte version { get; set; } public MqConnect() : base(MessageType.CONNECT) { } public MqConnect(byte header, uint len, Stream str) : base(header, len, str) { byte b; version = 0; int i = 0; while(true) { b = (byte)str.ReadByte(); if((version==0 || version==3) && b==protocolDesc3[i]){ if(i > 0) { version = 3; } i++; if(i>=protocolDesc3.Length){ break; } } else if((version==0 || version==4) && b==protocolDesc4[i]){ version=4; i++; if(i>=protocolDesc4.Length){ break; } } else { throw new ArgumentException("Connect.ProtocolDescription Error ["+i.ToString()+"]=0x"+b.ToString("X2")); } } byte connectFlags=(byte)str.ReadByte(); this.cleanSession=(connectFlags & 0x02)!=0; this.willRetained=(connectFlags & 0x20)!=0; this.willQos=(QoS)((connectFlags>>3) & 0x03); this.keepAlive=ReadUshortFromStream(str); this.clientId=ReadStringFromStream(str); if((connectFlags & 0x04)!=0) { willTopic=ReadStringFromStream(str); int wLen=ReadUshortFromStream(str); willPayload=new byte[wLen]; ReadCompleteBuffer(str, willPayload); } if((connectFlags & 0x80)!=0) { userName=ReadStringFromStream(str); } if((connectFlags & 0x40)!=0) { userPassword=ReadStringFromStream(str); } if(userPassword==null) { userPassword=string.Empty; } } public override void Serialise(Stream str) { byte _connectFlags=(byte)((cleanSession ? 0x02 : 0)); // Clean Start base.variableHeaderLength = (uint)( version==4? protocolDesc4.Length:protocolDesc3.Length //Length of the protocol description +3 //Connect Flags + Keep alive +enc.GetByteCount(clientId) // Length of the client ID string +2 // The length of the length of the clientID ); if(!string.IsNullOrEmpty(willTopic)) { _connectFlags=(byte)(4 | (willRetained ? 0x20 : 0) | (((byte)willQos) << 3)); base.variableHeaderLength += (uint)(enc.GetByteCount(willTopic) + (willPayload==null?0:willPayload.Length)+ 4); } if(!string.IsNullOrEmpty(userName)) { _connectFlags|=0x80; base.variableHeaderLength += (uint)(enc.GetByteCount(userName)+2); } if(!string.IsNullOrEmpty(userPassword)) { _connectFlags|=0x40; base.variableHeaderLength += (uint)(enc.GetByteCount(userPassword)+2); } base.Serialise(str); str.Write(version == 4 ? protocolDesc4 : protocolDesc3, 0, (version == 4 ? protocolDesc4 : protocolDesc3).Length); str.WriteByte(_connectFlags); // Write the keep alive value WriteToStream(str, this.keepAlive); // Write the payload WriteToStream(str, clientId); if(!string.IsNullOrEmpty(willTopic)) { // Write the will topic WriteToStream(str, willTopic); if(willPayload!=null) { WriteToStream(str, (ushort)willPayload.Length); str.Write(willPayload, 0, willPayload.Length); } else { WriteToStream(str, (ushort)0); } } if(!string.IsNullOrEmpty(userName)) { WriteToStream(str, userName); } if(!string.IsNullOrEmpty(userPassword)) { WriteToStream(str, userPassword); } } public override string ToString() { return string.Format("{0} - {1}", MessageType.CONNECT, clientId); } } internal class MqConnack : MqMessage { /// <summary>Connect return code</summary> public enum MqttConnectionResponse : byte { Accepted = 0, UnacceptableProtocolVersion = 1, IdentifierRejected = 2, ServerUnavailable = 3, BadUsernameOrPassword = 4, NotAuthorized = 5 } public MqttConnectionResponse Response { get; private set; } public MqConnack(MqttConnectionResponse response) : base(MessageType.CONNACK) { Response = response; } public MqConnack(byte header, uint len, Stream str) : base(header, len, str) { byte[] buffer = new byte[2]; ReadCompleteBuffer(str, buffer); Response = (MqttConnectionResponse)buffer[1]; } public override void Serialise(Stream str) { base.variableHeaderLength=2; base.Serialise(str); str.WriteByte(0); str.WriteByte((byte)Response); } public override string ToString() { return string.Format("{0}={1}", MessageType.CONNACK, this.Response); } } internal class MqSubscribe : MqMessage { private List<KeyValuePair<string, QoS>> _list=new List<KeyValuePair<string,QoS>>(); /// <summary>Subscribe to multiple topics</summary> public MqSubscribe() : base(MessageType.SUBSCRIBE) { base.QualityOfService = QoS.AtLeastOnce; } public MqSubscribe(byte header, uint len, Stream str) : base(header, len, str) { uint payloadLen = base.variableHeaderLength; base.MessageID=ReadUshortFromStream(str); payloadLen-=2; string topic; QoS sQoS; while(payloadLen>0) { topic=ReadStringFromStream(str); sQoS=(QoS)str.ReadByte(); _list.Add(new KeyValuePair<string,QoS>(topic, sQoS)); payloadLen-=(uint)(3+enc.GetByteCount(topic)); } } public void Add(string topic, QoS sQoS) { _list.Add(new KeyValuePair<string,QoS>(topic, sQoS)); } public List<KeyValuePair<string, QoS>> list { get { return _list; } } public override void Serialise(Stream str) { // calculate Length base.variableHeaderLength=2; foreach(var s in _list) { base.variableHeaderLength+=(uint)(3+enc.GetByteCount(s.Key)); } // Send base.Serialise(str); WriteToStream(str, base.MessageID); // Write the subscription payload foreach(var s in _list) { WriteToStream(str, s.Key); str.WriteByte((byte)s.Value); } } public override string ToString() { StringBuilder sb=new StringBuilder(); sb.AppendFormat("{0} [", MessageType.SUBSCRIBE); foreach(var s in _list) { sb.AppendFormat("({0} - {1}), ", s.Key, s.Value); } sb.Append("]"); return sb.ToString(); } } internal class MqSuback : MqMessage { private List<QoS> grantedQos=new List<QoS>(); public MqSuback() : base(MessageType.SUBACK) { } public MqSuback(byte header, uint len, Stream str) : base(header, len, str) { uint payloadLen = base.variableHeaderLength; base.Reason=MessageType.SUBSCRIBE; base.MessageID=ReadUshortFromStream(str); payloadLen-=2; while(payloadLen>0) { grantedQos.Add((QoS)(str.ReadByte())); payloadLen--; } } public void Add(QoS gQoS) { grantedQos.Add(gQoS); } public override void Serialise(Stream str) { // calculate Length base.variableHeaderLength=(uint)(2+grantedQos.Count); // Send base.Serialise(str); WriteToStream(str, base.MessageID); // Write the subscription payload for(int i=0; i<grantedQos.Count; i++) { str.WriteByte((byte)grantedQos[i]); } } public override string ToString() { StringBuilder sb=new StringBuilder(); sb.AppendFormat("{0} [", MessageType.SUBACK); foreach(QoS q in grantedQos) { sb.AppendFormat("{0}, ", q); } sb.Append("]"); return sb.ToString(); } } internal class MqPublish : MqMessage { private string _path; private string _payload; //public MqPublish(Topic topic) // : base(MessageType.PUBLISH) { // DataSource=topic; // this.Retained=DataSource.saved; //} public MqPublish(string path, string payload):base(MessageType.PUBLISH) { _path = path; _payload = payload; } public MqPublish(byte header, uint len, Stream str) : base(header, len, str) { uint payloadLen = base.variableHeaderLength; Path = ReadStringFromStream(str); payloadLen -= (uint)(enc.GetByteCount(Path) + 2); if(base.QualityOfService != QoS.AtMostOnce) { base.MessageID = ReadUshortFromStream(str); payloadLen -= 2; } byte[] tmp= new byte[payloadLen]; ReadCompleteBuffer(str, tmp); Payload=Encoding.UTF8.GetString(tmp); } //public Topic DataSource { get; private set; } public string Path { get { return (_path); } set { _path=value; } } public string Payload { get { return _payload; } set { _payload=value; } } public override void Serialise(Stream str) { byte[] pathBuf = enc.GetBytes(Path); string pys=this.Payload; if(pys==null) { pys=string.Empty; } byte[] payloadBuf=Encoding.UTF8.GetBytes(pys); base.variableHeaderLength =(uint)( 2 + pathBuf.Length // Topic + length +(base.QualityOfService == QoS.AtMostOnce ? 0 : 2) // Message ID for QoS > 0 +((payloadBuf==null)?0:payloadBuf.Length)); // Message Payload base.Serialise(str); WriteToStream(str, (ushort)pathBuf.Length); str.Write(pathBuf, 0, pathBuf.Length); if(base.QualityOfService != QoS.AtMostOnce) { WriteToStream(str, base.MessageID); } if(payloadBuf!=null && payloadBuf.Length>0) { str.Write(payloadBuf, 0, payloadBuf.Length); } //if(!Path.StartsWith("/etc")) { // Log.Debug(">{0}{1}={2}", this.Retained?"*":".", Path, pys??"null"); //} } public override string ToString() { return string.Format("{0} {1} {2}[{3}] {4},{5:X4}", MessageType.PUBLISH, this.Retained?"+":"-", Path, Payload, this.QualityOfService, this.MessageID); } } internal class MqMsgAck : MqMessage { public MqMsgAck(MessageType type, ushort msgId) : base(type) { base.MessageID=msgId; base.variableHeaderLength=2; } public MqMsgAck(byte header, uint len, Stream str) : base(header, len, str) { base.MessageID=ReadUshortFromStream(str); switch(base.MsgType) { case MessageType.PUBACK: base.Reason=MessageType.PUBLISH; break; case MessageType.PUBREC: base.Reason=MessageType.PUBLISH; break; case MessageType.PUBREL: base.Reason=MessageType.PUBREC; break; case MessageType.PUBCOMP: base.Reason=MessageType.PUBREL; break; default: throw new ArgumentOutOfRangeException(); } } public override void Serialise(Stream str) { base.Serialise(str); WriteToStream(str, base.MessageID); } public override string ToString() { return string.Format("{0} {1:X4}", base.MsgType, base.MessageID); } } internal class MqUnsubscribe : MqMessage { private List<string> _subscriptions=new List<string>(); public MqUnsubscribe() : base(MessageType.UNSUBSCRIBE) { base.QualityOfService = QoS.AtLeastOnce; } public MqUnsubscribe(byte header, uint len, Stream str) : base(header, len, str) { uint payloadLen = base.variableHeaderLength; base.MessageID=ReadUshortFromStream(str); payloadLen-=2; string topic; while(payloadLen>0) { topic=ReadStringFromStream(str); _subscriptions.Add(topic); payloadLen-=(uint)(2+enc.GetByteCount(topic)); } } public void Add(string path) { _subscriptions.Add(path); } public List<string> list { get { return _subscriptions; } } public override void Serialise(Stream str) { // calculate Length base.variableHeaderLength=2; foreach(string s in _subscriptions) { base.variableHeaderLength+=(uint)(2+enc.GetByteCount(s)); } // Send base.Serialise(str); WriteToStream(str, base.MessageID); // Write the subscription payload foreach(string s in _subscriptions) { WriteToStream(str, s); } } public override string ToString() { StringBuilder sb=new StringBuilder(); sb.AppendFormat("{0} [", MessageType.UNSUBSCRIBE); foreach(var s in _subscriptions) { sb.AppendFormat("{0}, ", s); } sb.Append("]"); return sb.ToString(); } } internal class MqUnsuback : MqMessage { public MqUnsuback() : base(MessageType.UNSUBACK) { } public MqUnsuback(byte header, uint len, Stream str) : base(header, len, str) { base.MessageID=ReadUshortFromStream(str); base.Reason=MessageType.UNSUBSCRIBE; } public override void Serialise(Stream str) { // calculate Length base.variableHeaderLength=2; // Send base.Serialise(str); WriteToStream(str, base.MessageID); } } internal class MqPingReq : MqMessage { public MqPingReq() : base(MessageType.PINGREQ) { } public MqPingReq(byte header, uint len, Stream str) : base(header, len, str) { } public override void Serialise(Stream str) { base.variableHeaderLength=0; base.Serialise(str); } } internal class MqPingResp : MqMessage { public MqPingResp() : base(MessageType.PINGRESP) { } public MqPingResp(byte header, uint len, Stream str) : base(header, len, str) { } public override void Serialise(Stream str) { base.variableHeaderLength=0; base.Serialise(str); } } internal class MqDisconnect : MqMessage { public MqDisconnect() : base(MessageType.DISCONNECT) { } public MqDisconnect(byte header, uint len, Stream str) : base(header, len, str) { } public override void Serialise(Stream str) { base.variableHeaderLength=0; base.Serialise(str); } } }
32.660225
156
0.611478
[ "MIT" ]
enviriot/EnviriotSW
plugins/MQTT/MqMessages.cs
20,284
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using UnityEngine; using UnityEditor; namespace Microsoft.MixedReality.Toolkit.Editor { /// <summary> /// Custom property drawer to show an optionally collapsible foldout help section in the Inspector /// </summary> /// <example> /// <code> /// [Help("This is a multiline optionally collapsable help section.\n • Great for providing simple instructions in Inspector.\n • Easy to use.\n • Saves space.")] /// </code> /// </example> [CustomPropertyDrawer(typeof(HelpAttribute))] public class HelpDrawer : DecoratorDrawer { /// <summary> /// Unity calls this function to draw the GUI /// </summary> /// <param name="position">Rectangle to display the GUI in</param> public override void OnGUI(Rect position) { HelpAttribute help = attribute as HelpAttribute; if (help.Collapsible) { HelpFoldOut = EditorGUI.Foldout(position, HelpFoldOut, help.Header); if (HelpFoldOut) { EditorGUI.HelpBox(position, help.Text, MessageType.Info); } } else { EditorGUI.HelpBox(position, help.Text, MessageType.Info); } cachedPosition = position; } /// <summary> /// Gets the height of the decorator /// </summary> public override float GetHeight() { HelpAttribute help = attribute as HelpAttribute; // Computing the actual height requires the cachedPosition because // CalcSize doesn't factor in word-wrapped height, and CalcHeight // requires a pre-determined width. GUIStyle helpStyle = EditorStyles.helpBox; GUIContent helpContent = new GUIContent(help.Text); float wrappedHeight = helpStyle.CalcHeight(helpContent, cachedPosition.width); // The height of the help box should be the content if expanded, or // just the header text if not expanded. float contentHeight = !help.Collapsible || HelpFoldOut ? wrappedHeight : helpStyle.lineHeight; return helpStyle.margin.top + helpStyle.margin.bottom + contentHeight; } #region Private /// <summary> /// The "help" foldout state /// </summary> private bool HelpFoldOut = false; private Rect cachedPosition = new Rect(); #endregion } }
34.853333
166
0.589135
[ "MIT" ]
AdrianaMusic/MixedRealityToolkit-Unity
Assets/MRTK/Core/Inspectors/PropertyDrawers/HelpDrawer.cs
2,622
C#
using RecipeSocial.Domain.Entities.Template; using System.Collections.Generic; namespace RecipeSocial.Domain.Entities { public class Tag : Base { public int Name { get; set; } public ICollection<RecipeTag> RecipeTags { get; set; } } }
20.461538
62
0.684211
[ "MIT" ]
jvalverdep/recipe-social-test
RecipeSocial.Domain/Entities/Tag.cs
268
C#
#if !NETSTANDARD13 /* * 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 Amazon.Runtime; namespace Amazon.SageMaker.Model { /// <summary> /// Paginator for the ListLabelingJobs operation ///</summary> public interface IListLabelingJobsPaginator { /// <summary> /// Enumerable containing all full responses for the operation /// </summary> IPaginatedEnumerable<ListLabelingJobsResponse> Responses { get; } /// <summary> /// Enumerable containing all of the LabelingJobSummaryList /// </summary> IPaginatedEnumerable<LabelingJobSummary> LabelingJobSummaryList { get; } } } #endif
33.8
108
0.676775
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/SageMaker/Generated/Model/_bcl45+netstandard/IListLabelingJobsPaginator.cs
1,352
C#
#if !(UNITY_IPHONE || UNITY_ANDROID || UNITY_METRO) using UnityEngine; using UniRx.Triggers; // for enable gameObject.EventAsObservbale() namespace UniRx.Examples { public class Sample03_GameObjectAsObservable : MonoBehaviour { void Start() { // All events can subscribe by ***AsObservable if enables UniRx.Triggers this.OnMouseDownAsObservable() .SelectMany(_ => this.gameObject.UpdateAsObservable()) .TakeUntil(this.gameObject.OnMouseUpAsObservable()) .Select(_ => Input.mousePosition) .RepeatUntilDestroy(this) .Subscribe(x => Debug.Log(x), ()=> Debug.Log("!!!" + "complete")); } } } #endif
33
85
0.59552
[ "MIT" ]
Bian-Sh/QFramework
Assets/QFramework/Framework/0.Libs/6.UniRx/Examples/Sample03_GameObjectAsObservable.cs
761
C#
using System; namespace aiala.Backend.ApiModels.Activities { public class ActivityMetadataModel { public DateTimeOffset Timestamp { get; set; } public decimal? Latitude { get; set; } public decimal? Longitude { get; set; } public Guid? ActiveTaskId { get; set; } public Guid? ActiveStepId { get; set; } } }
20.277778
53
0.627397
[ "MIT" ]
AIALA/aiala.backend
aiala.Backend/ApiModels/Activities/ActivityMetadataModel.cs
367
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FFMpegSharp.FFMPEG.Arguments { /// <summary> /// Represents start number parameter /// </summary> public class StartNumberArgument : Argument<int> { public StartNumberArgument() { } public StartNumberArgument(int value) : base(value) { } /// <summary> /// String representation of the argument /// </summary> /// <returns>String representation of the argument</returns> public override string GetStringValue() { return ArgumentsStringifier.StartNumber(Value); } } }
23
68
0.61413
[ "MIT" ]
qingqibing/FFMpegSharp
FFMpegSharp/FFMPEG/Arguments/StartNumberArgument.cs
738
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Newtonsoft.Json.Serialization; using Stripe; namespace server { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var price = Environment.GetEnvironmentVariable("PRICE"); if(price == "price_12345" || price == "" || price == null) { Console.WriteLine("You must set a Price ID in .env. Please see the README."); Environment.Exit(0); } StripeConfiguration.AppInfo = new AppInfo { Name = "stripe-samples/checkout-one-time-payments", Url = "https://github.com/stripe-samples/checkout-one-time-payments", Version = "0.0.1", }; services.Configure<StripeOptions>(options => { options.PublishableKey = Environment.GetEnvironmentVariable("STRIPE_PUBLISHABLE_KEY"); options.SecretKey = Environment.GetEnvironmentVariable("STRIPE_SECRET_KEY"); options.WebhookSecret = Environment.GetEnvironmentVariable("STRIPE_WEBHOOK_SECRET"); options.Price = Environment.GetEnvironmentVariable("PRICE"); options.Domain = Environment.GetEnvironmentVariable("DOMAIN"); }); services.AddControllersWithViews().AddNewtonsoftJson(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy(), }; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } //app.UseHttpsRedirection(); app.UseFileServer(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
37.211765
143
0.597534
[ "MIT" ]
codetiki/StripeTest
server/Startup.cs
3,163
C#
using Domain.Models; using Domain.ServiceExtensions; using Persistence.Repositories; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Domain.Services { public class ThreadsService : IThreadsService { private readonly ThreadsRepository _threadsRepository; private readonly Random _random; public ThreadsService(ThreadsRepository threadsRepository) { _threadsRepository = threadsRepository; } //ThreadsService service = new ThreadsService(new ThreadsRepository); public static async Task InitializeThreadCreation(int id, string data) { await _threadsService.CreateThread(id, data); } public async Task CreateThread(int threadId, string data) { var threadModel = new ThreadRequestModel { ThreadId = threadId, Data = data, TimeCreated = DateTime.Now }; await SaveThread(threadModel); } public async Task<IEnumerable<ThreadResponseModel>> GetNewestThreads() { var threads = await GetAll(); if (threads.Count() == 0) { throw new Exception("There id no data to show at this time."); } var newestThreads = threads.OrderByDescending(thread => thread.TimeCreated).Take(20); return newestThreads; } public async Task<IEnumerable<ThreadResponseModel>> GetAll() { var threads = await _threadsRepository.GetAll(); if (threads.Count() == 0) { throw new Exception("There id no data to show at this time."); } List<ThreadResponseModel> list = new List<ThreadResponseModel>(); IEnumerable<ThreadResponseModel> threadsConverted = list; for (var i = 0; i < threads.Count(); i++ ) { var model = threads.ElementAt(i).MapToResponseModel(); threadsConverted.Append(model); } return threadsConverted; } public async Task<ThreadResponseModel> SaveThread(ThreadRequestModel model) { var convertedModel = model.MapToWriteModel(); if (model == null) { throw new Exception("Bad Request"); } await _threadsRepository.WriteThread(convertedModel); return model.MapToResponseModel(); } } }
27.050505
97
0.585885
[ "Apache-2.0" ]
dorotaro/ThreadsApp_V1
Domain/Services/ThreadsService.cs
2,680
C#
using Assets.Scripts.InMaze.Networking.Jsonify; using UnityEngine; using UnityEngine.UI; namespace Assets.Scripts.InMaze.UI { public class PlayerNumber : StackableUi { // Use this for initialization void Start() { // Set next node LowerNode = GameObject.Find("TimeToBeat/TimePanel") .GetComponent<Counting>(); UpperNode = GameObject.Find("FlagUI/Distance") .GetComponent<DistanceFromFlag>(); // Self destruction if not in multiplayer mode if (GameObject.Find("MultiplayerScripts") == null) { Destroy(transform.parent.gameObject); } } // Update is called once per frame void Update() { if (PlayerNodes.present != null) // Update number of player(s) (including self) GetComponent<Text>().text = PlayerNodes.present.Count.ToString(); } } }
29.205882
81
0.565962
[ "Apache-2.0" ]
myze/Unity-App
Assets/Scripts/InMaze/UI/PlayerNumber.cs
995
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using AdvUtils; using CRFSharp; namespace GenerateFeatureDictMatch { public class GenerateFeatureDictMatch : IGenerateFeature { DictMatch dictmatch = null; List<Lemma> dm_r; List<int> dm_offsetList; // DictMatchFileName: lexical dictionary file name // BinaryDict: true - above dictionary file is binary format, otherwise, it is raw text const string KEY_LEXICAL_DICT_FILE_NAME = "DictMatchFileName"; const string KEY_BINARY_DICT_TYPE = "BinaryDict"; private Dictionary<string, string> LoadConfigFile(string strFileName) { var dict = new Dictionary<string,string>(); var sr = new StreamReader(strFileName); while (sr.EndOfStream == false) { var strLine = sr.ReadLine(); var items = strLine.Split('='); items[0] = items[0].ToLower().Trim(); items[1] = items[1].ToLower().Trim(); if (items[0] != KEY_LEXICAL_DICT_FILE_NAME.ToLower() && items[0] != KEY_BINARY_DICT_TYPE.ToLower()) { throw new Exception("Invalidate configuration file item"); } dict.Add(items[0], items[1]); } sr.Close(); return dict; } /// <summary> /// Initialize DictMatch Feature Generator /// </summary> /// <returns></returns> public bool Initialize() { dictmatch = new DictMatch(); dm_r = new List<Lemma>(); dm_offsetList = new List<int>(); Dictionary<string, string> configDict; configDict = LoadConfigFile("GenerateFeatureDictMatch.ini"); if (configDict.ContainsKey(KEY_LEXICAL_DICT_FILE_NAME.ToLower()) == false || configDict.ContainsKey(KEY_BINARY_DICT_TYPE.ToLower()) == false) { return false; } var strDictMatchFileName = configDict[KEY_LEXICAL_DICT_FILE_NAME.ToLower()]; var bBinaryDict = bool.Parse(configDict[KEY_BINARY_DICT_TYPE.ToLower()]); if (strDictMatchFileName.Length == 0) { return true; } if (bBinaryDict == true) { dictmatch.LoadDictFromBinary(strDictMatchFileName); } else { dictmatch.LoadDictFromRawText(strDictMatchFileName); } return true; } public List<List<string>> GenerateFeature(string strText) { var rstListList = new List<List<string>>(); if (dictmatch == null) { return rstListList; } dm_r.Clear(); dm_offsetList.Clear(); dictmatch.Search(strText, ref dm_r, ref dm_offsetList, DictMatch.DM_OUT_FMM); string [] astrDictMatch; astrDictMatch = new string[strText.Length]; for (var i = 0; i < dm_r.Count; i++) { var offset = dm_offsetList[i]; var len = (int)dm_r[i].len; for (var j = offset; j < offset + len; j++) { astrDictMatch[j] = dm_r[i].strProp; } } for (var i = 0;i < strText.Length;i++) { rstListList.Add(new List<string>()); rstListList[i].Add(strText[i].ToString()); if (astrDictMatch[i] != null) { rstListList[i].Add(astrDictMatch[i]); } else { rstListList[i].Add("NOR"); } } return rstListList; } } }
30.328244
95
0.507929
[ "BSD-3-Clause" ]
Oceania2018/CRFSharp
GenerateFeatureDictMatch/GenerateFeatureDictMatch.cs
3,975
C#
// This file has been autogenerated from a class added in the UI designer. using System; using Foundation; using WatchKit; namespace hearRINGWatchOS.WatchOSApp { public partial class InterfaceController : WKInterfaceController { public InterfaceController (IntPtr handle) : base (handle) { } } }
18.117647
74
0.766234
[ "MIT" ]
HayleyO/Senior-Design
src/watch/hearRING/hearRINGWatchOS/hearRINGWatchOS.WatchOSApp/InterfaceController.cs
308
C#
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Engines; using BenchmarkDotNet.Order; using System; using System.Security.Cryptography; namespace DotNext; [SimpleJob(runStrategy: RunStrategy.Throughput, launchCount: 1)] [Orderer(SummaryOrderPolicy.FastestToSlowest)] public class RandomStringBenchmark { private const string AllowedChars = "1234567890abcdef"; private readonly Random rnd = new(); private readonly RandomNumberGenerator rng = RandomNumberGenerator.Create(); [Benchmark] public string GuidString() => Guid.NewGuid().ToString(); [Benchmark] public string RandomString() => rnd.NextString(AllowedChars, 36); [Benchmark] public string CryptoRngString() => rng.NextString(AllowedChars, 36); }
30.12
80
0.767596
[ "MIT" ]
copenhagenatomics/dotNext
src/DotNext.Benchmarks/RandomStringBenchmark.cs
755
C#
namespace DotVVM.Framework.Compilation.Parser { public class ParserConstants { public const string ViewModelDirectiveName = "viewModel"; public const string MasterPageDirective = "masterPage"; public const string BaseTypeDirective = "baseType"; public const string ResourceTypeDirective = "resourceType"; public const string ResourceNamespaceDirective = "resourceNamespace"; public const string ImportNamespaceDirective = "import"; public const string WrapperTagNameDirective = "wrapperTag"; public const string NoWrapperTagNameDirective = "noWrapperTag"; public const string ServiceInjectDirective = "service"; public const string ViewModuleDirective = "js"; public const string ValueBinding = "value"; public const string CommandBinding = "command"; public const string ControlPropertyBinding = "controlProperty"; public const string ControlCommandBinding = "controlCommand"; public const string ResourceBinding = "resource"; public const string StaticCommandBinding = "staticCommand"; public const string RootSpecialBindingProperty = "_root"; public const string ParentSpecialBindingProperty = "_parent"; public const string ThisSpecialBindingProperty = "_this"; } }
46.517241
77
0.714603
[ "Apache-2.0" ]
AMBULATUR/dotvvm
src/DotVVM.Framework/Compilation/Parser/ParserConstants.cs
1,349
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Web.Http; using Microsoft.Owin.Security.OAuth; using Newtonsoft.Json.Serialization; namespace AutomatedComponentTestWriter { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Configure Web API to use only bearer token authentication. //config.SuppressDefaultHostAuthentication(); //config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); // Use camel case for JSON data. config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
32.470588
127
0.658514
[ "MIT" ]
cltalmadge/AutomatedComponentTestWriter
AutomatedComponentTestWriter/App_Start/WebApiConfig.cs
1,106
C#
namespace _06._Twitter { public class StartUp { public static void Main() { } } }
13.111111
33
0.491525
[ "MIT" ]
thelad43/CSharp-OOP-Advanced-SoftUni
10. Unit Testing - Exercise/06. Twitter/StartUp.cs
120
C#
using Microsoft.Tools.TeamMate.Foundation.Windows.Input; using Microsoft.Tools.TeamMate.Foundation.Windows.MVVM; using Microsoft.Tools.TeamMate.Model; using Microsoft.Tools.TeamMate.Services; using System.ComponentModel.Composition; using System.Windows.Input; namespace Microsoft.Tools.TeamMate.ViewModels { public class OverviewWindowViewModel : ViewModelBase { private ItemCountSummary itemCountSummary; public ItemCountSummary ItemCountSummary { get { return this.itemCountSummary; } set { SetProperty(ref this.itemCountSummary, value); } } public OverviewWindowViewModel() { this.HideCommand = new RelayCommand(this.HideFloatingWindow); } public ICommand HideCommand { get; private set; } public void HideFloatingWindow() { this.SettingsService.Settings.ShowItemCountInOverviewWindow = false; var volatileSettings = this.SettingsService.VolatileSettings; if (!volatileSettings.OverviewWindowWasHiddenBefore) { volatileSettings.OverviewWindowWasHiddenBefore = true; this.MessageBoxService.Show("You've hidden the work item overview window.\n\nYou can make it visible again from the application settings page.", TeamMateApplicationInfo.ApplicationName, System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information); } } public void ShowMainWindow() { this.WindowService.ShowHomePage(); } [Import] public WindowService WindowService { get; set; } [Import] public SettingsService SettingsService { get; set; } [Import] public MessageBoxService MessageBoxService { get; set; } } }
32.928571
160
0.671909
[ "MIT" ]
john-alessi/TeamMate
Source/TeamMate/ViewModels/OverviewWindowViewModel.cs
1,846
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Windows; namespace TCC.Updater { internal class Program { private static string SourcePath = Path.GetDirectoryName(typeof(Program).Assembly.Location)+ "/tmp"; private static string DestinationPath = Path.GetDirectoryName(typeof(Program).Assembly.Location); private static void Main(string[] args) { if (!HasUpdateArg(args)) return; WaitForTccExit(); CreateDirectories(); ReplaceFiles(); // delete temp folder Directory.Delete(SourcePath, true); // open release notes Process.Start("explorer.exe", "https://github.com/Foglio1024/Tera-custom-cooldowns/releases"); // launch TCC Process.Start(Path.GetDirectoryName(typeof(Program).Assembly.Location) + "/TCC.exe"); // exit Environment.Exit(0); } private static void ReplaceFiles() { foreach (var newPath in Directory.GetFiles(SourcePath, "*.*", SearchOption.AllDirectories).Where(p => !p.Contains(@"\config\"))) { File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath), true); Console.WriteLine($"Copied file {Path.GetFileName(newPath)}"); } } private static void CreateDirectories() { foreach (var dirPath in Directory.GetDirectories(SourcePath, "*", SearchOption.AllDirectories)) { Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath)); } } private static void WaitForTccExit() { var pl = Process.GetProcesses(); var tries = 10; while (pl.Any(x => x.ProcessName == "TCC")) { if (tries >= 0) { Console.Write($"\rWaiting for TCC to close... {tries} "); Thread.Sleep(1000); tries--; } else { Console.WriteLine("\nForce closing TCC..."); var tcc = Process.GetProcesses().FirstOrDefault(x => x.ProcessName == "TCC"); tcc?.Kill(); break; } } } private static bool HasUpdateArg(IEnumerable<string> args) { if (args.Any(x => x == "update")) return true; MessageBox.Show("This is not meant to be launched manually!", "TCC Updater", MessageBoxButton.OK, MessageBoxImage.Error); return false; } } }
34.725
140
0.542477
[ "MIT" ]
Foglio1024/Tera-custom-cooldowns
TCC.Updater/Program.cs
2,780
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32; using System; using System.Collections.Generic; using System.Globalization; using System.Resources; using System.Runtime.InteropServices; #if RUNTIME_TYPE_NETCORE using System.Runtime.InteropServices.ComTypes; #endif #nullable disable namespace Microsoft.Build.Tasks.Deployment.ManifestUtilities { internal class ComImporter { private readonly OutputMessageCollection _outputMessages; private readonly string _outputDisplayName; private readonly ResourceManager _resources = new ResourceManager("Microsoft.Build.Tasks.Core.Strings.ManifestUtilities", System.Reflection.Assembly.GetExecutingAssembly()); // These must be defined in sorted order! private static readonly string[] s_knownImplementedCategories = { "{02496840-3AC4-11cf-87B9-00AA006C8166}", //CATID_VBFormat "{02496841-3AC4-11cf-87B9-00AA006C8166}", //CATID_VBGetControl "{40FC6ED5-2438-11CF-A3DB-080036F12502}", }; private static readonly string[] s_knownSubKeys = { "Control", "Programmable", "ToolboxBitmap32", "TypeLib", "Version", "VersionIndependentProgID", }; public ComImporter(string path, OutputMessageCollection outputMessages, string outputDisplayName) { _outputMessages = outputMessages; _outputDisplayName = outputDisplayName; if (NativeMethods.SfcIsFileProtected(IntPtr.Zero, path) != 0) outputMessages.AddWarningMessage("GenerateManifest.ComImport", outputDisplayName, _resources.GetString("ComImporter.ProtectedFile")); object obj = null; try { NativeMethods.LoadTypeLibEx(path, NativeMethods.RegKind.RegKind_None, out obj); } catch (COMException) { } #pragma warning disable 618 #if RUNTIME_TYPE_NETCORE ITypeLib tlib = (ITypeLib)obj; #else UCOMITypeLib tlib = (UCOMITypeLib)obj; #endif if (tlib != null) { IntPtr typeLibAttrPtr = IntPtr.Zero; tlib.GetLibAttr(out typeLibAttrPtr); var typeLibAttr = (TYPELIBATTR)Marshal.PtrToStructure(typeLibAttrPtr, typeof(TYPELIBATTR)); tlib.ReleaseTLibAttr(typeLibAttrPtr); Guid tlbid = typeLibAttr.guid; tlib.GetDocumentation(-1, out _, out string docString, out _, out string helpFile); string helpdir = Util.FilterNonprintableChars(helpFile); //Path.GetDirectoryName(helpFile); TypeLib = new TypeLib(tlbid, new Version(typeLibAttr.wMajorVerNum, typeLibAttr.wMinorVerNum), helpdir, typeLibAttr.lcid, Convert.ToInt32(typeLibAttr.wLibFlags, CultureInfo.InvariantCulture)); var comClassList = new List<ComClass>(); int count = tlib.GetTypeInfoCount(); for (int i = 0; i < count; ++i) { tlib.GetTypeInfoType(i, out TYPEKIND tkind); if (tkind == TYPEKIND.TKIND_COCLASS) { #if RUNTIME_TYPE_NETCORE tlib.GetTypeInfo(i, out ITypeInfo tinfo); #else tlib.GetTypeInfo(i, out UCOMITypeInfo tinfo); #endif IntPtr tinfoAttrPtr = IntPtr.Zero; tinfo.GetTypeAttr(out tinfoAttrPtr); TYPEATTR tinfoAttr = (TYPEATTR)Marshal.PtrToStructure(tinfoAttrPtr, typeof(TYPEATTR)); tinfo.ReleaseTypeAttr(tinfoAttrPtr); Guid clsid = tinfoAttr.guid; tlib.GetDocumentation(i, out _, out docString, out _, out helpFile); string description = Util.FilterNonprintableChars(docString); ClassInfo info = GetRegisteredClassInfo(clsid); if (info == null) { continue; } comClassList.Add(new ComClass(tlbid, clsid, info.Progid, info.ThreadingModel, description)); } } if (comClassList.Count > 0) { ComClasses = comClassList.ToArray(); Success = true; } else { outputMessages.AddErrorMessage("GenerateManifest.ComImport", outputDisplayName, _resources.GetString("ComImporter.NoRegisteredClasses")); Success = false; } } else { outputMessages.AddErrorMessage("GenerateManifest.ComImport", outputDisplayName, _resources.GetString("ComImporter.TypeLibraryLoadFailure")); Success = false; } #pragma warning restore 618 } private void CheckForUnknownSubKeys(RegistryKey key) { CheckForUnknownSubKeys(key, Array.Empty<string>()); } private void CheckForUnknownSubKeys(RegistryKey key, string[] knownNames) { if (key.SubKeyCount > 0) { foreach (string name in key.GetSubKeyNames()) { if (Array.BinarySearch(knownNames, name, StringComparer.OrdinalIgnoreCase) < 0) { _outputMessages.AddWarningMessage("GenerateManifest.ComImport", _outputDisplayName, String.Format(CultureInfo.CurrentCulture, _resources.GetString("ComImporter.SubKeyNotImported"), key.Name + "\\" + name)); } } } } private void CheckForUnknownValues(RegistryKey key) { CheckForUnknownValues(key, Array.Empty<string>()); } private void CheckForUnknownValues(RegistryKey key, string[] knownNames) { if (key.ValueCount > 0) { foreach (string name in key.GetValueNames()) { if (!String.IsNullOrEmpty(name) && Array.BinarySearch( knownNames, name, StringComparer.OrdinalIgnoreCase) < 0) { _outputMessages.AddWarningMessage("GenerateManifest.ComImport", _outputDisplayName, String.Format(CultureInfo.CurrentCulture, _resources.GetString("ComImporter.ValueNotImported"), key.Name + "\\@" + name)); } } } } private ClassInfo GetRegisteredClassInfo(Guid clsid) { ClassInfo info = null; RegistryKey userKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\CLASSES\\CLSID"); if (GetRegisteredClassInfo(userKey, clsid, ref info)) { return info; } RegistryKey machineKey = Registry.ClassesRoot.OpenSubKey("CLSID"); if (GetRegisteredClassInfo(machineKey, clsid, ref info)) { return info; } return null; } private bool GetRegisteredClassInfo(RegistryKey rootKey, Guid clsid, ref ClassInfo info) { if (rootKey == null) { return false; } string sclsid = clsid.ToString("B"); RegistryKey classKey = rootKey.OpenSubKey(sclsid); if (classKey == null) { return false; } bool succeeded = true; string registeredPath = null; string threadingModel = null; string progid = null; string[] subKeyNames = classKey.GetSubKeyNames(); foreach (string subKeyName in subKeyNames) { RegistryKey subKey = classKey.OpenSubKey(subKeyName); if (String.Equals(subKeyName, "InProcServer32", StringComparison.OrdinalIgnoreCase)) { registeredPath = (string)subKey.GetValue(null); threadingModel = (string)subKey.GetValue("ThreadingModel"); CheckForUnknownSubKeys(subKey); CheckForUnknownValues(subKey, new string[] { "ThreadingModel" }); } else if (String.Equals(subKeyName, "ProgID", StringComparison.OrdinalIgnoreCase)) { progid = (string)subKey.GetValue(null); CheckForUnknownSubKeys(subKey); CheckForUnknownValues(subKey); } else if (String.Equals(subKeyName, "LocalServer32", StringComparison.OrdinalIgnoreCase)) { _outputMessages.AddWarningMessage("GenerateManifest.ComImport", _outputDisplayName, String.Format(CultureInfo.CurrentCulture, _resources.GetString("ComImporter.LocalServerNotSupported"), classKey.Name + "\\LocalServer32")); } else if (String.Equals(subKeyName, "Implemented Categories", StringComparison.OrdinalIgnoreCase)) { CheckForUnknownSubKeys(subKey, s_knownImplementedCategories); CheckForUnknownValues(subKey); } else { if (Array.BinarySearch(s_knownSubKeys, subKeyName, StringComparer.OrdinalIgnoreCase) < 0) { _outputMessages.AddWarningMessage("GenerateManifest.ComImport", _outputDisplayName, String.Format(CultureInfo.CurrentCulture, _resources.GetString("ComImporter.SubKeyNotImported"), classKey.Name + "\\" + subKeyName)); } } } if (String.IsNullOrEmpty(registeredPath)) { _outputMessages.AddErrorMessage("GenerateManifest.ComImport", _outputDisplayName, String.Format(CultureInfo.CurrentCulture, _resources.GetString("ComImporter.MissingValue"), classKey.Name + "\\InProcServer32", "(Default)")); succeeded = false; } info = new ClassInfo(progid, threadingModel); return succeeded; } public bool Success { get; } = true; public ComClass[] ComClasses { get; } public TypeLib TypeLib { get; } private class ClassInfo { internal readonly string Progid; internal readonly string ThreadingModel; internal ClassInfo(string progid, string threadingModel) { Progid = progid; ThreadingModel = threadingModel; } } } }
41.696154
243
0.575131
[ "MIT" ]
MarcoRossignoli/msbuild
src/Tasks/ManifestUtil/ComImporter.cs
10,843
C#
using System; using Newtonsoft.Json; using System.Xml.Serialization; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// AlipayOpenPublicPayeeBindDeleteModel Data Structure. /// </summary> [Serializable] public class AlipayOpenPublicPayeeBindDeleteModel : AlipayObject { /// <summary> /// 收款账号,需要解除绑定的收款支付宝账号,跟pid不要同时传 /// </summary> [JsonProperty("login_id")] [XmlElement("login_id")] public string LoginId { get; set; } /// <summary> /// 支付宝用户id,2088开头的16位长度字符串,跟login_id不要同时传 /// </summary> [JsonProperty("pid")] [XmlElement("pid")] public string Pid { get; set; } } }
25.678571
68
0.613352
[ "MIT" ]
Aosir/Payment
src/Essensoft.AspNetCore.Payment.Alipay/Domain/AlipayOpenPublicPayeeBindDeleteModel.cs
815
C#
// Description: Async extension methods for LINQ (Language Integrated Query). // Website & Documentation: https://github.com/zzzprojects/LINQ-Async // Forum: https://github.com/zzzprojects/LINQ-Async/issues // License: http://www.zzzprojects.com/license-agreement/ // More projects: http://www.zzzprojects.com/ // Copyright (c) 2015 ZZZ Projects. All rights reserved. using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Z.Linq { public static partial class EnumerableAsync { public static Task<bool> SequenceEqual<TSource>(this Task<IEnumerable<TSource>> first, IEnumerable<TSource> second, CancellationToken cancellationToken = default(CancellationToken)) { return Task.Factory.FromTaskEnumerable(first, second, Enumerable.SequenceEqual, cancellationToken); } public static Task<bool> SequenceEqual<TSource>(this Task<IEnumerable<TSource>> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer, CancellationToken cancellationToken = default(CancellationToken)) { return Task.Factory.FromTaskEnumerable(first, second, comparer, Enumerable.SequenceEqual, cancellationToken); } } }
46.296296
226
0.752
[ "MIT" ]
Littlepond/LINQ-Async
src/Z.Linq.Async.Shared/EnumerableAsync/LINQ/Immediate_Task/IEnumerable`/SequenceEqual.cs
1,252
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.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitAsOperator(BoundAsOperator node) { BoundExpression rewrittenOperand = VisitExpression(node.Operand); var rewrittenTargetType = (BoundTypeExpression)VisitTypeExpression(node.TargetType); TypeSymbol rewrittenType = VisitType(node.Type); return MakeAsOperator(node, node.Syntax, rewrittenOperand, rewrittenTargetType, node.Conversion, rewrittenType); } private BoundExpression MakeAsOperator( BoundAsOperator oldNode, SyntaxNode syntax, BoundExpression rewrittenOperand, BoundTypeExpression rewrittenTargetType, Conversion conversion, TypeSymbol rewrittenType) { // TODO: Handle dynamic operand type and target type Debug.Assert(rewrittenTargetType.Type.Equals(rewrittenType)); // target type cannot be a non-nullable value type Debug.Assert(!rewrittenType.IsValueType || rewrittenType.IsNullableType()); if (!_inExpressionLambda) { ConstantValue constantValue = Binder.GetAsOperatorConstantResult(rewrittenOperand.Type, rewrittenType, conversion.Kind, rewrittenOperand.ConstantValue); if (constantValue != null) { Debug.Assert(constantValue.IsNull); BoundExpression result = rewrittenType.IsNullableType() ? new BoundDefaultExpression(syntax, rewrittenType) : MakeLiteral(syntax, constantValue, rewrittenType); if (rewrittenOperand.ConstantValue != null) { // No need to preserve any side-effects from the operand. // We also can keep the "constant" notion of the result, which // enables some optimizations down the road. return result; } return new BoundSequence( syntax: syntax, locals: ImmutableArray<LocalSymbol>.Empty, sideEffects: ImmutableArray.Create<BoundExpression>(rewrittenOperand), value: result, type: rewrittenType); } if (conversion.IsImplicit) { // Operand with bound implicit conversion to target type. // We don't need a runtime check, generate a conversion for the operand instead. return MakeConversionNode(syntax, rewrittenOperand, conversion, rewrittenType, @checked: false); } } return oldNode.Update(rewrittenOperand, rewrittenTargetType, conversion, rewrittenType); } } }
44.657534
180
0.620859
[ "Apache-2.0" ]
20chan/roslyn
src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_AsOperator.cs
3,262
C#
namespace SoftGym.Services.Data.Contracts { using System.Collections.Generic; using System.Threading.Tasks; using SoftGym.Data.Models; public interface INotificationsService { public Task<Notification> CreateNotificationAsync(string content, string url, string userId = null); public Task<IEnumerable<T>> GetNotifications<T>(string userId); public Task<Notification> DeleteNotification(int notificationId); public Task<int> GetNotificationsCount(string userId); public Task<int> GetNewNotificationsCount(string userId); public Task ReadNotification(int notificationId); public Task<IEnumerable<T>> GetFilteredNotifications<T>(string userId, bool isRead); } }
29.92
108
0.731283
[ "MIT" ]
PlamenMichev/SoftGym
Services/SoftGym.Services.Data/Contracts/INotificationsService.cs
750
C#
using Assistant; using JsonData; using System.Collections.Generic; using System.Threading; namespace RazorEnhanced { public class Target { private int m_ptarget; private RazorEnhanced.Point3D m_pgtarget; public static bool HasTarget() { return Assistant.Targeting.HasTarget; } public static void WaitForTarget(int delay, bool noshow = false) { int subdelay = delay; Assistant.Targeting.NoShowTarget = noshow; while (Assistant.Targeting.HasTarget == false) { Thread.Sleep(2); subdelay -= 2; if (subdelay <= 0) break; } Assistant.Targeting.NoShowTarget = false; } public static void TargetExecute(int serial) { if (!CheckHealPoisonTarg(serial)) { Assistant.Targeting.Target(serial, true); } } public static void TargetExecute(RazorEnhanced.Item item) { Assistant.Targeting.Target(item.Serial, true); } public static void TargetExecute(RazorEnhanced.Mobile mobile) { if (!CheckHealPoisonTarg(mobile.Serial)) { Assistant.Targeting.Target(mobile.Serial, true); } } public static void TargetExecuteRelative(int serial, int offset) { Mobile m = Mobiles.FindBySerial(serial); if (m != null) TargetExecuteRelative(m, offset); } public static void TargetExecuteRelative(Mobile m, int offset) { Assistant.Point2D relpos = new Assistant.Point2D(); switch (m.Direction) { case "North": relpos.X = m.Position.X; relpos.Y = m.Position.Y - offset; break; case "South": relpos.X = m.Position.X; relpos.Y = m.Position.Y + offset; break; case "West": relpos.X = m.Position.X - offset; relpos.Y = m.Position.Y; break; case "East": relpos.X = m.Position.X + offset; relpos.Y = m.Position.Y; break; case "Up": relpos.X = m.Position.X - offset; relpos.Y = m.Position.Y - offset; break; case "Down": relpos.X = m.Position.X + offset; relpos.Y = m.Position.Y + offset; break; case "Left": relpos.X = m.Position.X - offset; relpos.Y = m.Position.Y + offset; break; case "Right": relpos.X = m.Position.X + offset; relpos.Y = m.Position.Y - offset; break; } Assistant.Point3D location = new Assistant.Point3D(relpos.X, relpos.Y, Statics.GetLandZ(relpos.X, relpos.Y, Player.Map)); Assistant.Targeting.Target(location, true); } public static void TargetExecute(int x, int y, int z) { Assistant.Point3D location = new Assistant.Point3D(x, y, z); Assistant.Targeting.Target(location, true); } public static void TargetExecute(int x, int y, int z, int gfx) { Assistant.Point3D location = new Assistant.Point3D(x, y, z); Assistant.Targeting.Target(location, gfx, true); } public static void Cancel() { //Assistant.Targeting.CancelClientTarget(true); Assistant.Targeting.CancelOneTimeTarget(true); } public static void Self() { if (World.Player != null) TargetExecute(World.Player.Serial); } public static void SelfQueued() { Assistant.Targeting.TargetSelf(true); } public static void Last() { if (!CheckHealPoisonTarg(GetLast())) Assistant.Targeting.LastTarget(); } public static void LastQueued() { Assistant.Targeting.LastTarget(true); } public static int GetLast() { return (int)Assistant.Targeting.GetLastTarger; } public static int GetLastAttack() { return (int)Assistant.Targeting.LastAttack; } public static void SetLast(RazorEnhanced.Mobile mob) { Assistant.Mobile mobile = World.FindMobile(mob.Serial); if (mobile != null) SetLast(mob.Serial); } public static void SetLast(int serial, bool wait = true) { TargetMessage(serial, wait); // Process message for highlight Assistant.Targeting.SetLastTarget(serial, 0, wait); } public static void ClearQueue() { Assistant.Targeting.ClearQueue(); } public static void ClearLast() { Assistant.Targeting.ClearLast(); } public static void ClearLastandQueue() { Assistant.Targeting.ClearQueue(); Assistant.Targeting.ClearLast(); } public int PromptTarget(string message = "Select Item or Mobile") { m_ptarget = -1; Misc.SendMessage(message, 945, true); Targeting.OneTimeTarget(false, new Targeting.TargetResponseCallback(PromptTargetExex_Callback)); while (!Targeting.HasTarget) Thread.Sleep(30); while (m_ptarget == -1 && Targeting.HasTarget) Thread.Sleep(30); Thread.Sleep(100); if (m_ptarget == -1) Misc.SendMessage("Prompt Target Cancelled", 945, true); return m_ptarget; } private void PromptTargetExex_Callback(bool loc, Assistant.Serial serial, Assistant.Point3D pt, ushort itemid) { m_ptarget = serial; } public Point3D PromptGroundTarget(string message = "Select Ground Position") { m_pgtarget = Point3D.MinusOne; Misc.SendMessage(message, 945, true); Targeting.OneTimeTarget(true, new Targeting.TargetResponseCallback(PromptGroundTargetExex_Callback)); while (!Targeting.HasTarget) Thread.Sleep(30); while (m_pgtarget.X == -1 && Targeting.HasTarget) Thread.Sleep(30); Thread.Sleep(100); if (m_pgtarget.X == -1) Misc.SendMessage("Prompt Gorund Target Cancelled", 945, true); return m_pgtarget; } private void PromptGroundTargetExex_Callback(bool loc, Assistant.Serial serial, Assistant.Point3D pt, ushort itemid) { if (!loc) { Mobile target = Mobiles.FindBySerial(serial); if (target == null) { m_pgtarget = Point3D.MinusOne; } else { m_pgtarget = target.Position; } } else m_pgtarget = new Point3D(pt.X, pt.Y, pt.Z); } // Check Poison private static bool CheckHealPoisonTarg(Assistant.Serial ser) { if (World.Player == null) return false; if (!RazorEnhanced.Settings.General.ReadBool("BlockHealPoison")) return false; if (ser.IsMobile && (World.Player.LastSpell == Spell.ToID(1, 4) || World.Player.LastSpell == Spell.ToID(4, 5) || World.Player.LastSpell == 202)) { Assistant.Mobile m = World.FindMobile(ser); if (m != null && m.Poisoned) { World.Player.SendMessage(MsgLevel.Warning, "Heal blocked, Target is poisoned!"); return true; } else if (m != null && m.Blessed) { World.Player.SendMessage(MsgLevel.Warning, "Heal blocked, Target is mortelled!"); return true; } return false; } else return false; } // Funzioni target per richiamare i target della gui private static string GetPlayerName(int s) { Assistant.Mobile mob = World.FindMobile(s); return mob != null ? mob.Name : string.Empty; } private static int[] m_NotoHues = new int[8] { 1, // black unused 0 0x059, // blue 0x0059 1 0x03F, // green 0x003F 2 0x3B2, // greyish 0x03b2 3 0x3B2, // grey " 4 0x090, // orange 0x0090 5 0x022, // red 0x0022 6 0x035, // yellow 0x0035 7 }; private static int GetPlayerColor(Mobile mob) { if (mob == null) return 0; return m_NotoHues[mob.Notoriety]; } public static void SetLastTargetFromList(string targetid) { TargetGUI targetdata = Settings.Target.TargetRead(targetid); if (targetdata != null) { Mobiles.Filter filter = targetdata.TargetGuiObject.Filter.ToMobileFilter(); string selector = targetdata.TargetGuiObject.Selector; List<Mobile> filterresult; filterresult = Mobiles.ApplyFilter(filter); Mobile mobtarget = Mobiles.Select(filterresult, selector); if (mobtarget == null) return; RazorEnhanced.Target.SetLast(mobtarget); } } public static Mobile GetTargetFromList(string targetid) { TargetGUI targetdata = Settings.Target.TargetRead(targetid); if (targetdata == null) return null; Mobiles.Filter filter = targetdata.TargetGuiObject.Filter.ToMobileFilter(); string selector = targetdata.TargetGuiObject.Selector; List<Mobile> filterresult; filterresult = Mobiles.ApplyFilter(filter); Mobile mobtarget = Mobiles.Select(filterresult, selector); if (mobtarget == null) return null; return mobtarget; } internal static void SetLastTargetFromListHotKey(string targetid) { TargetGUI targetdata = Settings.Target.TargetRead(targetid); if (targetdata == null) return; Mobiles.Filter filter = targetdata.TargetGuiObject.Filter.ToMobileFilter(); string selector = targetdata.TargetGuiObject.Selector; List<Mobile> filterresult; filterresult = Mobiles.ApplyFilter(filter); Mobile mobtarget = Mobiles.Select(filterresult, selector); if (mobtarget == null) return; TargetMessage(mobtarget.Serial, false); // Process message for highlight Assistant.Mobile mobile = World.FindMobile(mobtarget.Serial); if (mobile != null) Targeting.SetLastTarget(mobile.Serial, 0, false); } public static void PerformTargetFromList(string targetid) { TargetGUI targetdata = Settings.Target.TargetRead(targetid); if (targetdata == null) return; Mobiles.Filter filter = targetdata.TargetGuiObject.Filter.ToMobileFilter(); string selector = targetdata.TargetGuiObject.Selector; List<Mobile> filterresult; filterresult = Mobiles.ApplyFilter(filter); Mobile mobtarget = Mobiles.Select(filterresult, selector); if (mobtarget == null) return; TargetExecute(mobtarget.Serial); SetLast(mobtarget); } public static void AttackTargetFromList(string targetid) { TargetGUI targetdata = Settings.Target.TargetRead(targetid); if (targetdata == null) return; Mobiles.Filter filter = targetdata.TargetGuiObject.Filter.ToMobileFilter(); string selector = targetdata.TargetGuiObject.Selector; List<Mobile> filterresult; filterresult = Mobiles.ApplyFilter(filter); Mobile mobtarget = Mobiles.Select(filterresult, selector); if (mobtarget == null) return; AttackMessage(mobtarget.Serial, true); // Process message for highlight if (Targeting.LastAttack != mobtarget.Serial) { Assistant.Client.Instance.SendToClientWait(new ChangeCombatant(mobtarget.Serial)); Targeting.LastAttack = (uint)mobtarget.Serial; } Assistant.Client.Instance.SendToServerWait(new AttackReq(mobtarget.Serial)); // Real attack } internal static void TargetMessage(int serial, bool wait) { if (Assistant.Engine.MainWindow.ShowHeadTargetCheckBox.Checked) { if (Friend.IsFriend(serial)) Mobiles.Message(World.Player.Serial, 63, "Target: [" + GetPlayerName(serial) + "]", wait); else Mobiles.Message(World.Player.Serial, GetPlayerColor(Mobiles.FindBySerial(serial)), "Target: [" + GetPlayerName(serial) + "]", wait); } if (Assistant.Engine.MainWindow.HighlightTargetCheckBox.Checked) Mobiles.Message(serial, 10, "* Target *", wait); } internal static void AttackMessage(int serial, bool wait) { if (Assistant.Engine.MainWindow.ShowHeadTargetCheckBox.Checked) { if (Friend.IsFriend(serial)) Mobiles.Message(World.Player.Serial, 63, "Attack: [" + GetPlayerName(serial) + "]", wait); else Mobiles.Message(World.Player.Serial, GetPlayerColor(Mobiles.FindBySerial(serial)), "Attack: [" + GetPlayerName(serial) + "]", wait); } if (Assistant.Engine.MainWindow.HighlightTargetCheckBox.Checked) Mobiles.Message(serial, 10, "* Target *", wait); } } }
26.049774
147
0.680389
[ "Apache-2.0" ]
3HMonkey/Razor-Enhanced
Razor/RazorEnhanced/Target.cs
11,516
C#
//this source code was auto-generated by tolua#, do not modify it using System; using LuaInterface; public class TestProtolWrap { public static void Register(LuaState L) { L.BeginStaticLibs("TestProtol"); L.RegVar("data", get_data, set_data); L.EndStaticLibs(); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_data(IntPtr L) { try { LuaDLL.tolua_pushlstring(L, TestProtol.data, TestProtol.data.Length); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int set_data(IntPtr L) { try { byte[] arg0 = ToLua.CheckByteBuffer(L, 2); TestProtol.data = arg0; return 0; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } }
18.272727
72
0.697761
[ "MIT" ]
amostalong/SSFS
Assets/LuaFramework/ToLua/Examples/15_ProtoBuffer/TestProtolWrap.cs
806
C#
#region License /* Copyright © 2014-2019 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 System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Xml; namespace Amdocs.Ginger.Common.GeneralLib { public static class General { static string mAppDataFolder = null; public static string LocalUserApplicationDataFolderPath { get { if (mAppDataFolder == null) { // DoNotVerify so on Linux it will not return empty string appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.DoNotVerify); if (!Directory.Exists(appDataFolder)) // on Linux it sometimes not exist like on Azure build { Directory.CreateDirectory(appDataFolder); } appDataFolder = Path.Combine(appDataFolder, "amdocs", "Ginger"); if (!Directory.Exists(appDataFolder)) { Directory.CreateDirectory(appDataFolder); } mAppDataFolder = appDataFolder; } return mAppDataFolder; } } public static string DefualtUserLocalWorkingFolder { get { string workingFolder = Path.Combine(LocalUserApplicationDataFolderPath, "WorkingFolder"); if (!Directory.Exists(workingFolder)) { Directory.CreateDirectory(workingFolder); } return workingFolder; } } /// <summary> /// Should use the function temporary till solution will be implemented for VE fields search /// </summary> /// <param name="fieldName"></param> /// <returns></returns> public static bool IsFieldToAvoidInVeFieldSearch(string fieldName) { if (fieldName == "BackupDic" || fieldName == "GetNameForFileName" || fieldName == "FilePath" || fieldName == "FileName" || fieldName == "ObjFileExt" || fieldName == "ItemNameField" || fieldName == "ItemImageType" || fieldName == "ItemName" || fieldName == "RelativeFilePath" || fieldName == "ObjFolderName" || fieldName == "ContainingFolder" || fieldName == "ContainingFolderFullPath" || fieldName == "ActInputValues" || fieldName == "ActReturnValues" || fieldName == "ActFlowControls" || fieldName == "ScreenShots" || fieldName == "ListStringValue" || fieldName == "ListDynamicValue" || fieldName == "ValueExpression") { return true; } else { return false; } } public static Tuple<int, int> RecalculatingSizeWithKeptRatio(Tuple<int, int> a, int boxWidth, int boxHight) { //calculate the ratio double dbl = (double)a.Item1 / (double)a.Item2; if ((int)((double)boxHight * dbl) <= boxWidth) { return new Tuple<int, int>((int)((double)boxHight * dbl), boxHight); } else { return new Tuple<int, int>(boxWidth, (int)((double)boxWidth / dbl)); } } public static Tuple<int, int> GetImageHeightWidth(string path) { Tuple<int, int> a; using (Stream stream = File.OpenRead(path)) { using (System.Drawing.Image sourceImage = System.Drawing.Image.FromStream(stream, false, false)) { a = new Tuple<int, int>(sourceImage.Width, sourceImage.Height); } } return a; } public static Tuple<int, int> RecalculatingSizeWithKeptRatio(Image Img, int boxWidth, int boxHight) { //calculate the ratio double dbl = (double)Img.Width / (double)Img.Height; if ((int)((double)boxHight * dbl) <= boxWidth) { return new Tuple<int, int>((int)((double)boxHight * dbl), boxHight); } else { return new Tuple<int, int>(boxWidth, (int)((double)boxWidth / dbl)); } } public static string ImagetoBase64String(Image Img) { using (MemoryStream ms = new MemoryStream()) { // Convert Image to byte[] Img.Save(ms, ImageFormat.Bmp); byte[] imageBytes = ms.ToArray(); // Convert byte[] to base 64 string string base64String = Convert.ToBase64String(imageBytes); return base64String; } } public static string BitmapToBase64(Bitmap bitmap) { using (MemoryStream ms = new MemoryStream()) { bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png); byte[] byteImage = ms.ToArray(); return Convert.ToBase64String(byteImage); //Get Base64 } } public static string TimeConvert(string s) { double seconds = Convert.ToDouble(s); TimeSpan ts = TimeSpan.FromSeconds(seconds); return ts.ToString(@"hh\:mm\:ss"); } public static Image Base64StringToImage(string v) { byte[] imageBytes = Convert.FromBase64String(v); MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length); // Convert byte[] to Image ms.Write(imageBytes, 0, imageBytes.Length); Image image = Image.FromStream(ms, true); return image; } public static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs) { DirectoryInfo dir = new DirectoryInfo(sourceDirName); DirectoryInfo[] dirs = dir.GetDirectories(); // If the source directory does not exist, throw an exception. if (!dir.Exists) { throw new DirectoryNotFoundException( "Source directory does not exist or could not be found: " + sourceDirName); } // If the destination directory does not exist, create it. if (!Directory.Exists(destDirName)) { Directory.CreateDirectory(destDirName); } // Get the file contents of the directory to copy. FileInfo[] files = dir.GetFiles(); foreach (FileInfo file in files) { // Create the path to the new copy of the file. string temppath = System.IO.Path.Combine(destDirName, file.Name); // Copy the file. file.CopyTo(temppath, true); } // If copySubDirs is true, copy the subdirectories. if (copySubDirs) { foreach (DirectoryInfo subdir in dirs) { // Create the subdirectory. string temppath = System.IO.Path.Combine(destDirName, subdir.Name); // Copy the subdirectories. DirectoryCopy(subdir.FullName, temppath, copySubDirs); } } } public static void ClearDirectoryContent(string DirPath) { //clear directory System.IO.DirectoryInfo di = new DirectoryInfo(DirPath); foreach (FileInfo file in di.GetFiles()) file.Delete(); foreach (DirectoryInfo dir in di.GetDirectories()) { dir.Delete(true); } } public static string RemoveInvalidFileNameChars(string fileName) { foreach (char invalidChar in Path.GetInvalidFileNameChars()) { fileName = fileName.Replace(invalidChar.ToString(), ""); } fileName = fileName.Replace(@".", ""); fileName = fileName.Replace(@"?", ""); // on Linux it is valid but we do not want it // !!!!!!!!!!!!!!!!! //TODO: add more chars remove - see https://blog.josephscott.org/2007/02/12/things-that-shouldnt-be-in-file-names-for-1000-alex/ return fileName; } public static string RemoveInvalidCharsCombinePath(string filePath, string fileName) { return Path.Combine(filePath, RemoveInvalidFileNameChars(fileName)); } public class XmlNodeItem { public XmlNodeItem(string p, string v, string xp) { param = p; value = v; path = xp; } public static class Fields { public static string param = "param"; public static string value = "value"; public static string path = "path"; } public override String ToString() { return "Param:" + param + Environment.NewLine + "value:" + value + Environment.NewLine + "path:" + path; } public string param { get; set; } public string value { get; set; } public string path { get; set; } } public static List<XmlNodeItem> GetXMLNodesItems(XmlDocument xmlDoc, bool DisableProhibitDtd = false) { List<XmlNodeItem> returnDict = new List<XmlNodeItem>(); XmlReader rdr1 = XmlReader.Create(new System.IO.StringReader(xmlDoc.InnerXml)); XmlReader rdr = null; if (DisableProhibitDtd) { XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Parse; rdr = XmlReader.Create(new System.IO.StringReader(xmlDoc.InnerXml), settings); } else { rdr = XmlReader.Create(new System.IO.StringReader(xmlDoc.InnerXml)); } XmlReader subrdr = null; string Elm = ""; ArrayList ls = new ArrayList(); Dictionary<string, int> lspath = new Dictionary<string, int>(); List<string> DeParams = new List<string>(); while (rdr.Read()) { if (rdr.NodeType == XmlNodeType.Element) { Elm = rdr.Name; if (ls.Count <= rdr.Depth) ls.Add(Elm); else ls[rdr.Depth] = Elm; foreach (var p in DeParams) { if (p == rdr.Name) { subrdr = rdr.ReadSubtree(); subrdr.ReadToFollowing(p); returnDict.Add(new XmlNodeItem("AllDescOf" + p, subrdr.ReadInnerXml(), "/" + string.Join("/", ls.ToArray().Take(rdr.Depth)))); subrdr = null; } } } if (rdr.NodeType == XmlNodeType.Text) { // soup req contains sub xml, so parse them if (rdr.Value.StartsWith("<?xml")) { XmlDocument xmlnDoc = new XmlDocument(); xmlnDoc.LoadXml(rdr.Value); GetXMLNodesItems(xmlnDoc); } else { if (!lspath.Keys.Contains("/" + string.Join("/", ls.ToArray().Take(rdr.Depth)) + "/" + Elm)) { returnDict.Add(new XmlNodeItem(Elm, rdr.Value, "/" + string.Join("/", ls.ToArray().Take(rdr.Depth)))); lspath.Add("/" + string.Join("/", ls.ToArray().Take(rdr.Depth)) + "/" + Elm, 0); } else if (lspath.Keys.Contains("/" + string.Join("/", ls.ToArray().Take(rdr.Depth)) + "/" + Elm)) { returnDict.Add(new XmlNodeItem(Elm + "_" + lspath["/" + string.Join("/", ls.ToArray().Take(rdr.Depth)) + "/" + Elm], rdr.Value, "/" + string.Join("/", ls.ToArray().Take(rdr.Depth)))); lspath["/" + string.Join("/", ls.ToArray().Take(rdr.Depth)) + "/" + Elm]++; } } } } return returnDict; } public static string CorrectJSON(string WrongJson) { string CleanJson = WrongJson.Replace("\\", ""); string CleanJson1 = CleanJson.Substring(CleanJson.IndexOf("{")); string CleanJson2 = CleanJson1.Substring(0, CleanJson1.LastIndexOf("}") + 1); return CleanJson2; } } }
36.725333
211
0.51474
[ "Apache-2.0" ]
fainagof/Ginger
Ginger/GingerCoreCommon/GeneralLib/General.cs
13,775
C#
// This file has been generated using the Simplic.Flow.NodeGenerator using System; using Simplic.Flow; namespace Simplic.Flow.Node { [ActionNodeDefinition(Name = nameof(SystemDateTimeIsLeapYear_Int32), DisplayName = "IsLeapYear(Int32)", Category = "System/DateTime")] public class SystemDateTimeIsLeapYear_Int32 : ActionNode { public override bool Execute(IFlowRuntimeService runtime, DataPinScope scope) { try { var returnValue = System.DateTime.IsLeapYear( scope.GetValue<System.Int32>(InPinYear)); scope.SetValue(OutPinReturn, returnValue); if (OutNodeTrue != null && returnValue) { runtime.EnqueueNode(OutNodeTrue, scope); } else if (OutNodeFalse != null && !returnValue) { runtime.EnqueueNode(OutNodeFalse, scope); } if (OutNodeSuccess != null) { runtime.EnqueueNode(OutNodeSuccess, scope); } } catch (Exception ex) { Simplic.Log.LogManagerInstance.Instance.Error("Error in SystemDateTimeIsLeapYear_Int32: ", ex); if (OutNodeFailed != null) runtime.EnqueueNode(OutNodeFailed, scope); } return true; } public override string Name => nameof(SystemDateTimeIsLeapYear_Int32); public override string FriendlyName => nameof(SystemDateTimeIsLeapYear_Int32); [FlowPinDefinition( PinDirection = PinDirection.Out, DisplayName = "Success", Name = nameof(OutNodeSuccess), AllowMultiple = false)] public ActionNode OutNodeSuccess { get; set; } [FlowPinDefinition( PinDirection = PinDirection.Out, DisplayName = "Failed", Name = nameof(OutNodeFailed), AllowMultiple = false)] public ActionNode OutNodeFailed { get; set; } [FlowPinDefinition( PinDirection = PinDirection.Out, DisplayName = "True", Name = nameof(OutNodeTrue), AllowMultiple = false)] public ActionNode OutNodeTrue { get; set; } [FlowPinDefinition( PinDirection = PinDirection.Out, DisplayName = "False", Name = nameof(OutNodeFalse), AllowMultiple = false)] public ActionNode OutNodeFalse { get; set; } [DataPinDefinition( Id = "d37ecd11-f64e-465f-9caf-14b174a07e33", ContainerType = DataPinContainerType.Single, DataType = typeof(System.Int32), Direction = PinDirection.In, Name = nameof(InPinYear), DisplayName = "Year", IsGeneric = false, AllowedTypes = null)] public DataPin InPinYear { get; set; } [DataPinDefinition( Id = "d3307615-c1b0-43dc-aaa6-f552bfe90e28", ContainerType = DataPinContainerType.Single, DataType = typeof(System.Boolean), Direction = PinDirection.Out, Name = nameof(OutPinReturn), DisplayName = "Return", IsGeneric = false, AllowedTypes = null)] public DataPin OutPinReturn { get; set; } } }
35.126316
138
0.579263
[ "MIT" ]
simplic/flow
src/Simplic.Flow.Node/ActionNode/Generic/System.DateTime/SystemDateTimeIsLeapYear_Int32Node.cs
3,337
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** 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.Azure.ManagementGroups { [Obsolete(@"azure.managementgroups.getManagementGroup has been deprecated in favour of azure.management.getGroup")] public static class GetManagementGroup { /// <summary> /// Use this data source to access information about an existing Management Group. /// /// {{% examples %}} /// {{% /examples %}} /// /// Deprecated: azure.managementgroups.getManagementGroup has been deprecated in favour of azure.management.getGroup /// </summary> public static Task<GetManagementGroupResult> InvokeAsync(GetManagementGroupArgs? args = null, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetManagementGroupResult>("azure:managementgroups/getManagementGroup:getManagementGroup", args ?? new GetManagementGroupArgs(), options.WithVersion()); } public sealed class GetManagementGroupArgs : Pulumi.InvokeArgs { /// <summary> /// Specifies the name or UUID of this Management Group. /// </summary> [Input("groupId")] public string? GroupId { get; set; } /// <summary> /// Specifies the name or UUID of this Management Group. /// </summary> [Input("name")] public string? Name { get; set; } public GetManagementGroupArgs() { } } [OutputType] public sealed class GetManagementGroupResult { /// <summary> /// A friendly name for the Management Group. /// </summary> public readonly string DisplayName; public readonly string GroupId; /// <summary> /// The provider-assigned unique ID for this managed resource. /// </summary> public readonly string Id; public readonly string Name; /// <summary> /// The ID of any Parent Management Group. /// </summary> public readonly string ParentManagementGroupId; /// <summary> /// A list of Subscription ID's which are assigned to the Management Group. /// </summary> public readonly ImmutableArray<string> SubscriptionIds; [OutputConstructor] private GetManagementGroupResult( string displayName, string groupId, string id, string name, string parentManagementGroupId, ImmutableArray<string> subscriptionIds) { DisplayName = displayName; GroupId = groupId; Id = id; Name = name; ParentManagementGroupId = parentManagementGroupId; SubscriptionIds = subscriptionIds; } } }
32.709677
205
0.621959
[ "ECL-2.0", "Apache-2.0" ]
davidobrien1985/pulumi-azure
sdk/dotnet/ManagementGroups/GetManagementGroup.cs
3,042
C#
using MediatR; using Opdex.Platform.Application.Abstractions.Models.MarketTokens; using Opdex.Platform.Application.Abstractions.Models.Tokens; using Opdex.Platform.Common.Models; using System; namespace Opdex.Platform.Application.Abstractions.EntryQueries.Tokens; /// <summary> /// Get a market token by its market contract address and token contract address. /// </summary> public class GetMarketTokenByMarketAndTokenAddressQuery : IRequest<MarketTokenDto> { /// <summary> /// Constructor to create a get market token by market and token address query. /// </summary> /// <param name="market">The contract address of the market.</param> /// <param name="token">The contract address of the token in the market.</param> public GetMarketTokenByMarketAndTokenAddressQuery(Address market, Address token) { if (market == Address.Empty) { throw new ArgumentNullException(nameof(market), "Market address must be provided."); } if (token == Address.Empty) { throw new ArgumentNullException(nameof(token), "Token address must be provided."); } Market = market; Token = token; } public Address Market { get; } public Address Token { get; } }
34.162162
96
0.692247
[ "MIT" ]
Opdex/opdex-v1-api
src/Opdex.Platform.Application.Abstractions/EntryQueries/Tokens/GetMarketTokenByMarketAndTokenAddressQuery.cs
1,264
C#
/* * * (c) Copyright Ascensio System Limited 2010-2020 * * 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 ASC.Mail.Net.ABNF { #region usings using System; using System.IO; using System.Text; #endregion /// <summary> /// This class represent ABNF "char-val". Defined in RFC 5234 4. /// </summary> public class ABNF_CharVal : ABNF_Element { #region Members private readonly string m_Value = ""; #endregion #region Properties /// <summary> /// Gets value. /// </summary> public string Value { get { return m_Value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="value">The prose-val value.</param> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public ABNF_CharVal(string value) { if (value == null) { throw new ArgumentNullException("value"); } if (!Validate(value)) { //throw new ArgumentException("Invalid argument 'value' value. Value must be: 'DQUOTE *(%x20-21 / %x23-7E) DQUOTE'."); } m_Value = value; } #endregion #region Methods /// <summary> /// /// </summary> /// <param name="reader"></param> /// <returns></returns> public static ABNF_CharVal Parse(StringReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } /* char-val = DQUOTE *(%x20-21 / %x23-7E) DQUOTE ; quoted string of SP and VCHAR ; without DQUOTE */ if (reader.Peek() != '\"') { throw new ParseException("Invalid ABNF 'char-val' value '" + reader.ReadToEnd() + "'."); } // Eat DQUOTE reader.Read(); // TODO: *c-wsp StringBuilder value = new StringBuilder(); while (true) { // We reached end of stream, no closing DQUOTE. if (reader.Peek() == -1) { throw new ParseException("Invalid ABNF 'char-val' value '" + reader.ReadToEnd() + "'."); } // We have closing DQUOTE. else if (reader.Peek() == '\"') { reader.Read(); break; } // Allowed char. else if ((reader.Peek() >= 0x20 && reader.Peek() <= 0x21) || (reader.Peek() >= 0x23 && reader.Peek() <= 0x7E)) { value.Append((char) reader.Read()); } // Invalid value. else { throw new ParseException("Invalid ABNF 'char-val' value '" + reader.ReadToEnd() + "'."); } } return new ABNF_CharVal(value.ToString()); } #endregion #region Utility methods /// <summary> /// Validates "prose-val" value. /// </summary> /// <param name="value">The "prose-val" value.</param> /// <returns>Returns if value is "prose-val" value, otherwise false.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> private bool Validate(string value) { if (value == null) { throw new ArgumentNullException("value"); } // RFC 5234 4. // char-val = DQUOTE *(%x20-21 / %x23-7E) DQUOTE if (value.Length < 2) { return false; } for (int i = 0; i < value.Length; i++) { char c = value[i]; if (i == 0 && c != '\"') { return false; } else if (i == (value.Length - 1) && c != '\"') { return false; } else if (!((c >= 0x20 && c <= 0x21) || (c >= 0x23 && c <= 0x7E))) { return false; } } return true; } #endregion } }
28.630435
134
0.462415
[ "Apache-2.0" ]
Ektai-Solution-Pty-Ltd/CommunityServer
module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/ABNF/ABNF_CharVal.cs
5,268
C#
using Academy.Commands.Contracts; using Academy.Core.Contracts; using Academy.Framework.Core.Contracts; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; using System.Linq; using System.Text; namespace Academy.Core.Tests { [TestClass] public class Start_Should { public const string exitCommand = "Exit"; private Mock<IReader> readerMock; private Mock<IWriter> writerMock; private Mock<IParser> parserMock; private Mock<IDatabase> databaseMock; private StringBuilder builder; private IEngine engine; [TestInitialize] public void InitializingMocks() { this.readerMock = new Mock<IReader>(); this.writerMock = new Mock<IWriter>(); this.parserMock = new Mock<IParser>(); this.databaseMock = new Mock<IDatabase>(); this.builder = new StringBuilder(); this.engine = new Engine(readerMock.Object, writerMock.Object, parserMock.Object, databaseMock.Object); } [TestMethod] public void WriteACustomExceptionMessage_WhenArgumentOutOfRangeExceptionIsThrown() { //Arrange var expectedCustomException = "Invalid command parameters supplied or the entity with that ID for does not exist."; this.readerMock.SetupSequence(x => x.ReadLine()).Throws<ArgumentOutOfRangeException>().Returns(exitCommand); this.builder.AppendLine(expectedCustomException); //Act this.engine.Start(); //Assert this.writerMock.Verify(x => x.Write(builder.ToString()), Times.Once()); } [TestMethod] public void WriteAnExceptionMessage_WhenExceptionIsThrown() { //Arrange var exception = new Exception(); this.readerMock.SetupSequence(x => x.ReadLine()).Throws<Exception>().Returns(exitCommand); this.builder.AppendLine(exception.Message); //Act this.engine.Start(); //Assert this.writerMock.Verify(x => x.Write(builder.ToString()), Times.Once()); } [TestMethod] public void ProcessCommandAndWriteCorrectExecutionMessage_WhenParametersAreCorrect() { //Arrange var commandMock = new Mock<ICommand>(); var randomCommand = "CreateSeason 2016 2017 SoftwareAcademy"; var inputParameters = randomCommand.Split(' ').ToList(); var executionMessage = "Execution message"; commandMock.Setup(x => x.Execute(inputParameters)).Returns(executionMessage); this.readerMock.SetupSequence(x => x.ReadLine()).Returns(randomCommand).Returns(exitCommand); this.parserMock.Setup(x => x.ParseCommand(randomCommand)).Returns(commandMock.Object); this.parserMock.Setup(x => x.ParseParameters(randomCommand)).Returns(inputParameters); this.builder.AppendLine(executionMessage); //Act this.engine.Start(); //Assert this.writerMock.Verify(x => x.Write(builder.ToString()), Times.Once()); } } }
38.819277
130
0.627871
[ "MIT" ]
SvetozarMateev/Exercises
Academy/Academy.UnitTest/Core/EngineTests/Start_Should.cs
3,224
C#
using System; public class OtherStringOperations { public static void Main() { // String.Replace() example string cocktail = "Vodka + Martini + Cherry"; string replaced = cocktail.Replace("+", "and"); Console.WriteLine(replaced); // String.Remove() example string price = "$ 1234567"; string lowPrice = price.Remove(2, 3); Console.WriteLine(lowPrice); // Uppercase and lowercase conversion examples string alpha = "aBcDeFg"; string lowerAlpha = alpha.ToLower(); Console.WriteLine(lowerAlpha); string upperAlpha = alpha.ToUpper(); Console.WriteLine(upperAlpha); // Trim() example string s = " example of white space "; string clean = s.Trim(); Console.WriteLine(clean); // Trim(chars) example s = " \t\nHello!!! \n"; clean = s.Trim(' ', ',', '!', '\n', '\t'); Console.WriteLine(clean); // TrimStart() example s = " C# "; clean = s.TrimStart(); Console.WriteLine(clean); // TrimEnd() example s = " C# "; clean = s.TrimEnd(); Console.WriteLine(clean); } }
27.727273
55
0.540984
[ "CC0-1.0" ]
ivayloivanof/AdvancedCSharp
AdvancedCSharp/03.StringsAndTextProcessing/Demos/Other-String-Operations/OtherStringOperations.cs
1,220
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class Loser : MonoBehaviour { [SerializeField] TextMeshProUGUI playerLost; // Start is called before the first frame update void Start() { playerLost.text = FindObjectOfType<GameSession>().GetLoser() + " HAS LOST"; } // Update is called once per frame void Update() { } }
19.409091
83
0.665105
[ "MIT" ]
hkim1016/Pong
Pong/Assets/Scripts/Loser.cs
427
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class GameManager : MonoBehaviour { //public List<GameObject> npcObjs = new List<GameObject>(); Dictionary<string, float> npcInfo = new Dictionary<string, float>(); public GameObject NPCPrefab; //called before the first frame update void Start() { npcInfo.Add("bob", 0.6f); npcInfo.Add("lorg", 0.9f); npcInfo.Add("akshay", 0.56f); npcInfo.Add("sophie", 1f); npcInfo.Add("zach", 0.8f); npcInfo.Add("hao", 0.2f); // float testValue; // npcInfo.TryGetValue("akshay", out testValue); // print(testValue); foreach(KeyValuePair<string, float> pair in npcInfo) { print(pair.Key); print(pair.Value); GameObject NPC = Instantiate(NPCPrefab); NPC.GetComponentInChildren<TextMeshProUGUI>().SetText(pair.Key); NPC.GetComponent<NPCController>().sight = pair.Value; //loop through the dict //for each entry, instantiate an NPC //set name to the key //set sight to the value } // foreach(GameObject NPC in npcObjs) // { // NPC.GetComponent<NPCController>().nameCanvas.transform.GetChild(0); // } // for(int i = 0; i < npcObjs.Count; i++) // { // npcObjs[i].GetComponentInChildren<TextMeshProUGUI>().SetText("COOL PLAYER"); // } } //called once per frame void Update() { } }
26.278689
91
0.570805
[ "Unlicense" ]
honeyboyJones/code_lab_1_assignments
tea_game_hw/Assets/Scripts/w12/GameManager.cs
1,603
C#
using System.Collections.Generic; using System.Linq; using System.Net.WebSockets; namespace WebsocketsSimple.Server.Models { public class IdentityWS<T> : IIdentityWS<T> { public T UserId { get; set; } public ICollection<IConnectionWSServer> Connections { get; set; } public IConnectionWSServer GetConnection(WebSocket websocket) { return Connections.FirstOrDefault(s => s.Websocket.GetHashCode() == websocket.GetHashCode()); } } }
26.263158
105
0.681363
[ "Apache-2.0" ]
LiveOrDevTrying/WebsocketsSimple
WebsocketsSimple.Server/Models/IdentityWS.cs
501
C#
using System; using System.Collections.Generic; using System.Text; namespace Achamenes.ID3.Frames { [global::System.Serializable] public class OfficialAudioFileUrlFrame : UrlFrame { public OfficialAudioFileUrlFrame(string url) : base(url) { } public static Achamenes.ID3.Frames.Parsers.FrameParser CreateParser(ID3v2MajorVersion version, string frameID) { if(version==ID3v2MajorVersion.Version2 && frameID=="WAF") { return new Parsers.OfficialAudioFileUrlFrameParser(); } if((version==ID3v2MajorVersion.Version3 || version==ID3v2MajorVersion.Version4) && frameID=="WOAF") { return new Parsers.OfficialAudioFileUrlFrameParser(); } return null; } public override Achamenes.ID3.Frames.Writers.FrameWriter CreateWriter(ID3v2MajorVersion version, EncodingScheme encoding) { if(version==ID3v2MajorVersion.Version2) { return new Writers.UrlFrameWriter(this, "WAF", Writers.FrameHeaderWriter.CreateFrameHeaderWriter(version), encoding); } if(version==ID3v2MajorVersion.Version3 || version==ID3v2MajorVersion.Version4) { return new Writers.UrlFrameWriter(this, "WOAF", Writers.FrameHeaderWriter.CreateFrameHeaderWriter(version), encoding); } return null; } } }
30.170732
123
0.756669
[ "MIT", "Unlicense" ]
sahands/a-id3
ID3/Source/Frames/URL Frames/OfficialAudioFileUrlFrame.cs
1,237
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("XamarinClient.UWP")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("XamarinClient.UWP")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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")] [assembly: ComVisible(false)]
36.241379
84
0.74215
[ "MIT" ]
Bazzaware/ProfessionalCSharp7
DependencyInjection/PISample/XamarinClient/XamarinClient.UWP/Properties/AssemblyInfo.cs
1,054
C#
using System; using System.Collections.Generic; namespace InstructorIQ.Core.Data.Entities { /// <summary> /// Entity class representing data for table 'ImportJob'. /// </summary> public partial class ImportJob { /// <summary> /// Initializes a new instance of the <see cref="ImportJob"/> class. /// </summary> public ImportJob() { #region Generated Constructor #endregion } #region Generated Properties /// <summary> /// Gets or sets the property value representing column 'Id'. /// </summary> /// <value> /// The property value representing column 'Id'. /// </value> public Guid Id { get; set; } /// <summary> /// Gets or sets the property value representing column 'Type'. /// </summary> /// <value> /// The property value representing column 'Type'. /// </value> public string Type { get; set; } /// <summary> /// Gets or sets the property value representing column 'TenantId'. /// </summary> /// <value> /// The property value representing column 'TenantId'. /// </value> public Guid TenantId { get; set; } /// <summary> /// Gets or sets the property value representing column 'MappingJson'. /// </summary> /// <value> /// The property value representing column 'MappingJson'. /// </value> public string MappingJson { get; set; } /// <summary> /// Gets or sets the property value representing column 'StorageFile'. /// </summary> /// <value> /// The property value representing column 'StorageFile'. /// </value> public string StorageFile { get; set; } /// <summary> /// Gets or sets the property value representing column 'Created'. /// </summary> /// <value> /// The property value representing column 'Created'. /// </value> public DateTimeOffset Created { get; set; } /// <summary> /// Gets or sets the property value representing column 'CreatedBy'. /// </summary> /// <value> /// The property value representing column 'CreatedBy'. /// </value> public string CreatedBy { get; set; } /// <summary> /// Gets or sets the property value representing column 'Updated'. /// </summary> /// <value> /// The property value representing column 'Updated'. /// </value> public DateTimeOffset Updated { get; set; } /// <summary> /// Gets or sets the property value representing column 'UpdatedBy'. /// </summary> /// <value> /// The property value representing column 'UpdatedBy'. /// </value> public string UpdatedBy { get; set; } /// <summary> /// Gets or sets the property value representing column 'RowVersion'. /// </summary> /// <value> /// The property value representing column 'RowVersion'. /// </value> public Byte[] RowVersion { get; set; } #endregion #region Generated Relationships /// <summary> /// Gets or sets the navigation property for entity <see cref="Tenant" />. /// </summary> /// <value> /// The the navigation property for entity <see cref="Tenant" />. /// </value> /// <seealso cref="TenantId" /> public virtual Tenant Tenant { get; set; } #endregion } }
31.145299
82
0.538694
[ "Apache-2.0" ]
loresoft/InstructorIQ
service/src/InstructorIQ.Core/Data/Entities/ImportJob.cs
3,644
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.Outputs { [OutputType] public sealed class PacketCaptureFilterResponse { /// <summary> /// Local IP Address to be filtered on. Notation: "127.0.0.1" for single address entry. "127.0.0.1-127.0.0.255" for range. "127.0.0.1;127.0.0.5"? for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. /// </summary> public readonly string? LocalIPAddress; /// <summary> /// Local port to be filtered on. Notation: "80" for single port entry."80-85" for range. "80;443;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. /// </summary> public readonly string? LocalPort; /// <summary> /// Protocol to be filtered on. /// </summary> public readonly string? Protocol; /// <summary> /// Local IP Address to be filtered on. Notation: "127.0.0.1" for single address entry. "127.0.0.1-127.0.0.255" for range. "127.0.0.1;127.0.0.5;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. /// </summary> public readonly string? RemoteIPAddress; /// <summary> /// Remote port to be filtered on. Notation: "80" for single port entry."80-85" for range. "80;443;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. /// </summary> public readonly string? RemotePort; [OutputConstructor] private PacketCaptureFilterResponse( string? localIPAddress, string? localPort, string? protocol, string? remoteIPAddress, string? remotePort) { LocalIPAddress = localIPAddress; LocalPort = localPort; Protocol = protocol; RemoteIPAddress = remoteIPAddress; RemotePort = remotePort; } } }
43.280702
293
0.65302
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Network/Outputs/PacketCaptureFilterResponse.cs
2,467
C#
using System; using System.Collections.Generic; namespace tetris_ai_cn { public class Brick { /// <summary> /// 说明板块类型,0田字形,1|字形,2T字形,3Z字形,4S字形,5J字形,6L字形 /// </summary> public int type = 0; /// <summary> /// 以稀疏矩阵的方式存储每个方块相对板块的位置 /// </summary> public List<Node> typenodes; /// <summary> /// 以稀疏矩阵的方式存储每个方块对应背景矩阵arr的位置 /// </summary> public List<Node> posnodes; /// <summary> /// 板块中心位置 /// </summary> public Node pos = new Node { x = Form1.columns / 2 - 1, y = Form1.rows + 1 }; /// <summary> /// 新建板块 /// </summary> public Brick() { Random random = new Random(); int index = random.Next(0, 49) / 7; //int index = 1; typenodes = new List<Node>(); Node node1, node2, node3, node4; switch (index) { case 0: //田字形 type = 0; node1 = new Node() { x = 0, y = 0 }; typenodes.Add(node1); node2 = new Node() { x = 1, y = 0 }; typenodes.Add(node2); node3 = new Node() { x = 1, y = -1 }; typenodes.Add(node3); node4 = new Node() { x = 0, y = -1 }; typenodes.Add(node4); break; case 1: //|字形 type = 1; node1 = new Node() { x = 2, y = 0 }; typenodes.Add(node1); node2 = new Node() { x = 1, y = 0 }; typenodes.Add(node2); node3 = new Node() { x = 0, y = 0 }; typenodes.Add(node3); node4 = new Node() { x = -1, y = 0 }; typenodes.Add(node4); break; case 2: //T字形 type = 2; node1 = new Node() { x = -1, y = 0 }; typenodes.Add(node1); node2 = new Node() { x = 1, y = 0 }; typenodes.Add(node2); node3 = new Node() { x = 0, y = 0 }; typenodes.Add(node3); node4 = new Node() { x = 0, y = -1 }; typenodes.Add(node4); break; case 3: //z字形 type = 3; node1 = new Node() { x = 0, y = 0 }; typenodes.Add(node1); node2 = new Node() { x = 0, y = -1 }; typenodes.Add(node2); node3 = new Node() { x = 1, y = 0 }; typenodes.Add(node3); node4 = new Node() { x = 1, y = 1 }; typenodes.Add(node4); break; case 4: //s字形 type = 4; node1 = new Node() { x = 0, y = 0 }; typenodes.Add(node1); node2 = new Node() { x = 0, y = -1 }; typenodes.Add(node2); node3 = new Node() { x = -1, y = 0 }; typenodes.Add(node3); node4 = new Node() { x = -1, y = 1 }; typenodes.Add(node4); break; case 5: //J字形 type = 5; node1 = new Node() { x = 0, y = 2 }; typenodes.Add(node1); node2 = new Node() { x = 0, y = 1 }; typenodes.Add(node2); node3 = new Node() { x = 0, y = 0 }; typenodes.Add(node3); node4 = new Node() { x = -1, y = 0 }; typenodes.Add(node4); break; case 6: //L字形 type = 6; node1 = new Node() { x = 0, y = 2 }; typenodes.Add(node1); node2 = new Node() { x = 0, y = 1 }; typenodes.Add(node2); node3 = new Node() { x = 0, y = 0 }; typenodes.Add(node3); node4 = new Node() { x = 1, y = 0 }; typenodes.Add(node4); break; } } /// <summary> /// 指定类型新建板块 /// </summary> /// <param name="index">index整数,0~7分别代指一种板块类型,具体看type注释</param> public Brick(int index) { typenodes = new List<Node>(); Node node1, node2, node3, node4; switch (index) { case 0: //田字形 type = 0; node1 = new Node() { x = 0, y = 0 }; typenodes.Add(node1); node2 = new Node() { x = 1, y = 0 }; typenodes.Add(node2); node3 = new Node() { x = 1, y = -1 }; typenodes.Add(node3); node4 = new Node() { x = 0, y = -1 }; typenodes.Add(node4); break; case 1: //|字形 type = 1; node1 = new Node() { x = 2, y = 0 }; typenodes.Add(node1); node2 = new Node() { x = 1, y = 0 }; typenodes.Add(node2); node3 = new Node() { x = 0, y = 0 }; typenodes.Add(node3); node4 = new Node() { x = -1, y = 0 }; typenodes.Add(node4); break; case 2: //T字形 type = 2; node1 = new Node() { x = -1, y = 0 }; typenodes.Add(node1); node2 = new Node() { x = 1, y = 0 }; typenodes.Add(node2); node3 = new Node() { x = 0, y = 0 }; typenodes.Add(node3); node4 = new Node() { x = 0, y = -1 }; typenodes.Add(node4); break; case 3: //z字形 type = 3; node1 = new Node() { x = 0, y = 0 }; typenodes.Add(node1); node2 = new Node() { x = 0, y = -1 }; typenodes.Add(node2); node3 = new Node() { x = 1, y = 0 }; typenodes.Add(node3); node4 = new Node() { x = 1, y = 1 }; typenodes.Add(node4); break; case 4: //s字形 type = 4; node1 = new Node() { x = 0, y = 0 }; typenodes.Add(node1); node2 = new Node() { x = 0, y = -1 }; typenodes.Add(node2); node3 = new Node() { x = -1, y = 0 }; typenodes.Add(node3); node4 = new Node() { x = -1, y = 1 }; typenodes.Add(node4); break; case 5: //J字形 type = 5; node1 = new Node() { x = 0, y = 2 }; typenodes.Add(node1); node2 = new Node() { x = 0, y = 1 }; typenodes.Add(node2); node3 = new Node() { x = 0, y = 0 }; typenodes.Add(node3); node4 = new Node() { x = -1, y = 0 }; typenodes.Add(node4); break; case 6: //L字形 type = 6; node1 = new Node() { x = 0, y = 2 }; typenodes.Add(node1); node2 = new Node() { x = 0, y = 1 }; typenodes.Add(node2); node3 = new Node() { x = 0, y = 0 }; typenodes.Add(node3); node4 = new Node() { x = 1, y = 0 }; typenodes.Add(node4); break; } } /// <summary> /// 仅改变typenode来逆时针旋转,不考虑越界 /// </summary> public void Rotate() { List<Node> new_typenodes = new List<Node>(); foreach (Node item in typenodes) new_typenodes.Add(item.Trans()); typenodes = new_typenodes; } /// <summary> /// 仅改变typenode来逆时针旋转,不考虑越界 /// </summary> /// <param name="time">旋转次数</param> public void Rotate(int time) { for (int i = 0; i < time; i++) Rotate(); } /// <summary> /// 使板块逆时针旋转90度,只忽略背景图矩阵上界 /// </summary> /// <returns>返回false表示旋转失败</returns> public bool Transform() { List<Node> new_posnodes = new List<Node>(); List<Node> new_typenodes = new List<Node>(); foreach (Node item in typenodes) { new_item = item.Trans() + pos; if (new_item.y <= Form1.rows - 1) { if (new_item.x > Form1.columns - 1 || new_item.x < 0 || new_item.y < 0 || Form1.arr[new_item.x, new_item.y] == 1) return false; new_posnodes.Add(new_item); } new_typenodes.Add(item.Trans()); } posnodes = new_posnodes; typenodes = new_typenodes; eswn = (eswn + 1) % 4; return true; } /// <summary> /// 尝试左移,如能就左移 /// </summary> public void Leftmove() { if (Canmove(lpos + pos)) pos += lpos; } /// <summary> /// 尝试右移,如能就右移 /// </summary> public void Rightmove() { if (Canmove(rpos + pos)) pos += rpos; } /// <summary> /// 尝试下移,如能就下移 /// </summary> /// <returns></returns> public bool Dropmove() { if (Canmove(dpos + pos)) { pos += dpos; return true; } else return false; } /// <summary> /// 判断能否移动到new_pos /// </summary> /// <param name="new_pos">Node类坐标</param> /// <returns>返回能否</returns> public bool Canmove(Node new_pos) { List<Node> new_posnodes = new List<Node>(); foreach (Node item in typenodes) { Node new_item = new_pos + item; //三边满足 if (new_item.x >= 0 && new_item.x < Form1.columns && new_item.y >= 0) { //上越界 if (new_item.y > Form1.rows - 1) continue; //四边满足有重合 else if (Form1.arr[new_item.x, new_item.y] == 1) return false; //四边满足无重合 else new_posnodes.Add(new_item); } else return false; } posnodes = new_posnodes; return true; } /// <summary> /// 中间变量,请勿打扰 /// </summary> private Node new_item; /// <summary> /// 预定义的左方偏移 /// </summary> private static Node lpos = new Node { x = -1, y = 0 }; /// <summary> /// 预定义右方偏移 /// </summary> private static Node rpos = new Node { x = 1, y = 0 }; /// <summary> /// 预定义向下偏移 /// </summary> private static Node dpos = new Node { x = 0, y = -1 }; /// <summary> /// 模式匹配数组 /// </summary> public static int[,] MatchPattern = new int[,] { { 2,0,0,0,0},{ 2,0,0,0,0},{ 2,0,0,0,0},{ 2,0,0,0,0},//田字 { 4,0,0,0,0},{ 1,0,0,0,0},{ 4,0,0,0,0},{ 1,0,0,0,0},//一字 { 3,0,-1,0,0},{ 2,0, 1,0,0 },{ 3,0,0,0,0 },{ 2,0,-1,0,0 },//T字 { 2,0,1,0,0 },{ 3,0,-1,-1,0},{ 2,0,1,0,0 },{ 3,0,-1,-1,0},//Z字,2改成3增强不死性(概率不均时) { 2,0,-1,0,0},{ 3,0,0,1,0 },{ 2,0,-1,0,0},{ 3,0,0,1,0 },//S字,2改成3增强不死性(概率不均时) { 2,0,0,0,0 },{ 3,0,0,-1,0 },{ 2,0,2,0,0 },{ 3,0,0,0,0 },//J字 { 2,0,0,0,0 },{ 3,0,0,0,0 },{ 2,0,-2,0,0},{ 2,0,1,1,0 },//L字 }; /// <summary> /// 标记砖块的旋转状态 /// </summary> public int eswn = 0; } }
36.635854
148
0.340852
[ "MIT" ]
grdaimap/tetris_ai
tetris_ai_cn/tetris_ai_cn/Brick.cs
13,771
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the iotanalytics-2017-11-27.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.IoTAnalytics.Model { /// <summary> /// A summary of information about a data set. /// </summary> public partial class DatasetSummary { private List<DatasetActionSummary> _actions = new List<DatasetActionSummary>(); private DateTime? _creationTime; private string _datasetName; private DateTime? _lastUpdateTime; private DatasetStatus _status; private List<DatasetTrigger> _triggers = new List<DatasetTrigger>(); /// <summary> /// Gets and sets the property Actions. /// <para> /// A list of "DataActionSummary" objects. /// </para> /// </summary> [AWSProperty(Min=1, Max=1)] public List<DatasetActionSummary> Actions { get { return this._actions; } set { this._actions = value; } } // Check to see if Actions property is set internal bool IsSetActions() { return this._actions != null && this._actions.Count > 0; } /// <summary> /// Gets and sets the property CreationTime. /// <para> /// The time the data set was created. /// </para> /// </summary> public DateTime CreationTime { get { return this._creationTime.GetValueOrDefault(); } set { this._creationTime = value; } } // Check to see if CreationTime property is set internal bool IsSetCreationTime() { return this._creationTime.HasValue; } /// <summary> /// Gets and sets the property DatasetName. /// <para> /// The name of the data set. /// </para> /// </summary> [AWSProperty(Min=1, Max=128)] public string DatasetName { get { return this._datasetName; } set { this._datasetName = value; } } // Check to see if DatasetName property is set internal bool IsSetDatasetName() { return this._datasetName != null; } /// <summary> /// Gets and sets the property LastUpdateTime. /// <para> /// The last time the data set was updated. /// </para> /// </summary> public DateTime LastUpdateTime { get { return this._lastUpdateTime.GetValueOrDefault(); } set { this._lastUpdateTime = value; } } // Check to see if LastUpdateTime property is set internal bool IsSetLastUpdateTime() { return this._lastUpdateTime.HasValue; } /// <summary> /// Gets and sets the property Status. /// <para> /// The status of the data set. /// </para> /// </summary> public DatasetStatus Status { get { return this._status; } set { this._status = value; } } // Check to see if Status property is set internal bool IsSetStatus() { return this._status != null; } /// <summary> /// Gets and sets the property Triggers. /// <para> /// A list of triggers. A trigger causes data set content to be populated at a specified /// time interval or when another data set is populated. The list of triggers can be empty /// or contain up to five DataSetTrigger objects /// </para> /// </summary> [AWSProperty(Min=0, Max=5)] public List<DatasetTrigger> Triggers { get { return this._triggers; } set { this._triggers = value; } } // Check to see if Triggers property is set internal bool IsSetTriggers() { return this._triggers != null && this._triggers.Count > 0; } } }
30.382166
110
0.574843
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/IoTAnalytics/Generated/Model/DatasetSummary.cs
4,770
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Microsoft.Content.Recommendations.Common")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Microsoft.Content.Recommendations.Common")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("9e0ea8bc-0ce2-476f-a773-7ec0002b2805")] // 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")]
39.277778
84
0.747525
[ "MIT" ]
oswaldor/Plume
NLP/TopicExtraction/LatentDirichletAllocation/ModelBuilder/Properties/AssemblyInfo.cs
1,417
C#
using Klyte.AssetColorExpander.XML; using Klyte.Commons.Libraries; using System.Xml.Serialization; namespace Klyte.AssetColorExpander.Libraries { [XmlRoot("BuildingRuleLib")] public class ACEBuildingRuleLib : LibBaseFile<ACEBuildingRuleLib, BuildingCityDataRuleXml> { protected override string XmlName => "ACEBuildingRuleLib"; } }
25.571429
94
0.77095
[ "MIT" ]
klyte45/AssetColorExpander
Libraries/ACEBuildingRuleLib.cs
360
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using NuGet.VisualStudio; namespace NuGetConsole { /// <summary> /// ICommandExpansion provider (intellisense). /// To support command expansion, export an implementation of this interface /// and apply a HostName attribute to associate it with the host. /// </summary> public interface ICommandExpansionProvider { /// <summary> /// Create a command line expansion object. /// </summary> /// <param name="host">The host instance for command line expansion.</param> /// <returns>A command line expansion object.</returns> ICommandExpansion Create(IHost host); } }
35.304348
111
0.67734
[ "Apache-2.0" ]
0xced/NuGet.Client
src/NuGet.Clients/NuGet.Console/ICommandExpansionProvider.cs
812
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache v.2 license. using System; using Microsoft.SPOT; using System.IO; using System.Collections; using System.Text; using System.Net; using System.Threading; using Gadgeteer; namespace Gadgeteer.Networking { /// <summary> /// Encapsulates the data returned by the server. /// </summary> public class HttpResponse { internal HttpResponse(string statusCode, byte[] rawContentBytes, string url, WebHeaderCollection headerFields, string contentType) { this.StatusCode = statusCode; this.RawContentBytes = rawContentBytes; this.URL = url; this.headerFields = headerFields; this.ContentType = contentType; } /// <summary> /// Private collection that contains all the header fields sent by the server. Users can access this data via /// GetHeaderField(); /// </summary> private WebHeaderCollection headerFields; /// <summary> /// The status code that the server returns. /// </summary> /// public readonly string StatusCode; /// <summary> /// The mime-type of the encapsulated data. /// </summary> public readonly string ContentType; /// <summary> /// Gets the requested stream or an error message. /// </summary> public string Text { get { if (RawContentBytes != null) { try { return new string(Encoding.UTF8.GetChars(RawContentBytes)); } catch { Debug.Print("Could not decode the requested data and create text"); return null; } } return null; } } /// <summary> /// Gets the requested data as a <see cref="T:System.IO.Stream"/> object. /// </summary> public Stream Stream { get { if (RawContentBytes == null || RawContentBytes.Length <= 0) { return null; } MemoryStream stream = new MemoryStream(); stream.Write(RawContentBytes, 0, RawContentBytes.Length); stream.Position = 0; return stream; } } /// <summary> /// Return the requested data as a picture or an error message. /// </summary> public Picture Picture { get { if (RawContentBytes == null || RawContentBytes.Length <= 0) { return null; } try { string contentType = ContentType.ToLower(); switch (contentType) { case "image/jpeg": return new Picture(RawContentBytes, Picture.PictureEncoding.JPEG); case "image/gif": return new Picture(RawContentBytes, Picture.PictureEncoding.GIF); case "image/bmp": return new Picture(RawContentBytes, Picture.PictureEncoding.BMP); } } catch { Debug.Print("Could not decode the requested data and create picture"); } return null; } } private byte[] _rawContentBytes; /// <summary> /// Gets the raw binary data of the requested data. /// </summary> public byte[] RawContentBytes { get { return _rawContentBytes; } internal set { _rawContentBytes = value; } } /// <summary> /// The URL requested. /// </summary> public readonly string URL; /// <summary> /// Gets the value of the specified header field or null. /// </summary> /// <param name="name">a string that identifies the name of the header field.</param> /// <returns>The value of the specified header field.</returns> public string GetHeaderField(string name) { return headerFields[name]; } /// <summary> /// Get the header fields that are returned by the server /// </summary> /// <returns>Header fields that are returned by the server</returns> public WebHeaderCollection GetWebHeaderCollection() { return headerFields; } } }
30.55414
138
0.500521
[ "Apache-2.0" ]
martinca-msft/Gadgeteer
NETMF_44/GadgeteerCore/Libraries/Core/WebClient43/HttpResponse.cs
4,797
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EntityCollectionResponse.cs.tt namespace Microsoft.Graph { using System.Collections.Generic; using System.Text.Json.Serialization; /// <summary> /// The type ListItemsCollectionResponse. /// </summary> public class ListItemsCollectionResponse { /// <summary> /// Gets or sets the <see cref="IListItemsCollectionPage"/> value. /// </summary> [JsonPropertyName("value")] public IListItemsCollectionPage Value { get; set; } /// <summary> /// Gets or sets the nextLink string value. /// </summary> [JsonPropertyName("@odata.nextLink")] public string NextLink { get; set; } /// <summary> /// Gets or sets additional data. /// </summary> [JsonExtensionData] public IDictionary<string, object> AdditionalData { get; set; } } }
34.710526
153
0.557998
[ "MIT" ]
Aliases/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/ListItemsCollectionResponse.cs
1,319
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.DocumentDB.V20210315.Outputs { [OutputType] public sealed class IndexesResponse { /// <summary> /// The datatype for which the indexing behavior is applied to. /// </summary> public readonly string? DataType; /// <summary> /// Indicates the type of index. /// </summary> public readonly string? Kind; /// <summary> /// The precision of the index. -1 is maximum precision. /// </summary> public readonly int? Precision; [OutputConstructor] private IndexesResponse( string? dataType, string? kind, int? precision) { DataType = dataType; Kind = kind; Precision = precision; } } }
26.162791
81
0.594667
[ "Apache-2.0" ]
sebtelko/pulumi-azure-native
sdk/dotnet/DocumentDB/V20210315/Outputs/IndexesResponse.cs
1,125
C#
// <auto-generated /> using System; using Infrastructure.EF; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Infrastructure.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20210901201917_AddCompanyIdMigration")] partial class AddCompanyIdMigration { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.8") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Domain.Entities.Action", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<int>("ActionType") .HasColumnType("int"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("StageId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("StageId"); b.ToTable("Actions"); }); modelBuilder.Entity("Domain.Entities.Applicant", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<DateTime>("BirthDate") .HasColumnType("datetime2"); b.Property<string>("CompanyId") .HasColumnType("nvarchar(450)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime2"); b.Property<string>("CvFileInfoId") .HasColumnType("nvarchar(450)"); b.Property<string>("Email") .HasColumnType("nvarchar(max)"); b.Property<double>("Experience") .HasColumnType("float"); b.Property<string>("ExperienceDescription") .HasColumnType("nvarchar(max)"); b.Property<string>("FirstName") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsSelfApplied") .HasColumnType("bit"); b.Property<string>("LastName") .HasColumnType("nvarchar(max)"); b.Property<string>("LinkedInUrl") .HasColumnType("nvarchar(max)"); b.Property<string>("Phone") .HasColumnType("nvarchar(max)"); b.Property<string>("Skills") .HasColumnType("nvarchar(max)"); b.Property<string>("Skype") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("ToBeContacted") .HasColumnType("datetime2"); b.HasKey("Id"); b.HasIndex("CompanyId"); b.HasIndex("CvFileInfoId"); b.ToTable("Applicants"); }); modelBuilder.Entity("Domain.Entities.CandidateComment", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<string>("CandidateId") .HasColumnType("nvarchar(450)"); b.Property<string>("StageId") .HasColumnType("nvarchar(450)"); b.Property<string>("Text") .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.HasKey("Id"); b.HasIndex("CandidateId"); b.HasIndex("StageId"); b.ToTable("CandidateComments"); }); modelBuilder.Entity("Domain.Entities.CandidateReview", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<string>("CandidateId") .HasColumnType("nvarchar(450)"); b.Property<double>("Mark") .HasColumnType("float"); b.Property<string>("ReviewId") .HasColumnType("nvarchar(450)"); b.Property<string>("StageId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("CandidateId"); b.HasIndex("ReviewId"); b.HasIndex("StageId"); b.ToTable("CandidateReviews"); }); modelBuilder.Entity("Domain.Entities.CandidateToStage", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<string>("CandidateId") .HasColumnType("nvarchar(450)"); b.Property<DateTime>("DateAdded") .HasColumnType("datetime2"); b.Property<DateTime?>("DateRemoved") .HasColumnType("datetime2"); b.Property<string>("MoverId") .HasColumnType("nvarchar(450)"); b.Property<string>("StageId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("CandidateId"); b.HasIndex("MoverId"); b.HasIndex("StageId"); b.ToTable("CandidateToStages"); }); modelBuilder.Entity("Domain.Entities.Company", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("Logo") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Companies"); }); modelBuilder.Entity("Domain.Entities.CvParsingJob", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<string>("AWSJobId") .HasColumnType("nvarchar(max)"); b.Property<string>("TriggerId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("TriggerId"); b.ToTable("CvParsingJobs"); }); modelBuilder.Entity("Domain.Entities.EmailToken", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<string>("Token") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId") .IsUnique() .HasFilter("[UserId] IS NOT NULL"); b.ToTable("EmailToken"); }); modelBuilder.Entity("Domain.Entities.FileInfo", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("Path") .HasColumnType("nvarchar(max)"); b.Property<string>("PublicUrl") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("FileInfos"); }); modelBuilder.Entity("Domain.Entities.Interview", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<string>("CandidateId") .HasColumnType("nvarchar(450)"); b.Property<string>("CompanyId") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreatedDate") .HasColumnType("datetime2"); b.Property<double>("Duration") .HasColumnType("float"); b.Property<int>("InterviewType") .HasColumnType("int"); b.Property<string>("MeetingLink") .HasColumnType("nvarchar(max)"); b.Property<int>("MeetingSource") .HasColumnType("int"); b.Property<string>("Note") .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.Property<DateTime>("Scheduled") .HasColumnType("datetime2"); b.Property<string>("Title") .HasColumnType("nvarchar(max)"); b.Property<string>("VacancyId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("CandidateId"); b.HasIndex("VacancyId"); b.ToTable("Interviews"); }); modelBuilder.Entity("Domain.Entities.Pool", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<string>("CompanyId") .HasColumnType("nvarchar(450)"); b.Property<string>("CreatedById") .HasColumnType("nvarchar(450)"); b.Property<DateTime>("DateCreated") .HasColumnType("datetime2"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("CompanyId"); b.HasIndex("CreatedById"); b.ToTable("Pools"); }); modelBuilder.Entity("Domain.Entities.PoolToApplicant", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<string>("ApplicantId") .HasColumnType("nvarchar(450)"); b.Property<string>("PoolId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("ApplicantId"); b.HasIndex("PoolId"); b.ToTable("PoolToApplicants"); }); modelBuilder.Entity("Domain.Entities.Project", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<string>("AdditionalInfo") .HasColumnType("nvarchar(max)"); b.Property<string>("CompanyId") .HasColumnType("nvarchar(450)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime2"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<string>("Logo") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("TeamInfo") .HasColumnType("nvarchar(max)"); b.Property<string>("WebsiteLink") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("CompanyId"); b.ToTable("Projects"); }); modelBuilder.Entity("Domain.Entities.RefreshToken", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<DateTime>("Expires") .HasColumnType("datetime2"); b.Property<string>("Token") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("RefreshTokens"); }); modelBuilder.Entity("Domain.Entities.RegisterPermission", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<string>("CompanyId") .HasColumnType("nvarchar(450)"); b.Property<string>("Email") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("Expires") .HasColumnType("datetime2"); b.HasKey("Id"); b.HasIndex("CompanyId"); b.ToTable("RegisterPermissions"); }); modelBuilder.Entity("Domain.Entities.Review", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Reviews"); }); modelBuilder.Entity("Domain.Entities.ReviewToStage", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<string>("ReviewId") .HasColumnType("nvarchar(450)"); b.Property<string>("StageId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("ReviewId"); b.HasIndex("StageId"); b.ToTable("ReviewToStages"); }); modelBuilder.Entity("Domain.Entities.Role", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<int>("Key") .HasColumnType("int"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Roles"); }); modelBuilder.Entity("Domain.Entities.SkillsParsingJob", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<string>("OutputPath") .HasColumnType("nvarchar(max)"); b.Property<string>("TextPath") .HasColumnType("nvarchar(max)"); b.Property<string>("TriggerId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("TriggerId"); b.ToTable("SkillsParsingJobs"); }); modelBuilder.Entity("Domain.Entities.Stage", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<int>("Index") .HasColumnType("int"); b.Property<bool>("IsReviewable") .HasColumnType("bit"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<int>("Type") .HasColumnType("int"); b.Property<string>("VacancyId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("VacancyId"); b.ToTable("Stages"); }); modelBuilder.Entity("Domain.Entities.User", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<DateTime>("BirthDate") .HasColumnType("datetime2"); b.Property<string>("CompanyId") .HasColumnType("nvarchar(450)"); b.Property<DateTime>("CreationDate") .ValueGeneratedOnAdd() .HasColumnType("datetime2") .HasDefaultValueSql("GETUTCDATE()"); b.Property<string>("Email") .HasColumnType("nvarchar(max)"); b.Property<string>("FirstName") .HasColumnType("nvarchar(max)"); b.Property<string>("InterviewId") .HasColumnType("nvarchar(450)"); b.Property<bool>("IsEmailConfirmed") .HasColumnType("bit"); b.Property<string>("LastName") .HasColumnType("nvarchar(max)"); b.Property<string>("Password") .HasColumnType("nvarchar(max)"); b.Property<string>("PasswordSalt") .HasColumnType("nvarchar(max)"); b.Property<string>("Phone") .HasColumnType("nvarchar(max)"); b.Property<string>("ResetPasswordToken") .HasColumnType("nvarchar(max)"); b.Property<string>("Skype") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("CompanyId"); b.HasIndex("InterviewId"); b.ToTable("Users"); }); modelBuilder.Entity("Domain.Entities.UserFollowedEntity", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<string>("EntityId") .HasColumnType("nvarchar(max)"); b.Property<int>("EntityType") .HasColumnType("int"); b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("UserFollowedEntities"); }); modelBuilder.Entity("Domain.Entities.UserToRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<string>("RoleId") .HasColumnType("nvarchar(450)"); b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.HasIndex("UserId"); b.ToTable("UserToRoles"); }); modelBuilder.Entity("Domain.Entities.UsersToInterview", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<string>("InterviewId") .HasColumnType("nvarchar(450)"); b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("InterviewId"); b.HasIndex("UserId"); b.ToTable("UsersToInterviews"); }); modelBuilder.Entity("Domain.Entities.Vacancy", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<string>("CompanyId") .HasColumnType("nvarchar(450)"); b.Property<DateTime?>("CompletionDate") .HasColumnType("datetime2"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime2"); b.Property<DateTime>("DateOfOpening") .HasColumnType("datetime2"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsHot") .HasColumnType("bit"); b.Property<bool>("IsRemote") .HasColumnType("bit"); b.Property<DateTime>("ModificationDate") .HasColumnType("datetime2"); b.Property<DateTime>("PlannedCompletionDate") .HasColumnType("datetime2"); b.Property<string>("ProjectId") .HasColumnType("nvarchar(450)"); b.Property<string>("Requirements") .HasColumnType("nvarchar(max)"); b.Property<string>("ResponsibleHrId") .HasColumnType("nvarchar(450)"); b.Property<int>("SalaryFrom") .HasColumnType("int"); b.Property<int>("SalaryTo") .HasColumnType("int"); b.Property<string>("Sources") .HasColumnType("nvarchar(max)"); b.Property<int>("Status") .HasColumnType("int"); b.Property<int>("TierFrom") .HasColumnType("int"); b.Property<int>("TierTo") .HasColumnType("int"); b.Property<string>("Title") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("CompanyId"); b.HasIndex("ProjectId"); b.HasIndex("ResponsibleHrId"); b.ToTable("Vacancies"); }); modelBuilder.Entity("Domain.Entities.VacancyCandidate", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<string>("ApplicantId") .HasColumnType("nvarchar(450)"); b.Property<string>("Comments") .HasColumnType("nvarchar(max)"); b.Property<string>("ContactedById") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("DateAdded") .HasColumnType("datetime2"); b.Property<double>("Experience") .HasColumnType("float"); b.Property<DateTime?>("FirstContactDate") .HasColumnType("datetime2"); b.Property<string>("HrWhoAddedId") .HasColumnType("nvarchar(450)"); b.Property<bool>("IsSelfApplied") .HasColumnType("bit"); b.Property<bool>("IsViewed") .HasColumnType("bit"); b.Property<int>("SalaryExpectation") .HasColumnType("int"); b.Property<DateTime?>("SecondContactDate") .HasColumnType("datetime2"); b.Property<DateTime?>("ThirdContactDate") .HasColumnType("datetime2"); b.HasKey("Id"); b.HasIndex("ApplicantId"); b.HasIndex("HrWhoAddedId"); b.HasIndex("Id"); b.ToTable("VacancyCandidates"); }); modelBuilder.Entity("Domain.Entities.Action", b => { b.HasOne("Domain.Entities.Stage", "Stage") .WithMany("Actions") .HasForeignKey("StageId") .HasConstraintName("action_stage_FK") .OnDelete(DeleteBehavior.Restrict); b.Navigation("Stage"); }); modelBuilder.Entity("Domain.Entities.Applicant", b => { b.HasOne("Domain.Entities.Company", "Company") .WithMany("Applicants") .HasForeignKey("CompanyId") .HasConstraintName("applicant_company_FK") .OnDelete(DeleteBehavior.Restrict); b.HasOne("Domain.Entities.FileInfo", "CvFileInfo") .WithMany() .HasForeignKey("CvFileInfoId"); b.Navigation("Company"); b.Navigation("CvFileInfo"); }); modelBuilder.Entity("Domain.Entities.CandidateComment", b => { b.HasOne("Domain.Entities.VacancyCandidate", "Candidate") .WithMany("CandidateComments") .HasForeignKey("CandidateId") .HasConstraintName("candidate_comment_candidate_FK") .OnDelete(DeleteBehavior.Restrict); b.HasOne("Domain.Entities.Stage", "Stage") .WithMany("CandidateComments") .HasForeignKey("StageId") .HasConstraintName("candidate_comment_stage_FK") .OnDelete(DeleteBehavior.Restrict); b.Navigation("Candidate"); b.Navigation("Stage"); }); modelBuilder.Entity("Domain.Entities.CandidateReview", b => { b.HasOne("Domain.Entities.VacancyCandidate", "Candidate") .WithMany("Reviews") .HasForeignKey("CandidateId") .HasConstraintName("candidate_review_candidate_FK") .OnDelete(DeleteBehavior.Restrict); b.HasOne("Domain.Entities.Review", "Review") .WithMany("CandidateReviews") .HasForeignKey("ReviewId") .HasConstraintName("candidate_review_review_FK") .OnDelete(DeleteBehavior.Restrict); b.HasOne("Domain.Entities.Stage", "Stage") .WithMany("Reviews") .HasForeignKey("StageId") .HasConstraintName("candidate_review_stage_FK") .OnDelete(DeleteBehavior.Restrict); b.Navigation("Candidate"); b.Navigation("Review"); b.Navigation("Stage"); }); modelBuilder.Entity("Domain.Entities.CandidateToStage", b => { b.HasOne("Domain.Entities.VacancyCandidate", "Candidate") .WithMany("CandidateToStages") .HasForeignKey("CandidateId") .HasConstraintName("candidate_to_stage_candidate_FK") .OnDelete(DeleteBehavior.Restrict); b.HasOne("Domain.Entities.User", "Mover") .WithMany("MovedCandidateToStages") .HasForeignKey("MoverId") .HasConstraintName("candidate_to_stage_mover_FK") .OnDelete(DeleteBehavior.Restrict); b.HasOne("Domain.Entities.Stage", "Stage") .WithMany("CandidateToStages") .HasForeignKey("StageId") .HasConstraintName("candidate_to_stage_stage_FK") .OnDelete(DeleteBehavior.Restrict); b.Navigation("Candidate"); b.Navigation("Mover"); b.Navigation("Stage"); }); modelBuilder.Entity("Domain.Entities.CvParsingJob", b => { b.HasOne("Domain.Entities.User", "Trigger") .WithMany("CvParsingJobs") .HasForeignKey("TriggerId") .HasConstraintName("cv_parsing_job_user_FK") .OnDelete(DeleteBehavior.Restrict); b.Navigation("Trigger"); }); modelBuilder.Entity("Domain.Entities.EmailToken", b => { b.HasOne("Domain.Entities.User", "User") .WithOne("EmailToken") .HasForeignKey("Domain.Entities.EmailToken", "UserId") .HasConstraintName("email_token__user_FK") .OnDelete(DeleteBehavior.Restrict); b.Navigation("User"); }); modelBuilder.Entity("Domain.Entities.Interview", b => { b.HasOne("Domain.Entities.Applicant", "Candidate") .WithMany() .HasForeignKey("CandidateId"); b.HasOne("Domain.Entities.Vacancy", "Vacancy") .WithMany() .HasForeignKey("VacancyId"); b.Navigation("Candidate"); b.Navigation("Vacancy"); }); modelBuilder.Entity("Domain.Entities.Pool", b => { b.HasOne("Domain.Entities.Company", "Company") .WithMany("Pools") .HasForeignKey("CompanyId") .HasConstraintName("pool_company_FK") .OnDelete(DeleteBehavior.Restrict); b.HasOne("Domain.Entities.User", "CreatedBy") .WithMany() .HasForeignKey("CreatedById"); b.Navigation("Company"); b.Navigation("CreatedBy"); }); modelBuilder.Entity("Domain.Entities.PoolToApplicant", b => { b.HasOne("Domain.Entities.Applicant", "Applicant") .WithMany("ApplicantPools") .HasForeignKey("ApplicantId") .HasConstraintName("pool_applicant__applicant_FK") .OnDelete(DeleteBehavior.Restrict); b.HasOne("Domain.Entities.Pool", "Pool") .WithMany("PoolApplicants") .HasForeignKey("PoolId") .HasConstraintName("pool_applicant__pool_FK") .OnDelete(DeleteBehavior.Restrict); b.Navigation("Applicant"); b.Navigation("Pool"); }); modelBuilder.Entity("Domain.Entities.Project", b => { b.HasOne("Domain.Entities.Company", "Company") .WithMany("Projects") .HasForeignKey("CompanyId") .HasConstraintName("project_company_FK") .OnDelete(DeleteBehavior.Restrict); b.Navigation("Company"); }); modelBuilder.Entity("Domain.Entities.RefreshToken", b => { b.HasOne("Domain.Entities.User", "User") .WithMany("RefreshTokens") .HasForeignKey("UserId") .HasConstraintName("refresh_token__user_FK") .OnDelete(DeleteBehavior.Restrict); b.Navigation("User"); }); modelBuilder.Entity("Domain.Entities.RegisterPermission", b => { b.HasOne("Domain.Entities.Company", "Company") .WithMany() .HasForeignKey("CompanyId") .HasConstraintName("register_permission__company_FK") .OnDelete(DeleteBehavior.Restrict); b.Navigation("Company"); }); modelBuilder.Entity("Domain.Entities.ReviewToStage", b => { b.HasOne("Domain.Entities.Review", "Review") .WithMany("ReviewToStages") .HasForeignKey("ReviewId") .HasConstraintName("review_to_stage_review_FK") .OnDelete(DeleteBehavior.Restrict); b.HasOne("Domain.Entities.Stage", "Stage") .WithMany("ReviewToStages") .HasForeignKey("StageId") .HasConstraintName("review_to_stage_stage_FK") .OnDelete(DeleteBehavior.Restrict); b.Navigation("Review"); b.Navigation("Stage"); }); modelBuilder.Entity("Domain.Entities.SkillsParsingJob", b => { b.HasOne("Domain.Entities.User", "Trigger") .WithMany("SkillsParsingJobs") .HasForeignKey("TriggerId"); b.Navigation("Trigger"); }); modelBuilder.Entity("Domain.Entities.Stage", b => { b.HasOne("Domain.Entities.Vacancy", "Vacancy") .WithMany("Stages") .HasForeignKey("VacancyId") .HasConstraintName("stage_vacancy_FK") .OnDelete(DeleteBehavior.Restrict); b.Navigation("Vacancy"); }); modelBuilder.Entity("Domain.Entities.User", b => { b.HasOne("Domain.Entities.Company", "Company") .WithMany("Recruiters") .HasForeignKey("CompanyId") .HasConstraintName("user_company_FK") .OnDelete(DeleteBehavior.Restrict); b.HasOne("Domain.Entities.Interview", null) .WithMany("UserParticipants") .HasForeignKey("InterviewId"); b.Navigation("Company"); }); modelBuilder.Entity("Domain.Entities.UserFollowedEntity", b => { b.HasOne("Domain.Entities.User", "User") .WithMany() .HasForeignKey("UserId"); b.Navigation("User"); }); modelBuilder.Entity("Domain.Entities.UserToRole", b => { b.HasOne("Domain.Entities.Role", "Role") .WithMany("RoleUsers") .HasForeignKey("RoleId") .HasConstraintName("user_role__role_FK") .OnDelete(DeleteBehavior.Restrict); b.HasOne("Domain.Entities.User", "User") .WithMany("UserRoles") .HasForeignKey("UserId") .HasConstraintName("user_role__user_FK") .OnDelete(DeleteBehavior.Restrict); b.Navigation("Role"); b.Navigation("User"); }); modelBuilder.Entity("Domain.Entities.UsersToInterview", b => { b.HasOne("Domain.Entities.Interview", "Interview") .WithMany() .HasForeignKey("InterviewId"); b.HasOne("Domain.Entities.User", "User") .WithMany() .HasForeignKey("UserId"); b.Navigation("Interview"); b.Navigation("User"); }); modelBuilder.Entity("Domain.Entities.Vacancy", b => { b.HasOne("Domain.Entities.Company", "Company") .WithMany("Vacancies") .HasForeignKey("CompanyId") .HasConstraintName("vacancy_company_FK") .OnDelete(DeleteBehavior.Restrict); b.HasOne("Domain.Entities.Project", "Project") .WithMany("Vacancies") .HasForeignKey("ProjectId") .HasConstraintName("vacancy_project_FK") .OnDelete(DeleteBehavior.Restrict); b.HasOne("Domain.Entities.User", "ResponsibleHr") .WithMany("Vacancies") .HasForeignKey("ResponsibleHrId") .HasConstraintName("vacancy_user_FK") .OnDelete(DeleteBehavior.Restrict); b.Navigation("Company"); b.Navigation("Project"); b.Navigation("ResponsibleHr"); }); modelBuilder.Entity("Domain.Entities.VacancyCandidate", b => { b.HasOne("Domain.Entities.Applicant", "Applicant") .WithMany("Candidates") .HasForeignKey("ApplicantId") .HasConstraintName("candidate_applicant_FK") .OnDelete(DeleteBehavior.Restrict); b.HasOne("Domain.Entities.User", "HrWhoAdded") .WithMany("AddedCandidates") .HasForeignKey("HrWhoAddedId") .HasConstraintName("candidate_hr_who_added_FK") .OnDelete(DeleteBehavior.Restrict); b.Navigation("Applicant"); b.Navigation("HrWhoAdded"); }); modelBuilder.Entity("Domain.Entities.Applicant", b => { b.Navigation("ApplicantPools"); b.Navigation("Candidates"); }); modelBuilder.Entity("Domain.Entities.Company", b => { b.Navigation("Applicants"); b.Navigation("Pools"); b.Navigation("Projects"); b.Navigation("Recruiters"); b.Navigation("Vacancies"); }); modelBuilder.Entity("Domain.Entities.Interview", b => { b.Navigation("UserParticipants"); }); modelBuilder.Entity("Domain.Entities.Pool", b => { b.Navigation("PoolApplicants"); }); modelBuilder.Entity("Domain.Entities.Project", b => { b.Navigation("Vacancies"); }); modelBuilder.Entity("Domain.Entities.Review", b => { b.Navigation("CandidateReviews"); b.Navigation("ReviewToStages"); }); modelBuilder.Entity("Domain.Entities.Role", b => { b.Navigation("RoleUsers"); }); modelBuilder.Entity("Domain.Entities.Stage", b => { b.Navigation("Actions"); b.Navigation("CandidateComments"); b.Navigation("CandidateToStages"); b.Navigation("Reviews"); b.Navigation("ReviewToStages"); }); modelBuilder.Entity("Domain.Entities.User", b => { b.Navigation("AddedCandidates"); b.Navigation("CvParsingJobs"); b.Navigation("EmailToken"); b.Navigation("MovedCandidateToStages"); b.Navigation("RefreshTokens"); b.Navigation("SkillsParsingJobs"); b.Navigation("UserRoles"); b.Navigation("Vacancies"); }); modelBuilder.Entity("Domain.Entities.Vacancy", b => { b.Navigation("Stages"); }); modelBuilder.Entity("Domain.Entities.VacancyCandidate", b => { b.Navigation("CandidateComments"); b.Navigation("CandidateToStages"); b.Navigation("Reviews"); }); #pragma warning restore 612, 618 } } }
34.68745
117
0.435175
[ "MIT" ]
BinaryStudioAcademy/bsa-2021-scout
backend/src/Infrastructure/Migrations/20210901201917_AddCompanyIdMigration.Designer.cs
43,396
C#
using Olympic.RazorConverter.Razor.DOM; using Olympic.RazorConverter.WebForms.DOM; namespace Olympic.RazorConverter.Razor.Converters { using System.ComponentModel.Composition; using Olympic.RazorConverter.Razor.DOM; using Olympic.RazorConverter.WebForms.DOM; [Export(typeof(IWebFormsConverter<IRazorNode>))] public class WebFormsToRazorConverter : IWebFormsConverter<IRazorNode> { private IRazorNodeConverterProvider NodeConverterProvider { get; set; } [ImportingConstructor] public WebFormsToRazorConverter(IRazorNodeConverterProvider converterProvider) { NodeConverterProvider = converterProvider; } public IDocument<IRazorNode> Convert(IDocument<IWebFormsNode> srcDoc) { var rootNode = new RazorNode(); foreach (var srcNode in srcDoc.RootNode.Children) { foreach (var converter in NodeConverterProvider.NodeConverters) { if (converter.CanConvertNode(srcNode)) { if (srcNode.Type == NodeType.Directive && srcNode.Attributes.ContainsKey("namespace")) { var i = 1; } foreach (var dstNode in converter.ConvertNode(srcNode)) { rootNode.Children.Add(dstNode); } } } } return new Document<IRazorNode>(rootNode); } } }
31.423077
110
0.556916
[ "MIT" ]
olympicsoftware/razor-converter
Olympic.RazorConverter/Razor/Converters/WebFormsToRazorConverter.cs
1,636
C#
#if UNITY_EDITOR using EditorExtend; using Map; using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; namespace Map { [ExecuteInEditMode] public class TeleportRoot : MapEntityRoot { #region 私有属性 /// <summary> /// json数据 /// </summary> private EditorTeleport[] m_EditorTeleport; /// <summary> /// 传送门显示的名称 /// </summary> private string[] m_TeleportShowNames; /// <summary> /// 创建传送门携程 /// </summary> private IEnumerator m_CreateTeleportEnumerator; #endregion #region 公开属性 /// <summary> /// 当前包括的配置数据 /// </summary> public List<TeleportVO> m_TeleportList; /// <summary> /// key为chanel id /// </summary> //public Dictionary<int, int> m_SelectLocation; public List<TeleportInfo> m_SelectLocation; [System.Serializable] public class TeleportInfo { /// <summary> /// 选中的频道Id /// </summary> public int m_ChanelId; /// <summary> /// 选中的序列id /// </summary> public int m_SelectIndex; public TeleportInfo(int channelId,int selectIndex) { m_ChanelId = channelId; m_SelectIndex = selectIndex; } } #endregion #region 私有方法 private void OnDisable() { m_SelectLocation = null; } #endregion #region 公开方法 /// <summary> /// 获取传送点信息 /// </summary> /// <param name="channelId"></param> /// <returns></returns> public TeleportInfo GetTeleportInfo(int channelId) { if(m_SelectLocation == null || m_SelectLocation.Count<=0) { return null; } for(int iSelect = 0;iSelect<m_SelectLocation.Count;iSelect++) { if(m_SelectLocation[iSelect].m_ChanelId == channelId) { return m_SelectLocation[iSelect]; } } return null; } public void Init(EditorTeleport[] teleports, GamingMapArea area) { m_GamingMapArea = area; m_EditorTeleport = teleports; GetTeleportList(); GetTeleportShowNames(); //m_SelectLocation = new Dictionary<int, int>(); m_SelectLocation = new List<TeleportInfo>(); if (m_EditorTeleport != null && m_EditorTeleport.Length > 0) { for (int iTeleport = 0; m_EditorTeleport != null && iTeleport < m_EditorTeleport.Length; iTeleport++) { EditorChanel[] chanelList = m_EditorTeleport[iTeleport].chanelList; if (chanelList != null && chanelList.Length > 0) { for (int iChanel = 0; iChanel < chanelList.Length; iChanel++) { EditorChanel chanel = chanelList[iChanel]; TeleportChanelVO chanelVO = ConfigVO<TeleportChanelVO>.Instance.GetData(chanel.chanelId); if (chanelVO != null) { EditorLocation[] locations = GamingMap.GetEditorLocations(chanelVO.EndGamingMap, chanelVO.EndGamingMapArea); if (locations != null && locations.Length > 0) { List<EditorLocation> locationList = new List<EditorLocation>(); for (int iLocation = 0; iLocation < locations.Length; iLocation++) { EditorLocation location = locations[iLocation]; if (location.locationType == (int)LocationType.TeleportIn) { locationList.Add(location); } } for (int iLocation = 0; iLocation < locationList.Count; iLocation++) { if (locationList[iLocation].locationId == chanel.eLocation) { m_SelectLocation.Add(new TeleportInfo(chanel.chanelId, iLocation)); break; } } } } } } } } } public List<TeleportVO> GetTeleportList() { if (m_GamingMapArea == null) { return null; } m_TeleportList = m_GamingMapArea.GetTeleportList(); return m_TeleportList; } public string[] GetTeleportShowNames() { if (m_TeleportShowNames == null || m_TeleportShowNames.Length <= 0) { if (m_TeleportList != null && m_TeleportList.Count > 0) { m_TeleportShowNames = new string[m_TeleportList.Count]; for (int iTeleport = 0; iTeleport < m_TeleportList.Count; iTeleport++) { m_TeleportShowNames[iTeleport] = m_TeleportList[iTeleport].ID.ToString(); } } } return m_TeleportShowNames; } public IEnumerator OnUpdate(GamingMapArea mapArea) { m_GamingMapArea = mapArea; GetTeleportList(); yield return null; if (m_CreateTeleportEnumerator != null) { while (m_CreateTeleportEnumerator.MoveNext()) { yield return null; } m_CreateTeleportEnumerator = null; m_EditorTeleport = null; } yield return null; } #endregion #region 基类方法 public override void BeginExport() { base.BeginExport(); } public override void Clear(bool needDestroy = true) { base.Clear(needDestroy); } #endregion } } #endif
27.456311
116
0.536598
[ "Apache-2.0" ]
fqkw6/RewriteFrame
other/mapScritps/MapData/TeleportRoot.cs
5,786
C#
using System.Collections.Generic; namespace dotnet_new2 { public class MenuCategory : MenuNode { public IList<MenuNode> Children { get; set; } } }
16.9
53
0.668639
[ "MIT" ]
DamianEdwards/dotnet-new2
src/dotnet-new2/MenuCategory.cs
171
C#
using System.Reactive.Concurrency; namespace PicasaDatabaseReader.Core.Scheduling { public sealed class UISchedulerProvider : SchedulerProvider, IUISchedulerProvider { public IScheduler CurrentThread => Scheduler.CurrentThread; public IScheduler Immediate => Scheduler.Immediate; public IScheduler NewThread => NewThreadScheduler.Default; public IScheduler TaskPool => TaskPoolScheduler.Default; } }
29.866667
85
0.754464
[ "MIT" ]
StanleyGoldman/Picasa-database-reader
PicasaDatabaseReader.Core/Scheduling/UISchedulerProvider.cs
450
C#
using SortingPagination.DataAccess.Entities; using SortingPagination.Models; using System.Threading.Tasks; namespace SortingPagination.Services { public interface IOrderService { Task<ListResult<Order>> GetAsync(int pageIndex, int itemsPerPage, string orderBy); } }
26.090909
90
0.773519
[ "MIT" ]
marcominerva/OrderPagination
SortingPagination/Services/IOrderService.cs
289
C#
using System; class Student : Human { public int ClassNumber { get; private set; } public string Comment { get; set; } public Student(string firstName, string middleName, string lastName) : base(firstName, middleName, lastName) { } }
17.8
72
0.655431
[ "MIT" ]
hackohackob/TelerikAcademy
C# OOP/OOPPrinciples/School/Student.cs
269
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CodeGeneration { /// <summary> /// A generator used for creating or modifying member declarations in source. /// </summary> internal static class CodeGenerator { /// <summary> /// Annotation placed on generated syntax. /// </summary> public static readonly SyntaxAnnotation Annotation = new(nameof(CodeGenerator)); private static ICodeGenerationService GetCodeGenerationService( Workspace workspace, string language ) => workspace.Services .GetLanguageServices(language) .GetRequiredService<ICodeGenerationService>(); /// <summary> /// Returns a newly created event declaration node from the provided event. /// </summary> public static SyntaxNode CreateEventDeclaration( IEventSymbol @event, Workspace workspace, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null ) => GetCodeGenerationService(workspace, @event.Language) .CreateEventDeclaration(@event, destination, options); /// <summary> /// Returns a newly created field declaration node from the provided field. /// </summary> public static SyntaxNode CreateFieldDeclaration( IFieldSymbol field, Workspace workspace, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null ) => GetCodeGenerationService(workspace, field.Language) .CreateFieldDeclaration(field, destination, options); /// <summary> /// Returns a newly created method declaration node from the provided method. /// </summary> public static SyntaxNode CreateMethodDeclaration( IMethodSymbol method, Workspace workspace, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null ) => GetCodeGenerationService(workspace, method.Language) .CreateMethodDeclaration(method, destination, options); /// <summary> /// Returns a newly created property declaration node from the provided property. /// </summary> public static SyntaxNode CreatePropertyDeclaration( IPropertySymbol property, Workspace workspace, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null ) => GetCodeGenerationService(workspace, property.Language) .CreatePropertyDeclaration(property, destination, options); /// <summary> /// Returns a newly created named type declaration node from the provided named type. /// </summary> public static SyntaxNode CreateNamedTypeDeclaration( INamedTypeSymbol namedType, Workspace workspace, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null ) => GetCodeGenerationService(workspace, namedType.Language) .CreateNamedTypeDeclaration(namedType, destination, options); /// <summary> /// Returns a newly created namespace declaration node from the provided namespace. /// </summary> public static SyntaxNode CreateNamespaceDeclaration( INamespaceSymbol @namespace, Workspace workspace, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null ) => GetCodeGenerationService(workspace, @namespace.Language) .CreateNamespaceDeclaration(@namespace, destination, options); /// <summary> /// Create a new declaration node with an event declaration of the same signature as the specified symbol added to it. /// </summary> public static TDeclarationNode AddEventDeclaration<TDeclarationNode>( TDeclarationNode destination, IEventSymbol @event, Workspace workspace, CodeGenerationOptions? options = null ) where TDeclarationNode : SyntaxNode => GetCodeGenerationService(workspace, destination.Language) .AddEvent(destination, @event, options); /// <summary> /// Create a new declaration node with a field declaration of the same signature as the specified symbol added to it. /// </summary> public static TDeclarationNode AddFieldDeclaration<TDeclarationNode>( TDeclarationNode destination, IFieldSymbol field, Workspace workspace, CodeGenerationOptions? options = null ) where TDeclarationNode : SyntaxNode => GetCodeGenerationService(workspace, destination.Language) .AddField(destination, field, options); /// <summary> /// Create a new declaration node with a method declaration of the same signature as the specified symbol added to it. /// </summary> public static TDeclarationNode AddMethodDeclaration<TDeclarationNode>( TDeclarationNode destination, IMethodSymbol method, Workspace workspace, CodeGenerationOptions? options = null ) where TDeclarationNode : SyntaxNode => GetCodeGenerationService(workspace, destination.Language) .AddMethod(destination, method, options); /// <summary> /// Create a new declaration node with a property declaration of the same signature as the specified symbol added to it. /// </summary> public static TDeclarationNode AddPropertyDeclaration<TDeclarationNode>( TDeclarationNode destination, IPropertySymbol property, Workspace workspace, CodeGenerationOptions? options = null ) where TDeclarationNode : SyntaxNode => GetCodeGenerationService(workspace, destination.Language) .AddProperty(destination, property, options); /// <summary> /// Create a new declaration node with a named type declaration of the same signature as the specified symbol added to it. /// </summary> public static TDeclarationNode AddNamedTypeDeclaration<TDeclarationNode>( TDeclarationNode destination, INamedTypeSymbol namedType, Workspace workspace, CodeGenerationOptions? options = null ) where TDeclarationNode : SyntaxNode => GetCodeGenerationService(workspace, destination.Language) .AddNamedType(destination, namedType, options); /// <summary> /// Create a new declaration node with multiple member declarations of the same signatures as the specified symbols added to it. /// </summary> public static TDeclarationNode AddMemberDeclarations<TDeclarationNode>( TDeclarationNode destination, IEnumerable<ISymbol> members, Workspace workspace, CodeGenerationOptions? options = null ) where TDeclarationNode : SyntaxNode => GetCodeGenerationService(workspace, destination.Language) .AddMembers(destination, members, options); /// <summary> /// Create a new declaration node with one or more parameter declarations of the same signature as the specified symbols added to it. /// </summary> public static TDeclarationNode AddParameterDeclarations<TDeclarationNode>( TDeclarationNode destinationMember, IEnumerable<IParameterSymbol> parameters, Workspace workspace, CodeGenerationOptions? options = null ) where TDeclarationNode : SyntaxNode => GetCodeGenerationService(workspace, destinationMember.Language) .AddParameters(destinationMember, parameters, options); /// <summary> /// Create a new declaration node with the specified attributes added to it. /// </summary> public static TDeclarationNode AddAttributes<TDeclarationNode>( TDeclarationNode destination, Workspace workspace, IEnumerable<AttributeData> attributes, SyntaxToken? target = null, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default ) where TDeclarationNode : SyntaxNode => GetCodeGenerationService(workspace, destination.Language) .AddAttributes( destination, attributes, target, options ?? CodeGenerationOptions.Default, cancellationToken ); /// <summary> /// Removes the specified attribute node from the given declaration node. /// </summary> public static TDeclarationNode RemoveAttribute<TDeclarationNode>( TDeclarationNode destination, Workspace workspace, AttributeData attributeToRemove, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default ) where TDeclarationNode : SyntaxNode => GetCodeGenerationService(workspace, destination.Language) .RemoveAttribute( destination, attributeToRemove, options ?? CodeGenerationOptions.Default, cancellationToken ); /// <summary> /// Removes the specified attribute node from the given declaration node. /// </summary> public static TDeclarationNode RemoveAttribute<TDeclarationNode>( TDeclarationNode destination, Workspace workspace, SyntaxNode attributeToRemove, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default ) where TDeclarationNode : SyntaxNode => GetCodeGenerationService(workspace, destination.Language) .RemoveAttribute( destination, attributeToRemove, options ?? CodeGenerationOptions.Default, cancellationToken ); public static TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>( TDeclarationNode destination, Workspace workspace, IEnumerable<SyntaxToken> newModifiers, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default ) where TDeclarationNode : SyntaxNode => GetCodeGenerationService(workspace, destination.Language) .UpdateDeclarationModifiers( destination, newModifiers, options ?? new CodeGenerationOptions(reuseSyntax: true), cancellationToken ); public static TDeclarationNode UpdateDeclarationAccessibility<TDeclarationNode>( TDeclarationNode destination, Workspace workspace, Accessibility newAccessibility, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default ) where TDeclarationNode : SyntaxNode => GetCodeGenerationService(workspace, destination.Language) .UpdateDeclarationAccessibility( destination, newAccessibility, options ?? new CodeGenerationOptions(reuseSyntax: true), cancellationToken ); public static TDeclarationNode UpdateDeclarationType<TDeclarationNode>( TDeclarationNode destination, Workspace workspace, ITypeSymbol newType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default ) where TDeclarationNode : SyntaxNode => GetCodeGenerationService(workspace, destination.Language) .UpdateDeclarationType( destination, newType, options ?? new CodeGenerationOptions(reuseSyntax: true), cancellationToken ); public static TDeclarationNode UpdateDeclarationMembers<TDeclarationNode>( TDeclarationNode destination, Workspace workspace, IList<ISymbol> newMembers, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default ) where TDeclarationNode : SyntaxNode => GetCodeGenerationService(workspace, destination.Language) .UpdateDeclarationMembers( destination, newMembers, options ?? new CodeGenerationOptions(reuseSyntax: true), cancellationToken ); /// <summary> /// Create a new declaration node with one or more statements added to its body. /// </summary> public static TDeclarationNode AddStatements<TDeclarationNode>( TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, Workspace workspace, CodeGenerationOptions? options = null ) where TDeclarationNode : SyntaxNode => GetCodeGenerationService(workspace, destinationMember.Language) .AddStatements(destinationMember, statements, options); /// <summary> /// Create a new solution where the declaration of the destination symbol has an additional event of the same signature as the specified event symbol. /// Returns the document in the new solution where the destination symbol is declared. /// </summary> public static Task<Document> AddEventDeclarationAsync( Solution solution, INamedTypeSymbol destination, IEventSymbol @event, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default ) => GetCodeGenerationService(solution.Workspace, destination.Language) .AddEventAsync(solution, destination, @event, options, cancellationToken); /// <summary> /// Create a new solution where the declaration of the destination symbol has an additional field of the same signature as the specified field symbol. /// Returns the document in the new solution where the destination symbol is declared. /// </summary> public static Task<Document> AddFieldDeclarationAsync( Solution solution, INamedTypeSymbol destination, IFieldSymbol field, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default ) => GetCodeGenerationService(solution.Workspace, destination.Language) .AddFieldAsync(solution, destination, field, options, cancellationToken); /// <summary> /// Create a new solution where the declaration of the destination symbol has an additional method of the same signature as the specified method symbol. /// Returns the document in the new solution where the destination symbol is declared. /// </summary> public static Task<Document> AddMethodDeclarationAsync( Solution solution, INamedTypeSymbol destination, IMethodSymbol method, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default ) => GetCodeGenerationService(solution.Workspace, destination.Language) .AddMethodAsync(solution, destination, method, options, cancellationToken); /// <summary> /// Create a new solution where the declaration of the destination symbol has an additional property of the same signature as the specified property symbol. /// Returns the document in the new solution where the destination symbol is declared. /// </summary> public static Task<Document> AddPropertyDeclarationAsync( Solution solution, INamedTypeSymbol destination, IPropertySymbol property, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default ) => GetCodeGenerationService(solution.Workspace, destination.Language) .AddPropertyAsync(solution, destination, property, options, cancellationToken); /// <summary> /// Create a new solution where the declaration of the destination symbol has an additional named type of the same signature as the specified named type symbol. /// Returns the document in the new solution where the destination symbol is declared. /// </summary> public static Task<Document> AddNamedTypeDeclarationAsync( Solution solution, INamedTypeSymbol destination, INamedTypeSymbol namedType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default ) => GetCodeGenerationService(solution.Workspace, destination.Language) .AddNamedTypeAsync(solution, destination, namedType, options, cancellationToken); /// <summary> /// Create a new solution where the declaration of the destination symbol has an additional named type of the same signature as the specified named type symbol. /// Returns the document in the new solution where the destination symbol is declared. /// </summary> public static Task<Document> AddNamedTypeDeclarationAsync( Solution solution, INamespaceSymbol destination, INamedTypeSymbol namedType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default ) => GetCodeGenerationService(solution.Workspace, destination.Language) .AddNamedTypeAsync(solution, destination, namedType, options, cancellationToken); /// <summary> /// Create a new solution where the declaration of the destination symbol has an additional namespace of the same signature as the specified namespace symbol. /// Returns the document in the new solution where the destination symbol is declared. /// </summary> public static Task<Document> AddNamespaceDeclarationAsync( Solution solution, INamespaceSymbol destination, INamespaceSymbol @namespace, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default ) => GetCodeGenerationService(solution.Workspace, destination.Language) .AddNamespaceAsync(solution, destination, @namespace, options, cancellationToken); /// <summary> /// Create a new solution where the declaration of the destination symbol has an additional namespace or type of the same signature as the specified namespace or type symbol. /// Returns the document in the new solution where the destination symbol is declared. /// </summary> public static Task<Document> AddNamespaceOrTypeDeclarationAsync( Solution solution, INamespaceSymbol destination, INamespaceOrTypeSymbol namespaceOrType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default ) => GetCodeGenerationService(solution.Workspace, destination.Language) .AddNamespaceOrTypeAsync( solution, destination, namespaceOrType, options, cancellationToken ); /// <summary> /// Create a new solution where the declaration of the destination symbol has additional members of the same signature as the specified member symbols. /// Returns the document in the new solution where the destination symbol is declared. /// </summary> public static Task<Document> AddMemberDeclarationsAsync( Solution solution, INamedTypeSymbol destination, IEnumerable<ISymbol> members, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default ) => GetCodeGenerationService(solution.Workspace, destination.Language) .AddMembersAsync(solution, destination, members, options, cancellationToken); /// <summary> /// Returns <c>true</c> if additional declarations can be added to the destination symbol's declaration. /// </summary> public static bool CanAdd( Solution solution, ISymbol destination, CancellationToken cancellationToken = default ) => GetCodeGenerationService(solution.Workspace, destination.Language) .CanAddTo(destination, solution, cancellationToken); } }
47.842451
182
0.644941
[ "MIT" ]
belav/roslyn
src/Workspaces/Core/Portable/CodeGeneration/CodeGenerator.cs
21,866
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the email-2010-12-01.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.SimpleEmail.Model { /// <summary> /// Contains information associated with an Amazon CloudWatch event destination to which /// email sending events are published. /// /// /// <para> /// Event destinations, such as Amazon CloudWatch, are associated with configuration sets, /// which enable you to publish email sending events. For information about using configuration /// sets, see the <a href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/monitor-sending-activity.html">Amazon /// SES Developer Guide</a>. /// </para> /// </summary> public partial class CloudWatchDestination { private List<CloudWatchDimensionConfiguration> _dimensionConfigurations = new List<CloudWatchDimensionConfiguration>(); /// <summary> /// Gets and sets the property DimensionConfigurations. /// <para> /// A list of dimensions upon which to categorize your emails when you publish email sending /// events to Amazon CloudWatch. /// </para> /// </summary> [AWSProperty(Required=true)] public List<CloudWatchDimensionConfiguration> DimensionConfigurations { get { return this._dimensionConfigurations; } set { this._dimensionConfigurations = value; } } // Check to see if DimensionConfigurations property is set internal bool IsSetDimensionConfigurations() { return this._dimensionConfigurations != null && this._dimensionConfigurations.Count > 0; } } }
36.686567
127
0.689585
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/SimpleEmail/Generated/Model/CloudWatchDestination.cs
2,458
C#
using Comet.Blazor.Components; namespace Comet.Blazor.Handlers { internal class ButtonHandler : BlazorHandler<Button, BButton> { public static readonly PropertyMapper<Button> Mapper = new PropertyMapper<Button> { { nameof(Button.Text), MapTextProperty }, { nameof(Button.OnClick), MapOnClickProperty } }; public ButtonHandler() : base(Mapper) { } public static void MapOnClickProperty(IViewHandler viewHandler, Button virtualView) { var nativeView = (BButton)viewHandler.NativeView; nativeView.OnClick = virtualView.OnClick; } public static void MapTextProperty(IViewHandler viewHandler, Button virtualView) { var nativeView = (BButton)viewHandler.NativeView; nativeView.Text = virtualView.Text; } } }
27.666667
91
0.616648
[ "MIT" ]
PieEatingNinjas/Comet
src/Comet.Blazor/Handlers/ButtonHandler.cs
915
C#
using Microsoft.AspNetCore.Mvc; using Volo.Abp.AspNetCore.Mvc; namespace DevExtremeAngular.Controllers { public class HomeController : AbpController { public ActionResult Index() { return Redirect("~/swagger"); } } }
19.071429
47
0.640449
[ "MIT" ]
271943794/abp-samples
DevExtreme-Angular/aspnet-core/src/DevExtremeAngular.HttpApi.Host/Controllers/HomeController.cs
269
C#
// Straight Pointer Renderer|PointerRenderers|10020 namespace VRTK { using UnityEngine; /// <summary> /// The Straight Pointer Renderer emits a coloured beam from the end of the object it is attached to and simulates a laser beam. /// </summary> /// <remarks> /// It can be useful for pointing to objects within a scene and it can also determine the object it is pointing at and the distance the object is from the controller the beam is being emitted from. /// </remarks> /// <example> /// `VRTK/Examples/003_Controller_SimplePointer` shows the simple pointer in action and code examples of how the events are utilised and listened to can be viewed in the script `VRTK/Examples/Resources/Scripts/VRTK_ControllerPointerEvents_ListenerExample.cs` /// </example> [AddComponentMenu("VRTK/Scripts/Pointers/Pointer Renderers/VRTK_StraightPointerRenderer")] public class VRTK_StraightPointerRenderer : VRTK_BasePointerRenderer { [Header("Straight Pointer Appearance Settings")] [Tooltip("The maximum length the pointer tracer can reach.")] public float maximumLength = 100f; [Tooltip("The scale factor to scale the pointer tracer object by.")] public float scaleFactor = 0.002f; [Tooltip("The scale multiplier to scale the pointer cursor object by in relation to the `Scale Factor`.")] public float cursorScaleMultiplier = 25f; [Tooltip("The cursor will be rotated to match the angle of the target surface if this is true, if it is false then the pointer cursor will always be horizontal.")] public bool cursorMatchTargetRotation = false; [Tooltip("Rescale the cursor proportionally to the distance from the tracer origin.")] public bool cursorDistanceRescale = false; [Tooltip("The maximum scale the cursor is allowed to reach. This is only used when rescaling the cursor proportionally to the distance from the tracer origin.")] public Vector3 maximumCursorScale = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); [Header("Straight Pointer Custom Appearance Settings")] [Tooltip("A custom game object to use as the appearance for the pointer tracer. If this is empty then a Box primitive will be created and used.")] public GameObject customTracer; [Tooltip("A custom game object to use as the appearance for the pointer cursor. If this is empty then a Sphere primitive will be created and used.")] public GameObject customCursor; protected GameObject actualContainer; protected GameObject actualTracer; protected GameObject actualCursor; protected Vector3 cursorOriginalScale = Vector3.one; /// <summary> /// The UpdateRenderer method is used to run an Update routine on the pointer. /// </summary> public override void UpdateRenderer() { if ((controllingPointer != null && controllingPointer.IsPointerActive()) || IsVisible()) { float tracerLength = CastRayForward(); SetPointerAppearance(tracerLength); MakeRenderersVisible(); } base.UpdateRenderer(); } /// <summary> /// The GetPointerObjects returns an array of the auto generated GameObjects associated with the pointer. /// </summary> /// <returns>An array of pointer auto generated GameObjects.</returns> public override GameObject[] GetPointerObjects() { return new GameObject[] { actualContainer, actualCursor, actualTracer }; } protected override void ToggleRenderer(bool pointerState, bool actualState) { ToggleElement(actualTracer, pointerState, actualState, tracerVisibility, ref tracerVisible); ToggleElement(actualCursor, pointerState, actualState, cursorVisibility, ref cursorVisible); } protected override void CreatePointerObjects() { actualContainer = new GameObject(VRTK_SharedMethods.GenerateVRTKObjectName(true, gameObject.name, "StraightPointerRenderer_Container")); actualContainer.transform.SetParent(pointerOriginTransformFollowGameObject.transform); actualContainer.transform.localPosition = Vector3.zero; actualContainer.transform.localRotation = Quaternion.identity; actualContainer.transform.localScale = Vector3.one; VRTK_PlayerObject.SetPlayerObject(actualContainer, VRTK_PlayerObject.ObjectTypes.Pointer); CreateTracer(); CreateCursor(); Toggle(false, false); if (controllingPointer != null) { controllingPointer.ResetActivationTimer(true); controllingPointer.ResetSelectionTimer(true); } } protected override void DestroyPointerObjects() { if (actualContainer != null) { Destroy(actualContainer); } } protected override void ChangeMaterial(Color givenColor) { base.ChangeMaterial(givenColor); ChangeMaterialColor(actualTracer, givenColor); ChangeMaterialColor(actualCursor, givenColor); } protected override void UpdateObjectInteractor() { base.UpdateObjectInteractor(); //if the object interactor is too far from the pointer tip then set it to the pointer tip position to prevent glitching. if (objectInteractor != null && actualCursor != null && Vector3.Distance(objectInteractor.transform.position, actualCursor.transform.position) > 0f) { objectInteractor.transform.position = actualCursor.transform.position; } } protected virtual void CreateTracer() { if (customTracer != null) { actualTracer = Instantiate(customTracer); } else { actualTracer = GameObject.CreatePrimitive(PrimitiveType.Cube); actualTracer.GetComponent<BoxCollider>().isTrigger = true; actualTracer.AddComponent<Rigidbody>().isKinematic = true; actualTracer.layer = LayerMask.NameToLayer("Ignore Raycast"); SetupMaterialRenderer(actualTracer); } actualTracer.transform.name = VRTK_SharedMethods.GenerateVRTKObjectName(true, gameObject.name, "StraightPointerRenderer_Tracer"); actualTracer.transform.SetParent(actualContainer.transform); VRTK_PlayerObject.SetPlayerObject(actualTracer, VRTK_PlayerObject.ObjectTypes.Pointer); } protected virtual void CreateCursor() { if (customCursor != null) { actualCursor = Instantiate(customCursor); } else { actualCursor = GameObject.CreatePrimitive(PrimitiveType.Sphere); actualCursor.transform.localScale = Vector3.one * (scaleFactor * cursorScaleMultiplier); actualCursor.GetComponent<Collider>().isTrigger = true; actualCursor.AddComponent<Rigidbody>().isKinematic = true; actualCursor.layer = LayerMask.NameToLayer("Ignore Raycast"); SetupMaterialRenderer(actualCursor); } cursorOriginalScale = actualCursor.transform.localScale; actualCursor.transform.name = VRTK_SharedMethods.GenerateVRTKObjectName(true, gameObject.name, "StraightPointerRenderer_Cursor"); actualCursor.transform.SetParent(actualContainer.transform); VRTK_PlayerObject.SetPlayerObject(actualCursor, VRTK_PlayerObject.ObjectTypes.Pointer); } protected virtual void CheckRayMiss(bool rayHit, RaycastHit pointerCollidedWith) { if (!rayHit || (destinationHit.collider != null && destinationHit.collider != pointerCollidedWith.collider)) { if (destinationHit.collider != null) { PointerExit(destinationHit); } destinationHit = new RaycastHit(); ChangeColor(invalidCollisionColor); } } protected virtual void CheckRayHit(bool rayHit, RaycastHit pointerCollidedWith) { if (rayHit) { PointerEnter(pointerCollidedWith); destinationHit = pointerCollidedWith; ChangeColor(validCollisionColor); } } protected virtual float CastRayForward() { Transform origin = GetOrigin(); Ray pointerRaycast = new Ray(origin.position, origin.forward); RaycastHit pointerCollidedWith; #pragma warning disable 0618 bool rayHit = VRTK_CustomRaycast.Raycast(customRaycast, pointerRaycast, out pointerCollidedWith, layersToIgnore, maximumLength); #pragma warning restore 0618 CheckRayMiss(rayHit, pointerCollidedWith); CheckRayHit(rayHit, pointerCollidedWith); float actualLength = maximumLength; if (rayHit && pointerCollidedWith.distance < maximumLength) { actualLength = pointerCollidedWith.distance; } return OverrideBeamLength(actualLength); } protected virtual void SetPointerAppearance(float tracerLength) { if (actualContainer != null) { //if the additional decimal isn't added then the beam position glitches float beamPosition = tracerLength / (2f + BEAM_ADJUST_OFFSET); actualTracer.transform.localScale = new Vector3(scaleFactor, scaleFactor, tracerLength); actualTracer.transform.localPosition = Vector3.forward * beamPosition; actualCursor.transform.localScale = Vector3.one * (scaleFactor * cursorScaleMultiplier); actualCursor.transform.localPosition = new Vector3(0f, 0f, tracerLength); Transform origin = GetOrigin(); float objectInteractorScaleIncrease = 1.05f; ScaleObjectInteractor(actualCursor.transform.lossyScale * objectInteractorScaleIncrease); if (destinationHit.transform != null) { if (cursorMatchTargetRotation) { actualCursor.transform.forward = -destinationHit.normal; } if (cursorDistanceRescale) { float collisionDistance = Vector3.Distance(destinationHit.point, origin.position); actualCursor.transform.localScale = Vector3.Min(cursorOriginalScale * collisionDistance, maximumCursorScale); } } else { if (cursorMatchTargetRotation) { actualCursor.transform.forward = origin.forward; } if (cursorDistanceRescale) { actualCursor.transform.localScale = Vector3.Min(cursorOriginalScale * tracerLength, maximumCursorScale); } } ToggleRenderer(controllingPointer.IsPointerActive(), false); UpdateDependencies(actualCursor.transform.position); } } } }
46.425781
263
0.619941
[ "MIT" ]
Reality-Virtually-Hackathon/Proxemix
Assets/VRTK/Scripts/Pointers/PointerRenderers/VRTK_StraightPointerRenderer.cs
11,887
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using Windows.Foundation.Metadata; namespace UniversalPlatformTools { /// <summary> /// A Basic implementation of the <see cref="INotifyPropertyChanged"/> and <see cref="INotifyPropertyChanging"/> interfaces. /// </summary> [WebHostHidden] public class BaseNotifier : INotifyPropertyChanged, INotifyPropertyChanging { public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangingEventHandler PropertyChanging; protected virtual void NotifyPropertyChanged([CallerMemberName]string propertyName = "") { NotifyPropertyChanged(new PropertyChangedEventArgs(propertyName)); } protected virtual void NotifyPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } protected virtual void NotifyPropertyChanging([CallerMemberName]string propertyName = "") { NotifyPropertyChanging(new PropertyChangingEventArgs(propertyName)); } protected virtual void NotifyPropertyChanging(PropertyChangingEventArgs e) { PropertyChanging?.Invoke(this, e); } public BaseNotifier() { PropertyChanged += OnPropertyChanged; } protected virtual void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { } } }
30.980392
128
0.69557
[ "Apache-2.0" ]
LCTWorks/UniversalPlatformTools
BaseNotifier.cs
1,582
C#
namespace CribblyBackend.DataAccess.Tournaments.Repositories { public static class TournamentQueries { private const string allTournamentColumns = "Id, Date, IsOpenForRegistration, IsActive"; public static string Create = @"INSERT INTO Tournaments (Date, IsOpenForRegistration, IsActive) VALUES (@Date, FALSE, FALSE)"; public static string GetLast = $"SELECT Id, Date, IsOpenForRegistration, IsActive FROM Tournaments WHERE Id = LAST_INSERT_ID()"; public static string GetById = @"SELECT Id, Date, IsOpenForRegistration, IsActive FROM Tournaments WHERE Id = @Id"; // Note: this breaks the rule of using only parameterized query strings; however, the external world // CANNOT control flagName here since flagName is passed by us and never from an external source public static string GetAllWithActiveFlag(string flagName) => $@"SELECT Id, Date, IsOpenForRegistration, IsActive FROM Tournaments WHERE {flagName} = 1"; // `true` doesn't exist in mysql; use 1 // Note: this breaks the rule of using only parameterized query strings; however, the external world // CANNOT control flagName here since flagName is passed by us and never from an external source public static string SetFlag(string flagName) => $@"UPDATE Tournaments SET {flagName} = @Value WHERE Id = @Id"; } }
51.827586
144
0.664005
[ "MIT" ]
cszczepaniak/cribbly-backend
src/CribblyBackend.DataAccess/Tournaments/Repositories/TournamentQueries.cs
1,503
C#
using CefSharp; using CefSharp.WinForms; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace BGEngine.Forms { public partial class BrowserForm : Form { public BrowserForm(string address) { InitializeComponent(); BrowserSettings browserSettings = new BrowserSettings(); browserSettings.FileAccessFromFileUrls = CefState.Enabled; browserSettings.UniversalAccessFromFileUrls = CefState.Enabled; browserSettings.TextAreaResize = CefState.Enabled; var b = new ChromiumWebBrowser(address); b.BrowserSettings = browserSettings; b.Parent = this; b.Show(); } } }
26.484848
75
0.679634
[ "MIT" ]
Naamloos/BGEngine
BGEngine/Forms/BrowserForm.cs
876
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace SpeakerMeet.API.Controllers { [Route("api/[controller]")] public class ValuesController : Controller { // GET api/values [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public string Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody]string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
20.555556
55
0.522162
[ "MIT" ]
PacktPublishing/Improving-your-C-Sharp-Skills
Chapter06/SpeakerMeet/SpeakerMeet.API/Controllers/ValuesController.cs
927
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.Devices.AllJoyn { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented] #endif public partial class AllJoynCredentialsRequestedEventArgs { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public ushort AttemptCount { get { throw new global::System.NotImplementedException("The member ushort AllJoynCredentialsRequestedEventArgs.AttemptCount is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public global::Windows.Devices.AllJoyn.AllJoynCredentials Credentials { get { throw new global::System.NotImplementedException("The member AllJoynCredentials AllJoynCredentialsRequestedEventArgs.Credentials is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public string PeerUniqueName { get { throw new global::System.NotImplementedException("The member string AllJoynCredentialsRequestedEventArgs.PeerUniqueName is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public string RequestedUserName { get { throw new global::System.NotImplementedException("The member string AllJoynCredentialsRequestedEventArgs.RequestedUserName is not implemented in Uno."); } } #endif // Forced skipping of method Windows.Devices.AllJoyn.AllJoynCredentialsRequestedEventArgs.AttemptCount.get // Forced skipping of method Windows.Devices.AllJoyn.AllJoynCredentialsRequestedEventArgs.Credentials.get // Forced skipping of method Windows.Devices.AllJoyn.AllJoynCredentialsRequestedEventArgs.PeerUniqueName.get // Forced skipping of method Windows.Devices.AllJoyn.AllJoynCredentialsRequestedEventArgs.RequestedUserName.get #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public global::Windows.Foundation.Deferral GetDeferral() { throw new global::System.NotImplementedException("The member Deferral AllJoynCredentialsRequestedEventArgs.GetDeferral() is not implemented in Uno."); } #endif } }
49
162
0.75737
[ "Apache-2.0" ]
AbdalaMask/uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Devices.AllJoyn/AllJoynCredentialsRequestedEventArgs.cs
3,087
C#
using UnityEngine; namespace BehaviorDesigner.Runtime.Tasks.Unity.UnityAudioSource { [TaskCategory("Unity/AudioSource")] [TaskDescription("Sets the inTime value of the AudioSource. Returns Success.")] public class SetTime : Action { [Tooltip("The GameObject that the task operates on. If null the task GameObject is used.")] public SharedGameObject targetGameObject; [Tooltip("The inTime value of the AudioSource")] public SharedFloat time; private AudioSource audioSource; private GameObject prevGameObject; public override void OnStart() { var currentGameObject = GetDefaultGameObject(targetGameObject.Value); if (currentGameObject != prevGameObject) { audioSource = currentGameObject.GetComponent<AudioSource>(); prevGameObject = currentGameObject; } } public override TaskStatus OnUpdate() { if (audioSource == null) { Debug.LogWarning("AudioSource is null"); return TaskStatus.Failure; } audioSource.time = time.Value; return TaskStatus.Success; } public override void OnReset() { targetGameObject = null; time = 1; } } }
30.568182
99
0.607435
[ "Unlicense" ]
LaudateCorpus1/distributed-architecture-of-moba-game-server
PurificationPioneer/Assets/3rd/Behavior Designer/Runtime/Tasks/Unity/AudioSource/SetTime.cs
1,345
C#
// Debouncing for value filter (10 ms) conf.Column(c => c.Title).FilterValue(c => c.Title, ui => ui.ClientFiltering().Inputdelay(10)); // Debouncing for range value filter (10 ms) conf.Column(c => c.Price).FilterRange(c => c.Price, ui => ui.ClientFiltering().Inputdelay(10));
55.2
95
0.699275
[ "MIT" ]
reinforced/Reinforced.Lattice.Samples
Reinforced.Lattice.CaseStudies.Filtering/doc/filter-debouncing.cs
276
C#
using DemoCore.Application.ViewModels; using System; using System.Collections.Generic; namespace DemoCore.Application.Interfaces { public interface IBestWorkTimeService: IDisposable { void Register(BestWorkTimeVM bestWorkVM); IEnumerable<BestWorkTimeVM> GetAll(); BestWorkTimeVM GetById(int id); void Update(BestWorkTimeVM bestWorkVM); void Remove(int id); IEnumerable<SelectedItems> GetSelectedBestWorkTime(); //IList<CustomerHistoryData> GetAllHistory(Guid id); } }
29.888889
61
0.724907
[ "MIT" ]
hugomarshall/Demo
DemoCore/src/DemoCore.Application/Interfaces/IBestWorkTimeService.cs
540
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using BuildXL.Utilities.Tracing; namespace BuildXL.Engine.Cache.Artifacts { /// <summary> /// Counters for <see cref="LocalDiskContentStore" />. /// </summary> public enum LocalDiskContentStoreCounter { /// <summary> /// The amount of time it took to flush file content from page-cache to the underlying filesystem. /// This is a potentially expensive barrier operation needed to get up-to-date USNs. /// </summary> [CounterType(CounterType.Stopwatch)] FlushFileToFilesystemTime, /// <summary> /// The amount of bytes of file content hashed /// </summary> HashFileContentSizeBytes, /// <summary> /// The amount of time spent in TryProbeForExistence /// </summary> [CounterType(CounterType.Stopwatch)] TryProbeAndTrackPathForExistenceTime, /// <summary> /// The amount of time spent in TrackAbsentPath /// </summary> [CounterType(CounterType.Stopwatch)] TrackAbsentPathTime, /// <nodoc/> [CounterType(CounterType.Stopwatch)] TryMaterializeTime, /// <summary> /// The amount of time spent in TryDiscoverAsync /// </summary> [CounterType(CounterType.Stopwatch)] TryDiscoverTime, /// <nodoc/> [CounterType(CounterType.Stopwatch)] TryDiscoverTime_TryGetKnownContentHash, /// <nodoc/> [CounterType(CounterType.Stopwatch)] TryDiscoverTime_GetReparsePointType, /// <nodoc/> [CounterType(CounterType.Stopwatch)] TryDiscoverTime_OpenProbeHandle, /// <nodoc/> [CounterType(CounterType.Stopwatch)] TryDiscoverTime_OpenReadHandle, /// <nodoc/> [CounterType(CounterType.Stopwatch)] TryDiscoverTime_HashByTargetPath, /// <nodoc/> [CounterType(CounterType.Stopwatch)] TryDiscoverTime_HashFileContent, /// <nodoc/> [CounterType(CounterType.Stopwatch)] TryDiscoverTime_HashFileContentWithSemaphore, /// <nodoc/> [CounterType(CounterType.Stopwatch)] TryDiscoverTime_TrackChangesToFile, /// <nodoc/> [CounterType(CounterType.Stopwatch)] TryTrackChangesToFileTime, /// <nodoc/> [CounterType(CounterType.Stopwatch)] TryGetFileNameTime, /// <summary> /// The number of times the local disk content store is queried for untracked paths /// </summary> UntrackedPathCalls, /// <summary> /// The number of times the local disk content store is queried for tracked paths /// </summary> TrackedPathCalls } }
30.591837
107
0.601734
[ "MIT" ]
AzureMentor/BuildXL
Public/Src/Engine/Cache/Artifacts/LocalDiskContentStoreCounter.cs
2,998
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="XamlElementNameProvider.cs" company="Hukano"> // Copyright (c) Hukano. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Sundew.Xaml.Optimizations.Bindings.Internal.Xaml { using System.Xml.Linq; using Sundew.Xaml.Optimizations.Bindings.Internal.Parsing.Xaml; internal class XamlElementNameProvider { private readonly XamlElementNameResolver xamlElementNameResolver; private int identifier = 1; public XamlElementNameProvider(XamlElementNameResolver xamlElementNameResolver) { this.xamlElementNameResolver = xamlElementNameResolver; } public string GetName(IBinding binding) { var elementName = binding.TargetElementName; if (string.IsNullOrEmpty(elementName)) { return this.GetName(binding.TargetElement); } return elementName; } public string GetName(XElement xElement) { var name = this.xamlElementNameResolver.Resolve(xElement); if (!string.IsNullOrEmpty(name)) { return name; } var suggestedName = xElement.Name.LocalName + this.identifier++; while (!this.xamlElementNameResolver.TryAddName(suggestedName, xElement)) { suggestedName = xElement.Name.LocalName + this.identifier++; } return suggestedName; } public XAttribute TryGetNameAttribute(XElement xElement) { return this.xamlElementNameResolver.TryGetNameAttribute(xElement); } public void Reset() { this.identifier = 1; } } }
33.836066
120
0.55281
[ "MIT" ]
hugener/Sundew.Xaml.Optimizations
Sources/Sundew.Xaml.Optimizations/Bindings/Internal/Xaml/XamlElementNameProvider.cs
2,066
C#
using System; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; namespace IfacesEnumsStructsClasses { #region IHTMLRect Interface /// <summary><para><c>IHTMLRect</c> interface.</para></summary> [Guid("3050F4A3-98B5-11CF-BB82-00AA00BDCE0B")] [ComImport] [TypeLibType((short)4160)] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] public interface IHTMLRect { /// <summary><para><c>bottom</c> property of <c>IHTMLRect</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>bottom</c> property was the following: <c>long bottom</c>;</para></remarks> // IDL: long bottom; // VB6: bottom As Long int bottom { // IDL: HRESULT bottom ([out, retval] long* ReturnValue); // VB6: Function bottom As Long [DispId(1004)] get; // IDL: HRESULT bottom (long value); // VB6: Sub bottom (ByVal value As Long) [DispId(1004)] set; } /// <summary><para><c>left</c> property of <c>IHTMLRect</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>left</c> property was the following: <c>long left</c>;</para></remarks> // IDL: long left; // VB6: left As Long int left { // IDL: HRESULT left ([out, retval] long* ReturnValue); // VB6: Function left As Long [DispId(1001)] get; // IDL: HRESULT left (long value); // VB6: Sub left (ByVal value As Long) [DispId(1001)] set; } /// <summary><para><c>right</c> property of <c>IHTMLRect</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>right</c> property was the following: <c>long right</c>;</para></remarks> // IDL: long right; // VB6: right As Long int right { // IDL: HRESULT right ([out, retval] long* ReturnValue); // VB6: Function right As Long [DispId(1003)] get; // IDL: HRESULT right (long value); // VB6: Sub right (ByVal value As Long) [DispId(1003)] set; } /// <summary><para><c>top</c> property of <c>IHTMLRect</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>top</c> property was the following: <c>long top</c>;</para></remarks> // IDL: long top; // VB6: top As Long int top { // IDL: HRESULT top ([out, retval] long* ReturnValue); // VB6: Function top As Long [DispId(1002)] get; // IDL: HRESULT top (long value); // VB6: Sub top (ByVal value As Long) [DispId(1002)] set; } } #endregion }
36.975
136
0.539892
[ "Apache-2.0" ]
prog76/csexwb2
HTML_Interfaces/IHTMLRect.cs
2,958
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NosqlTransactionManager { public interface IWriteResource<T> { string ParticipantName { get; } T Create(T t); T Update(T t); bool Delete(T t); } }
18.294118
40
0.598071
[ "Apache-2.0" ]
vinayakbhadage/NosqlTransactionManager
TransctionAdministrator/NosqlTransctionManager/ResourceManager/IWriteResource.cs
313
C#
using System; using System.Threading.Tasks; using Resonance.Outbox.Serialization; using Resonance.Outbox.Storage; namespace Resonance.Outbox.Inbound { public class TransactionOutboxBuilder { private IMessageRepository _repository; private IMessageSerializer _serializer; private IStorageInitializer _storageInitializer; public TransactionOutboxBuilder UseRepository(IMessageRepository repository) { _repository = repository ?? throw new ArgumentNullException(nameof(repository)); return this; } public TransactionOutboxBuilder UseSerializer(IMessageSerializer serializer) { _serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); return this; } public TransactionOutboxBuilder UseStorageInitializer(IStorageInitializer initializer) { _storageInitializer = initializer ?? throw new ArgumentNullException(nameof(initializer)); return this; } public async Task<ITransactionalOutbox> Build() { if (_storageInitializer?.InitializeOnStartup == true) { await _storageInitializer.InitializeTables().ConfigureAwait(false); } return new TransactionalOutbox(_repository, _serializer); } } }
32.833333
102
0.676577
[ "Apache-2.0" ]
m-wilczynski/resonance
src/Outbox/Resonance.Outbox/Inbound/TransactionalOutboxBuilder.cs
1,381
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Dns.Models; using Microsoft.Azure.Management.Dns.Models; using System; using System.Collections; using System.Management.Automation; using ProjectResources = Microsoft.Azure.Commands.Dns.Properties.Resources; namespace Microsoft.Azure.Commands.Dns { /// <summary> /// Creates a new record set. /// </summary> [Cmdlet(VerbsCommon.New, "AzureRmDnsRecordSet", SupportsShouldProcess = true), OutputType(typeof(DnsRecordSet))] public class NewAzureDnsRecordSet : DnsBaseCmdlet { [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the records inthis record set (relative to the name of the zone and without a terminating dot).")] [ValidateNotNullOrEmpty] public string Name { get; set; } [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The zone in which to create the record set (without a terminating dot).", ParameterSetName = "Fields")] [ValidateNotNullOrEmpty] public string ZoneName { get; set; } [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group to which the zone belongs.", ParameterSetName = "Fields")] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } [Parameter(Mandatory = true, ValueFromPipeline = true, HelpMessage = "The DnsZone object representing the zone in which to create the record set.", ParameterSetName = "Object")] [ValidateNotNullOrEmpty] public DnsZone Zone { get; set; } [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The TTL value of all the records in this record set.")] [ValidateNotNullOrEmpty] public uint Ttl { get; set; } [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The type of DNS records in this record set.")] [ValidateNotNullOrEmpty] public RecordType RecordType { get; set; } [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hash table which represents resource tags.")] public Hashtable Metadata { get; set; } [Parameter(Mandatory = false, ValueFromPipeline = true, HelpMessage = "The dns records that are part of this record set.")] [ValidateNotNull] public DnsRecordBase[] DnsRecords { get; set; } [Parameter(Mandatory = false, HelpMessage = "Do not fail if the record set already exists.")] public SwitchParameter Overwrite { get; set; } [Parameter(Mandatory = false, HelpMessage = "Do not ask for confirmation.")] [Obsolete("This parameter is obsolete; use Confirm instead")] public SwitchParameter Force { get; set; } public override void ExecuteCmdlet() { string zoneName = null; string resourceGroupname = null; DnsRecordSet result = null; if (RecordType == RecordType.SOA) { throw new System.ArgumentException(ProjectResources.Error_AddRecordSOA); } if (ParameterSetName == "Fields") { zoneName = this.ZoneName; resourceGroupname = this.ResourceGroupName; } else if (ParameterSetName == "Object") { zoneName = this.Zone.Name; resourceGroupname = this.Zone.ResourceGroupName; } if(this.Name.EndsWith(zoneName.ToString())) { this.WriteWarning(string.Format(ProjectResources.Error_RecordSetNameEndsWithZoneName, this.Name, zoneName.ToString())); } if (zoneName != null && zoneName.EndsWith(".")) { zoneName = zoneName.TrimEnd('.'); this.WriteWarning(string.Format("Modifying zone name to remove terminating '.'. Zone name used is \"{0}\".", zoneName)); } if (this.DnsRecords == null) { this.WriteWarning(ProjectResources.Warning_DnsRecordsParamNeedsToBeSpecified); } ConfirmAction( ProjectResources.Progress_CreatingRecordSet, this.Name, () => { result = this.DnsClient.CreateDnsRecordSet(zoneName, resourceGroupname, this.Name, this.Ttl, this.RecordType, this.Metadata, this.Overwrite, this.DnsRecords); if (result != null) { WriteVerbose(ProjectResources.Success); WriteVerbose(string.Format(ProjectResources.Success_NewRecordSet, this.Name, zoneName, this.RecordType)); WriteVerbose(string.Format(ProjectResources.Success_RecordSetFqdn, this.Name, zoneName, this.RecordType)); } WriteObject(result); }); } } }
47.564516
203
0.611394
[ "MIT" ]
Andrean/azure-powershell
src/StackAdmin/Dns/Commands.Dns/Records/NewAzureDnsRescordSet.cs
5,777
C#
// Copyright (C) 2009-2021 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. using System; using Xtensive.Sql.Compiler; using Xtensive.Sql.Info; using SqlServerConnection = Microsoft.Data.SqlClient.SqlConnection; namespace Xtensive.Sql.Drivers.SqlServer.v09 { internal class Driver : SqlServer.Driver { protected override SqlCompiler CreateCompiler() { return new Compiler(this); } protected override Model.Extractor CreateExtractor() { return new Extractor(this); } protected override SqlTranslator CreateTranslator() { return new Translator(this); } protected override Sql.TypeMapper CreateTypeMapper() { return new TypeMapper(this); } protected override Info.ServerInfoProvider CreateServerInfoProvider() { return new ServerInfoProvider(this); } protected override void RegisterCustomMappings(TypeMappingRegistryBuilder builder) { builder.Add(typeof (DateTimeOffset), builder.Mapper.ReadDateTimeOffset, builder.Mapper.BindDateTimeOffset, builder.Mapper.MapDateTimeOffset); } protected override void RegisterCustomReverseMappings(TypeMappingRegistryBuilder builder) { builder.AddReverse(SqlType.DateTimeOffset, typeof (DateTimeOffset)); } // Constructors public Driver(CoreServerInfo coreServerInfo, ErrorMessageParser errorMessageParser, bool checkConnectionIsAlive) : base(coreServerInfo, errorMessageParser, checkConnectionIsAlive) { } } }
27
116
0.731481
[ "MIT" ]
DataObjects-NET/dataobjects-net
Orm/Xtensive.Orm.SqlServer/Sql.Drivers.SqlServer/v09/Driver.cs
1,620
C#
#region License // Copyright (c) 2019 smart-me AG https://www.smart-me.com/ // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #endregion using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using OidcWebExample.Helpers; using SmartMeApiClient; using SmartMeApiClient.Containers; namespace OidcWebExample.Pages.Devices { public class GetDevicesModel : PageModel { public IEnumerable<Device> Devices { get; set; } public async Task<IActionResult> OnGetAsync() { if (!User.Identity.IsAuthenticated) { return Redirect("/"); } var accessToken = await HttpContext.GetTokenAsync("access_token"); return await DevicesApi.GetDevicesAsync(accessToken, new ResultHandler<List<Device>> { OnSuccess = (devices) => { Devices = devices; return Page(); }, OnError = DefaultErrorHandler.Handle }); } } }
36.55
96
0.688554
[ "MIT" ]
eCarUp/smartme-api-client-library-dotnet
Src/OidcWebExample/Pages/Devices/GetDevices.cshtml.cs
2,195
C#