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 S7evemetry.Core;
using S7evemetry.Core.Packets.F1;
using S7evemetry.F1_2018.Structures;
using S7evemetry.F1_2018.Packets;
using System;
namespace S7evemetry.F1_2018.Observers
{
public abstract class CarTelemetryDataObserver : IObserver<PacketData<PacketHeader, CarTelemetryData, CarTelemetry>>
{
private IDisposable? _unsubscriber;
public void Subscribe(IObservable<PacketData<PacketHeader, CarTelemetryData, CarTelemetry>> listener)
{
_unsubscriber = listener.Subscribe(this);
}
public void Unsubscribe()
{
if (_unsubscriber != null)
{
_unsubscriber.Dispose();
_unsubscriber = null;
}
}
public abstract void OnCompleted();
public abstract void OnError(DataException error);
public abstract void OnError(Exception error);
public abstract void OnNext(PacketData<PacketHeader, CarTelemetryData, CarTelemetry> value);
}
}
| 25.027778 | 120 | 0.750277 | [
"MIT"
] | LuckyNoS7evin/s7evemetry | src/S7evemetry.F1_2018/Observers/CarTelemetryDataObserver.cs | 903 | C# |
using System;
using Pulumi;
namespace Logicality.Pulumi.Aws.Ec2
{
public class StandardVpcArgs
{
[Input("cidrBlockSegment")]
public int CidrBlockSegment { get; set; }
}
} | 18.181818 | 49 | 0.655 | [
"MIT"
] | logicality-io/dotnet-libs | libs/pulumi/src/Pulumi.Aws/Ec2/StandardVpcArgs.cs | 202 | C# |
namespace Owin.Scim.Tests.Querying.Filtering.Normalization
{
using Machine.Specifications;
using Scim.Querying;
public class with_terminal_attribute_no_filter : when_normalizing_a_path_filter
{
Establish context = () => PathFilter = "displayName";
It show_throw_exception = () => ScimFilter.Paths.ShouldContainOnly(
new PathFilterExpression("displayName", null));
It should_equal = () => ScimFilter.NormalizedFilterExpression.ShouldEqual("displayName");
}
} | 32.375 | 97 | 0.714286 | [
"MIT"
] | Mysonemo/Owin.Scim | source/_tests/Owin.Scim.Tests/Querying/Filtering/Normalization/with_terminal_attribute_no_filter.cs | 520 | C# |
namespace AkkaEventStore.Models
{
public class Address
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Country { get; set; }
public string City { get; set; }
}
} | 25.8 | 46 | 0.569767 | [
"MIT"
] | vladkosarev/Akka.net-EventSourcePersistence | src/AkkaEventStore/Models/Address.cs | 260 | C# |
using UnityEngine;
using UnInventory.Core.MVC.Model.Data;
namespace UnInventory.Core.MVC.View.Components.Entity
{
[RequireComponent(typeof(IEntityRootComponent))]
public abstract class EntityViewComponent : ViewComponent<DataEntity, IEntityRootComponent>
{
}
} | 27.8 | 95 | 0.784173 | [
"MIT"
] | GoodCatGames/UnInventory | Runtime/Core/MVC/View/Components/Entity/EntityViewComponent.cs | 280 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using CsvHelper;
using FluentValidation;
using FluentValidation.Results;
using Microsoft.Extensions.Logging;
using Sfa.Tl.Matching.Application.Interfaces;
using Sfa.Tl.Matching.Data.Interfaces;
using Sfa.Tl.Matching.Domain.Models;
using Sfa.Tl.Matching.Models.Dto;
namespace Sfa.Tl.Matching.Application.FileReader
{
public class CsvFileReader<TImportDto, TDto> : IFileReader<TImportDto, TDto> where TDto : class, new() where TImportDto : FileImportDto
{
private readonly ILogger<CsvFileReader<TImportDto, TDto>> _logger;
private readonly IDataParser<TDto> _dataParser;
private readonly IValidator<TImportDto> _validator;
private readonly IRepository<FunctionLog> _functionLogRepository;
public CsvFileReader(
ILogger<CsvFileReader<TImportDto, TDto>> logger,
IDataParser<TDto> dataParser,
IValidator<TImportDto> validator,
IRepository<FunctionLog> functionLogRepository)
{
_logger = logger;
_dataParser = dataParser;
_validator = validator;
_functionLogRepository = functionLogRepository;
}
public async Task<IList<TDto>> ValidateAndParseFileAsync(TImportDto fileImportDto)
{
var dtos = new List<TDto>();
var columnInfos = fileImportDto.GetType().GetProperties()
.Where(pr => pr.GetCustomAttribute<ColumnAttribute>(false) != null)
.Select(prop => new { ColumnInfo = prop, Index = prop.GetCustomAttribute<ColumnAttribute>(false).Order })
.ToList();
using var streamReader = new StreamReader(fileImportDto.FileDataStream);
using var reader = new CsvReader(streamReader, CultureInfo.CurrentCulture);
//Manually skip header rows
reader.Configuration.HasHeaderRecord = false;
if (fileImportDto.NumberOfHeaderRows.HasValue)
{
for (var i = 0; i < fileImportDto.NumberOfHeaderRows; i++)
{
await reader.ReadAsync();
}
}
var validationErrors = new List<FunctionLog>();
var startIndex = fileImportDto.NumberOfHeaderRows ?? 0;
while (await reader.ReadAsync())
{
var columnValues = reader.Context.Record;
ValidationResult validationResult;
foreach (var column in columnInfos)
{
//if column index is greater then csv column length then either csv is in invalid format or TImportDto has invalid config
//this will result in null values or column shifted data which should fail data validation
if (column.Index > columnValues.Length) continue;
var cellValue = columnValues[column.Index];
column.ColumnInfo.SetValue(fileImportDto, cellValue.Trim());
}
try
{
validationResult = await _validator.ValidateAsync(fileImportDto);
}
catch (Exception exception)
{
validationResult = new ValidationResult { Errors = { new ValidationFailure(typeof(TDto).Name, exception.ToString()) } };
}
if (!validationResult.IsValid)
{
LogErrorsAndWarnings(startIndex, validationResult, validationErrors);
startIndex++;
continue;
}
var dto = _dataParser.Parse(fileImportDto);
dtos.AddRange(dto);
startIndex++;
}
await _functionLogRepository.CreateManyAsync(validationErrors);
return dtos;
}
private void LogErrorsAndWarnings(int rowIndex, ValidationResult validationResult, List<FunctionLog> validationErrors)
{
validationErrors.AddRange(validationResult.Errors.Select(errorMessage => new FunctionLog
{
FunctionName = GetType().GetGenericArguments().ElementAt(0).Name.Replace("FileImportDto", string.Empty),
RowNumber = rowIndex,
ErrorMessage = errorMessage.ToString()
}).ToList());
_logger.LogError($"Row Number={rowIndex} failed with the following errors: \n\t{string.Join("\n\t", validationResult.Errors)}");
}
}
}
| 38.268293 | 141 | 0.615041 | [
"MIT"
] | uk-gov-mirror/SkillsFundingAgency.tl-matching | src/Sfa.Tl.Matching.Application/FileReader/CsvFileReader.cs | 4,709 | 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.Runtime.CompilerServices;
using Microsoft.ML;
[assembly: InternalsVisibleTo(assemblyName: "Microsoft.ML.Ensemble" + PublicKey.Value)]
[assembly: InternalsVisibleTo(assemblyName: "Microsoft.ML.StaticPipe" + PublicKey.Value)]
[assembly: InternalsVisibleTo(assemblyName: "RunTests" + InternalPublicKey.Value)]
[assembly: InternalsVisibleTo(assemblyName: "RunTestsMore" + InternalPublicKey.Value)]
[assembly: InternalsVisibleTo(assemblyName: "Microsoft.ML.Internal.MetaLinearLearner" + InternalPublicKey.Value)]
[assembly: InternalsVisibleTo(assemblyName: "ParameterMixer" + InternalPublicKey.Value)]
[assembly: InternalsVisibleTo(assemblyName: "Microsoft.ML.Runtime.Sar" + InternalPublicKey.Value)]
| 57.1875 | 113 | 0.809836 | [
"MIT"
] | cluesblues/machinelearning | src/Microsoft.ML.StandardLearners/Properties/AssemblyInfo.cs | 915 | C# |
using System;
namespace ExactOnline.Client.Models.Manufacturing
{
[SupportedActionsSDK(true, true, true, true)]
[DataServiceKey("ID")]
public class ProductionArea
{
/// <summary>Code of the production area group</summary>
public string Code { get; set; }
/// <summary>Reference to Cost center</summary>
public string Costcenter { get; set; }
/// <summary>Description of Costcenter</summary>
[SDKFieldType(FieldType.ReadOnly)]
public string CostcenterDescription { get; set; }
/// <summary>Reference to Cost unit</summary>
public string Costunit { get; set; }
/// <summary>Description of Costunit</summary>
[SDKFieldType(FieldType.ReadOnly)]
public string CostunitDescription { get; set; }
/// <summary>Creation date</summary>
[SDKFieldType(FieldType.ReadOnly)]
public DateTime? Created { get; set; }
/// <summary>User ID of creator</summary>
[SDKFieldType(FieldType.ReadOnly)]
public Guid? Creator { get; set; }
/// <summary>Name of creator</summary>
[SDKFieldType(FieldType.ReadOnly)]
public string CreatorFullName { get; set; }
/// <summary>Description of the production area</summary>
public string Description { get; set; }
/// <summary>Division code</summary>
[SDKFieldType(FieldType.ReadOnly)]
public int? Division { get; set; }
/// <summary>Primary key</summary>
public Guid ID { get; set; }
/// <summary>Indicates if this is the default production area. This will be used when creating a new production area</summary>
public byte IsDefault { get; set; }
/// <summary>Last modified date</summary>
[SDKFieldType(FieldType.ReadOnly)]
public DateTime? Modified { get; set; }
/// <summary>User ID of modifier</summary>
[SDKFieldType(FieldType.ReadOnly)]
public Guid? Modifier { get; set; }
/// <summary>Name of modifier</summary>
[SDKFieldType(FieldType.ReadOnly)]
public string ModifierFullName { get; set; }
/// <summary>Production area notes</summary>
public string Notes { get; set; }
}
}
| 43.173077 | 134 | 0.628062 | [
"MIT"
] | SEVENP/exactonline-api-dotnet-client | src/ExactOnline.Client.Models/Manufacturing/ProductionArea.cs | 2,245 | C# |
using WarHub.ArmouryModel.Source;
namespace WarHub.ArmouryModel.Concrete;
internal class SelectionEntryLinkSymbol : SelectionEntryBaseSymbol, INodeDeclaredSymbol<EntryLinkNode>
{
private ISelectionEntryContainerSymbol? lazyReference;
public SelectionEntryLinkSymbol(
ISymbol containingSymbol,
EntryLinkNode declaration,
DiagnosticBag diagnostics)
: base(containingSymbol, declaration, diagnostics)
{
Declaration = declaration;
ContainerKind = Declaration.Type switch
{
EntryLinkKind.SelectionEntry => ContainerEntryKind.Selection,
EntryLinkKind.SelectionEntryGroup => ContainerEntryKind.SelectionGroup,
_ => ContainerEntryKind.Error,
};
if (ContainerKind is ContainerEntryKind.Error)
{
diagnostics.Add(ErrorCode.ERR_UnknownEnumerationValue, Declaration);
}
}
public override EntryLinkNode Declaration { get; }
public override ContainerEntryKind ContainerKind { get; }
public override ISelectionEntryContainerSymbol ReferencedEntry => GetBoundField(ref lazyReference);
protected override void BindReferencesCore(Binder binder, DiagnosticBag diagnosticBag)
{
base.BindReferencesCore(binder, diagnosticBag);
lazyReference = binder.BindSharedSelectionEntrySymbol(Declaration, diagnosticBag);
}
}
| 33.95122 | 103 | 0.730603 | [
"MIT"
] | CloverFox/phalanx | src/WarHub.ArmouryModel.Concrete.Extensions/SelectionEntryLinkSymbol.cs | 1,392 | C# |
//------------------------------------------------------------------------------
// <自動產生的>
// 這段程式碼是由工具產生的。
//
// 變更這個檔案可能會導致不正確的行為,而且如果已重新產生
// 程式碼,則會遺失變更。
// </自動產生的>
//------------------------------------------------------------------------------
namespace HelpDesk.Web
{
public partial class Login
{
/// <summary>
/// account 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlInputText account;
/// <summary>
/// password 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlInputPassword password;
/// <summary>
/// LinkButtonSubmit 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton LinkButtonSubmit;
}
}
| 24.866667 | 81 | 0.453083 | [
"MIT"
] | gamegeartw/HelpDesk | HelpDesk.Web/Login.aspx.designer.cs | 1,483 | C# |
using UnityEngine;
namespace Jagapippi.UnityAsReadOnly
{
public interface IReadOnlyTerrainLayer
{
Vector4 diffuseRemapMax { get; }
Vector4 diffuseRemapMin { get; }
IReadOnlyTexture2D diffuseTexture { get; }
Vector4 maskMapRemapMax { get; }
Vector4 maskMapRemapMin { get; }
IReadOnlyTexture2D maskMapTexture { get; }
float metallic { get; }
IReadOnlyTexture2D normalMapTexture { get; }
float normalScale { get; }
float smoothness { get; }
Color specular { get; }
Vector2 tileOffset { get; }
Vector2 tileSize { get; }
}
public sealed class ReadOnlyTerrainLayer : ReadOnlyObject<TerrainLayer>, IReadOnlyTerrainLayer
{
public ReadOnlyTerrainLayer(TerrainLayer obj) : base(obj)
{
}
#region Properties
public Vector4 diffuseRemapMax => _obj.diffuseRemapMax;
public Vector4 diffuseRemapMin => _obj.diffuseRemapMin;
public ReadOnlyTexture2D diffuseTexture => _obj.diffuseTexture.AsReadOnly();
IReadOnlyTexture2D IReadOnlyTerrainLayer.diffuseTexture => this.diffuseTexture;
public Vector4 maskMapRemapMax => _obj.maskMapRemapMax;
public Vector4 maskMapRemapMin => _obj.maskMapRemapMin;
public ReadOnlyTexture2D maskMapTexture => _obj.maskMapTexture.AsReadOnly();
IReadOnlyTexture2D IReadOnlyTerrainLayer.maskMapTexture => this.maskMapTexture;
public float metallic => _obj.metallic;
public ReadOnlyTexture2D normalMapTexture => _obj.normalMapTexture.AsReadOnly();
IReadOnlyTexture2D IReadOnlyTerrainLayer.normalMapTexture => this.normalMapTexture;
public float normalScale => _obj.normalScale;
public float smoothness => _obj.smoothness;
public Color specular => _obj.specular;
public Vector2 tileOffset => _obj.tileOffset;
public Vector2 tileSize => _obj.tileSize;
#endregion
#region Public Methods
#endregion
}
public static class TerrainLayerExtensions
{
public static ReadOnlyTerrainLayer AsReadOnly(this TerrainLayer self) => self.IsTrulyNull() ? null : new ReadOnlyTerrainLayer(self);
}
} | 38.37931 | 140 | 0.691375 | [
"MIT"
] | su10/Unity-AsReadOnly | Assets/Jagapippi/UnityAsReadOnly/UnityEngine/ReadOnlyTerrainLayer.cs | 2,228 | C# |
using OkraConventionSample.Common;
using Okra.Navigation;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237
namespace OkraConventionSample.Pages
{
/// <summary>
/// A basic page that provides characteristics common to most applications.
/// </summary>
public sealed partial class FooPage : Page
{
public FooPage()
{
this.InitializeComponent();
}
}
}
| 26.575758 | 94 | 0.741163 | [
"Apache-2.0"
] | OkraFramework/Okra-Samples | OkraConventionSample/Pages/FooPage.xaml.cs | 879 | C# |
namespace UpcastingAndDowncasting.Entities
{
class BusinessAccount : Account
/* ": Account" Informa que a classe atual herdará o comportamento dess classe
** indicada. Nesse caso "Account" é a super-classe e "BusinessAccount" é a sub-classe.
*/
{
//Attributes
public double LoanLimit { get; set; }
//Constructors
public BusinessAccount()
{
}
//O uso do "base", possibilita chamar construtores da superclasse.
public BusinessAccount(int number, string holder, double balance, double LoanLimit) : base(number, holder, balance)
{
LoanLimit = LoanLimit;
}
//Methods
public void Loan(double amount)
{
if (amount <= LoanLimit)
{
Balance += amount;
}
}
}
}
| 25.205882 | 123 | 0.568261 | [
"MIT"
] | josejuarezjunior/CursoCSharp | UpcastingAndDowncasting/Entities/BusinessAccount.cs | 862 | C# |
/*
* LambdaSharp (λ#)
* Copyright (C) 2018-2021
* lambdasharp.net
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Amazon.DynamoDBv2.Model;
using LambdaSharp.DynamoDB.Serialization.Converters;
namespace LambdaSharp.DynamoDB.Serialization {
/// <summary>
/// The <see cref="DynamoSerializer"/> static class provides methods for (de)serializing values to/from DynamoDB attribute values.
/// The following list shows the default type mapping for DynamoDB attribute values:
/// <list type="bullet">
/// <item>
/// <term>Number</term>
/// <description>int, int?, long, long?, double, double?, decimal, decimal?, DateTimeOffset, DateTimeOffset?</description>
/// </item>
/// <item>
/// <term>String</term>
/// <description>string, enum</description>
/// </item>
/// <item>
/// <term>Binary</term>
/// <description>byte[]</description>
/// </item>
/// <item>
/// <term>Boolean</term>
/// <description>bool, bool?</description>
/// </item>
/// <item>
/// <term>Null</term>
/// <description>any nullable type</description>
/// </item>
/// <item>
/// <term>List</term>
/// <description>List<T></description>
/// </item>
/// <item>
/// <term>Map</term>
/// <description>Dictionary<string, object>, Dictionary<string, T>, T</description>
/// </item>
/// <item>
/// <term>String Set</term>
/// <description>ISet<string></description>
/// </item>
/// <item>
/// <term>Number Set</term>
/// <description>ISet<int>, ISet<long>, ISet<double>, ISet<decimal></description>
/// </item>
/// <item>
/// <term>Binary Set</term>
/// <description>ISet<byte[]></description>
/// </item>
/// </list>
/// </summary>
/// <seealso href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes">DynamoDB Data Types</seealso>
public static class DynamoSerializer {
//--- Class Methods ---
/// <summary>
/// The <see cref="Serialize(object?)"/> method serializes an object to a DynamoDB attribute value using the default <see cref="DynamoSerializerOptions"/> instance.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <returns>A DynamoDB attribute value or <c>null</c> when the object state cannot be represented in DynamoDB.</returns>
public static AttributeValue? Serialize(object? value)
=> Serialize(value, new DynamoSerializerOptions());
/// <summary>
/// The <see cref="Serialize(object?,DynamoSerializerOptions)"/> method serializes an object to a DynamoDB attribute value.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="options">The serialization options to use.</param>
/// <returns>A DynamoDB attribute value or <c>null</c> when the object state cannot be represented in DynamoDB.</returns>
public static AttributeValue? Serialize(object? value, DynamoSerializerOptions options) {
// check for types mapped to attribute type 'NULL'
if(value is null) {
return new AttributeValue {
NULL = true
};
}
// find a suiteable converter for the provided type
var typeToConvert = value.GetType();
var converter = options.GetConverters().FirstOrDefault(converter => converter.CanConvert(typeToConvert));
if(converter is null) {
throw new DynamoSerializationException($"cannot convert value of type '{typeToConvert?.FullName ?? "<null>"}'");
}
return converter.ToAttributeValue(value, typeToConvert, options);
}
/// <summary>
/// The <see cref="Deserialize(Dictionary{string, AttributeValue})"/> method deserializes a DynamoDB document into a <typeparamref name="TRecord"/> instance using the default <see cref="DynamoSerializerOptions"/> instance.
/// </summary>
/// <param name="document">The DynamoDB document to deserialize.</param>
/// <typeparam name="TRecord">The type to deserialize into.</typeparam>
/// <returns>An instance of <typeparamref name="TRecord"/> or <c>null</c> when the DynamoDB document is <c>null</c>.</returns>
public static TRecord? Deserialize<TRecord>(Dictionary<string, AttributeValue> document)
where TRecord : class
=> Deserialize<TRecord>(document, new DynamoSerializerOptions());
/// <summary>
/// The <see cref="Deserialize(Dictionary{string, AttributeValue},DynamoSerializerOptions)"/> method deserializes a DynamoDB document into a <typeparamref name="TRecord"/> instance.
/// </summary>
/// <param name="document">The DynamoDB document to deserialize.</param>
/// <param name="options">The deserialization options to use.</param>
/// <typeparam name="TRecord">The type to deserialize into.</typeparam>
/// <returns>An instance of <typeparamref name="TRecord"/> or <c>null</c> when the DynamoDB document is <c>null</c>.</returns>
public static TRecord? Deserialize<TRecord>(Dictionary<string, AttributeValue> document, DynamoSerializerOptions options)
where TRecord : class
=> (TRecord?)Deserialize(document, typeof(TRecord), options);
/// <summary>
/// The <see cref="Deserialize(Dictionary{string, AttributeValue},Type)"/> method deserializes a DynamoDB document into a <paramref name="targetType"/> instance using the default <see cref="DynamoSerializerOptions"/> instance.
/// </summary>
/// <param name="document">The DynamoDB document to deserialize.</param>
/// <param name="targetType">The type to deserialize into.</param>
/// <returns>An instance of <paramref name="targetType"/> or <c>null</c> when the DynamoDB document is <c>null</c>.</returns>
public static object? Deserialize(Dictionary<string, AttributeValue> document, Type? targetType)
=> Deserialize(document, targetType, new DynamoSerializerOptions());
/// <summary>
/// The <see cref="Deserialize(Dictionary{string, AttributeValue},Type,DynamoSerializerOptions)"/> method deserializes a DynamoDB document into a <paramref name="targetType"/> instance.
/// </summary>
/// <param name="document">The DynamoDB document to deserialize.</param>
/// <param name="targetType">The type to deserialize into.</param>
/// <param name="options">The deserialization options to use.</param>
/// <returns>An instance of <paramref name="targetType"/> or <c>null</c> when the DynamoDB document is <c>null</c>.</returns>
public static object? Deserialize(Dictionary<string, AttributeValue> document, Type? targetType, DynamoSerializerOptions options) {
var usedTargetType = ((targetType is null) || (targetType == typeof(object)))
? typeof(Dictionary<string, object>)
: targetType;
var converter = options.GetConverters().FirstOrDefault(converter => converter.CanConvert(usedTargetType));
if(converter == null) {
throw new DynamoSerializationException($"cannot convert document {nameof(AttributeValue.M)} (given: {targetType?.FullName ?? "<null>"})");
}
return converter.FromMap(document, usedTargetType, options);
}
/// <summary>
/// The <see cref="Deserialize(AttributeValue,Type)"/> method deserializes a DynamoDB attribute value into a <paramref name="targetType"/> instance using the default <see cref="DynamoSerializerOptions"/> instance.
/// </summary>
/// <param name="attribute">The DynamoDB attribute value to deserialize.</param>
/// <param name="targetType">The type to deserialize into.</param>
/// <returns>An instance of <paramref name="targetType"/> or <c>null</c> when the DynamoDB attribute value is <c>NULL</c>.</returns>
public static object? Deserialize(AttributeValue? attribute, Type? targetType)
=> Deserialize(attribute, targetType, new DynamoSerializerOptions());
/// <summary>
/// The <see cref="Deserialize(AttributeValue,Type,DynamoSerializerOptions)"/> method deserializes a DynamoDB attribute value into a <paramref name="targetType"/> instance.
/// </summary>
/// <param name="attribute">The DynamoDB attribute value to deserialize.</param>
/// <param name="targetType">The type to deserialize into.</param>
/// <param name="options">The deserialization options to use.</param>
/// <returns>An instance of <paramref name="targetType"/> or <c>null</c> when the DynamoDB attribute value is <c>NULL</c>.</returns>
public static object? Deserialize(AttributeValue? attribute, Type? targetType, DynamoSerializerOptions options) {
// handle missing value
if(attribute == null) {
return FindConverter(typeof(object), "<default>", (converter, usedTargetType) => converter.GetDefaultValue(usedTargetType, options));
}
// handle boolean value
if(attribute.IsBOOLSet) {
return FindConverter(typeof(bool), nameof(AttributeValue.BOOL), (converter, usedTargetType) => converter.FromBool(attribute.BOOL, usedTargetType, options));
}
// handle string value
if(!(attribute.S is null)) {
return FindConverter(typeof(string), nameof(AttributeValue.S), (converter, usedTargetType) => converter.FromString(attribute.S, usedTargetType, options));
}
// handle number value
if(!(attribute.N is null)) {
return FindConverter(typeof(double), nameof(AttributeValue.N), (converter, usedTargetType) => converter.FromNumber(attribute.N, usedTargetType, options));
}
// handle binary value
if(!(attribute.B is null)) {
return FindConverter(typeof(byte[]), nameof(AttributeValue.B), (converter, usedTargetType) => converter.FromBinary(attribute.B, usedTargetType, options));
}
// handle list value
if(attribute.IsLSet) {
return FindConverter(typeof(List<object>), nameof(AttributeValue.L), (converter, usedTargetType) => converter.FromList(attribute.L, usedTargetType, options));
}
// handle map value
if(attribute.IsMSet) {
return Deserialize(attribute.M, targetType, options);
}
// handle binary set value
if(attribute.BS.Any()) {
return FindConverter(typeof(HashSet<byte[]>), nameof(AttributeValue.BS), (converter, usedTargetType) => converter.FromBinarySet(attribute.BS, usedTargetType, options));
}
// handle string set value
if(attribute.SS.Any()) {
return FindConverter(typeof(HashSet<string>), nameof(AttributeValue.SS), (converter, usedTargetType) => converter.FromStringSet(attribute.SS, usedTargetType, options));
}
// handle number set value
if(attribute.NS.Any()) {
return FindConverter(typeof(HashSet<double>), nameof(AttributeValue.NS), (converter, usedTargetType) => converter.FromNumberSet(attribute.NS, usedTargetType, options));
}
// handle null value
if(attribute.NULL) {
return FindConverter(typeof(object), nameof(AttributeValue.NULL), (converter, usedTargetType) => converter.FromNull(usedTargetType, options));
}
throw new DynamoSerializationException($"invalid attribute value");
// local functions
object? FindConverter(Type defaultType, string attributeValueTypeName, Func<IDynamoAttributeConverter, Type, object?> convert) {
var usedTargetType = ((targetType is null) || (targetType == typeof(object)))
? defaultType
: targetType;
var converter = options.GetConverters().FirstOrDefault(converter => converter.CanConvert(usedTargetType));
if(converter == null) {
throw new DynamoSerializationException($"cannot convert attribute value {attributeValueTypeName} (given: {targetType?.FullName ?? "<null>"})");
}
return convert(converter, usedTargetType);
}
}
private static Type GetListItemType(Type type) {
if(type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(IList<>))) {
return type.GenericTypeArguments[0];
}
return type.GetInterfaces()
.Where(i => i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(IList<>)))
.Select(i => i.GenericTypeArguments[0])
.FirstOrDefault();
}
private static Type GetDictionaryItemType(Type type) {
if(
type.IsGenericType
&& (type.GetGenericTypeDefinition() == typeof(IDictionary<,>))
&& (type.GenericTypeArguments[0] == typeof(string))
) {
return type.GenericTypeArguments[1];
}
return type.GetInterfaces()
.Where(i => i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(IDictionary<,>)) && (i.GenericTypeArguments[0] == typeof(string)))
.Select(i => i.GenericTypeArguments[1])
.FirstOrDefault();
}
}
}
| 54.074074 | 234 | 0.622466 | [
"Apache-2.0"
] | LambdaSharp/LambdaSharpTool | src/LambdaSharp.DynamoDB.Serialization/DynamoSerializer.cs | 14,601 | 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>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("Game with sfmlui")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("Game with sfmlui")]
[assembly: System.Reflection.AssemblyTitleAttribute("Game with sfmlui")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 42.541667 | 81 | 0.632713 | [
"MIT"
] | pentatrax/SfmlUI-Game | Game with sfmlui/obj/Debug/netcoreapp3.1/Game with sfmlui.AssemblyInfo.cs | 1,021 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using PSRule.Definitions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace PSRule.Configuration
{
public class BaselineOption
{
internal sealed class BaselineRef : BaselineOption
{
public readonly string Name;
public BaselineRef(string name)
{
Name = name;
}
}
internal sealed class BaselineInline : BaselineOption, IBaselineSpec
{
public BaselineInline()
{
Binding = new BindingOption();
Configuration = new ConfigurationOption();
Rule = new RuleOption();
}
public BindingOption Binding { get; set; }
public ConfigurationOption Configuration { get; set; }
public RuleOption Rule { get; set; }
}
public static implicit operator BaselineOption(Hashtable hashtable)
{
var option = new BaselineInline();
// Build index to allow mapping
var index = PSRuleOption.BuildIndex(hashtable);
Load(option, index);
return option;
}
public static implicit operator BaselineOption(string value)
{
return new BaselineRef(value);
}
/// <summary>
/// Load matching values
/// </summary>
/// <param name="option">A baseline options object to load.</param>
/// <param name="properties">One or more indexed properties.</param>
internal static void Load(IBaselineSpec option, Dictionary<string, object> properties)
{
if (properties.TryPopValue("binding.field", out object value) && value is Hashtable map)
option.Binding.Field = new FieldMap(map);
if (properties.TryPopValue("binding.ignorecase", out value))
option.Binding.IgnoreCase = bool.Parse(value.ToString());
if (properties.TryPopValue("binding.nameseparator", out value))
option.Binding.NameSeparator = value.ToString();
if (properties.TryPopValue("binding.targetname", out value))
{
if (value.GetType().IsArray)
option.Binding.TargetName = ((object[])value).OfType<string>().ToArray();
else
option.Binding.TargetName = new string[] { value.ToString() };
}
if (properties.TryPopValue("binding.targettype", out value))
{
if (value.GetType().IsArray)
option.Binding.TargetType = ((object[])value).OfType<string>().ToArray();
else
option.Binding.TargetType = new string[] { value.ToString() };
}
if (properties.TryPopValue("binding.usequalifiedname", out value))
option.Binding.UseQualifiedName = bool.Parse(value.ToString());
if (properties.TryPopValue("rule.include", out value))
{
if (value.GetType().IsArray)
option.Rule.Include = ((object[])value).OfType<string>().ToArray();
else
option.Rule.Include = new string[] { value.ToString() };
}
if (properties.TryPopValue("rule.exclude", out value))
{
if (value.GetType().IsArray)
option.Rule.Exclude = ((object[])value).OfType<string>().ToArray();
else
option.Rule.Exclude = new string[] { value.ToString() };
}
if (properties.TryPopValue("rule.tag" , out value) && value is Hashtable tag)
option.Rule.Tag = tag;
// Process configuration values
if (properties.Count > 0)
{
var keys = properties.Keys.ToArray();
for (var i = 0; i < keys.Length; i++)
{
if (keys[i].Length > 14 && keys[i].StartsWith("Configuration.", StringComparison.OrdinalIgnoreCase))
option.Configuration[keys[i].Substring(14)] = properties[keys[i]];
}
}
}
}
}
| 36.576271 | 120 | 0.544949 | [
"MIT"
] | Bhaskers-Blu-Org2/PSRule | src/PSRule/Configuration/BaselineOption.cs | 4,318 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TodoASMX.UWP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TodoASMX.UWP")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | 35.896552 | 84 | 0.739673 | [
"Apache-2.0"
] | 4qu3l3c4r4/xamarin-forms-samples | WebServices/TodoASMX/UWP/Properties/AssemblyInfo.cs | 1,044 | C# |
using Steeltoe.Management.Census.Trace.Sampler;
using System;
using System.Collections.Generic;
using System.Text;
namespace Steeltoe.Management.Census.Trace.Config
{
[Obsolete("Use OpenCensus project packages")]
public sealed class TraceParams : ITraceParams
{
private const double DEFAULT_PROBABILITY = 1e-4;
private static readonly ISampler DEFAULT_SAMPLER = Samplers.GetProbabilitySampler(DEFAULT_PROBABILITY);
private const int DEFAULT_SPAN_MAX_NUM_ATTRIBUTES = 32;
private const int DEFAULT_SPAN_MAX_NUM_ANNOTATIONS = 32;
private const int DEFAULT_SPAN_MAX_NUM_MESSAGE_EVENTS = 128;
private const int DEFAULT_SPAN_MAX_NUM_LINKS = 128;
public static readonly ITraceParams DEFAULT =
new TraceParams(DEFAULT_SAMPLER, DEFAULT_SPAN_MAX_NUM_ATTRIBUTES, DEFAULT_SPAN_MAX_NUM_ANNOTATIONS, DEFAULT_SPAN_MAX_NUM_MESSAGE_EVENTS, DEFAULT_SPAN_MAX_NUM_LINKS);
internal TraceParams(ISampler sampler, int maxNumberOfAttributes, int maxNumberOfAnnotations, int maxNumberOfMessageEvents, int maxNumberOfLinks)
{
if (sampler == null)
{
throw new ArgumentNullException(nameof(sampler));
}
if (maxNumberOfAttributes <= 0)
{
throw new ArgumentOutOfRangeException(nameof(maxNumberOfAttributes));
}
if (maxNumberOfAnnotations <= 0)
{
throw new ArgumentOutOfRangeException(nameof(maxNumberOfAnnotations));
}
if (maxNumberOfMessageEvents <= 0)
{
throw new ArgumentOutOfRangeException(nameof(maxNumberOfMessageEvents));
}
if (maxNumberOfLinks <= 0)
{
throw new ArgumentOutOfRangeException(nameof(maxNumberOfLinks));
}
this.Sampler = sampler;
this.MaxNumberOfAttributes = maxNumberOfAttributes;
this.MaxNumberOfAnnotations = maxNumberOfAnnotations;
this.MaxNumberOfMessageEvents = maxNumberOfMessageEvents;
this.MaxNumberOfLinks = maxNumberOfLinks;
}
public ISampler Sampler { get; }
public int MaxNumberOfAttributes { get; }
public int MaxNumberOfAnnotations { get; }
public int MaxNumberOfMessageEvents { get; }
public int MaxNumberOfLinks { get; }
public TraceParamsBuilder ToBuilder()
{
return new TraceParamsBuilder(this);
}
public override string ToString()
{
return "TraceParams{"
+ "sampler=" + Sampler + ", "
+ "maxNumberOfAttributes=" + MaxNumberOfAttributes + ", "
+ "maxNumberOfAnnotations=" + MaxNumberOfAnnotations + ", "
+ "maxNumberOfMessageEvents=" + MaxNumberOfMessageEvents + ", "
+ "maxNumberOfLinks=" + MaxNumberOfLinks
+ "}";
}
public override bool Equals(object o)
{
if (o == this)
{
return true;
}
if (o is TraceParams)
{
TraceParams that = (TraceParams)o;
return (this.Sampler.Equals(that.Sampler))
&& (this.MaxNumberOfAttributes == that.MaxNumberOfAttributes)
&& (this.MaxNumberOfAnnotations == that.MaxNumberOfAnnotations)
&& (this.MaxNumberOfMessageEvents == that.MaxNumberOfMessageEvents)
&& (this.MaxNumberOfLinks == that.MaxNumberOfLinks);
}
return false;
}
public override int GetHashCode()
{
int h = 1;
h *= 1000003;
h ^= this.Sampler.GetHashCode();
h *= 1000003;
h ^= this.MaxNumberOfAttributes;
h *= 1000003;
h ^= this.MaxNumberOfAnnotations;
h *= 1000003;
h ^= this.MaxNumberOfMessageEvents;
h *= 1000003;
h ^= this.MaxNumberOfLinks;
return h;
}
}
}
| 38.495327 | 177 | 0.593348 | [
"ECL-2.0",
"Apache-2.0"
] | SteeltoeOSS/Management | src/Steeltoe.Management.OpenCensus/Impl/Trace/Config/TraceParams.cs | 4,121 | C# |
using System;
// ReSharper disable once CheckNamespace
namespace Mkh
{
public static class GuidExtensions
{
/// <summary>
/// 判断Guid是否为空
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static bool IsEmpty(this Guid s)
{
return s == Guid.Empty;
}
/// <summary>
/// 判断Guid是否不为空
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static bool NotEmpty(this Guid s)
{
return s != Guid.Empty;
}
}
}
| 21.068966 | 48 | 0.477905 | [
"MIT"
] | HmmmWoo/Mkh | src/01_Utils/Utils/Extensions/GuidExtensions.cs | 639 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NetNode")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ZeroCodeDesign")]
[assembly: AssemblyProduct("NetNode")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c2820fae-d8d9-43bf-8811-b9618ff04324")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("0.0.0.1")]
[assembly: AssemblyFileVersion("0.0.0.1")]
| 36.470588 | 84 | 0.751613 | [
"Apache-2.0"
] | bryanwayb/netnode | NetNode/Properties/AssemblyInfo.cs | 1,243 | C# |
using MessagePack;
using System.Collections.Generic;
namespace Blockcore.Platform.Networking.Messages
{
[MessagePackObject]
public class HubInfoMessage : BaseMessage
{
public override ushort Command => MessageTypes.INFO;
[Key(1)]
public string Name { get; set; }
[Key(2)]
public string ExternalEndpoint { get; set; }
[Key(3)]
public string InternalEndpoint { get; set; }
[Key(4)]
public string ConnectionType { get; set; }
[Key(5)]
public List<string> InternalAddresses = new List<string>();
[Key(6)]
public string FirstName { get; set; }
}
}
| 21.333333 | 65 | 0.63125 | [
"MIT"
] | block-core/blockcore-gateway | src/Blockcore.Hub.Networking/Messages/HubInfoMessage.cs | 640 | C# |
using System.ComponentModel.DataAnnotations;
namespace lygwys.BookList.Configuration.Dto
{
public class ChangeUiThemeInput
{
[Required]
[StringLength(32)]
public string Theme { get; set; }
}
}
| 19.166667 | 44 | 0.665217 | [
"MIT"
] | lygwys/lygwys.BookList-github | src/booklist-aspnet-core/src/lygwys.BookList.Application/Configuration/Dto/ChangeUiThemeInput.cs | 230 | C# |
namespace ArchiveTools
{
partial class FrmDisplayFileMetaData
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.dataGridView1 = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// dataGridView1
//
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.AllowUserToOrderColumns = true;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.dataGridView1.Location = new System.Drawing.Point(0, 0);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.ReadOnly = true;
this.dataGridView1.Size = new System.Drawing.Size(859, 431);
this.dataGridView1.TabIndex = 0;
//
// FrmDisplayFileMetaData
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(859, 431);
this.Controls.Add(this.dataGridView1);
this.Name = "FrmDisplayFileMetaData";
this.Text = "Archive Meta Data";
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.DataGridView dataGridView1;
}
} | 38.734375 | 131 | 0.601856 | [
"MIT"
] | BarkingCactii/OpenHistorian_Noja | Source/Tools/ArchiveTools/FrmDisplayFileMetaData.Designer.cs | 2,481 | C# |
namespace VacationManager.Data.Contracts
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public interface IRepository<TEntity> where TEntity : class
{
/// <summary>
/// Get entity by identifier.
/// </summary>
/// <param name="id"></param>
Task<TEntity> GetByIdAsync(Guid id);
/// <summary>
/// Get all entities.
/// </summary>
/// <returns></returns>
Task<List<TEntity>> GetAllAsync();
/// <summary>
/// Add an entity.
/// <param name="entity">The entity instance.</param>
/// </summary>
void AddAsync(TEntity entity);
/// <summary>
/// Update an entity.
/// </summary>
/// <param name="entity">The entity instance.</param>
Task<bool> UpdateAsync(TEntity entity);
/// <summary>
/// Delete an entity.
/// </summary>
/// <param name="entity">The entity instance.</param>
Task DeleteAsync(TEntity entity);
/// <summary>
/// Retrieve the count of all entities.
/// </summary>
Task<int> CountAllAsync();
}
}
| 26.666667 | 63 | 0.533333 | [
"MIT"
] | stoyankirov/Vacation-Manager | Server/VacationManager/VacationManager.Data.Contracts/IRepository.cs | 1,202 | C# |
using Mango.Fundamentals;
using Mango.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace MangoTest
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
Timer myTimer = new Timer(new TimeSpan(0, 0,10));
UIEffects acrylic = new UIEffects();
public MainPage()
{
this.InitializeComponent();
myTimer.TimerTicked += MyTimer_TimerTicked;
myTimer.TimerEnded += MyTimer_TimerEnded;
}
private void displayTimeLeft()
{
Debug.WriteLine(myTimer.TimeLeft);
}
private void MyTimer_TimerEnded(object sender, TimerEventArgs e)
{
}
private void MyTimer_TimerTicked(object sender, TimerEventArgs e)
{
displayTimeLeft();
}
private void StartTimerButton_Click(object sender, RoutedEventArgs e)
{
myTimer.StartTimer();
displayTimeLeft();
acrylic.createMSFTStyleAcrylicArea(hah);
}
private void RestartTimerButton_Click(object sender, RoutedEventArgs e)
{
myTimer.ResetTimer();
displayTimeLeft();
}
private void PauseTimerButton_Click(object sender, RoutedEventArgs e)
{
myTimer.PauseTimer();
}
private void Page_SizeChanged(object sender, SizeChangedEventArgs e)
{
acrylic.updateAcrylicGlassSize(acrylic, e.NewSize);
}
}
}
| 25.386364 | 107 | 0.636974 | [
"MIT"
] | colinkiama/Mango | MangoTest/MainPage.xaml.cs | 2,236 | C# |
using System;
using Microsoft.IdentityModel.Tokens;
namespace ChopstickDocker.Authentication.JwtBearer
{
public class TokenAuthConfiguration
{
public SymmetricSecurityKey SecurityKey { get; set; }
public string Issuer { get; set; }
public string Audience { get; set; }
public SigningCredentials SigningCredentials { get; set; }
public TimeSpan Expiration { get; set; }
}
}
| 22.684211 | 66 | 0.684455 | [
"MIT"
] | yhua045/chopstick-docker | aspnet-core/src/ChopstickDocker.Web.Core/Authentication/JwtBearer/TokenAuthConfiguration.cs | 433 | C# |
namespace SharpIrcBot.Plugins.Calc.AST
{
public enum Operation
{
Add = 1,
Subtract = 2,
Negate = 3,
Multiply = 4,
Divide = 5,
Remainder = 6,
Power = 7,
BinaryAnd = 8,
BinaryXor = 9,
BinaryOr = 10,
IntegralDivide = 11,
Factorial = 12,
}
}
| 18.210526 | 38 | 0.468208 | [
"MIT"
] | RavuAlHemio/SharpIrcBot | Plugins/Calc/AST/Operation.cs | 346 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("kbab")]
[assembly: AssemblyDescription("Arma 3 Server Browser")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Eirik Kvarstein")]
[assembly: AssemblyProduct("Arma3Favorites")]
[assembly: AssemblyCopyright("Copyright © Eirik Kvarstein 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9d54df33-46c6-44e7-b4ef-1536975ccd32")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39 | 84 | 0.749134 | [
"MIT"
] | everystone/kbab | Arma3Favorites/Properties/AssemblyInfo.cs | 1,446 | C# |
namespace PKHeX.Core.Injection
{
public static class RamOffsets
{
public static LiveHeXVersion[] GetValidVersions(SaveFile sf)
{
return sf switch
{
SAV8LA => new[] { LiveHeXVersion.LA_v100 , LiveHeXVersion.LA_v101, LiveHeXVersion.LA_v102 },
SAV8BS => new[] { LiveHeXVersion.BD_v100, LiveHeXVersion.SP_v100, LiveHeXVersion.BD_v110, LiveHeXVersion.SP_v110, LiveHeXVersion.BD_v111, LiveHeXVersion.SP_v111, LiveHeXVersion.BDSP_v112, LiveHeXVersion.BDSP_v113 },
SAV8SWSH => new[] { LiveHeXVersion.SWSH_Orion, LiveHeXVersion.SWSH_Rigel1, LiveHeXVersion.SWSH_Rigel2 },
SAV7b => new[] { LiveHeXVersion.LGPE_v102 },
SAV7USUM => new[] { LiveHeXVersion.UM_v12, LiveHeXVersion.US_v12 },
SAV7SM => new[] { LiveHeXVersion.SM_v12 },
SAV6AO => new[] { LiveHeXVersion.ORAS },
SAV6XY => new[] { LiveHeXVersion.XY },
_ => new[] { LiveHeXVersion.SWSH_Rigel2 },
};
}
public static bool IsLiveHeXSupported(SaveFile sav)
{
return sav switch
{
SAV8LA => true,
SAV8BS => true,
SAV8SWSH => true,
SAV7b => true,
SAV7USUM => true,
SAV7SM => true,
SAV6AO => true,
SAV6XY => true,
_ => false,
};
}
public static ICommunicator GetCommunicator(LiveHeXVersion lv, InjectorCommunicationType ict)
{
return lv switch
{
LiveHeXVersion.UM_v12 => new NTRClient(),
LiveHeXVersion.US_v12 => new NTRClient(),
LiveHeXVersion.SM_v12 => new NTRClient(),
LiveHeXVersion.ORAS => new NTRClient(),
LiveHeXVersion.XY => new NTRClient(),
_ => GetSwitchInterface(ict),
};
}
public static int GetB1S1Offset(LiveHeXVersion lv)
{
return lv switch
{
LiveHeXVersion.LGPE_v102 => 0x533675B0,
LiveHeXVersion.SWSH_Orion => 0x4293D8B0,
LiveHeXVersion.SWSH_Rigel1 => 0x4506D890,
LiveHeXVersion.SWSH_Rigel2 => 0x45075880,
LiveHeXVersion.UM_v12 => 0x33015AB0,
LiveHeXVersion.US_v12 => 0x33015AB0,
LiveHeXVersion.SM_v12 => 0x330D9838,
LiveHeXVersion.ORAS => 0x8C9E134,
LiveHeXVersion.XY => 0x8C861C8,
_ => 0x0,
};
}
public static int GetSlotSize(LiveHeXVersion lv)
{
return lv switch
{
LiveHeXVersion.LA_v102 => 360,
LiveHeXVersion.LA_v101 => 360,
LiveHeXVersion.LA_v100 => 360,
LiveHeXVersion.LGPE_v102 => 260,
LiveHeXVersion.UM_v12 => 232,
LiveHeXVersion.US_v12 => 232,
LiveHeXVersion.SM_v12 => 232,
LiveHeXVersion.ORAS => 232,
LiveHeXVersion.XY => 232,
_ => 344,
};
}
public static int GetGapSize(LiveHeXVersion lv)
{
return lv switch
{
LiveHeXVersion.LGPE_v102 => 380,
_ => 0,
};
}
public static int GetSlotCount(LiveHeXVersion lv)
{
return lv switch
{
LiveHeXVersion.LGPE_v102 => 25,
_ => 30,
};
}
public static int GetTrainerBlockSize(LiveHeXVersion lv)
{
return lv switch
{
LiveHeXVersion.BDSP_v113 => 0x50,
LiveHeXVersion.BDSP_v112 => 0x50,
LiveHeXVersion.BD_v111 => 0x50,
LiveHeXVersion.BD_v110 => 0x50,
LiveHeXVersion.BD_v100 => 0x50,
LiveHeXVersion.SP_v111 => 0x50,
LiveHeXVersion.SP_v110 => 0x50,
LiveHeXVersion.SP_v100 => 0x50,
LiveHeXVersion.LGPE_v102 => 0x168,
LiveHeXVersion.SWSH_Orion => 0x110,
LiveHeXVersion.SWSH_Rigel1 => 0x110,
LiveHeXVersion.SWSH_Rigel2 => 0x110,
LiveHeXVersion.UM_v12 => 0xC0,
LiveHeXVersion.US_v12 => 0xC0,
LiveHeXVersion.SM_v12 => 0xC0,
LiveHeXVersion.ORAS => 0x170,
LiveHeXVersion.XY => 0x170,
_ => 0x110,
};
}
public static uint GetTrainerBlockOffset(LiveHeXVersion lv)
{
return lv switch
{
LiveHeXVersion.LGPE_v102 => 0x53582030,
LiveHeXVersion.SWSH_Orion => 0x42935E48,
LiveHeXVersion.SWSH_Rigel1 => 0x45061108,
LiveHeXVersion.SWSH_Rigel2 => 0x45068F18,
LiveHeXVersion.UM_v12 => 0x33012818,
LiveHeXVersion.US_v12 => 0x33012818,
LiveHeXVersion.SM_v12 => 0x330D67D0,
LiveHeXVersion.ORAS => 0x8C81340,
LiveHeXVersion.XY => 0x8C79C3C,
_ => 0x0,
};
}
public static bool WriteBoxData(LiveHeXVersion lv)
{
return lv switch
{
LiveHeXVersion.LA_v102 => true,
LiveHeXVersion.LA_v101 => true,
LiveHeXVersion.LA_v100 => true,
LiveHeXVersion.UM_v12 => true,
LiveHeXVersion.US_v12 => true,
LiveHeXVersion.SM_v12 => true,
LiveHeXVersion.ORAS => true,
LiveHeXVersion.XY => true,
_ => false,
};
}
// relative to: PlayerWork.SaveData_TypeInfo
public static (string, int) BoxOffsets(LiveHeXVersion lv)
{
return lv switch
{
LiveHeXVersion.BDSP_v113 => ("[[[[main+4E59E60]+B8]+10]+A0]+20", 40),
LiveHeXVersion.BDSP_v112 => ("[[[[main+4E34DD0]+B8]+10]+A0]+20", 40),
LiveHeXVersion.BD_v111 => ("[[[[main+4C1DCF8]+B8]+10]+A0]+20", 40),
LiveHeXVersion.BD_v110 => ("[[[main+4E27C50]+B8]+170]+20", 40),
LiveHeXVersion.BD_v100 => ("[[[main+4C0ABD8]+520]+C0]+5E0", 40),
LiveHeXVersion.SP_v111 => ("[[[[main+4E34DD0]+B8]+10]+A0]+20", 40),
LiveHeXVersion.SP_v110 => ("[[[main+4E27C50]+B8]+170]+20", 40), // untested
LiveHeXVersion.SP_v100 => ("[[[main+4C0ABD8]+520]+C0]+5E0", 40), // untested
_ => (string.Empty, 0)
};
}
public static object? GetOffsets(LiveHeXVersion lv)
{
return lv switch
{
LiveHeXVersion.SWSH_Rigel2 => Offsets8.Rigel2,
_ => null,
};
}
private static ICommunicator GetSwitchInterface(InjectorCommunicationType ict)
{
// No conditional expression possible
return ict switch
{
InjectorCommunicationType.SocketNetwork => new SysBotMini(),
InjectorCommunicationType.USB => new UsbBotMini(),
_ => new SysBotMini(),
};
}
}
}
| 37.474747 | 231 | 0.505391 | [
"MIT"
] | CScorpion-h/PKHeX-Plugins | PKHeX.Core.Injection/LiveHeXOffsets/RamOffsets.cs | 7,422 | C# |
using ECSSharp.Framework;
namespace ECSSharp.Demo.Components
{
public sealed class Weapon : Component
{
public int Damage;
public uint Owner;
}
}
| 16 | 42 | 0.653409 | [
"MIT"
] | demonixis/ECSSharp | ECSSharp/Demo/Components/Weapon.cs | 178 | C# |
// Copyright © 2012-2020 Vaughn Vernon. All rights reserved.
//
// This Source Code Form is subject to the terms of the
// Mozilla Public License, v. 2.0. If a copy of the MPL
// was not distributed with this file, You can obtain
// one at https://mozilla.org/MPL/2.0/.
namespace Vlingo.Common.Pool
{
/// <summary>
/// An abstract <see cref="IResourcePool{TResource,TArguments}"/> that implements <code>TResource Acquire(TArguments arguments)</code>
/// using the default arguments from <see cref="IResourceFactory{TResource,TArguments}"/> <code>DefaultArguments</code>.
/// </summary>
/// <typeparam name="TResource">The type of the pooled resource</typeparam>
/// <typeparam name="TArguments">The type of the arguments to the acquire method</typeparam>
public abstract class ResourcePool<TResource, TArguments> : IResourcePool<TResource, TArguments>
{
protected IResourceFactory<TResource, TArguments> Factory;
public ResourcePool(IResourceFactory<TResource, TArguments> factory) => Factory = factory;
/// <summary>
/// Uses default arguments to acquire resource object.
/// </summary>
/// <returns>A resource object with default arguments</returns>
public virtual TResource Acquire() => Acquire(Factory.DefaultArguments);
public abstract TResource Acquire(TArguments arguments);
public abstract void Release(TResource resource);
public abstract int Size { get; }
public abstract ResourcePoolStats Stats();
}
} | 42.861111 | 138 | 0.701231 | [
"MPL-2.0"
] | Johnny-Bee/vlingo-net-common | src/Vlingo.Common/Pool/ResourcePool.cs | 1,544 | C# |
namespace Raven.Yabt.Database.Models
{
/// <summary>
/// Entity that belongs to a tenant/project
/// </summary>
public interface ITenantedEntity
{
/// <summary>
/// ID of a tenant/project
/// </summary>
string TenantId { get; }
}
} | 19.538462 | 48 | 0.622047 | [
"MIT"
] | ravendb/samples-yabt | back-end/Database/Models/ITenantedEntity.cs | 256 | C# |
// Copyright (c) 2019 .NET Foundation and Contributors. All rights reserved.
// 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 full license information.
using System;
using System.Collections.Generic;
using SimpleInjector;
namespace Splat.SimpleInjector
{
/// <summary>
/// Simple Injector implementation for <see cref="IMutableDependencyResolver"/>.
/// </summary>
/// <seealso cref="Splat.IDependencyResolver" />
public class SimpleInjectorDependencyResolver : IDependencyResolver
{
private Container _container;
/// <summary>
/// Initializes a new instance of the <see cref="SimpleInjectorDependencyResolver"/> class.
/// </summary>
/// <param name="container">The container.</param>
public SimpleInjectorDependencyResolver(Container container)
{
_container = container;
}
/// <inheritdoc />
public object GetService(Type serviceType, string contract = null) => _container.GetInstance(serviceType);
/// <inheritdoc />
public IEnumerable<object> GetServices(Type serviceType, string contract = null) =>
_container.GetAllInstances(serviceType);
/// <inheritdoc />
public void Register(Func<object> factory, Type serviceType, string contract = null) =>
_container.Register(serviceType, factory);
/// <inheritdoc />
public void UnregisterCurrent(Type serviceType, string contract = null)
{
throw new NotImplementedException();
}
/// <inheritdoc />
public void UnregisterAll(Type serviceType, string contract = null)
{
throw new NotImplementedException();
}
/// <inheritdoc />
public IDisposable ServiceRegistrationCallback(Type serviceType, string contract, Action<IDisposable> callback)
{
throw new NotImplementedException();
}
/// <inheritdoc />
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes of the instance.
/// </summary>
/// <param name="disposing">Whether or not the instance is disposing.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_container?.Dispose();
_container = null;
}
}
}
}
| 32.949367 | 119 | 0.61506 | [
"MIT"
] | alexshikov/splat | src/Splat.SimpleInjector/SimpleInjectorDependencyResolver.cs | 2,605 | C# |
using NUnit.Framework;
namespace Pagination.Web.Routing {
[TestFixture, TestOf(typeof(PageExtension))]
public class PageExtensionTest {
[TestCase("Width", 38)]
[TestCase("Type", "Appliance")]
[TestCase("_p_ipp", 12)]
[TestCase("_p_pbz", 511)]
public void RouteValues_SetsPropertyValue(string name, object value) {
var page = new Page {
ItemsPerPage = 12,
PageBaseZero = 511,
State = new {
Width = 38,
Type = "Appliance"
}
};
var routeValues = PageExtension.RouteValues(page);
var actual = routeValues[name];
var expected = value;
Assert.That(actual, Is.EqualTo(expected));
}
[Test]
public void RouteValues_UsesSpecifiedPage() {
var page = new Page {
ItemsPerPage = 12,
PageBaseZero = 511,
State = new {
Width = 38,
Type = "Appliance"
}
};
var routeValues = PageExtension.RouteValues(page, 622);
var actual = routeValues["_p_pbz"];
var expected = 622;
Assert.That(actual, Is.EqualTo(expected));
}
[Test]
public void RouteValues_ThrowsIfPageIsNull() {
Assert.That(() =>
PageExtension.RouteValues(null),
Throws.ArgumentNullException.With.Property("ParamName").EqualTo("page"));
}
}
}
| 31.196078 | 89 | 0.502828 | [
"MIT"
] | kyourek/Pagination | sln/Pagination.Web.Tests/Web/Routing/PageExtensionTest.cs | 1,593 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Monitorian.Core.Helper;
using Monitorian.Core.Models;
using Monitorian.Core.ViewModels;
using Monitorian.Core.Views.Controls;
using Monitorian.Core.Views.Touchpad;
using ScreenFrame.Movers;
namespace Monitorian.Core.Views
{
public partial class MainWindow : Window
{
private readonly StickWindowMover _mover;
private readonly TouchpadTracker _tracker;
public MainWindowViewModel ViewModel => (MainWindowViewModel)this.DataContext;
public MainWindow(AppControllerCore controller)
{
LanguageService.Switch();
InitializeComponent();
this.DataContext = new MainWindowViewModel(controller);
_mover = new StickWindowMover(this, controller.NotifyIconContainer.NotifyIcon);
if (OsVersion.Is11OrGreater)
_mover.KeepsDistance = true;
controller.WindowPainter.Add(this);
controller.WindowPainter.ThemeChanged += (_, _) =>
{
ViewModel.MonitorsView.Refresh();
};
_tracker = new TouchpadTracker(this);
_tracker.ManipulationDelta += (_, delta) =>
{
var slider = FocusManager.GetFocusedElement(this) as EnhancedSlider;
slider?.ChangeValue(delta);
};
_tracker.ManipulationCompleted += (_, _) =>
{
var slider = FocusManager.GetFocusedElement(this) as EnhancedSlider;
slider?.EnsureUpdateSource();
};
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
CheckDefaultHeights();
BindingOperations.SetBinding(
this,
UsesLargeElementsProperty,
new Binding(nameof(SettingsCore.UsesLargeElements))
{
Source = ((MainWindowViewModel)this.DataContext).Settings,
Mode = BindingMode.OneWay
});
//this.InvalidateProperty(UsesLargeElementsProperty);
}
protected override void OnClosed(EventArgs e)
{
BindingOperations.ClearBinding(
this,
UsesLargeElementsProperty);
base.OnClosed(e);
}
#region Elements
private const double ShrinkFactor = 0.64;
private Dictionary<string, double> _defaultHeights;
private const string SliderHeightName = "SliderHeight";
private void CheckDefaultHeights()
{
_defaultHeights = this.Resources.Cast<DictionaryEntry>()
.Where(x => (x.Key is string key) && key.EndsWith("Height", StringComparison.Ordinal))
.Where(x => x.Value is double height and > 0D)
.ToDictionary(x => (string)x.Key, x => (double)x.Value);
}
public bool UsesLargeElements
{
get { return (bool)GetValue(UsesLargeElementsProperty); }
set { SetValue(UsesLargeElementsProperty, value); }
}
public static readonly DependencyProperty UsesLargeElementsProperty =
DependencyProperty.Register(
"UsesLargeElements",
typeof(bool),
typeof(MainWindow),
new PropertyMetadata(
true,
(d, e) =>
{
// Setting the same value will not trigger calling this method.
var window = (MainWindow)d;
if (window._defaultHeights is null)
return;
var factor = (bool)e.NewValue ? 1D : ShrinkFactor;
foreach (var (key, value) in window._defaultHeights)
{
var buffer = value * factor;
if (key == SliderHeightName)
buffer = Math.Ceiling(buffer / 4) * 4;
window.Resources[key] = buffer;
}
}));
#endregion
#region Show/Hide
public bool IsForeground => _mover.IsForeground();
public void ShowForeground()
{
try
{
this.Topmost = true;
// When window is deactivated, a focused element will lose focus and usually,
// no element has focus until window is activated again and the last focused element
// will automatically get focus back. Therefore, in usual case, no focused element
// exists before Window.Show method. However, during window is not active, it is
// possible to set focus on an element and such focused element is found here.
// The issue is that such focused element will lose focus because the element which
// had focus before window was deactivated will restore focus even though any other
// element has focus. To prevent this unintended change of focus, it is necessary
// to set focus back on the element which had focus before Window.Show method.
var currentFocusedElement = FocusManager.GetFocusedElement(this);
base.Show();
if (currentFocusedElement is not null)
{
var restoredFocusedElement = FocusManager.GetFocusedElement(this);
if (restoredFocusedElement != currentFocusedElement)
FocusManager.SetFocusedElement(this, currentFocusedElement);
}
}
finally
{
this.Topmost = false;
}
}
public bool CanBeShown => (_preventionTime < DateTimeOffset.Now);
private DateTimeOffset _preventionTime;
protected override void OnDeactivated(EventArgs e)
{
base.OnDeactivated(e);
if (this.Visibility != Visibility.Visible)
return;
ViewModel.Deactivate();
// Set time to prevent this window from being shown unintentionally.
_preventionTime = DateTimeOffset.Now + TimeSpan.FromSeconds(0.2);
ClearHide();
}
public async void ClearHide()
{
// Clear focus.
FocusManager.SetFocusedElement(this, null);
// Wait for this window to be refreshed before being hidden.
await Task.Delay(TimeSpan.FromSeconds(0.1));
this.Hide();
}
#endregion
}
} | 28.403941 | 91 | 0.691467 | [
"MIT"
] | GhostyJade/Monitorian | Source/Monitorian.Core/Views/MainWindow.xaml.cs | 5,768 | C# |
using System.Web.Mvc;
using System.Web.Routing;
using AnglicanGeek.Mvc;
namespace Sample
{
public class RouteRegistrar : IRouteRegistrar
{
public void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
}
} | 26 | 91 | 0.572874 | [
"MIT"
] | half-ogre/AnglicanGeek.Mvc | Sample/RouteRegistrar.cs | 496 | C# |
// <auto-generated>
using Generator.Tests.Common;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.Extensions.Configuration;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlTypes;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using Tester;
namespace Tester.Integration.EfCore3.File_based_templatesBananaDbContext
{
#region Database context interface
public interface IBananaDbContext : IDisposable
{
DbSet<Stafford_ComputedColumn> Stafford_ComputedColumns { get; set; } // ComputedColumns
int SaveChanges();
int SaveChanges(bool acceptAllChangesOnSuccess);
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken));
Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken));
DatabaseFacade Database { get; }
DbSet<TEntity> Set<TEntity>() where TEntity : class;
string ToString();
EntityEntry Add(object entity);
EntityEntry<TEntity> Add<TEntity>(TEntity entity) where TEntity : class;
Task AddRangeAsync(params object[] entities);
Task AddRangeAsync(IEnumerable<object> entities, CancellationToken cancellationToken = default);
ValueTask<EntityEntry<TEntity>> AddAsync<TEntity>(TEntity entity, CancellationToken cancellationToken = default) where TEntity : class;
ValueTask<EntityEntry> AddAsync(object entity, CancellationToken cancellationToken = default);
void AddRange(IEnumerable<object> entities);
void AddRange(params object[] entities);
EntityEntry Attach(object entity);
EntityEntry<TEntity> Attach<TEntity>(TEntity entity) where TEntity : class;
void AttachRange(IEnumerable<object> entities);
void AttachRange(params object[] entities);
EntityEntry Entry(object entity);
EntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
TEntity Find<TEntity>(params object[] keyValues) where TEntity : class;
ValueTask<TEntity> FindAsync<TEntity>(object[] keyValues, CancellationToken cancellationToken) where TEntity : class;
ValueTask<TEntity> FindAsync<TEntity>(params object[] keyValues) where TEntity : class;
ValueTask<object> FindAsync(Type entityType, object[] keyValues, CancellationToken cancellationToken);
ValueTask<object> FindAsync(Type entityType, params object[] keyValues);
object Find(Type entityType, params object[] keyValues);
EntityEntry Remove(object entity);
EntityEntry<TEntity> Remove<TEntity>(TEntity entity) where TEntity : class;
void RemoveRange(IEnumerable<object> entities);
void RemoveRange(params object[] entities);
EntityEntry Update(object entity);
EntityEntry<TEntity> Update<TEntity>(TEntity entity) where TEntity : class;
void UpdateRange(IEnumerable<object> entities);
void UpdateRange(params object[] entities);
}
#endregion
#region Database context
public class BananaDbContext : DbContext, IBananaDbContext
{
private readonly IConfiguration _configuration;
public BananaDbContext()
{
}
public BananaDbContext(DbContextOptions<BananaDbContext> options)
: base(options)
{
}
public BananaDbContext(IConfiguration configuration)
{
_configuration = configuration;
}
public DbSet<Stafford_ComputedColumn> Stafford_ComputedColumns { get; set; } // ComputedColumns
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured && _configuration != null)
{
optionsBuilder.UseSqlServer(_configuration.GetConnectionString(@"McsfMultiDatabase"));
}
}
public bool IsSqlParameterNull(SqlParameter param)
{
var sqlValue = param.SqlValue;
var nullableValue = sqlValue as INullable;
if (nullableValue != null)
return nullableValue.IsNull;
return (sqlValue == null || sqlValue == DBNull.Value);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.HasSequence<int>("CountBy1", "dbo").StartsAt(1).IncrementsBy(1).IsCyclic(false);
modelBuilder.HasSequence<long>("CountByBigInt", "dbo").StartsAt(22).IncrementsBy(234).IsCyclic(true).HasMin(1).HasMax(9876543);
modelBuilder.HasSequence<decimal>("CountByDecimal", "dbo").StartsAt(593).IncrementsBy(82).IsCyclic(false).HasMin(5).HasMax(777777);
modelBuilder.HasSequence<decimal>("CountByNumeric", "dbo").StartsAt(789).IncrementsBy(987).IsCyclic(false).HasMin(345).HasMax(999999999999999999);
modelBuilder.HasSequence<short>("CountBySmallInt", "dbo").StartsAt(44).IncrementsBy(456).IsCyclic(true);
modelBuilder.HasSequence<byte>("CountByTinyInt", "dbo").StartsAt(33).IncrementsBy(3).IsCyclic(false);
modelBuilder.ApplyConfiguration(new Stafford_ComputedColumnConfiguration());
}
}
#endregion
#region Database context factory
public class BananaDbContextFactory : IDesignTimeDbContextFactory<BananaDbContext>
{
public BananaDbContext CreateDbContext(string[] args)
{
return new BananaDbContext();
}
}
#endregion
#region POCO classes
// ComputedColumns
public class Stafford_ComputedColumn
{
public int id { get; set; } // Id (Primary key)
public string MyColumn { get; set; } // MyColumn (length: 10)
}
#endregion
#region POCO Configuration
// ComputedColumns
public class Stafford_ComputedColumnConfiguration : IEntityTypeConfiguration<Stafford_ComputedColumn>
{
public void Configure(EntityTypeBuilder<Stafford_ComputedColumn> builder)
{
builder.ToTable("ComputedColumns", "Stafford");
builder.HasKey(x => x.id).HasName("PK_Stafford_ComputedColumns").IsClustered();
builder.Property(x => x.id).HasColumnName(@"Id").HasColumnType("int").IsRequired().ValueGeneratedOnAdd().UseIdentityColumn();
builder.Property(x => x.MyColumn).HasColumnName(@"MyColumn").HasColumnType("varchar(10)").IsRequired().IsUnicode(false).HasMaxLength(10);
}
}
#endregion
}
// </auto-generated>
| 38.983051 | 158 | 0.702174 | [
"Apache-2.0"
] | janissimsons/EntityFramework-Reverse-POCO-Code-First-Generator | Tester.Integration.EfCore3/File based templates/BananaDbContext.cs | 6,900 | C# |
//Problem URL: https://www.hackerrank.com/challenges/sock-merchant/problem
static int sockMerchant(int n, int[] ar) {
int pairs = 0;
var distinct = ar.Distinct().ToList();
for(int i = 0; i < distinct.Count(); i++){
pairs += ((int)Math.Floor(ar.Count(x => x == distinct[i]) / 2d));
}
return pairs;
}
| 28.083333 | 74 | 0.58457 | [
"Unlicense"
] | DKLynch/HackerRank-Challenges | Algorithms/Implementation/Sock Merchant/sockMerchant.cs | 337 | C# |
/*
* InterfaceDataRateCommand.cs
*
* Copyright (c) 2009, Michael Schwarz (http://www.schwarz-interactive.de)
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
using System;
using System.Text;
namespace MFToolkit.Net.XBee
{
public class InterfaceDataRateCommand : AtCommand
{
internal static string command = "BD";
public InterfaceDataRateCommand()
: base(InterfaceDataRateCommand.command)
{
}
public InterfaceDataRateCommand(int baudRate)
: this()
{
byte baudRateValue = 0x80;
switch(baudRate)
{
case 1200: baudRateValue = 0x00; break;
case 2400: baudRateValue = 0x01; break;
case 4800: baudRateValue = 0x02; break;
case 9600: baudRateValue = 0x03; break;
case 19200: baudRateValue = 0x04; break;
case 38400: baudRateValue = 0x05; break;
case 57600: baudRateValue = 0x06; break;
case 115200:baudRateValue = 0x07; break;
}
this.Value = new byte[] { baudRateValue };
}
}
} | 33.35 | 77 | 0.724638 | [
"MIT"
] | michaelschwarz/Zigbee | Zigbee/Request/AT/InterfaceDataRate.cs | 2,003 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.42000
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using TTC2017.SmartGrids.CIM.IEC61968.AssetModels;
using TTC2017.SmartGrids.CIM.IEC61968.Assets;
using TTC2017.SmartGrids.CIM.IEC61968.Common;
using TTC2017.SmartGrids.CIM.IEC61968.Metering;
using TTC2017.SmartGrids.CIM.IEC61968.WiresExt;
using TTC2017.SmartGrids.CIM.IEC61970.Core;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfAssetModels;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfCommon;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfERPSupport;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfOperations;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfTypeAsset;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfWork;
using TTC2017.SmartGrids.CIM.IEC61970.Meas;
using TTC2017.SmartGrids.CIM.IEC61970.Wires;
namespace TTC2017.SmartGrids.CIM.IEC61970.Informative.InfAssets
{
/// <summary>
/// The public interface for SubstationInfo
/// </summary>
[DefaultImplementationTypeAttribute(typeof(SubstationInfo))]
[XmlDefaultImplementationTypeAttribute(typeof(SubstationInfo))]
public interface ISubstationInfo : IModelElement, IAssetInfo
{
/// <summary>
/// The function property
/// </summary>
Nullable<SubstationFunctionKind> Function
{
get;
set;
}
/// <summary>
/// Gets fired before the Function property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> FunctionChanging;
/// <summary>
/// Gets fired when the Function property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> FunctionChanged;
}
}
| 34.103896 | 96 | 0.696497 | [
"MIT"
] | georghinkel/ttc2017smartGrids | generator/Schema/IEC61970/Informative/InfAssets/ISubstationInfo.cs | 2,628 | C# |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if HAVE_REFLECTION_EMIT
using System;
using System.Collections.Generic;
#if !HAVE_LINQ
using Microsoft.IdentityModel.Json.Utilities.LinqBridge;
#endif
using System.Text;
using System.Reflection;
using Microsoft.IdentityModel.Json.Utilities;
using System.Globalization;
namespace Microsoft.IdentityModel.Json.Serialization
{
/// <summary>
/// Get and set values for a <see cref="MemberInfo"/> using dynamic methods.
/// </summary>
internal class DynamicValueProvider : IValueProvider
{
private readonly MemberInfo _memberInfo;
private Func<object, object> _getter;
private Action<object, object> _setter;
/// <summary>
/// Initializes a new instance of the <see cref="DynamicValueProvider"/> class.
/// </summary>
/// <param name="memberInfo">The member info.</param>
public DynamicValueProvider(MemberInfo memberInfo)
{
ValidationUtils.ArgumentNotNull(memberInfo, nameof(memberInfo));
_memberInfo = memberInfo;
}
/// <summary>
/// Sets the value.
/// </summary>
/// <param name="target">The target to set the value on.</param>
/// <param name="value">The value to set on the target.</param>
public void SetValue(object target, object value)
{
try
{
if (_setter == null)
{
_setter = DynamicReflectionDelegateFactory.Instance.CreateSet<object>(_memberInfo);
}
#if DEBUG
// dynamic method doesn't check whether the type is 'legal' to set
// add this check for unit tests
if (value == null)
{
if (!ReflectionUtils.IsNullable(ReflectionUtils.GetMemberUnderlyingType(_memberInfo)))
{
throw new JsonSerializationException("Incompatible value. Cannot set {0} to null.".FormatWith(CultureInfo.InvariantCulture, _memberInfo));
}
}
else if (!ReflectionUtils.GetMemberUnderlyingType(_memberInfo).IsAssignableFrom(value.GetType()))
{
throw new JsonSerializationException("Incompatible value. Cannot set {0} to type {1}.".FormatWith(CultureInfo.InvariantCulture, _memberInfo, value.GetType()));
}
#endif
_setter(target, value);
}
catch (Exception ex)
{
throw new JsonSerializationException("Error setting value to '{0}' on '{1}'.".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex);
}
}
/// <summary>
/// Gets the value.
/// </summary>
/// <param name="target">The target to get the value from.</param>
/// <returns>The value.</returns>
public object GetValue(object target)
{
try
{
if (_getter == null)
{
_getter = DynamicReflectionDelegateFactory.Instance.CreateGet<object>(_memberInfo);
}
return _getter(target);
}
catch (Exception ex)
{
throw new JsonSerializationException("Error getting value from '{0}' on '{1}'.".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex);
}
}
}
}
#endif | 38.575 | 179 | 0.622597 | [
"MIT"
] | AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet | src/Microsoft.IdentityModel.Tokens/opensource/json/Serialization/DynamicValueProvider.cs | 4,631 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Biosite.Domain;
using Biosite.SharedKernel.Library;
namespace ConsoleApplicationTest
{
public class Program
{
static void Main(string[] args)
{
Draft draft = new Draft();
var x = SharedFunctions.SetQuartil(10, 100);
///SharedFunctions.CheckRange(Convert.ToInt16(draft.Quartils), 50, draft.ReferenceMinValue, draft.ReferenceMaxValue);
var quart = SharedFunctions.GetQuartil(50, x);
Console.WriteLine(draft.Quartils.ToList()[1][0] + " " + draft.Quartils.ToList()[1][1]);
Console.ReadKey();
}
}
}
| 21.393939 | 129 | 0.637394 | [
"MIT"
] | carlosrogerioinfo/BiositeHealth | ConsoleApplicationTest/Program.cs | 708 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SharpGL.SceneGraph.Core
{
/// <summary>
/// An object that is Bindable is able to set itself into
/// the current OpenGL instance. This can be lights, materials,
/// attributes and so on.
/// </summary>
public interface IBindable
{
/// <summary>
/// Bind to the specified OpenGL instance.
/// </summary>
/// <param name="gl">The OpenGL instance.</param>
void Bind(OpenGL gl);
}
}
| 25 | 67 | 0.62 | [
"MIT"
] | mind0n/hive | History/Samples/3d/SharpGL/Core/SharpGL.SceneGraph/Core/IBindable.cs | 552 | C# |
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using MediatR.CommandQuery.Commands;
using MediatR.CommandQuery.Definitions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace MediatR.CommandQuery.EntityFrameworkCore.Handlers
{
public class EntityUpdateCommandHandler<TContext, TEntity, TKey, TUpdateModel, TReadModel>
: EntityDataContextHandlerBase<TContext, TEntity, TKey, TReadModel, EntityUpdateCommand<TKey, TUpdateModel, TReadModel>, TReadModel>
where TContext : DbContext
where TEntity : class, IHaveIdentifier<TKey>, new()
{
public EntityUpdateCommandHandler(ILoggerFactory loggerFactory, TContext dataContext, IMapper mapper)
: base(loggerFactory, dataContext, mapper)
{
}
protected override async Task<TReadModel> Process(EntityUpdateCommand<TKey, TUpdateModel, TReadModel> request, CancellationToken cancellationToken)
{
var dbSet = DataContext
.Set<TEntity>();
var keyValue = new object[] { request.Id };
// find entity to update by message id, not model id
var entity = await dbSet
.FindAsync(keyValue, cancellationToken)
.ConfigureAwait(false);
if (entity == null)
return default;
// copy updates from model to entity
Mapper.Map(request.Model, entity);
// apply update metadata
if (entity is ITrackUpdated updateEntity)
{
updateEntity.Updated = request.Activated;
updateEntity.UpdatedBy = request.ActivatedBy;
}
// save updates
await DataContext
.SaveChangesAsync(cancellationToken)
.ConfigureAwait(false);
// return read model
var readModel = await Read(entity.Id, cancellationToken)
.ConfigureAwait(false);
return readModel;
}
}
} | 34.677966 | 155 | 0.636364 | [
"MIT"
] | loresoft/MediatR.CommandQuery | src/MediatR.CommandQuery.EntityFrameworkCore/Handlers/EntityUpdateCommandHandler.cs | 2,048 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace OdeToFood.Pages
{
public class PrivacyModel : PageModel
{
public void OnGet()
{
}
}
} | 17.9375 | 42 | 0.745645 | [
"MIT"
] | Enache-Ionut/OdeToFood | .NetCore Tutorials/OdeToFood/OdeToFood/Pages/Privacy.cshtml.cs | 289 | C# |
using Microsoft.Web.WebView2.Core;
namespace WebView2.DOM
{
// https://github.com/chromium/chromium/blob/master/third_party/blink/renderer/core/html/html_progress_element.idl
public class HTMLProgressElement : HTMLElement, ILabelableElement
{
protected internal HTMLProgressElement(CoreWebView2 coreWebView, string referenceId)
: base(coreWebView, referenceId) { }
public double value { get => Get<double>(); set => Set(value); }
public double max { get => Get<double>(); set => Set(value); }
public double position => Get<double>();
public NodeList<HTMLLabelElement> labels => Get<NodeList<HTMLLabelElement>>();
}
}
| 35.444444 | 115 | 0.744514 | [
"MIT"
] | R2D221/WebView2.DOM | WebView2.DOM/HTML/Forms/HTMLProgressElement.cs | 640 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("11. PermutationsWithRepetitions")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("11. PermutationsWithRepetitions")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bd702890-bae5-4a50-af45-5c5af772eef9")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.783784 | 84 | 0.749129 | [
"MIT"
] | b-slavov/Telerik-Software-Academy | 12.Data Structures and Algorithms/07.Recursion/Recursion/11.PermutationsWithRepetitions/Properties/AssemblyInfo.cs | 1,438 | C# |
using System.Diagnostics;
namespace OmniSharp.Extensions.LanguageServer.Protocol.Models
{
[DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")]
public class TextEdit
{
/// <summary>
/// The range of the text document to be manipulated. To insert
/// text into a document create a range where start === end.
/// </summary>
public Range Range { get; set; }
/// <summary>
/// The string to be inserted. For delete operations use an
/// empty string.
/// </summary>
public string NewText { get; set; }
private string DebuggerDisplay => $"{Range} {( string.IsNullOrWhiteSpace(NewText) ? string.Empty : NewText.Length > 30 ? NewText.Substring(0, 30) : NewText )}";
/// <inheritdoc />
public override string ToString() => DebuggerDisplay;
}
}
| 33.230769 | 168 | 0.607639 | [
"MIT"
] | kamit9171/csharp-language-server-protocol | src/Protocol/Models/TextEdit.cs | 864 | C# |
using SQLite.Net.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WhatsAPI.UniversalApps.Sample.Models
{
[SQLite.Net.Attributes.Table("messages")]
public class Messages
{
[PrimaryKey, AutoIncrement]
public int id { get; set; }
public string jid { get; set; }
public string messages { get; set; }
}
}
| 23.105263 | 46 | 0.681093 | [
"MIT"
] | billyriantono/WhatsAPI-UniversalAppsLib | WhatsAPI.UniversalApps.Sample/WhatsAPI.UniversalApps.Sample.Windows/Models/Messages.cs | 441 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using WellEngineered.CruiseControl.Core.Config;
using WellEngineered.CruiseControl.Core.Queues;
using WellEngineered.CruiseControl.Core.State;
using WellEngineered.CruiseControl.Core.Util;
using WellEngineered.CruiseControl.Remote;
using WellEngineered.CruiseControl.Remote.Events;
namespace WellEngineered.CruiseControl.Core
{
/// <summary>
///
/// </summary>
public class IntegrationQueueManager
: IQueueManager
{
private readonly IProjectIntegratorListFactory projectIntegratorListFactory;
private IProjectIntegratorList projectIntegrators;
private readonly IntegrationQueueSet integrationQueues = new IntegrationQueueSet();
private readonly IProjectStateManager stateManager;
/// <summary>
/// Initializes a new instance of the <see cref="IntegrationQueueManager" /> class.
/// </summary>
/// <param name="projectIntegratorListFactory">The project integrator list factory.</param>
/// <param name="configuration">The configuration.</param>
/// <param name="stateManager">The state manager.</param>
/// <remarks></remarks>
public IntegrationQueueManager(IProjectIntegratorListFactory projectIntegratorListFactory,
IConfiguration configuration,
IProjectStateManager stateManager)
{
this.projectIntegratorListFactory = projectIntegratorListFactory;
this.Initialize(configuration);
this.stateManager = stateManager;
}
/// <summary>
/// Gets the projects and integration queues snapshot from this server.
/// </summary>
public CruiseServerSnapshot GetCruiseServerSnapshot()
{
ProjectStatus[] projectStatuses = this.GetProjectStatuses();
QueueSetSnapshot queueSetSnapshot = this.integrationQueues.GetIntegrationQueueSnapshot();
return new CruiseServerSnapshot(projectStatuses, queueSetSnapshot);
}
/// <summary>
/// Starts all projects.
/// </summary>
/// <remarks></remarks>
public void StartAllProjects()
{
foreach (IProjectIntegrator integrator in this.projectIntegrators)
{
bool canStart = (integrator.Project == null) ||
((integrator.Project.StartupMode == ProjectStartupMode.UseLastState) &&
this.stateManager.CheckIfProjectCanStart(integrator.Name)) ||
((integrator.Project.StartupMode == ProjectStartupMode.UseInitialState) &&
(integrator.Project.InitialState == ProjectInitialState.Started));
if (canStart) integrator.Start();
}
}
/// <summary>
/// Stops all projects.
/// </summary>
/// <param name="restarting">The restarting.</param>
/// <remarks></remarks>
public void StopAllProjects(bool restarting)
{
foreach (IProjectIntegrator integrator in this.projectIntegrators)
{
integrator.Stop(restarting);
}
this.WaitForIntegratorsToExit();
// We should clear the integration queue so the queues can be rebuilt when start again.
this.integrationQueues.Clear();
}
/// <summary>
/// Aborts this instance.
/// </summary>
/// <remarks></remarks>
public void Abort()
{
foreach (IProjectIntegrator integrator in this.projectIntegrators)
{
integrator.Abort();
}
this.WaitForIntegratorsToExit();
// We should clear the integration queue so the queues can be rebuilt when start again.
this.integrationQueues.Clear();
}
/// <summary>
/// Gets the project statuses.
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
public ProjectStatus[] GetProjectStatuses()
{
ArrayList projectStatusList = new ArrayList();
foreach (IProjectIntegrator integrator in this.projectIntegrators)
{
IProject project = integrator.Project;
projectStatusList.Add(project.CreateProjectStatus(integrator));
}
return (ProjectStatus[]) projectStatusList.ToArray(typeof (ProjectStatus));
}
/// <summary>
/// Gets the integrator.
/// </summary>
/// <param name="projectName">Name of the project.</param>
/// <returns></returns>
/// <remarks></remarks>
public IProjectIntegrator GetIntegrator(string projectName)
{
if (string.IsNullOrEmpty(projectName))
throw new NoSuchProjectException(projectName);
IProjectIntegrator integrator = this.projectIntegrators[projectName];
if (integrator == null)
throw new NoSuchProjectException(projectName);
return integrator;
}
/// <summary>
/// Forces the build.
/// </summary>
/// <param name="projectName">Name of the project.</param>
/// <param name="enforcerName">Name of the enforcer.</param>
/// <param name="buildValues">The build values.</param>
/// <remarks></remarks>
public void ForceBuild(string projectName, string enforcerName, Dictionary<string, string> buildValues)
{
this.GetIntegrator(projectName).ForceBuild(enforcerName, buildValues);
}
/// <summary>
/// Waits for exit.
/// </summary>
/// <param name="projectName">Name of the project.</param>
/// <remarks></remarks>
public void WaitForExit(string projectName)
{
this.GetIntegrator(projectName).WaitForExit();
}
/// <summary>
/// Requests the specified project.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="request">The request.</param>
/// <remarks></remarks>
public void Request(string project, IntegrationRequest request)
{
this.GetIntegrator(project).Request(request);
}
/// <summary>
/// Cancels the pending request.
/// </summary>
/// <param name="projectName">Name of the project.</param>
/// <remarks></remarks>
public void CancelPendingRequest(string projectName)
{
this.GetIntegrator(projectName).CancelPendingRequest();
}
/// <summary>
/// Stops the specified project.
/// </summary>
/// <param name="project">The project.</param>
/// <remarks></remarks>
public void Stop(string project)
{
this.stateManager.RecordProjectAsStopped(project);
this.GetIntegrator(project).Stop(false);
}
/// <summary>
/// Starts the specified project.
/// </summary>
/// <param name="project">The project.</param>
/// <remarks></remarks>
public void Start(string project)
{
this.stateManager.RecordProjectAsStartable(project);
this.GetIntegrator(project).Start();
}
/// <summary>
/// Restarts the specified configuration.
/// </summary>
/// <param name="configuration">The configuration.</param>
/// <remarks></remarks>
public void Restart(IConfiguration configuration)
{
this.StopAllProjects(true);
this.Initialize(configuration);
this.StartAllProjects();
}
private void WaitForIntegratorsToExit()
{
foreach (IProjectIntegrator integrator in this.projectIntegrators)
{
integrator.WaitForExit();
}
}
private void Initialize(IConfiguration configuration)
{
foreach (IProject project in configuration.Projects)
{
// Force the queue to be created if it does not exist already.
IQueueConfiguration config = configuration.FindQueueConfiguration(project.QueueName);
this.integrationQueues.Add(project.QueueName, config);
}
this.projectIntegrators = this.projectIntegratorListFactory.CreateProjectIntegrators(configuration.Projects, this.integrationQueues);
if (this.projectIntegrators.Count == 0)
{
Log.Info("No projects found");
}
}
/// <summary>
/// Returns an array of the current queue names in usage.
/// </summary>
/// <returns>Array of current queue names in use.</returns>
public string[] GetQueueNames()
{
return this.integrationQueues.GetQueueNames();
}
/// <summary>
/// Associates the integration events.
/// </summary>
/// <param name="integrationStarted"></param>
/// <param name="integrationCompleted"></param>
public void AssociateIntegrationEvents(EventHandler<IntegrationStartedEventArgs> integrationStarted,
EventHandler<IntegrationCompletedEventArgs> integrationCompleted)
{
foreach (IProjectIntegrator integrator in this.projectIntegrators)
{
integrator.IntegrationStarted += integrationStarted;
integrator.IntegrationCompleted += integrationCompleted;
}
}
}
}
| 33.957854 | 136 | 0.651134 | [
"MIT"
] | wellengineered-us/cruisecontrol | src/WellEngineered.CruiseControl.Core/IntegrationQueueManager.cs | 8,863 | 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 rekognition-2016-06-27.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Rekognition.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Rekognition.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for StartTextDetection operation
/// </summary>
public class StartTextDetectionResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
StartTextDetectionResponse response = new StartTextDetectionResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("JobId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.JobId = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException"))
{
return AccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("IdempotentParameterMismatchException"))
{
return IdempotentParameterMismatchExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerError"))
{
return InternalServerErrorExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterException"))
{
return InvalidParameterExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidS3ObjectException"))
{
return InvalidS3ObjectExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("LimitExceededException"))
{
return LimitExceededExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ProvisionedThroughputExceededException"))
{
return ProvisionedThroughputExceededExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottlingException"))
{
return ThrottlingExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("VideoTooLargeException"))
{
return VideoTooLargeExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonRekognitionException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static StartTextDetectionResponseUnmarshaller _instance = new StartTextDetectionResponseUnmarshaller();
internal static StartTextDetectionResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static StartTextDetectionResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 43.112676 | 194 | 0.639334 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Rekognition/Generated/Model/Internal/MarshallTransformations/StartTextDetectionResponseUnmarshaller.cs | 6,122 | C# |
using System;
using System.Globalization;
namespace Captura.ValueConverters
{
public class GetTypeConverter : OneWayConverter
{
public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value?.GetType();
}
}
} | 23.846154 | 108 | 0.680645 | [
"MIT"
] | Lakritzator/Captura | src/Captura/ValueConverters/GetTypeConverter.cs | 310 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace _02.MirrorWords
{
class Program
{
static void Main(string[] args)
{
string pattern = @"([#]|[@])(?<firstword>[A-Za-z]{3,})\1\1(?<secondword>[A-Za-z]{3,})\1";
var text = Console.ReadLine();
Regex regex = new Regex(pattern);
MatchCollection matches = regex.Matches(text);
List<string> words = new List<string>();
if (matches.Count > 0)
{
Console.WriteLine($"{matches.Count} word pairs found!");
foreach (Match match in matches)
{
var firstWord = match.Groups["firstword"].Value.ToString();
var secondWord = match.Groups["secondword"].Value.ToString();
var reversed = new string(secondWord.Reverse().ToArray());
if (firstWord == reversed)
{
words.Add($"{firstWord} <=> {secondWord}");
}
}
if (words.Count > 0)
{
Console.WriteLine("The mirror words are:");
Console.WriteLine(string.Join(", ", words));
}
else
{
Console.WriteLine("No mirror words!");
}
}
else
{
Console.WriteLine("No word pairs found!");
Console.WriteLine("No mirror words!");
}
}
}
}
| 30.196429 | 102 | 0.440568 | [
"MIT"
] | RumenSinigerski/Exam-prep | ProgrammingFundamentalsFinalExamRetake-10April2020/02.MirrorWords/Program.cs | 1,693 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.WorkMailMessageFlow")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon WorkMail Message Flow. This release allows customers to access email messages as they flow to and from Amazon WorkMail.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.7.0.82")] | 46.21875 | 206 | 0.751859 | [
"Apache-2.0"
] | bgrainger/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/WorkMailMessageFlow/Properties/AssemblyInfo.cs | 1,479 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the connect-2017-08-08.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Connect.Model
{
/// <summary>
/// This is the response object from the UpdateContactFlowModuleMetadata operation.
/// </summary>
public partial class UpdateContactFlowModuleMetadataResponse : AmazonWebServiceResponse
{
}
} | 30.131579 | 105 | 0.740611 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/Connect/Generated/Model/UpdateContactFlowModuleMetadataResponse.cs | 1,145 | 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;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.vod.Model.V20170314;
namespace Aliyun.Acs.vod.Transform.V20170314
{
public class GetTotalStatisResponseUnmarshaller
{
public static GetTotalStatisResponse Unmarshall(UnmarshallerContext context)
{
GetTotalStatisResponse getTotalStatisResponse = new GetTotalStatisResponse();
getTotalStatisResponse.HttpResponse = context.HttpResponse;
getTotalStatisResponse.RequestId = context.StringValue("GetTotalStatis.RequestId");
getTotalStatisResponse.TranscodeDuration = context.LongValue("GetTotalStatis.TranscodeDuration");
getTotalStatisResponse.StorageUtilization = context.LongValue("GetTotalStatis.StorageUtilization");
getTotalStatisResponse.NetworkOut = context.LongValue("GetTotalStatis.NetworkOut");
return getTotalStatisResponse;
}
}
}
| 39.883721 | 102 | 0.773761 | [
"Apache-2.0"
] | sdk-team/aliyun-openapi-net-sdk | aliyun-net-sdk-vod/Vod/Transform/V20170314/GetTotalStatisResponseUnmarshaller.cs | 1,715 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Discord.WebSocket
{
/// <summary>
/// Represents generic op codes for voice disconnect.
/// </summary>
public enum VoiceCloseCode
{
/// <summary>
/// You sent an invalid opcode.
/// </summary>
UnknownOpcode = 4001,
/// <summary>
/// You sent an invalid payload in your identifying to the Gateway.
/// </summary>
DecodeFailure = 4002,
/// <summary>
/// You sent a payload before identifying with the Gateway.
/// </summary>
NotAuthenticated = 4003,
/// <summary>
/// The token you sent in your identify payload is incorrect.
/// </summary>
AuthenticationFailed = 4004,
/// <summary>
/// You sent more than one identify payload. Stahp.
/// </summary>
AlreadyAuthenticated = 4005,
/// <summary>
/// Your session is no longer valid.
/// </summary>
SessionNolongerValid = 4006,
/// <summary>
/// Your session has timed out.
/// </summary>
SessionTimeout = 4009,
/// <summary>
/// We can't find the server you're trying to connect to.
/// </summary>
ServerNotFound = 4011,
/// <summary>
/// We didn't recognize the protocol you sent.
/// </summary>
UnknownProtocol = 4012,
/// <summary>
/// Channel was deleted, you were kicked, voice server changed, or the main gateway session was dropped. Should not reconnect.
/// </summary>
Disconnected = 4014,
/// <summary>
/// The server crashed. Our bad! Try resuming.
/// </summary>
VoiceServerCrashed = 4015,
/// <summary>
/// We didn't recognize your encryption.
/// </summary>
UnknownEncryptionMode = 4016,
}
}
| 31.84375 | 138 | 0.540726 | [
"MIT"
] | AraHaan/Discord.Net | src/Discord.Net.WebSocket/API/Voice/VoiceCloseCode.cs | 2,038 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HexMovementInfo {
public List<Hex> traversableTiles { get; private set; }
public Dictionary<Hex, Hex> tileReturnPath { get; private set; }
public HexMovementInfo(List<Hex> traversableTiles, Dictionary<Hex, Hex> tileReturnPath) {
this.traversableTiles = traversableTiles;
this.tileReturnPath = tileReturnPath;
}
}
public class HexGrid {
public Vector2Int gridSize;
// TODO upgrade grid storage to Hash table
private Hex[,] hexGrid;
private Layout gridLayout;
public HexGrid(Vector2Int gridSize, Layout gridLayout) {
this.gridSize = gridSize;
this.hexGrid = new Hex[gridSize.x, gridSize.y];
this.gridLayout = gridLayout;
}
public List<Hex> GetHexesInRange(Hex startingHex, int range) {
if (range < 0) throw new ArgumentException("range cannot be negative");
List<Hex> results = new List<Hex>();
for(int x = -range; x <= range; x++) {
for(int y = Math.Max(-range, -x-range); y <= Math.Min(range, -x + range); y++) {
int z = -x -y;
Hex targetHex = GetHex(startingHex.coords + new Vector3Int(x, y, z));
if(!System.Object.ReferenceEquals(targetHex, null) && !targetHex.GetTileInfo().isBlocked) {
results.Add(targetHex);
}
}
}
return results;
}
public List<Hex> GetHexesInRange(Vector2Int axialCoords, int range) {
return GetHexesInRange(GetHex(axialCoords), range);
}
public List<Hex> GetHexesInRange(Vector3 worldCoords, int range) {
return GetHexesInRange(GetHexAt(worldCoords), range);
}
public HexMovementInfo GetHexesInMovementRange(Hex startingHex, int movementRange) {
// Modified Dijkstra's Algorithm AKA Uniform Cost Search
List<Hex> results = new List<Hex>();
results.Add(startingHex);
BucketPriority<Hex> frontier = new BucketPriority<Hex>(128, true);
frontier.Enqueue(0, startingHex);
Dictionary<Hex, int> costSoFar = new Dictionary<Hex, int>();
Dictionary<Hex, Hex> cameFrom = new Dictionary<Hex, Hex>();
if (!UnityEngine.Object.ReferenceEquals(startingHex, null)) {
costSoFar[startingHex] = 0;
}
while(!frontier.Empty()) {
Hex currentHex = frontier.Dequeue();
List<Hex> hexNeighbors = GetHexNeighbors(currentHex);
if (hexNeighbors.Count > 0) {
foreach (Hex nextHex in hexNeighbors) {
int newCost = costSoFar[currentHex] + nextHex.GetTileInfo().movementCost;
if ((!costSoFar.ContainsKey(nextHex) || newCost < costSoFar[nextHex]) && newCost < movementRange && !(nextHex.GetTileInfo().isBlocked || nextHex.GetTileInfo().isOccupied)) {
costSoFar[nextHex] = newCost;
int newPriority = newCost;
frontier.Enqueue(newPriority, nextHex);
cameFrom[nextHex] = currentHex;
results.Add(nextHex);
}
}
}
}
return new HexMovementInfo(results, cameFrom);
}
public Hex GetHex(Vector2Int axialCoords) {
if(axialCoords.x < 0 || axialCoords.y < 0 || axialCoords.x > gridSize.x -1 || axialCoords.y > gridSize.y -1) {
return null;
}
return hexGrid[axialCoords.x, axialCoords.y];
}
public Hex GetHex(Vector3Int coords) {
if (coords.x < 0 || coords.z < 0 || coords.x > gridSize.x -1 || coords.z > gridSize.y -1) {
return null;
}
return hexGrid[coords.x, coords.z];
}
public Hex GetHexAt(Vector2 worldCoords) {
FractionalHex fractHex = gridLayout.WorldToHex(worldCoords);
return GetHex(fractHex.HexRound().axialCoords);
}
public Hex GetHexAt(Vector3 worldCoords) {
return GetHexAt(new Vector2(worldCoords.x, worldCoords.z));
}
public List<Hex> GetHexNeighbors(Vector2Int axialCoords) {
List<Hex> neighbors = new List<Hex>();
Hex currentHex = GetHex(axialCoords);
for(int i = 0; i < 6; i++) {
Vector3Int neighborCoords = currentHex.GetNeighborCoords(i);
if(!object.ReferenceEquals(GetHex(neighborCoords),null)) {
neighbors.Add(GetHex(neighborCoords));
}
}
return neighbors;
}
public Hex GetRandomHex() {
Vector2Int randomCoords = GetRandomHexCoords();
Hex randomHex = GetHex(randomCoords);
return randomHex;
}
public Vector2Int GetRandomHexCoords() {
Vector2Int randomCoords = new Vector2Int();
randomCoords.x = UnityEngine.Random.Range(0, this.gridSize.x - 1);
randomCoords.y = UnityEngine.Random.Range(0, this.gridSize.y - 1);
return randomCoords;
}
public List<Hex> GetHexNeighbors(Vector3Int coords) {
return GetHexNeighbors(new Vector2Int(coords.x, coords.z));
}
public List<Hex> GetHexNeighbors(Hex currentHex) {
return GetHexNeighbors(currentHex.axialCoords);
}
public void SetHex(Vector2Int axialCoords, Hex hex) {
this.hexGrid[axialCoords.x, axialCoords.y] = hex;
}
public void SetHexAt(Vector2 worldCoords, Hex hex) {
FractionalHex fractHex = gridLayout.WorldToHex(worldCoords);
SetHex(fractHex.HexRound().axialCoords, hex);
}
public void SetHexAt(Vector3 worldCoords, Hex hex) {
SetHexAt(new Vector2(worldCoords.x, worldCoords.z), hex);
}
public Vector2Int WorldToHex(Vector2 worldCoords) {
return this.gridLayout.WorldToHex(worldCoords).HexRound().axialCoords;
}
public Vector2Int WorldToHex(Vector3 worldCoords) {
return WorldToHex(new Vector2(worldCoords.x, worldCoords.z));
}
public Vector3 HexToWorld(Vector2Int hexCoords) {
Vector2 temp = this.gridLayout.HexToWorld(GetHex(hexCoords));
return new Vector3(temp.x, 0, temp.y);
}
public Vector3 HexToWorld(Hex hex) {
Vector2 temp = this.gridLayout.HexToWorld(hex);
return new Vector3(temp.x, 0, temp.y);
}
public Vector2 HexToWorld2D(Vector2Int hexCoords) {
return this.gridLayout.HexToWorld(GetHex(hexCoords));
}
public Vector2 HexToWorld2D(Hex hex) {
return this.gridLayout.HexToWorld(hex);
}
}
public class Hex {
// vectorized cube constructor
public Hex(Vector3Int coords) {
this.coords = coords;
//this.hexTile = new GameObject("Blank Tile (" + coords.x + ", " + coords.z +")");
if (coords.x + coords.y + coords.z != 0) throw new ArgumentException("x + y + z must be 0");
}
// vectorized axial constructor
public Hex(Vector2Int axialCoords) : this(new Vector3Int(axialCoords.x, -axialCoords.x - axialCoords.y, axialCoords.y)) {
}
// cube constructor
public Hex(int x, int y, int z) : this(new Vector3Int(x, y, z)) {
}
// axial constructor
public Hex(int q, int r) : this(new Vector3Int(q, -q -r, r)) {
}
public readonly Vector3Int coords;
public Vector2Int axialCoords {
get {
return new Vector2Int(this.coords.x, this.coords.z);
}
}
private GameObject hexTile;
private TileInfo tileInfo;
public void SetHexTile(GameObject newTile) {
UnityEngine.Object.Destroy(hexTile);
this.hexTile = newTile;
this.tileInfo = hexTile.GetComponent<TileInfo>();
}
public GameObject GetHexTile() {
return this.hexTile;
}
public TileInfo GetTileInfo() {
return this.tileInfo;
}
public override bool Equals(object obj) {
if (!object.ReferenceEquals(obj,null)) {
return this.Equals((Hex)obj);
}
else {
return false;
}
}
public bool Equals(Hex obj) {
if (!object.ReferenceEquals(obj, null)) {
return this.coords == obj.coords;
}
else {
return false;
}
}
public override int GetHashCode() {
return (coords.x * 0x100000) + (coords.y * 0x1000) + coords.z;
}
public static bool operator ==(Hex h1, Hex h2) {
return h1.Equals(h2);
}
public static bool operator !=(Hex h1, Hex h2) {
return !h1.Equals(h2);
}
public Hex Add(Hex b) {
return new Hex(coords + b.coords);
}
public Hex Subtract(Hex b) {
return new Hex(coords - b.coords);
}
public Hex Scale(int k) {
return new Hex(coords.x * k, coords.y * k, coords.z * k);
}
public int Length() {
return (int)((Math.Abs(coords.x) + Math.Abs(coords.y) + Math.Abs(coords.z)) / 2);
}
public int Distance(Hex b) {
return Subtract(b).Length();
}
static public List<Hex> directions = new List<Hex>{new Hex(1, 0, -1), new Hex(1, -1, 0), new Hex(0, -1, 1), new Hex(-1, 0, 1), new Hex(-1, 1, 0), new Hex(0, 1, -1)};
static public Hex Direction(int direction) {
return Hex.directions[direction];
}
public Hex Neighbor(int direction) {
return Add(Hex.Direction(direction));
}
static public List<Vector3Int> directionOffsets = new List<Vector3Int> { new Vector3Int(1, 0, -1), new Vector3Int(1, -1, 0), new Vector3Int(0, -1, 1), new Vector3Int(-1, 0, 1), new Vector3Int(-1, 1, 0), new Vector3Int(0, 1, -1) };
static public Vector3 GetDirectionOffset(int direction) {
return Hex.directionOffsets[direction];
}
public Vector3Int GetNeighborCoords(int direction) {
return this.coords + Hex.directionOffsets[direction];
}
}
public struct Orientation {
public Orientation(double f0, double f1, double f2, double f3, double b0, double b1, double b2, double b3, double start_angle) {
this.f0 = f0;
this.f1 = f1;
this.f2 = f2;
this.f3 = f3;
this.b0 = b0;
this.b1 = b1;
this.b2 = b2;
this.b3 = b3;
this.start_angle = start_angle;
}
public readonly double f0;
public readonly double f1;
public readonly double f2;
public readonly double f3;
public readonly double b0;
public readonly double b1;
public readonly double b2;
public readonly double b3;
public readonly double start_angle;
static public readonly Orientation pointy = new Orientation(Math.Sqrt(3.0), Math.Sqrt(3.0) / 2.0, 0.0, 3.0 / 2.0, Math.Sqrt(3.0) / 3.0, -1.0 / 3.0, 0.0, 2.0 / 3.0, 0.5);
static public readonly Orientation flat = new Orientation(3.0 / 2.0, 0.0, Math.Sqrt(3.0) / 2.0, Math.Sqrt(3.0), 2.0 / 3.0, 0.0, -1.0 / 3.0, Math.Sqrt(3.0) / 3.0, 0.0);
}
public struct Layout {
public Layout(Orientation orientation, Vector2 size, Vector2 origin) {
this.orientation = orientation;
this.size = size;
this.origin = origin;
}
public readonly Orientation orientation;
public readonly Vector2 size;
public readonly Vector2 origin;
public Vector2 HexToWorld(Hex h) {
Orientation M = orientation;
float x = (float)(M.f0 * h.coords.x + M.f1 * h.coords.z) * size.x;
float y = (float)(M.f2 * h.coords.x + M.f3 * h.coords.z) * size.y;
return new Vector2(x + origin.x, y + origin.y);
}
public FractionalHex WorldToHex(Vector2 p) {
Orientation M = orientation;
Vector2 pt = new Vector2((p.x - origin.x) / size.x, (p.y - origin.y) / size.y);
float q = (float)(M.b0 * pt.x + M.b1 * pt.y);
float r = (float)(M.b2 * pt.x + M.b3 * pt.y);
return new FractionalHex(q, -q - r, r);
}
public Vector2 HexCornerOffset(int corner) {
Orientation M = orientation;
float angle = (float)(2.0 * Math.PI * (M.start_angle - corner) / 6.0);
return new Vector2((float)(size.x * Math.Cos(angle)), (float)(size.y * Math.Sin(angle)));
}
public List<Vector2> PolygonCorners(Hex h) {
List<Vector2> corners = new List<Vector2> { };
Vector2 center = HexToWorld(h);
for (int i = 0; i < 6; i++) {
Vector2 offset = HexCornerOffset(i);
corners.Add(new Vector2(center.x + offset.x, center.y + offset.y));
}
return corners;
}
}
public struct FractionalHex {
public FractionalHex(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
if (Math.Round(x + y + z) != 0) throw new ArgumentException("x + y + z must be 0");
}
public readonly double x;
public readonly double y;
public readonly double z;
public Hex HexRound() {
int xi = (int)(Math.Round(x));
int yi = (int)(Math.Round(y));
int zi = (int)(Math.Round(z));
double x_diff = Math.Abs(xi - x);
double r_diff = Math.Abs(yi - y);
double s_diff = Math.Abs(zi - z);
if (x_diff > r_diff && x_diff > s_diff) {
xi = -yi - zi;
}
else
if (r_diff > s_diff) {
yi = -xi - zi;
}
else {
zi = -xi - yi;
}
return new Hex(xi, yi, zi);
}
public FractionalHex HexLerp(FractionalHex b, double t) {
return new FractionalHex(x * (1.0 - t) + b.x * t, y * (1.0 - t) + b.y * t, z * (1.0 - t) + b.z * t);
}
static public List<Hex> HexLineDraw(Hex a, Hex b) {
int N = a.Distance(b);
FractionalHex a_nudge = new FractionalHex(a.coords.x + 0.000001, a.coords.y + 0.000001, a.coords.z - 0.000002);
FractionalHex b_nudge = new FractionalHex(b.coords.x + 0.000001, b.coords.y + 0.000001, b.coords.z - 0.000002);
List<Hex> results = new List<Hex> { };
double step = 1.0 / Math.Max(N, 1);
for (int i = 0; i <= N; i++) {
results.Add(a_nudge.HexLerp(b_nudge, step * i).HexRound());
}
return results;
}
}
public static class HexUtil {
public static Vector3 CubeLerp(Vector3 a, Vector3 b, float t) {
return new Vector3(Mathf.Lerp(a.x, b.x, t), Mathf.Lerp(a.y, b.y, t), Mathf.Lerp(a.z, b.z, t));
}
} | 33.45283 | 234 | 0.600536 | [
"MIT"
] | FriedYeti/Hex-Map-Generation | HexGrid.cs | 14,186 | C# |
/**
* Copyright (c) 2019-2021 LG Electronics, Inc.
*
* This software contains code licensed as described in LICENSE.
*
*/
using UnityEngine;
public class CameraManager : MonoBehaviour
{
public GameObject SimulatorCameraPrefab;
public Camera SimulatorCamera { get; private set; }
public SimulatorCameraController CameraController { get; private set; }
private void Awake()
{
SimulatorCamera = Instantiate(SimulatorCameraPrefab, transform).GetComponentInChildren<Camera>();
CameraController = SimulatorCamera.GetComponentInParent<SimulatorCameraController>();
}
private void OnEnable()
{
SimulatorManager.Instance.AgentManager.AgentChanged += OnAgentChange;
}
private void OnDisable()
{
SimulatorManager.Instance.AgentManager.AgentChanged -= OnAgentChange;
}
private void OnAgentChange(GameObject agent)
{
CameraController.SetFollowCameraState(agent);
}
public void SetFreeCameraState()
{
CameraController.SetFreeCameraState();
}
/// <summary>
/// API command to set free camera position and rotation
/// </summary>
public void SetFreeCameraState(Vector3 pos, Vector3 rot)
{
CameraController.SetFreeCameraState(pos, rot);
}
/// <summary>
/// API command to set camera state
/// </summary>
public void SetCameraState(CameraStateType state)
{
switch (state)
{
case CameraStateType.Free:
CameraController.SetFreeCameraState();
break;
case CameraStateType.Follow:
CameraController.SetFollowCameraState(SimulatorManager.Instance.AgentManager.CurrentActiveAgent);
break;
case CameraStateType.Cinematic:
CameraController.SetCinematicCameraState();
break;
case CameraStateType.Driver:
CameraController.SetDriverViewCameraState();
break;
}
}
public void ToggleCameraState()
{
CameraController.IncrementCameraState();
switch (CameraController.CurrentCameraState)
{
case CameraStateType.Free:
CameraController.SetFreeCameraState();
break;
case CameraStateType.Follow:
CameraController.SetFollowCameraState(SimulatorManager.Instance.AgentManager.CurrentActiveAgent);
break;
case CameraStateType.Cinematic:
CameraController.SetCinematicCameraState();
break;
case CameraStateType.Driver:
CameraController.SetDriverViewCameraState();
break;
}
SimulatorManager.Instance.UIManager?.SetCameraButtonState();
}
public CameraStateType GetCurrentCameraState()
{
return CameraController.CurrentCameraState;
}
public void Reset()
{
CameraController.SetFollowCameraState(gameObject);
}
}
| 29.339806 | 113 | 0.642952 | [
"Apache-2.0",
"BSD-3-Clause"
] | HaoruXue/simulator | Assets/Scripts/Managers/CameraManager.cs | 3,022 | C# |
using System;
using System.Threading.Tasks;
using System.ComponentModel.Design;
using System.Diagnostics.CodeAnalysis;
using System.Reactive.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using GitHub.Factories;
using GitHub.Services;
using GitHub.ViewModels.GitHubPane;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Threading;
using ReactiveUI;
namespace GitHub.VisualStudio.UI
{
/// <summary>
/// This class implements the tool window exposed by this package and hosts a user control.
/// </summary>
/// <remarks>
/// In Visual Studio tool windows are composed of a frame (implemented by the shell) and a pane,
/// usually implemented by the package implementer.
/// <para>
/// This class derives from the ToolWindowPane class provided from the MPF in order to use its
/// implementation of the IVsUIElementPane interface.
/// </para>
/// </remarks>
[Guid(GitHubPaneGuid)]
public class GitHubPane : ToolWindowPane
{
public const string GitHubPaneGuid = "6b0fdc0a-f28e-47a0-8eed-cc296beff6d2";
JoinableTask<IGitHubPaneViewModel> viewModelTask;
IDisposable viewSubscription;
ContentPresenter contentPresenter;
public FrameworkElement View
{
get { return contentPresenter.Content as FrameworkElement; }
set
{
viewSubscription?.Dispose();
viewSubscription = null;
contentPresenter.Content = value;
viewSubscription = value.WhenAnyValue(x => x.DataContext)
.SelectMany(x =>
{
var pane = x as IGitHubPaneViewModel;
return pane?.WhenAnyValue(p => p.IsSearchEnabled, p => p.SearchQuery)
?? Observable.Return(Tuple.Create<bool, string>(false, null));
})
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(x => UpdateSearchHost(x.Item1, x.Item2));
}
}
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public GitHubPane() : base(null)
{
Caption = "GitHub";
Content = contentPresenter = new ContentPresenter();
BitmapImageMoniker = new Microsoft.VisualStudio.Imaging.Interop.ImageMoniker()
{
Guid = Guids.guidImageMoniker,
Id = 1
};
ToolBar = new CommandID(Guids.guidGitHubToolbarCmdSet, PkgCmdIDList.idGitHubToolbar);
ToolBarLocation = (int)VSTWT_LOCATION.VSTWT_TOP;
}
public override bool SearchEnabled => true;
protected override void Initialize()
{
// Using JoinableTaskFactory from parent AsyncPackage. That way if VS shuts down before this
// work is done, we won't risk crashing due to arbitrary work going on in background threads.
var asyncPackage = (AsyncPackage)Package;
viewModelTask = asyncPackage.JoinableTaskFactory.RunAsync(() => InitializeAsync(asyncPackage));
}
public Task<IGitHubPaneViewModel> GetViewModelAsync() => viewModelTask.JoinAsync();
async Task<IGitHubPaneViewModel> InitializeAsync(AsyncPackage asyncPackage)
{
try
{
ShowInitializing();
// Allow MEF to initialize its cache asynchronously
var provider = (IGitHubServiceProvider)await asyncPackage.GetServiceAsync(typeof(IGitHubServiceProvider));
var teServiceHolder = provider.GetService<ITeamExplorerServiceHolder>();
teServiceHolder.ServiceProvider = this;
var factory = provider.GetService<IViewViewModelFactory>();
var viewModel = provider.ExportProvider.GetExportedValue<IGitHubPaneViewModel>();
await viewModel.InitializeAsync(this);
View = factory.CreateView<IGitHubPaneViewModel>();
View.DataContext = viewModel;
return viewModel;
}
catch (Exception e)
{
ShowError(e);
throw;
}
}
[SuppressMessage("Microsoft.Design", "CA1061:DoNotHideBaseClassMethods", Justification = "WTF CA, I'm overriding!")]
public override IVsSearchTask CreateSearch(uint dwCookie, IVsSearchQuery pSearchQuery, IVsSearchCallback pSearchCallback)
{
var pane = View?.DataContext as IGitHubPaneViewModel;
if (pane != null)
{
return new SearchTask(pane, dwCookie, pSearchQuery, pSearchCallback);
}
return null;
}
public override void ClearSearch()
{
var pane = View?.DataContext as IGitHubPaneViewModel;
if (pane != null)
{
pane.SearchQuery = null;
}
}
public override void OnToolWindowCreated()
{
base.OnToolWindowCreated();
Marshal.ThrowExceptionForHR(((IVsWindowFrame)Frame)?.SetProperty(
(int)__VSFPROPID5.VSFPROPID_SearchPlacement,
__VSSEARCHPLACEMENT.SP_STRETCH) ?? 0);
var pane = View?.DataContext as IGitHubPaneViewModel;
UpdateSearchHost(pane?.IsSearchEnabled ?? false, pane?.SearchQuery);
}
void ShowInitializing()
{
// This page is intentionally left blank.
}
void ShowError(Exception e)
{
View = new TextBox
{
Text = e.ToString(),
IsReadOnly = true,
};
}
void UpdateSearchHost(bool enabled, string query)
{
if (SearchHost != null)
{
SearchHost.IsEnabled = enabled;
if (SearchHost.SearchQuery?.SearchString != query)
{
SearchHost.SearchAsync(query != null ? new SearchQuery(query) : null);
}
}
}
class SearchTask : VsSearchTask
{
readonly IGitHubPaneViewModel viewModel;
public SearchTask(
IGitHubPaneViewModel viewModel,
uint dwCookie,
IVsSearchQuery pSearchQuery,
IVsSearchCallback pSearchCallback)
: base(dwCookie, pSearchQuery, pSearchCallback)
{
this.viewModel = viewModel;
}
protected override void OnStartSearch()
{
viewModel.SearchQuery = SearchQuery.SearchString;
base.OnStartSearch();
}
protected override void OnStopSearch() => viewModel.SearchQuery = null;
}
class SearchQuery : IVsSearchQuery
{
public SearchQuery(string query)
{
SearchString = query;
}
public uint ParseError => 0;
public string SearchString { get; }
public uint GetTokens(uint dwMaxTokens, IVsSearchToken[] rgpSearchTokens) => 0;
}
}
}
| 33.986111 | 129 | 0.586841 | [
"MIT"
] | 1587257781/VisualStudio | src/GitHub.VisualStudio/UI/GitHubPane.cs | 7,343 | C# |
using System;
using System.Data;
using System.Data.SqlClient;
namespace Insql.SqlServer
{
internal class SqlServerSessionFactory : IDbSessionFactory
{
private readonly DbContextOptions contextOptions;
private readonly IDbConnection dbConnection;
private readonly string connectionString;
private readonly SqlCredential connectionCredential;
public SqlServerSessionFactory(DbContextOptions contextOptions, IDbConnection dbConnection)
{
if (contextOptions == null)
{
throw new ArgumentNullException(nameof(contextOptions));
}
if (dbConnection == null)
{
throw new ArgumentNullException(nameof(dbConnection));
}
this.contextOptions = contextOptions;
this.dbConnection = dbConnection;
}
public SqlServerSessionFactory(DbContextOptions contextOptions, string connectionString)
{
if (contextOptions == null)
{
throw new ArgumentNullException(nameof(contextOptions));
}
if (string.IsNullOrWhiteSpace(connectionString))
{
throw new ArgumentNullException(nameof(connectionString));
}
this.contextOptions = contextOptions;
this.connectionString = connectionString;
}
public SqlServerSessionFactory(DbContextOptions contextOptions, string connectionString, SqlCredential connectionCredential)
{
if (contextOptions == null)
{
throw new ArgumentNullException(nameof(contextOptions));
}
if (string.IsNullOrWhiteSpace(connectionString))
{
throw new ArgumentNullException(nameof(connectionString));
}
this.contextOptions = contextOptions;
this.connectionString = connectionString;
this.connectionCredential = connectionCredential;
}
public IDbSession CreateSession()
{
if (this.dbConnection != null)
{
return new DbSession(this.dbConnection, false)
{
CommandTimeout = this.contextOptions.CommandTimeout,
};
}
if (this.connectionCredential != null)
{
return new DbSession(new SqlConnection(connectionString, connectionCredential), true)
{
CommandTimeout = this.contextOptions.CommandTimeout,
};
}
return new DbSession(new SqlConnection(connectionString), true)
{
CommandTimeout = this.contextOptions.CommandTimeout,
};
}
}
}
| 32.744186 | 132 | 0.589134 | [
"MIT"
] | rainrcn/insql | src/Insql/SqlServer/SqlServerSessionFactory.cs | 2,818 | C# |
namespace Bb.Sdk.Decompiler.IlParser
{
using System;
/// <summary>
/// IFormatProvider
/// </summary>
public interface IFormatProvider
{
/// <summary>
/// Arguments the specified ordinal.
/// </summary>
/// <param name="ordinal">The ordinal.</param>
/// <returns></returns>
string Argument(int ordinal);
/// <summary>
/// Escapeds the string.
/// </summary>
/// <param name="str">The string.</param>
/// <returns></returns>
string EscapedString(string str);
/// <summary>
/// Int16s to hexadecimal.
/// </summary>
/// <param name="int16">The int16.</param>
/// <returns></returns>
string Int16ToHex(int int16);
/// <summary>
/// Int32s to hexadecimal.
/// </summary>
/// <param name="int32">The int32.</param>
/// <returns></returns>
string Int32ToHex(int int32);
/// <summary>
/// Int8s to hexadecimal.
/// </summary>
/// <param name="int8">The int8.</param>
/// <returns></returns>
string Int8ToHex(int int8);
/// <summary>
/// Labels the specified offset.
/// </summary>
/// <param name="offset">The offset.</param>
/// <returns></returns>
string Label(int offset);
/// <summary>
/// Multiples the labels.
/// </summary>
/// <param name="offsets">The offsets.</param>
/// <returns></returns>
string MultipleLabels(int[] offsets);
/// <summary>
/// Sigs the byte array to string.
/// </summary>
/// <param name="sig">The sig.</param>
/// <returns></returns>
string SigByteArrayToString(byte[] sig);
}
}
| 26.478261 | 54 | 0.501916 | [
"BSD-3-Clause"
] | Black-Beard-Sdk/Decompile | src/Black.Beard.Sdk.Decompiler/Decompiler/IlParser/IFormatProvider.cs | 1,827 | C# |
using Microsoft.AspNetCore.Mvc;
using PokemonDb.Models;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace PokemonDb.Controllers
{
public class TrainersController : Controller
{
private readonly PokemonDbContext _db;
public TrainersController(PokemonDbContext db)
{
_db = db;
}
public ActionResult Index()
{
List<Trainer> model = _db.Trainers.ToList();
return View(model);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Trainer trainer)
{
_db.Trainers.Add(trainer);
_db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult Details(int id)
{
Trainer thisTrainer = _db.Trainers.FirstOrDefault(trainer => trainer.TrainerId == id);
return View(thisTrainer);
}
public ActionResult Edit(int id)
{
var thisTrainer = _db.Trainers.FirstOrDefault(trainer => trainer.TrainerId == id);
return View(thisTrainer);
}
[HttpPost]
public ActionResult Edit(Trainer trainer)
{
_db.Entry(trainer).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult Delete(int id)
{
var thisTrainer = _db.Trainers.FirstOrDefault(trainer => trainer.TrainerId == id);
return View(thisTrainer);
}
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
var thisTrainer = _db.Trainers.FirstOrDefault(trainer => trainer.TrainerId == id);
_db.Trainers.Remove(thisTrainer);
_db.SaveChanges();
return RedirectToAction("Index");
}
}
} | 27.513889 | 98 | 0.580515 | [
"MIT"
] | agatakolohe/Pokemon.Solution | PokemonDb/Controllers/TrainersController.cs | 1,981 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Microsoft.eShopWeb.ApplicationCore.Interfaces
{
public interface IBasketService
{
Task<int> GetBasketItemCountAsync(string userName);
Task TransferBasketAsync(string anonymousId, string userName);
Task AddItemToBasket(int basketId, int catalogItemId, decimal price, int quantity = 1);
Task SetQuantities(int basketId, Dictionary<string, int> quantities);
Task DeleteBasketAsync(int basketId);
}
}
| 33.375 | 95 | 0.73221 | [
"MIT"
] | fabianamrferreira/eShopOnWeb | src/ApplicationCore/Interfaces/IBasketService.cs | 536 | C# |
using System;
namespace CheapLevel
{
internal static class Program
{
[STAThread]
public static int Main(string[] args)
{
if (args.Length == 2)
{
if (!MainWindow.Extract(null, args[0], args[1]))
{
return 1;
}
}
else
{
new App().Run();
}
return 0;
}
}
}
| 17.961538 | 64 | 0.357602 | [
"Unlicense"
] | spadapet/cheaplevel | CheapLevel/Main.cs | 469 | C# |
using System;
namespace AspNetCoreIdentityExample.Domain.Entities
{
public class User
{
public string Id { get; set; }
public int AccessFailedCount { get; set; }
public string ConcurrencyStamp { get; set; }
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public bool LockoutEnabled { get; set; }
public DateTimeOffset? LockoutEnd { get; set; }
public string NormalizedEmail { get; set; }
public string NormalizedUserName { get; set; }
public string PasswordHash { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public string SecurityStamp { get; set; }
public bool TwoFactorEnabled { get; set; }
public string UserName { get; set; }
}
}
| 35.416667 | 55 | 0.625882 | [
"MIT"
] | execution/ASP.NET-Core-Identity-Example | AspNetCoreIdentityExample/AspNetCoreIdentityExample.Domain/Entities/User.cs | 852 | C# |
using eCommerceStarterCode.Data;
using eCommerceStarterCode.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace eCommerceStarterCode.Controllers
{
[Route("api/product")]
[ApiController]
public class ProductController : ControllerBase
{
private ApplicationDbContext _context;
public ProductController(ApplicationDbContext context)
{
_context = context;
}
//GET
[HttpGet]
public IActionResult Get()
{
var products = _context.Products.Include("Category").Include("User");
return Ok(products);
}
//GET BY ID
[HttpGet("{id}")]
public IActionResult Get(int id)
{
var products = _context.Products.FirstOrDefault(product => product.ProductID == id);
if (products == null)
{
return NotFound();
}
return Ok(products);
}
//POST NEW PRODUCT
[HttpPost]
public IActionResult Post([FromBody] Product value)
{
_context.Products.Add(value);
_context.SaveChanges();
return Ok(value);
}
//PUT
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody]Product value)
{
var product = _context.Products.FirstOrDefault(product => product.ProductID == id);
product.Name = value.Name;
product.Price = value.Price;
product.Description = value.Description;
product.AverageRating = value.AverageRating;
product.CategoryID = value.CategoryID;
_context.SaveChanges();
return Ok(product);
}
// DELETE
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
var product = _context.Products.FirstOrDefault(product => product.ProductID == id);
_context.Remove(product);
_context.SaveChanges();
return Ok();
}
}
}
| 27.222222 | 96 | 0.579592 | [
"MIT"
] | Daleyar/Themed-eCommerce- | eCommerceStarterCode/Controllers/ProductController.cs | 2,207 | C# |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// KoubeiMarketingDataIsvShopQueryModel Data Structure.
/// </summary>
[Serializable]
public class KoubeiMarketingDataIsvShopQueryModel : AlipayObject
{
/// <summary>
/// 门店ID列表(单次最多查询100个门店)
/// </summary>
[JsonProperty("shop_ids")]
public List<string> ShopIds { get; set; }
}
}
| 24.55 | 68 | 0.653768 | [
"MIT"
] | gebiWangshushu/payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/KoubeiMarketingDataIsvShopQueryModel.cs | 523 | C# |
#pragma checksum "..\..\Filter.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "80B9BA3285E1C2E1755A58DC03D23B09A88318EC045A1874AD0C9694EEB326E1"
//------------------------------------------------------------------------------
// <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>
//------------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
using ToDoListUI;
namespace ToDoListUI {
/// <summary>
/// Filter
/// </summary>
public partial class Filter : System.Windows.Window, System.Windows.Markup.IComponentConnector {
#line 10 "..\..\Filter.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ListBox ListName;
#line default
#line hidden
#line 11 "..\..\Filter.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ListBox ListDate;
#line default
#line hidden
#line 12 "..\..\Filter.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ListBox ListStatu;
#line default
#line hidden
#line 13 "..\..\Filter.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button btnListStatusOne;
#line default
#line hidden
#line 14 "..\..\Filter.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button btnListStatusZero;
#line default
#line hidden
#line 15 "..\..\Filter.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button btnListTASC;
#line default
#line hidden
#line 16 "..\..\Filter.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button btnListTDES;
#line default
#line hidden
#line 17 "..\..\Filter.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button btnMainMenu;
#line default
#line hidden
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/ToDoListUI;component/filter.xaml", System.UriKind.Relative);
#line 1 "..\..\Filter.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
switch (connectionId)
{
case 1:
this.ListName = ((System.Windows.Controls.ListBox)(target));
return;
case 2:
this.ListDate = ((System.Windows.Controls.ListBox)(target));
return;
case 3:
this.ListStatu = ((System.Windows.Controls.ListBox)(target));
return;
case 4:
this.btnListStatusOne = ((System.Windows.Controls.Button)(target));
#line 13 "..\..\Filter.xaml"
this.btnListStatusOne.Click += new System.Windows.RoutedEventHandler(this.btnListStatusOne_Click);
#line default
#line hidden
return;
case 5:
this.btnListStatusZero = ((System.Windows.Controls.Button)(target));
#line 14 "..\..\Filter.xaml"
this.btnListStatusZero.Click += new System.Windows.RoutedEventHandler(this.btnListStatusZero_Click);
#line default
#line hidden
return;
case 6:
this.btnListTASC = ((System.Windows.Controls.Button)(target));
#line 15 "..\..\Filter.xaml"
this.btnListTASC.Click += new System.Windows.RoutedEventHandler(this.btnListTASC_Click);
#line default
#line hidden
return;
case 7:
this.btnListTDES = ((System.Windows.Controls.Button)(target));
#line 16 "..\..\Filter.xaml"
this.btnListTDES.Click += new System.Windows.RoutedEventHandler(this.btnListTDES_Click);
#line default
#line hidden
return;
case 8:
this.btnMainMenu = ((System.Windows.Controls.Button)(target));
#line 17 "..\..\Filter.xaml"
this.btnMainMenu.Click += new System.Windows.RoutedEventHandler(this.btnMainMenu_Click);
#line default
#line hidden
return;
}
this._contentLoaded = true;
}
}
}
| 37.675127 | 145 | 0.612234 | [
"MIT"
] | Gestotudor/WPF_ToDoList | ToDoListUI/obj/Debug/Filter.g.cs | 7,424 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// Generated by Xsd2Code. Version 3.4.0.32989
// <NameSpace>NFe.NET</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>True</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>False</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net40</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>True</OrderXMLAttrib><EnableEncoding>True</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>True</GenerateShouldSerialize><DisableDebug>True</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>True</EnableInitializeFields>
// </auto-generated>
// ------------------------------------------------------------------------------
namespace NFCerta.NFe.Schemas.DownloadNFe
{
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.IO;
using System.Text;
using System.Xml;
using NFCerta.NFe.Schemas.TiposBasicos;
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.portalfiscal.inf.br/nfe")]
[System.Xml.Serialization.XmlRootAttribute("downloadNFe", Namespace = "http://www.portalfiscal.inf.br/nfe", IsNullable = false)]
public partial class TDownloadNFe
{
[EditorBrowsable(EditorBrowsableState.Never)]
private AmbienteSefaz tpAmbField;
[EditorBrowsable(EditorBrowsableState.Never)]
private TDownloadNFeXServ xServField;
[EditorBrowsable(EditorBrowsableState.Never)]
private string cNPJField;
[EditorBrowsable(EditorBrowsableState.Never)]
private string[] chNFeField;
[EditorBrowsable(EditorBrowsableState.Never)]
private TVerDownloadNFe versaoField;
private static System.Xml.Serialization.XmlSerializer serializer;
[System.Xml.Serialization.XmlElementAttribute(Order = 0)]
public AmbienteSefaz tpAmb
{
get
{
return this.tpAmbField;
}
set
{
this.tpAmbField = value;
}
}
[System.Xml.Serialization.XmlElementAttribute(Order = 1)]
public TDownloadNFeXServ xServ
{
get
{
return this.xServField;
}
set
{
this.xServField = value;
}
}
[System.Xml.Serialization.XmlElementAttribute(Order = 2)]
public string CNPJ
{
get
{
return this.cNPJField;
}
set
{
this.cNPJField = value;
}
}
[System.Xml.Serialization.XmlElementAttribute("chNFe", Order = 3)]
public string[] chNFe
{
get
{
return this.chNFeField;
}
set
{
this.chNFeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public TVerDownloadNFe versao
{
get
{
return this.versaoField;
}
set
{
this.versaoField = value;
}
}
private static System.Xml.Serialization.XmlSerializer Serializer
{
get
{
if ((serializer == null))
{
serializer = new System.Xml.Serialization.XmlSerializer(typeof(TDownloadNFe));
}
return serializer;
}
}
#region Serialize/Deserialize
/// <summary>
/// Serializes current TDownloadNFe object into an XML document
/// </summary>
/// <returns>string XML value</returns>
public virtual string Serialize(System.Text.Encoding encoding)
{
System.IO.StreamReader streamReader = null;
System.IO.MemoryStream memoryStream = null;
try
{
memoryStream = new System.IO.MemoryStream();
System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings();
xmlWriterSettings.Encoding = encoding;
System.Xml.XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings);
Serializer.Serialize(xmlWriter, this);
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
streamReader = new System.IO.StreamReader(memoryStream);
return streamReader.ReadToEnd();
}
finally
{
if ((streamReader != null))
{
streamReader.Dispose();
}
if ((memoryStream != null))
{
memoryStream.Dispose();
}
}
}
public virtual string Serialize()
{
return Serialize(Encoding.UTF8);
}
/// <summary>
/// Deserializes workflow markup into an TDownloadNFe object
/// </summary>
/// <param name="xml">string workflow markup to deserialize</param>
/// <param name="obj">Output TDownloadNFe object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool Deserialize(string xml, out TDownloadNFe obj, out System.Exception exception)
{
exception = null;
obj = default(TDownloadNFe);
try
{
obj = Deserialize(xml);
return true;
}
catch (System.Exception ex)
{
exception = ex;
return false;
}
}
public static bool Deserialize(string xml, out TDownloadNFe obj)
{
System.Exception exception = null;
return Deserialize(xml, out obj, out exception);
}
public static TDownloadNFe Deserialize(string xml)
{
System.IO.StringReader stringReader = null;
try
{
stringReader = new System.IO.StringReader(xml);
return ((TDownloadNFe)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
}
finally
{
if ((stringReader != null))
{
stringReader.Dispose();
}
}
}
/// <summary>
/// Serializes current TDownloadNFe object into file
/// </summary>
/// <param name="fileName">full path of outupt xml file</param>
/// <param name="exception">output Exception value if failed</param>
/// <returns>true if can serialize and save into file; otherwise, false</returns>
public virtual bool SaveToFile(string fileName, System.Text.Encoding encoding, out System.Exception exception)
{
exception = null;
try
{
SaveToFile(fileName, encoding);
return true;
}
catch (System.Exception e)
{
exception = e;
return false;
}
}
public virtual bool SaveToFile(string fileName, out System.Exception exception)
{
return SaveToFile(fileName, Encoding.UTF8, out exception);
}
public virtual void SaveToFile(string fileName)
{
SaveToFile(fileName, Encoding.UTF8);
}
public virtual void SaveToFile(string fileName, System.Text.Encoding encoding)
{
System.IO.StreamWriter streamWriter = null;
try
{
string xmlString = Serialize(encoding);
streamWriter = new System.IO.StreamWriter(fileName, false, Encoding.UTF8);
streamWriter.WriteLine(xmlString);
streamWriter.Close();
}
finally
{
if ((streamWriter != null))
{
streamWriter.Dispose();
}
}
}
/// <summary>
/// Deserializes xml markup from file into an TDownloadNFe object
/// </summary>
/// <param name="fileName">string xml file to load and deserialize</param>
/// <param name="obj">Output TDownloadNFe object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool LoadFromFile(string fileName, System.Text.Encoding encoding, out TDownloadNFe obj, out System.Exception exception)
{
exception = null;
obj = default(TDownloadNFe);
try
{
obj = LoadFromFile(fileName, encoding);
return true;
}
catch (System.Exception ex)
{
exception = ex;
return false;
}
}
public static bool LoadFromFile(string fileName, out TDownloadNFe obj, out System.Exception exception)
{
return LoadFromFile(fileName, Encoding.UTF8, out obj, out exception);
}
public static bool LoadFromFile(string fileName, out TDownloadNFe obj)
{
System.Exception exception = null;
return LoadFromFile(fileName, out obj, out exception);
}
public static TDownloadNFe LoadFromFile(string fileName)
{
return LoadFromFile(fileName, Encoding.UTF8);
}
public static TDownloadNFe LoadFromFile(string fileName, System.Text.Encoding encoding)
{
System.IO.FileStream file = null;
System.IO.StreamReader sr = null;
try
{
file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
sr = new System.IO.StreamReader(file, encoding);
string xmlString = sr.ReadToEnd();
sr.Close();
file.Close();
return Deserialize(xmlString);
}
finally
{
if ((file != null))
{
file.Dispose();
}
if ((sr != null))
{
sr.Dispose();
}
}
}
#endregion
}
//[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.33440")]
//[System.SerializableAttribute()]
//[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.portalfiscal.inf.br/nfe")]
//public enum TAmb
//{
// /// <remarks/>
// [System.Xml.Serialization.XmlEnumAttribute("1")]
// Item1,
// /// <remarks/>
// [System.Xml.Serialization.XmlEnumAttribute("2")]
// Item2,
//}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.portalfiscal.inf.br/nfe")]
public enum TDownloadNFeXServ
{
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("DOWNLOAD NFE")]
DOWNLOADNFE,
}
//[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.33440")]
//[System.SerializableAttribute()]
//[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.portalfiscal.inf.br/nfe")]
//public enum TVerDownloadNFe
//{
// /// <remarks/>
// [System.Xml.Serialization.XmlEnumAttribute("1.00")]
// Item100,
//}
}
| 36.353591 | 1,351 | 0.571429 | [
"MIT"
] | nfcerta/NFCerta.NFe | src/NFCerta.NFe/Schemas/DownloadNFe/downloadNFe_v1.00.designer.cs | 13,160 | C# |
using NodeCanvas.Framework;
using ParadoxNotion;
using ParadoxNotion.Design;
namespace NodeCanvas.Tasks.Conditions
{
[Category("Everland Games")]
public class IsEntityHealthFull : ConditionTask
{
[RequiredField]
public BBParameter<Entity> entity = default;
protected override bool OnCheck()
{
return entity.value.Health.IsFullHealth;
}
}
} | 23.944444 | 53 | 0.638051 | [
"MIT"
] | DanielEverland/project-tuba-public | Assets/AI/Scripts/Node Canvas/Conditions/IsEntityHealthFull.cs | 433 | C# |
//
// Copyright 2015 Blu Age Corporation - Plano, Texas
//
// 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.
// This file has been modified.
// Original copyright notice :
/*
* Copyright 2006-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace Summer.Batch.Infrastructure.Item
{
/// <summary>
/// A base exception class that all exceptions thrown from an ITemWriter extend.
/// </summary>
[Serializable]
public class ItemWriterException : Exception
{
/// <summary>
/// Create a new ItemWriterException based on a message and another exception.
/// </summary>
/// <param name="message"></param>
/// <param name="exception"></param>
public ItemWriterException(string message, Exception exception) : base(message, exception) { }
/// <summary>
/// Create a new ItemWriterException based on a message.
/// </summary>
/// <param name="message"></param>
public ItemWriterException(string message) : base(message) { }
}
} | 38.368421 | 103 | 0.66941 | [
"Apache-2.0"
] | Andrey-Ostapenko/SummerBatch | Summer.Batch.Infrastructure/Item/ItemWriterException.cs | 2,189 | C# |
namespace _02._02.Number_Checker
{
using System;
public class NumberChecker
{
public static void Main()
{
string enteredNumber = Console.ReadLine();
Console.WriteLine(enteredNumber.Contains(".")? "floating-point" : "integer");
}
}
}
| 20.2 | 89 | 0.577558 | [
"MIT"
] | spzvtbg/02-Tech-modul | Fundamental task solutions/06.Data Types and Variables - More Exercises/02.02. Number Checker/NumberChecker.cs | 305 | C# |
using NBitcoin;
using System;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Blockchain.TransactionBuilding;
using WalletWasabi.Blockchain.Transactions;
using WalletWasabi.Gui.Helpers;
using WalletWasabi.Gui.Models.StatusBarStatuses;
using WalletWasabi.Gui.ViewModels;
using WalletWasabi.Hwi;
using WalletWasabi.Hwi.Exceptions;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class SendTabViewModel : SendControlViewModel
{
public override string DoButtonText => "Send Transaction";
public override string DoingButtonText => "Sending Transaction...";
public SendTabViewModel(WalletViewModel walletViewModel) : base(walletViewModel, "Send")
{
}
protected override async Task DoAfterBuildTransaction(BuildTransactionResult result)
{
MainWindowViewModel.Instance.StatusBar.TryAddStatus(StatusType.SigningTransaction);
SmartTransaction signedTransaction = result.Transaction;
if (IsHardwareWallet && !result.Signed) // If hardware but still has a privkey then it's password, then meh.
{
try
{
IsHardwareBusy = true;
MainWindowViewModel.Instance.StatusBar.TryAddStatus(StatusType.AcquiringSignatureFromHardwareWallet);
var client = new HwiClient(Global.Network);
using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(3));
PSBT signedPsbt = null;
try
{
signedPsbt = await client.SignTxAsync(KeyManager.MasterFingerprint.Value, result.Psbt, cts.Token);
}
catch (HwiException)
{
await PinPadViewModel.UnlockAsync();
signedPsbt = await client.SignTxAsync(KeyManager.MasterFingerprint.Value, result.Psbt, cts.Token);
}
signedTransaction = signedPsbt.ExtractSmartTransaction(result.Transaction);
}
catch (Exception ex)
{
NotificationHelpers.Error(ex.ToUserFriendlyString());
return;
}
finally
{
MainWindowViewModel.Instance.StatusBar.TryRemoveStatus(StatusType.AcquiringSignatureFromHardwareWallet);
IsHardwareBusy = false;
}
}
MainWindowViewModel.Instance.StatusBar.TryAddStatus(StatusType.BroadcastingTransaction);
await Task.Run(async () => await Global.TransactionBroadcaster.SendTransactionAsync(signedTransaction));
ResetUi();
}
}
}
| 32.768116 | 111 | 0.764264 | [
"MIT"
] | adamlaska/WalletWasabi | WalletWasabi.Gui/Controls/WalletExplorer/SendTabViewModel.cs | 2,261 | C# |
/*
-- GENERATED BY NetCMS-Cli v0.1.0 BUILD 1200 --
Created on 7/21/2021 9:56:29 PM
Repos CLI: https://github.com/OpenCodeDev/OpenCodeDev.NetCMS.Compiler
License: MIT
Author: Max Samson
Company: OpenCodeDev
*/
using ProtoBuf.Grpc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Grpc.Core;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
// Shared Resources
using OpenCodeDev.NetCms.Shared.Api.Recipe.Controllers;
using OpenCodeDev.NetCms.Shared.Api.Recipe.Models;
using OpenCodeDev.NetCms.Shared.Api.Recipe.Messages;
// Server Resources
using OpenCodeDev.NetCMS.MyPlugin.Server.Database;
using OpenCodeDev.NetCMS.MyPlugin.Server.Api.Recipe.Services;
using OpenCodeDev.NetCMS.MyPlugin.Server.Api.Recipe.Models;
// NetCMS Core Sever
using OpenCodeDev.NetCMS.Core.Server.Extensions;
namespace OpenCodeDev.NetCMS.MyPlugin.Server.Api.Recipe.Controllers
{
/// <summary>
/// This class provides you with fully functional common api CRUD logic.<br/>
/// You can also inherit this class and override the logic to use your own custom logic. (Not Recommended)
/// </summary>
public class RecipeController
{
public virtual async Task<RecipePublicModel> Create(RecipeCreateRequest request, CallContext context = default)
{
var provider = context.ServerCallContext.GetHttpContext().RequestServices;
var db = provider.GetRequiredService<ApiDatabase>();
var newEntry = new RecipeModel() {
Name = request.Name,
Duration = request.Duration
};
db.Add(newEntry);
await db.SaveChangesAsync();
return newEntry;
}
public virtual async Task<RecipePublicModel> Delete(RecipeDeleteRequest request, CallContext context = default)
{
var provider = context.ServerCallContext.GetHttpContext().RequestServices;
var db = provider.GetRequiredService<ApiDatabase>();
var result = db.Recipe.Where(p => p.Id.Equals(request.Id)).FirstOrDefault();
if (result != null) { db.Recipe.Remove(result); }
else{
throw new RpcException(new Status(StatusCode.NotFound, "Cannot delete because entry wasn't found."));
}
await db.SaveChangesAsync();
return result;
}
public virtual async Task<List<RecipePublicModel>> Fetch(RecipeFetchRequest request, CallContext context = default)
{
var provider = context.ServerCallContext.GetHttpContext().RequestServices;
var db = provider.GetRequiredService<ApiDatabase>();
var result = db.Recipe
.WhereConditionsMet(request.Conditions)
.OrderByMatching(request.OrderBy)
.Take(request.Limit).Select(p=>(RecipePublicModel)p).ToList();
return result;
}
public virtual async Task<RecipePublicModel> FetchOne(RecipeFetchOneRequest request, CallContext context = default)
{
var provider = context.ServerCallContext.GetHttpContext().RequestServices;
var db = provider.GetRequiredService<ApiDatabase>();
var result = db.Recipe.Where(p => p.Id.Equals(request.Id)).FirstOrDefault();
if (result == null)
{
throw new RpcException(new Status(StatusCode.NotFound, $"Cannot find {request.Id} because entry wasn't found."));
}
return result;
}
public virtual async Task<RecipePublicModel> Update(RecipeUpdateOneRequest request, CallContext context = default)
{
var provider = context.ServerCallContext.GetHttpContext().RequestServices;
var db = provider.GetRequiredService<ApiDatabase>();
var myService = provider.GetRequiredService<RecipeMyService>();
var updating = db.Recipe.Where(p => p.Id.Equals(request.Id)).FirstOrDefault();
if(updating == null){
throw new RpcException(new Status(StatusCode.NotFound, $"Cannot update {request.Id} because entry wasn't found."));
}
updating.Name = request.Name;
updating.Duration = request.Duration;
// updating = myService.FilterUpdateReferences(db, updating, request);
db.Recipe.Add(updating);
await db.SaveChangesAsync();
return (RecipePublicModel)updating;
}
}
}
| 40.918182 | 131 | 0.666296 | [
"MIT"
] | OpenCodeDev/OpenCodeDev.NetCMS.Plugin | Server/_netcms_/_cs_files_/OpenCodeDev.NetCMS.MyPlugin.Server.Api.Recipe.Services.RecipeController.cs | 4,501 | C# |
[CompilerGeneratedAttribute] // RVA: 0x137890 Offset: 0x137991 VA: 0x137890
private sealed class ShortcutExtensions.<>c__DisplayClass39_0 // TypeDefIndex: 4974
{
// Fields
public Transform target; // 0x10
// Methods
// RVA: 0x19F5480 Offset: 0x19F5581 VA: 0x19F5480
public void .ctor() { }
// RVA: 0x19FB5F0 Offset: 0x19FB6F1 VA: 0x19FB5F0
internal Vector3 <DOLocalMoveZ>b__0() { }
// RVA: 0x19FB610 Offset: 0x19FB711 VA: 0x19FB610
internal void <DOLocalMoveZ>b__1(Vector3 x) { }
}
| 26.105263 | 83 | 0.735887 | [
"MIT"
] | SinsofSloth/RF5-global-metadata | _no_namespace/ShortcutExtensions.----c__DisplayClass39_0.cs | 496 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace StdProject
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Application.Current.MainWindow = this;
}
private void startButton_Click(object sender, RoutedEventArgs e)
{
ChangeView(new Students());
}
private void ChangeView(Page view)
{
mainFrame.NavigationService.Navigate(view);
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
MessageBoxResult key = MessageBox.Show("Are you sure you want to quit?", "Confirm", MessageBoxButton.OKCancel, MessageBoxImage.Question);
e.Cancel = (key == MessageBoxResult.Cancel);
}
}
}
| 27.302326 | 149 | 0.677172 | [
"MIT"
] | Lena341/StudentProject | StdProject/MainWindow.xaml.cs | 1,176 | C# |
namespace Plus.Communication.Packets.Incoming.Rooms.AI.Bots
{
using System;
using System.Drawing;
using HabboHotel.GameClients;
using HabboHotel.Rooms;
using HabboHotel.Users.Inventory.Bots;
using Outgoing.Inventory.Bots;
internal class PickUpBotEvent : IPacketEvent
{
public void Parse(GameClient session, ClientPacket packet)
{
if (!session.GetHabbo().InRoom)
{
return;
}
var botId = packet.PopInt();
if (botId == 0)
{
return;
}
var room = session.GetHabbo().CurrentRoom;
if (room == null)
{
return;
}
RoomUser botUser;
if (!room.GetRoomUserManager().TryGetBot(botId, out botUser))
{
return;
}
if (session.GetHabbo().Id != botUser.BotData.OwnerId && !session.GetHabbo().GetPermissions().HasRight("bot_place_any_override"))
{
session.SendWhisper("You can only pick up your own bots!");
return;
}
using (var dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
{
dbClient.SetQuery("UPDATE `bots` SET `room_id` = '0' WHERE `id` = @id LIMIT 1");
dbClient.AddParameter("id", botId);
dbClient.RunQuery();
}
room.GetGameMap().RemoveUserFromMap(botUser, new Point(botUser.X, botUser.Y));
session.GetHabbo().GetInventoryComponent().TryAddBot(new Bot(Convert.ToInt32(botUser.BotData.Id), Convert.ToInt32(botUser.BotData.OwnerId), botUser.BotData.Name,
botUser.BotData.Motto, botUser.BotData.Look, botUser.BotData.Gender));
session.SendPacket(new BotInventoryComposer(session.GetHabbo().GetInventoryComponent().GetBots()));
room.GetRoomUserManager().RemoveBot(botUser.VirtualId, false);
}
}
} | 34.931034 | 173 | 0.569102 | [
"Apache-2.0"
] | dotsudo/plus-clean | Communication/Packets/Incoming/Rooms/AI/Bots/PickUpBotEvent.cs | 2,028 | C# |
using RumahScarlett.Presentation.Views.Barang;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RumahScarlett.Presentation.Presenters.Barang
{
public interface IBarangPresenter : IBasePresenter<IBarangView>
{
}
}
| 21.5 | 66 | 0.803987 | [
"MIT"
] | izhal27/rumah_scarlett | src/RumahScarlett/RumahScarlett.Presentation/Presenters/Barang/IBarangPresenter.cs | 303 | C# |
using System;
using System.Security.Cryptography;
using System.Text;
namespace EasyAbp.Abp.WeChat.MiniProgram.Infrastructure
{
public static class AesHelper
{
public static string AesDecrypt(string inputData, string iv, string key)
{
var encryptedData = Convert.FromBase64String(inputData.Replace(" ", "+"));
var rijndaelCipher = new RijndaelManaged
{
Key = Convert.FromBase64String(key.Replace(" ", "+")),
IV = Convert.FromBase64String(iv.Replace(" ", "+")),
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7
};
var transform = rijndaelCipher.CreateDecryptor();
var plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
return Encoding.UTF8.GetString(plainText);
}
}
} | 33.464286 | 98 | 0.579509 | [
"MIT"
] | EasyAbp/Abp.WeChat | src/MiniProgram/EasyAbp.Abp.WeChat.MiniProgram/Infrastructure/AesHelper.cs | 939 | C# |
using System;
namespace Kifa {
public static class TimeSpanExtensions {
public static TimeSpan Or(this TimeSpan timeSpan, TimeSpan orTimeSpan) =>
timeSpan == TimeSpan.Zero ? orTimeSpan : timeSpan;
}
}
| 25.555556 | 81 | 0.682609 | [
"MIT"
] | Kimi-Arthur/KifaNet | src/Kifa/Extensions/TimeSpanExtensions.cs | 230 | C# |
using RazzleServer.Common.Util;
using RazzleServer.Game.Maple.Characters;
using RazzleServer.Game.Maple.Scripting;
namespace RazzleServer.Game.Scripts.Commands
{
public sealed class NoticeCommand : ACommandScript
{
public override string Name => "notice";
public override string Parameters => "{ -map | -channel | -world } message";
public override bool IsRestricted => true;
public override void Execute(GameCharacter caller, string[] args)
{
if (args.Length < 2)
{
ShowSyntax(caller);
}
else
{
var message = args.Fuse(1);
switch (args[0].ToLower())
{
case "-map":
caller.Map.Send(GamePackets.Notify(message));
break;
case "-channel":
caller.Client.Server.Send(GamePackets.Notify(message));
break;
case "-world":
caller.Client.Server.World.Send(GamePackets.Notify(message));
break;
default:
ShowSyntax(caller);
break;
}
}
}
}
}
| 28.12766 | 85 | 0.473525 | [
"MIT"
] | Bia10/RazzleServer | RazzleServer.Game/Scripts/Commands/NoticeCommand.cs | 1,324 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc.ModelBinding;
using Microsoft.AspNet.Mvc;
namespace System.Web.Http
{
/// <summary>
/// An action result that returns a <see cref="System.Net.HttpStatusCode.BadRequest"/> response and performs
/// content negotiation on an <see cref="HttpError"/> based on a <see cref="ModelStateDictionary"/>.
/// </summary>
public class InvalidModelStateResult : ObjectResult
{
/// <summary>Initializes a new instance of the <see cref="InvalidModelStateResult"/> class.</summary>
/// <param name="modelState">The model state to include in the error.</param>
/// <param name="includeErrorDetail">
/// <see langword="true"/> if the error should include exception messages; otherwise, <see langword="false"/>.
/// </param>
public InvalidModelStateResult([NotNull] ModelStateDictionary modelState, bool includeErrorDetail)
: base(new HttpError(modelState, includeErrorDetail))
{
ModelState = modelState;
IncludeErrorDetail = includeErrorDetail;
}
/// <summary>
/// Gets the model state to include in the error.
/// </summary>
public ModelStateDictionary ModelState { get; private set; }
/// <summary>
/// Gets a value indicating whether the error should include exception messages.
/// </summary>
public bool IncludeErrorDetail { get; private set; }
/// <inheritdoc />
public override async Task ExecuteResultAsync(ActionContext context)
{
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
await base.ExecuteResultAsync(context);
}
}
} | 42.456522 | 118 | 0.665643 | [
"Apache-2.0"
] | ardalis/Mvc | src/Microsoft.AspNet.Mvc.WebApiCompatShim/ActionResults/InvalidModelStateResult.cs | 1,955 | C# |
using System;
using System.Runtime.Serialization;
namespace ICSharpCode.SharpZipLib.Tar
{
[Serializable]
public class InvalidHeaderException : TarException
{
protected InvalidHeaderException(SerializationInfo information, StreamingContext context) : base(information, context)
{
}
public InvalidHeaderException()
{
}
public InvalidHeaderException(string message) : base(message)
{
}
public InvalidHeaderException(string message, Exception exception) : base(message, exception)
{
}
}
}
| 19.884615 | 120 | 0.765957 | [
"MIT"
] | moto2002/jiandangjianghu | src/ICSharpCode.SharpZipLib.Tar/InvalidHeaderException.cs | 517 | C# |
using System;
namespace _08._Beer_Kegs
{
class Program
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
double volume = 0;
double biggestVolume = 0;
string bestModel = string.Empty;
for (int i = 0; i < n; i++)
{
string model = Console.ReadLine();
double radius = double.Parse(Console.ReadLine());
int height = int.Parse(Console.ReadLine());
volume = Math.PI * Math.Pow(radius,2) * height;
if (volume > biggestVolume)
{
biggestVolume = volume;
bestModel = model;
}
}
Console.WriteLine(bestModel);
}
}
}
| 27.354839 | 66 | 0.439858 | [
"MIT"
] | GeorgiGradev/SoftUni | 02. Programming Fundamentals/02.02. Data Types and Variables - Exercise/08. Beer Kegs/Program.cs | 850 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void CompareEqualScalar_Vector64_Single()
{
var test = new SimpleBinaryOpTest__CompareEqualScalar_Vector64_Single();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareEqualScalar_Vector64_Single
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if (
(alignment != 16 && alignment != 8)
|| (alignment * 2) < sizeOfinArray1
|| (alignment * 2) < sizeOfinArray2
|| (alignment * 2) < sizeOfoutArray
)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(
ref Unsafe.AsRef<byte>(inArray1Ptr),
ref Unsafe.As<Single, byte>(ref inArray1[0]),
(uint)sizeOfinArray1
);
Unsafe.CopyBlockUnaligned(
ref Unsafe.AsRef<byte>(inArray2Ptr),
ref Unsafe.As<Single, byte>(ref inArray2[0]),
(uint)sizeOfinArray2
);
}
public void* inArray1Ptr =>
Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr =>
Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr =>
Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Single> _fld1;
public Vector64<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++)
{
_data1[i] = TestLibrary.Generator.GetSingle();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector64<Single>, byte>(ref testStruct._fld1),
ref Unsafe.As<Single, byte>(ref _data1[0]),
(uint)Unsafe.SizeOf<Vector64<Single>>()
);
for (var i = 0; i < Op2ElementCount; i++)
{
_data2[i] = TestLibrary.Generator.GetSingle();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector64<Single>, byte>(ref testStruct._fld2),
ref Unsafe.As<Single, byte>(ref _data2[0]),
(uint)Unsafe.SizeOf<Vector64<Single>>()
);
return testStruct;
}
public void RunStructFldScenario(
SimpleBinaryOpTest__CompareEqualScalar_Vector64_Single testClass
)
{
var result = AdvSimd.Arm64.CompareEqualScalar(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(
SimpleBinaryOpTest__CompareEqualScalar_Vector64_Single testClass
)
{
fixed (Vector64<Single>* pFld1 = &_fld1)
fixed (Vector64<Single>* pFld2 = &_fld2)
{
var result = AdvSimd.Arm64.CompareEqualScalar(
AdvSimd.LoadVector64((Single*)(pFld1)),
AdvSimd.LoadVector64((Single*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount =
Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount =
Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single);
private static readonly int RetElementCount =
Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector64<Single> _clsVar1;
private static Vector64<Single> _clsVar2;
private Vector64<Single> _fld1;
private Vector64<Single> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__CompareEqualScalar_Vector64_Single()
{
for (var i = 0; i < Op1ElementCount; i++)
{
_data1[i] = TestLibrary.Generator.GetSingle();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar1),
ref Unsafe.As<Single, byte>(ref _data1[0]),
(uint)Unsafe.SizeOf<Vector64<Single>>()
);
for (var i = 0; i < Op2ElementCount; i++)
{
_data2[i] = TestLibrary.Generator.GetSingle();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar2),
ref Unsafe.As<Single, byte>(ref _data2[0]),
(uint)Unsafe.SizeOf<Vector64<Single>>()
);
}
public SimpleBinaryOpTest__CompareEqualScalar_Vector64_Single()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++)
{
_data1[i] = TestLibrary.Generator.GetSingle();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector64<Single>, byte>(ref _fld1),
ref Unsafe.As<Single, byte>(ref _data1[0]),
(uint)Unsafe.SizeOf<Vector64<Single>>()
);
for (var i = 0; i < Op2ElementCount; i++)
{
_data2[i] = TestLibrary.Generator.GetSingle();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector64<Single>, byte>(ref _fld2),
ref Unsafe.As<Single, byte>(ref _data2[0]),
(uint)Unsafe.SizeOf<Vector64<Single>>()
);
for (var i = 0; i < Op1ElementCount; i++)
{
_data1[i] = TestLibrary.Generator.GetSingle();
}
for (var i = 0; i < Op2ElementCount; i++)
{
_data2[i] = TestLibrary.Generator.GetSingle();
}
_dataTable = new DataTable(
_data1,
_data2,
new Single[RetElementCount],
LargestVectorSize
);
}
public bool IsSupported => AdvSimd.Arm64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Arm64.CompareEqualScalar(
Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Arm64.CompareEqualScalar(
AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd.Arm64)
.GetMethod(
nameof(AdvSimd.Arm64.CompareEqualScalar),
new Type[] { typeof(Vector64<Single>), typeof(Vector64<Single>) }
)
.Invoke(
null,
new object[]
{
Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr)
}
);
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd.Arm64)
.GetMethod(
nameof(AdvSimd.Arm64.CompareEqualScalar),
new Type[] { typeof(Vector64<Single>), typeof(Vector64<Single>) }
)
.Invoke(
null,
new object[]
{
AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr))
}
);
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.CompareEqualScalar(_clsVar1, _clsVar2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Single>* pClsVar1 = &_clsVar1)
fixed (Vector64<Single>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.Arm64.CompareEqualScalar(
AdvSimd.LoadVector64((Single*)(pClsVar1)),
AdvSimd.LoadVector64((Single*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr);
var result = AdvSimd.Arm64.CompareEqualScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr));
var result = AdvSimd.Arm64.CompareEqualScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__CompareEqualScalar_Vector64_Single();
var result = AdvSimd.Arm64.CompareEqualScalar(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__CompareEqualScalar_Vector64_Single();
fixed (Vector64<Single>* pFld1 = &test._fld1)
fixed (Vector64<Single>* pFld2 = &test._fld2)
{
var result = AdvSimd.Arm64.CompareEqualScalar(
AdvSimd.LoadVector64((Single*)(pFld1)),
AdvSimd.LoadVector64((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Arm64.CompareEqualScalar(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Single>* pFld1 = &_fld1)
fixed (Vector64<Single>* pFld2 = &_fld2)
{
var result = AdvSimd.Arm64.CompareEqualScalar(
AdvSimd.LoadVector64((Single*)(pFld1)),
AdvSimd.LoadVector64((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.CompareEqualScalar(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.CompareEqualScalar(
AdvSimd.LoadVector64((Single*)(&test._fld1)),
AdvSimd.LoadVector64((Single*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(
Vector64<Single> op1,
Vector64<Single> op2,
void* result,
[CallerMemberName] string method = ""
)
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Single, byte>(ref outArray[0]),
ref Unsafe.AsRef<byte>(result),
(uint)Unsafe.SizeOf<Vector64<Single>>()
);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(
void* op1,
void* op2,
void* result,
[CallerMemberName] string method = ""
)
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Single, byte>(ref inArray1[0]),
ref Unsafe.AsRef<byte>(op1),
(uint)Unsafe.SizeOf<Vector64<Single>>()
);
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Single, byte>(ref inArray2[0]),
ref Unsafe.AsRef<byte>(op2),
(uint)Unsafe.SizeOf<Vector64<Single>>()
);
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Single, byte>(ref outArray[0]),
ref Unsafe.AsRef<byte>(result),
(uint)Unsafe.SizeOf<Vector64<Single>>()
);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(
Single[] left,
Single[] right,
Single[] result,
[CallerMemberName] string method = ""
)
{
bool succeeded = true;
if (
BitConverter.SingleToInt32Bits(Helpers.CompareEqual(left[0], right[0]))
!= BitConverter.SingleToInt32Bits(result[0])
)
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != 0)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation(
$"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.CompareEqualScalar)}<Single>(Vector64<Single>, Vector64<Single>): {method} failed:"
);
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation(
$" result: ({string.Join(", ", result)})"
);
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 37.373494 | 151 | 0.543762 | [
"MIT"
] | belav/runtime | src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/CompareEqualScalar.Vector64.Single.cs | 24,816 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThreeSidedCoin : MonoBehaviour {
public float thresholdVelocity;
public float angleAccuracy;
public GameObject Statistics;
bool hasHitTable;
bool hasReportedPosition;
Rigidbody body;
// Use this for initialization
void Start () {
body = GetComponent<Rigidbody>();
hasHitTable = false;
}
// Update is called once per frame
void Update () {
if (hasHitTable && !hasReportedPosition && body.velocity.magnitude < thresholdVelocity)
{
float angle = Vector3.Angle(Vector3.up, transform.up);
hasReportedPosition = true;
if (compareAngle(angle, 0f))
{
Debug.Log("Heads");
Statistics.SendMessage("Heads");
}
else if (compareAngle(angle, 180f))
{
Debug.Log("Tails");
Statistics.SendMessage("Tails");
}
else if (compareAngle(angle, 90f))
{
Debug.Log("Side");
Statistics.SendMessage("Side");
}
else
{
Debug.Log("Unknown");
Statistics.SendMessage("Unknown");
}
Destroy(gameObject);
}
}
void HitTable()
{
hasHitTable = true;
}
private bool compareAngle(float angle, float comparison)
{
return comparison - angleAccuracy < angle && comparison + angleAccuracy > angle;
}
void OutOfBounds()
{
Debug.Log("Unknown");
Statistics.SendMessage("Unknown");
Destroy(gameObject);
}
}
| 23.310811 | 95 | 0.547246 | [
"MIT"
] | stuart/ThreeUp | Assets/Scripts/ThreeSidedCoin.cs | 1,727 | C# |
// Generated by SharpKit.QooxDoo.Generator
using System;
using System.Collections.Generic;
using SharpKit.Html;
using SharpKit.JavaScript;
namespace qx.ui.mobile.list.renderer
{
/// <summary>
/// <para>Base class for all list item renderer.</para>
/// </summary>
[JsType(JsMode.Prototype, Name = "qx.ui.mobile.list.renderer.Abstract", OmitOptionalParameters = true, Export = false)]
public abstract partial class Abstract : qx.ui.mobile.container.Composite
{
#region Properties
/// <summary>
/// <para>Whether the widget can be activated or not. When the widget is activated
/// a css class active is automatically added to the widget, which
/// can indicate the acitvation status.</para>
/// </summary>
[JsProperty(Name = "activatable", NativeField = true)]
public bool Activatable { get; set; }
/// <summary>
/// <para>The default CSS class used for this widget. The default CSS class
/// should contain the common appearance of the widget.
/// It is set to the container element of the widget. Use <see cref="AddCssClass"/>
/// to enhance the default appearance of the widget.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "defaultCssClass", NativeField = true)]
public string DefaultCssClass { get; set; }
/// <summary>
/// <para>Whether the row is selectable.</para>
/// </summary>
[JsProperty(Name = "selectable", NativeField = true)]
public bool Selectable { get; set; }
/// <summary>
/// <para>Whether the row is selected.</para>
/// </summary>
[JsProperty(Name = "selected", NativeField = true)]
public bool Selected { get; set; }
/// <summary>
/// <para>Whether to show an arrow in the row.</para>
/// </summary>
[JsProperty(Name = "showArrow", NativeField = true)]
public bool ShowArrow { get; set; }
#endregion Properties
#region Methods
public Abstract() { throw new NotImplementedException(); }
public Abstract(object layout) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the row index of a certain DOM element in the list.</para>
/// </summary>
/// <param name="element">DOM element to retrieve the index from.</param>
/// <returns>the index of the row.</returns>
[JsMethod(Name = "getRowIndex")]
public double GetRowIndex(qx.html.Element element) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the row index of a certain DOM element in the list from the given event.</para>
/// </summary>
/// <param name="evt">The causing event.</param>
/// <returns>the index of the row.</returns>
[JsMethod(Name = "getRowIndexFromEvent")]
public double GetRowIndexFromEvent(qx.eventx.type.Event evt) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property selectable.</para>
/// </summary>
[JsMethod(Name = "getSelectable")]
public bool GetSelectable() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property selected.</para>
/// </summary>
[JsMethod(Name = "getSelected")]
public bool GetSelected() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property showArrow.</para>
/// </summary>
[JsMethod(Name = "getShowArrow")]
public bool GetShowArrow() { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property selectable
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property selectable.</param>
[JsMethod(Name = "initSelectable")]
public void InitSelectable(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property selected
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property selected.</param>
[JsMethod(Name = "initSelected")]
public void InitSelected(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property showArrow
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property showArrow.</param>
[JsMethod(Name = "initShowArrow")]
public void InitShowArrow(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property selectable equals true.</para>
/// </summary>
[JsMethod(Name = "isSelectable")]
public void IsSelectable() { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property selected equals true.</para>
/// </summary>
[JsMethod(Name = "isSelected")]
public void IsSelected() { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property showArrow equals true.</para>
/// </summary>
[JsMethod(Name = "isShowArrow")]
public void IsShowArrow() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets all defined child widgets. Override this method in your custom
/// list item renderer and reset all widgets displaying data. Needed as the
/// renderer is used for every row and otherwise data of a different row
/// might be displayed, when not all data displaying widgets are used for the row.
/// Gets called automatically by the <see cref="qx.ui.mobile.list.provider.Provider"/>.</para>
/// </summary>
[JsMethod(Name = "reset")]
public void Reset() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property selectable.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetSelectable")]
public void ResetSelectable() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property selected.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetSelected")]
public void ResetSelected() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property showArrow.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetShowArrow")]
public void ResetShowArrow() { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property selectable.</para>
/// </summary>
/// <param name="value">New value for property selectable.</param>
[JsMethod(Name = "setSelectable")]
public void SetSelectable(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property selected.</para>
/// </summary>
/// <param name="value">New value for property selected.</param>
[JsMethod(Name = "setSelected")]
public void SetSelected(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property showArrow.</para>
/// </summary>
/// <param name="value">New value for property showArrow.</param>
[JsMethod(Name = "setShowArrow")]
public void SetShowArrow(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property selectable.</para>
/// </summary>
[JsMethod(Name = "toggleSelectable")]
public void ToggleSelectable() { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property selected.</para>
/// </summary>
[JsMethod(Name = "toggleSelected")]
public void ToggleSelected() { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property showArrow.</para>
/// </summary>
[JsMethod(Name = "toggleShowArrow")]
public void ToggleShowArrow() { throw new NotImplementedException(); }
#endregion Methods
}
} | 40.700461 | 120 | 0.693841 | [
"MIT"
] | SharpKit/SharpKit-SDK | Defs/Qooxdoo/ui/mobile/list/renderer/Abstract.cs | 8,832 | C# |
using AutoMapper;
using Computerstore.Tests.RepositoryTests;
using ComputerStore.Api.Controllers;
using ComputerStore.Api.Repositories;
using ComputerStore.Api.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace Computerstore.Tests.ControllerTests
{
public class ControllerTest : RepositoryTestBase
{
#region - Private Properties -
private IMapper _mapper;
#endregion
#region - Constructor -
public ControllerTest()
{
// automapper configuration
var config = new AutoMapper.MapperConfiguration(cfg =>
{
cfg.AddProfile(new AutoMapperProfileConfiguration());
});
_mapper = config.CreateMapper();
}
#endregion
[Fact]
public async void TestPcPartControllerGetALl()
{
// arrange
var repo = new PcPartRepository(_context, _mapper);
var controller = new PcPartsController(repo);
// act
var result = await controller.Get();
// assert
var objectResult = Assert.IsType<OkObjectResult>(result);
Assert.Equal(StatusCodes.Status200OK, objectResult.StatusCode);
}
[Fact]
public async void TestPcPartControllerGetById()
{
// arrange
var repo = new PcPartRepository(_context, _mapper);
var controller = new PcPartsController(repo);
// act
var result = await controller.Get(1);
// assert
var objectResult = Assert.IsType<OkObjectResult>(result);
Assert.Equal(StatusCodes.Status200OK, objectResult.StatusCode);
}
[Fact]
public async void TestPcPartControllerParts()
{
// arrange
var repo = new PcPartRepository(_context, _mapper);
var controller = new PcPartsController(repo);
// act
var result = await controller.PartById();
// assert
var objectResult = Assert.IsType<OkObjectResult>(result);
Assert.Equal(StatusCodes.Status200OK, objectResult.StatusCode);
}
[Fact]
public async void TestPcPartControllerGetPartByPcPartId()
{
// arrange
var repo = new PcPartRepository(_context, _mapper);
var controller = new PcPartsController(repo);
// act
var result = await controller.PartByPartId(4);
// assert
var objectResult = Assert.IsType<OkObjectResult>(result);
Assert.Equal(StatusCodes.Status200OK, objectResult.StatusCode);
}
[Fact]
public void TestPcPartControllerGetCategories()
{
// arrange
var repo = new PcPartRepository(_context, _mapper);
var controller = new PcPartsController(repo);
// act
var result = controller.Categories();
// assert
var objectResult = Assert.IsType<OkObjectResult>(result);
Assert.Equal(StatusCodes.Status200OK, objectResult.StatusCode);
}
[Fact]
public async void TestPcPartControllerCategoryByName()
{
// arrange
var repo = new PcPartRepository(_context, _mapper);
var controller = new PcPartsController(repo);
// act
var result = await controller.CategoryByName("Gpu");
// assert
var objectResult = Assert.IsType<OkObjectResult>(result);
Assert.Equal(StatusCodes.Status200OK, objectResult.StatusCode);
}
[Fact]
public async void TestPcPartControllerBasicById()
{
// arrange
var repo = new PcPartRepository(_context, _mapper);
var controller = new PcPartsController(repo);
// act
var result = await controller.BasicById(4);
// assert
var objectResult = Assert.IsType<OkObjectResult>(result);
Assert.Equal(StatusCodes.Status200OK, objectResult.StatusCode);
}
[Fact]
public async void TestPcPartControllerImageByFileName()
{
// arrange
var repo = new PcPartRepository(_context, _mapper);
var controller = new PcPartsController(repo);
var contentType = "image/jpeg" ;
// act
var result = controller.ImageByFileName("amd_ryzen_5.jpg");
// assert
var objectResult = Assert.IsType<PhysicalFileResult>(result);
Assert.Equal(contentType, objectResult.ContentType);
}
}
}
| 29.166667 | 75 | 0.595102 | [
"MIT"
] | moesac0970/ComputerStore | Computerstore.Tests/ControllerTests/ControllerTest.cs | 4,902 | C# |
// 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.
namespace Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201
{
using Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="Server" />
/// </summary>
public partial class ServerTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>.
/// </returns>
public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue);
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="Server"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="Server" /> type, otherwise <c>false</c>
/// </returns>
public static bool CanConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return true;
}
global::System.Type type = sourceValue.GetType();
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
// we say yest to PSObjects
return true;
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
// we say yest to Hashtables/dictionaries
return true;
}
try
{
if (null != sourceValue.ToJsonString())
{
return true;
}
}
catch
{
// Not one of our objects
}
try
{
string text = sourceValue.ToString()?.Trim();
return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>
/// an instance of <see cref="Server" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="Server" />.</param>
/// <returns>
/// an instance of <see cref="Server" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.IServer ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.IServer).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return Server.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return Server.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return Server.DeserializeFromDictionary(sourceValue);
}
return null;
}
/// <summary>NotImplemented -- this will return <c>null</c></summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>will always return <c>null</c>.</returns>
public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null;
}
} | 50.979592 | 251 | 0.583533 | [
"MIT"
] | Agazoth/azure-powershell | src/PostgreSql/generated/api/Models/Api20171201/Server.TypeConverter.cs | 7,348 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using GraphX.PCL.Common;
using GraphX.PCL.Common.Exceptions;
using GraphX.PCL.Common.Interfaces;
using GraphX.PCL.Common.Models;
using QuickGraph;
#if WPF
using System.Windows;
#elif METRO
using Windows.UI.Xaml;
#endif
namespace GraphX.Controls.Models
{
public class StateStorage<TVertex, TEdge, TGraph>: IDisposable
where TEdge : class, IGraphXEdge<TVertex>
where TVertex: class, IGraphXVertex
where TGraph: class, IMutableBidirectionalGraph<TVertex, TEdge>
{
private readonly Dictionary<string, GraphState<TVertex, TEdge, TGraph>> _states;
private GraphArea<TVertex, TEdge, TGraph> _area;
public StateStorage(GraphArea<TVertex, TEdge, TGraph> area)
{
_area = area;
_states = new Dictionary<string, GraphState<TVertex, TEdge, TGraph>>();
}
/// <summary>
/// Returns true if state with supplied ID exists in the current states collection
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public bool ContainsState(string id)
{
return _states.ContainsKey(id);
}
/// <summary>
/// Save current graph state into memory (including visual and data controls)
/// </summary>
/// <param name="id">New unique state id</param>
/// <param name="description">Optional state description</param>
public virtual void SaveState(string id, string description = "")
{
_states.Add(id, GenerateGraphState(id, description));
}
/// <summary>
/// Save current graph state into memory (including visual and data controls) or update existing state
/// </summary>
/// <param name="id">State id</param>
/// <param name="description">Optional state description</param>
public virtual void SaveOrUpdateState(string id, string description = "")
{
if (ContainsState(id))
_states[id] = GenerateGraphState(id, description);
else SaveState(id, description);
}
protected virtual GraphState<TVertex, TEdge, TGraph> GenerateGraphState(string id, string description = "")
{
if (_area.LogicCore == null)
throw new GX_InvalidDataException("LogicCore -> Not initialized!");
var vposlist = _area.VertexList.ToDictionary(item => item.Key, item => item.Value.GetPositionGraphX());
var vedgelist = (from item in _area.EdgesList where item.Value.Visibility == Visibility.Visible select item.Key).ToList();
return new GraphState<TVertex, TEdge, TGraph>(id, _area.LogicCore.Graph, _area.LogicCore.AlgorithmStorage, vposlist, vedgelist, description);
}
/// <summary>
/// Import specified state to the StateStorage
/// </summary>
/// <param name="key">State key</param>
/// <param name="state">State object</param>
public virtual void ImportState(string key, GraphState<TVertex, TEdge, TGraph> state)
{
if (ContainsState(key))
throw new GX_ConsistencyException(string.Format("Graph state {0} already exist in state storage", key));
//if(!unsafeImport && (_area.LogicCore == null || _area.LogicCore.Graph == null || _area.LogicCore.Graph != state.Graph))
// throw new GX_ConsistencyException("Can't validate that imported graph state belong to the target area Graph! You can try to import the state with unsafeImport parameter set to True.");
_states.Add(key, state);
}
/// <summary>
/// Load previously saved state into layout
/// </summary>
/// <param name="id">Unique state id</param>
public virtual void LoadState(string id)
{
if (_area.LogicCore == null)
throw new GX_InvalidDataException("GraphArea.LogicCore -> Not initialized!");
if (!_states.ContainsKey(id))
{
Debug.WriteLine(string.Format("LoadState() -> State id {0} not found! Skipping...", id));
return;
}
// _area.RemoveAllVertices();
// _area.RemoveAllEdges();
//One action: clear all, preload vertices, assign Graph property
_area.PreloadVertexes(_states[id].Graph, true, true);
_area.LogicCore.Graph = _states[id].Graph;
_area.LogicCore.AlgorithmStorage = _states[id].AlgorithmStorage;
//setup vertex positions
foreach (var item in _states[id].VertexPositions)
{
_area.VertexList[item.Key].SetPosition(item.Value.X, item.Value.Y);
_area.VertexList[item.Key].SetCurrentValue(GraphAreaBase.PositioningCompleteProperty, true);
}
//setup visible edges
foreach (var item in _states[id].VisibleEdges)
{
var edgectrl = _area.ControlFactory.CreateEdgeControl(_area.VertexList[item.Source], _area.VertexList[item.Target],
item);
_area.InsertEdge(item, edgectrl);
//edgectrl.UpdateEdge();
}
_area.UpdateLayout();
foreach (var item in _area.EdgesList.Values)
{
item.UpdateEdge();
}
}
/// <summary>
/// Remove state by id
/// </summary>
/// <param name="id">Unique state id</param>
public virtual void RemoveState(string id)
{
if (_states.ContainsKey(id))
_states.Remove(id);
}
/// <summary>
/// Get all states from the storage
/// </summary>
public virtual Dictionary<string, GraphState<TVertex, TEdge, TGraph>> GetStates()
{
return _states;
}
/// <summary>
/// Get all states from the storage
/// </summary>
/// <param name="id">Unique state id</param>
public virtual GraphState<TVertex, TEdge, TGraph> GetState(string id)
{
return ContainsState(id) ? _states[id] : null;
}
public virtual void Dispose()
{
_states.ForEach(a=> a.Value.Dispose());
_states.Clear();
_area = null;
}
}
} | 39.150602 | 202 | 0.588552 | [
"Apache-2.0"
] | anh123minh/MyWPFApp | GraphX.Controls/Models/StateStorage.cs | 6,501 | C# |
using UnityEngine;
public class TailPieceTimelineEventHandler : MonoBehaviour
{
GameObject _objectToActivate;
public void Initialize(GameObject tailPieceWCollider)
{
_objectToActivate = tailPieceWCollider;
}
// this will be called from timeline
public void ActivateTailPiece()
{
_objectToActivate.SetActive(true);
}
} | 19.647059 | 58 | 0.790419 | [
"Apache-2.0"
] | Game-Bubble/Run-Transformer | Assets/Scripts/TailPieceTimelineEventHandler.cs | 334 | C# |
// Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.0.6365, generator: {generator})
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Commvault.Powershell.Models
{
using Commvault.Powershell.Runtime.PowerShell;
/// <summary>Any object</summary>
[System.ComponentModel.TypeConverter(typeof(AnyTypeConverter))]
public partial class Any
{
/// <summary>
/// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the
/// object before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content);
/// <summary>
/// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content);
/// <summary>
/// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow);
/// <summary>
/// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Commvault.Powershell.Models.Any"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
internal Any(global::System.Collections.IDictionary content)
{
bool returnNow = false;
BeforeDeserializeDictionary(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
AfterDeserializeDictionary(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Commvault.Powershell.Models.Any"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
internal Any(global::System.Management.Automation.PSObject content)
{
bool returnNow = false;
BeforeDeserializePSObject(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
AfterDeserializePSObject(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Commvault.Powershell.Models.Any"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <returns>an instance of <see cref="Commvault.Powershell.Models.IAny" />.</returns>
public static Commvault.Powershell.Models.IAny DeserializeFromDictionary(global::System.Collections.IDictionary content)
{
return new Any(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Commvault.Powershell.Models.Any"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <returns>an instance of <see cref="Commvault.Powershell.Models.IAny" />.</returns>
public static Commvault.Powershell.Models.IAny DeserializeFromPSObject(global::System.Management.Automation.PSObject content)
{
return new Any(content);
}
/// <summary>
/// Creates a new instance of <see cref="Any" />, deserializing the content from a json string.
/// </summary>
/// <param name="jsonText">a string containing a JSON serialized instance of this model.</param>
/// <returns>an instance of the <see cref="className" /> model class.</returns>
public static Commvault.Powershell.Models.IAny FromJsonString(string jsonText) => FromJson(Commvault.Powershell.Runtime.Json.JsonNode.Parse(jsonText));
/// <summary>Serializes this instance to a json string.</summary>
/// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns>
public string ToJsonString() => ToJson(null, Commvault.Powershell.Runtime.SerializationMode.IncludeAll)?.ToString();
}
/// Any object
[System.ComponentModel.TypeConverter(typeof(AnyTypeConverter))]
public partial interface IAny
{
}
} | 52.171875 | 159 | 0.665019 | [
"MIT"
] | Commvault/CVPowershellSDKV2 | generated/api/Models/Any.PowerShell.cs | 6,678 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using FoxGame.UI;
using FoxGame.Utils;
using FoxGame.Asset;
public class PrepareView : BaseView,IMsgReceiver
{
public Text Content;
public Image Img;
public Button StartBtn;
public GameObject MsgBox;
public Button OkBtn;
public override ViewConfigData ViewData {
get {
if (this._viewCfgData == null) {
this._viewCfgData = new ViewConfigData();
this._viewCfgData._viewID = ViewID.PrepareView;
this._viewCfgData._isNavigation = true;
this._viewCfgData._mountLayer = ViewMountLayer.Fixed;
this._viewCfgData._layerSiblingIdx = 1;
}
return this._viewCfgData;
}
}
private void Awake() {
StartBtn.gameObject.SetActive(false);
Img.gameObject.SetActive(false);
MsgBox.SetActive(false);
StartBtn.onClick.AddListener(()=> {
GameMain.Instance.EnterGame();
});
OkBtn.onClick.AddListener(() => {
Application.Quit();
});
}
void OnEnable() {
MsgDispatcher.GetInstance().Subscribe(GameEvents.UpdateAsset.ShowUpdateAssetInfo, this);
MsgDispatcher.GetInstance().Subscribe(GameEvents.UpdateAsset.UpdateAssetFinish, this);
}
void OnDisable() {
MsgDispatcher.GetInstance().UnSubscribe(GameEvents.UpdateAsset.ShowUpdateAssetInfo, this);
MsgDispatcher.GetInstance().UnSubscribe(GameEvents.UpdateAsset.UpdateAssetFinish, this);
}
public bool OnMsgHandler(string msgName, params object[] args) {
switch (msgName) {
case GameEvents.UpdateAsset.ShowUpdateAssetInfo: {
//Content.text = (string)args[0];
}
break;
case GameEvents.UpdateAsset.UpdateAssetFinish: {
Content.text = "资源更新完成";
StartBtn.gameObject.SetActive(true);
Img.gameObject.SetActive(true);
}
break;
}
return true;
}
}
| 30.027778 | 98 | 0.608696 | [
"MIT"
] | FoxGame825/FoxGameToolKit | Assets/Scripts/GameLogic/UI/PrepareView.cs | 2,176 | C# |
using System;
namespace D_Parser.Dom
{
public interface ITypeDeclaration : ISyntaxRegion, IVisitable<TypeDeclarationVisitor>
{
new CodeLocation Location { get; set; }
new CodeLocation EndLocation { get; set; }
ITypeDeclaration InnerDeclaration { get; set; }
ITypeDeclaration InnerMost { get; set; }
/// <summary>
/// Used e.g. if it's known that a type declaration expresses a variable's name
/// </summary>
bool ExpressesVariableAccess { get; set; }
string ToString();
string ToString(bool IncludesBase);
R Accept<R>(TypeDeclarationVisitor<R> vis);
ulong GetHash();
}
public abstract class AbstractTypeDeclaration : ITypeDeclaration
{
public ITypeDeclaration InnerMost
{
get
{
if (InnerDeclaration == null)
return this;
else
return InnerDeclaration.InnerMost;
}
set
{
if (InnerDeclaration == null)
InnerDeclaration = value;
else
InnerDeclaration.InnerMost = value;
}
}
public ITypeDeclaration InnerDeclaration
{
get;
set;
}
public override string ToString()
{
return ToString(true);
}
public abstract string ToString(bool IncludesBase);
public static implicit operator String(AbstractTypeDeclaration d)
{
return d == null? null : d.ToString(false);
}
CodeLocation _loc=CodeLocation.Empty;
/// <summary>
/// The type declaration's start location.
/// If inner declaration given, its start location will be returned.
/// </summary>
public CodeLocation Location
{
get
{
if (_loc != CodeLocation.Empty || InnerDeclaration==null)
return _loc;
return InnerMost.Location;
}
set { _loc = value; }
}
/// <summary>
/// The actual start location without regarding inner declarations.
/// </summary>
public CodeLocation NonInnerTypeDependendLocation
{
get { return _loc; }
}
public CodeLocation EndLocation
{
get;
set;
}
public bool ExpressesVariableAccess
{
get;
set;
}
public abstract void Accept(TypeDeclarationVisitor vis);
public abstract R Accept<R>(TypeDeclarationVisitor<R> vis);
public virtual ulong GetHash()
{
return (ulong)ToString().GetHashCode();
}
}
}
| 19.900901 | 86 | 0.677682 | [
"Apache-2.0"
] | rainers/D_Parser | DParser2/Dom/AbstractTypeDeclaration.cs | 2,211 | C# |
namespace CaballaRE
{
partial class MainWindow
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.listBox1 = new System.Windows.Forms.ListBox();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.button3 = new System.Windows.Forms.Button();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.tabControl2 = new System.Windows.Forms.TabControl();
this.tabPage4 = new System.Windows.Forms.TabPage();
this.tabPage5 = new System.Windows.Forms.TabPage();
this.label2 = new System.Windows.Forms.Label();
this.trackBar1 = new System.Windows.Forms.TrackBar();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.listBox3 = new System.Windows.Forms.ListBox();
this.button13 = new System.Windows.Forms.Button();
this.button11 = new System.Windows.Forms.Button();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.button6 = new System.Windows.Forms.Button();
this.button5 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.tabPage3 = new System.Windows.Forms.TabPage();
this.label1 = new System.Windows.Forms.Label();
this.button10 = new System.Windows.Forms.Button();
this.button8 = new System.Windows.Forms.Button();
this.button12 = new System.Windows.Forms.Button();
this.textBox2 = new System.Windows.Forms.TextBox();
this.button9 = new System.Windows.Forms.Button();
this.listBox2 = new System.Windows.Forms.ListBox();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.button7 = new System.Windows.Forms.Button();
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripProgressBar1 = new System.Windows.Forms.ToolStripProgressBar();
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.xLSExcelToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.xMLToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.dATUnencryptedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.dATToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.iDXToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.tabControl2.SuspendLayout();
this.tabPage4.SuspendLayout();
this.tabPage5.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
this.tabPage2.SuspendLayout();
this.tabPage3.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.statusStrip1.SuspendLayout();
this.contextMenuStrip1.SuspendLayout();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(6, 6);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(84, 28);
this.button1.TabIndex = 0;
this.button1.Text = "Open NRI";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(457, 6);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(84, 28);
this.button2.TabIndex = 1;
this.button2.Text = "Extract Image";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// listBox1
//
this.listBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.listBox1.FormattingEnabled = true;
this.listBox1.Location = new System.Drawing.Point(6, 3);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(120, 264);
this.listBox1.TabIndex = 2;
this.listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged);
//
// pictureBox1
//
this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pictureBox1.Location = new System.Drawing.Point(132, 3);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(482, 264);
this.pictureBox1.TabIndex = 3;
this.pictureBox1.TabStop = false;
//
// button3
//
this.button3.Location = new System.Drawing.Point(6, 6);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(84, 28);
this.button3.TabIndex = 4;
this.button3.Text = "Open DAT";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// tabControl1
//
this.tabControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Controls.Add(this.tabPage3);
this.tabControl1.Location = new System.Drawing.Point(12, 12);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(645, 376);
this.tabControl1.TabIndex = 5;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.tabControl2);
this.tabPage1.Controls.Add(this.button13);
this.tabPage1.Controls.Add(this.button11);
this.tabPage1.Controls.Add(this.button1);
this.tabPage1.Controls.Add(this.button2);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(637, 350);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "NRI Viewer";
this.tabPage1.UseVisualStyleBackColor = true;
//
// tabControl2
//
this.tabControl2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tabControl2.Controls.Add(this.tabPage4);
this.tabControl2.Controls.Add(this.tabPage5);
this.tabControl2.Location = new System.Drawing.Point(6, 40);
this.tabControl2.Name = "tabControl2";
this.tabControl2.SelectedIndex = 0;
this.tabControl2.Size = new System.Drawing.Size(628, 304);
this.tabControl2.TabIndex = 6;
//
// tabPage4
//
this.tabPage4.Controls.Add(this.listBox1);
this.tabPage4.Controls.Add(this.pictureBox1);
this.tabPage4.Location = new System.Drawing.Point(4, 22);
this.tabPage4.Name = "tabPage4";
this.tabPage4.Padding = new System.Windows.Forms.Padding(3);
this.tabPage4.Size = new System.Drawing.Size(620, 278);
this.tabPage4.TabIndex = 0;
this.tabPage4.Text = "Images";
this.tabPage4.UseVisualStyleBackColor = true;
//
// tabPage5
//
this.tabPage5.Controls.Add(this.label2);
this.tabPage5.Controls.Add(this.trackBar1);
this.tabPage5.Controls.Add(this.pictureBox2);
this.tabPage5.Controls.Add(this.listBox3);
this.tabPage5.Location = new System.Drawing.Point(4, 22);
this.tabPage5.Name = "tabPage5";
this.tabPage5.Padding = new System.Windows.Forms.Padding(3);
this.tabPage5.Size = new System.Drawing.Size(620, 278);
this.tabPage5.TabIndex = 1;
this.tabPage5.Text = "Animations";
this.tabPage5.UseVisualStyleBackColor = true;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(129, 3);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(112, 13);
this.label2.TabIndex = 3;
this.label2.Text = "No animation selected";
//
// trackBar1
//
this.trackBar1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.trackBar1.Location = new System.Drawing.Point(129, 222);
this.trackBar1.Name = "trackBar1";
this.trackBar1.Size = new System.Drawing.Size(485, 45);
this.trackBar1.TabIndex = 2;
this.trackBar1.TickStyle = System.Windows.Forms.TickStyle.TopLeft;
this.trackBar1.Scroll += new System.EventHandler(this.trackBar1_Scroll);
//
// pictureBox2
//
this.pictureBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pictureBox2.Location = new System.Drawing.Point(129, 19);
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.Size = new System.Drawing.Size(485, 197);
this.pictureBox2.TabIndex = 1;
this.pictureBox2.TabStop = false;
//
// listBox3
//
this.listBox3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.listBox3.FormattingEnabled = true;
this.listBox3.Location = new System.Drawing.Point(3, 3);
this.listBox3.Name = "listBox3";
this.listBox3.Size = new System.Drawing.Size(120, 264);
this.listBox3.TabIndex = 0;
this.listBox3.SelectedIndexChanged += new System.EventHandler(this.listBox3_SelectedIndexChanged);
//
// button13
//
this.button13.Location = new System.Drawing.Point(547, 6);
this.button13.Name = "button13";
this.button13.Size = new System.Drawing.Size(84, 28);
this.button13.TabIndex = 5;
this.button13.Text = "Extract All";
this.button13.UseVisualStyleBackColor = true;
this.button13.Click += new System.EventHandler(this.button13_Click);
//
// button11
//
this.button11.Location = new System.Drawing.Point(96, 6);
this.button11.Name = "button11";
this.button11.Size = new System.Drawing.Size(100, 28);
this.button11.TabIndex = 4;
this.button11.Text = "Decompress File";
this.button11.UseVisualStyleBackColor = true;
this.button11.Click += new System.EventHandler(this.button11_Click);
//
// tabPage2
//
this.tabPage2.Controls.Add(this.button6);
this.tabPage2.Controls.Add(this.button5);
this.tabPage2.Controls.Add(this.button4);
this.tabPage2.Controls.Add(this.textBox1);
this.tabPage2.Controls.Add(this.button3);
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
this.tabPage2.Size = new System.Drawing.Size(637, 350);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "DAT Viewer";
this.tabPage2.UseVisualStyleBackColor = true;
//
// button6
//
this.button6.Location = new System.Drawing.Point(186, 6);
this.button6.Name = "button6";
this.button6.Size = new System.Drawing.Size(105, 28);
this.button6.TabIndex = 8;
this.button6.Text = "Export XML";
this.button6.UseVisualStyleBackColor = true;
this.button6.Click += new System.EventHandler(this.button6_Click);
//
// button5
//
this.button5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button5.Location = new System.Drawing.Point(547, 6);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(84, 28);
this.button5.TabIndex = 7;
this.button5.Text = "Display";
this.button5.UseVisualStyleBackColor = true;
this.button5.Click += new System.EventHandler(this.button5_Click);
//
// button4
//
this.button4.Location = new System.Drawing.Point(96, 6);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(84, 28);
this.button4.TabIndex = 6;
this.button4.Text = "Export";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// textBox1
//
this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBox1.Location = new System.Drawing.Point(3, 40);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textBox1.Size = new System.Drawing.Size(628, 304);
this.textBox1.TabIndex = 5;
//
// tabPage3
//
this.tabPage3.Controls.Add(this.label1);
this.tabPage3.Controls.Add(this.button10);
this.tabPage3.Controls.Add(this.button8);
this.tabPage3.Controls.Add(this.button12);
this.tabPage3.Controls.Add(this.textBox2);
this.tabPage3.Controls.Add(this.button9);
this.tabPage3.Controls.Add(this.listBox2);
this.tabPage3.Controls.Add(this.dataGridView1);
this.tabPage3.Controls.Add(this.button7);
this.tabPage3.Location = new System.Drawing.Point(4, 22);
this.tabPage3.Name = "tabPage3";
this.tabPage3.Padding = new System.Windows.Forms.Padding(3);
this.tabPage3.Size = new System.Drawing.Size(637, 350);
this.tabPage3.TabIndex = 2;
this.tabPage3.Text = "LibConfig Editor";
this.tabPage3.UseVisualStyleBackColor = true;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(188, 38);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(70, 13);
this.label1.TabIndex = 11;
this.label1.Text = "Table: (none)";
//
// button10
//
this.button10.Location = new System.Drawing.Point(316, 6);
this.button10.Name = "button10";
this.button10.Size = new System.Drawing.Size(114, 23);
this.button10.TabIndex = 10;
this.button10.Text = "Localization Helper";
this.button10.UseVisualStyleBackColor = true;
this.button10.Click += new System.EventHandler(this.button10_Click);
//
// button8
//
this.button8.Location = new System.Drawing.Point(221, 6);
this.button8.Name = "button8";
this.button8.Size = new System.Drawing.Size(89, 23);
this.button8.TabIndex = 9;
this.button8.Text = "Import Table";
this.button8.UseVisualStyleBackColor = true;
this.button8.Click += new System.EventHandler(this.button8_Click);
//
// button12
//
this.button12.Location = new System.Drawing.Point(126, 6);
this.button12.Name = "button12";
this.button12.Size = new System.Drawing.Size(89, 23);
this.button12.TabIndex = 8;
this.button12.Text = "Update Table";
this.button12.UseVisualStyleBackColor = true;
this.button12.Click += new System.EventHandler(this.button12_Click);
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(6, 35);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(176, 20);
this.textBox2.TabIndex = 7;
this.textBox2.TextChanged += new System.EventHandler(this.textBox2_TextChanged);
//
// button9
//
this.button9.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button9.Location = new System.Drawing.Point(550, 6);
this.button9.Name = "button9";
this.button9.Size = new System.Drawing.Size(81, 23);
this.button9.TabIndex = 4;
this.button9.Text = "Export";
this.button9.UseVisualStyleBackColor = true;
this.button9.Paint += new System.Windows.Forms.PaintEventHandler(this.button9_Paint);
this.button9.MouseDown += new System.Windows.Forms.MouseEventHandler(this.button9_MouseDown);
//
// listBox2
//
this.listBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.listBox2.FormattingEnabled = true;
this.listBox2.Location = new System.Drawing.Point(6, 61);
this.listBox2.Name = "listBox2";
this.listBox2.Size = new System.Drawing.Size(176, 277);
this.listBox2.TabIndex = 2;
this.listBox2.SelectedIndexChanged += new System.EventHandler(this.listBox2_SelectedIndexChanged);
//
// dataGridView1
//
this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(188, 61);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.Size = new System.Drawing.Size(443, 283);
this.dataGridView1.TabIndex = 1;
//
// button7
//
this.button7.Location = new System.Drawing.Point(6, 6);
this.button7.Name = "button7";
this.button7.Size = new System.Drawing.Size(114, 23);
this.button7.TabIndex = 0;
this.button7.Text = "Load LibConfig.xml";
this.button7.UseVisualStyleBackColor = true;
this.button7.Click += new System.EventHandler(this.button7_Click);
//
// statusStrip1
//
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabel1,
this.toolStripProgressBar1});
this.statusStrip1.Location = new System.Drawing.Point(0, 391);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(669, 22);
this.statusStrip1.TabIndex = 6;
this.statusStrip1.Text = "statusStrip1";
//
// toolStripStatusLabel1
//
this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
this.toolStripStatusLabel1.Size = new System.Drawing.Size(654, 17);
this.toolStripStatusLabel1.Spring = true;
this.toolStripStatusLabel1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// toolStripProgressBar1
//
this.toolStripProgressBar1.Name = "toolStripProgressBar1";
this.toolStripProgressBar1.Size = new System.Drawing.Size(100, 16);
this.toolStripProgressBar1.Visible = false;
//
// contextMenuStrip1
//
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.xLSExcelToolStripMenuItem,
this.xMLToolStripMenuItem,
this.dATUnencryptedToolStripMenuItem,
this.dATToolStripMenuItem,
this.iDXToolStripMenuItem});
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional;
this.contextMenuStrip1.Size = new System.Drawing.Size(231, 114);
//
// xLSExcelToolStripMenuItem
//
this.xLSExcelToolStripMenuItem.Name = "xLSExcelToolStripMenuItem";
this.xLSExcelToolStripMenuItem.Size = new System.Drawing.Size(230, 22);
this.xLSExcelToolStripMenuItem.Text = "CSV (Currently selected table)";
this.xLSExcelToolStripMenuItem.Click += new System.EventHandler(this.xLSExcelToolStripMenuItem_Click);
//
// xMLToolStripMenuItem
//
this.xMLToolStripMenuItem.Name = "xMLToolStripMenuItem";
this.xMLToolStripMenuItem.Size = new System.Drawing.Size(230, 22);
this.xMLToolStripMenuItem.Text = "XML";
this.xMLToolStripMenuItem.Click += new System.EventHandler(this.xMLToolStripMenuItem_Click);
//
// dATUnencryptedToolStripMenuItem
//
this.dATUnencryptedToolStripMenuItem.Name = "dATUnencryptedToolStripMenuItem";
this.dATUnencryptedToolStripMenuItem.Size = new System.Drawing.Size(230, 22);
this.dATUnencryptedToolStripMenuItem.Text = "DAT (Unencrypted)";
this.dATUnencryptedToolStripMenuItem.Click += new System.EventHandler(this.dATUnencryptedToolStripMenuItem_Click);
//
// dATToolStripMenuItem
//
this.dATToolStripMenuItem.Name = "dATToolStripMenuItem";
this.dATToolStripMenuItem.Size = new System.Drawing.Size(230, 22);
this.dATToolStripMenuItem.Text = "DAT";
this.dATToolStripMenuItem.Click += new System.EventHandler(this.dATToolStripMenuItem_Click);
//
// iDXToolStripMenuItem
//
this.iDXToolStripMenuItem.Name = "iDXToolStripMenuItem";
this.iDXToolStripMenuItem.Size = new System.Drawing.Size(230, 22);
this.iDXToolStripMenuItem.Text = "IDX";
this.iDXToolStripMenuItem.Click += new System.EventHandler(this.iDXToolStripMenuItem_Click);
//
// MainWindow
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(669, 413);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.tabControl1);
this.Name = "MainWindow";
this.Text = "TO Toolbox";
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabControl2.ResumeLayout(false);
this.tabPage4.ResumeLayout(false);
this.tabPage5.ResumeLayout(false);
this.tabPage5.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
this.tabPage2.ResumeLayout(false);
this.tabPage2.PerformLayout();
this.tabPage3.ResumeLayout(false);
this.tabPage3.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.contextMenuStrip1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button5;
private System.Windows.Forms.Button button6;
private System.Windows.Forms.TabPage tabPage3;
private System.Windows.Forms.Button button7;
private System.Windows.Forms.ListBox listBox2;
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.Button button9;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
private System.Windows.Forms.ToolStripProgressBar toolStripProgressBar1;
private System.Windows.Forms.Button button12;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
private System.Windows.Forms.ToolStripMenuItem xLSExcelToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem xMLToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem dATUnencryptedToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem dATToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem iDXToolStripMenuItem;
private System.Windows.Forms.Button button8;
private System.Windows.Forms.Button button10;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button11;
private System.Windows.Forms.Button button13;
private System.Windows.Forms.TabControl tabControl2;
private System.Windows.Forms.TabPage tabPage4;
private System.Windows.Forms.TabPage tabPage5;
private System.Windows.Forms.ListBox listBox3;
private System.Windows.Forms.TrackBar trackBar1;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.Label label2;
}
}
| 51.699145 | 162 | 0.612849 | [
"MIT"
] | TricksterOnline/TO-Toolbox | CaballaRE/MainWindow.Designer.cs | 30,246 | 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.Runtime.InteropServices;
namespace System.Drawing.Imaging
{
/// <summary>
/// Specifies the attributes of a bitmap image.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public sealed partial class BitmapData
{
private int _width;
private int _height;
private int _stride;
private PixelFormat _pixelFormat;
private IntPtr _scan0;
private int _reserved;
}
}
| 28.521739 | 71 | 0.689024 | [
"MIT"
] | 06needhamt/runtime | src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/BitmapData.Windows.cs | 656 | C# |
using MagicalLifeAPI.Components.Generic.Renderable;
using MagicalLifeAPI.Entity.AI.Task;
using MagicalLifeAPI.Entity.AI.Task.Tasks;
using MagicalLifeAPI.World.Base;
using MagicalLifeAPI.World.Data;
using MagicalLifeAPI.World.Resources;
using MagicalLifeGUIWindows.Input.History;
using System;
using System.Linq;
namespace MagicalLifeGUIWindows.Input.Specialized_Handlers
{
public class MiningActionHandler
{
public MiningActionHandler()
{
InputHistory.InputAdded += this.InputHistory_InputAdded;
}
private void InputHistory_InputAdded()
{
HistoricalInput last = InputHistory.History.Last();
if (last.ActionSelected == ActionSelected.Mine)
{
foreach (MagicalLifeAPI.GUI.Selectable item in last.Selected)
{
Tile tile = World.GetTile(RenderInfo.Dimension, item.MapLocation.X, item.MapLocation.Y);
if (tile.Resources != null && tile.ImpendingAction == ActionSelected.None)
{
if (tile.Resources is RockBase)
{
HarvestTask task = new HarvestTask(tile.MapLocation, Guid.NewGuid());
tile.ImpendingAction = ActionSelected.Mine;
TaskManager.Manager.AddTask(task);
}
}
}
}
}
}
} | 34.325581 | 108 | 0.585366 | [
"MIT"
] | codacy-badger/MagicalLife | MagicalLifeGUIWindows/Input/Specialized Handlers/MiningActionHandler.cs | 1,478 | C# |
/*
* GluLamb
* A constrained glulam modelling toolkit.
* Copyright 2021 Tom Svilans
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GluLamb.Standards
{
/// <summary>
/// The CSA standard (CSA).
/// </summary>
public class CSA : StandardBase<CSA>
{
/// <summary>
/// From CAN/CSA-O122-16 (R2021) TODO
/// </summary>
/// <param name="curvature">Maximum curvature on inner face.</param>
/// <returns>Maximum lamination thickness.</returns>
public override double CalculateLaminationThickness(double curvature)
{
throw new NotImplementedException();
}
}
}
| 29.044444 | 77 | 0.675593 | [
"MIT"
] | tsvilans/glulamb | GluLamb/Standards/CSA.cs | 1,309 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SonsTestApp
{
static class Program
{
/// <summary>
/// Главная точка входа для приложения.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 21.913043 | 65 | 0.611111 | [
"MIT"
] | Di-Roll/Sharp-SoNS | SoNSClassLibrary/SonsTestApp/Program.cs | 536 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.