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; using System.Windows.Controls; namespace NineMensMorris.GameLogic { /// <summary> /// Represents a human player /// </summary> public class HumanPlayer : IPlayer { public int ID { get; private set; } private Game game; //reference to the host game private bool isActive = false; private bool manSelected = false; private Position lastClickPosition; public event EventHandler<Position> onManSelected; public event EventHandler<Position> onManDeselected; public void Init(Game game, int id) { this.game = game; this.ID = id; } public void BeginTurn(Game game) { isActive = true; manSelected = false; } public void EndTurn(Game game) { isActive = false; } /// <summary> /// Simulate a click on a point of the board /// </summary> /// <param name="currentActiveId"> The id of the player that was active when the click happened </param> // Introduced currentActiveId because playerA simulates his clicks, switches turns and then playerB also simulates the same click and erroneuosly thinks it is active! public void ClickPoint(int currentActiveId, Position position) { if(!isActive || currentActiveId != this.ID) //check if the player is active { return; } if(game.HasKillPending(this)) //the player has a pending kill { game.Kill(new Kill(this, position)); } else { switch (game.CheckPhase(this)) { case Phase.Placing: game.Place(new Placement(this, position)); //place down a man break; case Phase.Moving: case Phase.Flying: if (manSelected && game.GetOwnerId(position) != ID) //check if there is already a man selected and the newly selected man isn't one of our own { game.Move(new Move(this, lastClickPosition, position)); //move a man } else if(game.GetOwnerId(position) == this.ID) //make sure the first clicked man is one of ours { if (manSelected != false) { onManDeselected?.Invoke(this, lastClickPosition); } lastClickPosition = position; manSelected = true; //onManSelected event onManSelected?.Invoke(this, lastClickPosition); } break; default: break; } } } } }
32.84375
174
0.499524
[ "Apache-2.0" ]
YanickZengaffinen/AI
NineMensMorris/GameLogic/Players/HumanPlayer.cs
3,155
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using NUnit.Framework; using Microsoft.Maui.Controls; using Microsoft.Maui.Controls.Core.UnitTests; namespace Microsoft.Maui.Controls.Xaml.UnitTests { public class Dict : Dictionary<string, string> { } public class Gh8936VM { public Dict Data { get; set; } = new Dict { { "Key", "Value" } }; } public partial class Gh8936 : ContentPage { public Gh8936() => InitializeComponent(); public Gh8936(bool useCompiledXaml) { //this stub will be replaced at compile time } [TestFixture] class Tests { [SetUp] public void Setup() => Device.PlatformServices = new MockPlatformServices(); [TearDown] public void TearDown() => Device.PlatformServices = null; [Test] public void IndexerBindingOnSubclasses([Values(false, true)] bool useCompiledXaml) { var layout = new Gh8936(useCompiledXaml) { BindingContext = new Gh8936VM() }; Assert.That(layout.entry0.Text, Is.EqualTo("Value")); layout.entry0.Text = "Bar"; Assert.That(layout.entry0.Text, Is.EqualTo("Bar")); Assert.That(((Gh8936VM)layout.BindingContext).Data["Key"], Is.EqualTo("Bar")); } } } }
28
87
0.706169
[ "MIT" ]
pictos/maui
src/Controls/tests/Xaml.UnitTests/Issues/Gh8936.xaml.cs
1,232
C#
using System; using System.Collections.Generic; namespace generic_list { class Program { static void Main(string[] args) { //List<T> class //System.Collections.Generic //T -> object türündedir. List<int> sayiListesi = new List<int>(); sayiListesi.Add(23); sayiListesi.Add(10); sayiListesi.Add(4); sayiListesi.Add(5); sayiListesi.Add(52); sayiListesi.Add(92); sayiListesi.Add(34); List<string> renkListesi = new List<string>(); renkListesi.Add("Kırmızı"); renkListesi.Add("Mavi"); renkListesi.Add("Turuncu"); renkListesi.Add("Sarı"); renkListesi.Add("Yeşil"); //Count Console.WriteLine(renkListesi.Count); Console.WriteLine(sayiListesi.Count); //Foreach ve List.ForEach ile elemanlara erişim foreach (var sayi in sayiListesi) { Console.WriteLine(sayi); } foreach (var renk in renkListesi) { Console.WriteLine(renk); } sayiListesi.ForEach(sayi => Console.WriteLine(sayi)); renkListesi.ForEach(renk => Console.WriteLine(renk)); //Listenden eleman çıkarma sayiListesi.Remove(4); renkListesi.Remove("Yeşil"); sayiListesi.ForEach(sayi => Console.WriteLine(sayi)); renkListesi.ForEach(renk => Console.WriteLine(renk)); //Liste içerisinde Arama if(sayiListesi.Contains(10)) Console.WriteLine("10 Liste içerisinde bulundu!"); //Eleman ile index'e erişme Console.WriteLine(renkListesi.BinarySearch("Sarı")); //Diziyi List'e çevirme string[] hayvanlar = {"kedi", "köpek", "kuş"}; List<string> hayvanlarListesi = new List<string>(hayvanlar); //Listeyi nasıl temizleriz? hayvanlarListesi.Clear(); //List içerisinde nesne tutmak List<Kullanicilar> kullaniciListesi = new List<Kullanicilar>(); Kullanicilar kullanici1 = new Kullanicilar(); kullanici1.isim = "ELif"; kullanici1.soyisim = "Şirin"; kullanici1.yas = 23; Kullanicilar kullanici2 = new Kullanicilar(); kullanici2.isim = "Merve"; kullanici2.soyisim = "Altek"; kullanici2.yas = 29; kullaniciListesi.Add(kullanici1); kullaniciListesi.Add(kullanici2); List<Kullanicilar> yeniListe = new List<Kullanicilar>(); yeniListe.Add(new Kullanicilar(){ isim = "Elif", soyisim = "Şirin", yas = 23 }); foreach (var kullanici in kullaniciListesi) { Console.WriteLine("Kullanici Adi: " + kullanici.isim); Console.WriteLine("Kullanici Soyadi: " + kullanici.soyisim); Console.WriteLine("Kullanici Yaşı: " + kullanici.yas); } kullaniciListesi.Clear(); } } public class Kullanicilar{ public string isim { get; set; } public string soyisim { get; set; } public int yas { get; set; } } }
29.330579
76
0.513384
[ "MIT" ]
elifsirin42/Kodluyoruz-Csharp-101-Patikasi
Pratikler/generic-list/Program.cs
3,575
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager; using Azure.ResourceManager.Core; using Azure.ResourceManager.Sql.Models; namespace Azure.ResourceManager.Sql { /// <summary> A Class representing a ManagedInstanceAzureADOnlyAuthentication along with the instance operations that can be performed on it. </summary> public partial class ManagedInstanceAzureADOnlyAuthentication : ArmResource { /// <summary> Generate the resource identifier of a <see cref="ManagedInstanceAzureADOnlyAuthentication"/> instance. </summary> public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string managedInstanceName, string authenticationName) { var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/azureADOnlyAuthentications/{authenticationName}"; return new ResourceIdentifier(resourceId); } private readonly ClientDiagnostics _managedInstanceAzureADOnlyAuthenticationClientDiagnostics; private readonly ManagedInstanceAzureADOnlyAuthenticationsRestOperations _managedInstanceAzureADOnlyAuthenticationRestClient; private readonly ManagedInstanceAzureADOnlyAuthenticationData _data; /// <summary> Initializes a new instance of the <see cref="ManagedInstanceAzureADOnlyAuthentication"/> class for mocking. </summary> protected ManagedInstanceAzureADOnlyAuthentication() { } /// <summary> Initializes a new instance of the <see cref = "ManagedInstanceAzureADOnlyAuthentication"/> class. </summary> /// <param name="client"> The client parameters to use in these operations. </param> /// <param name="data"> The resource that is the target of operations. </param> internal ManagedInstanceAzureADOnlyAuthentication(ArmClient client, ManagedInstanceAzureADOnlyAuthenticationData data) : this(client, data.Id) { HasData = true; _data = data; } /// <summary> Initializes a new instance of the <see cref="ManagedInstanceAzureADOnlyAuthentication"/> class. </summary> /// <param name="client"> The client parameters to use in these operations. </param> /// <param name="id"> The identifier of the resource that is the target of operations. </param> internal ManagedInstanceAzureADOnlyAuthentication(ArmClient client, ResourceIdentifier id) : base(client, id) { _managedInstanceAzureADOnlyAuthenticationClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Sql", ResourceType.Namespace, DiagnosticOptions); TryGetApiVersion(ResourceType, out string managedInstanceAzureADOnlyAuthenticationApiVersion); _managedInstanceAzureADOnlyAuthenticationRestClient = new ManagedInstanceAzureADOnlyAuthenticationsRestOperations(_managedInstanceAzureADOnlyAuthenticationClientDiagnostics, Pipeline, DiagnosticOptions.ApplicationId, BaseUri, managedInstanceAzureADOnlyAuthenticationApiVersion); #if DEBUG ValidateResourceId(Id); #endif } /// <summary> Gets the resource type for the operations. </summary> public static readonly ResourceType ResourceType = "Microsoft.Sql/managedInstances/azureADOnlyAuthentications"; /// <summary> Gets whether or not the current instance has data. </summary> public virtual bool HasData { get; } /// <summary> Gets the data representing this Feature. </summary> /// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception> public virtual ManagedInstanceAzureADOnlyAuthenticationData Data { get { if (!HasData) throw new InvalidOperationException("The current instance does not have data, you must call Get first."); return _data; } } internal static void ValidateResourceId(ResourceIdentifier id) { if (id.ResourceType != ResourceType) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); } /// <summary> /// Gets a specific Azure Active Directory only authentication property. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/azureADOnlyAuthentications/{authenticationName} /// Operation Id: ManagedInstanceAzureADOnlyAuthentications_Get /// </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public async virtual Task<Response<ManagedInstanceAzureADOnlyAuthentication>> GetAsync(CancellationToken cancellationToken = default) { using var scope = _managedInstanceAzureADOnlyAuthenticationClientDiagnostics.CreateScope("ManagedInstanceAzureADOnlyAuthentication.Get"); scope.Start(); try { var response = await _managedInstanceAzureADOnlyAuthenticationRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); if (response.Value == null) throw await _managedInstanceAzureADOnlyAuthenticationClientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false); return Response.FromValue(new ManagedInstanceAzureADOnlyAuthentication(Client, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Gets a specific Azure Active Directory only authentication property. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/azureADOnlyAuthentications/{authenticationName} /// Operation Id: ManagedInstanceAzureADOnlyAuthentications_Get /// </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<ManagedInstanceAzureADOnlyAuthentication> Get(CancellationToken cancellationToken = default) { using var scope = _managedInstanceAzureADOnlyAuthenticationClientDiagnostics.CreateScope("ManagedInstanceAzureADOnlyAuthentication.Get"); scope.Start(); try { var response = _managedInstanceAzureADOnlyAuthenticationRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken); if (response.Value == null) throw _managedInstanceAzureADOnlyAuthenticationClientDiagnostics.CreateRequestFailedException(response.GetRawResponse()); return Response.FromValue(new ManagedInstanceAzureADOnlyAuthentication(Client, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Deletes an existing server Active Directory only authentication property. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/azureADOnlyAuthentications/{authenticationName} /// Operation Id: ManagedInstanceAzureADOnlyAuthentications_Delete /// </summary> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public async virtual Task<ArmOperation> DeleteAsync(bool waitForCompletion, CancellationToken cancellationToken = default) { using var scope = _managedInstanceAzureADOnlyAuthenticationClientDiagnostics.CreateScope("ManagedInstanceAzureADOnlyAuthentication.Delete"); scope.Start(); try { var response = await _managedInstanceAzureADOnlyAuthenticationRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); var operation = new SqlArmOperation(_managedInstanceAzureADOnlyAuthenticationClientDiagnostics, Pipeline, _managedInstanceAzureADOnlyAuthenticationRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name).Request, response, OperationFinalStateVia.Location); if (waitForCompletion) await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Deletes an existing server Active Directory only authentication property. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/azureADOnlyAuthentications/{authenticationName} /// Operation Id: ManagedInstanceAzureADOnlyAuthentications_Delete /// </summary> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual ArmOperation Delete(bool waitForCompletion, CancellationToken cancellationToken = default) { using var scope = _managedInstanceAzureADOnlyAuthenticationClientDiagnostics.CreateScope("ManagedInstanceAzureADOnlyAuthentication.Delete"); scope.Start(); try { var response = _managedInstanceAzureADOnlyAuthenticationRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken); var operation = new SqlArmOperation(_managedInstanceAzureADOnlyAuthenticationClientDiagnostics, Pipeline, _managedInstanceAzureADOnlyAuthenticationRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name).Request, response, OperationFinalStateVia.Location); if (waitForCompletion) operation.WaitForCompletionResponse(cancellationToken); return operation; } catch (Exception e) { scope.Failed(e); throw; } } } }
59.561497
312
0.709822
[ "MIT" ]
AntonioVT/azure-sdk-for-net
sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/ManagedInstanceAzureADOnlyAuthentication.cs
11,138
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using Microsoft.Extensions.Hosting; using Vostok.Logging.Abstractions; using Vostok.Logging.Console; using Vostok.Logging.Context; using Vostok.Logging.File; using Vostok.Logging.File.Configuration; namespace Vektonn.Hosting { public static class LoggingConfigurator { public static ILog SetupLocalLog(string applicationName, string? hostingEnvironment = null) { SetupUnhandledExceptionLogging(); var logs = new List<ILog>(); if (hostingEnvironment == Environments.Development) { logs.Add( new ConsoleLog( new ConsoleLogSettings { ColorsEnabled = true, })); } logs.Add( new FileLog( new FileLogSettings { Encoding = Encoding.UTF8, FileOpenMode = FileOpenMode.Append, FilePath = Path.Combine( FileSystemHelpers.PatchDirectoryName("logs"), $"{applicationName}.{{RollingSuffix}}.{DateTime.Now:HH-mm-ss}.log"), RollingStrategy = new RollingStrategyOptions { Type = RollingStrategyType.ByTime, Period = RollingPeriod.Day, MaxFiles = 30 } })); var localLog = new CompositeLog(logs.ToArray()) .ForContext("Local") .WithAllFlowingContextProperties(); return localLog; } private static void SetupUnhandledExceptionLogging() { AppDomain.CurrentDomain.UnhandledException += (_, e) => LogUnhandledException((Exception)e.ExceptionObject, "Unhandled exception in current AppDomain"); } private static void LogUnhandledException(Exception? exception, string logMessage) { Console.WriteLine(exception); LogProvider.Get().Fatal(exception, logMessage); } } }
33.705882
112
0.530977
[ "Apache-2.0" ]
vektonn/vektonn
src/Vektonn.Hosting/LoggingConfigurator.cs
2,292
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 iot-2015-05-28.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.IoT.Model { /// <summary> /// The audits that were performed. /// </summary> public partial class AuditTaskMetadata { private string _taskId; private AuditTaskStatus _taskStatus; private AuditTaskType _taskType; /// <summary> /// Gets and sets the property TaskId. /// <para> /// The ID of this audit. /// </para> /// </summary> [AWSProperty(Min=1, Max=40)] public string TaskId { get { return this._taskId; } set { this._taskId = value; } } // Check to see if TaskId property is set internal bool IsSetTaskId() { return this._taskId != null; } /// <summary> /// Gets and sets the property TaskStatus. /// <para> /// The status of this audit: one of "IN_PROGRESS", "COMPLETED", "FAILED" or "CANCELED". /// </para> /// </summary> public AuditTaskStatus TaskStatus { get { return this._taskStatus; } set { this._taskStatus = value; } } // Check to see if TaskStatus property is set internal bool IsSetTaskStatus() { return this._taskStatus != null; } /// <summary> /// Gets and sets the property TaskType. /// <para> /// The type of this audit: one of "ON_DEMAND_AUDIT_TASK" or "SCHEDULED_AUDIT_TASK". /// </para> /// </summary> public AuditTaskType TaskType { get { return this._taskType; } set { this._taskType = value; } } // Check to see if TaskType property is set internal bool IsSetTaskType() { return this._taskType != null; } } }
28.505263
101
0.587888
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/IoT/Generated/Model/AuditTaskMetadata.cs
2,708
C#
using FluentMigrator.Infrastructure.Extensions; namespace FluentMigrator.Runner.Generators.DB2 { using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using FluentMigrator.Model; using FluentMigrator.Runner.Generators.Base; internal class Db2Column : ColumnBase { #region Constructors public Db2Column(IQuoter quoter) : base(new Db2TypeMap(), quoter) { this.ClauseOrder = new List<Func<ColumnDefinition, string>> { FormatString, FormatType, this.FormatCCSID, this.FormatNullable, this.FormatDefaultValue, this.FormatIdentity }; this.AlterClauseOrder = new List<Func<ColumnDefinition, string>> { FormatType, this.FormatCCSID, this.FormatNullable, this.FormatDefaultValue, this.FormatIdentity }; } #endregion Constructors #region Properties public List<Func<ColumnDefinition, string>> AlterClauseOrder { get; set; } #endregion Properties #region Methods public string FormatAlterDefaultValue(string column, object defaultValue) { return Quoter.QuoteValue(defaultValue); } public string GenerateAlterClause(ColumnDefinition column) { if (column.IsIdentity) { throw new NotSupportedException("Altering an identity column is not supported."); } var alterClauses = AlterClauseOrder.Aggregate(new StringBuilder(), (acc, newRow) => { var clause = newRow(column); if (acc.Length == 0) { acc.Append(newRow(column)); } else if (!string.IsNullOrEmpty(clause)) { acc.Append(clause.PadLeft(clause.Length + 1)); } return acc; }); return string.Format( "ALTER COLUMN {0} SET DATA TYPE {1}", Quoter.QuoteColumnName(column.Name), alterClauses); } protected virtual string FormatCCSID(ColumnDefinition column) { if (column.Type == null) { return string.Empty; } var dbType = (DbType)column.Type; if (DbType.String.Equals(dbType) || DbType.StringFixedLength.Equals(dbType)) { // Force UTF-16 on double-byte character types. return "CCSID 1200"; } return string.Empty; } protected override string FormatDefaultValue(ColumnDefinition column) { var isCreate = column.GetAdditionalFeature("IsCreateColumn", false); if (isCreate && (column.DefaultValue is ColumnDefinition.UndefinedDefaultValue)) { return "DEFAULT"; } if (column.DefaultValue is ColumnDefinition.UndefinedDefaultValue) { return string.Empty; } var method = Quoter.QuoteValue(column.DefaultValue); if (string.IsNullOrEmpty(method)) { return string.Empty; } return "DEFAULT " + method; } protected override string FormatIdentity(ColumnDefinition column) { return column.IsIdentity ? "AS IDENTITY" : string.Empty; } protected override string FormatNullable(ColumnDefinition column) { if (column.IsNullable.HasValue && column.IsNullable.Value) { return string.Empty; } return "NOT NULL"; } #endregion Methods } }
29.207692
186
0.561759
[ "Apache-2.0" ]
quesadaao/fluentmigrator
src/FluentMigrator.Runner.Db2/Generators/Db2/Db2Column.cs
3,797
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TileStats : MonoBehaviour { public Sprite standardSprite; public Sprite mineSprite; public Sprite flagSprite; public List<Sprite> numberedSprites; public bool isMine=false; public int mineCount=0; public bool tileRevealed=false; public bool floodPerformed=false; public CreateField fieldScript; public bool tileFlagged=false; public bool flagDisabled=false; // Use this for initialization void Start () { fieldScript=FindObjectOfType<CreateField>(); } // Update is called once per frame void Update () { } public void DetermineSurroundingNumbers(List<GameObject> allTiles){ foreach(GameObject tile in allTiles){ if(tile.transform.position.x==transform.position.x || tile.transform.position.x==transform.position.x+1 || tile.transform.position.x==transform.position.x-1){ if(tile.transform.position.y==transform.position.y || tile.transform.position.y==transform.position.y+1 || tile.transform.position.y==transform.position.y-1){ if(tile.GetComponent<TileStats>().isMine==false){ tile.GetComponent<TileStats>().mineCount=tile.GetComponent<TileStats>().mineCount+1; //tile.GetComponent<SpriteRenderer>().sprite=numberedSprites[tile.GetComponent<TileStats>().mineCount]; } } } } } public void OnMouseOver(){ //tile isn't already revealed if(tileRevealed==false){ if(Input.GetMouseButton(0)){ //left click if(tileFlagged==false){ tileRevealed=true; if(isMine==true){ RevealBomb(); }else{ RevealNumber(); } } } if(flagDisabled==false){ if(Input.GetMouseButton(1)){ //right click if(tileFlagged==false){ //not flagged tileFlagged=true; GetComponent<SpriteRenderer>().sprite=flagSprite; }else{ //already flagged tileFlagged=false; GetComponent<SpriteRenderer>().sprite=standardSprite; } flagDisabled=true; StartCoroutine(EnableFlags()); } } } } public void RevealBomb(){ GetComponent<SpriteRenderer>().sprite=mineSprite; fieldScript.GameOver(); } public void RevealNumber(){ GetComponent<SpriteRenderer>().sprite=numberedSprites[mineCount]; if(mineCount==0){ fieldScript.FloodFillAlgorithm(transform.position.x, transform.position.y); } fieldScript.HaveAllBeenRevealed(); } public void Explode(){ tileRevealed=true; if(isMine==true){ GetComponent<SpriteRenderer>().sprite=mineSprite; }else{ GetComponent<SpriteRenderer>().sprite=numberedSprites[mineCount]; } } public IEnumerator EnableFlags(){ yield return new WaitForSeconds(0.1f); flagDisabled=false; } }
24.888889
162
0.71689
[ "MIT" ]
PacktPublishing/2D-Game-Programming-in-Unity
2.10/TileStats.cs
2,690
C#
//----------------------------------------------------------------------- // <copyright file="PathUtilities.cs" company="Sirenix IVS"> // Copyright (c) 2018 Sirenix IVS // // 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. // </copyright> //----------------------------------------------------------------------- namespace XamExporter.Utilities { using System; using System.IO; using System.Text; /// <summary> /// DirectoryInfo method extensions. /// </summary> public static class PathUtilities { /// <summary> /// Determines whether the directory has a given directory in its hierarchy of children. /// </summary> /// <param name="parentDir">The parent directory.</param> /// <param name="subDir">The sub directory.</param> public static bool HasSubDirectory(this DirectoryInfo parentDir, DirectoryInfo subDir) { var parentDirName = parentDir.FullName.TrimEnd('\\', '/'); while (subDir != null) { if (subDir.FullName.TrimEnd('\\', '/') == parentDirName) { return true; } else { subDir = subDir.Parent; } } return false; } } }
34.54717
96
0.549427
[ "Apache-2.0" ]
johnbrandle/odin-serializer
OdinSerializer/Utilities/Extensions/PathUtilities.cs
1,831
C#
using System; using System.Collections; using System.Collections.Immutable; using System.ComponentModel.DataAnnotations; using System.Linq; using AutoFixture; using AutoFixture.Xunit2; using Maxisoft.Utils.Empties; using Xunit; namespace Maxisoft.Utils.Tests.Empties { public class EmptyListTests { [Fact] public void Test_Enumerator() { var l = new EmptyList(); Assert.IsType<EmptyEnumerator>(l.GetEnumerator()); Assert.Empty(l); foreach (var _ in l) { Assert.False(true); } Assert.Equal(Enumerable.Empty<object>(), ((IEnumerable)l)); } [Theory, AutoData] public void TestAdd(string value) { var l = new EmptyList(); Assert.Throws<InvalidOperationException>(() => l.Add(value)); Assert.Empty(l); } [Theory, AutoData] public void TestInsert(int index, string value) { var l = new EmptyList(); Assert.Throws<InvalidOperationException>(() => l.Insert(index, value)); Assert.Empty(l); } [Fact] public void TestClear() { var l = new EmptyList(); l.Clear(); Assert.Empty(l); } [Theory, AutoData] public void TestContains(string value) { var l = new EmptyList(); Assert.False(l.Contains(value)); } [Theory, AutoData] public void TestCopyTo([Range(0, 16)]int arrayLength) { var fixture = new Fixture(); var array = new object[arrayLength]; for (var i = 0; i < arrayLength; i++) { array[i] = fixture.Create<object>(); } var l = new EmptyList(); var copy = array.ToImmutableList(); l.CopyTo(array, fixture.Create<int>()); Assert.Equal(copy, array); } [Theory, AutoData] public void TestRemove(string key) { var l = new EmptyList(); l.Remove(key); Assert.Empty(l); } [Theory, AutoData] public void TestRemoveAt(int index) { var l = new EmptyList(); l.RemoveAt(index); Assert.Empty(l); } [Theory, AutoData] public void TestIndexOf(string obj) { var l = new EmptyList(); Assert.Equal(-1, l.IndexOf(obj)); Assert.Empty(l); } [Theory, AutoData] public void TestIndexer(int index, string value) { var l = new EmptyList(); Assert.Throws<InvalidOperationException>(() => l[index]); Assert.Throws<InvalidOperationException>(() => l[index] = value); } [Fact] public void TestProperties() { var l = new EmptyList(); Assert.False(l.IsFixedSize); Assert.False(l.IsReadOnly); // ReSharper disable once xUnit2013 Assert.Equal(0, l.Count); Assert.False(l.IsSynchronized); // ReSharper disable once xUnit2005 Assert.IsType<EmptyList>(l.SyncRoot); } } }
28.099174
83
0.500882
[ "MIT" ]
sucrose0413/Maxisoft.Utils
Maxisoft.Utils.Tests/Empties/EmptyListTests.cs
3,402
C#
using GraphQL.Types; using Ianitor.Osp.Common.Shared.DataTransferObjects; #pragma warning disable 1591 namespace Ianitor.Osp.Backend.CoreServices.GraphQL.Types { public class SearchFilterDtoType : InputObjectGraphType<SearchFilterDto> { public SearchFilterDtoType() { Name = "SearchFilter"; Field(x => x.Language, true); Field(x => x.SearchTerm); Field(x => x.Type, true, typeof(SearchFilterTypesDtoType)); Field(x => x.AttributeNames, true, typeof(ListGraphType<StringGraphType>)); } } }
30.894737
88
0.65247
[ "MIT" ]
ianitor/ObjectServicePlatform
Osp/Backend/Ianitor.Osp.Backend.CoreServices/GraphQL/Types/SearchFilterDtoType.cs
587
C#
using System; using System.Runtime.InteropServices; namespace hds { public class AttributeClass1728 :GameObject { public Attribute Orientation = new Attribute(16, "Orientation"); public Attribute Position = new Attribute(24, "Position"); public Attribute HalfExtents = new Attribute(12, "HalfExtents"); public AttributeClass1728(string name,UInt16 _goid) : base(3, 0, name, _goid, 0xFFFFFFFF) { AddAttribute(ref Orientation, 0, -1); AddAttribute(ref Position, 1, -1); AddAttribute(ref HalfExtents, 2, -1); } } }
24.166667
68
0.677586
[ "MIT" ]
hdneo/mxo-hd
hds/resources/gameobjects/definitions/AttributeClasses/AttributeClass1728.cs
580
C#
// Decompiled with JetBrains decompiler // Type: Game.Server.Quests.TimeHelper // Assembly: Game.Server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null // MVID: 7994645F-6854-4AAC-A332-C61842D2DD9F // Assembly location: C:\Users\Pham Van Hungg\Desktop\Decompiler\Road\Game.Server.dll using System; namespace Game.Server.Quests { public class TimeHelper { public static int GetDaysBetween(DateTime min, DateTime max) { int num = (int) Math.Floor((min - DateTime.MinValue).TotalDays); return (int) Math.Floor((max - DateTime.MinValue).TotalDays) - num; } } }
29.85
85
0.721943
[ "MIT" ]
HuyTruong19x/DDTank4.1
Source Server/Game.Server/Server/Quests/TimeHelper.cs
599
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace Servidor { class Program { // Datos Recibidos Desde ElCliente. public static string data = null; public static void StartListening() { // Bufer de Datos paralosdatos recibidos byte[] bytes = new Byte[1024]; // Establece el punto deentrada final para el socket. // Dns.GetHostName devuelve el nombre del host donde correr la aplicacion IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 11000); // Crea un Socket TCP/IP x. Socket listener = new Socket(IPAddress.Any.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { listener.Bind(localEndPoint); listener.Listen(10); // Inicia a escuchas miestras llegan conexiones. while (true) { Console.WriteLine("Esperando por ceonexiones ..."); // el Programa es suspendido mientras espera oconexiones de entrada . Socket handler = listener.Accept(); data = null; // La conexion de entrada necesita ser procesada. while (true) { int bytesRec = handler.Receive(bytes); data += Encoding.ASCII.GetString(bytes, 0, bytesRec); } // Muestra los datos en la consola . Console.WriteLine("Texto recibido: {0}", data); string[] mensajedescompuestos = data.Split(','); string operacion = mensajedescompuestos[0]; double a = double.Parse(mensajedescompuestos[1]); double b = double.Parse(mensajedescompuestos[2]); double c = 0; switch(operacion) { case "suma": c = Aritmetica.getInstancia().sumar(a, b); break; case "resta": c = Aritmetica.getInstancia().restar(a, b); break; case "multiplicación": c = Aritmetica.getInstancia().multiplicar(a, b); break; case "división": c = Aritmetica.getInstancia().dividir(a, b); break; case "raíz": c = Aritmetica.getInstancia().raiz(a, b); break; case "potencia": c = Aritmetica.getInstancia().potencia(a, b); break; default: c = -1; break; } // Prepara los datos para responder al cliente. byte[] msg = Encoding.ASCII.GetBytes(c.ToString()); handler.Send(msg); handler.Shutdown(SocketShutdown.Both); handler.Close(); } } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.WriteLine("\nPresiones ENTER para continuar..."); Console.Read(); } public static int Main(String[] args) { StartListening(); return 0; } } }
35.672727
91
0.456167
[ "Apache-2.0" ]
cdanna5696/ProgramacionIIIdcs
Tarea Final/Servidor/Servidor/Program.cs
3,929
C#
using System; using System.Collections.Generic; using System.Text; namespace MarsRover_Core.Extensions { public static class EnumerationHelper { public static T ToEnum<T>(this string text) where T : struct { if (!Enum.TryParse(text, out T result)) throw new ArgumentOutOfRangeException($"Invalid {typeof(T).Name}: {text}"); return result; } public static IEnumerable<T> ToEnumList<T>(this string instructions) where T : struct { List<T> list = new List<T>(); foreach (var instruction in instructions) { list.Add(instruction.ToString().ToEnum<T>()); } return list; } } }
27.75
94
0.552124
[ "MIT" ]
N0bleA/MarsRover
MarsRover/MarsRover_Core/Extensions/EnumerationHelper.cs
779
C#
using Cauldron; using Cauldron.Activator; using Cauldron.Localization; using Cauldron.Reflection; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; namespace Cauldron.Consoles { /// <summary> /// Parses the parameters passed to the application /// </summary> public sealed class ParameterParser { internal const char ParameterKey = '-'; private Dictionary<IExecutionGroup, List<PropertyInfo>> activatedParameters = new Dictionary<IExecutionGroup, List<PropertyInfo>>(); private List<ExecutionGroupProperties> executionGroups; private bool isInitialized = false; private Locale locale; /// <summary> /// Initializes a new instance of the <see cref="ParameterParser"/> class /// </summary> /// <param name="executionGroups">The execution groups to parse to</param> public ParameterParser(params IExecutionGroup[] executionGroups) { if (Factory.HasContract(typeof(ILocalizationSource))) this.locale = Factory.Create<Locale>(); this.executionGroups = executionGroups .Select(x => new ExecutionGroupProperties { #if NETCORE Attribute = x.GetType().GetTypeInfo().GetCustomAttribute<ExecutionGroupAttribute>(), #else Attribute = x.GetType().GetCustomAttribute<ExecutionGroupAttribute>(), #endif ExecutionGroup = x }) .Where(x => x.Attribute != null) .OrderBy(x => x.Attribute.GroupIndex) .ToList(); } /// <summary> /// Gets or sets the <see cref="Console.ForegroundColor"/> of the description in the help text /// </summary> public ConsoleColor DescriptionColor { get; set; } = ConsoleColor.White; /// <summary> /// Gets or sets the <see cref="Console.ForegroundColor"/> of the group name in the help text /// </summary> public ConsoleColor GroupColor { get; set; } = ConsoleColor.White; /// <summary> /// Gets or sets the <see cref="Console.ForegroundColor"/> of the key in the help text /// </summary> public ConsoleColor KeyColor { get; set; } = ConsoleColor.Gray; /// <summary> /// Gets the parameters passed to the application /// </summary> public string[] Parameters { get; private set; } /// <summary> /// Gets or sets the <see cref="Console.ForegroundColor"/> of the usage example text in the help text /// </summary> public ConsoleColor UsageExampleColor { get; set; } = ConsoleColor.DarkGray; /// <summary> /// Starts the execution of the execution groups /// </summary> /// <returns>true if any of the execution group was executed; otherwise false</returns> public bool Execute() { if (!this.isInitialized) throw new Exception("Execute Parse(object, string[]) first before invoking Execute()"); if (this.activatedParameters.Count == 0) return false; var executableGroups = this.activatedParameters.Keys .Select(x => new { Attrib = this.executionGroups.FirstOrDefault(y => y.ExecutionGroup == x).Attribute, Group = x }) .OrderBy(x => x.Attrib.GroupIndex); foreach (var groups in executableGroups) { try { groups.Group.Execute(this); } catch { throw; } finally { Console.ResetColor(); } } return true; } /// <summary> /// Returns the property names of all active parameters /// </summary> /// <param name="executionGroup">The execution group</param> /// <returns>A list of property names of all active parameters</returns> public IList<string> GetActiveParameters(IExecutionGroup executionGroup) => this.activatedParameters[executionGroup].Select(x => x.Name).ToList(); /// <summary> /// Starts the parsing of the arguments /// </summary> /// <param name="args">A list of arguments that was passed to the application</param> public void Parse(string[] args) { if (this.isInitialized) throw new Exception("You cannot use the same instance of ParameterParser to parse another group of parameters. Please create a new instance."); this.Parameters = args; ParseGroups(this.executionGroups); var flatList = this.executionGroups.SelectMany(x => x.Parameters); // Search for dupletts and throw an exception if there is one... // Let the programer suffer var doubles = flatList .SelectMany(x => x.Parameters) .GroupBy(x => x) .Where(x => x.Skip(1).Any()) .Select(x => x.Key); if (doubles.Any()) throw new Exception("ParameterParser has found duplicate parameters in your parameter list. Please make sure that there are no doublets. " + doubles.Join(", ")); this.isInitialized = true; try { this.TryParseParameters(flatList, args); // Try to find out which groups were activated var activatedGroups = this.executionGroups.Where(x => this.activatedParameters.ContainsKey(x.ExecutionGroup)); // check if the isrequired parameters are set var requiredParameters = activatedGroups.SelectMany(x => x.Parameters.Where(y => y.Attribute.IsRequired && y.PropertyInfo.GetValue(x.ExecutionGroup) == null)); if (requiredParameters.Any()) throw new RequiredParametersMissingException("Unable to continue. Required parameters are not set.", requiredParameters.Select(x => x.Parameters.RandomPick()).ToArray()); // check if parameters with non optional values are set var nonOptionalValues = activatedGroups.SelectMany(x => x.Parameters.Where(y => this.activatedParameters[x.ExecutionGroup].Contains(y.PropertyInfo) && !y.Attribute.ValueOptional && y.PropertyInfo.GetValue(y.ExecutionGroup) == null)); if (nonOptionalValues.Any()) throw new RequiredValuesMissingException("Unable to continue. Parameters with non optional values have no values.", requiredParameters.Select(x => x.Parameters.RandomPick()).ToArray()); } catch { this.ShowHelp(); throw; } } /// <summary> /// Shows the help page of the application /// </summary> public void ShowHelp() { if (!this.isInitialized) throw new Exception("Execute ParameterParser.Parse(object, string[]) first before invoking ParameterParser.ShowHelp()"); var hasSource = Factory.HasContract(typeof(ILocalizationSource)); Console.Write("\n\n"); // Write the application info ConsoleUtils.WriteTable(new ConsoleTableColumn[] { new ConsoleTableColumn( hasSource? this.locale["application-name"] : "APPLICATION NAME:", hasSource? this.locale["version"] : "VERSION:", hasSource? this.locale["description"] : "DESCRIPTION:", hasSource? this.locale["product-name"] : "PRODUCT NAME:", hasSource? this.locale["publisher"] : "PUBLISHER:") { Foreground = this.KeyColor }, new ConsoleTableColumn( ApplicationInfo.ApplicationName ?? "", ApplicationInfo.ApplicationVersion?.ToString() ?? "", ApplicationInfo.Description ?? "", ApplicationInfo.ProductName ?? "", ApplicationInfo.ApplicationPublisher ?? "") { Foreground = this.DescriptionColor, Width = 2 } }); Console.Write("\n\n"); foreach (var group in this.executionGroups) { // Write the group name and divider Console.ForegroundColor = this.GroupColor; Console.WriteLine((hasSource ? this.locale[group.Attribute.GroupName] : group.Attribute.GroupName).PadRight(Console.WindowWidth - 1, '.')); var usageExampleText = hasSource ? $"{this.locale["usage-example"]}: " : "Usage example: "; // Write the usage example if there is one if (!string.IsNullOrEmpty(group.Attribute.UsageExample)) { Console.ForegroundColor = this.UsageExampleColor; Console.WriteLine(usageExampleText + Path.GetFileNameWithoutExtension(GetStartingAssembly().Location) + " " + group.Attribute.UsageExample); } // Write the parameter - description table ConsoleUtils.WriteTable(new ConsoleTableColumn[] { new ConsoleTableColumn(group.Parameters.Select(x=> x.Parameters.Where(y => !string.IsNullOrEmpty(y)).Join(", "))) { Foreground = this.KeyColor }, new ConsoleTableColumn(group.Parameters.Select(x=> { var description = hasSource? this.locale[x.Attribute.Description] : x.Attribute.Description; if(x.Attribute.IsRequired) return ReplaceKeywords( description + "\n!!" + (hasSource? this.locale["mandatory"] : "Mandatory"), x.Parameters.Last(), usageExampleText); return ReplaceKeywords(description, x.Parameters.Last(), usageExampleText); })) { Foreground = this.DescriptionColor, AlternativeForeground = this.UsageExampleColor, Width = 2 } }); Console.Write("\n"); } Console.ResetColor(); } private static Assembly GetStartingAssembly() { var assembly = Assembly.GetEntryAssembly(); #if !NETCORE if (assembly == null) assembly = Assembly.GetCallingAssembly(); if (assembly == null) assembly = Assembly.GetExecutingAssembly(); #endif return assembly; } private static void ParseGroups(IEnumerable<ExecutionGroupProperties> executionGroups) { foreach (var group in executionGroups) { var type = group.ExecutionGroup.GetType(); var parameters = type.GetPropertiesEx(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance) .Select(x => new { Property = x, Attrib = x.GetCustomAttribute<ParameterAttribute>() }) .Where(x => x.Attrib != null) .Select(x => new ExecutionGroupParameter(group.ExecutionGroup, x.Property, x.Attrib)); group.Parameters = parameters.ToList(); } } private static string ReplaceKeywords(string value, string parameter, string usageExampleText) => value .Replace("$ux$", $"\n!!{usageExampleText} {Path.GetFileNameWithoutExtension(GetStartingAssembly().Location)} {parameter}") .Replace("$mm$", $"\n!!{Path.GetFileNameWithoutExtension(GetStartingAssembly().Location)} {parameter}") .Replace("$me$", Path.GetFileNameWithoutExtension(GetStartingAssembly().Location)) .Replace("$pm$", parameter); private void TryParseParameters(IEnumerable<ExecutionGroupParameter> executionGroupParameters, string[] args) { var pairs = new Dictionary<ExecutionGroupParameter, List<string>>(); var currentList = new List<string>(); // Add default option if we have one var defaultParameter = executionGroupParameters.FirstOrDefault(x => x.Parameters.Any(y => y.Length == 0) /* Empty parameter is the default parameter */); if (defaultParameter != null) pairs.Add(defaultParameter, currentList); else // Just ignore default param currentList = null; foreach (var argument in args) { if (argument.Length == 0) continue; if (argument[0] == ParameterKey) { var match = executionGroupParameters.FirstOrDefault(x => x.Parameters.Any(y => y == argument)); if (match == null) throw new UnknownParameterException("Unknown parameter", argument); if (pairs.ContainsKey(match)) { currentList = pairs[match]; continue; } currentList = new List<string>(); pairs.Add(match, currentList); continue; } if (currentList != null) currentList.Add(argument); } // Remove the default parameter execution of we have other stuff in the queue if (pairs.Count > 1 && defaultParameter != null) pairs.Remove(defaultParameter); // assign the values foreach (var pair in pairs) { var executionGroupName = pair.Key.ExecutionGroup; if (this.activatedParameters.ContainsKey(executionGroupName)) this.activatedParameters[executionGroupName].Add(pair.Key.PropertyInfo); else this.activatedParameters.Add(executionGroupName, new List<PropertyInfo> { pair.Key.PropertyInfo }); // TODO - Add Custom converters // TODO - Add List, Collection and IEnumerable converters if (pair.Key.PropertyInfo.PropertyType.IsArray) { var childType = pair.Key.PropertyInfo.PropertyType.GetChildrenType(); pair.Key.PropertyInfo.SetValue(pair.Key.ExecutionGroup, pair.Value.Select(x => x.Convert(childType)).ToArray(childType)); } else if (pair.Key.PropertyInfo.PropertyType == typeof(bool)) pair.Key.PropertyInfo.SetValue(pair.Key.ExecutionGroup, true); else pair.Key.PropertyInfo.SetValue(pair.Key.ExecutionGroup, pair.Value.Join(" ").Convert(pair.Key.PropertyInfo.PropertyType)); } } } }
44.094118
249
0.572505
[ "MIT" ]
Capgemini/Cauldron
Shared/Cauldron.Consoles/ParameterParser.cs
14,994
C#
using System; using System.Collections.Generic; using System.Text; namespace LumiSoft.Net.IMAP { /// <summary> /// This class represents FETCH request BODY[] argument(data-item). Defined in RFC 3501. /// </summary> public class IMAP_t_Fetch_i_Body : IMAP_t_Fetch_i { private string m_Section = null; private int m_Offset = -1; private int m_MaxCount = -1; /// <summary> /// Default constructor. /// </summary> public IMAP_t_Fetch_i_Body() { } /// <summary> /// Default constructor. /// </summary> /// <param name="section">Body section. Value null means not specified.</param> /// <param name="offset">Data returning offset. Value -1 means not specified.</param> /// <param name="maxCount">Maximum number of bytes to return. Value -1 means not specified.</param> public IMAP_t_Fetch_i_Body(string section,int offset,int maxCount) { m_Section = section; m_Offset = offset; m_MaxCount = maxCount; } #region override method ToString /// <summary> /// Returns this as string. /// </summary> /// <returns>Returns this as string.</returns> public override string ToString() { StringBuilder retVal = new StringBuilder(); retVal.Append("BODY["); if(m_Section != null){ retVal.Append(m_Section); } retVal.Append("]"); if(m_Offset > -1){ retVal.Append("<" + m_Offset); if(m_MaxCount > -1){ retVal.Append("." + m_MaxCount); } retVal.Append(">"); } return retVal.ToString(); } #endregion #region Properties implementation /// <summary> /// Gets body section. Value null means not specified. /// </summary> public string Section { get{ return m_Section; } } /// <summary> /// Gets start offset. Value -1 means not specified. /// </summary> public int Offset { get{ return m_Offset; } } /// <summary> /// Gets maximum count of bytes to fetch. Value -1 means not specified. /// </summary> public int MaxCount { get{ return m_MaxCount; } } #endregion } }
28.202128
108
0.49189
[ "MIT" ]
bhuebschen/feuerwehrcloud-deiva
Mail/Net/IMAP/IMAP_t_Fetch_i_Body.cs
2,653
C#
using GalaSoft.MvvmLight; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using YouiToolkit.Models; namespace YouiToolkit.ViewModels { public class PageMaintainViewModel : ViewModelBase { /// <summary> /// 画直线 /// </summary> public PageMaintainModel maintainModel { get; set; } public PageMaintainViewModel() { maintainModel = PageMaintainModel.CreateInstance(); } } }
21.76
63
0.669118
[ "Unlicense" ]
MaQaQu/Tool
YouiToolkit/ViewModels/Maintain/PageMaintainViewModel.cs
552
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace InventoryManagementSystemAPI.DTOs { public class FindBarcodeItemDTO { [Required] public string Barcode { get; set; } public bool IsLoan { get; set; } } public class AddBarcodeItemDTO { [Required] public int ItemId { get; set; } [Required] public string Barcode { get; set; } public bool IsLoanItem { get; set; } public int Amount { get; set; } } public class RemoveBarcodeFromItemDTO { [Required] public string Barcode { get; set; } public bool IsConsumptionItem { get; set; } public int Amount { get; set; } } }
20.375
51
0.618405
[ "MIT" ]
Celestialy/Lagersystem-Vue-Preview
InventoryManagementSystemAPI/DTOs/Request/ItemBarcodeDTOs.cs
817
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.HDInsight.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// The Operations Management Suite (OMS) status response /// </summary> public partial class ClusterMonitoringResponse { /// <summary> /// Initializes a new instance of the ClusterMonitoringResponse class. /// </summary> public ClusterMonitoringResponse() { CustomInit(); } /// <summary> /// Initializes a new instance of the ClusterMonitoringResponse class. /// </summary> /// <param name="clusterMonitoringEnabled">The status of the Operations /// Management Suite (OMS) on the HDInsight cluster.</param> /// <param name="workspaceId">The workspace ID of the Operations /// Management Suite (OMS) on the HDInsight cluster.</param> public ClusterMonitoringResponse(bool? clusterMonitoringEnabled = default(bool?), string workspaceId = default(string)) { ClusterMonitoringEnabled = clusterMonitoringEnabled; WorkspaceId = workspaceId; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the status of the Operations Management Suite (OMS) on /// the HDInsight cluster. /// </summary> [JsonProperty(PropertyName = "ClusterMonitoringEnabled")] public bool? ClusterMonitoringEnabled { get; set; } /// <summary> /// Gets or sets the workspace ID of the Operations Management Suite /// (OMS) on the HDInsight cluster. /// </summary> [JsonProperty(PropertyName = "WorkspaceId")] public string WorkspaceId { get; set; } } }
35.296875
127
0.63745
[ "MIT" ]
216Giorgiy/azure-sdk-for-net
src/SDKs/HDInsight/Management.HDInsight/Generated/Models/ClusterMonitoringResponse.cs
2,259
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.CommandLineUtils; using Microsoft.Web.LibraryManager.Contracts; namespace Microsoft.Web.LibraryManager.Tools.Commands { /// <summary> /// Defines a command to allow cleaning the libman cache. /// </summary> internal class CacheCleanCommand : BaseCommand { public CacheCleanCommand(IHostEnvironment environment, bool throwOnUnexpectedArg = true) : base(throwOnUnexpectedArg, "clean", Resources.Text.CacheCleanCommandDesc, environment) { } /// <summary> /// Command argument that specifies the provider for which the cache should be cleaned. /// </summary> public CommandArgument Provider { get; private set; } public override BaseCommand Configure(CommandLineApplication parent = null) { base.Configure(parent); Provider = Argument("provider", Resources.Text.CacheCleanProviderArgumentDesc); return this; } protected override Task<int> ExecuteInternalAsync() { if (string.IsNullOrWhiteSpace(Provider.Value)) { try { if (Directory.Exists(HostInteractions.CacheDirectory)) { Directory.Delete(HostInteractions.CacheDirectory, true); } Logger.Log(Resources.Text.CacheCleanedMessage, LogLevel.Operation); } catch (Exception ex) { Logger.Log(string.Format(Resources.Text.CacheCleanFailed, ex.Message), LogLevel.Error); } } else if (Directory.Exists(Path.Combine(HostInteractions.CacheDirectory, Provider.Value))) { try { Directory.Delete(Path.Combine(HostInteractions.CacheDirectory, Provider.Value), true); Logger.Log(string.Format(Resources.Text.CacheForProviderCleanedMessage, Provider.Value), LogLevel.Operation); } catch (Exception ex) { Logger.Log(string.Format(Resources.Text.CacheCleanFailed, ex.Message), LogLevel.Error); } } else if (!ManifestDependencies.Providers.Any(p => p.Id == Provider.Value)) { throw new InvalidOperationException(string.Format(Resources.Text.ProviderNotInstalled, Provider.Value)); } return Task.FromResult(0); } } }
36.597403
129
0.598652
[ "Apache-2.0" ]
RobJohnston/LibraryManager
src/libman/Commands/CacheCleanCommand.cs
2,820
C#
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. #if STRIDE_GRAPHICS_API_DIRECT3D11 using System; using SharpDX.Direct3D11; using Stride.Graphics; using CommandList = Stride.Graphics.CommandList; namespace Stride.VirtualReality { internal class OculusOverlay : VROverlay, IDisposable { private readonly IntPtr ovrSession; internal IntPtr OverlayPtr; private readonly Texture[] textures; public OculusOverlay(IntPtr ovrSession, GraphicsDevice device, int width, int height, int mipLevels, int sampleCount) { int textureCount; this.ovrSession = ovrSession; OverlayPtr = OculusOvr.CreateQuadLayerTexturesDx(ovrSession, device.NativeDevice.NativePointer, out textureCount, width, height, mipLevels, sampleCount); if (OverlayPtr == IntPtr.Zero) { throw new Exception(OculusOvr.GetError()); } textures = new Texture[textureCount]; for (var i = 0; i < textureCount; i++) { var ptr = OculusOvr.GetQuadLayerTextureDx(ovrSession, OverlayPtr, OculusOvrHmd.Dx11Texture2DGuid, i); if (ptr == IntPtr.Zero) { throw new Exception(OculusOvr.GetError()); } textures[i] = new Texture(device); textures[i].InitializeFromImpl(new Texture2D(ptr), false); } } public override void Dispose() { } public override void UpdateSurface(CommandList commandList, Texture texture) { OculusOvr.SetQuadLayerParams(OverlayPtr, ref Position, ref Rotation, ref SurfaceSize, FollowHeadRotation); var index = OculusOvr.GetCurrentQuadLayerTargetIndex(ovrSession, OverlayPtr); commandList.Copy(texture, textures[index]); } } } #endif
37.140351
165
0.643836
[ "MIT" ]
DeZomB/stride
sources/engine/Stride.VirtualReality/OculusOVR/OculusOverlay.cs
2,117
C#
using Newtonsoft.Json; using System.ComponentModel; namespace Yandex.Weather.Data { /// <summary> /// Прогнозы по времени суток и 12-часовые прогнозы /// </summary> public class Parts { /// <summary> /// Прогноз на ночь. /// </summary> [DisplayName("Ночь")] [Description("Прогноз на ночь. Начало ночного периода соответствует времени начала суток. Для указания предстоящей ночной температуры используйте объект ночного прогноза следующего дня.")] [JsonProperty("night")] public Part Night { get; set; } /// <summary> /// Прогноз на утро. /// </summary> [DisplayName("Утро")] [Description("Прогноз на утро.")] [JsonProperty("morning")] public Part Morning { get; set; } /// <summary> /// Прогноз на день. /// </summary> [DisplayName("День")] [Description("Прогноз на день.")] [JsonProperty("day")] public Part Day { get; set; } /// <summary> /// Прогноз на вечер. /// </summary> [DisplayName("Вечер")] [Description("Прогноз на вечер.")] [JsonProperty("evening")] public Part Evening { get; set; } /// <summary> /// 12-часовой прогноз на день. /// </summary> [DisplayName("День. 12-часовой")] [Description("12-часовой прогноз на день.")] [JsonProperty("day_short")] public ShortPart DayShort { get; set; } /// <summary> /// 12-часовой прогноз на ночь текущих суток. /// </summary> [DisplayName("Ночь. 12-часовой")] [Description("12-часовой прогноз на ночь текущих суток.")] [JsonProperty("night_short")] public ShortPart NightShort { get; set; } } }
27.984615
196
0.55635
[ "MIT" ]
bankoViktor/yandex.weather
Data/Parts.cs
2,241
C#
using System; using System.Collections.Generic; using System.Linq; namespace School { public class School { private List<Student> students; private List<Course> courses; private List<Student> Students { get { return students; } set { if (value != null) { students = value; } else { throw new ArgumentException("Student cannot be null."); } } } private List<Course> Courses { get { return this.courses; } set { this.courses = value; } } public School() { this.Students = new List<Student>(); this.Courses = new List<Course>(); } public void AddCourse(Course course) { if (this.Courses.Contains(course)) { throw new InvalidOperationException("Such course already exsists!"); } else { this.Courses.Add(course); } } public void RemoveCourse(Course course) { if (this.Courses == null || this.Courses.Count == 0) { throw new InvalidOperationException("Couse list is empty!"); } if (this.Courses.Contains(course)) { this.Courses.Remove(course); } else { throw new InvalidOperationException("No such course in school!"); } } public void AddStudent(Student student) { if (IsStudentNumberTaken(this.Students, student)) { throw new InvalidOperationException("Such student with unique number exsists!"); } else { this.Students.Add(student); } } private bool IsStudentNumberTaken(List<Student> students, Student studentToCheckFor) { foreach (var student in students) { if (student.UniqueNumber == studentToCheckFor.UniqueNumber) { return true; } } return false; } public void RemoveStudent(Student student) { if (this.Students == null || this.Students.Count == 0) { throw new InvalidOperationException("Students list is empty!"); } if (this.Students.Contains(student)) { this.Students.Remove(student); } else { throw new ArgumentException("No such student in course!"); } } } }
24.677686
96
0.439384
[ "MIT" ]
d-georgiev-91/TelerikAcademy
Programming/HighQualityProgrammingCode/Unit-Test/School/School.cs
2,988
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.Domain.Transform; using Aliyun.Acs.Domain.Transform.V20180129; namespace Aliyun.Acs.Domain.Model.V20180129 { public class VerifyContactFieldRequest : RpcAcsRequest<VerifyContactFieldResponse> { public VerifyContactFieldRequest() : base("Domain", "2018-01-29", "VerifyContactField", "domain", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.Domain.Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.Domain.Endpoint.endpointRegionalType, null); } Method = MethodType.POST; } private string country; private string city; private string zhCity; private string telExt; private string province; private string zhRegistrantName; private string postalCode; private string lang; private string email; private string zhRegistrantOrganization; private string address; private string telArea; private string zhAddress; private string registrantType; private string domainName; private string telephone; private string zhProvince; private string registrantOrganization; private string userClientIp; private string registrantName; public string Country { get { return country; } set { country = value; DictionaryUtil.Add(QueryParameters, "Country", value); } } public string City { get { return city; } set { city = value; DictionaryUtil.Add(QueryParameters, "City", value); } } public string ZhCity { get { return zhCity; } set { zhCity = value; DictionaryUtil.Add(QueryParameters, "ZhCity", value); } } public string TelExt { get { return telExt; } set { telExt = value; DictionaryUtil.Add(QueryParameters, "TelExt", value); } } public string Province { get { return province; } set { province = value; DictionaryUtil.Add(QueryParameters, "Province", value); } } public string ZhRegistrantName { get { return zhRegistrantName; } set { zhRegistrantName = value; DictionaryUtil.Add(QueryParameters, "ZhRegistrantName", value); } } public string PostalCode { get { return postalCode; } set { postalCode = value; DictionaryUtil.Add(QueryParameters, "PostalCode", value); } } public string Lang { get { return lang; } set { lang = value; DictionaryUtil.Add(QueryParameters, "Lang", value); } } public string Email { get { return email; } set { email = value; DictionaryUtil.Add(QueryParameters, "Email", value); } } public string ZhRegistrantOrganization { get { return zhRegistrantOrganization; } set { zhRegistrantOrganization = value; DictionaryUtil.Add(QueryParameters, "ZhRegistrantOrganization", value); } } public string Address { get { return address; } set { address = value; DictionaryUtil.Add(QueryParameters, "Address", value); } } public string TelArea { get { return telArea; } set { telArea = value; DictionaryUtil.Add(QueryParameters, "TelArea", value); } } public string ZhAddress { get { return zhAddress; } set { zhAddress = value; DictionaryUtil.Add(QueryParameters, "ZhAddress", value); } } public string RegistrantType { get { return registrantType; } set { registrantType = value; DictionaryUtil.Add(QueryParameters, "RegistrantType", value); } } public string DomainName { get { return domainName; } set { domainName = value; DictionaryUtil.Add(QueryParameters, "DomainName", value); } } public string Telephone { get { return telephone; } set { telephone = value; DictionaryUtil.Add(QueryParameters, "Telephone", value); } } public string ZhProvince { get { return zhProvince; } set { zhProvince = value; DictionaryUtil.Add(QueryParameters, "ZhProvince", value); } } public string RegistrantOrganization { get { return registrantOrganization; } set { registrantOrganization = value; DictionaryUtil.Add(QueryParameters, "RegistrantOrganization", value); } } public string UserClientIp { get { return userClientIp; } set { userClientIp = value; DictionaryUtil.Add(QueryParameters, "UserClientIp", value); } } public string RegistrantName { get { return registrantName; } set { registrantName = value; DictionaryUtil.Add(QueryParameters, "RegistrantName", value); } } public override VerifyContactFieldResponse GetResponse(UnmarshallerContext unmarshallerContext) { return VerifyContactFieldResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
18.704871
136
0.620251
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-domain/Domain/Model/V20180129/VerifyContactFieldRequest.cs
6,528
C#
using System; namespace AutomationAssessment.DataAccess { public class Class1 { } }
10.888889
41
0.683673
[ "MIT" ]
philmcgaw/AutomationAssessment
AutomationAssessment.DataAccess/Class1.cs
100
C#
using Microsoft.Phone.Controls; using SuperMap.WindowsPhone.Core; namespace PhoneApp1 { public partial class MainPage : PhoneApplicationPage { // 构造函数 public MainPage() { InitializeComponent(); MyMap.ViewBounds = new Rectangle2D(-180, -90, 90, 180); } } }
18.222222
67
0.597561
[ "Apache-2.0" ]
SuperMap/iClient-for-Win8
iClient60ForWP8/WP8_test/Map_test/Map_ViewBounds_test/MainPage.xaml.cs
338
C#
using MathLibrary; using System; using System.Collections.Generic; using System.Text; namespace MathForGames { class Scene { private Actor[] _actors; private Matrix3 _transform = new Matrix3(); public bool Started { get; private set; } public Matrix3 World { get { return _transform; } } public Scene() { _actors = new Actor[0]; } //checks the collision of all the actors private void CheckCollision() { for (int i = 0; i < _actors.Length; i++) { for (int j = 0; j < _actors.Length; j++) { if (i >= _actors.Length) break; if (_actors[i].CheckCollision(_actors[j]) && i != j) _actors[i].OnCollision(_actors[j]); } } } //adds an actor public void AddActor(Actor actor) { //creating a new array with a size one greater than our old array Actor[] appendedArray = new Actor[_actors.Length + 1]; //copy values from the old array to the new array for (int i = 0; i < _actors.Length; i++) { appendedArray[i] = _actors[i]; } //set the last value in the new array to be the actor we want to add appendedArray[_actors.Length] = actor; //Set old array to hold values of the new arrat _actors = appendedArray; } //adds an actor with specific cordinates public void AddActor(Actor actor,float x, float y) { actor.LocalPosition = new Vector2(x, y); //creating a new array with a size one greater than our old array Actor[] appendedArray = new Actor[_actors.Length + 1]; //copy values from the old array to the new array for (int i = 0; i < _actors.Length; i++) { appendedArray[i] = _actors[i]; } //set the last value in the new array to be the actor we want to add appendedArray[_actors.Length] = actor; //Set old array to hold values of the new arrat _actors = appendedArray; } //removes the actor from the index public bool RemoveActor(int index) { //checks if the index is outside the range of the array if (index >= 0 || index >= _actors.Length) { return false; } bool actorRemoved = false; //creates a new array with a size one less than the old array Actor[] tempArray = new Actor[_actors.Length - 1]; //creates variable to access tempArray index int j = 0; //copy values from tthe old array to the new one for (int i = 0; i < _actors.Length; i++) { //if the current index is not the index that needs to be removed //add the value into the old array and increment j if (i != index) { tempArray[j] = _actors[i]; j++; } else { actorRemoved = true; if (_actors[i].Started) _actors[i].End(); } } //set the old array to be the tempArray _actors = tempArray; return false; } //removes a certain actor public bool RemoveActor(Actor actor) { //checks to see if the actor was null if (actor == null) { return false; } bool actorRemoved = false; Actor[] newArray = new Actor[_actors.Length - 1]; int j = 0; for (int i = 0; i < _actors.Length; i++) { if (actor != _actors[i]) { if (j < newArray.Length) { newArray[j] = _actors[i]; j++; } else { actorRemoved = true; if (actor.Started) actor.End(); } } } _actors = newArray; return actorRemoved; } public virtual void Start() { for (int i = 0; i < _actors.Length; i++) { _actors[i].Start(); } Started = true; } public virtual void Update(float deltaTime) { for (int i = 0; i < _actors.Length; i++) { if (!_actors[i].Started) { _actors[i].Start(); } _actors[i].Update(deltaTime); } } public virtual void Draw() { for (int i = 0; i < _actors.Length; i++) { _actors[i].Draw(); } CheckCollision(); } public virtual void End() { for (int i = 0; i < _actors.Length; i++) { if (_actors[i].Started) _actors[i].End(); _actors[i].Draw(); } Started = false; } } }
31.243243
81
0.418685
[ "MIT" ]
Noaheasley/AWeekOfZeds
MathForGames/Scene.cs
5,782
C#
using System; namespace Callbag.Basics.Sink { public static class SinkExtension { public static void ForEach<T>(this ISource<T> source, in Action<T> operation) { source.Greet(new ForEach<T>(operation)); } } }
21.5
85
0.612403
[ "CC0-1.0" ]
mr-rampage/csharp-callbags
Callbag.Basics/Sink/Sink.cs
260
C#
// Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) : [www.daimto.com](http://www.daimto.com/) // // 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0 // Template File Name: APIKey.tt // Build date: 2017-10-08 // C# generater version: 1.0.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // About // // Unoffical sample for the Cloudvideointelligence v1beta1 API for C#. // This sample is designed to be used with the Google .Net client library. (https://github.com/google/google-api-dotnet-client) // // API Description: Cloud Video Intelligence API. // API Documentation Link https://cloud.google.com/video-intelligence/docs/ // // Discovery Doc https://www.googleapis.com/discovery/v1/apis/Cloudvideointelligence/v1beta1/rest // //------------------------------------------------------------------------------ // Installation // // This sample code uses the Google .Net client library (https://github.com/google/google-api-dotnet-client) // // NuGet package: // // Location: https://www.nuget.org/packages/Google.Apis.Cloudvideointelligence.v1beta1/ // Install Command: PM> Install-Package Google.Apis.Cloudvideointelligence.v1beta1 // //------------------------------------------------------------------------------ using Google.Apis.Cloudvideointelligence.v1beta1; using Google.Apis.Services; using System; namespace GoogleSamplecSharpSample.Cloudvideointelligencev1beta1.Auth { /// <summary> /// When calling APIs that do not access private user data, you can use simple API keys. These keys are used to authenticate your /// application for accounting purposes. The Google API Console documentation also describes API keys. /// https://support.google.com/cloud/answer/6158857 /// </summary> public static class ApiKeyExample { /// <summary> /// Get a valid CloudvideointelligenceService for a public API Key. /// </summary> /// <param name="apiKey">API key from Google Developer console</param> /// <returns>CloudvideointelligenceService</returns> public static CloudvideointelligenceService GetService(string apiKey) { try { if (string.IsNullOrEmpty(apiKey)) throw new ArgumentNullException("api Key"); return new CloudvideointelligenceService(new BaseClientService.Initializer() { ApiKey = apiKey, ApplicationName = string.Format("{0} API key example", System.Diagnostics.Process.GetCurrentProcess().ProcessName), }); } catch (Exception ex) { throw new Exception("Failed to create new Cloudvideointelligence Service", ex); } } } }
44.82716
135
0.624621
[ "Apache-2.0" ]
AhmerRaza/Google-Dotnet-Samples
Samples/Cloud Video Intelligence API/v1beta1/APIKey.cs
3,633
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; static class Tags { public static readonly ushort SpawnPlayerTag = 0; public static readonly ushort MovePlayerTag = 1; public static readonly ushort DespawnPlayerTag = 2; public static readonly ushort SpawnFoodTag = 3; public static readonly ushort MoveFoodTag = 4; public static readonly ushort SetRadiusTag = 5; }
25.294118
55
0.755814
[ "MIT" ]
DarkRiftNetworking/AgarUnityComplete
Assets/Tags.cs
432
C#
//----------------------------------------------------------------------- // <copyright> // // Copyright (c) TU Chemnitz, Prof. Technische Thermodynamik // Written by Noah Pflugradt. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the distribution. // All advertising materials mentioning features or use of this software must display the following acknowledgement: // “This product includes software developed by the TU Chemnitz, Prof. Technische Thermodynamik and its contributors.” // Neither the name of the University nor the names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, // BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, S // PECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; L // OSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // </copyright> //----------------------------------------------------------------------- #region using System.Collections.ObjectModel; using Database.Helpers; using Database.Tables.BasicHouseholds; using JetBrains.Annotations; using LoadProfileGenerator.Presenters.BasicElements; using LoadProfileGenerator.Views.SpecialViews; #endregion namespace LoadProfileGenerator.Presenters.SpecialViews { internal class AffordancesWithRealDevicesPresenter : PresenterBaseWithAppPresenter<AffordancesWithRealDevicesView> { [ItemNotNull] [NotNull] private readonly ObservableCollection<AffEntry> _selectedAffordances = new ObservableCollection<AffEntry>(); public AffordancesWithRealDevicesPresenter([NotNull] ApplicationPresenter applicationPresenter, [NotNull] AffordancesWithRealDevicesView view) : base(view, "HeaderString", applicationPresenter) { Refresh(); } [NotNull] [UsedImplicitly] public string HeaderString => "Affordance with Real Devices View"; [ItemNotNull] [NotNull] [UsedImplicitly] public ObservableCollection<AffEntry> SelectedAffordances => _selectedAffordances; public override void Close(bool saveToDB, bool removeLast = false) { ApplicationPresenter.CloseTab(this, removeLast); } public override bool Equals(object obj) { var presenter = obj as AffordancesWithRealDevicesPresenter; return presenter?.HeaderString.Equals(HeaderString) == true; } public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hash = 17; // Suitable nullity checks etc, of course :) hash = hash * 23 + TabHeaderPath.GetHashCode(); return hash; } } public void Refresh() { _selectedAffordances.Clear(); var affordances = Sim.Affordances.Items; foreach (var affordance in affordances) { foreach (var device in affordance.AffordanceDevices) { if (device.Device?.AssignableDeviceType == AssignableDeviceType.Device) { var add = true; // double check if this is a category to ignore like f.ex. furniture var rd = device.Device as RealDevice; if (rd?.DeviceCategory != null) { if (rd.DeviceCategory.IgnoreInRealDeviceViews) { add = false; } } if (add) { SelectedAffordances.Add(new AffEntry(affordance, device.Device)); } } } } } public class AffEntry { public AffEntry([NotNull] Affordance affordance, [NotNull] IAssignableDevice devices) { Affordance = affordance; Device = devices; } [NotNull] [UsedImplicitly] public Affordance Affordance { [UsedImplicitly] get; } [NotNull] [UsedImplicitly] public IAssignableDevice Device { get; } } } }
43.231405
145
0.632575
[ "MIT" ]
kyleniemeyer/LoadProfileGenerator
WpfApplication1/Presenters/SpecialViews/AffordancesWithRealDevicesPresenter.cs
5,237
C#
using Synuit.Toolkit.AuditLogging.EntityFramework.Entities; using Synuit.Toolkit.AuditLogging.Events; using Synuit.Toolkit.AuditLogging.Helpers.JsonHelpers; namespace Synuit.Toolkit.AuditLogging.EntityFramework.Mapping { public static class AuditMapping { public static TAuditLog MapToEntity<TAuditLog>(this AuditEvent auditEvent) where TAuditLog : AuditLog, new() { var auditLog = new TAuditLog { Event = auditEvent.Event, Source = auditEvent.Source, SubjectIdentifier = auditEvent.SubjectIdentifier, SubjectName = auditEvent.SubjectName, SubjectType = auditEvent.SubjectType, Category = auditEvent.Category, Data = AuditLogSerializer.Serialize(auditEvent, AuditLogSerializer.BaseAuditEventJsonSettings), Action = auditEvent.Action == null ? null : AuditLogSerializer.Serialize(auditEvent.Action), SubjectAdditionalData = auditEvent.SubjectAdditionalData == null ? null : AuditLogSerializer.Serialize(auditEvent.SubjectAdditionalData) }; return auditLog; } } }
42.857143
152
0.6675
[ "MIT" ]
Synuit-Platform/Synuit.Toolkit
Synuit.Toolkit.AuditLogging/src/Synuit.ToolkitAuditLogging.EntityFramework/Mapping/AuditMapping.cs
1,202
C#
using System.Linq; using MedicalExaminer.Common.ConnectionSettings; using MedicalExaminer.Common.Queries.Permissions; using MedicalExaminer.Common.Services.Permissions; using MedicalExaminer.Models; using MedicalExaminer.Models.Enums; using Xunit; namespace MedicalExaminer.API.Tests.Services.Permission { public class InvalidUserPermissionUpdateServiceTests : ServiceTestsBase< InvalidUserPermissionQuery, UserConnectionSettings, bool, MeUser, InvalidUserPermissionUpdateService> { private MeUser user1 = new MeUser { UserId = "UserId1", Permissions = new[] { new MEUserPermission { PermissionId = "DuplicatePermissionID", LocationId = "SiteId", UserRole = UserRoles.MedicalExaminer }, new MEUserPermission { PermissionId = "NotDuplicatePermissionID", LocationId = "SiteId", UserRole = UserRoles.MedicalExaminer } } }; private MeUser duplicatePermissionUser = new MeUser { UserId = "UserId2", Permissions = new[] { new MEUserPermission { PermissionId = "DuplicatePermissionID", LocationId = "NationalId", UserRole = UserRoles.MedicalExaminer }, new MEUserPermission { PermissionId = "DuplicatePermissionID", LocationId = "NationalId", UserRole = UserRoles.MedicalExaminerOfficer } } }; private MeUser nullPermissionUser = new MeUser { UserId = "UserId2", Permissions = new[] { new MEUserPermission { PermissionId = null, LocationId = "NationalId", UserRole = UserRoles.MedicalExaminer }, new MEUserPermission { PermissionId = null, LocationId = "NationalId", UserRole = UserRoles.MedicalExaminerOfficer } } }; private MeUser whiteSpaceStringEmptyPermissionUser = new MeUser { UserId = "UserId2", Permissions = new[] { new MEUserPermission { PermissionId = string.Empty, LocationId = "NationalId", UserRole = UserRoles.MedicalExaminer }, new MEUserPermission { PermissionId = "", LocationId = "NationalId", UserRole = UserRoles.MedicalExaminerOfficer } } }; [Fact] public async void No_Update_Valid_PermissionIDs_When_No_Duplicate_PermissionIDs_Exists() { // Arrange var query = new InvalidUserPermissionQuery(); var user2permissionId1 = user1.Permissions.First().PermissionId; var user2permissionId2 = user1.Permissions.Last().PermissionId; // Act var result = await Service.Handle(query); // Assert Assert.Equal(user1.Permissions.First().PermissionId, user2permissionId1); Assert.Equal(user1.Permissions.Last().PermissionId, user2permissionId2); } [Fact] public async void Update_Invalid_PermissionIDs_When_Duplicate_PermissionIDs_Exists() { // Arrange var query = new InvalidUserPermissionQuery(); var user2permissionId1 = duplicatePermissionUser.Permissions.First().PermissionId; var user2permissionId2 = duplicatePermissionUser.Permissions.Last().PermissionId; // Act var result = await Service.Handle(query); // Assert Assert.NotEqual(duplicatePermissionUser.Permissions.First().PermissionId, user2permissionId1); Assert.NotEqual(duplicatePermissionUser.Permissions.Last().PermissionId, user2permissionId2); } [Fact] public async void Update_Invalid_PermissionIDs_When_Null_PermissionIDs_Exists() { // Arrange var query = new InvalidUserPermissionQuery(); // Act var result = await Service.Handle(query); // Assert Assert.NotNull(nullPermissionUser.Permissions.First().PermissionId); Assert.NotNull(nullPermissionUser.Permissions.Last().PermissionId); } [Fact] public async void Update_Invalid_PermissionIDs_When_WhiteSpace_PermissionIDs_Exists() { // Arrange var query = new InvalidUserPermissionQuery(); // Act var result = await Service.Handle(query); // Assert Assert.NotEqual(whiteSpaceStringEmptyPermissionUser.Permissions.First().PermissionId, string.Empty); Assert.NotEqual(whiteSpaceStringEmptyPermissionUser.Permissions.Last().PermissionId, string.Empty); } protected override MeUser[] GetExamples() { return new[] { user1, duplicatePermissionUser, nullPermissionUser, whiteSpaceStringEmptyPermissionUser }; } } }
33.335294
112
0.548615
[ "MIT" ]
neiltait/medex_api_pub
MedicalExaminer.API.Tests/Services/Permission/InvalidUserPermissionUpdateServiceTests.cs
5,669
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.EntityFrameworkCore.Infrastructure; namespace Microsoft.EntityFrameworkCore.Metadata.Internal { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public class StoreFunction : TableBase, IStoreFunction { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public StoreFunction(IRuntimeDbFunction dbFunction, RelationalModel model) : base(dbFunction.Name, dbFunction.Schema, model) { DbFunctions = new SortedDictionary<string, IDbFunction>(StringComparer.Ordinal) { { dbFunction.ModelName, dbFunction } }; IsBuiltIn = dbFunction.IsBuiltIn; ReturnType = dbFunction.StoreType; Parameters = new StoreFunctionParameter[dbFunction.Parameters.Count]; for (var i = 0; i < dbFunction.Parameters.Count; i++) { Parameters[i] = new StoreFunctionParameter(this, (IRuntimeDbFunctionParameter)dbFunction.Parameters[i]); } dbFunction.StoreFunction = this; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual SortedDictionary<string, IDbFunction> DbFunctions { get; } /// <inheritdoc /> public virtual bool IsBuiltIn { get; } /// <inheritdoc /> public virtual string? ReturnType { get; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual StoreFunctionParameter[] Parameters { get; } /// <inheritdoc /> public override IColumnBase? FindColumn(IProperty property) => property.GetFunctionColumnMappings() .FirstOrDefault(cm => cm.TableMapping.Table == this) ?.Column; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public override string ToString() => ((IStoreFunction)this).ToDebugString(MetadataDebugStringOptions.SingleLineDefault); /// <inheritdoc /> IEnumerable<IFunctionMapping> IStoreFunction.EntityTypeMappings { [DebuggerStepThrough] get => EntityTypeMappings.Cast<IFunctionMapping>(); } /// <inheritdoc /> IEnumerable<IFunctionColumn> IStoreFunction.Columns { [DebuggerStepThrough] get => Columns.Values.Cast<IFunctionColumn>(); } /// <inheritdoc /> IEnumerable<IStoreFunctionParameter> IStoreFunction.Parameters { [DebuggerStepThrough] get => Parameters; } /// <inheritdoc /> IEnumerable<IDbFunction> IStoreFunction.DbFunctions { [DebuggerStepThrough] get => DbFunctions.Values; } /// <inheritdoc /> [DebuggerStepThrough] IFunctionColumn? IStoreFunction.FindColumn(string name) => (IFunctionColumn?)base.FindColumn(name); /// <inheritdoc /> [DebuggerStepThrough] IFunctionColumn? IStoreFunction.FindColumn(IProperty property) => (IFunctionColumn?)FindColumn(property); } }
46.470085
133
0.653669
[ "MIT" ]
aayjaychan/efcore
src/EFCore.Relational/Metadata/Internal/StoreFunction.cs
5,437
C#
using System.Runtime.Serialization; using System.Xml.Serialization; namespace API.RareCarat.Example.Model { /// <summary> /// Certificated grading for the diamond's fluorescence. /// </summary> public enum FluorescenceGrade { /// <summary> /// No fluorescence. /// </summary> None = 0, /// <summary> /// No fluorescence. /// </summary> Negligible = 0, /// <summary> /// Faint fluorescence. /// </summary> Faint = 1, /// <summary> /// Medium fluorescence. /// </summary> Medium = 2, /// <summary> /// Strong fluorescence. /// </summary> Strong = 3, /// <summary> /// Very strong fluorescence. /// </summary> [EnumMember(Value = "Very Strong")] VeryStrong = 4, /// <summary> /// Unknown fluorescence. /// </summary> Unknown = 999 } }
23.571429
60
0.483838
[ "Apache-2.0" ]
RareCarat/api-example-dotnet
src/Web/Model/Diamond/FluorescenceGrade.cs
992
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.StorageCache.Inputs { /// <summary> /// Rule to place restrictions on portions of the cache namespace being presented to clients. /// </summary> public sealed class NfsAccessRuleArgs : Pulumi.ResourceArgs { /// <summary> /// Access allowed by this rule. /// </summary> [Input("access", required: true)] public InputUnion<string, Pulumi.AzureNextGen.StorageCache.NfsAccessRuleAccess> Access { get; set; } = null!; /// <summary> /// GID value that replaces 0 when rootSquash is true. /// </summary> [Input("anonymousGID")] public Input<string>? AnonymousGID { get; set; } /// <summary> /// UID value that replaces 0 when rootSquash is true. /// </summary> [Input("anonymousUID")] public Input<string>? AnonymousUID { get; set; } /// <summary> /// Filter applied to the scope for this rule. The filter's format depends on its scope. 'default' scope matches all clients and has no filter value. 'network' scope takes a filter in CIDR format (for example, 10.99.1.0/24). 'host' takes an IP address or fully qualified domain name as filter. If a client does not match any filter rule and there is no default rule, access is denied. /// </summary> [Input("filter")] public Input<string>? Filter { get; set; } /// <summary> /// Map root accesses to anonymousUID and anonymousGID. /// </summary> [Input("rootSquash")] public Input<bool>? RootSquash { get; set; } /// <summary> /// Scope for this rule. The scope and filter determine which clients match the rule. /// </summary> [Input("scope", required: true)] public InputUnion<string, Pulumi.AzureNextGen.StorageCache.NfsAccessRuleScope> Scope { get; set; } = null!; /// <summary> /// For the default policy, allow access to subdirectories under the root export. If this is set to no, clients can only mount the path '/'. If set to yes, clients can mount a deeper path, like '/a/b'. /// </summary> [Input("submountAccess")] public Input<bool>? SubmountAccess { get; set; } /// <summary> /// Allow SUID semantics. /// </summary> [Input("suid")] public Input<bool>? Suid { get; set; } public NfsAccessRuleArgs() { AnonymousGID = "-2"; AnonymousUID = "-2"; } } }
38.808219
392
0.614543
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/StorageCache/Inputs/NfsAccessRuleArgs.cs
2,833
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; namespace Ninject.AzureFunctions.Tests.Utility { public class FakeHttpRequest<T> : HttpRequest,IDisposable { public FakeHttpRequest(T body) { Body = new MemoryStream(); Writer = new StreamWriter(Body); var serializedBody = JsonConvert.SerializeObject(body); Writer.WriteLine(serializedBody); Writer.Flush(); Body.Seek(0, SeekOrigin.Begin); } public StreamWriter Writer { get; set; } public override Task<IFormCollection> ReadFormAsync(CancellationToken cancellationToken = new CancellationToken()) { throw new NotImplementedException(); } public override HttpContext HttpContext { get; } public override string Method { get; set; } public override string Scheme { get; set; } public override bool IsHttps { get; set; } public override HostString Host { get; set; } public override PathString PathBase { get; set; } public override PathString Path { get; set; } public override QueryString QueryString { get; set; } public override IQueryCollection Query { get; set; } public override string Protocol { get; set; } public override IHeaderDictionary Headers { get; } public override IRequestCookieCollection Cookies { get; set; } public override long? ContentLength { get; set; } public override string ContentType { get; set; } public override Stream Body { get; set; } public override bool HasFormContentType { get; } public override IFormCollection Form { get; set; } public void Dispose() { Body?.Dispose(); Writer?.Dispose(); } } }
33.416667
122
0.638404
[ "MIT" ]
SebastianAtWork/AzureFunctions.Plus
source/Ninject.AzureFunctions.Tests/Utility/FakeHttpRequest.cs
2,007
C#
/* ============================================================================== * 功能描述:TreeNode * 创 建 者:gz * 创建日期:2017/4/19 12:20:32 * ==============================================================================*/ using System; namespace Tree.TreeLib { /// <summary> /// TreeNode /// Definition for a binary tree node. /// </summary> public class TreeNode { public TreeNode(int x) { val = x; } public int val; public TreeNode left; public TreeNode right; public bool isLeaf() { return left == null && right == null; } public int Height { get { if (this == null) return 0; return 1 + Math.Max(height(this.left), height(this.right)); } } private int height(TreeNode node) { if (node == null) return 0; return 1 + Math.Max(height(node.left), height(node.right)); } } }
21.7
83
0.37788
[ "MIT" ]
Devin-X/leetcode-csharp
Tree/Tree.TreeLib/TreeNode.cs
1,115
C#
using Suigetsu.Core.Extensions; namespace Suigetsu.Core.Util { /// <summary> /// Utility methods for the <see cref="T:System.Type" /> class and generic objects. /// </summary> public static class TypeUtils { /// <summary> /// <para>Tries to instantiate the given value/primitive type.</para> /// Shortcut for: <seealso cref="M:Suigetsu.Core.Extensions.TypeExtensions.Default(System.Type)" /> /// </summary> public static T Default<T>() => (T)typeof(T).Default(); } }
32.058824
111
0.605505
[ "MIT" ]
fc1943s/Suigetsu
v1-cs/Core/Suigetsu.Core/Util/TypeUtils.cs
547
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using System.Data.Linq; namespace WcfServer { public sealed class NWindMtomService : NWindService { } public sealed class NWindTextService : NWindService { } public abstract class NWindService : INWindService { static OrderSet SharedLoad() { OrderSet result = new OrderSet(); using (var ctx = new NWindDataContext()) { DataLoadOptions options = new DataLoadOptions(); options.LoadWith<Order>(order => order.Order_Details); ctx.LoadOptions = options; result.Orders.AddRange(ctx.Orders); } return result; } public OrderSet LoadFoo() { return SharedLoad(); } public OrderSet LoadBar() { return SharedLoad(); } public OrderSet RoundTripFoo(OrderSet set) { return set; } public OrderSet RoundTripBar(OrderSet set) { return set; } } [DataContract] public class OrderSet { public OrderSet() { Orders = new List<Order>(); } [DataMember(Order = 1)] public List<Order> Orders { get; private set; } } }
24
71
0.545082
[ "Apache-2.0" ]
0xec/protobuf-net
WcfPerfTest/WcfServer/NWindService.svc.cs
1,466
C#
using UnityEngine; using System.Collections; public class FlyMovement : Movement { public override IEnumerator Traverse (Tile tile) { // Store the distance between the start tile and target tile float dist = Mathf.Sqrt(Mathf.Pow(tile.pos.x - unit.tile.pos.x, 2) + Mathf.Pow(tile.pos.y - unit.tile.pos.y, 2)); yield return StartCoroutine(base.Traverse(tile)); // Fly high enough not to clip through any ground tiles float y = Tile.stepHeight * 10; float duration = (y - jumper.position.y) * 0.5f; Tweener tweener = jumper.MoveToLocal(new Vector3(0, y, 0), duration, EasingEquations.EaseInOutQuad); while (tweener != null) yield return null; // Turn to face the general direction Directions dir; Vector3 toTile = (tile.center - transform.position); if (Mathf.Abs(toTile.x) > Mathf.Abs(toTile.z)) dir = toTile.x > 0 ? Directions.East : Directions.West; else dir = toTile.z > 0 ? Directions.North : Directions.South; yield return StartCoroutine(Turn(dir)); // Move to the correct position duration = dist * 0.5f; tweener = transform.MoveTo(tile.center, duration, EasingEquations.EaseInOutQuad); while (tweener != null) yield return null; // Land duration = (y - tile.center.y) * 0.5f; tweener = jumper.MoveToLocal(Vector3.zero, 0.5f, EasingEquations.EaseInOutQuad); while (tweener != null) yield return null; } }
33.609756
115
0.706821
[ "MIT" ]
Spex130/TacticsPunk
Assets/Scripts/View Model Component/Movement Types/FlyMovement.cs
1,380
C#
using System; using System.Collections.Generic; namespace Seekatar.Interfaces { /// <summary> /// Factory for discovering types from assemblies then creating them on demand /// </summary> /// <typeparam name="T">type of object to serve up</typeparam> public interface IObjectFactory<T> where T : class { /// <summary> /// Get the instance of an object type that this factory loaded by name /// </summary> /// <param name="name">name that matches with ObjectName</param> /// <returns>The instance or null</returns> T? GetInstance(string name); /// <summary> /// Get the instance of an object type that this factory loaded by Type /// </summary> /// <param name="type">type that has been registered</param> /// <returns>The instance or null</returns> T? GetInstance(Type type); /// <summary> /// Get a list of the loaded types. /// </summary> IReadOnlyDictionary<string, Type> LoadedTypes { get; } } }
31.205882
82
0.606032
[ "MIT" ]
Seekatar/Tools-DotNet
src/Tools/Interfaces/IObjectFactory.cs
1,061
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CustomObject : MonoBehaviour, IPhylloEffected { protected Vector3 _currentPos; protected Vector3 _targetPos; protected float _posLerpSpeed; public static CustomObject Create(GameObject prefab) { CustomObject obj = prefab.AddComponent<CustomObject>(); return obj; } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void ChangeScale(float size) { transform.localScale = new Vector3(size, size, size); } public void LerpToTarget() { transform.localPosition = Vector3.Lerp(transform.localPosition, _targetPos, _posLerpSpeed); } public void SetLerpSpeed(float speed) { _posLerpSpeed = speed; } public void SetTargetPosition(Vector3 newEndPos) { _targetPos = newEndPos; } }
20.510638
99
0.674274
[ "MIT" ]
EvgenyTimoshin/Game-Engines-1-Assignment-Procedural-Audio-Visuals
ProceduralSoundViz/Assets/Scripts/CustomObject.cs
966
C#
using System; using System.Collections.Generic; using System.Text; namespace puck.core.Abstract { public interface I_BaseModel { public Guid Id { get; set; } public Guid ParentId { get; set; } public String NodeName { get; set; } public string LastEditedBy { get; set; } public string CreatedBy { get; set; } public string Path { get; set; } public DateTime Created { get; set; } public DateTime Updated { get; set; } public int Revision { get; set; } public string Variant { get; set; } public bool Published { get; set; } public int SortOrder { get; set; } public string TemplatePath { get; set; } public string TypeChain { get; set; } public string Type { get; set; } public List<string> References { get; set; } } }
31.925926
52
0.597448
[ "MIT" ]
jules-source/puck-core
core/Abstract/I_BaseModel.cs
864
C#
using OpenQA.Selenium; using System.Collections.Generic; using Website.PageObjects.Controls; namespace Website.PageObjects { /// <summary> /// Step3 page Object /// </summary> public class Step3 : BasePage { private readonly IWebDriver webDriver; private readonly string PageName = "/step3.html"; private IWebElement LinkStep1 => webDriver.FindElement(By.Id("LinkStep1")); private IWebElement SelectedProtein => webDriver.FindElement(By.Id("SelectedProtein")); private IWebElement SelectedML => webDriver.FindElement(By.Id("SelectedML")); private IWebElement ProteinSizerData => webDriver.FindElement(By.Id("ProteinSizerData")); private IWebElement Regenerate => webDriver.FindElement(By.Id("Regenerate")); private readonly ProteinDataTable proteinDataTable; public Step3(IWebDriver webDriver) : base(webDriver) { this.webDriver = webDriver; PODriver.GotoURL(webDriver, PageName); proteinDataTable = new ProteinDataTable(ProteinSizerData); } //properties public string LinkStep1text { get { return LinkStep1.GetAttribute("innerText"); } } public string SelectedProteinText { get { return SelectedProtein.GetAttribute("innerText"); } } public string SelectedMLText { get { return SelectedML.GetAttribute("innerText"); } } public ProteinDataTable ProteinDataTable { get { return proteinDataTable; } } //methods public Index ClickLinkStep1() { LinkStep1.Click(); return new Index(webDriver); } public Step3 ClickRegenerate() { Regenerate.Click(); return this; } public List<List<string>> GetproteinData() { return ProteinDataTable.GetTableContents(); } } }
35.363636
104
0.630848
[ "MIT" ]
darrenudaiyan/SeleniumFramework
Selenium.Framework/Website.PageObjects/Pages/Step3.cs
1,947
C#
// SPDX-License-Identifier: Apache-2.0 // Licensed to the Ed-Fi Alliance under one or more agreements. // The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. // See the LICENSE and NOTICES files in the project root for more information. using System.Linq; using System.Net.Http.Formatting; using System.Web.Http; using EdFi.Ods.Api.Architecture; using EdFi.Ods.Api.Services.Filters; using EdFi.Ods.Common; using EdFi.Ods.Common.Metadata; using EdFi.Ods.Common.Security; namespace EdFi.Ods.Api.Startup.HttpConfigurators { public class ProfilesHttpConfigurator : IHttpConfigurator { private readonly IApiKeyContextProvider _apiKeyContextProvider; private readonly IProfileResourceNamesProvider _profileResourceNamesProvider; public ProfilesHttpConfigurator(IApiKeyContextProvider apiKeyContextProvider, IProfileResourceNamesProvider profileResourceNamesProvider) { _apiKeyContextProvider = Preconditions.ThrowIfNull(apiKeyContextProvider, nameof(apiKeyContextProvider)); _profileResourceNamesProvider = Preconditions.ThrowIfNull( profileResourceNamesProvider, nameof(profileResourceNamesProvider)); } public void Configure(HttpConfiguration config) { Preconditions.ThrowIfNull(config, nameof(config)); ConfigureProfilesJsonSerializer(config); ConfigureProfilesAuthorizationFilter(config); HttpConfigHelper.ConfigureJsonFormatter(config); } private void ConfigureProfilesJsonSerializer(HttpConfiguration config) { // Replace existing JSON formatter to be profiles-aware var existingJsonFormatter = config.Formatters.SingleOrDefault(f => f is JsonMediaTypeFormatter); // Remove the original one if (existingJsonFormatter != null) { config.Formatters.Remove(existingJsonFormatter); } // Add our customized json formatter, supporting dynamic addition of media types for deserializing messages config.Formatters.Insert(0, new ProfilesContentTypeAwareJsonMediaTypeFormatter()); } private void ConfigureProfilesAuthorizationFilter(HttpConfiguration config) { config.Filters.Add(new ProfilesAuthorizationFilter(_apiKeyContextProvider, _profileResourceNamesProvider)); } } }
39.015873
119
0.722945
[ "Apache-2.0" ]
gmcelhanon/Ed-Fi-ODS-1
Application/EdFi.Ods.Api.Startup/HttpConfigurators/ProfilesHttpConfigurator.cs
2,460
C#
using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace DancingGoat.Models { public class ConfirmSubscriptionModel { [Required] public string SubscriptionHash { get; set; } public string DateTime { get; set; } [Bindable(false)] public string ConfirmationResult { get; set; } } }
20.222222
54
0.667582
[ "MIT" ]
Kentico/xperience-module-intercom
src/DancingGoatCore/Models/Subscription/ConfirmSubscriptionModel.cs
366
C#
using System.Net; using FubuCore; using FubuMVC.Core.Continuations; namespace FubuMVC.Core.Resources.Etags { public class ETagHandler<T> { private readonly IEtagCache _cache; //private readonly IETagGenerator<T> _generator; //, IETagGenerator<T> generator public ETagHandler(IEtagCache cache) { _cache = cache; //_generator = generator; } public FubuContinuation Matches(ETaggedRequest request) { var current = _cache.Current(request.ResourceHash); return current.IsNotEmpty() && current == request.IfNoneMatch ? FubuContinuation.EndWithStatusCode(HttpStatusCode.NotModified) : FubuContinuation.NextBehavior(); } // This needs to be in a different class. Unit te //public HttpHeaderValues CreateETag(ETagTuple<T> tuple) //{ // var etag = _generator.Create(tuple.Target); // _cache.Register(tuple.Request.ResourceHash, etag); // return new HttpHeaderValues(HttpResponseHeaders.ETag, etag); //} } }
32.777778
88
0.599153
[ "Apache-2.0" ]
ketiko/fubumvc
src/FubuMVC.Core/Resources/Etags/ETagHandler.cs
1,180
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.DataFactory.Models { using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Google Cloud Storage read settings. /// </summary> public partial class GoogleCloudStorageReadSettings : StoreReadSettings { /// <summary> /// Initializes a new instance of the GoogleCloudStorageReadSettings /// class. /// </summary> public GoogleCloudStorageReadSettings() { CustomInit(); } /// <summary> /// Initializes a new instance of the GoogleCloudStorageReadSettings /// class. /// </summary> /// <param name="additionalProperties">Unmatched properties from the /// message are deserialized this collection</param> /// <param name="maxConcurrentConnections">The maximum concurrent /// connection count for the source data store. Type: integer (or /// Expression with resultType integer).</param> /// <param name="recursive">If true, files under the folder path will /// be read recursively. Default is true. Type: boolean (or Expression /// with resultType boolean).</param> /// <param name="wildcardFolderPath">Google Cloud Storage /// wildcardFolderPath. Type: string (or Expression with resultType /// string).</param> /// <param name="wildcardFileName">Google Cloud Storage /// wildcardFileName. Type: string (or Expression with resultType /// string).</param> /// <param name="prefix">The prefix filter for the Google Cloud Storage /// object name. Type: string (or Expression with resultType /// string).</param> /// <param name="fileListPath">Point to a text file that lists each /// file (relative path to the path configured in the dataset) that you /// want to copy. Type: string (or Expression with resultType /// string).</param> /// <param name="enablePartitionDiscovery">Indicates whether to enable /// partition discovery.</param> /// <param name="partitionRootPath">Specify the root path where /// partition discovery starts from. Type: string (or Expression with /// resultType string).</param> /// <param name="deleteFilesAfterCompletion">Indicates whether the /// source files need to be deleted after copy completion. Default is /// false. Type: boolean (or Expression with resultType /// boolean).</param> /// <param name="modifiedDatetimeStart">The start of file's modified /// datetime. Type: string (or Expression with resultType /// string).</param> /// <param name="modifiedDatetimeEnd">The end of file's modified /// datetime. Type: string (or Expression with resultType /// string).</param> public GoogleCloudStorageReadSettings(IDictionary<string, object> additionalProperties = default(IDictionary<string, object>), object maxConcurrentConnections = default(object), object recursive = default(object), object wildcardFolderPath = default(object), object wildcardFileName = default(object), object prefix = default(object), object fileListPath = default(object), bool? enablePartitionDiscovery = default(bool?), object partitionRootPath = default(object), object deleteFilesAfterCompletion = default(object), object modifiedDatetimeStart = default(object), object modifiedDatetimeEnd = default(object)) : base(additionalProperties, maxConcurrentConnections) { Recursive = recursive; WildcardFolderPath = wildcardFolderPath; WildcardFileName = wildcardFileName; Prefix = prefix; FileListPath = fileListPath; EnablePartitionDiscovery = enablePartitionDiscovery; PartitionRootPath = partitionRootPath; DeleteFilesAfterCompletion = deleteFilesAfterCompletion; ModifiedDatetimeStart = modifiedDatetimeStart; ModifiedDatetimeEnd = modifiedDatetimeEnd; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets if true, files under the folder path will be read /// recursively. Default is true. Type: boolean (or Expression with /// resultType boolean). /// </summary> [JsonProperty(PropertyName = "recursive")] public object Recursive { get; set; } /// <summary> /// Gets or sets google Cloud Storage wildcardFolderPath. Type: string /// (or Expression with resultType string). /// </summary> [JsonProperty(PropertyName = "wildcardFolderPath")] public object WildcardFolderPath { get; set; } /// <summary> /// Gets or sets google Cloud Storage wildcardFileName. Type: string /// (or Expression with resultType string). /// </summary> [JsonProperty(PropertyName = "wildcardFileName")] public object WildcardFileName { get; set; } /// <summary> /// Gets or sets the prefix filter for the Google Cloud Storage object /// name. Type: string (or Expression with resultType string). /// </summary> [JsonProperty(PropertyName = "prefix")] public object Prefix { get; set; } /// <summary> /// Gets or sets point to a text file that lists each file (relative /// path to the path configured in the dataset) that you want to copy. /// Type: string (or Expression with resultType string). /// </summary> [JsonProperty(PropertyName = "fileListPath")] public object FileListPath { get; set; } /// <summary> /// Gets or sets indicates whether to enable partition discovery. /// </summary> [JsonProperty(PropertyName = "enablePartitionDiscovery")] public bool? EnablePartitionDiscovery { get; set; } /// <summary> /// Gets or sets specify the root path where partition discovery starts /// from. Type: string (or Expression with resultType string). /// </summary> [JsonProperty(PropertyName = "partitionRootPath")] public object PartitionRootPath { get; set; } /// <summary> /// Gets or sets indicates whether the source files need to be deleted /// after copy completion. Default is false. Type: boolean (or /// Expression with resultType boolean). /// </summary> [JsonProperty(PropertyName = "deleteFilesAfterCompletion")] public object DeleteFilesAfterCompletion { get; set; } /// <summary> /// Gets or sets the start of file's modified datetime. Type: string /// (or Expression with resultType string). /// </summary> [JsonProperty(PropertyName = "modifiedDatetimeStart")] public object ModifiedDatetimeStart { get; set; } /// <summary> /// Gets or sets the end of file's modified datetime. Type: string (or /// Expression with resultType string). /// </summary> [JsonProperty(PropertyName = "modifiedDatetimeEnd")] public object ModifiedDatetimeEnd { get; set; } } }
46.622754
621
0.645004
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/datafactory/Microsoft.Azure.Management.DataFactory/src/Generated/Models/GoogleCloudStorageReadSettings.cs
7,786
C#
using Framework.Jab.Jab.Factory; using Jab; namespace Framework.Jab.Jab; [ServiceProviderModule] [Import(typeof(IFactoryModule))] internal interface IJabModule { }
16.6
33
0.801205
[ "BSD-3-Clause" ]
byCrookie/Framework
src/Framework.Jab/Jab/IJabModule.cs
168
C#
using System.Collections; using System.Collections.Generic; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; namespace Tests { public class CrosshairControllerUnitTest { CrossHairController crossHairController; RayCastControllerMock rayCastControllerMock; [SetUp] public void Setup() { GameObject crossHairGo = Object.Instantiate(new GameObject()); crossHairController = crossHairGo.AddComponent<CrossHairController>(); GameObject raycasterGo = Object.Instantiate(new GameObject()); rayCastControllerMock = raycasterGo.AddComponent<RayCastControllerMock>(); } [UnityTest] public IEnumerator CrosshairControllerIsInstantiatedTest() { Assert.NotNull(crossHairController); yield return null; } [UnityTest] public IEnumerator CrossHairFollowsCameraTest() { rayCastControllerMock.SetIsRaycasting(false); yield return null; Assert.IsTrue(AreVectorsEqual(crossHairController.gameObject.transform.localPosition, crossHairController.cameraPositionOffset)); Assert.IsTrue(AreVectorsEqual(crossHairController.gameObject.transform.localEulerAngles, crossHairController.cameraRotationOffset)); } [UnityTest] public IEnumerator CrossHairFollowsTrackableTest() { Pose pose = new Pose(); pose.position = new Vector3(1, 2, 3); pose.rotation.eulerAngles = new Vector3(4, 5, 6); rayCastControllerMock.SetIsRaycasting(true); rayCastControllerMock.SetPose(pose); yield return null; Assert.IsTrue(AreVectorsEqual(crossHairController.gameObject.transform.position, pose.position)); Assert.IsTrue(AreVectorsEqual(crossHairController.gameObject.transform.eulerAngles, pose.rotation.eulerAngles)); } [TearDown] public void TearDown() { Object.Destroy(crossHairController.gameObject); Object.Destroy(rayCastControllerMock.gameObject); } public bool AreVectorsEqual(Vector3 a, Vector3 b) { if (Vector3.Distance(a, b) < 0.001f) return true; else return false; } } public class RayCastControllerMock : RayCastController { public void SetIsRaycasting(bool value) { isRaycastingToTrackable = value; } public void SetPose(Pose pose) { hitPose = pose; } private void Start() { /*Do Nothing*/} private void Update() { /*Do Nothing*/} } }
34.896104
144
0.65054
[ "MIT" ]
paulrus123/MeasAR
MeasAR/Assets/UnitTests/CrosshairControllerUnitTest.cs
2,689
C#
 using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Web; using Microsoft.WindowsAzure.Mobile.Service; using Microsoft.WindowsAzure.Mobile.Service.Security; using Newtonsoft.Json.Linq; using Owin; namespace AzureForMobile.Sample.Backend.Utils { public class CustomLoginProvider : LoginProvider { internal const string ProviderName = "custom"; public override string Name { get { return ProviderName; } } public CustomLoginProvider(IServiceTokenHandler tokenHandler) : base(tokenHandler) { TokenLifetime = TimeSpan.FromDays(365); } public override void ConfigureMiddleware(IAppBuilder appBuilder, ServiceSettingsDictionary settings) { // Not Applicable - used for federated identity flows } public override ProviderCredentials CreateCredentials(ClaimsIdentity claimsIdentity) { if (claimsIdentity == null) { throw new ArgumentNullException("claimsIdentity"); } var username = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier).Value; var credentials = new CustomLoginProviderCredentials { UserId = TokenHandler.CreateUserId(Name, username) }; return credentials; } public override ProviderCredentials ParseCredentials(JObject serialized) { if (serialized == null) { throw new ArgumentNullException("serialized"); } return serialized.ToObject<CustomLoginProviderCredentials>(); } } }
29.779661
108
0.626636
[ "MIT" ]
Ideine/Apptracktive-Plugins
AzureForMobile/AzureForMobile.Sample/AzureForMobile.Sample.Backend/Utils/CustomLoginProvider.cs
1,759
C#
using CodeTweet.IdentityDal; using CodeTweet.IdentityDal.Model; using CodeTweet.Queueing; using CodeTweet.Queueing.ZeroMQ; using CodeTweet.TweetsDal; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace CodeTweet.Web { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); if (env.IsDevelopment()) { builder.AddUserSecrets<Startup>(); } builder.AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationIdentityContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Identity"))); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationIdentityContext>() .AddDefaultTokenProviders(); services.AddMvc(); services.AddDbContext<TweetsContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Tweets"))); services.AddTransient<ITweetsRepository, TweetsRepository>(); ZeroConfiguration zeroConfiguration = new ZeroConfiguration(); Configuration.GetSection("ZeroMq").Bind(zeroConfiguration); services.AddSingleton<INotificationEnqueue>(provider => new ZeroNotificationEnqueue(zeroConfiguration)); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseIdentity(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
33.593023
116
0.626514
[ "MIT" ]
spikecannon/FirstRepo
CodeTweet/CodeTweet.Web/Startup.cs
2,891
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.Oci.Database { /// <summary> /// This resource provides the Exadata Infrastructure resource in Oracle Cloud Infrastructure Database service. /// /// Creates an Exadata infrastructure resource. Applies to Exadata Cloud@Customer instances only. /// To create an Exadata Cloud Service infrastructure resource, use the [CreateCloudExadataInfrastructure](https://docs.cloud.oracle.com/iaas/api/#/en/database/latest/CloudExadataInfrastructure/CreateCloudExadataInfrastructure) operation. /// /// ## Example Usage /// /// ```csharp /// using Pulumi; /// using Oci = Pulumi.Oci; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var testExadataInfrastructure = new Oci.Database.ExadataInfrastructure("testExadataInfrastructure", new Oci.Database.ExadataInfrastructureArgs /// { /// AdminNetworkCidr = @var.Exadata_infrastructure_admin_network_cidr, /// CloudControlPlaneServer1 = @var.Exadata_infrastructure_cloud_control_plane_server1, /// CloudControlPlaneServer2 = @var.Exadata_infrastructure_cloud_control_plane_server2, /// CompartmentId = @var.Compartment_id, /// DisplayName = @var.Exadata_infrastructure_display_name, /// DnsServers = @var.Exadata_infrastructure_dns_server, /// Gateway = @var.Exadata_infrastructure_gateway, /// InfiniBandNetworkCidr = @var.Exadata_infrastructure_infini_band_network_cidr, /// Netmask = @var.Exadata_infrastructure_netmask, /// NtpServers = @var.Exadata_infrastructure_ntp_server, /// Shape = @var.Exadata_infrastructure_shape, /// TimeZone = @var.Exadata_infrastructure_time_zone, /// ActivationFile = @var.Exadata_infrastructure_activation_file, /// ComputeCount = @var.Exadata_infrastructure_compute_count, /// Contacts = /// { /// new Oci.Database.Inputs.ExadataInfrastructureContactArgs /// { /// Email = @var.Exadata_infrastructure_contacts_email, /// IsPrimary = @var.Exadata_infrastructure_contacts_is_primary, /// Name = @var.Exadata_infrastructure_contacts_name, /// IsContactMosValidated = @var.Exadata_infrastructure_contacts_is_contact_mos_validated, /// PhoneNumber = @var.Exadata_infrastructure_contacts_phone_number, /// }, /// }, /// CorporateProxy = @var.Exadata_infrastructure_corporate_proxy, /// DefinedTags = @var.Exadata_infrastructure_defined_tags, /// FreeformTags = /// { /// { "Department", "Finance" }, /// }, /// MaintenanceWindow = new Oci.Database.Inputs.ExadataInfrastructureMaintenanceWindowArgs /// { /// Preference = @var.Exadata_infrastructure_maintenance_window_preference, /// DaysOfWeeks = /// { /// new Oci.Database.Inputs.ExadataInfrastructureMaintenanceWindowDaysOfWeekArgs /// { /// Name = @var.Exadata_infrastructure_maintenance_window_days_of_week_name, /// }, /// }, /// HoursOfDays = @var.Exadata_infrastructure_maintenance_window_hours_of_day, /// LeadTimeInWeeks = @var.Exadata_infrastructure_maintenance_window_lead_time_in_weeks, /// Months = /// { /// new Oci.Database.Inputs.ExadataInfrastructureMaintenanceWindowMonthArgs /// { /// Name = @var.Exadata_infrastructure_maintenance_window_months_name, /// }, /// }, /// WeeksOfMonths = @var.Exadata_infrastructure_maintenance_window_weeks_of_month, /// }, /// StorageCount = @var.Exadata_infrastructure_storage_count, /// }); /// } /// /// } /// ``` /// /// ## Import /// /// ExadataInfrastructures can be imported using the `id`, e.g. /// /// ```sh /// $ pulumi import oci:database/exadataInfrastructure:ExadataInfrastructure test_exadata_infrastructure "id" /// ``` /// </summary> [OciResourceType("oci:database/exadataInfrastructure:ExadataInfrastructure")] public partial class ExadataInfrastructure : Pulumi.CustomResource { /// <summary> /// The requested number of additional storage servers activated for the Exadata infrastructure. /// </summary> [Output("activatedStorageCount")] public Output<int> ActivatedStorageCount { get; private set; } = null!; /// <summary> /// (Updatable) The activation zip file. If provided in config, exadata infrastructure will be activated after creation. Updates are not allowed on activated exadata infrastructure. /// </summary> [Output("activationFile")] public Output<string?> ActivationFile { get; private set; } = null!; /// <summary> /// The requested number of additional storage servers for the Exadata infrastructure. /// </summary> [Output("additionalStorageCount")] public Output<int> AdditionalStorageCount { get; private set; } = null!; /// <summary> /// (Updatable) The CIDR block for the Exadata administration network. /// </summary> [Output("adminNetworkCidr")] public Output<string> AdminNetworkCidr { get; private set; } = null!; /// <summary> /// (Updatable) The IP address for the first control plane server. /// </summary> [Output("cloudControlPlaneServer1")] public Output<string> CloudControlPlaneServer1 { get; private set; } = null!; /// <summary> /// (Updatable) The IP address for the second control plane server. /// </summary> [Output("cloudControlPlaneServer2")] public Output<string> CloudControlPlaneServer2 { get; private set; } = null!; /// <summary> /// (Updatable) The [OCID](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the compartment. /// </summary> [Output("compartmentId")] public Output<string> CompartmentId { get; private set; } = null!; /// <summary> /// The number of compute servers for the Exadata infrastructure. /// </summary> [Output("computeCount")] public Output<int> ComputeCount { get; private set; } = null!; /// <summary> /// (Updatable) The list of contacts for the Exadata infrastructure. /// </summary> [Output("contacts")] public Output<ImmutableArray<Outputs.ExadataInfrastructureContact>> Contacts { get; private set; } = null!; /// <summary> /// (Updatable) The corporate network proxy for access to the control plane network. Oracle recommends using an HTTPS proxy when possible for enhanced security. /// </summary> [Output("corporateProxy")] public Output<string> CorporateProxy { get; private set; } = null!; /// <summary> /// The number of enabled CPU cores. /// </summary> [Output("cpusEnabled")] public Output<int> CpusEnabled { get; private set; } = null!; [Output("createAsync")] public Output<bool?> CreateAsync { get; private set; } = null!; /// <summary> /// The CSI Number of the Exadata infrastructure. /// </summary> [Output("csiNumber")] public Output<string> CsiNumber { get; private set; } = null!; /// <summary> /// Size, in terabytes, of the DATA disk group. /// </summary> [Output("dataStorageSizeInTbs")] public Output<double> DataStorageSizeInTbs { get; private set; } = null!; /// <summary> /// The local node storage allocated in GBs. /// </summary> [Output("dbNodeStorageSizeInGbs")] public Output<int> DbNodeStorageSizeInGbs { get; private set; } = null!; /// <summary> /// (Updatable) Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). /// </summary> [Output("definedTags")] public Output<ImmutableDictionary<string, object>> DefinedTags { get; private set; } = null!; /// <summary> /// The user-friendly name for the Exadata infrastructure. The name does not need to be unique. /// </summary> [Output("displayName")] public Output<string> DisplayName { get; private set; } = null!; /// <summary> /// (Updatable) The list of DNS server IP addresses. Maximum of 3 allowed. /// </summary> [Output("dnsServers")] public Output<ImmutableArray<string>> DnsServers { get; private set; } = null!; /// <summary> /// (Updatable) Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). Example: `{"Department": "Finance"}` /// </summary> [Output("freeformTags")] public Output<ImmutableDictionary<string, object>> FreeformTags { get; private set; } = null!; /// <summary> /// (Updatable) The gateway for the control plane network. /// </summary> [Output("gateway")] public Output<string> Gateway { get; private set; } = null!; /// <summary> /// (Updatable) The CIDR block for the Exadata InfiniBand interconnect. /// </summary> [Output("infiniBandNetworkCidr")] public Output<string> InfiniBandNetworkCidr { get; private set; } = null!; /// <summary> /// Additional information about the current lifecycle state. /// </summary> [Output("lifecycleDetails")] public Output<string> LifecycleDetails { get; private set; } = null!; /// <summary> /// A field to capture ‘Maintenance SLO Status’ for the Exadata infrastructure with values ‘OK’, ‘DEGRADED’. Default is ‘OK’ when the infrastructure is provisioned. /// </summary> [Output("maintenanceSloStatus")] public Output<string> MaintenanceSloStatus { get; private set; } = null!; /// <summary> /// (Updatable) The scheduling details for the quarterly maintenance window. Patching and system updates take place during the maintenance window. /// </summary> [Output("maintenanceWindow")] public Output<Outputs.ExadataInfrastructureMaintenanceWindow> MaintenanceWindow { get; private set; } = null!; /// <summary> /// The total number of CPU cores available. /// </summary> [Output("maxCpuCount")] public Output<int> MaxCpuCount { get; private set; } = null!; /// <summary> /// The total available DATA disk group size. /// </summary> [Output("maxDataStorageInTbs")] public Output<double> MaxDataStorageInTbs { get; private set; } = null!; /// <summary> /// The total local node storage available in GBs. /// </summary> [Output("maxDbNodeStorageInGbs")] public Output<int> MaxDbNodeStorageInGbs { get; private set; } = null!; /// <summary> /// The total memory available in GBs. /// </summary> [Output("maxMemoryInGbs")] public Output<int> MaxMemoryInGbs { get; private set; } = null!; /// <summary> /// The memory allocated in GBs. /// </summary> [Output("memorySizeInGbs")] public Output<int> MemorySizeInGbs { get; private set; } = null!; /// <summary> /// (Updatable) The netmask for the control plane network. /// </summary> [Output("netmask")] public Output<string> Netmask { get; private set; } = null!; /// <summary> /// (Updatable) The list of NTP server IP addresses. Maximum of 3 allowed. /// </summary> [Output("ntpServers")] public Output<ImmutableArray<string>> NtpServers { get; private set; } = null!; /// <summary> /// The shape of the Exadata infrastructure. The shape determines the amount of CPU, storage, and memory resources allocated to the instance. /// </summary> [Output("shape")] public Output<string> Shape { get; private set; } = null!; /// <summary> /// The current lifecycle state of the Exadata infrastructure. /// </summary> [Output("state")] public Output<string> State { get; private set; } = null!; /// <summary> /// The number of storage servers for the Exadata infrastructure. /// </summary> [Output("storageCount")] public Output<int> StorageCount { get; private set; } = null!; /// <summary> /// The date and time the Exadata infrastructure was created. /// </summary> [Output("timeCreated")] public Output<string> TimeCreated { get; private set; } = null!; /// <summary> /// (Updatable) The time zone of the Exadata infrastructure. For details, see [Exadata Infrastructure Time Zones](https://docs.cloud.oracle.com/iaas/Content/Database/References/timezones.htm). /// </summary> [Output("timeZone")] public Output<string> TimeZone { get; private set; } = null!; /// <summary> /// Create a ExadataInfrastructure resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public ExadataInfrastructure(string name, ExadataInfrastructureArgs args, CustomResourceOptions? options = null) : base("oci:database/exadataInfrastructure:ExadataInfrastructure", name, args ?? new ExadataInfrastructureArgs(), MakeResourceOptions(options, "")) { } private ExadataInfrastructure(string name, Input<string> id, ExadataInfrastructureState? state = null, CustomResourceOptions? options = null) : base("oci:database/exadataInfrastructure:ExadataInfrastructure", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing ExadataInfrastructure resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static ExadataInfrastructure Get(string name, Input<string> id, ExadataInfrastructureState? state = null, CustomResourceOptions? options = null) { return new ExadataInfrastructure(name, id, state, options); } } public sealed class ExadataInfrastructureArgs : Pulumi.ResourceArgs { /// <summary> /// (Updatable) The activation zip file. If provided in config, exadata infrastructure will be activated after creation. Updates are not allowed on activated exadata infrastructure. /// </summary> [Input("activationFile")] public Input<string>? ActivationFile { get; set; } /// <summary> /// The requested number of additional storage servers for the Exadata infrastructure. /// </summary> [Input("additionalStorageCount")] public Input<int>? AdditionalStorageCount { get; set; } /// <summary> /// (Updatable) The CIDR block for the Exadata administration network. /// </summary> [Input("adminNetworkCidr", required: true)] public Input<string> AdminNetworkCidr { get; set; } = null!; /// <summary> /// (Updatable) The IP address for the first control plane server. /// </summary> [Input("cloudControlPlaneServer1", required: true)] public Input<string> CloudControlPlaneServer1 { get; set; } = null!; /// <summary> /// (Updatable) The IP address for the second control plane server. /// </summary> [Input("cloudControlPlaneServer2", required: true)] public Input<string> CloudControlPlaneServer2 { get; set; } = null!; /// <summary> /// (Updatable) The [OCID](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the compartment. /// </summary> [Input("compartmentId", required: true)] public Input<string> CompartmentId { get; set; } = null!; /// <summary> /// The number of compute servers for the Exadata infrastructure. /// </summary> [Input("computeCount")] public Input<int>? ComputeCount { get; set; } [Input("contacts")] private InputList<Inputs.ExadataInfrastructureContactArgs>? _contacts; /// <summary> /// (Updatable) The list of contacts for the Exadata infrastructure. /// </summary> public InputList<Inputs.ExadataInfrastructureContactArgs> Contacts { get => _contacts ?? (_contacts = new InputList<Inputs.ExadataInfrastructureContactArgs>()); set => _contacts = value; } /// <summary> /// (Updatable) The corporate network proxy for access to the control plane network. Oracle recommends using an HTTPS proxy when possible for enhanced security. /// </summary> [Input("corporateProxy")] public Input<string>? CorporateProxy { get; set; } [Input("createAsync")] public Input<bool>? CreateAsync { get; set; } [Input("definedTags")] private InputMap<object>? _definedTags; /// <summary> /// (Updatable) Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). /// </summary> public InputMap<object> DefinedTags { get => _definedTags ?? (_definedTags = new InputMap<object>()); set => _definedTags = value; } /// <summary> /// The user-friendly name for the Exadata infrastructure. The name does not need to be unique. /// </summary> [Input("displayName", required: true)] public Input<string> DisplayName { get; set; } = null!; [Input("dnsServers", required: true)] private InputList<string>? _dnsServers; /// <summary> /// (Updatable) The list of DNS server IP addresses. Maximum of 3 allowed. /// </summary> public InputList<string> DnsServers { get => _dnsServers ?? (_dnsServers = new InputList<string>()); set => _dnsServers = value; } [Input("freeformTags")] private InputMap<object>? _freeformTags; /// <summary> /// (Updatable) Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). Example: `{"Department": "Finance"}` /// </summary> public InputMap<object> FreeformTags { get => _freeformTags ?? (_freeformTags = new InputMap<object>()); set => _freeformTags = value; } /// <summary> /// (Updatable) The gateway for the control plane network. /// </summary> [Input("gateway", required: true)] public Input<string> Gateway { get; set; } = null!; /// <summary> /// (Updatable) The CIDR block for the Exadata InfiniBand interconnect. /// </summary> [Input("infiniBandNetworkCidr", required: true)] public Input<string> InfiniBandNetworkCidr { get; set; } = null!; /// <summary> /// (Updatable) The scheduling details for the quarterly maintenance window. Patching and system updates take place during the maintenance window. /// </summary> [Input("maintenanceWindow")] public Input<Inputs.ExadataInfrastructureMaintenanceWindowArgs>? MaintenanceWindow { get; set; } /// <summary> /// (Updatable) The netmask for the control plane network. /// </summary> [Input("netmask", required: true)] public Input<string> Netmask { get; set; } = null!; [Input("ntpServers", required: true)] private InputList<string>? _ntpServers; /// <summary> /// (Updatable) The list of NTP server IP addresses. Maximum of 3 allowed. /// </summary> public InputList<string> NtpServers { get => _ntpServers ?? (_ntpServers = new InputList<string>()); set => _ntpServers = value; } /// <summary> /// The shape of the Exadata infrastructure. The shape determines the amount of CPU, storage, and memory resources allocated to the instance. /// </summary> [Input("shape", required: true)] public Input<string> Shape { get; set; } = null!; /// <summary> /// The number of storage servers for the Exadata infrastructure. /// </summary> [Input("storageCount")] public Input<int>? StorageCount { get; set; } /// <summary> /// (Updatable) The time zone of the Exadata infrastructure. For details, see [Exadata Infrastructure Time Zones](https://docs.cloud.oracle.com/iaas/Content/Database/References/timezones.htm). /// </summary> [Input("timeZone", required: true)] public Input<string> TimeZone { get; set; } = null!; public ExadataInfrastructureArgs() { } } public sealed class ExadataInfrastructureState : Pulumi.ResourceArgs { /// <summary> /// The requested number of additional storage servers activated for the Exadata infrastructure. /// </summary> [Input("activatedStorageCount")] public Input<int>? ActivatedStorageCount { get; set; } /// <summary> /// (Updatable) The activation zip file. If provided in config, exadata infrastructure will be activated after creation. Updates are not allowed on activated exadata infrastructure. /// </summary> [Input("activationFile")] public Input<string>? ActivationFile { get; set; } /// <summary> /// The requested number of additional storage servers for the Exadata infrastructure. /// </summary> [Input("additionalStorageCount")] public Input<int>? AdditionalStorageCount { get; set; } /// <summary> /// (Updatable) The CIDR block for the Exadata administration network. /// </summary> [Input("adminNetworkCidr")] public Input<string>? AdminNetworkCidr { get; set; } /// <summary> /// (Updatable) The IP address for the first control plane server. /// </summary> [Input("cloudControlPlaneServer1")] public Input<string>? CloudControlPlaneServer1 { get; set; } /// <summary> /// (Updatable) The IP address for the second control plane server. /// </summary> [Input("cloudControlPlaneServer2")] public Input<string>? CloudControlPlaneServer2 { get; set; } /// <summary> /// (Updatable) The [OCID](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the compartment. /// </summary> [Input("compartmentId")] public Input<string>? CompartmentId { get; set; } /// <summary> /// The number of compute servers for the Exadata infrastructure. /// </summary> [Input("computeCount")] public Input<int>? ComputeCount { get; set; } [Input("contacts")] private InputList<Inputs.ExadataInfrastructureContactGetArgs>? _contacts; /// <summary> /// (Updatable) The list of contacts for the Exadata infrastructure. /// </summary> public InputList<Inputs.ExadataInfrastructureContactGetArgs> Contacts { get => _contacts ?? (_contacts = new InputList<Inputs.ExadataInfrastructureContactGetArgs>()); set => _contacts = value; } /// <summary> /// (Updatable) The corporate network proxy for access to the control plane network. Oracle recommends using an HTTPS proxy when possible for enhanced security. /// </summary> [Input("corporateProxy")] public Input<string>? CorporateProxy { get; set; } /// <summary> /// The number of enabled CPU cores. /// </summary> [Input("cpusEnabled")] public Input<int>? CpusEnabled { get; set; } [Input("createAsync")] public Input<bool>? CreateAsync { get; set; } /// <summary> /// The CSI Number of the Exadata infrastructure. /// </summary> [Input("csiNumber")] public Input<string>? CsiNumber { get; set; } /// <summary> /// Size, in terabytes, of the DATA disk group. /// </summary> [Input("dataStorageSizeInTbs")] public Input<double>? DataStorageSizeInTbs { get; set; } /// <summary> /// The local node storage allocated in GBs. /// </summary> [Input("dbNodeStorageSizeInGbs")] public Input<int>? DbNodeStorageSizeInGbs { get; set; } [Input("definedTags")] private InputMap<object>? _definedTags; /// <summary> /// (Updatable) Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). /// </summary> public InputMap<object> DefinedTags { get => _definedTags ?? (_definedTags = new InputMap<object>()); set => _definedTags = value; } /// <summary> /// The user-friendly name for the Exadata infrastructure. The name does not need to be unique. /// </summary> [Input("displayName")] public Input<string>? DisplayName { get; set; } [Input("dnsServers")] private InputList<string>? _dnsServers; /// <summary> /// (Updatable) The list of DNS server IP addresses. Maximum of 3 allowed. /// </summary> public InputList<string> DnsServers { get => _dnsServers ?? (_dnsServers = new InputList<string>()); set => _dnsServers = value; } [Input("freeformTags")] private InputMap<object>? _freeformTags; /// <summary> /// (Updatable) Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). Example: `{"Department": "Finance"}` /// </summary> public InputMap<object> FreeformTags { get => _freeformTags ?? (_freeformTags = new InputMap<object>()); set => _freeformTags = value; } /// <summary> /// (Updatable) The gateway for the control plane network. /// </summary> [Input("gateway")] public Input<string>? Gateway { get; set; } /// <summary> /// (Updatable) The CIDR block for the Exadata InfiniBand interconnect. /// </summary> [Input("infiniBandNetworkCidr")] public Input<string>? InfiniBandNetworkCidr { get; set; } /// <summary> /// Additional information about the current lifecycle state. /// </summary> [Input("lifecycleDetails")] public Input<string>? LifecycleDetails { get; set; } /// <summary> /// A field to capture ‘Maintenance SLO Status’ for the Exadata infrastructure with values ‘OK’, ‘DEGRADED’. Default is ‘OK’ when the infrastructure is provisioned. /// </summary> [Input("maintenanceSloStatus")] public Input<string>? MaintenanceSloStatus { get; set; } /// <summary> /// (Updatable) The scheduling details for the quarterly maintenance window. Patching and system updates take place during the maintenance window. /// </summary> [Input("maintenanceWindow")] public Input<Inputs.ExadataInfrastructureMaintenanceWindowGetArgs>? MaintenanceWindow { get; set; } /// <summary> /// The total number of CPU cores available. /// </summary> [Input("maxCpuCount")] public Input<int>? MaxCpuCount { get; set; } /// <summary> /// The total available DATA disk group size. /// </summary> [Input("maxDataStorageInTbs")] public Input<double>? MaxDataStorageInTbs { get; set; } /// <summary> /// The total local node storage available in GBs. /// </summary> [Input("maxDbNodeStorageInGbs")] public Input<int>? MaxDbNodeStorageInGbs { get; set; } /// <summary> /// The total memory available in GBs. /// </summary> [Input("maxMemoryInGbs")] public Input<int>? MaxMemoryInGbs { get; set; } /// <summary> /// The memory allocated in GBs. /// </summary> [Input("memorySizeInGbs")] public Input<int>? MemorySizeInGbs { get; set; } /// <summary> /// (Updatable) The netmask for the control plane network. /// </summary> [Input("netmask")] public Input<string>? Netmask { get; set; } [Input("ntpServers")] private InputList<string>? _ntpServers; /// <summary> /// (Updatable) The list of NTP server IP addresses. Maximum of 3 allowed. /// </summary> public InputList<string> NtpServers { get => _ntpServers ?? (_ntpServers = new InputList<string>()); set => _ntpServers = value; } /// <summary> /// The shape of the Exadata infrastructure. The shape determines the amount of CPU, storage, and memory resources allocated to the instance. /// </summary> [Input("shape")] public Input<string>? Shape { get; set; } /// <summary> /// The current lifecycle state of the Exadata infrastructure. /// </summary> [Input("state")] public Input<string>? State { get; set; } /// <summary> /// The number of storage servers for the Exadata infrastructure. /// </summary> [Input("storageCount")] public Input<int>? StorageCount { get; set; } /// <summary> /// The date and time the Exadata infrastructure was created. /// </summary> [Input("timeCreated")] public Input<string>? TimeCreated { get; set; } /// <summary> /// (Updatable) The time zone of the Exadata infrastructure. For details, see [Exadata Infrastructure Time Zones](https://docs.cloud.oracle.com/iaas/Content/Database/References/timezones.htm). /// </summary> [Input("timeZone")] public Input<string>? TimeZone { get; set; } public ExadataInfrastructureState() { } } }
43.078913
297
0.602553
[ "ECL-2.0", "Apache-2.0" ]
EladGabay/pulumi-oci
sdk/dotnet/Database/ExadataInfrastructure.cs
33,332
C#
using System; using System.IO; using System.Linq; using EventStore.Core.Index; using EventStore.Core.Util; using NUnit.Framework; namespace EventStore.Core.Tests.Index.IndexVAny { [TestFixture] public class saving_empty_index_to_a_file : SpecificationWithDirectoryPerTestFixture { private string _filename; private IndexMap _map; [OneTimeSetUp] public override void TestFixtureSetUp() { base.TestFixtureSetUp(); _filename = GetFilePathFor("indexfile"); _map = IndexMapTestFactory.FromFile(_filename); _map.SaveToFile(_filename); } [Test] public void the_file_exists() { Assert.IsTrue(File.Exists(_filename)); } [Test] public void the_file_contains_correct_data() { using (var fs = File.OpenRead(_filename)) using (var reader = new StreamReader(fs)) { var text = reader.ReadToEnd(); var lines = text.Replace("\r", "").Split('\n'); fs.Position = 32; var md5 = MD5Hash.GetHashFor(fs); var md5String = BitConverter.ToString(md5).Replace("-", ""); Assert.AreEqual(5, lines.Count()); Assert.AreEqual(md5String, lines[0]); Assert.AreEqual(IndexMap.IndexMapVersion.ToString(), lines[1]); Assert.AreEqual("-1/-1", lines[2]); Assert.AreEqual($"{int.MaxValue}", lines[3]); Assert.AreEqual("", lines[4]); } } [Test] public void saved_file_could_be_read_correctly_and_without_errors() { var map = IndexMapTestFactory.FromFile(_filename); Assert.AreEqual(-1, map.PrepareCheckpoint); Assert.AreEqual(-1, map.CommitCheckpoint); } } }
26.929825
87
0.708795
[ "Apache-2.0", "CC0-1.0" ]
JasonKStevens/EventStoreRx
src/EventStore.Core.Tests/Index/IndexVAny/saving_empty_index_to_a_file.cs
1,535
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/ShlObj_core.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows.IID; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="IShellDetails" /> struct.</summary> public static unsafe partial class IShellDetailsTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="IShellDetails" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(IShellDetails).GUID, Is.EqualTo(IID_IShellDetails)); } /// <summary>Validates that the <see cref="IShellDetails" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<IShellDetails>(), Is.EqualTo(sizeof(IShellDetails))); } /// <summary>Validates that the <see cref="IShellDetails" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(IShellDetails).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="IShellDetails" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(IShellDetails), Is.EqualTo(8)); } else { Assert.That(sizeof(IShellDetails), Is.EqualTo(4)); } } }
34.490196
145
0.681637
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
tests/Interop/Windows/Windows/um/ShlObj_core/IShellDetailsTests.cs
1,761
C#
using System; using Xunit; using static PrimeFuncPack.UnitTest.TestData; namespace PrimeFuncPack.Tests; partial class ThreeDependencyTest { [Theory] [MemberData(nameof(ServiceProviderTestSource.NullableProviders), MemberType = typeof(ServiceProviderTestSource))] public void ResolveThird_ExpectResolvedValueIsEqualToThirdSourceValue( IServiceProvider serviceProvider) { var third = LowerSomeTextStructType; var dependency = Dependency.From( _ => PlusFifteenIdRefType, _ => ZeroIdNullNameRecord, _ => third); var actual = dependency.ResolveThird(serviceProvider); Assert.Equal(third, actual); } }
27.84
117
0.712644
[ "MIT" ]
pfpack/pfpack-dependency-pipeline
src/dependency-core/Core.Tests/Tests.Dependency.03/Resolve/Resolve.T3.cs
696
C#
using System.Collections; using System.Collections.Generic; using Levels.Music; using UnityEngine; [CreateAssetMenu(fileName = "Audio", menuName = "ScriptableObjects/BeatMapData", order = 1)] public class BeatMapData : ScriptableObject { public List<int> timestampList; public BeatMap beatMapBase; public AudioClip GetAudioClip() { return beatMapBase.audioClip; } public BeatMap GenerateBeatMap() { BeatMap beatMap = beatMapBase.ShallowClone(); beatMap.beatObjectList.Clear(); foreach (int timestampInt in timestampList) { BeatObject beatObject = new BeatObject(); beatObject.beatTime = timestampInt / 1000f; beatMap.beatObjectList.Add(beatObject); } return beatMap; } }
24.787879
92
0.656479
[ "MIT" ]
TurnipXenon/GameDevMama
Assets/Scripts/ScriptableObjects/BeatMapData.cs
820
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/objidl.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="IInitializeSpy" /> struct.</summary> public static unsafe partial class IInitializeSpyTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="IInitializeSpy" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(IInitializeSpy).GUID, Is.EqualTo(IID_IInitializeSpy)); } /// <summary>Validates that the <see cref="IInitializeSpy" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<IInitializeSpy>(), Is.EqualTo(sizeof(IInitializeSpy))); } /// <summary>Validates that the <see cref="IInitializeSpy" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(IInitializeSpy).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="IInitializeSpy" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(IInitializeSpy), Is.EqualTo(8)); } else { Assert.That(sizeof(IInitializeSpy), Is.EqualTo(4)); } } } }
36.480769
145
0.630996
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
tests/Interop/Windows/um/objidl/IInitializeSpyTests.cs
1,899
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Mono.Linker; using Mono.Linker.Steps; #if NET5_LINKER using Microsoft.Android.Sdk.ILLink; #endif using Mono.Tuner; using Mobile.Tuner; using Mono.Cecil; namespace MonoDroid.Tuner { public class RemoveAttributes : RemoveAttributesBase { protected virtual bool DebugBuild { get { #if NET5_LINKER return true; #else return context.LinkSymbols; #endif } } protected override bool IsRemovedAttribute (CustomAttribute attribute) { // note: this also avoid calling FullName (which allocates a string) var attr_type = attribute.Constructor.DeclaringType; switch (attr_type.Name) { case "IntDefinitionAttribute": return attr_type.Namespace == "Android.Runtime"; case "ObsoleteAttribute": // System.Mono*Attribute from mono/mcs/build/common/MonoTODOAttribute.cs case "MonoDocumentationNoteAttribute": case "MonoExtensionAttribute": case "MonoInternalNoteAttribute": case "MonoLimitationAttribute": case "MonoNotSupportedAttribute": case "MonoTODOAttribute": return attr_type.Namespace == "System"; case "MonoFIXAttribute": return attr_type.Namespace == "System.Xml"; // remove debugging-related attributes if we're not linking symbols (i.e. we're building release builds) case "DebuggableAttribute": case "DebuggerBrowsableAttribute": case "DebuggerDisplayAttribute": case "DebuggerHiddenAttribute": case "DebuggerNonUserCodeAttribute": case "DebuggerStepperBoundaryAttribute": case "DebuggerStepThroughAttribute": case "DebuggerTypeProxyAttribute": case "DebuggerVisualizerAttribute": return !DebugBuild && attr_type.Namespace == "System.Diagnostics"; case "NullableContextAttribute": case "NullableAttribute": return attr_type.Namespace == "System.Runtime.CompilerServices"; case "AllowNullAttribute": case "MaybeNullAttribute": case "NotNullAttribute": case "NotNullWhenAttribute": case "NotNullIfNotNullAttribute": return attr_type.Namespace == "System.Diagnostics.CodeAnalysis"; default: return false; } } } }
28.447368
107
0.753469
[ "MIT" ]
Mhtshum/xamarin-android
src/Xamarin.Android.Build.Tasks/Linker/MonoDroid.Tuner/RemoveAttributes.cs
2,162
C#
// <copyright file="AbstractRandomNumberGenerator.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2010 Math.NET // // 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. // </copyright> namespace ai.lib.algorithms.random { using System; /// <summary> /// Abstract class for random number generators. This class introduces a layer between <see cref="System.Random"/> /// and the Math.Net Numerics random number generators to provide thread safety. /// </summary> public abstract class AbstractRandomNumberGenerator : Random { /// <summary> /// </summary> protected AbstractRandomNumberGenerator() { } /// <summary> /// Returns a nonnegative random number. /// </summary> /// <returns> /// A 32-bit signed integer greater than or equal to zero and less than <see cref="F:System.Int32.MaxValue"/>. /// </returns> public override int Next() { return (int)(Sample() * int.MaxValue); } /// <summary> /// Returns a random number less then a specified maximum. /// </summary> /// <param name="maxValue">The exclusive upper bound of the random number returned.</param> /// <returns>A 32-bit signed integer less than <paramref name="maxValue"/>.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="maxValue"/> is negative. </exception> public override int Next(int maxValue) { if (maxValue <= 0) { throw new ArgumentOutOfRangeException("Argument must be positive"); } return (int)(Sample() * maxValue); } /// <summary> /// Returns a random number within a specified range. /// </summary> /// <param name="minValue">The inclusive lower bound of the random number returned.</param> /// <param name="maxValue">The exclusive upper bound of the random number returned. <paramref name="maxValue"/> must be greater than or equal to <paramref name="minValue"/>.</param> /// <returns> /// A 32-bit signed integer greater than or equal to <paramref name="minValue"/> and less than <paramref name="maxValue"/>; that is, the range of return values includes <paramref name="minValue"/> but not <paramref name="maxValue"/>. If <paramref name="minValue"/> equals <paramref name="maxValue"/>, <paramref name="minValue"/> is returned. /// </returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="minValue"/> is greater than <paramref name="maxValue"/>. </exception> public override int Next(int minValue, int maxValue) { if (minValue > maxValue) { throw new ArgumentOutOfRangeException("Min must be > max"); } return (int)(Sample() * (maxValue - minValue)) + minValue; } /// <summary> /// Fills the elements of a specified array of bytes with random numbers. /// </summary> /// <param name="buffer">An array of bytes to contain random numbers.</param> /// <exception cref="T:System.ArgumentNullException"><paramref name="buffer"/> is null. </exception> public override void NextBytes(byte[] buffer) { for (var i = 0; i < buffer.Length; i++) { buffer[i] = (byte)(Next() & 0xFF); } } } }
43.925234
349
0.638936
[ "MIT" ]
ivan-alles/poker-acpc
lib/algorithms/trunk/src/main/net/ai.lib.algorithms/random/AbstractRandomNumberGenerator.cs
4,702
C#
using PhotoApp.Data; using PhotoApp.Data.Models; using PhotoApp.Services.Models.Photo; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PhotoApp.Services.PhotoService { public class PhotoService : IPhotoService { private readonly PhotoAppDbContext dbContext; public PhotoService(PhotoAppDbContext dbContext) { this.dbContext = dbContext; } public async Task<int> AddPhotoAsync(string photoLink) { var model = new Photo { Link = photoLink, }; await dbContext.Photos.AddAsync(model); await dbContext.SaveChangesAsync(); int photoId = model.PhotoId; return photoId; } public async Task AssingPhotoToChallangeAsync(AssignPhotoToChallangeServiceModel serviceModel) { PhotoChallange photoChallange = new PhotoChallange { PhotoId = serviceModel.PhotoId, ChallangeId = serviceModel.ChallangeId }; await dbContext.PhotosChallanges.AddAsync(photoChallange); await dbContext.SaveChangesAsync(); } public async Task<PhotoServiceModel> FindPhotoByIdAsync(int id) { PhotoServiceModel photoServiceModel; if (id != default(int)) { Photo photo = dbContext.Photos.Where(p => p.PhotoId == id).FirstOrDefault(); photoServiceModel = new PhotoServiceModel { PhotoId = photo.PhotoId, PhotoLink = photo.Link }; return photoServiceModel; } photoServiceModel = new PhotoServiceModel { PhotoId = 0, PhotoLink = null }; return photoServiceModel; } } }
25.474359
102
0.5692
[ "MIT" ]
Mirkoniks/PhotoApp
src/Services/PhotoApp.Services/PhotoService/PhotoService.cs
1,989
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; interface IBaseLogic<T> where T : new() { /// <summary> /// 条件查询实例 /// </summary> /// <param name="entity">条件实例</param> /// <returns></returns> IList<T> Select(T entity); /// <summary> /// 查询所有实例 /// </summary> /// <returns></returns> IList<T> Selects(); }
18.571429
41
0.571795
[ "Unlicense" ]
xzssws/Code-Generate
DynamicFramework/Basic/DynamicFramework_Independent/SingleDaoTemplate/Base/IBaseLogic.cs
424
C#
using System.Collections.Generic; using System.Linq; using System.Security.Claims; using Newtonsoft.Json.Linq; namespace IdentityServer3.Core.Services.Default { /// <summary> /// Claims filter for facebook. /// </summary> public class FacebookClaimsFilter : ClaimsFilterBase { /// <summary> /// Initializes a new instance of the <see cref="FacebookClaimsFilter"/> class. /// </summary> public FacebookClaimsFilter() : this("Facebook") { } /// <summary> /// Initializes a new instance of the <see cref="FacebookClaimsFilter"/> class. /// </summary> /// <param name="provider">The provider this claims filter will operate against.</param> public FacebookClaimsFilter(string provider) : base(provider) { } /// <summary> /// Transforms the claims if this provider is used. /// </summary> /// <param name="claims">The claims.</param> /// <returns></returns> protected override IEnumerable<Claim> TransformClaims(IEnumerable<Claim> claims) { var nameClaim = claims.FirstOrDefault(x => x.Type == "urn:facebook:name"); var firstNameClaim = claims.FirstOrDefault(x => x.Type == "urn:facebook:first_name"); var lastNameClaim = claims.FirstOrDefault(x => x.Type == "urn:facebook:last_name"); var profileImageClaim = claims.FirstOrDefault(x => x.Type == "urn:facebook:picture"); var list = claims.ToList(); if (nameClaim != null) { if (list.All(c => c.Type != Constants.ClaimTypes.Name)) { list.Add(new Claim(Constants.ClaimTypes.Name, nameClaim.Value)); } } if (firstNameClaim != null) { if (list.All(c => c.Type != Constants.ClaimTypes.GivenName)) { list.Add(new Claim(Constants.ClaimTypes.GivenName, firstNameClaim.Value)); } } if (lastNameClaim != null) { if (list.All(c => c.Type != Constants.ClaimTypes.FamilyName)) { list.Add(new Claim(Constants.ClaimTypes.FamilyName, lastNameClaim.Value)); } } if (profileImageClaim != null) { if (list.All(c => c.Type != Constants.ClaimTypes.Picture)) { list.Add(new Claim(Constants.ClaimTypes.Picture, profileImageClaim.Value)); } } return list; } } }
35.447368
97
0.536006
[ "Apache-2.0" ]
DomainGroupOSS/IdentityServer3
source/Core/Services/ExternalClaimsFilter/FacebookClaimsFilter.cs
2,696
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace Datahub.Core.Migrations.Core { public partial class oboardingOtherField : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>( name: "Project_Engagement_Category_Other", table: "OnboardingApps", type: "nvarchar(max)", nullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Project_Engagement_Category_Other", table: "OnboardingApps"); } } }
29.458333
71
0.609618
[ "MIT" ]
NRCan/datahub-portal
Datahub.Core/Migrations/Core/20211115184452_oboardingOtherField.cs
709
C#
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using JetBrains.Annotations; using lib.Commands; using lib.Primitives; namespace lib.Utils { public static class Compressor { [NotNull] public static string SerializeSolutionToString([NotNull] this byte[] solutionContent) { return Convert.ToBase64String(solutionContent.Compress()); } [NotNull] public static byte[] SerializeSolutionFromString([NotNull] this string solutionString) { return Convert.FromBase64String(solutionString).Decompress(); } public static byte[] Compress(this byte[] data) { var memoryStream = new MemoryStream(); using (var zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create)) { var entry = zipArchive.CreateEntry("data", CompressionLevel.Optimal); using (var stream = entry.Open()) stream.Write(data, 0, data.Length); } return memoryStream.ToArray(); } public static byte[] Decompress(this byte[] data) { var dataStream = new MemoryStream(data); using (var zipArchive = new ZipArchive(dataStream, ZipArchiveMode.Read)) { var entry = zipArchive.GetEntry("data"); using (var stream = entry.Open()) { var result = new MemoryStream(); stream.CopyTo(result); return result.ToArray(); } } } } public static class CommandSerializer { [NotNull] public static byte[] Save([NotNull] ICommand[] commands) { return commands.SelectMany(x => x.Encode()).ToArray(); } [NotNull] public static ICommand[] Load([NotNull] byte[] content) { var commands = new List<ICommand>(); using (var stream = new BinaryReader(new MemoryStream(content))) { while (stream.BaseStream.Position != stream.BaseStream.Length) commands.Add(LoadSingleCommand(stream)); } return commands.ToArray(); } [NotNull] private static ICommand LoadSingleCommand([NotNull] BinaryReader binaryReader) { var firstByte = binaryReader.ReadByte(); if (firstByte.TryExtractMask("11111111", out _)) return new Halt(); if (firstByte.TryExtractMask("11111110", out _)) return new Wait(); if (firstByte.TryExtractMask("11111101", out _)) return new Flip(); if (firstByte.TryExtractMask("*****111", out var fusionPNearDistance)) return new FusionP(new NearDifference(fusionPNearDistance)); if (firstByte.TryExtractMask("*****110", out var fusionSNearDistance)) return new FusionP(new NearDifference(fusionSNearDistance)); if (firstByte.TryExtractMask("*****011", out var fillNearDistance)) return new Fill(new NearDifference(fillNearDistance)); if (firstByte.TryExtractMask("*****010", out var voidNearDistance)) return new Voidd(new NearDifference(voidNearDistance)); var secondByte = binaryReader.ReadByte(); if (firstByte.TryExtractMask("00**0100", out var sMoveA) && secondByte.TryExtractMask("000*****", out var sMoveI)) return new SMove(new LongLinearDifference(sMoveA, sMoveI)); if (firstByte.TryExtractMask("****1100", out var lMoveFirstP) && secondByte.TryExtractMask("********", out var lMoveSecondP)) { var shortDistance2A = lMoveFirstP >> 2; var shortDistance1A = lMoveFirstP & 0b11; var shortDistance2I = lMoveSecondP >> 4; var shortDistance1I = lMoveSecondP & 0b1111; return new LMove(new ShortLinearDifference(shortDistance1A, shortDistance1I), new ShortLinearDifference(shortDistance2A, shortDistance2I)); } if (firstByte.TryExtractMask("*****101", out var fissionNearDistance)) return new Fission(new NearDifference(fissionNearDistance), secondByte); var thirdByte = binaryReader.ReadByte(); var fourthByte = binaryReader.ReadByte(); if (firstByte.TryExtractMask("*****001", out var gFillNearDistance)) return new GFill(new NearDifference(gFillNearDistance), new FarDifference(secondByte, thirdByte, fourthByte)); if (firstByte.TryExtractMask("*****000", out var gVoidNearDistance)) return new GVoid(new NearDifference(gVoidNearDistance), new FarDifference(secondByte, thirdByte, fourthByte)); throw new Exception("Can't parse command from the stream: " + $"[{firstByte}, {secondByte}, {thirdByte}, {fourthByte}...]"); } } }
41.672
126
0.582261
[ "MIT" ]
igorlukanin/icfpc2018-kontur-ru
lib/Utils/CommandSerializer.cs
5,209
C#
using DeliveryService.Data.Interface; using DeliveryService.Data.Model; using System.Linq; namespace DeliveryService.Data.Repository { public class RouteRepository : Repository<Route>, IRouteRepository { public RouteRepository(DeliveryServiceContext context) : base(context) { } } }
25.416667
82
0.763934
[ "MIT" ]
rtarantelli/DeliveryService
DeliveryService.Data/Repository/RouteRepository.cs
307
C#
using System; using System.Windows.Forms; using System.Security.Permissions; namespace SmallSharpToolscom.CompositePackage { public partial class EditorTextBox : RichTextBox { private bool m_FilterMouseClickMessages; public bool FilterMouseClickMessages { get { return m_FilterMouseClickMessages; } set { m_FilterMouseClickMessages = value; } } public EditorTextBox() { InitializeComponent(); } // Override WndProc so that we can ignore the mouse clicks when macro recording [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] protected override void WndProc(ref Message m) { switch (m.Msg) { case NativeMethods.WM_LBUTTONDOWN: case NativeMethods.WM_RBUTTONDOWN: case NativeMethods.WM_MBUTTONDOWN: case NativeMethods.WM_LBUTTONDBLCLK: if (m_FilterMouseClickMessages) { Focus(); return; } break; } base.WndProc(ref m); } private void richTextBoxCtrl_MouseRecording(object sender, EventArgs e) { SetCursor(m_FilterMouseClickMessages); } private void richTextBoxCtrl_MouseLeave(object sender, EventArgs e) { if(m_FilterMouseClickMessages) SetCursor(!m_FilterMouseClickMessages); } private void SetCursor(bool cursorNo) { Cursor = cursorNo ? Cursors.No : Cursors.Default; } } }
29.393443
102
0.555494
[ "Apache-2.0" ]
Listers/SmallSharpToolsDotNet
VisualStudioPlugins/CompositePackage/EditorTextBox.cs
1,793
C#
using Easy_Playable_Maker.Engine; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Windows.Forms; using System.Threading.Tasks; namespace Easy_Playable_Maker { static class Program { //Version.txt and BuildData.cs need regular updates /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainView()); } } }
21.103448
59
0.736928
[ "MIT" ]
KidoHyde/EasyPlayableMaker
Easy Playable Maker/Program.cs
614
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using SEDC.PizzaApp.Models; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; namespace SEDC.PizzaApp.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { return View(); } public IActionResult Privacy() { return View(); } [Route("AboutUs")] public IActionResult About() { StaticDb.Message = "About action changed the message!"; return View(); } [Route("ContactUs")] public IActionResult Contact() { return View(); } public IActionResult ReturnAnotherView() { return View("NewView"); //Home folder -> NewView.cshtml } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } } //localhost:344/ContactUs //localhost:344/AboutUs
25.563636
112
0.602418
[ "MIT" ]
sedc-codecademy/skwd9-net-08-aspnetmvc
G2/Class04 - Views pt.1/SEDC.PizzaApp/SEDC.PizzaApp/Controllers/HomeController.cs
1,408
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace RedButton.Common.TeklaStructures.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("RedButton.Common.TeklaStructures.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
44.1875
198
0.617751
[ "MIT" ]
SmartPluginsCommunity/RedButton
src/Common/RedButton.Common.TeklaStructures/Properties/Resources.Designer.cs
2,830
C#
using Orchard.ContentManagement; using Orchard.ContentManagement.Drivers; using Orchard.ContentManagement.Handlers; using Orchard.Fields.Fields; using Orchard.Fields.Settings; using Orchard.Fields.ViewModels; using Orchard.Localization; using System; using System.Collections.Generic; using System.Globalization; namespace Orchard.Fields.Drivers { public class NumericFieldDriver : ContentFieldDriver<NumericField> { public IOrchardServices Services { get; set; } private const string TemplateName = "Fields/Numeric.Edit"; private readonly Lazy<CultureInfo> _cultureInfo; public NumericFieldDriver(IOrchardServices services) { Services = services; T = NullLocalizer.Instance; _cultureInfo = new Lazy<CultureInfo>(() => CultureInfo.GetCultureInfo(Services.WorkContext.CurrentCulture)); } public Localizer T { get; set; } private static string GetPrefix(ContentField field, ContentPart part) { return part.PartDefinition.Name + "." + field.Name; } private static string GetDifferentiator(NumericField field, ContentPart part) { return field.Name; } protected override DriverResult Display(ContentPart part, NumericField field, string displayType, dynamic shapeHelper) { return ContentShape("Fields_Numeric", GetDifferentiator(field, part), () => { return shapeHelper.Fields_Numeric() .Settings(field.PartFieldDefinition.Settings.GetModel<NumericFieldSettings>()) .Value(Convert.ToString(field.Value, _cultureInfo.Value)); }); } protected override DriverResult Editor(ContentPart part, NumericField field, dynamic shapeHelper) { return ContentShape("Fields_Numeric_Edit", GetDifferentiator(field, part), () => { var settings = field.PartFieldDefinition.Settings.GetModel<NumericFieldSettings>(); var value = part.IsNew() && field.Value == null ? settings.DefaultValue : Convert.ToString(field.Value, _cultureInfo.Value); var model = new NumericFieldViewModel { Field = field, Settings = settings, Value = value }; return shapeHelper.EditorTemplate(TemplateName: TemplateName, Model: model, Prefix: GetPrefix(field, part)); }); } protected override DriverResult Editor(ContentPart part, NumericField field, IUpdateModel updater, dynamic shapeHelper) { var viewModel = new NumericFieldViewModel(); if (updater.TryUpdateModel(viewModel, GetPrefix(field, part), null, null)) { Decimal value; var settings = field.PartFieldDefinition.Settings.GetModel<NumericFieldSettings>(); field.Value = null; if (String.IsNullOrWhiteSpace(viewModel.Value)) { if (settings.Required) { updater.AddModelError(GetPrefix(field, part), T("The field {0} is mandatory.", T(field.DisplayName))); } } else if (!Decimal.TryParse(viewModel.Value, NumberStyles.Any, _cultureInfo.Value, out value)) { updater.AddModelError(GetPrefix(field, part), T("{0} is an invalid number", T(field.DisplayName))); } else { field.Value = value; if (settings.Minimum.HasValue && value < settings.Minimum.Value) { updater.AddModelError(GetPrefix(field, part), T("The value must be greater than {0}", settings.Minimum.Value)); } if (settings.Maximum.HasValue && value > settings.Maximum.Value) { updater.AddModelError(GetPrefix(field, part), T("The value must be less than {0}", settings.Maximum.Value)); } // checking the number of decimals if (Math.Round(value, settings.Scale) != value) { if (settings.Scale == 0) { updater.AddModelError(GetPrefix(field, part), T("The field {0} must be an integer", T(field.DisplayName))); } else { updater.AddModelError(GetPrefix(field, part), T("Invalid number of digits for {0}, max allowed: {1}", T(field.DisplayName), settings.Scale)); } } } } return Editor(part, field, shapeHelper); } protected override void Importing(ContentPart part, NumericField field, ImportContentContext context) { context.ImportAttribute(field.FieldDefinition.Name + "." + field.Name, "Value", v => field.Value = decimal.Parse(v, CultureInfo.InvariantCulture), () => field.Value = (decimal?)null); } protected override void Exporting(ContentPart part, NumericField field, ExportContentContext context) { context.Element(field.FieldDefinition.Name + "." + field.Name).SetAttributeValue("Value", !field.Value.HasValue ? String.Empty : field.Value.Value.ToString(CultureInfo.InvariantCulture)); } protected override void Describe(DescribeMembersContext context) { context .Member(null, typeof(decimal), T("Value"), T("The value of the field.")) .Enumerate<NumericField> (() => field => new[] { field.Value }); } } }
47.470588
199
0.602762
[ "BSD-3-Clause" ]
Codinlab/Orchard
src/Orchard.Web/Modules/Orchard.Fields/Drivers/NumericFieldDriver.cs
5,651
C#
using System.Security.Claims; using Microsoft.IdentityModel.Tokens; namespace Devon4Net.Infrastructure.JWT.Handlers { public interface IJwtHandler { string CreateJwtToken(List<Claim> clientClaims); List<Claim> GetUserClaims(string jwtToken); string GetClaimValue(List<Claim> claimList, string claim); string GetClaimValue(string token, string claim); SecurityKey GetIssuerSigningKey(); bool ValidateToken(string jwtToken, out ClaimsPrincipal claimsPrincipal, out SecurityToken securityToken); string CreateRefreshToken(); } }
37.1875
114
0.739496
[ "Apache-2.0" ]
MelaniaOgalla/devon4net
source/Modules/Devon4Net.Infrastructure.JWT/Handlers/IJwtHandler.cs
597
C#
//----------------------------------------------------------------------------- // Copyright : (c) Chris Moore, 2020 // License : MIT //----------------------------------------------------------------------------- namespace Z0 { partial struct RP { /// <summary> /// Defines the literal '{0}.{1}' /// </summary> [RenderPattern("{0}.{1}")] public const string SlotDot2 = Slot0 + Dot + Slot1; /// <summary> /// Defines the literal '{0}.{1}.{2}' /// </summary> [RenderPattern("{0}.{1}.{2}")] public const string SlotDot3 = SlotDot2 + Dot + Slot2; /// <summary> /// Defines the literal '{0}.{1}.{2}.{3}' /// </summary> [RenderPattern("{0}.{1}.{2}.{3}")] public const string SlotDot4 = SlotDot3 + Dot + Slot3; /// <summary> /// Defines the literal '{0}.{1}.{2}.{3}.{4}' /// </summary> [RenderPattern(5, "{0}.{1}.{2}.{3}.{4}")] public const string SlotDot5 = SlotDot4 + Dot + Slot4; } }
32.212121
79
0.400753
[ "BSD-3-Clause" ]
0xCM/z0
src/root/src/render/literals/SlotDot.cs
1,063
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: IEntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The interface IWindowsUpdateForBusinessConfigurationDeviceUpdateStatesCollectionRequest. /// </summary> public partial interface IWindowsUpdateForBusinessConfigurationDeviceUpdateStatesCollectionRequest : IBaseRequest { /// <summary> /// Adds the specified WindowsUpdateState to the collection via POST. /// </summary> /// <param name="windowsUpdateState">The WindowsUpdateState to add.</param> /// <returns>The created WindowsUpdateState.</returns> System.Threading.Tasks.Task<WindowsUpdateState> AddAsync(WindowsUpdateState windowsUpdateState); /// <summary> /// Adds the specified WindowsUpdateState to the collection via POST. /// </summary> /// <param name="windowsUpdateState">The WindowsUpdateState to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created WindowsUpdateState.</returns> System.Threading.Tasks.Task<WindowsUpdateState> AddAsync(WindowsUpdateState windowsUpdateState, CancellationToken cancellationToken); /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> System.Threading.Tasks.Task<IWindowsUpdateForBusinessConfigurationDeviceUpdateStatesCollectionPage> GetAsync(); /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> System.Threading.Tasks.Task<IWindowsUpdateForBusinessConfigurationDeviceUpdateStatesCollectionPage> GetAsync(CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IWindowsUpdateForBusinessConfigurationDeviceUpdateStatesCollectionRequest Expand(string value); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> IWindowsUpdateForBusinessConfigurationDeviceUpdateStatesCollectionRequest Expand(Expression<Func<WindowsUpdateState, object>> expandExpression); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IWindowsUpdateForBusinessConfigurationDeviceUpdateStatesCollectionRequest Select(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> IWindowsUpdateForBusinessConfigurationDeviceUpdateStatesCollectionRequest Select(Expression<Func<WindowsUpdateState, object>> selectExpression); /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> IWindowsUpdateForBusinessConfigurationDeviceUpdateStatesCollectionRequest Top(int value); /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> IWindowsUpdateForBusinessConfigurationDeviceUpdateStatesCollectionRequest Filter(string value); /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> IWindowsUpdateForBusinessConfigurationDeviceUpdateStatesCollectionRequest Skip(int value); /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> IWindowsUpdateForBusinessConfigurationDeviceUpdateStatesCollectionRequest OrderBy(string value); } }
48.759259
154
0.660653
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IWindowsUpdateForBusinessConfigurationDeviceUpdateStatesCollectionRequest.cs
5,266
C#
using Playnite.SDK; using Playnite.SDK.Data; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ReviewViewer { public class ReviewViewerSettings : ObservableObject { [DontSerialize] private bool useMatchingSteamApiLang { get; set; } = true; public bool UseMatchingSteamApiLang { get => useMatchingSteamApiLang; set { useMatchingSteamApiLang = value; OnPropertyChanged(); } } [DontSerialize] private bool downloadDataOnGameSelection { get; set; } = true; public bool DownloadDataOnGameSelection { get => downloadDataOnGameSelection; set { downloadDataOnGameSelection = value; OnPropertyChanged(); } } [DontSerialize] private double descriptionHeight { get; set; } = 180; public double DescriptionHeight { get => descriptionHeight; set { descriptionHeight = value; OnPropertyChanged(); } } [DontSerialize] private bool displayHelpfulnessData { get; set; } = true; public bool DisplayHelpfulnessData { get => displayHelpfulnessData; set { displayHelpfulnessData = value; OnPropertyChanged(); } } [DontSerialize] private bool displayReviewDate { get; set; } = true; public bool DisplayReviewDate { get => displayReviewDate; set { displayReviewDate = value; OnPropertyChanged(); } } } public class ReviewViewerSettingsViewModel : ObservableObject, ISettings { private readonly ReviewViewer plugin; private ReviewViewerSettings editingClone { get; set; } private ReviewViewerSettings settings; public ReviewViewerSettings Settings { get => settings; set { settings = value; OnPropertyChanged(); } } public ReviewViewerSettingsViewModel(ReviewViewer plugin) { // Injecting your plugin instance is required for Save/Load method because Playnite saves data to a location based on what plugin requested the operation. this.plugin = plugin; // Load saved settings. var savedSettings = plugin.LoadPluginSettings<ReviewViewerSettings>(); // LoadPluginSettings returns null if not saved data is available. if (savedSettings != null) { Settings = savedSettings; } else { Settings = new ReviewViewerSettings(); } } public void BeginEdit() { // Code executed when settings view is opened and user starts editing values. editingClone = Serialization.GetClone(Settings); } public void CancelEdit() { // Code executed when user decides to cancel any changes made since BeginEdit was called. // This method should revert any changes made to Option1 and Option2. Settings = editingClone; } public void EndEdit() { // Code executed when user decides to confirm changes made since BeginEdit was called. // This method should save settings made to Option1 and Option2. plugin.SavePluginSettings(Settings); } public bool VerifySettings(out List<string> errors) { // Code execute when user decides to confirm changes made since BeginEdit was called. // Executed before EndEdit is called and EndEdit is not called if false is returned. // List of errors is presented to user if verification fails. errors = new List<string>(); return true; } } }
30.427536
166
0.5618
[ "MIT" ]
azuravian/PlayniteExtensionsCollection
source/Generic/ReviewViewer/ReviewViewerSettings.cs
4,201
C#
using PrisonBack.Domain.Repositories; using PrisonBack.Domain.Services; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace PrisonBack.Services { public class InviteCodeService : IInviteCodeService { private readonly IInviteCodeRepository _inviteCodeRepository; public InviteCodeService(IInviteCodeRepository inviteCodeRepository) { _inviteCodeRepository = inviteCodeRepository; } public void ChangeStatus(string code) { _inviteCodeRepository.ChangeStatus(code); } public void CreateCode() { _inviteCodeRepository.CreateCode(); } public bool IsActive(string code) { return _inviteCodeRepository.IsActive(code); } } }
24.057143
76
0.669834
[ "MIT" ]
KamilMaciuszek/PrisonBack
PrisonBack/PrisonBack/Services/InviteCodeService.cs
844
C#
using System; using System.Collections; using System.Collections.Generic; using Newtonsoft.Json; using UnityEngine; using UnityEngine.UI; using Random = UnityEngine.Random; public class OnlineRoomSelection : MonoBehaviour { public GameObject NameInputField; public GameObject RoomsGameObject; public Text PlayerName; public Text P1Label; public Text P2Label; private static RenjuBoard RenjuBoard; private static List<RoomSummary> RoomSummaries; private static TextAsset AnimalsTextFile; private static string[] animals; public void Init(RenjuBoard renjuBoard) { RenjuBoard = renjuBoard; } void Start() { if (GameConfiguration.IsOnlineGame) { AnimalsTextFile = Resources.Load<TextAsset>("animals"); animals = AnimalsTextFile.text.Split(); InvokeRepeating("RefreshLobbyIfNotInGame", 0.2f, 3f); //refresh every 3s InvokeRepeating("RefreshRoomIfWaitingForOpponent", 0.2f, 1f); InvokeRepeating("KeepConnectionToServerAlive", 0.2f, 5f); //evict player if this is not called after a while foreach (Transform roomTransform in RoomsGameObject.transform) { foreach (Transform t in roomTransform) { if (t.name == "JoinButton") { string buttonText = t.GetChild(0).GetComponent<Text>().text; int roomNumber = Int32.Parse(buttonText.Substring(buttonText.IndexOf('#') + 1)); t.GetComponent<Button>().onClick.AddListener(() => OnJoinButtonPress(roomNumber)); } } } } else { HideRoomSelectionUI(); } /*JsonConvert.DefaultSettings = () => new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, //need to be able to update some properties of Room without overwriting others };*/ } void RefreshLobbyIfNotInGame() { if (OnlineMultiplayerClient.OnlinePlayerNumber == PlayerNumber.Neither) { StartCoroutine(RefreshLobby()); } } void RefreshRoomIfWaitingForOpponent() { if (OnlineMultiplayerClient.OnlinePlayerNumber == PlayerNumber.One && string.IsNullOrEmpty(OnlineMultiplayerClient.OnlineRoomInfo.P2()) || OnlineMultiplayerClient.OnlinePlayerNumber == PlayerNumber.Two && string.IsNullOrEmpty(OnlineMultiplayerClient.OnlineRoomInfo.P1())) { StartCoroutine(RefreshRoom()); } } void KeepConnectionToServerAlive() { if (OnlineMultiplayerClient.OnlinePlayerNumber != PlayerNumber.Neither) { StartCoroutine(KeepAlive()); } } IEnumerator RefreshLobby() { using (WWW www = new WWW(GameConfiguration.ServerUrl + "refresh-lobby")) { yield return www; //MAJOR KEY, otherwise anything written here assumes www is null //(spent hrs debugging this then realized I stumbled across this before) if (www.isDone) { RoomSummaries = JsonConvert.DeserializeObject<List<RoomSummary>>(www.text); int currentRoomIndex = 0; foreach (Transform roomTransform in RoomsGameObject.transform) { foreach (Transform t in roomTransform) { if (t.name == "BlackPlayerName") { t.GetComponent<Text>().text = RoomSummaries[currentRoomIndex].P1; } if (t.name == "WhitePlayerName") { t.GetComponent<Text>().text = RoomSummaries[currentRoomIndex].P2; } } currentRoomIndex++; } } } } IEnumerator RefreshRoom() { using (WWW www = new WWW(GameConfiguration.ServerUrl + "refresh-room?room=" + OnlineMultiplayerClient.OnlineRoomNumber)) { yield return www; if (www.isDone) { RoomSummary response = JsonConvert.DeserializeObject<RoomSummary>(www.text); OnlineMultiplayerClient.OnlineRoomInfo.SetP1(response.P1); OnlineMultiplayerClient.OnlineRoomInfo.SetP2(response.P2); P1Label.text = response.P1; P2Label.text = response.P2; } } } IEnumerator KeepAlive() { using (WWW www = new WWW(GameConfiguration.ServerUrl + "keep-alive?room=" + OnlineMultiplayerClient.OnlineRoomNumber + "&player-number=" + OnlineMultiplayerClient.OnlinePlayerNumber)) { yield return www; if (www.isDone) { // Check if server gave us a -1 error code, meaning opponent disconnected / forfeit / ragequit if (www.text == "-1") { RenjuBoard.SetWinner(OnlineMultiplayerClient.OnlinePlayerNumber); RenjuBoard.WinMessage.GetComponent<TextMesh>().text = "The opponent has left. \nYou win!"; OnlineMultiplayerClient.OnlinePlayerNumber = PlayerNumber.Neither; //prevent KeepAlive being called again } } } } private void OnJoinButtonPress(int roomNumber) { StartCoroutine(JoinRoomGivenRoomNumberAndPlayerName(roomNumber, PlayerName.text)); } public IEnumerator JoinRoomGivenRoomNumberAndPlayerName(int roomNumber, string playerName) { if (string.IsNullOrEmpty(playerName)) { playerName = animals[(int)(Random.value * animals.Length)]; } using (WWW www = new WWW(GameConfiguration.ServerUrl + "join?room=" + roomNumber + "&name=" + playerName)) { yield return www; if (www.isDone) { if (www.text == "1") { OnlineMultiplayerClient.OnlinePlayerNumber = PlayerNumber.One; OnlineMultiplayerClient.OnlineRoomNumber = roomNumber; P1Label.text = playerName; HideRoomSelectionUI(); } else if (www.text == "2") { OnlineMultiplayerClient.OnlinePlayerNumber = PlayerNumber.Two; OnlineMultiplayerClient.OnlineRoomNumber = roomNumber; P2Label.text = playerName; HideRoomSelectionUI(); } else { // ask user to retry, since someone else may have taken their place? } } } } private void HideRoomSelectionUI() { NameInputField.SetActive(false); RoomsGameObject.SetActive(false); } public void ExitBackToLobby() { NameInputField.SetActive(true); RoomsGameObject.SetActive(true); PlayerName.text = ""; P1Label.text = ""; P2Label.text = ""; } }
35.325243
191
0.565755
[ "MIT" ]
henrysun18/Renju_Unity3D
Online/OnlineRoomSelection.cs
7,279
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ASC.Web.Projects.Resources { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class ImportResource { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal ImportResource() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ASC.Web.Projects.Resources.ImportResource", typeof(ImportResource).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Empty Email. /// </summary> public static string EmptyEmail { get { return ResourceManager.GetString("EmptyEmail", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The URL field is empty. /// </summary> public static string EmptyURL { get { return ResourceManager.GetString("EmptyURL", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Importing completed. /// </summary> public static string ImportCompleted { get { return ResourceManager.GetString("ImportCompleted", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Error while importing. /// </summary> public static string ImportFailed { get { return ResourceManager.GetString("ImportFailed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Invalid company URL.. /// </summary> public static string InvalidCompaniUrl { get { return ResourceManager.GetString("InvalidCompaniUrl", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Invalid email.. /// </summary> public static string InvalidEmail { get { return ResourceManager.GetString("InvalidEmail", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Importing from Basecamp. /// </summary> public static string PopupPanelHeader { get { return ResourceManager.GetString("PopupPanelHeader", resourceCulture); } } /// <summary> /// Looks up a localized string similar to awaiting. /// </summary> public static string StatusAwaiting { get { return ResourceManager.GetString("StatusAwaiting", resourceCulture); } } } }
39.117647
192
0.555075
[ "Apache-2.0" ]
jeanluctritsch/CommunityServer
web/studio/ASC.Web.Studio/Products/Projects/Resources/ImportResource.Designer.cs
5,322
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace SQLiteTool.Util { public static class FocusExtension { public static bool GetIsFocused(DependencyObject obj) { return (bool)obj.GetValue(IsFocusedProperty); } public static void SetIsFocused(DependencyObject obj, bool value) { obj.SetValue(IsFocusedProperty, value); } public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached( "IsFocused", typeof(bool), typeof(FocusExtension), new UIPropertyMetadata(false, OnIsFocusedPropertyChanged)); private static void OnIsFocusedPropertyChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { var uie = (UIElement)d; if ((bool)e.NewValue) { uie.Focus(); } } } }
28.102564
76
0.597628
[ "Apache-2.0" ]
zhaotianff/SQLiteTool
Util/FocusExtension.cs
1,098
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace E4d.Wapi { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } }
21.038462
57
0.720293
[ "MIT" ]
eDyablo/handicraft
csharp/wapi/Program.cs
547
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.Collections.Immutable; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Extensions; using MicroBenchmarks; namespace System.Collections { [BenchmarkCategory(Categories.Libraries, Categories.Collections, Categories.GenericCollections)] [GenericTypeArguments(typeof(int))] // value type [GenericTypeArguments(typeof(string))] // reference type public class ContainsTrueComparer<T> where T : IEquatable<T> { private sealed class WrapDefaultComparer : IEqualityComparer<T>, IComparer<T> { public int Compare(T x, T y) => Comparer<T>.Default.Compare(x, y); public bool Equals(T x, T y) => EqualityComparer<T>.Default.Equals(x, y); public int GetHashCode(T obj) => EqualityComparer<T>.Default.GetHashCode(obj); } private T[] _found; private HashSet<T> _hashSet; private SortedSet<T> _sortedSet; private ImmutableHashSet<T> _immutableHashSet; private ImmutableSortedSet<T> _immutableSortedSet; [Params(Utils.DefaultCollectionSize)] public int Size; [GlobalSetup(Target = nameof(HashSet))] public void SetupHashSet() { _found = ValuesGenerator.ArrayOfUniqueValues<T>(Size); _hashSet = new HashSet<T>(_found, new WrapDefaultComparer()); } [Benchmark] public bool HashSet() { bool result = default; HashSet<T> collection = _hashSet; T[] found = _found; for (int i = 0; i < found.Length; i++) result ^= collection.Contains(found[i]); return result; } [GlobalSetup(Target = nameof(SortedSet))] public void SetupSortedSet() { _found = ValuesGenerator.ArrayOfUniqueValues<T>(Size); _sortedSet = new SortedSet<T>(_found, new WrapDefaultComparer()); } [Benchmark] public bool SortedSet() { bool result = default; SortedSet<T> collection = _sortedSet; T[] found = _found; for (int i = 0; i < found.Length; i++) result ^= collection.Contains(found[i]); return result; } [GlobalSetup(Target = nameof(ImmutableHashSet))] public void SetupImmutableHashSet() { _found = ValuesGenerator.ArrayOfUniqueValues<T>(Size); _immutableHashSet = Immutable.ImmutableHashSet.CreateRange(_found).WithComparer(new WrapDefaultComparer()); } [Benchmark] public bool ImmutableHashSet() { bool result = default; ImmutableHashSet<T> collection = _immutableHashSet; T[] found = _found; for (int i = 0; i < found.Length; i++) result ^= collection.Contains(found[i]); return result; } [GlobalSetup(Target = nameof(ImmutableSortedSet))] public void SetupImmutableSortedSet() { _found = ValuesGenerator.ArrayOfUniqueValues<T>(Size); _immutableSortedSet = Immutable.ImmutableSortedSet.CreateRange(_found).WithComparer(new WrapDefaultComparer()); } [Benchmark] public bool ImmutableSortedSet() { bool result = default; ImmutableSortedSet<T> collection = _immutableSortedSet; T[] found = _found; for (int i = 0; i < found.Length; i++) result ^= collection.Contains(found[i]); return result; } } }
35.971698
123
0.608445
[ "MIT" ]
BruceForstall/performance
src/benchmarks/micro/libraries/System.Collections/Contains/ContainsTrueComparer.cs
3,815
C#
using System; using System.Threading; using System.Net.Sockets; using System.Text; using System.Linq; using System.Numerics; using NetworkServices; namespace ChatClient { class Program { private static Client client; static void Main(string[] args) { try { client = new Client(); Thread receiveThread = new Thread(new ThreadStart(client.ReceiveMessage)); receiveThread.Start();                 Console.WriteLine($"[You communicate under: {client.UserName}]"); client.SendMessage(); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { client.Disconnect(); } } } }
21.461538
90
0.512545
[ "MIT" ]
Sunshine-ki/BMSTU7_NETWORK_CP
src/ChatClient/ChatClient/Program.cs
855
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: EntityType.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Text.Json.Serialization; /// <summary> /// The type Android Device Owner Pkcs Certificate Profile. /// </summary> [JsonConverter(typeof(DerivedTypeConverter<AndroidDeviceOwnerPkcsCertificateProfile>))] public partial class AndroidDeviceOwnerPkcsCertificateProfile : AndroidDeviceOwnerCertificateProfileBase { ///<summary> /// The AndroidDeviceOwnerPkcsCertificateProfile constructor ///</summary> public AndroidDeviceOwnerPkcsCertificateProfile() { this.ODataType = "microsoft.graph.androidDeviceOwnerPkcsCertificateProfile"; } /// <summary> /// Gets or sets certificate store. /// Target store certificate. Possible values are: user, machine. /// </summary> [JsonPropertyName("certificateStore")] public CertificateStore? CertificateStore { get; set; } /// <summary> /// Gets or sets certificate template name. /// PKCS Certificate Template Name /// </summary> [JsonPropertyName("certificateTemplateName")] public string CertificateTemplateName { get; set; } /// <summary> /// Gets or sets certification authority. /// PKCS Certification Authority /// </summary> [JsonPropertyName("certificationAuthority")] public string CertificationAuthority { get; set; } /// <summary> /// Gets or sets certification authority name. /// PKCS Certification Authority Name /// </summary> [JsonPropertyName("certificationAuthorityName")] public string CertificationAuthorityName { get; set; } /// <summary> /// Gets or sets certification authority type. /// Certification authority type. Possible values are: notConfigured, microsoft, digiCert. /// </summary> [JsonPropertyName("certificationAuthorityType")] public DeviceManagementCertificationAuthority? CertificationAuthorityType { get; set; } /// <summary> /// Gets or sets custom subject alternative names. /// Custom Subject Alternative Name Settings. This collection can contain a maximum of 500 elements. /// </summary> [JsonPropertyName("customSubjectAlternativeNames")] public IEnumerable<CustomSubjectAlternativeName> CustomSubjectAlternativeNames { get; set; } /// <summary> /// Gets or sets subject alternative name format string. /// Custom String that defines the AAD Attribute. /// </summary> [JsonPropertyName("subjectAlternativeNameFormatString")] public string SubjectAlternativeNameFormatString { get; set; } /// <summary> /// Gets or sets subject name format string. /// Custom format to use with SubjectNameFormat = Custom. Example: CN={{EmailAddress}},E={{EmailAddress}},OU=Enterprise Users,O=Contoso Corporation,L=Redmond,ST=WA,C=US /// </summary> [JsonPropertyName("subjectNameFormatString")] public string SubjectNameFormatString { get; set; } /// <summary> /// Gets or sets managed device certificate states. /// Certificate state for devices. This collection can contain a maximum of 2147483647 elements. /// </summary> [JsonPropertyName("managedDeviceCertificateStates")] public IAndroidDeviceOwnerPkcsCertificateProfileManagedDeviceCertificateStatesCollectionPage ManagedDeviceCertificateStates { get; set; } /// <summary> /// Gets or sets managedDeviceCertificateStatesNextLink. /// </summary> [JsonPropertyName("managedDeviceCertificateStates@odata.nextLink")] [JsonConverter(typeof(NextLinkConverter))] public string ManagedDeviceCertificateStatesNextLink { get; set; } } }
42.361905
176
0.642311
[ "MIT" ]
ScriptBox99/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/model/AndroidDeviceOwnerPkcsCertificateProfile.cs
4,448
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/ObjIdl.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop { [Guid("00000026-0000-0000-C000-000000000046")] public unsafe partial struct IUrlMon { public void** lpVtbl; [return: NativeTypeName("HRESULT")] public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("void **")] void** ppvObject) { return ((delegate* stdcall<IUrlMon*, Guid*, void**, int>)(lpVtbl[0]))((IUrlMon*)Unsafe.AsPointer(ref this), riid, ppvObject); } [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* stdcall<IUrlMon*, uint>)(lpVtbl[1]))((IUrlMon*)Unsafe.AsPointer(ref this)); } [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* stdcall<IUrlMon*, uint>)(lpVtbl[2]))((IUrlMon*)Unsafe.AsPointer(ref this)); } [return: NativeTypeName("HRESULT")] public int AsyncGetClassBits([NativeTypeName("const IID &")] Guid* rclsid, [NativeTypeName("LPCWSTR")] ushort* pszTYPE, [NativeTypeName("LPCWSTR")] ushort* pszExt, [NativeTypeName("DWORD")] uint dwFileVersionMS, [NativeTypeName("DWORD")] uint dwFileVersionLS, [NativeTypeName("LPCWSTR")] ushort* pszCodeBase, [NativeTypeName("IBindCtx *")] IBindCtx* pbc, [NativeTypeName("DWORD")] uint dwClassContext, [NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("DWORD")] uint flags) { return ((delegate* stdcall<IUrlMon*, Guid*, ushort*, ushort*, uint, uint, ushort*, IBindCtx*, uint, Guid*, uint, int>)(lpVtbl[3]))((IUrlMon*)Unsafe.AsPointer(ref this), rclsid, pszTYPE, pszExt, dwFileVersionMS, dwFileVersionLS, pszCodeBase, pbc, dwClassContext, riid, flags); } } }
50.285714
491
0.671875
[ "MIT" ]
john-h-k/terrafx.interop.windows
sources/Interop/Windows/um/ObjIdl/IUrlMon.cs
2,114
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 codebuild-2016-10-06.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.CodeBuild { /// <summary> /// Configuration for accessing Amazon CodeBuild service /// </summary> public partial class AmazonCodeBuildConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.5.0.2"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonCodeBuildConfig() { this.AuthenticationServiceName = "codebuild"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "codebuild"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2016-10-06"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
26.175
107
0.58787
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/CodeBuild/Generated/AmazonCodeBuildConfig.cs
2,094
C#
using System; using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using MediatR; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Client; namespace OmniSharp.Extensions.DebugAdapter.Shared { public class DapResponseRouter : IResponseRouter { internal readonly IOutputHandler OutputHandler; internal readonly ISerializer Serializer; internal readonly ConcurrentDictionary<long, (string method, TaskCompletionSource<JToken> pendingTask)> Requests = new ConcurrentDictionary<long, (string method, TaskCompletionSource<JToken> pendingTask)>(); internal static readonly ConcurrentDictionary<Type, string> MethodCache = new ConcurrentDictionary<Type, string>(); public DapResponseRouter(IOutputHandler outputHandler, ISerializer serializer) { OutputHandler = outputHandler; Serializer = serializer; } public void SendNotification(string method) => OutputHandler.Send( new OutgoingNotification { Method = method } ); public void SendNotification<T>(string method, T @params) => OutputHandler.Send( new OutgoingNotification { Method = method, Params = @params } ); public void SendNotification(IRequest @params) => SendNotification(GetMethodName(@params.GetType()), @params); public Task<TResponse> SendRequest<TResponse>(IRequest<TResponse> @params, CancellationToken cancellationToken) => SendRequest(GetMethodName(@params.GetType()), @params).Returning<TResponse>(cancellationToken); public IResponseRouterReturns SendRequest(string method) => new ResponseRouterReturnsImpl(this, method, new object()); public IResponseRouterReturns SendRequest<T>(string method, T @params) => new ResponseRouterReturnsImpl(this, method, @params); public bool TryGetRequest(long id, [NotNullWhen(true)] out string method, [NotNullWhen(true)] out TaskCompletionSource<JToken> pendingTask) { var result = Requests.TryGetValue(id, out var source); method = source.method; pendingTask = source.pendingTask; return result; } private string GetMethodName(Type type) { if (!MethodCache.TryGetValue(type, out var methodName)) { var attribute = MethodAttribute.From(type); if (attribute == null) { throw new NotSupportedException($"Unable to infer method name for type {type.FullName}"); } methodName = attribute.Method; MethodCache.TryAdd(type, methodName); } return methodName; } private class ResponseRouterReturnsImpl : IResponseRouterReturns { private readonly DapResponseRouter _router; private readonly string _method; private readonly object _params; public ResponseRouterReturnsImpl(DapResponseRouter router, string method, object @params) { _router = router; _method = method; _params = @params; } public async Task<TResponse> Returning<TResponse>(CancellationToken cancellationToken) { var nextId = _router.Serializer.GetNextId(); var tcs = new TaskCompletionSource<JToken>(); _router.Requests.TryAdd(nextId, ( _method, tcs )); cancellationToken.ThrowIfCancellationRequested(); _router.OutputHandler.Send( new OutgoingRequest { Method = _method, Params = _params, Id = nextId } ); if (_method != RequestNames.Cancel) { cancellationToken.Register( () => { if (tcs.Task.IsCompleted) return; _router.SendRequest(RequestNames.Cancel, new { requestId = nextId }).Returning<CancelArguments>(CancellationToken.None); } ); } try { var result = await tcs.Task.ConfigureAwait(false); if (typeof(TResponse) == typeof(Unit)) { return (TResponse) (object) Unit.Value; } return result.ToObject<TResponse>(_router.Serializer.JsonSerializer); } finally { _router.Requests.TryRemove(nextId, out _); } } public async Task ReturningVoid(CancellationToken cancellationToken) => await Returning<Unit>(cancellationToken).ConfigureAwait(false); } } }
38.094203
148
0.579989
[ "MIT" ]
kamit9171/csharp-language-server-protocol
src/Dap.Shared/DapResponseRouter.cs
5,257
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 Xunit; namespace System.SpanTests { public static partial class SpanTests { [Fact] public static void ZeroLengthSequenceCompareTo() { int[] a = new int[3]; Span<int> first = new Span<int>(a, 1, 0); Span<int> second = new Span<int>(a, 2, 0); int result = first.SequenceCompareTo(second); Assert.Equal(0, result); } [Fact] public static void SameSpanSequenceCompareTo() { int[] a = { 4, 5, 6 }; Span<int> span = new Span<int>(a); int result = span.SequenceCompareTo(span); Assert.Equal(0, result); } [Fact] public static void LengthMismatchSequenceCompareTo() { int[] a = { 4, 5, 6 }; Span<int> first = new Span<int>(a, 0, 2); Span<int> second = new Span<int>(a, 0, 3); int result = first.SequenceCompareTo(second); Assert.True(result < 0); result = second.SequenceCompareTo(first); Assert.True(result > 0); // one sequence is empty first = new Span<int>(a, 1, 0); result = first.SequenceCompareTo(second); Assert.True(result < 0); result = second.SequenceCompareTo(first); Assert.True(result > 0); } [Fact] public static void OnSequenceCompareToOfEqualSpansMakeSureEveryElementIsCompared() { for (int length = 0; length < 100; length++) { TIntLog log = new TIntLog(); TInt[] first = new TInt[length]; TInt[] second = new TInt[length]; for (int i = 0; i < length; i++) { first[i] = second[i] = new TInt(10 * (i + 1), log); } Span<TInt> firstSpan = new Span<TInt>(first); ReadOnlySpan<TInt> secondSpan = new ReadOnlySpan<TInt>(second); int result = firstSpan.SequenceCompareTo(secondSpan); Assert.Equal(0, result); // Make sure each element of the array was compared once. (Strictly speaking, it would not be illegal for // SequenceCompareTo to compare an element more than once but that would be a non-optimal implementation and // a red flag. So we'll stick with the stricter test.) Assert.Equal(first.Length, log.Count); foreach (TInt elem in first) { int numCompares = log.CountCompares(elem.Value, elem.Value); Assert.True(numCompares == 1, $"Expected {numCompares} == 1 for element {elem.Value}."); } } } [Fact] public static void SequenceCompareToSingleMismatch() { for (int length = 1; length < 32; length++) { for (int mismatchIndex = 0; mismatchIndex < length; mismatchIndex++) { TIntLog log = new TIntLog(); TInt[] first = new TInt[length]; TInt[] second = new TInt[length]; for (int i = 0; i < length; i++) { first[i] = second[i] = new TInt(10 * (i + 1), log); } second[mismatchIndex] = new TInt(second[mismatchIndex].Value + 1, log); Span<TInt> firstSpan = new Span<TInt>(first); ReadOnlySpan<TInt> secondSpan = new ReadOnlySpan<TInt>(second); int result = firstSpan.SequenceCompareTo(secondSpan); Assert.True(result < 0); Assert.Equal(1, log.CountCompares(first[mismatchIndex].Value, second[mismatchIndex].Value)); result = secondSpan.SequenceCompareTo(firstSpan); // adds to log.CountCompares Assert.True(result > 0); Assert.Equal(2, log.CountCompares(first[mismatchIndex].Value, second[mismatchIndex].Value)); } } } [Fact] public static void SequenceCompareToNoMatch() { for (int length = 1; length < 32; length++) { TIntLog log = new TIntLog(); TInt[] first = new TInt[length]; TInt[] second = new TInt[length]; for (int i = 0; i < length; i++) { first[i] = new TInt(i + 1, log); second[i] = new TInt(length + i + 1, log); } Span<TInt> firstSpan = new Span<TInt>(first); ReadOnlySpan<TInt> secondSpan = new ReadOnlySpan<TInt>(second); int result = firstSpan.SequenceCompareTo(secondSpan); Assert.True(result < 0); Assert.Equal(1, log.CountCompares(firstSpan[0].Value, secondSpan[0].Value)); result = secondSpan.SequenceCompareTo(firstSpan); // adds to log.CountCompares Assert.True(result > 0); Assert.Equal(2, log.CountCompares(firstSpan[0].Value, secondSpan[0].Value)); } } [Fact] public static void MakeSureNoSequenceCompareToChecksGoOutOfRange() { const int GuardValue = 77777; const int GuardLength = 50; Action<int, int> checkForOutOfRangeAccess = delegate (int x, int y) { if (x == GuardValue || y == GuardValue) throw new Exception("Detected out of range access in IndexOf()"); }; for (int length = 0; length < 100; length++) { TInt[] first = new TInt[GuardLength + length + GuardLength]; TInt[] second = new TInt[GuardLength + length + GuardLength]; for (int i = 0; i < first.Length; i++) { first[i] = second[i] = new TInt(GuardValue, checkForOutOfRangeAccess); } for (int i = 0; i < length; i++) { first[GuardLength + i] = second[GuardLength + i] = new TInt(10 * (i + 1), checkForOutOfRangeAccess); } Span<TInt> firstSpan = new Span<TInt>(first, GuardLength, length); Span<TInt> secondSpan = new Span<TInt>(second, GuardLength, length); int result = firstSpan.SequenceCompareTo(secondSpan); Assert.Equal(0, result); } } } }
38.691011
125
0.506171
[ "MIT" ]
CliffordOzewell/corefx
src/System.Memory/tests/Span/SequenceCompareTo.T.cs
6,887
C#
using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace AnimalShelter.Migrations { public partial class Initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Animals", columns: table => new { AnimalId = table.Column<int>(type: "int", nullable: false) .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true), Species = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true), Age = table.Column<int>(type: "int", nullable: false), Breed = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true), Gender = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Animals", x => x.AnimalId); }); migrationBuilder.InsertData( table: "Animals", columns: new[] { "AnimalId", "Age", "Breed", "Gender", "Name", "Species" }, values: new object[,] { { 1, 5, "Siamese", "Female", "Jackie", "Cat" }, { 2, 10, "German Shephard", "Male", "Buddy", "Dog" }, { 3, 1, "Orange Tabby", "Male", "Milo", "Cat" }, { 4, 2, "Siberian Husky", "Female", "Margo", "Dog" }, { 5, 3, "Labrador", "Female", "Suzie", "Dog" } }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Animals"); } } }
43.276596
114
0.515733
[ "MIT" ]
an12346/AnimalShelter
AnimalShelter/Migrations/20220121174343_Initial.cs
2,036
C#
using System; using System.IO; using System.Text; using QQ.Framework.Utils; namespace QQ.Framework.Packets.PCTLV { [TlvTag(TlvTags.AccountBasicInfo)] internal class TLV0108 : BaseTLV { public TLV0108() { Command = 0x0108; Name = "SSO2::TLV_AccountBasicInfo_0x108"; } public void Parser_Tlv(QQUser user, BinaryReader buf) { var type = buf.BeReadUInt16(); //type var length = buf.BeReadUInt16(); //length WSubVer = buf.BeReadUInt16(); //wSubVer if (WSubVer == 0x0001) { var len = buf.BeReadUInt16(); var buffer = buf.ReadBytes(len); var bufAccountBasicInfo = new BinaryReader(new MemoryStream(buffer)); len = bufAccountBasicInfo.BeReadUInt16(); buffer = bufAccountBasicInfo.ReadBytes(len); var info = new BinaryReader(new MemoryStream(buffer)); var wSsoAccountWFaceIndex = info.BeReadUInt16(); len = info.ReadByte(); if (len > 0) { user.NickName = Encoding.UTF8.GetString(info.ReadBytes(len)); } user.Gender = info.ReadByte(); var dwSsoAccountDwUinFlag = info.BeReadUInt32(); user.Age = info.ReadByte(); var bufStOther = bufAccountBasicInfo.ReadBytes( (int) (bufAccountBasicInfo.BaseStream.Length - bufAccountBasicInfo.BaseStream.Position)); } else { throw new Exception($"{Name} 无法识别的版本号 {WSubVer}"); } } } }
33.230769
113
0.530671
[ "MIT" ]
0nise/PCQQ-Agreement
QQ.Framework/Packets/PCTLV/TLV_0108.cs
1,744
C#
namespace UAlbion.Api { public interface IEvent { } }
14.5
31
0.689655
[ "MIT" ]
mrwillbarnz/ualbion
Api/IEvent.cs
60
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using AutoMapper; using Covid19Api.Presentation.Response; using Covid19Api.Repositories.Abstractions; using Covid19Api.UseCases.Abstractions.Queries.CountryStatisticsAggregates; using MediatR; namespace Covid19Api.UseCases.Queries.CountryStatisticsAggregates { public class LoadCountryStatisticsAggregatesForCountryInYearQueryHandler : IRequestHandler< LoadCountryStatisticsAggregatesForCountryInYearQuery, IEnumerable<CountryStatisticAggregateDto>> { private readonly IMapper mapper; private readonly ICountryStatisticsAggregatesReadRepository countryStatisticsAggregatesReadRepository; public LoadCountryStatisticsAggregatesForCountryInYearQueryHandler(IMapper mapper, ICountryStatisticsAggregatesReadRepository countryStatisticsAggregatesReadRepository) { this.mapper = mapper; this.countryStatisticsAggregatesReadRepository = countryStatisticsAggregatesReadRepository; } public async Task<IEnumerable<CountryStatisticAggregateDto>> Handle( LoadCountryStatisticsAggregatesForCountryInYearQuery request, CancellationToken cancellationToken) { var aggregates = await this.countryStatisticsAggregatesReadRepository.FindForCountryInYearAsync(request.Country, request.Year); return aggregates.Any() ? this.mapper.Map<IEnumerable<CountryStatisticAggregateDto>>(aggregates) : Array.Empty<CountryStatisticAggregateDto>(); } } }
42.846154
111
0.766607
[ "MIT" ]
alsami/Covid-19-API
src/Covid19Api.UseCases/Queries/CountryStatisticsAggregates/LoadCountryStatisticsAggregatesForCountryInYearQueryHandler.cs
1,671
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. 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. */ namespace TencentCloud.Privatedns.V20201028.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DeletePrivateZoneResponse : AbstractModel { /// <summary> /// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 /// </summary> [JsonProperty("RequestId")] public string RequestId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
30.454545
81
0.666418
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Privatedns/V20201028/Models/DeletePrivateZoneResponse.cs
1,398
C#
using System.Collections.Generic; namespace WorkshopManager.Forms.ToolsForRequestVIew { public class RequestUnderModification { public static Request Value { get; set; } private static readonly RequestUnderModification instance = new RequestUnderModification(); private RequestUnderModification() { Value = new Request("-", "-", "-", "-", new List<Part>(), true); } public static RequestUnderModification Instance { get { return instance; } } } }
23.68
99
0.581081
[ "MIT" ]
BartoszBaczek/WorkshopRequestsManager
Project/WorkshopManager/WorkshopManager/Forms/RequestUnderModification.cs
594
C#
using ScottPlot.Config; using ScottPlot.Diagnostic.Attributes; using ScottPlot.Drawing; using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Linq; using System.Runtime.InteropServices; namespace ScottPlot { #pragma warning disable CS0618 // Type or member is obsolete public class PlottableHeatmap : Plottable, IPlottable { // these fields are updated when the intensities are analyzed private double[] NormalizedIntensities; private double min; private double max; private int width; private int height; private Bitmap BmpHeatmap; private Bitmap BmpScale; // these fields are customized by the user public string label; public Colormap Colormap; public double[] AxisOffsets; public double[] AxisMultipliers; public double? ScaleMin; public double? ScaleMax; public double? TransparencyThreshold; public Bitmap BackgroundImage; public bool DisplayImageAbove; public bool ShowAxisLabels; // call this externally if data changes public void UpdateData(double[,] intensities) { width = intensities.GetLength(1); height = intensities.GetLength(0); double[] intensitiesFlattened = intensities.Cast<double>().ToArray(); min = intensitiesFlattened.Min(); max = intensitiesFlattened.Max(); double normalizeMin = (ScaleMin.HasValue && ScaleMin.Value < min) ? ScaleMin.Value : min; double normalizeMax = (ScaleMax.HasValue && ScaleMax.Value > max) ? ScaleMax.Value : max; if (TransparencyThreshold.HasValue) TransparencyThreshold = Normalize(TransparencyThreshold.Value, min, max, ScaleMin, ScaleMax); NormalizedIntensities = Normalize(intensitiesFlattened, null, null, ScaleMin, ScaleMax); int[] flatARGB = Colormap.GetRGBAs(NormalizedIntensities, Colormap, minimumIntensity: TransparencyThreshold ?? 0); double[] normalizedValues = Normalize(Enumerable.Range(0, 256).Select(i => (double)i).Reverse().ToArray(), null, null, ScaleMin, ScaleMax); int[] scaleRGBA = Colormap.GetRGBAs(normalizedValues, Colormap); BmpHeatmap?.Dispose(); BmpScale?.Dispose(); BmpHeatmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); BmpScale = new Bitmap(1, 256, PixelFormat.Format32bppArgb); Rectangle rect = new Rectangle(0, 0, BmpHeatmap.Width, BmpHeatmap.Height); Rectangle rectScale = new Rectangle(0, 0, BmpScale.Width, BmpScale.Height); BitmapData bmpData = BmpHeatmap.LockBits(rect, ImageLockMode.ReadWrite, BmpHeatmap.PixelFormat); BitmapData scaleBmpData = BmpScale.LockBits(rectScale, ImageLockMode.ReadWrite, BmpScale.PixelFormat); Marshal.Copy(flatARGB, 0, bmpData.Scan0, flatARGB.Length); Marshal.Copy(scaleRGBA, 0, scaleBmpData.Scan0, scaleRGBA.Length); BmpHeatmap.UnlockBits(bmpData); BmpScale.UnlockBits(scaleBmpData); } private double Normalize(double input, double? min = null, double? max = null, double? scaleMin = null, double? scaleMax = null) => Normalize(new double[] { input }, min, max, scaleMin, scaleMax)[0]; private double[] Normalize(double[] input, double? min = null, double? max = null, double? scaleMin = null, double? scaleMax = null) { min = min ?? input.Min(); max = max ?? input.Max(); min = (scaleMin.HasValue && scaleMin.Value < min) ? scaleMin.Value : min; max = (scaleMax.HasValue && scaleMax.Value > max) ? scaleMax.Value : max; double[] normalized = input.AsParallel().AsOrdered().Select(i => (i - min.Value) / (max.Value - min.Value)).ToArray(); if (scaleMin.HasValue) { double threshold = (scaleMin.Value - min.Value) / (max.Value - min.Value); normalized = normalized.AsParallel().AsOrdered().Select(i => i < threshold ? threshold : i).ToArray(); } if (scaleMax.HasValue) { double threshold = (scaleMax.Value - min.Value) / (max.Value - min.Value); normalized = normalized.AsParallel().AsOrdered().Select(i => i > threshold ? threshold : i).ToArray(); } return normalized; } public override LegendItem[] GetLegendItems() { var singleLegendItem = new LegendItem(label, Color.Gray, lineWidth: 10, markerShape: MarkerShape.none); return new LegendItem[] { singleLegendItem }; } public override AxisLimits2D GetLimits() => ShowAxisLabels ? new AxisLimits2D(-10, BmpHeatmap.Width, -5, BmpHeatmap.Height) : new AxisLimits2D(-3, BmpHeatmap.Width, -3, BmpHeatmap.Height); public override int GetPointCount() => NormalizedIntensities.Length; public string ValidationErrorMessage { get; private set; } public bool IsValidData(bool deepValidation = false) { if (NormalizedIntensities is null || BmpHeatmap is null) { ValidationErrorMessage = "Call UpdateData() to process data"; return false; } ValidationErrorMessage = ""; return true; } public override void Render(Settings settings) => throw new NotImplementedException("use new Render method"); public void Render(PlotDimensions dims, Bitmap bmp, bool lowQuality = false) { RenderHeatmap(dims, bmp, lowQuality); RenderScale(dims, bmp, lowQuality); if (ShowAxisLabels) RenderAxis(dims, bmp, lowQuality); } private void RenderHeatmap(PlotDimensions dims, Bitmap bmp, bool lowQuality) { using (Graphics gfx = GDI.Graphics(bmp, lowQuality)) { gfx.InterpolationMode = InterpolationMode.NearestNeighbor; double minScale = Math.Min(dims.PxPerUnitX, dims.PxPerUnitY); if (BackgroundImage != null && !DisplayImageAbove) gfx.DrawImage( BackgroundImage, dims.GetPixelX(0), dims.GetPixelY(0) - (float)(height * minScale), (float)(width * minScale), (float)(height * minScale)); gfx.DrawImage( BmpHeatmap, dims.GetPixelX(0), dims.GetPixelY(0) - (float)(height * minScale), (float)(width * minScale), (float)(height * minScale)); if (BackgroundImage != null && DisplayImageAbove) gfx.DrawImage(BackgroundImage, dims.GetPixelX(0), dims.GetPixelY(0) - (float)(height * minScale), (float)(width * minScale), (float)(height * minScale)); } } private void RenderScale(PlotDimensions dims, Bitmap bmp, bool lowQuality = false) { using (Graphics gfx = GDI.Graphics(bmp, lowQuality)) using (var pen = GDI.Pen(Color.Black)) using (var brush = GDI.Brush(Color.Black)) using (Font font = GDI.Font(null, 12)) using (var sf2 = new StringFormat() { LineAlignment = StringAlignment.Far }) { gfx.InterpolationMode = InterpolationMode.NearestNeighbor; float pxFromBottom = 30; float pxFromRight = dims.Width - 150; float pxWidth = 30; RectangleF scaleRect = new RectangleF(pxFromRight, pxFromBottom, pxWidth, dims.DataHeight); gfx.DrawImage(BmpScale, scaleRect); gfx.DrawRectangle(pen, pxFromRight, pxFromBottom, pxWidth / 2, dims.DataHeight); string maxString = ScaleMax.HasValue ? $"{(ScaleMax.Value < max ? "≥ " : "")}{ ScaleMax.Value:f3}" : $"{max:f3}"; string minString = ScaleMin.HasValue ? $"{(ScaleMin.Value > min ? "≤ " : "")}{ScaleMin.Value:f3}" : $"{min:f3}"; gfx.DrawString(maxString, font, brush, new PointF(scaleRect.X + 30, scaleRect.Top)); gfx.DrawString(minString, font, brush, new PointF(scaleRect.X + 30, scaleRect.Bottom), sf2); } } private void RenderAxis(PlotDimensions dims, Bitmap bmp, bool lowQuality) { using (Graphics gfx = GDI.Graphics(bmp, lowQuality)) using (Pen pen = GDI.Pen(Color.Black)) using (Brush brush = GDI.Brush(Color.Black)) using (Font axisFont = GDI.Font(null, 12)) using (StringFormat right_centre = new StringFormat() { Alignment = StringAlignment.Far, LineAlignment = StringAlignment.Center }) using (StringFormat centre_top = new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Near }) { double offset = -2; double minScale = Math.Min(dims.PxPerUnitX, dims.PxPerUnitY); gfx.DrawString($"{AxisOffsets[0]:f3}", axisFont, brush, dims.GetPixelX(0), dims.GetPixelY(offset), centre_top); gfx.DrawString($"{AxisOffsets[0] + AxisMultipliers[0]:f3}", axisFont, brush, new PointF((float)((width * minScale) + dims.GetPixelX(0)), dims.GetPixelY(offset)), centre_top); gfx.DrawString($"{AxisOffsets[1]:f3}", axisFont, brush, dims.GetPixelX(offset), dims.GetPixelY(0), right_centre); gfx.DrawString($"{AxisOffsets[1] + AxisMultipliers[1]:f3}", axisFont, brush, new PointF(dims.GetPixelX(offset), dims.GetPixelY(0) - (float)(height * minScale)), right_centre); } } public override string ToString() { string label = string.IsNullOrWhiteSpace(this.label) ? "" : $" ({this.label})"; return $"PlottableHeatmap{label} with {GetPointCount()} points"; } } }
46.794521
191
0.601093
[ "MIT" ]
54dg007/ScottPlot
src/ScottPlot/plottables/PlottableHeatmap.cs
10,254
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.Linq; using Microsoft.CodeAnalysis.Tags; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion { internal static class CommonCompletionItem { public static CompletionItem Create( string displayText, CompletionItemRules rules, Glyph? glyph = null, ImmutableArray<SymbolDisplayPart> description = default, string sortText = null, string filterText = null, bool showsWarningIcon = false, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default) { tags = tags.NullToEmpty(); if (glyph != null) { // put glyph tags first tags = GlyphTags.GetTags(glyph.Value).AddRange(tags); } if (showsWarningIcon) { tags = tags.Add(WellKnownTags.Warning); } properties = properties ?? ImmutableDictionary<string, string>.Empty; if (!description.IsDefault && description.Length > 0) { properties = properties.Add("Description", EncodeDescription(description)); } return CompletionItem.Create( displayText: displayText, filterText: filterText, sortText: sortText, properties: properties, tags: tags, rules: rules); } public static bool HasDescription(CompletionItem item) { return item.Properties.ContainsKey("Description"); } public static CompletionDescription GetDescription(CompletionItem item) { if (item.Properties.TryGetValue("Description", out var encodedDescription)) { return DecodeDescription(encodedDescription); } else { return CompletionDescription.Empty; } } private static char[] s_descriptionSeparators = new char[] { '|' }; private static string EncodeDescription(ImmutableArray<SymbolDisplayPart> description) { return EncodeDescription(description.ToTaggedText()); } private static string EncodeDescription(ImmutableArray<TaggedText> description) { if (description.Length > 0) { return string.Join("|", description .SelectMany(d => new string[] { d.Tag, d.Text }) .Select(t => t.Escape('\\', s_descriptionSeparators))); } else { return null; } } private static CompletionDescription DecodeDescription(string encoded) { var parts = encoded.Split(s_descriptionSeparators).Select(t => t.Unescape('\\')).ToArray(); var builder = ImmutableArray<TaggedText>.Empty.ToBuilder(); for (int i = 0; i < parts.Length; i += 2) { builder.Add(new TaggedText(parts[i], parts[i + 1])); } return CompletionDescription.Create(builder.ToImmutable()); } } }
33.423077
161
0.558688
[ "Apache-2.0" ]
Iscgx/roslyn
src/Features/Core/Portable/Completion/CommonCompletionItem.cs
3,478
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 machinelearning-2014-12-12.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.MachineLearning.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.MachineLearning.Model.Internal.MarshallTransformations { /// <summary> /// DeleteTags Request Marshaller /// </summary> public class DeleteTagsRequestMarshaller : IMarshaller<IRequest, DeleteTagsRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DeleteTagsRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DeleteTagsRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.MachineLearning"); string target = "AmazonML_20141212.DeleteTags"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2014-12-12"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetResourceId()) { context.Writer.WritePropertyName("ResourceId"); context.Writer.Write(publicRequest.ResourceId); } if(publicRequest.IsSetResourceType()) { context.Writer.WritePropertyName("ResourceType"); context.Writer.Write(publicRequest.ResourceType); } if(publicRequest.IsSetTagKeys()) { context.Writer.WritePropertyName("TagKeys"); context.Writer.WriteArrayStart(); foreach(var publicRequestTagKeysListValue in publicRequest.TagKeys) { context.Writer.Write(publicRequestTagKeysListValue); } context.Writer.WriteArrayEnd(); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static DeleteTagsRequestMarshaller _instance = new DeleteTagsRequestMarshaller(); internal static DeleteTagsRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DeleteTagsRequestMarshaller Instance { get { return _instance; } } } }
35.860656
135
0.605714
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/MachineLearning/Generated/Model/Internal/MarshallTransformations/DeleteTagsRequestMarshaller.cs
4,375
C#
using BattleshipGame.UI; using UnityEditor; using UnityEngine; namespace BattleshipGame.Editor { [CustomEditor(typeof(GridNumbersBuilder))] public class GridNumbersBuilderEditor : UnityEditor.Editor { public override void OnInspectorGUI() { DrawDefaultInspector(); var indexPrinter = (GridNumbersBuilder) target; if (GUILayout.Button("Print")) indexPrinter.Print(); if (GUILayout.Button("Undo")) indexPrinter.Undo(); } } }
28.444444
64
0.658203
[ "MIT" ]
MusapKahraman/Battleship
Battleship-Client/Assets/Scripts/Editor/GridNumbersBuilderEditor.cs
514
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("Grades")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Grades")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("fbcee393-9780-4c70-ab1f-7896bcf91ba3")] // 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")]
37.25
84
0.741984
[ "MIT" ]
pirocorp/Programming-Basics
ProgrammingBasicsExamPreparation/Grades/Properties/AssemblyInfo.cs
1,344
C#