content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.ServiceFabric.Common
{
using System;
using System.Collections.Generic;
/// <summary>
/// Describes the parameters for resuming an unmonitored manual Service Fabric application upgrade
/// </summary>
public partial class ResumeApplicationUpgradeDescription
{
/// <summary>
/// Initializes a new instance of the ResumeApplicationUpgradeDescription class.
/// </summary>
/// <param name="upgradeDomainName">The name of the upgrade domain in which to resume the upgrade.</param>
public ResumeApplicationUpgradeDescription(
string upgradeDomainName)
{
upgradeDomainName.ThrowIfNull(nameof(upgradeDomainName));
this.UpgradeDomainName = upgradeDomainName;
}
/// <summary>
/// Gets the name of the upgrade domain in which to resume the upgrade.
/// </summary>
public string UpgradeDomainName { get; }
}
}
| 38.30303 | 114 | 0.606013 | [
"MIT"
] | Bhaskers-Blu-Org2/service-fabric-client-dotnet | src/Microsoft.ServiceFabric.Common/Generated/ResumeApplicationUpgradeDescription.cs | 1,264 | C# |
using System;
using System.Collections.Generic;
using HotChocolate.Language.Utilities;
namespace HotChocolate.Language;
/// <summary>
/// Represents a filed definition of an interface- or object-type.
/// </summary>
public sealed class FieldDefinitionNode : NamedSyntaxNode
{
/// <summary>
/// Initializes a new instance of <see cref="FieldDefinitionNode"/>.
/// </summary>
/// <param name="location">
/// The location of the syntax node within the original source text.
/// </param>
/// <param name="name">
/// The name that this syntax node holds.
/// </param>
/// <param name="description">
/// The description of the directive.
/// </param>
/// <param name="arguments">
/// The arguments of this field definition.
/// </param>
/// <param name="type">
/// The return type of this field definition.
/// </param>
/// <param name="directives">
/// The applied directives.
/// </param>
public FieldDefinitionNode(
Location? location,
NameNode name,
StringValueNode? description,
IReadOnlyList<InputValueDefinitionNode> arguments,
ITypeNode type,
IReadOnlyList<DirectiveNode> directives)
: base(location, name, directives)
{
Description = description;
Arguments = arguments ?? throw new ArgumentNullException(nameof(arguments));
Type = type ?? throw new ArgumentNullException(nameof(type));
}
/// <inheritdoc />
public override SyntaxKind Kind => SyntaxKind.FieldDefinition;
/// <summary>
/// Gets the description of this field definition.
/// </summary>
public StringValueNode? Description { get; }
/// <summary>
/// Gets the arguments of this field definition.
/// </summary>
public IReadOnlyList<InputValueDefinitionNode> Arguments { get; }
/// <summary>
/// Gets the return type of this field definition.
/// </summary>
public ITypeNode Type { get; }
/// <inheritdoc />
public override IEnumerable<ISyntaxNode> GetNodes()
{
if (Description is not null)
{
yield return Description;
}
yield return Name;
foreach (InputValueDefinitionNode argument in Arguments)
{
yield return argument;
}
yield return Type;
foreach (DirectiveNode directive in Directives)
{
yield return directive;
}
}
/// <summary>
/// Returns the GraphQL syntax representation of this <see cref="ISyntaxNode"/>.
/// </summary>
/// <returns>
/// Returns the GraphQL syntax representation of this <see cref="ISyntaxNode"/>.
/// </returns>
public override string ToString() => SyntaxPrinter.Print(this, true);
/// <summary>
/// Returns the GraphQL syntax representation of this <see cref="ISyntaxNode"/>.
/// </summary>
/// <param name="indented">
/// A value that indicates whether the GraphQL output should be formatted,
/// which includes indenting nested GraphQL tokens, adding
/// new lines, and adding white space between property names and values.
/// </param>
/// <returns>
/// Returns the GraphQL syntax representation of this <see cref="ISyntaxNode"/>.
/// </returns>
public override string ToString(bool indented) => SyntaxPrinter.Print(this, indented);
/// <summary>
/// Creates a new node from the current instance and replaces the
/// <see cref="Location" /> with <paramref name="location" />.
/// </summary>
/// <param name="location">
/// The location that shall be used to replace the current location.
/// </param>
/// <returns>
/// Returns the new node with the new <paramref name="location" />.
/// </returns>
public FieldDefinitionNode WithLocation(Location? location)
=> new(location, Name, Description, Arguments, Type, Directives);
/// <summary>
/// Creates a new node from the current instance and replaces the
/// <see cref="NamedSyntaxNode.Name" /> with <paramref name="name" />.
/// </summary>
/// <param name="name">
/// The name that shall be used to replace the current name.
/// </param>
/// <returns>
/// Returns the new node with the new <paramref name="name" />.
/// </returns>
public FieldDefinitionNode WithName(NameNode name)
=> new(Location, name, Description, Arguments, Type, Directives);
/// <summary>
/// Creates a new node from the current instance and replaces the
/// <see cref="Description" /> with <paramref name="description" />.
/// </summary>
/// <param name="description">
/// The description that shall be used to replace the current description.
/// </param>
/// <returns>
/// Returns the new node with the new <paramref name="description" />.
/// </returns>
public FieldDefinitionNode WithDescription(StringValueNode? description)
=> new(Location, Name, description, Arguments, Type, Directives);
/// <summary>
/// Creates a new node from the current instance and replaces the
/// <see cref="Arguments" /> with <paramref name="arguments" />.
/// </summary>
/// <param name="arguments">
/// The arguments that shall be used to replace the current <see cref="Arguments"/>.
/// </param>
/// <returns>
/// Returns the new node with the new <paramref name="arguments" />.
/// </returns>
public FieldDefinitionNode WithArguments(IReadOnlyList<InputValueDefinitionNode> arguments)
=> new(Location, Name, Description, arguments, Type, Directives);
/// <summary>
/// Creates a new node from the current instance and replaces the
/// <see cref="Type" /> with <paramref name="type" />.
/// </summary>
/// <param name="type">
/// The type that shall be used to replace the current <see cref="Type"/>.
/// </param>
/// <returns>
/// Returns the new node with the new <paramref name="type" />.
/// </returns>
public FieldDefinitionNode WithType(ITypeNode type)
=> new(Location, Name, Description, Arguments, type, Directives);
/// <summary>
/// Creates a new node from the current instance and replaces the
/// <see cref="NamedSyntaxNode.Directives" /> with <paramref name="directives" />.
/// </summary>
/// <param name="directives">
/// The directives that shall be used to replace the current directives.
/// </param>
/// <returns>
/// Returns the new node with the new <paramref name="directives" />.
/// </returns>
public FieldDefinitionNode WithDirectives(IReadOnlyList<DirectiveNode> directives)
=> new(Location, Name, Description, Arguments, Type, directives);
}
| 36.128342 | 95 | 0.632771 | [
"MIT"
] | ChilliCream/prometheus | src/HotChocolate/Language/src/Language.SyntaxTree/FieldDefinitionNode.cs | 6,756 | C# |
namespace Roslin.Msg.sensor_msgs
{
[MsgInfo("sensor_msgs/JoyFeedbackArray", "cde5730a895b1fc4dee6f91b754b213d", @"# This message publishes values for multiple feedback at once.
JoyFeedback[] array")]
public partial class JoyFeedbackArray : RosMsg
{
public JoyFeedback[] array
{
get;
set;
}
public JoyFeedbackArray(): base()
{
}
public JoyFeedbackArray(System.IO.BinaryReader binaryReader): base(binaryReader)
{
}
public override void Serilize(System.IO.BinaryWriter binaryWriter)
{
binaryWriter.Write(array.Length); for ( int i = 0 ; i < array . Length ; i ++ ) array [ i ] . Serilize ( binaryWriter ) ;
}
public override void Deserilize(System.IO.BinaryReader binaryReader)
{
array = new JoyFeedback[binaryReader.ReadInt32()]; for ( int i = 0 ; i < array . Length ; i ++ ) array [ i ] = new JoyFeedback ( binaryReader ) ;
}
}
} | 33.354839 | 167 | 0.591876 | [
"MIT"
] | MoeLang/Roslin | Msg/GenMsgs/sensor_msgs/JoyFeedbackArray.cs | 1,034 | C# |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System.Reflection
namespace System.Reflection
{
using System;
using System.Runtime.CompilerServices;
// This is defined to support VarArgs
//typedef ArgIterator va_list;
[Serializable()]
internal sealed class RuntimeMethodInfo : MethodInfo
{
public extern override Type ReturnType
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
}
} // Namespace
| 38.375 | 227 | 0.37785 | [
"Apache-2.0"
] | Sirokujira/MicroFrameworkPK_v4_3 | Framework/Subset_of_CorLib/System/Reflection/RuntimeMethodInfo.cs | 921 | C# |
namespace JoinRpg.Dal.Impl.Migrations
{
using System.Data.Entity.Migrations;
public partial class ProjectPlugins : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.ProjectPlugins",
c => new
{
ProjectPluginId = c.Int(nullable: false, identity: true),
Name = c.String(),
Configuration = c.String(),
Project_ProjectId = c.Int(),
})
.PrimaryKey(t => t.ProjectPluginId)
.ForeignKey("dbo.Projects", t => t.Project_ProjectId)
.Index(t => t.Project_ProjectId);
}
public override void Down()
{
DropForeignKey("dbo.ProjectPlugins", "Project_ProjectId", "dbo.Projects");
DropIndex("dbo.ProjectPlugins", new[] { "Project_ProjectId" });
DropTable("dbo.ProjectPlugins");
}
}
}
| 30.65625 | 86 | 0.508665 | [
"MIT"
] | HeyLaurelTestOrg/joinrpg-net | src/JoinRpg.Dal.Impl/Migrations/201606092055571_ProjectPlugins.cs | 981 | C# |
using System;
using System.Windows.Media;
using TomLabs.WPF.Tools;
namespace TomLabs.KCDModToolbox.App.ViewModels.Sandbox.Console
{
public class ConsoleEntry : BaseViewModel
{
public bool IsUserInput { get; set; }
public DateTime Created { get; set; }
public string CommandText { get; set; }
public Color Foreground { get; set; }
public ConsoleEntry(string commandText, bool isUserInput = false)
{
Created = DateTime.Now;
CommandText = commandText;
IsUserInput = isUserInput;
if (IsUserInput)
{
Foreground = Colors.Yellow;
}
else
{
Foreground = GetColorByCommandText(CommandText);
}
}
private Color GetColorByCommandText(string commandText)
{
if (commandText.Contains("[VERBOSE]"))
{
return Colors.Blue;
}
else if (commandText.Contains("[DEBUG]"))
{
return Colors.LightGreen;
}
else if (commandText.Contains("[INFO]"))
{
return Colors.Cyan;
}
else if (commandText.Contains("[WARN]") || commandText.Contains("[WARNING]"))
{
return Colors.Orange;
}
else if (commandText.Contains("[ERROR]"))
{
return Colors.Red;
}
else
{
return Colors.White;
}
}
}
}
| 20.152542 | 80 | 0.659378 | [
"MIT"
] | TomasBouda/KCD-ModToolbox | src/TomLabs.KCDModToolbox/TomLabs.KCDModToolbox.App/ViewModels/Sandbox/Console/ConsoleEntry.cs | 1,191 | C# |
using EasyAbp.EShop.Plugins;
using EasyAbp.EShop.Orders;
using EasyAbp.EShop.Payments;
using EasyAbp.EShop.Products;
using EasyAbp.EShop.Stores;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.AutoMapper;
using Volo.Abp.Modularity;
using Volo.Abp.Application;
namespace EasyAbp.EShop
{
[DependsOn(
typeof(EShopDomainModule),
typeof(EShopApplicationContractsModule),
typeof(AbpDddApplicationModule),
typeof(AbpAutoMapperModule),
typeof(EShopOrdersApplicationModule),
typeof(EShopPaymentsApplicationModule),
typeof(EShopPluginsApplicationModule),
typeof(EShopProductsApplicationModule),
typeof(EShopStoresApplicationModule)
)]
public class EShopApplicationModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddAutoMapperObjectMapper<EShopApplicationModule>();
Configure<AbpAutoMapperOptions>(options =>
{
options.AddMaps<EShopApplicationModule>(validate: true);
});
}
}
}
| 31.555556 | 83 | 0.709507 | [
"MIT"
] | EasyAbp/EShop | integration/EasyAbp.EShop/src/EasyAbp.EShop.Application/EasyAbp/EShop/EShopApplicationModule.cs | 1,138 | C# |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace OpenSim.Framework.Communications.Capabilities
{
[LLSDType("MAP")]
public class LLSDCapEvent
{
public int id = 0;
public OSDArray events = new OSDArray();
public LLSDCapEvent()
{
}
}
}
| 45.04878 | 80 | 0.731456 | [
"BSD-3-Clause"
] | Ana-Green/halcyon-1 | OpenSim/Framework/Communications/Capabilities/LLSDCapEvent.cs | 1,847 | C# |
// <copyright file="IGitClogRunner.cs" company="Float">
// Copyright (c) 2020 Float, All rights reserved.
// Shared under an MIT license. See license.md for details.
// </copyright>
using System;
using System.Collections.Generic;
namespace Cake.Git.Clog
{
/// <summary>
/// An interface for the git-clog runner.
/// </summary>
public interface IGitClogRunner
{
/// <summary>
/// Run git-clog with an action to configure settings.
/// </summary>
/// <param name="configure">An action to configure settings.</param>
/// <returns>The standard output.</returns>
IEnumerable<string> RunWithResult(Action<GitClogSettings> configure = null);
/// <summary>
/// Run git-clog with the given settings.
/// </summary>
/// <param name="settings">The settings.</param>
/// <returns>The standard output.</returns>
IEnumerable<string> RunWithResult(GitClogSettings settings);
}
}
| 31.870968 | 84 | 0.632591 | [
"MIT"
] | steverichey/Cake.Git.Clog | Cake.Git.Clog/IGitClogRunner.cs | 990 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.ML.Calibrators;
using Microsoft.ML.Data;
using Microsoft.ML.Trainers;
using Microsoft.ML.Trainers.FastTree;
using Microsoft.ML.Trainers.LightGbm;
namespace Microsoft.ML.AutoML
{
using ITrainerEstimator = ITrainerEstimator<IPredictionTransformer<object>, object>;
internal class AveragedPerceptronBinaryExtension : ITrainerExtension
{
private const int DefaultNumIterations = 10;
public IEnumerable<SweepableParam> GetHyperparamSweepRanges()
{
return SweepableParams.BuildAveragePerceptronParams();
}
public ITrainerEstimator CreateInstance(MLContext mlContext, IEnumerable<SweepableParam> sweepParams,
ColumnInformation columnInfo, IDataView validationSet)
{
AveragedPerceptronTrainer.Options options = null;
if (sweepParams == null || !sweepParams.Any())
{
options = new AveragedPerceptronTrainer.Options();
options.NumberOfIterations = DefaultNumIterations;
options.LabelColumnName = columnInfo.LabelColumnName;
}
else
{
options = TrainerExtensionUtil.CreateOptions<AveragedPerceptronTrainer.Options>(sweepParams, columnInfo.LabelColumnName);
if (!sweepParams.Any(p => p.Name == "NumberOfIterations"))
{
options.NumberOfIterations = DefaultNumIterations;
}
}
return mlContext.BinaryClassification.Trainers.AveragedPerceptron(options);
}
public PipelineNode CreatePipelineNode(IEnumerable<SweepableParam> sweepParams, ColumnInformation columnInfo)
{
Dictionary<string, object> additionalProperties = null;
if (sweepParams == null || !sweepParams.Any(p => p.Name != "NumberOfIterations"))
{
additionalProperties = new Dictionary<string, object>()
{
{ "NumberOfIterations", DefaultNumIterations }
};
}
return TrainerExtensionUtil.BuildPipelineNode(TrainerExtensionCatalog.GetTrainerName(this), sweepParams,
columnInfo.LabelColumnName, additionalProperties: additionalProperties);
}
}
internal class FastForestBinaryExtension : ITrainerExtension
{
public IEnumerable<SweepableParam> GetHyperparamSweepRanges()
{
return SweepableParams.BuildFastForestParams();
}
public ITrainerEstimator CreateInstance(MLContext mlContext, IEnumerable<SweepableParam> sweepParams,
ColumnInformation columnInfo, IDataView validationSet)
{
var options = TrainerExtensionUtil.CreateOptions<FastForestBinaryTrainer.Options>(sweepParams, columnInfo.LabelColumnName);
options.ExampleWeightColumnName = columnInfo.ExampleWeightColumnName;
return mlContext.BinaryClassification.Trainers.FastForest(options);
}
public PipelineNode CreatePipelineNode(IEnumerable<SweepableParam> sweepParams, ColumnInformation columnInfo)
{
return TrainerExtensionUtil.BuildPipelineNode(TrainerExtensionCatalog.GetTrainerName(this), sweepParams,
columnInfo.LabelColumnName, columnInfo.ExampleWeightColumnName);
}
}
internal class FastTreeBinaryExtension : ITrainerExtension
{
public IEnumerable<SweepableParam> GetHyperparamSweepRanges()
{
return SweepableParams.BuildFastTreeParams();
}
public ITrainerEstimator CreateInstance(MLContext mlContext, IEnumerable<SweepableParam> sweepParams,
ColumnInformation columnInfo, IDataView validationSet)
{
var options = TrainerExtensionUtil.CreateOptions<FastTreeBinaryTrainer.Options>(sweepParams, columnInfo.LabelColumnName);
options.ExampleWeightColumnName = columnInfo.ExampleWeightColumnName;
return mlContext.BinaryClassification.Trainers.FastTree(options);
}
public PipelineNode CreatePipelineNode(IEnumerable<SweepableParam> sweepParams, ColumnInformation columnInfo)
{
return TrainerExtensionUtil.BuildPipelineNode(TrainerExtensionCatalog.GetTrainerName(this), sweepParams,
columnInfo.LabelColumnName, columnInfo.ExampleWeightColumnName);
}
}
internal class LightGbmBinaryExtension : ITrainerExtension
{
public IEnumerable<SweepableParam> GetHyperparamSweepRanges()
{
return SweepableParams.BuildLightGbmParams();
}
public ITrainerEstimator CreateInstance(MLContext mlContext, IEnumerable<SweepableParam> sweepParams,
ColumnInformation columnInfo, IDataView validationSet)
{
LightGbmBinaryTrainer.Options options = TrainerExtensionUtil.CreateLightGbmOptions<LightGbmBinaryTrainer.Options, float, BinaryPredictionTransformer<CalibratedModelParametersBase<LightGbmBinaryModelParameters, PlattCalibrator>>, CalibratedModelParametersBase<LightGbmBinaryModelParameters, PlattCalibrator>>(sweepParams, columnInfo);
return mlContext.BinaryClassification.Trainers.LightGbm(options);
}
public PipelineNode CreatePipelineNode(IEnumerable<SweepableParam> sweepParams, ColumnInformation columnInfo)
{
return TrainerExtensionUtil.BuildLightGbmPipelineNode(TrainerExtensionCatalog.GetTrainerName(this), sweepParams,
columnInfo.LabelColumnName, columnInfo.ExampleWeightColumnName, columnInfo.GroupIdColumnName);
}
}
internal class LinearSvmBinaryExtension : ITrainerExtension
{
public IEnumerable<SweepableParam> GetHyperparamSweepRanges()
{
return SweepableParams.BuildLinearSvmParams();
}
public ITrainerEstimator CreateInstance(MLContext mlContext, IEnumerable<SweepableParam> sweepParams,
ColumnInformation columnInfo, IDataView validationSet)
{
var options = TrainerExtensionUtil.CreateOptions<LinearSvmTrainer.Options>(sweepParams, columnInfo.LabelColumnName);
return mlContext.BinaryClassification.Trainers.LinearSvm(options);
}
public PipelineNode CreatePipelineNode(IEnumerable<SweepableParam> sweepParams, ColumnInformation columnInfo)
{
return TrainerExtensionUtil.BuildPipelineNode(TrainerExtensionCatalog.GetTrainerName(this), sweepParams,
columnInfo.LabelColumnName);
}
}
internal class SdcaLogisticRegressionBinaryExtension : ITrainerExtension
{
public IEnumerable<SweepableParam> GetHyperparamSweepRanges()
{
return SweepableParams.BuildSdcaParams();
}
public ITrainerEstimator CreateInstance(MLContext mlContext, IEnumerable<SweepableParam> sweepParams,
ColumnInformation columnInfo, IDataView validationSet)
{
var options = TrainerExtensionUtil.CreateOptions<SdcaLogisticRegressionBinaryTrainer.Options>(sweepParams, columnInfo.LabelColumnName);
return mlContext.BinaryClassification.Trainers.SdcaLogisticRegression(options);
}
public PipelineNode CreatePipelineNode(IEnumerable<SweepableParam> sweepParams, ColumnInformation columnInfo)
{
return TrainerExtensionUtil.BuildPipelineNode(TrainerExtensionCatalog.GetTrainerName(this), sweepParams,
columnInfo.LabelColumnName);
}
}
internal class LbfgsLogisticRegressionBinaryExtension : ITrainerExtension
{
public IEnumerable<SweepableParam> GetHyperparamSweepRanges()
{
return SweepableParams.BuildLbfgsLogisticRegressionParams();
}
public ITrainerEstimator CreateInstance(MLContext mlContext, IEnumerable<SweepableParam> sweepParams,
ColumnInformation columnInfo, IDataView validationSet)
{
var options = TrainerExtensionUtil.CreateOptions<LbfgsLogisticRegressionBinaryTrainer.Options>(sweepParams, columnInfo.LabelColumnName);
options.ExampleWeightColumnName = columnInfo.ExampleWeightColumnName;
return mlContext.BinaryClassification.Trainers.LbfgsLogisticRegression(options);
}
public PipelineNode CreatePipelineNode(IEnumerable<SweepableParam> sweepParams, ColumnInformation columnInfo)
{
return TrainerExtensionUtil.BuildPipelineNode(TrainerExtensionCatalog.GetTrainerName(this), sweepParams,
columnInfo.LabelColumnName, columnInfo.ExampleWeightColumnName);
}
}
internal class SgdCalibratedBinaryExtension : ITrainerExtension
{
public IEnumerable<SweepableParam> GetHyperparamSweepRanges()
{
return SweepableParams.BuildSgdParams();
}
public ITrainerEstimator CreateInstance(MLContext mlContext, IEnumerable<SweepableParam> sweepParams,
ColumnInformation columnInfo, IDataView validationSet)
{
var options = TrainerExtensionUtil.CreateOptions<SgdCalibratedTrainer.Options>(sweepParams, columnInfo.LabelColumnName);
options.ExampleWeightColumnName = columnInfo.ExampleWeightColumnName;
return mlContext.BinaryClassification.Trainers.SgdCalibrated(options);
}
public PipelineNode CreatePipelineNode(IEnumerable<SweepableParam> sweepParams, ColumnInformation columnInfo)
{
return TrainerExtensionUtil.BuildPipelineNode(TrainerExtensionCatalog.GetTrainerName(this), sweepParams,
columnInfo.LabelColumnName, columnInfo.ExampleWeightColumnName);
}
}
internal class SymbolicSgdLogisticRegressionBinaryExtension : ITrainerExtension
{
public IEnumerable<SweepableParam> GetHyperparamSweepRanges()
{
return SweepableParams.BuildSymSgdLogisticRegressionParams();
}
public ITrainerEstimator CreateInstance(MLContext mlContext, IEnumerable<SweepableParam> sweepParams,
ColumnInformation columnInfo, IDataView validationSet)
{
var options = TrainerExtensionUtil.CreateOptions<SymbolicSgdLogisticRegressionBinaryTrainer.Options>(sweepParams, columnInfo.LabelColumnName);
return mlContext.BinaryClassification.Trainers.SymbolicSgdLogisticRegression(options);
}
public PipelineNode CreatePipelineNode(IEnumerable<SweepableParam> sweepParams, ColumnInformation columnInfo)
{
return TrainerExtensionUtil.BuildPipelineNode(TrainerExtensionCatalog.GetTrainerName(this), sweepParams,
columnInfo.LabelColumnName);
}
}
}
| 46.542373 | 345 | 0.719683 | [
"MIT"
] | 1Crazymoney/machinelearning | src/Microsoft.ML.AutoML/TrainerExtensions/BinaryTrainerExtensions.cs | 10,986 | C# |
using EmbyTV.EPGProvider;
using MediaBrowser.Controller.Net;
using ServiceStack;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using EmbyTV.Configuration;
using EmbyTV.TunerHost;
namespace EmbyTV.Api
{
[Route("/EmbyTv/SchedulesDirect/Headends", "GET")]
public class GetSchedulesDirectHeadends : IReturn<HeadendsResult>
{
}
[Route("/EmbyTv/Tuner/ConfigurationFields", "GET")]
public class GetTunerConfigurationFields : IReturn<ConfigurationFieldsDefaults>
{
}
public class EmbyTvConfigService : IRestfulService
{
public async Task<object> Get(GetSchedulesDirectHeadends request)
{
var headends = await SchedulesDirect.Current.GetHeadends(Plugin.Instance.Configuration.zipCode, CancellationToken.None).ConfigureAwait(false);
var availableLineups = await SchedulesDirect.Current.getLineups(CancellationToken.None).ConfigureAwait(false);
return new HeadendsResult
{
Headends = headends,
AvaliableLineups = availableLineups
};
}
public async Task<object> Get(GetTunerConfigurationFields request)
{
return new ConfigurationFieldsDefaults {DefaultsBuilders = TunerHostStatics.BuildDefaultForTunerHostsBuilders()};
}
}
public class HeadendsResult
{
public List<Headend> Headends { get; set; }
public List<string> AvaliableLineups { get; set; }
}
public class ConfigurationFieldsDefaults
{
public List<FieldBuilder> DefaultsBuilders { get; set; }
}
}
| 32.137255 | 154 | 0.693716 | [
"MIT"
] | thecat18/MediaBrowser.Plugins | EmbyTV/Api/EmbyTvConfigService.cs | 1,641 | C# |
using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
using BoDi;
using FluentAssertions;
using Moq;
using Xunit;
using TechTalk.SpecFlow.Bindings.Discovery;
using TechTalk.SpecFlow.Configuration;
using TechTalk.SpecFlow.Infrastructure;
using TechTalk.SpecFlow.RuntimeTests.Infrastructure;
using TechTalk.SpecFlow.Tracing;
namespace TechTalk.SpecFlow.RuntimeTests
{
public class TestRunnerManagerRunnerCreationTests
{
private readonly Mock<ITestRunner> testRunnerFake = new Mock<ITestRunner>();
private readonly Mock<IObjectContainer> objectContainerStub = new Mock<IObjectContainer>();
private readonly Mock<IObjectContainer> globalObjectContainerStub = new Mock<IObjectContainer>();
private readonly SpecFlow.Configuration.SpecFlowConfiguration _specFlowConfigurationStub = ConfigurationLoader.GetDefault();
private readonly Assembly anAssembly = Assembly.GetExecutingAssembly();
private readonly Assembly anotherAssembly = typeof(TestRunnerManager).Assembly;
private TestRunnerManager CreateTestRunnerFactory()
{
objectContainerStub.Setup(o => o.Resolve<ITestRunner>()).Returns(testRunnerFake.Object);
globalObjectContainerStub.Setup(o => o.Resolve<IBindingAssemblyLoader>()).Returns(new BindingAssemblyLoader());
globalObjectContainerStub.Setup(o => o.Resolve<ITraceListenerQueue>()).Returns(new Mock<ITraceListenerQueue>().Object);
var testRunContainerBuilderStub = new Mock<IContainerBuilder>();
testRunContainerBuilderStub.Setup(b => b.CreateTestThreadContainer(It.IsAny<IObjectContainer>()))
.Returns(objectContainerStub.Object);
var runtimeBindingRegistryBuilderMock = new Mock<IRuntimeBindingRegistryBuilder>();
var testRunnerManager = new TestRunnerManager(globalObjectContainerStub.Object, testRunContainerBuilderStub.Object, _specFlowConfigurationStub, runtimeBindingRegistryBuilderMock.Object,
Mock.Of<ITestTracer>());
testRunnerManager.Initialize(anAssembly);
return testRunnerManager;
}
[Fact]
public void Should_resolve_a_test_runner()
{
var factory = CreateTestRunnerFactory();
var testRunner = factory.CreateTestRunner(0);
testRunner.Should().NotBeNull();
}
[Fact]
public void Should_initialize_test_runner_with_the_provided_assembly()
{
var factory = CreateTestRunnerFactory();
factory.CreateTestRunner(0);
testRunnerFake.Verify(tr => tr.OnTestRunStart());
}
[Fact]
public void Should_initialize_test_runner_with_additional_step_assemblies()
{
var factory = CreateTestRunnerFactory();
_specFlowConfigurationStub.AddAdditionalStepAssembly(anotherAssembly);
factory.CreateTestRunner(0);
testRunnerFake.Verify(tr => tr.OnTestRunStart());
}
[Fact]
public void Should_initialize_test_runner_with_the_provided_assembly_even_if_there_are_additional_ones()
{
var factory = CreateTestRunnerFactory();
_specFlowConfigurationStub.AddAdditionalStepAssembly(anotherAssembly);
factory.CreateTestRunner(0);
testRunnerFake.Verify(tr => tr.OnTestRunStart());
}
[Fact]
public void Should_resolve_a_test_runner_specific_test_tracer()
{
//This test can't run in NCrunch as when NCrunch runs the tests it will disable the ability to get different test runners for each thread
//as it manages the parallelisation
//see https://github.com/techtalk/SpecFlow/issues/638
if (!TestEnvironmentHelper.IsBeingRunByNCrunch())
{
var testRunner1 = TestRunnerManager.GetTestRunner(anAssembly, 0);
testRunner1.OnFeatureStart(new FeatureInfo(new CultureInfo("en-US"), "sds", "sss"));
testRunner1.OnScenarioInitialize(new ScenarioInfo("foo", "foo_desc"));
testRunner1.OnScenarioStart();
var tracer1 = testRunner1.ScenarioContext.ScenarioContainer.Resolve<ITestTracer>();
var testRunner2 = TestRunnerManager.GetTestRunner(anAssembly, 1);
testRunner2.OnFeatureStart(new FeatureInfo(new CultureInfo("en-US"), "sds", "sss"));
testRunner2.OnScenarioInitialize(new ScenarioInfo("foo", "foo_desc"));
testRunner1.OnScenarioStart();
var tracer2 = testRunner2.ScenarioContext.ScenarioContainer.Resolve<ITestTracer>();
tracer1.Should().NotBeSameAs(tracer2);
}
}
}
}
| 43 | 197 | 0.686669 | [
"Apache-2.0",
"MIT"
] | Blackbaud-ChrisKessel/SpecFlow | Tests/TechTalk.SpecFlow.RuntimeTests/TestRunnerManagerRunnerCreationTests.cs | 4,816 | C# |
using System;
using System.Collections.Specialized;
using System.Configuration.Install;
using System.Diagnostics;
using System.Net;
using System.ServiceProcess;
using System.Threading;
using System.Threading.Tasks;
using System.Text;
using System.Linq;
using System.IO;
namespace StackExchange.NetGain
{
public class TcpService : ServiceBase
{
public TcpService(string configuration, IMessageProcessor processor, IProtocolFactory factory)
{
if(processor == null) throw new ArgumentNullException("processor");
this.processor = processor;
this.factory = factory;
Configuration = configuration;
ServiceName = processor.Name;
MaxIncomingQuota = TcpHandler.DefaultMaxIncomingQuota;
MaxOutgoingQuota = TcpHandler.DefaultMaxOutgoingQuota;
}
public string Configuration { get; set; }
public IPEndPoint[] Endpoints { get; set; }
protected virtual void Configure()
{
processor.Configure(this);
}
public const string DefaultServiceName = "SocketServerLocal";
private TcpServer server;
private IMessageProcessor processor;
private IProtocolFactory factory;
public TextWriter ErrorLog { get; set; } = Console.Error;
public TextWriter Log { get; set; } = Console.Out;
public void StartService()
{
if (processor == null) throw new ObjectDisposedException(GetType().Name);
if(server == null)
{
var tmp = new TcpServer() { Log = Log, ErrorLog = ErrorLog };
tmp.MessageProcessor = processor;
tmp.ProtocolFactory = factory;
tmp.Backlog = 100;
if (Interlocked.CompareExchange(ref server, tmp, null) == null)
{
ThreadPool.QueueUserWorkItem(delegate
{
try
{
if(!Environment.UserInteractive)
{
// why? you may ask; because I need win32 to acknowledge the service is started so we can query the names etc
Thread.Sleep(250);
}
string svcName = GetServiceName();
if (!string.IsNullOrEmpty(svcName))
{
ActualServiceName = svcName;
}
Configure();
tmp.MaxIncomingQuota = MaxIncomingQuota;
tmp.MaxOutgoingQuota = MaxOutgoingQuota;
tmp.Start(Configuration, Endpoints);
} catch (Exception ex)
{
ErrorLog?.WriteLine(ex.Message);
Stop(); // argh!
}
});
}
}
}
private string actualServiceName;
public string ActualServiceName
{
get { return actualServiceName ?? ServiceName; }
set { actualServiceName = value; }
}
static String GetServiceName() // http://stackoverflow.com/questions/1841790/how-can-a-windows-service-determine-its-servicename
{
// Calling System.ServiceProcess.ServiceBase::ServiceNamea allways returns
// an empty string,
// see https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=387024
// So we have to do some more work to find out our service name, this only works if
// the process contains a single service, if there are more than one services hosted
// in the process you will have to do something else
int processId = System.Diagnostics.Process.GetCurrentProcess().Id;
String query = "SELECT * FROM Win32_Service where ProcessId = " + processId;
using (var searcher = new System.Management.ManagementObjectSearcher(query))
{
foreach (System.Management.ManagementObject queryObj in searcher.Get())
{
return queryObj["Name"].ToString();
}
}
return null;
}
protected override void Dispose(bool disposing)
{
if(disposing)
{
if(processor != null) processor.Dispose();
if(server != null) ((IDisposable) server).Dispose();
}
processor = null;
factory = null;
server = null;
base.Dispose(disposing);
}
protected override void OnStart(string[] args)
{
StartService();
}
public void StopService()
{
TcpServer tmp;
if((tmp = Interlocked.Exchange(ref server, null)) != null)
{
tmp.Stop();
}
}
protected override void OnStop()
{
StopService();
}
private static void LogWhileDying(object ex, TextWriter errorLog)
{
Exception typed = ex as Exception;
errorLog?.WriteLine(typed == null ? Convert.ToString(ex) : typed.Message);
if(typed != null)
{
errorLog?.WriteLine(typed.StackTrace);
}
#if DEBUG
if (Debugger.IsAttached)
{
Debugger.Break();
}
#endif
}
public static string InstallerServiceName { get; set; }
public static int Run<T>(string configuration, string[] args, IPEndPoint[] endpoints, IProtocolFactory protocolFactory)
where T : IMessageProcessor, new()
=> Run<T>(configuration, args, endpoints, protocolFactory, Console.Out, Console.Error);
public static int Run<T>(string configuration, string[] args, IPEndPoint[] endpoints, IProtocolFactory protocolFactory, TextWriter log, TextWriter errorLog)
where T : IMessageProcessor, new()
{
try
{
AppDomain.CurrentDomain.UnhandledException += (s, e) => LogWhileDying(e.ExceptionObject, errorLog);
string name = null;
bool uninstall = false, install = false, benchmark = false, hasErrors = false;
for (int i = 0; i < args.Length; i++ )
{
switch(args[i])
{
case "-u": uninstall = true; break;
case "-i": install = true; break;
case "-b": benchmark = true; break;
default:
if(args[i].StartsWith("-n:"))
{
name = args[i].Substring(3);
} else
{
errorLog?.WriteLine("Unknown argument: " + args[i]);
hasErrors = true;
}
break;
}
}
if (hasErrors)
{
errorLog?.WriteLine("Support flags:");
errorLog?.WriteLine("-i\tinstall service");
errorLog?.WriteLine("-u\tuninstall service");
errorLog?.WriteLine("-b\tbenchmark");
errorLog?.WriteLine("-n:name\toverride service name");
errorLog?.WriteLine("(no args) execute in console");
return -1;
}
if(uninstall)
{
log?.WriteLine("Uninstalling service...");
InstallerServiceName = name;
ManagedInstallerClass.InstallHelper(new string[] { "/u", typeof(T).Assembly.Location });
}
if(install)
{
log?.WriteLine("Installing service...");
InstallerServiceName = name;
ManagedInstallerClass.InstallHelper(new string[] { typeof(T).Assembly.Location });
}
if(install || uninstall)
{
log?.WriteLine("(done)");
return 0;
}
if(benchmark)
{
var factory = BasicBinaryProtocolFactory.Default;
using (var svc = new TcpService("", new EchoProcessor(), factory))
{
svc.MaxIncomingQuota = -1;
log?.WriteLine("Running benchmark using " + svc.ServiceName + "....");
svc.StartService();
svc.RunEchoBenchmark(1, 500000, factory, log);
svc.RunEchoBenchmark(50, 10000, factory, log);
svc.RunEchoBenchmark(100, 5000, factory, log);
svc.StopService();
}
return 0;
}
if (Environment.UserInteractive)// user facing
{
using (var messageProcessor = new T())
using (var svc = new TcpService(configuration, messageProcessor, protocolFactory) {
ErrorLog = errorLog, Log = log
})
{
svc.Endpoints = endpoints;
if (!string.IsNullOrEmpty(name)) svc.ActualServiceName = name;
svc.StartService();
log?.WriteLine("Running " + svc.ActualServiceName +
" in interactive mode; press any key to quit");
Console.ReadKey();
log?.WriteLine("Exiting...");
svc.StopService();
}
return 0;
}
else
{
var svc = new TcpService(configuration, new T(), protocolFactory) {
ErrorLog = errorLog, Log = log
};
svc.Endpoints = endpoints;
ServiceBase.Run(svc);
return 0;
}
}
catch (Exception ex)
{
LogWhileDying(ex, errorLog);
return -1;
}
}
internal class EchoProcessor : IMessageProcessor
{
public string Name { get { return "Echo"; } }
public string Description { get { return "Garbage in, garbage out"; } }
void IMessageProcessor.Configure(TcpService service)
{
service.Endpoints = new[] {new IPEndPoint(IPAddress.Loopback, 5999)};
}
void IMessageProcessor.StartProcessor(NetContext context, string configuration) { }
void IMessageProcessor.EndProcessor(NetContext context) { }
void IMessageProcessor.Heartbeat(NetContext context) { }
void IDisposable.Dispose() { }
void IMessageProcessor.OpenConnection(NetContext context, Connection connection) { }
void IMessageProcessor.CloseConnection(NetContext context, Connection connection) { }
void IMessageProcessor.Authenticate(NetContext context, Connection connection, StringDictionary claims) { }
void IMessageProcessor.AfterAuthenticate(NetContext context, Connection connection) { }
void IMessageProcessor.Received(NetContext context, Connection connection, object message)
{ // right back at you!
connection.Send(context, message);
}
void IMessageProcessor.Flushed(NetContext context, Connection connection) { }
void IMessageProcessor.OnShutdown(NetContext context, Connection conn) { }
}
internal void RunEchoBenchmark(int clients, int iterations, IProtocolFactory factory, TextWriter log)
{
Thread[] threads = new Thread[clients];
int remaining = clients;
ManualResetEvent evt = new ManualResetEvent(false);
Stopwatch watch = new Stopwatch();
long opsPerSecond;
//ThreadStart work = () => RunEchoClient(iterations, ref remaining, evt, watch, factory);
//for (int i = 0; i < clients; i++)
//{
// threads[i] = new Thread(work);
//}
//for (int i = 0; i < clients; i++)
//{
// threads[i].Start();
//}
//for (int i = 0; i < clients; i++)
//{
// threads[i].Join();
//}
//watch.Stop();
//opsPerSecond = watch.ElapsedMilliseconds == 0 ? -1 : (clients * iterations * 1000) / watch.ElapsedMilliseconds;
//log?.WriteLine("Total elapsed: {0}ms, {1}ops/s (individual clients)", watch.ElapsedMilliseconds, opsPerSecond);
var endpoints = Enumerable.Repeat(new IPEndPoint(IPAddress.Loopback, 5999), clients).ToArray();
var tasks = new Task[iterations];
byte[] message = new byte[1000];
new Random(123456).NextBytes(message);
using(var clientGroup = new TcpClientGroup())
{
clientGroup.MaxIncomingQuota = -1;
clientGroup.ProtocolFactory = factory;
clientGroup.Open(endpoints);
watch = Stopwatch.StartNew();
for(int i = 0 ; i < iterations ; i++)
{
tasks[i] = clientGroup.Execute(message);
}
Task.WaitAll(tasks);
watch.Stop();
}
opsPerSecond = watch.ElapsedMilliseconds == 0 ? -1 : (iterations * 1000) / watch.ElapsedMilliseconds;
log?.WriteLine("Total elapsed: {0}ms, {1}ops/s (grouped clients)", watch.ElapsedMilliseconds, opsPerSecond);
}
void RunEchoClient(int iterations, ref int outstanding, ManualResetEvent evt, Stopwatch mainWatch, IProtocolFactory factory)
{
Task<object> last = null;
var message = Encoding.UTF8.GetBytes("hello");
using (var client = new TcpClient())
{
client.ProtocolFactory = factory;
client.Open(new IPEndPoint(IPAddress.Loopback, 5999));
if (Interlocked.Decrement(ref outstanding) == 0)
{
mainWatch.Start();
evt.Set();
}
else evt.WaitOne();
var watch = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
last = client.Execute(message);
last.Wait();
watch.Stop();
//log?.WriteLine("{0}ms", watch.ElapsedMilliseconds);
}
}
public int MaxIncomingQuota { get; set; }
public int MaxOutgoingQuota { get; set; }
}
}
| 41.252011 | 164 | 0.498733 | [
"MIT"
] | ASSETEX/Aych.netgain | src/StackExchange.NetGain/TcpService.cs | 15,389 | C# |
#region License
// Distributed under the MIT License
// ============================================================
// Copyright (c) 2019 Hotcakes Commerce, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using DotNetNuke.Entities.Users;
using Hotcakes.Commerce.Contacts;
using Hotcakes.Commerce.Data;
using Hotcakes.Commerce.Data.EF;
using Hotcakes.Commerce.Dnn.Data;
using Hotcakes.Commerce.Globalization;
using Hotcakes.Commerce.Membership;
using Hotcakes.Common.Dnn;
namespace Hotcakes.Commerce.Dnn
{
[Serializable]
public class DnnAffiliateRepository : AffiliateRepository
{
public DnnAffiliateRepository(HccRequestContext context)
: base(context)
{
_userCtl = DnnUserController.Instance;
_portalId = DnnGlobal.Instance.GetPortalId();
}
#region Obsolete
[Obsolete("Obsolete in 1.8.0. Use Factory.CreateRepo instead")]
public DnnAffiliateRepository(HccRequestContext context, bool isForMemoryOnly)
: this(context)
{
}
#endregion
#region Internal declaration
internal class AffiliateReportHelper
{
private readonly bool _applyVATRules;
private readonly AffiliateReportCriteria _criteria;
private readonly int _pageNumber;
private readonly int _pageSize;
private readonly DnnAffiliateRepository _rep;
private readonly long _storeId;
private readonly IRepoStrategy<hcc_Affiliate> _strategy;
internal int RowCount;
internal AffiliateReportHelper(DnnAffiliateRepository rep, IRepoStrategy<hcc_Affiliate> strategy,
AffiliateReportCriteria criteria, int pageNumber, int pageSize)
{
_rep = rep;
_strategy = strategy;
_criteria = criteria;
_pageNumber = pageNumber;
_pageSize = pageSize;
_storeId = _rep.Context.CurrentStore.Id;
_applyVATRules = _rep.Context.CurrentStore.Settings.ApplyVATRules;
}
internal List<AffiliateReportData> GetReport()
{
List<AffiliateReportData> result = null;
IEnumerable<DnnUser> users = null;
var query = BuildReportQuery();
query = FilterQueryBySearchText(query, ref users);
RowCount = query.Count();
query = ApplySorting(query);
result = ApplyPaging(query);
if (users == null)
{
users = GetDnnUsers(result);
}
result.ForEach(i =>
{
var user = users.FirstOrDefault(u => u.UserID == i.UserId);
if (user != null)
{
i.Company = user.ProfileCompany;
i.FirstName = user.FirstName;
i.LastName = user.LastName;
i.Email = user.Email;
if (string.IsNullOrEmpty(i.FirstName) && string.IsNullOrEmpty(i.LastName))
{
i.LastName = user.DisplayName;
}
}
else
{
i.UserId = -1;
i.LastName = "[USER ACCOUNT DELETED]";
}
});
return result;
}
internal AffiliateReportTotals GetTotals()
{
IEnumerable<DnnUser> users = null;
var query = BuildReportQuery();
query = FilterQueryBySearchText(query, ref users);
return new AffiliateReportTotals
{
OrdersCount = query.Sum(i => (int?) i.OrdersCount) ?? 0,
SalesAmount = query.Sum(i => (decimal?) i.SalesAmount) ?? 0,
Commission = query.Sum(i => (decimal?) i.Commission) ?? 0,
CommissionPaid = query.Sum(i => (decimal?) i.CommissionPayed) ?? 0,
PaymentsCount = query.Sum(i => (int?) i.PaymentsCount) ?? 0
};
}
internal AffiliateReportTotals GetTotals(TotalsReturnType returnType)
{
IEnumerable<DnnUser> users = null;
var query = BuildReportQuery();
query = FilterQueryBySearchText(query, ref users);
var totals = new AffiliateReportTotals();
if (returnType == TotalsReturnType.ReturnAll || returnType == TotalsReturnType.ReturnReferrals)
{
totals.ReferralsCount = query.Sum(i => (int?) i.SignupsCount) ?? 0;
}
if (returnType == TotalsReturnType.ReturnAll || returnType == TotalsReturnType.ReturnOrders)
{
totals.OrdersCount = query.Sum(i => (int?) i.OrdersCount) ?? 0;
totals.SalesAmount = query.Sum(i => (decimal?) i.SalesAmount) ?? 0;
}
if (returnType == TotalsReturnType.ReturnAll || returnType == TotalsReturnType.ReturnPayments)
{
totals.Commission = query.Sum(i => (decimal?) i.Commission) ?? 0;
totals.CommissionPaid = query.Sum(i => (decimal?) i.CommissionPayed) ?? 0;
totals.PaymentsCount = query.Sum(i => (int?) i.PaymentsCount) ?? 0;
}
return totals;
}
internal AffiliateReportTotals GetAffiliateTotals(long affId)
{
IEnumerable<DnnUser> users = null;
var query = BuildReportQuery().Where(a => a.Id == affId);
query = FilterQueryBySearchText(query, ref users);
return new AffiliateReportTotals
{
ReferralsCount = query.Sum(i => (int?) i.SignupsCount) ?? 0,
OrdersCount = query.Sum(i => (int?) i.OrdersCount) ?? 0,
SalesAmount = query.Sum(i => (decimal?) i.SalesAmount) ?? 0,
Commission = query.Sum(i => (decimal?) i.Commission) ?? 0,
CommissionPaid = query.Sum(i => (decimal?) i.CommissionPayed) ?? 0,
PaymentsCount = query.Sum(i => (int?) i.PaymentsCount) ?? 0
};
}
internal AffiliateReportTotals GetAffiliateTotals(long affId, TotalsReturnType returnType)
{
IEnumerable<DnnUser> users = null;
var query = BuildReportQuery().Where(a => a.Id == affId);
query = FilterQueryBySearchText(query, ref users);
var totals = new AffiliateReportTotals();
if (returnType == TotalsReturnType.ReturnAll || returnType == TotalsReturnType.ReturnReferrals)
{
totals.ReferralsCount = query.Sum(i => (int?) i.SignupsCount) ?? 0;
}
if (returnType == TotalsReturnType.ReturnAll || returnType == TotalsReturnType.ReturnOrders)
{
totals.OrdersCount = query.Sum(i => (int?) i.OrdersCount) ?? 0;
totals.SalesAmount = query.Sum(i => (decimal?) i.SalesAmount) ?? 0;
}
if (returnType == TotalsReturnType.ReturnAll || returnType == TotalsReturnType.ReturnPayments)
{
totals.Commission = query.Sum(i => (decimal?) i.Commission) ?? 0;
totals.CommissionPaid = query.Sum(i => (decimal?) i.CommissionPayed) ?? 0;
totals.PaymentsCount = query.Sum(i => (int?) i.PaymentsCount) ?? 0;
}
return totals;
}
#region Implementation
private IQueryable<AffiliateReportData> BuildReportQuery()
{
var orders = _strategy.GetQuery<hcc_Order>()
.Where(o => o.StoreId == _storeId)
.Where(o => o.TimeOfOrder >= _criteria.StartDateUtc && o.TimeOfOrder <= _criteria.EndDateUtc);
var signups = _strategy.GetQuery()
.Where(i => i.CreationDate >= _criteria.StartDateUtc && i.CreationDate <= _criteria.EndDateUtc);
var payments = _strategy.GetQuery<hcc_AffiliatePayments>()
.Where(i => i.PaymentDate >= _criteria.StartDateUtc && i.PaymentDate <= _criteria.EndDateUtc);
var affiliates = _strategy.GetQuery().Where(a => a.StoreId == _storeId);
if (!string.IsNullOrEmpty(_criteria.ReferralAffiliateID))
affiliates = affiliates.Where(a => a.ReferralID == _criteria.ReferralAffiliateID);
if (_criteria.ShowOnlyNonApproved)
affiliates = affiliates.Where(a => !a.Approved);
var query = affiliates.GroupJoin(orders, a => a.Id, o => o.AffiliateId,
(a, oColl) => new {Affiliate = a, Orders = oColl})
.GroupJoin(signups, ao => ao.Affiliate.AffiliateID, s => s.ReferralID,
(ao, sColl) => new {ao.Affiliate, ao.Orders, Signups = sColl})
.GroupJoin(payments, aos => aos.Affiliate.Id, p => p.AffiliateId,
(aos, pColl) => new {aos.Affiliate, aos.Orders, aos.Signups, Payments = pColl})
.Select(aosp => new AffiliateReportData
{
Id = aosp.Affiliate.Id,
AffiliateId = aosp.Affiliate.AffiliateID,
UserId = aosp.Affiliate.UserId,
OrdersCount = aosp.Orders.Count(),
SignupsCount = aosp.Signups.Count(),
SalesAmount =
_applyVATRules
? aosp.Orders.Sum(o => (decimal?) o.SubTotal - (decimal?) o.ItemsTax) ?? 0
: aosp.Orders.Sum(o => (decimal?) o.SubTotal + (decimal?) o.OrderDiscounts) ?? 0,
// TODO: Old Affiliate Report use TotalOrderBeforeDiscounts
Commission = aosp.Affiliate.CommissionType == 2
? Math.Round(aosp.Affiliate.CommissionAmount*aosp.Orders.Count(), 2)
: Math.Round(
aosp.Affiliate.CommissionAmount/100*
(_applyVATRules
? aosp.Orders.Sum(o => (decimal?) o.SubTotal - (decimal?) o.ItemsTax) ?? 0
: aosp.Orders.Sum(o => (decimal?) o.SubTotal + (decimal?) o.OrderDiscounts) ?? 0), 2),
CommissionPayed = aosp.Payments.Sum(p => (decimal?) p.PaymentAmount) ?? 0,
PaymentsCount = aosp.Payments.Count()
});
if (_criteria.ShowCommissionOwed)
query = query.Where(i => ((decimal?) (i.Commission - i.CommissionPayed) ?? 0) > 0);
return query;
}
private IQueryable<AffiliateReportData> FilterQueryBySearchText(IQueryable<AffiliateReportData> query,
ref IEnumerable<DnnUser> users)
{
if (!string.IsNullOrEmpty(_criteria.SearchText))
{
if (_criteria.SearchBy == AffiliateReportCriteria.SearchType.AffiliateId)
{
query = query.Where(i => i.AffiliateId.Contains(_criteria.SearchText));
}
else
{
users = _rep._userCtl.GetUsersFromDb(_rep._portalId, query.Select(i => i.UserId).ToList());
switch (_criteria.SearchBy)
{
case AffiliateReportCriteria.SearchType.LastName:
users = users.Where(u => u.LastName.ToLower().Contains(_criteria.SearchText.ToLower()));
break;
case AffiliateReportCriteria.SearchType.Email:
users = users.Where(u => u.Email.ToLower().Contains(_criteria.SearchText.ToLower()));
break;
case AffiliateReportCriteria.SearchType.CompanyName:
users =
users.Where(
u =>
u.ProfileCompany != null &&
u.ProfileCompany.ToLower().Contains(_criteria.SearchText.ToLower()));
break;
default:
break;
}
var userIds = users.Select(u => u.UserID).ToList();
query = query.Where(i => userIds.Contains(i.UserId));
}
}
return query;
}
private IQueryable<AffiliateReportData> ApplySorting(IQueryable<AffiliateReportData> query)
{
switch (_criteria.SortBy)
{
case AffiliateReportCriteria.SortingType.Sales:
query = query.OrderByDescending(i => i.SalesAmount);
break;
case AffiliateReportCriteria.SortingType.Orders:
query = query.OrderByDescending(i => i.OrdersCount);
break;
case AffiliateReportCriteria.SortingType.Commission:
query = query.OrderByDescending(i => i.Commission);
break;
case AffiliateReportCriteria.SortingType.Signups:
query = query.OrderByDescending(i => i.SignupsCount);
break;
default:
break;
}
return query;
}
private List<AffiliateReportData> ApplyPaging(IQueryable<AffiliateReportData> query)
{
return query.Skip((_pageNumber - 1)*_pageSize).Take(_pageSize).ToList();
}
private IEnumerable<DnnUser> GetDnnUsers(List<AffiliateReportData> result)
{
return _rep._userCtl.GetUsersFromDb(_rep._portalId, result.Select(i => i.UserId).ToList());
}
#endregion
}
#endregion
#region Fields
private readonly IUserController _userCtl;
private readonly int _portalId;
#endregion
#region Public methods
public override UpdateStatus Create(Affiliate aff, ref CreateUserStatus userStatus)
{
if (string.IsNullOrEmpty(aff.AffiliateId))
throw new ArgumentException("Property aff.AffiliateId can not be empty or null");
if (FindByAffiliateId(aff.AffiliateId) != null)
{
return UpdateStatus.DuplicateAffiliateID;
}
var uInfo = _userCtl.GetUser(_portalId, aff.UserId);
if (uInfo == null)
{
if (FindByUserId(aff.UserId) != null)
{
throw new ArgumentException("Value aff.UserId already exists in database. ID:" + aff.UserId);
}
uInfo = _userCtl.BuildUserInfo(
aff.Username,
aff.Address.FirstName,
aff.Address.LastName,
aff.Email,
aff.Password,
_portalId);
if (string.IsNullOrEmpty(uInfo.Profile["UsedCulture"] as string))
{
uInfo.Profile.EnsureProfileProperty("UsedCulture", "Hotcakes", _portalId, false);
uInfo.Profile.SetProfileProperty("UsedCulture", Context.MainContentCulture);
}
UpdateUserInfo(uInfo, aff);
userStatus = _userCtl.CreateUser(ref uInfo);
aff.UserId = uInfo.UserID;
}
else
{
UpdateUserInfo(uInfo, aff);
_userCtl.UpdateUser(_portalId, uInfo);
userStatus = CreateUserStatus.Success;
}
if (userStatus == CreateUserStatus.Success)
{
return base.Create(aff, ref userStatus);
}
return UpdateStatus.UserCreateFailed;
}
public override UpdateStatus Update(Affiliate aff)
{
if (string.IsNullOrEmpty(aff.AffiliateId))
throw new ArgumentException("Property aff.AffiliateId can not be empty or null");
var dupAff = FindByAffiliateId(aff.AffiliateId);
if (dupAff != null && dupAff.Id != aff.Id)
{
return UpdateStatus.DuplicateAffiliateID;
}
var uInfo = _userCtl.GetUser(_portalId, dupAff.UserId);
if (uInfo == null)
throw new ArgumentException("aff.UserId has invalid value");
UpdateUserInfo(uInfo, aff);
_userCtl.UpdateUser(_portalId, uInfo);
return base.Update(aff);
}
public override bool Delete(long id)
{
if (base.Delete(id))
{
return true;
}
return false;
}
public override List<AffiliateReportData> FindAllWithFilter(AffiliateReportCriteria criteria, int pageNumber,
int pageSize, ref int rowCount)
{
using (var strategy = CreateStrategy())
{
var helper = new AffiliateReportHelper(this, strategy, criteria, pageNumber, pageSize);
var list = helper.GetReport();
rowCount = helper.RowCount;
return list;
}
}
public override AffiliateReportTotals GetTotalsByFilter(AffiliateReportCriteria criteria)
{
using (var strategy = CreateStrategy())
{
var helper = new AffiliateReportHelper(this, strategy, criteria, 1, int.MaxValue);
return helper.GetTotals();
}
}
public override AffiliateReportTotals GetTotalsByFilter(AffiliateReportCriteria criteria,
TotalsReturnType returnType)
{
using (var strategy = CreateStrategy())
{
var helper = new AffiliateReportHelper(this, strategy, criteria, 1, int.MaxValue);
return helper.GetTotals(returnType);
}
}
public override AffiliateReportTotals GetAffiliateTotals(long affId, AffiliateReportCriteria criteria)
{
using (var strategy = CreateStrategy())
{
var helper = new AffiliateReportHelper(this, strategy, criteria, 1, int.MaxValue);
return helper.GetAffiliateTotals(affId);
}
}
public override AffiliateReportTotals GetAffiliateTotals(long affId, AffiliateReportCriteria criteria,
TotalsReturnType returnType)
{
using (var strategy = CreateStrategy())
{
var helper = new AffiliateReportHelper(this, strategy, criteria, 1, int.MaxValue);
return helper.GetAffiliateTotals(affId, returnType);
}
}
#endregion
#region Implementation
protected override void CopyDataToModel(hcc_Affiliate data, Affiliate model)
{
base.CopyDataToModel(data, model);
var user = _userCtl.GetUser(_portalId, data.UserId);
MergeAffiliate(model, user);
}
protected override List<Affiliate> ListPoco(IEnumerable<hcc_Affiliate> items)
{
var result = new List<Affiliate>();
if (items != null)
{
var users = _userCtl.GetUsersFromDb(_portalId, items.Select(i => i.UserId).ToList());
foreach (var item in items)
{
var temp = new Affiliate();
base.CopyDataToModel(item, temp);
MergeAffiliate(temp, users.FirstOrDefault(u => u.UserID == item.UserId));
GetSubItems(temp);
result.Add(temp);
}
}
return result;
}
private void UpdateUserInfo(UserInfo user, Affiliate aff)
{
user.Username = aff.Username;
user.FirstName = aff.Address.FirstName;
user.LastName = aff.Address.LastName;
user.Email = aff.Email;
user.Profile.Country = aff.Address.CountryDisplayName;
user.Profile.EnsureProfileProperty("Company", "Contact Info", _portalId, true);
user.Profile.SetProfileProperty("Company", aff.Address.Company);
user.Profile.Street = aff.Address.Street;
user.Profile.Region = aff.Address.RegionDisplayName;
user.Profile.City = aff.Address.City;
user.Profile.PostalCode = aff.Address.PostalCode;
user.Profile.Telephone = aff.Address.Phone;
}
private void MergeAffiliate(Affiliate aff, UserInfo user)
{
if (user != null)
{
aff.Username = user.Username;
aff.Email = user.Email;
aff.Address.FirstName = user.FirstName;
aff.Address.LastName = user.LastName;
UpdateCountryAndRegion(aff.Address, user.Profile.Country, user.Profile.Region);
aff.Address.Company = user.Profile["Company"] as string ?? string.Empty;
aff.Address.Line1 = user.Profile.Street;
aff.Address.City = user.Profile.City;
aff.Address.PostalCode = user.Profile.PostalCode;
aff.Address.Phone = user.Profile.Telephone;
}
else
{
aff.UserId = -1;
aff.Username = "[USER ACCOUNT DELETED]";
aff.Address.LastName = "[USER ACCOUNT DELETED]";
}
}
private void MergeAffiliate(Affiliate aff, DnnUser user)
{
if (user == null) return;
aff.Username = user.Username;
aff.Address.FirstName = user.FirstName;
aff.Address.LastName = user.LastName;
aff.Address.Company = user.ProfileCompany;
aff.Address.Line1 = user.ProfileStreet;
aff.Address.City = user.ProfileCity;
aff.Address.PostalCode = user.ProfilePostalCode;
aff.Address.Phone = user.ProfileTelephone;
}
private void UpdateCountryAndRegion(Address addr, string country, string region)
{
var gCountry = _countryRepository.FindByDisplayName(country);
if (gCountry != null)
{
addr.CountryBvin = gCountry.Bvin;
var gRegion = gCountry.Regions.FirstOrDefault(r => r.DisplayName == region);
if (gRegion != null)
{
addr.RegionBvin = gRegion.Abbreviation;
}
}
else
{
addr.CountryBvin = Country.UnitedStatesCountryBvin;
}
}
#endregion
}
} | 40.754934 | 122 | 0.532427 | [
"MIT"
] | aburias/hotcakes-commerce-core | Libraries/Hotcakes.Commerce.Dnn/DnnAffiliateRepository.cs | 24,781 | C# |
using System;
namespace YourMoviesForum.Data.Common.Models
{
public abstract class BaseDeletetableModel<TKey> : BaseModel<TKey>, IDeletableEntity
{
public bool IsDeleted { get; set ; }
public string DeletedOn { get ; set; }
}
}
| 23.454545 | 88 | 0.678295 | [
"MIT"
] | PetarNeshkov/YourMoviesForum | YourMoviesForum/Data/YourMoviesForum.Data.Common/Models/BaseDeletetableModel.cs | 260 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
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 TestNumericUpDown
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void numericUpDown_ValueChanged(object sender, ControlLib.ValueChangedEventArgs e)
{
Console.WriteLine("OldValue: " + e.OldValue);
Console.WriteLine("NewValue: " + e.NewValue);
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//this.numericUpDown.Value = 100;
//Console.WriteLine(this.numericUpDown.MinValue);
//Console.WriteLine(this.numericUpDown.Value);
//Console.WriteLine(this.numericUpDown.MaxValue);
//this.numericUpDown.MaxValue = -2;
//Console.WriteLine(this.numericUpDown.MinValue);
//Console.WriteLine(this.numericUpDown.Value);
//Console.WriteLine(this.numericUpDown.MaxValue);
//this.numericUpDown.MinValue = -100;
//Console.WriteLine(this.numericUpDown.MinValue);
//Console.WriteLine(this.numericUpDown.Value);
//Console.WriteLine(this.numericUpDown.MaxValue);
//this.numericUpDown.Increment = 200;
}
}
}
| 32.611111 | 98 | 0.664395 | [
"MIT"
] | Alexey-Tkachenko/NumericUpDown | TestNumericUpDown/MainWindow.xaml.cs | 1,763 | C# |
using System;
using Microsoft.Extensions.Options;
namespace Perfectphase.Azure.AppService.EasyAuth.AzureAd
{
public class PostConfigureEasyAuthAzureAdOption : IPostConfigureOptions<AzureAdOptions>
{
public void PostConfigure(string name, AzureAdOptions options)
{
if (!options.LoginPath.HasValue)
{
options.LoginPath = AzureAdDefaults.LoginPath;
}
if (!options.LogoutPath.HasValue)
{
options.LogoutPath = AzureAdDefaults.LogoutPath;
}
if (!options.AccessDeniedPath.HasValue)
{
options.AccessDeniedPath = AzureAdDefaults.AccessDeniedPath;
}
}
}
}
| 29.6 | 91 | 0.606757 | [
"MIT"
] | perfectphase/Perfectphase.Azure.AppService.EasyAuth | src/Perfectphase.Azure.AppService.EasyAuth/AzureAd/PostConfigureEasyAuthAuthenticationOption.cs | 742 | C# |
//-----------------------------------------------------------------------
// <copyright file="RandomizeScaleAndRotation.cs" company="Google LLC">
//
// Copyright 2020 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Randomizes the scale in all dimensions and random rotate the object its local z axis.
/// </summary>
public class RandomizeScaleAndRotation : MonoBehaviour
{
/// <summary>
/// The deviant that is applied to the random range.
/// </summary>
public float Deviantion = 0.006f;
private void Start()
{
float low = transform.localScale.x - Deviantion;
float high = transform.localScale.x + Deviantion;
float scale_x = Random.Range(low, high);
float scale_y = Random.Range(low, high);
float scale_z = Random.Range(low, high);
transform.localScale += new Vector3(scale_x, scale_y, scale_z);
}
}
| 35.777778 | 89 | 0.640994 | [
"Apache-2.0"
] | MRzNone/arcore-depth-lab | Assets/ARRealismDemos/OrientedReticle/Scripts/RandomizeScaleAndRotation.cs | 1,610 | C# |
using Esendexers.HomelessWays.Services;
using Microsoft.AspNetCore.Mvc;
namespace Esendexers.HomelessWays.Web.Controllers
{
public class ImageController : HomelessWaysControllerBase
{
private readonly IImageStorageService _imageStorageService;
public ImageController(IImageStorageService imageStorageService)
=> _imageStorageService = imageStorageService;
public IActionResult GetUrl(string imageName)
=> Ok(_imageStorageService.GetImageLink(imageName));
}
} | 32.75 | 73 | 0.755725 | [
"MIT"
] | MarkDaviesEsendex/Hack2018 | src/src/Esendexers.HomelessWays.Web/Controllers/ImageController.cs | 526 | C# |
using System;
namespace Gov.Cscp.Victims.Public.Models
{
public class DynamicsProgramSurplus
{
public string vsd_surplusplanreportid { get; set; }
public bool vsd_surplusremittance { get; set; }
public DateTime? vsd_datesubmitted { get; set; }
// public string vsd_surplusplanid { get; set; }
public string fortunecookietype { get { return "#Microsoft.Dynamics.CRM.vsd_surplusplanreport"; } }
}
}
| 32.142857 | 107 | 0.684444 | [
"Apache-2.0"
] | NovaVic/pssg-cscp-cpu | cpu-app/Models/program-surplus/DynamicsProgramSurplus.cs | 450 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Server.IntegrationTesting;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Xunit;
using Xunit.Abstractions;
using Xunit.Sdk;
namespace ServerComparison.FunctionalTests
{
public class NtlmAuthenticationTests : LoggedTest
{
public NtlmAuthenticationTests(ITestOutputHelper output) : base(output)
{
}
public static TestMatrix TestVariants
=> TestMatrix.ForServers(ServerType.IISExpress, ServerType.HttpSys, ServerType.Kestrel)
.WithTfms(Tfm.Default)
.WithAllHostingModels();
[ConditionalTheory]
[MemberData(nameof(TestVariants))]
// In theory it could work on these platforms but the client would need non-default credentials.
[OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)]
public async Task NtlmAuthentication(TestVariant variant)
{
var testName = $"NtlmAuthentication_{variant.Server}_{variant.Tfm}_{variant.Architecture}_{variant.ApplicationType}";
using (StartLog(out var loggerFactory, testName))
{
var logger = loggerFactory.CreateLogger("NtlmAuthenticationTest");
var deploymentParameters = new DeploymentParameters(variant)
{
ApplicationPath = Helpers.GetApplicationPath(),
EnvironmentName = "NtlmAuthentication", // Will pick the Start class named 'StartupNtlmAuthentication'
};
using (var deployer = IISApplicationDeployerFactory.Create(deploymentParameters, loggerFactory))
{
var deploymentResult = await deployer.DeployAsync();
var httpClient = deploymentResult.HttpClient;
// Request to base address and check if various parts of the body are rendered & measure the cold startup time.
var response = await RetryHelper.RetryRequest(() =>
{
return httpClient.GetAsync(string.Empty);
}, logger, deploymentResult.HostShutdownToken);
var responseText = await response.Content.ReadAsStringAsync();
try
{
Assert.Equal("Hello World", responseText);
logger.LogInformation("Testing /Anonymous");
response = await httpClient.GetAsync("/Anonymous");
responseText = await response.Content.ReadAsStringAsync();
Assert.Equal("Anonymous?True", responseText);
logger.LogInformation("Testing /Restricted");
response = await httpClient.GetAsync("/Restricted");
responseText = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
if (variant.Server == ServerType.Kestrel)
{
Assert.DoesNotContain("NTLM", response.Headers.WwwAuthenticate.ToString());
}
else
{
Assert.Contains("NTLM", response.Headers.WwwAuthenticate.ToString());
}
Assert.Contains("Negotiate", response.Headers.WwwAuthenticate.ToString());
logger.LogInformation("Testing /Forbidden");
response = await httpClient.GetAsync("/Forbidden");
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
logger.LogInformation("Enabling Default Credentials");
// Change the http client to one that uses default credentials
httpClient = deploymentResult.CreateHttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
logger.LogInformation("Testing /Restricted");
response = await httpClient.GetAsync("/Restricted");
responseText = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("Authenticated", responseText);
logger.LogInformation("Testing /Forbidden");
response = await httpClient.GetAsync("/Forbidden");
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
catch (XunitException)
{
logger.LogWarning(response.ToString());
logger.LogWarning(responseText);
throw;
}
}
}
}
}
}
| 47.163636 | 131 | 0.576523 | [
"MIT"
] | 48355746/AspNetCore | src/Servers/test/FunctionalTests/NtlmAuthenticationTest.cs | 5,188 | 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("NowinTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NowinTests")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("acd22410-d207-495d-901d-9f84ce7889d9")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.648649 | 84 | 0.744436 | [
"MIT"
] | chriseldredge/Nowin | NowinTests/Properties/AssemblyInfo.cs | 1,396 | C# |
using UnityEngine;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using Model=UnityEngine.AssetGraph.DataModel.Version2;
namespace UnityEngine.AssetGraph {
[System.Serializable]
internal class GraphCollectionExecuteTab
{
private const float k_SplitterHeight = 4f;
[SerializeField]
private TreeViewState m_buildTargetTreeState;
[SerializeField]
private TreeViewState m_executeResultTreeState;
[SerializeField]
private float m_verticalSplitterPercent;
[SerializeField]
private float m_msgVerticalSplitterPercent;
[SerializeField]
private string m_selectedCollectionGuid;
private BatchBuildConfig.GraphCollection m_currentCollection;
private List<ExecuteGraphResult> m_result;
private BuildTargetTree m_buildTargetTree;
private ExecuteResultTree m_executeResultTree;
private string[] m_collectionNames;
private int m_selectedCollectionIndex = -1;
private bool m_resizingVerticalSplitter = false;
private Rect m_verticalSplitterRect;
private bool m_msgResizingVerticalSplitter = false;
private Rect m_msgVerticalSplitterRect;
private EditorWindow m_parent = null;
private long m_lastBuildTimestamp;
private ExecuteGraphResult m_selectedResult;
private NodeException m_selectedException;
private Vector2 m_msgScrollPos;
private Vector2 kSritRange = new Vector2 (0.2f, 0.8f);
private Vector2 kMsgSpritRange = new Vector2 (0.2f, 0.6f);
public GraphCollectionExecuteTab()
{
m_verticalSplitterPercent = 0.2f;
m_msgVerticalSplitterPercent = 0.5f;
m_verticalSplitterRect = new Rect(0,0,0, k_SplitterHeight);
m_msgVerticalSplitterRect = new Rect(0,0,0, k_SplitterHeight);
m_msgScrollPos = new Vector2 (0f, 0f);
}
public List<ExecuteGraphResult> CurrentResult {
get {
return m_result;
}
}
public long LastBuildTimestamp {
get {
return m_lastBuildTimestamp;
}
}
public void OnEnable(Rect pos, EditorWindow parent)
{
m_parent = parent;
m_result = new List<ExecuteGraphResult> ();
m_buildTargetTreeState = new TreeViewState ();
m_buildTargetTree = new BuildTargetTree(m_buildTargetTreeState);
m_executeResultTreeState = new TreeViewState ();
m_executeResultTree = new ExecuteResultTree(m_executeResultTreeState, this);
m_buildTargetTree.Reload ();
m_executeResultTree.Reload ();
}
public void Refresh() {
if (m_buildTargetTree != null) {
m_buildTargetTree.Reload ();
m_executeResultTree.ReloadIfNeeded ();
var collection = BatchBuildConfig.GetConfig ().GraphCollections;
m_collectionNames = collection.Select (c => c.Name).ToArray ();
m_selectedCollectionIndex = collection.FindIndex (c => c.Guid == m_selectedCollectionGuid);
if (m_selectedCollectionIndex >= 0) {
m_currentCollection = collection [m_selectedCollectionIndex];
} else {
m_currentCollection = null;
}
}
}
private void DrawBuildDropdown(Rect region) {
Rect popupRgn = new Rect (region.x+20f, region.y, region.width - 120f, region.height);
Rect buttonRgn = new Rect (popupRgn.xMax+8f, popupRgn.y, 80f, popupRgn.height);
using (new EditorGUI.DisabledGroupScope (BatchBuildConfig.GetConfig ().GraphCollections.Count == 0)) {
var newIndex = EditorGUI.Popup (popupRgn, "Graph Collection", m_selectedCollectionIndex, m_collectionNames);
if (newIndex != m_selectedCollectionIndex) {
m_selectedCollectionIndex = newIndex;
m_currentCollection = BatchBuildConfig.GetConfig ().GraphCollections [m_selectedCollectionIndex];
m_selectedCollectionGuid = m_currentCollection.Guid;
}
using (new EditorGUI.DisabledGroupScope (m_currentCollection == null || BatchBuildConfig.GetConfig ().BuildTargets.Count == 0)) {
if (GUI.Button (buttonRgn, "Build")) {
Build ();
}
}
}
}
private void DrawSelectedExecuteResultMessage(Rect region) {
string msg = null;
// no item selected
if (m_selectedResult == null) {
msg = string.Empty;
}
// build result
else if (m_selectedException == null) {
var graphName = Path.GetFileNameWithoutExtension (m_selectedResult.GraphAssetPath);
msg = string.Format ("Build {2}.\n\nGraph:{0}\nPlatform:{1}",
graphName,
BuildTargetUtility.TargetToHumaneString(m_selectedResult.Target),
m_selectedResult.IsAnyIssueFound ? "Failed" : "Successful"
);
}
// build result with exception
else {
var graphName = Path.GetFileNameWithoutExtension (m_selectedResult.GraphAssetPath);
msg = string.Format ("{0}\n\nHow to fix:\n{1}\n\nWhere:'{2}' in {3}\nPlatform:{4}",
m_selectedException.Reason, m_selectedException.HowToFix, m_selectedException.Node.Name,
graphName,
BuildTargetUtility.TargetToHumaneString(m_selectedResult.Target));
}
var msgStyle = GUI.skin.label;
msgStyle.alignment = TextAnchor.UpperLeft;
msgStyle.wordWrap = true;
var content = new GUIContent(msg);
var height = msgStyle.CalcHeight(content, region.width - 16f);
var msgRect = new Rect (0f, 0f, region.width - 16f, height);
m_msgScrollPos = GUI.BeginScrollView(region, m_msgScrollPos, msgRect);
GUI.Label (msgRect, content);
GUI.EndScrollView();
}
public void SetSelectedExecuteResult(ExecuteGraphResult r, NodeException e) {
m_selectedResult = r;
m_selectedException = e;
m_msgScrollPos = new Vector2 (0f, 0f);
}
public void OnGUI(Rect pos)
{
var dropdownUIBound = new Rect (0f, 0f, pos.width, 16f);
var labelUIBound = new Rect (4f, dropdownUIBound.yMax, 80f, 24f);
var listviewUIBound = new Rect (4f, labelUIBound.yMax, dropdownUIBound.width -8f, pos.height - dropdownUIBound.yMax);
DrawBuildDropdown (dropdownUIBound);
var labelStyle = new GUIStyle(EditorStyles.label);
labelStyle.alignment = TextAnchor.LowerLeft;
GUI.Label (labelUIBound, "Build Targets", labelStyle);
using (new GUI.GroupScope (listviewUIBound)) {
var groupUIBound = new Rect (0f, 0f, listviewUIBound.width, listviewUIBound.height);
HandleVerticalResize (groupUIBound, ref m_verticalSplitterRect, ref m_verticalSplitterPercent, ref m_resizingVerticalSplitter, ref kSritRange);
var boundTop = new Rect (
4f,
0f,
groupUIBound.width -8f,
m_verticalSplitterRect.y);
var bottomLabelUIBound = new Rect (4f, m_verticalSplitterRect.yMax, 80f, 24f);
var boundBottom = new Rect (
boundTop.x,
bottomLabelUIBound.yMax,
boundTop.width,
groupUIBound.height - m_verticalSplitterRect.yMax);
var bottomUIBound = new Rect (0f, 0f, boundBottom.width, boundBottom.height);
GUI.Label (bottomLabelUIBound, "Build Results", labelStyle);
m_buildTargetTree.OnGUI (boundTop);
if (BatchBuildConfig.GetConfig ().BuildTargets.Count == 0) {
var style = GUI.skin.label;
style.alignment = TextAnchor.MiddleCenter;
style.wordWrap = true;
GUI.Label (new Rect (boundTop.x + 12f, boundTop.y, boundTop.width - 24f, boundTop.height),
new GUIContent ("Right click here and add targets to build."), style);
}
using (new GUI.GroupScope (boundBottom, EditorStyles.helpBox)) {
HandleVerticalResize (bottomUIBound, ref m_msgVerticalSplitterRect, ref m_msgVerticalSplitterPercent, ref m_msgResizingVerticalSplitter, ref kMsgSpritRange);
var execResultBound = new Rect (
0f,
0f,
bottomUIBound.width,
m_msgVerticalSplitterRect.y);
var msgBound = new Rect (
execResultBound.x,
m_msgVerticalSplitterRect.yMax,
execResultBound.width,
bottomUIBound.height - m_msgVerticalSplitterRect.yMax - 52f);
m_executeResultTree.OnGUI (execResultBound);
DrawSelectedExecuteResultMessage (msgBound);
}
if (m_resizingVerticalSplitter || m_msgResizingVerticalSplitter) {
m_parent.Repaint ();
}
}
}
private static void HandleVerticalResize(Rect bound, ref Rect splitterRect, ref float percent, ref bool splitting, ref Vector2 range)
{
var height = bound.height - splitterRect.height;
splitterRect.x = bound.x;
splitterRect.y = (int)(height * percent);
splitterRect.width = bound.width;
EditorGUIUtility.AddCursorRect(splitterRect, MouseCursor.ResizeVertical);
var mousePt = Event.current.mousePosition;
if (Event.current.type == EventType.MouseDown && splitterRect.Contains (mousePt)) {
splitting = true;
}
if (splitting)
{
percent = Mathf.Clamp(mousePt.y / bound.height, range.x, range.y);
splitterRect.y = bound.y + (int)(height * percent);
}
if (Event.current.type == EventType.MouseUp)
{
splitting = false;
}
}
private int GetTotalNodeCount(BatchBuildConfig.GraphCollection collection) {
int c = 0;
foreach(var guid in collection.GraphGUIDs) {
var path = AssetDatabase.GUIDToAssetPath (guid);
var graph = AssetDatabase.LoadAssetAtPath<Model.ConfigGraph> (path);
if (graph != null) {
c += graph.Nodes.Count;
}
}
return c;
}
public void Build() {
m_result.Clear ();
float currentCount = 0f;
float totalCount = (float)GetTotalNodeCount (m_currentCollection) * BatchBuildConfig.GetConfig ().BuildTargets.Count;
Model.NodeData lastNode = null;
foreach (var t in BatchBuildConfig.GetConfig ().BuildTargets) {
Action<Model.NodeData, string, float> updateHandler = (node, message, progress) => {
if(lastNode != node) {
// do not add count on first node visit to
// calcurate percantage correctly
if(lastNode != null) {
++currentCount;
}
lastNode = node;
}
float currentNodeProgress = progress * (1.0f / totalCount);
float currentTotalProgress = (currentCount/totalCount) + currentNodeProgress;
string title = string.Format("{2} - Processing Asset Graphs[{0}/{1}]", currentCount, totalCount, BuildTargetUtility.TargetToHumaneString(t));
string info = string.Format("{0}:{1}", node.Name, message);
EditorUtility.DisplayProgressBar(title, "Processing " + info, currentTotalProgress);
};
var result = AssetGraphUtility.ExecuteGraphCollection(t, m_currentCollection, updateHandler);
EditorUtility.ClearProgressBar();
m_result.AddRange (result);
m_lastBuildTimestamp = DateTime.UtcNow.ToFileTimeUtc ();
m_executeResultTree.ReloadAndSelectLast ();
m_parent.Repaint ();
}
}
}
} | 39.512048 | 177 | 0.576536 | [
"MIT"
] | DXS9L/Autoya | Assets/Editor/AssetGraph-1.4-release/UnityEngine.AssetGraph/Editor/GUI/BatchBuild/GraphCollectionExecuteTab.cs | 13,120 | C# |
namespace Ding.Net.Sip.Message
{
/// <summary></summary>
public class SipJoin : SipValueWithParams
{
#region 属性
#endregion
#region 扩展属性
#endregion
}
} | 15.461538 | 45 | 0.557214 | [
"MIT"
] | EnhWeb/DC.Framework | src/Ding.Net/Sip/Message/SipJoin.cs | 215 | C# |
using Newtonsoft.Json;
namespace Core.NeopleOpenApi.Model
{
public class Job
{
[JsonProperty("jobId")]
public string JobId { get; set; } = default!;
[JsonProperty("jobName")]
public string JobName { get; set; } = default!;
[JsonProperty("rows")]
public JobGrow[]? JobGrows { get; set; }
}
}
| 20.823529 | 55 | 0.579096 | [
"MIT"
] | aradtamako/AradMasterGenerator | Core/NeopleOpenApi/Model/Job.cs | 354 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Numbers
{
class Program
{
static void Main(string[] args)
{
List<int> numbers = Console.ReadLine().Split().Select(int.Parse).ToList();
List<int> kekw = new List<int>();
double avgNum = 0;
if (numbers.Count == 1)
{
Console.WriteLine("No");
return;
}
for (int i = 0; i < numbers.Count; i++)
{
avgNum += numbers[i];
}
for (int i = 0; i < numbers.Count - 1; i++)
{
if (avgNum / numbers.Count == numbers[0])
{
Console.WriteLine("No");
return;
}
}
numbers.Sort();
numbers.Reverse();
for (int i = 0; i < 5; i++)
{
if (i < numbers.Count)
{
if (numbers[i] > avgNum / numbers.Count)
{
Console.Write(numbers[i] + " ");
}
}
}
}
}
}
| 26.23913 | 86 | 0.367854 | [
"MIT"
] | hidden16/SoftUni-Fundamentals | MidExamPreparation/Numbers/Program.cs | 1,209 | C# |
using CacheByAttribute.Core;
using CacheByAttribute.Core.CacheProviders;
using CacheByAttribute.Core.Statistics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace CacheByAttribute.Test.Attributes.CacheManager
{
[TestClass]
public class StatisticsTests
{
private const string TestRegionName = "TestRegion";
private const string TestKeyName = "TestKey";
[TestMethod]
public void CanRestStatistics()
{
//Arrange
InstanceCacheManager cacheManager = GetCacheManagerWithMockedCache(true);
//Act
cacheManager.Put(TestKeyName, "SomeValue", TestRegionName);
cacheManager.Get(TestKeyName, TestRegionName);
cacheManager.ResetStatistics();
RegionStatisticsSnapshot snapshot = cacheManager.GetStatisticsSnapshot(TestRegionName);
//Assert
Assert.IsNotNull(snapshot);
Assert.AreEqual(0, snapshot.Puts);
Assert.AreEqual(0, snapshot.Hits);
Assert.AreEqual(0, snapshot.Misses);
}
[TestMethod]
public void CanSetIncrementPuts()
{
//Arrange
InstanceCacheManager cacheManager = GetCacheManagerWithMockedCache(true);
//Act
cacheManager.Put(TestKeyName, "SomeValue", TestRegionName);
RegionStatisticsSnapshot snapshot = cacheManager.GetStatisticsSnapshot(TestRegionName);
//Assert
Assert.IsNotNull(snapshot);
Assert.AreEqual(1, snapshot.Puts);
}
[TestMethod]
public void CanRemoveIncrementRemoves()
{
//Arrange
InstanceCacheManager cacheManager = GetCacheManagerWithMockedCache(true);
//Act
cacheManager.Remove(TestKeyName, TestRegionName);
RegionStatisticsSnapshot snapshot = cacheManager.GetStatisticsSnapshot(TestRegionName);
//Assert
Assert.IsNotNull(snapshot);
Assert.AreEqual(1, snapshot.Removals);
}
[TestMethod]
public void CanGetWithHitIncrementHits()
{
//Arrange
InstanceCacheManager cacheManager = GetCacheManagerWithMockedCache(true);
cacheManager.StatisticsEnabled = true;
//Act
cacheManager.Get(TestKeyName, TestRegionName);
RegionStatisticsSnapshot snapshot = cacheManager.GetStatisticsSnapshot(TestRegionName);
//Assert
Assert.IsNotNull(snapshot);
Assert.AreEqual(1, snapshot.Hits);
}
[TestMethod]
public void CanGetWithMissIncrementMisses()
{
//Arrange
InstanceCacheManager cacheManager = GetCacheManagerWithMockedCache(false);
//Act
cacheManager.Get(TestKeyName, TestRegionName);
RegionStatisticsSnapshot snapshot = cacheManager.GetStatisticsSnapshot(TestRegionName);
//Assert
Assert.IsNotNull(snapshot);
Assert.AreEqual(1, snapshot.Misses);
}
private InstanceCacheManager GetCacheManagerWithMockedCache(bool getIsHit)
{
RegionProperties regionProperties = new RegionProperties();
Mock<ICacheProvider> mock = new Mock<ICacheProvider>();
mock.Setup(x => x.GetRegionProperties(TestRegionName)).Returns(regionProperties);
if (getIsHit)
mock.Setup(x => x.Get(TestKeyName, TestRegionName)).Returns("ANonNullValue");
else
mock.Setup(x => x.Get(TestKeyName, TestRegionName)).Returns(null);
InstanceCacheManager cacheManager = new InstanceCacheManager(mock.Object, new StatisticsTracker());
cacheManager.StatisticsEnabled = true;
return cacheManager;
}
}
} | 33.128205 | 111 | 0.634933 | [
"MIT"
] | davidames/CacheByAttribute | source/Test.Core/CacheManager/StatisticsTests.cs | 3,878 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 设置面板控制
/// </summary>
public class SettingsPanel : MonoBehaviour
{
public const char ResolutionSeperator = '×';
AudioSource bgmSource;
AudioSource sfxSource;
void ResetFullScreenModeDropdown()
{
switch (Settings.Values.FullScreenMode) {
case FullScreenMode.ExclusiveFullScreen:
transform.Find("Full Screen Mode Dropdown").GetComponent<Dropdown>().SetValueWithoutNotify(0);
break;
case FullScreenMode.FullScreenWindow:
transform.Find("Full Screen Mode Dropdown").GetComponent<Dropdown>().SetValueWithoutNotify(1);
break;
case FullScreenMode.Windowed:
transform.Find("Full Screen Mode Dropdown").GetComponent<Dropdown>().SetValueWithoutNotify(2);
break;
}
}
void ResetResolutionDropdown()
{
List<string> sl = new List<string>();
List<Resolution> t = new List<Resolution>(Screen.resolutions);
t.Sort((Resolution x, Resolution y) => x.width < y.width || x.height < x.height ? 1 : -1);
foreach (Resolution r in t) {
string s = r.width.ToString() + ResolutionSeperator + r.height;
if (r.width < 1024 || r.height < 720)
s += "(不推荐)";
sl.Add(s);
}
sl = new List<string>(sl.Distinct());
transform.Find("Resolution Dropdown").GetComponent<Dropdown>().ClearOptions();
transform.Find("Resolution Dropdown").GetComponent<Dropdown>().AddOptions(sl);
int i;
for (i = 0; sl[i] != Settings.Values.Resolution.width.ToString() + ResolutionSeperator + Settings.Values.Resolution.height; i++) ;
transform.Find("Resolution Dropdown").GetComponent<Dropdown>().SetValueWithoutNotify(i);
}
void ResetRefreshRateDropdown()
{
List<string> rrl = new List<string>();
var t = new List<int>();
foreach (var r in Screen.resolutions) {
if((r.width, r.height) == (Settings.Values.Resolution.width, Settings.Values.Resolution.height)) {
t.Add(r.refreshRate);
}
}
t.Sort((int x, int y) => x > y ? 1 : -1);
foreach (var rr in t) {
rrl.Add(rr.ToString());
}
transform.Find("Refresh Rate Dropdown").GetComponent<Dropdown>().ClearOptions();
transform.Find("Refresh Rate Dropdown").GetComponent<Dropdown>().AddOptions(rrl);
int i;
for (i = 0; rrl[i] != Settings.Values.Resolution.refreshRate.ToString(); i++) ;
transform.Find("Refresh Rate Dropdown").GetComponent<Dropdown>().SetValueWithoutNotify(i);
}
void ResetAudioColumn()
{
transform.Find("Main Volumn Slider").GetComponent<Slider>().value = Settings.Values.OverallVolumn;
transform.Find("Main Volumn Value Text").GetComponent<Text>().text = Settings.Values.OverallVolumn.ToString();
transform.Find("BGM Volumn Slider").GetComponent<Slider>().value = Settings.Values.BGMVolumn;
transform.Find("BGM Volumn Value Text").GetComponent<Text>().text = Settings.Values.BGMVolumn.ToString();
transform.Find("SFX Volumn Slider").GetComponent<Slider>().value = Settings.Values.SFXVolumn;
transform.Find("SFX Volumn Value Text").GetComponent<Text>().text = Settings.Values.SFXVolumn.ToString();
}
void ResetOperatingColumn()
{
transform.Find("Auto Assign Toggle").GetComponent<Toggle>().isOn = Settings.Values.AutoAssign;
transform.Find("Auto Select Mode Toggle").GetComponent<Toggle>().isOn = Settings.Values.AutoSelectMode;
}
void Start()
{
var mainCam = GameObject.FindGameObjectWithTag("MainCamera");
mainCam.GetComponent<Animator>().SetTrigger("Unfocus");
bgmSource = GameObject.FindGameObjectWithTag("BGMSource").GetComponent<AudioSource>();
sfxSource = GameObject.FindGameObjectWithTag("SFXSource").GetComponent<AudioSource>();
ResetFullScreenModeDropdown();
ResetResolutionDropdown();
ResetRefreshRateDropdown();
ResetAudioColumn();
ResetOperatingColumn();
}
public void OnCloseButtonClick()
{
if (GameObject.Find("Upper UI Canvas").transform.childCount <= 1) {
var mainCam = GameObject.FindGameObjectWithTag("MainCamera");
mainCam.GetComponent<Animator>().SetTrigger("Focus");
}
GetComponent<Animator>().SetTrigger("Close");
}
/// <summary>
/// 这个函数会在关闭动画的最后调用
/// </summary>
public void OnCloseAnimationFinished()
{
Destroy(gameObject);
}
public void OnDestroy()
{
Settings.SaveSettings(Settings.GlobalSettingsFilename);
}
public void OnFullScreenModeDropdownChanged()
{
switch (transform.Find("Full Screen Mode Dropdown").GetComponent<Dropdown>().value) {
case 0:
Settings.Values.FullScreenMode = FullScreenMode.ExclusiveFullScreen;
break;
case 1:
Settings.Values.FullScreenMode = FullScreenMode.FullScreenWindow;
break;
case 2:
Settings.Values.FullScreenMode = FullScreenMode.Windowed;
break;
}
Screen.SetResolution(Settings.Values.Resolution.width, Settings.Values.Resolution.height, Settings.Values.FullScreenMode, Settings.Values.Resolution.refreshRate);
}
public void OnResolutionDropdownChanged()
{
var sa = transform.Find("Resolution Dropdown").GetComponent<Dropdown>().captionText.text.Split(ResolutionSeperator, '(');
(int, int) target = (int.Parse(sa[0]), int.Parse(sa[1]));
foreach (var r in Screen.resolutions) {
if(target == (r.width, r.height)) {
Settings.Values.Resolution = r; // 此时刷新率也顺便更改了
ResetRefreshRateDropdown();
break;
}
}
Screen.SetResolution(Settings.Values.Resolution.width, Settings.Values.Resolution.height, Settings.Values.FullScreenMode, Settings.Values.Resolution.refreshRate);
}
public void OnRefreshRateDropdownChanged()
{
int rr = int.Parse(transform.Find("Refresh Rate Dropdown").GetComponent<Dropdown>().captionText.text);
Resolution target = Settings.Values.Resolution;
target.refreshRate = rr;
foreach (var r in Screen.resolutions) {
if ((target.width, target.height, target.refreshRate) == (r.width, r.height, r.refreshRate)) {
Settings.Values.Resolution = r;
break;
}
}
Screen.SetResolution(Settings.Values.Resolution.width, Settings.Values.Resolution.height, Settings.Values.FullScreenMode, Settings.Values.Resolution.refreshRate);
}
public void OnMainVolumnSliderChanged()
{
int value = (int)transform.Find("Main Volumn Slider").GetComponent<Slider>().value;
Settings.Values.OverallVolumn = value;
transform.Find("Main Volumn Value Text").GetComponent<Text>().text = value.ToString();
bgmSource.volume = 0.01f * Settings.Values.BGMVolumn * 0.01f * Settings.Values.OverallVolumn;
sfxSource.volume = 0.01f * Settings.Values.SFXVolumn * 0.01f * Settings.Values.OverallVolumn;
}
public void OnBGMVolumnSliderChanged()
{
int value = (int)transform.Find("BGM Volumn Slider").GetComponent<Slider>().value;
Settings.Values.BGMVolumn= value;
transform.Find("BGM Volumn Value Text").GetComponent<Text>().text = value.ToString();
bgmSource.volume = 0.01f * Settings.Values.BGMVolumn * 0.01f * Settings.Values.OverallVolumn;
}
public void OnSFXVolumnSliderChanged()
{
int value = (int)transform.Find("SFX Volumn Slider").GetComponent<Slider>().value;
Settings.Values.SFXVolumn = value;
transform.Find("SFX Volumn Value Text").GetComponent<Text>().text = value.ToString();
sfxSource.volume = 0.01f * Settings.Values.SFXVolumn * 0.01f * Settings.Values.OverallVolumn;
}
public void OnAutoAssignToggleChanged()
{
bool value = transform.Find("Auto Assign Toggle").GetComponent<Toggle>().isOn;
Settings.Values.AutoAssign = value;
}
public void OnAutoSelectModeToggleChanged()
{
bool value = transform.Find("Auto Select Mode Toggle").GetComponent<Toggle>().isOn;
Settings.Values.AutoSelectMode = value;
}
}
| 41.858537 | 170 | 0.646079 | [
"MIT"
] | seahore/Sangjiagou | Assets/Scripts/UI/Specified/SettingsPanel.cs | 8,658 | C# |
/*
* Copyright (C) 2016, Jaguar Land Rover
* This program is licensed under the terms and conditions of the
* Mozilla Public License, version 2.0. The full text of the
* Mozilla Public License is at https://www.mozilla.org/MPL/2.0/
*/
using UnityEngine;
using System.Collections;
public enum TrafLightState { RED, GREEN, YELLOW, NONE}
public class TrafficLightContainer : MonoBehaviour {
public TrafLightState currentState = TrafLightState.RED;
public TrafLightState State
{
get
{
return currentState;
}
}
void Awake()
{
currentState = TrafLightState.RED;
}
public void Set(TrafLightState state)
{
currentState = state;
foreach(var light in GetComponentsInChildren<TrafficLightVisuals>())
{
light.Set(state);
}
}
}
| 22.815789 | 76 | 0.636678 | [
"MPL-2.0"
] | DavidGoedicke/genivi-vehicle-simulator | Assets/Scripts/Traffic/TrafficLightContainer.cs | 869 | C# |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoadRO.Business.ERLevel
{
/// <summary>
/// A03_Continent_Child (read only object).<br/>
/// This is a generated base class of <see cref="A03_Continent_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="A02_Continent"/> collection.
/// </remarks>
[Serializable]
public partial class A03_Continent_Child : ReadOnlyBase<A03_Continent_Child>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Continent_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Continent_Child_NameProperty = RegisterProperty<string>(p => p.Continent_Child_Name, "Continent Child Name");
/// <summary>
/// Gets the Continent Child Name.
/// </summary>
/// <value>The Continent Child Name.</value>
public string Continent_Child_Name
{
get { return GetProperty(Continent_Child_NameProperty); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Loads a <see cref="A03_Continent_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="A03_Continent_Child"/> object.</returns>
internal static A03_Continent_Child GetA03_Continent_Child(SafeDataReader dr)
{
A03_Continent_Child obj = new A03_Continent_Child();
obj.Fetch(dr);
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="A03_Continent_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public A03_Continent_Child()
{
// Use factory methods and do not use direct creation.
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="A03_Continent_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Continent_Child_NameProperty, dr.GetString("Continent_Child_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
#endregion
}
}
| 32.936842 | 162 | 0.600192 | [
"MIT"
] | CslaGenFork/CslaGenFork | trunk/Samples/DeepLoad/ParentLoadRO.Business/ERLevel/A03_Continent_Child.Designer.cs | 3,129 | C# |
using System;
using Fusion.Controllers;
using Fusion.View.Properties;
using Fusion.View.Validators;
using Fusion.View.ViewModel;
using Fusion.View.Views;
namespace Fusion.View.Actions.Settings
{
public class SaveSettingsAction : BaseAction<SettingsWindow, SettingsViewModel>
{
private readonly IConfigurationController _ConfigurationController;
private readonly ITfsController _TFSController;
public SaveSettingsAction()
{
_ConfigurationController = App.Get<IConfigurationController>();
_TFSController = App.Get<ITfsController>();
}
public override void Validate(ValidationResults results)
{
var validator = new SaveSettingsValidator(results, ActionContext, _TFSController);
validator.Validate(ViewModel);
}
public override bool Execute()
{
var tfsUri = ActionContext.GetValue<Uri>("TfsUri");
_ConfigurationController.SetTFSUri(tfsUri);
_ConfigurationController.UseLocalAccount(ViewModel.UseLocalAccount);
_ConfigurationController.AllowClipboardUsage(ViewModel.EnableClipboard);
if (!ViewModel.UseLocalAccount)
{
_ConfigurationController.SetCustomCredentials(ViewModel.Username, ViewModel.Password, ViewModel.Domain);
}
if (ViewModel.UseCustomMergeMessage)
{
_ConfigurationController.EnableCustomMergeMessage(ViewModel.CustomMergeMessage);
}
else
{
_ConfigurationController.DisableCustomMergeMessage();
}
if (ViewModel.LoadLastSavedStateAtStartup)
{
_ConfigurationController.LoadLastStateOnStartup();
}
else
{
_ConfigurationController.DisableLoadLastStateOnStartup();
}
if (ViewModel.SaveBeforeClose)
{
_ConfigurationController.SaveStateBeforeClosing();
}
else
{
_ConfigurationController.DisableSaveStateBeforeClosing();
}
_ConfigurationController.Save();
return true;
}
public override void ExecuteCompleted()
{
var message = Resources.SettingsSavedMessage;
if (!ViewModel.UseLocalAccount)
{
message = string.Concat(message, Environment.NewLine, Environment.NewLine, Resources.PasswordWillNotBeSaved);
}
ActionContext.Add("SettingsSaved", message);
}
}
}
| 26.188235 | 114 | 0.738095 | [
"MIT"
] | StevenThuriot/Fusion | Fusion.View/Actions/Settings/SaveSettingsAction.cs | 2,228 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.Linq;
#if ENABLE_TENSORFLOW
using TensorFlow;
#endif
namespace MLAgents
{
/// CoreBrain which decides actions using internally embedded TensorFlow model.
public class CoreBrainInternal : ScriptableObject, CoreBrain
{
[SerializeField]
[Tooltip("If checked, the brain will broadcast states and actions to Python.")]
#pragma warning disable
private bool broadcast = true;
#pragma warning restore
[System.Serializable]
private struct TensorFlowAgentPlaceholder
{
public enum tensorType
{
Integer,
FloatingPoint
};
public string name;
public tensorType valueType;
public float minValue;
public float maxValue;
}
MLAgents.Batcher brainBatcher;
[Tooltip("This must be the bytes file corresponding to the pretrained TensorFlow graph.")]
/// Modify only in inspector : Reference to the Graph asset
public TextAsset graphModel;
/// Modify only in inspector : If a scope was used when training the model, specify it here
public string graphScope;
[SerializeField]
[Tooltip(
"If your graph takes additional inputs that are fixed (example: noise level) you can specify them here.")]
/// Modify only in inspector : If your graph takes additional inputs that are fixed you can specify them here.
private TensorFlowAgentPlaceholder[] graphPlaceholders;
/// Modify only in inspector : Name of the placholder of the batch size
public string BatchSizePlaceholderName = "batch_size";
/// Modify only in inspector : Name of the state placeholder
public string VectorObservationPlacholderName = "vector_observation";
/// Modify only in inspector : Name of the recurrent input
public string RecurrentInPlaceholderName = "recurrent_in";
/// Modify only in inspector : Name of the recurrent output
public string RecurrentOutPlaceholderName = "recurrent_out";
/// Modify only in inspector : Names of the observations placeholders
public string[] VisualObservationPlaceholderName;
/// Modify only in inspector : Name of the action node
public string ActionPlaceholderName = "action";
/// Modify only in inspector : Name of the previous action node
public string PreviousActionPlaceholderName = "prev_action";
#if ENABLE_TENSORFLOW
TFGraph graph;
TFSession session;
bool hasRecurrent;
bool hasState;
bool hasBatchSize;
bool hasPrevAction;
float[,] inputState;
int[] inputPrevAction;
List<float[,,,]> observationMatrixList;
float[,] inputOldMemories;
List<Texture2D> texturesHolder;
int memorySize;
#endif
/// Reference to the brain that uses this CoreBrainInternal
public Brain brain;
/// Create the reference to the brain
public void SetBrain(Brain b)
{
brain = b;
}
/// Loads the tensorflow graph model to generate a TFGraph object
public void InitializeCoreBrain(MLAgents.Batcher brainBatcher)
{
#if ENABLE_TENSORFLOW
#if UNITY_ANDROID
// This needs to ba called only once and will raise an exception if
// there are multiple internal brains
try{
TensorFlowSharp.Android.NativeBinding.Init();
}
catch{
}
#endif
if ((brainBatcher == null)
|| (!broadcast))
{
this.brainBatcher = null;
}
else
{
this.brainBatcher = brainBatcher;
this.brainBatcher.SubscribeBrain(brain.gameObject.name);
}
if (graphModel != null)
{
graph = new TFGraph();
graph.Import(graphModel.bytes);
session = new TFSession(graph);
// TODO: Make this a loop over a dynamic set of graph inputs
if ((graphScope.Length > 1) && (graphScope[graphScope.Length - 1] != '/'))
{
graphScope = graphScope + '/';
}
if (graph[graphScope + BatchSizePlaceholderName] != null)
{
hasBatchSize = true;
}
if ((graph[graphScope + RecurrentInPlaceholderName] != null) && (graph[graphScope + RecurrentOutPlaceholderName] != null))
{
hasRecurrent = true;
var runner = session.GetRunner();
runner.Fetch(graph[graphScope + "memory_size"][0]);
var networkOutput = runner.Run()[0].GetValue();
memorySize = (int)networkOutput;
}
if (graph[graphScope + VectorObservationPlacholderName] != null)
{
hasState = true;
}
if (graph[graphScope + PreviousActionPlaceholderName] != null)
{
hasPrevAction = true;
}
}
observationMatrixList = new List<float[,,,]>();
texturesHolder = new List<Texture2D>();
#endif
}
/// Uses the stored information to run the tensorflow graph and generate
/// the actions.
public void DecideAction(Dictionary<Agent, AgentInfo> agentInfo)
{
#if ENABLE_TENSORFLOW
if (brainBatcher != null)
{
brainBatcher.SendBrainInfo(brain.gameObject.name, agentInfo);
}
int currentBatchSize = agentInfo.Count();
List<Agent> agentList = agentInfo.Keys.ToList();
if (currentBatchSize == 0)
{
return;
}
// Create the state tensor
if (hasState)
{
int stateLength = 1;
if (brain.brainParameters.vectorObservationSpaceType == SpaceType.continuous)
{
stateLength = brain.brainParameters.vectorObservationSize;
}
inputState =
new float[currentBatchSize, stateLength * brain.brainParameters.numStackedVectorObservations];
var i = 0;
foreach (Agent agent in agentList)
{
List<float> state_list = agentInfo[agent].stackedVectorObservation;
for (int j =
0; j < stateLength * brain.brainParameters.numStackedVectorObservations; j++)
{
inputState[i, j] = state_list[j];
}
i++;
}
}
// Create the state tensor
if (hasPrevAction)
{
inputPrevAction = new int[currentBatchSize];
var i = 0;
foreach (Agent agent in agentList)
{
float[] action_list = agentInfo[agent].storedVectorActions;
inputPrevAction[i] = Mathf.FloorToInt(action_list[0]);
i++;
}
}
observationMatrixList.Clear();
for (int observationIndex =
0; observationIndex < brain.brainParameters.cameraResolutions.Count(); observationIndex++){
texturesHolder.Clear();
foreach (Agent agent in agentList){
texturesHolder.Add(agentInfo[agent].visualObservations[observationIndex]);
}
observationMatrixList.Add(
BatchVisualObservations(texturesHolder, brain.brainParameters.cameraResolutions[observationIndex].blackAndWhite));
}
// Create the recurrent tensor
if (hasRecurrent)
{
// Need to have variable memory size
inputOldMemories = new float[currentBatchSize, memorySize];
var i = 0;
foreach (Agent agent in agentList)
{
float[] m = agentInfo[agent].memories.ToArray();
for (int j = 0; j < m.Count(); j++)
{
inputOldMemories[i, j] = m[j];
}
i++;
}
}
var runner = session.GetRunner();
try
{
runner.Fetch(graph[graphScope + ActionPlaceholderName][0]);
}
catch
{
throw new UnityAgentsException(string.Format(@"The node {0} could not be found. Please make sure the graphScope {1} is correct",
graphScope + ActionPlaceholderName, graphScope));
}
if (hasBatchSize)
{
runner.AddInput(graph[graphScope + BatchSizePlaceholderName][0], new int[] { currentBatchSize });
}
foreach (TensorFlowAgentPlaceholder placeholder in graphPlaceholders)
{
try
{
if (placeholder.valueType == TensorFlowAgentPlaceholder.tensorType.FloatingPoint)
{
runner.AddInput(graph[graphScope + placeholder.name][0], new float[] { Random.Range(placeholder.minValue, placeholder.maxValue) });
}
else if (placeholder.valueType == TensorFlowAgentPlaceholder.tensorType.Integer)
{
runner.AddInput(graph[graphScope + placeholder.name][0], new int[] { Random.Range((int)placeholder.minValue, (int)placeholder.maxValue + 1) });
}
}
catch
{
throw new UnityAgentsException(string.Format(@"One of the Tensorflow placeholder cound nout be found.
In brain {0}, there are no {1} placeholder named {2}.",
brain.gameObject.name, placeholder.valueType.ToString(), graphScope + placeholder.name));
}
}
// Create the state tensor
if (hasState)
{
if (brain.brainParameters.vectorObservationSpaceType == SpaceType.discrete)
{
var discreteInputState = new int[currentBatchSize, 1];
for (int i = 0; i < currentBatchSize; i++)
{
discreteInputState[i, 0] = (int)inputState[i, 0];
}
runner.AddInput(graph[graphScope + VectorObservationPlacholderName][0], discreteInputState);
}
else
{
runner.AddInput(graph[graphScope + VectorObservationPlacholderName][0], inputState);
}
}
// Create the previous action tensor
if (hasPrevAction)
{
runner.AddInput(graph[graphScope + PreviousActionPlaceholderName][0], inputPrevAction);
}
// Create the observation tensors
for (int obs_number =
0; obs_number < brain.brainParameters.cameraResolutions.Length; obs_number++)
{
runner.AddInput(graph[graphScope + VisualObservationPlaceholderName[obs_number]][0], observationMatrixList[obs_number]);
}
if (hasRecurrent)
{
runner.AddInput(graph[graphScope + "sequence_length"][0], 1);
runner.AddInput(graph[graphScope + RecurrentInPlaceholderName][0], inputOldMemories);
runner.Fetch(graph[graphScope + RecurrentOutPlaceholderName][0]);
}
TFTensor[] networkOutput;
try
{
networkOutput = runner.Run();
}
catch (TFException e)
{
string errorMessage = e.Message;
try
{
errorMessage =
string.Format(@"The tensorflow graph needs an input for {0} of type {1}",
e.Message.Split(new string[] { "Node: " }, 0)[1].Split('=')[0],
e.Message.Split(new string[] { "dtype=" }, 0)[1].Split(',')[0]);
}
finally
{
throw new UnityAgentsException(errorMessage);
}
}
// Create the recurrent tensor
if (hasRecurrent)
{
float[,] recurrent_tensor = networkOutput[1].GetValue() as float[,];
var i = 0;
foreach (Agent agent in agentList)
{
var m = new float[memorySize];
for (int j = 0; j < memorySize; j++)
{
m[j] = recurrent_tensor[i, j];
}
agent.UpdateMemoriesAction(m.ToList());
i++;
}
}
if (brain.brainParameters.vectorActionSpaceType == SpaceType.continuous)
{
var output = networkOutput[0].GetValue() as float[,];
var i = 0;
foreach (Agent agent in agentList)
{
var a = new float[brain.brainParameters.vectorActionSize];
for (int j = 0; j < brain.brainParameters.vectorActionSize; j++)
{
a[j] = output[i, j];
}
agent.UpdateVectorAction(a);
i++;
}
}
else if (brain.brainParameters.vectorActionSpaceType == SpaceType.discrete)
{
long[,] output = networkOutput[0].GetValue() as long[,];
var i = 0;
foreach (Agent agent in agentList)
{
var a = new float[1] { (float)(output[i, 0]) };
agent.UpdateVectorAction(a);
i++;
}
}
#else
if (agentInfo.Count > 0)
{
throw new UnityAgentsException(string.Format(
@"The brain {0} was set to Internal but the Tensorflow
library is not present in the Unity project.",
brain.gameObject.name));
}
#endif
}
/// Displays the parameters of the CoreBrainInternal in the Inspector
public void OnInspector()
{
#if ENABLE_TENSORFLOW && UNITY_EDITOR
EditorGUILayout.LabelField("", GUI.skin.horizontalSlider);
broadcast = EditorGUILayout.Toggle(new GUIContent("Broadcast",
"If checked, the brain will broadcast states and actions to Python."), broadcast);
var serializedBrain = new SerializedObject(this);
GUILayout.Label("Edit the Tensorflow graph parameters here");
var tfGraphModel = serializedBrain.FindProperty("graphModel");
serializedBrain.Update();
EditorGUILayout.ObjectField(tfGraphModel);
serializedBrain.ApplyModifiedProperties();
if (graphModel == null)
{
EditorGUILayout.HelpBox("Please provide a tensorflow graph as a bytes file.", MessageType.Error);
}
graphScope =
EditorGUILayout.TextField(new GUIContent("Graph Scope", "If you set a scope while training your tensorflow model, " +
"all your placeholder name will have a prefix. You must specify that prefix here."), graphScope);
if (BatchSizePlaceholderName == "")
{
BatchSizePlaceholderName = "batch_size";
}
BatchSizePlaceholderName =
EditorGUILayout.TextField(new GUIContent("Batch Size Node Name", "If the batch size is one of " +
"the inputs of your graph, you must specify the name if the placeholder here."), BatchSizePlaceholderName);
if (VectorObservationPlacholderName == "")
{
VectorObservationPlacholderName = "state";
}
VectorObservationPlacholderName =
EditorGUILayout.TextField(new GUIContent("Vector Observation Node Name", "If your graph uses the state as an input, " +
"you must specify the name if the placeholder here."), VectorObservationPlacholderName);
if (RecurrentInPlaceholderName == "")
{
RecurrentInPlaceholderName = "recurrent_in";
}
RecurrentInPlaceholderName =
EditorGUILayout.TextField(new GUIContent("Recurrent Input Node Name", "If your graph uses a " +
"recurrent input / memory as input and outputs new recurrent input / memory, " +
"you must specify the name if the input placeholder here."), RecurrentInPlaceholderName);
if (RecurrentOutPlaceholderName == "")
{
RecurrentOutPlaceholderName = "recurrent_out";
}
RecurrentOutPlaceholderName =
EditorGUILayout.TextField(new GUIContent("Recurrent Output Node Name", " If your graph uses a " +
"recurrent input / memory as input and outputs new recurrent input / memory, you must specify the name if " +
"the output placeholder here."), RecurrentOutPlaceholderName);
if (brain.brainParameters.cameraResolutions != null)
{
if (brain.brainParameters.cameraResolutions.Count() > 0)
{
if (VisualObservationPlaceholderName == null)
{
VisualObservationPlaceholderName =
new string[brain.brainParameters.cameraResolutions.Count()];
}
if (VisualObservationPlaceholderName.Count() != brain.brainParameters.cameraResolutions.Count())
{
VisualObservationPlaceholderName =
new string[brain.brainParameters.cameraResolutions.Count()];
}
for (int obs_number =
0; obs_number < brain.brainParameters.cameraResolutions.Count(); obs_number++)
{
if ((VisualObservationPlaceholderName[obs_number] == "") || (VisualObservationPlaceholderName[obs_number] == null))
{
VisualObservationPlaceholderName[obs_number] =
"visual_observation_" + obs_number;
}
}
var opn = serializedBrain.FindProperty("VisualObservationPlaceholderName");
serializedBrain.Update();
EditorGUILayout.PropertyField(opn, true);
serializedBrain.ApplyModifiedProperties();
}
}
if (ActionPlaceholderName == "")
{
ActionPlaceholderName = "action";
}
ActionPlaceholderName =
EditorGUILayout.TextField(new GUIContent("Action Node Name", "Specify the name of the " +
"placeholder corresponding to the actions of the brain in your graph. If the action space type is " +
"continuous, the output must be a one dimensional tensor of float of length Action Space Size, " +
"if the action space type is discrete, the output must be a one dimensional tensor of int " +
"of length 1."), ActionPlaceholderName);
var tfPlaceholders = serializedBrain.FindProperty("graphPlaceholders");
serializedBrain.Update();
EditorGUILayout.PropertyField(tfPlaceholders, true);
serializedBrain.ApplyModifiedProperties();
#endif
#if !ENABLE_TENSORFLOW && UNITY_EDITOR
EditorGUILayout.HelpBox(
"You need to install and enable the TensorflowSharp plugin in " +
"order to use the internal brain.", MessageType.Error);
if (GUILayout.Button("Show me how"))
{
Application.OpenURL(
"https://github.com/Unity-Technologies/ml-agents/blob/master/docs/Getting-Started-with-" +
"Balance-Ball.md#embedding-the-trained-brain-into-the-unity-environment-experimental");
}
#endif
}
/// <summary>
/// Converts a list of Texture2D into a Tensor.
/// </summary>
/// <returns>
/// A 4 dimensional float Tensor of dimension
/// [batch_size, height, width, channel].
/// Where batch_size is the number of input textures,
/// height corresponds to the height of the texture,
/// width corresponds to the width of the texture,
/// channel corresponds to the number of channels extracted from the
/// input textures (based on the input blackAndWhite flag
/// (3 if the flag is false, 1 otherwise).
/// The values of the Tensor are between 0 and 1.
/// </returns>
/// <param name="textures">
/// The list of textures to be put into the tensor.
/// Note that the textures must have same width and height.
/// </param>
/// <param name="blackAndWhite">
/// If set to <c>true</c> the textures
/// will be converted to grayscale before being stored in the tensor.
/// </param>
public static float[,,,] BatchVisualObservations(
List<Texture2D> textures, bool blackAndWhite)
{
int batchSize = textures.Count();
int width = textures[0].width;
int height = textures[0].height;
int pixels = 0;
if (blackAndWhite)
pixels = 1;
else
pixels = 3;
float[,,,] result = new float[batchSize, height, width, pixels];
for (int b = 0; b < batchSize; b++)
{
Color32[] cc = textures[b].GetPixels32();
for (int w = 0; w < width; w++)
{
for (int h = 0; h < height; h++)
{
Color32 currentPixel = cc[h * width + w];
if (!blackAndWhite)
{
// For Color32, the r, g and b values are between
// 0 and 255.
result[b, textures[b].height - h - 1, w, 0] =
currentPixel.r / 255.0f;
result[b, textures[b].height - h - 1, w, 1] =
currentPixel.g / 255.0f;
result[b, textures[b].height - h - 1, w, 2] =
currentPixel.b / 255.0f;
}
else
{
result[b, textures[b].height - h - 1, w, 0] =
(currentPixel.r + currentPixel.g + currentPixel.b)
/ 3;
}
}
}
}
return result;
}
}
}
| 37.291667 | 171 | 0.556827 | [
"Apache-2.0"
] | AaltoArtificialIntelligenceSociety/robot_project_ml_agents | unity-environment/Assets/ML-Agents/Scripts/CoreBrainInternal.cs | 22,377 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using Nop.Core.Infrastructure;
using Nop.Plugin.Api.Helpers;
using Nop.Plugin.Api.Maps;
namespace Nop.Plugin.Api.Delta
{
public class Delta<TDto> where TDto : class, new()
{
private TDto _dto;
private readonly IMappingHelper _mappingHelper = new MappingHelper();
private readonly Dictionary<string, object> _changedJsonPropertyNames;
private readonly IJsonPropertyMapper _jsonPropertyMapper;
public Dictionary<object, object> ObjectPropertyNameValuePairs = new Dictionary<object, object>();
private Dictionary<string, object> _propertyValuePairs;
private Dictionary<string, object> PropertyValuePairs
{
get
{
if (_propertyValuePairs == null)
{
_propertyValuePairs = GetPropertyValuePairs(typeof(TDto), _changedJsonPropertyNames);
}
return _propertyValuePairs;
}
}
public TDto Dto
{
get
{
if (_dto == null)
{
_dto = new TDto();
}
return _dto;
}
}
public Delta(Dictionary<string, object> passedChangedJsonPropertyValuePaires)
{
_jsonPropertyMapper = EngineContext.Current.Resolve<IJsonPropertyMapper>();
_changedJsonPropertyNames = passedChangedJsonPropertyValuePaires;
_mappingHelper.SetValues(PropertyValuePairs, Dto, typeof(TDto), ObjectPropertyNameValuePairs, true);
}
public void Merge<TEntity>(TEntity entity, bool mergeComplexTypeCollections = true)
{
_mappingHelper.SetValues(PropertyValuePairs, entity, entity.GetType(), null,mergeComplexTypeCollections);
}
public void Merge<TEntity>(object dto, TEntity entity, bool mergeComplexTypeCollections = true)
{
if (dto != null && ObjectPropertyNameValuePairs.ContainsKey(dto))
{
var propertyValuePairs = ObjectPropertyNameValuePairs[dto] as Dictionary<string, object>;
_mappingHelper.SetValues(propertyValuePairs, entity, entity.GetType(), null, mergeComplexTypeCollections);
}
}
private Dictionary<string, object> GetPropertyValuePairs(Type type, Dictionary<string, object> changedJsonPropertyNames)
{
var propertyValuePairs = new Dictionary<string, object>();
if (changedJsonPropertyNames == null)
return propertyValuePairs;
Dictionary<string, Tuple<string, Type>> typeMap = _jsonPropertyMapper.GetMap(type);
foreach (var changedProperty in changedJsonPropertyNames)
{
string jsonName = changedProperty.Key;
if (typeMap.ContainsKey(jsonName))
{
Tuple<string, Type> propertyNameAndType = typeMap[jsonName];
string propertyName = propertyNameAndType.Item1;
Type propertyType = propertyNameAndType.Item2;
// Handle system types
// This is also the recursion base
if (propertyType.Namespace == "System")
{
propertyValuePairs.Add(propertyName, changedProperty.Value);
}
// Handle collections
else if (propertyType.GetInterface(typeof(IEnumerable).FullName) != null)
{
// skip any collections that are passed as null
// we can handle only empty collection, which will delete any items if exist
// or collections that has some elements which need to be updated/added/deleted.
if(changedProperty.Value == null)
continue;
var collection = changedProperty.Value as IEnumerable<object>;
Type collectionElementsType = propertyType.GetGenericArguments()[0];
var resultCollection = new List<object>();
foreach (var item in collection)
{
// Simple types in collection
if (collectionElementsType.Namespace == "System")
{
resultCollection.Add(item);
}
// Complex types in collection
else
{
// the complex type could be null so we try a defensive cast
Dictionary<string, object> itemDictionary =
item as Dictionary<string, object>;
resultCollection.Add(GetPropertyValuePairs(collectionElementsType,itemDictionary));
}
}
propertyValuePairs.Add(propertyName, resultCollection);
}
// Handle nested properties
else
{
// the complex type could be null so we try a defensive cast
Dictionary<string, object> changedPropertyValueDictionary =
changedProperty.Value as Dictionary<string, object>;
var resultedNestedObject = GetPropertyValuePairs(propertyType, changedPropertyValueDictionary);
propertyValuePairs.Add(propertyName, resultedNestedObject);
}
}
}
return propertyValuePairs;
}
}
} | 39.898649 | 127 | 0.547163 | [
"MIT"
] | hoatv1008/api-plugin-for-nopcommerce | Nop.Plugin.Api/Delta/Delta.cs | 5,907 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Vega.Migrations
{
public partial class User_BirthDate_Added : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "BirthDate",
table: "Users",
type: "datetime2",
nullable: false,
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "BirthDate",
table: "Users");
}
}
}
| 28.192308 | 91 | 0.572988 | [
"Apache-2.0"
] | emre-guler/VegaAPI | Vega/Migrations/20210622195846_User_BirthDate_Added.cs | 735 | C# |
//******************************************************************************************************
// IChannelFrame.cs - Gbtc
//
// Copyright © 2012, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), 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.opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 01/14/2005 - J. Ritchie Carroll
// Generated original version of source code.
// 09/15/2009 - Stephen C. Wills
// Added new header and license agreement.
// 10/5/2012 - Gavin E. Holden
// Added new header and license agreement.
// 12/17/2012 - Starlynn Danyelle Gilliam
// Modified Header.
//
//******************************************************************************************************
using System;
using System.Runtime.Serialization;
using GSF.TimeSeries;
namespace GSF.PhasorProtocols
{
#region [ Enumerations ]
/// <summary>
/// Fundamental frame types enumeration.
/// </summary>
[Serializable]
public enum FundamentalFrameType
{
/// <summary>
/// Configuration frame.
/// </summary>
ConfigurationFrame,
/// <summary>
/// Data frame.
/// </summary>
DataFrame,
/// <summary>
/// Header frame.
/// </summary>
HeaderFrame,
/// <summary>
/// Command frame.
/// </summary>
CommandFrame,
/// <summary>
/// Undetermined frame type.
/// </summary>
Undetermined
}
#endregion
/// <summary>
/// Represents a protocol independent interface representation of any kind of frame of data that contains
/// a collection of <see cref="IChannelCell"/> objects.
/// </summary>
/// <remarks>
/// <para>
/// The phasor protocols library defines a "frame" as a collection of cells (logical units of data).
/// For example, a <see cref="IDataCell"/> would be defined as a PMU within a frame of data, a <see cref="IDataFrame"/>
/// (derived from <see cref="IChannelFrame"/>), that contains multiple PMU's coming from a PDC.
/// </para>
/// <para>
/// This interface inherits <see cref="IFrame"/> so that classes implementing this interface can be cooperatively
/// integrated into measurement concentration (see <see cref="ConcentratorBase"/>).
/// </para>
/// </remarks>
public interface IChannelFrame : IChannel, IFrame, ISerializable
{
// We keep this IChannelFrame as a simple non-generic interface to prevent complex circular type definitions
// that would be caused by a strongly-typed "parent" reference in IChannelCell. The parent reference is
// extremely useful in the actual protocol implementations since many of the properties of a cell and a
// frame may be shared. The strongly-typed generic version of the IChannelFrame interface is below.
/// <summary>
/// Gets the <see cref="FundamentalFrameType"/> for this <see cref="IChannelFrame"/>.
/// </summary>
FundamentalFrameType FrameType { get; }
/// <summary>
/// Gets the simple reference to the collection of cells for this <see cref="IChannelFrame"/>.
/// </summary>
object Cells { get; }
/// <summary>
/// Gets or sets the ID code of this <see cref="IChannelFrame"/>.
/// </summary>
ushort IDCode { get; set; }
/// <summary>
/// Gets UNIX based time representation of the ticks of this <see cref="IChannelFrame"/>.
/// </summary>
UnixTimeTag TimeTag { get; }
}
/// <summary>
/// Represents a strongly-typed protocol independent interface representation of any kind of frame of data that
/// contains a collection of <see cref="IChannelCell"/> objects.
/// </summary>
/// <remarks>
/// This interface inherits <see cref="IFrame"/> so that classes implementing this interface can be cooperatively
/// integrated into measurement concentration (see <see cref="ConcentratorBase"/>).
/// </remarks>
/// <typeparam name="T">Specific <see cref="IChannelCell"/> type that the <see cref="IChannelFrame{T}"/> contains.</typeparam>
public interface IChannelFrame<T> : IChannelFrame where T : IChannelCell
{
/// <summary>
/// Gets the strongly-typed reference to the collection of cells for this <see cref="IChannelFrame{T}"/>.
/// </summary>
new IChannelCellCollection<T> Cells { get; }
/// <summary>
/// Gets or sets the parsing state for this <see cref="IChannelFrame{T}"/>.
/// </summary>
new IChannelFrameParsingState<T> State { get; set; }
}
} | 41.44697 | 130 | 0.605008 | [
"MIT"
] | GridProtectionAlliance/gsf | Source/Libraries/GSF.PhasorProtocols/IChannelFrame.cs | 5,474 | C# |
using System;
using R5T.Angleterria;
using R5T.Lombardy;using R5T.T0064;
namespace R5T.Pompeii.Default
{[ServiceImplementationMarker]
/// <summary>
/// Gets the binaries directory path from the solution file path assuming the standard development directory structure enforced by Visual Studio:
/// ../{Solution Directory}/{Project Directory}/bin/Debug/netcoreapp2.2 (the binaries directory)
/// </summary>
public class StandardProjectBuildOutputBinariesDirectoryPathProvider : IProjectBuildOutputBinariesDirectoryPathProvider,IServiceImplementation
{
private ISolutionFilePathProvider SolutionFilePathProvider { get; }
private IEntryPointProjectNameProvider EntryPointProjectNameProvider { get; }
private IVisualStudioStringlyTypedPathPartsOperator VisualStudioStringlyTypedPathPartsOperator { get; }
private ISolutionAndProjectFileSystemConventions SolutionAndProjectFileSystemConventions { get; }
private IStringlyTypedPathOperator StringlyTypedPathOperator { get; }
public StandardProjectBuildOutputBinariesDirectoryPathProvider(ISolutionFilePathProvider solutionFilePathProvider, IEntryPointProjectNameProvider entryPointProjectNameProvider,
IVisualStudioStringlyTypedPathPartsOperator visualStudioStringlyTypedPathPartsOperator,
ISolutionAndProjectFileSystemConventions solutionAndProjectFileSystemConventions,
IStringlyTypedPathOperator stringlyTypedPathOperator)
{
this.SolutionFilePathProvider = solutionFilePathProvider;
this.VisualStudioStringlyTypedPathPartsOperator = visualStudioStringlyTypedPathPartsOperator;
this.EntryPointProjectNameProvider = entryPointProjectNameProvider;
this.SolutionAndProjectFileSystemConventions = solutionAndProjectFileSystemConventions;
this.StringlyTypedPathOperator = stringlyTypedPathOperator;
}
public string GetProjectBuildOutputBinariesDirectoryPath()
{
var solutionFilePath = this.SolutionFilePathProvider.GetSolutionFilePath();
var solutionDirectoryPath = this.StringlyTypedPathOperator.GetDirectoryPathForFilePath(solutionFilePath);
var entryPointProjectName = this.EntryPointProjectNameProvider.GetEntryPointProjectName();
var entryPointProjectDirectoryName = this.VisualStudioStringlyTypedPathPartsOperator.GetProjectDirectoryNameForProjectName(entryPointProjectName);
var entryPointProjectDirectoryPath = this.StringlyTypedPathOperator.GetDirectoryPath(solutionDirectoryPath, entryPointProjectDirectoryName);
var binDirectoryPath = this.StringlyTypedPathOperator.GetDirectoryPath(entryPointProjectDirectoryPath, BinDirectory.DirectoryName);
var debugDirectoryPath = this.StringlyTypedPathOperator.GetDirectoryPath(binDirectoryPath, DebugDirectory.DirectoryName);
var framworkDirectoryName = this.SolutionAndProjectFileSystemConventions.GetFrameworkDirectoryNameFromFrameworkName(NetCoreAppV2_2.FrameworkName);
var binariesOutputDirectoryPath = this.StringlyTypedPathOperator.GetDirectoryPath(debugDirectoryPath, framworkDirectoryName);
return binariesOutputDirectoryPath;
}
}
}
| 60.636364 | 185 | 0.787106 | [
"MIT"
] | MinexAutomation/R5T.Pompeii.Default | source/R5T.Pompeii.Default/Code/Services/Implementations/StandardProjectBuildOutputBinariesDirectoryPathProvider.cs | 3,335 | C# |
using System.ComponentModel.DataAnnotations;
namespace ConsoleAppNetCore3Ef3.EntityFrameworkCore.Entities
{
public class RoomDetail
{
[Key]
public int Id { get; set; }
public int Windows { get; set; }
public int Beds { get; set; }
public RoomDetail()
{
}
public RoomDetail(int windows, int beds)
{
Windows = windows;
Beds = beds;
}
}
} | 19.8 | 61 | 0.505051 | [
"MIT"
] | Logerfo/LINQKit | examples/ConsoleAppNetCore3Ef3/EntityFrameworkCore/Entities/RoomDetail.cs | 497 | C# |
#region BSD License
/*
*
* Original BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
* © Component Factory Pty Ltd, 2006 - 2016, (Version 4.5.0.0) All rights reserved.
*
* New BSD 3-Clause License (https://github.com/Krypton-Suite/Standard-Toolkit/blob/master/LICENSE)
* Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV), et al. 2017 - 2022. All rights reserved.
*
*/
#endregion
namespace Krypton.Navigator
{
/// <summary>
/// Storage for button related properties.
/// </summary>
public class NavigatorButton : Storage
{
#region Static Fields
private const Keys DEFAULT_SHORTCUT_PREVIOUS = (Keys.Control | Keys.Shift | Keys.F6);
private const Keys DEFAULT_SHORTCUT_NEXT = (Keys.Control | Keys.F6);
private const Keys DEFAULT_SHORTCUT_CONTEXT = (Keys.Control | Keys.Alt | Keys.Down);
private const Keys DEFAULT_SHORTCUT_CLOSE = (Keys.Control | Keys.F4);
#endregion
#region Instance Fields
private readonly KryptonNavigator _navigator;
private DirectionButtonAction _actionPrevious;
private ButtonDisplay _displayPrevious;
private DirectionButtonAction _actionNext;
private ButtonDisplay _displayNext;
private ContextButtonAction _actionContext;
private ButtonDisplay _displayContext;
private CloseButtonAction _actionClosed;
private ButtonDisplay _displayClosed;
private ButtonDisplayLogic _displayLogic;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the NavigatorButton class.
/// </summary>
/// <param name="navigator">Reference to owning navigator instance.</param>
/// <param name="needPaint">Delegate for notifying paint requests.</param>
public NavigatorButton(KryptonNavigator navigator,
NeedPaintHandler needPaint)
{
Debug.Assert(navigator != null);
// Remember back reference
_navigator = navigator;
// Store the provided paint notification delegate
NeedPaint = needPaint;
// Create collection for use defined and fixed buttons
ButtonSpecs = new NavigatorButtonSpecCollection(navigator);
FixedSpecs = new NavFixedButtonSpecCollection(navigator);
// Create the fixed buttons
PreviousButton = new ButtonSpecNavPrevious(_navigator);
NextButton = new ButtonSpecNavNext(_navigator);
ContextButton = new ButtonSpecNavContext(_navigator);
CloseButton = new ButtonSpecNavClose(_navigator);
// Hook into the click events for the buttons
PreviousButton.Click += OnPreviousClick;
NextButton.Click += OnNextClick;
ContextButton.Click += OnContextClick;
CloseButton.Click += OnCloseClick;
// Add fixed buttons into the display collection
FixedSpecs.AddRange(new ButtonSpecNavFixed[] { PreviousButton, NextButton, ContextButton, CloseButton });
// Default fields
_displayLogic = ButtonDisplayLogic.Context;
ContextMenuMapText = MapKryptonPageText.TextTitle;
ContextMenuMapImage = MapKryptonPageImage.Small;
_actionClosed = CloseButtonAction.RemovePageAndDispose;
_actionContext = ContextButtonAction.SelectPage;
_actionPrevious = _actionNext = DirectionButtonAction.ModeAppropriateAction;
_displayPrevious = _displayNext = _displayContext = _displayClosed = ButtonDisplay.Logic;
CloseButtonShortcut = DEFAULT_SHORTCUT_CLOSE;
ContextButtonShortcut = DEFAULT_SHORTCUT_CONTEXT;
NextButtonShortcut = DEFAULT_SHORTCUT_NEXT;
PreviousButtonShortcut = DEFAULT_SHORTCUT_PREVIOUS;
}
#endregion
#region IsDefault
/// <summary>
/// Gets a value indicating if all values are default.
/// </summary>
[Browsable(false)]
public override bool IsDefault => ((ButtonSpecs.Count == 0) &&
PreviousButton.IsDefault &&
(PreviousButtonAction == DirectionButtonAction.ModeAppropriateAction) &&
(PreviousButtonDisplay == ButtonDisplay.Logic) &&
(PreviousButtonShortcut == DEFAULT_SHORTCUT_PREVIOUS) &&
NextButton.IsDefault &&
(NextButtonAction == DirectionButtonAction.ModeAppropriateAction) &&
(NextButtonDisplay == ButtonDisplay.Logic) &&
(NextButtonShortcut == DEFAULT_SHORTCUT_NEXT) &&
ContextButton.IsDefault &&
(ContextButtonDisplay == ButtonDisplay.Logic) &&
(ContextButtonShortcut == DEFAULT_SHORTCUT_CONTEXT) &&
(ContextMenuMapText == MapKryptonPageText.TextTitle) &&
(ContextMenuMapImage == MapKryptonPageImage.Small) &&
CloseButton.IsDefault &&
(CloseButtonAction == CloseButtonAction.RemovePageAndDispose) &&
(CloseButtonDisplay == ButtonDisplay.Logic) &&
(CloseButtonShortcut == DEFAULT_SHORTCUT_CLOSE) &&
(ButtonDisplayLogic == ButtonDisplayLogic.Context));
#endregion
#region ButtonSpecs
/// <summary>
/// Gets the collection of button specifications.
/// </summary>
[Category(@"Visuals")]
[Description(@"Collection of button specifications.")]
[MergableProperty(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public NavigatorButtonSpecCollection ButtonSpecs { get; }
#endregion
#region PreviousButton
/// <summary>
/// Gets access to the previous button specification.
/// </summary>
[Category(@"Visuals")]
[Description(@"Previous button specification.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ButtonSpecNavPrevious PreviousButton { get; }
private bool ShouldSerializePreviousButton() => !PreviousButton.IsDefault;
#endregion
#region PreviousButtonAction
/// <summary>
/// Gets and sets the action to take when the previous button is clicked.
/// </summary>
[Category(@"Visuals")]
[Description(@"Action to take when the previous button is clicked.")]
[DefaultValue(typeof(DirectionButtonAction), "Mode Appropriate Action")]
public DirectionButtonAction PreviousButtonAction
{
get => _actionPrevious;
set
{
if (_actionPrevious != value)
{
_actionPrevious = value;
_navigator.OnViewBuilderPropertyChanged(nameof(PreviousButtonAction));
}
}
}
#endregion
#region PreviousButtonDisplay
/// <summary>
/// Gets and set the logic used to decide how to show the previous button.
/// </summary>
[Category(@"Visuals")]
[Description(@"Logic used to decide if previous button is Displayed.")]
[DefaultValue(typeof(ButtonDisplay), "Logic")]
public ButtonDisplay PreviousButtonDisplay
{
get => _displayPrevious;
set
{
if (_displayPrevious != value)
{
_displayPrevious = value;
_navigator.OnViewBuilderPropertyChanged(nameof(PreviousButtonDisplay));
}
}
}
#endregion
#region PreviousButtonShortcut
/// <summary>
/// Gets access to the shortcut for invoking the previous action.
/// </summary>
[Localizable(true)]
[Category(@"Visuals")]
[Description(@"Shortcut for invoking the previous action.")]
[DefaultValue(typeof(Keys), "F6, Shift, Control")]
public Keys PreviousButtonShortcut { get; set; }
private bool ShouldSerializePreviousButtonShortcut() => (PreviousButtonShortcut != DEFAULT_SHORTCUT_PREVIOUS);
/// <summary>
/// Resets the PreviousButtonShortcut property to its default value.
/// </summary>
public void ResetPreviousButtonShortcut()
{
PreviousButtonShortcut = DEFAULT_SHORTCUT_PREVIOUS;
}
#endregion
#region NextButton
/// <summary>
/// Gets access to the next button specification.
/// </summary>
[Category(@"Visuals")]
[Description(@"Next button specification.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ButtonSpecNavNext NextButton { get; }
private bool ShouldSerializeNextButton() => !NextButton.IsDefault;
#endregion
#region NextButtonAction
/// <summary>
/// Gets and sets the action to take when the next button is clicked.
/// </summary>
[Category(@"Visuals")]
[Description(@"Action to take when the next button is clicked.")]
[DefaultValue(typeof(DirectionButtonAction), "Mode Appropriate Action")]
public DirectionButtonAction NextButtonAction
{
get => _actionNext;
set
{
if (_actionNext != value)
{
_actionNext = value;
_navigator.OnViewBuilderPropertyChanged(nameof(NextButtonAction));
}
}
}
#endregion
#region NextButtonDisplay
/// <summary>
/// Gets and set the logic used to decide how to show the next button.
/// </summary>
[Category(@"Visuals")]
[Description(@"Logic used to decide if next button is Displayed.")]
[DefaultValue(typeof(ButtonDisplay), "Logic")]
public ButtonDisplay NextButtonDisplay
{
get => _displayNext;
set
{
if (_displayNext != value)
{
_displayNext = value;
_navigator.OnViewBuilderPropertyChanged(nameof(NextButtonDisplay));
}
}
}
#endregion
#region NextButtonShortcut
/// <summary>
/// Gets access to the shortcut for invoking the next action.
/// </summary>
[Localizable(true)]
[Category(@"Visuals")]
[Description(@"Shortcut for invoking the next action.")]
[DefaultValue(typeof(Keys), "F6, Control")]
public Keys NextButtonShortcut { get; set; }
private bool ShouldSerializeNextButtonShortcut() => (NextButtonShortcut != DEFAULT_SHORTCUT_NEXT);
/// <summary>
/// Resets the NextButtonShortcut property to its default value.
/// </summary>
public void ResetNextButtonShortcut()
{
NextButtonShortcut = DEFAULT_SHORTCUT_NEXT;
}
#endregion
#region ContextButton
/// <summary>
/// Gets access to the context button specification.
/// </summary>
[Category(@"Visuals")]
[Description(@"Context button specification.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ButtonSpecNavContext ContextButton { get; }
private bool ShouldSerializeContextButton() => !ContextButton.IsDefault;
#endregion
#region ContextButtonAction
/// <summary>
/// Gets and sets the action to take when the context button is clicked.
/// </summary>
[Category(@"Visuals")]
[Description(@"Action to take when the context button is clicked.")]
[DefaultValue(typeof(ContextButtonAction), "Select Page")]
public ContextButtonAction ContextButtonAction
{
get => _actionContext;
set
{
if (_actionContext != value)
{
_actionContext = value;
_navigator.OnViewBuilderPropertyChanged(nameof(ContextButtonAction));
}
}
}
#endregion
#region ContextButtonDisplay
/// <summary>
/// Gets and set the logic used to decide how to show the context button.
/// </summary>
[Category(@"Visuals")]
[Description(@"Logic used to decide if context button is Displayed.")]
[DefaultValue(typeof(ButtonDisplay), "Logic")]
public ButtonDisplay ContextButtonDisplay
{
get => _displayContext;
set
{
if (_displayContext != value)
{
_displayContext = value;
_navigator.OnViewBuilderPropertyChanged(nameof(ContextButtonDisplay));
}
}
}
#endregion
#region ContextButtonShortcut
/// <summary>
/// Gets access to the shortcut for invoking the context action.
/// </summary>
[Localizable(true)]
[Category(@"Visuals")]
[Description(@"Shortcut for invoking the context action.")]
[DefaultValue(typeof(Keys), "Down, Alt, Control")]
public Keys ContextButtonShortcut { get; set; }
private bool ShouldSerializeContextButtonShortcut() => (ContextButtonShortcut != DEFAULT_SHORTCUT_CONTEXT);
/// <summary>
/// Resets the ContextButtonShortcut property to its default value.
/// </summary>
public void ResetContextButtonShortcut()
{
ContextButtonShortcut = DEFAULT_SHORTCUT_CONTEXT;
}
#endregion
#region ContextMenuMapText
/// <summary>
/// Gets and set the mapping used to generate context menu item image.
/// </summary>
[Category(@"Visuals")]
[Description(@"Mapping used to generate context menu item image.")]
[DefaultValue(typeof(MapKryptonPageText), "Text - Title")]
public MapKryptonPageText ContextMenuMapText { get; set; }
#endregion
#region ContextMenuMapImage
/// <summary>
/// Gets and set the mapping used to generate context menu item text.
/// </summary>
[Category(@"Visuals")]
[Description(@"Mapping used to generate context menu item text.")]
[DefaultValue(typeof(MapKryptonPageImage), "Small")]
public MapKryptonPageImage ContextMenuMapImage { get; set; }
#endregion
#region CloseButton
/// <summary>
/// Gets access to the close button specification.
/// </summary>
[Category(@"Visuals")]
[Description(@"Close button specification.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ButtonSpecNavClose CloseButton { get; }
private bool ShouldSerializeCloseButton() => !CloseButton.IsDefault;
#endregion
#region CloseButtonAction
/// <summary>
/// Gets and sets the action to take when the close button is clicked.
/// </summary>
[Category(@"Visuals")]
[Description(@"Action to take when the close button is clicked.")]
[DefaultValue(typeof(CloseButtonAction), "RemovePage & Dispose")]
public CloseButtonAction CloseButtonAction
{
get => _actionClosed;
set
{
if (_actionClosed != value)
{
_actionClosed = value;
_navigator.OnViewBuilderPropertyChanged(nameof(CloseButtonAction));
}
}
}
#endregion
#region CloseButtonDisplay
/// <summary>
/// Gets and set the logic used to decide how to show the close button.
/// </summary>
[Category(@"Visuals")]
[Description(@"Logic used to decide if close button is Displayed.")]
[DefaultValue(typeof(ButtonDisplay), "Logic")]
public ButtonDisplay CloseButtonDisplay
{
get => _displayClosed;
set
{
if (_displayClosed != value)
{
_displayClosed = value;
_navigator.OnViewBuilderPropertyChanged(nameof(CloseButtonDisplay));
}
}
}
#endregion
#region CloseButtonShortcut
/// <summary>
/// Gets access to the shortcut for invoking the close action.
/// </summary>
[Localizable(true)]
[Category(@"Visuals")]
[Description(@"Shortcut for invoking the close action.")]
[DefaultValue(typeof(Keys), "F4, Control")]
public Keys CloseButtonShortcut { get; set; }
private bool ShouldSerializeCloseButtonShortcut() => (CloseButtonShortcut != DEFAULT_SHORTCUT_CLOSE);
/// <summary>
/// Resets the CloseButtonShortcut property to its default value.
/// </summary>
public void ResetCloseButtonShortcut()
{
CloseButtonShortcut = DEFAULT_SHORTCUT_CLOSE;
}
#endregion
#region ButtonDisplayLogic
/// <summary>
/// Gets and sets the logic used to control button display.
/// </summary>
[Category(@"Visuals")]
[Description(@"Define the logic used to control button display.")]
[DefaultValue(typeof(ButtonDisplayLogic), "Context")]
public ButtonDisplayLogic ButtonDisplayLogic
{
get => _displayLogic;
set
{
if (_displayLogic != value)
{
_displayLogic = value;
_navigator.OnViewBuilderPropertyChanged(nameof(ButtonDisplayLogic));
}
}
}
/// <summary>
/// Resets the ButtonDisplayLogic property to its default value.
/// </summary>
public void ResetButtonDisplayLogic()
{
ButtonDisplayLogic = ButtonDisplayLogic.Context;
}
#endregion
#region Internal
internal NavFixedButtonSpecCollection FixedSpecs { get; }
#endregion
#region Implementation
private void OnPreviousClick(object sender, EventArgs e)
{
_navigator.PerformPreviousAction();
}
private void OnNextClick(object sender, EventArgs e)
{
_navigator.PerformNextAction();
}
private void OnContextClick(object sender, EventArgs e)
{
_navigator.PerformContextAction();
}
private void OnCloseClick(object sender, EventArgs e)
{
_navigator.PerformCloseAction();
}
#endregion
}
}
| 37.093333 | 119 | 0.582058 | [
"BSD-3-Clause"
] | Krypton-Suite/standard-toolkit | Source/Krypton Components/Krypton.Navigator/Palette/NavigatorButton.cs | 19,477 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace _3DShapeEditor.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("_3DShapeEditor.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 38.680556 | 180 | 0.60395 | [
"MIT"
] | arkadiusz-gorecki/3D-Shape-Editor | Properties/Resources.Designer.cs | 2,787 | C# |
namespace Catel.Data
{
using System;
using System.Collections.Generic;
using System.Linq;
using Catel.Logging;
using Catel.Reflection;
/// <summary>
/// Memory efficient typed property bag that takes care of boxing.
/// </summary>
public partial class TypedPropertyBag : PropertyBagBase
{
private static readonly ILog Log = LogManager.GetCurrentClassLogger();
private readonly Dictionary<string, Type> _propertyTypes = new Dictionary<string, Type>();
public override string[] GetAllNames()
{
lock (_propertyTypes)
{
return _propertyTypes.Keys.ToArray();
}
}
public override bool IsAvailable(string name)
{
Argument.IsNotNullOrWhitespace(nameof(name), name);
lock (_propertyTypes)
{
return _propertyTypes.ContainsKey(name);
}
}
private Type GetRegisteredPropertyType(string name)
{
lock (_propertyTypes)
{
if (_propertyTypes.TryGetValue(name, out var existingType))
{
return existingType;
}
}
return null;
}
private void EnsureIntegrity(string name, Type type)
{
lock (_propertyTypes)
{
if (_propertyTypes.TryGetValue(name, out var existingType))
{
if (existingType != type && !existingType.IsAssignableFromEx(type))
{
throw Log.ErrorAndCreateException<InvalidOperationException>($"Property '{name}' is already registered as '{existingType.FullName}' which is not compatible with '{type.FullName}'");
}
}
else
{
_propertyTypes[name] = type;
}
}
}
}
}
| 29.161765 | 205 | 0.527484 | [
"MIT"
] | Catel/Catel | src/Catel.Core/Data/PropertyBags/TypedPropertyBag.cs | 1,985 | C# |
namespace NanoLoggerLevelEnricher.Test
{
using System;
using Moq;
using Serilog;
using Serilog.Configuration;
using Xunit;
public class NanoLoggerLevelEnricherExtensions
{
[Fact]
public void NanoLoggerLevelEnricher_Add()
{
// arrange
var loggerConfiguration = new LoggerConfiguration();
// act
loggerConfiguration
.Enrich.WithLoggerLevel()
.CreateLogger();
}
[Fact]
public void NanoLoggerLevelEnricher_Error()
{
// act
var result = Record.Exception(() => ((LoggerEnrichmentConfiguration) null).WithLoggerLevel());
// assert
Assert.IsType<ArgumentNullException>(result);
Assert.Equal("Value cannot be null. (Parameter 'enrichmentConfiguration')", result.Message);
}
}
}
| 26 | 106 | 0.581319 | [
"MIT"
] | prrandrade/NanoLogger | test/NanoLoggerLevelEnricher.Test/NanoLoggerLevelEnricherExtensions.cs | 912 | C# |
using TramsDataApi.ResponseModels.ApplyToBecome;
namespace TramsDataApi.UseCases
{
public interface IGetA2BContributor
{
A2BContributorResponse Execute(string contributorId);
}
} | 22.111111 | 61 | 0.773869 | [
"MIT"
] | DFE-Digital/trams-data-api | TramsDataApi/UseCases/IGetA2BContributor.cs | 199 | C# |
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Linq;
using SharpGLTF.Collections;
namespace SharpGLTF.Schema2
{
partial class KHR_lights_punctualglTFextension
{
internal KHR_lights_punctualglTFextension(ModelRoot root)
{
_lights = new ChildrenCollection<PunctualLight, ModelRoot>(root);
}
/// <inheritdoc />
protected override IEnumerable<ExtraProperties> GetLogicalChildren()
{
return base.GetLogicalChildren().Concat(_lights);
}
public IReadOnlyList<PunctualLight> Lights => _lights;
public PunctualLight CreateLight(string name, PunctualLightType ltype)
{
var light = new PunctualLight(ltype);
light.Name = name;
_lights.Add(light);
return light;
}
}
/// <summary>
/// Defines all the types of <see cref="PunctualLight"/> types.
/// </summary>
public enum PunctualLightType
{
Directional,
Point,
Spot
}
/// <remarks>
/// This is part of <see href="https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual"/> extension.
/// </remarks>
[System.Diagnostics.DebuggerDisplay("{LightType} {Color} {Intensity} {Range}")]
public sealed partial class PunctualLight
{
#region lifecycle
internal PunctualLight() { }
internal PunctualLight(PunctualLightType ltype)
{
_type = ltype.ToString().ToLowerInvariant();
if (ltype == PunctualLightType.Spot) _spot = new PunctualLightSpot();
}
/// <summary>
/// Sets the cone angles for the <see cref="PunctualLightType.Spot"/> light.
/// </summary>
/// <param name="innerConeAngle">
/// Gets the Angle, in radians, from centre of spotlight where falloff begins.
/// Must be greater than or equal to 0 and less than outerConeAngle.
/// </param>
/// <param name="outerConeAngle">
/// Gets Angle, in radians, from centre of spotlight where falloff ends.
/// Must be greater than innerConeAngle and less than or equal to PI / 2.0.
/// </param>
public void SetSpotCone(float innerConeAngle, float outerConeAngle)
{
if (_spot == null) throw new InvalidOperationException($"Expected {PunctualLightType.Spot} but found {LightType}");
if (innerConeAngle > outerConeAngle) throw new ArgumentException($"{nameof(innerConeAngle)} must be equal or smaller than {nameof(outerConeAngle)}");
_spot.InnerConeAngle = innerConeAngle;
_spot.OuterConeAngle = outerConeAngle;
}
/// <summary>
/// Defines the light color, intensity and range for the current <see cref="PunctualLight"/>.
/// </summary>
/// <param name="color">RGB value for light's color in linear space.</param>
/// <param name="intensity">
/// Brightness of light in. The units that this is defined in depend on the type of light.
/// point and spot lights use luminous intensity in candela (lm/sr) while directional
/// lights use illuminance in lux (lm/m2)
/// </param>
/// <param name="range">
/// Hint defining a distance cutoff at which the light's intensity may be considered
/// to have reached zero. Supported only for point and spot lights. Must be > 0.
/// When undefined, range is assumed to be infinite.
/// </param>
public void SetColor(Vector3 color, float intensity = 1, float range = 0)
{
this.Color = color;
this.Intensity = intensity;
this.Range = range;
}
#endregion
#region properties
/// <summary>
/// Gets the Local light direction.
/// </summary>
/// <remarks>
/// For light types that have a direction (directional and spot lights),
/// the light's direction is defined as the 3-vector (0.0, 0.0, -1.0)
/// </remarks>
public static Vector3 LocalDirection => -Vector3.UnitZ;
/// <summary>
/// Gets the zero-based index of this <see cref="PunctualLight"/> at <see cref="ModelRoot.LogicalPunctualLights"/>
/// </summary>
public int LogicalIndex => this.LogicalParent.LogicalPunctualLights.IndexOfReference(this);
/// <summary>
/// Gets the type of light.
/// </summary>
public PunctualLightType LightType => (PunctualLightType)Enum.Parse(typeof(PunctualLightType), _type, true);
/// <summary>
/// Gets the Angle, in radians, from centre of spotlight where falloff begins.
/// Must be greater than or equal to 0 and less than outerConeAngle.
/// </summary>
public float InnerConeAngle => this._spot == null ? 0 : (float)this._spot.InnerConeAngle;
/// <summary>
/// Gets Angle, in radians, from centre of spotlight where falloff ends.
/// Must be greater than innerConeAngle and less than or equal to PI / 2.0.
/// </summary>
public float OuterConeAngle => this._spot == null ? 0 : (float)this._spot.OuterConeAngle;
/// <summary>
/// Gets or sets the RGB value for light's color in linear space.
/// </summary>
public Vector3 Color
{
get => _color.AsValue(_colorDefault);
set => _color = value.AsNullable(_colorDefault, Vector3.Zero, Vector3.One);
}
/// <summary>
/// Gets or sets the Brightness of light in. The units that this is defined in depend on the type of light.
/// point and spot lights use luminous intensity in candela (lm/sr) while directional
/// lights use illuminance in lux (lm/m2)
/// </summary>
public float Intensity
{
get => (float)_intensity.AsValue(_intensityDefault);
set => _intensity = ((double)value).AsNullable(_intensityDefault, _intensityMinimum, float.MaxValue);
}
/// <summary>
/// Gets or sets a Hint defining a distance cutoff at which the light's intensity may be considered
/// to have reached zero. Supported only for point and spot lights. Must be > 0.
/// When undefined, range is assumed to be infinite.
/// </summary>
public float Range
{
get => (float)_range.AsValue(0);
set => _range = LightType == PunctualLightType.Directional ? 0 : ((double)value).AsNullable(0, _rangeMinimum, float.MaxValue);
}
#endregion
}
partial class PunctualLightSpot
{
public Double InnerConeAngle
{
get => _innerConeAngle.AsValue(_innerConeAngleDefault);
set => _innerConeAngle = value.AsNullable(_innerConeAngleDefault, _innerConeAngleMinimum, _innerConeAngleMaximum);
}
public Double OuterConeAngle
{
get => _outerConeAngle.AsValue(_outerConeAngleDefault);
set => _outerConeAngle = value.AsNullable(_outerConeAngleDefault, _outerConeAngleMinimum, _outerConeAngleMaximum);
}
}
partial class ModelRoot
{
/// <summary>
/// Gets A collection of <see cref="PunctualLight"/> instances.
/// </summary>
/// <remarks>
/// This is part of <see href="https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual">KHR_lights_punctual</see> extension.
/// </remarks>
public IReadOnlyList<PunctualLight> LogicalPunctualLights
{
get
{
var ext = this.GetExtension<KHR_lights_punctualglTFextension>();
if (ext == null) return Array.Empty<PunctualLight>();
return ext.Lights;
}
}
/// <summary>
/// Creates a new <see cref="PunctualLight"/> instance and
/// adds it to <see cref="ModelRoot.LogicalPunctualLights"/>.
/// </summary>
/// <param name="lightType">A value of <see cref="PunctualLightType"/> describing the type of light to create.</param>
/// <returns>A <see cref="PunctualLight"/> instance.</returns>
public PunctualLight CreatePunctualLight(PunctualLightType lightType)
{
return CreatePunctualLight(null, lightType);
}
/// <summary>
/// Creates a new <see cref="PunctualLight"/> instance.
/// and adds it to <see cref="ModelRoot.LogicalPunctualLights"/>.
/// </summary>
/// <param name="name">The name of the instance.</param>
/// <param name="lightType">A value of <see cref="PunctualLightType"/> describing the type of light to create.</param>
/// <returns>A <see cref="PunctualLight"/> instance.</returns>
public PunctualLight CreatePunctualLight(string name, PunctualLightType lightType)
{
var ext = this.GetExtension<KHR_lights_punctualglTFextension>();
if (ext == null)
{
this.UsingExtension(typeof(ModelRoot), typeof(KHR_lights_punctualglTFextension));
ext = new KHR_lights_punctualglTFextension(this);
this.SetExtension(ext);
}
return ext.CreateLight(name, lightType);
}
}
partial class KHR_lights_punctualnodeextension
{
internal KHR_lights_punctualnodeextension(Node node)
{
}
public int LightIndex
{
get => _light;
set => _light = value;
}
}
partial class Node
{
/// <summary>
/// Gets or sets the <see cref="Schema2.PunctualLight"/> of this <see cref="Node"/>.
/// </summary>
/// <remarks>
/// This is part of <see href="https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual"/> extension.
/// </remarks>
public PunctualLight PunctualLight
{
get
{
var ext = this.GetExtension<KHR_lights_punctualnodeextension>();
if (ext == null) return null;
return this.LogicalParent.LogicalPunctualLights[ext.LightIndex];
}
set
{
if (value == null) { this.RemoveExtensions<KHR_lights_punctualnodeextension>(); return; }
Guard.MustShareLogicalParent(this, value, nameof(value));
this.UsingExtension(typeof(KHR_lights_punctualnodeextension));
var ext = new KHR_lights_punctualnodeextension(this);
ext.LightIndex = value.LogicalIndex;
this.SetExtension(ext);
}
}
}
}
| 38.682927 | 169 | 0.587822 | [
"MIT"
] | bertt/SharpGLTF | src/SharpGLTF.Core/Schema2/khr.lights.cs | 11,104 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Identity.Client.Core;
using Microsoft.Identity.Client.Http;
using Microsoft.Identity.Client.UI;
using Microsoft.Identity.Client.Utils;
using Windows.ApplicationModel.Core;
using Windows.Security.Authentication.Web;
namespace Microsoft.Identity.Client.Platforms.uap
{
internal class WebUI : IWebUI
{
private const int WABRetryAttempts = 2;
private readonly bool _useCorporateNetwork;
private readonly bool _silentMode;
private readonly RequestContext _requestContext;
public WebUI(CoreUIParent parent, RequestContext requestContext)
{
_useCorporateNetwork = parent.UseCorporateNetwork;
_silentMode = parent.UseHiddenBrowser;
_requestContext = requestContext;
}
public async Task<AuthorizationResult> AcquireAuthorizationAsync(
Uri authorizationUri,
Uri redirectUri,
RequestContext requestContext,
CancellationToken cancellationToken)
{
bool ssoMode = string.Equals(redirectUri.OriginalString, Constants.UapWEBRedirectUri, StringComparison.OrdinalIgnoreCase);
WebAuthenticationResult webAuthenticationResult;
WebAuthenticationOptions options = (_useCorporateNetwork &&
(ssoMode || redirectUri.Scheme == Constants.MsAppScheme))
? WebAuthenticationOptions.UseCorporateNetwork
: WebAuthenticationOptions.None;
if (_silentMode)
{
options |= WebAuthenticationOptions.SilentMode;
}
try
{
webAuthenticationResult = await RetryOperationHelper.ExecuteWithRetryAsync(
() => InvokeWABOnMainThreadAsync(authorizationUri, redirectUri, ssoMode, options),
WABRetryAttempts,
onAttemptFailed: (attemptNumber, exception) =>
{
_requestContext.Logger.Warning($"Attempt {attemptNumber} to call WAB failed");
_requestContext.Logger.WarningPii(exception);
})
.ConfigureAwait(false);
}
catch (Exception ex)
{
requestContext.Logger.ErrorPii(ex);
throw new MsalClientException(
MsalError.AuthenticationUiFailedError,
"Web Authentication Broker (WAB) authentication failed. To collect WAB logs, please follow https://aka.ms/msal-net-wab-logs",
ex);
}
AuthorizationResult result = ProcessAuthorizationResult(webAuthenticationResult);
return result;
}
private async Task<WebAuthenticationResult> InvokeWABOnMainThreadAsync(
Uri authorizationUri,
Uri redirectUri,
bool ssoMode,
WebAuthenticationOptions options)
{
return await CoreApplication.MainView.CoreWindow.Dispatcher.RunTaskAsync(
async () =>
{
if (ssoMode)
{
return await
WebAuthenticationBroker.AuthenticateAsync(options, authorizationUri)
.AsTask()
.ConfigureAwait(false);
}
else
{
return await WebAuthenticationBroker
.AuthenticateAsync(options, authorizationUri, redirectUri)
.AsTask()
.ConfigureAwait(false);
}
})
.ConfigureAwait(false);
}
private static AuthorizationResult ProcessAuthorizationResult(WebAuthenticationResult webAuthenticationResult)
{
AuthorizationResult result;
switch (webAuthenticationResult.ResponseStatus)
{
case WebAuthenticationStatus.Success:
result = AuthorizationResult.FromUri(webAuthenticationResult.ResponseData);
break;
case WebAuthenticationStatus.ErrorHttp:
result = AuthorizationResult.FromStatus(AuthorizationStatus.ErrorHttp);
result.Code = webAuthenticationResult.ResponseErrorDetail.ToString(CultureInfo.InvariantCulture);
break;
case WebAuthenticationStatus.UserCancel:
result = AuthorizationResult.FromStatus(AuthorizationStatus.UserCancel);
break;
default:
result = AuthorizationResult.FromStatus(
AuthorizationStatus.UnknownError,
MsalError.WABError,
MsalErrorMessage.WABError(
webAuthenticationResult.ResponseStatus.ToString(),
webAuthenticationResult.ResponseErrorDetail.ToString(CultureInfo.InvariantCulture),
webAuthenticationResult.ResponseData));
break;
}
return result;
}
public Uri UpdateRedirectUri(Uri redirectUri)
{
RedirectUriHelper.Validate(redirectUri, usesSystemBrowser: false);
return redirectUri;
}
}
}
| 40.690647 | 145 | 0.582037 | [
"MIT"
] | isra-fel/microsoft-authentication-library-for-dotnet | src/client/Microsoft.Identity.Client/Platforms/uap/WebUI.cs | 5,658 | C# |
using System;
using System.IO;
using System.Collections.Specialized;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Xamarin.MacDev;
namespace Xamarin.MacDev.Tasks
{
public abstract class CodesignVerifyTaskBase : ToolTask
{
#region Inputs
public string SessionId { get; set; }
[Required]
public string CodesignAllocate { get; set; }
[Required]
public string Resource { get; set; }
#endregion
protected override string ToolName {
get { return "codesign"; }
}
protected override string GenerateFullPathToTool ()
{
if (!string.IsNullOrEmpty (ToolPath))
return Path.Combine (ToolPath, ToolExe);
var path = Path.Combine ("/usr/bin", ToolExe);
return File.Exists (path) ? path : ToolExe;
}
// Note: Xamarin.Mac and Xamarin.iOS should both override this method to do pass platform-specific verify rules
protected override string GenerateCommandLineCommands ()
{
var args = new ProcessArgumentBuilder ();
args.Add ("--verify");
args.Add ("-vvvv");
args.AddQuoted (Resource);
return args.ToString ();
}
protected override void LogEventsFromTextOutput (string singleLine, MessageImportance messageImportance)
{
// TODO: do proper parsing of error messages and such
Log.LogMessage (messageImportance, "{0}", singleLine);
}
public override bool Execute ()
{
EnvironmentVariables = new string[] {
"CODESIGN_ALLOCATE=" + CodesignAllocate
};
return base.Execute ();
}
}
}
| 21.695652 | 113 | 0.709419 | [
"BSD-3-Clause"
] | Acidburn0zzz/xamarin-macios | msbuild/Xamarin.MacDev.Tasks.Core/Tasks/CodesignVerifyTaskBase.cs | 1,499 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Generator3.Renderer.Public
{
public static class Constructors
{
public static string Render(this IEnumerable<Model.Public.Constructor> constructors)
{
return constructors
.Select(constructor => constructor.Render())
.Join(Environment.NewLine);
}
}
}
| 24.058824 | 92 | 0.645477 | [
"MIT"
] | GirCore/gir.core | src/Generation/Generator3/Renderer/Public/Constructor/Constructors.cs | 411 | C# |
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using static UI.UIProperties;
namespace UI.UserControls.TaskControls
{
/// <summary>
/// Interaction logic for ModifyTask.xaml
/// </summary>
public partial class ModifyTask : UserControl
{
/// <summary>
/// Initializes a new instance of the <see cref="ModifyTask"/> class.
/// </summary>
public ModifyTask()
{
InitializeComponent();
}
/// <summary>Handles the Click event of the ModifyButton control.</summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
private void ModifyButton_Click(object sender, RoutedEventArgs e)
{
try
{
if (TaskListBox.SelectedItem == null || string.IsNullOrEmpty(NewNameBox.Text) || string.IsNullOrEmpty(NewDatePicker.Text))
//Shows a message box with a warning
ShowWarning("All fields should be full!");
else
{
//Gets the Task from the box
Task selectedTask = (Task)TaskListBox.SelectedItem;
//Make changes to the Task
selectedTask.Name = NewNameBox.Text;
selectedTask.Date = DateTime.Parse(NewDatePicker.Text);
selectedTask.IsDone = (bool)CompletedCheckBox.IsChecked ? true : false;
//Modifies the Task
taskBusiness.ModifyTask(selectedTask, currentUser);
//Loads the new list box
LoadTaskListBox();
//Shows success info
ShowInfo("Task modified successfully!");
}
}
catch(Exception exception)
{
//Shows the message of the current exception
ShowError(exception.Message);
}
}
/// <summary>
/// Loads the task ListBox.
/// </summary>
public void LoadTaskListBox()
{
//Gets all user Tasks
List<Task> Tasks = taskBusiness.ListAllTasks(currentUser);
//Deletes current items
TaskListBox.Items.Clear();
//Adds Tasks to the List Box
foreach (Task @Task in Tasks)
{
TaskListBox.Items.Add(@Task);
}
}
}
}
| 32.746835 | 138 | 0.536529 | [
"MIT"
] | Miroslav312/RedsPO | RedsPO/UI/UserControls/TaskControls/ModifyTask.xaml.cs | 2,589 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
namespace Unity.ProjectAuditor.Editor.UI
{
class AssemblySelectionWindow : EditorWindow
{
MultiColumnHeaderState m_MultiColumnHeaderState;
MultiSelectionTable m_MultiSelectionTable;
ProjectAuditorWindow m_ProjectAuditorWindow;
TreeViewState m_TreeViewState;
string[] m_Names;
bool m_RequestClose;
public static AssemblySelectionWindow Open(float screenX, float screenY,
ProjectAuditorWindow projectAuditorWindow, TreeViewSelection selection, string[] names)
{
var window = GetWindow<AssemblySelectionWindow>("Assemblies");
window.position = new Rect(screenX, screenY, 400, 500);
window.SetData(projectAuditorWindow, selection, names);
window.Show();
return window;
}
public static void CloseAll()
{
var window = GetWindow<AssemblySelectionWindow>("Assemblies");
window.Close();
}
void OnEnable()
{
m_RequestClose = false;
}
void OnDestroy()
{
ApplySelection();
}
void OnLostFocus()
{
m_RequestClose = true;
}
void Update()
{
if (m_RequestClose)
Close();
}
public static bool IsOpen()
{
var windows = Resources.FindObjectsOfTypeAll(typeof(AssemblySelectionWindow));
if (windows != null && windows.Length > 0)
return true;
return false;
}
void SetData(ProjectAuditorWindow projectAuditorWindow, TreeViewSelection selection, string[] names)
{
m_Names = names;
m_ProjectAuditorWindow = projectAuditorWindow;
CreateTable(projectAuditorWindow, selection);
}
void CreateTable(ProjectAuditorWindow projectAuditorWindow, TreeViewSelection selection)
{
if (m_TreeViewState == null)
m_TreeViewState = new TreeViewState();
MultiSelectionTable.HeaderData[] headerData =
{
new MultiSelectionTable.HeaderData("Assembly", "Assembly Name", 350, 100, true, false),
new MultiSelectionTable.HeaderData("Show", "Check to show this assembly in the analysis views", 40, 100,
false, false),
new MultiSelectionTable.HeaderData("Group", "Assembly Group", 100, 100, true, false)
};
m_MultiColumnHeaderState = MultiSelectionTable.CreateDefaultMultiColumnHeaderState(headerData);
var multiColumnHeader = new MultiColumnHeader(m_MultiColumnHeaderState);
multiColumnHeader.SetSorting((int)MultiSelectionTable.MyColumns.ItemName, true);
multiColumnHeader.ResizeToFit();
m_MultiSelectionTable = new MultiSelectionTable(m_TreeViewState, multiColumnHeader, m_Names, selection);
}
void ApplySelection()
{
var analytic = ProjectAuditorAnalytics.BeginAnalytic();
var selection = m_MultiSelectionTable.GetTreeViewSelection();
m_ProjectAuditorWindow.SetAssemblySelection(selection);
var payload = new Dictionary<string, string>();
string[] selectedAsmNames = selection.GetSelectedStrings(m_Names, false);
if (selectedAsmNames == null || selectedAsmNames.Length == 0)
{
payload["numSelected"] = "0";
payload["numUnityAssemblies"] = "0";
}
else
{
payload["numSelected"] = selectedAsmNames.Length.ToString();
payload["numUnityAssemblies"] = selectedAsmNames.Where(name => name.Contains("Unity")).Count().ToString();
}
ProjectAuditorAnalytics.SendUIButtonEventWithKeyValues(ProjectAuditorAnalytics.UIButton.AssemblySelectApply, analytic, payload);
}
void OnGUI()
{
EditorGUILayout.BeginVertical(GUILayout.ExpandWidth(true));
var style = new GUIStyle(GUI.skin.label);
style.alignment = TextAnchor.MiddleLeft;
GUILayout.Label("Select Assembly : ", style);
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Clear", GUILayout.Width(50))) m_MultiSelectionTable.ClearSelection();
if (GUILayout.Button("Apply", GUILayout.Width(50)))
{
ApplySelection();
}
EditorGUILayout.EndHorizontal();
if (m_MultiSelectionTable != null)
{
var r = EditorGUILayout.GetControlRect(GUILayout.ExpandHeight(true));
m_MultiSelectionTable.OnGUI(r);
}
EditorGUILayout.EndVertical();
}
}
}
| 35.014085 | 140 | 0.609413 | [
"MIT"
] | avram/ProjectAuditor | Editor/UI/AssemblySelectionWindow.cs | 4,972 | C# |
namespace Day07Task1Result
{
public static class Data
{
public static long[] Program => new long[] { 3, 8, 1001, 8, 10, 8, 105, 1, 0, 0, 21, 34, 43, 60, 81, 94, 175, 256, 337, 418, 99999, 3, 9, 101, 2, 9, 9, 102, 4, 9, 9, 4, 9, 99, 3, 9, 102, 2, 9, 9, 4, 9, 99, 3, 9, 102, 4, 9, 9, 1001, 9, 4, 9, 102, 3, 9, 9, 4, 9, 99, 3, 9, 102, 4, 9, 9, 1001, 9, 2, 9, 1002, 9, 3, 9, 101, 4, 9, 9, 4, 9, 99, 3, 9, 1001, 9, 4, 9, 102, 2, 9, 9, 4, 9, 99, 3, 9, 102, 2, 9, 9, 4, 9, 3, 9, 1001, 9, 2, 9, 4, 9, 3, 9, 102, 2, 9, 9, 4, 9, 3, 9, 101, 1, 9, 9, 4, 9, 3, 9, 1002, 9, 2, 9, 4, 9, 3, 9, 1001, 9, 2, 9, 4, 9, 3, 9, 101, 2, 9, 9, 4, 9, 3, 9, 101, 1, 9, 9, 4, 9, 3, 9, 102, 2, 9, 9, 4, 9, 3, 9, 1002, 9, 2, 9, 4, 9, 99, 3, 9, 101, 2, 9, 9, 4, 9, 3, 9, 1001, 9, 1, 9, 4, 9, 3, 9, 101, 1, 9, 9, 4, 9, 3, 9, 102, 2, 9, 9, 4, 9, 3, 9, 1002, 9, 2, 9, 4, 9, 3, 9, 1001, 9, 1, 9, 4, 9, 3, 9, 1001, 9, 2, 9, 4, 9, 3, 9, 101, 1, 9, 9, 4, 9, 3, 9, 1001, 9, 1, 9, 4, 9, 3, 9, 1001, 9, 2, 9, 4, 9, 99, 3, 9, 1002, 9, 2, 9, 4, 9, 3, 9, 102, 2, 9, 9, 4, 9, 3, 9, 1002, 9, 2, 9, 4, 9, 3, 9, 102, 2, 9, 9, 4, 9, 3, 9, 1001, 9, 1, 9, 4, 9, 3, 9, 1002, 9, 2, 9, 4, 9, 3, 9, 1001, 9, 2, 9, 4, 9, 3, 9, 101, 1, 9, 9, 4, 9, 3, 9, 101, 2, 9, 9, 4, 9, 3, 9, 1001, 9, 2, 9, 4, 9, 99, 3, 9, 101, 2, 9, 9, 4, 9, 3, 9, 101, 1, 9, 9, 4, 9, 3, 9, 101, 1, 9, 9, 4, 9, 3, 9, 101, 1, 9, 9, 4, 9, 3, 9, 1001, 9, 1, 9, 4, 9, 3, 9, 1001, 9, 2, 9, 4, 9, 3, 9, 1001, 9, 2, 9, 4, 9, 3, 9, 102, 2, 9, 9, 4, 9, 3, 9, 1001, 9, 2, 9, 4, 9, 3, 9, 1002, 9, 2, 9, 4, 9, 99, 3, 9, 1001, 9, 1, 9, 4, 9, 3, 9, 1001, 9, 1, 9, 4, 9, 3, 9, 1002, 9, 2, 9, 4, 9, 3, 9, 1001, 9, 1, 9, 4, 9, 3, 9, 1002, 9, 2, 9, 4, 9, 3, 9, 102, 2, 9, 9, 4, 9, 3, 9, 1001, 9, 2, 9, 4, 9, 3, 9, 1001, 9, 2, 9, 4, 9, 3, 9, 101, 2, 9, 9, 4, 9, 3, 9, 102, 2, 9, 9, 4, 9, 99 };
}
}
| 226.875 | 1,741 | 0.421488 | [
"MIT"
] | sowiszcze/AdventOfCode2019 | Day07Task1Result/Data.cs | 1,817 | C# |
namespace PrintAllMinionNames
{
using System;
using System.Collections.Generic;
using Microsoft.Data.SqlClient;
class Engine
{
public void Run()
{
using (var connection = new SqlConnection(Configuration.ConnectionString))
{
connection.Open();
var minionNames = GetAllMinionNames(connection);
PrintAllMinionNames(minionNames);
}
}
private static void PrintAllMinionNames(List<string> minionNames)
{
if (minionNames.Count > 0)
{
for (int i = 0; i < minionNames.Count / 2; i++)
{
Console.WriteLine(minionNames[i]);
Console.WriteLine(minionNames[minionNames.Count - 1 - i]);
}
if (minionNames.Count % 2 != 0)
{
Console.WriteLine(minionNames[minionNames.Count / 2]);
}
}
}
private static List<string> GetAllMinionNames(SqlConnection connection)
{
var minionNames = new List<string>();
var selectNameQuery = Queries.SelectMinions;
var command = new SqlCommand(selectNameQuery, connection);
using (var dataReader = command.ExecuteReader())
{
while (dataReader.Read())
{
var name = dataReader[0]?.ToString();
minionNames.Add(name);
}
}
return minionNames;
}
}
}
| 27.033333 | 86 | 0.493835 | [
"MIT"
] | ivanov-mi/SoftUni-Training | 05EntityFrameworkCore/01AdoNetIntroduction/07PrintAllMinionNames/Engine.cs | 1,624 | C# |
namespace OJS.Workers.ExecutionStrategies.NodeJs
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using OJS.Workers.Common;
using OJS.Workers.Common.Extensions;
using OJS.Workers.ExecutionStrategies.Models;
using OJS.Workers.Executors;
using static OJS.Workers.Common.Constants;
public class NodeJsPreprocessExecuteAndRunCodeAgainstUnitTestsWithMochaExecutionStrategy :
NodeJsPreprocessExecuteAndRunJsDomUnitTestsExecutionStrategy
{
public NodeJsPreprocessExecuteAndRunCodeAgainstUnitTestsWithMochaExecutionStrategy(
IProcessExecutorFactory processExecutorFactory,
string nodeJsExecutablePath,
string mochaModulePath,
string chaiModulePath,
string jsdomModulePath,
string jqueryModulePath,
string handlebarsModulePath,
string sinonModulePath,
string sinonChaiModulePath,
string underscoreModulePath,
int baseTimeUsed,
int baseMemoryUsed)
: base(
processExecutorFactory,
nodeJsExecutablePath,
mochaModulePath,
chaiModulePath,
jsdomModulePath,
jqueryModulePath,
handlebarsModulePath,
sinonModulePath,
sinonChaiModulePath,
underscoreModulePath,
baseTimeUsed,
baseMemoryUsed) =>
this.Random = new Random();
protected override string JsCodePreevaulationCode => @"
chai.use(sinonChai);
let bgCoderConsole = {};
before(function(done)
{
jsdom.env({
html: '',
done: function(errors, window) {
global.window = window;
global.document = window.document;
global.$ = jq(window);
global.handlebars = handlebars;
Object.getOwnPropertyNames(window)
.filter(function(prop) {
return prop.toLowerCase().indexOf('html') >= 0;
}).forEach(function(prop) {
global[prop] = window[prop];
});
Object.keys(console)
.forEach(function (prop) {
bgCoderConsole[prop] = console[prop];
console[prop] = new Function('');
});
done();
}
});
});
after(function() {
Object.keys(bgCoderConsole)
.forEach(function (prop) {
console[prop] = bgCoderConsole[prop];
});
});";
protected override string JsCodeEvaluation => @"
" + TestsPlaceholder;
protected override string JsCodePostevaulationCode => string.Empty;
private Random Random { get; }
protected override IExecutionResult<TestResult> ExecuteAgainstTestsInput(
IExecutionContext<TestsInputModel> executionContext,
IExecutionResult<TestResult> result)
{
var executor = this.CreateExecutor(ProcessExecutorType.Restricted);
var codeSavePath = this.SaveCodeToTempFile(executionContext);
// Process the submission and check each test
result.Results.AddRange(this.ProcessTests(
executionContext,
executor,
executionContext.Input.GetChecker(),
codeSavePath));
// Clean up
File.Delete(codeSavePath);
return result;
}
protected override string BuildTests(IEnumerable<TestContext> tests)
{
// Swap the testInput for every copy of the user's tests
var testGroupRoof = 1;
// Create a random name for the variable keeping track of the testGroup, so that the user can't manipulate it
var testGroupVariableName = "testGroup" + this.Random.Next(10000);
var problemTests = tests.ToList();
var testsCode = problemTests[0].Input;
// We set the state of the tested entity in a beforeEach hook to ensure the user doesnt manipulate the entity
testsCode += @"
let " + testGroupVariableName + $@" = 0;
beforeEach(function(){{
if(" + testGroupVariableName + $@" < {testGroupRoof}) {{
{problemTests[1].Input}
}}";
testGroupRoof++;
var beforeHookTests = problemTests.Skip(1).ToList();
foreach (var test in beforeHookTests)
{
testsCode += @"
else if(" + testGroupVariableName + $@" < {testGroupRoof}) {{
{test.Input}
}}";
testGroupRoof++;
}
testsCode += @"
});";
// Insert a copy of the user tests for each test file
for (int i = 0; i < problemTests.Count; i++)
{
testsCode += $@"
describe('Test {i} ', function(){{
after(function () {{
" + testGroupVariableName + $@"++;
}});
{UserInputPlaceholder}
}});";
}
return testsCode;
}
protected override List<TestResult> ProcessTests(
IExecutionContext<TestsInputModel> executionContext,
IExecutor executor,
IChecker checker,
string codeSavePath)
{
var testResults = new List<TestResult>();
var arguments = new List<string>();
arguments.Add(this.MochaModulePath);
arguments.Add(codeSavePath);
arguments.AddRange(this.AdditionalExecutionArguments);
var testCount = 0;
var processExecutionResult = executor.Execute(
this.NodeJsExecutablePath,
string.Empty,
executionContext.TimeLimit,
executionContext.MemoryLimit,
arguments);
var mochaResult = JsonExecutionResult.Parse(processExecutionResult.ReceivedOutput);
var numberOfUserTests = mochaResult.UsersTestCount;
var correctSolutionTestPasses = mochaResult.InitialPassingTests;
// an offset for tracking the current subset of tests (by convention we always have 2 Zero tests)
var testOffset = numberOfUserTests * 2;
foreach (var test in executionContext.Input.Tests)
{
var message = TestPassedMessage;
TestResult testResult = null;
if (testCount == 0)
{
var minTestCount = int.Parse(
Regex.Match(
test.Input,
"<minTestCount>(\\d+)</minTestCount>").Groups[1].Value);
if (numberOfUserTests < minTestCount)
{
message = $"Insufficient amount of tests, you have to have atleast {minTestCount} tests!";
}
testResult = this.CheckAndGetTestResult(
test,
processExecutionResult,
checker,
message);
}
else if (testCount == 1)
{
if (numberOfUserTests == 0)
{
message = "The submitted code was either incorrect or contained no tests!";
}
else if (correctSolutionTestPasses != numberOfUserTests)
{
message = "Error: Some tests failed while running the correct solution!";
}
testResult = this.CheckAndGetTestResult(
test,
processExecutionResult,
checker,
message);
}
else
{
var numberOfPasses = mochaResult.TestErrors.Skip(testOffset).Take(numberOfUserTests).Count(x => x == null);
if (numberOfPasses >= correctSolutionTestPasses)
{
message = "No unit test covering this functionality!";
}
testResult = this.CheckAndGetTestResult(
test,
processExecutionResult,
checker,
message);
testOffset += numberOfUserTests;
}
testCount++;
testResults.Add(testResult);
}
return testResults;
}
protected override string PreprocessJsSubmission<TInput>(string template, IExecutionContext<TInput> context)
{
var code = context.Code.Trim(';');
var processedCode =
template.Replace(RequiredModules, this.JsCodeRequiredModules)
.Replace(PreevaluationPlaceholder, this.JsCodePreevaulationCode)
.Replace(EvaluationPlaceholder, this.JsCodeEvaluation)
.Replace(PostevaluationPlaceholder, this.JsCodePostevaulationCode)
.Replace(NodeDisablePlaceholder, this.JsNodeDisableCode)
.Replace(TestsPlaceholder, this.BuildTests((context.Input as TestsInputModel)?.Tests))
.Replace(UserInputPlaceholder, code);
return processedCode;
}
}
}
| 35.724528 | 127 | 0.546953 | [
"MIT"
] | Digid-GMAO/MyTested.AspNet.TV | src/Huge Code Base/Open Judge System/Workers/OJS.Workers.ExecutionStrategies/NodeJs/NodeJsPreprocessExecuteAndRunCodeAgainstUnitTestsWithMochaExecutionStrategy.cs | 9,469 | C# |
/*
* SHSim.act - wpn_DCRack
*
* © 2007-2016 skwas. All rights reserved.
* This code is provided as is. Change at your own risk.
* --------------------------------------------------
*
* S3D template for the wpn_DCRack controller of Silent Hunter.
*
* For documentation on templates, requirements and restrictions, please refer to the documentation.
*
*/
using System.Collections.Generic;
using SilentHunter.Controllers;
namespace SHSim
{
/// <summary>
/// wpn_DCRack render controller.
/// </summary>
public class wpn_DCRack
: BehaviorController
{
/// <summary>
/// Visual barrel object.
/// </summary>
public string Barrel;
/// <summary>
/// The DCRack ammo storage.
/// </summary>
public List<DCRackAmmoStorage> ammo_storage;
}
public class DCRackAmmoStorage
{
/// <summary>
/// object->amun_DepthCharge. The depth charge's type.
/// </summary>
public ulong type;
/// <summary>
/// The amount of this type.
/// </summary>
public int amount;
}
} | 21.869565 | 100 | 0.638171 | [
"Apache-2.0"
] | skwasjer/SilentHunter | src/SilentHunter.Controllers/SHSim/wpn_DCRack.cs | 1,009 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Principal;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Serialization;
using MaxMelcher.QueryLogger.Utils;
using Microsoft.AspNet.SignalR.Client;
using mshtml;
using SearchQueryTool.Helpers;
using SearchQueryTool.Model;
using Path = System.IO.Path;
using ResultItem = SearchQueryTool.Model.ResultItem;
using ADAL = Microsoft.IdentityModel.Clients.ActiveDirectory;
namespace SearchQueryTool
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
{
private enum SearchMethodType
{
Query,
Suggest
}
private enum PropertyType
{
Managed,
Crawled
}
private const string DefaultSharePointSiteUrl = "http://localhost";
private const string ConnectionPropsXmlFileName = "connection-props.xml";
private const string AuthorityUri = "https://login.windows.net/common/oauth2/authorize";
private ADAL.AuthenticationContext AuthContext = null;
private SearchQueryRequest _searchQueryRequest;
private readonly SearchSuggestionsRequest _searchSuggestionsRequest;
private SearchConnection _searchConnection;
public SearchResultPresentationSettings SearchPresentationSettings;
private string _presetAnnotation;
private SearchResult _searchResults;
private bool _enableExperimentalFeatures;
private bool _firstInit = true;
public SearchPresetList SearchPresets { get; set; }
private string PresetFolderPath { get; set; }
public SearchHistory SearchHistory { get; set; }
internal string HistoryFolderPath { get; set; }
public History History { get; }
public SafeObservable<SearchQueryDebug> ObservableQueryCollection { get; set; }
private readonly object _locker = new object();
private IHubProxy _hub;
private HubConnection _hubConnection;
public MainWindow()
{
ServicePointManager.ServerCertificateValidationCallback +=
(sender, certificate, chain, sslPolicyErrors) => true;
_searchQueryRequest = new SearchQueryRequest { SharePointSiteUrl = DefaultSharePointSiteUrl };
_searchSuggestionsRequest = new SearchSuggestionsRequest { SharePointSiteUrl = DefaultSharePointSiteUrl };
_searchSuggestionsRequest = new SearchSuggestionsRequest { SharePointSiteUrl = DefaultSharePointSiteUrl };
_searchConnection = new SearchConnection();
ObservableQueryCollection = new SafeObservable<SearchQueryDebug>(Dispatcher);
InitializeComponent();
InitializeControls();
HistoryFolderPath = InitDirectoryFromSetting("HistoryFolderPath", @".\History");
var historyMaxFiles = ReadSettingInt("HistoryMaxFiles", 1000);
History = new History(this);
History.PruneHistoryDir(HistoryFolderPath, historyMaxFiles);
SearchHistory = new SearchHistory(HistoryFolderPath);
History.RefreshHistoryButtonState();
History.LoadLatestHistory(HistoryFolderPath);
// Get setting or use sensible default if not found
var tmpPath = ReadSetting("PresetsFolderPath");
if (!Regex.IsMatch(tmpPath, @"^\w", RegexOptions.IgnoreCase) && !tmpPath.StartsWith(@"\"))
{
tmpPath = Path.GetFullPath(tmpPath);
}
PresetFolderPath = (!string.IsNullOrEmpty(tmpPath)) ? tmpPath : Path.GetFullPath(@".\Presets");
if (!Directory.Exists(tmpPath))
{
try
{
Directory.CreateDirectory(tmpPath);
}
catch (Exception)
{
}
}
LoadSearchPresetsFromFolder(PresetFolderPath);
}
private string InitDirectoryFromSetting(string settingName, string defaultPath)
{
var tmpPath = String.Empty;
try
{
tmpPath = ReadSetting(settingName);
tmpPath = (!String.IsNullOrEmpty(tmpPath)) ? tmpPath : Path.GetFullPath(defaultPath);
if (!Directory.Exists(tmpPath))
{
Directory.CreateDirectory(tmpPath);
}
}
catch (Exception ex)
{
StateBarTextBlock.Text = String.Format("Failed to create folder for setting {0}, defaultPath {1}: {2}", settingName, defaultPath, ex.Message);
}
return tmpPath;
}
private static int ReadSettingInt(string key, int defaultValue)
{
int ret;
try
{
ret = Int32.Parse(ConfigurationManager.AppSettings[key]); ;
}
catch (Exception)
{
ret = defaultValue;
}
return ret;
}
private void InitializeControls()
{
// Default to setting identify as current Windows user identify
SetCurrentWindowsUserIdentity();
// Only load connection properties on initial load to avoid overriding settings in preset
if (_firstInit)
{
_searchConnection = LoadSearchConnection();
// Expand connection box on first startup
ConnectionExpanderBox.IsExpanded = true;
_firstInit = false;
}
//LoadSearchPresetsFromFolder();
AnnotatePresetTextBox.Text = _presetAnnotation;
UpdateRequestUriStringTextBlock();
UpdateSearchQueryRequestControls(_searchQueryRequest);
UpdateSearchConnectionControls(_searchConnection);
//Enable the cross acces to this collection elsewhere - see: http://stackoverflow.com/questions/14336750/upgrading-to-net-4-5-an-itemscontrol-is-inconsistent-with-its-items-source
DebugGrid.ItemsSource = ObservableQueryCollection;
}
static string ReadSetting(string key)
{
string ret = null;
try
{
var appSettings = ConfigurationManager.AppSettings;
string result = appSettings[key] ?? String.Empty;
ret = result;
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error reading app settings");
}
return ret;
}
private void UpdateSearchQueryRequestControls(SearchQueryRequest searchQueryRequest)
{
QueryTextBox.Text = searchQueryRequest.QueryText;
EnableStemmingCheckBox.IsChecked = searchQueryRequest.EnableStemming;
EnablePhoneticCheckBox.IsChecked = searchQueryRequest.EnablePhonetic;
EnableNicknamesCheckBox.IsChecked = searchQueryRequest.EnableNicknames;
TrimDuplicatesCheckBox.IsChecked = searchQueryRequest.TrimDuplicates;
EnableFqlCheckBox.IsChecked = searchQueryRequest.EnableFql;
EnableQueryRulesCheckBox.IsChecked = searchQueryRequest.EnableQueryRules;
ProcessBestBetsCheckBox.IsChecked = searchQueryRequest.ProcessBestBets;
ByPassResultTypesCheckBox.IsChecked = searchQueryRequest.ByPassResultTypes;
ProcessPersonalFavoritesCheckBox.IsChecked = searchQueryRequest.ProcessPersonalFavorites;
GenerateBlockRankLogCheckBox.IsChecked = searchQueryRequest.GenerateBlockRankLog;
IncludeRankDetailCheckBox.IsChecked = searchQueryRequest.IncludeRankDetail;
StartRowTextBox.Text = (searchQueryRequest.StartRow != null) ? searchQueryRequest.StartRow.ToString() : "0";
RowsTextBox.Text = (searchQueryRequest.RowLimit != null) ? searchQueryRequest.RowLimit.ToString() : "10";
RowsPerPageTextBox.Text = (searchQueryRequest.RowsPerPage != null)
? searchQueryRequest.RowsPerPage.ToString()
: "0";
SelectPropertiesTextBox.Text = searchQueryRequest.SelectProperties;
RefinersTextBox.Text = searchQueryRequest.Refiners;
SortListTextBox.Text = searchQueryRequest.SortList;
HiddenConstraintsTextBox.Text = searchQueryRequest.HiddenConstraints;
TrimDuplicatesIncludeIdTextBox.Text = searchQueryRequest.TrimDuplicatesIncludeId.ToString();
HitHighlightedPropertiesTextBox.Text = searchQueryRequest.HitHighlightedProperties;
PersonalizationDataTextBox.Text = searchQueryRequest.PersonalizationData;
CultureTextBox.Text = searchQueryRequest.Culture;
QueryTemplateTextBox.Text = searchQueryRequest.QueryTemplate;
RefinementFiltersTextBox.Text = searchQueryRequest.RefinementFilters;
// NB: Avoid setting this. Buggy?
//RankingModelIdTextBox.Text = _searchQueryRequest.RankingModelId;
SourceIdTextBox.Text = searchQueryRequest.SourceId;
CollapseSpecTextBox.Text = searchQueryRequest.CollapseSpecification;
AppendedQueryPropertiesTextBox.Text = searchQueryRequest.AppendedQueryProperties;
}
private SearchMethodType CurrentSearchMethodType
{
get
{
var selectedTabItem = SearchMethodTypeTabControl.SelectedItem as TabItem;
if (selectedTabItem == QueryMethodTypeTabItem)
{
// query
return SearchMethodType.Query;
}
// suggest
return SearchMethodType.Suggest;
}
}
private HttpMethodType CurrentHttpMethodType
{
get
{
if (HttpGetMethodRadioButton == null) return HttpMethodType.Get; // default to HTTP Get
return (HttpGetMethodRadioButton.IsChecked.Value ? HttpMethodType.Get : HttpMethodType.Post);
}
}
#region Event Handlers
#region Event Handlers for controls common to both query and suggestions
/// <summary>
/// Handles the Click event of the RunButton control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param>
private async void RunButton_Click(object sender, RoutedEventArgs e)
{
string dc = (AuthenticationMethodComboBox.SelectedItem as ComboBoxItem).DataContext as string;
if (AuthenticationTypeComboBox.SelectedIndex == 1 && dc == "SPOAuth2")
{
await AdalLogin(false);
}
SearchMethodType currentSelectedSearchMethodType = CurrentSearchMethodType;
// fire off the query operation
if (currentSelectedSearchMethodType == SearchMethodType.Query)
{
StartSearchQueryRequest();
}
else if (currentSelectedSearchMethodType == SearchMethodType.Suggest)
{
StartSearchSuggestionRequest();
}
}
/// <summary>
/// Handles the LostFocus event of the SharePointSiteUrlTextBox control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param>
private void SharePointSiteUrlTextBox_LostFocus(object sender, RoutedEventArgs e)
{
string url = SharePointSiteUrlTextBox.Text.Trim();
try
{
Uri testUri = new Uri(url);
}
catch (Exception)
{
SharePointSiteUrlAlertImage.Visibility = Visibility.Visible;
return;
}
SharePointSiteUrlAlertImage.Visibility = Visibility.Hidden;
_searchQueryRequest.SharePointSiteUrl = SharePointSiteUrlTextBox.Text.Trim();
_searchSuggestionsRequest.SharePointSiteUrl = SharePointSiteUrlTextBox.Text.Trim();
// TODO: Should we reset auth cookies if site url changes? Then we need to detect the history
// _searchQueryRequest.Cookies = null;
// _searchSuggestionsRequest.Cookies = null;
UpdateRequestUriStringTextBlock();
}
/// <summary>
/// Handles the SelectionChanged event of the SearchMethodTypeTabControl control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="SelectionChangedEventArgs" /> instance containing the event data.</param>
private void SearchMethodTypeTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
UpdateRequestUriStringTextBlock();
}
/// <summary>
/// Handles the SelectionChanged event of the AuthenticationTypeComboBox control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="SelectionChangedEventArgs" /> instance containing the event data.</param>
private void AuthenticationTypeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int selectedIndex = AuthenticationTypeComboBox.SelectedIndex;
if (selectedIndex == 0) // use current user
{
if (AuthenticationUsernameTextBox != null)
AuthenticationUsernameTextBox.IsEnabled = false;
if (AuthenticationPasswordTextBox != null)
AuthenticationPasswordTextBox.IsEnabled = false;
if (AuthenticationMethodComboBox != null)
{
AuthenticationMethodComboBox.SelectedIndex = 0;
AuthenticationMethodComboBox.IsEnabled = false;
}
SetCurrentWindowsUserIdentity();
_searchQueryRequest.AuthenticationType = AuthenticationType.CurrentUser;
_searchSuggestionsRequest.AuthenticationType = AuthenticationType.CurrentUser;
if (UsernameAndPasswordTextBoxContainer != null)
{
UsernameAndPasswordTextBoxContainer.Visibility = Visibility.Visible;
}
if (LoginButtonContainer != null)
{
LoginButtonContainer.Visibility = Visibility.Hidden;
}
if (AuthenticationMethodComboBox != null)
AuthenticationMethodComboBox.IsEnabled = true;
}
else if (selectedIndex == 1)
{
AuthenticationMethodComboBox.IsEnabled = true;
AuthenticationUsernameTextBox.IsEnabled = true;
AuthenticationPasswordTextBox.IsEnabled = true;
AuthenticationMethodComboBox_SelectionChanged(null, null);
if (AuthenticationMethodComboBox != null)
AuthenticationMethodComboBox.IsEnabled = true;
}
else
{
//anonymous
_searchQueryRequest.AuthenticationType = AuthenticationType.Anonymous;
_searchSuggestionsRequest.AuthenticationType = AuthenticationType.Anonymous;
if (AuthenticationMethodComboBox != null)
AuthenticationMethodComboBox.IsEnabled = false;
}
AuthenticationMethodComboBox_SelectionChanged(sender, e);
}
private void AuthenticationMethodComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// 0 - Windows
// 1 - SharePoint Online
// 2 - Forms-based
// 3 - Forefront gateway (UAG/TMG)
//if (this.AuthenticationTypeComboBox.SelectedIndex == 2) return;
//if (this.AuthenticationMethodComboBox.SelectedIndex == 2) return; //anonymous
if (AuthenticationTypeComboBox.SelectedIndex == 0)
{
return;
}
LoginInfo.Visibility = Visibility.Hidden;
string dc = (AuthenticationMethodComboBox.SelectedItem as ComboBoxItem).DataContext as string;
if (AuthenticationTypeComboBox.SelectedIndex == 2) dc = "Anonymous";
if (dc == "WinAuth")
{
_searchQueryRequest.AuthenticationType = AuthenticationType.Windows;
_searchSuggestionsRequest.AuthenticationType = _searchQueryRequest.AuthenticationType;
UsernameAndPasswordTextBoxContainer.Visibility = Visibility.Visible;
LoginButtonContainer.Visibility = Visibility.Hidden;
}
else if (dc == "SPOAuth")
{
_searchQueryRequest.AuthenticationType = AuthenticationType.SPO;
_searchSuggestionsRequest.AuthenticationType = _searchQueryRequest.AuthenticationType;
UsernameAndPasswordTextBoxContainer.Visibility = Visibility.Hidden;
LoginButtonContainer.Visibility = Visibility.Visible;
LoggedinLabel.Visibility = Visibility.Hidden;
LoginInfo.Visibility = Visibility.Visible;
}
else if (dc == "SPOAuth2")
{
_searchQueryRequest.AuthenticationType = AuthenticationType.SPOManagement;
_searchSuggestionsRequest.AuthenticationType = _searchQueryRequest.AuthenticationType;
UsernameAndPasswordTextBoxContainer.Visibility = Visibility.Hidden;
LoginButtonContainer.Visibility = Visibility.Visible;
LoggedinLabel.Visibility = Visibility.Hidden;
LoginInfo.Visibility = Visibility.Visible;
}
else if (dc == "FormsAuth")
{
_searchQueryRequest.AuthenticationType = AuthenticationType.Forms;
_searchSuggestionsRequest.AuthenticationType = _searchQueryRequest.AuthenticationType;
UsernameAndPasswordTextBoxContainer.Visibility = Visibility.Visible;
LoginButtonContainer.Visibility = Visibility.Hidden;
}
else if (dc == "ForefrontAuth")
{
_searchQueryRequest.AuthenticationType = AuthenticationType.Forefront;
_searchSuggestionsRequest.AuthenticationType = _searchQueryRequest.AuthenticationType;
UsernameAndPasswordTextBoxContainer.Visibility = Visibility.Hidden;
LoginButtonContainer.Visibility = Visibility.Visible;
LoggedinLabel.Visibility = Visibility.Hidden;
}
else if (dc == "Anonymous")
{
_searchQueryRequest.AuthenticationType = AuthenticationType.Anonymous;
_searchSuggestionsRequest.AuthenticationType = _searchQueryRequest.AuthenticationType;
UsernameAndPasswordTextBoxContainer.Visibility = Visibility.Hidden;
LoginButtonContainer.Visibility = Visibility.Hidden;
}
}
private void AuthenticationUsernameTextBox_LostFocus(object sender, RoutedEventArgs e)
{
_searchQueryRequest.UserName = AuthenticationUsernameTextBox.Text;
_searchSuggestionsRequest.UserName = AuthenticationUsernameTextBox.Text;
}
private void AuthenticationPasswordTextBox_LostFocus(object sender, RoutedEventArgs e)
{
AuthenticationUsernameTextBox_LostFocus(sender, e); // trigger setting of username
_searchQueryRequest.SecurePassword = AuthenticationPasswordTextBox.SecurePassword;
_searchQueryRequest.Password = AuthenticationPasswordTextBox.Password;
_searchSuggestionsRequest.SecurePassword = AuthenticationPasswordTextBox.SecurePassword;
_searchSuggestionsRequest.Password = AuthenticationPasswordTextBox.Password;
}
private async void LoginButton_Click(object sender, RoutedEventArgs e)
{
LoggedinLabel.Visibility = Visibility.Hidden;
_searchQueryRequest.Cookies = null;
_searchSuggestionsRequest.Cookies = null;
try
{
SharePointSiteUrlTextBox_LostFocus(sender, e);
string dc = ((ComboBoxItem)AuthenticationMethodComboBox.SelectedItem).DataContext as string;
if (dc == "SPOAuth2")
{
try
{
await AdalLogin(true);
if (string.IsNullOrWhiteSpace(_searchQueryRequest.Token)) throw new ApplicationException("No token");
LoggedinLabel.Visibility = Visibility.Visible;
}
catch (Exception exception)
{
ShowMsgBox(
$"Authentication failed. Please try again.\n\n{_searchQueryRequest.SharePointSiteUrl}\n\n{exception.Message}");
}
}
else
{
AuthContext = null;
CookieCollection cc = WebAuthentication.GetAuthenticatedCookies(_searchQueryRequest.SharePointSiteUrl, _searchQueryRequest.AuthenticationType);
if (cc == null)
{
ShowMsgBox(
$"Authentication failed. Please try again.\n\n{_searchQueryRequest.SharePointSiteUrl}");
}
else
{
LoggedinLabel.Visibility = Visibility.Visible;
}
_searchQueryRequest.Cookies = cc;
_searchSuggestionsRequest.Cookies = cc;
}
}
catch (Exception ex)
{
ShowError(ex);
ShowMsgBox(
$"Authentication failed. Please try again.\n\n{_searchQueryRequest.SharePointSiteUrl}\n\n{ex.Message}");
}
}
async Task AdalLogin(bool forcePrompt)
{
var spUri = new Uri(_searchQueryRequest.SharePointSiteUrl);
string resourceUri = spUri.Scheme + "://" + spUri.Authority;
const string clientId = "9bc3ab49-b65d-410a-85ad-de819febfddc";
const string redirectUri = "https://oauth.spops.microsoft.com/";
Window ownerWindow = Application.Current.MainWindow.Owner;
ADAL.AuthenticationResult authenticationResult;
if (AuthContext == null || forcePrompt)
{
ADAL.TokenCache cache = new ADAL.TokenCache();
AuthContext = new ADAL.AuthenticationContext(AuthorityUri, cache);
}
try
{
if (forcePrompt) throw new ADAL.AdalSilentTokenAcquisitionException();
authenticationResult = await AuthContext.AcquireTokenSilentAsync(resourceUri, clientId);
}
catch (ADAL.AdalSilentTokenAcquisitionException)
{
var authParam = new ADAL.PlatformParameters(ADAL.PromptBehavior.Always, ownerWindow);
authenticationResult = await AuthContext.AcquireTokenAsync(resourceUri, clientId, new Uri(redirectUri), authParam);
}
_searchQueryRequest.Token = authenticationResult.CreateAuthorizationHeader();
_searchSuggestionsRequest.Token = authenticationResult.CreateAuthorizationHeader();
}
#endregion
#region Event Handlers for Controls on the Search Query Tab
/// <summary>
/// Handles the Handler event of the SearchQueryTextBox_LostFocus control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param>
private void SearchQueryTextBox_LostFocus_Handler(object sender, RoutedEventArgs e)
{
TextBox tb = sender as TextBox;
if (tb != null)
{
string dataContext = (tb.DataContext as string) ?? "";
switch (dataContext.ToLower())
{
case "query":
_searchQueryRequest.QueryText = tb.Text.Trim();
break;
case "querytemplate":
_searchQueryRequest.QueryTemplate = tb.Text.Trim();
break;
case "selectproperties":
_searchQueryRequest.SelectProperties = tb.Text.Trim();
break;
case "refiners":
_searchQueryRequest.Refiners = tb.Text.Trim();
break;
case "refinementfilters":
_searchQueryRequest.RefinementFilters = tb.Text.Trim();
break;
case "trimduplicatesincludeid":
_searchQueryRequest.TrimDuplicatesIncludeId = DataConverter.TryConvertToLong(tb.Text.Trim());
break;
case "sortlist":
_searchQueryRequest.SortList = tb.Text.Trim();
break;
case "hithighlightedproperties":
_searchQueryRequest.HitHighlightedProperties = tb.Text.Trim();
break;
case "rankingmodelid":
_searchQueryRequest.RankingModelId = tb.Text.Trim();
break;
case "hiddenconstraints":
_searchQueryRequest.HiddenConstraints = tb.Text.Trim();
break;
case "personalizationdata":
_searchQueryRequest.PersonalizationData = tb.Text.Trim();
break;
case "resultsurl":
_searchQueryRequest.ResultsUrl = tb.Text.Trim();
break;
case "querytag":
_searchQueryRequest.QueryTag = tb.Text.Trim();
break;
case "collapsespecification":
_searchQueryRequest.CollapseSpecification = tb.Text.Trim();
break;
case "startrow":
_searchQueryRequest.StartRow = DataConverter.TryConvertToInt(tb.Text.Trim());
break;
case "rows":
_searchQueryRequest.RowLimit = DataConverter.TryConvertToInt(tb.Text.Trim());
break;
case "rowsperpage":
_searchQueryRequest.RowsPerPage = DataConverter.TryConvertToInt(tb.Text.Trim());
break;
case "appendedqueryproperties":
_searchQueryRequest.AppendedQueryProperties = tb.Text.Trim();
break;
}
UpdateRequestUriStringTextBlock();
}
if (sender is ComboBox cb)
{
string dataContext = (cb.DataContext as string) ?? "";
switch (dataContext.ToLower())
{
case "sourceid":
{
string sourceId = cb.Text;
ComboBoxItem comboBoxItem = cb.SelectedItem as ComboBoxItem;
if (comboBoxItem?.Tag != null)
{
sourceId = comboBoxItem.Tag as string;
}
if (sourceId != null)
{
_searchQueryRequest.SourceId = System.Web.HttpUtility.UrlDecode(sourceId.Trim());
}
cb.Text = _searchQueryRequest.SourceId;
break;
}
case "culture":
{
string culture = cb.Text;
ComboBoxItem comboBoxItem = cb.SelectedItem as ComboBoxItem;
if (comboBoxItem?.Tag != null)
{
culture = comboBoxItem.Tag as string;
}
if (culture != null)
{
_searchQueryRequest.Culture = culture;
}
cb.Text = _searchQueryRequest.Culture;
break;
}
}
UpdateRequestUriStringTextBlock();
}
}
/// <summary>
/// Handles the CheckChanged event of the SearchQueryCheckBox control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param>
private void SearchQueryCheckBox_CheckChanged(object sender, RoutedEventArgs e)
{
if (sender is CheckBox cb)
{
string datacontext = (cb.DataContext as string) ?? "";
switch (datacontext.ToLower())
{
case "enablestemming":
_searchQueryRequest.EnableStemming = cb.IsChecked;
break;
case "enablequeryrules":
_searchQueryRequest.EnableQueryRules = cb.IsChecked;
break;
case "enablenicknames":
_searchQueryRequest.EnableNicknames = cb.IsChecked;
break;
case "processbestbets":
_searchQueryRequest.ProcessBestBets = cb.IsChecked;
break;
case "trimduplicates":
_searchQueryRequest.TrimDuplicates = cb.IsChecked;
break;
case "enablefql":
_searchQueryRequest.EnableFql = cb.IsChecked;
break;
case "enablephonetic":
_searchQueryRequest.EnablePhonetic = cb.IsChecked;
break;
case "bypassresulttypes":
_searchQueryRequest.ByPassResultTypes = cb.IsChecked;
break;
case "processpersonalfavorites":
_searchQueryRequest.ProcessPersonalFavorites = cb.IsChecked;
break;
case "generateblockranklog":
_searchQueryRequest.GenerateBlockRankLog = cb.IsChecked;
break;
case "includerankdetail":
_searchQueryRequest.IncludeRankDetail = cb.IsChecked;
break;
case "experimentalfeatures":
_enableExperimentalFeatures = cb.IsChecked.Value;
break;
}
UpdateRequestUriStringTextBlock();
}
}
/// <summary>
/// Handles the SelectionChanged event of the QueryLogClientTypeComboBox control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="SelectionChangedEventArgs" /> instance containing the event data.</param>
private void QueryLogClientTypeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string selectedValue = ((ComboBoxItem)QueryLogClientTypeComboBox.SelectedItem).DataContext as string;
_searchQueryRequest.ClientType = selectedValue;
UpdateRequestUriStringTextBlock();
}
private void ResetCheckboxesButton_Click(object sender, RoutedEventArgs e)
{
_searchQueryRequest.EnableStemming = null;
EnableStemmingCheckBox.IsChecked = null;
_searchQueryRequest.EnableQueryRules = null;
EnableQueryRulesCheckBox.IsChecked = null;
_searchQueryRequest.EnableNicknames = null;
EnableNicknamesCheckBox.IsChecked = null;
_searchQueryRequest.ProcessBestBets = null;
ProcessBestBetsCheckBox.IsChecked = null;
_searchQueryRequest.TrimDuplicates = null;
TrimDuplicatesCheckBox.IsChecked = null;
_searchQueryRequest.EnableFql = null;
EnableFqlCheckBox.IsChecked = null;
_searchQueryRequest.EnablePhonetic = null;
EnablePhoneticCheckBox.IsChecked = null;
_searchQueryRequest.ByPassResultTypes = null;
ByPassResultTypesCheckBox.IsChecked = null;
_searchQueryRequest.ProcessPersonalFavorites = null;
ProcessPersonalFavoritesCheckBox.IsChecked = null;
_searchQueryRequest.GenerateBlockRankLog = null;
GenerateBlockRankLogCheckBox.IsChecked = null;
UpdateRequestUriStringTextBlock();
}
private void HttpMethodModeRadioButton_Checked(object sender, RoutedEventArgs e)
{
UpdateRequestUriStringTextBlock();
}
#endregion
#region Event Handlers for Controls on the Search Suggestion Tab
private void SearchSuggestionsTextBox_LostFocus_Handler(object sender, RoutedEventArgs e)
{
if (sender is TextBox tb)
{
string dataContext = (tb.DataContext as string) ?? "";
switch (dataContext.ToLower())
{
case "query":
_searchSuggestionsRequest.QueryText = tb.Text.Trim();
break;
case "numberofquerysuggestions":
_searchSuggestionsRequest.NumberOfQuerySuggestions = DataConverter.TryConvertToInt(tb.Text.Trim());
break;
case "numberofresultsuggestions":
_searchSuggestionsRequest.NumberOfResultSuggestions = DataConverter.TryConvertToInt(tb.Text.Trim());
break;
}
UpdateRequestUriStringTextBlock();
}
if (sender is ComboBox cb)
{
string dataContext = (cb.DataContext as string) ?? "";
switch (dataContext.ToLower())
{
case "suggestionsculture":
{
string suggestionsCulture = cb.Text;
if (cb.SelectedItem is ComboBoxItem comboBoxItem && comboBoxItem.Tag != null)
{
suggestionsCulture = comboBoxItem.Tag as string;
}
if (!string.IsNullOrWhiteSpace(suggestionsCulture))
{
_searchSuggestionsRequest.Culture = DataConverter.TryConvertToInt(suggestionsCulture);
cb.Text = _searchSuggestionsRequest.Culture.ToString();
}
else
{
_searchSuggestionsRequest.Culture = null;
cb.Text = "";
}
break;
}
}
UpdateRequestUriStringTextBlock();
}
}
private void SearchSuggestionsCheckBox_CheckChanged(object sender, RoutedEventArgs e)
{
if (sender is CheckBox cb)
{
string datacontext = (cb.DataContext as string) ?? "";
switch (datacontext.ToLower())
{
case "prequerysuggestions":
_searchSuggestionsRequest.PreQuerySuggestions = cb.IsChecked;
break;
case "showpeoplenamesuggestions":
_searchSuggestionsRequest.ShowPeopleNameSuggestions = cb.IsChecked;
break;
case "hithighlighting":
_searchSuggestionsRequest.HitHighlighting = cb.IsChecked;
break;
case "capitalizefirstletters":
_searchSuggestionsRequest.CapitalizeFirstLetters = cb.IsChecked;
break;
}
UpdateRequestUriStringTextBlock();
}
}
#endregion
#region Event Handlers for Menu controls
/// <summary>
/// Handles the Click event of the PasteExampleButton control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param>
private void PasteExampleButton_Click(object sender, RoutedEventArgs e)
{
if (e.Source != null)
{
object d = (e.Source as Button).DataContext;
if (d != null && d is String)
{
string senderDatacontext = d as string;
if (!string.IsNullOrWhiteSpace(senderDatacontext))
{
string exampleString = SampleStrings.GetExampleStringFor(senderDatacontext);
if (!string.IsNullOrWhiteSpace(exampleString))
{
switch (senderDatacontext.ToLower())
{
case "rankingmodelid":
RankingModelIdTextBox.Text = exampleString;
RankingModelIdTextBox.Focus();
break;
case "hiddenconstraints":
HiddenConstraintsTextBox.Text = exampleString;
HiddenConstraintsTextBox.Focus();
break;
case "selectproperties":
SelectPropertiesTextBox.Text = exampleString;
SelectPropertiesTextBox.Focus();
break;
case "refiners":
RefinersTextBox.Text = exampleString;
RefinersTextBox.Focus();
break;
case "refinementfilters":
RefinementFiltersTextBox.Text = exampleString;
RefinementFiltersTextBox.Focus();
break;
case "sortlist":
SortListTextBox.Text = exampleString;
SortListTextBox.Focus();
break;
case "sourceid":
SourceIdTextBox.Text = exampleString;
SourceIdTextBox.Focus();
break;
default:
break;
}
}
}
}
}
}
private void CleanSelectProperties_Click(object sender, RoutedEventArgs e)
{
var dirtyProperties = SelectPropertiesTextBox.Text;
if (!string.IsNullOrWhiteSpace(dirtyProperties))
{
var dirtyPropertyList = dirtyProperties.Split(',');
if (dirtyPropertyList != null && dirtyPropertyList.Length > 0)
{
var cleanList = dirtyPropertyList.Distinct().ToList();
cleanList.Sort();
var cleanProperties = String.Join(",", cleanList);
SelectPropertiesTextBox.Text = cleanProperties;
SelectPropertiesTextBox.Focus();
}
}
}
private void MenuSaveConnectionProperties_Click(object sender, RoutedEventArgs e)
{
// Create a connection object with all data from the user interface
var connection = GetSearchConnectionFromUi();
// Store to disk as XML
try
{
var outputPath = Path.Combine(Environment.CurrentDirectory, ConnectionPropsXmlFileName);
connection.SaveXml(outputPath);
StateBarTextBlock.Text = $"Successfully saved connection properties to {Path.GetFullPath(outputPath)}";
}
catch (Exception ex)
{
ShowMsgBox("Failed to save connection properties. Error:" + ex.Message);
}
}
/// <summary>
/// Handles the Click event of the MenuFileExit control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param>
private void MenuFileExit_Click(object sender, RoutedEventArgs e)
{
Close();
}
/// <summary>
/// Handles the Click event of the MenuAbout control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param>
private void MenuAbout_Click(object sender, RoutedEventArgs e)
{
new AboutBox().Show();
}
#endregion
#endregion
#region Request Building methods and Helpers
/// <summary>
/// Starts the search query request.
/// </summary>
private void StartSearchQueryRequest()
{
string status = "Init";
string queryText = QueryTextBox.Text.Trim();
if (string.IsNullOrEmpty(queryText))
{
QueryTextBox.Focus();
return;
}
try
{
_searchQueryRequest.QueryText = queryText;
UpdateRequestUriStringTextBlock();
status = "Running";
MarkRequestOperation(true, status);
RequestStarted();
_searchQueryRequest.HttpMethodType = CurrentHttpMethodType;
_searchQueryRequest.AcceptType = AcceptJsonRadioButton.IsChecked.Value
? AcceptType.Json
: AcceptType.Xml;
//todo this should be split to several methods so we can reuse them
Task.Factory.StartNew(() => HttpRequestRunner.RunWebRequest(_searchQueryRequest),
TaskCreationOptions.LongRunning)
.ContinueWith(task =>
{
if (task.Exception != null)
{
RequestFailed();
ShowError(task.Exception);
}
else
{
var requestResponsePair = task.Result;
if (requestResponsePair != null)
{
var response = requestResponsePair.Item2;
if (null != response)
{
if (response.StatusCode.Equals(HttpStatusCode.OK))
{
RequestSuccessful();
status = "Done";
}
else
{
RequestFailed();
status = String.Format("HTTP {0}, {1}", response.StatusCode, response.StatusDescription);
}
}
}
var searchResults = GetResultItem(requestResponsePair);
_searchResults = searchResults;
// set status
SetHitStatus(searchResults);
// set the result
SetStatsResult(searchResults);
SetRawResult(searchResults);
SetPrimaryQueryResultItems(searchResults);
SetRefinementResultItems(searchResults);
SetSecondaryQueryResultItems(searchResults);
}
}, TaskScheduler.FromCurrentSynchronizationContext()).ContinueWith(task =>
{
if (task.Exception != null)
{
ShowError(task.Exception);
}
MarkRequestOperation(false, status);
});
}
catch (Exception ex)
{
MarkRequestOperation(false, status);
RequestFailed();
ShowError(ex);
}
}
private void SetHitStatus(SearchQueryResult searchResults)
{
this.Dispatcher.Invoke(() =>
{
if (null != searchResults)
{
var totalRows = 0;
var queryElapsedTime = "0";
if (null != searchResults.QueryElapsedTime)
{
queryElapsedTime = searchResults.QueryElapsedTime;
}
if (null != searchResults.PrimaryQueryResult)
{
totalRows = searchResults.PrimaryQueryResult.TotalRows;
}
HitStatusTextBlock.Text = String.Format("{0} hits in {1} ms", totalRows, queryElapsedTime);
}
});
}
private void RequestStarted()
{
this.Dispatcher.Invoke(() =>
{
ConnectionExpanderBox.Foreground = Brushes.Purple;
HitStatusTextBlock.Text = "...";
});
}
private void RequestSuccessful()
{
this.Dispatcher.Invoke(() =>
{
ConnectionExpanderBox.IsExpanded = false;
ConnectionExpanderBox.Foreground = Brushes.Green;
RequestUriLengthTextBox.Foreground = Brushes.Gray;
HitStatusTextBlock.Foreground = Brushes.Black;
// Save this successful item to our history
History.SaveHistoryItem();
// Reload entire history list and reset the current point to the latest entry
SearchHistory = new SearchHistory(HistoryFolderPath);
History.RefreshHistoryButtonState();
RefreshBreadCrumbs();
});
}
private void RequestFailed()
{
this.Dispatcher.Invoke(() =>
{
ConnectionExpanderBox.Foreground = Brushes.Red;
HitStatusTextBlock.Foreground = Brushes.Red;
RequestUriLengthTextBox.Foreground = Brushes.Red;
});
}
private Button GetHiddenConstraintsButton(string text)
{
var panel = new StackPanel
{
Orientation = Orientation.Horizontal,
};
var uriSource = new Uri(@"/SearchQueryTool;component/Images/remove.png", UriKind.Relative);
//var uriSource = new Uri(@"/Resources;Images/remove.png", UriKind.Relative);
//var uriSource = new Uri(@"/Resources;remove.png", UriKind.Relative);
//var img = new BitmapImage(uriSource);
//var img = new BitmapImage(new Uri("Images/alert_icon.png", UriKind.Relative));
var img = new BitmapImage(new Uri("Images/remove.png", UriKind.Relative));
//var icon = new Image() { Source = new BitmapImage(uriSource), Margin = new Thickness(5, 0, 5, 0) };
var icon = new Image() { Source = img, Margin = new Thickness(5, 0, 5, 0) };
panel.Children.Add(icon);
panel.Children.Add(new TextBlock() { Text = text });
var button = new Button
{
Margin = new Thickness(5),
Content = panel,
};
button.Click += HiddenConstraintsRemoveButton_OnClick;
return button;
}
private static List<string> ParseHiddenConstraints(string input)
{
var ret = new List<string>();
if (string.IsNullOrWhiteSpace(input)) return ret;
var regex = new Regex(@"(?<key>\(*\w+)[:|=<>](?<value>""[\S\s]+""\)*|\w+\)*)");
try
{
var buf = input;
var match = regex.Match(buf);
while (match.Success)
{
var m = match.Captures[0].ToString();
buf = buf.Replace(m, "").Trim();
ret.Add(m);
match = regex.Match(buf);
}
}
catch
{
// ignore
}
return ret;
}
private void RefreshBreadCrumbs()
{
this.Dispatcher.Invoke(() =>
{
// Clear old hidden constraints
HiddenConstraintWrapPanel.Children.Clear();
// ParseHiddenConstraints hidden constraints and populate panel with new breadcrumb buttons
var hiddenConstraints = HiddenConstraintsTextBox.Text;
if (string.IsNullOrWhiteSpace(hiddenConstraints))
{
// Initialize state when we have no hidden constraints
ExpanderHiddenConstraints.Header = String.Format("Hidden Constraints");
BreadCrumbDockPanel.Visibility = Visibility.Collapsed;
}
else
{
// Extract patterns like with quotes and space, e.g.: ContentSource:"Local SharePoint"
var list = ParseHiddenConstraints(hiddenConstraints);
if (list.Any())
{
ExpanderHiddenConstraints.Header = String.Format("Hidden Constraints ({0})", list.Count());
foreach (var button in list.Select(GetHiddenConstraintsButton))
{
HiddenConstraintWrapPanel.Children.Add(button);
}
BreadCrumbDockPanel.Visibility = Visibility.Visible;
}
else
{
// Hide breadcrumbs when there are no matches
BreadCrumbDockPanel.Visibility = Visibility.Collapsed;
}
}
});
}
private void HiddenConstraintsRemoveButton_OnClick(object sender, RoutedEventArgs e)
{
// Read text from button
var btn = sender as Button;
if (btn != null)
{
var btnPanel = btn.Content as StackPanel;
if (btnPanel != null)
{
var textBlock = btnPanel.Children.OfType<TextBlock>().FirstOrDefault();
if (textBlock != null)
{
var text = textBlock.Text;
// Remove text from HiddenConstraints
if (!string.IsNullOrWhiteSpace(text))
{
HiddenConstraintsTextBox.Text = HiddenConstraintsTextBox.Text.Replace(text.Trim(), "").Trim();
// Fire focus lost event to refresh the breadcrumbs (i.e. should remove the button we clicked)
RefreshBreadCrumbs();
}
}
}
}
}
private SearchQueryResult GetResultItem(HttpRequestResponsePair requestResponsePair)
{
SearchQueryResult searchResults;
var request = requestResponsePair.Item1;
using (var response = requestResponsePair.Item2)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
NameValueCollection requestHeaders = new NameValueCollection();
foreach (var header in request.Headers.AllKeys)
{
requestHeaders.Add(header, request.Headers[header]);
}
NameValueCollection responseHeaders = new NameValueCollection();
foreach (var header in response.Headers.AllKeys)
{
responseHeaders.Add(header, response.Headers[header]);
}
string requestContent = "";
if (request.Method == "POST")
{
requestContent = requestResponsePair.Item3;
}
searchResults = new SearchQueryResult
{
RequestUri = request.RequestUri,
RequestMethod = request.Method,
RequestContent = requestContent,
ContentType = response.ContentType,
ResponseContent = content,
RequestHeaders = requestHeaders,
ResponseHeaders = responseHeaders,
StatusCode = response.StatusCode,
StatusDescription = response.StatusDescription,
HttpProtocolVersion = response.ProtocolVersion.ToString()
};
searchResults.Process();
}
}
return searchResults;
}
/// <summary>
/// Starts the search suggestion request.
/// </summary>
private void StartSearchSuggestionRequest()
{
string queryText = SuggestionsQueryTextBox.Text.Trim();
if (string.IsNullOrEmpty(queryText))
{
SuggestionsQueryTextBox.Focus();
return;
}
_searchSuggestionsRequest.QueryText = queryText;
UpdateRequestUriStringTextBlock();
try
{
MarkRequestOperation(true, "Running");
_searchSuggestionsRequest.HttpMethodType = HttpMethodType.Get;
// Only get is supported for suggestions
_searchSuggestionsRequest.AcceptType = AcceptJsonRadioButton.IsChecked.Value
? AcceptType.Json
: AcceptType.Xml;
_searchSuggestionsRequest.Cookies = _searchQueryRequest.Cookies;
_searchSuggestionsRequest.UserName = _searchQueryRequest.UserName;
_searchSuggestionsRequest.Password = _searchQueryRequest.Password;
_searchSuggestionsRequest.SecurePassword = _searchQueryRequest.SecurePassword;
Task.Factory.StartNew(() => { return HttpRequestRunner.RunWebRequest(_searchSuggestionsRequest); },
TaskCreationOptions.LongRunning)
.ContinueWith(task =>
{
MarkRequestOperation(false, "Done");
if (task.Exception != null)
{
ShowError(task.Exception);
}
else
{
var requestResponsePair = task.Result;
var request = requestResponsePair.Item1;
using (var response = requestResponsePair.Item2)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
NameValueCollection requestHeaders = new NameValueCollection();
foreach (var header in request.Headers.AllKeys)
{
requestHeaders.Add(header, request.Headers[header]);
}
NameValueCollection responseHeaders = new NameValueCollection();
foreach (var header in response.Headers.AllKeys)
{
responseHeaders.Add(header, response.Headers[header]);
}
var searchResults = new SearchSuggestionsResult
{
RequestUri = request.RequestUri,
RequestMethod = request.Method,
ContentType = response.ContentType,
ResponseContent = content,
RequestHeaders = requestHeaders,
ResponseHeaders = responseHeaders,
StatusCode = response.StatusCode,
StatusDescription = response.StatusDescription,
HttpProtocolVersion = response.ProtocolVersion.ToString()
};
searchResults.Process();
// set the result
SetStatsResult(searchResults);
SetRawResult(searchResults);
SetSuggestionsResultItems(searchResults);
}
}
}
}, TaskScheduler.FromCurrentSynchronizationContext());
}
catch (Exception ex)
{
// log
ShowError(ex);
}
finally
{
MarkRequestOperation(false, "Done");
}
}
/// <summary>
/// Creates and populates the the Statistics tab from data from the passed in <paramref name="searchResult" />.
/// This method is used for both query and suggestions.
/// </summary>
/// <param name="searchResult">The search result.</param>
private void SetStatsResult(SearchResult searchResult)
{
ScrollViewer sv = new ScrollViewer();
sv.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
sv.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
TextBox tb = new TextBox
{
BorderBrush = null,
IsReadOnly = true,
IsReadOnlyCaretVisible = false,
TextWrapping = TextWrapping.WrapWithOverflow
};
tb.AppendText(
$"HTTP/{searchResult.HttpProtocolVersion} {(int)searchResult.StatusCode} {searchResult.StatusDescription}\n");
if (searchResult.StatusCode != HttpStatusCode.OK)
{
tb.AppendText(searchResult.ResponseContent);
}
if (searchResult is SearchQueryResult)
{
var searchQueryResult = searchResult as SearchQueryResult;
if (!string.IsNullOrEmpty(searchQueryResult.SerializedQuery))
tb.AppendText($"\tSerialized Query:\n{searchQueryResult.SerializedQuery}\n\n");
if (!string.IsNullOrEmpty(searchQueryResult.QueryElapsedTime))
tb.AppendText($"\tElapsed Time (ms): {searchQueryResult.QueryElapsedTime}\n\n");
if (searchQueryResult.TriggeredRules != null && searchQueryResult.TriggeredRules.Count > 0)
{
tb.AppendText("\tTriggered Rules:\n");
foreach (var rule in searchQueryResult.TriggeredRules)
{
tb.AppendText($"\t\tQuery Rule Id: {rule}\n");
}
tb.AppendText("\n");
}
if (searchQueryResult.PrimaryQueryResult != null)
{
tb.AppendText("\tPrimary Query Results:\n");
tb.AppendText($"\t\tTotal Rows: {searchQueryResult.PrimaryQueryResult.TotalRows}\n");
tb.AppendText(
$"\t\tTotal Rows Including Duplicates: {searchQueryResult.PrimaryQueryResult.TotalRowsIncludingDuplicates}\n");
tb.AppendText($"\t\tQuery Id: {searchQueryResult.PrimaryQueryResult.QueryId}\n");
tb.AppendText($"\t\tQuery Rule Id: {searchQueryResult.PrimaryQueryResult.QueryRuleId}\n");
tb.AppendText($"\t\tQuery Modification: {searchQueryResult.PrimaryQueryResult.QueryModification}\n");
}
if (searchQueryResult.SecondaryQueryResults != null)
{
tb.AppendText("\n");
tb.AppendText("\tSecondary Query Results:\n");
foreach (var sqr in searchQueryResult.SecondaryQueryResults)
{
tb.AppendText(String.Format("\t\tSecondary Query Result {0}\n", sqr.QueryRuleId));
tb.AppendText(String.Format("\t\tTotal Rows: {0}\n", sqr.TotalRows));
tb.AppendText(String.Format("\t\tTotal Rows Including Duplicates: {0}\n",
sqr.TotalRowsIncludingDuplicates));
tb.AppendText(String.Format("\t\tQuery Id: {0}\n", sqr.QueryId));
tb.AppendText(String.Format("\t\tQuery Rule Id: {0}\n", sqr.QueryRuleId));
tb.AppendText(String.Format("\t\tQuery Modification: {0}\n", sqr.QueryModification));
}
}
}
sv.Content = tb;
StatsResultTabItem.Content = sv;
}
/// <summary>
/// Creates and populates the the Headers tab from data from the passed in <paramref name="requestHeaders" /> and
/// <paramref name="responseHeaders" />.
/// This method is used for both query and suggestions.
/// </summary>
/// <param name="searchResult">The search result.</param>
private void SetRawResult(SearchResult searchResult)
{
ScrollViewer sv = new ScrollViewer();
sv.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
sv.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
TextBox tb = new TextBox
{
BorderBrush = null,
IsReadOnly = true,
IsReadOnlyCaretVisible = false,
FontSize = 12
};
tb.AppendText(String.Format("{0}\t{1}\tHTTP {2}\n\n", searchResult.RequestMethod, searchResult.RequestUri,
searchResult.HttpProtocolVersion));
tb.AppendText("Request:" + Environment.NewLine);
foreach (var header in searchResult.RequestHeaders.AllKeys)
{
tb.AppendText(String.Format("\t{0}: {1}{2}", header, searchResult.RequestHeaders[header],
Environment.NewLine));
}
tb.AppendText("\n\t" + searchResult.RequestContent + "\n");
tb.AppendText("\n\n");
tb.AppendText("Response:\n");
tb.AppendText(String.Format("\tHTTP/{0} {1} {2}\n", searchResult.HttpProtocolVersion,
(int)searchResult.StatusCode, searchResult.StatusDescription));
foreach (var header in searchResult.ResponseHeaders.AllKeys)
{
tb.AppendText(String.Format("\t{0}: {1}{2}", header, searchResult.ResponseHeaders[header],
Environment.NewLine));
}
if (AcceptJsonRadioButton.IsChecked.HasValue && AcceptJsonRadioButton.IsChecked.Value)
{
searchResult.ResponseContent = JsonHelper.FormatJson(searchResult.ResponseContent);
}
else
{
searchResult.ResponseContent = XmlHelper.PrintXml(searchResult.ResponseContent);
}
tb.AppendText("\n\t" + searchResult.ResponseContent + "\n");
sv.Content = tb;
RawResultTabItem.Content = sv;
}
/// <summary>
/// Creates and populates the the Primary results tab from data from the passed in <paramref name="searchResult" />.
/// This method is used for only query results.
/// </summary>
/// <param name="searchResult">The search result.</param>
private void SetPrimaryQueryResultItems(SearchQueryResult searchResult)
{
ScrollViewer sv = new ScrollViewer();
sv.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
sv.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
if (searchResult.PrimaryQueryResult != null && searchResult.PrimaryQueryResult.RelevantResults != null /*&&
searchResult.PrimaryQueryResult.TotalRows > 0*/)
{
StackPanel spTop = new StackPanel { Orientation = Orientation.Vertical };
int counter = 1;
foreach (ResultItem resultItem in searchResult.PrimaryQueryResult.RelevantResults)
{
StackPanel spEntry = new StackPanel { Margin = new Thickness(25) };
string resultTitle;
if (!string.IsNullOrWhiteSpace(resultItem.Title))
resultTitle = resultItem.Title + "";
else if (resultItem.ContainsKey("PreferredName"))
resultTitle = resultItem["PreferredName"] + "";
else if (resultItem.ContainsKey("DocId"))
resultTitle = String.Format("DocId: {0}", resultItem["DocId"] + "");
else
resultTitle = "<No title to display>";
resultTitle = counter + ". " + resultTitle;
if (SearchPresentationSettings != null && SearchPresentationSettings.PrimaryResultsTitleFormat != null)
{
var userFormat = SearchPresentationSettings.PrimaryResultsTitleFormat;
if (!string.IsNullOrWhiteSpace(userFormat))
{
resultTitle = CustomizeTitle(userFormat, resultItem, counter);
}
}
string path = resultItem.Path;
Hyperlink titleLink = new Hyperlink();
if (!string.IsNullOrWhiteSpace(resultItem.Path))
{
string linkpath = resultItem.Path.Replace('\\', '/'); // for fileshares which have url replacement
titleLink.NavigateUri = new Uri(linkpath);
titleLink.RequestNavigate += HyperlinkOnRequestNavigate;
}
titleLink.Foreground = Brushes.DarkBlue;
titleLink.FontSize = 14;
titleLink.Inlines.Add(new Run(resultTitle));
TextBlock linkBlock = new TextBlock();
linkBlock.Inlines.Add(titleLink);
spEntry.Children.Add(linkBlock);
//Dont expand entries
Expander propsExpander = new Expander { IsExpanded = false, Header = "View" };
StackPanel spProps = new StackPanel();
var keys = resultItem.Keys.ToList();
keys.Sort();
if (_searchQueryRequest.IncludeRankDetail.HasValue &&
_searchQueryRequest.IncludeRankDetail.Value && !keys.Exists(k => k.Equals("rankdetail", StringComparison.InvariantCultureIgnoreCase)))
{
keys.Add("RankDetail");
resultItem["RankDetail"] = string.Empty;
}
foreach (string key in keys)
{
var val = resultItem[key];
DockPanel propdp = new DockPanel();
if (string.Equals("Path", key, StringComparison.InvariantCultureIgnoreCase) && !string.IsNullOrWhiteSpace(val))
{
val = val.Replace('\\', '/');
TextBox textBox = new TextBox
{
IsReadOnly = true,
IsReadOnlyCaretVisible = false,
Text = String.Format("{0}: ", key),
BorderBrush = null,
BorderThickness = new Thickness(0),
Foreground = Brushes.DarkGreen,
FontWeight = FontWeights.Bold,
FontSize = 14
};
propdp.Children.Add(textBox);
Hyperlink hyperlink = new Hyperlink
{
NavigateUri = new Uri(val),
};
hyperlink.RequestNavigate += HyperlinkOnRequestNavigate;
hyperlink.Inlines.Add(new Run(val));
TextBlock tb = new TextBlock();
tb.Inlines.Add(hyperlink);
propdp.Children.Add(tb);
}
else if (key.Equals("RankDetail", StringComparison.InvariantCultureIgnoreCase)
/* &&!string.IsNullOrWhiteSpace(val)*/)
{
string langKey =
resultItem.Keys.FirstOrDefault(
k => k.Equals("language", StringComparison.InvariantCultureIgnoreCase));
string titleKey =
resultItem.Keys.FirstOrDefault(
k => k.Equals("title", StringComparison.InvariantCultureIgnoreCase));
Helpers.RankDetail.ResultItem item = new Helpers.RankDetail.ResultItem
{
Xml = val,
Title = resultItem[langKey],
Path = path,
Language = resultItem[titleKey],
};
string workIdKey =
resultItem.Keys.FirstOrDefault(
k => k.Equals("WorkId", StringComparison.InvariantCultureIgnoreCase) || k.Equals("DocId", StringComparison.InvariantCultureIgnoreCase));
if (!string.IsNullOrWhiteSpace(workIdKey))
{
item.WorkId = resultItem[workIdKey];
}
if (string.IsNullOrWhiteSpace(workIdKey) && string.IsNullOrWhiteSpace(val))
{
MessageBox.Show(
"You must include the managed properties 'WorkId' or 'DocId' in the select properties to get rank details when more than 100 results are matched",
"Property WorkId missing", MessageBoxButton.OK);
return;
}
var tb = new TextBox
{
IsReadOnly = true,
IsReadOnlyCaretVisible = true,
Text = "Show rank details...",
BorderBrush = null,
BorderThickness = new Thickness(0),
Foreground = Brushes.DodgerBlue,
FontSize = 14,
TextDecorations = TextDecorations.Underline,
Cursor = Cursors.Hand,
Background = Brushes.Transparent,
DataContext = item
};
tb.PreviewMouseLeftButtonUp += rankDetail_MouseLeftButtonUp;
propdp.Children.Add(tb);
}
else
{
TextBox textBox = new TextBox
{
IsReadOnly = true,
IsReadOnlyCaretVisible = false,
Text = String.Format("{0}: ", key),
BorderBrush = null,
BorderThickness = new Thickness(0),
Foreground = Brushes.DarkGreen,
FontWeight = FontWeights.Bold,
FontSize = 14
};
propdp.Children.Add(textBox);
string formatedVal = val;
if (key.Equals("Edges", StringComparison.InvariantCultureIgnoreCase))
formatedVal = JsonHelper.FormatJson(val);
propdp.Children.Add
(
new TextBox
{
IsReadOnly = true,
IsReadOnlyCaretVisible = true,
Text = formatedVal,
BorderBrush = null,
BorderThickness = new Thickness(0),
Foreground = Brushes.Green,
FontSize = 14
}
);
}
spProps.Children.Add(propdp);
}
//add everything to the item
propsExpander.Content = spProps;
spEntry.Children.Add(propsExpander);
spTop.Children.Add(spEntry);
//if there is an OWA Server and the Property ServerRedirectedEmbedURL is set, then add an inline Browser Control to show the preview
if (_enableExperimentalFeatures && resultItem.ContainsKey("ServerRedirectedEmbedURL"))
{
string embedUrl = resultItem["ServerRedirectedEmbedURL"];
if (!string.IsNullOrEmpty(embedUrl))
{
//add a preview control
Expander previewExpander = new Expander { IsExpanded = false, Header = "Preview" };
StackPanel previewPanel = new StackPanel();
WebBrowser browser = new WebBrowser();
browser.Height = 400;
previewExpander.Content = previewPanel;
previewExpander.Expanded += (sender, args) =>
{
if (browser.Source == null) //only load the first time
{
browser.Navigate(new Uri(embedUrl));
}
};
previewPanel.Children.Add(browser);
spEntry.Children.Add(previewExpander);
}
}
if (_enableExperimentalFeatures && resultItem.ContainsKey("FileType"))
//add a preview for html content
{
string fileType = resultItem["FileType"];
if (fileType.Equals("html"))
{
//add a preview control
Expander previewExpander = new Expander { IsExpanded = false, Header = "Preview" };
StackPanel previewPanel = new StackPanel();
WebBrowser browser = new WebBrowser();
browser.Height = 400;
previewExpander.Content = previewPanel;
previewExpander.Expanded += (sender, args) =>
{
if (browser.Source == null) //only load the first time
{
browser.Navigate(new Uri(resultItem["Path"]));
browser.Navigated += delegate
{
HTMLDocument htmlDocument = ((HTMLDocument)browser.Document);
IHTMLStyleSheet styleSheet = htmlDocument.createStyleSheet("", 0);
styleSheet.cssText = "body {zoom: 80% }";
};
}
};
previewPanel.Children.Add(browser);
spEntry.Children.Add(previewExpander);
}
}
//add an link to view all properties according to this article: http://blogs.technet.com/b/searchguys/archive/2013/12/11/how-to-all-managed-properties-of-a-document.aspx
AddViewAllPropertiesLink(resultItem, spProps);
counter++;
}
sv.Content = spTop;
}
else
{
TextBox tb = new TextBox
{
BorderBrush = null,
BorderThickness = new Thickness(0),
IsReadOnly = true,
IsReadOnlyCaretVisible = false,
Text = "The query returned zero items!",
Margin = new Thickness(30)
};
sv.Content = tb;
}
PrimaryResultsTabItem.Content = sv;
}
private string CustomizeTitle(string userFormat, ResultItem resultItem, int counter)
{
var customizedTitle = userFormat;
foreach (KeyValuePair<string, string> item in resultItem)
{
var oldValue = "{" + $"{item.Key}" + "}";
var newValue = resultItem[item.Key] + "";
customizedTitle = Regex.Replace(customizedTitle, oldValue, newValue, RegexOptions.IgnoreCase);
}
customizedTitle = customizedTitle.Replace("{counter}", $"{counter}");
return customizedTitle;
}
/// <summary>
/// Open the path to the item in a browser
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void HyperlinkOnRequestNavigate(object sender, RequestNavigateEventArgs e)
{
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
e.Handled = true;
}
private void AddViewAllPropertiesLink(ResultItem resultItem, StackPanel spEntry)
{
DockPanel propdp = new DockPanel();
var tb = new TextBox
{
IsReadOnly = true,
IsReadOnlyCaretVisible = false,
Text = "Managed properties ",
BorderBrush = null,
BorderThickness = new Thickness(0),
Foreground = Brushes.DodgerBlue,
FontSize = 14,
FontWeight = FontWeights.Bold,
TextDecorations = TextDecorations.Underline,
Cursor = Cursors.Hand,
};
tb.PreviewMouseLeftButtonUp += (sender, e) => OpenPreviewAllProperties(sender, e, resultItem, PropertyType.Managed);
propdp.Children.Add(tb);
var tb2 = new TextBox
{
IsReadOnly = true,
IsReadOnlyCaretVisible = false,
Text = "Crawled property names",
BorderBrush = null,
BorderThickness = new Thickness(0),
Foreground = Brushes.DodgerBlue,
FontSize = 14,
FontWeight = FontWeights.Bold,
TextDecorations = TextDecorations.Underline,
Cursor = Cursors.Hand,
};
tb2.PreviewMouseLeftButtonUp += (sender, e) => OpenPreviewAllProperties(sender, e, resultItem, PropertyType.Crawled);
propdp.Children.Add(tb2);
spEntry.Children.Add(propdp);
}
private void OpenPreviewAllProperties(object sender, MouseButtonEventArgs e, ResultItem resultItem, PropertyType propertyType)
{
//Todo this method neeeds some refactor love
MarkRequestOperation(false, "Running");
//Query a new search with refiner: "ManagedProperties(filter=5000/0/*) and the path of the selected item
SearchQueryRequest sqr = new SearchQueryRequest();
sqr.AcceptType = _searchQueryRequest.AcceptType;
sqr.AuthenticationType = _searchQueryRequest.AuthenticationType;
sqr.ClientType = _searchQueryRequest.ClientType;
sqr.Culture = _searchQueryRequest.Culture;
sqr.EnableFql = _searchQueryRequest.EnableFql;
sqr.EnableNicknames = _searchQueryRequest.EnableFql;
sqr.EnablePhonetic = _searchQueryRequest.EnablePhonetic;
sqr.EnableQueryRules = _searchQueryRequest.EnableQueryRules;
sqr.EnableStemming = _searchQueryRequest.EnableStemming;
if (_searchQueryRequest.SourceId != null)
{
sqr.SourceId = _searchQueryRequest.SourceId;
}
//try get the search result with the workId of the current hit, see: http://techmikael.blogspot.no/2014/10/look-up-item-based-on-items-id.html
string workIdKey =
resultItem.Keys.FirstOrDefault(k => k.Equals("WorkId", StringComparison.InvariantCultureIgnoreCase) || k.Equals("DocId", StringComparison.InvariantCultureIgnoreCase));
if (workIdKey == null)
{
MessageBox.Show(
"You must include the managed properties 'WorkId/DocId' in the select properties to get all properties",
"Property WorkId missing", MessageBoxButton.OK);
return;
}
sqr.QueryText = string.Format("WorkId:\"{0}\"", resultItem[workIdKey]);
sqr.ResultsUrl = _searchQueryRequest.ResultsUrl;
sqr.SharePointSiteUrl = _searchQueryRequest.SharePointSiteUrl;
sqr.Cookies = _searchQueryRequest.Cookies;
sqr.Token = _searchQueryRequest.Token;
sqr.UserName = _searchQueryRequest.UserName;
sqr.Password = _searchQueryRequest.Password;
sqr.SecurePassword = _searchQueryRequest.SecurePassword;
if (propertyType == PropertyType.Managed)
{
//this is the magic ingredient to get all the properties back
sqr.Refiners = "ManagedProperties(filter=5000/0/*)";
}
else
{
sqr.Refiners = "CrawledProperties(filter=5000/0/*)";
}
try
{
var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
var tokenSource = new CancellationTokenSource();
CancellationToken ct = tokenSource.Token;
Task.Factory.StartNew(() => HttpRequestRunner.RunWebRequest(sqr), ct,
TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent, scheduler).ContinueWith(
task =>
{
HttpRequestResponsePair result = task.Result;
SearchQueryResult resultItem2 = GetResultItem(result);
//Extract all Properties from refiner result
if (resultItem2.PrimaryQueryResult == null ||
resultItem2.PrimaryQueryResult.RefinerResults == null)
{
MessageBox.Show(
"The ManagedProperties property does not contain values. See https://github.com/wobba/SPO-Trigger-Reindex for more information on how to enable this feature.",
"ManagedProperties is empty", MessageBoxButton.OK);
return;
}
if (propertyType == PropertyType.Crawled)
{
RefinerResult crawledPropertyNames = resultItem2.PrimaryQueryResult.RefinerResults[0];
ResultItem cpResult = new ResultItem();
var cpGroupMapper = new Dictionary<string, string>
{
{ "00020329-0000-0000-C000-000000000046", "SharePoint" },
{ "00130329-0000-0130-c000-000000131346", "SharePoint" },
{ "00140329-0000-0140-c000-000000141446", "SharePoint" },
{ "0b63e343-9ccc-11d0-bcdb-00805fccce04", "Basic" },
{ "158d7563-aeff-4dbf-bf16-4a1445f0366c","SharePoint" },
{ "49691c90-7e17-101a-a91c-08002b2ecda9", "Basic" },
{ "B725F130-47EF-101A-A5F1-02608C9EEBAC","Basic" },
{ "012357bd-1113-171d-1f25-292bb0b0b0b0", "Internal" },
{ "ED280121-B677-4E2A-8FBC-0D9E2325B0A2", "SharePoint" },
{ "F29F85E0-4FF9-1068-AB91-08002B27B3D9","Office" },
{ "64ae120f-487d-445a-8d5a-5258f99cb970","Document Parser" },
{ "e835446c-937b-4492-95f3-d89988b01039","MetadataExtractor" }
};
foreach (var item in crawledPropertyNames)
{
foreach (var map in cpGroupMapper)
{
if (Regex.IsMatch(item.Name, map.Key + ":", RegexOptions.IgnoreCase))
{
item.Name = Regex.Replace(item.Name, map.Key + ":", "", RegexOptions.IgnoreCase);
while (cpResult.ContainsKey(item.Name))
{
item.Name += " ";
}
cpResult.Add(item.Name, map.Value + ":" + map.Key);
}
}
}
PropertiesDetail pd = new PropertiesDetail(cpResult, sqr.QueryText);
pd.Show();
}
else
{
var refiners = resultItem2.PrimaryQueryResult.RefinerResults[0];
//Query again with the select properties set
sqr.Refiners = "";
sqr.SelectProperties = String.Join(",", refiners.Select(x => x.Name).ToArray());
sqr.SelectProperties = string.Join(",",
sqr.SelectProperties.Split(',').Except(new[]
{"ClassificationLastScan", "ClassificationConfidence", "ClassificationCount", "ClassificationContext"}));
sqr.HttpMethodType = HttpMethodType.Post;
Task.Factory.StartNew(() => HttpRequestRunner.RunWebRequest(sqr), ct,
TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent, scheduler)
.ContinueWith(
innerTask =>
{
HttpRequestResponsePair innerResult = innerTask.Result;
SearchQueryResult innerResult2 = GetResultItem(innerResult);
if (innerResult2.PrimaryQueryResult == null)
{
MessageBox.Show("Could not load properties for the item");
}
else
{
//Open the new window and show the properties there
ResultItem relevantResult = innerResult2.PrimaryQueryResult.RelevantResults[0];
PropertiesDetail pd = new PropertiesDetail(relevantResult, sqr.QueryText);
pd.Show();
}
}).ContinueWith(innerTask =>
{
if (innerTask.Exception != null)
{
ShowError(task.Exception);
}
}, scheduler);
}
}, scheduler).ContinueWith(task =>
{
if (task.Exception != null)
{
ShowError(task.Exception);
}
MarkRequestOperation(false, "Done");
}, scheduler);
}
catch (Exception ex)
{
ShowError(ex);
}
finally
{
MarkRequestOperation(false, "Done");
}
}
private void rankDetail_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
TextBox tb = (TextBox)sender;
Helpers.RankDetail.ResultItem item = (Helpers.RankDetail.ResultItem)tb.DataContext;
if (string.IsNullOrWhiteSpace(item.Xml))
{
// We have more than 100 results and have to request more
//Todo this method neeeds some refactor love
MarkRequestOperation(false, "Running");
SearchQueryRequest sqr = new SearchQueryRequest
{
AcceptType = _searchQueryRequest.AcceptType,
AuthenticationType = _searchQueryRequest.AuthenticationType,
ClientType = _searchQueryRequest.ClientType,
Culture = _searchQueryRequest.Culture,
EnableFql = _searchQueryRequest.EnableFql,
EnableNicknames = _searchQueryRequest.EnableFql,
EnablePhonetic = _searchQueryRequest.EnablePhonetic,
EnableQueryRules = _searchQueryRequest.EnableQueryRules,
EnableStemming = _searchQueryRequest.EnableStemming,
RankingModelId = _searchQueryRequest.RankingModelId,
RowLimit = 1,
IncludeRankDetail = true,
QueryText = _searchQueryRequest.QueryText,
QueryTemplate = _searchQueryRequest.QueryTemplate,
ResultsUrl = _searchQueryRequest.ResultsUrl,
SharePointSiteUrl = _searchQueryRequest.SharePointSiteUrl,
Cookies = _searchQueryRequest.Cookies,
UserName = _searchQueryRequest.UserName,
Password = _searchQueryRequest.Password,
SecurePassword = _searchQueryRequest.SecurePassword,
Token = _searchQueryRequest.Token
};
if (!string.IsNullOrWhiteSpace(_searchQueryRequest.RefinementFilters))
{
sqr.RefinementFilters = _searchQueryRequest.RefinementFilters + ",";
}
sqr.RefinementFilters += "WorkId:" + item.WorkId;
try
{
var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
CancellationToken ct = new CancellationToken();
Task.Factory.StartNew(() => HttpRequestRunner.RunWebRequest(sqr), ct,
TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent, scheduler).ContinueWith(
task =>
{
var result = task.Result;
SearchQueryResult searchResult = GetResultItem(result);
if (searchResult.PrimaryQueryResult != null &&
searchResult.PrimaryQueryResult.RelevantResults != null &&
searchResult.PrimaryQueryResult.TotalRows > 0)
{
ResultItem resultItem = searchResult.PrimaryQueryResult.RelevantResults.First();
var rdKey = resultItem.Keys.SingleOrDefault(k => k.ToLower() == "rankdetail");
if (rdKey != null)
{
item.Xml = resultItem[rdKey];
}
RankDetail rd = new RankDetail();
rd.DataContext = item;
rd.Show();
}
}, scheduler).ContinueWith(task =>
{
if (task.Exception != null)
{
ShowError(task.Exception);
}
MarkRequestOperation(false, "Done");
}, scheduler);
}
catch (Exception ex)
{
ShowError(ex);
}
finally
{
MarkRequestOperation(false, "Done");
}
}
else
{
RankDetail rd = new RankDetail();
rd.DataContext = tb.DataContext;
rd.Show();
}
}
/// <summary>
/// Creates and populates the the Refinement results tab from data from the passed in <paramref name="searchResult" />.
/// This method is used for only query results.
/// </summary>
/// <param name="searchResult">The search result.</param>
private void SetRefinementResultItems(SearchQueryResult searchResult)
{
ScrollViewer sv = new ScrollViewer();
sv.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
sv.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
if (searchResult.PrimaryQueryResult != null && searchResult.PrimaryQueryResult.RefinerResults != null
&& searchResult.PrimaryQueryResult.RefinerResults.Count > 0)
{
StackPanel spTop = new StackPanel { Orientation = Orientation.Vertical };
int counter = 1;
foreach (var refinerItem in searchResult.PrimaryQueryResult.RefinerResults)
{
StackPanel spEntry = new StackPanel { Margin = new Thickness(25) };
TextBox titleTB = new TextBox
{
IsReadOnly = true,
IsReadOnlyCaretVisible = false,
Text = String.Format("{0}. {1}", counter, refinerItem.Name),
BorderBrush = null,
BorderThickness = new Thickness(0),
Foreground = Brushes.DarkBlue,
FontSize = 18
};
spEntry.Children.Add(titleTB);
Expander propsExpander = new Expander { IsExpanded = false, Header = "View Entries" };
StackPanel spProps = new StackPanel();
foreach (var re in refinerItem)
{
DockPanel propdp = new DockPanel();
propdp.Children.Add
(
new TextBox
{
IsReadOnly = true,
IsReadOnlyCaretVisible = false,
Text = "Refinement Name:",
BorderBrush = null,
BorderThickness = new Thickness(0),
Foreground = Brushes.DarkGreen,
FontWeight = FontWeights.Normal,
FontSize = 12
}
);
propdp.Children.Add
(
new TextBox
{
IsReadOnly = true,
IsReadOnlyCaretVisible = false,
Text = String.Format("{0}", re.Name.Replace("\n", " ")),
BorderBrush = null,
BorderThickness = new Thickness(0),
Foreground = Brushes.DarkMagenta,
FontWeight = FontWeights.Normal,
FontSize = 12
}
);
spProps.Children.Add(propdp);
propdp = new DockPanel();
propdp.Children.Add
(
new TextBox
{
IsReadOnly = true,
IsReadOnlyCaretVisible = false,
Text = "Refinement Count:",
BorderBrush = null,
BorderThickness = new Thickness(0),
Foreground = Brushes.DarkGreen,
FontWeight = FontWeights.Normal,
FontSize = 12
}
);
propdp.Children.Add
(
new TextBox
{
IsReadOnly = true,
IsReadOnlyCaretVisible = false,
Text = String.Format("{0}", re.Count),
BorderBrush = null,
BorderThickness = new Thickness(0),
Foreground = Brushes.DarkMagenta,
FontWeight = FontWeights.Normal,
FontSize = 12
}
);
spProps.Children.Add(propdp);
propdp = new DockPanel();
propdp.Children.Add
(
new TextBox
{
IsReadOnly = true,
IsReadOnlyCaretVisible = false,
Text = "Refinement Token:",
BorderBrush = null,
BorderThickness = new Thickness(0),
Foreground = Brushes.DarkGreen,
FontWeight = FontWeights.Normal,
FontSize = 12
}
);
propdp.Children.Add
(
new TextBox
{
IsReadOnly = true,
IsReadOnlyCaretVisible = false,
Text = String.Format("{0}", re.Token.Replace("\n", " ")),
BorderBrush = null,
BorderThickness = new Thickness(0),
Foreground = Brushes.DarkMagenta,
FontWeight = FontWeights.Normal,
FontSize = 12
}
);
spProps.Children.Add(propdp);
propdp = new DockPanel();
propdp.Children.Add
(
new TextBox
{
IsReadOnly = true,
IsReadOnlyCaretVisible = false,
Text = "Refinement Value:",
BorderBrush = null,
BorderThickness = new Thickness(0),
Foreground = Brushes.DarkGreen,
FontWeight = FontWeights.Normal,
FontSize = 12
}
);
propdp.Children.Add
(
new TextBox
{
IsReadOnly = true,
IsReadOnlyCaretVisible = false,
Text = String.Format("{0}", re.Value.Replace("\n", " ")),
BorderBrush = null,
BorderThickness = new Thickness(0),
Foreground = Brushes.DarkMagenta,
FontWeight = FontWeights.Normal,
FontSize = 12
}
);
spProps.Children.Add(propdp);
spProps.Children.Add(new Line { Height = 18 });
}
propsExpander.Content = spProps;
spEntry.Children.Add(propsExpander);
spTop.Children.Add(spEntry);
counter++;
}
sv.Content = spTop;
}
RefinementResultsTabItem.Content = sv;
}
/// <summary>
/// Creates and populates the the Secondary results tab from data from the passed in <paramref name="searchResult" />.
/// This method is used for only query results.
/// </summary>
/// <param name="searchResult">The search result.</param>
private void SetSecondaryQueryResultItems(SearchQueryResult searchResult)
{
ScrollViewer sv = new ScrollViewer();
sv.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
sv.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
if (searchResult.SecondaryQueryResults != null && searchResult.SecondaryQueryResults.Count > 0)
{
StackPanel spTop = new StackPanel { Orientation = Orientation.Vertical };
int counter = 1;
foreach (var sqr in searchResult.SecondaryQueryResults)
{
if (sqr.RelevantResults == null || sqr.RelevantResults.Count == 0)
continue;
foreach (var resultItem in sqr.RelevantResults)
{
StackPanel spEntry = new StackPanel { Margin = new Thickness(25) };
string resultTitle;
if (resultItem.ContainsKey("Title"))
resultTitle = resultItem["Title"];
else if (resultItem.ContainsKey("title"))
resultTitle = resultItem["title"];
else if (resultItem.ContainsKey("DocId"))
resultTitle = String.Format("DocId: {0}", resultItem["DocId"]);
else
resultTitle = "";
TextBox titleTB = new TextBox
{
IsReadOnly = true,
IsReadOnlyCaretVisible = false,
Text = String.Format("{0}. {1}", counter, resultTitle),
BorderBrush = null,
BorderThickness = new Thickness(0),
Foreground = Brushes.DarkBlue,
FontSize = 14
};
spEntry.Children.Add(titleTB);
Expander propsExpander = new Expander
{
IsExpanded = searchResult.SecondaryQueryResults.Count == 1,
Header = "View"
};
StackPanel spProps = new StackPanel();
foreach (var kv in resultItem)
{
DockPanel propdp = new DockPanel();
propdp.Children.Add
(
new TextBox
{
IsReadOnly = true,
IsReadOnlyCaretVisible = false,
Text = String.Format("{0}: ", kv.Key),
BorderBrush = null,
BorderThickness = new Thickness(0),
Foreground = Brushes.DarkGreen,
FontWeight = FontWeights.Bold,
FontSize = 14
}
);
propdp.Children.Add
(
new TextBox
{
IsReadOnly = true,
IsReadOnlyCaretVisible = true,
Text = String.Format("{0}", kv.Value),
BorderBrush = null,
BorderThickness = new Thickness(0),
Foreground = Brushes.Green,
FontSize = 14
}
);
spProps.Children.Add(propdp);
}
propsExpander.Content = spProps;
spEntry.Children.Add(propsExpander);
spTop.Children.Add(spEntry);
counter++;
}
}
sv.Content = spTop;
}
SecondaryResultsTabItem.Content = sv;
}
/// <summary>
/// Creates and populates the the Suggestion results tab from data from the passed in <paramref name="searchResult" />.
/// This method is used for only suggestion results.
/// </summary>
/// <param name="searchResult">The search result.</param>
private void SetSuggestionsResultItems(SearchSuggestionsResult searchResult)
{
ScrollViewer sv = new ScrollViewer();
sv.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
sv.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
if (searchResult.SuggestionResults != null && searchResult.SuggestionResults.Count > 0)
{
StackPanel spTop = new StackPanel { Orientation = Orientation.Vertical };
int counter = 1;
foreach (var resultITem in searchResult.SuggestionResults)
{
StackPanel spEntry = new StackPanel { Margin = new Thickness(25) };
TextBox queryTB = new TextBox
{
IsReadOnly = true,
IsReadOnlyCaretVisible = false,
Text = String.Format("{0}. {1}", counter, resultITem.Query),
BorderBrush = null,
BorderThickness = new Thickness(0),
Foreground = Brushes.DarkBlue,
FontSize = 14
};
spEntry.Children.Add(queryTB);
TextBox isPersonalTB = new TextBox
{
IsReadOnly = true,
IsReadOnlyCaretVisible = false,
Text = String.Format("IsPersonal: {0}", resultITem.IsPersonal),
BorderBrush = null,
BorderThickness = new Thickness(0),
Foreground = Brushes.Chocolate,
FontSize = 14
};
spEntry.Children.Add(isPersonalTB);
spTop.Children.Add(spEntry);
counter++;
}
sv.Content = spTop;
}
else
{
TextBox tb = new TextBox
{
BorderBrush = null,
BorderThickness = new Thickness(0),
IsReadOnly = true,
IsReadOnlyCaretVisible = false,
Text = "The query returned no items!",
Margin = new Thickness(30)
};
sv.Content = tb;
}
SuggestionResultsTabItem.Content = sv;
}
/// <summary>
/// Updates the request URI string text block.
/// </summary>
private void UpdateRequestUriStringTextBlock()
{
try
{
if (SharePointSiteUrlTextBox != null)
{
_searchQueryRequest.SharePointSiteUrl = SharePointSiteUrlTextBox.Text.Trim();
_searchSuggestionsRequest.SharePointSiteUrl = SharePointSiteUrlTextBox.Text.Trim();
}
var searchMethodType = CurrentSearchMethodType;
var httpMethodType = CurrentHttpMethodType;
if (searchMethodType == SearchMethodType.Query)
{
if (httpMethodType == HttpMethodType.Get)
{
var uri = _searchQueryRequest.GenerateHttpGetUri().ToString();
if (RequestUriLengthTextBox != null)
{
RequestUriLengthTextBox.Text = $"HTTP GET {uri.Length.ToString()}";
}
RequestUriStringTextBox.Text = uri;
}
else if (httpMethodType == HttpMethodType.Post)
{
var uri = _searchQueryRequest.GenerateHttpGetUri().ToString();
if (RequestUriLengthTextBox != null)
{
RequestUriLengthTextBox.Text = $"HTTP POST {uri.Length.ToString()}";
}
RequestUriStringTextBox.Text = _searchQueryRequest.GenerateHttpPostUri().ToString();
}
}
else if (searchMethodType == SearchMethodType.Suggest)
{
RequestUriStringTextBox.Text = _searchSuggestionsRequest.GenerateHttpGetUri().ToString();
}
}
catch (Exception ex)
{
ShowError(ex);
}
RequestUriStringTextBox.Visibility = Visibility.Visible;
}
/// <summary>
/// Marks the request operation by disabling or enabling controls.
/// </summary>
/// <param name="starting">if set to <c>true</c> [starting] all ResultTabs are cleared.</param>
/// <param name="status">The status.</param>
private void MarkRequestOperation(bool starting, string status)
{
this.Dispatcher.Invoke(() =>
{
RunButton.IsEnabled = !starting;
if (starting)
{
ClearResultTabs();
QueryGroupBox.IsEnabled = false;
ConnectionExpanderBox.IsEnabled = false;
}
else
{
QueryGroupBox.IsEnabled = true;
ConnectionExpanderBox.IsEnabled = true;
}
ProgressBar.Visibility = starting ? Visibility.Visible : Visibility.Hidden;
Duration duration = new Duration(TimeSpan.FromSeconds(30));
DoubleAnimation doubleanimation = new DoubleAnimation(100.0, duration);
if (starting)
ProgressBar.BeginAnimation(RangeBase.ValueProperty, doubleanimation);
else
ProgressBar.BeginAnimation(RangeBase.ValueProperty, null);
StateBarTextBlock.Text = status;
});
}
/// <summary>
/// Clears the result tabs.
/// </summary>
private void ClearResultTabs()
{
this.Dispatcher.Invoke(() =>
{
StatsResultTabItem.Content = null;
RawResultTabItem.Content = null;
PrimaryResultsTabItem.Content = null;
RefinementResultsTabItem.Content = null;
SecondaryResultsTabItem.Content = null;
SuggestionResultsTabItem.Content = null;
});
}
/// <summary>
/// Shows the error.
/// </summary>
/// <param name="error">The error.</param>
private void ShowError(Exception error)
{
ClearResultTabs();
ScrollViewer sv = new ScrollViewer();
sv.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
sv.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
TextBox tb = new TextBox();
tb.BorderBrush = null;
tb.IsReadOnly = true;
tb.TextWrapping = TextWrapping.Wrap;
tb.IsReadOnlyCaretVisible = false;
if (error != null)
{
tb.AppendText(error.Message + Environment.NewLine + Environment.NewLine);
}
if (error != null)
{
Exception inner = error.InnerException;
while (inner != null)
{
tb.AppendText(inner.Message + Environment.NewLine + Environment.NewLine);
inner = inner.InnerException;
}
}
sv.Content = tb;
StatsResultTabItem.Content = sv;
}
private void ShowMsgBox(string message)
{
MessageBox.Show(message);
}
/// <summary>
/// Sets the impersonation level selections.
/// </summary>
private void SetCurrentWindowsUserIdentity()
{
WindowsIdentity currentWindowsIdentity = WindowsIdentity.GetCurrent();
if (currentWindowsIdentity != null)
{
if (AuthenticationUsernameTextBox != null
&& string.IsNullOrWhiteSpace(AuthenticationUsernameTextBox.Text))
AuthenticationUsernameTextBox.Text = currentWindowsIdentity.Name;
}
}
/// <summary>
/// Adds the copy command.
/// </summary>
/// <param name="control">The control.</param>
private void AddCopyCommand(Control control)
{
ContextMenu cm = new ContextMenu();
control.ContextMenu = cm;
MenuItem mi = new MenuItem();
mi.Command = ApplicationCommands.Copy;
mi.CommandTarget = control;
mi.Header = ApplicationCommands.Copy.Text;
cm.Items.Add(mi);
CommandBinding copyCmdBinding = new CommandBinding();
copyCmdBinding.Command = ApplicationCommands.Copy;
copyCmdBinding.Executed += CopyCmdBinding_Executed;
copyCmdBinding.CanExecute += CopyCmdBinding_CanExecute;
control.CommandBindings.Add(copyCmdBinding);
}
/// <summary>
/// Handles the Executed event of the CopyCmdBinding control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="ExecutedRoutedEventArgs" /> instance containing the event data.</param>
private void CopyCmdBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
// Set text to clip board
if (sender is TreeViewItem)
{
Clipboard.SetText((string)(sender as TreeViewItem).Header);
}
}
/// <summary>
/// Handles the CanExecute event of the CopyCmdBinding control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="CanExecuteRoutedEventArgs" /> instance containing the event data.</param>
private void CopyCmdBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
//Check for text
if (sender is TreeViewItem)
{
TreeViewItem tvi = sender as TreeViewItem;
if (tvi.Header != null)
{
e.CanExecute = true;
}
else
{
e.CanExecute = false;
}
}
}
#endregion
private void ConnectToSignalR_OnClick(object sender, RoutedEventArgs e)
{
try
{
if (_hubConnection != null)
{
_hubConnection.Dispose();
}
_hubConnection = new HubConnection(SignalRHubUrlTextBox.Text);
_hub = _hubConnection.CreateHubProxy("UlsHub");
_hubConnection.StateChanged += change =>
{
if (change.NewState == ConnectionState.Disconnected)
{
Dispatcher.BeginInvoke(new Action(() =>
{
SignalRUrlImage.ToolTip = "Disconnected";
SignalRUrlImage.Source = new BitmapImage(new Uri("Images/alert_icon.png", UriKind.Relative));
SignalRUrlImage.Visibility = Visibility.Visible;
DebugTabItem.IsEnabled = false;
}));
}
else if (change.NewState == ConnectionState.Connected)
{
Dispatcher.BeginInvoke(new Action(() =>
{
SignalRUrlImage.ToolTip = "Connected";
SignalRUrlImage.Source =
new BitmapImage(new Uri("Images/connected_icon.png", UriKind.Relative));
SignalRUrlImage.Visibility = Visibility.Visible;
DebugTabItem.IsEnabled = true;
}));
}
else if (change.NewState == ConnectionState.Reconnecting)
{
Dispatcher.BeginInvoke(new Action(() =>
{
SignalRUrlImage.ToolTip = "Reconnecting";
SignalRUrlImage.Source =
new BitmapImage(new Uri("Images/reconnect_icon.png", UriKind.Relative));
SignalRUrlImage.Visibility = Visibility.Visible;
DebugTabItem.IsEnabled = false;
}));
}
};
_hub.On<LogEntry>("addSearchQuery", ProcessQueryLogEntry);
_hubConnection.Start().Wait();
}
catch (Exception ex)
{
ShowMsgBox("Could not connect to signalr hub: " + ex.Message);
}
}
public void LogMessageToFile(string msg)
{
StreamWriter sw = File.AppendText(
"c:\\log.txt");
try
{
string logLine = String.Format(
"{0}.", msg);
sw.WriteLine(logLine);
}
finally
{
sw.Close();
}
}
private void ProcessQueryLogEntry(LogEntry logEntry)
{
try
{
Regex firstQuery =
new Regex(
"^Microsoft.Office.Server.Search.Query.Ims.ImsQueryInternal : New request: Query text '(.*)', Query template '(.*)'; HiddenConstraints:(.*); SiteSubscriptionId: (.*)");
Regex personalResults =
new Regex(
"^Microsoft.Office.Server.Search.Query.Pipeline.Processing.QueryRouterEvaluator : QueryRouterEvaluator: Received (.*) PersonalFavoriteResults.*");
Regex relevantResults =
new Regex(
"^Microsoft.Office.Server.Search.Query.Pipeline.Processing.QueryRouterEvaluator : QueryRouterEvaluator: Received (.*) RelevantResults results.*");
Regex refinementResults =
new Regex(
"^Microsoft.Office.Server.Search.Query.Pipeline.Processing.QueryRouterEvaluator : QueryRouterEvaluator: Received (.*) RefinementResults.*");
Regex boundVariables = new Regex("^QueryClassifierEvaluator : (.*)$");
//TODO simplify this logic
//if (logEntry.Message.Contains("SharePoint"))
// LogMessageToFile(logEntry.Message);
if (firstQuery.IsMatch(logEntry.Message))
{
var query = firstQuery.Match(logEntry.Message).Groups[1].Value;
var queryTemplate = firstQuery.Match(logEntry.Message).Groups[2].Value;
var hiddenConstraints = firstQuery.Match(logEntry.Message).Groups[3].Value;
var siteSubscriptionId = firstQuery.Match(logEntry.Message).Groups[4].Value;
if (!string.IsNullOrEmpty(query))
{
SearchQueryDebug debug = new SearchQueryDebug(logEntry.Correlation, Dispatcher);
debug.Query = string.Format("{0}", query);
if (!string.IsNullOrEmpty(queryTemplate))
{
debug.Template = string.Format("{0}", queryTemplate);
}
if (!string.IsNullOrWhiteSpace(hiddenConstraints))
{
debug.HiddenConstraint = string.Format("{0}", hiddenConstraints);
}
if (!string.IsNullOrEmpty(siteSubscriptionId))
{
debug.SiteSubscriptionId = string.Format("{0}", siteSubscriptionId);
}
ObservableQueryCollection.Add(debug);
}
}
else
{
//locking?
SearchQueryDebug debug =
ObservableQueryCollection.FirstOrDefault(d => d.Correlation == logEntry.Correlation);
if (debug != null)
{
if (logEntry.Message.StartsWith("QueryTemplateHelper: "))
{
try
{
Monitor.Enter(_locker);
string queryTemplateHelper = logEntry.Message.Replace("QueryTemplateHelper: ", "");
debug.QueryTemplateHelper.Add(queryTemplateHelper);
}
finally
{
Monitor.Exit(_locker);
}
}
else if (logEntry.Category == "Linguistic Processing")
{
try
{
Monitor.Enter(_locker);
if (
logEntry.Message.StartsWith(
"Microsoft.Ceres.ContentEngine.NlpEvaluators.QuerySuggestionEvaluator"))
{
debug.QuerySuggestion =
logEntry.Message.Replace(
"Microsoft.Ceres.ContentEngine.NlpEvaluators.QuerySuggestionEvaluator: ", "");
}
else if (string.IsNullOrEmpty(debug.QueryExpanded1))
{
debug.QueryExpanded1 =
logEntry.Message.Replace(
"Microsoft.Ceres.ContentEngine.NlpEvaluators.Tokenizer.QueryWordBreakerProducer: ",
"");
}
else if (logEntry.Message.StartsWith("..."))
{
debug.QueryExpanded3 += logEntry.Message.TrimStart(new[] { '.' });
}
else if (string.IsNullOrEmpty(debug.QueryExpanded2))
{
debug.QueryExpanded2 =
logEntry.Message.Replace(
"Microsoft.Ceres.ContentEngine.NlpEvaluators.Tokenizer.QueryWordBreakerProducer: ",
"").TrimEnd(new[] { '.' });
}
}
finally
{
Monitor.Exit(_locker);
}
}
else if (boundVariables.IsMatch(logEntry.Message))
{
string value = boundVariables.Match(logEntry.Message).Groups[1].Value;
debug.BoundVariables.Add(value);
}
else if (relevantResults.IsMatch(logEntry.Message))
{
debug.RelevantResults = relevantResults.Match(logEntry.Message).Groups[1].Value;
}
else if (refinementResults.IsMatch(logEntry.Message))
{
debug.RefinerResults = refinementResults.Match(logEntry.Message).Groups[1].Value;
}
}
else if (ObservableQueryCollection.Any(q => logEntry.Message.Contains(q.Correlation)))
//child correlation, this can be a very expensive query...
{
if (
logEntry.Message.StartsWith(
"Microsoft.Office.Server.Search.Query.Pipeline.Processing.QueryRouterEvaluator : QueryRouterEvaluator: "))
{
debug =
ObservableQueryCollection.FirstOrDefault(
q => logEntry.Message.Contains(q.Correlation));
if (debug != null)
debug.PersonalResults = personalResults.Match(logEntry.Message).Groups[1].Value;
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
private void QueryDoubleClick(object sender, MouseButtonEventArgs e)
{
//QueryTextBox.Text = "";
}
private void FreshnessBoost_Click(object sender, RoutedEventArgs e)
{
FreshnessBoost fb = new FreshnessBoost();
fb.Show();
}
private void Options_Click(object sender, RoutedEventArgs e)
{
var options = new SearchPresentationSettings();
options.Show();
}
/// <summary>
/// Get a SearchConnection object based on the current alues of the relevant input boxes in the user interface.
/// </summary>
/// <returns>A SearchConnection object</returns>
internal SearchConnection GetSearchConnectionFromUi()
{
var connection = new SearchConnection
{
SpSiteUrl = SharePointSiteUrlTextBox.Text.Trim(),
Timeout = WebRequestTimeoutTextBox.Text.Trim(),
Accept = (AcceptJsonRadioButton.IsChecked == true ? "json" : "xml"),
HttpMethod = (HttpGetMethodRadioButton.IsChecked == true ? "GET" : "POST"),
Username = (AuthenticationUsernameTextBox.IsEnabled) ? AuthenticationUsernameTextBox.Text.Trim() : "",
AuthTypeIndex = AuthenticationTypeComboBox.SelectedIndex,
AuthMethodIndex = AuthenticationMethodComboBox.SelectedIndex,
EnableExperimentalFeatures = _enableExperimentalFeatures
};
return connection;
}
/// <summary>
/// Get a SearchQueryRequest object based on the current alues of the relevant input boxes in the user interface.
/// </summary>
/// <returns>A SearchConnection object</returns>
internal SearchQueryRequest GetSearchQueryRequestFromUi()
{
return _searchQueryRequest;
}
/// <summary>
/// Save current search query and connection settings to a new XML file. A file dialog asks end user for output path.
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">Parameters in the event</param>
private void SaveAsNewPresetButton_OnClick(object sender, RoutedEventArgs e)
{
try
{
var request = GetSearchQueryRequestFromUi();
var connection = GetSearchConnectionFromUi();
var annotation = AnnotatePresetTextBox.Text;
var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
var timeStamp = DateTime.Now;
var versionHistory = $"{timeStamp}: Created by {userName}";
var newAnnotation = $"{annotation}\r\n- {versionHistory}";
var preset = new SearchPreset()
{
Request = request,
Connection = connection,
Annotation = newAnnotation
};
// Bring up Save As dialog to save current settings as new preset to set the Path and Name (derived from path) for the preset
var dlg = new Microsoft.Win32.SaveFileDialog
{
FileName = "Example Preset Query Settings",
DefaultExt = ".xml",
InitialDirectory = Path.GetFullPath(PresetFolderPath),
Filter = "Xml files (.xml)|*.xml"
};
if (dlg.ShowDialog() == true)
{
preset.Path = dlg.FileName;
preset.Name = Path.GetFileNameWithoutExtension(preset.Path);
var r = preset.Save();
AnnotatePresetTextBox.Text = newAnnotation;
StateBarTextBlock.Text = String.Format("{0} new preset {1}", r ? "Saved" : "Failed to save", preset.Path);
// Reload saved files to populate combobox again
LoadSearchPresetsFromFolder(PresetFolderPath);
}
else
{
StateBarTextBlock.Text = String.Format("Failed to write XML preset");
}
}
catch (Exception ex)
{
StateBarTextBlock.Text = String.Format("Failed to write XML preset: {0}", ex.Message);
}
}
/// <summary>
/// Save an updated version of the currently selected settings.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SavePresetButton_OnClick(object sender, RoutedEventArgs e)
{
var selected = PresetComboBox.SelectedItem as SearchPreset;
if (selected != null)
{
var annotation = AnnotatePresetTextBox.Text;
var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
var timeStamp = DateTime.Now;
var versionHistory = $"{timeStamp}: Version saved by {userName}";
var newAnnotation = $"{annotation}\r\n- {versionHistory}";
var preset = new SearchPreset()
{
Request = GetSearchQueryRequestFromUi(),
Connection = GetSearchConnectionFromUi(),
PresentationSettings = SearchPresentationSettings,
Annotation = newAnnotation,
Path = selected.Path,
Name = Path.GetFileNameWithoutExtension(selected.Path)
};
var r = preset.Save();
AnnotatePresetTextBox.Text = newAnnotation;
StateBarTextBlock.Text = String.Format("{0} preset {1}", r ? "Saved" : "Failed to save", preset.Path);
}
}
/// <summary>
/// Load a preset from XML
/// </summary>
/// <param name="path">Path to XML file containing the deserialized preset.</param>
protected internal void LoadPreset(string path)
{
var serializer = new XmlSerializer(typeof(SearchPreset));
try
{
using (var reader = new StreamReader(path))
{
var searchPreset = serializer.Deserialize(reader) as SearchPreset;
if (searchPreset != null)
{
_searchQueryRequest = searchPreset.Request;
_searchConnection = searchPreset.Connection;
SearchPresentationSettings = searchPreset.PresentationSettings ?? new SearchResultPresentationSettings();
_presetAnnotation = searchPreset.Annotation;
InitializeControls();
StateBarTextBlock.Text = String.Format("Successfully read XML preset from {0}", path);
}
else
{
throw new Exception(String.Format("Failed to deserialize file: '{0}'", path));
}
}
}
catch (Exception ex)
{
StateBarTextBlock.Text = String.Format("Failed to read XML from {0}: {1}", path, ex.Message);
}
}
/// <summary>
/// Load search connection setting from file and return as an SearchConnection object.
/// </summary>
/// <returns></returns>
private SearchConnection LoadSearchConnection()
{
var connection = new SearchConnection();
try
{
var path = Path.Combine(Environment.CurrentDirectory, ConnectionPropsXmlFileName);
connection.Load(path);
}
catch (Exception ex)
{
ShowMsgBox("Failed to read connection properties. Error:" + ex.Message);
}
return connection;
}
private void UpdateSearchConnectionControls(SearchConnection connection)
{
if (connection == null)
{
return;
}
try
{
if (!string.IsNullOrEmpty(connection.SpSiteUrl)) { SharePointSiteUrlTextBox.Text = connection.SpSiteUrl; }
if (!string.IsNullOrEmpty(connection.Timeout)) { WebRequestTimeoutTextBox.Text = connection.Timeout; }
if (!string.IsNullOrEmpty(connection.Accept))
{
switch (connection.Accept.ToLower())
{
case "json":
AcceptJsonRadioButton.IsChecked = true;
break;
case "xml":
AcceptXmlRadioButton.IsChecked = true;
break;
}
}
if (!string.IsNullOrEmpty(connection.HttpMethod))
{
switch (connection.HttpMethod.ToLower())
{
case "get":
HttpGetMethodRadioButton.IsChecked = true;
break;
case "post":
HttpPostMethodRadioButton.IsChecked = true;
break;
}
}
AuthenticationTypeComboBox.SelectedIndex = connection.AuthTypeIndex;
AuthenticationMethodComboBox.SelectedIndex = connection.AuthMethodIndex;
if (!string.IsNullOrEmpty(connection.HttpMethod) && AuthenticationUsernameTextBox.IsEnabled)
{
AuthenticationUsernameTextBox.Text = connection.Username;
_searchQueryRequest.UserName = connection.Username;
_searchSuggestionsRequest.UserName = connection.Username;
}
ExperimentalFeaturesCheckBox.IsChecked = connection.EnableExperimentalFeatures;
}
catch (Exception ex)
{
ShowMsgBox("Failed to update connection properties. Error:" + ex.Message);
}
}
private void LoadSearchPresetsFromFolder(string presetFolderPath)
{
try
{
var presetFilter = PresetFilterTextBox.Text;
SearchPresets = new SearchPresetList(presetFolderPath);
PresetComboBox.ItemsSource = SearchPresets.Presets;
}
catch (Exception ex)
{
ShowMsgBox("Failed to read search presets. Error:" + ex.Message);
}
}
/// <summary>
/// Handle event when an entry in the preset combobox is selected.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PresetComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedPreset = (PresetComboBox.SelectedItem as SearchPreset);
// Load this preset and refresh user interface
if (selectedPreset != null)
{
LoadPreset(selectedPreset.Path);
}
}
private void CopyClipboardButton_OnClickButton_OnClick(object sender, RoutedEventArgs e)
{
if (_searchResults == null)
{
StateBarTextBlock.Text = "No search result to copy";
return;
}
string content;
if (AcceptJsonRadioButton.IsChecked.HasValue && AcceptJsonRadioButton.IsChecked.Value)
{
content = JsonHelper.FormatJson(_searchResults.ResponseContent);
content = Regex.Replace(content, "\r\n\\s+\r\n", "\r\n");
}
else
{
content = XmlHelper.PrintXml(_searchResults.ResponseContent);
}
Clipboard.SetText(content);
}
private void PresetComboBox_OnDropDownOpened(object sender, EventArgs e)
{
RefreshPresetList();
}
public void RefreshPresetList()
{
try
{
var filter = PresetFilterTextBox.Text;
var presets = SearchPresets.Presets.Where(p => p.Include(filter));
PresetComboBox.ItemsSource = presets;
}
catch (Exception ex)
{
ShowMsgBox("Failed to read search presets. Error:" + ex.Message);
}
}
private void BackButton_OnClick(object sender, RoutedEventArgs e)
{
History.BackButton_OnClick(sender, e);
}
private void ForwardButton_OnClick(object sender, RoutedEventArgs e)
{
History.ForwardButton_OnClick(sender, e);
}
private void AnnotatePreset_OnClick(object sender, RoutedEventArgs e)
{
AnnotatePresetTextBox.Visibility = AnnotatePresetTextBox.IsVisible ? Visibility.Collapsed : Visibility.Visible;
}
private void PresetFilterTextBox_OnLostFocus(object sender, RoutedEventArgs e)
{
RefreshPresetList();
PresetComboBox.IsDropDownOpen = true;
}
private void PresetFilterTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
RefreshPresetList();
PresetComboBox.IsDropDownOpen = true;
}
}
private void ClearHistory_Click(object sender, RoutedEventArgs e)
{
History.Clear_OnClick(sender, e);
History.PruneHistoryDir(HistoryFolderPath, 0);
ResetCheckboxesButton_Click(sender, e);
_searchQueryRequest = new SearchQueryRequest();
InitializeControls();
}
}
} | 44.244646 | 195 | 0.491426 | [
"MIT"
] | shijuraj/PnP-Tools | Solutions/SharePoint.Search.QueryTool/SearchQueryTool/MainWindow.xaml.cs | 146,673 | C# |
//
// Copyright (c) 2010-2018 Antmicro
// Copyright (c) 2011-2015 Realtime Embedded
//
// This file is licensed under the MIT License.
// Full license text is available in 'licenses/MIT.txt'.
//
using System;
using Antmicro.Renode.Core;
using Antmicro.Renode.Core.Structure;
using Antmicro.Renode.Logging;
using Antmicro.Renode.Peripherals.Bus;
using System.Collections.Generic;
using System.Linq;
namespace Antmicro.Renode.Peripherals.I2C
{
public sealed class XIIC : SimpleContainer<II2CPeripheral>, IDoubleWordPeripheral
{
public XIIC (Machine machine) : base(machine)
{
IRQ = new GPIO ();
Reset ();
}
public uint ReadDoubleWord (long offset)
{
switch ((Offset)offset) {
case Offset.ControlRegister:
return control;
case Offset.StatusRegister:
return status;
case Offset.I2CAddressRegister:
return slaveAddress;
case Offset.I2CDataRegister:
return ReceiveData ();
case Offset.InterruptStatusRegister:
return interruptStatus;
case Offset.TransferSizeRegister:
return transferSize;
case Offset.SlaveMonitorPauseRegister:
return slaveMonitorPause;
case Offset.TimeoutRegister:
return timeout;
case Offset.InterruptMaskRegister:
return interruptMask;
default:
this.LogUnhandledRead(offset);
return 0;
}
}
public void WriteDoubleWord (long offset, uint value)
{
switch ((Offset)offset) {
case Offset.ControlRegister:
control = value & 0xFF7F;
if ((control & (1 << (int)Control.ClearFifo)) > 0) {
fifo.Clear ();
transferSize = 0;
control &= ~((uint)1 << (int)Control.ClearFifo);
}
break;
case Offset.I2CAddressRegister:
slaveAddress = (byte)value;
status |= (1 << (int)Status.BusActive);
TransferData ();
break;
case Offset.StatusRegister:
// seems that Linux does write to status register
break;
case Offset.I2CDataRegister:
fifo.Enqueue ((byte)value);
transferSize = (uint)(fifo.Count - 1);
break;
case Offset.InterruptStatusRegister:
interruptStatus &= ~value;
Update ();
break;
case Offset.TransferSizeRegister:
transferSize = value & 0xFF;
break;
case Offset.SlaveMonitorPauseRegister:
slaveMonitorPause = value & 0x0F;
break;
case Offset.TimeoutRegister:
timeout = value & 0xFF;
break;
case Offset.InterruptEnableRegister:
interruptMask &= ~(value & 0x2FF);
Update ();
break;
case Offset.InterruptDisableRegister:
interruptMask |= (value & 0x2FF);
Update ();
break;
default:
throw new ArgumentOutOfRangeException ();
}
}
public GPIO IRQ { get; private set; }
public override void Reset ()
{
timeout = TimeoutRegisterReset;
interruptMask = InterruptMaskRegisterReset;
}
private uint ReceiveData ()
{
if (fifo.Count == 0) {
SetInterrupt (Interrupts.ReceiveTransmitUnderflow);
return 0;
}
var ret = fifo.Dequeue();
if(fifo.Count == 0)
{
status &= ~((uint)(1<< (int)Status.ReceiverDataValid));
}
return ret;
}
private void TransferData ()
{
II2CPeripheral device;
if (!TryGetByAddress(slaveAddress, out device)) {
SetInterrupt (Interrupts.NoACK);
return;
}
if ((control & (1 << (int)Control.Direction)) == 0) {
//write
var data = fifo.ToArray ();
this.DebugLog (
"Write {0} to {1} (0x{2:X})",
data.Select (x => x.ToString ()).Aggregate ((x,y) => x + " " + y),
device.GetType ().Name,
slaveAddress
);
fifo.Clear ();
device.Write (data);
SetInterrupt (Interrupts.TransferComplete);
status &= ~((uint)(1 << (int)Status.TransmitDataValid));
} else {
//read
var data = device.Read ();
foreach (var item in data) {
fifo.Enqueue (item);
}
this.DebugLog (
"Read from {0} (0x{1:X})",
device.GetType().Name,
slaveAddress,
data.Select (x => x.ToString ()).Aggregate ((x,y) => x + " " + y)
);
SetInterrupt (Interrupts.TransferComplete);
status |= (uint)(1 << (int)Status.ReceiverDataValid);
status &= ~(uint)(1 << (int)Status.BusActive);
}
}
private void Update ()
{
if ((interruptStatus & (~interruptMask)) > 0)
{
this.NoisyLog ("Irq set");
IRQ.Set ();
}
else
{
this.NoisyLog ("Irq unset");
IRQ.Unset ();
}
}
private void ClearInterrupt(params Interrupts[] interrupt)
{
foreach (var item in interrupt)
{
interruptStatus &= (uint)~(1<<(int)item);
}
Update ();
}
private void SetInterrupt(params Interrupts[] interrupt)
{
foreach (var item in interrupt)
{
interruptStatus |= (uint)(1 << (int)item);
}
Update ();
}
private uint timeout;
private uint interruptMask;
private uint interruptStatus;
private uint slaveMonitorPause;
private uint transferSize;
private byte slaveAddress;
private uint status;
private uint control;
private Queue<byte> fifo = new Queue<byte> ();
private const int TimeoutRegisterReset = 0x1F; // R_TIME_OUT_REG_RESET
private const int InterruptMaskRegisterReset = 0x2FF; // R_INTRPT_MASK_REG_RESET 0x2FF
private const int RegisterCount = (int)Offset.InterruptDisableRegister + 1; // R_MAX
private enum Status
{
RXReadWrite = 3,
ReceiverDataValid = 5,
TransmitDataValid = 6,
ReceiverOverflow = 7,
BusActive = 8
}
private enum Control
{
Direction = 0x0,
MasterSlave = 0x1,
AddressMode = 0x2,
AcknowledgeEnabled = 0x3,
Hold = 0x4,
SlaveMonitorMode = 0x5,
ClearFifo = 0x6
}
private enum Interrupts
{
TransferComplete = 0x0,
MoreData = 0x1,
NoACK = 0x2,
TransferTimeout = 0x3,
MonitoredSlaveReady = 0x4,
ReceiveOverflow = 0x5,
FifoTransmitOverflow = 0x6,
ReceiveTransmitUnderflow = 0x7,
ArbitrationLost = 0x9,
}
private enum Offset
{
ControlRegister = 0x0 , // R_CONTROL_REG
StatusRegister = 0x4 , // R_STATUS_REG
I2CAddressRegister = 0x8 , // R_I2C_ADDRESS_REG
I2CDataRegister = 0xC , // R_I2C_DATA_REG
InterruptStatusRegister = 0x10, // R_INTERRUPT_STATUS_REG
TransferSizeRegister = 0x14, // R_TRANSFER_SIZE_REG
SlaveMonitorPauseRegister = 0x18, // R_SLAVE_MON_PAUSE_REG
TimeoutRegister = 0x1C, // R_TIME_OUT_REG
InterruptMaskRegister = 0x20, // R_INTRPT_MASK_REG
InterruptEnableRegister = 0x24, // R_INTRPT_ENABLE_REG
InterruptDisableRegister = 0x28 // R_INTRPT_DISABLE_REG
}
}
}
| 32.742537 | 94 | 0.485926 | [
"MIT"
] | UPBIoT/renode-iot | src/Infrastructure/src/Emulator/Peripherals/Peripherals/I2C/XIIC.cs | 8,775 | C# |
using System;
using System.Collections.Generic;
using Advertise.DomainClasses.Entities.Users;
using Microsoft.AspNet.Identity.EntityFramework;
namespace Advertise.DomainClasses.Entities.Roles
{
/// <summary>
/// </summary>
public class Role : IdentityRole<Guid, UserRole>
{
#region NavigationProperties
/// <summary>
/// توضیحات دسته بندی
/// </summary>
public virtual ICollection<RoleAction> Actions { get; set; }
#endregion
#region Properties
/// <summary>
/// کد دسته بندی
/// </summary>
public virtual string Code { get; set; }
/// <summary>
/// </summary>
public virtual byte[] RowVersion { get; set; }
/// <summary>
/// </summary>
public virtual RoleType Type { get; set; }
/// <summary>
/// </summary>
public virtual bool IsSystemRole { get; set; }
#endregion
}
} | 23.238095 | 68 | 0.563525 | [
"Apache-2.0"
] | imangit/Advertise | Advertise/Advertise.DomainClasses/Entities/Roles/Role.cs | 1,003 | C# |
namespace ARMeilleure.Decoders
{
class OpCode32AluReg : OpCode32Alu, IOpCode32AluReg
{
public int Rm { get; }
public new static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new OpCode32AluReg(inst, address, opCode);
public OpCode32AluReg(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode)
{
Rm = (opCode >> 0) & 0xf;
}
}
}
| 29.133333 | 133 | 0.638444 | [
"MIT"
] | 0MrDarn0/Ryujinx | ARMeilleure/Decoders/OpCode32AluReg.cs | 439 | C# |
/*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*
*
*
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace JDCloudSDK.Vod.Model
{
/// <summary>
/// 查询分类响应信息
/// </summary>
public class CategoryObject
{
///<summary>
/// 分类ID
///</summary>
public long? Id{ get; set; }
///<summary>
/// 分类名称
///</summary>
public string Name{ get; set; }
///<summary>
/// 分类级别。取值范围为 [0, 3],取值为 0 时为虚拟根节点
///
///</summary>
public int? Level{ get; set; }
///<summary>
/// 父分类ID,取值为 0 或 null 时,表示该分类为一级分类
///
///</summary>
public long? ParentId{ get; set; }
///<summary>
/// 分类描述信息
///</summary>
public string Description{ get; set; }
///<summary>
/// 创建时间
///</summary>
public DateTime? CreateTime{ get; set; }
///<summary>
/// 修改时间
///</summary>
public DateTime? UpdateTime{ get; set; }
}
}
| 23.847222 | 76 | 0.567851 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Vod/Model/CategoryObject.cs | 1,855 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/**
* @author Allware Ltda. (http://www.allware.cl)
* @copyright 2015 Transbank S.A. (http://www.tranbank.cl)
* @date May 2016
* @license GNU LGPL
* @version 1.0
*/
namespace Transbank.NET.sample.certificates
{
public class CertNormalMall
{
internal static Dictionary<string, string> certificate()
{
/** Crea un Dictionary para almacenar los datos de integración pruebas */
Dictionary<string, string> certificate = new Dictionary<string, string>();
/** Agregar datos de integración a Dictionary */
String certFolder = System.Web.HttpContext.Current.Server.MapPath(".");
/** Modo de Utilización */
certificate.Add("environment", "INTEGRACION");
/** Certificado Publico (Dirección fisica de certificado o contenido) */
certificate.Add("public_cert", certFolder + "\\certificates\\597020000542\\tbk.pem");
/** Ejemplo de Ruta de Certificado de Salida */
certificate.Add("webpay_cert", certFolder + "\\certificates\\597020000542\\597020000542.pfx");
/** Ejemplo de Password de Certificado de Salida */
certificate.Add("password", "transbank123");
/** Codigo Comercio */
certificate.Add("commerce_code", "597020000542");
return certificate;
}
internal static Dictionary<string, string> store_codes()
{
/** Crea un Dictionary para almacenar los datos de tiendas */
Dictionary<string, string> store_codes = new Dictionary<string, string>();
/** Agregar datos de integración a Dictionary */
/** Tienda 1 */
store_codes.Add("tienda1", "597020000543");
/** Tienda 2 */
store_codes.Add("tienda2", "597020000544");
return store_codes;
}
}
} | 30.691176 | 107 | 0.586967 | [
"BSD-3-Clause"
] | TransbankDevelopers/libwebpay-dotnet | transbank.net/sample/certificates/cert-normal-mall.cs | 2,094 | C# |
/*********************************************
作者:曹旭升
QQ:279060597
访问博客了解详细介绍及更多内容:
http://blog.shengxunwei.com
**********************************************/
namespace Sheng.SailingEase.Components.WindowComponent.View
{
partial class WindowEditView
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.txtName = new Sheng.SailingEase.Controls.SETextBox();
this.txtCode = new Sheng.SailingEase.Controls.SETextBox();
this.btnCancel = new Sheng.SailingEase.Controls.SEButton();
this.btnOK = new Sheng.SailingEase.Controls.SEButton();
this.SuspendLayout();
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(29, 34);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(155, 12);
this.label1.TabIndex = 0;
this.label1.Text = "${WindowEditView_LabelName}:";
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(29, 61);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(155, 12);
this.label2.TabIndex = 1;
this.label2.Text = "${WindowEditView_LabelCode}:";
this.txtName.AllowEmpty = false;
this.txtName.HighLight = true;
this.txtName.LimitMaxValue = false;
this.txtName.Location = new System.Drawing.Point(105, 31);
this.txtName.MaxLength = 100;
this.txtName.MaxValue = ((long)(2147483647));
this.txtName.Name = "txtName";
this.txtName.Regex = "";
this.txtName.RegexMsg = null;
this.txtName.Size = new System.Drawing.Size(230, 21);
this.txtName.TabIndex = 2;
this.txtName.Title = "";
this.txtName.ValueCompareTo = null;
this.txtName.WaterText = "";
this.txtCode.AllowEmpty = false;
this.txtCode.HighLight = true;
this.txtCode.LimitMaxValue = false;
this.txtCode.Location = new System.Drawing.Point(105, 58);
this.txtCode.MaxLength = 100;
this.txtCode.MaxValue = ((long)(2147483647));
this.txtCode.Name = "txtCode";
this.txtCode.Regex = "";
this.txtCode.RegexMsg = null;
this.txtCode.Size = new System.Drawing.Size(230, 21);
this.txtCode.TabIndex = 3;
this.txtCode.Title = "";
this.txtCode.ValueCompareTo = null;
this.txtCode.WaterText = "";
this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(340, 114);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(75, 23);
this.btnCancel.TabIndex = 4;
this.btnCancel.Text = "${WindowEditView_ButtonCancel}";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnOK.Location = new System.Drawing.Point(259, 114);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(75, 23);
this.btnOK.TabIndex = 5;
this.btnOK.Text = "${WindowEditView_ButtonOK}";
this.btnOK.UseVisualStyleBackColor = true;
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
this.AcceptButton = this.btnOK;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(427, 149);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.txtCode);
this.Controls.Add(this.txtName);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "FormFormAdd";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "${WindowEditView}";
this.Load += new System.EventHandler(this.WindowEditView_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private Sheng.SailingEase.Controls.SETextBox txtName;
private Sheng.SailingEase.Controls.SETextBox txtCode;
private Sheng.SailingEase.Controls.SEButton btnCancel;
private Sheng.SailingEase.Controls.SEButton btnOK;
}
}
| 50.06087 | 161 | 0.585374 | [
"MIT"
] | ckalvin-hub/Sheng.Winform.IDE | SourceCode/Source/Components/Components.Window/View/WindowEditView.designer.cs | 5,805 | C# |
/*
* Copyright 2013 ThirdMotion, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @class strange.extensions.context.impl.ContextView
*
* The Root View of a Context hierarchy.
*
* Extend this class to create your AppRoot, then attach
* that MonoBehaviour to the GameObject at the very top of
* your display hierarchy.
*
* The startup sequence looks like this:
void Awake()
{
context = new MyContext(this, true);
context.Start ();
}
*/
using System;
using UnityEngine;
using strange.extensions.context.api;
namespace strange.extensions.context.impl
{
public class ContextView : MonoBehaviour, IContextView
{
public IContext context{get;set;}
public ContextView ()
{
}
/// <summary>
/// When a ContextView is Destroyed, automatically removes the associated Context.
/// </summary>
protected virtual void OnDestroy()
{
if (context != null)
Context.firstContext.RemoveContext(context);
}
#region IView implementation
public bool requiresContext {get;set;}
public bool registeredWithContext {get;set;}
public bool autoRegisterWithContext{ get; set; }
#endregion
}
}
| 23.478873 | 84 | 0.717457 | [
"Apache-2.0"
] | Lenovezhou/Screenshow | Assets/Scripts/StrangeIoC/scripts/strange/extensions/context/impl/ContextView.cs | 1,667 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace DataStructures.Graphs
{
public class GraphNode<T, TCost> : Node<T>
where TCost : IComparable
{
public List<Neighbor<T, TCost>> Neighbors { get; private set; }
public GraphNode(T value) : base(value) {
Neighbors = new List<Neighbor<T, TCost>>();
}
public GraphNode<T, TCost> AddNeighbor(Node<T> neighbor, TCost cost)
{
if (!Neighbors.Any(x => x.Node.Value.Equals(neighbor.Value)))
{
Neighbors.Add(new Neighbor<T, TCost>(neighbor, cost));
}
return this;
}
}
}
| 25.555556 | 76 | 0.566667 | [
"MIT"
] | pablocsilva/algorithms | DataStructures/Graphs/GraphNode.cs | 692 | 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 appmesh-2019-01-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AppMesh.Model
{
/// <summary>
/// Container for the parameters to the CreateRoute operation.
/// Creates a route that is associated with a virtual router.
///
///
/// <para>
/// You can use the <code>prefix</code> parameter in your route specification for path-based
/// routing of requests. For example, if your virtual service name is
/// <code>my-service.local</code> and you want the route to match requests to
/// <code>my-service.local/metrics</code>, your prefix should be <code>/metrics</code>.
/// </para>
///
/// <para>
/// If your route matches a request, you can distribute traffic to one or more target
/// virtual nodes with relative weighting.
/// </para>
///
/// <para>
/// For more information about routes, see <a href="https://docs.aws.amazon.com/app-mesh/latest/userguide/routes.html">Routes</a>.
/// </para>
/// </summary>
public partial class CreateRouteRequest : AmazonAppMeshRequest
{
private string _clientToken;
private string _meshName;
private string _meshOwner;
private string _routeName;
private RouteSpec _spec;
private List<TagRef> _tags = new List<TagRef>();
private string _virtualRouterName;
/// <summary>
/// Gets and sets the property ClientToken.
/// <para>
/// Unique, case-sensitive identifier that you provide to ensure the idempotency of therequest.
/// Up to 36 letters, numbers, hyphens, and underscores are allowed.
/// </para>
/// </summary>
public string ClientToken
{
get { return this._clientToken; }
set { this._clientToken = value; }
}
// Check to see if ClientToken property is set
internal bool IsSetClientToken()
{
return this._clientToken != null;
}
/// <summary>
/// Gets and sets the property MeshName.
/// <para>
/// The name of the service mesh to create the route in.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=255)]
public string MeshName
{
get { return this._meshName; }
set { this._meshName = value; }
}
// Check to see if MeshName property is set
internal bool IsSetMeshName()
{
return this._meshName != null;
}
/// <summary>
/// Gets and sets the property MeshOwner.
/// <para>
/// The AWS IAM account ID of the service mesh owner. If the account ID is not your own,
/// then the account that you specify must share the mesh with your account
/// before you can create the resource in the service mesh. For more information
/// about mesh sharing, see <a href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working
/// with Shared Meshes</a>.
/// </para>
/// </summary>
[AWSProperty(Min=12, Max=12)]
public string MeshOwner
{
get { return this._meshOwner; }
set { this._meshOwner = value; }
}
// Check to see if MeshOwner property is set
internal bool IsSetMeshOwner()
{
return this._meshOwner != null;
}
/// <summary>
/// Gets and sets the property RouteName.
/// <para>
/// The name to use for the route.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=255)]
public string RouteName
{
get { return this._routeName; }
set { this._routeName = value; }
}
// Check to see if RouteName property is set
internal bool IsSetRouteName()
{
return this._routeName != null;
}
/// <summary>
/// Gets and sets the property Spec.
/// <para>
/// The route specification to apply.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public RouteSpec Spec
{
get { return this._spec; }
set { this._spec = value; }
}
// Check to see if Spec property is set
internal bool IsSetSpec()
{
return this._spec != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// Optional metadata that you can apply to the route to assist with categorization and
/// organization. Each tag consists of a key and an optional value, both of which
/// you define. Tag keys can have a maximum character length of 128 characters,
/// and tag values can have a maximum length of 256 characters.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=50)]
public List<TagRef> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property VirtualRouterName.
/// <para>
/// The name of the virtual router in which to create the route. If the virtual router
/// is in a shared mesh, then you must be the owner of the virtual router resource.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=255)]
public string VirtualRouterName
{
get { return this._virtualRouterName; }
set { this._virtualRouterName = value; }
}
// Check to see if VirtualRouterName property is set
internal bool IsSetVirtualRouterName()
{
return this._virtualRouterName != null;
}
}
} | 34.20197 | 134 | 0.570935 | [
"Apache-2.0"
] | Vfialkin/aws-sdk-net | sdk/src/Services/AppMesh/Generated/Model/CreateRouteRequest.cs | 6,943 | C# |
using System.Linq;
using Dalmatian.Web.ViewModels.Dogs;
using Dalmatian.Web.ViewModels.Persons;
namespace Dalmatian.Web.Areas.Administration.Controllers
{
using Dalmatian.Services.Data;
using Dalmatian.Web.ViewModels.Administration.Dashboard;
using Microsoft.AspNetCore.Mvc;
public class DashboardController : AdministrationController
{
private readonly ISettingsService settingsService;
private readonly IDogsService dogsService;
private readonly IPersonsService persons;
public DashboardController(ISettingsService settingsService, IDogsService dogsService, IPersonsService persons)
{
this.settingsService = settingsService;
this.dogsService = dogsService;
this.persons = persons;
}
public IActionResult Index()
{
var viewModel = new IndexViewModel
{
DogCount = this.dogsService.GetDogCount(),
DogBaerTestCount = this.dogsService.GetDogBaerTestCount(),
DogHipRatingCount = this.dogsService.GetDogHipRatingCount(),
DogLiveCount = this.dogsService.GetDogLiveCount(),
DogDeadCount = this.dogsService.GetDogDeadCount(),
DogNewRegisters = this.dogsService.GetDogNewRegister().Cast<DogNewRegisterViewModel>(),
Persons = this.persons.GetTenPersons(),
DogMaleCount = this.dogsService.GetDogMaleCount(),
DogFemaleCount = this.dogsService.GetDogFemaleCount(),
DogColorBlackCount = this.dogsService.GetDogColorBlackCount(),
DogColorBrownCount = this.dogsService.GetDogColorBrownCount(),
};
return this.View(viewModel);
}
}
}
| 38.673913 | 119 | 0.666105 | [
"MIT"
] | angelneychev/Dalmatian | src/Web/Dalmatian.Web/Areas/Administration/Controllers/DashboardController.cs | 1,781 | C# |
using System.Collections.Generic;
using System.ComponentModel;
using GeneticSharp.Domain.Randomizations;
using System.Linq;
namespace GeneticSharp.Domain.Mutations
{
/// <summary>
/// Partial Shuffle Mutation (PSM).
/// <remarks>
/// In the partial shuffle mutation operator, we take a sequence S limited by two
/// positions i and j randomly chosen, such that i<j. The gene order in this sequence
/// will be shuffled. Sequence will be shuffled until it becomes different than the starting order
/// <see href="http://arxiv.org/ftp/arxiv/papers/1203/1203.3099.pdf">Analyzing the Performance of Mutation Operators to Solve the Travelling Salesman Problem</see>
/// </remarks>
/// </summary>
[DisplayName("Partial Shuffle (PSM)")]
public class PartialShuffleMutation : SequenceMutationBase
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="PartialShuffleMutation"/> class.
/// </summary>
public PartialShuffleMutation()
{
IsOrdered = true;
}
#endregion
#region Methods
/// <summary>
/// Mutate selected sequence.
/// </summary>
/// <returns>The resulted sequence after mutation operation.</returns>
/// <param name="sequence">The sequence to be mutated.</param>
protected override IEnumerable<T> MutateOnSequence<T>(IEnumerable<T> sequence)
{
// If there is at least two differente genes on source sequence,
// Then is possible shuffle their in sequence.
if (sequence.Distinct().Count() > 1)
{
var result = sequence.Shuffle(RandomizationProvider.Current);
while (sequence.SequenceEqual(result))
{
result = sequence.Shuffle(RandomizationProvider.Current);
}
return result;
}
// All genes on sequence are equal, then sequence cannot be shuffled.
return sequence;
}
#endregion
}
}
| 36.741379 | 167 | 0.610981 | [
"MIT"
] | JianLoong/GeneticSharp | src/GeneticSharp.Domain/Mutations/PartialShuffleMutation.cs | 2,133 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace DMTools.Web.Areas.Identity.Pages.Account.Manage
{
public class GenerateRecoveryCodesModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly ILogger<GenerateRecoveryCodesModel> _logger;
public GenerateRecoveryCodesModel(
UserManager<IdentityUser> userManager,
ILogger<GenerateRecoveryCodesModel> logger)
{
_userManager = userManager;
_logger = logger;
}
[TempData]
public string[] RecoveryCodes { get; set; }
[TempData]
public string StatusMessage { get; set; }
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var isTwoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user);
if (!isTwoFactorEnabled)
{
var userId = await _userManager.GetUserIdAsync(user);
throw new InvalidOperationException($"Cannot generate recovery codes for user with ID '{userId}' because they do not have 2FA enabled.");
}
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var isTwoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user);
var userId = await _userManager.GetUserIdAsync(user);
if (!isTwoFactorEnabled)
{
throw new InvalidOperationException($"Cannot generate recovery codes for user with ID '{userId}' as they do not have 2FA enabled.");
}
var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
RecoveryCodes = recoveryCodes.ToArray();
_logger.LogInformation("User with ID '{UserId}' has generated new 2FA recovery codes.", userId);
StatusMessage = "You have generated new recovery codes.";
return RedirectToPage("./ShowRecoveryCodes");
}
}
} | 36.805556 | 153 | 0.632075 | [
"MIT"
] | PeshekhonovK/DMTools | Web/DMTools.Web/Areas/Identity/Pages/Account/Manage/GenerateRecoveryCodes.cshtml.cs | 2,650 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Storage;
namespace Microsoft.EntityFrameworkCore.TestUtilities.FakeProvider
{
public class FakeRelationalDatabaseCreator : IRelationalDatabaseCreator
{
public bool EnsureDeleted()
{
throw new NotImplementedException();
}
public Task<bool> EnsureDeletedAsync(CancellationToken cancellationToken = new CancellationToken())
{
throw new NotImplementedException();
}
public bool EnsureCreated()
{
throw new NotImplementedException();
}
public Task<bool> EnsureCreatedAsync(CancellationToken cancellationToken = new CancellationToken())
{
throw new NotImplementedException();
}
public bool Exists()
{
throw new NotImplementedException();
}
public Task<bool> ExistsAsync(CancellationToken cancellationToken = new CancellationToken())
{
throw new NotImplementedException();
}
public void Create()
{
throw new NotImplementedException();
}
public Task CreateAsync(CancellationToken cancellationToken = new CancellationToken())
{
throw new NotImplementedException();
}
public void Delete()
{
throw new NotImplementedException();
}
public Task DeleteAsync(CancellationToken cancellationToken = new CancellationToken())
{
throw new NotImplementedException();
}
public void CreateTables()
{
throw new NotImplementedException();
}
public Task CreateTablesAsync(CancellationToken cancellationToken = new CancellationToken())
{
throw new NotImplementedException();
}
public string GenerateCreateScript()
{
throw new NotImplementedException();
}
}
}
| 27.810127 | 111 | 0.630405 | [
"Apache-2.0"
] | Alecu100/EntityFrameworkCore | test/EFCore.Relational.Tests/TestUtilities/FakeProvider/FakeRelationalDatabaseCreator.cs | 2,197 | C# |
using System;
using NUnit.Framework;
using NUnit.Framework.Constraints;
using Microsoft.Maui.Controls.Core.UnitTests;
namespace Microsoft.Maui.Controls.Xaml.UnitTests
{
public partial class StyleSheet : ContentPage
{
public StyleSheet()
{
InitializeComponent();
}
public StyleSheet(bool useCompiledXaml)
{
//this stub will be replaced at compile time
}
[TestFixture]
public class Tests
{
[SetUp]
public void SetUp()
{
Device.PlatformServices = new MockPlatformServices();
Microsoft.Maui.Controls.Internals.Registrar.RegisterAll(new Type[0]);
}
[TestCase(false), TestCase(true)]
public void EmbeddedStyleSheetsAreLoaded(bool useCompiledXaml)
{
var layout = new StyleSheet(useCompiledXaml);
Assert.That(layout.Resources.StyleSheets[0].Styles.Count, Is.GreaterThanOrEqualTo(1));
}
[TestCase(false), TestCase(true)]
public void StyleSheetsAreApplied(bool useCompiledXaml)
{
var layout = new StyleSheet(useCompiledXaml);
Assert.That(layout.label0.TextColor, Is.EqualTo(Color.Azure));
Assert.That(layout.label0.BackgroundColor, Is.EqualTo(Color.AliceBlue));
}
}
}
} | 25.152174 | 90 | 0.73293 | [
"MIT"
] | pictos/maui | src/Controls/tests/Xaml.UnitTests/StyleSheet.xaml.cs | 1,157 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GSMailApi
{
class GSMail
{
}
}
| 13.153846 | 33 | 0.725146 | [
"MIT"
] | ALEX-ANV/GSMail | GSMailApi/GSMail.cs | 173 | 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 Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Domain.Model.V20180129;
using System;
using System.Collections.Generic;
namespace Aliyun.Acs.Domain.Transform.V20180129
{
public class SaveSingleTaskForDeletingDSRecordResponseUnmarshaller
{
public static SaveSingleTaskForDeletingDSRecordResponse Unmarshall(UnmarshallerContext context)
{
SaveSingleTaskForDeletingDSRecordResponse saveSingleTaskForDeletingDSRecordResponse = new SaveSingleTaskForDeletingDSRecordResponse();
saveSingleTaskForDeletingDSRecordResponse.HttpResponse = context.HttpResponse;
saveSingleTaskForDeletingDSRecordResponse.RequestId = context.StringValue("SaveSingleTaskForDeletingDSRecord.RequestId");
saveSingleTaskForDeletingDSRecordResponse.TaskNo = context.StringValue("SaveSingleTaskForDeletingDSRecord.TaskNo");
return saveSingleTaskForDeletingDSRecordResponse;
}
}
} | 44.179487 | 138 | 0.790482 | [
"Apache-2.0"
] | brightness007/unofficial-aliyun-openapi-net-sdk | aliyun-net-sdk-domain/Domain/Transform/V20180129/SaveSingleTaskForDeletingDSRecordResponseUnmarshaller.cs | 1,723 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrimeiroTests
{
internal class ContasTests
{
}
}
| 14.538462 | 33 | 0.746032 | [
"MIT"
] | N0N4T0/dio-bootcamp-1 | Primeiro/PrimeiroTests/ContasTests.cs | 191 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
using Squidex.Infrastructure;
using Squidex.Infrastructure.Collections;
using Squidex.Infrastructure.Security;
using Squidex.Shared;
namespace Squidex.Domain.Apps.Core.Apps
{
public sealed class Roles
{
private readonly ArrayDictionary<string, Role> inner;
public static readonly IReadOnlyDictionary<string, Role> Defaults = new Dictionary<string, Role>
{
[Role.Owner] =
new Role(Role.Owner, new PermissionSet(
Clean(Permissions.App))),
[Role.Reader] =
new Role(Role.Reader, new PermissionSet(
Clean(Permissions.AppAssetsRead),
Clean(Permissions.AppContentsRead))),
[Role.Editor] =
new Role(Role.Editor, new PermissionSet(
Clean(Permissions.AppAssets),
Clean(Permissions.AppContents),
Clean(Permissions.AppRolesRead),
Clean(Permissions.AppWorkflowsRead))),
[Role.Developer] =
new Role(Role.Developer, new PermissionSet(
Clean(Permissions.AppApi),
Clean(Permissions.AppAssets),
Clean(Permissions.AppContents),
Clean(Permissions.AppPatterns),
Clean(Permissions.AppRolesRead),
Clean(Permissions.AppRules),
Clean(Permissions.AppSchemas),
Clean(Permissions.AppWorkflows)))
};
public static readonly Roles Empty = new Roles(new ArrayDictionary<string, Role>());
public int CustomCount
{
get { return inner.Count; }
}
public Role this[string name]
{
get { return inner[name]; }
}
public IEnumerable<Role> Custom
{
get { return inner.Values; }
}
public IEnumerable<Role> All
{
get { return inner.Values.Union(Defaults.Values); }
}
private Roles(ArrayDictionary<string, Role> roles)
{
inner = roles;
}
public Roles(IEnumerable<KeyValuePair<string, Role>> items)
{
inner = new ArrayDictionary<string, Role>(Cleaned(items));
}
[Pure]
public Roles Remove(string name)
{
return Create(inner.Without(name));
}
[Pure]
public Roles Add(string name)
{
var newRole = new Role(name);
if (inner.ContainsKey(name))
{
throw new ArgumentException("Name already exists.", nameof(name));
}
if (IsDefault(name))
{
return this;
}
return Create(inner.With(name, newRole));
}
[Pure]
public Roles Update(string name, params string[] permissions)
{
Guard.NotNullOrEmpty(name);
Guard.NotNull(permissions);
if (!inner.TryGetValue(name, out var role))
{
return this;
}
return Create(inner.With(name, role.Update(permissions), DeepComparer<Role>.Instance));
}
public static bool IsDefault(string role)
{
return role != null && Defaults.ContainsKey(role);
}
public static bool IsDefault(Role role)
{
return role != null && Defaults.ContainsKey(role.Name);
}
public bool ContainsCustom(string name)
{
return inner.ContainsKey(name);
}
public bool Contains(string name)
{
return inner.ContainsKey(name) || Defaults.ContainsKey(name);
}
public bool TryGet(string app, string name, [MaybeNullWhen(false)] out Role value)
{
Guard.NotNull(app);
if (Defaults.TryGetValue(name, out var role) || inner.TryGetValue(name, out role))
{
value = role.ForApp(app);
return true;
}
value = null!;
return false;
}
private static string Clean(string permission)
{
permission = Permissions.ForApp(permission).Id;
var prefix = Permissions.ForApp(Permissions.App);
if (permission.StartsWith(prefix.Id, StringComparison.OrdinalIgnoreCase))
{
permission = permission.Substring(prefix.Id.Length);
}
if (permission.Length == 0)
{
return Permission.Any;
}
return permission.Substring(1);
}
private static KeyValuePair<string, Role>[] Cleaned(IEnumerable<KeyValuePair<string, Role>> items)
{
return items.Where(x => !Defaults.ContainsKey(x.Key)).ToArray();
}
private Roles Create(ArrayDictionary<string, Role> newRoles)
{
return ReferenceEquals(inner, newRoles) ? this : new Roles(newRoles);
}
}
}
| 30.043011 | 106 | 0.525412 | [
"MIT"
] | andrewcampkin/squidex | backend/src/Squidex.Domain.Apps.Core.Model/Apps/Roles.cs | 5,591 | C# |
using System;
using System.Numerics;
using LBPLibrary;
using LBP.UnitTests;
using Accord.Math;
using System.IO;
using Xunit;
namespace LBP.UnitTests
{
public class BMPWriterTests
{
TestImage testImg = new TestImage(); // Initialize testimage function
string filename = Directory.GetCurrentDirectory() + @"\Test.png";
[Fact]
public void SaveAndRead_IntegerArray_EqualsInputArray()
{
testImg.New();
Functions.Save(filename, testImg.Image.ToDouble(), false);
float[,] readedArray = Functions.Load(filename);
Assert.Equal(testImg.Image, readedArray);
}
[Fact]
public void SaveAndRead_FloatArray_EqualsInputArray()
{ // Float type's precision is only 7 digits!!
testImg.New("Add residual");
Functions.Save(filename, testImg.Image.ToDouble(), false);
float[,] readedArray = Functions.Load(filename);
testImg.Image = testImg.Image.Round().ToSingle(); // Round
Assert.Equal(testImg.Image, readedArray);
}
[Fact]
public void SaveAndRead_FloatArrayNormalized_EqualsNormalizedArray()
{ // Float type's precision is only 7 digits!!
testImg.New("Add residual");
Functions.Save(filename, testImg.Image.ToDouble(), true);
float[,] readedArray = Functions.Load(filename);
testImg.Image = Functions.Normalize(testImg.Image.ToDouble()).Multiply(255).Round().ToSingle(); // Normalize array
Assert.Equal(testImg.Image, readedArray);
}
}
}
| 30.698113 | 126 | 0.62815 | [
"MIT"
] | MIPT-Oulu/LocalBinaryPattern | LBP/LBP.UnitTests/Tests/BMPWriterTests.cs | 1,629 | C# |
// Copyright 2021 Google LLC
//
// 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
//
// https://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.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.ResourceManager.V3.Snippets
{
using Google.Api.Gax;
using Google.Cloud.ResourceManager.V3;
using System;
using System.Linq;
using System.Threading.Tasks;
public sealed partial class GeneratedTagBindingsClientStandaloneSnippets
{
/// <summary>Snippet for ListTagBindingsAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task ListTagBindingsResourceNamesAsync()
{
// Create client
TagBindingsClient tagBindingsClient = await TagBindingsClient.CreateAsync();
// Initialize request argument(s)
IResourceName parent = new UnparsedResourceName("a/wildcard/resource");
// Make the request
PagedAsyncEnumerable<ListTagBindingsResponse, TagBinding> response = tagBindingsClient.ListTagBindingsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TagBinding item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTagBindingsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TagBinding item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TagBinding> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TagBinding item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
}
}
}
| 41.64 | 128 | 0.633365 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/cloud/resourcemanager/v3/google-cloud-resourcemanager-v3-csharp/Google.Cloud.ResourceManager.V3.StandaloneSnippets/TagBindingsClient.ListTagBindingsResourceNamesAsyncSnippet.g.cs | 3,123 | C# |
//
// NonNullDictionary.cs
//
// Copyright (c) 2017 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace Couchbase.Lite.Util
{
[ExcludeFromCodeCoverage]
internal sealed class CollectionDebuggerView<TKey, TValue>
{
#region Variables
private readonly ICollection<KeyValuePair<TKey, TValue>> _c;
#endregion
#region Properties
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public KeyValuePair<TKey, TValue>[] Items
{
get {
var o = new KeyValuePair<TKey, TValue>[_c.Count];
_c.CopyTo(o, 0);
return o;
}
}
#endregion
#region Constructors
public CollectionDebuggerView(ICollection<KeyValuePair<TKey, TValue>> col)
{
_c = col;
}
#endregion
}
/// <summary>
/// A dictionary that ignores any attempts to insert a null object into it.
/// Usefor for creating JSON objects that should not contain null values
/// </summary>
// ReSharper disable UseNameofExpression
[DebuggerDisplay("Count={Count}")]
// ReSharper restore UseNameofExpression
[DebuggerTypeProxy(typeof(CollectionDebuggerView<,>))]
[ExcludeFromCodeCoverage]
internal sealed class NonNullDictionary<TK, TV> : IDictionary<TK, TV>, IReadOnlyDictionary<TK, TV>
{
#region Variables
private readonly IDictionary<TK, TV> _data = new Dictionary<TK, TV>();
#endregion
#region Properties
/// <inheritdoc />
public int Count => _data.Count;
/// <inheritdoc />
public bool IsReadOnly => _data.IsReadOnly;
/// <inheritdoc />
public TV this[TK index]
{
get => _data[index];
set {
if(IsAddable(value)) {
_data[index] = value;
}
}
}
/// <inheritdoc />
public ICollection<TK> Keys => _data.Keys;
/// <inheritdoc />
public ICollection<TV> Values => _data.Values;
/// <inheritdoc />
IEnumerable<TK> IReadOnlyDictionary<TK, TV>.Keys => _data.Keys;
/// <inheritdoc />
IEnumerable<TV> IReadOnlyDictionary<TK, TV>.Values => _data.Values;
#endregion
#region Private Methods
[SuppressMessage("ReSharper", "ConditionIsAlwaysTrueOrFalse", Justification = "item is a Nullable type during the block")]
private static bool IsAddable(TV item)
{
if (!(item is ValueType)) {
return item != null;
}
var underlyingType = Nullable.GetUnderlyingType(typeof(TV));
if(underlyingType != null) {
return item != null;
}
return true;
}
#endregion
#region ICollection<KeyValuePair<TK,TV>>
/// <inheritdoc />
public void Add(KeyValuePair<TK, TV> item)
{
if(IsAddable(item.Value)) {
_data.Add(item);
}
}
/// <inheritdoc />
public void Clear()
{
_data.Clear();
}
/// <inheritdoc />
public bool Contains(KeyValuePair<TK, TV> item)
{
return _data.Contains(item);
}
/// <inheritdoc />
public void CopyTo(KeyValuePair<TK, TV>[] array, int arrayIndex)
{
_data.CopyTo(array, arrayIndex);
}
/// <inheritdoc />
public bool Remove(KeyValuePair<TK, TV> item)
{
return _data.Remove(item);
}
#endregion
#region IDictionary<TK,TV>
/// <inheritdoc />
public void Add(TK key, TV value)
{
if(IsAddable(value)) {
_data.Add(key, value);
}
}
/// <inheritdoc />
public bool ContainsKey(TK key)
{
return _data.ContainsKey(key);
}
/// <inheritdoc />
public bool Remove(TK key)
{
return _data.Remove(key);
}
/// <inheritdoc />
public bool TryGetValue(TK key, out TV value)
{
return _data.TryGetValue(key, out value);
}
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator()
{
return _data.GetEnumerator();
}
#endregion
#region IEnumerable<KeyValuePair<TK,TV>>
/// <inheritdoc />
public IEnumerator<KeyValuePair<TK, TV>> GetEnumerator()
{
return _data.GetEnumerator();
}
#endregion
}
}
| 25.219626 | 130 | 0.559755 | [
"Apache-2.0"
] | Pio1006/couchbase-lite-net | src/Couchbase.Lite.Shared/Util/NonNullDictionary.cs | 5,399 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210
{
using Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.PowerShell;
/// <summary>Recovery plan A2A input.</summary>
[System.ComponentModel.TypeConverter(typeof(RecoveryPlanA2AInputTypeConverter))]
public partial class RecoveryPlanA2AInput
{
/// <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 an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.RecoveryPlanA2AInput"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanA2AInput" />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanA2AInput DeserializeFromDictionary(global::System.Collections.IDictionary content)
{
return new RecoveryPlanA2AInput(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.RecoveryPlanA2AInput"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanA2AInput" />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanA2AInput DeserializeFromPSObject(global::System.Management.Automation.PSObject content)
{
return new RecoveryPlanA2AInput(content);
}
/// <summary>
/// Creates a new instance of <see cref="RecoveryPlanA2AInput" />, 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 Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanA2AInput FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode.Parse(jsonText));
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.RecoveryPlanA2AInput"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
internal RecoveryPlanA2AInput(global::System.Collections.IDictionary content)
{
bool returnNow = false;
BeforeDeserializeDictionary(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanA2AInputInternal)this).PrimaryZone = (string) content.GetValueForProperty("PrimaryZone",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanA2AInputInternal)this).PrimaryZone, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanA2AInputInternal)this).RecoveryZone = (string) content.GetValueForProperty("RecoveryZone",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanA2AInputInternal)this).RecoveryZone, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanProviderSpecificInputInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanProviderSpecificInputInternal)this).InstanceType, global::System.Convert.ToString);
AfterDeserializeDictionary(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.RecoveryPlanA2AInput"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
internal RecoveryPlanA2AInput(global::System.Management.Automation.PSObject content)
{
bool returnNow = false;
BeforeDeserializePSObject(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanA2AInputInternal)this).PrimaryZone = (string) content.GetValueForProperty("PrimaryZone",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanA2AInputInternal)this).PrimaryZone, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanA2AInputInternal)this).RecoveryZone = (string) content.GetValueForProperty("RecoveryZone",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanA2AInputInternal)this).RecoveryZone, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanProviderSpecificInputInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRecoveryPlanProviderSpecificInputInternal)this).InstanceType, global::System.Convert.ToString);
AfterDeserializePSObject(content);
}
/// <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, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode.IncludeAll)?.ToString();
}
/// Recovery plan A2A input.
[System.ComponentModel.TypeConverter(typeof(RecoveryPlanA2AInputTypeConverter))]
public partial interface IRecoveryPlanA2AInput
{
}
} | 69.792593 | 353 | 0.706113 | [
"MIT"
] | AverageDesigner/azure-powershell | src/Migrate/generated/api/Models/Api20210210/RecoveryPlanA2AInput.PowerShell.cs | 9,288 | C# |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Abp.Application.Services.Dto;
using Abp.AspNetCore.Mvc.Authorization;
using WeixinProject.Authorization;
using WeixinProject.Controllers;
using WeixinProject.Users;
using WeixinProject.Web.Models.Users;
namespace WeixinProject.Web.Controllers
{
[AbpMvcAuthorize(PermissionNames.Pages_Users)]
public class UsersController : WeixinProjectControllerBase
{
private readonly IUserAppService _userAppService;
public UsersController(IUserAppService userAppService)
{
_userAppService = userAppService;
}
public async Task<ActionResult> Index()
{
var users = (await _userAppService.GetAll(new PagedResultRequestDto {MaxResultCount = int.MaxValue})).Items; // Paging not implemented yet
var roles = (await _userAppService.GetRoles()).Items;
var model = new UserListViewModel
{
Users = users,
Roles = roles
};
return View(model);
}
public async Task<ActionResult> EditUserModal(long userId)
{
var user = await _userAppService.Get(new EntityDto<long>(userId));
var roles = (await _userAppService.GetRoles()).Items;
var model = new EditUserModalViewModel
{
User = user,
Roles = roles
};
return View("_EditUserModal", model);
}
}
}
| 32.06383 | 150 | 0.633709 | [
"MIT"
] | Yuexs/WeixinProject | src/WeixinProject.Web.Mvc/Controllers/UsersController.cs | 1,509 | C# |
using KD.Dova.Api;
using System.Collections.Generic;
namespace KD.Dova.Utils
{
/// <summary>
/// Contains mapping for Java types.
/// </summary>
internal static class JavaMapper
{
private const string JAVA_ARRAY_FIELD_CHAR = "[";
private static List<JavaType> JAVA_TYPES { get; set; }
static JavaMapper()
{
JAVA_TYPES = new List<JavaType>();
// Add basic Java types mappings
JAVA_TYPES.Add(new JavaType("void", "V", typeof(void)));
JAVA_TYPES.Add(new JavaType("boolean", "Z", typeof(bool)));
JAVA_TYPES.Add(new JavaType("byte", "B", typeof(byte)));
JAVA_TYPES.Add(new JavaType("char", "C", typeof(char)));
JAVA_TYPES.Add(new JavaType("short", "S", typeof(short)));
JAVA_TYPES.Add(new JavaType("int", "I", typeof(int)));
JAVA_TYPES.Add(new JavaType("long", "J", typeof(long)));
JAVA_TYPES.Add(new JavaType("float", "F", typeof(float)));
JAVA_TYPES.Add(new JavaType("double", "D", typeof(double)));
JAVA_TYPES.Add(new JavaType("string", "Ljava/lang/String;", typeof(string)));
JAVA_TYPES.Add(new JavaType("object", "Ljava/lang/Object;", typeof(object)));
JAVA_TYPES.Add(new JavaType("object", "Ljava/lang/Object;", typeof(JObject))); // We need to double register this because JObject is a wrapper for Java object.
}
/// <summary>
/// Returns currently registered Java JNI types.
/// </summary>
/// <returns></returns>
public static IEnumerable<JavaType> GetRegisteredJavaTypes()
{
var copy = new JavaType[JAVA_TYPES.Count];
JAVA_TYPES.CopyTo(copy);
return copy;
}
}
}
| 39.065217 | 171 | 0.587646 | [
"MIT"
] | Sejoslaw/KD.Dova | KD.Dova/Utils/JavaMapper.cs | 1,799 | C# |
/*
Copyright (c) 2014 Code Owls LLC
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.Collections.Generic;
using CodeOwls.PowerShell.Provider.PathNodeProcessors;
using CodeOwls.PowerShell.Provider.PathNodes;
namespace CodeOwls.PowerShell.Paths.Processors
{
public interface IPathResolver
{
IEnumerable<IPathNode> ResolvePath( IProviderContext providerContext, string path );
}
}
| 38.486486 | 92 | 0.780197 | [
"MIT"
] | jzabroski/SHiPS | src/p2f/src/CodeOwls.PowerShell/CodeOwls.PowerShell.Paths/Processors/IPathResolver.cs | 1,426 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace InDesign.Renew.XML
{
public partial class FormPrincipale : Form
{
public const string CurrentVersion = "0.1b";
public string CurrentOS = Environment.OSVersion.ToString();
public const string CommonInDesignPath = @"C:\Program Files\Adobe\Adobe InDesign CC 2018\AMT";
public FormPrincipale()
{
InitializeComponent();
}
private void btnGetCurrentCode_Click(object sender, EventArgs e)
{
XmlDocument docXML = new XmlDocument();
docXML.Load(filename: @"C:\Program Files\Adobe\Adobe InDesign CC 2018\AMT\application.xml");
MessageBox.Show(docXML.SelectSingleNode("//configuration/payload/other/data").ToString());
docXML.Save(Path.Combine(CommonInDesignPath, "application.xml"));
}
private void infoToolStripMenuItem_Click(object sender, EventArgs e) => MessageBox.Show("Quest'applicazione è stata realizzada da Diego Di Palma sotto licenza MIT.\n" +
"Per ogni problema contattare lo sviluppatore via email (diegodipalma@outlook.com) o via Telegram " +
$"(t.me/diegodipalma) indicando versione ({CurrentVersion}) e Sistema Operativo ({(CurrentOS)}).");
private void aiutoToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("1 - Premere il pulsante \"Get current code\" per caricare in memoria il codice che si sta utilizzando;\n" +
"2 - ");
}
}
}
| 39.977273 | 176 | 0.677658 | [
"MIT"
] | diegodipalma/InDesign.Renew.XML | InDesign.Renew.XML/FormPrincipale.cs | 1,762 | C# |
namespace DotBPE.Rpc
{
public enum AuditLogType
{
ClientCall = 1,
ServiceReceive = 2
}
}
| 13 | 28 | 0.564103 | [
"MIT"
] | dotbpe/dotbpe | src/DotBPE.Rpc/Diagnostics/AuditLogType.cs | 117 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers
{
internal static partial class MemberDeclarationsOrganizer
{
public static SyntaxList<MemberDeclarationSyntax> Organize(
SyntaxList<MemberDeclarationSyntax> members,
CancellationToken cancellationToken)
{
// Break the list of members up into groups based on the PP
// directives between them.
var groups = members.SplitNodesOnPreprocessorBoundaries(cancellationToken);
// Go into each group and organize them. We'll then have a list of
// lists. Flatten that list and return that.
var sortedGroups = groups.Select(OrganizeMemberGroup).Flatten().ToList();
if (sortedGroups.SequenceEqual(members))
{
return members;
}
return sortedGroups.ToSyntaxList();
}
private static void TransferTrivia<TSyntaxNode>(
IList<TSyntaxNode> originalList,
IList<TSyntaxNode> finalList) where TSyntaxNode : SyntaxNode
{
Contract.Requires(originalList.Count == finalList.Count);
if (originalList.Count >= 2)
{
// Ok, we wanted to reorder the list. But we're definitely not done right now. While
// most of the list will look fine, we will have issues with the first node. First,
// we don't want to move any pp directives or banners that are on the first node.
// Second, it can often be the case that the node doesn't even have any trivia. We
// want to follow the user's style. So we find the node that was in the index that
// the first node moved to, and we attempt to keep an appropriate amount of
// whitespace based on that.
// If the first node didn't move, then we don't need to do any of this special fixup
// logic.
if (originalList[0] != finalList[0])
{
// First. Strip any pp directives or banners on the first node. They have to
// move to the first node in the final list.
CopyBanner(originalList, finalList);
// Now, we need to fix up the first node wherever it is in the final list. We
// need to strip it of its banner, and we need to add additional whitespace to
// match the user's style
FixupOriginalFirstNode(originalList, finalList);
}
}
}
private static void FixupOriginalFirstNode<TSyntaxNode>(IList<TSyntaxNode> originalList, IList<TSyntaxNode> finalList) where TSyntaxNode : SyntaxNode
{
// Now, find the original node in the final list.
var originalFirstNode = originalList[0];
var indexInFinalList = finalList.IndexOf(originalFirstNode);
// Find the initial node we had at that same index.
var originalNodeAtThatIndex = originalList[indexInFinalList];
// If that node had blank lines above it, then place that number of blank
// lines before the first node in the final list.
var blankLines = originalNodeAtThatIndex.GetLeadingBlankLines();
originalFirstNode = originalFirstNode.GetNodeWithoutLeadingBannerAndPreprocessorDirectives()
.WithPrependedLeadingTrivia(blankLines);
finalList[indexInFinalList] = originalFirstNode;
}
private static void CopyBanner<TSyntaxNode>(
IList<TSyntaxNode> originalList,
IList<TSyntaxNode> finalList) where TSyntaxNode : SyntaxNode
{
// First. Strip any pp directives or banners on the first node. They
// have to stay at the top of the list.
var banner = originalList[0].GetLeadingBannerAndPreprocessorDirectives();
// Now, we want to remove any blank lines from the new first node and then
// reattach the banner.
var finalFirstNode = finalList[0];
finalFirstNode = finalFirstNode.GetNodeWithoutLeadingBlankLines();
finalFirstNode = finalFirstNode.WithLeadingTrivia(banner.Concat(finalFirstNode.GetLeadingTrivia()));
// Place the updated first node back in the result list
finalList[0] = finalFirstNode;
}
private static IList<MemberDeclarationSyntax> OrganizeMemberGroup(IList<MemberDeclarationSyntax> members)
{
if (members.Count > 1)
{
var initialList = new List<MemberDeclarationSyntax>(members);
var finalList = initialList.OrderBy(new Comparer()).ToList();
if (!finalList.SequenceEqual(initialList))
{
// Ok, we wanted to reorder the list. But we're definitely not done right now.
// While most of the list will look fine, we will have issues with the first
// node. First, we don't want to move any pp directives or banners that are on
// the first node. Second, it can often be the case that the node doesn't even
// have any trivia. We want to follow the user's style. So we find the node that
// was in the index that the first node moved to, and we attempt to keep an
// appropriate amount of whitespace based on that.
TransferTrivia(initialList, finalList);
return finalList;
}
}
return members;
}
}
}
| 46.575758 | 161 | 0.61825 | [
"Apache-2.0"
] | DaiMichael/roslyn | src/Features/CSharp/Portable/Organizing/Organizers/MemberDeclarationsOrganizer.cs | 6,150 | C# |
using CarWash.Persistence.Models;
using CarWash.Persistence.UseCases.WorkDays;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
namespace CarWash.Tests.Core
{
[TestClass]
public class WorkDaysFormatterTests
{
[TestMethod]
public void ShouldReturnListOfUpcomingWeekdaysAsString_DAYdotMONTH()
{
// given
var formatter = new WorkDaysFormatter();
var expectedList = new List<string>()
{
"11.11",
"12.11",
"13.11"
};
var listOfDaysToFormat = new List<WorkDay>()
{
new WorkDay(new DateTime(2017,11,11)),
new WorkDay(new DateTime(2017,11,12)),
new WorkDay(new DateTime(2017,11,13))
};
// when
var resultList = formatter.WorkDaysToString(listOfDaysToFormat);
// then
for (int i = 0; i < 3; i++)
{
Assert.AreEqual(expectedList[i], resultList[i]);
}
}
[TestMethod]
public void ShouldReturnMonthAndDayWithZeroBeforeNumberWhenNumberHasOneLetter()
{
// given
var formatter = new WorkDaysFormatter();
var expectedList = new List<string>()
{
"01.01",
"02.01",
"03.01"
};
var listOfDaysToFormat = new List<WorkDay>()
{
new WorkDay(new DateTime(2017,01,01)),
new WorkDay(new DateTime(2017,01,02)),
new WorkDay(new DateTime(2017,01,03))
};
// when
var resultList = formatter.WorkDaysToString(listOfDaysToFormat);
// then
for (int i = 0; i < 3; i++)
{
Assert.AreEqual(expectedList[i], resultList[i]);
}
}
[TestMethod]
public void ShouldReturnStringOf4WorkHoursGivenWorkDayAt3Oclock()
{
// given
var formatter = new WorkDaysFormatter();
var workDay = new WorkDay(new DateTime(2017, 01, 01, 15, 0, 0));
var expected = new List<string>()
{
"15:00",
"15:15",
"15:30",
"15:45"
};
// when
var result = formatter.WorkingHoursLeftToString(workDay);
// then
Assert.AreEqual(expected.Count, result.Count);
for (int i = 0; i < expected.Count; i++)
{
Assert.AreEqual(expected[i], result[i]);
}
}
}
}
| 29.12766 | 87 | 0.490504 | [
"MIT"
] | krisSzell/CarWash | CarWash/CarWash.Tests/Core/WorkDaysFormatterTests.cs | 2,740 | C# |
namespace Vwm.RTree.Api.Exceptions
{
public class ForbiddenException: ApiExceptionBase
{
public ForbiddenException(string message)
: base(message, HttpStatusCodes._Forbidden)
{
}
}
}
| 18.909091 | 51 | 0.711538 | [
"MIT"
] | tousekjan/fit-ctu-vwm-rtree | server/Vwm.RTree.Api/Exceptions/ForbiddenException.cs | 210 | C# |
// Programmer: Carl Childers
// Date: 9/25/2017
//
// Handles pausing, and creates an indicator showing exactly when the game will resume after pausing.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Pauser : MonoBehaviour {
public string PauseButton = "Pause";
public string UnpauseButton = "Fire1";
public string FadeInTrigger = "FadeIn";
public string SkipIntroTrigger = "Skip";
public string FadeOutTrigger = "FadeOut";
public string UnpauseWaitTrigger = "ClockStart";
public string SaveButtonName = "Save";
public string TitleSceneName = "TitleScene";
public float UnpauseDelay = 1f;
public Vector2 ItemListTopCenter;
public float ItemHorizontalSpacing = 100;
public float ItemVerticalSpacing = 100;
public int ItemRowSize = 2;
public RectTransform PauseScreen;
public RectTransform UnpauseIndicator;
public Font ItemListFont;
public Color ItemListTextColor = Color.white;
public int ItemListFontSize = 24;
public float ItemListTextSpace = 100;
RectTransform myPauseScreen;
RectTransform myUnpauseIndicator;
bool isPaused;
public bool IsPaused {
get { return isPaused; }
}
bool pausingEnabled = true;
public bool PausingEnabled {
get { return pausingEnabled; }
set { pausingEnabled = value; }
}
float unpauseWaitCounter;
bool exitingGame;
static Pauser thePauser;
GameTosser theTosser;
Dictionary<JuggleObjectType, int> itemsInPlay;
Dictionary<JuggleObjectType, RectTransform> itemDisplays;
[ExecuteInEditMode]
void OnValidate()
{
ItemRowSize = Mathf.Max(1, ItemRowSize);
}
public static Pauser GetPauser()
{
if (thePauser != null)
{
return thePauser;
}
else
{
return GameObject.FindObjectOfType<Pauser>();
}
}
void Awake()
{
thePauser = this;
}
void Update()
{
if (!isPaused)
{
if (Input.GetButtonDown(PauseButton) && CanPause())
{
BeginPause();
}
else
{
// Update unpause delay
if (unpauseWaitCounter > 0)
{
unpauseWaitCounter -= Time.unscaledDeltaTime;
if (unpauseWaitCounter <= 0)
{
// Actually resume the game
Time.timeScale = 1;
if (theTosser != null)
{
theTosser.HideItemTrails();
}
}
}
}
}
else
{
if (Input.GetButtonDown(SaveButtonName))
{
SaveAndQuit();
}
if (Input.GetButtonDown(UnpauseButton))
{
EndPause();
}
}
}
void OnApplicationQuit()
{
exitingGame = true;
}
void OnApplicationFocus(bool hasFocus)
{
if (exitingGame || !CanPause())
return;
if (!hasFocus)
{
BeginPause(true);
}
}
void OnApplicationPause(bool pauseStatus)
{
if (exitingGame || !CanPause())
return;
if (pauseStatus)
{
BeginPause(true);
}
}
public void BeginPause(bool skipIntro = false)
{
if (!isPaused)
{
isPaused = true;
Time.timeScale = 0;
if (myPauseScreen == null)
{
myPauseScreen = Instantiate(PauseScreen);
Canvas theCanvas = GameObject.FindObjectOfType<Canvas>();
if (theCanvas != null)
{
myPauseScreen.SetParent(theCanvas.transform);
myPauseScreen.anchoredPosition = Vector2.zero;
myPauseScreen.localScale = Vector3.one;
}
}
else
{
myPauseScreen.gameObject.SetActive(true);
}
// In case the unpause warning was still playing, cancel it
if (myUnpauseIndicator != null && myUnpauseIndicator.gameObject.activeSelf)
{
myUnpauseIndicator.gameObject.SetActive(false);
}
Animator pauseAnim = myPauseScreen.GetComponent<Animator>();
if (!skipIntro)
{
pauseAnim.SetTrigger(FadeInTrigger);
}
else
{
pauseAnim.SetTrigger(SkipIntroTrigger);
}
InitItemList();
}
}
void InitItemList()
{
// Find tosser and create dictionaries, if necessary
if (theTosser == null)
{
theTosser = GameObject.FindObjectOfType<GameTosser>();
}
if (theTosser == null)
return;
if (itemsInPlay == null)
{
itemsInPlay = new Dictionary<JuggleObjectType, int>();
}
else
{
itemsInPlay.Clear();
}
if (itemDisplays == null)
{
itemDisplays = new Dictionary<JuggleObjectType, RectTransform>();
}
// Find how many of which types are currently in play
foreach (JuggleObject item in theTosser.ObjectsInPlay)
{
if (!itemsInPlay.ContainsKey(item.MyType))
{
itemsInPlay.Add(item.MyType, 1);
}
else
{
itemsInPlay[item.MyType]++;
}
}
// Create a display for each type in play, as needed
foreach (JuggleObjectType itemType in itemsInPlay.Keys)
{
//print(itemsInPlay[itemType] + " " + itemType.SingularName + " in play");
if (!itemDisplays.ContainsKey(itemType))
{
CreateItemDisplay(itemType);
}
}
// Remove displays that are no longer needed
Dictionary<JuggleObjectType, RectTransform> itemDisplaysCopy = new Dictionary<JuggleObjectType, RectTransform>(itemDisplays);
foreach (JuggleObjectType itemType in itemDisplaysCopy.Keys)
{
if (!itemsInPlay.ContainsKey(itemType))
{
GameObject.Destroy(itemDisplays[itemType].gameObject);
itemDisplays.Remove(itemType);
}
}
// Position the displays, and update the item count for each display
int row = 0, col = 0;
int currentRowSize = Mathf.Min(ItemRowSize, itemDisplays.Keys.Count);
int numItemsPositioned = 0;
foreach (JuggleObjectType itemType in itemDisplays.Keys)
{
PositionItemDisplay(itemDisplays[itemType], row, col, currentRowSize);
UpdateItemCount(itemDisplays[itemType], itemsInPlay[itemType]);
numItemsPositioned++;
col++;
if (col >= currentRowSize)
{
row++;
col = 0;
currentRowSize = Mathf.Min(ItemRowSize + (row % 2), itemDisplays.Keys.Count - numItemsPositioned);
}
}
}
void CreateItemDisplay(JuggleObjectType itemType)
{
GameObject newDisplayObj = new GameObject(itemType.SingularName + " display", typeof(RectTransform));
RectTransform newDisplay = newDisplayObj.GetComponent<RectTransform>();
newDisplay.SetParent(myPauseScreen);
newDisplay.localScale = Vector3.one;
itemDisplays.Add(itemType, newDisplay);
// Create the image icon as a child object, so the icon's rotation doesn't interfere with the text.
GameObject itemImageObj = new GameObject("Item Icon", typeof(RectTransform));
RectTransform itemImageTransform = itemImageObj.GetComponent<RectTransform>();
itemImageTransform.SetParent(newDisplay);
itemImageTransform.localScale = Vector3.one;
Image displayImage = itemImageObj.AddComponent<Image>();
displayImage.sprite = itemType.OffScreenSprite;
if (itemType.UseItemColor)
{
displayImage.color = itemType.ItemColor;
}
itemImageTransform.localRotation = Quaternion.Euler(0, 0, itemType.PauseScreenRotation);
// Determine display size of the icon
Vector2 iconSize = new Vector2(itemType.OffScreenSprite.bounds.size.x, itemType.OffScreenSprite.bounds.size.y)
* itemType.OffScreenSprite.pixelsPerUnit;
float greaterSize = Mathf.Max(iconSize.x, iconSize.y);
if (greaterSize > 0)
{
float sizeRatio = itemType.PauseScreenSize / Mathf.Max(iconSize.x, iconSize.y);
itemImageTransform.sizeDelta = iconSize * sizeRatio;
}
}
void PositionItemDisplay(RectTransform inDisplay, int row, int col, int rowSize)
{
Vector2 itemPos = ItemListTopCenter + Vector2.down * row * ItemVerticalSpacing;
itemPos.x += (-(rowSize - 1) / 2f + col) * ItemHorizontalSpacing;
itemPos.x -= ItemListTextSpace / 2f;
inDisplay.anchoredPosition = itemPos;
inDisplay.gameObject.SetActive(true);
}
// Creates a text child for an item display, or retreives it if already there, and updates the item count
void UpdateItemCount(RectTransform inDisplay, int itemCount)
{
Text itemCountText = inDisplay.GetComponentInChildren<Text>();
if (itemCountText == null)
{
GameObject textObj = new GameObject("Item Count", typeof(RectTransform));
itemCountText = textObj.AddComponent<Text>();
itemCountText.font = ItemListFont;
itemCountText.fontSize = ItemListFontSize;
itemCountText.color = ItemListTextColor;
itemCountText.horizontalOverflow = HorizontalWrapMode.Overflow;
itemCountText.verticalOverflow = VerticalWrapMode.Overflow;
itemCountText.alignment = TextAnchor.LowerLeft;
RectTransform textTransform = itemCountText.GetComponent<RectTransform>();
textTransform.SetParent(inDisplay);
textTransform.localScale = Vector3.one;
textTransform.sizeDelta = Vector2.one * ItemListTextSpace;
textTransform.anchoredPosition = new Vector2(inDisplay.sizeDelta.x / 2 + textTransform.sizeDelta.x / 2, 0);
}
itemCountText.text = " x " + itemCount;
}
void EndPause()
{
if (isPaused)
{
isPaused = false;
unpauseWaitCounter = UnpauseDelay;
if (myPauseScreen != null)
{
Animator pauseAnim = myPauseScreen.GetComponent<Animator>();
pauseAnim.SetTrigger(FadeOutTrigger);
}
// Hide item displays before the pause screen fades out
if (itemDisplays != null)
{
foreach (JuggleObjectType itemType in itemDisplays.Keys)
{
itemDisplays[itemType].gameObject.SetActive(false);
}
}
StartUnpauseWarning();
}
}
void StartUnpauseWarning()
{
if (myUnpauseIndicator == null)
{
myUnpauseIndicator = Instantiate(UnpauseIndicator);
Canvas theCanvas = GameObject.FindObjectOfType<Canvas>();
if (theCanvas != null)
{
myUnpauseIndicator.SetParent(theCanvas.transform);
myUnpauseIndicator.anchoredPosition = Vector2.zero;
myUnpauseIndicator.localScale = Vector3.one;
}
}
else
{
myUnpauseIndicator.gameObject.SetActive(true);
}
Animator indicatorAnim = myUnpauseIndicator.GetComponent<Animator>();
indicatorAnim.ResetTrigger(UnpauseWaitTrigger);
indicatorAnim.SetTrigger(UnpauseWaitTrigger);
if (theTosser == null)
{
theTosser = GameObject.FindObjectOfType<GameTosser>();
}
if (theTosser != null)
{
theTosser.ShowItemTrails();
}
}
public float GetTimeTillUnpause()
{
return unpauseWaitCounter;
}
public bool IsPausedOrWaitingToResume()
{
return (isPaused || unpauseWaitCounter > 0);
}
public bool CanPause()
{
if (theTosser == null)
{
theTosser = GameObject.FindObjectOfType<GameTosser>();
}
if (theTosser != null && theTosser.TheJuggler != null)
{
return !theTosser.TheJuggler.InGameOver;
}
else
{
return false;
}
}
void SaveAndQuit()
{
Bookmark.Save();
Time.timeScale = 1;
GameControl.GetGameControl().LoadScene(TitleSceneName);
}
}
| 24.034562 | 127 | 0.712204 | [
"MIT"
] | marooncarl/marooncarl.github.io | MaxJuggle/UI/InGame/Pauser.cs | 10,433 | C# |
using UnityEngine;
using System.Collections.Generic;
public class TwoPlayers : MonoBehaviour
{
public GameObject greySquare;
private float iniXPos;
private float iniYPos;
private void Start()
{
this.iniXPos = -6f;
this.iniYPos = 0.5f;
this.LoadGrid();
}
private void Update()
{
VerifyWinner();
}
private void LoadGrid()
{
for (int l = 0; l < 14; l++)
{
for (int c = 0; c < 14; c++)
{
float x = c * 0.32f;
float y = l * 0.32f;
Vector3 pos = new Vector3(x, y);
var square = Instantiate(greySquare, pos, Quaternion.identity);
square.transform.parent = transform;
}
}
Vector3 position = new Vector3(iniXPos, iniYPos);
transform.position = position;
}
private void VerifyWinner()
{
int blue = 0;
int red = 0;
for (int i = 0; i < transform.childCount; i++)
{
var o = transform.GetChild(i).gameObject;
if (o.CompareTag("Grey"))
{
var color = o.GetComponent<GreySquare>().Color;
if (color.Equals(Commons.Colors.Blue.ToString()))
{
blue++;
}
if (color.Equals(Commons.Colors.Red.ToString()))
{
red++;
}
}
}
}
}
| 22.772727 | 79 | 0.461078 | [
"MIT"
] | HudsonSchumaker/Color-Square | xbox/Assets/Scripts/TwoPlayers.cs | 1,503 | C# |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
using System;
namespace AmplifyShaderEditor
{
[System.Serializable]
[NodeAttributes( "Vector3", "Constants", "Vector3 property", null, KeyCode.Alpha3 )]
public sealed class Vector3Node : PropertyNode
{
[SerializeField]
private Vector3 m_defaultValue = Vector3.zero;
[SerializeField]
private Vector3 m_materialValue = Vector3.zero;
private const float LabelWidth = 8;
private int m_cachedPropertyId = -1;
public Vector3Node() : base() { }
public Vector3Node( int uniqueId, float x, float y, float width, float height ) : base( uniqueId, x, y, width, height ) { }
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
m_insideSize.Set( 50, 30 );
m_selectedLocation = PreviewLocation.BottomCenter;
AddOutputVectorPorts( WirePortDataType.FLOAT3, "XYZ" );
m_precisionString = UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, m_outputPorts[ 0 ].DataType );
m_previewShaderGUID = "8a44d38f06246bf48944b3f314bc7920";
}
public override void CopyDefaultsToMaterial()
{
m_materialValue = m_defaultValue;
}
public override void DrawSubProperties()
{
m_defaultValue = EditorGUILayoutVector3Field( Constants.DefaultValueLabel, m_defaultValue );
}
public override void DrawMaterialProperties()
{
EditorGUI.BeginChangeCheck();
m_materialValue = EditorGUILayoutVector3Field( Constants.MaterialValueLabel, m_materialValue );
if ( EditorGUI.EndChangeCheck() )
{
//MarkForPreviewUpdate();
if ( m_materialMode )
m_requireMaterialUpdate = true;
}
}
public override void SetPreviewInputs()
{
base.SetPreviewInputs();
if ( m_cachedPropertyId == -1 )
m_cachedPropertyId = Shader.PropertyToID( "_InputVector" );
if ( m_materialMode && m_currentParameterType != PropertyType.Constant )
PreviewMaterial.SetVector( m_cachedPropertyId, new Vector4( m_materialValue[ 0 ], m_materialValue[ 1 ], m_materialValue[ 2 ], 0 ) );
else
PreviewMaterial.SetVector( m_cachedPropertyId, new Vector4( m_defaultValue[ 0 ], m_defaultValue[ 1 ], m_defaultValue[ 2 ], 0 ) );
}
public override void Draw( DrawInfo drawInfo )
{
base.Draw( drawInfo );
if ( m_isVisible )
{
m_propertyDrawPos = m_remainingBox;
m_propertyDrawPos.x = m_remainingBox.x - LabelWidth * drawInfo.InvertedZoom;
m_propertyDrawPos.width = drawInfo.InvertedZoom * Constants.FLOAT_DRAW_WIDTH_FIELD_SIZE;
m_propertyDrawPos.height = drawInfo.InvertedZoom * Constants.FLOAT_DRAW_HEIGHT_FIELD_SIZE;
EditorGUI.BeginChangeCheck();
for ( int i = 0; i < 3; i++ )
{
m_propertyDrawPos.y = m_outputPorts[ i + 1 ].Position.y - 2 * drawInfo.InvertedZoom;
if ( m_materialMode && m_currentParameterType != PropertyType.Constant )
{
float val = m_materialValue[ i ];
UIUtils.DrawFloat( this, ref m_propertyDrawPos, ref val, LabelWidth * drawInfo.InvertedZoom );
m_materialValue[ i ] = val;
}
else
{
float val = m_defaultValue[ i ];
UIUtils.DrawFloat( this, ref m_propertyDrawPos, ref val, LabelWidth * drawInfo.InvertedZoom );
m_defaultValue[ i ] = val;
}
}
if ( EditorGUI.EndChangeCheck() )
{
m_requireMaterialUpdate = m_materialMode;
//MarkForPreviewUpdate();
BeginDelayedDirtyProperty();
}
}
}
public override void ConfigureLocalVariable( ref MasterNodeDataCollector dataCollector )
{
Vector3 value = m_defaultValue;
dataCollector.AddLocalVariable( UniqueId, CreateLocalVarDec( value.x + "," + value.y + "," + value.z ) );
m_outputPorts[ 0 ].SetLocalValue( m_propertyName );
m_outputPorts[ 1 ].SetLocalValue( m_propertyName + ".x" );
m_outputPorts[ 2 ].SetLocalValue( m_propertyName + ".y" );
m_outputPorts[ 3 ].SetLocalValue( m_propertyName + ".z" );
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
base.GenerateShaderForOutput( outputId, ref dataCollector, ignoreLocalvar );
m_precisionString = UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, m_outputPorts[ 0 ].DataType );
if ( m_currentParameterType != PropertyType.Constant )
return GetOutputVectorItem( 0, outputId, PropertyData );
if ( m_outputPorts[ outputId ].IsLocalValue )
{
return m_outputPorts[ outputId ].LocalValue;
}
if ( CheckLocalVariable( ref dataCollector ) )
{
return m_outputPorts[ outputId ].LocalValue;
}
Vector3 value = m_defaultValue;
string result = string.Empty;
switch ( outputId )
{
case 0:
{
result = m_precisionString+"(" + value.x + "," + value.y + "," + value.z + ")";
}
break;
case 1:
{
result = value.x.ToString();
}
break;
case 2:
{
result = value.y.ToString();
}
break;
case 3:
{
result = value.z.ToString();
}
break;
}
if ( result.Equals( string.Empty ) )
{
UIUtils.ShowMessage( "Vector3Node generating empty code", MessageSeverity.Warning );
}
return result;
}
public override string GetPropertyValue()
{
return PropertyAttributes + m_propertyName + "(\"" + m_propertyInspectorName + "\", Vector) = (" + m_defaultValue.x + "," + m_defaultValue.y + "," + m_defaultValue.z + ",0)";
}
public override void UpdateMaterial( Material mat )
{
base.UpdateMaterial( mat );
if ( UIUtils.IsProperty( m_currentParameterType ) )
{
mat.SetVector( m_propertyName, m_materialValue );
}
}
public override void SetMaterialMode( Material mat, bool fetchMaterialValues )
{
base.SetMaterialMode( mat , fetchMaterialValues );
if ( fetchMaterialValues && m_materialMode && UIUtils.IsProperty( m_currentParameterType ) && mat.HasProperty( m_propertyName ) )
{
m_materialValue = mat.GetVector( m_propertyName );
}
}
public override void ForceUpdateFromMaterial( Material material )
{
if ( UIUtils.IsProperty( m_currentParameterType ) && material.HasProperty( m_propertyName ) )
m_materialValue = material.GetVector( m_propertyName );
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
string[] components = GetCurrentParam( ref nodeParams ).Split( IOUtils.VECTOR_SEPARATOR );
if ( components.Length == 3 )
{
m_defaultValue.x = Convert.ToSingle( components[ 0 ] );
m_defaultValue.y = Convert.ToSingle( components[ 1 ] );
m_defaultValue.z = Convert.ToSingle( components[ 2 ] );
}
else
{
UIUtils.ShowMessage( "Incorrect number of float3 values", MessageSeverity.Error );
}
}
public override void ReadAdditionalClipboardData( ref string[] nodeParams )
{
base.ReadAdditionalClipboardData( ref nodeParams );
m_materialValue = IOUtils.StringToVector3( GetCurrentParam( ref nodeParams ) );
}
public override void WriteAdditionalClipboardData( ref string nodeInfo )
{
base.WriteAdditionalClipboardData( ref nodeInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, IOUtils.Vector3ToString( m_materialValue ) );
}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, m_defaultValue.x.ToString() + IOUtils.VECTOR_SEPARATOR +
m_defaultValue.y.ToString() + IOUtils.VECTOR_SEPARATOR +
m_defaultValue.z.ToString() );
}
public override string GetPropertyValStr()
{
return ( m_materialMode && m_currentParameterType != PropertyType.Constant ) ? m_materialValue.x.ToString( Mathf.Abs( m_materialValue.x ) > 1000 ? Constants.PropertyBigVectorFormatLabel : Constants.PropertyVectorFormatLabel ) + IOUtils.VECTOR_SEPARATOR +
m_materialValue.y.ToString( Mathf.Abs( m_materialValue.y ) > 1000 ? Constants.PropertyBigVectorFormatLabel : Constants.PropertyVectorFormatLabel ) + IOUtils.VECTOR_SEPARATOR +
m_materialValue.z.ToString( Mathf.Abs( m_materialValue.z ) > 1000 ? Constants.PropertyBigVectorFormatLabel : Constants.PropertyVectorFormatLabel ) :
m_defaultValue.x.ToString( Mathf.Abs( m_defaultValue.x ) > 1000 ? Constants.PropertyBigVectorFormatLabel : Constants.PropertyVectorFormatLabel ) + IOUtils.VECTOR_SEPARATOR +
m_defaultValue.y.ToString( Mathf.Abs( m_defaultValue.y ) > 1000 ? Constants.PropertyBigVectorFormatLabel : Constants.PropertyVectorFormatLabel ) + IOUtils.VECTOR_SEPARATOR +
m_defaultValue.z.ToString( Mathf.Abs( m_defaultValue.z ) > 1000 ? Constants.PropertyBigVectorFormatLabel : Constants.PropertyVectorFormatLabel );
}
public Vector3 Value
{
get { return m_defaultValue; }
set { m_defaultValue = value; }
}
}
}
| 35.358268 | 257 | 0.708607 | [
"MIT"
] | affloeck/Vanish | Assets/Plugins/AmplifyShaderEditor/Plugins/Editor/Nodes/Constants/Vector3Node.cs | 8,981 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace Heavylink.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
} | 47.204955 | 229 | 0.586431 | [
"MIT"
] | ognjengt/heavylink | Heavylink/Heavylink/Areas/HelpPage/SampleGeneration/HelpPageSampleGenerator.cs | 20,959 | C# |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos.Query
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos;
using Microsoft.Azure.Documents;
using Newtonsoft.Json;
/// <summary>
/// This class is used as a proxy to wrap the DefaultDocumentQueryExecutionContext which is needed
/// for sending the query to Gateway first and then uses PipelinedDocumentQueryExecutionContext after
/// it gets the necessary info. This has been added since we
/// haven't produced Linux/Mac version of the ServiceInterop native binary which holds the logic for
/// parsing the query without having this extra hop to Gateway
/// </summary>
internal sealed class CosmosProxyItemQueryExecutionContext : CosmosQueryExecutionContext
{
private CosmosQueryExecutionContext innerExecutionContext;
private CosmosQueryContext queryContext;
private readonly CosmosContainerSettings containerSettings;
public CosmosProxyItemQueryExecutionContext(
CosmosQueryContext queryContext,
CosmosContainerSettings containerSettings)
{
if (queryContext == null)
{
throw new ArgumentNullException(nameof(queryContext));
}
if (queryContext == null)
{
throw new ArgumentNullException(nameof(queryContext));
}
this.innerExecutionContext = new CosmosGatewayQueryExecutionContext(queryContext);
this.queryContext = queryContext;
this.containerSettings = containerSettings;
}
public override bool IsDone => this.innerExecutionContext.IsDone;
public override void Dispose()
{
this.innerExecutionContext.Dispose();
}
public override async Task<CosmosQueryResponse> ExecuteNextAsync(CancellationToken token)
{
if (this.IsDone)
{
throw new InvalidOperationException(RMResources.DocumentQueryExecutionContextIsDone);
}
CosmosQueryResponse response = await this.innerExecutionContext.ExecuteNextAsync(token);
// If the query failed because of cross partition query not servable then parse the query plan that is returned in the error
// and create the correct context to execute it. For all other responses just return it since there is no query plan to parse.
if (response.StatusCode != HttpStatusCode.BadRequest || response.Headers.SubStatusCode != SubStatusCodes.CrossPartitionQueryNotServable)
{
return response;
}
PartitionedQueryExecutionInfo partitionedQueryExecutionInfo =
JsonConvert.DeserializeObject<PartitionedQueryExecutionInfo>(response.Error.AdditionalErrorInfo);
string rewrittenQuery = partitionedQueryExecutionInfo.QueryInfo.RewrittenQuery;
if (!string.IsNullOrEmpty(rewrittenQuery))
{
this.queryContext.SqlQuerySpec.QueryText = rewrittenQuery;
}
List<PartitionKeyRange> partitionKeyRanges =
await this.queryContext.QueryClient.GetTargetPartitionKeyRanges(
this.queryContext.ResourceLink.OriginalString,
this.containerSettings.ResourceId,
partitionedQueryExecutionInfo.QueryRanges);
this.innerExecutionContext = await CosmosQueryExecutionContextFactory.CreateSpecializedDocumentQueryExecutionContext(
this.queryContext,
partitionedQueryExecutionInfo,
partitionKeyRanges,
this.containerSettings.ResourceId,
token);
return await this.innerExecutionContext.ExecuteNextAsync(token);
}
}
}
| 42 | 148 | 0.65379 | [
"MIT"
] | JohnLTaylor/azure-cosmos-dotnet-v3 | Microsoft.Azure.Cosmos/src/Query/CosmosProxyItemQueryExecutionContext.cs | 4,118 | C# |
namespace Laba_graphic_10
{
partial class Form1
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором форм Windows
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.button1 = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// pictureBox1
//
this.pictureBox1.Location = new System.Drawing.Point(12, 12);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(906, 562);
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
//
// button1
//
this.button1.Location = new System.Drawing.Point(265, 604);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(282, 29);
this.button1.TabIndex = 1;
this.button1.Text = "Нарисовать";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(936, 645);
this.Controls.Add(this.button1);
this.Controls.Add(this.pictureBox1);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Button button1;
}
}
| 37.28 | 110 | 0.557225 | [
"MIT"
] | IlonaZellka/DonNU | course_2/computer_graphics/Laba_graphic_10/Laba_graphic_10/Form1.Designer.cs | 3,063 | C# |
namespace MathCore.Monads.WorkFlow
{
/// <summary>Работа, возвращающая указанное константное значение</summary>
/// <typeparam name="T">Тип возвращаемого работой значения</typeparam>
public class ConstValueWork<T> : Work<T>
{
/// <summary>Значение, возвращаемое работой</summary>
public T Value { get; set; }
/// <summary>Инициализация новой работы, возвращающей константное значение</summary>
/// <param name="Value">Значение, которое будет возвращать работа</param>
/// <param name="BaseWork">Базовая работа</param>
internal ConstValueWork(T Value, Work BaseWork = null) : base(BaseWork) => this.Value = Value;
/// <inheritdoc />
protected override IWorkResult Execute(IWorkResult BaseResult) => new WorkResult<T>(Value, BaseResult?.Error);
}
} | 46.277778 | 118 | 0.677071 | [
"MIT"
] | Infarh/MathCore | MathCore/Monads/WorkFlow/ConstValueWork.cs | 1,043 | C# |
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
namespace XLua.CSObjectWrap
{
using Utils = XLua.Utils;
public class SpineSkinAttachmentKeyTupleWrap
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
System.Type type = typeof(Spine.Skin.AttachmentKeyTuple);
Utils.BeginObjectRegister(type, L, translator, 0, 0, 2, 0);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "slotIndex", _g_get_slotIndex);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "name", _g_get_name);
Utils.EndObjectRegister(type, L, translator, null, null,
null, null, null);
Utils.BeginClassRegister(type, L, __CreateInstance, 1, 0, 0);
Utils.EndClassRegister(type, L, translator);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __CreateInstance(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
if(LuaAPI.lua_gettop(L) == 3 && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 2) && (LuaAPI.lua_isnil(L, 3) || LuaAPI.lua_type(L, 3) == LuaTypes.LUA_TSTRING))
{
int _slotIndex = LuaAPI.xlua_tointeger(L, 2);
string _name = LuaAPI.lua_tostring(L, 3);
Spine.Skin.AttachmentKeyTuple gen_ret = new Spine.Skin.AttachmentKeyTuple(_slotIndex, _name);
translator.Push(L, gen_ret);
return 1;
}
if (LuaAPI.lua_gettop(L) == 1)
{
translator.Push(L, default(Spine.Skin.AttachmentKeyTuple));
return 1;
}
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to Spine.Skin.AttachmentKeyTuple constructor!");
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_slotIndex(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Spine.Skin.AttachmentKeyTuple gen_to_be_invoked;translator.Get(L, 1, out gen_to_be_invoked);
LuaAPI.xlua_pushinteger(L, gen_to_be_invoked.slotIndex);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_name(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Spine.Skin.AttachmentKeyTuple gen_to_be_invoked;translator.Get(L, 1, out gen_to_be_invoked);
LuaAPI.lua_pushstring(L, gen_to_be_invoked.name);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
}
}
| 28.081301 | 159 | 0.607122 | [
"BSD-3-Clause"
] | doupihule/gameDemo | Assets/XLua/Gen/SpineSkinAttachmentKeyTupleWrap.cs | 3,456 | C# |
using System;
using Newtonsoft.Json;
namespace RavenNest.BusinessLogic.Patreon
{
internal class TypeEnumConverter : JsonConverter
{
public override bool CanConvert(Type t) => t == typeof(TypeEnum) || t == typeof(TypeEnum?);
public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null) return null;
var value = serializer.Deserialize<string>(reader);
switch (value)
{
case "campaign":
return TypeEnum.Campaign;
case "goal":
return TypeEnum.Goal;
case "reward":
return TypeEnum.Reward;
case "user":
return TypeEnum.User;
}
throw new Exception("Cannot unmarshal type TypeEnum");
}
public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
{
if (untypedValue == null)
{
serializer.Serialize(writer, null);
return;
}
var value = (TypeEnum)untypedValue;
switch (value)
{
case TypeEnum.Campaign:
serializer.Serialize(writer, "campaign");
return;
case TypeEnum.Goal:
serializer.Serialize(writer, "goal");
return;
case TypeEnum.Reward:
serializer.Serialize(writer, "reward");
return;
case TypeEnum.User:
serializer.Serialize(writer, "user");
return;
}
throw new Exception("Cannot marshal type TypeEnum");
}
public static readonly TypeEnumConverter Singleton = new TypeEnumConverter();
}
}
| 33.775862 | 115 | 0.520163 | [
"MIT"
] | zerratar/RavenNest | src/RavenNest.BusinessLogic/Patreon/TypeEnumConverter.cs | 1,961 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WFA_Kalitim
{
class IPhone :MobilePhone
{
public byte KameraSayisi { get; set; }
public byte KameraMP { get; set; }
}
}
| 18.5 | 47 | 0.621622 | [
"MIT"
] | BercKoskun/CSharpBilge | OOP/30.01/WFA_Kalitim/WFA_Kalitim/IPhone.cs | 335 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Concurrency.Models
{
public class ConcurrentAccountWithToken : BankAccount
{
}
}
| 15.636364 | 57 | 0.75 | [
"MIT"
] | priyank89patel/EFCore_Concurrency | src/Concurrency/Concurrency/Models/ConcurrentAccountWithToken.cs | 174 | C# |
// (c) 2021 Francesco Del Re <francesco.delre.87@gmail.com>
// This code is licensed under MIT license (see LICENSE.txt for details)
using SharpSanitizer.Entity;
using SharpSanitizer.Enum;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
namespace SharpSanitizer
{
public sealed class SharpSanitizer<T> : ISharpSanitizer<T>
{
private readonly Dictionary<string, Constraint> _propertiesConstraints;
public SharpSanitizer(Dictionary<string, Constraint> propertiesConstraints)
{
_propertiesConstraints = propertiesConstraints;
}
/// <summary>
/// Sanitizes the properties of the object.
/// </summary>
/// <param name="obj">The object to be sanitized</param>
public void Sanitize(T obj)
{
if (obj == null) return;
PropertyInfo[] properties = obj.GetType().GetProperties();
foreach (PropertyInfo pi in properties)
{
var constraintFound = _propertiesConstraints.TryGetValue(pi.Name, out Constraint constraint);
if (!constraintFound) continue;
var propertyValue = pi.GetValue(obj, null);
var propertyType = Type.GetTypeCode(pi.PropertyType);
switch (propertyType)
{
case TypeCode.String:
{
var propertyValueSanitize = ApplyStringConstraint(propertyValue?.ToString(), constraint);
pi.SetValue(obj, propertyValueSanitize);
break;
}
case TypeCode.Empty:
break;
case TypeCode.Object:
{
var propertyValueSanitize = Activator.CreateInstance(pi.PropertyType);
pi.SetValue(obj, propertyValueSanitize);
break;
}
case TypeCode.DBNull:
break;
case TypeCode.Boolean:
break;
case TypeCode.Char:
break;
case TypeCode.SByte:
break;
case TypeCode.Byte:
break;
case TypeCode.Int16:
{
var propertyValueSanitize = ApplyIntegerConstraint((int)propertyValue, constraint);
pi.SetValue(obj, propertyValueSanitize);
break;
}
case TypeCode.UInt16:
break;
case TypeCode.Int32:
{
var propertyValueSanitize = ApplyIntegerConstraint((int)propertyValue, constraint);
pi.SetValue(obj, propertyValueSanitize);
break;
}
case TypeCode.UInt32:
break;
case TypeCode.Int64:
break;
case TypeCode.UInt64:
break;
case TypeCode.Single:
break;
case TypeCode.Double:
break;
case TypeCode.Decimal:
break;
case TypeCode.DateTime:
break;
}
}
}
/// <summary>
/// Sanitizes the properties of objects within the list.
/// </summary>
/// <param name="list">The list to be sanitized</param>
public void Sanitize(IEnumerable<T> list)
{
foreach (var obj in list)
{
Sanitize(obj);
}
}
/// <summary>
/// Apply the current constraint to the string property.
/// </summary>
/// <param name="propertyValue">The original property value.</param>
/// <param name="constraint">The constraint configuration.</param>
/// <returns></returns>
private static string ApplyStringConstraint(string propertyValue, Constraint constraint)
{
switch (constraint.ConstraintType)
{
case ConstraintType.NotNull:
return propertyValue?.Trim() ?? string.Empty;
case ConstraintType.Max:
{
var integerRefValue = constraint.ConstraintValue.IntegerValue;
var trimString = propertyValue?.Trim();
return trimString?.Length <= integerRefValue
? trimString : trimString?.Substring(0, integerRefValue);
}
case ConstraintType.MaxNotNull:
{
var integerRefValue = constraint.ConstraintValue.IntegerValue;
if (propertyValue == null) return string.Empty;
var trimString = propertyValue?.Trim();
return trimString?.Length <= integerRefValue
? trimString : trimString?.Substring(0, integerRefValue);
}
case ConstraintType.Lowercase:
{
if (propertyValue == null) return string.Empty;
return propertyValue?.Trim().ToLowerInvariant();
}
case ConstraintType.Uppercase:
{
if (propertyValue == null) return string.Empty;
return propertyValue?.Trim().ToUpperInvariant();
}
case ConstraintType.NoWhiteSpace:
{
if (propertyValue == null) return string.Empty;
return Regex.Replace(propertyValue, @"\s+", ""); ;
}
case ConstraintType.NoSpecialCharacters:
{
if (propertyValue == null) return string.Empty;
return Regex.Replace(propertyValue, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
}
default:
return propertyValue?.Trim();
}
}
/// <summary>
/// Apply the current constraint to the integer property.
/// </summary>
/// <param name="propertyValue">The original property value.</param>
/// <param name="constraint">The constraint configuration.</param>
/// <returns></returns>
private static int ApplyIntegerConstraint(int propertyValue, Constraint constraint)
{
var integerRefValue = constraint.ConstraintValue.IntegerValue;
switch (constraint.ConstraintType)
{
case ConstraintType.Min:
{
return propertyValue > integerRefValue ? integerRefValue : propertyValue;
}
case ConstraintType.Max:
{
return propertyValue > integerRefValue ? integerRefValue : propertyValue;
}
case ConstraintType.NotNegative:
{
return propertyValue < 0 ? integerRefValue : propertyValue;
}
default:
return propertyValue;
}
}
}
}
| 40.793651 | 117 | 0.479507 | [
"MIT"
] | engineering87/SharpSanitizer | src/SharpSanitizer/SharpSanitizer.cs | 7,712 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IvyFEM
{
public class TetrahedronFEEdge2ndInterpolate : IEdgeInterpolate3D
{
public TetrahedronFE Owner { get; set; }
public TetrahedronFEEdge2ndInterpolate()
{
}
public TetrahedronFEEdge2ndInterpolate(TetrahedronFE owner)
{
Owner = owner;
}
public uint GetNodeCount()
{
// 10の頂点
return 10;
}
public uint GetEdgeCount()
{
// 20の辺
return 20;
}
public double[] GetNodeL(int nodeId)
{
throw new NotImplementedException();
}
public double[] CalcN(double[] L)
{
throw new NotImplementedException();
}
public double[][] CalcNu(double[] L)
{
throw new NotImplementedException();
}
public double[,][] CalcNuv(double[] L)
{
throw new NotImplementedException();
}
public double[] CalcSN()
{
throw new NotImplementedException();
}
public double[,] CalcSNN()
{
throw new NotImplementedException();
}
public double[,][,] CalcSNuNv()
{
throw new NotImplementedException();
}
public double[][,] CalcSNuN()
{
throw new NotImplementedException();
}
public int[][] GetEdgePointIdss()
{
const int faceCnt = 4;
int[][] facePtNo = new int[faceCnt][]
{
new int[] { 1, 2, 3 },
new int[] { 0, 2, 3 },
new int[] { 0, 1, 3 },
new int[] { 0, 1, 2 }
};
IList<int>[] vNoss = new List<int>[faceCnt];
for (int iface = 0; iface < faceCnt; iface++)
{
var list = new List<KeyValuePair<int, int>>();
for (int i = 0; i < 3; i++)
{
int ptNo = facePtNo[iface][i];
list.Add(new KeyValuePair<int, int>(Owner.VertexCoordIds[ptNo], ptNo));
}
list.Sort((a, b) =>
{
double diff = a.Key - b.Key;
if (diff > 0)
{
return 1;
}
else if (diff < 0)
{
return -1;
}
return 0;
});
IList<int> vNos = new List<int>();
vNoss[iface] = vNos;
foreach (var pair in list)
{
int coId = pair.Key;
int vNo = pair.Value;
vNos.Add(vNo);
}
}
int[][] edgePointId = new int[20][]
{
new int[]{ 0, 4 },
new int[]{ 1, 4 },
new int[]{ 0, 6 },
new int[]{ 2, 6 },
new int[]{ 0, 7 },
new int[]{ 3, 7 },
new int[]{ 1, 5 },
new int[]{ 2, 5 },
new int[]{ 3, 8 },
new int[]{ 1, 8 },
new int[]{ 2, 9 },
new int[]{ 3, 9 },
null,
null,
null,
null,
null,
null,
null,
null
};
{
int iface = 0;
var vNos = vNoss[iface];
for (int eIndex = 12; eIndex < 14; eIndex++)
{
int vNo = vNos[eIndex - 12];
int[] pointIds = null;
if (vNo == 1)
{
pointIds = new int[] { 9, 1 };
}
else if (vNo == 2)
{
pointIds = new int[] { 8, 2 };
}
else if (vNo == 3)
{
pointIds = new int[] { 5, 3 };
}
else
{
System.Diagnostics.Debug.Assert(false);
}
edgePointId[eIndex] = pointIds;
}
}
{
int iface = 1;
var vNos = vNoss[iface];
for (int eIndex = 14; eIndex < 16; eIndex++)
{
int vNo = vNos[eIndex - 14];
int[] pointIds = null;
if (vNo == 0)
{
pointIds = new int[] { 9, 0 };
}
else if (vNo == 2)
{
pointIds = new int[] { 7, 2 };
}
else if (vNo == 3)
{
pointIds = new int[] { 6, 3 };
}
else
{
System.Diagnostics.Debug.Assert(false);
}
edgePointId[eIndex] = pointIds;
}
}
{
int iface = 2;
var vNos = vNoss[iface];
for (int eIndex = 16; eIndex < 18; eIndex++)
{
int vNo = vNos[eIndex - 16];
int[] pointIds = null;
if (vNo == 0)
{
pointIds = new int[] { 8, 0 };
}
else if (vNo == 1)
{
pointIds = new int[] { 7, 1 };
}
else if (vNo == 3)
{
pointIds = new int[] { 4, 3 };
}
else
{
System.Diagnostics.Debug.Assert(false);
}
edgePointId[eIndex] = pointIds;
}
}
{
int iface = 3;
var vNos = vNoss[iface];
for (int eIndex = 18; eIndex < 20; eIndex++)
{
int vNo = vNos[eIndex - 18];
int[] pointIds = null;
if (vNo == 0)
{
pointIds = new int[] { 5, 0 };
}
else if (vNo == 1)
{
pointIds = new int[] { 6, 1 };
}
else if (vNo == 2)
{
pointIds = new int[] { 4, 2 };
}
else
{
System.Diagnostics.Debug.Assert(false);
}
edgePointId[eIndex] = pointIds;
}
}
return edgePointId;
}
private int[][] GetLongEdgePointIdss()
{
int[][] edgePointId = new int[6][]
{
new int[]{ 0, 1 },
new int[]{ 0, 2 },
new int[]{ 0, 3 },
new int[]{ 1, 2 },
new int[]{ 3, 1 },
new int[]{ 2, 3 }
};
return edgePointId;
}
private void CalcLens(out double[] lens)
{
int[][] longEdgePointId = GetLongEdgePointIdss();
lens = new double[6];
for (int eIndex = 0; eIndex < 6; eIndex++)
{
int[] edgePointId1 = longEdgePointId[eIndex];
int iPtId = edgePointId1[0];
int jPtId = edgePointId1[1];
int coId1 = Owner.VertexCoordIds[iPtId];
int coId2 = Owner.VertexCoordIds[jPtId];
double[] co1 = Owner.World.GetCoord((uint)Owner.QuantityId, coId1);
double[] co2 = Owner.World.GetCoord((uint)Owner.QuantityId, coId2);
lens[eIndex] = Math.Sqrt(
(co2[0] - co1[0]) * (co2[0] - co1[0]) +
(co2[1] - co1[1]) * (co2[1] - co1[1]) +
(co2[2] - co1[2]) * (co2[2] - co1[2]));
}
}
private void CalcGradLs(
double[] a, double[] b, double[]c, double[] d,
out double[][] gradLs)
{
gradLs = new double[4][];
for (int i = 0; i < 3; i++)
{
double[] gradL = new double[3];
gradLs[i] = gradL;
gradL[0] = b[i];
gradL[1] = c[i];
gradL[2] = d[i];
}
{
int i = 3;
double[] gradL = new double[3];
gradLs[i] = gradL;
for (int idim = 0; idim < 3; idim++)
{
double[] gradL0 = gradLs[0];
double[] gradL1 = gradLs[1];
double[] gradL2 = gradLs[2];
gradL[idim] = -gradL0[idim] - gradL1[idim] - gradL2[idim];
}
}
}
// gradLを使う
// FIXME: 三角形要素と整合した規格化の実施
private void CalcNVecss(
double[][] gradLs,
out OpenTK.Vector3d[][] nVecss)
{
var gradL1Vec = new OpenTK.Vector3d(gradLs[0][0], gradLs[0][1], gradLs[0][2]);
var gradL2Vec = new OpenTK.Vector3d(gradLs[1][0], gradLs[1][1], gradLs[1][2]);
var gradL3Vec = new OpenTK.Vector3d(gradLs[2][0], gradLs[2][1], gradLs[2][2]);
var gradL4Vec = new OpenTK.Vector3d(gradLs[3][0], gradLs[3][1], gradLs[3][2]);
nVecss = new OpenTK.Vector3d[4][];
{
int iface = 0;
var n2 = new OpenTK.Vector3d(gradL2Vec);
var n3 = new OpenTK.Vector3d(gradL3Vec);
var n4 = new OpenTK.Vector3d(gradL4Vec);
nVecss[iface] = new OpenTK.Vector3d[] { n2, n3, n4 };
}
{
int iface = 1;
var n1 = new OpenTK.Vector3d(gradL1Vec);
var n3 = new OpenTK.Vector3d(gradL3Vec);
var n4 = new OpenTK.Vector3d(gradL4Vec);
nVecss[iface] = new OpenTK.Vector3d[] { n1, n3, n4 };
}
{
int iface = 2;
var n1 = new OpenTK.Vector3d(gradL1Vec);
var n2 = new OpenTK.Vector3d(gradL2Vec);
var n4 = new OpenTK.Vector3d(gradL4Vec);
nVecss[iface] = new OpenTK.Vector3d[] { n1, n2, n4 };
}
{
int iface = 3;
var n1 = new OpenTK.Vector3d(gradL1Vec);
var n2 = new OpenTK.Vector3d(gradL2Vec);
var n3 = new OpenTK.Vector3d(gradL3Vec);
nVecss[iface] = new OpenTK.Vector3d[] { n1, n2, n3 };
}
}
public double[][] CalcEdgeN(double[] L)
{
double[][] edgeNs = new double[20][];
double[] a;
double[] b;
double[] c;
double[] d;
Owner.CalcTransMatrix(out a, out b, out c, out d);
int[][] edgePointId = GetEdgePointIdss();
double[] lens;
CalcLens(out lens);
double[][] gradLs;
CalcGradLs(a, b, c, d, out gradLs);
OpenTK.Vector3d[][] nVecss;
CalcNVecss(gradLs, out nVecss);
{
int eIndex = 0;
double[] edgeN = new double[3];
edgeNs[eIndex] = edgeN;
for (int idim = 0; idim < 3; idim++)
{
edgeN[idim] = lens[0] * L[0] * gradLs[1][idim];
}
}
{
int eIndex = 1;
double[] edgeN = new double[3];
edgeNs[eIndex] = edgeN;
for (int idim = 0; idim < 3; idim++)
{
edgeN[idim] = lens[0] * L[1] * gradLs[0][idim];
}
}
{
int eIndex = 2;
double[] edgeN = new double[3];
edgeNs[eIndex] = edgeN;
for (int idim = 0; idim < 3; idim++)
{
edgeN[idim] = lens[1] * L[0] * gradLs[2][idim];
}
}
{
int eIndex = 3;
double[] edgeN = new double[3];
edgeNs[eIndex] = edgeN;
for (int idim = 0; idim < 3; idim++)
{
edgeN[idim] = lens[1] * L[2] * gradLs[0][idim];
}
}
{
int eIndex = 4;
double[] edgeN = new double[3];
edgeNs[eIndex] = edgeN;
for (int idim = 0; idim < 3; idim++)
{
edgeN[idim] = lens[2] * L[0] * gradLs[3][idim];
}
}
{
int eIndex = 5;
double[] edgeN = new double[3];
edgeNs[eIndex] = edgeN;
for (int idim = 0; idim < 3; idim++)
{
edgeN[idim] = lens[2] * L[3] * gradLs[0][idim];
}
}
{
int eIndex = 6;
double[] edgeN = new double[3];
edgeNs[eIndex] = edgeN;
for (int idim = 0; idim < 3; idim++)
{
edgeN[idim] = lens[3] * L[1] * gradLs[2][idim];
}
}
{
int eIndex = 7;
double[] edgeN = new double[3];
edgeNs[eIndex] = edgeN;
for (int idim = 0; idim < 3; idim++)
{
edgeN[idim] = lens[3] * L[2] * gradLs[1][idim];
}
}
{
int eIndex = 8;
double[] edgeN = new double[3];
edgeNs[eIndex] = edgeN;
for (int idim = 0; idim < 3; idim++)
{
edgeN[idim] = lens[4] * L[3] * gradLs[1][idim];
}
}
{
int eIndex = 9;
double[] edgeN = new double[3];
edgeNs[eIndex] = edgeN;
for (int idim = 0; idim < 3; idim++)
{
edgeN[idim] = lens[4] * L[1] * gradLs[3][idim];
}
}
{
int eIndex = 10;
double[] edgeN = new double[3];
edgeNs[eIndex] = edgeN;
for (int idim = 0; idim < 3; idim++)
{
edgeN[idim] = lens[5] * L[2] * gradLs[3][idim];
}
}
{
int eIndex = 11;
double[] edgeN = new double[3];
edgeNs[eIndex] = edgeN;
for (int idim = 0; idim < 3; idim++)
{
edgeN[idim] = lens[5] * L[3] * gradLs[2][idim];
}
}
{
for (int iVNo = 0; iVNo < 2; iVNo++)
{
int eIndex = 12 + iVNo;
int vIndex = edgePointId[eIndex][1];
System.Diagnostics.Debug.Assert(vIndex >= 0 && vIndex < 4);
double[] edgeN = new double[3];
edgeNs[eIndex] = edgeN;
int iface = 0;
double[] n2 = new double[] { nVecss[iface][0].X, nVecss[iface][0].Y, nVecss[iface][0].Z };
double[] n3 = new double[] { nVecss[iface][1].X, nVecss[iface][1].Y, nVecss[iface][1].Z };
double[] n4 = new double[] { nVecss[iface][2].X, nVecss[iface][2].Y, nVecss[iface][2].Z };
for (int idim = 0; idim < 3; idim++)
{
if (vIndex == 1)
{
edgeN[idim] = 4.0 * L[2] * L[3] * n2[idim];
}
else if (vIndex == 2)
{
edgeN[idim] = 4.0 * L[1] * L[3] * n3[idim];
}
else if (vIndex == 3)
{
edgeN[idim] = 4.0 * L[1] * L[2] * n4[idim];
}
else
{
System.Diagnostics.Debug.Assert(false);
}
}
}
}
{
for (int iVNo = 0; iVNo < 2; iVNo++)
{
int eIndex = 14 + iVNo;
int vIndex = edgePointId[eIndex][1];
System.Diagnostics.Debug.Assert(vIndex >= 0 && vIndex < 4);
double[] edgeN = new double[3];
edgeNs[eIndex] = edgeN;
int iface = 1;
double[] n1 = new double[] { nVecss[iface][0].X, nVecss[iface][0].Y, nVecss[iface][0].Z };
double[] n3 = new double[] { nVecss[iface][1].X, nVecss[iface][1].Y, nVecss[iface][1].Z };
double[] n4 = new double[] { nVecss[iface][2].X, nVecss[iface][2].Y, nVecss[iface][2].Z };
for (int idim = 0; idim < 3; idim++)
{
if (vIndex == 0)
{
edgeN[idim] = 4.0 * L[2] * L[3] * n1[idim];
}
else if (vIndex == 2)
{
edgeN[idim] = 4.0 * L[0] * L[3] * n3[idim];
}
else if (vIndex == 3)
{
edgeN[idim] = 4.0 * L[0] * L[2] * n4[idim];
}
else
{
System.Diagnostics.Debug.Assert(false);
}
}
}
}
{
for (int iVNo = 0; iVNo < 2; iVNo++)
{
int eIndex = 16 + iVNo;
int vIndex = edgePointId[eIndex][1];
System.Diagnostics.Debug.Assert(vIndex >= 0 && vIndex < 4);
double[] edgeN = new double[3];
edgeNs[eIndex] = edgeN;
int iface = 2;
double[] n1 = new double[] { nVecss[iface][0].X, nVecss[iface][0].Y, nVecss[iface][0].Z };
double[] n2 = new double[] { nVecss[iface][1].X, nVecss[iface][1].Y, nVecss[iface][1].Z };
double[] n4 = new double[] { nVecss[iface][2].X, nVecss[iface][2].Y, nVecss[iface][2].Z };
for (int idim = 0; idim < 3; idim++)
{
if (vIndex == 0)
{
edgeN[idim] = 4.0 * L[1] * L[3] * n1[idim];
}
else if (vIndex == 1)
{
edgeN[idim] = 4.0 * L[0] * L[3] * n2[idim];
}
else if (vIndex == 3)
{
edgeN[idim] = 4.0 * L[0] * L[1] * n4[idim];
}
else
{
System.Diagnostics.Debug.Assert(false);
}
}
}
}
{
for (int iVNo = 0; iVNo < 2; iVNo++)
{
int eIndex = 18 + iVNo;
int vIndex = edgePointId[eIndex][1];
System.Diagnostics.Debug.Assert(vIndex >= 0 && vIndex < 4);
double[] edgeN = new double[3];
edgeNs[eIndex] = edgeN;
int iface = 3;
double[] n1 = new double[] { nVecss[iface][0].X, nVecss[iface][0].Y, nVecss[iface][0].Z };
double[] n2 = new double[] { nVecss[iface][1].X, nVecss[iface][1].Y, nVecss[iface][1].Z };
double[] n3 = new double[] { nVecss[iface][2].X, nVecss[iface][2].Y, nVecss[iface][2].Z };
for (int idim = 0; idim < 3; idim++)
{
if (vIndex == 0)
{
edgeN[idim] = 4.0 * L[1] * L[2] * n1[idim];
}
else if (vIndex == 1)
{
edgeN[idim] = 4.0 * L[0] * L[2] * n2[idim];
}
else if (vIndex == 2)
{
edgeN[idim] = 4.0 * L[0] * L[1] * n3[idim];
}
else
{
System.Diagnostics.Debug.Assert(false);
}
}
}
}
return edgeNs;
}
public double[][] CalcRotEdgeN(double[] L)
{
double[][] rotEdgeNs = new double[20][];
double[] a;
double[] b;
double[] c;
double[] d;
Owner.CalcTransMatrix(out a, out b, out c, out d);
int[][] edgePointId = GetEdgePointIdss();
double[] lens;
CalcLens(out lens);
double[][] gradLs;
CalcGradLs(a, b, c, d, out gradLs);
OpenTK.Vector3d[][] nVecss;
CalcNVecss(gradLs, out nVecss);
{
int eIndex = 0;
int iPt1 = 0;
int iPt2 = 1;
OpenTK.Vector3d gradLVec1 = new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
OpenTK.Vector3d gradLVec2 = new OpenTK.Vector3d(gradLs[iPt2][0], gradLs[iPt2][1], gradLs[iPt2][2]);
var gradL1xgrapdL2Vec = OpenTK.Vector3d.Cross(gradLVec1, gradLVec2);
double[] gradL1xgradL2 = { gradL1xgrapdL2Vec.X, gradL1xgrapdL2Vec.Y, gradL1xgrapdL2Vec.Z };
double[] rotEdgeN = new double[3];
rotEdgeNs[eIndex] = rotEdgeN;
for (int idim = 0; idim < 3; idim++)
{
rotEdgeN[idim] = lens[0] * gradL1xgradL2[idim];
}
}
{
int eIndex = 1;
int iPt1 = 1;
int iPt2 = 0;
OpenTK.Vector3d gradLVec1 = new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
OpenTK.Vector3d gradLVec2 = new OpenTK.Vector3d(gradLs[iPt2][0], gradLs[iPt2][1], gradLs[iPt2][2]);
var gradL1xgrapdL2Vec = OpenTK.Vector3d.Cross(gradLVec1, gradLVec2);
double[] gradL1xgradL2 = { gradL1xgrapdL2Vec.X, gradL1xgrapdL2Vec.Y, gradL1xgrapdL2Vec.Z };
double[] rotEdgeN = new double[3];
rotEdgeNs[eIndex] = rotEdgeN;
for (int idim = 0; idim < 3; idim++)
{
rotEdgeN[idim] = lens[0] * gradL1xgradL2[idim];
}
}
{
int eIndex = 2;
int iPt1 = 0;
int iPt2 = 2;
OpenTK.Vector3d gradLVec1 = new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
OpenTK.Vector3d gradLVec2 = new OpenTK.Vector3d(gradLs[iPt2][0], gradLs[iPt2][1], gradLs[iPt2][2]);
var gradL1xgrapdL2Vec = OpenTK.Vector3d.Cross(gradLVec1, gradLVec2);
double[] gradL1xgradL2 = { gradL1xgrapdL2Vec.X, gradL1xgrapdL2Vec.Y, gradL1xgrapdL2Vec.Z };
double[] rotEdgeN = new double[3];
rotEdgeNs[eIndex] = rotEdgeN;
for (int idim = 0; idim < 3; idim++)
{
rotEdgeN[idim] = lens[1] * gradL1xgradL2[idim];
}
}
{
int eIndex = 3;
int iPt1 = 2;
int iPt2 = 0;
OpenTK.Vector3d gradLVec1 = new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
OpenTK.Vector3d gradLVec2 = new OpenTK.Vector3d(gradLs[iPt2][0], gradLs[iPt2][1], gradLs[iPt2][2]);
var gradL1xgrapdL2Vec = OpenTK.Vector3d.Cross(gradLVec1, gradLVec2);
double[] gradL1xgradL2 = { gradL1xgrapdL2Vec.X, gradL1xgrapdL2Vec.Y, gradL1xgrapdL2Vec.Z };
double[] rotEdgeN = new double[3];
rotEdgeNs[eIndex] = rotEdgeN;
for (int idim = 0; idim < 3; idim++)
{
rotEdgeN[idim] = lens[1] * gradL1xgradL2[idim];
}
}
{
int eIndex = 4;
int iPt1 = 0;
int iPt2 = 3;
OpenTK.Vector3d gradLVec1 = new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
OpenTK.Vector3d gradLVec2 = new OpenTK.Vector3d(gradLs[iPt2][0], gradLs[iPt2][1], gradLs[iPt2][2]);
var gradL1xgrapdL2Vec = OpenTK.Vector3d.Cross(gradLVec1, gradLVec2);
double[] gradL1xgradL2 = { gradL1xgrapdL2Vec.X, gradL1xgrapdL2Vec.Y, gradL1xgrapdL2Vec.Z };
double[] rotEdgeN = new double[3];
rotEdgeNs[eIndex] = rotEdgeN;
for (int idim = 0; idim < 3; idim++)
{
rotEdgeN[idim] = lens[2] * gradL1xgradL2[idim];
}
}
{
int eIndex = 5;
int iPt1 = 3;
int iPt2 = 0;
OpenTK.Vector3d gradLVec1 = new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
OpenTK.Vector3d gradLVec2 = new OpenTK.Vector3d(gradLs[iPt2][0], gradLs[iPt2][1], gradLs[iPt2][2]);
var gradL1xgrapdL2Vec = OpenTK.Vector3d.Cross(gradLVec1, gradLVec2);
double[] gradL1xgradL2 = { gradL1xgrapdL2Vec.X, gradL1xgrapdL2Vec.Y, gradL1xgrapdL2Vec.Z };
double[] rotEdgeN = new double[3];
rotEdgeNs[eIndex] = rotEdgeN;
for (int idim = 0; idim < 3; idim++)
{
rotEdgeN[idim] = lens[2] * gradL1xgradL2[idim];
}
}
{
int eIndex = 6;
int iPt1 = 1;
int iPt2 = 2;
OpenTK.Vector3d gradLVec1 = new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
OpenTK.Vector3d gradLVec2 = new OpenTK.Vector3d(gradLs[iPt2][0], gradLs[iPt2][1], gradLs[iPt2][2]);
var gradL1xgrapdL2Vec = OpenTK.Vector3d.Cross(gradLVec1, gradLVec2);
double[] gradL1xgradL2 = { gradL1xgrapdL2Vec.X, gradL1xgrapdL2Vec.Y, gradL1xgrapdL2Vec.Z };
double[] rotEdgeN = new double[3];
rotEdgeNs[eIndex] = rotEdgeN;
for (int idim = 0; idim < 3; idim++)
{
rotEdgeN[idim] = lens[3] * gradL1xgradL2[idim];
}
}
{
int eIndex = 7;
int iPt1 = 2;
int iPt2 = 1;
OpenTK.Vector3d gradLVec1 = new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
OpenTK.Vector3d gradLVec2 = new OpenTK.Vector3d(gradLs[iPt2][0], gradLs[iPt2][1], gradLs[iPt2][2]);
var gradL1xgrapdL2Vec = OpenTK.Vector3d.Cross(gradLVec1, gradLVec2);
double[] gradL1xgradL2 = { gradL1xgrapdL2Vec.X, gradL1xgrapdL2Vec.Y, gradL1xgrapdL2Vec.Z };
double[] rotEdgeN = new double[3];
rotEdgeNs[eIndex] = rotEdgeN;
for (int idim = 0; idim < 3; idim++)
{
rotEdgeN[idim] = lens[3] * gradL1xgradL2[idim];
}
}
{
int eIndex = 8;
int iPt1 = 3;
int iPt2 = 1;
OpenTK.Vector3d gradLVec1 = new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
OpenTK.Vector3d gradLVec2 = new OpenTK.Vector3d(gradLs[iPt2][0], gradLs[iPt2][1], gradLs[iPt2][2]);
var gradL1xgrapdL2Vec = OpenTK.Vector3d.Cross(gradLVec1, gradLVec2);
double[] gradL1xgradL2 = { gradL1xgrapdL2Vec.X, gradL1xgrapdL2Vec.Y, gradL1xgrapdL2Vec.Z };
double[] rotEdgeN = new double[3];
rotEdgeNs[eIndex] = rotEdgeN;
for (int idim = 0; idim < 3; idim++)
{
rotEdgeN[idim] = lens[4] * gradL1xgradL2[idim];
}
}
{
int eIndex = 9;
int iPt1 = 1;
int iPt2 = 3;
OpenTK.Vector3d gradLVec1 = new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
OpenTK.Vector3d gradLVec2 = new OpenTK.Vector3d(gradLs[iPt2][0], gradLs[iPt2][1], gradLs[iPt2][2]);
var gradL1xgrapdL2Vec = OpenTK.Vector3d.Cross(gradLVec1, gradLVec2);
double[] gradL1xgradL2 = { gradL1xgrapdL2Vec.X, gradL1xgrapdL2Vec.Y, gradL1xgrapdL2Vec.Z };
double[] rotEdgeN = new double[3];
rotEdgeNs[eIndex] = rotEdgeN;
for (int idim = 0; idim < 3; idim++)
{
rotEdgeN[idim] = lens[4] * gradL1xgradL2[idim];
}
}
{
int eIndex = 10;
int iPt1 = 2;
int iPt2 = 3;
OpenTK.Vector3d gradLVec1 = new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
OpenTK.Vector3d gradLVec2 = new OpenTK.Vector3d(gradLs[iPt2][0], gradLs[iPt2][1], gradLs[iPt2][2]);
var gradL1xgrapdL2Vec = OpenTK.Vector3d.Cross(gradLVec1, gradLVec2);
double[] gradL1xgradL2 = { gradL1xgrapdL2Vec.X, gradL1xgrapdL2Vec.Y, gradL1xgrapdL2Vec.Z };
double[] rotEdgeN = new double[3];
rotEdgeNs[eIndex] = rotEdgeN;
for (int idim = 0; idim < 3; idim++)
{
rotEdgeN[idim] = lens[5] * gradL1xgradL2[idim];
}
}
{
int eIndex = 11;
int iPt1 = 3;
int iPt2 = 2;
OpenTK.Vector3d gradLVec1 = new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
OpenTK.Vector3d gradLVec2 = new OpenTK.Vector3d(gradLs[iPt2][0], gradLs[iPt2][1], gradLs[iPt2][2]);
var gradL1xgrapdL2Vec = OpenTK.Vector3d.Cross(gradLVec1, gradLVec2);
double[] gradL1xgradL2 = { gradL1xgrapdL2Vec.X, gradL1xgrapdL2Vec.Y, gradL1xgrapdL2Vec.Z };
double[] rotEdgeN = new double[3];
rotEdgeNs[eIndex] = rotEdgeN;
for (int idim = 0; idim < 3; idim++)
{
rotEdgeN[idim] = lens[5] * gradL1xgradL2[idim];
}
}
{
for (int iVNo = 0; iVNo < 2; iVNo++)
{
int eIndex = 12 + iVNo;
int vIndex = edgePointId[eIndex][1];
System.Diagnostics.Debug.Assert(vIndex >= 0 && vIndex < 4);
double[] rotEdgeN = new double[3];
rotEdgeNs[eIndex] = rotEdgeN;
double L1 = 0.0;
double L2 = 0.0;
double[] gradL3xn4 = null;
double[] gradL5xn6 = null;
int iface = 0;
var n2 = nVecss[iface][0];
var n3 = nVecss[iface][1];
var n4 = nVecss[iface][2];
if (vIndex == 1)
{
L1 = L[2];
L2 = L[3];
{
int iPt1 = 3;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n2);
gradL3xn4 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
{
int iPt1 = 2;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n2);
gradL5xn6 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
}
else if (vIndex == 2)
{
L1 = L[1];
L2 = L[3];
{
int iPt1 = 3;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n3);
gradL3xn4 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
{
int iPt1 = 1;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n3);
gradL5xn6 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
}
else if (vIndex == 3)
{
L1 = L[1];
L2 = L[2];
{
int iPt1 = 2;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n4);
gradL3xn4 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
{
int iPt1 = 1;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n4);
gradL5xn6 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
}
else
{
System.Diagnostics.Debug.Assert(false);
}
for (int idim = 0; idim < 3; idim++)
{
rotEdgeN[idim] = 4.0 * L1 * gradL3xn4[idim] + 4.0 * L2 * gradL5xn6[idim];
}
}
}
{
for (int iVNo = 0; iVNo < 2; iVNo++)
{
int eIndex = 14 + iVNo;
int vIndex = edgePointId[eIndex][1];
System.Diagnostics.Debug.Assert(vIndex >= 0 && vIndex < 4);
double[] rotEdgeN = new double[3];
rotEdgeNs[eIndex] = rotEdgeN;
double L1 = 0.0;
double L2 = 0.0;
double[] gradL3xn4 = null;
double[] gradL5xn6 = null;
int iface = 1;
var n1 = nVecss[iface][0];
var n3 = nVecss[iface][1];
var n4 = nVecss[iface][2];
if (vIndex == 0)
{
L1 = L[2];
L2 = L[3];
{
int iPt1 = 3;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n1);
gradL3xn4 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
{
int iPt1 = 2;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n1);
gradL5xn6 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
}
else if (vIndex == 2)
{
L1 = L[0];
L2 = L[3];
{
int iPt1 = 3;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n3);
gradL3xn4 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
{
int iPt1 = 0;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n3);
gradL5xn6 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
}
else if (vIndex == 3)
{
L1 = L[0];
L2 = L[2];
{
int iPt1 = 2;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n4);
gradL3xn4 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
{
int iPt1 = 0;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n4);
gradL5xn6 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
}
else
{
System.Diagnostics.Debug.Assert(false);
}
for (int idim = 0; idim < 3; idim++)
{
rotEdgeN[idim] = 4.0 * L1 * gradL3xn4[idim] + 4.0 * L2 * gradL5xn6[idim];
}
}
}
{
for (int iVNo = 0; iVNo < 2; iVNo++)
{
int eIndex = 16 + iVNo;
int vIndex = edgePointId[eIndex][1];
System.Diagnostics.Debug.Assert(vIndex >= 0 && vIndex < 4);
double[] rotEdgeN = new double[3];
rotEdgeNs[eIndex] = rotEdgeN;
double L1 = 0.0;
double L2 = 0.0;
double[] gradL3xn4 = null;
double[] gradL5xn6 = null;
int iface = 2;
var n1 = nVecss[iface][0];
var n2 = nVecss[iface][1];
var n4 = nVecss[iface][2];
if (vIndex == 0)
{
L1 = L[1];
L2 = L[3];
{
int iPt1 = 3;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n1);
gradL3xn4 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
{
int iPt1 = 1;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n1);
gradL5xn6 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
}
else if (vIndex == 1)
{
L1 = L[0];
L2 = L[3];
{
int iPt1 = 3;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n2);
gradL3xn4 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
{
int iPt1 = 0;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n2);
gradL5xn6 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
}
else if (vIndex == 3)
{
L1 = L[0];
L2 = L[1];
{
int iPt1 = 1;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n4);
gradL3xn4 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
{
int iPt1 = 0;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n4);
gradL5xn6 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
}
else
{
System.Diagnostics.Debug.Assert(false);
}
for (int idim = 0; idim < 3; idim++)
{
rotEdgeN[idim] = 4.0 * L1 * gradL3xn4[idim] + 4.0 * L2 * gradL5xn6[idim];
}
}
}
{
for (int iVNo = 0; iVNo < 2; iVNo++)
{
int eIndex = 18 + iVNo;
int vIndex = edgePointId[eIndex][1];
System.Diagnostics.Debug.Assert(vIndex >= 0 && vIndex < 4);
double[] rotEdgeN = new double[3];
rotEdgeNs[eIndex] = rotEdgeN;
double L1 = 0.0;
double L2 = 0.0;
double[] gradL3xn4 = null;
double[] gradL5xn6 = null;
int iface = 3;
var n1 = nVecss[iface][0];
var n2 = nVecss[iface][1];
var n3 = nVecss[iface][2];
if (vIndex == 0)
{
L1 = L[1];
L2 = L[2];
{
int iPt1 = 2;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n1);
gradL3xn4 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
{
int iPt1 = 1;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n1);
gradL5xn6 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
}
else if (vIndex == 1)
{
L1 = L[0];
L2 = L[2];
{
int iPt1 = 2;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n2);
gradL3xn4 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
{
int iPt1 = 0;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n2);
gradL5xn6 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
}
else if (vIndex == 2)
{
L1 = L[0];
L2 = L[1];
{
int iPt1 = 1;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n3);
gradL3xn4 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
{
int iPt1 = 0;
OpenTK.Vector3d gradLVec1 =
new OpenTK.Vector3d(gradLs[iPt1][0], gradLs[iPt1][1], gradLs[iPt1][2]);
var gradL1xn2Vec = OpenTK.Vector3d.Cross(gradLVec1, n3);
gradL5xn6 = new double[] { gradL1xn2Vec.X, gradL1xn2Vec.Y, gradL1xn2Vec.Z };
}
}
else
{
System.Diagnostics.Debug.Assert(false);
}
for (int idim = 0; idim < 3; idim++)
{
rotEdgeN[idim] = 4.0 * L1 * gradL3xn4[idim] + 4.0 * L2 * gradL5xn6[idim];
}
}
}
return rotEdgeNs;
}
}
}
| 40.696563 | 115 | 0.38164 | [
"Apache-2.0"
] | ryujimiya/IvyFEM | src/IvyFEM/IvyFEM/TetrahedronFEEdge2ndInterpolate.cs | 48,601 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.V20200301
{
public static class GetVirtualRouter
{
/// <summary>
/// VirtualRouter Resource.
/// </summary>
public static Task<GetVirtualRouterResult> InvokeAsync(GetVirtualRouterArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetVirtualRouterResult>("azure-native:network/v20200301:getVirtualRouter", args ?? new GetVirtualRouterArgs(), options.WithVersion());
}
public sealed class GetVirtualRouterArgs : Pulumi.InvokeArgs
{
/// <summary>
/// Expands referenced resources.
/// </summary>
[Input("expand")]
public string? Expand { get; set; }
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
/// <summary>
/// The name of the Virtual Router.
/// </summary>
[Input("virtualRouterName", required: true)]
public string VirtualRouterName { get; set; } = null!;
public GetVirtualRouterArgs()
{
}
}
[OutputType]
public sealed class GetVirtualRouterResult
{
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
public readonly string Etag;
/// <summary>
/// The Gateway on which VirtualRouter is hosted.
/// </summary>
public readonly Outputs.SubResourceResponse? HostedGateway;
/// <summary>
/// The Subnet on which VirtualRouter is hosted.
/// </summary>
public readonly Outputs.SubResourceResponse? HostedSubnet;
/// <summary>
/// Resource ID.
/// </summary>
public readonly string? Id;
/// <summary>
/// Resource location.
/// </summary>
public readonly string? Location;
/// <summary>
/// Resource name.
/// </summary>
public readonly string Name;
/// <summary>
/// List of references to VirtualRouterPeerings.
/// </summary>
public readonly ImmutableArray<Outputs.SubResourceResponse> Peerings;
/// <summary>
/// The provisioning state of the resource.
/// </summary>
public readonly string ProvisioningState;
/// <summary>
/// Resource tags.
/// </summary>
public readonly ImmutableDictionary<string, string>? Tags;
/// <summary>
/// Resource type.
/// </summary>
public readonly string Type;
/// <summary>
/// VirtualRouter ASN.
/// </summary>
public readonly double? VirtualRouterAsn;
/// <summary>
/// VirtualRouter IPs.
/// </summary>
public readonly ImmutableArray<string> VirtualRouterIps;
[OutputConstructor]
private GetVirtualRouterResult(
string etag,
Outputs.SubResourceResponse? hostedGateway,
Outputs.SubResourceResponse? hostedSubnet,
string? id,
string? location,
string name,
ImmutableArray<Outputs.SubResourceResponse> peerings,
string provisioningState,
ImmutableDictionary<string, string>? tags,
string type,
double? virtualRouterAsn,
ImmutableArray<string> virtualRouterIps)
{
Etag = etag;
HostedGateway = hostedGateway;
HostedSubnet = hostedSubnet;
Id = id;
Location = location;
Name = name;
Peerings = peerings;
ProvisioningState = provisioningState;
Tags = tags;
Type = type;
VirtualRouterAsn = virtualRouterAsn;
VirtualRouterIps = virtualRouterIps;
}
}
}
| 30.29078 | 188 | 0.582768 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Network/V20200301/GetVirtualRouter.cs | 4,271 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.ComponentModel;
using Pulumi;
namespace Pulumi.AzureNative.ContainerService.V20190601
{
/// <summary>
/// AgentPoolType represents types of an agent pool
/// </summary>
[EnumType]
public readonly struct AgentPoolType : IEquatable<AgentPoolType>
{
private readonly string _value;
private AgentPoolType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static AgentPoolType VirtualMachineScaleSets { get; } = new AgentPoolType("VirtualMachineScaleSets");
public static AgentPoolType AvailabilitySet { get; } = new AgentPoolType("AvailabilitySet");
public static bool operator ==(AgentPoolType left, AgentPoolType right) => left.Equals(right);
public static bool operator !=(AgentPoolType left, AgentPoolType right) => !left.Equals(right);
public static explicit operator string(AgentPoolType value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is AgentPoolType other && Equals(other);
public bool Equals(AgentPoolType other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Size of agent VMs.
/// </summary>
[EnumType]
public readonly struct ContainerServiceVMSizeTypes : IEquatable<ContainerServiceVMSizeTypes>
{
private readonly string _value;
private ContainerServiceVMSizeTypes(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static ContainerServiceVMSizeTypes Standard_A1 { get; } = new ContainerServiceVMSizeTypes("Standard_A1");
public static ContainerServiceVMSizeTypes Standard_A10 { get; } = new ContainerServiceVMSizeTypes("Standard_A10");
public static ContainerServiceVMSizeTypes Standard_A11 { get; } = new ContainerServiceVMSizeTypes("Standard_A11");
public static ContainerServiceVMSizeTypes Standard_A1_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_A1_v2");
public static ContainerServiceVMSizeTypes Standard_A2 { get; } = new ContainerServiceVMSizeTypes("Standard_A2");
public static ContainerServiceVMSizeTypes Standard_A2_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_A2_v2");
public static ContainerServiceVMSizeTypes Standard_A2m_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_A2m_v2");
public static ContainerServiceVMSizeTypes Standard_A3 { get; } = new ContainerServiceVMSizeTypes("Standard_A3");
public static ContainerServiceVMSizeTypes Standard_A4 { get; } = new ContainerServiceVMSizeTypes("Standard_A4");
public static ContainerServiceVMSizeTypes Standard_A4_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_A4_v2");
public static ContainerServiceVMSizeTypes Standard_A4m_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_A4m_v2");
public static ContainerServiceVMSizeTypes Standard_A5 { get; } = new ContainerServiceVMSizeTypes("Standard_A5");
public static ContainerServiceVMSizeTypes Standard_A6 { get; } = new ContainerServiceVMSizeTypes("Standard_A6");
public static ContainerServiceVMSizeTypes Standard_A7 { get; } = new ContainerServiceVMSizeTypes("Standard_A7");
public static ContainerServiceVMSizeTypes Standard_A8 { get; } = new ContainerServiceVMSizeTypes("Standard_A8");
public static ContainerServiceVMSizeTypes Standard_A8_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_A8_v2");
public static ContainerServiceVMSizeTypes Standard_A8m_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_A8m_v2");
public static ContainerServiceVMSizeTypes Standard_A9 { get; } = new ContainerServiceVMSizeTypes("Standard_A9");
public static ContainerServiceVMSizeTypes Standard_B2ms { get; } = new ContainerServiceVMSizeTypes("Standard_B2ms");
public static ContainerServiceVMSizeTypes Standard_B2s { get; } = new ContainerServiceVMSizeTypes("Standard_B2s");
public static ContainerServiceVMSizeTypes Standard_B4ms { get; } = new ContainerServiceVMSizeTypes("Standard_B4ms");
public static ContainerServiceVMSizeTypes Standard_B8ms { get; } = new ContainerServiceVMSizeTypes("Standard_B8ms");
public static ContainerServiceVMSizeTypes Standard_D1 { get; } = new ContainerServiceVMSizeTypes("Standard_D1");
public static ContainerServiceVMSizeTypes Standard_D11 { get; } = new ContainerServiceVMSizeTypes("Standard_D11");
public static ContainerServiceVMSizeTypes Standard_D11_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_D11_v2");
public static ContainerServiceVMSizeTypes Standard_D11_v2_Promo { get; } = new ContainerServiceVMSizeTypes("Standard_D11_v2_Promo");
public static ContainerServiceVMSizeTypes Standard_D12 { get; } = new ContainerServiceVMSizeTypes("Standard_D12");
public static ContainerServiceVMSizeTypes Standard_D12_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_D12_v2");
public static ContainerServiceVMSizeTypes Standard_D12_v2_Promo { get; } = new ContainerServiceVMSizeTypes("Standard_D12_v2_Promo");
public static ContainerServiceVMSizeTypes Standard_D13 { get; } = new ContainerServiceVMSizeTypes("Standard_D13");
public static ContainerServiceVMSizeTypes Standard_D13_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_D13_v2");
public static ContainerServiceVMSizeTypes Standard_D13_v2_Promo { get; } = new ContainerServiceVMSizeTypes("Standard_D13_v2_Promo");
public static ContainerServiceVMSizeTypes Standard_D14 { get; } = new ContainerServiceVMSizeTypes("Standard_D14");
public static ContainerServiceVMSizeTypes Standard_D14_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_D14_v2");
public static ContainerServiceVMSizeTypes Standard_D14_v2_Promo { get; } = new ContainerServiceVMSizeTypes("Standard_D14_v2_Promo");
public static ContainerServiceVMSizeTypes Standard_D15_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_D15_v2");
public static ContainerServiceVMSizeTypes Standard_D16_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_D16_v3");
public static ContainerServiceVMSizeTypes Standard_D16s_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_D16s_v3");
public static ContainerServiceVMSizeTypes Standard_D1_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_D1_v2");
public static ContainerServiceVMSizeTypes Standard_D2 { get; } = new ContainerServiceVMSizeTypes("Standard_D2");
public static ContainerServiceVMSizeTypes Standard_D2_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_D2_v2");
public static ContainerServiceVMSizeTypes Standard_D2_v2_Promo { get; } = new ContainerServiceVMSizeTypes("Standard_D2_v2_Promo");
public static ContainerServiceVMSizeTypes Standard_D2_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_D2_v3");
public static ContainerServiceVMSizeTypes Standard_D2s_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_D2s_v3");
public static ContainerServiceVMSizeTypes Standard_D3 { get; } = new ContainerServiceVMSizeTypes("Standard_D3");
public static ContainerServiceVMSizeTypes Standard_D32_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_D32_v3");
public static ContainerServiceVMSizeTypes Standard_D32s_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_D32s_v3");
public static ContainerServiceVMSizeTypes Standard_D3_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_D3_v2");
public static ContainerServiceVMSizeTypes Standard_D3_v2_Promo { get; } = new ContainerServiceVMSizeTypes("Standard_D3_v2_Promo");
public static ContainerServiceVMSizeTypes Standard_D4 { get; } = new ContainerServiceVMSizeTypes("Standard_D4");
public static ContainerServiceVMSizeTypes Standard_D4_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_D4_v2");
public static ContainerServiceVMSizeTypes Standard_D4_v2_Promo { get; } = new ContainerServiceVMSizeTypes("Standard_D4_v2_Promo");
public static ContainerServiceVMSizeTypes Standard_D4_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_D4_v3");
public static ContainerServiceVMSizeTypes Standard_D4s_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_D4s_v3");
public static ContainerServiceVMSizeTypes Standard_D5_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_D5_v2");
public static ContainerServiceVMSizeTypes Standard_D5_v2_Promo { get; } = new ContainerServiceVMSizeTypes("Standard_D5_v2_Promo");
public static ContainerServiceVMSizeTypes Standard_D64_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_D64_v3");
public static ContainerServiceVMSizeTypes Standard_D64s_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_D64s_v3");
public static ContainerServiceVMSizeTypes Standard_D8_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_D8_v3");
public static ContainerServiceVMSizeTypes Standard_D8s_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_D8s_v3");
public static ContainerServiceVMSizeTypes Standard_DS1 { get; } = new ContainerServiceVMSizeTypes("Standard_DS1");
public static ContainerServiceVMSizeTypes Standard_DS11 { get; } = new ContainerServiceVMSizeTypes("Standard_DS11");
public static ContainerServiceVMSizeTypes Standard_DS11_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_DS11_v2");
public static ContainerServiceVMSizeTypes Standard_DS11_v2_Promo { get; } = new ContainerServiceVMSizeTypes("Standard_DS11_v2_Promo");
public static ContainerServiceVMSizeTypes Standard_DS12 { get; } = new ContainerServiceVMSizeTypes("Standard_DS12");
public static ContainerServiceVMSizeTypes Standard_DS12_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_DS12_v2");
public static ContainerServiceVMSizeTypes Standard_DS12_v2_Promo { get; } = new ContainerServiceVMSizeTypes("Standard_DS12_v2_Promo");
public static ContainerServiceVMSizeTypes Standard_DS13 { get; } = new ContainerServiceVMSizeTypes("Standard_DS13");
public static ContainerServiceVMSizeTypes Standard_DS13_2_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_DS13-2_v2");
public static ContainerServiceVMSizeTypes Standard_DS13_4_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_DS13-4_v2");
public static ContainerServiceVMSizeTypes Standard_DS13_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_DS13_v2");
public static ContainerServiceVMSizeTypes Standard_DS13_v2_Promo { get; } = new ContainerServiceVMSizeTypes("Standard_DS13_v2_Promo");
public static ContainerServiceVMSizeTypes Standard_DS14 { get; } = new ContainerServiceVMSizeTypes("Standard_DS14");
public static ContainerServiceVMSizeTypes Standard_DS14_4_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_DS14-4_v2");
public static ContainerServiceVMSizeTypes Standard_DS14_8_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_DS14-8_v2");
public static ContainerServiceVMSizeTypes Standard_DS14_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_DS14_v2");
public static ContainerServiceVMSizeTypes Standard_DS14_v2_Promo { get; } = new ContainerServiceVMSizeTypes("Standard_DS14_v2_Promo");
public static ContainerServiceVMSizeTypes Standard_DS15_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_DS15_v2");
public static ContainerServiceVMSizeTypes Standard_DS1_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_DS1_v2");
public static ContainerServiceVMSizeTypes Standard_DS2 { get; } = new ContainerServiceVMSizeTypes("Standard_DS2");
public static ContainerServiceVMSizeTypes Standard_DS2_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_DS2_v2");
public static ContainerServiceVMSizeTypes Standard_DS2_v2_Promo { get; } = new ContainerServiceVMSizeTypes("Standard_DS2_v2_Promo");
public static ContainerServiceVMSizeTypes Standard_DS3 { get; } = new ContainerServiceVMSizeTypes("Standard_DS3");
public static ContainerServiceVMSizeTypes Standard_DS3_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_DS3_v2");
public static ContainerServiceVMSizeTypes Standard_DS3_v2_Promo { get; } = new ContainerServiceVMSizeTypes("Standard_DS3_v2_Promo");
public static ContainerServiceVMSizeTypes Standard_DS4 { get; } = new ContainerServiceVMSizeTypes("Standard_DS4");
public static ContainerServiceVMSizeTypes Standard_DS4_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_DS4_v2");
public static ContainerServiceVMSizeTypes Standard_DS4_v2_Promo { get; } = new ContainerServiceVMSizeTypes("Standard_DS4_v2_Promo");
public static ContainerServiceVMSizeTypes Standard_DS5_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_DS5_v2");
public static ContainerServiceVMSizeTypes Standard_DS5_v2_Promo { get; } = new ContainerServiceVMSizeTypes("Standard_DS5_v2_Promo");
public static ContainerServiceVMSizeTypes Standard_E16_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_E16_v3");
public static ContainerServiceVMSizeTypes Standard_E16s_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_E16s_v3");
public static ContainerServiceVMSizeTypes Standard_E2_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_E2_v3");
public static ContainerServiceVMSizeTypes Standard_E2s_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_E2s_v3");
public static ContainerServiceVMSizeTypes Standard_E32_16s_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_E32-16s_v3");
public static ContainerServiceVMSizeTypes Standard_E32_8s_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_E32-8s_v3");
public static ContainerServiceVMSizeTypes Standard_E32_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_E32_v3");
public static ContainerServiceVMSizeTypes Standard_E32s_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_E32s_v3");
public static ContainerServiceVMSizeTypes Standard_E4_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_E4_v3");
public static ContainerServiceVMSizeTypes Standard_E4s_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_E4s_v3");
public static ContainerServiceVMSizeTypes Standard_E64_16s_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_E64-16s_v3");
public static ContainerServiceVMSizeTypes Standard_E64_32s_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_E64-32s_v3");
public static ContainerServiceVMSizeTypes Standard_E64_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_E64_v3");
public static ContainerServiceVMSizeTypes Standard_E64s_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_E64s_v3");
public static ContainerServiceVMSizeTypes Standard_E8_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_E8_v3");
public static ContainerServiceVMSizeTypes Standard_E8s_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_E8s_v3");
public static ContainerServiceVMSizeTypes Standard_F1 { get; } = new ContainerServiceVMSizeTypes("Standard_F1");
public static ContainerServiceVMSizeTypes Standard_F16 { get; } = new ContainerServiceVMSizeTypes("Standard_F16");
public static ContainerServiceVMSizeTypes Standard_F16s { get; } = new ContainerServiceVMSizeTypes("Standard_F16s");
public static ContainerServiceVMSizeTypes Standard_F16s_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_F16s_v2");
public static ContainerServiceVMSizeTypes Standard_F1s { get; } = new ContainerServiceVMSizeTypes("Standard_F1s");
public static ContainerServiceVMSizeTypes Standard_F2 { get; } = new ContainerServiceVMSizeTypes("Standard_F2");
public static ContainerServiceVMSizeTypes Standard_F2s { get; } = new ContainerServiceVMSizeTypes("Standard_F2s");
public static ContainerServiceVMSizeTypes Standard_F2s_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_F2s_v2");
public static ContainerServiceVMSizeTypes Standard_F32s_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_F32s_v2");
public static ContainerServiceVMSizeTypes Standard_F4 { get; } = new ContainerServiceVMSizeTypes("Standard_F4");
public static ContainerServiceVMSizeTypes Standard_F4s { get; } = new ContainerServiceVMSizeTypes("Standard_F4s");
public static ContainerServiceVMSizeTypes Standard_F4s_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_F4s_v2");
public static ContainerServiceVMSizeTypes Standard_F64s_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_F64s_v2");
public static ContainerServiceVMSizeTypes Standard_F72s_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_F72s_v2");
public static ContainerServiceVMSizeTypes Standard_F8 { get; } = new ContainerServiceVMSizeTypes("Standard_F8");
public static ContainerServiceVMSizeTypes Standard_F8s { get; } = new ContainerServiceVMSizeTypes("Standard_F8s");
public static ContainerServiceVMSizeTypes Standard_F8s_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_F8s_v2");
public static ContainerServiceVMSizeTypes Standard_G1 { get; } = new ContainerServiceVMSizeTypes("Standard_G1");
public static ContainerServiceVMSizeTypes Standard_G2 { get; } = new ContainerServiceVMSizeTypes("Standard_G2");
public static ContainerServiceVMSizeTypes Standard_G3 { get; } = new ContainerServiceVMSizeTypes("Standard_G3");
public static ContainerServiceVMSizeTypes Standard_G4 { get; } = new ContainerServiceVMSizeTypes("Standard_G4");
public static ContainerServiceVMSizeTypes Standard_G5 { get; } = new ContainerServiceVMSizeTypes("Standard_G5");
public static ContainerServiceVMSizeTypes Standard_GS1 { get; } = new ContainerServiceVMSizeTypes("Standard_GS1");
public static ContainerServiceVMSizeTypes Standard_GS2 { get; } = new ContainerServiceVMSizeTypes("Standard_GS2");
public static ContainerServiceVMSizeTypes Standard_GS3 { get; } = new ContainerServiceVMSizeTypes("Standard_GS3");
public static ContainerServiceVMSizeTypes Standard_GS4 { get; } = new ContainerServiceVMSizeTypes("Standard_GS4");
public static ContainerServiceVMSizeTypes Standard_GS4_4 { get; } = new ContainerServiceVMSizeTypes("Standard_GS4-4");
public static ContainerServiceVMSizeTypes Standard_GS4_8 { get; } = new ContainerServiceVMSizeTypes("Standard_GS4-8");
public static ContainerServiceVMSizeTypes Standard_GS5 { get; } = new ContainerServiceVMSizeTypes("Standard_GS5");
public static ContainerServiceVMSizeTypes Standard_GS5_16 { get; } = new ContainerServiceVMSizeTypes("Standard_GS5-16");
public static ContainerServiceVMSizeTypes Standard_GS5_8 { get; } = new ContainerServiceVMSizeTypes("Standard_GS5-8");
public static ContainerServiceVMSizeTypes Standard_H16 { get; } = new ContainerServiceVMSizeTypes("Standard_H16");
public static ContainerServiceVMSizeTypes Standard_H16m { get; } = new ContainerServiceVMSizeTypes("Standard_H16m");
public static ContainerServiceVMSizeTypes Standard_H16mr { get; } = new ContainerServiceVMSizeTypes("Standard_H16mr");
public static ContainerServiceVMSizeTypes Standard_H16r { get; } = new ContainerServiceVMSizeTypes("Standard_H16r");
public static ContainerServiceVMSizeTypes Standard_H8 { get; } = new ContainerServiceVMSizeTypes("Standard_H8");
public static ContainerServiceVMSizeTypes Standard_H8m { get; } = new ContainerServiceVMSizeTypes("Standard_H8m");
public static ContainerServiceVMSizeTypes Standard_L16s { get; } = new ContainerServiceVMSizeTypes("Standard_L16s");
public static ContainerServiceVMSizeTypes Standard_L32s { get; } = new ContainerServiceVMSizeTypes("Standard_L32s");
public static ContainerServiceVMSizeTypes Standard_L4s { get; } = new ContainerServiceVMSizeTypes("Standard_L4s");
public static ContainerServiceVMSizeTypes Standard_L8s { get; } = new ContainerServiceVMSizeTypes("Standard_L8s");
public static ContainerServiceVMSizeTypes Standard_M128_32ms { get; } = new ContainerServiceVMSizeTypes("Standard_M128-32ms");
public static ContainerServiceVMSizeTypes Standard_M128_64ms { get; } = new ContainerServiceVMSizeTypes("Standard_M128-64ms");
public static ContainerServiceVMSizeTypes Standard_M128ms { get; } = new ContainerServiceVMSizeTypes("Standard_M128ms");
public static ContainerServiceVMSizeTypes Standard_M128s { get; } = new ContainerServiceVMSizeTypes("Standard_M128s");
public static ContainerServiceVMSizeTypes Standard_M64_16ms { get; } = new ContainerServiceVMSizeTypes("Standard_M64-16ms");
public static ContainerServiceVMSizeTypes Standard_M64_32ms { get; } = new ContainerServiceVMSizeTypes("Standard_M64-32ms");
public static ContainerServiceVMSizeTypes Standard_M64ms { get; } = new ContainerServiceVMSizeTypes("Standard_M64ms");
public static ContainerServiceVMSizeTypes Standard_M64s { get; } = new ContainerServiceVMSizeTypes("Standard_M64s");
public static ContainerServiceVMSizeTypes Standard_NC12 { get; } = new ContainerServiceVMSizeTypes("Standard_NC12");
public static ContainerServiceVMSizeTypes Standard_NC12s_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_NC12s_v2");
public static ContainerServiceVMSizeTypes Standard_NC12s_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_NC12s_v3");
public static ContainerServiceVMSizeTypes Standard_NC24 { get; } = new ContainerServiceVMSizeTypes("Standard_NC24");
public static ContainerServiceVMSizeTypes Standard_NC24r { get; } = new ContainerServiceVMSizeTypes("Standard_NC24r");
public static ContainerServiceVMSizeTypes Standard_NC24rs_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_NC24rs_v2");
public static ContainerServiceVMSizeTypes Standard_NC24rs_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_NC24rs_v3");
public static ContainerServiceVMSizeTypes Standard_NC24s_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_NC24s_v2");
public static ContainerServiceVMSizeTypes Standard_NC24s_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_NC24s_v3");
public static ContainerServiceVMSizeTypes Standard_NC6 { get; } = new ContainerServiceVMSizeTypes("Standard_NC6");
public static ContainerServiceVMSizeTypes Standard_NC6s_v2 { get; } = new ContainerServiceVMSizeTypes("Standard_NC6s_v2");
public static ContainerServiceVMSizeTypes Standard_NC6s_v3 { get; } = new ContainerServiceVMSizeTypes("Standard_NC6s_v3");
public static ContainerServiceVMSizeTypes Standard_ND12s { get; } = new ContainerServiceVMSizeTypes("Standard_ND12s");
public static ContainerServiceVMSizeTypes Standard_ND24rs { get; } = new ContainerServiceVMSizeTypes("Standard_ND24rs");
public static ContainerServiceVMSizeTypes Standard_ND24s { get; } = new ContainerServiceVMSizeTypes("Standard_ND24s");
public static ContainerServiceVMSizeTypes Standard_ND6s { get; } = new ContainerServiceVMSizeTypes("Standard_ND6s");
public static ContainerServiceVMSizeTypes Standard_NV12 { get; } = new ContainerServiceVMSizeTypes("Standard_NV12");
public static ContainerServiceVMSizeTypes Standard_NV24 { get; } = new ContainerServiceVMSizeTypes("Standard_NV24");
public static ContainerServiceVMSizeTypes Standard_NV6 { get; } = new ContainerServiceVMSizeTypes("Standard_NV6");
public static bool operator ==(ContainerServiceVMSizeTypes left, ContainerServiceVMSizeTypes right) => left.Equals(right);
public static bool operator !=(ContainerServiceVMSizeTypes left, ContainerServiceVMSizeTypes right) => !left.Equals(right);
public static explicit operator string(ContainerServiceVMSizeTypes value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is ContainerServiceVMSizeTypes other && Equals(other);
public bool Equals(ContainerServiceVMSizeTypes other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The load balancer sku for the managed cluster.
/// </summary>
[EnumType]
public readonly struct LoadBalancerSku : IEquatable<LoadBalancerSku>
{
private readonly string _value;
private LoadBalancerSku(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static LoadBalancerSku Standard { get; } = new LoadBalancerSku("standard");
public static LoadBalancerSku Basic { get; } = new LoadBalancerSku("basic");
public static bool operator ==(LoadBalancerSku left, LoadBalancerSku right) => left.Equals(right);
public static bool operator !=(LoadBalancerSku left, LoadBalancerSku right) => !left.Equals(right);
public static explicit operator string(LoadBalancerSku value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is LoadBalancerSku other && Equals(other);
public bool Equals(LoadBalancerSku other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Network plugin used for building Kubernetes network.
/// </summary>
[EnumType]
public readonly struct NetworkPlugin : IEquatable<NetworkPlugin>
{
private readonly string _value;
private NetworkPlugin(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static NetworkPlugin Azure { get; } = new NetworkPlugin("azure");
public static NetworkPlugin Kubenet { get; } = new NetworkPlugin("kubenet");
public static bool operator ==(NetworkPlugin left, NetworkPlugin right) => left.Equals(right);
public static bool operator !=(NetworkPlugin left, NetworkPlugin right) => !left.Equals(right);
public static explicit operator string(NetworkPlugin value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is NetworkPlugin other && Equals(other);
public bool Equals(NetworkPlugin other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Network policy used for building Kubernetes network.
/// </summary>
[EnumType]
public readonly struct NetworkPolicy : IEquatable<NetworkPolicy>
{
private readonly string _value;
private NetworkPolicy(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static NetworkPolicy Calico { get; } = new NetworkPolicy("calico");
public static NetworkPolicy Azure { get; } = new NetworkPolicy("azure");
public static bool operator ==(NetworkPolicy left, NetworkPolicy right) => left.Equals(right);
public static bool operator !=(NetworkPolicy left, NetworkPolicy right) => !left.Equals(right);
public static explicit operator string(NetworkPolicy value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is NetworkPolicy other && Equals(other);
public bool Equals(NetworkPolicy other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// OsType to be used to specify os type. Choose from Linux and Windows. Default to Linux.
/// </summary>
[EnumType]
public readonly struct OSType : IEquatable<OSType>
{
private readonly string _value;
private OSType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static OSType Linux { get; } = new OSType("Linux");
public static OSType Windows { get; } = new OSType("Windows");
public static bool operator ==(OSType left, OSType right) => left.Equals(right);
public static bool operator !=(OSType left, OSType right) => !left.Equals(right);
public static explicit operator string(OSType value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is OSType other && Equals(other);
public bool Equals(OSType other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The type of identity used for the managed cluster. Type 'SystemAssigned' will use an implicitly created identity in master components and an auto-created user assigned identity in MC_ resource group in agent nodes. Type 'None' will not use MSI for the managed cluster, service principal will be used instead.
/// </summary>
[EnumType]
public readonly struct ResourceIdentityType : IEquatable<ResourceIdentityType>
{
private readonly string _value;
private ResourceIdentityType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static ResourceIdentityType SystemAssigned { get; } = new ResourceIdentityType("SystemAssigned");
public static ResourceIdentityType None { get; } = new ResourceIdentityType("None");
public static bool operator ==(ResourceIdentityType left, ResourceIdentityType right) => left.Equals(right);
public static bool operator !=(ResourceIdentityType left, ResourceIdentityType right) => !left.Equals(right);
public static explicit operator string(ResourceIdentityType value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is ResourceIdentityType other && Equals(other);
public bool Equals(ResourceIdentityType other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// ScaleSetEvictionPolicy to be used to specify eviction policy for low priority virtual machine scale set. Default to Delete.
/// </summary>
[EnumType]
public readonly struct ScaleSetEvictionPolicy : IEquatable<ScaleSetEvictionPolicy>
{
private readonly string _value;
private ScaleSetEvictionPolicy(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static ScaleSetEvictionPolicy Delete { get; } = new ScaleSetEvictionPolicy("Delete");
public static ScaleSetEvictionPolicy Deallocate { get; } = new ScaleSetEvictionPolicy("Deallocate");
public static bool operator ==(ScaleSetEvictionPolicy left, ScaleSetEvictionPolicy right) => left.Equals(right);
public static bool operator !=(ScaleSetEvictionPolicy left, ScaleSetEvictionPolicy right) => !left.Equals(right);
public static explicit operator string(ScaleSetEvictionPolicy value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is ScaleSetEvictionPolicy other && Equals(other);
public bool Equals(ScaleSetEvictionPolicy other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// ScaleSetPriority to be used to specify virtual machine scale set priority. Default to regular.
/// </summary>
[EnumType]
public readonly struct ScaleSetPriority : IEquatable<ScaleSetPriority>
{
private readonly string _value;
private ScaleSetPriority(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static ScaleSetPriority Low { get; } = new ScaleSetPriority("Low");
public static ScaleSetPriority Regular { get; } = new ScaleSetPriority("Regular");
public static bool operator ==(ScaleSetPriority left, ScaleSetPriority right) => left.Equals(right);
public static bool operator !=(ScaleSetPriority left, ScaleSetPriority right) => !left.Equals(right);
public static explicit operator string(ScaleSetPriority value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is ScaleSetPriority other && Equals(other);
public bool Equals(ScaleSetPriority other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
}
| 75.401302 | 316 | 0.753193 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/ContainerService/V20190601/Enums.cs | 34,760 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace NotFoundMiddlewareSample.Middleware
{
public class NotFoundPageMiddleware
{
private readonly RequestDelegate _next;
private readonly RequestTracker _requestTracker;
private readonly ILogger _logger;
private readonly NotFoundMiddlewareOptions _options;
public NotFoundPageMiddleware(RequestDelegate next,
ILoggerFactory loggerFactory,
RequestTracker requestTracker,
IOptions<NotFoundMiddlewareOptions> options)
{
_next = next;
_requestTracker = requestTracker;
_logger = loggerFactory.CreateLogger<NotFoundPageMiddleware>();
_options = options.Value;
}
public async Task Invoke(HttpContext httpContext)
{
if (!httpContext.Request.Path.StartsWithSegments(_options.Path))
{
await _next(httpContext);
return;
}
if (httpContext.Request.Query.Keys.Contains("path") &&
httpContext.Request.Query.Keys.Contains("fixedpath"))
{
var request = _requestTracker.GetRequest(httpContext.Request.Query["path"]);
request.SetCorrectedPath(httpContext.Request.Query["fixedpath"]);
_requestTracker.UpdateRequest(request);
}
Render404List(httpContext);
}
private async void Render404List(HttpContext httpContext)
{
var model = _requestTracker.ListRequests()
.OrderByDescending(r => r.Count);
var requestPage = new RequestPage(model);
await requestPage.ExecuteAsync(httpContext);
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class NotFoundPageMiddlewareExtensions
{
public static IApplicationBuilder UseNotFoundPageMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<NotFoundPageMiddleware>();
}
}
public class RequestPage : BaseView
{
private readonly IEnumerable<NotFoundRequest> _requests;
public RequestPage(IEnumerable<NotFoundRequest> requests)
{
_requests = requests;
}
public override async Task ExecuteAsync()
{
WriteLiteral("\r\n");
Response.ContentType = "text/html";
WriteLiteral(@"
<!DOCTYPE html>
<html>
<head>
<meta charset=""utf-8"" />
<title>Fix 404s</title>
<script src=""//ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.1.min.js""></script>
<style>
body {
font-size: .813em;
white-space: nowrap;
margin: 20px;
}
col:nth-child(2n) {
background-color: #FAFAFA;
}
form {
display: inline-block;
}
h1 {
margin-left: 25px;
}
table {
margin: 0px auto;
border-collapse: collapse;
border-spacing: 0px;
table-layout: fixed;
width: 100%;
}
td, th {
padding: 4px;
}
thead {
font-size: 1em;
font-family: Arial;
}
tr {
height: 23px;}
#requestHeader {
border-bottom: solid 1px gray;
border-top: solid 1px gray;
margin-bottom: 2px;
font-size: 1em;
line-height: 2em;
}
.collapse {
color: black;
float: right;
font-weight: normal;
width: 1em;
}
.date, .time {
width: 70px;
}
.logHeader {
border-bottom: 1px solid lightgray;
color: gray;
text-align: left;
}
.logState {
text-overflow: ellipsis;
overflow: hidden;
}
.logTd {
border-left: 1px solid gray;
padding: 0px;
}
.logs {
width: 80%;
}
.logRow:hover {
background-color: #D6F5FF;
}
.requestRow>td {
border-bottom: solid 1px gray;
}
.severity {
width: 80px;
}
.summary {
color: black;
line-height: 1.8em;
}
.summary>th {
font-weight: normal;
}
.tab {
margin-left: 30px;
}
#viewOptions {
margin: 20px;
}
#viewOptions > * {
margin: 5px;
}
body {
font-family: 'Segoe UI', Tahoma, Arial, Helvtica, sans-serif;
line-height: 1.4em;
}
h1 {
font-family: 'Segoe UI', Helvetica, sans-serif;
font-size: 2.5em;
}
td {
text-overflow: ellipsis;
overflow: hidden;
}
tr:nth-child(2n) {
background-color: #F6F6F6;
}
.critical {
background-color: red;
color: white;
}
.error {
color: red;
}
.information {
color: blue;
}
.debug {
color: black;
}
.warning {
color: orange;
}
</style>
</head>
<body>
<h1>Fix 404s</h1>");
// render requests
WriteLiteral(@"
<table>
<thead id=""requestHeader"">
<th class=""path"">Path</th>
<th>404 Count</th>
<th>Corrected Path</th>
</thead>
<tbody>
");
foreach (var request in _requests)
{
WriteLiteral(@"<tr class=""requestRow"">");
WriteLiteral($"<td>{request.Path}</td><td>{request.Count}</td>");
if (!String.IsNullOrEmpty(request.CorrectedPath))
{
WriteLiteral($"<td>{ request.CorrectedPath}</td>");
}
else
{ // TODO: UrlEncode request.Path
WriteLiteral(@"<td><input type=""text"" /> <a href=""?path=" + request.Path + @"&fixedPath="" class=""fixLink"">Save</a></td>");
}
WriteLiteral("</tr>");
}
WriteLiteral(@"
</tbody>
</table>
<script type=""text/javascript"">
$(function() {
$("".fixLink"").click(function(event) {
event.preventDefault();
url = $(this).attr(""href"");
url += $(this).prev().val();
document.location = url;
});
});
</script>
</body>
</html>
");
}
}
} | 21.281022 | 153 | 0.597496 | [
"MIT"
] | ardalis/NotFoundMiddlewareSample | src/NotFoundMiddlewareSample/Middleware/NotFoundPageMiddleware.cs | 5,831 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using Xunit;
namespace System.Globalization.Tests
{
public class TaiwanCalendarToDateTime
{
public static IEnumerable<object[]> ToDateTime_TestData()
{
yield return new object[] { 1, 1, 1, 0, 0, 0, 0 };
yield return new object[] { 8088, 12, 31, 23, 59, 59, 999 };
Random random = new Random(-55);
yield return new object[]
{
TaiwanCalendarUtilities.RandomYear(),
random.Next(1, 13),
random.Next(1, 29),
random.Next(0, 24),
random.Next(0, 60),
random.Next(0, 60),
random.Next(0, 1000)
};
}
[Theory]
[MemberData(nameof(ToDateTime_TestData))]
public void ToDateTime(
int year,
int month,
int day,
int hour,
int minute,
int second,
int millisecond
)
{
TaiwanCalendar calendar = new TaiwanCalendar();
DateTime expected = new DateTime(
year + 1911,
month,
day,
hour,
minute,
second,
millisecond
);
Assert.Equal(
expected,
calendar.ToDateTime(year, month, day, hour, minute, second, millisecond)
);
Assert.Equal(
expected,
calendar.ToDateTime(year, month, day, hour, minute, second, millisecond, 0)
);
Assert.Equal(
expected,
calendar.ToDateTime(year, month, day, hour, minute, second, millisecond, 1)
);
}
}
}
| 29.5 | 91 | 0.482794 | [
"MIT"
] | belav/runtime | src/libraries/System.Globalization.Calendars/tests/TaiwanCalendar/TaiwanCalendarToDateTime.cs | 1,947 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.