content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HappyLogging")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HappyLogging")]
[assembly: AssemblyCopyright("Copyright © Productive Rage 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d2f6e473-37a3-441d-ad95-a0ce5adcce72")]
// 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.2.2.0")]
[assembly: AssemblyFileVersion("1.2.2.0")]
| 39.111111 | 85 | 0.725142 | [
"MIT"
] | dionrhys/HappyLogging | HappyLogging/Properties/AssemblyInfo.cs | 1,411 | C# |
using System;
using System.Linq;
namespace TanmaNabu.Core.Extensions
{
public static class EnumExtension
{
public static string AllowedValues<T>(this T item)
{
return $"Allowed values: {string.Join(", ", Enum.GetValues(item.GetType()).Cast<T>().ToList())}";
}
}
}
| 22.428571 | 109 | 0.61465 | [
"MIT"
] | kubagdynia/TanmaNabu | TanmaNabu/Core/Extensions/EnumExtension.cs | 316 | C# |
using System;
using RazorTechnologies.TagHelpers.Core.Annotations;
namespace RazorTechnologies.TagHelpers.LayoutManager.Controls.Attributes
{
[System.AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public sealed class DataViewLableVMAttribute : BaseViewModelAttribute, IViewModelControlAttribute
{
public DataViewLableVMAttribute(string lable, string separator = " : ")
{
Lable = lable;
Separator = separator;
}
public string Lable { get; private set; }
public string Separator { get; private set; }
}
}
| 29.809524 | 101 | 0.699681 | [
"Apache-2.0"
] | arsalanfallahpour/RazorTechnologies | Source/Helpers/TagHelpers/Source/LayoutManager/Controls/Lable/DataViewLableVMAttribute.cs | 628 | 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.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.DesignerAttribute;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Implementation.TodoComments;
using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Serialization;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.TodoComments;
using Microsoft.CodeAnalysis.UnitTests;
using Microsoft.VisualStudio.Threading;
using Nerdbank.Streams;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.Next.UnitTests.Remote
{
[UseExportProvider]
[Trait(Traits.Feature, Traits.Features.RemoteHost)]
public class ServiceHubServicesTests
{
private static TestWorkspace CreateWorkspace(Type[] additionalParts = null)
=> new TestWorkspace(composition: FeaturesTestCompositions.Features.WithTestHostParts(TestHost.OutOfProcess).AddParts(additionalParts));
private static Solution WithChangedOptionsFromRemoteWorkspace(Solution solution, RemoteWorkspace remoteWorkpace)
=> solution.WithChangedOptionsFrom(remoteWorkpace.Options);
[Fact]
[Obsolete]
public void TestRemoteHostCreation()
{
var remoteLogger = new TraceSource("inprocRemoteClient");
var testData = new RemoteHostTestData(new RemoteWorkspaceManager(new SolutionAssetCache()), isInProc: true);
var streams = FullDuplexStream.CreatePair();
using var _ = new RemoteHostService(streams.Item1, new InProcRemoteHostClient.ServiceProvider(remoteLogger, testData));
}
[Fact]
public async Task TestRemoteHostSynchronize()
{
var code = @"class Test { void Method() { } }";
using var workspace = CreateWorkspace();
workspace.InitializeDocuments(LanguageNames.CSharp, files: new[] { code }, openDocuments: false);
using var client = await InProcRemoteHostClient.GetTestClientAsync(workspace).ConfigureAwait(false);
var solution = workspace.CurrentSolution;
await UpdatePrimaryWorkspace(client, solution);
await VerifyAssetStorageAsync(client, solution, includeProjectCones: true);
var remoteWorkpace = client.GetRemoteWorkspace();
solution = WithChangedOptionsFromRemoteWorkspace(solution, remoteWorkpace);
Assert.Equal(
await solution.State.GetChecksumAsync(CancellationToken.None),
await remoteWorkpace.CurrentSolution.State.GetChecksumAsync(CancellationToken.None));
}
[Fact]
public async Task TestRemoteHostTextSynchronize()
{
var code = @"class Test { void Method() { } }";
using var workspace = CreateWorkspace();
workspace.InitializeDocuments(LanguageNames.CSharp, files: new[] { code }, openDocuments: false);
var client = await InProcRemoteHostClient.GetTestClientAsync(workspace).ConfigureAwait(false);
var solution = workspace.CurrentSolution;
// sync base solution
await UpdatePrimaryWorkspace(client, solution);
await VerifyAssetStorageAsync(client, solution, includeProjectCones: true);
// get basic info
var oldDocument = solution.Projects.First().Documents.First();
var oldState = await oldDocument.State.GetStateChecksumsAsync(CancellationToken.None);
var oldText = await oldDocument.GetTextAsync();
// update text
var newText = oldText.WithChanges(new TextChange(TextSpan.FromBounds(0, 0), "/* test */"));
// sync
await client.TryInvokeAsync<IRemoteAssetSynchronizationService>(
(service, cancellationToken) => service.SynchronizeTextAsync(oldDocument.Id, oldState.Text, newText.GetTextChanges(oldText), cancellationToken),
CancellationToken.None);
// apply change to solution
var newDocument = oldDocument.WithText(newText);
var newState = await newDocument.State.GetStateChecksumsAsync(CancellationToken.None);
// check that text already exist in remote side
Assert.True(client.TestData.WorkspaceManager.SolutionAssetCache.TryGetAsset<SerializableSourceText>(newState.Text, out var serializableRemoteText));
Assert.Equal(newText.ToString(), (await serializableRemoteText.GetTextAsync(CancellationToken.None)).ToString());
}
[Fact]
public async Task TestTodoComments()
{
var source = @"
// TODO: Test";
using var workspace = CreateWorkspace();
workspace.SetOptions(workspace.Options.WithChangedOption(TodoCommentOptions.TokenList, "HACK:1|TODO:1|UNDONE:1|UnresolvedMergeConflict:0"));
workspace.InitializeDocuments(LanguageNames.CSharp, files: new[] { source }, openDocuments: false);
using var client = await InProcRemoteHostClient.GetTestClientAsync(workspace).ConfigureAwait(false);
var remoteWorkspace = client.GetRemoteWorkspace();
// Ensure remote workspace is in sync with normal workspace.
var solution = workspace.CurrentSolution;
var assetProvider = await GetAssetProviderAsync(workspace, remoteWorkspace, solution);
var solutionChecksum = await solution.State.GetChecksumAsync(CancellationToken.None);
await remoteWorkspace.UpdatePrimaryBranchSolutionAsync(assetProvider, solutionChecksum, solution.WorkspaceVersion, CancellationToken.None);
var callback = new TodoCommentsListener();
var cancellationTokenSource = new CancellationTokenSource();
using var connection = client.CreateConnection<IRemoteTodoCommentsDiscoveryService>(callback);
var invokeTask = connection.TryInvokeAsync(
(service, callbackId, cancellationToken) => service.ComputeTodoCommentsAsync(callbackId, cancellationToken),
cancellationTokenSource.Token);
var data = await callback.Data.WithTimeout(TimeSpan.FromMinutes(1));
Assert.Equal(solution.Projects.Single().Documents.Single().Id, data.Item1);
Assert.Equal(1, data.Item2.Length);
var commentInfo = data.Item2[0];
Assert.Equal(new TodoCommentData(
documentId: solution.Projects.Single().Documents.Single().Id,
priority: 1,
message: "TODO: Test",
mappedFilePath: null,
originalFilePath: "test1.cs",
originalLine: 2,
mappedLine: 2,
originalColumn: 3,
mappedColumn: 3), commentInfo);
cancellationTokenSource.Cancel();
Assert.True(await invokeTask);
}
private class TodoCommentsListener : ITodoCommentsListener
{
private readonly TaskCompletionSource<(DocumentId, ImmutableArray<TodoCommentData>)> _dataSource = new();
public Task<(DocumentId, ImmutableArray<TodoCommentData>)> Data => _dataSource.Task;
public ValueTask ReportTodoCommentDataAsync(DocumentId documentId, ImmutableArray<TodoCommentData> data, CancellationToken cancellationToken)
{
_dataSource.SetResult((documentId, data));
return ValueTaskFactory.CompletedTask;
}
}
private static async Task<AssetProvider> GetAssetProviderAsync(Workspace workspace, Workspace remoteWorkspace, Solution solution, Dictionary<Checksum, object> map = null)
{
// make sure checksum is calculated
await solution.State.GetChecksumAsync(CancellationToken.None);
map ??= new Dictionary<Checksum, object>();
await solution.AppendAssetMapAsync(includeProjectCones: true, map, CancellationToken.None);
var sessionId = 0;
var storage = new SolutionAssetCache();
var assetSource = new SimpleAssetSource(workspace.Services.GetService<ISerializerService>(), map);
return new AssetProvider(sessionId, storage, assetSource, remoteWorkspace.Services.GetService<ISerializerService>());
}
[Fact]
public async Task TestDesignerAttributes()
{
var source = @"[System.ComponentModel.DesignerCategory(""Form"")] class Test { }";
using var workspace = CreateWorkspace();
workspace.InitializeDocuments(LanguageNames.CSharp, files: new[] { source }, openDocuments: false);
using var client = await InProcRemoteHostClient.GetTestClientAsync(workspace).ConfigureAwait(false);
var remoteWorkspace = client.GetRemoteWorkspace();
var cancellationTokenSource = new CancellationTokenSource();
var solution = workspace.CurrentSolution;
// Ensure remote workspace is in sync with normal workspace.
var assetProvider = await GetAssetProviderAsync(workspace, remoteWorkspace, solution);
var solutionChecksum = await solution.State.GetChecksumAsync(CancellationToken.None);
await remoteWorkspace.UpdatePrimaryBranchSolutionAsync(assetProvider, solutionChecksum, solution.WorkspaceVersion, CancellationToken.None);
var callback = new DesignerAttributeListener();
using var connection = client.CreateConnection<IRemoteDesignerAttributeDiscoveryService>(callback);
var invokeTask = connection.TryInvokeAsync(
(service, callbackId, cancellationToken) => service.StartScanningForDesignerAttributesAsync(callbackId, cancellationToken),
cancellationTokenSource.Token);
var infos = await callback.Infos;
Assert.Equal(1, infos.Length);
var info = infos[0];
Assert.Equal("Form", info.Category);
Assert.Equal(solution.Projects.Single().Documents.Single().Id, info.DocumentId);
cancellationTokenSource.Cancel();
Assert.True(await invokeTask);
}
private class DesignerAttributeListener : IDesignerAttributeListener
{
private readonly TaskCompletionSource<ImmutableArray<DesignerAttributeData>> _infosSource = new();
public Task<ImmutableArray<DesignerAttributeData>> Infos => _infosSource.Task;
public ValueTask OnProjectRemovedAsync(ProjectId projectId, CancellationToken cancellationToken)
=> ValueTaskFactory.CompletedTask;
public ValueTask ReportDesignerAttributeDataAsync(ImmutableArray<DesignerAttributeData> infos, CancellationToken cancellationToken)
{
_infosSource.SetResult(infos);
return ValueTaskFactory.CompletedTask;
}
}
[Fact]
public async Task TestUnknownProject()
{
var workspace = CreateWorkspace(new[] { typeof(NoCompilationLanguageServiceFactory) });
var solution = workspace.CurrentSolution.AddProject("unknown", "unknown", NoCompilationConstants.LanguageName).Solution;
using var client = await InProcRemoteHostClient.GetTestClientAsync(workspace).ConfigureAwait(false);
var remoteWorkspace = client.GetRemoteWorkspace();
await UpdatePrimaryWorkspace(client, solution);
await VerifyAssetStorageAsync(client, solution, includeProjectCones: true);
// Only C# and VB projects are supported in Remote workspace.
// See "RemoteSupportedLanguages.IsSupported"
Assert.Empty(remoteWorkspace.CurrentSolution.Projects);
solution = WithChangedOptionsFromRemoteWorkspace(solution, remoteWorkspace);
// No serializable remote options affect options checksum, so the checksums should match.
Assert.Equal(
await solution.State.GetChecksumAsync(CancellationToken.None),
await remoteWorkspace.CurrentSolution.State.GetChecksumAsync(CancellationToken.None));
solution = solution.RemoveProject(solution.ProjectIds.Single());
solution = WithChangedOptionsFromRemoteWorkspace(solution, remoteWorkspace);
Assert.Equal(
await solution.State.GetChecksumAsync(CancellationToken.None),
await remoteWorkspace.CurrentSolution.State.GetChecksumAsync(CancellationToken.None));
}
[Fact]
public async Task TestRemoteHostSynchronizeIncrementalUpdate()
{
using var workspace = CreateWorkspace();
using var client = await InProcRemoteHostClient.GetTestClientAsync(workspace).ConfigureAwait(false);
var remoteWorkspace = client.GetRemoteWorkspace();
var solution = Populate(workspace.CurrentSolution);
// verify initial setup
await UpdatePrimaryWorkspace(client, solution);
await VerifyAssetStorageAsync(client, solution, includeProjectCones: false);
solution = WithChangedOptionsFromRemoteWorkspace(solution, remoteWorkspace);
Assert.Equal(
await solution.State.GetChecksumAsync(CancellationToken.None),
await remoteWorkspace.CurrentSolution.State.GetChecksumAsync(CancellationToken.None));
// incrementally update
solution = await VerifyIncrementalUpdatesAsync(remoteWorkspace, client, solution, csAddition: " ", vbAddition: " ");
Assert.Equal(
await solution.State.GetChecksumAsync(CancellationToken.None),
await remoteWorkspace.CurrentSolution.State.GetChecksumAsync(CancellationToken.None));
// incrementally update
solution = await VerifyIncrementalUpdatesAsync(remoteWorkspace, client, solution, csAddition: "\r\nclass Addition { }", vbAddition: "\r\nClass VB\r\nEnd Class");
Assert.Equal(
await solution.State.GetChecksumAsync(CancellationToken.None),
await remoteWorkspace.CurrentSolution.State.GetChecksumAsync(CancellationToken.None));
}
[Fact]
public void TestRemoteWorkspaceCircularReferences()
{
using var tempRoot = new TempRoot();
var file = tempRoot.CreateDirectory().CreateFile("p1.dll");
file.CopyContentFrom(typeof(object).Assembly.Location);
var p1 = ProjectId.CreateNewId();
var p2 = ProjectId.CreateNewId();
var solutionInfo = SolutionInfo.Create(
SolutionId.CreateNewId(), VersionStamp.Create(), "",
new[]
{
ProjectInfo.Create(
p1, VersionStamp.Create(), "p1", "p1", LanguageNames.CSharp, outputFilePath: file.Path,
projectReferences: new [] { new ProjectReference(p2) }),
ProjectInfo.Create(
p2, VersionStamp.Create(), "p2", "p2", LanguageNames.CSharp,
metadataReferences: new [] { MetadataReference.CreateFromFile(file.Path) })
});
var languages = ImmutableHashSet.Create(LanguageNames.CSharp);
using var remoteWorkspace = new RemoteWorkspace(FeaturesTestCompositions.RemoteHost.GetHostServices(), WorkspaceKind.RemoteWorkspace);
var optionService = remoteWorkspace.Services.GetRequiredService<IOptionService>();
var options = new SerializableOptionSet(languages, optionService, ImmutableHashSet<IOption>.Empty, ImmutableDictionary<OptionKey, object>.Empty, ImmutableHashSet<OptionKey>.Empty);
// this shouldn't throw exception
remoteWorkspace.TrySetCurrentSolution(solutionInfo, workspaceVersion: 1, options, out var solution);
Assert.NotNull(solution);
}
private async Task<Solution> VerifyIncrementalUpdatesAsync(Workspace remoteWorkspace, RemoteHostClient client, Solution solution, string csAddition, string vbAddition)
{
var remoteSolution = remoteWorkspace.CurrentSolution;
var projectIds = solution.ProjectIds;
for (var i = 0; i < projectIds.Count; i++)
{
var projectName = $"Project{i}";
var project = solution.GetProject(projectIds[i]);
var documentIds = project.DocumentIds;
for (var j = 0; j < documentIds.Count; j++)
{
var documentName = $"Document{j}";
var currentSolution = UpdateSolution(solution, projectName, documentName, csAddition, vbAddition);
await UpdatePrimaryWorkspace(client, currentSolution);
var currentRemoteSolution = remoteWorkspace.CurrentSolution;
VerifyStates(remoteSolution, currentRemoteSolution, projectName, documentName);
solution = currentSolution;
remoteSolution = currentRemoteSolution;
Assert.Equal(
await solution.State.GetChecksumAsync(CancellationToken.None),
await remoteSolution.State.GetChecksumAsync(CancellationToken.None));
}
}
return solution;
}
private static void VerifyStates(Solution solution1, Solution solution2, string projectName, string documentName)
{
Assert.True(solution1.Workspace is RemoteWorkspace);
Assert.True(solution2.Workspace is RemoteWorkspace);
SetEqual(solution1.ProjectIds, solution2.ProjectIds);
var (project, document) = GetProjectAndDocument(solution1, projectName, documentName);
var projectId = project.Id;
var documentId = document.Id;
var projectIds = solution1.ProjectIds;
for (var i = 0; i < projectIds.Count; i++)
{
var currentProjectId = projectIds[i];
var projectStateShouldSame = projectId != currentProjectId;
Assert.Equal(projectStateShouldSame, object.ReferenceEquals(solution1.GetProject(currentProjectId).State, solution2.GetProject(currentProjectId).State));
if (!projectStateShouldSame)
{
SetEqual(solution1.GetProject(currentProjectId).DocumentIds, solution2.GetProject(currentProjectId).DocumentIds);
var documentIds = solution1.GetProject(currentProjectId).DocumentIds;
for (var j = 0; j < documentIds.Count; j++)
{
var currentDocumentId = documentIds[j];
var documentStateShouldSame = documentId != currentDocumentId;
Assert.Equal(documentStateShouldSame, object.ReferenceEquals(solution1.GetDocument(currentDocumentId).State, solution2.GetDocument(currentDocumentId).State));
}
}
}
}
private static async Task VerifyAssetStorageAsync(InProcRemoteHostClient client, Solution solution, bool includeProjectCones)
{
var map = await solution.GetAssetMapAsync(includeProjectCones, CancellationToken.None);
var storage = client.TestData.WorkspaceManager.SolutionAssetCache;
TestUtils.VerifyAssetStorage(map, storage);
}
private static Solution UpdateSolution(Solution solution, string projectName, string documentName, string csAddition, string vbAddition)
{
var (_, document) = GetProjectAndDocument(solution, projectName, documentName);
return document.WithText(GetNewText(document, csAddition, vbAddition)).Project.Solution;
}
private static SourceText GetNewText(Document document, string csAddition, string vbAddition)
{
if (document.Project.Language == LanguageNames.CSharp)
{
return SourceText.From(document.State.GetTextSynchronously(CancellationToken.None).ToString() + csAddition);
}
return SourceText.From(document.State.GetTextSynchronously(CancellationToken.None).ToString() + vbAddition);
}
private static (Project, Document) GetProjectAndDocument(Solution solution, string projectName, string documentName)
{
var project = solution.Projects.First(p => string.Equals(p.Name, projectName, StringComparison.OrdinalIgnoreCase));
var document = project.Documents.First(d => string.Equals(d.Name, documentName, StringComparison.OrdinalIgnoreCase));
return (project, document);
}
// make sure we always move remote workspace forward
private int _solutionVersion = 0;
private async Task UpdatePrimaryWorkspace(RemoteHostClient client, Solution solution)
{
var checksum = await solution.State.GetChecksumAsync(CancellationToken.None);
await client.TryInvokeAsync<IRemoteAssetSynchronizationService>(
solution,
async (service, solutionInfo, cancellationToken) => await service.SynchronizePrimaryWorkspaceAsync(solutionInfo, checksum, _solutionVersion++, cancellationToken),
CancellationToken.None);
}
private static Solution Populate(Solution solution)
{
solution = AddProject(solution, LanguageNames.CSharp, new[]
{
"class CS { }",
"class CS2 { }"
}, new[]
{
"cs additional file content"
}, Array.Empty<ProjectId>());
solution = AddProject(solution, LanguageNames.VisualBasic, new[]
{
"Class VB\r\nEnd Class",
"Class VB2\r\nEnd Class"
}, new[]
{
"vb additional file content"
}, new ProjectId[] { solution.ProjectIds.First() });
solution = AddProject(solution, LanguageNames.CSharp, new[]
{
"class Top { }"
}, new[]
{
"cs additional file content"
}, solution.ProjectIds.ToArray());
solution = AddProject(solution, LanguageNames.CSharp, new[]
{
"class OrphanCS { }",
"class OrphanCS2 { }"
}, new[]
{
"cs additional file content",
"cs additional file content2"
}, Array.Empty<ProjectId>());
return solution;
}
private static Solution AddProject(Solution solution, string language, string[] documents, string[] additionalDocuments, ProjectId[] p2pReferences)
{
var projectName = $"Project{solution.ProjectIds.Count}";
var project = solution.AddProject(projectName, $"{projectName}.dll", language)
.AddMetadataReference(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
.AddAnalyzerReference(new AnalyzerFileReference(typeof(object).Assembly.Location, new TestAnalyzerAssemblyLoader()));
var projectId = project.Id;
solution = project.Solution;
for (var i = 0; i < documents.Length; i++)
{
var current = solution.GetProject(projectId);
solution = current.AddDocument($"Document{i}", SourceText.From(documents[i])).Project.Solution;
}
for (var i = 0; i < additionalDocuments.Length; i++)
{
var current = solution.GetProject(projectId);
solution = current.AddAdditionalDocument($"AdditionalDocument{i}", SourceText.From(additionalDocuments[i])).Project.Solution;
}
for (var i = 0; i < p2pReferences.Length; i++)
{
var current = solution.GetProject(projectId);
solution = current.AddProjectReference(new ProjectReference(p2pReferences[i])).Solution;
}
return solution;
}
private static void SetEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual)
{
var expectedSet = new HashSet<T>(expected);
var result = expected.Count() == actual.Count() && expectedSet.SetEquals(actual);
if (!result)
{
Assert.True(result);
}
}
}
}
| 45.789091 | 192 | 0.65355 | [
"MIT"
] | Blokyk/roslyn | src/VisualStudio/Core/Test.Next/Services/ServiceHubServicesTests.cs | 25,186 | C# |
#region LICENSE
/*
File modified by Ellis Spice, 2020
Original file created and released by PlayGen Ltd, 2018
*/
#endregion
using System.Collections.Generic;
using UnityEngine;
namespace BUCK.LocalizationSystem
{
/// <inheritdoc />
/// <summary>
/// Class for setting the options on a Dropdown using the list of keys and sprites provided.
/// </summary>
public abstract class BaseDropdownLocalization : UILocalization
{
/// <summary>
/// The localization options for this dropdown.
/// </summary>
[SerializeField, Tooltip("The localization options for this dropdown.")]
protected LocalizationOptionDataList _options = new LocalizationOptionDataList();
/// <summary>
/// The localization options for this dropdown.
/// </summary>
public List<LocalizationOptionData> Options { get => _options.Options; set { _options.Options = value; Set(); } }
/// <summary>
/// Currently selected value on the Dropdown.
/// </summary>
public virtual int Value { get; protected set; }
/// <summary>
/// Add options to the Options list.
/// </summary>
/// <param name="options">Collection of options to add.</param>
public virtual void AddOptions(IEnumerable<LocalizationOptionData> options)
{
Options.AddRange(options);
Set();
}
/// <summary>
/// Add options to the Options list.
/// </summary>
/// <param name="options">Collection of options to add.</param>
public virtual void AddOptions(IEnumerable<string> options)
{
foreach (var option in options)
{
Options.Add(new LocalizationOptionData(option));
}
Set();
}
/// <summary>
/// Add options to the Options list.
/// </summary>
/// <param name="options">Collection of options to add.</param>
public virtual void AddOptions(IEnumerable<Sprite> options)
{
foreach (var option in options)
{
Options.Add(new LocalizationOptionData(option));
}
Set();
}
/// <summary>
/// Clear the current options and add provided options to the Options list.
/// </summary>
/// <param name="options">Collection of options to replace current list with.</param>
public virtual void ReplaceOptions(IEnumerable<LocalizationOptionData> options)
{
ClearOptions();
AddOptions(options);
}
/// <summary>
/// Clear the current options and add provided options to the Options list.
/// </summary>
/// <param name="options">Collection of options to replace current list with.</param>
public virtual void ReplaceOptions(IEnumerable<string> options)
{
ClearOptions();
AddOptions(options);
}
/// <summary>
/// Clear the current options and add provided options to the Options list.
/// </summary>
/// <param name="options">Collection of options to replace current list with.</param>
public virtual void ReplaceOptions(IEnumerable<Sprite> options)
{
ClearOptions();
AddOptions(options);
}
/// <summary>
/// Clear the current options.
/// </summary>
public virtual void ClearOptions()
{
Options.Clear();
Set();
}
}
} | 33.740741 | 121 | 0.568332 | [
"Apache-2.0"
] | ellisspice/BUCK | Assets/BUCK/Localization System/Scripts/Runtime/BaseDropdownLocalization.cs | 3,646 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using HavenSoft.HexManiac.Core.Models.Code;
using static HavenSoft.HexManiac.Core.Models.HardcodeTablesModel;
namespace HavenSoft.HexManiac.Core.Models {
/// <summary>
/// Shared resources that involve an expensive setup, (so we only want to do it once) but then cannot be edited after being initialized.
/// </summary>
public class Singletons {
private const string TableReferenceFileName = "resources/tableReference.txt";
private const string ConstantReferenceFileName = "resources/constantReference.txt";
private const string ThumbReferenceFileName = "resources/armReference.txt";
private const string ScriptReferenceFileName = "resources/scriptReference.txt";
private const string BattleScriptReferenceFileName = "resources/battleScriptReference.txt";
private const string AnimationScriptReferenceFileName = "resources/animationScriptReference.txt";
public IMetadataInfo MetadataInfo { get; }
public IReadOnlyDictionary<string, GameReferenceTables> GameReferenceTables { get; }
public IReadOnlyDictionary<string, GameReferenceConstants> GameReferenceConstants { get; }
public IReadOnlyList<ConditionCode> ThumbConditionalCodes { get; }
public IReadOnlyList<IInstruction> ThumbInstructionTemplates { get; }
public IReadOnlyList<ScriptLine> ScriptLines { get; }
public IReadOnlyList<ScriptLine> BattleScriptLines { get; }
public IReadOnlyList<ScriptLine> AnimationScriptLines { get; }
public IWorkDispatcher WorkDispatcher { get; }
public Singletons(IWorkDispatcher dispatcher = null) {
MetadataInfo = new MetadataInfo();
GameReferenceTables = CreateGameReferenceTables();
GameReferenceConstants = CreateGameReferenceConstants();
(ThumbConditionalCodes, ThumbInstructionTemplates) = LoadThumbReference();
ScriptLines = LoadScriptReference<XSEScriptLine>(ScriptReferenceFileName);
BattleScriptLines = LoadScriptReference<BSEScriptLine>(BattleScriptReferenceFileName);
AnimationScriptLines = LoadScriptReference<ASEScriptLine>(AnimationScriptReferenceFileName);
WorkDispatcher = dispatcher ?? InstantDispatch.Instance;
}
public Singletons(IMetadataInfo metadataInfo, IReadOnlyDictionary<string, GameReferenceTables> gameReferenceTables) {
MetadataInfo = metadataInfo;
GameReferenceTables = gameReferenceTables;
WorkDispatcher = InstantDispatch.Instance;
}
private IReadOnlyList<ScriptLine> LoadScriptReference<TLine>(string file) where TLine : ScriptLine {
if (!File.Exists(file)) return new List<ScriptLine>();
Func<string, ScriptLine> factory = line => new XSEScriptLine(line);
if (typeof(TLine) == typeof(BSEScriptLine)) factory = line => new BSEScriptLine(line);
if (typeof(TLine) == typeof(ASEScriptLine)) factory = line => new ASEScriptLine(line);
var lines = File.ReadAllLines(file);
var scriptLines = new List<ScriptLine>();
ScriptLine active = null;
foreach (var line in lines) {
if (string.IsNullOrEmpty(line)) continue;
if (!line.StartsWith(" ") && active != null) active = null;
if (line.StartsWith("#")) continue;
if (line.Trim().StartsWith("#") && active != null) {
active.AddDocumentation(line.Trim());
} else {
active = factory(line);
scriptLines.Add(active);
}
}
return scriptLines.ToArray();
}
private static readonly string[] referenceOrder = new string[] { "name", Ruby, Sapphire, Ruby1_1, Sapphire1_1, FireRed, LeafGreen, FireRed1_1, LeafGreen1_1, Emerald, "format" };
private IReadOnlyDictionary<string, GameReferenceTables> CreateGameReferenceTables() {
if (!File.Exists(TableReferenceFileName)) return new Dictionary<string, GameReferenceTables>();
var lines = File.ReadAllLines(TableReferenceFileName);
var tables = new Dictionary<string, List<ReferenceTable>>();
for (int i = 0; i < referenceOrder.Length - 2; i++) tables[referenceOrder[i + 1]] = new List<ReferenceTable>();
foreach (var line in lines) {
var row = line.Trim();
if (row.StartsWith("//")) continue;
var segments = row.Split("//")[0].Split(",");
if (segments.Length != referenceOrder.Length) continue;
var name = segments[0].Trim();
var offset = 0;
if (name.Contains("+")) {
var parts = name.Split("+");
name = parts[0];
int.TryParse(parts[1], NumberStyles.HexNumber, CultureInfo.CurrentCulture, out offset);
} else if (name.Contains("-")) {
var parts = name.Split("-");
name = parts[0];
int.TryParse(parts[1], NumberStyles.HexNumber, CultureInfo.CurrentCulture, out offset);
offset = -offset;
}
var format = segments.Last().Trim();
for (int i = 0; i < referenceOrder.Length - 2; i++) {
var addressHex = segments[i + 1].Trim();
if (addressHex == string.Empty) continue;
if (!int.TryParse(addressHex, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out int address)) continue;
tables[referenceOrder[i + 1]].Add(new ReferenceTable(name, offset, address, format));
}
}
var readonlyTables = new Dictionary<string, GameReferenceTables>();
foreach (var pair in tables) readonlyTables.Add(pair.Key, new GameReferenceTables(pair.Value));
return readonlyTables;
}
private IReadOnlyDictionary<string,GameReferenceConstants> CreateGameReferenceConstants() {
if (!File.Exists(ConstantReferenceFileName)) return new Dictionary<string, GameReferenceConstants>();
var lines = File.ReadAllLines(ConstantReferenceFileName);
var constants = new Dictionary<string, List<ReferenceConstant>>();
for (int i = 0; i < referenceOrder.Length - 2; i++) constants[referenceOrder[i + 1]] = new List<ReferenceConstant>();
foreach (var line in lines) {
if (string.IsNullOrWhiteSpace(line)) continue;
var cleanLine = line.Trim();
if (cleanLine.Length < 6) continue;
if (!char.IsLetter(cleanLine[0])) continue;
var gameCode = cleanLine.Substring(0, 5).ToUpper();
if (!constants.TryGetValue(gameCode, out var collection)) continue;
collection.Add(new ReferenceConstant(cleanLine.Substring(5)));
}
var readonlyConstants = new Dictionary<string, GameReferenceConstants>();
foreach (var pair in constants) readonlyConstants.Add(pair.Key, new GameReferenceConstants(pair.Value));
return readonlyConstants;
}
private (IReadOnlyList<ConditionCode>, IReadOnlyList<IInstruction>) LoadThumbReference() {
var conditionalCodes = new List<ConditionCode>();
var instructionTemplates = new List<IInstruction>();
if (!File.Exists(ThumbReferenceFileName)) return (new List<ConditionCode>(), new List<IInstruction>());
var engineLines = File.ReadAllLines(ThumbReferenceFileName);
foreach (var line in engineLines) {
if (ConditionCode.TryLoadConditionCode(line, out var condition)) conditionalCodes.Add(condition);
else if (Instruction.TryLoadInstruction(line, out var instruction)) instructionTemplates.Add(instruction);
}
return (conditionalCodes, instructionTemplates);
}
}
public static class GameReferenceTableDictionaryExtensions {
public static string[] GuessSources(this IReadOnlyDictionary<string, GameReferenceTables> self, string code, int address) {
var result = self.Count.Range().Select(i => string.Empty).ToArray();
if (!self.TryGetValue(code, out var tables)) return result;
var index = tables.GetIndexOfNearestAddress(address);
var name = tables[index].Name;
var diff = address - tables[index].Address;
var keys = self.Keys.ToArray();
for (int i = 0; i < self.Count; i++) {
var currentTable = self[keys[i]].FirstOrDefault(table => table.Name == name);
if (currentTable == null) continue;
result[i] = (currentTable.Address + diff).ToAddress();
}
return result;
}
}
public class GameReferenceTables : IReadOnlyList<ReferenceTable> {
private readonly IReadOnlyList<ReferenceTable> core;
public ReferenceTable this[string name] => core.FirstOrDefault(table => table.Name == name);
public ReferenceTable this[int index] => core[index];
public int Count => core.Count;
public GameReferenceTables(IReadOnlyList<ReferenceTable> list) => core = list;
public IEnumerator<ReferenceTable> GetEnumerator() => core.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => core.GetEnumerator();
/// <summary>
/// Given an address, finds the reference table nearest to that address
/// and returns its index.
/// </summary>
public int GetIndexOfNearestAddress(int address) {
var distance = int.MaxValue;
var index = -1;
for (int i = 0; i < Count; i++) {
var currentDistance = Math.Abs(this[i].Address - address);
if (currentDistance > distance) continue;
distance = currentDistance;
index = i;
}
return index;
}
}
public class ReferenceTable {
public string Name { get; }
public int Offset { get; }
public int Address { get; }
public string Format { get; }
public ReferenceTable(string name, int offset, int address, string format) => (Name, Offset, Address, Format) = (name, offset, address, format);
public override string ToString() => $"{Address:X6} -> {Name}, {Offset}, {Format}";
}
public class GameReferenceConstants : IReadOnlyList<ReferenceConstant> {
private readonly IReadOnlyList<ReferenceConstant> core;
public ReferenceConstant this[string name] => core.FirstOrDefault(table => table.Name == name);
public ReferenceConstant this[int index] => core[index];
public int Count => core.Count;
public GameReferenceConstants(IReadOnlyList<ReferenceConstant> list) => core = list;
public IEnumerator<ReferenceConstant> GetEnumerator() => core.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => core.GetEnumerator();
}
public class ReferenceConstant {
public IReadOnlyList<int> Addresses { get; }
public string Name { get; }
public int Length { get; }
public int Offset { get; }
public string Note { get; }
// BRPE0:constant.name+1 123456,123456,123456 # note
public ReferenceConstant(string line) {
var parts = line.Substring(1).Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
// Length
if (line[0] == '.') Length = 1;
else if (line[0] == ':') Length = 2;
else throw new NotImplementedException();
// Name/Offset
if (parts[0].Contains("-")) {
var offsetSplit = parts[0].Split('-');
Name = offsetSplit[0];
Offset = -int.Parse(offsetSplit[1]);
} else if (parts[0].Contains("+")) {
var offsetSplit = parts[0].Split('+');
Name = offsetSplit[0];
Offset = int.Parse(offsetSplit[1]);
} else {
Name = parts[0];
}
// Addresses
Addresses = parts[1].Split(',').Select(adr => int.Parse(adr, NumberStyles.HexNumber)).ToList();
// Note
var commentParts = line.Split(new[] { '#' }, 2);
if (commentParts.Length > 1) Note = commentParts[1].Trim();
}
public IEnumerable<StoredMatchedWord> ToStoredMatchedWords() {
foreach (var address in Addresses) {
yield return new StoredMatchedWord(address, Name, Length, Offset, Note);
}
}
}
public interface IMetadataInfo {
string VersionNumber { get; }
}
internal class MetadataInfo : IMetadataInfo {
public string VersionNumber { get; }
public MetadataInfo() {
var assembly = Assembly.GetExecutingAssembly();
var fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
VersionNumber = $"{fvi.FileMajorPart}.{fvi.FileMinorPart}.{fvi.FileBuildPart}";
if (fvi.FilePrivatePart != 0) VersionNumber += "." + fvi.FilePrivatePart;
}
}
}
| 47.316176 | 183 | 0.650738 | [
"MIT"
] | KiraDank/HexManiacAdvance | src/HexManiac.Core/Models/Singletons.cs | 12,872 | C# |
/*
* Copyright (C) 2021 - 2021, SanteSuite Inc. and the SanteSuite Contributors (See NOTICE.md for full copyright notices)
* Copyright (C) 2019 - 2021, Fyfe Software Inc. and the SanteSuite Contributors
* Portions Copyright (C) 2015-2018 Mohawk College of Applied Arts and Technology
*
* 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.
*
* User: fyfej
* Date: 2021-8-5
*/
using Newtonsoft.Json;
using SanteDB.Core.Model.Attributes;
using System;
using System.Xml.Serialization;
namespace SanteDB.Core.Model.Acts
{
/// <summary>
/// Represents the model of a clinical protocol
/// </summary>
/// <remarks>
/// <para>The protocol type is used to store and retrieve the particular definition of a clinical protocol. In
/// SanteDB, a clinical protocol represents a series of steps that *should* be taken by a clinician when caring for
/// a patient.</para>
/// <para>
/// A series of proposed steps generated by these protocol definitions are used to represent a care plan (<see cref="CarePlan"/>).
/// </para>
/// </remarks>
[XmlType(nameof(Protocol), Namespace = "http://santedb.org/model"), JsonObject(nameof(Protocol))]
[KeyLookup(nameof(Name))]
public class Protocol : BaseEntityData
{
/// <summary>
/// Gets or sets the name of the protocol
/// </summary>
[XmlElement("name"), JsonProperty("name")]
public String Name { get; set; }
/// <summary>
/// Gets or sets the handler for this protocol (which can load the definition
/// </summary>
[XmlIgnore, JsonIgnore]
public Type HandlerClass
{
get
{
return System.Type.GetType(this.HandlerClassName);
}
set
{
this.HandlerClassName = value.AssemblyQualifiedName;
}
}
/// <summary>
/// Gets or sets the handler class AQN
/// </summary>
[XmlElement("handlerClass"), JsonProperty("handlerClass")]
public String HandlerClassName { get; set; }
/// <summary>
/// Contains instructions which the handler class can understand
/// </summary>
[XmlIgnore, JsonIgnore]
public byte[] Definition { get; set; }
/// <summary>
/// Gets or sets the OID
/// </summary>
[XmlElement("oid"), JsonProperty("oid")]
public String Oid { get; set; }
/// <summary>
/// Semantic equality
/// </summary>
public override bool SemanticEquals(object obj)
{
var other = obj as Protocol;
if (other == null) return false;
return base.SemanticEquals(obj) &&
this.Name == other.Name;
}
}
} | 34.863158 | 134 | 0.61413 | [
"Apache-2.0"
] | santedb/santedb-model | SanteDB.Core.Model/Acts/Protocol.cs | 3,314 | C# |
using System.Collections.Generic;
using Newtonsoft.Json;
namespace StackExchange.NET.Models
{
public class SuggestedEdits
{
[JsonProperty("proposing_user")]
public ProposingUser ProposingUser { get; set; }
[JsonProperty("creation_date")]
public long CreationDate { get; set; }
[JsonProperty("post_type")]
public Enums.PostType PostType { get; set; }
[JsonProperty("post_id")]
public long PostId { get; set; }
[JsonProperty("suggested_edit_id")]
public long SuggestedEditId { get; set; }
[JsonProperty("comment")]
public string Comment { get; set; }
[JsonProperty("rejection_date", NullValueHandling = NullValueHandling.Ignore)]
public long? RejectionDate { get; set; }
[JsonProperty("tags", NullValueHandling = NullValueHandling.Ignore)]
public List<string> Tags { get; set; }
[JsonProperty("title", NullValueHandling = NullValueHandling.Ignore)]
public string Title { get; set; }
[JsonProperty("approval_date", NullValueHandling = NullValueHandling.Ignore)]
public long? ApprovalDate { get; set; }
}
}
| 27.102564 | 80 | 0.728477 | [
"MIT"
] | gethari/FluentExchange | StackExchange.NET/StackExchange.NET/Models/SuggestedEdits.cs | 1,059 | C# |
//-------------------------------------------------------------------------------------
// Copyright (c) 2014, Anthilla S.r.l. (http://www.anthilla.com)
// All rights reserved.
//
// 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 Anthilla S.r.l. 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 ANTHILLA S.R.L. 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.
//
// 20141110
//-------------------------------------------------------------------------------------
using System;
using System.IO;
using System.Linq;
using antdlib.Common;
using static antdlib.Terminal.Terminal;
using static antdlib.Antdsh.Execute;
using static System.Console;
namespace antdlib.Antdsh {
public class SystemShellMgmt {
/// <summary>
/// 01 - recupero il volume su cui è montato BootExt
/// 02 - uso df {volume} per trovare lo spazio libero, espresso in byte
/// </summary>
public static bool ChechDiskSpace() {
WriteLine("Checking Disk Space");
var blkid = Execute("blkid | grep /dev/sda | grep BootExt");
var volume = blkid.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries).ToArray()[0].Replace(":", "");
var available = Execute($"df -k {volume} | sed -e 1d|head -3").
Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries).ToArray()[3];
var availableInt = Convert.ToInt32(available);
var msg = (availableInt > 0) ? "There's enought disk space for the update" : "Not enough free disk space, try to remove something...";
WriteLine($"{msg}");
return (availableInt > 0);
}
/// <summary>
/// 03 - se c'è spazio libero scarica i file del Kernel
/// li scarica in una cartella tmp e poi li sposta in /mnt/cdrom/Kernel
/// - active-firmware
/// - active-initrd
/// - active-kernel
/// - active-modules
/// 04 - e in /mnt/cdrom/System
/// - active-system
/// </summary>
public static void DownloadNewFiles() {
var firmwareTmp = $"{Parameter.AntdTmpDir}/firmare";
FileSystem.Download("/url/download/firmware", $"{firmwareTmp}");
var initrdTmp = $"{Parameter.AntdTmpDir}/initrd";
FileSystem.Download("/url/download/initrd", $"{initrdTmp}");
var kernelTmp = $"{Parameter.AntdTmpDir}/kernel";
FileSystem.Download("/url/download/kernel", $"{kernelTmp}");
var modulesTmp = $"{Parameter.AntdTmpDir}/modules";
FileSystem.Download("/url/download/modules", $"{modulesTmp}");
var systemTmp = $"{Parameter.AntdTmpDir}/system";
FileSystem.Download("/url/download/system", $"{systemTmp}");
Execute($"cp {firmwareTmp} {Parameter.RepoKernel}");
Execute($"cp {initrdTmp} {Parameter.RepoKernel}");
Execute($"cp {kernelTmp} {Parameter.RepoKernel}");
Execute($"cp {modulesTmp} {Parameter.RepoKernel}");
Execute($"cp {systemTmp} {Parameter.RepoSystem}");
Execute($"rm {Parameter.RepoKernel}/active-firmware");
Execute($"rm {Parameter.RepoKernel}/active-initrd");
Execute($"rm {Parameter.RepoKernel}/active-kernel");
Execute($"rm {Parameter.RepoKernel}/active-modules");
Execute($"rm {Parameter.RepoSystem}/active-system");
Execute($"ln -s {Parameter.RepoKernel}/firmware {Parameter.RepoKernel}/active-firmware");
Execute($"ln -s {Parameter.RepoKernel}/initrd {Parameter.RepoKernel}/active-initrd");
Execute($"ln -s {Parameter.RepoKernel}/kernel {Parameter.RepoKernel}/active-kernel");
Execute($"ln -s {Parameter.RepoKernel}/modules {Parameter.RepoKernel}/active-modules");
Execute($"ln -s {Parameter.RepoSystem}/system {Parameter.RepoSystem}/active-system");
CleanTmp();
}
/// <summary>
/// 05 - copia il file di grub
/// </summary>
public static void CopyGrub() {
WriteLine("Copying grub.conf file");
Execute($"cp /mnt/cdrom/grub/grub.cfg /mnt/cdrom/DIRS/DIR_cfg_antd_config/grub{DateTime.Now.ToString("yyyyMMdd")}.conf");
}
/// <summary>
/// 06 - riavvia il sistema
/// </summary>
public static void Reboot() {
WriteLine("Rebooting system right now!");
Execute("reboot");
}
/// <summary>
/// 07 - il sistema è stato aggiornato (forse) e riavviato con i nuovi file: controlla lo status
/// </summary>
public static void VerifyUpdate() {
var versionInfo = Execute("uname -a").Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries).ToArray()[2];
WriteLine($"This aos version is: {versionInfo}");
}
/// <summary>
/// 08 - se ve tutto bene antd si avvia in automatico al riavvio, la prima cosa che fa è create le units di sistema
/// </summary>
public static void CreateUnitsForSystem() {
WriteLine("Setting system units");
WriteLine("Reload daemon now...");
Execute("systemctl daemon-reload");
}
/// <summary>
/// 09 - controlla la cartella /mnt/cdrom/DIRS e monta il suo contenuto
/// todo: crea file o cartelle se non ci sono
/// </summary>
public static void SetAndMountDirs() {
WriteLine("Mounting directories and files: ");
var directories = Directory.EnumerateDirectories(Parameter.RepoDirs).Where(d => !d.Contains(".ori"));
foreach (var t in directories) {
var path = Path.GetFileName(t);
if (path == null)
continue;
var newPath = path.Replace("_", "/");
WriteLine($"{t} mounted on {newPath}");
Execute($"mount --bind {t} {newPath}");
}
var files = Directory.EnumerateFiles(Parameter.RepoDirs).Where(f => !f.Contains(".ori"));
foreach (var t in files) {
var path = Path.GetFileName(t);
if (path == null)
continue;
var newPath = path.Replace("_", "/");
WriteLine($"{t} mounted on {newPath}");
Execute($"mount --bind {t} {newPath}");
}
}
}
}
| 48.745342 | 146 | 0.586519 | [
"BSD-3-Clause"
] | Heather/Antd | antdlib/Antdsh/SystemShellMgmt.cs | 7,854 | C# |
//
// Enums.cs
//
// Authors:
// Alan McGovern alan.mcgovern@gmail.com
//
// Copyright (C) 2006 Alan McGovern
//
// 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;
namespace MonoTorrent
{
public enum DhtState
{
NotReady,
Initialising,
Ready
}
}
namespace MonoTorrent.Common
{
public enum ListenerStatus
{
Listening,
PortNotFree,
NotListening
}
public enum PeerStatus
{
Available,
Connecting,
Connected
}
public enum Direction
{
None,
Incoming,
Outgoing
}
public enum TorrentState
{
Stopped,
Paused,
Downloading,
Seeding,
Hashing,
Stopping,
Error,
Metadata
}
public enum Priority
{
DoNotDownload = 0,
Lowest = 1,
Low = 2,
Normal = 4,
High = 8,
Highest = 16,
Immediate = 32
}
public enum TrackerState
{
Ok,
Offline,
InvalidResponse
}
public enum TorrentEvent
{
None,
Started,
Stopped,
Completed
}
public enum PeerConnectionEvent
{
IncomingConnectionReceived,
OutgoingConnectionCreated,
Disconnected
}
public enum PieceEvent
{
BlockWriteQueued,
BlockNotRequested,
BlockWrittenToDisk,
HashPassed,
HashFailed
}
public enum PeerListType
{
NascentPeers,
CandidatePeers,
OptimisticUnchokeCandidatePeers
}
}
| 20.866142 | 73 | 0.624151 | [
"ECL-2.0"
] | 727021/MCLawl | MCLawl/Queue/Enums.cs | 2,650 | C# |
using System;
using ACMESharp.Authorizations;
using PKISharp.WACS.Plugins.Interfaces;
using PKISharp.WACS.Services;
namespace PKISharp.WACS.Plugins.ValidationPlugins
{
/// <summary>
/// Base implementation for all validation plugins
/// </summary>
public abstract class Validation<TOptions, TChallenge> : IValidationPlugin where TChallenge : IChallengeValidationDetails
{
protected ILogService _log;
protected string _identifier;
protected TChallenge _challenge;
protected TOptions _options;
public Validation(ILogService logService, TOptions options, string identifier)
{
_log = logService;
_identifier = identifier;
_options = options;
}
/// <summary>
/// Handle the challenge
/// </summary>
/// <param name="challenge"></param>
public void PrepareChallenge(IChallengeValidationDetails challenge)
{
if (challenge.GetType() != typeof(TChallenge))
{
throw new InvalidOperationException();
}
else
{
_challenge = (TChallenge)challenge;
PrepareChallenge();
}
}
/// <summary>
/// Handle the challenge
/// </summary>
/// <param name="challenge"></param>
public abstract void PrepareChallenge();
/// <summary>
/// Clean up after validation
/// </summary>
public abstract void CleanUp();
#region IDisposable
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
CleanUp();
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
#endregion
}
}
| 26.012821 | 125 | 0.54411 | [
"Apache-2.0"
] | FuseCP-TRobinson/win-acme | src/main/Plugins/ValidationPlugins/Validation.cs | 2,031 | C# |
using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Miru.Consolables;
using Miru.Core;
using Miru.Storages;
namespace Miru.Testing
{
public static class StorageTestServiceCollectionExtensions
{
public static IServiceCollection AddTestStorage(this IServiceCollection services)
{
return services.AddStorage<TestStorage>();
}
public static FormFile FormFile(this ITestFixture fixture, MiruPath path, string contentType)
{
var stream = File.OpenRead(path);
var file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(path))
{
Headers = new HeaderDictionary(),
ContentType = contentType
};
return file;
}
}
} | 28.533333 | 101 | 0.632009 | [
"MIT"
] | MiruFx/Miru | src/Miru.Testing/StorageTestServiceCollectionExtensions.cs | 856 | C# |
namespace ConDep.Dsl
{
public interface IOfferAwsBootstrapEbsOptions
{
IOfferAwsBootstrapEbsOptions DeleteOnTermination(bool delete);
IOfferAwsBootstrapEbsOptions Encrypted(bool encrypted);
IOfferAwsBootstrapEbsOptions Iops(int iops);
IOfferAwsBootstrapEbsOptions SnapshotId(string id);
IOfferAwsBootstrapEbsOptions VolumeSize(int sizeInGb);
IOfferAwsBootstrapEbsOptions VolumeType(string type);
IOfferAwsBootstrapEbsOptions VolumeType(AwsBootstrapVolumeType type);
}
} | 41.307692 | 77 | 0.77095 | [
"BSD-2-Clause"
] | kjelliverb/condep-dsl-operations-aws | src/ConDep.Dsl.Operations.Aws/Ec2/IOfferAwsBootstrapEbsOptions.cs | 537 | C# |
using System;
using System.Collections.Generic;
namespace SolidSoft.AMFCore.Messaging.Api.Messaging
{
/// <summary>
/// Event object corresponds to the connect/disconnect events among providers/consumers and pipes.
/// </summary>
public class PipeConnectionEvent
{
/// <summary>
/// A provider connects as pull mode.
/// </summary>
public const int PROVIDER_CONNECT_PULL = 0;
/// <summary>
/// A provider connects as push mode.
/// </summary>
public const int PROVIDER_CONNECT_PUSH = 1;
/// <summary>
/// A provider disconnects.
/// </summary>
public const int PROVIDER_DISCONNECT = 2;
/// <summary>
/// A consumer connects as pull mode.
/// </summary>
public const int CONSUMER_CONNECT_PULL = 3;
/// <summary>
/// A consumer connects as push mode.
/// </summary>
public const int CONSUMER_CONNECT_PUSH = 4;
/// <summary>
/// A consumer disconnects.
/// </summary>
public const int CONSUMER_DISCONNECT = 5;
/// <summary>
/// Provider.
/// </summary>
private IProvider _provider;
/// <summary>
/// Gets or sets pipe connection provider.
/// </summary>
public IProvider Provider
{
get { return _provider; }
set { _provider = value; }
}
/// <summary>
/// Consumer.
/// </summary>
private IConsumer _consumer;
/// <summary>
/// Gets or sets pipe connection consumer.
/// </summary>
public IConsumer Consumer
{
get { return _consumer; }
set { _consumer = value; }
}
/// <summary>
/// Event type.
/// </summary>
private int _type;
/// <summary>
/// Gets or sets event type.
/// </summary>
public int Type
{
get { return _type; }
set { _type = value; }
}
/// <summary>
/// Params map.
/// </summary>
Dictionary<string, object> _parameterMap;
/// <summary>
/// Gets or sets event parameters.
/// </summary>
public Dictionary<string, object> ParameterMap
{
get { return _parameterMap; }
set { _parameterMap = value; }
}
object _source;
/// <summary>
/// Gets or sets the vent source.
/// </summary>
public object Source
{
get { return _source; }
set { _source = value; }
}
/// <summary>
/// Construct an object with the specific pipe as the source.
/// </summary>
/// <param name="source">A pipe that triggers this event.</param>
public PipeConnectionEvent(Object source)
{
_source = source;
}
}
} | 29.298077 | 103 | 0.4936 | [
"MIT"
] | SolidSoft-Lda/AMFCore | SolidSoft.AMFCore/Messaging/Api/Messaging/PipeConnectionEvent.cs | 3,049 | C# |
using System;
namespace Anvyl.JsonLocalizer.Presentation.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
} | 20.909091 | 70 | 0.691304 | [
"MIT"
] | JTOne123/Anvyl.JsonLocalizer | src/Anvyl.JsonLocalizer.Presentation/Models/ErrorViewModel.cs | 230 | 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 firehose-2015-08-04.normal.json service model.
*/
using System;
using Amazon.Runtime;
using Amazon.Util.Internal;
namespace Amazon.KinesisFirehose
{
/// <summary>
/// Configuration for accessing Amazon KinesisFirehose service
/// </summary>
public partial class AmazonKinesisFirehoseConfig : ClientConfig
{
private static readonly string UserAgentString =
InternalSDKUtils.BuildUserAgentString("3.3.8.9");
private string _userAgent = UserAgentString;
/// <summary>
/// Default constructor
/// </summary>
public AmazonKinesisFirehoseConfig()
{
this.AuthenticationServiceName = "firehose";
}
/// <summary>
/// The constant used to lookup in the region hash the endpoint.
/// </summary>
public override string RegionEndpointServiceName
{
get
{
return "firehose";
}
}
/// <summary>
/// Gets the ServiceVersion property.
/// </summary>
public override string ServiceVersion
{
get
{
return "2015-08-04";
}
}
/// <summary>
/// Gets the value of UserAgent property.
/// </summary>
public override string UserAgent
{
get
{
return _userAgent;
}
}
}
} | 26.4375 | 106 | 0.591962 | [
"Apache-2.0"
] | woellij/aws-sdk-net | sdk/src/Services/KinesisFirehose/Generated/AmazonKinesisFirehoseConfig.cs | 2,115 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Serialization;
using taskt.UI.CustomControls;
using taskt.UI.Forms;
namespace taskt.Core.Automation.Commands
{
[Serializable]
[Attributes.ClassAttributes.Group("Dictionary Commands")]
[Attributes.ClassAttributes.SubGruop("Dictionary Action")]
[Attributes.ClassAttributes.Description("This command Reads a Config file and stores it into a Dictionary.")]
[Attributes.ClassAttributes.UsesDescription("Use this command when you want to load a config file.")]
[Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop and OLEDB to achieve automation.")]
public class LoadDictionaryCommand : ScriptCommand
{
[XmlAttribute]
[Attributes.PropertyAttributes.PropertyDescription("Please Enter the Dictionary Variable Name")]
[Attributes.PropertyAttributes.PropertyUIHelper(Attributes.PropertyAttributes.PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)]
[Attributes.PropertyAttributes.InputSpecification("Enter a name for a Dictionary.")]
[Attributes.PropertyAttributes.SampleUsage("**myDictionary** or **{{{vDictionary}}}**")]
[Attributes.PropertyAttributes.Remarks("")]
[Attributes.PropertyAttributes.PropertyShowSampleUsageInDescription(true)]
[Attributes.PropertyAttributes.PropertyInstanceType(Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.Dictionary)]
[Attributes.PropertyAttributes.PropertyRecommendedUIControl(Attributes.PropertyAttributes.PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)]
[Attributes.PropertyAttributes.PropertyIsVariablesList(true)]
public string v_DictionaryName { get; set; }
[XmlAttribute]
[Attributes.PropertyAttributes.PropertyDescription("Please indicate the Workbook File Path")]
[Attributes.PropertyAttributes.PropertyUIHelper(Attributes.PropertyAttributes.PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)]
[Attributes.PropertyAttributes.PropertyUIHelper(Attributes.PropertyAttributes.PropertyUIHelper.UIAdditionalHelperType.ShowFileSelectionHelper)]
[Attributes.PropertyAttributes.InputSpecification("Enter or Select the path to the applicable file that should be loaded into the Dictionary.")]
[Attributes.PropertyAttributes.SampleUsage("**C:\\temp\\myfile.xlsx** or **{{{vFilePath}}}**")]
[Attributes.PropertyAttributes.Remarks("If file does not contain extension, supplement extensions supported by Excel.\nIf file does not contain folder path, file will be opened in the same folder as script file.")]
[Attributes.PropertyAttributes.PropertyShowSampleUsageInDescription(true)]
[Attributes.PropertyAttributes.PropertyTextBoxSetting(1, false)]
public string v_FilePath { get; set; }
[XmlAttribute]
[Attributes.PropertyAttributes.PropertyDescription("Please indicate the Sheet Name")]
[Attributes.PropertyAttributes.PropertyUIHelper(Attributes.PropertyAttributes.PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)]
[Attributes.PropertyAttributes.InputSpecification("Enter the sheet name of the workbook to be read.")]
[Attributes.PropertyAttributes.SampleUsage("**Sheet1** or **{{{vSheet}}}**")]
[Attributes.PropertyAttributes.Remarks("Sheet has one table")]
[Attributes.PropertyAttributes.PropertyShowSampleUsageInDescription(true)]
[Attributes.PropertyAttributes.PropertyTextBoxSetting(1, false)]
public string v_SheetName { get; set; }
[XmlAttribute]
[Attributes.PropertyAttributes.PropertyDescription("Please indicate the Key Column")]
[Attributes.PropertyAttributes.PropertyUIHelper(Attributes.PropertyAttributes.PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)]
[Attributes.PropertyAttributes.InputSpecification("Enter the key column name to create a Dictionary off of.")]
[Attributes.PropertyAttributes.SampleUsage("**Key** or **{{{vKeyColumn}}}**")]
[Attributes.PropertyAttributes.Remarks("This value is NOT Column Index Value like A, B. Please specify table column name.")]
[Attributes.PropertyAttributes.PropertyShowSampleUsageInDescription(true)]
[Attributes.PropertyAttributes.PropertyTextBoxSetting(1, false)]
public string v_KeyColumn { get; set; }
[XmlAttribute]
[Attributes.PropertyAttributes.PropertyDescription("Please indicate the Value Column")]
[Attributes.PropertyAttributes.PropertyUIHelper(Attributes.PropertyAttributes.PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)]
[Attributes.PropertyAttributes.InputSpecification("Enter a value column name to create a Dictionary off of.")]
[Attributes.PropertyAttributes.SampleUsage("**Value** or **{{{vValueColumn}}}**")]
[Attributes.PropertyAttributes.Remarks("This value is NOT Column Index Value like A, B. Please specify table column name.")]
[Attributes.PropertyAttributes.PropertyShowSampleUsageInDescription(true)]
[Attributes.PropertyAttributes.PropertyTextBoxSetting(1, false)]
public string v_ValueColumn { get; set; }
public LoadDictionaryCommand()
{
this.CommandName = "LoadDictionaryCommand";
this.SelectionName = "Load Dictionary";
this.CommandEnabled = true;
this.CustomRendering = true;
}
public override void RunCommand(object sender)
{
var engine = (Core.Automation.Engine.AutomationEngineInstance)sender;
var vInstance = DateTime.Now.ToString();
var vFilePath = v_FilePath.ConvertToUserVariable(sender);
var vSheet = v_SheetName.ConvertToUserVariable(sender);
var vKeyColumn = v_KeyColumn.ConvertToUserVariable(sender);
var vValueColumn = v_ValueColumn.ConvertToUserVariable(sender);
vFilePath = Core.FilePathControls.formatFilePath(vFilePath, engine);
if (!System.IO.File.Exists(vFilePath) && !FilePathControls.hasExtension(vFilePath))
{
string[] exts = new string[] { ".xlsx", ".xlsm", ".xls"};
foreach (string ext in exts)
{
if (System.IO.File.Exists(vFilePath + ext))
{
vFilePath += ext;
break;
}
}
}
//var vDictionaryName = v_DictionaryName;
//var vDictionary = LookupVariable(engine);
//if (vDictionary != null)
//{
// vDictionaryName = vDictionary.VariableName;
//}
//var newExcelSession = new Microsoft.Office.Interop.Excel.Application
//{
// Visible = false
//};
//engine.AddAppInstance(vInstance, newExcelSession);
//var excelObject = engine.GetAppInstance(vInstance);
//Microsoft.Office.Interop.Excel.Application excelInstance = (Microsoft.Office.Interop.Excel.Application)excelObject;
//Query required from workbook using OLEDB
DatasetCommands dataSetCommand = new DatasetCommands();
string param = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""" + vFilePath + @""";Extended Properties=""Excel 12.0;HDR=YES;IMEX=1""";
string queue = "Select " + vKeyColumn + "," + vValueColumn + " From " + "[" + vSheet + "$]";
// DBG
//MessageBox.Show(param + "\n" + queue);
DataTable requiredData = dataSetCommand.CreateDataTable(param, queue);
var dictlist = requiredData.AsEnumerable().Select(x => new
{
keys = (string)x[v_KeyColumn],
values = (string)x[v_ValueColumn]
}).ToList();
Dictionary<string, string> outputDictionary = new Dictionary<string, string>();
foreach (var dict in dictlist)
{
outputDictionary.Add(dict.keys, dict.values);
}
outputDictionary.StoreInUserVariable(engine, v_DictionaryName);
//Script.ScriptVariable newDictionary = new Script.ScriptVariable
//{
// VariableName = vDictionaryName,
// VariableValue = outputDictionary
//};
//close excel
//excelInstance.Quit();
//remove instance
//engine.RemoveAppInstance(vInstance);
//Overwrites variable if it already exists
//if (engine.VariableList.Exists(x => x.VariableName == newDictionary.VariableName))
//{
// Script.ScriptVariable tempDictionary = engine.VariableList.Where(x => x.VariableName == newDictionary.VariableName).FirstOrDefault();
// engine.VariableList.Remove(tempDictionary);
//}
//engine.VariableList.Add(newDictionary);
}
private Script.ScriptVariable LookupVariable(Core.Automation.Engine.AutomationEngineInstance sendingInstance)
{
//search for the variable
var requiredVariable = sendingInstance.VariableList.Where(var => var.VariableName == v_DictionaryName).FirstOrDefault();
//if variable was not found but it starts with variable naming pattern
if ((requiredVariable == null) && (v_DictionaryName.StartsWith(sendingInstance.engineSettings.VariableStartMarker)) && (v_DictionaryName.EndsWith(sendingInstance.engineSettings.VariableEndMarker)))
{
//reformat and attempt
var reformattedVariable = v_DictionaryName.Replace(sendingInstance.engineSettings.VariableStartMarker, "").Replace(sendingInstance.engineSettings.VariableEndMarker, "");
requiredVariable = sendingInstance.VariableList.Where(var => var.VariableName == reformattedVariable).FirstOrDefault();
}
return requiredVariable;
}
public override List<Control> Render(frmCommandEditor editor)
{
base.Render(editor);
//create standard group controls
//RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_FilePath", this, editor));
//RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_DictionaryName", this, editor));
//RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_SheetName", this, editor));
//RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_KeyColumn", this, editor));
//RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_ValueColumn", this, editor));
var ctrls = CommandControls.MultiCreateInferenceDefaultControlGroupFor(this, editor);
RenderedControls.AddRange(ctrls);
return RenderedControls;
}
public override string GetDisplayValue()
{
return base.GetDisplayValue() + " [Load Dictionary from '" + v_FilePath + "' and store in: '" +v_DictionaryName+ "']";
}
public override bool IsValidate(frmCommandEditor editor)
{
base.IsValidate(editor);
if (String.IsNullOrEmpty(v_DictionaryName))
{
this.IsValid = false;
this.validationResult += "Dictionary Variable Name is empty.\n";
}
if (String.IsNullOrEmpty(v_FilePath))
{
this.IsValid = false;
this.validationResult += "Workbook file path is empty.\n";
}
if (String.IsNullOrEmpty(v_SheetName))
{
this.IsValid = false;
this.validationResult += "Sheet name is empty.\n";
}
if (String.IsNullOrEmpty(v_KeyColumn))
{
this.IsValid = false;
this.validationResult += "Key column is empty.\n";
}
if (String.IsNullOrEmpty(v_ValueColumn))
{
this.IsValid = false;
this.validationResult += "Value column is empty.\n";
}
return this.IsValid;
}
}
} | 52.261603 | 222 | 0.667447 | [
"Apache-2.0"
] | rcktrncn/taskt | taskt/Core/Automation/Commands/Dictionary/LoadDictionaryCommand.cs | 12,388 | C# |
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using UnityEngine.UI;
using naichilab.InputEvents;
public class TouchListenerSample : MonoBehaviour
{
private List<string> logs = new List<string> ();
const int MAX_LOGS = 30;
public Circle circle;
void OnEnable ()
{
TouchManager.Instance.Drag += OnSwipe;
TouchManager.Instance.TouchStart += OnTouchStart;
TouchManager.Instance.TouchEnd += OnTouchEnd;
TouchManager.Instance.FlickStart += OnFlickStart;
TouchManager.Instance.FlickComplete += OnFlickComplete;
}
void OnDisable ()
{
if (TouchManager.Instance != null) {
TouchManager.Instance.Drag -= OnSwipe;
TouchManager.Instance.TouchStart -= OnTouchStart;
TouchManager.Instance.TouchEnd -= OnTouchEnd;
TouchManager.Instance.FlickStart -= OnFlickStart;
TouchManager.Instance.FlickComplete -= OnFlickComplete;
}
}
void OnTouchStart (object sender, CustomInputEventArgs e)
{
string text = string.Format ("OnTouchStart X={0} Y={1}", e.Input.ScreenPosition.x, e.Input.ScreenPosition.y);
Debug.Log (text);
this.circle.Speed = Vector3.zero;
this.circle.SetPosition (e.Input.ScreenPosition);
}
void OnTouchEnd (object sender, CustomInputEventArgs e)
{
string text = string.Format ("OnTouchEnd X={0} Y={1}", e.Input.ScreenPosition.x, e.Input.ScreenPosition.y);
Debug.Log (text);
this.circle.Speed = Vector3.zero;
}
void OnSwipe (object sender, CustomInputEventArgs e)
{
string text = string.Format ("OnSwipe Pos[{0},{1}] Move[{2},{3}]", new object[] {
e.Input.ScreenPosition.x.ToString ("0"),
e.Input.ScreenPosition.y.ToString ("0"),
e.Input.DeltaPosition.x.ToString ("0"),
e.Input.DeltaPosition.y.ToString ("0")
});
this.circle.MovePosition (e.Input.DeltaPosition);
}
void OnFlickStart (object sender, FlickEventArgs e)
{
string text = string.Format ("OnFlickStart [{0}] Speed[{1}] Accel[{2}] ElapseTime[{3}]", new object[] {
e.Direction.ToString (),
e.Speed.ToString ("0.000"),
e.Acceleration.ToString ("0.000"),
e.ElapsedTime.ToString ("0.000"),
});
Debug.Log (text);
}
void OnFlickComplete (object sender, FlickEventArgs e)
{
string text = string.Format ("OnFlickComplete [{0}] Speed[{1}] Accel[{2}] ElapseTime[{3}]", new object[] {
e.Direction.ToString (),
e.Speed.ToString ("0.000"),
e.Acceleration.ToString ("0.000"),
e.ElapsedTime.ToString ("0.000")
});
Debug.Log (text);
text = string.Format ("[{0}]->[{1}]", new object[]{ e.StartInput.ScreenPosition, e.EndInput.ScreenPosition });
Debug.Log (text);
this.circle.Speed = (e.MovedDistance / e.ElapsedTime);
}
}
| 30.450549 | 114 | 0.670516 | [
"MIT"
] | naichilab/Unity-TouchManager | Assets/naichilab/TouchManager/Sample/TouchListenerSample.cs | 2,773 | C# |
using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace VoxelImporter.grendgine_collada
{
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(ElementName="sources", Namespace="http://www.collada.org/2005/11/COLLADASchema", IsNullable=true)]
public partial class Grendgine_Collada_Shader_Sources
{
[XmlAttribute("entry")]
public string Entry;
[XmlElement(ElementName = "inline")]
public string[] Inline;
[XmlElement(ElementName = "import")]
public Grendgine_Collada_Ref_String[] Import;
}
}
| 25.96 | 142 | 0.765794 | [
"MIT"
] | Syrapt0r/Protocol-18 | Assets/VoxelImporter/Scripts/Editor/Library/Collada_Main/Collada_FX/Shaders/Grendgine_Collada_Shader_Sources.cs | 649 | C# |
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace XamarinOxyPlot.ViewModels.Base
{
public abstract class ViewModelBase : INotifyPropertyChanged
{
public virtual void OnAppearing(object navigationContext)
{
}
public virtual void OnDisappearing()
{
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged([CallerMemberName]string propertyName = "")
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
| 25.576923 | 84 | 0.657143 | [
"MIT"
] | jsuarezruiz/OxyPlot-Xamarin.Forms-Sample | src/XamarinOxyPlot/XamarinOxyPlot/ViewModels/Base/ViewModelBase.cs | 667 | C# |
using ServiceLayer;
namespace ExampleServices
{
public class DocumentServicePlugin : Plugin
{
private readonly DocumentResultTypeHttpConverter _documentResultTypeConverter = new DocumentResultTypeHttpConverter();
public DocumentServicePlugin() : base("Document Service")
{
}
public override void Install()
{
Context.ResultTypeConverters.Install(_documentResultTypeConverter);
}
public override void Uninstall()
{
Context.ResultTypeConverters.Uninstall(_documentResultTypeConverter);
}
}
}
| 25.416667 | 126 | 0.67377 | [
"MIT"
] | davidomid/ServiceLayer | ExampleServices/Plugins/DocumentServicePlugin.cs | 612 | C# |
//-----------------------------------------------------------------------
// <copyright file="StateException.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.Azure.Monitoring.SmartDetectors.State
{
using System;
using System.Runtime.Serialization;
/// <summary>
/// Represents a base class for all state related exceptions
/// </summary>
[Serializable]
public class StateException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="StateException"/> class
/// </summary>
public StateException()
: base()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="StateException"/> class
/// </summary>
/// <param name="message">The exception message</param>
public StateException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="StateException"/> class
/// </summary>
/// <param name="innerException">The actual exception that was thrown when saving state</param>
public StateException(Exception innerException)
: base(null, innerException)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="StateException"/> class
/// </summary>
/// <param name="message">The exception message</param>
/// <param name="innerException">The actual exception that was thrown when saving state</param>
public StateException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="StateException"/> class
/// </summary>
/// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown</param>
/// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
protected StateException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
} | 37.75 | 146 | 0.575331 | [
"MIT"
] | Azure/SmartDetectorsMonitoringAppliance | src/SDK/SmartDetectorsSDK/State/StateException.cs | 2,418 | C# |
namespace DXFramework.UI
{
public class UIConstraint
{
public UIConstraint(Edge controlEdge, UIControl anchor, Edge anchorEdge, float distance = 0f, ConstraintCategory constraintCategory = ConstraintCategory.All)
{
ControlEdge = controlEdge;
Anchor = anchor;
AnchorEdge = anchorEdge;
Distance = distance;
Category = constraintCategory;
}
public Edge ControlEdge { get; }
public UIControl Anchor { get; }
public Edge AnchorEdge { get; }
public float Distance { get; }
public ConstraintCategory Category { get; }
}
} | 23.083333 | 159 | 0.727437 | [
"MIT"
] | adamxi/SharpDXFramework | DXFramework/UI/Constrainer/UIConstraint.cs | 556 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Miniblink
{
public class WKEException : Exception
{
public WKEException(string message = null) : base(message)
{
}
}
public class WKECreateException : WKEException
{
}
public class WKEFunctionNotFondException : WKEException
{
public string FunctionName { get; }
public WKEFunctionNotFondException(string functionName)
{
FunctionName = functionName;
}
}
}
| 18.75 | 66 | 0.64 | [
"MIT"
] | h1213159982/HDF | Example/WinForm/Miniblink/Miniblink/WKEException.cs | 602 | C# |
/*
* Copyright 2016 Google Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
using Grpc.Core;
using System;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Google.Api.Gax.Grpc.IntegrationTests
{
/// <summary>
/// Test fixture for a simple gRPC service hosted on a local port. This can be manually constructed,
/// or used as a dependency for a test collection.
/// </summary>
[CollectionDefinition(nameof(TestServiceFixture))]
public class TestServiceFixture : IDisposable, ICollectionFixture<TestServiceFixture>
{
private readonly Server _server;
public int Port => _server.Ports.First().BoundPort;
public string Endpoint => $"localhost:{Port}";
public TestServiceFixture()
{
_server = new Server
{
Services = { TestService.BindService(new TestServiceImpl()) },
Ports = { new ServerPort("localhost", 0, ServerCredentials.Insecure) }
};
_server.Start();
}
public void Dispose()
{
Task.Run(() => _server.ShutdownAsync()).Wait();
}
private class TestServiceImpl : TestService.TestServiceBase
{
public override Task<SimpleResponse> DoSimple(SimpleRequest request, ServerCallContext context)
=> Task.FromResult(new SimpleResponse { Name = request.Name });
}
}
}
| 32.326531 | 107 | 0.63952 | [
"BSD-3-Clause"
] | Global19/gax-dotnet | Google.Api.Gax.Grpc.IntegrationTests/TestServiceFixture.cs | 1,586 | C# |
namespace CoreDrawablesGenerator.Generator
{
public class DrawablesOutput
{
public Drawable[,] Drawables { get; }
public string ImagePath { get; }
public int ImageWidth { get; }
public int ImageHeight { get; }
public int OffsetX { get; }
public int OffsetY { get; }
public DrawablesOutput(Drawable[,] drawables) : this(drawables, drawables.GetLength(0) * 32, drawables.GetLength(1) * 8, 0, 0) { }
public DrawablesOutput(Drawable[,] drawables, int imageWidth, int imageHeight, int offsetX, int offsetY, string imagePath = null)
{
Drawables = drawables;
ImageWidth = imageWidth;
ImageHeight = imageHeight;
OffsetX = offsetX;
OffsetY = offsetY;
ImagePath = imagePath;
}
}
}
| 33.52 | 138 | 0.600239 | [
"MIT"
] | Silverfeelin/Starbound-CoreDrawablesGenerator | CoreDrawablesGenerator/Generator/DrawablesOutput.cs | 840 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Collections;
using Microsoft.Azure.Batch;
using System.Collections.Generic;
namespace Microsoft.Azure.Commands.Batch.Models
{
public class NewVMUserParameters : VMOperationParameters
{
public NewVMUserParameters(BatchAccountContext context, string poolName, string vmName, PSVM vm, IEnumerable<BatchClientBehavior> additionalBehaviors = null)
: base(context, poolName, vmName, vm, additionalBehaviors)
{ }
/// <summary>
/// The name of the local windows account created.
/// </summary>
public string VMUserName { get; set; }
/// <summary>
/// The account password.
/// </summary>
public string Password { get; set; }
/// <summary>
/// The expiry time.
/// </summary>
public DateTime ExpiryTime { get; set; }
/// <summary>
/// The administrative privilege level of the user account.
/// </summary>
public bool IsAdmin { get; set; }
}
}
| 37.571429 | 167 | 0.589354 | [
"MIT"
] | Nilambari/azure-powershell | src/ResourceManager/Batch/Commands.Batch/Models/NewVMUserParameters.cs | 1,795 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using dtasetup;
using dtasetup.gui;
using dtasetup.domain.constants;
namespace dtasetup.domain
{
public static class VideoBackBuffer
{
public static void DisableBackBuffer()
{
Logger.Log("Disabling back buffer in VRAM.");
try
{
BinaryWriter writer = new BinaryWriter(File.Open(ProgramConstants.gamepath + ProgramConstants.LAUNCHER_EXENAME, FileMode.Open, FileAccess.ReadWrite));
writer.Seek(568367, SeekOrigin.Begin);
writer.BaseStream.Position = 568367;
byte[] bytesToWrite = new byte[4];
bytesToWrite[0] = 0x90;
bytesToWrite[1] = 0x90;
bytesToWrite[2] = 0x90;
bytesToWrite[3] = 0x90;
writer.BaseStream.Write(bytesToWrite, 0, 4);
writer.Close();
}
catch
{
Logger.Log("Disabling back buffer in VRAM failed.");
}
}
public static void EnableBackBuffer()
{
Logger.Log("Enabling back buffer in VRAM.");
try
{
BinaryWriter writer = new BinaryWriter(File.Open(ProgramConstants.gamepath + ProgramConstants.LAUNCHER_EXENAME, FileMode.Open, FileAccess.ReadWrite));
writer.Seek(568367, SeekOrigin.Begin);
writer.BaseStream.Position = 568367;
byte[] bytesToWrite = new byte[4];
bytesToWrite[0] = 0x3C;
bytesToWrite[1] = 0x01;
bytesToWrite[2] = 0x75;
bytesToWrite[3] = 0x0C;
writer.BaseStream.Write(bytesToWrite, 0, 4);
writer.Close();
}
catch
{
Logger.Log("Disabling back buffer in VRAM failed.");
}
}
}
}
| 33.716667 | 167 | 0.524963 | [
"MIT"
] | 0999312/xna-cncnet-client | DXMainClient/Domain/VideoBackBuffer.cs | 1,966 | C# |
using Hl7.Fhir.Model;
using Hl7.Fhir.Tests;
using Hl7.Fhir.Utility;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Tasks = System.Threading.Tasks;
namespace Hl7.Fhir.Tests
{
/// <summary>
/// All this is to do is read all the unit test data to ensure that they are all compatible with STU3
/// (By just trying to de-serialize all the content)
/// </summary>
[TestClass]
public class TestDataVersionCheck
{
[TestMethod] // not everything parses correctly
public async Tasks.Task VerifyAllTestData()
{
string location = typeof(TestDataHelper).GetTypeInfo().Assembly.Location;
var path = Path.GetDirectoryName(location) + "\\TestData";
Console.WriteLine(path);
StringBuilder issues = new StringBuilder();
await ValidateFolder(path, path, issues);
Console.Write(issues.ToString());
Assert.AreEqual("", issues.ToString());
}
private async Tasks.Task ValidateFolder(string basePath, string path, StringBuilder issues)
{
var xmlParser = new Fhir.Serialization.FhirXmlParser();
var jsonParser = new Fhir.Serialization.FhirJsonParser();
Console.WriteLine($"Validating test files in {path.Replace(basePath, "")}");
foreach (var item in Directory.EnumerateFiles(path))
{
try
{
if (item.EndsWith(".dll"))
continue;
if (item.EndsWith(".exe"))
continue;
if (item.EndsWith(".pdb"))
continue;
string content = File.ReadAllText(item);
if (new FileInfo(item).Extension == ".xml")
{
Console.WriteLine($" {item.Replace(path+"\\", "")}");
await xmlParser.ParseAsync<Resource>(content);
}
else if (new FileInfo(item).Extension == ".json")
{
Console.WriteLine($" {item.Replace(path + "\\", "")}");
await jsonParser.ParseAsync<Resource>(content);
}
else
{
Console.WriteLine($" {item} (unknown content)");
}
}
catch (Exception ex)
{
Console.WriteLine($" {item} (parse error)");
Console.WriteLine($" --> {ex.Message}");
issues.AppendLine($" {item} (parse error) --> {ex.Message}");
}
}
foreach (var item in Directory.EnumerateDirectories(path))
{
await ValidateFolder(basePath, item, issues);
}
}
}
} | 39.025641 | 105 | 0.512812 | [
"BSD-3-Clause"
] | FirelyTeam/fhir-net-api | src/Hl7.Fhir.Core.Tests/TestDataVersionCheck.cs | 3,046 | C# |
using System;
using MongoDB.Bson.Serialization.Attributes;
namespace ETModel
{
[BsonIgnoreExtraElements]
public abstract class Component : Object, IDisposable
{
[BsonIgnore]
public long InstanceId { get; private set; }
[BsonIgnore]
private bool isFromPool;
[BsonIgnore]
public bool IsFromPool
{
get
{
return this.isFromPool;
}
set
{
this.isFromPool = value;
if (!this.isFromPool)
{
return;
}
this.InstanceId = IdGenerater.GenerateId();
Game.EventSystem.Add(this);
}
}
[BsonIgnore]
public bool IsDisposed
{
get
{
return this.InstanceId == 0;
}
}
[BsonIgnore]
public Component Parent { get; set; }
public T GetParent<T>() where T : Component
{
return this.Parent as T;
}
[BsonIgnore]
public Entity Entity
{
get
{
return this.Parent as Entity;
}
}
protected Component()
{
this.InstanceId = IdGenerater.GenerateId();
}
public virtual void Dispose()
{
if (this.IsDisposed)
{
return;
}
// 触发Destroy事件
Game.EventSystem.Destroy(this);
Game.EventSystem.Remove(this.InstanceId);
this.InstanceId = 0;
if (this.IsFromPool)
{
Game.ObjectPool.Recycle(this);
}
}
public override void EndInit()
{
Game.EventSystem.Deserialize(this);
}
}
} | 14.532609 | 54 | 0.62902 | [
"MIT"
] | Seven15/ET | Unity/Assets/Model/Base/Object/Component.cs | 1,347 | C# |
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
namespace YamlDotNet.Serialization
{
/// <summary>
/// An object that contains part of a YAML stream.
/// </summary>
public sealed class StreamFragment : IYamlSerializable
{
private readonly List<ParsingEvent> events = new List<ParsingEvent>();
/// <summary>
/// Gets or sets the events.
/// </summary>
/// <value>The events.</value>
public IList<ParsingEvent> Events
{
get
{
return events;
}
}
#region IYamlSerializable Members
/// <summary>
/// Reads this object's state from a YAML parser.
/// </summary>
/// <param name="parser"></param>
void IYamlSerializable.ReadYaml(IParser parser)
{
events.Clear();
int depth = 0;
do
{
if (!parser.MoveNext())
{
throw new InvalidOperationException("The parser has reached the end before deserialization completed.");
}
events.Add(parser.Current);
depth += parser.Current.NestingIncrease;
} while (depth > 0);
Debug.Assert(depth == 0);
}
/// <summary>
/// Writes this object's state to a YAML emitter.
/// </summary>
/// <param name="emitter"></param>
void IYamlSerializable.WriteYaml(IEmitter emitter)
{
foreach (var item in events)
{
emitter.Emit(item);
}
}
#endregion
}
} | 31 | 110 | 0.678545 | [
"MIT"
] | Schumix/YamlDotNet | YamlDotNet/Serialization/StreamFragment.cs | 2,666 | C# |
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
*
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter;
namespace Org.OpenAPITools.Model
{
/// <summary>
/// FileSchemaTestClass
/// </summary>
[DataContract]
public partial class FileSchemaTestClass : IEquatable<FileSchemaTestClass>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="FileSchemaTestClass" /> class.
/// </summary>
/// <param name="file">file.</param>
/// <param name="files">files.</param>
public FileSchemaTestClass(File file = default(File), List<File> files = default(List<File>))
{
this.File = file;
this.Files = files;
}
/// <summary>
/// Gets or Sets File
/// </summary>
[DataMember(Name="file", EmitDefaultValue=false)]
public File File { get; set; }
/// <summary>
/// Gets or Sets Files
/// </summary>
[DataMember(Name="files", EmitDefaultValue=false)]
public List<File> Files { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class FileSchemaTestClass {\n");
sb.Append(" File: ").Append(File).Append("\n");
sb.Append(" Files: ").Append(Files).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as FileSchemaTestClass);
}
/// <summary>
/// Returns true if FileSchemaTestClass instances are equal
/// </summary>
/// <param name="input">Instance of FileSchemaTestClass to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(FileSchemaTestClass input)
{
if (input == null)
return false;
return
(
this.File == input.File ||
(this.File != null &&
this.File.Equals(input.File))
) &&
(
this.Files == input.Files ||
this.Files != null &&
input.Files != null &&
this.Files.SequenceEqual(input.Files)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.File != null)
hashCode = hashCode * 59 + this.File.GetHashCode();
if (this.Files != null)
hashCode = hashCode * 59 + this.Files.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 32.978873 | 159 | 0.562246 | [
"Apache-2.0"
] | 0x0c/openapi-generator | samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs | 4,683 | C# |
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Mozlite.Extensions.Security.Permissions;
using MS.Extensions.Security;
namespace MS.Areas.Security.Pages.Admin
{
/// <summary>
/// 锁定用户。
/// </summary>
[PermissionAuthorize(Security.Permissions.Users)]
public class LockoutModel : ModelBase
{
private readonly IUserManager _userManager;
public LockoutModel(IUserManager userManager)
{
_userManager = userManager;
}
public class InputModel
{
/// <summary>
/// 用户Id。
/// </summary>
public int UserId { get; set; }
public DateTimeOffset LockoutEnd { get; set; }
public string Reason { get; set; }
}
[BindProperty]
public InputModel Input { get; set; }
public void OnGet(int id)
{
Input = new InputModel
{
UserId = id,
LockoutEnd = DateTimeOffset.Now.AddDays(1)
};
}
public async Task<IActionResult> OnPostAsync()
{
if (await _userManager.LockoutAsync(Input.UserId, Input.LockoutEnd))
{
var user = await _userManager.FindByIdAsync(Input.UserId);
var message = $"锁定了用户“{user.UserName}”到{Input.LockoutEnd}";
if (!string.IsNullOrEmpty(Input.Reason))
message += $"(原因:{Input.Reason})!";
else
message += "!";
Log(message);
return Success($"你已经成功锁定了用户“{user.UserName}”!");
}
return Error("锁定用户失败!");
}
public async Task<IActionResult> OnPostUnlockAsync(int id)
{
if (await _userManager.LockoutAsync(id))
{
var user = await _userManager.FindByIdAsync(id);
Log($"解锁了用户“{user.UserName}”的信息!");
return Success($"你已经成功解锁了用户“{user.UserName}”!");
}
return Error("解锁用户失败!");
}
}
} | 28.863014 | 80 | 0.525866 | [
"Apache-2.0"
] | Mozlite/Docs | src/MS.Extensions.Security/Areas/Security/Pages/Admin/Lockout.cshtml.cs | 2,253 | C# |
using System;
using System.Globalization;
using System.Linq;
using System.Text;
using Microsoft.EntityFrameworkCore;
using P01_BillsPaymentSystem.Data;
using P01_BillsPaymentSystem.Data.Models;
using P01_BillsPaymentSystem.Initializer;
namespace P01_BillsPaymentSystem
{
public class StartUp
{
public static void Main(string[] args)
{
using (var context = new BillsPaymentSystemContext())
{
int userId = int.Parse(Console.ReadLine());
User user = GetUser(context, userId);
if (user == null)
{
Console.WriteLine($"User with id {userId} not found!");
}
else
{
string userInfo = GetUserInfo(user);
Console.WriteLine(userInfo);
}
PayBills(context, user, 10);
}
}
private static void PayBills(BillsPaymentSystemContext context, User user, decimal amount)
{
decimal bankAccountMoney = user.PaymentMethods
.Where(p => p.BankAccount != null)
.Sum(p => p.BankAccount.Balance);
decimal creditcardMoney = user.PaymentMethods
.Where(p => p.CreditCard != null)
.Sum(p => p.CreditCard.LimitLeft);
decimal totalMoney = bankAccountMoney + creditcardMoney;
if (totalMoney < amount)
{
Console.WriteLine("Insufficient funds!");
}
else
{
BankAccount[] bankAccounts = user.PaymentMethods
.Where(p => p.BankAccount != null)
.Select(p => p.BankAccount)
.OrderBy(b => b.BankAccountId).ToArray();
foreach (BankAccount account in bankAccounts)
{
if (account.Balance >= amount)
{
account.Withdraw(amount);
amount = 0;
break;
}
else
{
account.Withdraw(account.Balance);
amount -= account.Balance;
}
}
if (amount > 0)
{
CreditCard[] creditCards = user.PaymentMethods
.Where(p => p.CreditCard != null)
.Select(p => p.CreditCard)
.OrderBy(c => c.CreditCardId)
.ToArray();
foreach (CreditCard card in creditCards)
{
if (card.LimitLeft >= amount)
{
card.Withdraw(amount);
break;
}
else
{
card.Withdraw(card.LimitLeft);
amount -= card.LimitLeft;
}
}
}
context.SaveChanges();
}
}
private static string GetUserInfo(User user)
{
var userInfo = new StringBuilder();
userInfo.AppendLine($"User: {user.FirstName} {user.LastName}");
userInfo.AppendLine("Bank Accounts:");
BankAccount[] bankAccounts = user.PaymentMethods
.Where(p => p.BankAccount != null)
.Select(p => p.BankAccount).ToArray();
foreach (BankAccount account in bankAccounts)
{
userInfo.AppendLine($"-- ID: {account.BankAccountId}");
userInfo.AppendLine($"--- Balance: {account.Balance:F2}");
userInfo.AppendLine($"--- Bank: {account.BankName}");
userInfo.AppendLine($"--- SWIFT: {account.SwiftCode}");
}
userInfo.AppendLine("Credit Cards:");
CreditCard[] creditCards = user.PaymentMethods
.Where(p => p.CreditCard != null)
.Select(p => p.CreditCard).ToArray();
foreach (CreditCard card in creditCards)
{
userInfo.AppendLine($"-- ID: {card.CreditCardId}");
userInfo.AppendLine($"--- Limit: {card.Limit:F2}");
userInfo.AppendLine($"--- Money Owed: {card.MoneyOwed:F2}");
userInfo.AppendLine($"--- Limit Left:: {card.LimitLeft:F2}");
userInfo.AppendLine(
$"--- Expiration Date: {card.ExpirationDate.ToString("yyyy/MM", CultureInfo.InvariantCulture)}");
}
return userInfo.ToString().TrimEnd();
}
private static User GetUser(BillsPaymentSystemContext context, int userId)
{
User user = context.Users
.Where(u => u.UserId == userId)
.Include(u => u.PaymentMethods)
.ThenInclude(p => p.BankAccount)
.Include(u => u.PaymentMethods)
.ThenInclude(p => p.CreditCard)
.FirstOrDefault();
return user;
}
}
}
| 33.006289 | 117 | 0.467416 | [
"MIT"
] | ViktorAleksandrov/SoftUni--CSharp-DB-Fundamentals | Databases Advanced - Entity Framework/06. Advanced Relations and Aggregation/P01_BillsPaymentSystem/StartUp.cs | 5,250 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Ecm.V20190719.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DetachDisksRequest : AbstractModel
{
/// <summary>
/// 将要卸载的云硬盘ID, 通过[DescribeDisks](/document/product/362/16315)接口查询,单次请求最多可卸载10块弹性云盘。
/// </summary>
[JsonProperty("DiskIds")]
public string[] DiskIds{ get; set; }
/// <summary>
/// 对于非共享型云盘,会忽略该参数;对于共享型云盘,该参数表示要从哪个CVM实例上卸载云盘。
/// </summary>
[JsonProperty("InstanceId")]
public string InstanceId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamArraySimple(map, prefix + "DiskIds.", this.DiskIds);
this.SetParamSimple(map, prefix + "InstanceId", this.InstanceId);
}
}
}
| 31.921569 | 92 | 0.652334 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Ecm/V20190719/Models/DetachDisksRequest.cs | 1,772 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1.Views.access
{
public partial class SuccessForRegister : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
} | 20.117647 | 64 | 0.707602 | [
"MIT"
] | kevinkda/UnivCourse | Course Experiment Report/ASP.NET 2019-2020-2/提交版/ASP.NETMVC应用程序设计课程设计-2017102531010-唐可寅/项目文件/CourseSolutionASP.NET/WebApplication1/Views/access/SuccessForRegister.aspx.cs | 344 | C# |
// ReSharper disable once CheckNamespace
namespace HandyControlDemo.UserControl
{
/// <summary>
/// TimeBarDemoCtl.xaml 的交互逻辑
/// </summary>
public partial class TimeBarDemoCtl
{
public TimeBarDemoCtl()
{
InitializeComponent();
}
}
}
| 19.666667 | 41 | 0.60339 | [
"MIT"
] | 82571701/HandyControl | HandyControlDemo/UserControl/Controls/TimeBarDemoCtl.xaml.cs | 307 | 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("08. Number as array")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("08. Number as array")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("dfee57d7-a442-4db9-b0c4-91b52aab7fc3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.135135 | 84 | 0.742027 | [
"MIT"
] | AyrFX/03.Telerik-Academy-2016-CSharp-Part-2-Homewoks | 03. Methods/08. Number as array/Properties/AssemblyInfo.cs | 1,414 | C# |
using SkiAnalyze.Core.Common;
using SkiAnalyze.Core.Entities.GondolaAggregate;
using SkiAnalyze.Core.Interfaces;
using SkiAnalyze.Core.Entities.PisteAggregate;
using SkiAnalyze.Core.Entities.TrackAggregate;
using SkiAnalyze.Core.Entities.TrackAggregate.Specifications;
using SkiAnalyze.SharedKernel.Interfaces;
namespace SkiAnalyze.Core.Services.Stats;
public class StatsService : IStatsService
{
private readonly IReadRepository<TrackPoint> _trackPointRepository;
private readonly IReadRepository<Run> _runRepository;
public StatsService(IReadRepository<TrackPoint> trackPointRepository,
IReadRepository<Run> runRepository)
{
_trackPointRepository = trackPointRepository;
_runRepository = runRepository;
}
public async Task<List<BaseStatValue<PisteDifficulty, double>>> GetDifficultyStats(int trackId)
{
var points = await _trackPointRepository.ListAsync(new GetTrackPointsForTrackSpec(trackId));
var results = new List<BaseStatValue<PisteDifficulty, double>>();
foreach(PisteDifficulty difficulty in Enum.GetValues(typeof(PisteDifficulty)))
{
var count = points.Count(x => x.Piste?.Difficulty == difficulty);
var percentage = (double) count / points.Count;
results.Add(new BaseStatValue<PisteDifficulty, double>(difficulty, percentage));
}
return results;
}
public async Task<List<BaseStatValue<Gondola, int>>> GetTopGondolas(int trackId)
{
var runs = await _runRepository.ListAsync(new GetRunsForTrackSpec(trackId));
var results = new List<BaseStatValue<Gondola, int>>();
var dictionary = new Dictionary<Gondola, int>();
foreach (var run in runs.Where(x => x.Gondola != null))
{
if (dictionary.ContainsKey(run.Gondola!))
{
dictionary[run.Gondola!]++;
} else
{
dictionary[run.Gondola!] = 1;
}
}
return dictionary
.Select(x => new BaseStatValue<Gondola, int>(x.Key, x.Value))
.OrderByDescending(x => x.Value)
.Take(3)
.ToList();
}
public async Task<List<BaseStatValue<PisteDifficulty, double>>> GetAverageHeartRatePerPisteDifficulty(int trackId)
{
var trackPoints = await _trackPointRepository.ListAsync(new GetTrackPointsForTrackSpec(trackId));
var grouped = trackPoints
.Where(x => x.Piste != null)
.GroupBy(x => x.Piste!.Difficulty);
var stats = grouped
.Where(x => x.Key != null)
.Select(x => new BaseStatValue<PisteDifficulty, double?>(x.Key!.Value, x.Average(x => x.HeartRate)));
return stats.Where(x => x.Value.HasValue)
.Select(x => new BaseStatValue<PisteDifficulty, double>(x.Key, x.Value!.Value))
.OrderBy(x => x.Key)
.ToList();
}
public async Task<List<BaseStatValue<string, int>>> GetGondolaCountByProperty(int trackId, string propertyName)
{
var runs = await _runRepository.ListAsync(new GetRunsForTrackSpec(trackId));
var results = new List<BaseStatValue<string, int>>();
var dictionary = new Dictionary<string, int>();
string GetValue(Gondola gondola)
{
return propertyName switch
{
"bubble" => BoolToString(gondola.Bubble),
"heating" => BoolToString(gondola.Heating),
"occupancy" => gondola.Occupancy?.ToString() ?? "unknown",
_ => gondola.Type
};
}
foreach (var run in runs.Where(x => x.Gondola != null))
{
var value = GetValue(run.Gondola!);
if (dictionary.ContainsKey(value))
{
dictionary[value]++;
}
else
{
dictionary[value] = 1;
}
}
return dictionary
.Select(x => new BaseStatValue<string, int>(x.Key, x.Value))
.OrderByDescending(x => x.Value)
.ToList();
}
private string BoolToString(bool? value)
{
if (!value.HasValue)
return "unknown";
return value.Value ? "yes" : "no";
}
}
| 35.081967 | 118 | 0.612383 | [
"MIT"
] | soerenchrist/SkiAnalyze | src/SkiAnalyze.Core/Services/Stats/StatsService.cs | 4,282 | 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("Commands.IotHub")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Commands.IotHub")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("78770a60-b18a-4442-a982-0cee0356f8db")]
// 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.0")]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
| 38.756757 | 85 | 0.728033 | [
"MIT"
] | Acidburn0zzz/azure-powershell | src/ResourceManager/IotHub/Commands.IotHub/Properties/AssemblyInfo.cs | 1,399 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Kinect;
using System.Windows.Media.Media3D;
namespace KinectWithHomeAssistant
{
class ObjLine
{
private Point3D objPoint = new Point3D();
private Vector3D objVector = new Vector3D();
// Takes in elbow point and hand point to determine vectors
public ObjLine(CameraSpacePoint Point_1, CameraSpacePoint Point_2)
{
objPoint.X = Point_1.X;
objPoint.Y = Point_1.Y;
objPoint.Z = Point_1.Z;
objVector.X = Point_2.X - Point_1.X;
objVector.Y = Point_2.Y - Point_1.Y;
objVector.Z = Point_2.Z - Point_2.Z;
}
public Point3D Point { get { return objPoint; } }
public Vector3D Vector { get { return objVector; } }
public Point3D LineIntersect(ObjLine Line)
{
// Find new cross product of the lines
Vector3D perpendicularFromLine1ToLine2 = Vector3D.CrossProduct(Line.Vector, Vector3D.CrossProduct(this.Vector, Line.Vector));
Vector3D perpendicularFromLine2ToLine1 = Vector3D.CrossProduct(this.Vector, Vector3D.CrossProduct(Line.Vector, this.Vector));
// Use Max Coordinates if lines are parallel
if (perpendicularFromLine1ToLine2 == new Vector3D(0, 0, 0))
{
return new Point3D(double.MaxValue, double.MaxValue, double.MaxValue);
}
// Finds ths othogonal projections, QP and PQ
Vector3D orthoVector1 = new Vector3D(Line.Point.X - this.Point.X, Line.Point.Y - this.Point.Y, Line.Point.Z - Line.Point.Z);
Vector3D orthoVector2 = new Vector3D(this.Point.X - Line.Point.X, this.Point.Y - Line.Point.Y, this.Point.Z - Line.Point.Z);
// Create dot product of two lines
double dotProduct1 = Vector3D.DotProduct(perpendicularFromLine1ToLine2, orthoVector1);
double dotProduct2 = Vector3D.DotProduct(perpendicularFromLine2ToLine1, orthoVector2);
// Find positions of points
Point3D point1 = Line.Point + Vector3D.Multiply(Line.Vector, dotProduct1);
Point3D point2 = Line.Point + Vector3D.Multiply(Line.Vector, dotProduct2);
double midX = (point1.X + point2.X) / 2;
double midY = (point1.Y + point2.Y) / 2;
double midZ = (point1.Z + point2.Z) / 2;
// Return mid point
return new Point3D(midX, midY, midZ);
}
}
}
| 38.969697 | 137 | 0.634914 | [
"MIT"
] | croggero/KinectWithHomeAssistant | KinectWithHomeAssistant/Lines.cs | 2,574 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.DataFactory.Inputs
{
/// <summary>
/// The Azure Blob storage.
/// </summary>
public sealed class AzureBlobDatasetArgs : Pulumi.ResourceArgs
{
[Input("annotations")]
private InputList<object>? _annotations;
/// <summary>
/// List of tags that can be used for describing the Dataset.
/// </summary>
public InputList<object> Annotations
{
get => _annotations ?? (_annotations = new InputList<object>());
set => _annotations = value;
}
/// <summary>
/// The data compression method used for the blob storage.
/// </summary>
[Input("compression")]
public Input<object>? Compression { get; set; }
/// <summary>
/// Dataset description.
/// </summary>
[Input("description")]
public Input<string>? Description { get; set; }
/// <summary>
/// The name of the Azure Blob. Type: string (or Expression with resultType string).
/// </summary>
[Input("fileName")]
public Input<object>? FileName { get; set; }
/// <summary>
/// The folder that this Dataset is in. If not specified, Dataset will appear at the root level.
/// </summary>
[Input("folder")]
public Input<Inputs.DatasetFolderArgs>? Folder { get; set; }
/// <summary>
/// The path of the Azure Blob storage. Type: string (or Expression with resultType string).
/// </summary>
[Input("folderPath")]
public Input<object>? FolderPath { get; set; }
/// <summary>
/// The format of the Azure Blob storage.
/// </summary>
[Input("format")]
public Input<object>? Format { get; set; }
/// <summary>
/// Linked service reference.
/// </summary>
[Input("linkedServiceName", required: true)]
public Input<Inputs.LinkedServiceReferenceArgs> LinkedServiceName { get; set; } = null!;
/// <summary>
/// The end of Azure Blob's modified datetime. Type: string (or Expression with resultType string).
/// </summary>
[Input("modifiedDatetimeEnd")]
public Input<object>? ModifiedDatetimeEnd { get; set; }
/// <summary>
/// The start of Azure Blob's modified datetime. Type: string (or Expression with resultType string).
/// </summary>
[Input("modifiedDatetimeStart")]
public Input<object>? ModifiedDatetimeStart { get; set; }
[Input("parameters")]
private InputMap<Inputs.ParameterSpecificationArgs>? _parameters;
/// <summary>
/// Parameters for dataset.
/// </summary>
public InputMap<Inputs.ParameterSpecificationArgs> Parameters
{
get => _parameters ?? (_parameters = new InputMap<Inputs.ParameterSpecificationArgs>());
set => _parameters = value;
}
/// <summary>
/// Columns that define the physical type schema of the dataset. Type: array (or Expression with resultType array), itemType: DatasetSchemaDataElement.
/// </summary>
[Input("schema")]
public Input<object>? Schema { get; set; }
/// <summary>
/// Columns that define the structure of the dataset. Type: array (or Expression with resultType array), itemType: DatasetDataElement.
/// </summary>
[Input("structure")]
public Input<object>? Structure { get; set; }
/// <summary>
/// The root of blob path. Type: string (or Expression with resultType string).
/// </summary>
[Input("tableRootLocation")]
public Input<object>? TableRootLocation { get; set; }
/// <summary>
/// Type of dataset.
/// Expected value is 'AzureBlob'.
/// </summary>
[Input("type", required: true)]
public Input<string> Type { get; set; } = null!;
public AzureBlobDatasetArgs()
{
}
}
}
| 34.531746 | 159 | 0.586302 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/DataFactory/Inputs/AzureBlobDatasetArgs.cs | 4,351 | C# |
using System;
using Adriva.Extensions.Optimization.Abstractions;
using Microsoft.AspNetCore.Hosting;
namespace Adriva.Extensions.Optimization.Web
{
internal static class AssetExtensions
{
/// <summary>
/// Gets the location of the asset that represents either the absolute or relative path that can be used in html.
/// </summary>
/// <param name="asset">The asset that the content will be read.</param>
/// <param name="hostingEnvironment">Current hosting environment.</param>
/// <param name="options">Currently active instance of WebOptimizationOptions class that will be used to construct a Url or path.</param>
/// <returns><A string that represents either the relative or the absolute path of the asset.</returns>
public static string GetWebLocation(this Asset asset, IWebHostEnvironment hostingEnvironment, WebOptimizationOptions options = null)
{
if (null == asset) throw new ArgumentNullException(nameof(asset));
if (null == asset.Location) throw new ArgumentNullException(nameof(asset.Location));
string assetLocation;
if (!asset.Location.IsAbsoluteUri)
{
if (asset.Location.OriginalString.StartsWith("/")) assetLocation = Convert.ToString(asset.Location.OriginalString);
else assetLocation = string.Concat("/", asset.Location.OriginalString);
}
else
{
if (asset.Location.IsFile)
{
Uri webRootUri = new Uri(hostingEnvironment.WebRootPath.EndsWith("/", StringComparison.Ordinal) ? hostingEnvironment.WebRootPath : hostingEnvironment.WebRootPath + "/");
assetLocation = webRootUri.MakeRelativeUri(asset.Location).OriginalString;
}
else return Convert.ToString(asset.Location);
}
return $"{options?.AssetRootUrl}{assetLocation}";
}
}
} | 48.634146 | 189 | 0.648445 | [
"MIT"
] | adriva/coreframework | Optimization/src/Adriva.Extensions.Optimization.Web/AssetExtensions.cs | 1,994 | 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;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.Implementation.Highlighting;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters
{
[ExportHighlighter(LanguageNames.CSharp)]
internal class AsyncAwaitHighlighter : AbstractKeywordHighlighter
{
protected override bool IsHighlightableNode(SyntaxNode node)
=> node.IsReturnableConstruct();
protected override IEnumerable<TextSpan> GetHighlightsForNode(SyntaxNode node, CancellationToken cancellationToken)
{
var spans = new List<TextSpan>();
HighlightRelatedKeywords(node, spans);
return spans;
}
private static void HighlightRelatedKeywords(SyntaxNode node, List<TextSpan> spans)
{
// Highlight async keyword
switch (node)
{
case MethodDeclarationSyntax methodDeclaration:
{
var asyncModifier = methodDeclaration.Modifiers.FirstOrDefault(m => m.Kind() == SyntaxKind.AsyncKeyword);
if (asyncModifier.Kind() != SyntaxKind.None)
{
spans.Add(asyncModifier.Span);
}
break;
}
case LocalFunctionStatementSyntax localFunction:
{
var asyncModifier = localFunction.Modifiers.FirstOrDefault(m => m.Kind() == SyntaxKind.AsyncKeyword);
if (asyncModifier.Kind() != SyntaxKind.None)
{
spans.Add(asyncModifier.Span);
}
break;
}
case AnonymousFunctionExpressionSyntax anonymousFunction:
if (anonymousFunction.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword)
{
spans.Add(anonymousFunction.AsyncKeyword.Span);
}
break;
case AwaitExpressionSyntax awaitExpression:
// Note if there is already a highlight for the previous token, merge it
// with this span. That way, we highlight nested awaits with a single span.
var handled = false;
var awaitToken = awaitExpression.AwaitKeyword;
var previousToken = awaitToken.GetPreviousToken();
if (!previousToken.Span.IsEmpty)
{
var index = spans.FindIndex(s => s.Contains(previousToken.Span));
if (index >= 0)
{
var span = spans[index];
spans[index] = TextSpan.FromBounds(span.Start, awaitToken.Span.End);
handled = true;
}
}
if (!handled)
{
spans.Add(awaitToken.Span);
}
break;
case UsingStatementSyntax usingStatement:
if (usingStatement.AwaitKeyword.Kind() == SyntaxKind.AwaitKeyword)
{
spans.Add(usingStatement.AwaitKeyword.Span);
}
break;
case LocalDeclarationStatementSyntax localDeclaration:
if (localDeclaration.AwaitKeyword.Kind() == SyntaxKind.AwaitKeyword && localDeclaration.UsingKeyword.Kind() == SyntaxKind.UsingKeyword)
{
spans.Add(localDeclaration.AwaitKeyword.Span);
}
break;
case CommonForEachStatementSyntax forEachStatement:
if (forEachStatement.AwaitKeyword.Kind() == SyntaxKind.AwaitKeyword)
{
spans.Add(forEachStatement.AwaitKeyword.Span);
}
break;
}
foreach (var child in node.ChildNodes())
{
// Only recurse if we have anything to do
if (!child.IsReturnableConstruct())
{
HighlightRelatedKeywords(child, spans);
}
}
}
}
}
| 42.327434 | 161 | 0.526448 | [
"Apache-2.0"
] | DustinCampbell/roslyn | src/EditorFeatures/CSharp/Highlighting/KeywordHighlighters/AsyncAwaitHighlighter.cs | 4,785 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace Bookalytics.Migrations
{
public partial class AddingBookTitle : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Title",
table: "Books",
type: "nvarchar(max)",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Title",
table: "Books");
}
}
}
| 25.958333 | 71 | 0.560193 | [
"MIT"
] | iwanmitowski/Bookalytics | Bookalytics/Bookalytics/Migrations/20211007133622_AddingBookTitle.cs | 625 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using frontend.Data;
#nullable disable
namespace frontend.Migrations
{
[DbContext(typeof(DataContext))]
partial class DataContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "6.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("frontend.Meal", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("LastDateTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PhotoPath")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Summary")
.HasColumnType("text");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Meals");
});
#pragma warning restore 612, 618
}
}
}
| 32.59322 | 103 | 0.531981 | [
"MIT"
] | jackyma001/meal | backend/Migrations/DataContextModelSnapshot.cs | 1,925 | C# |
using System;
using System.Net;
using SmartStore.Core;
using SmartStore.Core.Caching;
using SmDir = SmartStore.Core.Domain.Directory;
namespace SmartStore.Services.Directory
{
public partial class GeoCountryLookup : IGeoCountryLookup
{
private readonly IWebHelper _webHelper;
private readonly ICountryService _countryService;
private readonly IRequestCache _requestCache;
private readonly ICacheManager _cache;
public GeoCountryLookup(IWebHelper webHelper, IRequestCache requestCache, ICacheManager cache, ICountryService countryService)
{
this._webHelper = webHelper;
this._requestCache = requestCache;
this._cache = cache;
this._countryService = countryService;
}
private MaxMind.GeoIP.LookupService GetLookupService()
{
return _cache.Get("GeoCountryLookup", () =>
{
var lookupService = new MaxMind.GeoIP.LookupService(_webHelper.MapPath("~/App_Data/GeoIP.dat"));
return lookupService;
});
}
public virtual string LookupCountryCode(string str)
{
if (String.IsNullOrEmpty(str))
return string.Empty;
IPAddress addr;
try
{
addr = IPAddress.Parse(str);
}
catch
{
return string.Empty;
}
return LookupCountryCode(addr);
}
public virtual string LookupCountryCode(IPAddress addr)
{
try
{
var lookupService = GetLookupService();
var country = lookupService.getCountry(addr);
var code = country.getCode();
if (code == "--")
return string.Empty;
return code;
}
catch
{
return string.Empty;
}
}
public virtual string LookupCountryName(string str)
{
if (String.IsNullOrEmpty(str))
return string.Empty;
IPAddress addr;
try
{
addr = IPAddress.Parse(str);
}
catch
{
return string.Empty;
}
return LookupCountryName(addr);
}
public virtual string LookupCountryName(IPAddress addr)
{
try
{
var lookupService = GetLookupService();
var country = lookupService.getCountry(addr);
return country.getName();
}
catch
{
return string.Empty;
}
}
public virtual bool IsEuIpAddress(string ipAddress, out SmDir.Country euCountry)
{
euCountry = null;
if (ipAddress.IsEmpty())
return false;
euCountry = _requestCache.Get("GeoCountryLookup.EuCountry.{0}".FormatInvariant(ipAddress), () =>
{
var countryCode = LookupCountryCode(ipAddress);
if (countryCode.IsEmpty())
return (SmDir.Country)null;
var country = _countryService.GetCountryByTwoLetterIsoCode(countryCode);
return country;
});
if (euCountry == null)
return false;
return euCountry.SubjectToVat;
}
}
} | 24.243902 | 128 | 0.617371 | [
"MIT"
] | jenmcquade/csharp-snippets | SmartStoreNET-3.x/src/Libraries/SmartStore.Services/Directory/GeoCountryLookup.cs | 2,982 | C# |
using NUnit.Framework;
using System;
using System.Linq;
using OpenQA.Selenium.Environment;
using System.Collections.ObjectModel;
using OpenQA.Selenium.Interactions;
using System.Collections.Generic;
namespace OpenQA.Selenium.IE
{
[TestFixture]
public class IeSpecificTests : DriverTestFixture
{
//[Test]
public void KeysTest()
{
List<string> keyComboNames = new List<string>()
{
"Control",
"Shift",
"Alt",
"Control + Shift",
"Control + Alt",
"Shift + Alt",
"Control + Shift + Alt"
};
List<string> colorNames = new List<string>()
{
"red",
"green",
"lightblue",
"yellow",
"lightgreen",
"silver",
"magenta"
};
List<List<string>> modifierCombonations = new List<List<string>>()
{
new List<string>() { Keys.Control },
new List<string>() { Keys.Shift },
new List<string>() { Keys.Alt },
new List<string>() { Keys.Control, Keys.Shift },
new List<string>() { Keys.Control, Keys.Alt },
new List<string>() { Keys.Shift, Keys.Alt },
new List<string>() { Keys.Control, Keys.Shift, Keys.Alt}
};
List<string> expectedColors = new List<string>()
{
"rgba(255, 0, 0, 1)",
"rgba(0, 128, 0, 1)",
"rgba(173, 216, 230, 1)",
"rgba(255, 255, 0, 1)",
"rgba(144, 238, 144, 1)",
"rgba(192, 192, 192, 1)",
"rgba(255, 0, 255, 1)"
};
bool passed = true;
string errors = string.Empty;
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("keyboard_shortcut.html");
IWebElement body = driver.FindElement(By.CssSelector("body"));
Actions actions = new Actions(driver);
for (int i = 0; i < keyComboNames.Count; i++)
{
for (int j = 0; j < modifierCombonations[i].Count; j++)
{
actions.KeyDown(modifierCombonations[i][j]);
}
actions.SendKeys("1");
// Alternatively, the following single line of code would release
// all modifier keys, instead of looping through each key.
// actions.SendKeys(Keys.Null);
for (int j = 0; j < modifierCombonations[i].Count; j++)
{
actions.KeyUp(modifierCombonations[i][j]);
}
actions.Perform();
string background = body.GetCssValue("background-color");
passed = passed && background == expectedColors[i];
if (background != expectedColors[i])
{
if (errors.Length > 0)
{
errors += "\n";
}
errors += string.Format("Key not properly processed for {0}. Background should be {1}, Expected: '{2}', Actual: '{3}'",
keyComboNames[i],
colorNames[i],
expectedColors[i],
background);
}
}
Assert.IsTrue(passed, errors);
}
//[Test]
public void InputOnChangeAlert()
{
driver.Url = alertsPage;
driver.FindElement(By.Id("input")).Clear();
IAlert alert = WaitFor<IAlert>(() => { return driver.SwitchTo().Alert(); }, "No alert found");
alert.Accept();
}
//[Test]
public void ScrollingFrameTest()
{
try
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("frameScrollPage.html");
WaitFor(FrameToExistAndBeSwitchedTo("scrolling_frame"), "No frame with name or id 'scrolling_frame' found");
IWebElement element = driver.FindElement(By.Name("scroll_checkbox"));
element.Click();
Assert.IsTrue(element.Selected);
driver.SwitchTo().DefaultContent();
WaitFor(FrameToExistAndBeSwitchedTo("scrolling_child_frame"), "No frame with name or id 'scrolling_child_frame' found");
WaitFor(FrameToExistAndBeSwitchedTo("scrolling_frame"), "No frame with name or id 'scrolling_frame' found");
element = driver.FindElement(By.Name("scroll_checkbox"));
element.Click();
Assert.IsTrue(element.Selected);
}
finally
{
driver.SwitchTo().DefaultContent();
}
}
//[Test]
public void AlertSelectTest()
{
driver.Url = alertsPage;
driver.FindElement(By.Id("value1")).Click();
IAlert alert = WaitFor<IAlert>(() => { return driver.SwitchTo().Alert(); }, "No alert found");
alert.Accept();
}
//[Test]
public void ShouldBeAbleToBrowseTransformedXml()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.Id("linkId")).Click();
// Using transformed XML (Issue 1203)
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("transformable.xml");
driver.FindElement(By.Id("x")).Click();
// Sleep is required; driver may not be fast enough after this Click().
System.Threading.Thread.Sleep(2000);
Assert.AreEqual("XHTML Test Page", driver.Title);
// Act on the result page to make sure the window handling is still valid.
driver.FindElement(By.Id("linkId")).Click();
Assert.AreEqual("We Arrive Here", driver.Title);
}
//[Test]
public void ShouldBeAbleToStartMoreThanOneInstanceOfTheIEDriverSimultaneously()
{
IWebDriver secondDriver = new InternetExplorerDriver();
driver.Url = xhtmlTestPage;
secondDriver.Url = formsPage;
Assert.AreEqual("XHTML Test Page", driver.Title);
Assert.AreEqual("We Leave From Here", secondDriver.Title);
// We only need to quit the second driver if the test passes
secondDriver.Quit();
}
//[Test]
public void ShouldPropagateSessionCookies()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("sessionCookie.html");
IWebElement setColorButton = driver.FindElement(By.Id("setcolorbutton"));
setColorButton.Click();
IWebElement openWindowButton = driver.FindElement(By.Id("openwindowbutton"));
openWindowButton.Click();
System.Threading.Thread.Sleep(2000);
string startWindow = driver.CurrentWindowHandle;
driver.SwitchTo().Window("cookiedestwindow");
string bodyStyle = driver.FindElement(By.TagName("body")).GetAttribute("style");
driver.Close();
driver.SwitchTo().Window(startWindow);
Assert.IsTrue(bodyStyle.Contains("BACKGROUND-COLOR: #80ffff") || bodyStyle.Contains("background-color: rgb(128, 255, 255)"));
}
//[Test]
public void ShouldHandleShowModalDialogWindows()
{
driver.Url = alertsPage;
string originalWindowHandle = driver.CurrentWindowHandle;
IWebElement element = driver.FindElement(By.Id("dialog"));
element.Click();
WaitFor(() => { return driver.WindowHandles.Count > 1; }, "Window count was not greater than 1");
ReadOnlyCollection<string> windowHandles = driver.WindowHandles;
Assert.AreEqual(2, windowHandles.Count);
string dialogHandle = string.Empty;
foreach (string handle in windowHandles)
{
if (handle != originalWindowHandle)
{
dialogHandle = handle;
break;
}
}
Assert.AreNotEqual(string.Empty, dialogHandle);
driver.SwitchTo().Window(dialogHandle);
IWebElement closeElement = driver.FindElement(By.Id("close"));
closeElement.Click();
WaitFor(() => { return driver.WindowHandles.Count == 1; }, "Window count was not 1");
windowHandles = driver.WindowHandles;
Assert.AreEqual(1, windowHandles.Count);
driver.SwitchTo().Window(originalWindowHandle);
}
//[Test]
public void ScrollTest()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("scroll.html");
driver.FindElement(By.Id("line8")).Click();
Assert.AreEqual("line8", driver.FindElement(By.Id("clicked")).Text);
driver.FindElement(By.Id("line1")).Click();
Assert.AreEqual("line1", driver.FindElement(By.Id("clicked")).Text);
}
//[Test]
public void ShouldNotScrollOverflowElementsWhichAreVisible()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("scroll2.html");
var list = driver.FindElement(By.TagName("ul"));
var item = list.FindElement(By.Id("desired"));
item.Click();
Assert.AreEqual(0, ((IJavaScriptExecutor)driver).ExecuteScript("return arguments[0].scrollTop;", list), "Should not have scrolled");
}
//[Test]
public void ShouldNotScrollIfAlreadyScrolledAndElementIsInView()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("scroll3.html");
driver.FindElement(By.Id("button1")).Click();
var scrollTop = GetScrollTop();
driver.FindElement(By.Id("button2")).Click();
Assert.AreEqual(scrollTop, GetScrollTop());
}
//[Test]
public void ShouldBeAbleToHandleCascadingModalDialogs()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("modal_dialogs/modalindex.html");
string parentHandle = driver.CurrentWindowHandle;
// Launch first modal
driver.FindElement(By.CssSelector("input[type='button'][value='btn1']")).Click();
WaitFor(() => { return driver.WindowHandles.Count > 1; }, "Window count was not greater than 1");
ReadOnlyCollection<string> windows = driver.WindowHandles;
string firstWindowHandle = windows.Except(new List<string>() { parentHandle }).First();
driver.SwitchTo().Window(firstWindowHandle);
Assert.AreEqual(2, windows.Count);
// Launch second modal
driver.FindElement(By.CssSelector("input[type='button'][value='btn2']")).Click();
WaitFor(() => { return driver.WindowHandles.Count > 2; }, "Window count was not greater than 2");
ReadOnlyCollection<string> windows_1 = driver.WindowHandles;
string secondWindowHandle = windows_1.Except(windows).First();
driver.SwitchTo().Window(secondWindowHandle);
Assert.AreEqual(3, windows_1.Count);
// Launch third modal
driver.FindElement(By.CssSelector("input[type='button'][value='btn3']")).Click();
WaitFor(() => { return driver.WindowHandles.Count > 3; }, "Window count was not greater than 3");
ReadOnlyCollection<string> windows_2 = driver.WindowHandles;
string finalWindowHandle = windows_2.Except(windows_1).First();
Assert.AreEqual(4, windows_2.Count);
driver.SwitchTo().Window(finalWindowHandle).Close();
driver.SwitchTo().Window(secondWindowHandle).Close();
driver.SwitchTo().Window(firstWindowHandle).Close();
driver.SwitchTo().Window(parentHandle);
}
//[Test]
public void ShouldBeAbleToHandleCascadingModalDialogsLaunchedWithJavaScriptLinks()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("modal_dialogs/modalindex.html");
string parentHandle = driver.CurrentWindowHandle;
// Launch first modal
driver.FindElement(By.CssSelector("a[id='lnk1']")).Click();
WaitFor(() => { return driver.WindowHandles.Count > 1; }, "Window count was not greater than 1");
ReadOnlyCollection<string> windows = driver.WindowHandles;
string firstWindowHandle = windows.Except(new List<string>() { parentHandle }).First();
driver.SwitchTo().Window(firstWindowHandle);
Assert.AreEqual(2, windows.Count);
// Launch second modal
driver.FindElement(By.CssSelector("a[id='lnk2']")).Click();
System.Threading.Thread.Sleep(5000);
WaitFor(() => { return driver.WindowHandles.Count > 2; }, "Window count was not greater than 2");
ReadOnlyCollection<string> windows_1 = driver.WindowHandles;
string secondWindowHandle = windows_1.Except(windows).First();
driver.SwitchTo().Window(secondWindowHandle);
Assert.AreEqual(3, windows_1.Count);
// Launch third modal
driver.FindElement(By.CssSelector("a[id='lnk3']")).Click();
WaitFor(() => { return driver.WindowHandles.Count > 3; }, "Window count was not greater than 3");
ReadOnlyCollection<string> windows_2 = driver.WindowHandles;
string finalWindowHandle = windows_2.Except(windows_1).First();
Assert.AreEqual(4, windows_2.Count);
driver.SwitchTo().Window(finalWindowHandle).Close();
driver.SwitchTo().Window(secondWindowHandle).Close();
driver.SwitchTo().Window(firstWindowHandle).Close();
driver.SwitchTo().Window(parentHandle);
}
//[Test]
public void TestInvisibleZOrder()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("elementObscuredByInvisibleElement.html");
IWebElement element = driver.FindElement(By.CssSelector("#gLink"));
element.Click();
}
private long GetScrollTop()
{
return (long)((IJavaScriptExecutor)driver).ExecuteScript("return document.body.scrollTop;");
}
private Func<bool> FrameToExistAndBeSwitchedTo(string frameName)
{
return () =>
{
try
{
driver.SwitchTo().Frame(frameName);
}
catch (NoSuchFrameException)
{
return false;
}
return true;
};
}
}
}
| 40.762943 | 144 | 0.560628 | [
"Apache-2.0"
] | 10088/selenium | dotnet/test/ie/IeSpecificTests.cs | 14,960 | C# |
namespace CookWithMe.Web.ViewModels.Users.Profile
{
using System.Collections.Generic;
public class UserProfileCookedRecipesViewModel
{
public UserProfileCookedRecipesViewModel()
{
this.CookedRecipes = new List<UserProfileCookedRecipesRecipeViewModel>();
}
public string UserName { get; set; }
public string FullName { get; set; }
public ICollection<UserProfileCookedRecipesRecipeViewModel> CookedRecipes { get; set; }
}
}
| 26.473684 | 95 | 0.687873 | [
"MIT"
] | VioletaKirova/CookWithMe | Web/CookWithMe.Web.ViewModels/Users/Profile/UserProfileCookedRecipesViewModel.cs | 505 | C# |
namespace Contoso.FoodDelivery;
public class RestaurantMenuItem
{
#pragma warning disable CS8618
/// <summary>
/// Constructor for EF Core, as it cannot pass a Restaurant in the constructor.
/// </summary>
private RestaurantMenuItem() { }
#pragma warning restore CS8618
internal RestaurantMenuItem(Restaurant restaurant, string name, string description)
{
Restaurant = restaurant;
Name = name;
Description = description;
}
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public bool Featured { get; private set; }
public Restaurant Restaurant { get; }
public void SetFeatured()
{
if (Restaurant.Plan == PlanType.Unlimited)
{
Featured = true;
return;
}
throw new CannotSetMenuItemFeaturedException($"Setting featured menu items is only available in {PlanType.Unlimited} plan");
}
}
| 24.404762 | 132 | 0.644878 | [
"MIT"
] | fbeltrao/minimal-apis-in-production | src/Contoso.FoodDelivery/RestaurantMenuItem.cs | 1,027 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using CompanyName.MyMeetings.BuildingBlocks.Application;
using CompanyName.MyMeetings.Modules.UserAccess.Application.Configuration.Commands;
using CompanyName.MyMeetings.Modules.UserAccess.Application.Contracts;
using FluentValidation;
using MediatR;
namespace CompanyName.MyMeetings.Modules.UserAccess.Infrastructure.Configuration.Processing
{
internal class ValidationCommandHandlerDecorator<T> : ICommandHandler<T> where T : ICommand
{
private readonly IList<IValidator<T>> _validators;
private readonly ICommandHandler<T> _decorated;
public ValidationCommandHandlerDecorator(
IList<IValidator<T>> validators,
ICommandHandler<T> decorated)
{
this._validators = validators;
_decorated = decorated;
}
public Task<Unit> Handle(T command, CancellationToken cancellationToken)
{
var errors = _validators
.Select(v => v.Validate(command))
.SelectMany(result => result.Errors)
.Where(error => error != null)
.ToList();
if (errors.Any())
{
throw new InvalidCommandException(errors.Select(x => x.ErrorMessage).ToList());
}
return _decorated.Handle(command, cancellationToken);
}
}
} | 34.232558 | 95 | 0.66712 | [
"MIT"
] | nliebelt/modular-monolith-with-ddd | src/Modules/UserAccess/Infrastructure/Configuration/Processing/ValidationCommandHandlerDecorator.cs | 1,474 | C# |
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.Options;
using OmniSharp.Options;
using OmniSharp.Roslyn.Options;
using RoslynFormattingOptions = Microsoft.CodeAnalysis.Formatting.FormattingOptions;
namespace OmniSharp.Roslyn.CSharp.Services
{
[Export(typeof(IWorkspaceOptionsProvider)), Shared]
public class CSharpWorkspaceOptionsProvider : IWorkspaceOptionsProvider
{
private static OptionSet GetOptions(OptionSet optionSet, FormattingOptions formattingOptions)
{
return optionSet
.WithChangedOption(RoslynFormattingOptions.NewLine, LanguageNames.CSharp, formattingOptions.NewLine)
.WithChangedOption(RoslynFormattingOptions.UseTabs, LanguageNames.CSharp, formattingOptions.UseTabs)
.WithChangedOption(RoslynFormattingOptions.TabSize, LanguageNames.CSharp, formattingOptions.TabSize)
.WithChangedOption(RoslynFormattingOptions.IndentationSize, LanguageNames.CSharp, formattingOptions.IndentationSize)
.WithChangedOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName, formattingOptions.SpacingAfterMethodDeclarationName)
.WithChangedOption(CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis, formattingOptions.SpaceWithinMethodDeclarationParenthesis)
.WithChangedOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses, formattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses)
.WithChangedOption(CSharpFormattingOptions.SpaceAfterMethodCallName, formattingOptions.SpaceAfterMethodCallName)
.WithChangedOption(CSharpFormattingOptions.SpaceWithinMethodCallParentheses, formattingOptions.SpaceWithinMethodCallParentheses)
.WithChangedOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses, formattingOptions.SpaceBetweenEmptyMethodCallParentheses)
.WithChangedOption(CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword, formattingOptions.SpaceAfterControlFlowStatementKeyword)
.WithChangedOption(CSharpFormattingOptions.SpaceWithinExpressionParentheses, formattingOptions.SpaceWithinExpressionParentheses)
.WithChangedOption(CSharpFormattingOptions.SpaceWithinCastParentheses, formattingOptions.SpaceWithinCastParentheses)
.WithChangedOption(CSharpFormattingOptions.SpaceWithinOtherParentheses, formattingOptions.SpaceWithinOtherParentheses)
.WithChangedOption(CSharpFormattingOptions.SpaceAfterCast, formattingOptions.SpaceAfterCast)
.WithChangedOption(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration, formattingOptions.SpacesIgnoreAroundVariableDeclaration)
.WithChangedOption(CSharpFormattingOptions.SpaceBeforeOpenSquareBracket, formattingOptions.SpaceBeforeOpenSquareBracket)
.WithChangedOption(CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets, formattingOptions.SpaceBetweenEmptySquareBrackets)
.WithChangedOption(CSharpFormattingOptions.SpaceWithinSquareBrackets, formattingOptions.SpaceWithinSquareBrackets)
.WithChangedOption(CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration, formattingOptions.SpaceAfterColonInBaseTypeDeclaration)
.WithChangedOption(CSharpFormattingOptions.SpaceAfterComma, formattingOptions.SpaceAfterComma)
.WithChangedOption(CSharpFormattingOptions.SpaceAfterDot, formattingOptions.SpaceAfterDot)
.WithChangedOption(CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement, formattingOptions.SpaceAfterSemicolonsInForStatement)
.WithChangedOption(CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration, formattingOptions.SpaceBeforeColonInBaseTypeDeclaration)
.WithChangedOption(CSharpFormattingOptions.SpaceBeforeComma, formattingOptions.SpaceBeforeComma)
.WithChangedOption(CSharpFormattingOptions.SpaceBeforeDot, formattingOptions.SpaceBeforeDot)
.WithChangedOption(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement, formattingOptions.SpaceBeforeSemicolonsInForStatement)
.WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, BinaryOperatorSpacingOptionForStringValue(formattingOptions.SpacingAroundBinaryOperator))
.WithChangedOption(CSharpFormattingOptions.IndentBraces, formattingOptions.IndentBraces)
.WithChangedOption(CSharpFormattingOptions.IndentBlock, formattingOptions.IndentBlock)
.WithChangedOption(CSharpFormattingOptions.IndentSwitchSection, formattingOptions.IndentSwitchSection)
.WithChangedOption(CSharpFormattingOptions.IndentSwitchCaseSection, formattingOptions.IndentSwitchCaseSection)
.WithChangedOption(CSharpFormattingOptions.IndentSwitchCaseSectionWhenBlock, formattingOptions.IndentSwitchCaseSectionWhenBlock)
.WithChangedOption(CSharpFormattingOptions.LabelPositioning, LabelPositionOptionForStringValue(formattingOptions.LabelPositioning))
.WithChangedOption(CSharpFormattingOptions.WrappingPreserveSingleLine, formattingOptions.WrappingPreserveSingleLine)
.WithChangedOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, formattingOptions.WrappingKeepStatementsOnSingleLine)
.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInTypes, formattingOptions.NewLinesForBracesInTypes)
.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInMethods, formattingOptions.NewLinesForBracesInMethods)
.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInProperties, formattingOptions.NewLinesForBracesInProperties)
.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInAccessors, formattingOptions.NewLinesForBracesInAccessors)
.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods, formattingOptions.NewLinesForBracesInAnonymousMethods)
.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks, formattingOptions.NewLinesForBracesInControlBlocks)
.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes, formattingOptions.NewLinesForBracesInAnonymousTypes)
.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, formattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers)
.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody, formattingOptions.NewLinesForBracesInLambdaExpressionBody)
.WithChangedOption(CSharpFormattingOptions.NewLineForElse, formattingOptions.NewLineForElse)
.WithChangedOption(CSharpFormattingOptions.NewLineForCatch, formattingOptions.NewLineForCatch)
.WithChangedOption(CSharpFormattingOptions.NewLineForFinally, formattingOptions.NewLineForFinally)
.WithChangedOption(CSharpFormattingOptions.NewLineForMembersInObjectInit, formattingOptions.NewLineForMembersInObjectInit)
.WithChangedOption(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes, formattingOptions.NewLineForMembersInAnonymousTypes)
.WithChangedOption(CSharpFormattingOptions.NewLineForClausesInQuery, formattingOptions.NewLineForClausesInQuery);
}
private static LabelPositionOptions LabelPositionOptionForStringValue(string value)
{
switch (value.ToUpper())
{
case "LEFTMOST":
return LabelPositionOptions.LeftMost;
case "NOINDENT":
return LabelPositionOptions.NoIndent;
default:
return LabelPositionOptions.OneLess;
}
}
private static BinaryOperatorSpacingOptions BinaryOperatorSpacingOptionForStringValue(string value)
{
switch (value.ToUpper())
{
case "IGNORE":
return BinaryOperatorSpacingOptions.Ignore;
case "REMOVE":
return BinaryOperatorSpacingOptions.Remove;
default:
return BinaryOperatorSpacingOptions.Single;
}
}
public OptionSet Process(OptionSet workOptionSet, FormattingOptions options)
{
return GetOptions(workOptionSet, options);
}
}
}
| 84.990196 | 184 | 0.785212 | [
"MIT"
] | jpfeiffer16/omnisharp-roslyn | src/OmniSharp.Roslyn.CSharp/Services/CSharpWorkspaceOptionsProvider.cs | 8,669 | C# |
using System;
namespace Codility.MaximumSliceProblem.MaxSliceSum
{
class Program
{
static void Main(string[] args)
{
var algorithm = new Algorithm();
var array1 = new int[] { 3, 2, -6, 4, 0 };
var result1 = algorithm.Solution(array1);
Print(array1, result1);
var array2 = new int[] { 3 };
var result2 = algorithm.Solution(array2);
Print(array2, result2);
var array3 = new int[] { -10 };
var result3 = algorithm.Solution(array3);
Print(array3, result3);
var array4 = new int[] { 5, -7, 3, 5, -2, 4, -1 };
var result4 = algorithm.Solution(array4);
Print(array4, result4);
}
private static void Print(int[] a, int result)
{
Console.WriteLine($"Array {string.Join(',', a)} has max sum {result}");
}
}
}
| 27.470588 | 83 | 0.512848 | [
"MIT"
] | danijel-scukanec/codility | Codility.MaximumSliceProblem.MaxSliceSum/Program.cs | 936 | C# |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.OutlookApi
{
/// <summary>
/// DispatchInterface _FormNameRuleCondition
/// SupportByVersion Outlook, 12,14,15,16
/// </summary>
[SupportByVersion("Outlook", 12,14,15,16)]
[EntityType(EntityType.IsDispatchInterface), BaseType]
public class _FormNameRuleCondition : COMObject
{
#pragma warning disable
#region Type Information
/// <summary>
/// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(_FormNameRuleCondition);
return _type;
}
}
#endregion
#region Ctor
/// <param name="factory">current used factory core</param>
/// <param name="parentObject">object there has created the proxy</param>
/// <param name="proxyShare">proxy share instead if com proxy</param>
public _FormNameRuleCondition(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public _FormNameRuleCondition(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _FormNameRuleCondition(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _FormNameRuleCondition(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _FormNameRuleCondition(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _FormNameRuleCondition(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _FormNameRuleCondition() : base()
{
}
/// <param name="progId">registered progID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _FormNameRuleCondition(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Outlook 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.FormNameRuleCondition.Application"/> </remarks>
[SupportByVersion("Outlook", 12,14,15,16)]
[BaseResult]
public NetOffice.OutlookApi._Application Application
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.OutlookApi._Application>(this, "Application");
}
}
/// <summary>
/// SupportByVersion Outlook 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.FormNameRuleCondition.Class"/> </remarks>
[SupportByVersion("Outlook", 12,14,15,16)]
public NetOffice.OutlookApi.Enums.OlObjectClass Class
{
get
{
return Factory.ExecuteEnumPropertyGet<NetOffice.OutlookApi.Enums.OlObjectClass>(this, "Class");
}
}
/// <summary>
/// SupportByVersion Outlook 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.FormNameRuleCondition.Session"/> </remarks>
[SupportByVersion("Outlook", 12,14,15,16)]
[BaseResult]
public NetOffice.OutlookApi._NameSpace Session
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.OutlookApi._NameSpace>(this, "Session");
}
}
/// <summary>
/// SupportByVersion Outlook 12, 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.FormNameRuleCondition.Parent"/> </remarks>
[SupportByVersion("Outlook", 12,14,15,16), ProxyResult]
public object Parent
{
get
{
return Factory.ExecuteReferencePropertyGet(this, "Parent");
}
}
/// <summary>
/// SupportByVersion Outlook 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.FormNameRuleCondition.Enabled"/> </remarks>
[SupportByVersion("Outlook", 12,14,15,16)]
public bool Enabled
{
get
{
return Factory.ExecuteBoolPropertyGet(this, "Enabled");
}
set
{
Factory.ExecuteValuePropertySet(this, "Enabled", value);
}
}
/// <summary>
/// SupportByVersion Outlook 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.FormNameRuleCondition.ConditionType"/> </remarks>
[SupportByVersion("Outlook", 12,14,15,16)]
public NetOffice.OutlookApi.Enums.OlRuleConditionType ConditionType
{
get
{
return Factory.ExecuteEnumPropertyGet<NetOffice.OutlookApi.Enums.OlRuleConditionType>(this, "ConditionType");
}
}
/// <summary>
/// SupportByVersion Outlook 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.FormNameRuleCondition.FormName"/> </remarks>
[SupportByVersion("Outlook", 12,14,15,16)]
public object FormName
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "FormName");
}
set
{
Factory.ExecuteVariantPropertySet(this, "FormName", value);
}
}
#endregion
#region Methods
#endregion
#pragma warning restore
}
}
| 30.951754 | 177 | 0.692929 | [
"MIT"
] | NetOfficeFw/NetOffice | Source/Outlook/DispatchInterfaces/_FormNameRuleCondition.cs | 7,059 | C# |
// <copyright file="SimpleSpanProcessor.cs" company="OpenTelemetry Authors">
// Copyright 2018, OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
namespace OpenTelemetry.Trace.Export
{
using System.Threading;
using System.Threading.Tasks;
using OpenTelemetry.Trace;
/// <summary>
/// Implements simple span processor that exports spans in OnEnd call without batching.
/// </summary>
public class SimpleSpanProcessor : SpanProcessor
{
public SimpleSpanProcessor(SpanExporter exporter) : base(exporter)
{
}
/// <inheritdoc />
public override void OnStart(Span span)
{
}
/// <inheritdoc />
public override void OnEnd(Span span)
{
// do not await, just start export
this.Exporter.ExportAsync(new[] { span }, CancellationToken.None);
}
/// <inheritdoc />
public override Task ShutdownAsync(CancellationToken cancellationToken)
{
return this.Exporter.ShutdownAsync(cancellationToken);
}
}
}
| 31.941176 | 91 | 0.667894 | [
"Apache-2.0"
] | gibletto/opentelemetry-dotnet | src/OpenTelemetry/Trace/Export/SimpleSpanProcessor.cs | 1,631 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace CorvallisBus.Core.Models.Connexionz
{
/// <summary>
/// An association between a Connexionz Platform Tag and a list of arrivals for the stop which corresponds to that tag.
/// </summary>
public record ConnexionzPlatformET(
int PlatformTag,
List<ConnexionzRouteET>? RouteEstimatedArrivals)
{
public ConnexionzPlatformET(RoutePositionPlatform routePositionPlatform)
: this(
int.Parse(routePositionPlatform.PlatformTag),
routePositionPlatform.Route
?.Select(r => new ConnexionzRouteET(r))
?.ToList())
{
}
}
} | 32.173913 | 123 | 0.62973 | [
"MIT"
] | RikkiGibson/Corvallis-Bus-Server | CorvallisBus.Core/Models/Connexionz/ConnexionzPlatformET.cs | 742 | C# |
using Lumina.Data;
using Lumina.Excel;
using Lumina.Excel.GeneratedSheets;
namespace Glamourer.Customization
{
[Sheet("CharaMakeParams")]
public class CharaMakeParams : ExcelRow
{
public const int NumMenus = 28;
public const int NumVoices = 12;
public const int NumGraphics = 10;
public const int MaxNumValues = 100;
public const int NumFaces = 8;
public const int NumFeatures = 7;
public const int NumEquip = 3;
public enum MenuType
{
ListSelector = 0,
IconSelector = 1,
ColorPicker = 2,
DoubleColorPicker = 3,
MultiIconSelector = 4,
Percentage = 5,
}
public struct Menu
{
public uint Id;
public byte InitVal;
public MenuType Type;
public byte Size;
public byte LookAt;
public uint Mask;
public CustomizationId Customization;
public uint[] Values;
public byte[] Graphic;
}
public struct FacialFeatures
{
public uint[] Icons;
}
public LazyRow<Race> Race { get; set; } = null!;
public LazyRow<Tribe> Tribe { get; set; } = null!;
public sbyte Gender { get; set; }
public Menu[] Menus { get; set; } = new Menu[NumMenus];
public byte[] Voices { get; set; } = new byte[NumVoices];
public FacialFeatures[] FacialFeatureByFace { get; set; } = new FacialFeatures[NumFaces];
public CharaMakeType.CharaMakeTypeUnkData3347Obj[] Equip { get; set; } = new CharaMakeType.CharaMakeTypeUnkData3347Obj[NumEquip];
public override void PopulateData(RowParser parser, Lumina.GameData gameData, Language language)
{
RowId = parser.RowId;
SubRowId = parser.SubRowId;
Race = new LazyRow<Race>(gameData, parser.ReadColumn<uint>(0), language);
Tribe = new LazyRow<Tribe>(gameData, parser.ReadColumn<uint>(1), language);
Gender = parser.ReadColumn<sbyte>(2);
for (var i = 0; i < NumMenus; ++i)
{
Menus[i].Id = parser.ReadColumn<uint>(3 + 0 * NumMenus + i);
Menus[i].InitVal = parser.ReadColumn<byte>(3 + 1 * NumMenus + i);
Menus[i].Type = (MenuType) parser.ReadColumn<byte>(3 + 2 * NumMenus + i);
Menus[i].Size = parser.ReadColumn<byte>(3 + 3 * NumMenus + i);
Menus[i].LookAt = parser.ReadColumn<byte>(3 + 4 * NumMenus + i);
Menus[i].Mask = parser.ReadColumn<uint>(3 + 5 * NumMenus + i);
Menus[i].Customization = (CustomizationId) parser.ReadColumn<uint>(3 + 6 * NumMenus + i);
Menus[i].Values = new uint[Menus[i].Size];
switch (Menus[i].Type)
{
case MenuType.ColorPicker:
case MenuType.DoubleColorPicker:
case MenuType.Percentage:
break;
default:
for (var j = 0; j < Menus[i].Size; ++j)
Menus[i].Values[j] = parser.ReadColumn<uint>(3 + (7 + j) * NumMenus + i);
break;
}
Menus[i].Graphic = new byte[NumGraphics];
for (var j = 0; j < NumGraphics; ++j)
Menus[i].Graphic[j] = parser.ReadColumn<byte>(3 + (MaxNumValues + 7 + j) * NumMenus + i);
}
for (var i = 0; i < NumVoices; ++i)
Voices[i] = parser.ReadColumn<byte>(3 + (MaxNumValues + 7 + NumGraphics) * NumMenus + i);
for (var i = 0; i < NumFaces; ++i)
{
FacialFeatureByFace[i].Icons = new uint[NumFeatures];
for (var j = 0; j < NumFeatures; ++j)
FacialFeatureByFace[i].Icons[j] =
(uint) parser.ReadColumn<int>(3 + (MaxNumValues + 7 + NumGraphics) * NumMenus + NumVoices + j * NumFaces + i);
}
for (var i = 0; i < NumEquip; ++i)
{
Equip[i] = new CharaMakeType.CharaMakeTypeUnkData3347Obj()
{
Helmet = parser.ReadColumn<ulong>(
3 + (MaxNumValues + 7 + NumGraphics) * NumMenus + NumVoices + NumFaces * NumFeatures + i * 7 + 0),
Top = parser.ReadColumn<ulong>(
3 + (MaxNumValues + 7 + NumGraphics) * NumMenus + NumVoices + NumFaces * NumFeatures + i * 7 + 1),
Gloves = parser.ReadColumn<ulong>(
3 + (MaxNumValues + 7 + NumGraphics) * NumMenus + NumVoices + NumFaces * NumFeatures + i * 7 + 2),
Legs = parser.ReadColumn<ulong>(
3 + (MaxNumValues + 7 + NumGraphics) * NumMenus + NumVoices + NumFaces * NumFeatures + i * 7 + 3),
Shoes = parser.ReadColumn<ulong>(
3 + (MaxNumValues + 7 + NumGraphics) * NumMenus + NumVoices + NumFaces * NumFeatures + i * 7 + 4),
Weapon = parser.ReadColumn<ulong>(
3 + (MaxNumValues + 7 + NumGraphics) * NumMenus + NumVoices + NumFaces * NumFeatures + i * 7 + 5),
SubWeapon = parser.ReadColumn<ulong>(
3 + (MaxNumValues + 7 + NumGraphics) * NumMenus + NumVoices + NumFaces * NumFeatures + i * 7 + 6),
};
}
}
}
}
| 47.704 | 152 | 0.479121 | [
"Apache-2.0"
] | 4679/Glamourer | Glamourer.GameData/Customization/CharaMakeParams.cs | 5,965 | C# |
using System;
namespace ForgedOnce.TsLanguageServices.FullSyntaxTree.TransportModel
{
public interface IJSDocType : ForgedOnce.TsLanguageServices.FullSyntaxTree.TransportModel.ITypeNode, ForgedOnce.TsLanguageServices.FullSyntaxTree.TransportModel.INode
{
}
} | 34.75 | 171 | 0.816547 | [
"MIT"
] | YevgenNabokov/ForgedOnce.TSLanguageServices | ForgedOnce.TsLanguageServices.FullSyntaxTree/TransportModel/Generated/IJSDocType.cs | 278 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Physics;
using Microsoft.MixedReality.Toolkit.Utilities;
using System;
using Unity.Profiling;
using UnityEngine;
using UnityPhysics = UnityEngine.Physics;
namespace Microsoft.MixedReality.Toolkit.Input
{
/// <summary>
/// This class provides Gaze as an Input Source so users can interact with objects using their head.
/// </summary>
[DisallowMultipleComponent]
[AddComponentMenu("Scripts/MRTK/Services/GazeProvider")]
public class GazeProvider :
InputSystemGlobalHandlerListener,
IMixedRealityGazeProvider,
IMixedRealityGazeProviderHeadOverride,
IMixedRealityEyeGazeProvider,
IMixedRealityInputHandler
{
private const float VelocityThreshold = 0.1f;
private const float MovementThreshold = 0.01f;
/// <summary>
/// Used on Gaze Pointer initialization. To make the object lock/not lock when focus locked durign runtime, use the IsTargetPositionLockedOnFocusLock
/// attribute of <see cref="GazePointer.IsTargetPositionLockedOnFocusLock"/>
/// </summary>
[SerializeField]
[Tooltip("If true, initializes the gaze cursor to stay locked on the object when the cursor's focus is locked, otherwise it will continue following the head's direction")]
private bool lockCursorWhenFocusLocked = true;
[SerializeField]
[Tooltip("If true, the gaze cursor will disappear when the pointer's focus is locked, to prevent the cursor from floating idly in the world.")]
private bool setCursorInvisibleWhenFocusLocked = false;
[SerializeField]
[Tooltip("Maximum distance at which the gaze can hit a GameObject.")]
private float maxGazeCollisionDistance = 10.0f;
/// <summary>
/// The LayerMasks, in prioritized order, that are used to determine the GazeTarget when raycasting.
/// <example>
/// <para>Allow the cursor to hit SR, but first prioritize any DefaultRaycastLayers (potentially behind SR)</para>
/// <code language="csharp"><![CDATA[
/// int sr = LayerMask.GetMask("SR");
/// int nonSR = Physics.DefaultRaycastLayers & ~sr;
/// GazeProvider.Instance.RaycastLayerMasks = new LayerMask[] { nonSR, sr };
/// ]]></code>
/// </example>
/// </summary>
[SerializeField]
[Tooltip("The LayerMasks, in prioritized order, that are used to determine the GazeTarget when raycasting.")]
private LayerMask[] raycastLayerMasks = { UnityPhysics.DefaultRaycastLayers };
/// <summary>
/// Current stabilization method, used to smooth out the gaze ray data.
/// If left null, no stabilization will be performed.
/// </summary>
[SerializeField]
[Tooltip("Stabilizer, if any, used to smooth out the gaze ray data.")]
private GazeStabilizer stabilizer = null;
/// <summary>
/// Transform that should be used as the source of the gaze position and rotation.
/// Defaults to the main camera.
/// </summary>
[SerializeField]
[Tooltip("Transform that should be used to represent the gaze position and rotation. Defaults to CameraCache.Main")]
private Transform gazeTransform = null;
[SerializeField]
[Range(0.01f, 1f)]
[Tooltip("Minimum head velocity threshold")]
private float minHeadVelocityThreshold = 0.5f;
[SerializeField]
[Range(0.1f, 5f)]
[Tooltip("Maximum head velocity threshold")]
private float maxHeadVelocityThreshold = 2f;
#region IMixedRealityGazeProvider Implementation
/// <inheritdoc />
public bool Enabled
{
get { return enabled; }
set { enabled = value; }
}
/// <inheritdoc />
public IMixedRealityInputSource GazeInputSource
{
get
{
if (gazeInputSource == null)
{
gazeInputSource = new BaseGenericInputSource("Gaze", sourceType: InputSourceType.Head);
gazePointer.SetGazeInputSourceParent(gazeInputSource);
}
return gazeInputSource;
}
}
private BaseGenericInputSource gazeInputSource;
/// <inheritdoc />
public IMixedRealityPointer GazePointer => gazePointer ?? InitializeGazePointer();
private InternalGazePointer gazePointer = null;
/// <inheritdoc />
public GameObject GazeCursorPrefab { private get; set; }
/// <inheritdoc />
public IMixedRealityCursor GazeCursor => GazePointer.BaseCursor;
/// <inheritdoc />
public GameObject GazeTarget { get; private set; }
/// <inheritdoc />
public MixedRealityRaycastHit HitInfo { get; private set; }
/// <inheritdoc />
public Vector3 HitPosition { get; private set; }
/// <inheritdoc />
public Vector3 HitNormal { get; private set; }
/// <inheritdoc />
public Vector3 GazeOrigin => GazePointer != null ? GazePointer.Rays[0].Origin : Vector3.zero;
/// <inheritdoc />
public Vector3 GazeDirection => GazePointer != null ? GazePointer.Rays[0].Direction : Vector3.forward;
/// <inheritdoc />
public Vector3 HeadVelocity { get; private set; }
/// <inheritdoc />
public Vector3 HeadMovementDirection { get; private set; }
/// <inheritdoc />
public GameObject GameObjectReference => gameObject;
#endregion IMixedRealityGazeProvider Implementation
private float lastHitDistance = 2.0f;
private bool delayInitialization = true;
private Vector3 lastHeadPosition = Vector3.zero;
private Vector3? overrideHeadPosition = null;
private Vector3? overrideHeadForward = null;
#region InternalGazePointer Class
private class InternalGazePointer : GenericPointer
{
private readonly Transform gazeTransform;
private readonly BaseRayStabilizer stabilizer;
private readonly GazeProvider gazeProvider;
public InternalGazePointer(GazeProvider gazeProvider, string pointerName, IMixedRealityInputSource inputSourceParent, LayerMask[] raycastLayerMasks, float pointerExtent, Transform gazeTransform, BaseRayStabilizer stabilizer)
: base(pointerName, inputSourceParent)
{
this.gazeProvider = gazeProvider;
PrioritizedLayerMasksOverride = raycastLayerMasks;
this.pointerExtent = pointerExtent;
this.gazeTransform = gazeTransform;
this.stabilizer = stabilizer;
IsInteractionEnabled = true;
}
#region IMixedRealityPointer Implementation
/// <inheritdoc />
public override IMixedRealityController Controller { get; set; }
/// <inheritdoc />
public override IMixedRealityInputSource InputSourceParent { get; protected set; }
private float pointerExtent;
/// <inheritdoc />
public override float PointerExtent
{
get => pointerExtent;
set => pointerExtent = value;
}
// Is the pointer currently down
private bool isDown = false;
// Input source that raised pointer down
private IMixedRealityInputSource currentInputSource;
// Handedness of the input source that raised pointer down
private Handedness currentHandedness = Handedness.None;
/// <summary>
/// Only for use when initializing Gaze Pointer on startup.
/// </summary>
internal void SetGazeInputSourceParent(IMixedRealityInputSource gazeInputSource)
{
InputSourceParent = gazeInputSource;
}
private static readonly ProfilerMarker OnPreSceneQueryPerfMarker = new ProfilerMarker("[MRTK] InternalGazePointer.OnPreSceneQuery");
/// <inheritdoc />
public override void OnPreSceneQuery()
{
using (OnPreSceneQueryPerfMarker.Auto())
{
Vector3 newGazeOrigin;
Vector3 newGazeNormal;
if (gazeProvider.IsEyeTrackingEnabledAndValid)
{
gazeProvider.gazeInputSource.SourceType = InputSourceType.Eyes;
newGazeOrigin = gazeProvider.LatestEyeGaze.origin;
newGazeNormal = gazeProvider.LatestEyeGaze.direction;
}
else
{
gazeProvider.gazeInputSource.SourceType = InputSourceType.Head;
if (gazeProvider.UseHeadGazeOverride && gazeProvider.overrideHeadPosition.HasValue && gazeProvider.overrideHeadForward.HasValue)
{
newGazeOrigin = gazeProvider.overrideHeadPosition.Value;
newGazeNormal = gazeProvider.overrideHeadForward.Value;
// Reset values in case the override source is removed
gazeProvider.overrideHeadPosition = null;
gazeProvider.overrideHeadForward = null;
}
else
{
newGazeOrigin = gazeTransform.position;
newGazeNormal = gazeTransform.forward;
}
// Update gaze info from stabilizer
if (stabilizer != null)
{
stabilizer.UpdateStability(gazeTransform.localPosition, gazeTransform.localRotation * Vector3.forward);
newGazeOrigin = gazeTransform.parent.TransformPoint(stabilizer.StablePosition);
newGazeNormal = gazeTransform.parent.TransformDirection(stabilizer.StableRay.direction);
}
}
Vector3 endPoint = newGazeOrigin + (newGazeNormal * pointerExtent);
Rays[0].UpdateRayStep(ref newGazeOrigin, ref endPoint);
gazeProvider.HitPosition = Rays[0].Origin + (gazeProvider.lastHitDistance * Rays[0].Direction);
}
}
private static readonly ProfilerMarker OnPostSceneQueryPerfMarker = new ProfilerMarker("[MRTK] InternalGazePointer.OnPostSceneQuery");
public override void OnPostSceneQuery()
{
using (OnPostSceneQueryPerfMarker.Auto())
{
if (isDown)
{
CoreServices.InputSystem.RaisePointerDragged(this, MixedRealityInputAction.None, currentHandedness, currentInputSource);
}
}
}
/// <inheritdoc />
public override void OnPreCurrentPointerTargetChange() { }
/// <inheritdoc />
public override Vector3 Position => gazeTransform.position;
/// <inheritdoc />
public override Quaternion Rotation => gazeTransform.rotation;
/// <inheritdoc />
public override void Reset()
{
Controller = null;
}
#endregion IMixedRealityPointer Implementation
/// <summary>
/// Press this pointer. This sends a pointer down event across the input system.
/// </summary>
/// <param name="mixedRealityInputAction">The input action that corresponds to the pressed button or axis.</param>
/// <param name="handedness">Optional handedness of the source that pressed the pointer.</param>
public void RaisePointerDown(MixedRealityInputAction mixedRealityInputAction, Handedness handedness = Handedness.None, IMixedRealityInputSource inputSource = null)
{
isDown = true;
currentHandedness = handedness;
currentInputSource = inputSource;
CoreServices.InputSystem?.RaisePointerDown(this, mixedRealityInputAction, handedness, inputSource);
}
/// <summary>
/// Release this pointer. This sends pointer clicked and pointer up events across the input system.
/// </summary>
/// <param name="mixedRealityInputAction">The input action that corresponds to the released button or axis.</param>
/// <param name="handedness">Optional handedness of the source that released the pointer.</param>
public void RaisePointerUp(MixedRealityInputAction mixedRealityInputAction, Handedness handedness = Handedness.None, IMixedRealityInputSource inputSource = null)
{
isDown = false;
currentHandedness = Handedness.None;
currentInputSource = null;
CoreServices.InputSystem?.RaisePointerClicked(this, mixedRealityInputAction, 0, handedness, inputSource);
CoreServices.InputSystem?.RaisePointerUp(this, mixedRealityInputAction, handedness, inputSource);
}
}
#endregion InternalGazePointer Class
#region MonoBehaviour Implementation
private void OnValidate()
{
if (minHeadVelocityThreshold > maxHeadVelocityThreshold)
{
Debug.LogWarning("Minimum head velocity threshold should be less than the maximum velocity threshold. Changing now.");
minHeadVelocityThreshold = maxHeadVelocityThreshold;
}
}
/// <inheritdoc />
protected override void OnEnable()
{
base.OnEnable();
if (!delayInitialization)
{
// The first time we call OnEnable we skip this.
RaiseSourceDetected();
}
}
/// <inheritdoc />
protected override async void Start()
{
base.Start();
await EnsureInputSystemValid();
if (this == null)
{
// We've been destroyed during the await.
return;
}
GazePointer.BaseCursor?.SetVisibility(true);
if (delayInitialization)
{
delayInitialization = false;
RaiseSourceDetected();
}
}
private static readonly ProfilerMarker UpdatePerfMarker = new ProfilerMarker("[MRTK] GazeProvider.Update");
private void Update()
{
using (UpdatePerfMarker.Auto())
{
if (MixedRealityRaycaster.DebugEnabled && gazeTransform != null)
{
Debug.DrawRay(GazeOrigin, (HitPosition - GazeOrigin), Color.white);
}
// If flagged to do so (setCursorInvisibleWhenFocusLocked) and active (IsInteractionEnabled), set the visibility to !IsFocusLocked,
// but don't touch the visibility when not active or not flagged.
if (setCursorInvisibleWhenFocusLocked && gazePointer != null &&
gazePointer.IsInteractionEnabled && GazeCursor != null && gazePointer.IsFocusLocked == GazeCursor.IsVisible)
{
GazeCursor.SetVisibility(!gazePointer.IsFocusLocked);
}
}
}
private static readonly ProfilerMarker LateUpdatePerfMarker = new ProfilerMarker("[MRTK] GazeProvider.LateUpdate");
private void LateUpdate()
{
using (LateUpdatePerfMarker.Auto())
{
// Update head velocity.
Vector3 headPosition = GazeOrigin;
Vector3 headDelta = headPosition - lastHeadPosition;
if (headDelta.sqrMagnitude < MovementThreshold * MovementThreshold)
{
headDelta = Vector3.zero;
}
if (Time.fixedDeltaTime > 0)
{
float velocityAdjustmentRate = 3f * Time.fixedDeltaTime;
HeadVelocity = HeadVelocity * (1f - velocityAdjustmentRate) + headDelta * velocityAdjustmentRate / Time.fixedDeltaTime;
if (HeadVelocity.sqrMagnitude < VelocityThreshold * VelocityThreshold)
{
HeadVelocity = Vector3.zero;
}
}
// Update Head Movement Direction
float multiplier = Mathf.Clamp01(Mathf.InverseLerp(minHeadVelocityThreshold, maxHeadVelocityThreshold, HeadVelocity.magnitude));
Vector3 newHeadMoveDirection = Vector3.Lerp(headPosition, HeadVelocity, multiplier).normalized;
lastHeadPosition = headPosition;
float directionAdjustmentRate = Mathf.Clamp01(5f * Time.fixedDeltaTime);
HeadMovementDirection = Vector3.Slerp(HeadMovementDirection, newHeadMoveDirection, directionAdjustmentRate);
if (MixedRealityRaycaster.DebugEnabled && gazeTransform != null)
{
Debug.DrawLine(lastHeadPosition, lastHeadPosition + HeadMovementDirection * 10f, Color.Lerp(Color.red, Color.green, multiplier));
Debug.DrawLine(lastHeadPosition, lastHeadPosition + HeadVelocity, Color.yellow);
}
}
}
/// <inheritdoc />
protected override void OnDisable()
{
base.OnDisable();
GazePointer?.BaseCursor?.SetVisibility(false);
// if true, component has never started and never fired onSourceDetected event
if (!delayInitialization)
{
CoreServices.InputSystem?.RaiseSourceLost(GazeInputSource);
}
}
#endregion MonoBehaviour Implementation
#region InputSystemGlobalHandlerListener Implementation
/// <inheritdoc />
protected override void RegisterHandlers()
{
CoreServices.InputSystem?.RegisterHandler<IMixedRealityInputHandler>(this);
}
/// <inheritdoc />
protected override void UnregisterHandlers()
{
CoreServices.InputSystem?.UnregisterHandler<IMixedRealityInputHandler>(this);
}
#endregion InputSystemGlobalHandlerListener Implementation
#region IMixedRealityInputHandler Implementation
public void OnInputUp(InputEventData eventData)
{
for (int i = 0; i < eventData.InputSource.Pointers.Length; i++)
{
if (eventData.InputSource.Pointers[i].PointerId == GazePointer.PointerId)
{
gazePointer.RaisePointerUp(eventData.MixedRealityInputAction, eventData.Handedness, eventData.InputSource);
return;
}
}
}
public void OnInputDown(InputEventData eventData)
{
for (int i = 0; i < eventData.InputSource.Pointers.Length; i++)
{
if (eventData.InputSource.Pointers[i].PointerId == GazePointer.PointerId)
{
gazePointer.RaisePointerDown(eventData.MixedRealityInputAction, eventData.Handedness, eventData.InputSource);
return;
}
}
}
#endregion IMixedRealityInputHandler Implementation
#region Utilities
private static readonly ProfilerMarker InitializeGazePointerPerfMarker = new ProfilerMarker("[MRTK] GazeProvider.InitializeGazePointer");
private IMixedRealityPointer InitializeGazePointer()
{
using (InitializeGazePointerPerfMarker.Auto())
{
if (gazeTransform == null)
{
gazeTransform = CameraCache.Main.transform;
}
Debug.Assert(gazeTransform != null, "No gaze transform to raycast from!");
gazePointer = new InternalGazePointer(this, "Gaze Pointer", null, raycastLayerMasks, maxGazeCollisionDistance, gazeTransform, stabilizer);
if ((GazeCursor == null) &&
(GazeCursorPrefab != null))
{
GameObject cursor = Instantiate(GazeCursorPrefab);
MixedRealityPlayspace.AddChild(cursor.transform);
SetGazeCursor(cursor);
}
// Initialize gaze pointer
gazePointer.IsTargetPositionLockedOnFocusLock = lockCursorWhenFocusLocked;
return gazePointer;
}
}
private static readonly ProfilerMarker RaiseSourceDetectedPerfMarker = new ProfilerMarker("[MRTK] GazeProvider.RaiseSourceDetectec");
private async void RaiseSourceDetected()
{
using (RaiseSourceDetectedPerfMarker.Auto())
{
await EnsureInputSystemValid();
if (this == null)
{
// We've been destroyed during the await.
return;
}
CoreServices.InputSystem?.RaiseSourceDetected(GazeInputSource);
GazePointer.BaseCursor?.SetVisibility(true);
}
}
/// <inheritdoc />
public void UpdateGazeInfoFromHit(MixedRealityRaycastHit raycastHit)
{
HitInfo = raycastHit;
if (raycastHit.transform != null)
{
GazeTarget = raycastHit.transform.gameObject;
var ray = GazePointer.Rays[0];
var lhd = (raycastHit.point - ray.Origin).magnitude;
lastHitDistance = lhd;
HitPosition = ray.Origin + lhd * ray.Direction;
HitNormal = raycastHit.normal;
}
else
{
GazeTarget = null;
HitPosition = Vector3.zero;
HitNormal = Vector3.zero;
}
}
/// <summary>
/// Set the gaze cursor.
/// </summary>
public void SetGazeCursor(GameObject cursor)
{
Debug.Assert(cursor != null);
cursor.transform.parent = transform.parent;
GazePointer.BaseCursor = cursor.GetComponent<IMixedRealityCursor>();
Debug.Assert(GazePointer.BaseCursor != null, "Failed to load cursor");
GazePointer.BaseCursor.SetVisibilityOnSourceDetected = false;
GazePointer.BaseCursor.Pointer = GazePointer;
}
#endregion Utilities
#region IMixedRealityEyeGazeProvider Implementation
private DateTime latestEyeTrackingUpdate = DateTime.MinValue;
private static readonly float maxEyeTrackingTimeoutInSeconds = 2.0f;
/// <inheritdoc />
public bool IsEyeTrackingEnabledAndValid => IsEyeTrackingDataValid && IsEyeTrackingEnabled;
/// <inheritdoc />
public bool IsEyeTrackingDataValid => (DateTime.UtcNow - latestEyeTrackingUpdate).TotalSeconds <= maxEyeTrackingTimeoutInSeconds;
/// <inheritdoc />
public bool? IsEyeCalibrationValid { get; private set; } = null;
/// <inheritdoc />
public Ray LatestEyeGaze { get; private set; } = default(Ray);
/// <inheritdoc />
public bool IsEyeTrackingEnabled { get; set; }
/// <inheritdoc />
public DateTime Timestamp { get; private set; }
/// <inheritdoc />
public void UpdateEyeGaze(IMixedRealityEyeGazeDataProvider provider, Ray eyeRay, DateTime timestamp)
{
LatestEyeGaze = eyeRay;
latestEyeTrackingUpdate = DateTime.UtcNow;
Timestamp = timestamp;
}
/// <inheritdoc />
public void UpdateEyeTrackingStatus(IMixedRealityEyeGazeDataProvider provider, bool userIsEyeCalibrated)
{
IsEyeCalibrationValid = userIsEyeCalibrated;
}
#endregion IMixedRealityEyeGazeProvider Implementation
#region IMixedRealityGazeProviderHeadOverride Implementation
/// <inheritdoc />
public bool UseHeadGazeOverride { get; set; }
/// <inheritdoc />
public void OverrideHeadGaze(Vector3 position, Vector3 forward)
{
overrideHeadPosition = position;
overrideHeadForward = forward;
}
#endregion IMixedRealityGazeProviderHeadOverride Implementation
}
}
| 39.590476 | 236 | 0.597426 | [
"MIT"
] | FamiizCEO/MixedRealityToolkit-Unity | Assets/MRTK/Services/InputSystem/GazeProvider.cs | 24,944 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/objidlbase.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace TerraFX.Interop
{
[Guid("000001CF-0000-0000-C000-000000000046")]
[NativeTypeName("struct IMarshal2 : IMarshal")]
[NativeInheritance("IMarshal")]
public unsafe partial struct IMarshal2
{
public void** lpVtbl;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(0)]
[return: NativeTypeName("HRESULT")]
public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
{
return ((delegate* unmanaged<IMarshal2*, Guid*, void**, int>)(lpVtbl[0]))((IMarshal2*)Unsafe.AsPointer(ref this), riid, ppvObject);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(1)]
[return: NativeTypeName("ULONG")]
public uint AddRef()
{
return ((delegate* unmanaged<IMarshal2*, uint>)(lpVtbl[1]))((IMarshal2*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(2)]
[return: NativeTypeName("ULONG")]
public uint Release()
{
return ((delegate* unmanaged<IMarshal2*, uint>)(lpVtbl[2]))((IMarshal2*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(3)]
[return: NativeTypeName("HRESULT")]
public int GetUnmarshalClass([NativeTypeName("const IID &")] Guid* riid, void* pv, [NativeTypeName("DWORD")] uint dwDestContext, void* pvDestContext, [NativeTypeName("DWORD")] uint mshlflags, [NativeTypeName("CLSID *")] Guid* pCid)
{
return ((delegate* unmanaged<IMarshal2*, Guid*, void*, uint, void*, uint, Guid*, int>)(lpVtbl[3]))((IMarshal2*)Unsafe.AsPointer(ref this), riid, pv, dwDestContext, pvDestContext, mshlflags, pCid);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(4)]
[return: NativeTypeName("HRESULT")]
public int GetMarshalSizeMax([NativeTypeName("const IID &")] Guid* riid, void* pv, [NativeTypeName("DWORD")] uint dwDestContext, void* pvDestContext, [NativeTypeName("DWORD")] uint mshlflags, [NativeTypeName("DWORD *")] uint* pSize)
{
return ((delegate* unmanaged<IMarshal2*, Guid*, void*, uint, void*, uint, uint*, int>)(lpVtbl[4]))((IMarshal2*)Unsafe.AsPointer(ref this), riid, pv, dwDestContext, pvDestContext, mshlflags, pSize);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(5)]
[return: NativeTypeName("HRESULT")]
public int MarshalInterface(IStream* pStm, [NativeTypeName("const IID &")] Guid* riid, void* pv, [NativeTypeName("DWORD")] uint dwDestContext, void* pvDestContext, [NativeTypeName("DWORD")] uint mshlflags)
{
return ((delegate* unmanaged<IMarshal2*, IStream*, Guid*, void*, uint, void*, uint, int>)(lpVtbl[5]))((IMarshal2*)Unsafe.AsPointer(ref this), pStm, riid, pv, dwDestContext, pvDestContext, mshlflags);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(6)]
[return: NativeTypeName("HRESULT")]
public int UnmarshalInterface(IStream* pStm, [NativeTypeName("const IID &")] Guid* riid, void** ppv)
{
return ((delegate* unmanaged<IMarshal2*, IStream*, Guid*, void**, int>)(lpVtbl[6]))((IMarshal2*)Unsafe.AsPointer(ref this), pStm, riid, ppv);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(7)]
[return: NativeTypeName("HRESULT")]
public int ReleaseMarshalData(IStream* pStm)
{
return ((delegate* unmanaged<IMarshal2*, IStream*, int>)(lpVtbl[7]))((IMarshal2*)Unsafe.AsPointer(ref this), pStm);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(8)]
[return: NativeTypeName("HRESULT")]
public int DisconnectObject([NativeTypeName("DWORD")] uint dwReserved)
{
return ((delegate* unmanaged<IMarshal2*, uint, int>)(lpVtbl[8]))((IMarshal2*)Unsafe.AsPointer(ref this), dwReserved);
}
}
}
| 48.456522 | 240 | 0.6559 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | sources/Interop/Windows/um/objidlbase/IMarshal2.cs | 4,460 | C# |
using Kerberos.NET.Entities;
using System;
using System.Threading.Tasks;
namespace Kerberos.NET.Server
{
public class PaDataTimestampHandler : KdcPreAuthenticationHandlerBase
{
public PaDataTimestampHandler(IRealmService service)
: base(service)
{
}
public override async Task<KrbPaData> Validate(KrbKdcReq asReq, IKerberosPrincipal principal)
{
var timestamp = asReq.DecryptTimestamp(await principal.RetrieveLongTermCredential());
if (timestamp == DateTimeOffset.MinValue)
{
return new KrbPaData
{
Type = PaDataType.PA_ENC_TIMESTAMP
};
}
var skew = Service.Settings.MaximumSkew;
DateTimeOffset now = Service.Now();
if ((now - timestamp) > skew)
{
throw new KerberosValidationException(
$"Timestamp window is greater than allowed skew. Start: {timestamp}; End: {now}; Skew: {skew}"
);
}
return null;
}
}
} | 28.125 | 114 | 0.563556 | [
"MIT"
] | DamirAinullin/Kerberos.NET | Kerberos.NET/Server/PaDataTimestampHandler.cs | 1,127 | 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 Chislo1.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.258065 | 151 | 0.580038 | [
"Apache-2.0"
] | MiracleSirius1/Projects | Chislo1/Chislo1/Properties/Settings.Designer.cs | 1,064 | C# |
/*
Copyright © 2018-2021, ETH Zurich, D-BSSE, Aaron Ponti & Todd Duncombe
All rights reserved. This program and the accompanying materials
are made available under the terms of the Apache-2.0 license
which accompanies this distribution, and is available at
https://www.apache.org/licenses/LICENSE-2.0
SpectraSorter is based on FXStreamer by Oliver Lischtschenko (Ocean Optics):
Lischtschenko, O.; private communication on OBP protocol, 2018.
The original code is added to the repository.
*/
using spectra.plotting;
using spectra.processing;
using spectra.ui;
using spectra.ui.components;
using spectra.utils;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
namespace SpectraSorterUnitTests
{
[TestClass]
public class PlotterTests
{
MainPlotter mMainPlotter = new MainPlotter(new MainChart());
[TestInitialize]
public void TestInitialize()
{
this.mMainPlotter.Reset();
}
[TestMethod]
public void TestXAxisSetBoundsFromData()
{
float[] XData = { 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f };
this.mMainPlotter.XAxisSetBoundsFromData(XData);
Assert.AreEqual(this.mMainPlotter.XAxisLowerBound, 5.0f);
Assert.AreEqual(this.mMainPlotter.XAxisUpperBound, 12.0f);
}
[TestMethod]
public void TestYAxisInitFromData()
{
float[] YData = { 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f };
CircularBuffer<float[]> CircYData = new CircularBuffer<float[]>(1);
CircYData.Enqueue(YData);
this.mMainPlotter.YAxisInitFromData(CircYData);
Assert.AreEqual(this.mMainPlotter.YAxisLowerBound, 5.0f);
Assert.AreEqual(this.mMainPlotter.YAxisUpperBound, 12.0f);
}
[TestMethod]
public void TestYAxisSetBoundsAsAllowedFromDataFloat()
{
float[] YData1 = { 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f };
float[] YData2 = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f };
float[] YData3 = { 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f, 16.0f };
Dictionary<string, CircularBuffer<float>> MapCircYData = new Dictionary<string, CircularBuffer<float>>();
CircularBuffer<float> CircYData1 = new CircularBuffer<float>(YData1.Length);
foreach (float value in YData1)
{
CircYData1.Enqueue(value);
}
CircularBuffer<float> CircYData2 = new CircularBuffer<float>(YData2.Length);
foreach (float value in YData2)
{
CircYData2.Enqueue(value);
}
CircularBuffer<float> CircYData3 = new CircularBuffer<float>(YData3.Length);
foreach (float value in YData3)
{
CircYData3.Enqueue(value);
}
MapCircYData["ID1"] = CircYData1;
MapCircYData["ID2"] = CircYData2;
MapCircYData["ID3"] = CircYData3;
this.mMainPlotter.YAxisSetBoundsAsAllowedFromData(MapCircYData);
Assert.AreEqual(this.mMainPlotter.YAxisLowerBound, 1.0f);
Assert.AreEqual(this.mMainPlotter.YAxisUpperBound, 16.0f);
}
[TestMethod]
public void TestYAxisSetBoundsAsAllowedFromDataInt()
{
float[] YData1 = { 5, 6, 7, 8, 9, 10, 11, 12 };
float[] YData2 = { 1, 2, 3, 4, 5, 6, 7, 8 };
float[] YData3 = { 9, 10, 11, 12, 13, 14, 15, 16 };
Dictionary<string, CircularBuffer<int>> MapCircYData = new Dictionary<string, CircularBuffer<int>>();
CircularBuffer<int> CircYData1 = new CircularBuffer<int>(YData1.Length);
foreach (int value in YData1)
{
CircYData1.Enqueue(value);
}
CircularBuffer<int> CircYData2 = new CircularBuffer<int>(YData2.Length);
foreach (int value in YData2)
{
CircYData2.Enqueue(value);
}
CircularBuffer<int> CircYData3 = new CircularBuffer<int>(YData3.Length);
foreach (int value in YData3)
{
CircYData3.Enqueue(value);
}
MapCircYData["ID1"] = CircYData1;
MapCircYData["ID2"] = CircYData2;
MapCircYData["ID3"] = CircYData3;
this.mMainPlotter.YAxisSetBoundsAsAllowedFromData(MapCircYData);
Assert.AreEqual(this.mMainPlotter.YAxisLowerBound, 1);
Assert.AreEqual(this.mMainPlotter.YAxisUpperBound, 16);
}
[TestMethod]
public void TestYAxisSetBoundsConstrainedByCurrentXAxisRange()
{
float[] XData = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f };
float[] YData = { 11.0f, 12.0f, 13.0f, 14.0f, 15.0f, 16.0f, 17.0f, 18.0f, 19.0f, 20.0f };
this.mMainPlotter.XAxisLowerBound = 3.0f;
this.mMainPlotter.XAxisUpperBound = 8.0f;
this.mMainPlotter.YAxisSetBoundsConstrainedByCurrentXAxisRange(XData, YData);
Assert.AreEqual(this.mMainPlotter.YAxisLowerBound, 13.0f);
Assert.AreEqual(this.mMainPlotter.YAxisUpperBound, 18.0f);
}
}
} | 36.818792 | 118 | 0.584579 | [
"Apache-2.0"
] | SpectraSorter/SpectraSorter | src/UnitTests/PlotterTests.cs | 5,489 | C# |
namespace Oniqys.Blazor.Controls.Layouter
{
public interface ILayouter
{
}
}
| 12.857143 | 42 | 0.677778 | [
"MIT"
] | cct-blog/Oniqys.Blazor | Oniqys.Blazor/Controls/Layouter/ILayouter.cs | 92 | C# |
// CivOne
//
// To the extent possible under law, the person who associated CC0 with
// CivOne has waived all copyright and related or neighboring rights
// to CivOne.
//
// You should have received a copy of the CC0 legalcode along with this
// work. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
using CivOne.Advances;
using CivOne.Enums;
namespace CivOne.Units
{
internal class Chariot : BaseUnitLand
{
public Chariot() : base(4, 4, 1, 2)
{
Type = UnitType.Chariot;
Name = "Chariot";
RequiredTech = new TheWheel();
ObsoleteTech = new Chivalry();
SetIcon('D', 0, 2);
}
}
} | 23.807692 | 73 | 0.691438 | [
"CC0-1.0"
] | Andersw88/CivOne | src/Units/Chariot.cs | 619 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Hangfire;
using Hangfire.States;
namespace AspEfCore.Web.Jobs
{
public class Services
{
private static readonly Random Rand = new Random();
public async Task EmptyDefault()
{
await Task.Yield();
}
public async Task Async(CancellationToken cancellationToken)
{
await Task.Yield();
await Task.Delay(TimeSpan.FromSeconds(20), cancellationToken);
}
[Queue("critical")]
public async Task EmptyCritical()
{
await Task.Yield();
}
[AutomaticRetry(Attempts = 0), LatencyTimeout(30)]
public async Task Error()
{
await Task.Yield();
Console.WriteLine("Beginning error task...");
throw new InvalidOperationException(null, new FileLoadException());
}
[Queue("critical")]
public async Task<int> Random(int number)
{
int time;
lock (Rand)
{
time = Rand.Next(10);
}
if (time < 5)
{
throw new Exception();
}
await Task.Delay(TimeSpan.FromSeconds(5 + time));
Console.WriteLine("Finished task: " + number);
return time;
}
public async Task Cancelable(int iterationCount, IJobCancellationToken token)
{
try
{
for (var i = 1; i <= iterationCount; i++)
{
await Task.Delay(1000);
Console.WriteLine("Performing step {0} of {1}...", i, iterationCount);
token.ThrowIfCancellationRequested();
}
}
catch (OperationCanceledException)
{
Console.WriteLine("Cancellation requested, exiting...");
throw;
}
}
[DisplayName("Name: {0}")]
public async Task Args(string name, int authorId, DateTime createdAt)
{
await Task.Yield();
Console.WriteLine($"{name}, {authorId}, {createdAt}");
}
public async Task Custom(int id, string[] values, CustomObject objects, DayOfWeek dayOfWeek)
{
await Task.Yield();
}
public async Task FullArgs(
bool b,
int i,
char c,
DayOfWeek e,
string s,
TimeSpan t,
DateTime d,
CustomObject o,
string[] sa,
int[] ia,
long[] ea,
object[] na,
List<string> sl)
{
await Task.Yield();
}
public async Task LongRunning(IJobCancellationToken token)
{
await Task.Delay(TimeSpan.FromMinutes(30), token.ShutdownToken);
}
public class CustomObject
{
public int Id { get; set; }
public CustomObject[] Children { get; set; }
}
public async Task Write(char character)
{
await Task.Yield();
Console.Write(character);
}
public async Task WriteBlankLine()
{
await Task.Yield();
Console.WriteLine();
}
[IdempotentCompletion]
public static async Task<IState> WriteLine(string value)
{
await Task.Yield();
Console.WriteLine(value);
return new AwaitingState("asfafs", new EnqueuedState("criticalll"));
}
}
} | 26.528571 | 100 | 0.507808 | [
"MIT"
] | Alice52/C | project/csharp/ASPEfCore/ASPEfCore.Web/Jobs/Services.cs | 3,716 | 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 chat.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.193694 | 229 | 0.586332 | [
"MIT"
] | monsterddq/rscchat | Asp.Net/server/chat/chat/Areas/HelpPage/SampleGeneration/HelpPageSampleGenerator.cs | 20,954 | C# |
// Copyright 2006-2008 Splicer Project - http://www.codeplex.com/splicer/
//
// 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.Collections;
using System.Collections.Generic;
using NUnit.Framework;
namespace Splicer.Timeline.Tests
{
[TestFixture]
public class VirtualClipCollectionFixture
{
[Test]
public void AddOneClips()
{
var collection = new VirtualClipCollection();
collection.AddVirtualClip(new MockClip(1, 5, 2));
Assert.AreEqual(1, collection[0].Offset);
Assert.AreEqual(5, collection[0].Duration);
Assert.AreEqual(2, collection[0].MediaStart);
}
[Test]
public void AddTwoClips()
{
var collection = new VirtualClipCollection();
collection.AddVirtualClip(new MockClip(0, 5, 0));
collection.AddVirtualClip(new MockClip(5, 5, 0));
Assert.AreEqual(0, collection[0].Offset);
Assert.AreEqual(5, collection[0].Duration);
Assert.AreEqual(0, collection[0].MediaStart);
Assert.AreEqual(5, collection[1].Offset);
Assert.AreEqual(5, collection[1].Duration);
Assert.AreEqual(0, collection[1].MediaStart);
}
[Test]
public void Scenario1()
{
var collection = new VirtualClipCollection();
collection.AddVirtualClip(new MockClip(5, 10, 0));
collection.AddVirtualClip(new MockClip(0, 7, 0));
Assert.AreEqual(0, collection[0].Offset);
Assert.AreEqual(7, collection[0].Duration);
Assert.AreEqual(0, collection[0].MediaStart);
// this should be reduced in length 2 seconds, and moved 2 seconds forward
Assert.AreEqual(7, collection[1].Offset);
Assert.AreEqual(8, collection[1].Duration);
Assert.AreEqual(2, collection[1].MediaStart);
}
[Test]
public void Scenario2()
{
var collection = new VirtualClipCollection();
collection.AddVirtualClip(new MockClip(0, 7, 0));
collection.AddVirtualClip(new MockClip(5, 10, 0));
Assert.AreEqual(0, collection[0].Offset);
Assert.AreEqual(5, collection[0].Duration);
Assert.AreEqual(0, collection[0].MediaStart);
Assert.AreEqual(5, collection[1].Offset);
Assert.AreEqual(10, collection[1].Duration);
Assert.AreEqual(0, collection[1].MediaStart);
}
[Test]
public void Scenario3()
{
var collection = new VirtualClipCollection();
collection.AddVirtualClip(new MockClip(2, 2, 0));
collection.AddVirtualClip(new MockClip(0, 10, 0));
Assert.AreEqual(1, collection.Count);
Assert.AreEqual(0, collection[0].Offset);
Assert.AreEqual(10, collection[0].Duration);
Assert.AreEqual(0, collection[0].MediaStart);
}
[Test]
public void Scenario4()
{
var collection = new VirtualClipCollection();
collection.AddVirtualClip(new MockClip(0, 10, 0));
collection.AddVirtualClip(new MockClip(2, 2, 0));
Assert.AreEqual(3, collection.Count);
Assert.AreEqual(0, collection[0].Offset);
Assert.AreEqual(2, collection[0].Duration);
Assert.AreEqual(0, collection[0].MediaStart);
Assert.AreEqual(2, collection[1].Offset);
Assert.AreEqual(2, collection[1].Duration);
Assert.AreEqual(0, collection[1].MediaStart);
Assert.AreEqual(4, collection[2].Offset);
Assert.AreEqual(6, collection[2].Duration);
Assert.AreEqual(4, collection[2].MediaStart);
}
[Test]
public void StronglyTypedEnumerate()
{
var collection = new VirtualClipCollection();
collection.AddVirtualClip(new MockClip(0, 10, 0));
collection.AddVirtualClip(new MockClip(2, 2, 0));
// test the strongly typed enumerator
int index = 0;
IEnumerator<IVirtualClip> genericEnumerator = collection.GetEnumerator();
while (genericEnumerator.MoveNext())
{
Assert.AreSame(genericEnumerator.Current, collection[index++]);
}
Assert.AreEqual(3, index);
}
[Test]
public void UntypedEnumerate()
{
var collection = new VirtualClipCollection();
collection.AddVirtualClip(new MockClip(0, 10, 0));
collection.AddVirtualClip(new MockClip(2, 2, 0));
// and the untyped enumerator
int index = 0;
IEnumerator enumerator = ((IEnumerable) collection).GetEnumerator();
while (enumerator.MoveNext())
{
Assert.AreSame(enumerator.Current, collection[index++]);
}
Assert.AreEqual(3, index);
}
}
} | 34.886792 | 86 | 0.598882 | [
"Apache-2.0"
] | Supermortal/MusicianHelper | splicer-99885/src/Backup/Splicer.Tests/Timeline/VirtualClipCollectionFixture.cs | 5,547 | C# |
namespace Tomba
{
public enum OrderType
{
ASC,
DESC
}
}
| 9.333333 | 25 | 0.47619 | [
"Apache-2.0"
] | tomba-io/csharp | src/Tomba/Models/OrderType.cs | 84 | C# |
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using SharpGen.Model;
using System.Collections.Generic;
using System.Linq;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace SharpGen.Generator.Marshallers
{
class NullableInstanceMarshaller : MarshallerBase, IMarshaller
{
public NullableInstanceMarshaller(GlobalNamespaceProvider globalNamespace) : base(globalNamespace)
{
}
public bool CanMarshal(CsMarshalBase csElement)
{
return csElement.PassedByNullableInstance && !csElement.HasNativeValueType;
}
public ArgumentSyntax GenerateManagedArgument(CsParameter csElement)
{
return GenerateManagedValueTypeArgument(csElement);
}
public ParameterSyntax GenerateManagedParameter(CsParameter csElement)
{
return GenerateManagedValueTypeParameter(csElement);
}
public StatementSyntax GenerateManagedToNative(CsMarshalBase csElement, bool singleStackFrame)
{
return GenerateNullCheckIfNeeded(csElement,
ExpressionStatement(AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
GetMarshalStorageLocation(csElement),
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(csElement.Name),
IdentifierName("Value")))));
}
public IEnumerable<StatementSyntax> GenerateManagedToNativeProlog(CsMarshalCallableBase csElement)
{
yield return LocalDeclarationStatement(
VariableDeclaration(ParseTypeName(csElement.PublicType.QualifiedName),
SingletonSeparatedList(
VariableDeclarator(GetMarshalStorageLocationIdentifier(csElement)))));
}
public ArgumentSyntax GenerateNativeArgument(CsMarshalCallableBase csElement)
{
return Argument(GenerateNullCheckIfNeeded(csElement,
PrefixUnaryExpression(SyntaxKind.AddressOfExpression,
GetMarshalStorageLocation(csElement)),
CastExpression(
PointerType(PredefinedType(Token(SyntaxKind.VoidKeyword))),
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))));
}
public StatementSyntax GenerateNativeCleanup(CsMarshalBase csElement, bool singleStackFrame)
{
return null;
}
public StatementSyntax GenerateNativeToManaged(CsMarshalBase csElement, bool singleStackFrame)
{
return ExpressionStatement(AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
IdentifierName(csElement.Name),
GetMarshalStorageLocation(csElement)));
}
public IEnumerable<StatementSyntax> GenerateNativeToManagedExtendedProlog(CsMarshalCallableBase csElement)
{
return Enumerable.Empty<StatementSyntax>();
}
public FixedStatementSyntax GeneratePin(CsParameter csElement)
{
return null;
}
public bool GeneratesMarshalVariable(CsMarshalCallableBase csElement)
{
return true;
}
public TypeSyntax GetMarshalTypeSyntax(CsMarshalBase csElement)
{
return ParseTypeName(csElement.MarshalType.QualifiedName);
}
}
}
| 37.652174 | 114 | 0.677829 | [
"MIT"
] | JKamsker/SharpGenTools | SharpGen/Generator/Marshallers/NullableInstanceMarshaller.cs | 3,466 | C# |
// Created by Kearan Petersen : https://www.blumalice.wordpress.com | https://www.linkedin.com/in/kearan-petersen/
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Events;
namespace SOFlow.Fading
{
public class GenericFader : MonoBehaviour
{
/// <summary>
/// The fade curve.
/// </summary>
public AnimationCurve FadeCurve = new AnimationCurve(new Keyframe(0f, 0f), new Keyframe(1f, 1f));
/// <summary>
/// The faded colour.
/// </summary>
public Color FadedColour = Color.white;
/// <summary>
/// The fade targets.
/// </summary>
public List<Fadable> FadeTargets = new List<Fadable>();
/// <summary>
/// The fade time.
/// </summary>
public float FadeTime = 1f;
/// <summary>
/// Event raised when the fading is completed.
/// </summary>
public UnityEvent OnFadeComplete = new UnityEvent();
/// <summary>
/// Event raised before the fade starts.
/// </summary>
public UnityEvent OnFadeStart = new UnityEvent();
/// <summary>
/// Event raised when waiting between fades.
/// </summary>
public UnityEvent OnFadeWait = new UnityEvent();
/// <summary>
/// Enable to only allow fading in.
/// </summary>
public bool OnlyFadeIn;
/// <summary>
/// The unfade curve.
/// </summary>
public AnimationCurve UnfadeCurve = new AnimationCurve(new Keyframe(0f, 0f), new Keyframe(1f, 1f));
/// <summary>
/// The unfaded colour.
/// </summary>
public Color UnfadedColour = Color.white;
/// <summary>
/// The unfade time.
/// </summary>
public float UnfadeTime = 1f;
/// <summary>
/// The wait between fades.
/// </summary>
public float WaitBetweenFades = 1f;
/// <summary>
/// Indicates whether we are currently fading.
/// </summary>
public bool Fading
{
get;
private set;
}
/// <summary>
/// Initiates the fade.
/// </summary>
public async void Fade()
{
if(!Fading && gameObject.activeInHierarchy)
{
OnFadeStart.Invoke();
Fading = true;
float startTime = Time.realtimeSinceStartup;
float endTime = startTime + FadeTime;
while(Time.realtimeSinceStartup < endTime)
{
float percentage = (Time.realtimeSinceStartup - startTime) /
(endTime - startTime);
foreach(Fadable fadable in FadeTargets)
{
fadable.OnUpdateColour(Color.Lerp(UnfadedColour, FadedColour, FadeCurve.Evaluate(percentage)),
percentage);
}
await Task.Yield();
}
foreach(Fadable fadable in FadeTargets)
{
fadable.OnUpdateColour(FadedColour, 1f);
}
if(!OnlyFadeIn)
{
OnFadeWait.Invoke();
await Task.Delay((int)(WaitBetweenFades * 1000));
Unfade();
}
else
{
Fading = false;
OnFadeComplete.Invoke();
}
}
}
private async void Unfade()
{
float startTime = Time.realtimeSinceStartup;
float endTime = startTime + UnfadeTime;
while(Time.realtimeSinceStartup < endTime)
{
float percentage = (Time.realtimeSinceStartup - startTime) /
(endTime - startTime);
foreach(Fadable fadable in FadeTargets)
{
fadable.OnUpdateColour(Color.Lerp(FadedColour, UnfadedColour, UnfadeCurve.Evaluate(percentage)),
percentage);
}
await Task.Yield();
}
foreach(Fadable fadable in FadeTargets)
{
fadable.OnUpdateColour(UnfadedColour, 0f);
}
Fading = false;
OnFadeComplete.Invoke();
}
#if UNITY_EDITOR
/// <summary>
/// Adds a Generic Fader to the scene.
/// </summary>
[UnityEditor.MenuItem("GameObject/SOFlow/Fading/Faders/Add Generic Fader", false, 10)]
public static void AddComponentToScene()
{
GameObject _gameObject = new GameObject("Generic Fader", typeof(GenericFader));
if(UnityEditor.Selection.activeTransform != null)
{
_gameObject.transform.SetParent(UnityEditor.Selection.activeTransform);
}
UnityEditor.Selection.activeGameObject = _gameObject;
}
#endif
}
} | 29.817143 | 118 | 0.498467 | [
"MIT"
] | BLUDRAG/SOFlow-Extensions | Assets/SOFlow Extensions/Fading/Faders/GenericFader.cs | 5,218 | 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 OnvifVideoSample.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("OnvifVideoSample.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 43.671875 | 182 | 0.614669 | [
"MIT"
] | BigOtzelot/OnvifLogInfoTester | OnvifLogInfoTester/Properties/Resources.Designer.cs | 2,797 | C# |
// (c) Nick Polyak 2013 - http://awebpros.com/
// License: Code Project Open License (CPOL) 1.92(http://www.codeproject.com/info/cpol10.aspx)
//
// short overview of copyright rules:
// 1. you can use this framework in any commercial or non-commercial
// product as long as you retain this copyright message
// 2. Do not blame the author(s) of this software if something goes wrong.
//
// Also as a courtesy, please, mention this software in any documentation for the
// products that use it.
using System;
namespace NP.Concepts.Binding.GettersAndSetters
{
public class APropGetter<PropertyType> : IPropGetter<PropertyType>
{
object _obj;
AProp<object, PropertyType> _aProp;
public APropGetter(object obj, AProp<object, PropertyType> aProp)
{
_obj = obj;
_aProp = aProp;
_aProp.AddOnPropertyChangedHandler(_obj, OnPropChanged);
}
~APropGetter()
{
_aProp.RemoveOnPropertyChangedHandler(_obj, OnPropChanged);
}
void OnPropChanged(object obj, PropertyType oldValue, PropertyType newValue)
{
TriggerPropertyChanged();
}
public event Action PropertyChangedEvent;
public PropertyType GetPropValue() => _aProp.GetProperty(_obj);
public void TriggerPropertyChanged()
{
PropertyChangedEvent?.Invoke();
}
}
public class APropWithDefaultGetter<PropertyType> :
GenericSimplePropWithDefaultGetter<PropertyType>
{
AProp<object, PropertyType> _aProp;
protected override void OnObjUnset()
{
_aProp.RemoveOnPropertyChangedHandler(TheObj, OnPropChanged);
}
protected override void OnObjSet()
{
_aProp.AddOnPropertyChangedHandler(TheObj, OnPropChanged);
}
public APropWithDefaultGetter
(
AProp<object, PropertyType> aProp,
PropertyType defaultValue = default(PropertyType)
)
: base(defaultValue)
{
_aProp = aProp;
}
void OnPropChanged(object obj, PropertyType oldValue, PropertyType newValue)
{
TriggerPropertyChanged();
}
public override PropertyType GetPropValue()
{
return _aProp.GetProperty(TheObj);
}
}
public class APropSetter<PropertyType> :
GenericSimplePropSetter<PropertyType>
{
protected override void OnObjSet()
{
}
protected override void SetPropValue(PropertyType propValue)
{
_aProp.SetProperty(TheObj, propValue);
}
AProp<object, PropertyType> _aProp;
void Init(AProp<object, PropertyType> aProp)
{
_aProp = aProp;
}
public APropSetter(AProp<object, PropertyType> aProp) : base()
{
Init(aProp);
}
public APropSetter(object obj, AProp<object, PropertyType> aProp) : base(obj)
{
Init(aProp);
}
}
}
| 27.122807 | 94 | 0.610931 | [
"Apache-2.0"
] | npolyak/NP.Concepts.Bindings | GettersAndSetters/APropsGetterAndSetter.cs | 3,094 | 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.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.ChangeSignature
{
internal sealed class ParameterConfiguration
{
public readonly ExistingParameter? ThisParameter;
public readonly ImmutableArray<Parameter> ParametersWithoutDefaultValues;
public readonly ImmutableArray<Parameter> RemainingEditableParameters;
public readonly ExistingParameter? ParamsParameter;
public readonly int SelectedIndex;
public ParameterConfiguration(
ExistingParameter? thisParameter,
ImmutableArray<Parameter> parametersWithoutDefaultValues,
ImmutableArray<Parameter> remainingEditableParameters,
ExistingParameter? paramsParameter,
int selectedIndex)
{
ThisParameter = thisParameter;
ParametersWithoutDefaultValues = parametersWithoutDefaultValues;
RemainingEditableParameters = remainingEditableParameters;
ParamsParameter = paramsParameter;
SelectedIndex = selectedIndex;
}
public static ParameterConfiguration Create(ImmutableArray<Parameter> parameters, bool isExtensionMethod, int selectedIndex)
{
var parametersList = parameters.ToList();
ExistingParameter? thisParameter = null;
var parametersWithoutDefaultValues = ArrayBuilder<Parameter>.GetInstance();
var remainingReorderableParameters = ArrayBuilder<Parameter>.GetInstance();
ExistingParameter? paramsParameter = null;
if (parametersList.Count > 0 && isExtensionMethod)
{
// Extension method `this` parameters cannot be added, so must be pre-existing.
thisParameter = (ExistingParameter)parametersList[0];
parametersList.RemoveAt(0);
}
if ((parametersList.LastOrDefault() as ExistingParameter)?.Symbol.IsParams == true)
{
// Params arrays cannot be added, so must be pre-existing.
paramsParameter = (ExistingParameter)parametersList[parametersList.Count - 1];
parametersList.RemoveAt(parametersList.Count - 1);
}
var seenDefaultValues = false;
foreach (var param in parametersList)
{
if (param.HasDefaultValue)
{
seenDefaultValues = true;
}
(seenDefaultValues ? remainingReorderableParameters : parametersWithoutDefaultValues).Add(param);
}
return new ParameterConfiguration(thisParameter, parametersWithoutDefaultValues.ToImmutableAndFree(), remainingReorderableParameters.ToImmutableAndFree(), paramsParameter, selectedIndex);
}
internal ParameterConfiguration WithoutAddedParameters()
=> Create(ToListOfParameters().OfType<ExistingParameter>().ToImmutableArray<Parameter>(), ThisParameter != null, selectedIndex: 0);
public ImmutableArray<Parameter> ToListOfParameters()
{
var list = ArrayBuilder<Parameter>.GetInstance();
if (ThisParameter != null)
{
list.Add(ThisParameter);
}
list.AddRange(ParametersWithoutDefaultValues);
list.AddRange(RemainingEditableParameters);
if (ParamsParameter != null)
{
list.Add(ParamsParameter);
}
return list.ToImmutableAndFree();
}
}
}
| 40.468085 | 199 | 0.656151 | [
"MIT"
] | BrianFreemanAtlanta/roslyn | src/Features/Core/Portable/ChangeSignature/ParameterConfiguration.cs | 3,806 | C# |
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Obi{
[ExecuteInEditMode]
public class ObiCurve : MonoBehaviour {
[Serializable]
public struct ControlPoint{
public enum BezierCPMode {
Aligned,
Mirrored,
Free,
}
public Vector3 position;
public Vector3 normal;
public Vector3 inTangent;
public Vector3 outTangent;
public BezierCPMode tangentMode;
public ControlPoint(Vector3 position, Vector3 normal){
this.position = position;
this.normal = normal;
this.inTangent = -Vector3.right* 0.33f;
this.outTangent = Vector3.right* 0.33f;
this.tangentMode = BezierCPMode.Aligned;
}
public ControlPoint(Vector3 position, Vector3 normal, Vector3 inTangent, Vector3 outTangent, BezierCPMode tangentMode){
this.position = position;
this.normal = normal;
this.inTangent = inTangent;
this.outTangent = outTangent;
this.tangentMode = tangentMode;
}
public ControlPoint Transform (Vector3 translation, Quaternion rotation){
return new ControlPoint(position+translation,normal, rotation*inTangent, rotation*outTangent, tangentMode);
}
public ControlPoint Transform(Transform t){
return new ControlPoint(t.TransformPoint(position),t.TransformVector(normal),t.TransformVector(inTangent),t.TransformVector(outTangent), tangentMode);
}
public ControlPoint InverseTransform(Transform t){
return new ControlPoint(t.InverseTransformPoint(position),t.InverseTransformVector(normal),t.InverseTransformVector(inTangent),t.InverseTransformVector(outTangent), tangentMode);
}
// return tangent in world space:
public Vector3 GetInTangent(){
return position + inTangent;
}
// return tangent in local space:
public Vector3 GetOutTangent(){
return position + outTangent;
}
public ControlPoint SetInTangent(Vector3 tangent){
Vector3 newTangent = tangent - position;
switch(tangentMode){
case BezierCPMode.Mirrored: outTangent = -newTangent; break;
case BezierCPMode.Aligned: outTangent = -newTangent.normalized * outTangent.magnitude; break;
}
return new ControlPoint(position,normal,newTangent,outTangent,tangentMode);
}
public ControlPoint SetOutTangent(Vector3 tangent){
Vector3 newTangent = tangent - position;
switch(tangentMode){
case BezierCPMode.Mirrored: inTangent = -newTangent; break;
case BezierCPMode.Aligned: inTangent = -newTangent.normalized * inTangent.magnitude; break;
}
return new ControlPoint(position,normal,inTangent,newTangent,tangentMode);
}
}
protected const int arcLenghtSamples = 20;
public bool closed = false;
public List<ControlPoint> controlPoints = null;
[HideInInspector][SerializeField] protected List<float> arcLengthTable = null;
[HideInInspector][SerializeField] protected float totalSplineLenght = 0.0f;
/**
* Returns world-space spline lenght.
*/
public float Length{
get{return totalSplineLenght;}
}
public int MinPoints{
get{return 2;}
}
public void Awake(){
if (controlPoints == null){
controlPoints = new List<ControlPoint>(){
new ControlPoint(Vector3.left,Vector3.up),
new ControlPoint(Vector3.zero,Vector3.up)}
;
}
if (arcLengthTable == null){
arcLengthTable = new List<float>();
RecalculateSplineLenght(0.00001f,7);
}
}
public int GetNumSpans(){
if (controlPoints == null || controlPoints.Count < MinPoints)
return 0;
return closed ? controlPoints.Count : controlPoints.Count-1;
}
public int AddPoint(float mu){
if (controlPoints.Count >= MinPoints){
if (!System.Single.IsNaN(mu)){
float p;
int i = GetSpanControlPointForMu(mu,out p);
Vector3 normal = GetNormalAt(mu);
int next = (i+1) % controlPoints.Count;
Vector3 P0_1 = (1-p)*controlPoints[i].position + p*controlPoints[i].GetOutTangent();
Vector3 P1_2 = (1-p)*controlPoints[i].GetOutTangent() + p*controlPoints[next].GetInTangent();
Vector3 P2_3 = (1-p)*controlPoints[next].GetInTangent() + p*controlPoints[next].position;
Vector3 P01_12 = (1-p)*P0_1 + p*P1_2;
Vector3 P12_23 = (1-p)*P1_2 + p*P2_3;
Vector3 P0112_1223 = (1-p)*P01_12 + p*P12_23;
controlPoints[i] = controlPoints[i].SetOutTangent(P0_1);
controlPoints[next] = controlPoints[next].SetInTangent(P2_3);
controlPoints.Insert(i+1, new ControlPoint(P0112_1223,normal,P01_12 - P0112_1223,P12_23 - P0112_1223,ControlPoint.BezierCPMode.Aligned));
return i+1;
}
}
return -1;
}
public float GetClosestMuToPoint(Vector3 point,float samples){
if (controlPoints.Count >= MinPoints){
samples = Mathf.Max(1,samples);
float step = 1/(float)samples;
int numSpans = GetNumSpans();
float closestMu = 0;
float minDistance = float.MaxValue;
Matrix4x4 l2w = transform.localToWorldMatrix;
for(int k = 0; k < controlPoints.Count; ++k) {
Vector3 _p = l2w.MultiplyPoint3x4(controlPoints[k].position);
Vector3 p = l2w.MultiplyPoint3x4(controlPoints[k].GetOutTangent());
Vector3 p_ = l2w.MultiplyPoint3x4(controlPoints[k+1].GetInTangent());
Vector3 p__ = l2w.MultiplyPoint3x4(controlPoints[k+1].position);
Vector3 lastPoint = Evaluate3D(_p,p,p_,p__,0);
for(int i = 1; i <= samples; ++i){
Vector2 currentPoint = Evaluate3D(_p,p,p_,p__,i*step);
float mu;
float distance = Vector2.SqrMagnitude(ObiUtils.ProjectPointLine(point,lastPoint,currentPoint,out mu) - point);
if (distance < minDistance){
minDistance = distance;
closestMu = ((k-1) + (i-1)*step + mu/samples) / (float)numSpans;
}
lastPoint = currentPoint;
}
}
return closestMu;
}else{
Debug.LogWarning("Catmull-Rom spline needs at least 4 control points to be defined.");
}
return 0;
}
/**
* Recalculates spline arc lenght in world space using Gauss-Lobatto adaptive integration.
* @param acc minimum accuray desired (eg 0.00001f)
* @param maxevals maximum number of spline evaluations we want to allow per segment.
*/
public float RecalculateSplineLenght(float acc, int maxevals){
totalSplineLenght = 0.0f;
arcLengthTable.Clear();
arcLengthTable.Add(0);
float step = 1/(float)(arcLenghtSamples+1);
if (controlPoints.Count >= MinPoints){
Matrix4x4 l2w = transform.localToWorldMatrix;
for(int k = 0; k < GetNumSpans(); ++k) {
Vector3 _p = l2w.MultiplyPoint3x4(controlPoints[k].position);
Vector3 p = l2w.MultiplyPoint3x4(controlPoints[k].GetOutTangent());
Vector3 p_ = l2w.MultiplyPoint3x4(controlPoints[(k+1) % controlPoints.Count].GetInTangent());
Vector3 p__ = l2w.MultiplyPoint3x4(controlPoints[(k+1) % controlPoints.Count].position);
for(int i = 0; i <= Mathf.Max(1,arcLenghtSamples); ++i){
float a = i*step;
float b = (i+1)*step;
float segmentLength = GaussLobattoIntegrationStep(_p,p,p_,p__,a,b,
EvaluateFirstDerivative3D(_p,p,p_,p__,a).magnitude,
EvaluateFirstDerivative3D(_p,p,p_,p__,b).magnitude,0,maxevals,acc);
totalSplineLenght += segmentLength;
arcLengthTable.Add(totalSplineLenght);
}
}
}else{
Debug.LogWarning("Catmull-Rom spline needs at least 4 control points to be defined.");
}
return totalSplineLenght;
}
/**
* One step of the adaptive integration method using Gauss-Lobatto quadrature.
* Takes advantage of the fact that the arc lenght of a vector function is equal to the
* integral of the magnitude of first derivative.
*/
private float GaussLobattoIntegrationStep(Vector3 p1,Vector3 p2,Vector3 p3,Vector3 p4,
float a, float b,
float fa, float fb, int nevals, int maxevals, float acc){
if (nevals >= maxevals) return 0;
// Constants used in the algorithm
float alpha = Mathf.Sqrt(2.0f/3.0f);
float beta = 1.0f/Mathf.Sqrt(5.0f);
// Here the abcissa points and function values for both the 4-point
// and the 7-point rule are calculated (the points at the end of
// interval come from the function call, i.e., fa and fb. Also note
// the 7-point rule re-uses all the points of the 4-point rule.)
float h=(b-a)/2;
float m=(a+b)/2;
float mll=m-alpha*h;
float ml =m-beta*h;
float mr =m+beta*h;
float mrr=m+alpha*h;
nevals += 5;
float fmll= EvaluateFirstDerivative3D(p1,p2,p3,p4,mll).magnitude;
float fml = EvaluateFirstDerivative3D(p1,p2,p3,p4,ml).magnitude;
float fm = EvaluateFirstDerivative3D(p1,p2,p3,p4,m).magnitude;
float fmr = EvaluateFirstDerivative3D(p1,p2,p3,p4,mr).magnitude;
float fmrr= EvaluateFirstDerivative3D(p1,p2,p3,p4,mrr).magnitude;
// Both the 4-point and 7-point rule integrals are evaluted
float integral4 = (h/6)*(fa+fb+5*(fml+fmr));
float integral7 = (h/1470)*(77*(fa+fb)+432*(fmll+fmrr)+625*(fml+fmr)+672*fm);
// The difference betwen the 4-point and 7-point integrals is the
// estimate of the accuracy
if((integral4-integral7) < acc || mll<=a || b<=mrr)
{
if (!(m>a && b>m))
{
Debug.LogError("Spline integration reached an interval with no more machine numbers");
}
return integral7;
}else{
return GaussLobattoIntegrationStep(p1,p2,p3,p4, a, mll, fa, fmll, nevals, maxevals, acc)
+ GaussLobattoIntegrationStep(p1,p2,p3,p4, mll, ml, fmll, fml, nevals, maxevals, acc)
+ GaussLobattoIntegrationStep(p1,p2,p3,p4, ml, m, fml, fm, nevals, maxevals, acc)
+ GaussLobattoIntegrationStep(p1,p2,p3,p4, m, mr, fm, fmr, nevals, maxevals, acc)
+ GaussLobattoIntegrationStep(p1,p2,p3,p4, mr, mrr, fmr, fmrr, nevals, maxevals, acc)
+ GaussLobattoIntegrationStep(p1,p2,p3,p4, mrr, b, fmrr, fb, nevals, maxevals, acc);
}
}
/**
* Returns the curve parameter (mu) at a certain length of the curve, using linear interpolation
* of the values cached in arcLengthTable.
*/
public float GetMuAtLenght(float length){
if (length <= 0) return 0;
if (length >= totalSplineLenght) return 1;
int i;
for (i = 1; i < arcLengthTable.Count; ++i) {
if (length < arcLengthTable[i]) break;
}
float prevMu = (i-1)/(float)(arcLengthTable.Count-1);
float nextMu = i/(float)(arcLengthTable.Count-1);
float s = (length - arcLengthTable[i-1]) / (arcLengthTable[i] - arcLengthTable[i-1]);
return prevMu + (nextMu - prevMu) * s;
}
public int GetSpanControlPointForMu(float mu, out float spanMu){
int spanCount = GetNumSpans();
spanMu = mu * spanCount;
int i = (mu >= 1f) ? (spanCount - 1) : (int) spanMu;
spanMu -= i;
return i;
}
/**
* Returns spline position at time mu, with 0<=mu<=1 where 0 is the start of the spline
* and 1 is the end.
*/
public Vector3 GetPositionAt(float mu){
if (controlPoints.Count >= MinPoints){
if (!System.Single.IsNaN(mu)){
float p;
int i = GetSpanControlPointForMu(mu,out p);
return Evaluate3D(controlPoints[i].position,
controlPoints[i].GetOutTangent(),
controlPoints[(i+1) % controlPoints.Count].GetInTangent(),
controlPoints[(i+1) % controlPoints.Count].position,p);
}else{
return controlPoints[0].position;
}
}
//Special case: degenerate spline - point
else if (controlPoints.Count == 1){
return controlPoints[0].position;
}else{
throw new InvalidOperationException("Cannot get position in Catmull-Rom spline because it has zero control points.");
}
}
/**
* Returns normal tangent vector at time mu, with 0<=mu<=1 where 0 is the start of the spline
* and 1 is the end.
*/
public Vector3 GetFirstDerivativeAt(float mu){
if (controlPoints.Count >= MinPoints){
if (!System.Single.IsNaN(mu)){
float p;
int i = GetSpanControlPointForMu(mu,out p);
return EvaluateFirstDerivative3D(controlPoints[i].position,
controlPoints[i].GetOutTangent(),
controlPoints[(i+1) % controlPoints.Count].GetInTangent(),
controlPoints[(i+1) % controlPoints.Count].position,p);
}else{
return controlPoints[controlPoints.Count-1].position-controlPoints[0].position;
}
}else{
throw new InvalidOperationException("Cannot get tangent in Catmull-Rom spline because it has zero or one control points.");
}
}
/**
* Returns acceleration at time mu, with 0<=mu<=1 where 0 is the start of the spline
* and 1 is the end.
*/
public Vector3 GetSecondDerivativeAt(float mu){
if (controlPoints.Count >= MinPoints){
if (!System.Single.IsNaN(mu)){
float p;
int i = GetSpanControlPointForMu(mu,out p);
return EvaluateSecondDerivative3D(controlPoints[i].position,
controlPoints[i].GetOutTangent(),
controlPoints[(i+1) % controlPoints.Count].GetInTangent(),
controlPoints[(i+1) % controlPoints.Count].position,p);
}else{
return Vector3.zero;
}
}
//In all degenerate cases (straight lines or points), acceleration is zero:
return Vector3.zero;
}
public Vector3 GetNormalAt(float mu){
if (controlPoints.Count >= MinPoints){
if (!System.Single.IsNaN(mu)){
float p;
int i = GetSpanControlPointForMu(mu,out p);
return Vector3.Slerp(controlPoints[i].normal,controlPoints[(i+1) % controlPoints.Count].normal,p);
}else{
return Vector3.zero;
}
}
//In all degenerate cases (straight lines or points), acceleration is zero:
return Vector3.zero;
}
/**
* 1D bezier spline interpolation
*/
public float Evaluate1D(float y0, float y1, float y2, float y3, float mu){
float imu = 1 - mu;
return imu * imu * imu * y0 +
3f * imu * imu * mu * y1 +
3f * imu * mu * mu * y2 +
mu * mu * mu * y3;
}
/**
* 1D catmull rom spline second derivative
*/
public float EvaluateFirstDerivative1D(float y0, float y1, float y2, float y3, float mu){
float imu = 1 - mu;
return 3f * imu * imu * (y1 - y0) +
6f * imu * mu * (y2 - y1) +
3f * mu * mu * (y3 - y2);
}
/**
* 1D catmull rom spline second derivative
*/
public float EvaluateSecondDerivative1D(float y0, float y1, float y2, float y3, float mu){
float imu = 1 - mu;
return 3f * imu * imu * (y1 - y0) +
6f * imu * mu * (y2 - y1) +
3f * mu * mu * (y3 - y2);
}
/**
* 3D spline interpolation
*/
public Vector3 Evaluate3D(Vector3 y0, Vector3 y1, Vector3 y2, Vector3 y3, float mu){
return new Vector3(Evaluate1D(y0.x,y1.x,y2.x,y3.x,mu),
Evaluate1D(y0.y,y1.y,y2.y,y3.y,mu),
Evaluate1D(y0.z,y1.z,y2.z,y3.z,mu));
}
/**
* 3D spline first derivative
*/
public Vector3 EvaluateFirstDerivative3D(Vector3 y0, Vector3 y1, Vector3 y2, Vector3 y3, float mu){
return new Vector3(EvaluateFirstDerivative1D(y0.x,y1.x,y2.x,y3.x,mu),
EvaluateFirstDerivative1D(y0.y,y1.y,y2.y,y3.y,mu),
EvaluateFirstDerivative1D(y0.z,y1.z,y2.z,y3.z,mu));
}
/**
* 3D spline second derivative
*/
public Vector3 EvaluateSecondDerivative3D(Vector3 y0, Vector3 y1, Vector3 y2, Vector3 y3, float mu){
return new Vector3(EvaluateSecondDerivative1D(y0.x,y1.x,y2.x,y3.x,mu),
EvaluateSecondDerivative1D(y0.y,y1.y,y2.y,y3.y,mu),
EvaluateSecondDerivative1D(y0.z,y1.z,y2.z,y3.z,mu));
}
}
}
| 29.227273 | 181 | 0.67049 | [
"Unlicense"
] | WeTeamA/ChemHack | Assets/Obi/Scripts/Utils/ObiCurve.cs | 15,434 | C# |
//
// WPFEngine.cs
//
// Author:
// Carlos Alberto Cortez <calberto.cortez@gmail.com>
// Luis Reis <luiscubal@gmail.com>
// Thomas Ziegler <ziegler.thomas@web.de>
// Eric Maupin <ermau@xamarin.com>
//
// Copyright (c) 2011 Carlos Alberto Cortez
// Copyright (c) 2012 Lu�s Reis
// Copyright (c) 2012 Thomas Ziegler
// Copyright (c) 2012 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Xwt.Backends;
using Xwt.Drawing;
namespace Xwt.WPFBackend
{
public class WPFEngine : Xwt.Backends.ToolkitEngineBackend
{
System.Windows.Application application;
public static WPFEngine Instance { get; private set; }
public WPFEngine ()
{
Instance = this;
}
public override void InitializeApplication ()
{
application = System.Windows.Application.Current;
if (application == null)
application = new System.Windows.Application ();
application.ShutdownMode = ShutdownMode.OnExplicitShutdown;
RegisterBackend<IWindowBackend, WindowBackend> ();
RegisterBackend<IDialogBackend, DialogBackend> ();
RegisterBackend<INotebookBackend, NotebookBackend> ();
RegisterBackend<IMenuBackend, MenuBackend> ();
RegisterBackend<IMenuItemBackend, MenuItemBackend> ();
RegisterBackend<ICheckBoxMenuItemBackend, CheckboxMenuItemBackend> ();
RegisterBackend<IRadioButtonMenuItemBackend, RadioButtonMenuItemBackend> ();
RegisterBackend<ISeparatorMenuItemBackend, SeparatorMenuItemBackend> ();
RegisterBackend<IBoxBackend, BoxBackend> ();
RegisterBackend<ILabelBackend, LabelBackend> ();
RegisterBackend<ITextEntryBackend, TextEntryBackend> ();
RegisterBackend<IButtonBackend, ButtonBackend> ();
RegisterBackend<IToggleButtonBackend, ToggleButtonBackend> ();
RegisterBackend<IMenuButtonBackend, MenuButtonBackend> ();
RegisterBackend<ICheckBoxBackend, CheckBoxBackend> ();
RegisterBackend<ITreeViewBackend, TreeViewBackend> ();
RegisterBackend<ITreeStoreBackend, TreeStoreBackend> ();
RegisterBackend<IImageViewBackend, ImageViewBackend> ();
RegisterBackend<ISeparatorBackend, SeparatorBackend> ();
RegisterBackend<ImageBackendHandler, ImageHandler> ();
RegisterBackend<FontBackendHandler, WpfFontBackendHandler> ();
RegisterBackend<ClipboardBackend, WpfClipboardBackend> ();
RegisterBackend<IComboBoxBackend, ComboBoxBackend> ();
RegisterBackend<IComboBoxEntryBackend, ComboBoxEntryBackend> ();
RegisterBackend<IScrollViewBackend, ScrollViewBackend> ();
RegisterBackend<IFrameBackend, FrameBackend> ();
RegisterBackend<ICanvasBackend, CanvasBackend> ();
RegisterBackend<ContextBackendHandler, WpfContextBackendHandler> ();
RegisterBackend<DrawingPathBackendHandler, WpfContextBackendHandler> ();
RegisterBackend<GradientBackendHandler, WpfGradientBackendHandler> ();
RegisterBackend<TextLayoutBackendHandler, WpfTextLayoutBackendHandler> ();
RegisterBackend<ICustomWidgetBackend, CustomWidgetBackend> ();
RegisterBackend<IPanedBackend, PanedBackend> ();
RegisterBackend<IScrollAdjustmentBackend, ScrollAdjustmentBackend> ();
RegisterBackend<IOpenFileDialogBackend, OpenFileDialogBackend> ();
RegisterBackend<ISaveFileDialogBackend, SaveFileDialogBackend> ();
RegisterBackend<ISelectFolderDialogBackend, SelectFolderDialogBackend> ();
RegisterBackend<IAlertDialogBackend, AlertDialogBackend> ();
RegisterBackend<ImageBuilderBackendHandler, WpfImageBuilderBackendHandler> ();
RegisterBackend<ImagePatternBackendHandler, WpfImagePatternBackendHandler> ();
RegisterBackend<IListViewBackend, ListViewBackend> ();
RegisterBackend<IListStoreBackend, ListDataSource> ();
RegisterBackend<IListBoxBackend, ListBoxBackend> ();
RegisterBackend<IPopoverBackend, PopoverBackend> ();
RegisterBackend<IProgressBarBackend, ProgressBarBackend> ();
RegisterBackend<IRichTextViewBackend, RichTextViewBackend> ();
RegisterBackend<ILinkLabelBackend, LinkLabelBackend> ();
RegisterBackend<ISpinnerBackend, SpinnerBackend> ();
RegisterBackend<DesktopBackend, WpfDesktopBackend>();
RegisterBackend<IExpanderBackend, ExpanderBackend>();
RegisterBackend<IDatePickerBackend, DatePickerBackend>();
RegisterBackend<ISelectColorDialogBackend, SelectColorDialogBackend>();
RegisterBackend<IRadioButtonBackend, RadioButtonBackend>();
RegisterBackend<ISpinButtonBackend, SpinButtonBackend>();
RegisterBackend<ISliderBackend, SliderBackend> ();
RegisterBackend<IScrollbarBackend, ScrollbarBackend> ();
RegisterBackend<IEmbeddedWidgetBackend, EmbedNativeWidgetBackend>();
RegisterBackend<IPasswordEntryBackend, PasswordEntryBackend> ();
RegisterBackend<IWebViewBackend, WebViewBackend> ();
RegisterBackend<KeyboardHandler, WpfKeyboardHandler> ();
RegisterBackend<ICalendarBackend, CalendarBackend> ();
}
public override void DispatchPendingEvents()
{
application.Dispatcher.Invoke ((Action)(() => { }), DispatcherPriority.Background);
}
public override void RunApplication ()
{
application.Run ();
}
public override void ExitApplication ()
{
application.Shutdown();
}
public override void InvokeAsync (Action action)
{
if (action == null)
throw new ArgumentNullException ("action");
application.Dispatcher.BeginInvoke (action, new object [0]);
}
public override object TimerInvoke (Func<bool> action, TimeSpan timeSpan)
{
if (action == null)
throw new ArgumentNullException ("action");
return Timeout.Add (action, timeSpan, application.Dispatcher);
}
public override void CancelTimerInvoke (object id)
{
if (id == null)
throw new ArgumentNullException ("id");
Timeout.CancelTimeout ((uint)id);
}
public override IWindowFrameBackend GetBackendForWindow (object nativeWindow)
{
return new WindowFrameBackend () {
Window = (System.Windows.Window) nativeWindow
};
}
public override object GetBackendForImage (object nativeImage)
{
if (nativeImage is WpfImage)
return nativeImage;
return ImageHandler.LoadFromImageSource ((System.Windows.Media.ImageSource) nativeImage);
}
public override object GetBackendForContext (object nativeWidget, object nativeContext)
{
return new DrawingContext (
(System.Windows.Media.DrawingContext)nativeContext,
((System.Windows.Media.Visual)nativeWidget).GetScaleFactor ()
);
}
public override object GetNativeWidget (Widget w)
{
var backend = (IWpfWidgetBackend) Toolkit.GetBackend (w);
return backend.Widget;
}
public override object GetNativeParentWindow (Widget w)
{
var backend = (IWpfWidgetBackend)Toolkit.GetBackend (w);
FrameworkElement e = backend.Widget;
while ((e = e.Parent as FrameworkElement) != null)
if (e is System.Windows.Window)
return e;
return null;
}
public override bool HasNativeParent (Widget w)
{
var b = (IWidgetBackend) Toolkit.GetBackend (w);
if (b is XwtWidgetBackend)
b = ((XwtWidgetBackend)b).NativeBackend;
IWpfWidgetBackend wb = (IWpfWidgetBackend)b;
return VisualTreeHelper.GetParent (wb.Widget) != null;
}
public override object GetNativeImage (Image image)
{
var source = (WpfImage)Toolkit.GetBackend (image);
return source.MainFrame ?? source.GetBestFrame (ApplicationContext, 1, image.Width, image.Height, true);
}
public override object RenderWidget (Widget widget)
{
try {
var w = ((WidgetBackend)widget.GetBackend ()).Widget;
RenderTargetBitmap rtb = new RenderTargetBitmap ((int)w.ActualWidth, (int)w.ActualHeight, 96, 96, PixelFormats.Pbgra32);
rtb.Render(w);
return new WpfImage(rtb);
} catch (Exception ex) {
throw new InvalidOperationException ("Rendering element not supported", ex);
}
}
public override void RenderImage (object nativeWidget, object nativeContext, ImageDescription img, double x, double y)
{
WpfImage im = (WpfImage)img.Backend;
System.Windows.Media.DrawingContext dc = nativeContext as System.Windows.Media.DrawingContext;
FrameworkElement w = (FrameworkElement)nativeWidget;
if (dc != null)
im.Draw (ApplicationContext, dc, Util.GetScaleFactor (w), x, y, img);
}
}
}
| 39.118852 | 125 | 0.740702 | [
"MIT"
] | thiagoabreu/xwt | Xwt.WPF/Xwt.WPFBackend/WPFEngine.cs | 9,547 | C# |
using System;
namespace ETModel
{
public abstract class Singleton<T> where T : class, new()
{
private static T m_instance;
public static T Instance
{
get
{
if (Singleton<T>.m_instance == null)
{
Singleton<T>.m_instance = Activator.CreateInstance<T>();
if (Singleton<T>.m_instance != null)
{
(Singleton<T>.m_instance as Singleton<T>).Init();
}
}
return Singleton<T>.m_instance;
}
}
public static void Release()
{
if (Singleton<T>.m_instance != null)
{
Singleton<T>.m_instance = (T)((object)null);
}
}
public virtual void Init()
{
}
public virtual void Dispose()
{
}
}
} | 22.023256 | 76 | 0.423442 | [
"MIT"
] | passiony/ETFramework | Unity/Assets/Model/Module/Singleton/Singleton.cs | 947 | C# |
/* MIT LICENSE
Copyright 2018 Max Brauer (ma.brauer@live.de)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in the
Software without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("Korrektur Hilfe")]
[assembly: AssemblyDescription("Die Hilfe für Kontrolleure bei OstEpu")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Max Brauer")]
[assembly: AssemblyProduct("KorrekturHilfe")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly
// für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("add940ab-9113-4f0b-9ebc-adf984517925")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden,
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 44.266667 | 106 | 0.777485 | [
"MIT"
] | Garados007/Korregator | KorrekturHilfe/Properties/AssemblyInfo.cs | 2,673 | C# |
using System.Threading.Tasks;
using StateMachines;
using Units.Formation;
namespace LifeCycle.Level.States
{
public class DivingWaveState : IAwaitableState<LevelStateType>
{
private readonly ShipsFormation _shipsFormation;
private readonly LevelContext _levelContext;
private readonly LevelSettings _levelSettings;
public DivingWaveState(ShipsFormation shipsFormation, LevelContext levelContext, LevelSettings levelSettings)
{
_shipsFormation = shipsFormation;
_levelContext = levelContext;
_levelSettings = levelSettings;
}
public async Task RunState()
{
await _shipsFormation.StartAttackWave();
_levelContext.TimeToWait = _levelSettings.TimeBetweenWaves;
}
public LevelStateType Type => LevelStateType.DivingWave;
public bool IsExitState => false;
}
} | 31.896552 | 117 | 0.688649 | [
"MIT"
] | Volodej/GalagaTestProject | Assets/Scripts/LifeCycle/Level/States/DivingWaveState.cs | 925 | C# |
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Infrastructure;
using OpenIddict.Abstractions;
using static OpenIddict.Abstractions.OpenIddictConstants;
using static OpenIddict.Validation.OpenIddictValidationEvents;
using SR = OpenIddict.Abstractions.OpenIddictResources;
namespace OpenIddict.Validation.Owin
{
/// <summary>
/// Provides the entry point necessary to register the OpenIddict validation in an OWIN pipeline.
/// </summary>
public class OpenIddictValidationOwinHandler : AuthenticationHandler<OpenIddictValidationOwinOptions>
{
private readonly IOpenIddictValidationDispatcher _dispatcher;
private readonly IOpenIddictValidationFactory _factory;
/// <summary>
/// Creates a new instance of the <see cref="OpenIddictValidationOwinHandler"/> class.
/// </summary>
/// <param name="dispatcher">The OpenIddict validation provider used by this instance.</param>
/// <param name="factory">The OpenIddict validation factory used by this instance.</param>
public OpenIddictValidationOwinHandler(
IOpenIddictValidationDispatcher dispatcher,
IOpenIddictValidationFactory factory)
{
_dispatcher = dispatcher;
_factory = factory;
}
/// <inheritdoc/>
protected override async Task InitializeCoreAsync()
{
// Note: the transaction may be already attached when replaying an OWIN request
// (e.g when using a status code pages middleware re-invoking the OWIN pipeline).
var transaction = Context.Get<OpenIddictValidationTransaction>(typeof(OpenIddictValidationTransaction).FullName);
if (transaction is null)
{
// Create a new transaction and attach the OWIN request to make it available to the OWIN handlers.
transaction = await _factory.CreateTransactionAsync();
transaction.Properties[typeof(IOwinRequest).FullName!] = new WeakReference<IOwinRequest>(Request);
// Attach the OpenIddict validation transaction to the OWIN shared dictionary
// so that it can retrieved while performing sign-in/sign-out operations.
Context.Set(typeof(OpenIddictValidationTransaction).FullName, transaction);
}
var context = new ProcessRequestContext(transaction);
await _dispatcher.DispatchAsync(context);
// Store the context in the transaction so that it can be retrieved from InvokeAsync().
transaction.SetProperty(typeof(ProcessRequestContext).FullName!, context);
}
/// <inheritdoc/>
public override async Task<bool> InvokeAsync()
{
// Note: due to internal differences between ASP.NET Core and Katana, the request MUST start being processed
// in InitializeCoreAsync() to ensure the request context is available from AuthenticateCoreAsync() when
// active authentication is used, as AuthenticateCoreAsync() is always called before InvokeAsync() in this case.
var transaction = Context.Get<OpenIddictValidationTransaction>(typeof(OpenIddictValidationTransaction).FullName) ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0166));
var context = transaction.GetProperty<ProcessRequestContext>(typeof(ProcessRequestContext).FullName!) ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0166));
if (context.IsRequestHandled)
{
return true;
}
else if (context.IsRequestSkipped)
{
return false;
}
else if (context.IsRejected)
{
var notification = new ProcessErrorContext(transaction)
{
Response = new OpenIddictResponse
{
Error = context.Error ?? Errors.InvalidRequest,
ErrorDescription = context.ErrorDescription,
ErrorUri = context.ErrorUri
}
};
await _dispatcher.DispatchAsync(notification);
if (notification.IsRequestHandled)
{
return true;
}
else if (notification.IsRequestSkipped)
{
return false;
}
throw new InvalidOperationException(SR.GetResourceString(SR.ID0111));
}
return false;
}
/// <inheritdoc/>
protected override async Task<AuthenticationTicket?> AuthenticateCoreAsync()
{
var transaction = Context.Get<OpenIddictValidationTransaction>(typeof(OpenIddictValidationTransaction).FullName) ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0166));
// Note: in many cases, the authentication token was already validated by the time this action is called
// (generally later in the pipeline, when using the pass-through mode). To avoid having to re-validate it,
// the authentication context is resolved from the transaction. If it's not available, a new one is created.
var context = transaction.GetProperty<ProcessAuthenticationContext>(typeof(ProcessAuthenticationContext).FullName!);
if (context is null)
{
context = new ProcessAuthenticationContext(transaction);
await _dispatcher.DispatchAsync(context);
// Store the context object in the transaction so it can be later retrieved by handlers
// that want to access the authentication result without triggering a new authentication flow.
transaction.SetProperty(typeof(ProcessAuthenticationContext).FullName!, context);
}
if (context.IsRequestHandled || context.IsRequestSkipped)
{
return null;
}
else if (context.IsRejected)
{
// Note: the missing_token error is special-cased to indicate to Katana
// that no authentication result could be produced due to the lack of token.
// This also helps reducing the logging noise when no token is specified.
if (string.Equals(context.Error, Errors.MissingToken, StringComparison.Ordinal))
{
return null;
}
var properties = new AuthenticationProperties(new Dictionary<string, string?>
{
[OpenIddictValidationOwinConstants.Properties.Error] = context.Error,
[OpenIddictValidationOwinConstants.Properties.ErrorDescription] = context.ErrorDescription,
[OpenIddictValidationOwinConstants.Properties.ErrorUri] = context.ErrorUri
});
return new AuthenticationTicket(null, properties);
}
else
{
Debug.Assert(context.Principal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
Debug.Assert(!string.IsNullOrEmpty(context.Principal.GetTokenType()), SR.GetResourceString(SR.ID4009));
Debug.Assert(!string.IsNullOrEmpty(context.Token), SR.GetResourceString(SR.ID4010));
// Store the token to allow any OWIN/Katana component (e.g a controller)
// to retrieve it (e.g to make an API request to another application).
var properties = new AuthenticationProperties(new Dictionary<string, string?>
{
[context.Principal.GetTokenType()!] = context.Token
})
{
ExpiresUtc = context.Principal.GetExpirationDate(),
IssuedUtc = context.Principal.GetCreationDate()
};
return new AuthenticationTicket((ClaimsIdentity) context.Principal.Identity, properties);
}
}
/// <inheritdoc/>
protected override async Task TeardownCoreAsync()
{
// Note: OWIN authentication handlers cannot reliabily write to the response stream
// from ApplyResponseGrantAsync or ApplyResponseChallengeAsync because these methods
// are susceptible to be invoked from AuthenticationHandler.OnSendingHeaderCallback,
// where calling Write or WriteAsync on the response stream may result in a deadlock
// on hosts using streamed responses. To work around this limitation, this handler
// doesn't implement ApplyResponseGrantAsync but TeardownCoreAsync, which is never called
// by AuthenticationHandler.OnSendingHeaderCallback. In theory, this would prevent
// OpenIddictValidationOwinMiddleware from both applying the response grant and allowing
// the next middleware in the pipeline to alter the response stream but in practice,
// OpenIddictValidationOwinMiddleware is assumed to be the only middleware allowed to write
// to the response stream when a response grant (sign-in/out or challenge) was applied.
// Note: unlike the ASP.NET Core host, the OWIN host MUST check whether the status code
// corresponds to a challenge response, as LookupChallenge() will always return a non-null
// value when active authentication is used, even if no challenge was actually triggered.
var challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
if (challenge is not null && (Response.StatusCode == 401 || Response.StatusCode == 403))
{
var transaction = Context.Get<OpenIddictValidationTransaction>(typeof(OpenIddictValidationTransaction).FullName) ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0166));
transaction.Properties[typeof(AuthenticationProperties).FullName!] = challenge.Properties ?? new AuthenticationProperties();
var context = new ProcessChallengeContext(transaction)
{
Response = new OpenIddictResponse()
};
await _dispatcher.DispatchAsync(context);
if (context.IsRequestHandled || context.IsRequestSkipped)
{
return;
}
else if (context.IsRejected)
{
var notification = new ProcessErrorContext(transaction)
{
Response = new OpenIddictResponse
{
Error = context.Error ?? Errors.InvalidRequest,
ErrorDescription = context.ErrorDescription,
ErrorUri = context.ErrorUri
}
};
await _dispatcher.DispatchAsync(notification);
if (notification.IsRequestHandled || context.IsRequestSkipped)
{
return;
}
throw new InvalidOperationException(SR.GetResourceString(SR.ID0111));
}
}
}
}
}
| 47.726908 | 140 | 0.624453 | [
"Apache-2.0"
] | Eduard-byte/2FA | src/OpenIddict.Validation.Owin/OpenIddictValidationOwinHandler.cs | 11,886 | 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;
using System.Collections.Generic;
using Cake.Core.Diagnostics.Formatting;
namespace Cake.Core.Diagnostics
{
/// <summary>
/// The default Cake build log.
/// </summary>
public sealed class CakeBuildLog : ICakeLog
{
private readonly IConsole _console;
private readonly object _lock;
private readonly IDictionary<LogLevel, ConsolePalette> _palettes;
/// <summary>
/// Gets or sets the verbosity.
/// </summary>
/// <value>The verbosity.</value>
public Verbosity Verbosity { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="CakeBuildLog" /> class.
/// </summary>
/// <param name="console">The console.</param>
/// <param name="verbosity">The verbosity.</param>
public CakeBuildLog(IConsole console, Verbosity verbosity = Verbosity.Normal)
{
_console = console;
_lock = new object();
_palettes = CreatePalette();
Verbosity = verbosity;
}
/// <summary>
/// Writes the text representation of the specified array of objects to the
/// log using the specified verbosity, log level and format information.
/// </summary>
/// <param name="verbosity">The verbosity.</param>
/// <param name="level">The log level.</param>
/// <param name="format">A composite format string.</param>
/// <param name="args">An array of objects to write using format.</param>
public void Write(Verbosity verbosity, LogLevel level, string format, params object[] args)
{
if (verbosity > Verbosity)
{
return;
}
lock (_lock)
{
try
{
var palette = _palettes[level];
var tokens = FormatParser.Parse(format);
foreach (var token in tokens)
{
SetPalette(token, palette);
if (level > LogLevel.Error)
{
_console.Write("{0}", token.Render(args));
}
else
{
_console.WriteError("{0}", token.Render(args));
}
}
}
finally
{
_console.ResetColor();
if (level > LogLevel.Error)
{
_console.WriteLine();
}
else
{
_console.WriteErrorLine();
}
}
}
}
private void SetPalette(FormatToken token, ConsolePalette palette)
{
var property = token as PropertyToken;
if (property != null)
{
_console.BackgroundColor = palette.ArgumentBackground;
_console.ForegroundColor = palette.ArgumentForeground;
}
else
{
_console.BackgroundColor = palette.Background;
_console.ForegroundColor = palette.Foreground;
}
}
private IDictionary<LogLevel, ConsolePalette> CreatePalette()
{
var background = _console.BackgroundColor;
var palette = new Dictionary<LogLevel, ConsolePalette>
{
{ LogLevel.Fatal, new ConsolePalette(ConsoleColor.Magenta, ConsoleColor.White, ConsoleColor.DarkMagenta, ConsoleColor.White) },
{ LogLevel.Error, new ConsolePalette(ConsoleColor.DarkRed, ConsoleColor.White, ConsoleColor.Red, ConsoleColor.White) },
{ LogLevel.Warning, new ConsolePalette(background, ConsoleColor.Yellow, background, ConsoleColor.Yellow) },
{ LogLevel.Information, new ConsolePalette(background, ConsoleColor.White, ConsoleColor.DarkBlue, ConsoleColor.White) },
{ LogLevel.Verbose, new ConsolePalette(background, ConsoleColor.Gray, background, ConsoleColor.White) },
{ LogLevel.Debug, new ConsolePalette(background, ConsoleColor.DarkGray, background, ConsoleColor.Gray) }
};
return palette;
}
}
} | 39.376068 | 143 | 0.536358 | [
"MIT"
] | DixonDs/cake | src/Cake.Core/Diagnostics/CakeBuildLog.cs | 4,609 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using CoreWCF.IdentityModel.Selectors;
using CoreWCF.Security;
namespace CoreWCF
{
public abstract class MessageSecurityVersion
{
public static MessageSecurityVersion WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11
{
get
{
return WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11MessageSecurityVersion.Instance;
}
}
public static MessageSecurityVersion WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10
{
get
{
return WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion.Instance;
}
}
public static MessageSecurityVersion WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10
{
get
{
return WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion.Instance;
}
}
public static MessageSecurityVersion WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12
{
get
{
return WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12MessageSecurityVersion.Instance;
}
}
public static MessageSecurityVersion WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10
{
get
{
return WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion.Instance;
}
}
public static MessageSecurityVersion WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10
{
get
{
return WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion.Instance;
}
}
public static MessageSecurityVersion Default
{
get
{
return WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11MessageSecurityVersion.Instance;
}
}
internal static MessageSecurityVersion WSSXDefault
{
get
{
return WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12MessageSecurityVersion.Instance;
}
}
internal MessageSecurityVersion() { }
public SecurityVersion SecurityVersion
{
get
{
return MessageSecurityTokenVersion.SecurityVersion;
}
}
public TrustVersion TrustVersion
{
get
{
return MessageSecurityTokenVersion.TrustVersion;
}
}
public SecureConversationVersion SecureConversationVersion
{
get
{
return MessageSecurityTokenVersion.SecureConversationVersion;
}
}
public SecurityTokenVersion SecurityTokenVersion
{
get
{
return MessageSecurityTokenVersion;
}
}
public abstract SecurityPolicyVersion SecurityPolicyVersion { get; }
public abstract BasicSecurityProfileVersion BasicSecurityProfileVersion { get; }
internal abstract MessageSecurityTokenVersion MessageSecurityTokenVersion { get; }
internal class WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11MessageSecurityVersion : MessageSecurityVersion
{
public static MessageSecurityVersion Instance { get; } = new WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11MessageSecurityVersion();
public override BasicSecurityProfileVersion BasicSecurityProfileVersion
{
get { return null; }
}
internal override MessageSecurityTokenVersion MessageSecurityTokenVersion
{
get { return MessageSecurityTokenVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005; }
}
public override SecurityPolicyVersion SecurityPolicyVersion
{
get { return SecurityPolicyVersion.WSSecurityPolicy11; }
}
public override string ToString()
{
return "WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11";
}
}
internal class WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion : MessageSecurityVersion
{
public static MessageSecurityVersion Instance { get; } = new WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion();
public override BasicSecurityProfileVersion BasicSecurityProfileVersion
{
get { return BasicSecurityProfileVersion.BasicSecurityProfile10; }
}
internal override MessageSecurityTokenVersion MessageSecurityTokenVersion
{
get { return MessageSecurityTokenVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10; }
}
public override SecurityPolicyVersion SecurityPolicyVersion
{
get { return SecurityPolicyVersion.WSSecurityPolicy11; }
}
public override string ToString()
{
return "WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10";
}
}
internal class WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion : MessageSecurityVersion
{
public static MessageSecurityVersion Instance { get; } = new WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion();
public override SecurityPolicyVersion SecurityPolicyVersion
{
get { return SecurityPolicyVersion.WSSecurityPolicy11; }
}
public override BasicSecurityProfileVersion BasicSecurityProfileVersion
{
get { return BasicSecurityProfileVersion.BasicSecurityProfile10; }
}
internal override MessageSecurityTokenVersion MessageSecurityTokenVersion
{
get { return MessageSecurityTokenVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10; }
}
public override string ToString()
{
return "WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10";
}
}
internal class WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion : MessageSecurityVersion
{
public static MessageSecurityVersion Instance { get; } = new WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion();
public override SecurityPolicyVersion SecurityPolicyVersion
{
get { return SecurityPolicyVersion.WSSecurityPolicy12; }
}
public override BasicSecurityProfileVersion BasicSecurityProfileVersion
{
get { return null; }
}
internal override MessageSecurityTokenVersion MessageSecurityTokenVersion
{
get { return MessageSecurityTokenVersion.WSSecurity10WSTrust13WSSecureConversation13BasicSecurityProfile10; }
}
public override string ToString()
{
return "WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10";
}
}
internal class WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12MessageSecurityVersion : MessageSecurityVersion
{
public static MessageSecurityVersion Instance { get; } = new WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12MessageSecurityVersion();
public override SecurityPolicyVersion SecurityPolicyVersion
{
get { return SecurityPolicyVersion.WSSecurityPolicy12; }
}
public override BasicSecurityProfileVersion BasicSecurityProfileVersion
{
get { return null; }
}
internal override MessageSecurityTokenVersion MessageSecurityTokenVersion
{
get { return MessageSecurityTokenVersion.WSSecurity11WSTrust13WSSecureConversation13; }
}
public override string ToString()
{
return "WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12";
}
}
internal class WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion : MessageSecurityVersion
{
public static MessageSecurityVersion Instance { get; } = new WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion();
public override SecurityPolicyVersion SecurityPolicyVersion
{
get { return SecurityPolicyVersion.WSSecurityPolicy12; }
}
public override BasicSecurityProfileVersion BasicSecurityProfileVersion
{
get { return null; }
}
internal override MessageSecurityTokenVersion MessageSecurityTokenVersion
{
get { return MessageSecurityTokenVersion.WSSecurity11WSTrust13WSSecureConversation13BasicSecurityProfile10; }
}
public override string ToString()
{
return "WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10";
}
}
}
}
| 40.333333 | 201 | 0.68905 | [
"MIT"
] | AlexanderSemenyak/CoreWCF | src/CoreWCF.Primitives/src/CoreWCF/MessageSecurityVersion.cs | 10,648 | C# |
using ICSharpCode.NRefactory.TypeSystem;
using Mono.Cecil;
namespace Bridge.Contract
{
public interface IValidator
{
bool CanIgnoreType(Mono.Cecil.TypeDefinition type);
void CheckIdentifier(string name, ICSharpCode.NRefactory.CSharp.AstNode context);
void CheckConstructors(Mono.Cecil.TypeDefinition type, ITranslator translator);
void CheckFields(Mono.Cecil.TypeDefinition type, ITranslator translator);
void CheckFileName(Mono.Cecil.TypeDefinition type, ITranslator translator);
void CheckMethodArguments(Mono.Cecil.MethodDefinition method);
void CheckMethods(Mono.Cecil.TypeDefinition type, ITranslator translator);
void CheckModule(Mono.Cecil.TypeDefinition type, ITranslator translator);
void CheckModuleDependenies(Mono.Cecil.TypeDefinition type, ITranslator translator);
void CheckProperties(Mono.Cecil.TypeDefinition type, ITranslator translator);
void CheckType(Mono.Cecil.TypeDefinition type, ITranslator translator);
ICSharpCode.NRefactory.TypeSystem.IAttribute GetAttribute(System.Collections.Generic.IEnumerable<ICSharpCode.NRefactory.TypeSystem.IAttribute> attributes, string name);
Mono.Cecil.CustomAttribute GetAttribute(System.Collections.Generic.IEnumerable<Mono.Cecil.CustomAttribute> attributes, string name);
string GetAttributeValue(System.Collections.Generic.IEnumerable<Mono.Cecil.CustomAttribute> attributes, string name);
string GetCustomConstructor(Mono.Cecil.TypeDefinition type);
string GetCustomTypeName(Mono.Cecil.TypeDefinition type, IEmitter emitter, bool excludeNs);
System.Collections.Generic.HashSet<string> GetParentTypes(System.Collections.Generic.IDictionary<string, Mono.Cecil.TypeDefinition> allTypes);
bool HasAttribute(System.Collections.Generic.IEnumerable<ICSharpCode.NRefactory.TypeSystem.IAttribute> attributes, string name);
bool HasAttribute(System.Collections.Generic.IEnumerable<Mono.Cecil.CustomAttribute> attributes, string name);
bool IsDelegateOrLambda(ICSharpCode.NRefactory.Semantics.ResolveResult result);
bool IsExternalType(TypeDefinition type, bool ignoreLiteral = false);
bool IsExternalType(ICSharpCode.NRefactory.TypeSystem.ITypeDefinition typeDefinition, bool ignoreLiteral = false);
bool IsVirtualType(ICSharpCode.NRefactory.TypeSystem.ITypeDefinition typeDefinition);
bool IsExternalInterface(ICSharpCode.NRefactory.TypeSystem.ITypeDefinition typeDefinition, out bool isNative);
IExternalInterface IsExternalInterface(ICSharpCode.NRefactory.TypeSystem.ITypeDefinition typeDefinition);
bool IsImmutableType(ICustomAttributeProvider type);
bool IsExternalType(IEntity enity, bool ignoreLiteral = false);
bool IsBridgeClass(Mono.Cecil.TypeDefinition type);
bool IsObjectLiteral(ICSharpCode.NRefactory.TypeSystem.ITypeDefinition type);
bool IsObjectLiteral(Mono.Cecil.TypeDefinition type);
bool IsAccessorsIndexer(IEntity enity);
int GetObjectInitializationMode(TypeDefinition type);
int GetObjectCreateMode(TypeDefinition type);
}
} | 43.310811 | 176 | 0.780343 | [
"Apache-2.0"
] | Angolar/Bridge | Compiler/Contract/IValidator.cs | 3,205 | C# |
using System;
using System.Collections.Generic;
using Umbraco.Core;
using umbraco.BusinessLogic.Actions;
using umbraco.businesslogic;
using umbraco.cms.businesslogic.macro;
using umbraco.cms.businesslogic.media;
using umbraco.interfaces;
namespace umbraco.cms
{
/// <summary>
/// Extension methods for the PluginTypeResolver
/// </summary>
public static class PluginManagerExtensions
{
/// <summary>
/// Returns all available IActions in application
/// </summary>
/// <param name="resolver"></param>
/// <returns></returns>
internal static IEnumerable<Type> ResolveActions(this PluginManager resolver)
{
return resolver.ResolveTypes<IAction>();
}
/// <summary>
/// Returns all available IDataType in application
/// </summary>
/// <param name="resolver"></param>
/// <returns></returns>
internal static IEnumerable<Type> ResolveMacroEngines(this PluginManager resolver)
{
return resolver.ResolveTypes<IMacroEngine>();
}
/// <summary>
/// Returns all available IMediaFactory in application
/// </summary>
/// <param name="resolver"></param>
/// <returns></returns>
[Obsolete("We don't use IMediaFactory anymore, we need to remove this when we remove the MediaFactory instance that uses this method")]
internal static IEnumerable<Type> ResolveMediaFactories(this PluginManager resolver)
{
return resolver.ResolveTypes<IMediaFactory>();
}
}
} | 27.192308 | 137 | 0.724187 | [
"MIT"
] | filipesousa20/Umbraco-CMS-V7 | src/umbraco.cms/PluginManagerExtensions.cs | 1,414 | C# |
namespace FluentlyHttpClient.Entity
{
public static class Constants
{
public const int ShortTextLength = 30;
public const int NormalTextLength = 70;
public const int LongTextLength = 1500;
public const string SchemaName = "cache";
public const string HttpResponseTable = "HttpResponses";
}
} | 23.615385 | 58 | 0.758958 | [
"MIT"
] | AChehre/FluentlyHttpClient | src/FluentlyHttpClient.Entity/Constants.cs | 309 | C# |
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WalletManager.Data;
using WalletManager.Models;
namespace WalletManager.Services
{
public class WalletAddressService : IWalletAddressService
{
private readonly WalletManagerContext _context;
public WalletAddressService(WalletManagerContext walletManagerContext)
{
_context = walletManagerContext;
}
public async Task Add(WalletAddress walletAddress)
{
await _context.AddAsync(walletAddress);
await _context.SaveChangesAsync();
}
public async Task<WalletAddress> GetWalletAddress(int id) =>
await _context.WalletAddresses.Where(u => u.WalletAddressId == id).FirstOrDefaultAsync();
public async Task<IEnumerable<WalletAddress>> GetUserWallets(int userId) =>
await _context.WalletAddresses.Where(u => u.UserId == userId).Include(u => u.Chain).ToListAsync();
public async Task Delete(WalletAddress walletAddress)
{
_context.Remove(walletAddress);
await _context.SaveChangesAsync();
}
}
}
| 31.358974 | 110 | 0.688471 | [
"MIT"
] | Hossein-79/WalletManager | Services/WalletAddressService.cs | 1,225 | C# |
using System;
using Xunit;
using Xunit.Extensions;
namespace Humanizer.Tests.Localisation.uzLatn
{
public class TimeSpanHumanizeTests : AmbientCulture
{
public TimeSpanHumanizeTests() : base("uz-Latn-UZ") { }
[Theory]
[InlineData(14, "2 hafta")]
[InlineData(7, "1 hafta")]
public void Weeks(int days, string expected)
{
var actual = TimeSpan.FromDays(days).Humanize();
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(6, "6 kun")]
[InlineData(2, "2 kun")]
public void Days(int days, string expected)
{
var actual = TimeSpan.FromDays(days).Humanize();
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(2, "2 soat")]
[InlineData(1, "1 soat")]
public void Hours(int hours, string expected)
{
var actual = TimeSpan.FromHours(hours).Humanize();
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(2, "2 minut")]
[InlineData(1, "1 minut")]
public void Minutes(int minutes, string expected)
{
var actual = TimeSpan.FromMinutes(minutes).Humanize();
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(2, "2 sekund")]
[InlineData(1, "1 sekund")]
public void Seconds(int seconds, string expected)
{
var actual = TimeSpan.FromSeconds(seconds).Humanize();
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(2, "2 millisekund")]
[InlineData(1, "1 millisekund")]
public void Milliseconds(int ms, string expected)
{
var actual = TimeSpan.FromMilliseconds(ms).Humanize();
Assert.Equal(expected, actual);
}
[Fact]
public void NoTime()
{
var noTime = TimeSpan.Zero;
var actual = noTime.Humanize();
Assert.Equal("vaqt yo`q", actual);
}
}
}
| 28.972973 | 67 | 0.525653 | [
"MIT"
] | ErikSchierboom/Humanizer | src/Humanizer.Tests/Localisation/uz-Latn-UZ/TimeSpanHumanizeTests.cs | 2,073 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UserController : MonoBehaviour {
//Transform object used to change user's position/view
public Transform viewT;
//Force modifiers for force and torque
public float forceMod = 5, torqueMod = 0.5f;
//Vector3 objects representing values for torque & force
public Vector3 forceVal, torqueVal;
// initialize fuel rate and battery life
public float fuelrate = 1000000;
public float batterylife = 10000000;
public float initialFuelrate = 1000000/100;
public float initialBatterylife = 10000000/100;
public int decreasedrate = 100;
public float time = 0;
public Text fuelText;
public Text batteryText;
public Text speedText;
private int infoCycle = 0;
private int timer = 0;
Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
SetFuelText();
SetBatteryText();
SetSpeedText();
}
private void OnCollisionEnter(Collision collision)
{
rb.angularVelocity = Vector3.zero;
}
private void OnCollisionStay(Collision collision)
{
rb.angularVelocity = Vector3.zero;
}
private void FixedUpdate()
{
//Checks to see if it should quit right away
if (Input.GetKey(KeyCode.Escape)) {
Application.Quit();
}
//Cycles through information
if (Input.GetKey("i") && timer<0) {
if(infoCycle < 2) {
infoCycle++;
} else {
infoCycle = 0;
}
timer = 30;
}
timer--;
SetFuelText();
SetBatteryText();
SetSpeedText();
// disable the controls if either fuelrate or batterylife is empty
if ( fuelrate <= 0 || batterylife <= 0 ) {
return;
}
batterylife -= decreasedrate * Time.deltaTime;
//force & torque initializations
forceVal = new Vector3(0, 0, 0);
torqueVal = new Vector3(0, 0, 0);
//force calculations:
//forward propulsion
if (Input.GetKey("w"))
{
updateForce(viewT.forward);
}
//left propulsion
if (Input.GetKey("a"))
{
updateForce(-viewT.right);
}
//backwards propulsion
if (Input.GetKey("s"))
{
updateForce(-viewT.forward);
}
//right propulsion
if (Input.GetKey("d"))
{
updateForce(viewT.right);
}
//upwards propulsion
if (Input.GetKey("space"))
{
updateForce(viewT.up);
}
//downwards propulsion
if (Input.GetKey("c"))
{
updateForce(-viewT.up);
}
//torque/rotation calcs
//roll left
if (Input.GetKey("q"))
{
updateTorque(viewT.forward);
}
//roll right
if (Input.GetKey("e"))
{
updateTorque(-viewT.forward);
}
//yaw right
if (Input.GetKey("right"))
{
updateTorque(viewT.up);
}
//yaw left
if (Input.GetKey("left"))
{
updateTorque(-viewT.up);
}
//pitch forwards (down)
if (Input.GetKey("up"))
{
updateTorque(viewT.right);
}
//pitch backwards (up)
if (Input.GetKey("down"))
{
updateTorque(-viewT.right);
}
//stabilization
if (Input.GetKey("z"))
{
fuelrate -= decreasedrate * Time.deltaTime;
forceVal = -rb.velocity * forceMod * 0.3f;
//torqueVal = -rb.angularVelocity.normalized * torqueMod * 1f;
if (rb.angularVelocity.magnitude > 2f * Time.deltaTime)
{
rb.AddTorque(-(rb.angularVelocity/4) * torqueMod, ForceMode.Force);
}
else
{
rb.angularVelocity = Vector3.zero;
}
Debug.Log("Stabilizing User");
}
//apply force
rb.AddForce(forceVal);
//apply torque
rb.AddTorque(torqueVal);
}
private void updateForce(Vector3 forceChange) {
forceVal += forceChange * forceMod;
fuelrate -= decreasedrate * Time.deltaTime;
}
private void updateTorque(Vector3 torqueChange) {
torqueVal += torqueChange * torqueMod;
fuelrate -= decreasedrate * Time.deltaTime;
}
private void SetFuelText() {
if(infoCycle != 2) {
fuelText.text = "Fuel: " + (fuelrate/initialFuelrate).ToString("N2") + "%";
} else {
fuelText.text = "";
}
}
private void SetBatteryText() {
if(infoCycle != 2) {
batteryText.text = "Battery: " + (batterylife/initialBatterylife).ToString("N2") + "%";
} else {
batteryText.text = "";
}
}
private void SetSpeedText() {
if(infoCycle != 1) {
speedText.text = "Speed: " + rb.velocity.magnitude.ToString("N2") + " m/s";
} else {
speedText.text = "";
}
}
} | 25.631068 | 99 | 0.525189 | [
"MIT"
] | alexbary2/cs409_prototype | CDCM/Assets/Project/Scripts/UserController.cs | 5,280 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ClassBoxData
{
public class Box
{
private const string ERROR_MESSAGE = "cannot be zero or negative.";
public Box(double length, double width, double height)
{
this.Length = length;
this.Width = width;
this.Height = height;
}
private double length;
private double width;
private double height;
public double Length
{
get { return this.length; }
private set
{
if (value <= 0)
{
throw new Exception("Length " + ERROR_MESSAGE);
}
this.length = value;
}
}
public double Width
{
get { return this.width; }
private set
{
if (value <= 0)
{
throw new Exception("Width " + ERROR_MESSAGE);
}
width = value;
}
}
public double Height
{
get { return this.height; }
private set
{
if (value <= 0)
{
throw new Exception("Height " + ERROR_MESSAGE);
}
this.height = value;
}
}
public double GetSurfaceArea()
{
var surfaceArea = 2 * (this.Length * this.Height) + 2 * (this.Length * this.Width) + 2 * (this.Height * this.Width);
return surfaceArea;
}
public double GetLateralArea()
{
var lateralArea = 2 * (this.Length * this.height) + 2 * (this.Height * this.width);
return lateralArea;
}
public double GetVolume()
{
var volume = this.Length * this.Height * this.Width;
return volume;
}
}
}
| 23.761905 | 128 | 0.451403 | [
"MIT"
] | BlagoKolev/SoftUni | C# OOP/Encapsulation/ClassBoxData/Box.cs | 1,998 | C# |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* 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 ASC.Bookmarking;
using ASC.Bookmarking.Business.Permissions;
using ASC.Bookmarking.Common;
using ASC.Bookmarking.Pojo;
using ASC.Core;
using ASC.Core.Users;
using ASC.Web.Community.Modules.Bookmarking.UserControls.Resources;
using ASC.Web.Core.Helpers;
using ASC.Web.Core.Utility.Skins;
using ASC.Web.UserControls.Bookmarking.Common.Util;
namespace ASC.Web.UserControls.Bookmarking.Common.Presentation
{
public abstract class BookmarkInfoBase : System.Web.UI.UserControl
{
#region Fields
protected void Page_Load(object sender, EventArgs e)
{
InitUserControl();
}
public abstract void InitUserControl();
protected BookmarkingServiceHelper ServiceHelper = BookmarkingServiceHelper.GetCurrentInstanse();
#endregion
#region Bookmark Fields
public Bookmark Bookmark { get; set; }
public UserBookmark UserBookmark { get; set; }
public string Description
{
get { return Bookmark.Description.ReplaceSingleQuote(); }
}
public string URL
{
get { return Bookmark.URL; }
}
public string Name
{
get { return Bookmark.Name.ReplaceSingleQuote(); }
}
public long Raiting
{
get { return ServiceHelper.GetUserBookmarksCount(Bookmark); }
}
public string TagsString
{
get { return BookmarkingServiceHelper.ConvertBookmarkToTagsString(Bookmark).ReplaceSingleQuote(); }
}
public DateTime Date
{
get { return Bookmark.Date; }
}
public long GetBookmarkID()
{
return Bookmark == null ? 0 : Bookmark.ID;
}
public string UserBookmarkDescription
{
get
{
return UserBookmark == null
? Description
: UserBookmark.Description.ReplaceSingleQuote();
}
}
public bool HasDescription()
{
return !string.IsNullOrEmpty(UserBookmarkDescription);
}
public string UserBookmarkName
{
get
{
return UserBookmark == null
? Name
: UserBookmark.Name.ReplaceSingleQuote();
}
}
public string UserTagsString { get; set; }
public DateTime UserDate
{
get
{
return UserBookmark == null
? Date
: UserBookmark.DateAdded;
}
}
public bool IsTagsIncluded()
{
if (Bookmark != null)
{
var tags = Bookmark.Tags;
if (tags != null && tags.Count > 0)
{
return true;
}
}
return false;
}
public bool IsCurrentUserBookmark()
{
return ServiceHelper.IsCurrentUserBookmark(Bookmark);
}
public string GetThumbnailUrl()
{
return BookmarkingServiceHelper.GetThumbnailUrl(URL);
}
public string GetMediumThumbnailUrl()
{
return BookmarkingServiceHelper.GetMediumThumbnailUrl(URL);
}
public string GetTagsWebPath()
{
return WebImageSupplier.GetAbsoluteWebPath(BookmarkingRequestConstants.TagsImageName, BookmarkingSettings.ModuleId);
}
public string GetSearchByTagUrl(object bookmarkTagName)
{
var name = bookmarkTagName as string;
return ServiceHelper.GetSearchByTagUrl(name);
}
public string GetBookmarkInfoUrlAddedByTab()
{
var url = string.Format("{0}&{1}={2}",
BookmarkingServiceHelper.GenerateBookmarkInfoUrl(URL),
BookmarkingRequestConstants.SelectedTab,
BookmarkingRequestConstants.SelectedTabBookmarkAddedBy
);
return url;
}
public string GetBookmarkInfoUrl()
{
return BookmarkingServiceHelper.GenerateBookmarkInfoUrl(URL);
}
public string GetBookmarkRaiting()
{
return new BookmarkRaitingUserControl().GetBookmarkRaiting(Bookmark, GetUniqueId().ToString(), GetSingleBookmarkID());
}
public string GetUserBookmarkRaiting()
{
return new BookmarkRaitingUserControl().GetBookmarkRaiting(Bookmark, UserBookmark, GetUniqueId().ToString(), GetSingleBookmarkID());
}
public string GetSingleBookmarkID()
{
return GetUniqueId() + "SingleBookmark";
}
#endregion
#region User Info
public bool ShowAddedByUserInfo
{
get
{
var displayMode = BookmarkingBusinessFactory.GetDisplayMode();
switch (displayMode)
{
case BookmarkDisplayMode.AllBookmarks:
return true;
case BookmarkDisplayMode.SelectedBookmark:
return true;
}
return false;
}
}
public string RenderProfileLink()
{
return RenderProfileLink(GetBookmarkCreator());
}
public string RenderProfileLink(UserInfo userInfo)
{
try
{
return userInfo.RenderCustomProfileLink("describe-text", "link gray");
}
catch
{
return string.Empty;
}
}
public string RenderProfileLink(Object userID)
{
var user = GetUserInfoByUserID(userID);
return RenderProfileLink(user);
}
public string GetBookmarkCreatorImageUrl()
{
return GetImageUrl(GetBookmarkCreator());
}
private static string GetImageUrl(UserInfo userInfo)
{
try
{
return userInfo.GetMediumPhotoURL();
}
catch
{
return string.Empty;
}
}
protected UserInfo GetBookmarkCreator()
{
return Bookmark == null
? null
: CoreContext.UserManager.GetUsers(Bookmark.UserCreatorID);
}
public string GetUserImageUrl(object userID)
{
var user = GetUserInfoByUserID(userID);
return GetImageUrl(user);
}
public string GetUserImage(object userID)
{
var user = GetUserInfoByUserID(userID);
return BookmarkingServiceHelper.GetHTMLUserAvatar(user.ID);
}
private static UserInfo GetUserInfoByUserID(object userID)
{
try
{
var id = (Guid)userID;
return CoreContext.UserManager.GetUsers(id);
}
catch
{
return null;
}
}
#endregion
#region Uuid
private Guid _uniqueId;
public Guid UniqueId
{
get
{
if (Guid.Empty.Equals(_uniqueId))
{
_uniqueId = Guid.NewGuid();
}
return _uniqueId;
}
set { _uniqueId = value; }
}
/// <summary>
/// Return unique id, which will be upted for every instance.
/// Calling this method for the same instance will return the same result.
/// </summary>
/// <returns></returns>
public Guid GetUniqueId()
{
return UniqueId;
}
#endregion
#region Added By Info
public string GetDateAddedAsString(object date)
{
try
{
var dateAdded = (DateTime)date;
return BookmarkingConverter.GetDateAsString(dateAdded);
}
catch
{
return string.Empty;
}
}
public string GetDateAddedAsString()
{
try
{
return Date.ToShortTimeString() + " " + Date.ToShortDateString();
}
catch
{
return string.Empty;
}
}
public long CommentsCount
{
get
{
return Bookmark != null
? ServiceHelper.GetCommentsCount(Bookmark)
: 0;
}
}
public string CommentString
{
get
{
var commentsCount = CommentsCount;
if (commentsCount == 0)
{
return string.Empty;
}
var comments = GrammaticalHelper.ChooseNumeralCase((int)commentsCount,
BookmarkingUCResource.CommentsNominative,
BookmarkingUCResource.CommentsGenitiveSingular,
BookmarkingUCResource.CommentsGenitivePlural);
return String.Format("{0} {1}", commentsCount, comments);
}
}
public string GetUserPageLink(object userID)
{
return BookmarkingServiceHelper.GetUserPageLink(new Guid(userID.ToString()));
}
#endregion
#region Display Mode
public bool IsAllBookmarksMode()
{
var displayMode = BookmarkingBusinessFactory.GetDisplayMode();
return BookmarkDisplayMode.AllBookmarks == displayMode;
}
public bool IsBookmarkInfoMode
{
get
{
var displayMode = BookmarkingBusinessFactory.GetDisplayMode();
return BookmarkDisplayMode.SelectedBookmark == displayMode;
}
}
public string FavouriteBookmarksMode
{
get
{
var displayMode = BookmarkingBusinessFactory.GetDisplayMode();
return (BookmarkDisplayMode.Favourites == displayMode).ToString().ToLower();
}
}
#endregion
#region Permissions Check
public static bool PermissionCheckAddToFavourite()
{
return BookmarkingPermissionsCheck.PermissionCheckAddToFavourite();
}
public bool PermissionCheckRemoveFromFavourite()
{
return UserBookmark != null && BookmarkingPermissionsCheck.PermissionCheckRemoveFromFavourite(UserBookmark);
}
#endregion
public string GetUniqueIDFromSingleBookmark(string SingleBookmarkDivID)
{
if (!string.IsNullOrEmpty(SingleBookmarkDivID))
{
var a = SingleBookmarkDivID.Split(new string[] { "SingleBookmark" }, StringSplitOptions.None);
if (a.Length == 2)
{
return a[0];
}
}
return Guid.NewGuid().ToString();
}
public string GetRandomGuid()
{
return Guid.NewGuid().ToString();
}
public string GetUserBookmarkDescriptionIfChanged(object o)
{
try
{
if (o is UserBookmark)
{
var ub = o as UserBookmark;
return Bookmark != null
? BookmarkingServiceHelper.GetUserBookmarkDescriptionIfChanged(Bookmark, ub)
: BookmarkingServiceHelper.GetUserBookmarkDescriptionIfChanged(ub);
}
}
catch
{
}
return string.Empty;
}
}
} | 28.655844 | 145 | 0.504343 | [
"Apache-2.0"
] | jeanluctritsch/CommunityServer | web/studio/ASC.Web.Studio/Products/Community/Modules/Bookmarking/UserControls/Common/Presentation/BookmarkInfoBase.cs | 13,239 | 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 gamelift-2015-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.GameLift.Model
{
/// <summary>
/// Represents the returned data in response to a request action.
/// </summary>
public partial class UpdateBuildResponse : AmazonWebServiceResponse
{
private Build _build;
/// <summary>
/// Gets and sets the property Build.
/// <para>
/// Object that contains the updated build record.
/// </para>
/// </summary>
public Build Build
{
get { return this._build; }
set { this._build = value; }
}
// Check to see if Build property is set
internal bool IsSetBuild()
{
return this._build != null;
}
}
} | 28.482143 | 106 | 0.64953 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/GameLift/Generated/Model/UpdateBuildResponse.cs | 1,595 | C# |
using System.Diagnostics;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Castle.Windsor;
using LightBlue;
using LightBlue.Windsor;
using Microsoft.WindowsAzure.ServiceRuntime;
namespace TestWindsorRole
{
public class WorkerRole : RoleEntryPoint
{
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private readonly ManualResetEvent _runCompleteEvent = new ManualResetEvent(false);
private IWindsorContainer _container;
public override void Run()
{
Trace.TraceInformation("TestWindorRole is running");
try
{
RunAsync(_cancellationTokenSource.Token).Wait();
}
finally
{
_runCompleteEvent.Set();
}
}
public override bool OnStart()
{
ServicePointManager.DefaultConnectionLimit = 12;
var result = base.OnStart();
_container = new WindsorContainer();
_container.InstallLightBlue();
Trace.TraceInformation("TestWindorRole has been started");
return result;
}
public override void OnStop()
{
Trace.TraceInformation("TestWindorRole is stopping");
_cancellationTokenSource.Cancel();
_runCompleteEvent.WaitOne();
base.OnStop();
Trace.TraceInformation("TestWindorRole has stopped");
}
private async Task RunAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
Trace.TraceInformation(
"Working: "
+ _container.Resolve<IAzureSettings>()["WindsorSetting"]);
await Task.Delay(1000, cancellationToken);
}
}
}
} | 26.328767 | 106 | 0.601457 | [
"Apache-2.0"
] | ColinScott/LightBlue | TestWindsorRole/WorkerRole.cs | 1,922 | C# |
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace CrossSiteScripting.Pages
{
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
[IgnoreAntiforgeryToken]
public class ErrorModel : PageModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
private readonly ILogger<ErrorModel> _logger;
public ErrorModel(ILogger<ErrorModel> logger)
{
_logger = logger;
}
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
| 25.69697 | 88 | 0.6875 | [
"MIT"
] | AnzhelikaKravchuk/asp-dot-net-core-in-action-2e | Chapter18/B_CrossSiteScripting/CrossSiteScripting/Pages/Error.cshtml.cs | 848 | C# |
using System.Web.Mvc;
using System.Web.Routing;
namespace PlatformProject.Web
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
} | 26.368421 | 99 | 0.55489 | [
"MIT"
] | ectechno/mulgala | PlatformProject.Web/App_Start/RouteConfig.cs | 503 | C# |
using MedicationMngApp.Models;
using MedicationMngApp.Views;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Xamarin.Forms;
using XF.Material.Forms.UI.Dialogs;
namespace MedicationMngApp.ViewModels
{
public class RegisterViewModel : BaseViewModel
{
private string firstname = string.Empty;
private string lastname = string.Empty;
private DateTime? birthday = null;
private string email = string.Empty;
private string username = string.Empty;
private string password = string.Empty;
private string confirmpassword = string.Empty;
public Command RegisterCommand { get; }
public RegisterViewModel()
{
RegisterCommand = new Command(OnRegisterClicked);
}
private bool Validate()
{
ResetErrors();
return !string.IsNullOrWhiteSpace(firstname)
&& !string.IsNullOrWhiteSpace(lastname)
&& birthday != null
&& !string.IsNullOrWhiteSpace(email)
&& new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$").Match(email).Success
&& !string.IsNullOrWhiteSpace(username)
&& !string.IsNullOrWhiteSpace(password)
&& !string.IsNullOrWhiteSpace(confirmpassword)
&& password == confirmpassword;
}
private void ValidateMessage()
{
if (string.IsNullOrWhiteSpace(firstname))
{
IsErrorFirstName = true;
ErrorFirstName = "Please enter a valid first name.";
}
if (string.IsNullOrWhiteSpace(lastname))
{
IsErrorLastName = true;
ErrorLastName = "Please enter a valid last name.";
}
if (birthday == null)
{
IsErrorBirthday = true;
ErrorBirthday = "Please select a valid date of birth.";
}
if (string.IsNullOrWhiteSpace(email))
{
IsErrorEmail = true;
ErrorEmail = "Please enter a valid email.";
}
if (!(new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$").Match(email).Success))
{
IsErrorEmail = true;
ErrorEmail = "Please enter a valid email format.";
}
if (string.IsNullOrWhiteSpace(username))
{
IsErrorUsername = true;
ErrorUsername = "Please enter a valid username.";
}
if (string.IsNullOrWhiteSpace(password))
{
IsErrorPassword = true;
ErrorPassword = "Please enter a valid password.";
}
if (string.IsNullOrWhiteSpace(confirmpassword))
{
IsErrorConfirmPassword = true;
ErrorConfirmPassword = "Please enter a valid confirm password.";
}
if (!string.IsNullOrWhiteSpace(password) && !string.IsNullOrWhiteSpace(confirmpassword) && password != confirmpassword)
{
IsErrorPassword = true;
IsErrorConfirmPassword = true;
ErrorConfirmPassword = "Passwords do not match.";
ErrorPassword = "Passwords do not match.";
}
}
#region Bindings
//Fields
public string FirstName
{
get => firstname;
set => SetProperty(ref firstname, value);
}
public string LastName
{
get => lastname;
set => SetProperty(ref lastname, value);
}
public DateTime? Birthday
{
get => birthday;
set => SetProperty(ref birthday, value.Value);
}
public string Email
{
get => email;
set => SetProperty(ref email, value);
}
public string Username
{
get => username;
set => SetProperty(ref username, value);
}
public string Password
{
get => password;
set => SetProperty(ref password, value);
}
public string ConfirmPassword
{
get => confirmpassword;
set => SetProperty(ref confirmpassword, value);
}
//Errors
private bool isErrorFirstName = false;
private bool isErrorLastName = false;
private bool isErrorBirthday = false;
private bool isErrorEmail = false;
private bool isErrorUsername = false;
private bool isErrorPassword = false;
private bool isErrorConfirmPassword = false;
private string errorFirstName = string.Empty;
private string errorLastName = string.Empty;
private string errorBirthday = string.Empty;
private string errorEmail = string.Empty;
private string errorUsername = string.Empty;
private string errorPassword = string.Empty;
private string errorConfirmPassword = string.Empty;
void ResetErrors()
{
IsErrorFirstName = false;
IsErrorLastName = false;
IsErrorBirthday = false;
IsErrorEmail = false;
IsErrorUsername = false;
IsErrorPassword = false;
IsErrorConfirmPassword = false;
}
public bool IsErrorFirstName
{
get => isErrorFirstName;
set => SetProperty(ref isErrorFirstName, value);
}
public bool IsErrorLastName
{
get => isErrorLastName;
set => SetProperty(ref isErrorLastName, value);
}
public bool IsErrorBirthday
{
get => isErrorBirthday;
set => SetProperty(ref isErrorBirthday, value);
}
public bool IsErrorEmail
{
get => isErrorEmail;
set => SetProperty(ref isErrorEmail, value);
}
public bool IsErrorUsername
{
get => isErrorUsername;
set => SetProperty(ref isErrorUsername, value);
}
public bool IsErrorPassword
{
get => isErrorPassword;
set => SetProperty(ref isErrorPassword, value);
}
public bool IsErrorConfirmPassword
{
get => isErrorConfirmPassword;
set => SetProperty(ref isErrorConfirmPassword, value);
}
public string ErrorFirstName
{
get => errorFirstName;
set
{
if (string.IsNullOrWhiteSpace(value))
IsErrorFirstName = false;
else
IsErrorFirstName = true;
SetProperty(ref errorFirstName, value);
}
}
public string ErrorLastName
{
get => errorLastName;
set
{
if (string.IsNullOrWhiteSpace(value))
IsErrorLastName = false;
else
IsErrorLastName = true;
SetProperty(ref errorLastName, value);
}
}
public string ErrorBirthday
{
get => errorBirthday;
set
{
if (string.IsNullOrWhiteSpace(value))
IsErrorBirthday = false;
else
IsErrorBirthday = true;
SetProperty(ref errorBirthday, value);
}
}
public string ErrorEmail
{
get => errorEmail;
set
{
if (string.IsNullOrWhiteSpace(value))
IsErrorEmail = false;
else
IsErrorEmail = true;
SetProperty(ref errorEmail, value);
}
}
public string ErrorUsername
{
get => errorUsername;
set
{
if (string.IsNullOrWhiteSpace(value))
IsErrorUsername = false;
else
IsErrorUsername = true;
SetProperty(ref errorUsername, value);
}
}
public string ErrorPassword
{
get => errorPassword;
set
{
if (string.IsNullOrWhiteSpace(value))
IsErrorPassword = false;
else
IsErrorPassword = true;
SetProperty(ref errorPassword, value);
}
}
public string ErrorConfirmPassword
{
get => errorConfirmPassword;
set
{
if (string.IsNullOrWhiteSpace(value))
IsErrorConfirmPassword = false;
else
IsErrorConfirmPassword = true;
SetProperty(ref errorConfirmPassword, value);
}
}
#endregion //Bindings
private async void OnRegisterClicked()
{
if (CanSubmit)
{
IsBusy = true;
try
{
if (Validate())
{
if (NetworkStatus.IsInternet())
{
using (await MaterialDialog.Instance.LoadingDialogAsync(message: "Signing you up...", configuration: Common.LoadingDialogConfig))
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Common.SERVICE_CREDENTIALS));
AddAccountRequestObject accountObj = new AddAccountRequestObject
{
account = new Account
{
FirstName = firstname,
LastName = lastname,
Birthday = birthday.Value,
Email = email,
Username = username,
Password = confirmpassword
}
};
string serializedObject = JsonConvert.SerializeObject(accountObj, Formatting.Indented);
using (HttpContent content = new StringContent(serializedObject, Encoding.UTF8, Common.HEADER_CONTENT_TYPE))
{
using (HttpResponseMessage response = await client.PostAsync(Common.POST_ADD_ACCOUNT, content))
{
if (response.IsSuccessStatusCode)
{
string jData = await response.Content.ReadAsStringAsync();
if (!string.IsNullOrWhiteSpace(jData))
{
AddAccountResult result = JsonConvert.DeserializeObject<AddAccountResult>(jData);
switch (result.result)
{
case -69://sql return value -69
{
await Common.ShowAlertAsync("Error", "Username already exists!", "OK", true);
IsErrorUsername = true;
ErrorUsername = "Username already exists!";
break;
}
case -70://sql return value -70
{
await Common.ShowAlertAsync("Error", "Email already exists!", "OK", true);
IsErrorEmail = true;
ErrorEmail = "Email already exists!";
break;
}
case 1://sql return value 1
{
await Common.ShowAlertAsync("Registration Success", "You have successfully registered.", "OK");
await Common.NavigateBack();
break;
}
default:
{
await Common.ShowMessageAsyncUnknownError();
break;
}
}
}
}
}
}
}
}
}
else
{
await Common.ShowMessageAsyncNetworkError();
}
}
else
{
ValidateMessage();
}
}
catch (Exception error)
{
await Common.ShowMessageAsyncApplicationError(error.Message);
}
finally
{
IsBusy = false;
}
}
}
}
}
| 38.028205 | 196 | 0.426741 | [
"MIT"
] | johphil/MedicationMngApp | MedicationMngApp/MedicationMngApp/ViewModels/RegisterViewModel.cs | 14,833 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LionFire.Framework.Pack
{
public class Class1
{
}
}
| 14.769231 | 33 | 0.739583 | [
"MIT"
] | LionFire/Core | src/LionFire.Framework.Pack/Class1.cs | 194 | C# |
using Prism.Commands;
using Prism.Forms.Tests.Mocks;
using Prism.Services;
using System;
using System.Threading.Tasks;
using Xunit;
namespace Prism.Forms.Tests.Services
{
public class PageDialogServiceFixture
{
[Fact]
public async Task DisplayActionSheetNoButtons_ShouldThrowException()
{
var service = new PageDialogServiceMock("cancel");
var argumentException = await Assert.ThrowsAsync<ArgumentException>(() => service.DisplayActionSheet(null, null));
Assert.Equal(typeof(ArgumentException), argumentException.GetType());
}
[Fact]
public async Task DisplayActionSheet_CancelButtonPressed()
{
var service = new PageDialogServiceMock("cancel");
var cancelButtonPressed = false;
var cancelCommand = new DelegateCommand(() => cancelButtonPressed = true);
var button = ActionSheetButton.CreateCancelButton("cancel", cancelCommand);
await service.DisplayActionSheet(null, button);
Assert.True(cancelButtonPressed);
}
[Fact]
public async Task DisplayActionSheet_DestroyButtonPressed()
{
var service = new PageDialogServiceMock("destroy");
var destroyButtonPressed = false;
var cancelCommand = new DelegateCommand(() => destroyButtonPressed = false);
var button = ActionSheetButton.CreateCancelButton("cancel", cancelCommand);
var destroyCommand = new DelegateCommand(() => destroyButtonPressed = true);
var destroyButton = ActionSheetButton.CreateDestroyButton("destroy", destroyCommand);
await service.DisplayActionSheet(null, button, destroyButton);
Assert.True(destroyButtonPressed);
}
[Fact]
public async Task DisplayActionSheet_NoButtonPressed()
{
var service = new PageDialogServiceMock(null);
var buttonPressed = false;
var cancelCommand = new DelegateCommand(() => buttonPressed = true);
var button = ActionSheetButton.CreateCancelButton("cancel", cancelCommand);
var destroyCommand = new DelegateCommand(() => buttonPressed = true);
var destroyButton = ActionSheetButton.CreateDestroyButton("destroy", destroyCommand);
await service.DisplayActionSheet(null, button, destroyButton);
Assert.False(buttonPressed);
}
[Fact]
public async Task DisplayActionSheet_OtherButtonPressed()
{
var service = new PageDialogServiceMock("other");
var buttonPressed = false;
var command = new DelegateCommand(() => buttonPressed = true);
var button = ActionSheetButton.CreateButton("other", command);
await service.DisplayActionSheet(null, button);
Assert.True(buttonPressed);
}
[Fact]
public async Task DisplayActionSheet_NullButtonAndOtherButtonPressed()
{
var service = new PageDialogServiceMock("other");
var buttonPressed = false;
var command = new DelegateCommand(() => buttonPressed = true);
var button = ActionSheetButton.CreateButton("other", command);
await service.DisplayActionSheet(null, button, null);
Assert.True(buttonPressed);
}
}
}
| 42.4 | 126 | 0.64888 | [
"Apache-2.0"
] | WertherHu/Prism | Source/Xamarin/Prism.Forms.Tests/Services/PageDialogServiceFixture.cs | 3,394 | C# |
namespace Boards.API.Resources
{
public class UserResource
{
public int Id { get; set; }
public string Email { get; set; }
}
} | 19.25 | 41 | 0.584416 | [
"MIT"
] | m0wo/boards-api | Boards.API/Resources/UserResource.cs | 154 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Pixie.Core.Services
{
public interface IPXClientService
{
string Id { get; }
}
}
| 15 | 37 | 0.683333 | [
"MIT"
] | amazedevil/Pixie | Pixie/Core/Services/IPXClientService.cs | 182 | C# |
// C# 9.0 までは
// Func<string, int> f = m;
// みたいに書かないとダメだった(ターゲット型推論)。
var f = m;
Delegate d = m;
MulticastDelegate md = m;
// Delegate は ICloneable を実装しているので一応これも OK。
// (ただし、ICloneable インターフェイス自体今どき使わない。)
ICloneable c = m;
// これも一応できるけど、そんなに使い道がないというかたまにミスの原因になるので警告。
// object obj = m(); の () 付け忘れをたまにやるので…
object obj = m;
int m(string s) => s.Length;
// System.Action とかになるやつ:
var a1 = (int a) => { };
var a4 = (int a, int b, int c, int d) => { };
var a16 = (int a, int b, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n, int o, int p) => { };
var f1 = (int a) => a.ToString();
var f4 = (int a, int b, int c, int d) => $"{a}.{b}.{c}.{d}";
// コンパイラー生成の独自デリゲートになるやつ:
// ref 系
var i1 = (in int a) => { };
var r1 = (ref int a) => { };
var o1 = (out int a) => a = 0;
// 引数の数オーバー
var a17 = (int a, int b, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n, int o, int p, int q) => { };
#if ERROR
// Func<int, bool> になる。
var a = (int x) => true;
// 左辺に型を明示してあると Action/Func 以外の型になる。
Predicate<int> p = (int x) => true;
// p に直接 (int x) => true を代入するのは行けるのに、
// var 変数宣言を挟むとダメ。
// (Func<int, bool> から Predicate<int> への変換が許されていない。)
p = a;
#endif
| 27.044444 | 137 | 0.58751 | [
"Apache-2.0"
] | ufcpp/UfcppSample | Demo/2021/Csharp10/Lambda/NaturalType/Program.cs | 1,663 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.