content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
/* * Copyright 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 dms-2016-01-01.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.DatabaseMigrationService { /// <summary> /// Configuration for accessing Amazon DatabaseMigrationService service /// </summary> public partial class AmazonDatabaseMigrationServiceConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.3.12.13"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonDatabaseMigrationServiceConfig() { this.AuthenticationServiceName = "dms"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "dms"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2016-01-01"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
26.725
101
0.596352
[ "Apache-2.0" ]
akdor1154/aws-sdk-net
sdk/src/Services/DatabaseMigrationService/Generated/AmazonDatabaseMigrationServiceConfig.cs
2,138
C#

1.75
2
0
[ "MIT" ]
manekovskiy/Web-Forms-Routing-Through-Attributes
PhysicalFilePathUpdater.cs
9
C#
using System; using System.Threading.Tasks; using Orleans.Runtime; using Orleans.Serialization; using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; namespace Orleans.Streams { internal class PersistentStreamProducer<T> : IInternalAsyncBatchObserver<T> { private readonly StreamImpl<T> stream; private readonly IQueueAdapter queueAdapter; private readonly SerializationManager serializationManager; internal bool IsRewindable { get; private set; } internal PersistentStreamProducer(StreamImpl<T> stream, IStreamProviderRuntime providerUtilities, IQueueAdapter queueAdapter, bool isRewindable, SerializationManager serializationManager) { this.stream = stream; this.queueAdapter = queueAdapter; this.serializationManager = serializationManager; IsRewindable = isRewindable; var logger = providerUtilities.ServiceProvider.GetRequiredService<ILoggerFactory>().CreateLogger(this.GetType().Name); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Created PersistentStreamProducer for stream {0}, of type {1}, and with Adapter: {2}.", stream.ToString(), typeof (T), this.queueAdapter.Name); } public Task OnNextAsync(T item, StreamSequenceToken token) { return this.queueAdapter.QueueMessageAsync(this.stream.StreamId.Guid, this.stream.StreamId.Namespace, item, token, RequestContextExtensions.Export(this.serializationManager)); } public Task OnCompletedAsync() { // Maybe send a close message to the rendezvous? throw new NotImplementedException("OnCompletedAsync is not implemented for now."); } public Task OnErrorAsync(Exception ex) { // Maybe send a close message to the rendezvous? throw new NotImplementedException("OnErrorAsync is not implemented for now."); } public Task Cleanup() { return Task.CompletedTask; } } }
40.862745
195
0.691459
[ "MIT" ]
angerico-carino/orleans
src/Orleans.Core/Streams/PersistentStreams/PersistentStreamProducer.cs
2,084
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Text; using Silk.NET.Core; using Silk.NET.Core.Native; using Silk.NET.Core.Attributes; using Silk.NET.Core.Contexts; using Silk.NET.Core.Loader; #pragma warning disable 1591 namespace Silk.NET.Vulkan { [NativeName("Name", "VkPipelineCreationFeedbackCreateInfoEXT")] public unsafe partial struct PipelineCreationFeedbackCreateInfoEXT { public PipelineCreationFeedbackCreateInfoEXT ( StructureType? sType = StructureType.PipelineCreationFeedbackCreateInfoExt, void* pNext = null, PipelineCreationFeedbackEXT* pPipelineCreationFeedback = null, uint? pipelineStageCreationFeedbackCount = null, PipelineCreationFeedbackEXT* pPipelineStageCreationFeedbacks = null ) : this() { if (sType is not null) { SType = sType.Value; } if (pNext is not null) { PNext = pNext; } if (pPipelineCreationFeedback is not null) { PPipelineCreationFeedback = pPipelineCreationFeedback; } if (pipelineStageCreationFeedbackCount is not null) { PipelineStageCreationFeedbackCount = pipelineStageCreationFeedbackCount.Value; } if (pPipelineStageCreationFeedbacks is not null) { PPipelineStageCreationFeedbacks = pPipelineStageCreationFeedbacks; } } /// <summary></summary> [NativeName("Type", "VkStructureType")] [NativeName("Type.Name", "VkStructureType")] [NativeName("Name", "sType")] public StructureType SType; /// <summary></summary> [NativeName("Type", "void*")] [NativeName("Type.Name", "void")] [NativeName("Name", "pNext")] public void* PNext; /// <summary></summary> [NativeName("Type", "VkPipelineCreationFeedbackEXT*")] [NativeName("Type.Name", "VkPipelineCreationFeedbackEXT")] [NativeName("Name", "pPipelineCreationFeedback")] public PipelineCreationFeedbackEXT* PPipelineCreationFeedback; /// <summary></summary> [NativeName("Type", "uint32_t")] [NativeName("Type.Name", "uint32_t")] [NativeName("Name", "pipelineStageCreationFeedbackCount")] public uint PipelineStageCreationFeedbackCount; /// <summary></summary> [NativeName("Type", "VkPipelineCreationFeedbackEXT*")] [NativeName("Type.Name", "VkPipelineCreationFeedbackEXT")] [NativeName("Name", "pPipelineStageCreationFeedbacks")] public PipelineCreationFeedbackEXT* PPipelineStageCreationFeedbacks; } }
34.892857
94
0.647219
[ "MIT" ]
DmitryGolubenkov/Silk.NET
src/Vulkan/Silk.NET.Vulkan/Structs/PipelineCreationFeedbackCreateInfoEXT.gen.cs
2,931
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Metadata; using Sekai.Database.Models; namespace Sekai.Database.Context { public class TimelineContext : DbContext { public DbSet<TimelineEntry> TimelineEntries { get; set; } protected override void OnConfiguring(DbContextOptions builder) { var connection = "Filename=TimelineList2.db"; builder.UseSQLite(connection); } protected override void OnModelCreating(ModelBuilder builder) { builder.Entity<TimelineEntry>(b => { b.Key(thread => thread.Id); }); builder.Model.GetEntityType(typeof(TimelineEntry)).GetProperty("Id").GenerateValueOnAdd = true; } } }
27.75
107
0.655405
[ "MIT" ]
drasticactions/sekai
Sekai/Sekai.Database/Context/TimelineContext.cs
890
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20210201Preview.Outputs { /// <summary> /// Scope of Network Manager. /// </summary> [OutputType] public sealed class NetworkManagerPropertiesResponseNetworkManagerScopes { /// <summary> /// List of management groups. /// </summary> public readonly ImmutableArray<string> ManagementGroups; /// <summary> /// List of subscriptions. /// </summary> public readonly ImmutableArray<string> Subscriptions; [OutputConstructor] private NetworkManagerPropertiesResponseNetworkManagerScopes( ImmutableArray<string> managementGroups, ImmutableArray<string> subscriptions) { ManagementGroups = managementGroups; Subscriptions = subscriptions; } } }
29.461538
81
0.664926
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20210201Preview/Outputs/NetworkManagerPropertiesResponseNetworkManagerScopes.cs
1,149
C#
using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif public class LayerHandler { public static bool[] layer_pack_used = new bool[4]; private LayerHandler() { for (int k = 0; k < 4; k++) layer_pack_used [k] = false; } private static LayerHandler _instance = null; public static LayerHandler GetInstance() { if (_instance == null) { _instance = new LayerHandler(); } return _instance; } public enum LAYER_MODE { LAYER_MODE_LEFT_SCREEN, LAYER_MODE_RIGHT_SCREEN, LAYER_MODE_LEFT_FINALSCREEN, LAYER_MODE_RIGHT_FINALSCREEN }; public enum LAYER_PACK_LAYER_NUMBER { LAYER_PACK_CAM1_LS = 27, LAYER_PACK_CAM1_RS = 28, LAYER_PACK_CAM1_LFS = 29, LAYER_PACK_CAM1_RFS = 30, LAYER_PACK_CAM2_LS = 23, LAYER_PACK_CAM2_RS = 24, LAYER_PACK_CAM2_LFS = 25, LAYER_PACK_CAM2_RFS = 26, LAYER_PACK_CAM3_LS = 19, LAYER_PACK_CAM3_RS = 20, LAYER_PACK_CAM3_LFS = 21, LAYER_PACK_CAM3_RFS = 22, LAYER_PACK_CAM4_LS = 15, LAYER_PACK_CAM4_RS = 16, LAYER_PACK_CAM4_LFS = 17, LAYER_PACK_CAM4_RFS = 18 }; public void setUsed(sl.ZED_CAMERA_ID lp, bool used) { layer_pack_used [(int)lp] = used; } public bool getUsed(sl.ZED_CAMERA_ID lp) { return layer_pack_used [(int)lp]; } public int getLayerNumber(sl.ZED_CAMERA_ID lp, LAYER_MODE mode) { switch (lp) { case sl.ZED_CAMERA_ID.CAMERA_ID_01: { switch (mode) { case LAYER_MODE.LAYER_MODE_LEFT_SCREEN: return (int)LAYER_PACK_LAYER_NUMBER.LAYER_PACK_CAM1_LS; case LAYER_MODE.LAYER_MODE_RIGHT_SCREEN: return (int)LAYER_PACK_LAYER_NUMBER.LAYER_PACK_CAM1_RS; case LAYER_MODE.LAYER_MODE_LEFT_FINALSCREEN: return (int)LAYER_PACK_LAYER_NUMBER.LAYER_PACK_CAM1_LFS; case LAYER_MODE.LAYER_MODE_RIGHT_FINALSCREEN: return (int)LAYER_PACK_LAYER_NUMBER.LAYER_PACK_CAM1_RFS; default : return -1; } } break; case sl.ZED_CAMERA_ID.CAMERA_ID_02: { switch (mode) { case LAYER_MODE.LAYER_MODE_LEFT_SCREEN: return (int)LAYER_PACK_LAYER_NUMBER.LAYER_PACK_CAM2_LS; case LAYER_MODE.LAYER_MODE_RIGHT_SCREEN: return (int)LAYER_PACK_LAYER_NUMBER.LAYER_PACK_CAM2_RS; case LAYER_MODE.LAYER_MODE_LEFT_FINALSCREEN: return (int)LAYER_PACK_LAYER_NUMBER.LAYER_PACK_CAM2_LFS; case LAYER_MODE.LAYER_MODE_RIGHT_FINALSCREEN: return (int)LAYER_PACK_LAYER_NUMBER.LAYER_PACK_CAM2_RFS; default : return -1; } } break; case sl.ZED_CAMERA_ID.CAMERA_ID_03: { switch (mode) { case LAYER_MODE.LAYER_MODE_LEFT_SCREEN: return (int)LAYER_PACK_LAYER_NUMBER.LAYER_PACK_CAM3_LS; case LAYER_MODE.LAYER_MODE_RIGHT_SCREEN: return (int)LAYER_PACK_LAYER_NUMBER.LAYER_PACK_CAM3_RS; case LAYER_MODE.LAYER_MODE_LEFT_FINALSCREEN: return (int)LAYER_PACK_LAYER_NUMBER.LAYER_PACK_CAM3_LFS; case LAYER_MODE.LAYER_MODE_RIGHT_FINALSCREEN: return (int)LAYER_PACK_LAYER_NUMBER.LAYER_PACK_CAM3_RFS; default : return -1; } } break; case sl.ZED_CAMERA_ID.CAMERA_ID_04: { switch (mode) { case LAYER_MODE.LAYER_MODE_LEFT_SCREEN: return (int)LAYER_PACK_LAYER_NUMBER.LAYER_PACK_CAM4_LS; case LAYER_MODE.LAYER_MODE_RIGHT_SCREEN: return (int)LAYER_PACK_LAYER_NUMBER.LAYER_PACK_CAM4_RS; case LAYER_MODE.LAYER_MODE_LEFT_FINALSCREEN: return (int)LAYER_PACK_LAYER_NUMBER.LAYER_PACK_CAM4_LFS; case LAYER_MODE.LAYER_MODE_RIGHT_FINALSCREEN: return (int)LAYER_PACK_LAYER_NUMBER.LAYER_PACK_CAM4_RFS; default : return -1; } } break; default : return -1; } } }
23.346405
64
0.740761
[ "MIT" ]
rush17m/zed-unity
ZEDCamera/Assets/ZED/SDK/Helpers/Scripts/Utilities/LayerHandler.cs
3,574
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace Vim.UnitTest { public abstract class StringUtilTest { public sealed class ReplaceNoCase : StringUtilTest { private void Expect(string source, string toFind, string toReplace, string expected) { for (int i = 0; i < toFind.Length; i++) { var original = toFind[i]; var changed = Char.IsUpper(original) ? Char.ToLower(original) : Char.ToUpper(original); var toFindChanged = toFind.Replace(original, changed); var replace = StringUtil.replaceNoCase(source, toFindChanged, toReplace); Assert.Equal(expected, replace); } } [Fact] public void Front() { Expect("cat", "ca", "bel", "belt"); } [Fact] public void Back() { Expect("cat", "at", "ode", "code"); } [Fact] public void Middle() { Expect("cat", "a", "o", "cot"); } [Fact] public void Many() { Expect("ceedeed", "ee", "o", "codod"); } } } }
28.019608
108
0.441568
[ "Apache-2.0" ]
Kazark/VsVim
Test/VimCoreTest/StringUtilTest.cs
1,431
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _03BarracksFactory.Contracts { public interface IUnit : IDestroyable, IAttacker { } }
16.214286
52
0.757709
[ "MIT" ]
BorislavBarov/OOP-Advanced-With-C-Sharp
Exercise/05. Reflection - Exercise/03.BarracksFactory/Contracts/IUnit.cs
229
C#
using System.Collections.Generic; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; namespace WebApplication.Models { // Add profile data for application users by adding properties to the ApplicationUser class public class ApplicationUser : IdentityUser { public List<UserPermission> Permissions { get; set; } } }
28.916667
95
0.760807
[ "MIT" ]
aggieben/authorization-demo
Models/ApplicationUser.cs
347
C#
#pragma checksum "F:\DotNetSelfPractise_Home\source\MyProjects\YogiProjects\NextCRUD\Views\Person\Thanks.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "831c764df7527b4b6309c5905dfacf25555ba1f2" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Person_Thanks), @"mvc.1.0.view", @"/Views/Person/Thanks.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "F:\DotNetSelfPractise_Home\source\MyProjects\YogiProjects\NextCRUD\Views\_ViewImports.cshtml" using NextCRUD; #line default #line hidden #nullable disable #nullable restore #line 2 "F:\DotNetSelfPractise_Home\source\MyProjects\YogiProjects\NextCRUD\Views\_ViewImports.cshtml" using NextCRUD.Models; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"831c764df7527b4b6309c5905dfacf25555ba1f2", @"/Views/Person/Thanks.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"4d9bf6eb48413c3305220aca2c2a0ff664f84f18", @"/Views/_ViewImports.cshtml")] public class Views_Person_Thanks : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<Person> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Index", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Create", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; #pragma warning restore 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #nullable restore #line 2 "F:\DotNetSelfPractise_Home\source\MyProjects\YogiProjects\NextCRUD\Views\Person\Thanks.cshtml" ViewData["Title"] = "Thanks"; #line default #line hidden #nullable disable __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "831c764df7527b4b6309c5905dfacf25555ba1f23889", async() => { WriteLiteral("Show all"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_0.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n<h1>Thanks</h1>\r\n<h3>Thanks "); #nullable restore #line 7 "F:\DotNetSelfPractise_Home\source\MyProjects\YogiProjects\NextCRUD\Views\Person\Thanks.cshtml" Write(Model.Name); #line default #line hidden #nullable disable WriteLiteral("</h3>\r\n"); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "831c764df7527b4b6309c5905dfacf25555ba1f25316", async() => { WriteLiteral("Create New"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_1.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n\r\n\r\n"); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<Person> Html { get; private set; } } } #pragma warning restore 1591
59.868852
299
0.751232
[ "MIT" ]
Amphibian007/DotNetSelfPractise_Home
source/MyProjects/YogiProjects/NextCRUD/obj/Debug/netcoreapp3.1/Razor/Views/Person/Thanks.cshtml.g.cs
7,304
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Immutable; using osu.Framework.Input.Handlers; using osu.Framework.Input.StateChanges; using osu.Framework.Input.StateChanges.Events; using osu.Framework.Platform; using osuTK; using osuTK.Input; namespace osu.Framework.Input { public class UserInputManager : PassThroughInputManager { protected override ImmutableArray<InputHandler> InputHandlers => Host.AvailableInputHandlers; protected override bool HandleHoverEvents => Host.Window?.CursorInWindow ?? true; protected internal override bool ShouldBeAlive => true; protected internal UserInputManager() { // UserInputManager is at the very top of the draw hierarchy, so it has no parent updating its IsAlive state IsAlive = true; UseParentInput = false; } public override void HandleInputStateChange(InputStateChangeEvent inputStateChange) { switch (inputStateChange) { case MousePositionChangeEvent mousePositionChange: var mouse = mousePositionChange.State.Mouse; // confine cursor if (Host.Window != null && Host.Window.CursorState.HasFlag(CursorState.Confined)) { var clientSize = Host.Window.ClientSize; mouse.Position = Vector2.Clamp(mouse.Position, Vector2.Zero, new Vector2(clientSize.Width, clientSize.Height)); } break; case ButtonStateChangeEvent<MouseButton> buttonChange: if (buttonChange.Kind == ButtonStateChangeKind.Pressed && Host.Window?.CursorInWindow == false) return; break; case MouseScrollChangeEvent _: if (Host.Window?.CursorInWindow == false) return; break; } base.HandleInputStateChange(inputStateChange); } } }
36.33871
136
0.598313
[ "MIT" ]
EVAST9919/osu-framework
osu.Framework/Input/UserInputManager.cs
2,194
C#
using SpaceShared; using SpaceShared.APIs; using StardewModdingAPI; using StardewModdingAPI.Events; using StardewValley; namespace JumpOver { public class Mod : StardewModdingAPI.Mod { public static Mod instance; public static Configuration Config; /// <summary>The mod entry point, called after the mod is first loaded.</summary> /// <param name="helper">Provides simplified APIs for writing mods.</param> public override void Entry(IModHelper helper) { instance = this; Log.Monitor = Monitor; Config = helper.ReadConfig<Configuration>(); helper.Events.GameLoop.GameLaunched += onGameLaunched; helper.Events.Input.ButtonPressed += onButtonPressed; } private void onGameLaunched(object sender, GameLaunchedEventArgs e) { var capi = Helper.ModRegistry.GetApi<GenericModConfigMenuAPI>("spacechase0.GenericModConfigMenu"); if (capi != null) { capi.RegisterModConfig(ModManifest, () => Config = new Configuration(), () => Helper.WriteConfig(Config)); capi.RegisterSimpleOption(ModManifest, "Jump Key", "The key to jump", () => Config.keyJump, (SButton val) => Config.keyJump = val); } } /// <summary>Raised after the player presses a button on the keyboard, controller, or mouse.</summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event arguments.</param> private void onButtonPressed(object sender, ButtonPressedEventArgs e) { if (!Context.IsWorldReady || !Context.IsPlayerFree || Game1.activeClickableMenu != null) return; if ( e.Button == Config.keyJump && Game1.player.yJumpVelocity == 0 ) { // This is terrible for this case, redo it new Jump(Game1.player, Helper.Events); } } internal class Jump { private readonly Farmer player; private readonly IModEvents events; private float prevJumpVel = 0; //private bool wasGoingOver = false; public Jump(StardewValley.Farmer thePlayer, IModEvents events) { player = thePlayer; this.events = events; prevJumpVel = player.yJumpVelocity; player.synchronizedJump(8); events.GameLoop.UpdateTicked += onUpdateTicked; } /// <summary>Raised after the game state is updated (≈60 times per second).</summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event arguments.</param> private void onUpdateTicked(object sender, UpdateTickedEventArgs e) { if (player.yJumpVelocity == 0 && prevJumpVel < 0) { player.canMove = true; events.GameLoop.UpdateTicked -= onUpdateTicked; } else { int tx = (int)player.position.X / Game1.tileSize; int ty = (int)player.position.Y / Game1.tileSize; int ox = 0, oy = 0; // Offset x, y switch (player.facingDirection.Value) { case Game1.up: oy = -1; break; case Game1.down: oy = 1; break; case Game1.left: ox = -1; break; case Game1.right: ox = 1; break; } var bb = player.GetBoundingBox(); var bb1 = player.GetBoundingBox(); bb1.X += ox * Game1.tileSize; bb1.Y += oy * Game1.tileSize; var bb2 = player.GetBoundingBox(); bb2.X += ox * Game1.tileSize * 2; bb2.Y += oy * Game1.tileSize * 2; bool n0 = player.currentLocation.isCollidingPosition(bb, Game1.viewport, true, 0, false, player); bool n1 = player.currentLocation.isCollidingPosition(bb1, Game1.viewport, true, 0, false, player); bool n2 = player.currentLocation.isCollidingPosition(bb2, Game1.viewport, true, 0, false, player); //Log.trace($"{n0} {n1} {n2}"); if ( n0 || ( !n0 && n1 && !n2 ) /*|| wasGoingOver*/ ) { //wasGoingOver = true; Game1.player.canMove = false; player.position.X += ox * 5; player.position.Y += oy * 5; } } prevJumpVel = player.yJumpVelocity; } } } }
40.297521
147
0.522765
[ "MIT" ]
strobel1ght/StardewValleyMods
JumpOver/Mod.cs
4,878
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Linq; using Microsoft.Quantum.Simulation.Simulators; using Microsoft.Quantum.Simulation.Common; using Microsoft.Quantum.Simulation.Core; using CommandLine; using Microsoft.Quantum.Simulation.Simulators.QCTraceSimulators; namespace Microsoft.Quantum.Samples.IntegerFactorization { /// <summary> /// Common command line options for the application /// </summary> /// /// You can call `dotnet run -- --help` to see a help description for the application class CommonOptions { [Option('n', "number", Required = false, Default = 15, HelpText = "Number to be factored")] public long NumberToFactor { get; set; } [Option('f', "fourier", Required = false, Default = false, HelpText = "Use Fourier-based arithmetic")] public bool UseQFTArithmetic { get; set; } } [Verb("simulate", isDefault: true, HelpText = "Simulate Shor's algorithm")] class SimulateOptions : CommonOptions { [Option('t', "trials", Required = false, Default = 100, HelpText = "Number of trials to perform")] public long NumberOfTrials { get; set; } [Option('d', "dense", Required = false, Default = false, HelpText = "Use dense states for simulation")] public bool UseDense { get; set; } } [Verb("estimate", HelpText = "Estimate the resources to perform one round of period finding in Shor's algorithm")] class EstimateOptions : CommonOptions { [Option('g', "generator", Required = true, HelpText = "A coprime to `number` of which the period is estimated")] public long Generator { get; set; } } [Verb("visualize", HelpText = "Visualize the estimation of the resources to perform one round of period finding in Shor's algorithm")] class VisualizeOptions : CommonOptions { [Option('g', "generator", Required = true, HelpText = "A coprime to `number` of which the period is estimated")] public long Generator { get; set; } [Option('r', "resource", Required = false, Default = 0, HelpText = "The resource - CNOT: 0; QubitClifford: 1; R: 2; Measure: 3; T: 4")] public PrimitiveOperationsGroups Resource { get; set; } [Option("quantum-viz", HelpText = "Use quantum-viz.js for visualization")] public bool QuantumViz { get; set; } } /// <summary> /// This is a Console program that runs Shor's algorithm /// on a Quantum Simulator. /// </summary> class Program { static int Main(string[] args) => Parser.Default.ParseArguments<SimulateOptions, EstimateOptions, VisualizeOptions>(args).MapResult( (SimulateOptions options) => Simulate(options), (EstimateOptions options) => Estimate(options), (VisualizeOptions options) => Visualize(options), _ => 1 ); // By default we use `ApplyOrderFindingOracle` as inner operation for order finding // that relies on the reversible implementation for modular multiplication `ModularMulByConstant`. // If we set the `fourier` option via command line arguments, we map this operation to the // alternative `ApplyOrderFindingOracleFourierArithmetic` that uses the Q# library function // `MultiplyByModularInteger` that is based on Fourier arithmetic instead. private static void RegisterReplacement(CommonOptions options, SimulatorBase sim) { if (options.UseQFTArithmetic) { sim.Register(typeof(ApplyOrderFindingOracle), typeof(ApplyOrderFindingOracleFourierArithmetic), typeof(IUnitary)); } } static int Simulate(SimulateOptions options) { // Repeat Shor's algorithm multiple times as the algorithm is // probabilistic and there are several ways that it can fail. for (int i = 0; i < options.NumberOfTrials; ++i) { try { // Make sure to use simulator within using block. // This ensures that all resources used by QuantumSimulator // are properly released if the algorithm fails and throws an exception. using var sim = options.UseDense ? (CommonNativeSimulator)new QuantumSimulator() : (CommonNativeSimulator)new SparseSimulator(); RegisterReplacement(options, sim); // Report the number being factored to the standard output Console.WriteLine($"=========================================="); Console.WriteLine($"Factoring {options.NumberToFactor}"); // Compute the factors (long factor1, long factor2) = FactorSemiprimeInteger.Run(sim, options.NumberToFactor).Result; Console.WriteLine($"Factors are {factor1} and {factor2}"); // Stop once the factorization has been found break; } // Shor's algorithm is a probabilistic algorithm and can fail with certain // probability in several ways. For more details see Shor.qs. // If the run of Shor's algorithm fails it throws ExecutionFailException. // However, due to the use of System.Task in .Run method, // the exception of interest is getting wrapped into AggregateException. catch (AggregateException e ) { // Report the failure of the algorithm to standard output Console.WriteLine($"This run of Shor's algorithm failed:"); // Unwrap AggregateException to get the message from Q# fail statement. // Go through all inner exceptions. foreach (Exception eInner in e.InnerExceptions) { // If the exception of type ExecutionFailException if (eInner is ExecutionFailException failException) { // Print the message it contains Console.WriteLine($" {failException.Message}"); } } } } return 0; } static int Estimate(EstimateOptions options) { var config = ResourcesEstimator.RecommendedConfig(); config.CallStackDepthLimit = 3; var estimator = new ResourcesEstimator(config); RegisterReplacement(options, estimator); var bitsize = (long)System.Math.Ceiling(System.Math.Log2(options.NumberToFactor + 1)); EstimateFrequency.Run(estimator, options.Generator, options.NumberToFactor, bitsize).Wait(); Console.WriteLine(estimator.ToTSV()); Console.WriteLine(); Console.WriteLine(estimator.ToCSV()["PrimitiveOperationsCounter"]); return 0; } static int Visualize(VisualizeOptions options) { var bitsize = (long)System.Math.Ceiling(System.Math.Log2(options.NumberToFactor + 1)); if (options.QuantumViz) { var config = QuantumVizEstimator.RecommendedConfig(); var estimator = new QuantumVizEstimator(config); RegisterReplacement(options, estimator); EstimateFrequency.Run(estimator, options.Generator, options.NumberToFactor, bitsize).Wait(); Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(estimator.Circuit)); } else { var config = FlameGraphResourcesEstimator.RecommendedConfig(); var estimator = new FlameGraphResourcesEstimator(config, options.Resource); RegisterReplacement(options, estimator); EstimateFrequency.Run(estimator, options.Generator, options.NumberToFactor, bitsize).Wait(); Console.WriteLine(string.Join(System.Environment.NewLine, estimator.FlameGraphData.Select(pair => $"{pair.Key} {pair.Value}"))); } return 0; } } }
45.344262
148
0.608339
[ "MIT" ]
CyberNitta/Quantum
samples/algorithms/integer-factorization/Program.cs
8,300
C#
namespace Raspicam.Net.Mmal.Components.EncoderComponents { interface IImageEncoder : IEncoder { } }
21
57
0.771429
[ "MIT" ]
zeroexploit/MMALSharp
Source/Raspicam.Net/Mmal/Components/EncoderComponents/IImageEncoder.cs
107
C#
using System; using LuaInterface; using SLua; using System.Collections.Generic; public class Lua_UnityEngine_ParticleSystemCollisionQuality : LuaObject { static public void reg(IntPtr l) { getEnumTable(l,"UnityEngine.ParticleSystemCollisionQuality"); addMember(l,0,"High"); addMember(l,1,"Medium"); addMember(l,2,"Low"); LuaDLL.lua_pop(l, 1); } }
25.714286
73
0.758333
[ "MIT" ]
zhangjie0072/FairyGUILearn
Assets/Slua/LuaObject/Unity/Lua_UnityEngine_ParticleSystemCollisionQuality.cs
362
C#
using System; namespace FormsSample.Models { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty( RequestId ); } }
17.272727
66
0.736842
[ "MIT" ]
fjeller/Smarthouse.AspnetCore.Samples
__NetCore2/FormsSample/FormsSample/Models/ErrorViewModel.cs
190
C#
using Autofac; using Newbe.Claptrap.StorageProvider.Relational; namespace Newbe.Claptrap.StorageProvider.MySql.Module { public class MySqlStorageModule : Autofac.Module, IClaptrapAppModule { public string Name { get; } = "MySql storage module"; public string Description { get; } = "Module for support event store and state store by using MySql"; protected override void Load(ContainerBuilder builder) { base.Load(builder); builder.RegisterType<DbFactory>() .As<IDbFactory>() .SingleInstance(); builder.RegisterType<MySqlAdoCache>() .As<IMySqlAdoCache>() .SingleInstance(); builder.RegisterBuildCallback(container => { var cache = container.Resolve<ISqlTemplateCache>(); }); } } }
32.851852
109
0.602029
[ "MIT" ]
Z4t4r/Newbe.Claptrap
src/Newbe.Claptrap.StorageProvider.MySql/Module/MySqlStorageModule.cs
887
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Runtime.Serialization.Json; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; using Aksl.Concurrency; using Aksl.BulkInsert; using Contoso.Domain.Models; using Contoso.DataSource.Dtos; using Contoso.DataSource; namespace Contoso.ConsoleApp { public partial class WebApiSender { #region Batch Messages Blocks public async Task MultiplePipeBlockAsync(int recieverCount = 1, int messageCount = 10000) { for (int i = 0; i < recieverCount; i++) { await PipeBulkInsertBlockAsync(i, messageCount); } } public async Task PipeBulkInsertBlockAsync(int seqNumber = 1, int orderCount = 4000) { if (!_isInitialize) { throw new InvalidOperationException("not initialize"); } #region Block Method (int blockCount, int minPerBlock, int maxPerBlock) blockBascInfo = BlockHelper.GetBasciBlockInfo(orderCount); int[] blockInfos = BlockHelper.GetBlockInfo(messageCount: orderCount, blockCount: blockBascInfo.blockCount, minPerBlock: blockBascInfo.minPerBlock, maxPerBlock: blockBascInfo.maxPerBlock); #endregion int boundedCapacity = blockInfos.Sum(b => b); Debug.Assert(orderCount == boundedCapacity); var logger = _loggerFactory.CreateLogger($"PipeBulkInser-{seqNumber}:{orderCount}"); try { var pipeBulkInserter = this.ServiceProvider.GetRequiredService<IPipeBulkInserter<OrderDto, OrderDto>>(); var contosoDataSourceFactory = this.ServiceProvider.GetRequiredService<IDataSourceFactory<IContosoDataSource>>(); var orderDataSource = contosoDataSourceFactory.Current.OrderDataSource; _totalCount = 0; var transportTimeWatcher = Stopwatch.StartNew(); TimeSpan totalTransportTime = TimeSpan.Zero; var executionTimeWatcher = Stopwatch.StartNew(); logger.LogInformation($"----begin pipe bulk insert {orderCount} orders,now:{DateTime.Now.TimeOfDay}----"); int start = 0; for (int i = 0; i < blockInfos.Count(); i++) { int insertOrderCount = blockInfos[i]; var orders = OrderJsonProvider.CreateOrders(start, insertOrderCount); start += insertOrderCount; transportTimeWatcher.Restart(); var dbOrders = await orderDataSource.PipeBulkInsertOrdersAsync(orders); totalTransportTime += transportTimeWatcher.Elapsed; transportTimeWatcher.Reset(); if (dbOrders?.Count() > 0) { await ProcessPipeOrdersAsync(dbOrders); } } logger .LogInformation($"----pipe bulk insert {orderCount} orders,cost time:\"{executionTimeWatcher.Elapsed}\",transport time:{ totalTransportTime },count/time(sec):{Math.Ceiling(orderCount / totalTransportTime.TotalSeconds)},now:\"{DateTime.Now.TimeOfDay}\"----"); } catch (Exception ex) { logger.LogError($"Error while pipe bulk insert: {ex.Message}"); } } #endregion } }
38.631579
278
0.619891
[ "MIT" ]
aksl2019/Aksl-2.0
Aksl.BulkInsert/Contoso/Contoso.ConsoleApp/Pipe/BatchBlock.cs
3,672
C#
using TMPro; using UnityEngine; namespace UI { [RequireComponent(typeof(TextMeshProUGUI))] public class UpdateSizeUI : MonoBehaviour { private TextMeshProUGUI _tmPro; private void Start() { _tmPro = GetComponent<TextMeshProUGUI>(); } public void ChangeData(float data) { _tmPro.text = data.ToString(); } } }
19.380952
53
0.584767
[ "Apache-2.0" ]
Hadjime/ProjectPainter
Assets/Scripts/UI/UpdateSizeUI.cs
409
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the chime-2018-05-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Chime.Model { /// <summary> /// Container for the parameters to the UpdateBot operation. /// Updates the status of the specified bot, such as starting or stopping the bot from /// running in your Amazon Chime Enterprise account. /// </summary> public partial class UpdateBotRequest : AmazonChimeRequest { private string _accountId; private string _botId; private bool? _disabled; /// <summary> /// Gets and sets the property AccountId. /// <para> /// The Amazon Chime account ID. /// </para> /// </summary> [AWSProperty(Required=true)] public string AccountId { get { return this._accountId; } set { this._accountId = value; } } // Check to see if AccountId property is set internal bool IsSetAccountId() { return this._accountId != null; } /// <summary> /// Gets and sets the property BotId. /// <para> /// The bot ID. /// </para> /// </summary> [AWSProperty(Required=true)] public string BotId { get { return this._botId; } set { this._botId = value; } } // Check to see if BotId property is set internal bool IsSetBotId() { return this._botId != null; } /// <summary> /// Gets and sets the property Disabled. /// <para> /// When true, stops the specified bot from running in your account. /// </para> /// </summary> public bool Disabled { get { return this._disabled.GetValueOrDefault(); } set { this._disabled = value; } } // Check to see if Disabled property is set internal bool IsSetDisabled() { return this._disabled.HasValue; } } }
28.676768
103
0.593519
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Chime/Generated/Model/UpdateBotRequest.cs
2,839
C#
using System.Collections.Generic; using System.Linq; namespace Sanakan.Web.Models { /// <summary> /// Describes user profile in a website. /// </summary> public class UserSiteProfile { /// <summary> /// The aggregated number of cards grouped by rarity. /// </summary> public IDictionary<string, long> CardsCount { get; set; } = null; /// <summary> /// The wallet content. /// </summary> public IDictionary<string, long> Wallet { get; set; } = null; /// <summary> /// The favourite card. /// </summary> public CardFinalView Waifu { get; set; } = null; /// <summary> /// The list of cards which have gallery tag. /// </summary> public IEnumerable<CardFinalView> Gallery { get; set; } = Enumerable.Empty<CardFinalView>(); /// <summary> /// The list of expeditions. /// </summary> public IEnumerable<ExpeditionCard> Expeditions { get; set; } = Enumerable.Empty<ExpeditionCard>(); /// <summary> /// The list of tags which user has in cards. /// </summary> public List<string> TagList { get; set; } = null; /// <summary> /// User exchange rules. /// </summary> public string ExchangeConditions { get; set; } = null; /// <summary> /// The user title. /// </summary> public string? UserTitle { get; set; } /// <summary> /// The image position in user profile background. /// </summary> public int BackgroundPosition { get; set; } /// <summary> /// The image position in user profile foreground. /// </summary> public int ForegroundPosition { get; set; } /// <summary> /// The image in user profile background. /// </summary> public string? BackgroundImageUrl { get; set; } /// <summary> /// The character image in user profile foreground. /// </summary> public string? ForegroundImageUrl { get; set; } /// <summary> /// The main profile foreground color. /// </summary> public string? ForegroundColor { get; set; } /// <summary> /// The user karma. /// </summary> public double Karma { get; set; } } }
29.036585
106
0.536749
[ "MPL-2.0" ]
Jozpod/sanakan
Web/Models/UserSiteProfile.cs
2,383
C#
namespace Acme.ShoppingCart.WebApi.Models.Responses { /// <summary> /// Configuration /// </summary> public class ConfigurationModel { /// <summary> /// Service bus configuration /// </summary> public ServicebusModel ServiceBus { get; set; } /// <summary> /// Identity Server configuration /// </summary> public IdentityServerModel IdentityServer { get; set; } /// <summary> /// Policy Server configuration /// </summary> public PolicyServerModel PolicyServer { get; set; } } }
29.7
63
0.575758
[ "MIT" ]
cortside/coeus
shoppingcart-api/src/Acme.ShoppingCart.WebApi/Models/Responses/ConfigurationModel.cs
594
C#
#pragma checksum "..\..\..\App.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "1B6550EACFFCBCD0E3C4D10DD80D1379D5FE9024" //------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ using Prism.Interactivity; using Prism.Interactivity.InteractionRequest; using Prism.Mvvm; using Prism.Regions; using Prism.Regions.Behaviors; using Prism.Services.Dialogs; using Prism.Unity; using PrismMetroSample.Shell; using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Controls.Ribbon; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; namespace PrismMetroSample.Shell { /// <summary> /// App /// </summary> public partial class App : Prism.Unity.PrismApplication { private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.8.1.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/PrismMetroSample.Shell;component/app.xaml", System.UriKind.Relative); #line 1 "..\..\..\App.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } /// <summary> /// Application Entry Point. /// </summary> [System.STAThreadAttribute()] [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.8.1.0")] public static void Main() { PrismMetroSample.Shell.App app = new PrismMetroSample.Shell.App(); app.InitializeComponent(); app.Run(); } } }
31.546512
127
0.629193
[ "MIT" ]
MrViliam/NetCoreWpfMVVMPrismSample
PrismMetroSample/PrismMetroSample.Shell/obj/Debug/netcoreapp3.1/App.g.cs
2,821
C#
using Model.Effects; namespace Model.Items { class Poison : Item { public Poison() { Name = "Poison Potion"; UserTarget = TargetType.Any; SpriteNumber = 705; InColor = UnityEngine.Color.magenta; OutColor = UnityEngine.Color.clear; } public override void Use(Tile tile) { Unit unit = tile.GetUnit(); if (unit != null) Common.Command.AddEffect(unit, new Effects.Poison()); } } }
23.913043
69
0.501818
[ "MIT" ]
unagi11/project21
Assets/Scripts/Model/Items/Poison.cs
550
C#
using System; using Microsoft.Azure.WebJobs; namespace HttpBinding { public static class HttpExtension { public static IWebJobsBuilder AddHttpBinding(this IWebJobsBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } builder.AddExtension<HttpBinding>(); return builder; } } }
21.55
82
0.584687
[ "MIT" ]
Jandev/CustomBindings
HttpBinding/HttpExtension.cs
433
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. using System; using System.Globalization; using System.Text; using static TerraFX.Utilities.HashUtilities; namespace TerraFX.Numerics { /// <summary>Defines a quaternion.</summary> public readonly struct Quaternion : IEquatable<Quaternion>, IFormattable { #region Fields private readonly float _x; private readonly float _y; private readonly float _z; private readonly float _w; #endregion #region Constructors /// <summary>Initializes a new instance of the <see cref="Quaternion" /> struct.</summary> /// <param name="x">The value of the x-component.</param> /// <param name="y">The value of the y-component.</param> /// <param name="z">The value of the z-component.</param> /// <param name="w">The value of the w-component.</param> public Quaternion(float x, float y, float z, float w) { _x = x; _y = y; _z = z; _w = w; } #endregion #region Properties /// <summary>Gets the value of the x-component.</summary> public float X { get { return _x; } } /// <summary>Gets the value of the y-component.</summary> public float Y { get { return _y; } } /// <summary>Gets the value of the z-component.</summary> public float Z { get { return _z; } } /// <summary>Gets the value of the w-component.</summary> public float W { get { return _w; } } #endregion #region Comparison Operators /// <summary>Compares two <see cref="Quaternion" /> instances to determine equality.</summary> /// <param name="left">The <see cref="Quaternion" /> to compare with <paramref name="right" />.</param> /// <param name="right">The <see cref="Quaternion" /> to compare with <paramref name="left" />.</param> /// <returns><c>true</c> if <paramref name="left" /> and <paramref name="right" /> are equal; otherwise, <c>false</c>.</returns> public static bool operator ==(Quaternion left, Quaternion right) { return (left.X == right.X) && (left.Y == right.Y) && (left.Z == right.Z) && (left.W == right.W); } /// <summary>Compares two <see cref="Quaternion" /> instances to determine inequality.</summary> /// <param name="left">The <see cref="Quaternion" /> to compare with <paramref name="right" />.</param> /// <param name="right">The <see cref="Quaternion" /> to compare with <paramref name="left" />.</param> /// <returns><c>true</c> if <paramref name="left" /> and <paramref name="right" /> are not equal; otherwise, <c>false</c>.</returns> public static bool operator !=(Quaternion left, Quaternion right) { return (left.X != right.X) || (left.Y != right.Y) || (left.Z != right.Z) || (left.W != right.W); } #endregion #region Methods /// <summary>Creates a new <see cref="Quaternion" /> instance with <see cref="X" /> set to the specified value.</summary> /// <param name="value">The new value of the x-component.</param> /// <returns>A new <see cref="Quaternion" /> instance with <see cref="X" /> set to <paramref name="value" />.</returns> public Quaternion WithX(float value) { return new Quaternion(value, Y, Z, W); } /// <summary>Creates a new <see cref="Quaternion" /> instance with <see cref="Y" /> set to the specified value.</summary> /// <param name="value">The new value of the y-component.</param> /// <returns>A new <see cref="Quaternion" /> instance with <see cref="Y" /> set to <paramref name="value" />.</returns> public Quaternion WithY(float value) { return new Quaternion(X, value, Z, W); } /// <summary>Creates a new <see cref="Quaternion" /> instance with <see cref="Z" /> set to the specified value.</summary> /// <param name="value">The new value of the z-component.</param> /// <returns>A new <see cref="Quaternion" /> instance with <see cref="Z" /> set to <paramref name="value" />.</returns> public Quaternion WithZ(float value) { return new Quaternion(X, Y, value, W); } /// <summary>Creates a new <see cref="Quaternion" /> instance with <see cref="W" /> set to the specified value.</summary> /// <param name="value">The new value of the w-component.</param> /// <returns>A new <see cref="Quaternion" /> instance with <see cref="W" /> set to <paramref name="value" />.</returns> public Quaternion WithW(float value) { return new Quaternion(X, Y, Z, value); } #endregion #region System.IEquatable<Quaternion> Methods /// <summary>Compares a <see cref="Quaternion" /> with the current instance to determine equality.</summary> /// <param name="other">The <see cref="Quaternion" /> to compare with the current instance.</param> /// <returns><c>true</c> if <paramref name="other" /> is equal to the current instance; otherwise, <c>false</c>.</returns> public bool Equals(Quaternion other) { return this == other; } #endregion #region System.IFormattable Methods /// <summary>Converts the current instance to an equivalent <see cref="string" /> value.</summary> /// <param name="format">The format to use or <c>null</c> to use the default format.</param> /// <param name="formatProvider">The provider to use when formatting the current instance or <c>null</c> to use the default provider.</param> /// <returns>An equivalent <see cref="string" /> value for the current instance.</returns> public string ToString(string? format, IFormatProvider? formatProvider) { var separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator; return new StringBuilder(9 + (separator.Length * 3)) .Append('<') .Append(X.ToString(format, formatProvider)) .Append(separator) .Append(' ') .Append(Y.ToString(format, formatProvider)) .Append(separator) .Append(' ') .Append(Z.ToString(format, formatProvider)) .Append(separator) .Append(' ') .Append(W.ToString(format, formatProvider)) .Append('>') .ToString(); } #endregion #region System.Object Methods /// <summary>Compares a <see cref="object" /> with the current instance to determine equality.</summary> /// <param name="obj">The <see cref="object" /> to compare with the current instance.</param> /// <returns><c>true</c> if <paramref name="obj" /> is an instance of <see cref="Quaternion" /> and is equal to the current instance; otherwise, <c>false</c>.</returns> public override bool Equals(object? obj) { return (obj is Quaternion other) && Equals(other); } /// <summary>Gets a hash code for the current instance.</summary> /// <returns>A hash code for the current instance.</returns> public override int GetHashCode() { var combinedValue = 0; { combinedValue = CombineValue(X.GetHashCode(), combinedValue); combinedValue = CombineValue(Y.GetHashCode(), combinedValue); combinedValue = CombineValue(Z.GetHashCode(), combinedValue); combinedValue = CombineValue(W.GetHashCode(), combinedValue); } return FinalizeValue(combinedValue, sizeof(float) * 4); } /// <summary>Converts the current instance to an equivalent <see cref="string" /> value.</summary> /// <returns>An equivalent <see cref="string" /> value for the current instance.</returns> public override string ToString() { return ToString(format: null, formatProvider: null); } #endregion } }
43.039604
176
0.566483
[ "MIT" ]
johnkellyoxford/terrafx
sources/Core/Numerics/Quaternion.cs
8,695
C#
// (c) Copyright HutongGames, LLC 2010-2015. All rights reserved. // edited in project using this as a submodule // INSTRUCTIONS // This set of utils is here to help custom action development, and scripts in general that wants to connect and work with PlayMaker API. public partial class PlayMakerUtils { // This is the main file to keep old package happy. Each section of PlayMaker Utils are now in distinct files with partial implementation. }
45.8
140
0.762009
[ "MIT" ]
pdyxs/UnityProjectStarter
Assets/Plugins/Externals/PlayMaker Utils/PlayMakerUtils.cs
458
C#
using Microsoft.Extensions.Logging; using NICE.Identity.Authorisation.WebAPI.ApiModels; using NICE.Identity.Authorisation.WebAPI.Repositories; using System; using System.Collections.Generic; using System.Linq; namespace NICE.Identity.Authorisation.WebAPI.Services { public interface IJobsService { Job CreateJob(Job job); List<Job> GetJobs(); Job GetJob(int jobId); Job UpdateJob(int jobId, Job job); int DeleteJob(int jobId); void DeleteAllJobsForOrganisation(int organisationId); } public class JobsService : IJobsService { private readonly IdentityContext _context; private readonly ILogger<JobsService> _logger; public JobsService(IdentityContext context, ILogger<JobsService> logger) { _context = context ?? throw new ArgumentNullException(nameof(context)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public Job CreateJob(Job job) { try { var jobToCreate = new DataModels.Job(); jobToCreate.UpdateFromApiModel(job); var createdJob = _context.Jobs.Add(jobToCreate); _context.SaveChanges(); return new Job(createdJob.Entity); } catch (Exception e) { _logger.LogError($"Failed to create job for {job.JobId.ToString()} - exception: {e.Message}"); throw new Exception($"Failed to create job for {job.JobId.ToString()} - exception: {e.Message}"); } } public List<Job> GetJobs() { return _context.Jobs.Select(job => new Job(job)).ToList(); } public Job GetJob(int jobId) { var job = _context.Jobs.Where((j => j.JobId == jobId)).FirstOrDefault(); return job != null ? new Job(job) : null; } public Job UpdateJob(int jobId, Job job) { try { var jobToUpdate = _context.Jobs.Find(jobId); if (jobToUpdate == null) throw new Exception($"Job not found {jobId.ToString()}"); jobToUpdate.UpdateFromApiModel(job); _context.SaveChanges(); return new Job(jobToUpdate); } catch (Exception e) { _logger.LogError($"Failed to update job {jobId.ToString()} - exception: {e.Message}"); throw new Exception($"Failed to update job {jobId.ToString()} - exception: {e.Message}"); } } public int DeleteJob(int jobId) { try { var jobToDelete = _context.Jobs.Find(jobId); if (jobToDelete == null) return 0; _context.Jobs.RemoveRange(jobToDelete); return _context.SaveChanges(); } catch (Exception e) { _logger.LogError($"Failed to delete job {jobId.ToString()} - exception: {e.Message}"); throw new Exception($"Failed to delete job {jobId.ToString()} - exception: {e.Message}"); } } /// <summary> /// Delete all jobs relating to an organisation /// </summary> /// <param name="organisationId"></param> /// <returns></returns> public void DeleteAllJobsForOrganisation(int organisationId) { try { var jobToDelete = _context.Jobs.Where((j => j.OrganisationId == organisationId)).ToList(); foreach (var job in jobToDelete) { _context.Jobs.RemoveRange(job); } // SaveChanges() is done in the DeleteOrganisation method to avoid foreign key constraints } catch (Exception e) { _logger.LogError($"Failed to delete jobs for organisation {organisationId.ToString()} - exception: {e.Message}"); throw new Exception($"Failed to delete jobs for organisation {organisationId.ToString()} - exception: {e.Message}"); } } } }
36.491667
134
0.533912
[ "MIT" ]
nhsevidence/identity
NICE.Identity.Authorisation.WebAPI/Services/JobsService.cs
4,381
C#
using RimWorld; using System; using System.Linq; using System.Collections.Generic; using UnityEngine; using Verse; using AbilityUser; namespace TorannMagic { [StaticConstructorOnStartup] public class FlyingObject_DemonFlight : Projectile { private static readonly Color wingColor = new Color(10f, 10f, 10f); private static readonly Material wingsNS = MaterialPool.MatFrom("Other/demonwings_up", ShaderDatabase.Transparent); private static readonly Material wingsE = MaterialPool.MatFrom("Other/demonwings_up_east", ShaderDatabase.Transparent); private static readonly Material wingsW = MaterialPool.MatFrom("Other/demonwings_up_west", ShaderDatabase.Transparent); protected new Vector3 origin; protected new Vector3 destination; protected float speed = 40f; protected new int ticksToImpact; protected Thing assignedTarget; protected Thing flyingThing; public DamageInfo? impactDamage; public bool damageLaunched = true; public bool explosion = false; public int timesToDamage = 3; public int weaponDmg = 0; private int wingDelay = 0; private bool wingDisplay = true; IntVec3 expCell1; IntVec3 expCell2; float hyp = 0; float angleRad = 0; float angleDeg = 0; float xProb; bool xflag = false; bool zflag = false; Pawn pawn; private int verVal; private int pwrVal; private float arcaneDmg = 1; TMPawnSummoned newPawn = new TMPawnSummoned(); protected new int StartingTicksToImpact { get { int num = Mathf.RoundToInt((this.origin - this.destination).magnitude / (this.speed / 100f)); bool flag = num < 1; if (flag) { num = 1; } return num; } } protected new IntVec3 DestinationCell { get { return new IntVec3(this.destination); } } public new Vector3 ExactPosition { get { Vector3 b = (this.destination - this.origin) * (1f - (float)this.ticksToImpact / (float)this.StartingTicksToImpact); return this.origin + b + Vector3.up * this.def.Altitude; } } public new Quaternion ExactRotation { get { return Quaternion.LookRotation(this.destination - this.origin); } } public override Vector3 DrawPos { get { return this.ExactPosition; } } public override void ExposeData() { base.ExposeData(); Scribe_Values.Look<Vector3>(ref this.origin, "origin", default(Vector3), false); Scribe_Values.Look<Vector3>(ref this.destination, "destination", default(Vector3), false); Scribe_Values.Look<int>(ref this.ticksToImpact, "ticksToImpact", 0, false); Scribe_Values.Look<int>(ref this.timesToDamage, "timesToDamage", 0, false); Scribe_Values.Look<int>(ref this.verVal, "verVal", 0, false); Scribe_Values.Look<int>(ref this.pwrVal, "pwrVal", 0, false); Scribe_Values.Look<bool>(ref this.damageLaunched, "damageLaunched", true, false); Scribe_Values.Look<bool>(ref this.explosion, "explosion", false, false); Scribe_References.Look<Thing>(ref this.assignedTarget, "assignedTarget", false); Scribe_References.Look<Pawn>(ref this.pawn, "pawn", false); Scribe_Deep.Look<Thing>(ref this.flyingThing, "flyingThing", new object[0]); } private void Initialize() { if (pawn != null) { FleckMaker.Static(pawn.TrueCenter(), pawn.Map, FleckDefOf.ExplosionFlash, 12f); SoundDefOf.Ambient_AltitudeWind.sustainFadeoutTime.Equals(30.0f); FleckMaker.ThrowDustPuff(pawn.Position, pawn.Map, Rand.Range(1.2f, 1.8f)); expCell1 = this.DestinationCell; expCell2 = this.DestinationCell; XProb(this.DestinationCell, this.origin); } //flyingThing.ThingID += Rand.Range(0, 2147).ToString(); } public void Launch(Thing launcher, LocalTargetInfo targ, Thing flyingThing, DamageInfo? impactDamage) { this.Launch(launcher, base.Position.ToVector3Shifted(), targ, flyingThing, impactDamage); } public void Launch(Thing launcher, LocalTargetInfo targ, Thing flyingThing) { this.Launch(launcher, base.Position.ToVector3Shifted(), targ, flyingThing, null); } public void Launch(Thing launcher, Vector3 origin, LocalTargetInfo targ, Thing flyingThing, DamageInfo? newDamageInfo = null) { Hediff invul = new Hediff(); invul.def = TorannMagicDefOf.TM_HediffInvulnerable; invul.Severity = 5; bool spawned = flyingThing.Spawned; pawn = launcher as Pawn; pawn.health.AddHediff(invul, null, null); pwrVal = 2; verVal = 2; if (spawned) { flyingThing.DeSpawn(); } // ModOptions.Constants.SetPawnInFlight(true); // this.origin = origin; this.impactDamage = newDamageInfo; this.flyingThing = flyingThing; bool flag = targ.Thing != null; if (flag) { this.assignedTarget = targ.Thing; } this.destination = targ.Cell.ToVector3Shifted() + new Vector3(Rand.Range(-0.3f, 0.3f), 0f, Rand.Range(-0.3f, 0.3f)); this.ticksToImpact = this.StartingTicksToImpact; this.Initialize(); } public override void Tick() { //base.Tick(); Vector3 exactPosition = this.ExactPosition; this.ticksToImpact--; bool flag = !this.ExactPosition.InBounds(base.Map); if (flag) { this.ticksToImpact++; base.Position = this.ExactPosition.ToIntVec3(); this.Destroy(DestroyMode.Vanish); } else { base.Position = this.ExactPosition.ToIntVec3(); FleckMaker.ThrowDustPuff(base.Position, base.Map, Rand.Range(0.8f, 1.2f)); bool flag2 = this.ticksToImpact <= 0; if (flag2) { bool flag3 = this.DestinationCell.InBounds(base.Map); if (flag3) { base.Position = this.DestinationCell; } this.ImpactSomething(); } } } public override void Draw() { bool flag = this.flyingThing != null; if (flag) { bool flag2 = this.flyingThing is Pawn; if (flag2) { Vector3 arg_2B_0 = this.DrawPos; bool flag3 = false; if (flag3) { return; } bool flag4 = !this.DrawPos.ToIntVec3().IsValid; if (flag4) { return; } Pawn pawn = this.flyingThing as Pawn; pawn.Drawer.DrawAt(this.DrawPos); if (wingDisplay) { if (wingDelay < 5) { DrawWings(this.DrawPos, pawn, 10); wingDelay++; } else { wingDelay = 0; wingDisplay = false; } } else { if (wingDelay < 3) { wingDelay++; } else { wingDelay = 0; wingDisplay = true; } } } else { Graphics.DrawMesh(MeshPool.plane10, this.DrawPos, this.ExactRotation, this.flyingThing.def.DrawMatSingle, 0); } base.Comps_PostDraw(); } } private void DrawWings(Vector3 pawnVec, Pawn flyingPawn, int magnitude) { bool flag = !pawn.Dead && !pawn.Downed; if (flag) { float num = Mathf.Lerp(1.2f, 1.55f, magnitude); Vector3 vector = pawnVec; vector.y = Altitudes.AltitudeFor(AltitudeLayer.MoteOverhead); float angle = (float)Rand.Range(0, 360); Vector3 s = new Vector3(5f, 5f, 5f); Matrix4x4 matrix = default(Matrix4x4); matrix.SetTRS(vector, Quaternion.AngleAxis(0f, Vector3.up), s); if (flyingPawn.Rotation == Rot4.South || flyingPawn.Rotation == Rot4.North) { Graphics.DrawMesh(MeshPool.plane10, matrix, FlyingObject_DemonFlight.wingsNS, 0); } if (flyingPawn.Rotation == Rot4.East) { Graphics.DrawMesh(MeshPool.plane10, matrix, FlyingObject_DemonFlight.wingsE, 0); } if (flyingPawn.Rotation == Rot4.West) { Graphics.DrawMesh(MeshPool.plane10, matrix, FlyingObject_DemonFlight.wingsW, 0); } } } private void ImpactSomething() { bool flag = this.assignedTarget != null; if (flag) { Pawn pawn = this.assignedTarget as Pawn; bool flag2 = pawn != null && pawn.GetPosture() != PawnPosture.Standing && (this.origin - this.destination).MagnitudeHorizontalSquared() >= 20.25f && Rand.Value > 0.2f; if (flag2) { this.Impact(null); } else { this.Impact(this.assignedTarget); } } else { this.Impact(null); } } protected new void Impact(Thing hitThing) { bool flag = hitThing == null; if (flag) { Pawn pawn; bool flag2 = (pawn = (base.Position.GetThingList(base.Map).FirstOrDefault((Thing x) => x == this.assignedTarget) as Pawn)) != null; if (flag2) { hitThing = pawn; } } bool hasValue = this.impactDamage.HasValue; if (hasValue) { for (int i = 0; i < this.timesToDamage; i++) { bool flag3 = this.damageLaunched; if (flag3) { this.flyingThing.TakeDamage(this.impactDamage.Value); } else { hitThing.TakeDamage(this.impactDamage.Value); } } bool flag4 = this.explosion; if (flag4) { GenExplosion.DoExplosion(base.Position, base.Map, 0.9f, DamageDefOf.Stun, this, -1, 0, null, null, null, null, null, 0f, 1, false, null, 0f, 1, 0f, false); } } try { SoundDefOf.Ambient_AltitudeWind.sustainFadeoutTime.Equals(30.0f); this.FireExplosion(pwrVal, verVal, base.Position, base.Map, (1.2f + (float)(verVal * .8f))); FleckMaker.ThrowSmoke(pawn.Position.ToVector3(), base.Map, (0.8f + (float)(verVal * .8f))); for (int i = 0; i < (2 + verVal); i++) { expCell1 = GetNewPos(expCell1, this.origin.x <= this.DestinationCell.x, this.origin.z <= this.DestinationCell.z, false, 0, 0, xProb, 1 - xProb); FleckMaker.ThrowSmoke(expCell1.ToVector3(), base.Map, 1.6f); expCell2 = GetNewPos(expCell2, this.origin.x <= this.DestinationCell.x, this.origin.z <= this.DestinationCell.z, false, 0, 0, 1 - xProb, xProb); FleckMaker.ThrowSmoke(expCell2.ToVector3(), base.Map, 1.6f); } for (int i = 0; i < (4 + (3 * verVal)); i++) { CellRect cellRect = CellRect.CenteredOn(expCell1, (1 + verVal)); cellRect.ClipInsideMap(base.Map); IntVec3 randomCell = cellRect.RandomCell; this.FireExplosion(pwrVal, verVal, randomCell, base.Map, .4f); cellRect = CellRect.CenteredOn(expCell2, (1 + verVal)); randomCell = cellRect.RandomCell; this.FireExplosion(pwrVal, verVal, randomCell, base.Map, .4f); } GenSpawn.Spawn(this.flyingThing, base.Position, base.Map); ModOptions.Constants.SetPawnInFlight(false); Pawn p = this.flyingThing as Pawn; RemoveInvul(p); this.Destroy(DestroyMode.Vanish); } catch { GenSpawn.Spawn(this.flyingThing, base.Position, base.Map); ModOptions.Constants.SetPawnInFlight(false); Pawn p = this.flyingThing as Pawn; RemoveInvul(p); this.Destroy(DestroyMode.Vanish); } } protected void FireExplosion(int pwr, int ver, IntVec3 pos, Map map, float radius) { ThingDef def = this.def; Explosion(pwr, pos, map, radius, DamageDefOf.Burn, this.pawn, null, def, ThingDefOf.Explosion, null, 0.3f, 1, false, null, 0f, 1); } public void Explosion(int pwr, IntVec3 center, Map map, float radius, DamageDef damType, Thing instigator, SoundDef explosionSound = null, ThingDef projectile = null, ThingDef source = null, ThingDef postExplosionSpawnThingDef = null, float postExplosionSpawnChance = 0f, int postExplosionSpawnThingCount = 1, bool applyDamageToExplosionCellsNeighbors = false, ThingDef preExplosionSpawnThingDef = null, float preExplosionSpawnChance = 0f, int preExplosionSpawnThingCount = 1) { System.Random rnd = new System.Random(); int modDamAmountRand = GenMath.RoundRandom(rnd.Next(6 + pwr, 13 + (4 * pwr))); modDamAmountRand *= Mathf.RoundToInt(this.arcaneDmg); if (map == null) { Log.Warning("Tried to do explosion in a null map."); return; } Explosion explosion = (Explosion)GenSpawn.Spawn(ThingDefOf.Explosion, center, map); explosion.damageFalloff = false; explosion.chanceToStartFire = 0.0f; explosion.Position = center; explosion.radius = radius; explosion.damType = damType; explosion.instigator = instigator; explosion.damAmount = ((projectile == null) ? GenMath.RoundRandom((float)damType.defaultDamage) : modDamAmountRand); explosion.weapon = source; explosion.preExplosionSpawnThingDef = preExplosionSpawnThingDef; explosion.preExplosionSpawnChance = preExplosionSpawnChance; explosion.preExplosionSpawnThingCount = preExplosionSpawnThingCount; explosion.postExplosionSpawnThingDef = postExplosionSpawnThingDef; explosion.postExplosionSpawnChance = postExplosionSpawnChance; explosion.postExplosionSpawnThingCount = postExplosionSpawnThingCount; explosion.applyDamageToExplosionCellsNeighbors = applyDamageToExplosionCellsNeighbors; explosion.StartExplosion(explosionSound, null); } private void XProb(IntVec3 target, Vector3 origin) { hyp = Mathf.Sqrt((Mathf.Pow(origin.x - target.x, 2)) + (Mathf.Pow(origin.z - target.z, 2))); angleRad = Mathf.Asin(Mathf.Abs(origin.x - target.x) / hyp); angleDeg = Mathf.Rad2Deg * angleRad; xProb = angleDeg / 90; } private IntVec3 GetNewPos(IntVec3 curPos, bool xdir, bool zdir, bool halfway, float zvar, float xvar, float xguide, float zguide) { float rand = (float)Rand.Range(0, 100); bool flagx = rand <= ((xguide + Mathf.Abs(xvar)) * 100) && !xflag; bool flagz = rand <= ((zguide + Mathf.Abs(zvar)) * 100) && !zflag; if (halfway) { xvar = (-1 * xvar); zvar = (-1 * zvar); } if (xdir && zdir) { //top right if (flagx) { if (xguide + xvar >= 0) { curPos.x++; } else { curPos.x--; } } if (flagz) { if (zguide + zvar >= 0) { curPos.z++; } else { curPos.z--; } } } if (xdir && !zdir) { //bottom right if (flagx) { if (xguide + xvar >= 0) { curPos.x++; } else { curPos.x--; } } if (flagz) { if ((-1 * zguide) + zvar >= 0) { curPos.z++; } else { curPos.z--; } } } if (!xdir && zdir) { //top left if (flagx) { if ((-1 * xguide) + xvar >= 0) { curPos.x++; } else { curPos.x--; } } if (flagz) { if (zguide + zvar >= 0) { curPos.z++; } else { curPos.z--; } } } if (!xdir && !zdir) { //bottom left if (flagx) { if ((-1 * xguide) + xvar >= 0) { curPos.x++; } else { curPos.x--; } } if (flagz) { if ((-1 * zguide) + zvar >= 0) { curPos.z++; } else { curPos.z--; } } } else { //no direction identified } return curPos; //return curPos; } private void RemoveInvul(Pawn abilityUser) { List<Hediff> list = new List<Hediff>(); List<Hediff> arg_32_0 = list; IEnumerable<Hediff> arg_32_1; if (abilityUser == null) { arg_32_1 = null; } else { Pawn_HealthTracker expr_1A = abilityUser.health; if (expr_1A == null) { arg_32_1 = null; } else { HediffSet expr_26 = expr_1A.hediffSet; arg_32_1 = ((expr_26 != null) ? expr_26.hediffs : null); } } arg_32_0.AddRange(arg_32_1); Pawn expr_3E = abilityUser; int? arg_84_0; if (expr_3E == null) { arg_84_0 = null; } else { Pawn_HealthTracker expr_52 = expr_3E.health; if (expr_52 == null) { arg_84_0 = null; } else { HediffSet expr_66 = expr_52.hediffSet; arg_84_0 = ((expr_66 != null) ? new int?(expr_66.hediffs.Count<Hediff>()) : null); } } bool flag = (arg_84_0 ?? 0) > 0; if (flag) { foreach (Hediff current in list) { if (current.def.defName == "Burn") { current.Severity = -5; } if (current.def.defName == "TM_HediffInvulnerable") { current.Severity = -5; return; } } } list.Clear(); list = null; } } }
37.110721
484
0.47921
[ "BSD-3-Clause" ]
TorannD/TMagic
Source/TMagic/TMagic/FlyingObject_DemonFlight.cs
21,118
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; using System.Reflection; using System.Windows.Forms; using System.Security.AccessControl; using System.Security.Principal; using Microsoft.Win32; namespace Charlotte.Commons { public static class ProcMain { // APP_IDENT の衝突の解消 -> t20210105_SolveUUIDCollision public const string APP_IDENT = "{ebf8c57b-0d72-476e-b45c-aec266a1bb87}"; // アプリ毎に変更する。 public const string APP_TITLE = "Elsa20200001-Game"; public static string SelfFile; public static string SelfDir; public static ArgsReader ArgsReader; public static void CUIMain(Action<ArgsReader> mainFunc) { try { WriteLog = message => Console.WriteLine("[" + DateTime.Now + "] " + message); SelfFile = Assembly.GetEntryAssembly().Location; SelfDir = Path.GetDirectoryName(SelfFile); WorkingDir.Root = WorkingDir.CreateProcessRoot(); ArgsReader = GetArgsReader(); mainFunc(ArgsReader); WorkingDir.Root.Delete(); WorkingDir.Root = null; } catch (Exception e) { WriteLog(e); } } public static void GUIMain(Func<Form> getMainForm) { Application.ThreadException += new ThreadExceptionEventHandler(ApplicationThreadException); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomainUnhandledException); SystemEvents.SessionEnding += new SessionEndingEventHandler(SessionEnding); //WriteLog = message => { }; SelfFile = Assembly.GetEntryAssembly().Location; SelfDir = Path.GetDirectoryName(SelfFile); Mutex procMutex = new Mutex(false, APP_IDENT); if (procMutex.WaitOne(0)) { if (GlobalProcMtx.Create(APP_IDENT, APP_TITLE)) { CheckSelfFile(); Directory.SetCurrentDirectory(SelfDir); CheckLogonUserAndTmp(); WorkingDir.Root = WorkingDir.CreateProcessRoot(); ArgsReader = GetArgsReader(); // core > Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(getMainForm()); // < core WorkingDir.Root.Delete(); WorkingDir.Root = null; GlobalProcMtx.Release(); } procMutex.ReleaseMutex(); } procMutex.Close(); } public static Action<object> WriteLog = message => { }; private static ArgsReader GetArgsReader() { return new ArgsReader(Environment.GetCommandLineArgs(), 1); } private static void ApplicationThreadException(object sender, ThreadExceptionEventArgs e) { try { MessageBox.Show( "[Application_ThreadException]\n" + e.Exception, APP_TITLE + " / Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } catch { } Environment.Exit(1); } private static void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e) { try { MessageBox.Show( "[CurrentDomain_UnhandledException]\n" + e.ExceptionObject, APP_TITLE + " / Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } catch { } Environment.Exit(2); } private static void SessionEnding(object sender, SessionEndingEventArgs e) { Environment.Exit(3); } private static void CheckSelfFile() { string file = SelfFile; Encoding SJIS = Encoding.GetEncoding(932); if (file != SJIS.GetString(SJIS.GetBytes(file))) { MessageBox.Show( "Shift_JIS に変換出来ない文字を含むパスからは実行できません。", APP_TITLE + " / エラー", MessageBoxButtons.OK, MessageBoxIcon.Error ); Environment.Exit(4); } if (file.Substring(1, 2) != ":\\") { MessageBox.Show( "ネットワークパスからは実行できません。", APP_TITLE + " / エラー", MessageBoxButtons.OK, MessageBoxIcon.Error ); Environment.Exit(5); } } private static void CheckLogonUserAndTmp() { string userName = Environment.GetEnvironmentVariable("UserName"); Encoding SJIS = Encoding.GetEncoding(932); if ( userName == null || userName == "" || userName != SJIS.GetString(SJIS.GetBytes(userName)) || userName.StartsWith(" ") || userName.EndsWith(" ") ) { MessageBox.Show( "Windows ログオン・ユーザー名に問題があります。", APP_TITLE + " / エラー", MessageBoxButtons.OK, MessageBoxIcon.Error ); Environment.Exit(7); } string tmp = Environment.GetEnvironmentVariable("TMP"); if ( tmp == null || tmp == "" || tmp != SJIS.GetString(SJIS.GetBytes(tmp)) || //tmp.Length < 3 || tmp.Length < 4 || // ルートDIR禁止 tmp[1] != ':' || tmp[2] != '\\' || !Directory.Exists(tmp) || tmp.Contains(' ') ) { MessageBox.Show( "環境変数 TMP に問題があります。", APP_TITLE + " / エラー", MessageBoxButtons.OK, MessageBoxIcon.Error ); Environment.Exit(8); } } private class GlobalProcMtx { private static Mutex ProcMtx; public static bool Create(string procMtxName, string title) { try { MutexSecurity security = new MutexSecurity(); security.AddAccessRule( new MutexAccessRule( new SecurityIdentifier( WellKnownSidType.WorldSid, null ), MutexRights.FullControl, AccessControlType.Allow ) ); bool createdNew; ProcMtx = new Mutex(false, @"Global\Global_" + procMtxName, out createdNew, security); if (ProcMtx.WaitOne(0)) return true; ProcMtx.Close(); ProcMtx = null; } catch (Exception e) { MessageBox.Show("" + e, title + " / Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } CloseProcMtx(); MessageBox.Show( "Already started on the other logon session !", title + " / Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); return false; } public static void Release() { CloseProcMtx(); } private static void CloseProcMtx() { try { ProcMtx.ReleaseMutex(); } catch { } try { ProcMtx.Close(); } catch { } ProcMtx = null; } } } }
21.393617
117
0.650588
[ "MIT" ]
soleil-taruto/Elsa
e20201006_NovelAdv/Elsa20200001/Elsa20200001/Commons/ProcMain.cs
6,253
C#
/****************************************************************************** * Spine Runtimes License Agreement * Last updated January 1, 2020. Replaces all prior versions. * * Copyright (c) 2013-2020, Esoteric Software LLC * * Integration of the Spine Runtimes into software or otherwise creating * derivative works of the Spine Runtimes is permitted under the terms and * conditions of Section 2 of the Spine Editor License Agreement: * http://esotericsoftware.com/spine-editor-license * * Otherwise, it is permitted to integrate the Spine Runtimes into software * or otherwise create derivative works of the Spine Runtimes (collectively, * "Products"), provided that each user of the Products must obtain their own * Spine Editor license and redistribution of the Products in any form must * include this license and copyright notice. * * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) 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 * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ #define AUTOINIT_SPINEREFERENCE using UnityEngine; namespace Spine.Unity { [CreateAssetMenu(menuName = "Spine/Animation Reference Asset", order = 100)] public class AnimationReferenceAsset : ScriptableObject, IHasSkeletonDataAsset { const bool QuietSkeletonData = true; [SerializeField] protected SkeletonDataAsset skeletonDataAsset; [SerializeField, SpineAnimation] protected string animationName; private Animation animation; public SkeletonDataAsset SkeletonDataAsset { get { return skeletonDataAsset; } } public Animation Animation { get { #if AUTOINIT_SPINEREFERENCE if (animation == null) Initialize(); #endif return animation; } } public void Initialize () { if (skeletonDataAsset == null) return; this.animation = skeletonDataAsset.GetSkeletonData(AnimationReferenceAsset.QuietSkeletonData).FindAnimation(animationName); if (this.animation == null) Debug.LogWarningFormat("Animation '{0}' not found in SkeletonData : {1}.", animationName, skeletonDataAsset.name); } public static implicit operator Animation (AnimationReferenceAsset asset) { return asset.Animation; } } }
42.641791
145
0.726986
[ "MIT" ]
BaekNothing/Dalpangyeekiwoogi
Assets/Spine/Runtime/spine-unity/Asset Types/AnimationReferenceAsset.cs
2,857
C#
using System; using System.IO; using Elide.Core; using Elide.Environment; using Elide.Scintilla; using Elide.Scintilla.ObjectModel; using System.Collections.Generic; namespace Elide.TextEditor { public abstract class TextDocument : Document { private SciDocument sciDoc; protected TextDocument(FileInfo fileInfo, SciDocument sciDoc) : base(fileInfo) { this.sciDoc = sciDoc; } protected TextDocument(string title, SciDocument sciDoc) : base(title) { this.sciDoc = sciDoc; } public override void Dispose() { if (sciDoc != null) { sciDoc.Dispose(); sciDoc = null; base.Dispose(); } } public override void Close() { DocumentClosed(this); } internal void ChangeFile(FileInfo fileInfo) { FileInfo = fileInfo; } public SciDocument GetSciDocument() { return sciDoc; } public override bool IsDirty { get; set; } internal int FirstVisibleLine { get; set; } internal IEnumerable<TextSelection> Selections { get; set; } internal event Action<TextDocument> DocumentClosed; } }
23.288136
87
0.54294
[ "MIT" ]
vorov2/ela
Elide/Elide.TextEditor/TextDocument.cs
1,376
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("Cil.Todo.Data.Model")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Cil.Todo.Data.Model")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("67415045-4107-418d-b112-232e42383293")] // 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.743444
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
NazliAksoy/todo
Data/Cil.Todo.Data.Model/Properties/AssemblyInfo.cs
1,414
C#
using System; using System.Collections.Specialized; using System.Diagnostics; using System.Net; using System.Text; using System.Threading.Tasks; using Nano.Web.Core; using Nano.Web.Core.Host.HttpListener; using NUnit.Framework; namespace Nano.Tests.SpeedTests { [TestFixture] public class FuncSpeedTest { [Explicit] [TestCase( 1 )] [TestCase( 100 )] [TestCase( 1000 )] [TestCase( 10000 )] [TestCase( 100000 )] public void SimpleSpeedTest( int requestCount ) { ServicePointManager.UseNagleAlgorithm = false; ServicePointManager.DefaultConnectionLimit = int.MaxValue; var nanoConfiguration = new NanoConfiguration(); nanoConfiguration.AddFunc( "/Customer/CreateCustomer", context => new { CustomerId = 1, FirstName = context.Request.GetRequestParameterValue( "firstName" ), LastName = context.Request.GetRequestParameterValue( "lastName" ) } ); using( HttpListenerNanoServer.Start( nanoConfiguration, "http://localhost:4545" ) ) { var parameters = new NameValueCollection { { "firstName", "Clark" }, { "lastName", "Kent" } }; var stopwatch = Stopwatch.StartNew(); Parallel.For( 0, requestCount, i => { using( var client = new WebClient() ) { byte[] responsebytes = client.UploadValues( "http://localhost:4545/Customer/CreateCustomer", "POST", parameters ); string responsebody = Encoding.UTF8.GetString( responsebytes ); if( requestCount == 1 ) Trace.WriteLine( responsebody ); } } ); var elapsedTime = stopwatch.Elapsed; Trace.WriteLine( string.Format( "{0} requests completed in {1}", requestCount, elapsedTime.GetFormattedTime() ) ); var averageRequestTimeInMilliseconds = elapsedTime.TotalMilliseconds / requestCount; var averageRequestTimeSpan = TimeSpan.FromTicks( (long)( TimeSpan.TicksPerMillisecond * averageRequestTimeInMilliseconds ) ); Trace.WriteLine( string.Format( "Average request time: {0}", averageRequestTimeSpan.GetFormattedTime() ) ); } } } }
41.431034
141
0.596754
[ "MIT" ]
revnique/Nano
src/Nano.Tests/SpeedTests/FuncSpeedTest.cs
2,405
C#
/* MIT License Copyright(c) 2014-2018 Infragistics, 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 Mono.Cecil; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BreakingChangesDetector { internal class TypeReferenceEqualityComparer : IEqualityComparer<TypeReference> { public static readonly TypeReferenceEqualityComparer Instance = new TypeReferenceEqualityComparer(); private TypeReferenceEqualityComparer() { } public bool Equals(TypeReference x, TypeReference y) { return MetadataResolver.AreSame(x, y); } public int GetHashCode(TypeReference obj) { return MetadataResolver.GetHashCode(obj); } } }
34.686275
102
0.765404
[ "MIT" ]
IG-JM/BreakingChangesDetector
BreakingChangesDetector/TypeReferenceEqualityComparer.cs
1,771
C#
using OmniSharp; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("OmniSharp" + OmniSharpPublicKey.Key)] [assembly: InternalsVisibleTo("OmniSharp.Host" + OmniSharpPublicKey.Key)] [assembly: InternalsVisibleTo("OmniSharp.MSBuild" + OmniSharpPublicKey.Key)] [assembly: InternalsVisibleTo("OmniSharp.Roslyn" + OmniSharpPublicKey.Key)] [assembly: InternalsVisibleTo("OmniSharp.Roslyn.CSharp" + OmniSharpPublicKey.Key)] [assembly: InternalsVisibleTo("OmniSharp.DotNetTest.Tests" + OmniSharpPublicKey.Key)] [assembly: InternalsVisibleTo("OmniSharp.Tests" + OmniSharpPublicKey.Key)]
54.363636
85
0.817726
[ "MIT" ]
Anakael/omnisharp-roslyn
src/OmniSharp.Shared/AssemblyInfo.cs
600
C#
namespace SKIT.FlurlHttpClient.Wechat.Api.Models { /// <summary> /// <para>表示 [POST] /cgi-bin/account/fastregister 接口的请求。</para> /// </summary> public class CgibinAccountFastRegisterRequest : WechatApiRequest, IMapResponse<CgibinAccountFastRegisterRequest, CgibinAccountFastRegisterResponse> { /// <summary> /// 获取或设置公众号扫码授权的凭证。 /// </summary> [Newtonsoft.Json.JsonProperty("ticket")] [System.Text.Json.Serialization.JsonPropertyName("ticket")] public string Ticket { get; set; } = string.Empty; } }
35.8125
151
0.666667
[ "MIT" ]
vst-h/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat.Api/Models/CgibinAccount/CgibinAccountFastRegisterRequest.cs
623
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("Sport.Scoring.Tennis.Console")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Sport.Scoring.Tennis.Console")] [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("01f269a2-c1d9-4c46-b65e-a8af69a2eeb5")] // 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.621622
84
0.746676
[ "Apache-2.0" ]
oromand/tennis-scoring
Sport.Scoring.Tennis.Console/Properties/AssemblyInfo.cs
1,432
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RotateManipulator.cs" company="Helix 3D Toolkit"> // http://helixtoolkit.codeplex.com, license: MIT // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace HelixToolkit.Wpf { using System; using System.Windows; using System.Windows.Input; using System.Windows.Media.Media3D; /// <summary> /// A visual element containing a manipulator that can rotate around an axis. /// </summary> public class RotateManipulator : Manipulator { /// <summary> /// Identifies the <see cref="Axis"/> dependency property. /// </summary> public static readonly DependencyProperty AxisProperty = DependencyProperty.Register( "Axis", typeof(Vector3D), typeof(RotateManipulator), new UIPropertyMetadata(new Vector3D(0, 0, 1), GeometryChanged)); /// <summary> /// Identifies the <see cref="Diameter"/> dependency property. /// </summary> public static readonly DependencyProperty DiameterProperty = DependencyProperty.Register( "Diameter", typeof(double), typeof(RotateManipulator), new UIPropertyMetadata(3.0, GeometryChanged)); /// <summary> /// Identifies the <see cref="InnerDiameter"/> dependency property. /// </summary> public static readonly DependencyProperty InnerDiameterProperty = DependencyProperty.Register( "InnerDiameter", typeof(double), typeof(RotateManipulator), new UIPropertyMetadata(2.5, GeometryChanged)); /// <summary> /// Identifies the <see cref="Length"/> dependency property. /// </summary> public static readonly DependencyProperty LengthProperty = DependencyProperty.Register( "Length", typeof(double), typeof(RotateManipulator), new UIPropertyMetadata(0.1, GeometryChanged)); /// <summary> /// Identifies the <see cref="Pivot"/> dependency property. /// </summary> public static readonly DependencyProperty PivotProperty = DependencyProperty.Register( "Pivot", typeof(Point3D), typeof(Manipulator), new PropertyMetadata(new Point3D())); /// <summary> /// The last point. /// </summary> private Point3D lastPoint; /// <summary> /// Initializes a new instance of the <see cref = "RotateManipulator" /> class. /// </summary> public RotateManipulator() { this.Model = new GeometryModel3D(); this.Visual3DModel = this.Model; this.OnGeometryChanged(); } /// <summary> /// Gets or sets the rotation axis. /// </summary> /// <value>The axis.</value> public Vector3D Axis { get { return (Vector3D)this.GetValue(AxisProperty); } set { this.SetValue(AxisProperty, value); } } /// <summary> /// Gets or sets the diameter. /// </summary> /// <value>The diameter.</value> public double Diameter { get { return (double)this.GetValue(DiameterProperty); } set { this.SetValue(DiameterProperty, value); } } /// <summary> /// Gets or sets the inner diameter. /// </summary> /// <value>The inner diameter.</value> public double InnerDiameter { get { return (double)this.GetValue(InnerDiameterProperty); } set { this.SetValue(InnerDiameterProperty, value); } } /// <summary> /// Gets or sets the length of the cylinder. /// </summary> /// <value>The length.</value> public double Length { get { return (double)this.GetValue(LengthProperty); } set { this.SetValue(LengthProperty, value); } } /// <summary> /// Gets or sets the pivot point of the manipulator. /// </summary> /// <value> The position. </value> public Point3D Pivot { get { return (Point3D)this.GetValue(PivotProperty); } set { this.SetValue(PivotProperty, value); } } /// <summary> /// The on geometry changed. /// </summary> protected override void OnGeometryChanged() { var mb = new MeshBuilder(false, false); var p0 = new Point3D(0, 0, 0); var d = this.Axis; d.Normalize(); var p1 = p0 - (d * this.Length * 0.5); var p2 = p0 + (d * this.Length * 0.5); mb.AddPipe(p1, p2, this.InnerDiameter, this.Diameter, 60); this.Model.Geometry = mb.ToMesh(); } /// <summary> /// The on mouse down. /// </summary> /// <param name="e"> /// The event arguments. /// </param> protected override void OnMouseDown(MouseButtonEventArgs e) { base.OnMouseDown(e); var hitPlaneOrigin = this.ToWorld(this.Position); var hitPlaneNormal = this.ToWorld(this.Axis); var p = e.GetPosition(this.ParentViewport); var hitPoint = this.GetHitPlanePoint(p, hitPlaneOrigin, hitPlaneNormal); if (hitPoint != null) { this.lastPoint = this.ToLocal(hitPoint.Value); } } /// <summary> /// The on mouse move. /// </summary> /// <param name="e"> /// The event arguments. /// </param> protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (this.IsMouseCaptured) { var hitPlaneOrigin = this.ToWorld(this.Position); var hitPlaneNormal = this.ToWorld(this.Axis); var position = e.GetPosition(this.ParentViewport); var hitPoint = this.GetHitPlanePoint(position, hitPlaneOrigin, hitPlaneNormal); if (hitPoint == null) { return; } var currentPoint = this.ToLocal(hitPoint.Value); var v = this.lastPoint - this.Position; var u = currentPoint - this.Position; v.Normalize(); u.Normalize(); var currentAxis = Vector3D.CrossProduct(u, v); double sign = -Vector3D.DotProduct(this.Axis, currentAxis); double theta = Math.Sign(sign) * Math.Asin(currentAxis.Length) / Math.PI * 180; this.Value += theta; if (this.TargetTransform != null) { var rotateTransform = new RotateTransform3D(new AxisAngleRotation3D(this.Axis, theta), Pivot); this.TargetTransform = Transform3DHelper.CombineTransform(rotateTransform, this.TargetTransform); } hitPoint = this.GetHitPlanePoint(position, hitPlaneOrigin, hitPlaneNormal); if (hitPoint != null) { this.lastPoint = this.ToLocal(hitPoint.Value); } } } } }
33.110638
120
0.508546
[ "BSD-3-Clause" ]
BigJohnn/KinectUI
HelixToolkit.Wpf/Visual3Ds/Manipulators/RotateManipulator.cs
7,783
C#
using EfficientDynamoDb.DocumentModel; namespace EfficientDynamoDb.Operations.BatchWriteItem { public class BatchWritePutRequest { /// <summary> /// A map of attributes and their values. Each entry in this map consists of an attribute name and an attribute value. /// </summary> public Document Item { get; } public BatchWritePutRequest(Document item) => Item = item; } }
30.428571
127
0.678404
[ "MIT" ]
AllocZero/EfficientDynamoDb
src/EfficientDynamoDb/Operations/BatchWriteItem/BatchWritePutRequest.cs
426
C#
using NUnit.Framework; using System.Collections.Generic; namespace csharp { [TestFixture] public class GildedRoseTest { [Test] public void foo() { IList<Item> Items = new List<Item> { new Item { Name = "fixme", SellIn = 0, Quality = 0 } }; GildedRose app = new GildedRose(Items); app.UpdateQuality(); Assert.AreEqual("fixme", Items[0].Name); } } }
23.473684
104
0.556054
[ "MIT" ]
empalacios/GildedRose-Refactoring-Kata
csharp/GildedRoseTest.cs
448
C#
// This is an independent project of an individual developer. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com //------------------------------------------------------------------------------ // <copyright company="DMV"> // Copyright 2014 Ded Medved // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //------------------------------------------------------------------------------ using System.Collections.Generic; using Microsoft.SqlServer.Dac.CodeAnalysis; using Microsoft.SqlServer.Dac.Model; using Microsoft.SqlServer.TransactSql.ScriptDom; namespace Cheburashka { public static class DmvRuleSetup { // public static void RuleSetup(SqlRuleExecutionContext context, out List<SqlRuleProblem> problems, out SqlSchemaModel sqlSchemaModel, out TSqlObject sqlElement, out TSqlFragment sqlFragment) public static void RuleSetup(SqlRuleExecutionContext context, out List<SqlRuleProblem> problems, out TSqlModel model, out TSqlFragment sqlFragment, out TSqlObject modelElement) { //DMVSettings.LoadSettings(); // Get Model collation SqlComparer.Comparer = context.SchemaModel.CollationComparer; problems = new List<SqlRuleProblem>(); model = context.SchemaModel; sqlFragment = context.ScriptFragment; modelElement = context.ModelElement; } //public static void RefreshDDLCache(ModelStore sqlSchemaModel) //{ // //DMVSettings.RefreshColumnCache(sqlSchemaModel); // //DMVSettings.RefreshConstraintsAndIndexesCache(sqlSchemaModel); //} public static void GetLocalObjectNameParts(TSqlObject sqlElement, out string objectSchema, out string objectTable) { objectSchema = sqlElement.Name.HasName ? sqlElement.Name.Parts[0] : ""; objectTable = sqlElement.Name.HasName ? sqlElement.Name.Parts[1] : ""; } } }
44.775862
199
0.642665
[ "Apache-2.0" ]
dedmedved/cheburashka
Cheburashka/Rules/Utility Classes/DMVRuleSetup.cs
2,599
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Lclb.Cllb.Interfaces { using Microsoft.Rest; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for Pmuareamarketevents. /// </summary> public static partial class PmuareamarketeventsExtensions { /// <summary> /// Get adoxio_pmuarea_marketevents from adoxio_pmuareas /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioPmuareaid'> /// key: adoxio_pmuareaid of adoxio_pmuarea /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static MicrosoftDynamicsCRMadoxioEventCollection Get(this IPmuareamarketevents operations, string adoxioPmuareaid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.GetAsync(adoxioPmuareaid, top, skip, search, filter, count, orderby, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get adoxio_pmuarea_marketevents from adoxio_pmuareas /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioPmuareaid'> /// key: adoxio_pmuareaid of adoxio_pmuarea /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMadoxioEventCollection> GetAsync(this IPmuareamarketevents operations, string adoxioPmuareaid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(adoxioPmuareaid, top, skip, search, filter, count, orderby, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get adoxio_pmuarea_marketevents from adoxio_pmuareas /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioPmuareaid'> /// key: adoxio_pmuareaid of adoxio_pmuarea /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<MicrosoftDynamicsCRMadoxioEventCollection> GetWithHttpMessages(this IPmuareamarketevents operations, string adoxioPmuareaid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null) { return operations.GetWithHttpMessagesAsync(adoxioPmuareaid, top, skip, search, filter, count, orderby, select, expand, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Get adoxio_pmuarea_marketevents from adoxio_pmuareas /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioPmuareaid'> /// key: adoxio_pmuareaid of adoxio_pmuarea /// </param> /// <param name='adoxioEventid'> /// key: adoxio_eventid of adoxio_event /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static MicrosoftDynamicsCRMadoxioEvent MarketeventsByKey(this IPmuareamarketevents operations, string adoxioPmuareaid, string adoxioEventid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.MarketeventsByKeyAsync(adoxioPmuareaid, adoxioEventid, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get adoxio_pmuarea_marketevents from adoxio_pmuareas /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioPmuareaid'> /// key: adoxio_pmuareaid of adoxio_pmuarea /// </param> /// <param name='adoxioEventid'> /// key: adoxio_eventid of adoxio_event /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMadoxioEvent> MarketeventsByKeyAsync(this IPmuareamarketevents operations, string adoxioPmuareaid, string adoxioEventid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.MarketeventsByKeyWithHttpMessagesAsync(adoxioPmuareaid, adoxioEventid, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get adoxio_pmuarea_marketevents from adoxio_pmuareas /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioPmuareaid'> /// key: adoxio_pmuareaid of adoxio_pmuarea /// </param> /// <param name='adoxioEventid'> /// key: adoxio_eventid of adoxio_event /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<MicrosoftDynamicsCRMadoxioEvent> MarketeventsByKeyWithHttpMessages(this IPmuareamarketevents operations, string adoxioPmuareaid, string adoxioEventid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null) { return operations.MarketeventsByKeyWithHttpMessagesAsync(adoxioPmuareaid, adoxioEventid, select, expand, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } } }
49.143541
519
0.548924
[ "Apache-2.0" ]
BrendanBeachBC/jag-lcrb-carla-public
cllc-interfaces/Dynamics-Autorest/PmuareamarketeventsExtensions.cs
10,271
C#
using System; using UnityEngine; /// <summary> /// An object that can be grabbed and thrown by OVRGrabber. /// </summary> public class OVRCookedCopyGrabbable : OVRCookedGrabbable { [SerializeField] OVRCookedGrabbable grabbablePrefab; public override OVRCookedGrabbable GetGrabbable() { OVRCookedGrabbable copiedGrabbable = GameObject.Instantiate(grabbablePrefab, transform.position, Quaternion.identity); copiedGrabbable.GrabbedKinematic = grabbablePrefab.GetComponent<Rigidbody>().isKinematic; Debug.Log($"Created new copied grabbable. Kinematic: {copiedGrabbable.GrabbedKinematic}"); return copiedGrabbable; } protected override void Start() { base.Start(); } }
28.538462
126
0.726415
[ "MIT" ]
gpiffaretti/ovrcooked
Assets/OVRCooked/Scripts/OVR/OVRCookedCopyGrabbable.cs
744
C#
using Content.Server.GameObjects.Components.Atmos; using Content.Server.GameObjects.Components.Mobs; using Content.Server.GameObjects.Components.Nutrition; using Content.Shared.GameObjects.Components.Damage; using Content.Shared.GameObjects.Verbs; using Robust.Server.Console; using Robust.Server.Interfaces.GameObjects; using Robust.Shared.Interfaces.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; namespace Content.Server.GlobalVerbs { /// <summary> /// Completely removes all damage from the DamageableComponent (heals the mob). /// </summary> [GlobalVerb] class RejuvenateVerb : GlobalVerb { public override bool RequireInteractionRange => false; public override bool BlockedByContainers => false; public override void GetData(IEntity user, IEntity target, VerbData data) { data.Text = Loc.GetString("Rejuvenate"); data.CategoryData = VerbCategories.Debug; data.Visibility = VerbVisibility.Invisible; var groupController = IoCManager.Resolve<IConGroupController>(); if (user.TryGetComponent<IActorComponent>(out var player)) { if (!target.HasComponent<IDamageableComponent>() && !target.HasComponent<HungerComponent>() && !target.HasComponent<ThirstComponent>()) { return; } if (groupController.CanCommand(player.playerSession, "rejuvenate")) { data.Visibility = VerbVisibility.Visible; } } } public override void Activate(IEntity user, IEntity target) { var groupController = IoCManager.Resolve<IConGroupController>(); if (user.TryGetComponent<IActorComponent>(out var player)) { if (groupController.CanCommand(player.playerSession, "rejuvenate")) PerformRejuvenate(target); } } public static void PerformRejuvenate(IEntity target) { if (target.TryGetComponent(out IDamageableComponent damage)) { damage.Heal(); } if (target.TryGetComponent(out HungerComponent hunger)) { hunger.ResetFood(); } if (target.TryGetComponent(out ThirstComponent thirst)) { thirst.ResetThirst(); } if (target.TryGetComponent(out StunnableComponent stun)) { stun.ResetStuns(); } if (target.TryGetComponent(out FlammableComponent flammable)) { flammable.Extinguish(); } if (target.TryGetComponent(out CreamPiedComponent creamPied)) { creamPied.Wash(); } } } }
32.611111
110
0.59046
[ "MIT" ]
AlphaQwerty/space-station-14
Content.Server/GlobalVerbs/RejuvenateVerb.cs
2,937
C#
using Polly; using Polly.Extensions.Http; using System; using System.Net.Http; using System.Threading.Tasks; namespace LocationFromIP.CodeTest.Infrastructure.WeatherApi { internal static class PollyPolicy { internal static IAsyncPolicy<HttpResponseMessage> Create() { var circuitBreaker = CreateCircuitBreaker(); var waitAndRetry = HttpPolicyExtensions.HandleTransientHttpError() .WaitAndRetryAsync(new[] { TimeSpan.FromSeconds(0.5), }); return waitAndRetry.WrapAsync(circuitBreaker); } private static IAsyncPolicy<HttpResponseMessage> CreateCircuitBreaker() { var httpErrors = HttpPolicyExtensions.HandleTransientHttpError() .CircuitBreakerAsync( handledEventsAllowedBeforeBreaking: 10, durationOfBreak: TimeSpan.FromSeconds(10)); var timeouts = Policy.Handle<TaskCanceledException>().CircuitBreakerAsync( exceptionsAllowedBeforeBreaking: 10, durationOfBreak: TimeSpan.FromSeconds(10)); return httpErrors.WrapAsync(timeouts); } } }
32.666667
87
0.61146
[ "MIT" ]
DanHarltey/CodeTest-LocationFromIP
src/LocationFromIP.CodeTest.Infrastructure/WeatherApi/PollyPolicy.cs
1,276
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.Network.V20200801.Outputs { [OutputType] public sealed class VirtualApplianceSkuPropertiesResponse { /// <summary> /// Virtual Appliance Scale Unit. /// </summary> public readonly string? BundledScaleUnit; /// <summary> /// Virtual Appliance Version. /// </summary> public readonly string? MarketPlaceVersion; /// <summary> /// Virtual Appliance Vendor. /// </summary> public readonly string? Vendor; [OutputConstructor] private VirtualApplianceSkuPropertiesResponse( string? bundledScaleUnit, string? marketPlaceVersion, string? vendor) { BundledScaleUnit = bundledScaleUnit; MarketPlaceVersion = marketPlaceVersion; Vendor = vendor; } } }
27.674419
81
0.630252
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Network/V20200801/Outputs/VirtualApplianceSkuPropertiesResponse.cs
1,190
C#
using System.Runtime.Serialization; namespace Service.MarketProduct.Grpc.Models { [DataContract] public class ProductListGrpcResponse { [DataMember(Order = 1)] public MarketProductGrpcModel[] Products { get; set; } } }
20.727273
56
0.763158
[ "MIT" ]
MyJetEducation/Service.MarketProduct
src/Service.MarketProduct.Grpc/Models/ProductListGrpcResponse.cs
230
C#
using System; using System.Collections.Generic; using System.Text; namespace MathObjects { public static class AdditionTime { static public int Sum(int augEnd, int addEnd) { var sum = augEnd + addEnd; return sum; } static public decimal Sum(decimal augEnd, decimal addEnd) { var sum = augEnd + addEnd; return sum; } static public decimal Sum(decimal[] doubleArray) { decimal result = 0; foreach (var x in doubleArray) { result = Sum(result, x); } return result; } static public int Sum(int[] doubleArray) { int result = 0; foreach (var x in doubleArray) { result = Sum(result, x); } return result; } } }
20.021739
65
0.479913
[ "MIT" ]
Rjp76/Calctime
MathObjects/Addition.cs
923
C#
using UnityEngine; using static Assets.Core.Utils.GW; namespace Assets.Core.Controller.Environments { public static partial class GBE { public struct Environment { private const string copyright = "©"; private readonly string ipAddress; private readonly string name; private readonly Protocol protocol; private readonly string supportLink; private readonly int webServerPort; public Environment(string ipAddress, string name, Protocol protocol, string supportLink, int webServerPort) { this.ipAddress = ipAddress; this.name = name; this.protocol = protocol; this.supportLink = supportLink; this.webServerPort = webServerPort; } public string GetCopyright() => string.Format("{0} {1}", copyright, Application.productName); public string GetName() => name; public string GetIpAddress() => ipAddress; public Protocol GetProtocol() => protocol; public string GetSupportLink() => supportLink; public string GetUriString() => string.Format("{0}://{1}{2}", protocol.ToString().ToLower(), ipAddress, webServerPort == 80 ? "" : $":{webServerPort}"); } } }
30.1
110
0.535548
[ "MIT" ]
Devwarlt/r-unity-lite
Assets/Core/Controller/Environments/GBE.Environment.cs
1,508
C#
using System; using System.Text; namespace DoFactory.HeadFirst.State.Gumball { class GumballMachineTestDrive { static void Main(string[] args) { var gumballMachine = new GumballMachine(5); Console.WriteLine(gumballMachine); gumballMachine.InsertQuarter(); gumballMachine.TurnCrank(); Console.WriteLine(gumballMachine); gumballMachine.InsertQuarter(); gumballMachine.EjectQuarter(); gumballMachine.TurnCrank(); Console.WriteLine(gumballMachine); gumballMachine.InsertQuarter(); gumballMachine.TurnCrank(); gumballMachine.InsertQuarter(); gumballMachine.TurnCrank(); gumballMachine.EjectQuarter(); Console.WriteLine(gumballMachine); gumballMachine.InsertQuarter(); gumballMachine.InsertQuarter(); gumballMachine.TurnCrank(); gumballMachine.InsertQuarter(); gumballMachine.TurnCrank(); gumballMachine.InsertQuarter(); gumballMachine.TurnCrank(); Console.WriteLine(gumballMachine); // Wait for user Console.ReadKey(); } } #region GumballMachine public class GumballMachine { private GumballMachineState _state = GumballMachineState.SoldOut; private int _count = 0; public GumballMachine(int count) { this._count = count; if (_count > 0) { _state = GumballMachineState.NoQuarter; } } public void InsertQuarter() { if (_state == GumballMachineState.HasQuarter) { Console.WriteLine("You can't insert another quarter"); } else if (_state == GumballMachineState.NoQuarter) { _state = GumballMachineState.HasQuarter; Console.WriteLine("You inserted a quarter"); } else if (_state == GumballMachineState.SoldOut) { Console.WriteLine("You can't insert a quarter, the machine is sold out"); } else if (_state == GumballMachineState.Sold) { Console.WriteLine("Please wait, we're already giving you a gumball"); } } public void EjectQuarter() { if (_state == GumballMachineState.HasQuarter) { Console.WriteLine("Quarter returned"); _state = GumballMachineState.NoQuarter; } else if (_state == GumballMachineState.NoQuarter) { Console.WriteLine("You haven't inserted a quarter"); } else if (_state == GumballMachineState.Sold) { Console.WriteLine("Sorry, you already turned the crank"); } else if (_state == GumballMachineState.SoldOut) { Console.WriteLine("You can't eject, you haven't inserted a quarter yet"); } } public void TurnCrank() { if (_state == GumballMachineState.Sold) { Console.WriteLine("Turning twice doesn't get you another gumball!"); } else if (_state == GumballMachineState.NoQuarter) { Console.WriteLine("You turned but there's no quarter"); } else if (_state == GumballMachineState.SoldOut) { Console.WriteLine("You turned, but there are no gumballs"); } else if (_state == GumballMachineState.HasQuarter) { Console.WriteLine("You turned..."); _state = GumballMachineState.Sold; Dispense(); } } public void Dispense() { if (_state == GumballMachineState.Sold) { Console.WriteLine("A gumball comes rolling out the slot"); _count = _count - 1; if (_count == 0) { Console.WriteLine("Oops, out of gumballs!"); _state = GumballMachineState.SoldOut; } else { _state = GumballMachineState.NoQuarter; } } else if (_state == GumballMachineState.NoQuarter) { Console.WriteLine("You need to pay first"); } else if (_state == GumballMachineState.SoldOut) { Console.WriteLine("No gumball dispensed"); } else if (_state == GumballMachineState.HasQuarter) { Console.WriteLine("No gumball dispensed"); } } public void Refill(int numGumBalls) { _count = numGumBalls; _state = GumballMachineState.NoQuarter; } public override string ToString() { StringBuilder result = new StringBuilder(); result.Append("\nMighty Gumball, Inc."); result.Append("\nJava-enabled Standing Gumball Model #2004\n"); result.Append("Inventory: " + _count + " gumball"); if (_count != 1) { result.Append("s"); } result.Append("\nMachine is "); if (_state == GumballMachineState.SoldOut) { result.Append("sold out"); } else if (_state == GumballMachineState.NoQuarter) { result.Append("waiting for quarter"); } else if (_state == GumballMachineState.HasQuarter) { result.Append("waiting for turn of crank"); } else if (_state == GumballMachineState.Sold) { result.Append("delivering a gumball"); } result.Append("\n"); return result.ToString(); } } #endregion #region State // State enumercation public enum GumballMachineState { SoldOut, NoQuarter, HasQuarter, Sold } #endregion }
29.896714
89
0.510364
[ "MIT" ]
kiapanahi/famous-design-patterns
Head First/DoFactory.HeadFirst.State.Gumball/GumballMachineTestDrive.cs
6,368
C#
#pragma warning disable SA1107,SA1127,SA1128,SA1402,SA1516,SA1515,SA1600 namespace OfaSchlupfer.MSSQLReflection.AST { using ScriptDom = Microsoft.SqlServer.TransactSql.ScriptDom; public interface IAuthorization { Identifier Owner { get; set; } } }
27
72
0.751852
[ "MIT" ]
FlorianGrimm/OfaSchlupfer
OfaSchlupfer.MSSQLReflection/AST/Nodes/IAuthorization.cs
270
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. To update the generation of this file, modify and re-call LittleBaby.Framework.FixedMathematics.VectorGenerator.Generate() Method. // </auto-generated> //------------------------------------------------------------------------------ namespace LittleBaby.Framework.FixedMathematics { using System; using System.ComponentModel; using System.Runtime.CompilerServices; using Unity.Mathematics; using static Unity.Mathematics.math; using static LittleBaby.Framework.FixedMathematics.fmath; [System.Serializable] public partial struct ulong3 : System.IEquatable<ulong3>, IFormattable { public static readonly ulong3 zero; public static readonly ulong3 one = new ulong3(1UL); public ulong x; public ulong y; public ulong z; [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong3(ulong x, ulong y, ulong z) { this.x = x; this.y = y; this.z = z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong3(ulong x, ulong2 yz) { this.x = x; this.y = yz.x; this.z = yz.y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong3(ulong2 xy, ulong z) { this.x = xy.x; this.y = xy.y; this.z = z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong3(ulong3 xyz) { this.x = xyz.x; this.y = xyz.y; this.z = xyz.z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong3(ulong v) { this.x = v; this.y = v; this.z = v; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong3(bool3 v) { this.x = v.x ? 1UL : 0UL; this.y = v.y ? 1UL : 0UL; this.z = v.z ? 1UL : 0UL; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong3(bool v) { this.x = v ? 1UL : 0UL; this.y = v ? 1UL : 0UL; this.z = v ? 1UL : 0UL; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong3(int3 v) { this.x = (ulong)v.x; this.y = (ulong)v.y; this.z = (ulong)v.z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong3(int v) { this.x = (ulong)v; this.y = (ulong)v; this.z = (ulong)v; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong3(uint3 v) { this.x = (ulong)v.x; this.y = (ulong)v.y; this.z = (ulong)v.z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong3(uint v) { this.x = (ulong)v; this.y = (ulong)v; this.z = (ulong)v; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong3(long3 v) { this.x = (ulong)v.x; this.y = (ulong)v.y; this.z = (ulong)v.z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong3(long v) { this.x = (ulong)v; this.y = (ulong)v; this.z = (ulong)v; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong3(float3 v) { this.x = (ulong)v.x; this.y = (ulong)v.y; this.z = (ulong)v.z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong3(float v) { this.x = (ulong)v; this.y = (ulong)v; this.z = (ulong)v; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong3(double3 v) { this.x = (ulong)v.x; this.y = (ulong)v.y; this.z = (ulong)v.z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong3(double v) { this.x = (ulong)v; this.y = (ulong)v; this.z = (ulong)v; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong3(ffloat3 v) { this.x = (ulong)v.x; this.y = (ulong)v.y; this.z = (ulong)v.z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong3(ffloat v) { this.x = (ulong)v; this.y = (ulong)v; this.z = (ulong)v; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator ulong3(ulong v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator ulong3(bool3 v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator ulong3(bool v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator ulong3(int3 v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator ulong3(int v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator ulong3(uint3 v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator ulong3(uint v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator ulong3(long3 v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator ulong3(long v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator ulong3(float3 v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator ulong3(float v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator ulong3(double3 v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator ulong3(double v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator ulong3(ffloat3 v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator ulong3(ffloat v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator bool3(ulong3 v) { return new bool3(v.x != 0UL, v.y != 0UL, v.z != 0UL); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator int3(ulong3 v) { return new int3((int)v.x, (int)v.y, (int)v.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator uint3(ulong3 v) { return new uint3((uint)v.x, (uint)v.y, (uint)v.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator float3(ulong3 v) { return new float3((float)v.x, (float)v.y, (float)v.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator double3(ulong3 v) { return new double3((double)v.x, (double)v.y, (double)v.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator ++(ulong3 v) { return new ulong3(++v.x, ++v.y, ++v.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator --(ulong3 v) { return new ulong3(--v.x, --v.y, --v.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator ~(ulong3 v) { return new ulong3(~v.x, ~v.y, ~v.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator +(ulong3 lhs, ulong3 rhs) { return new ulong3(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator +(ulong3 lhs, ulong rhs) { return new ulong3(lhs.x + rhs, lhs.y + rhs, lhs.z + rhs); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator +(ulong lhs, ulong3 rhs) { return new ulong3(lhs + rhs.x, lhs + rhs.y, lhs + rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator -(ulong3 lhs, ulong3 rhs) { return new ulong3(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator -(ulong3 lhs, ulong rhs) { return new ulong3(lhs.x - rhs, lhs.y - rhs, lhs.z - rhs); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator -(ulong lhs, ulong3 rhs) { return new ulong3(lhs - rhs.x, lhs - rhs.y, lhs - rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator *(ulong3 lhs, ulong3 rhs) { return new ulong3(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator *(ulong3 lhs, ulong rhs) { return new ulong3(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator *(ulong lhs, ulong3 rhs) { return new ulong3(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator /(ulong3 lhs, ulong3 rhs) { return new ulong3(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator /(ulong3 lhs, ulong rhs) { return new ulong3(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator /(ulong lhs, ulong3 rhs) { return new ulong3(lhs / rhs.x, lhs / rhs.y, lhs / rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator %(ulong3 lhs, ulong3 rhs) { return new ulong3(lhs.x % rhs.x, lhs.y % rhs.y, lhs.z % rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator %(ulong3 lhs, ulong rhs) { return new ulong3(lhs.x % rhs, lhs.y % rhs, lhs.z % rhs); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator %(ulong lhs, ulong3 rhs) { return new ulong3(lhs % rhs.x, lhs % rhs.y, lhs % rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator &(ulong3 lhs, ulong3 rhs) { return new ulong3(lhs.x & rhs.x, lhs.y & rhs.y, lhs.z & rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator &(ulong3 lhs, ulong rhs) { return new ulong3(lhs.x & rhs, lhs.y & rhs, lhs.z & rhs); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator &(ulong lhs, ulong3 rhs) { return new ulong3(lhs & rhs.x, lhs & rhs.y, lhs & rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator |(ulong3 lhs, ulong3 rhs) { return new ulong3(lhs.x | rhs.x, lhs.y | rhs.y, lhs.z | rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator |(ulong3 lhs, ulong rhs) { return new ulong3(lhs.x | rhs, lhs.y | rhs, lhs.z | rhs); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator |(ulong lhs, ulong3 rhs) { return new ulong3(lhs | rhs.x, lhs | rhs.y, lhs | rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator ^(ulong3 lhs, ulong3 rhs) { return new ulong3(lhs.x ^ rhs.x, lhs.y ^ rhs.y, lhs.z ^ rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator ^(ulong3 lhs, ulong rhs) { return new ulong3(lhs.x ^ rhs, lhs.y ^ rhs, lhs.z ^ rhs); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator ^(ulong lhs, ulong3 rhs) { return new ulong3(lhs ^ rhs.x, lhs ^ rhs.y, lhs ^ rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 operator >(ulong3 lhs, ulong3 rhs) { return new bool3(lhs.x > rhs.x, lhs.y > rhs.y, lhs.z > rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 operator >(ulong3 lhs, ulong rhs) { return new bool3(lhs.x > rhs, lhs.y > rhs, lhs.z > rhs); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 operator >(ulong lhs, ulong3 rhs) { return new bool3(lhs > rhs.x, lhs > rhs.y, lhs > rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 operator >=(ulong3 lhs, ulong3 rhs) { return new bool3(lhs.x >= rhs.x, lhs.y >= rhs.y, lhs.z >= rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 operator >=(ulong3 lhs, ulong rhs) { return new bool3(lhs.x >= rhs, lhs.y >= rhs, lhs.z >= rhs); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 operator >=(ulong lhs, ulong3 rhs) { return new bool3(lhs >= rhs.x, lhs >= rhs.y, lhs >= rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 operator <(ulong3 lhs, ulong3 rhs) { return new bool3(lhs.x < rhs.x, lhs.y < rhs.y, lhs.z < rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 operator <(ulong3 lhs, ulong rhs) { return new bool3(lhs.x < rhs, lhs.y < rhs, lhs.z < rhs); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 operator <(ulong lhs, ulong3 rhs) { return new bool3(lhs < rhs.x, lhs < rhs.y, lhs < rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 operator <=(ulong3 lhs, ulong3 rhs) { return new bool3(lhs.x <= rhs.x, lhs.y <= rhs.y, lhs.z <= rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 operator <=(ulong3 lhs, ulong rhs) { return new bool3(lhs.x <= rhs, lhs.y <= rhs, lhs.z <= rhs); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 operator <=(ulong lhs, ulong3 rhs) { return new bool3(lhs <= rhs.x, lhs <= rhs.y, lhs <= rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 operator ==(ulong3 lhs, ulong3 rhs) { return new bool3(lhs.x == rhs.x, lhs.y == rhs.y, lhs.z == rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 operator ==(ulong3 lhs, ulong rhs) { return new bool3(lhs.x == rhs, lhs.y == rhs, lhs.z == rhs); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 operator ==(ulong lhs, ulong3 rhs) { return new bool3(lhs == rhs.x, lhs == rhs.y, lhs == rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 operator !=(ulong3 lhs, ulong3 rhs) { return new bool3(lhs.x != rhs.x, lhs.y != rhs.y, lhs.z != rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 operator !=(ulong3 lhs, ulong rhs) { return new bool3(lhs.x != rhs, lhs.y != rhs, lhs.z != rhs); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 operator !=(ulong lhs, ulong3 rhs) { return new bool3(lhs != rhs.x, lhs != rhs.y, lhs != rhs.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator <<(ulong3 x, Int32 n) { return new ulong3(x.x << n, x.y << n, x.z << n); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 operator >>(ulong3 x, Int32 n) { return new ulong3(x.x >> n, x.y >> n, x.z >> n); } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xxxx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, x, x, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xxxy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, x, x, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xxxz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, x, x, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xxyx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, x, y, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xxyy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, x, y, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xxyz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, x, y, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xxzx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, x, z, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xxzy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, x, z, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xxzz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, x, z, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xyxx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, y, x, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xyxy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, y, x, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xyxz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, y, x, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xyyx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, y, y, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xyyy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, y, y, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xyyz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, y, y, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xyzx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, y, z, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xyzy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, y, z, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xyzz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, y, z, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xzxx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, z, x, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xzxy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, z, x, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xzxz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, z, x, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xzyx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, z, y, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xzyy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, z, y, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xzyz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, z, y, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xzzx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, z, z, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xzzy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, z, z, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 xzzz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(x, z, z, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yxxx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, x, x, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yxxy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, x, x, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yxxz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, x, x, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yxyx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, x, y, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yxyy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, x, y, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yxyz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, x, y, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yxzx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, x, z, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yxzy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, x, z, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yxzz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, x, z, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yyxx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, y, x, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yyxy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, y, x, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yyxz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, y, x, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yyyx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, y, y, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yyyy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, y, y, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yyyz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, y, y, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yyzx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, y, z, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yyzy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, y, z, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yyzz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, y, z, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yzxx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, z, x, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yzxy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, z, x, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yzxz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, z, x, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yzyx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, z, y, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yzyy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, z, y, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yzyz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, z, y, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yzzx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, z, z, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yzzy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, z, z, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 yzzz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(y, z, z, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zxxx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, x, x, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zxxy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, x, x, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zxxz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, x, x, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zxyx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, x, y, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zxyy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, x, y, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zxyz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, x, y, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zxzx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, x, z, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zxzy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, x, z, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zxzz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, x, z, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zyxx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, y, x, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zyxy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, y, x, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zyxz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, y, x, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zyyx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, y, y, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zyyy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, y, y, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zyyz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, y, y, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zyzx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, y, z, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zyzy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, y, z, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zyzz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, y, z, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zzxx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, z, x, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zzxy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, z, x, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zzxz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, z, x, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zzyx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, z, y, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zzyy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, z, y, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zzyz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, z, y, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zzzx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, z, z, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zzzy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, z, z, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong4 zzzz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong4(z, z, z, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 xxx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(x, x, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 xxy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(x, x, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 xxz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(x, x, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 xyx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(x, y, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 xyy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(x, y, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 xyz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(x, y, z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { x = value.x; y = value.y; z = value.z; } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 xzx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(x, z, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 xzy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(x, z, y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { x = value.x; z = value.y; y = value.z; } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 xzz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(x, z, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 yxx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(y, x, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 yxy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(y, x, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 yxz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(y, x, z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { y = value.x; x = value.y; z = value.z; } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 yyx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(y, y, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 yyy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(y, y, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 yyz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(y, y, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 yzx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(y, z, x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { y = value.x; z = value.y; x = value.z; } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 yzy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(y, z, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 yzz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(y, z, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 zxx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(z, x, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 zxy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(z, x, y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { z = value.x; x = value.y; y = value.z; } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 zxz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(z, x, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 zyx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(z, y, x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { z = value.x; y = value.y; x = value.z; } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 zyy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(z, y, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 zyz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(z, y, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 zzx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(z, z, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 zzy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(z, z, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong3 zzz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong3(z, z, z); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong2 xx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong2(x, x); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong2 xy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong2(x, y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { x = value.x; y = value.y; } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong2 xz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong2(x, z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { x = value.x; z = value.y; } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong2 yx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong2(y, x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { y = value.x; x = value.y; } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong2 yy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong2(y, y); } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong2 yz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong2(y, z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { y = value.x; z = value.y; } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong2 zx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong2(z, x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { z = value.x; x = value.y; } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong2 zy { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong2(z, y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { z = value.x; y = value.y; } } [EditorBrowsable(EditorBrowsableState.Never)] public ulong2 zz { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new ulong2(z, z); } } unsafe public ulong this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { #if ENABLE_UNITY_COLLECTIONS_CHECKS if ((uint)index >= 3) { throw new System.ArgumentException("index must be between[0...2]"); } #endif fixed (ulong3* array = &this) { return ((ulong*)array)[index]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { #if ENABLE_UNITY_COLLECTIONS_CHECKS if ((uint)index >= 3) { throw new System.ArgumentException("index must be between[0...2]"); } #endif fixed (ulong* array = &x) { array[index] = value; } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(ulong3 rhs) { return this.x == rhs.x && this.y == rhs.y && this.z == rhs.z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object o) { return o is ulong3 converted && Equals(converted); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { return (int)fmath.hash(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override string ToString() { return String.Format("ulong3({0}, {1}, {2})", x, y, z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public String ToString(String format, IFormatProvider formatProvider) { return String.Format("ulong3({0}, {1}, {2})", x.ToString(format, formatProvider), y.ToString(format, formatProvider), z.ToString(format, formatProvider)); } internal sealed class DebuggerProxy { public ulong x; public ulong y; public ulong z; public DebuggerProxy(ulong3 v) { x = v.x; y = v.y; z = v.z; } } } public static partial class fmath { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 ulong3() { return new ulong3(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 ulong3(ulong x, ulong y, ulong z) { return new ulong3(x, y, z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 ulong3(ulong x, ulong2 yz) { return new ulong3(x, yz); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 ulong3(ulong2 xy, ulong z) { return new ulong3(xy, z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 ulong3(ulong3 xyz) { return new ulong3(xyz); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 ulong3(ulong v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 ulong3(bool3 v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 ulong3(bool v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 ulong3(int3 v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 ulong3(int v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 ulong3(uint3 v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 ulong3(uint v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 ulong3(long3 v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 ulong3(long v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 ulong3(float3 v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 ulong3(float v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 ulong3(double3 v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 ulong3(double v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 ulong3(ffloat3 v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 ulong3(ffloat v) { return new ulong3(v); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 bool3(ulong3 v) { return (bool3)v; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int3 int3(ulong3 v) { return (int3)v; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint3 uint3(ulong3 v) { return (uint3)v; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float3 float3(ulong3 v) { return (float3)v; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double3 double3(ulong3 v) { return (double3)v; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint hash(ulong3 v) { return math.csum(fold_to_uint(v) * math.uint3(0xF25BE857U, 0x9BC17CE7U, 0xC8B86851U)) + 0x64095221U; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint3 hashwide(ulong3 v) { return (fold_to_uint(v) * math.uint3(0xADF428FFU, 0xA3977109U, 0x745ED837U)) + 0x9CDC88F5U; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong shuffle(ulong3 left, ulong3 right, ShuffleComponent x) { return select_shuffle_component(left, right, x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong2 shuffle(ulong3 left, ulong3 right, ShuffleComponent x, ShuffleComponent y) { return ulong2( select_shuffle_component(left, right, x), select_shuffle_component(left, right, y)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong3 shuffle(ulong3 left, ulong3 right, ShuffleComponent x, ShuffleComponent y, ShuffleComponent z) { return ulong3( select_shuffle_component(left, right, x), select_shuffle_component(left, right, y), select_shuffle_component(left, right, z)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong4 shuffle(ulong3 left, ulong3 right, ShuffleComponent x, ShuffleComponent y, ShuffleComponent z, ShuffleComponent w) { return ulong4( select_shuffle_component(left, right, x), select_shuffle_component(left, right, y), select_shuffle_component(left, right, z), select_shuffle_component(left, right, w)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static ulong select_shuffle_component(ulong3 a, ulong3 b, ShuffleComponent component) { switch (component) { case ShuffleComponent.LeftX: return a.x; case ShuffleComponent.LeftY: return a.y; case ShuffleComponent.LeftZ: return a.z; case ShuffleComponent.RightX: return b.x; case ShuffleComponent.RightY: return b.y; case ShuffleComponent.RightZ: return b.z; default: throw new System.ArgumentException("Invalid shuffle component: " + component); } } } }
42.692565
166
0.596579
[ "MIT" ]
zengliugen/LittleBaby.Framework
UnityProject/Packages/LittleBaby.Framework.FixedMathematics/Runtime/Generated/ulong3.gen.cs
51,105
C#
using Core; using Core.Entities; using Core.Services.Interfaces; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading.Tasks; using Willezone.Azure.WebJobs.Extensions.DependencyInjection; namespace Restaurant { public static class CreateSupplierOrderActivity { [FunctionName(Constants.CreateSupplierOrderActivityFunctionName)] public static async Task<string> Run( [ActivityTrigger]SupplierOrder supplierOrder, [Inject]IBaseRepositoryFactory<SupplierOrder> supplierOrdersRepositoryFactory, ILogger log) { if (supplierOrder != null && !string.IsNullOrEmpty(supplierOrder.SupplierId) && (supplierOrder.OrderedItems?.Any() ?? false)) { var cosmosDbEndpoint = Environment.GetEnvironmentVariable(Constants.CosmosDbEndpointKeyName); var cosmosDbKey = Environment.GetEnvironmentVariable(Constants.CosmosDbKeyKeyName); var repo = supplierOrdersRepositoryFactory.GetInstance(cosmosDbEndpoint, cosmosDbKey, Constants.SupplierOrdersCollectionName); supplierOrder.CreatedAt = DateTime.UtcNow; supplierOrder.LastModified = supplierOrder.CreatedAt; supplierOrder.Status = SupplierOrderStatus.Processing; return await repo.AddAsync(supplierOrder); } return null; } } }
38.410256
142
0.690254
[ "MIT" ]
ecraciun/ServerlessRoboRestaurant
Restaurant/CreateSupplierOrderActivity.cs
1,498
C#
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // 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("LegendaryClient")] [assembly: AssemblyDescription("League of Legends Client")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("LegendaryCoding")] [assembly: AssemblyProduct("LegendaryClient")] [assembly: AssemblyCopyright("Copyright (c) 2013-2014, Eddy5641 (Ed V)")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
44.46
96
0.758884
[ "BSD-2-Clause" ]
ResQue1980/RtmpsLegendaryClient
LegendaryClient/Properties/AssemblyInfo.cs
2,225
C#
namespace Merchain.Data.Models { public class ProductColor { public int ProductId { get; set; } public virtual Product Product { get; set; } public int ColorId { get; set; } public virtual Color Color { get; set; } } }
19.071429
52
0.59176
[ "MIT" ]
pavelMihhailov/CodingLife
Merchain/Data/Merchain.Data.Models/ProductColor.cs
269
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the route53-2013-04-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Route53.Model { /// <summary> /// A complex type that identifies a hosted zone that a specified Amazon VPC is associated /// with and the owner of the hosted zone. If there is a value for <code>OwningAccount</code>, /// there is no value for <code>OwningService</code>, and vice versa. /// </summary> public partial class HostedZoneOwner { private string _owningAccount; private string _owningService; /// <summary> /// Gets and sets the property OwningAccount. /// <para> /// If the hosted zone was created by an account, or was created by an Amazon Web Services /// service that creates hosted zones using the current account, <code>OwningAccount</code> /// contains the account ID of that account. For example, when you use Cloud Map to create /// a hosted zone, Cloud Map creates the hosted zone using the current account. /// </para> /// </summary> public string OwningAccount { get { return this._owningAccount; } set { this._owningAccount = value; } } // Check to see if OwningAccount property is set internal bool IsSetOwningAccount() { return this._owningAccount != null; } /// <summary> /// Gets and sets the property OwningService. /// <para> /// If an Amazon Web Services service uses its own account to create a hosted zone and /// associate the specified VPC with that hosted zone, <code>OwningService</code> contains /// an abbreviation that identifies the service. For example, if Amazon Elastic File System /// (Amazon EFS) created a hosted zone and associated a VPC with the hosted zone, the /// value of <code>OwningService</code> is <code>efs.amazonaws.com</code>. /// </para> /// </summary> [AWSProperty(Max=128)] public string OwningService { get { return this._owningService; } set { this._owningService = value; } } // Check to see if OwningService property is set internal bool IsSetOwningService() { return this._owningService != null; } } }
36.802326
105
0.648657
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Route53/Generated/Model/HostedZoneOwner.cs
3,165
C#
using MO.Common.Collection; using MO.Common.Lang; using System.Xml; namespace MO.Common.Content { //============================================================ // <T>XML文档工具类。</T> //============================================================ public class RXml { // 扩展名 public const string EXT = "xml"; // 全扩展名 public const string EXTENSION = ".xml"; // 默认根节点名称 public const string ROOT_NAME = "Configuration"; // 默认节点名称 public const string NODE_NAME = "Node"; //============================================================ // <T>查找元素列表中的节点对象。</T> // // @param elements 元素列表 // @return 节点对象 //============================================================ internal static FXmlNode FindNode(FXmlElements elements) { foreach(FXmlElement element in elements) { if(element is FXmlNode) { return (FXmlNode)element; } } return null; } //============================================================ // <T>同步元素列表到文档元素中。</T> // // @param parent 元素对象 // @param elements 元素列表 //============================================================ internal static void SyncNodeFromElements(FXmlElement parent, XmlNodeList elements) { if((null != parent) && (null != elements)) { // 同步节点 foreach(XmlNode element in elements) { if(element.NodeType == XmlNodeType.Element) { // 处理元素节点 string name = element.Name; FXmlElement node = null; FAttributes nodeAttrs = new FAttributes(); // 同步属性 XmlAttributeCollection eattrs = element.Attributes; if(null != eattrs) { foreach(XmlAttribute attr in eattrs) { nodeAttrs[attr.Name] = attr.Value; } } // 设置文本 bool hasChild = true; if(1 == element.ChildNodes.Count) { XmlNode child = element.FirstChild; if(child.NodeType == XmlNodeType.Text) { node = parent.CreateNode(name, nodeAttrs); node._type = EXmlElementType.Node; node.Text = child.Value; hasChild = false; } else if(child.NodeType == XmlNodeType.CDATA) { node = parent.CreateNode(name, nodeAttrs); node._type = EXmlElementType.Node; node.Text = child.Value; hasChild = false; } } if(null == node) { node = parent.CreateNode(name, nodeAttrs); } if(hasChild && (element.ChildNodes.Count > 0)) { SyncNodeFromElements(node, element.ChildNodes); } } else if(element.NodeType == XmlNodeType.Comment) { // 处理注释节点 parent.CreateComment().Text = element.Value; } } } } //============================================================ // <T>同步文档元素到元素对象中。</T> // // @param node 文档元素 // @param element 元素对象 //============================================================ internal static void SyncElementFromNode(FXmlElement node, XmlNode element) { XmlDocument doc = element.OwnerDocument; // 设置元素内容 if(node._type == EXmlElementType.Data) { element.AppendChild(doc.CreateTextNode(node.Text)); return; } else if(!RString.IsEmpty(node.Text)) { element.AppendChild(doc.CreateTextNode(node.Text)); } // 同步属性列表 FAttributes attrs = node.Attributes; if(attrs != null) { foreach(IStringPair pair in attrs) { XmlAttribute xattr = doc.CreateAttribute(pair.Name); xattr.Value = pair.Value; element.Attributes.Append(xattr); } } // 同步元素列表 if(node.HasElement()) { foreach(FXmlElement nodeElement in node.Elements) { if(nodeElement is FXmlComment) { element.AppendChild(doc.CreateComment(nodeElement.Text)); } else if(nodeElement._type == EXmlElementType.Data) { element.AppendChild(doc.CreateCDataSection(nodeElement.Text)); } else { XmlNode celement = doc.CreateElement(nodeElement.Name); element.AppendChild(celement); SyncElementFromNode(nodeElement, celement); } } } } //============================================================ // <T>从文档节点中建立属性表。</T> // // @param parent 文档元素 // @param attributes 属性列表 //============================================================ public static void BuildAttributes(FXmlNode parent, FAttributes attributes) { if((parent != null) && parent.HasNode()) { foreach(FXmlNode node in parent.Nodes) { attributes[node.Name] = node.Text; } } } //============================================================ // <T>从文档节点中建立哈希表。</T> // // @param parent 文档元素 // @param map 文档节点哈希表 //============================================================ public static void BuildMap(FXmlNode parent, FXmlNodeMap map) { if((parent != null) && parent.HasNode()) { foreach(FXmlNode node in parent.Nodes) { map.Set(node.Name, node); } } } //============================================================ // <T>从文档节点中建立哈希表。</T> // // @param parent 文档元素 // @param map 文档节点哈希表 // @param name 节点名称 // @param attrName 属性名称 //============================================================ public static void BuildMap(FXmlNode parent, FXmlNodeMap map, string name, string attrName) { if(parent != null && parent.Nodes != null) { foreach(FXmlNode node in parent.Nodes) { if(node.IsName(name)) { map.Set(node.Get(attrName), node); } } } } } }
36.679775
99
0.425946
[ "Apache-2.0" ]
favedit/MoCross
Utiliy/Common/MuCommon/Content/RXml.cs
6,941
C#
// This file is part of Core WF which is licensed under the MIT license. // See LICENSE file in the project root for full license information. namespace CoreWf.Statements { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using CoreWf.Validation; using System.Linq; using CoreWf.Expressions; using CoreWf.Runtime; using CoreWf.Internals; public sealed class Compensate : NativeActivity { private static readonly Constraint compensateWithNoTarget = Compensate.CompensateWithNoTarget(); private InternalCompensate internalCompensate; private DefaultCompensation defaultCompensation; private readonly Variable<CompensationToken> currentCompensationToken; public Compensate() : base() { this.currentCompensationToken = new Variable<CompensationToken>(); } [DefaultValue(null)] public InArgument<CompensationToken> Target { get; set; } private DefaultCompensation DefaultCompensation { get { if (this.defaultCompensation == null) { this.defaultCompensation = new DefaultCompensation() { Target = new InArgument<CompensationToken>(this.currentCompensationToken), }; } return this.defaultCompensation; } } private InternalCompensate InternalCompensate { get { if (this.internalCompensate == null) { this.internalCompensate = new InternalCompensate() { Target = new InArgument<CompensationToken>(new ArgumentValue<CompensationToken> { ArgumentName = "Target" }), }; } return this.internalCompensate; } } protected override void CacheMetadata(NativeActivityMetadata metadata) { RuntimeArgument targetArgument = new RuntimeArgument("Target", typeof(CompensationToken), ArgumentDirection.In); metadata.Bind(this.Target, targetArgument); metadata.SetArgumentsCollection(new Collection<RuntimeArgument> { targetArgument }); metadata.SetImplementationVariablesCollection(new Collection<Variable> { this.currentCompensationToken }); Fx.Assert(DefaultCompensation != null, "DefaultCompensation must be valid"); Fx.Assert(InternalCompensate != null, "InternalCompensate must be valid"); metadata.SetImplementationChildrenCollection( new Collection<Activity> { DefaultCompensation, InternalCompensate }); } internal override IList<Constraint> InternalGetConstraints() { return new List<Constraint>(1) { compensateWithNoTarget }; } private static Constraint CompensateWithNoTarget() { DelegateInArgument<Compensate> element = new DelegateInArgument<Compensate> { Name = "element" }; DelegateInArgument<ValidationContext> validationContext = new DelegateInArgument<ValidationContext> { Name = "validationContext" }; Variable<bool> assertFlag = new Variable<bool> { Name = "assertFlag" }; Variable<IEnumerable<Activity>> elements = new Variable<IEnumerable<Activity>>() { Name = "elements" }; Variable<int> index = new Variable<int>() { Name = "index" }; return new Constraint<Compensate> { Body = new ActivityAction<Compensate, ValidationContext> { Argument1 = element, Argument2 = validationContext, Handler = new Sequence { Variables = { assertFlag, elements, index }, Activities = { new If { Condition = new InArgument<bool>((env) => element.Get(env).Target != null), Then = new Assign<bool> { To = assertFlag, Value = true }, Else = new Sequence { Activities = { new Assign<IEnumerable<Activity>> { To = elements, Value = new GetParentChain { ValidationContext = validationContext, }, }, new While(env => (assertFlag.Get(env) != true) && index.Get(env) < elements.Get(env).Count()) { Body = new Sequence { Activities = { new If(env => (elements.Get(env).ElementAt(index.Get(env))).GetType() == typeof(CompensationParticipant)) { Then = new Assign<bool> { To = assertFlag, Value = true }, }, new Assign<int> { To = index, Value = new InArgument<int>(env => index.Get(env) + 1) }, } } } } } }, new AssertValidation { Assertion = new InArgument<bool>(assertFlag), Message = new InArgument<string>(SR.CompensateWithNoTargetConstraint) } } } } }; } protected override void Execute(NativeActivityContext context) { CompensationExtension compensationExtension = context.GetExtension<CompensationExtension>(); if (compensationExtension == null) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.CompensateWithoutCompensableActivity(this.DisplayName))); } if (Target.IsEmpty) { CompensationToken ambientCompensationToken = (CompensationToken)context.Properties.Find(CompensationToken.PropertyName); CompensationTokenData ambientTokenData = ambientCompensationToken == null ? null : compensationExtension.Get(ambientCompensationToken.CompensationId); if (ambientTokenData != null && ambientTokenData.IsTokenValidInSecondaryRoot) { this.currentCompensationToken.Set(context, ambientCompensationToken); if (ambientTokenData.ExecutionTracker.Count > 0) { context.ScheduleActivity(DefaultCompensation); } } else { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.InvalidCompensateActivityUsage(this.DisplayName))); } } else { CompensationToken compensationToken = Target.Get(context); CompensationTokenData tokenData = compensationToken == null ? null : compensationExtension.Get(compensationToken.CompensationId); if (compensationToken == null) { throw FxTrace.Exception.Argument("Target", SR.InvalidCompensationToken(this.DisplayName)); } if (compensationToken.CompensateCalled) { // No-Op return; } if (tokenData == null || tokenData.CompensationState != CompensationState.Completed) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.CompensableActivityAlreadyConfirmedOrCompensated)); } // A valid in-arg was passed... tokenData.CompensationState = CompensationState.Compensating; compensationToken.CompensateCalled = true; context.ScheduleActivity(InternalCompensate); } } protected override void Cancel(NativeActivityContext context) { // Suppress Cancel } } }
43.891304
166
0.453987
[ "MIT" ]
OIgnat/corewf
src/CoreWf/Statements/Compensate.cs
10,095
C#
/* * API Doctor * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * * 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. */ namespace ApiDoctor.ConsoleApp.Auth { using System.Threading.Tasks; using System.Collections.Generic; using ApiDoctor.Validation; public class BasicAccount : IServiceAccount { public BasicAccount() { } public string BaseUrl { get; set; } public bool Enabled { get; set; } public string Name { get; set; } public string[] AdditionalHeaders { get; set; } public string Username { get; set; } public string Password { get; set; } public string[] Scopes { get; set; } public string[] ApiVersions { get; set; } public string[] Tags { get; set; } public AccountTransforms Transformations { get; } public Task PrepareForRequestAsync() { return Task.FromResult(true); } public AuthenicationCredentials CreateCredentials() { return new BasicCredentials { Username = this.Username, Password = this.Password }; } public void OverrideBaseUrl(string newBaseUrl) { this.BaseUrl = newBaseUrl; } } }
35.661538
95
0.673425
[ "MIT" ]
BarryShehadeh/apidoctor
ApiDoctor.Console/Auth/BasicAccount.cs
2,320
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using System; using System.Linq; namespace Deformer { [CreateAssetMenu(menuName = "rsTools/MeshObject")] public class MeshDescription : ScriptableObject { [SerializeField] Mesh _mesh; [SerializeField] private int _vertCount; [SerializeField] private string _objName; [SerializeField] private string _objNameNice; //[SerializeField] Dictionary<string, DeformerData> _deformers = new Dictionary<string, DeformerData>(); [SerializeField] StringDeformerDataDictionary _deformers; public MeshDescription(int vertCount, string objName, Mesh mesh) { _vertCount = vertCount; _objName = objName; _mesh = mesh; if (_deformers == null) _deformers = new StringDeformerDataDictionary(); } public DeformerData AddDeformer(string name) { if (_deformers == null) _deformers = new StringDeformerDataDictionary(); string fullPath = _objName + "_" + name; if (!_deformers.ContainsKey(fullPath)) { Debug.Log("Adding Deformer " + fullPath); DeformerData def = new DeformerData(fullPath, _vertCount); _deformers.Add(fullPath, def); } return _deformers[fullPath]; } public void RemoveDeformer(string name) { string fullPath = _objName + "_" + name; if (_deformers != null) { if (_deformers.ContainsKey(fullPath)) { _deformers.Remove(fullPath); } } } public void RemoveDeformer(DeformerData deformer) { if (_deformers != null) { if (_deformers.ContainsValue(deformer)) { string key = _deformers.FindFirstKeyByValue(deformer); _deformers.Remove(key); } } } public void CacheAllWeightmaps() { string fullPath = _objName + "_" + name; foreach (DeformerData p in _deformers.Values) { foreach (Weightmap w in p.Weightmaps) { w.CacheWeights(); } } } public List<string> KeyList { get { return new List<string>(_deformers.Keys); } } public List<DeformerData> DeformerList { get { return new List<DeformerData>(_deformers.Values); } } public int VertCount { get { return _vertCount; } set { _vertCount = value; } } public string Name { get { return _objName; } set { _objName = value; } } public string NiceName { get { return _objNameNice; } set { _objNameNice = value; } } public Mesh Mesh { get { return _mesh; } set { _mesh = value; } } public DeformerData GetDeformer(string name) { if (!_deformers.ContainsKey(name)) return null; return _deformers[name]; } public Weightmap GetWeightmap(string deformerName, string name) { DeformerData data = GetDeformer(deformerName); if (data != null) { return data.GetWeightmap(name); } return null; } public Weightmap FindWeightmap(string name) { foreach (DeformerData p in _deformers.Values) { foreach (Weightmap w in p.Weightmaps) { if (name == w.name) { return w; } } } return null; } public List<string> GetWeightmaps() { List<string> weightmaps = new List<string>(); foreach (DeformerData p in _deformers.Values) { foreach (Weightmap w in p.Weightmaps) { weightmaps.Add(w.name); } } return weightmaps; } public void RemoveDeformer(string name, DeformerData deformer) { if (_deformers.ContainsValue(deformer)) { _deformers.Remove(name); } } } }
30.30137
112
0.52396
[ "MIT" ]
robertstratton630/unityComputeShaders
rsDeformerTools/Utils/MeshDescription.cs
4,424
C#
using System; using System.Collections; namespace IrProject.Indexing { /// <summary> /// Represents the page graph (or link graph) as an adjacency list. /// Used to build the graph by adding pages and links and return the calculated hub and authority scores. /// </summary> public class AHPageGraph { public static float THRESHOLD = 0.001f; //reasonable value for converging private Hashtable forwardLinks; private Hashtable backLinks; private Hashtable globalIds; //key=global docId, value=local id private Hashtable localIds; //key=local id, value = global docId private bool calculatedAH; private bool pagesAdded; private float[] authScores; //position = docId private float[] hubScores; //position = docId private int cursor; //keeps track of current number of pages public AHPageGraph(int rootSize) { cursor = 0; globalIds = new Hashtable(); localIds = new Hashtable(); calculatedAH = false; pagesAdded = false; } public void AddPage(int docId) { if (pagesAdded) throw new Exception("you cannot add a page after adding a link"); if (!globalIds.Contains(docId)) { int id = cursor; //for clarity localIds.Add(id, docId); globalIds.Add(docId, id); cursor++; } } public void AddLink(int fromDocId, int toDocId) { if (!pagesAdded) { forwardLinks = new Hashtable(globalIds.Count); backLinks = new Hashtable(globalIds.Count); pagesAdded = true; } //convert to internal ids int fromId = Convert.ToInt16(globalIds[fromDocId]); int toId = Convert.ToInt16(globalIds[toDocId]); ArrayList links = (ArrayList)forwardLinks[fromId]; if (links == null) { links = new ArrayList(); forwardLinks.Add(fromId, links); } links.Add(toId); links = (ArrayList)backLinks[toId]; if (links == null) { links = new ArrayList(); backLinks.Add(toId, links); } links.Add(fromId); } public Hashtable BaseSet { get { return globalIds; } } public int BaseSetSize { get { return globalIds.Count; } } public AHDocument[] GetAuthorities() { return getScores(new AHDocumentComparer(AHDocumentComparer.AUTHORITIES)); } public AHDocument[] GetHubs() { return getScores(new AHDocumentComparer(AHDocumentComparer.HUBS)); } private AHDocument[] getScores(AHDocumentComparer comparer) { if (!calculatedAH) //ensures that scores are calculated (only once) before returned { runAuthHubAlgorithm(); calculatedAH = true; } AHDocument[] results = new AHDocument[globalIds.Count]; for (int id=0; id<results.Length; id++) results[id] = new AHDocument(Convert.ToInt16(localIds[id]), authScores[id], hubScores[id]); Array.Sort(results, comparer); return results; } private void runAuthHubAlgorithm() { int count = globalIds.Count; //initialize all scores to 1 authScores = new float[count]; hubScores = new float[count]; for (int i=0; i<count; i++) { authScores[i] = 1; hubScores[i] = 1; } ArrayList list; float aCounter; float hCounter; float[] authTemp = new float[count]; //holds the difference of auth scores between iterations float[] hubsTemp = new float[count]; //holds the difference of hub scores between iterations while (notConverged(authTemp, hubsTemp)) { //add the hub scores of all backlinks to the authority score of the current page for (int i=0; i<count; i++) { //update difference arrays authTemp[i] = authScores[i]; hubsTemp[i] = hubScores[i]; if (backLinks[i] != null) { list = (ArrayList)backLinks[i]; authScores[i] = 0; foreach (int docId in list) authScores[i] += hubScores[docId]; } } //add the auth scores of all forwardlinks to the hub score of the current page for (int i=0; i<count; i++) { list = (ArrayList)forwardLinks[i]; hubScores[i] = 0; if (list != null) foreach (int docId in list) hubScores[i] += authScores[docId]; } // normalize aCounter = 0; hCounter = 0; for (int i=0; i<count; i++) { aCounter += Convert.ToSingle(Math.Pow(authScores[i], 2)); hCounter += Convert.ToSingle(Math.Pow(hubScores[i], 2)); } for (int i=0; i<count; i++) { authScores[i] = authScores[i] / (float)Math.Sqrt(aCounter); hubScores[i] = hubScores[i] / (float)Math.Sqrt(hCounter); } } } private bool notConverged(float[] authTemp, float[] hubsTemp) { int count = globalIds.Count; for (int i=0; i<count; i++) if ( (Math.Abs(authScores[i] - authTemp[i]) > THRESHOLD) || (Math.Abs(hubScores[i] - hubsTemp[i]) > THRESHOLD) ) return true; return false; } } }
27.354286
106
0.645707
[ "Unlicense" ]
ic4f/oldcode
2007-ir-crawl-index-search/Indexing/AHPageGraph.cs
4,787
C#
// MyPlugin file generated by Kari. // This file should be included almost as-is in the generated output. // The text version of this file and the helpers for the attributes defined here are available in the // MyPluginAnnotations.Generated.cs version of this file. namespace Kari.Plugins.MyPlugin { // It is important to import things inside the namespace. // Obviously, you cannot import Kari specific things or things defined in your other files, // unless you also export the source code from those files. using System; using System.Diagnostics; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)] [Conditional("CodeGeneration")] public class MyPluginAttribute : Attribute { } // You may include things besides attributes in this file, // if you want them shared between your and your consumer's project. public interface IExample { } }
36.8
101
0.733696
[ "MIT" ]
AntonC9018/Kari
source/dotnet_new_templates/basic_plugin_project/MyPluginAnnotations.cs
920
C#
using _03_Challenge_Repository; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _03_Challenge_Console { public class ProgramUI { private BadgesRepository _repo = new BadgesRepository(); public void Run() { SeedBadges(); while (Menu()) { Console.WriteLine("\n\nPress any key to continue..."); Console.ReadKey(); Console.Clear(); } } private bool Menu() { Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MAIN MENU~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n"); Console.WriteLine("Enter the NUMBER you would like to do:\n\n" + "\t1. Add a Badge \n" + "\t2. Edit a Badge\n" + "\t3. List All Badges\n" + "\t4. Exit"); int input = Convert.ToInt32(Console.ReadLine()); switch (input) { case 1: AddBadge(); break; case 2: EditBadge(); break; case 3: ListAllBadges(); break; case 4: return false; default: Console.WriteLine("\nPlease enter a vaild number"); return true; } return true; } private void AddBadge() { Console.Clear(); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~ADD BADGE~~~~~~~~~~~~~~~~~~~~~~\n\n"); Console.WriteLine("What is the number of the badge:"); int badgeID = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("\nList the FIRST door that it needs access to (ex. A1) and then press any key to continue:"); string response = Console.ReadLine().ToUpper(); List<string> listResponse = new List<string> { response }; bool keepAsking = true; while (keepAsking) { Console.WriteLine("\nAny other doors? Enter [Y]es or [N]o:"); string userResponse = Console.ReadLine().ToLower(); if (userResponse == "yes" || userResponse == "y") { Console.WriteLine("\nList another door that it needs access to (ex. A1):"); string addDoor = Console.ReadLine().ToUpper(); listResponse.Add(addDoor); } else if (userResponse == "no" || userResponse == "n") { keepAsking = false; } else { Console.WriteLine("\nPlease enter a valide response."); } } Badge newBadge = new Badge(badgeID, listResponse); if (_repo.AddBadgeToDictionary(newBadge)) { Console.WriteLine("\nYou successfully added a new Badge."); } else { Console.WriteLine("\nYou were NOT able to add this Badge."); } } private void EditBadge() { Console.Clear(); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~EDIT BADGE~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n"); while (RemoveOrAddDoorMenu()) { Console.WriteLine("\n\nPress any key to continue..."); Console.ReadKey(); Console.Clear(); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~EDIT BADGE~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n"); } } private bool RemoveOrAddDoorMenu() { Console.WriteLine("\nEnter the NUMBER you would like to do:\n" + "\t1. Add a Door.\n" + "\t2. Remove a Door.\n" + "\t3. See List of Badges.\n" + "\t4. Back to Menu.\n"); int input = Convert.ToInt32(Console.ReadLine()); if (input == 1) { EditAddDoor(); return true; } else if (input == 2) { EditRemoveDoor(); return true; } else if (input == 3) { ListAllBadges(); return true; } else if (input == 4) { return false; } else { Console.WriteLine("\nPlease enter a vaild number"); return true; } } private void EditAddDoor() { Console.Clear(); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ADD DOOR~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n"); Console.WriteLine("\nEnter the BADGE ID:"); int badgeID = Convert.ToInt32(Console.ReadLine()); var dict = _repo.GetListBadge(); if (dict.ContainsKey(badgeID)) { foreach (var badge in dict.OrderBy(key => key.Key)) { if (badge.Key == badgeID) { int firstCount = badge.Value.Count; var list = badge.Value; var valueAsString = string.Join(", ", list); Console.WriteLine($"\n\tBadge ID {badge.Key} has access to doors: {valueAsString}."); Console.WriteLine("\nEnter the door you would like to ADD (ex. A1):"); string additionDoor = Console.ReadLine().ToUpper(); badge.Value.Add(additionDoor); int secondCount = badge.Value.Count; var list2 = badge.Value; list2.Sort(); var valueAsStringAgain = string.Join(", ", list2); if (secondCount > firstCount) { Console.WriteLine($"\nDoor was ADDED."); Console.WriteLine($"\n\tBadge ID {badge.Key} has access to doors: {valueAsStringAgain}."); } else { Console.WriteLine("\nCould NOT add the door."); } } } } else { Console.WriteLine("\nThere is NOT a BADGE ID in the database."); } } private void EditRemoveDoor() { Console.Clear(); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~REMOVE DOOR~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n"); Console.WriteLine("\nEnter the BADGE ID:"); int badgeID = Convert.ToInt32(Console.ReadLine()); var dict = _repo.GetListBadge(); if (dict.ContainsKey(badgeID)) { foreach (var badge in dict.OrderBy(key => key.Key)) { if (badge.Key == badgeID) { int firstCount = badge.Value.Count; var list = badge.Value; var valueAsString = string.Join(", ", list); Console.WriteLine($"\n\tBadge ID {badge.Key} has access to doors: {valueAsString}."); Console.WriteLine("\nEnter the door you would like to REMOVE (ex. A1):"); string additionDoor = Console.ReadLine().ToUpper(); badge.Value.Remove(additionDoor); int secondCount = badge.Value.Count; var list2 = badge.Value; list2.Sort(); var valueAsStringAgain = string.Join(", ", list2); if (secondCount < firstCount) { Console.WriteLine($"\nDoor was REMOVED."); Console.WriteLine($"\n\tBadge ID {badge.Key} has access to doors: {valueAsStringAgain}."); } else { Console.WriteLine("\nCould NOT remove the door."); } } } } else { Console.WriteLine("\nThere is NOT a BADGE ID in the database."); } } private void ListAllBadges() { Console.Clear(); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~LIST OF BADGES~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n"); var dict = _repo.GetListBadge(); if (dict.Count > 0) { foreach (var badge in dict.OrderBy(key => key.Key)) { var list = badge.Value; list.Sort(); var valueAsString = string.Join(", ", list); Console.WriteLine($"\n\tBadge ID {badge.Key} has access to doors: {valueAsString}."); } } } private void SeedBadges() { _repo.AddBadgeToDictionary(new Badge(1, new List<string> { "A1", "B1", "A5" })); _repo.AddBadgeToDictionary(new Badge(31, new List<string> { "A1", "B2", "A3" })); _repo.AddBadgeToDictionary(new Badge(3, new List<string> { "A1", "B1", "A7" })); } } }
35.3663
124
0.41595
[ "MIT" ]
CazaresCode/GoldBadge_Challenges
03_Challenge_Console/ProgramUI.cs
9,657
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cus.Entities.Entities { public class Shippers { public int ShipperID {get; set;} public string CompanyName {get; set;} public string Phone {get; set;} } }
16.375
39
0.736641
[ "Unlicense" ]
wugelis/Cus.WebForm
Cus.Entities/Entities/Shippers.cs
262
C#
#pragma warning disable 1591 using System; using System.Collections.Generic; using System.Text; namespace AjaxControlToolkit { public interface IClientStateManager { bool SupportsClientState { get; } void LoadClientState(string clientState); string SaveClientState(); } } #pragma warning restore 1591
21
49
0.735119
[ "BSD-3-Clause" ]
sergiolmachado/AjaxControlToolkit-master
AjaxControlToolkit/ExtenderBase/IClientStateManager.cs
336
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Web; using Azure.Storage.Files.Shares; using Frank.Libraries.AzureStorage.FileShare.Exceptions; using Microsoft.Extensions.Options; namespace Frank.Libraries.AzureStorage.FileShare { public class FileShareClient : IFileShareClient { private readonly ShareClient _shareClient; private readonly IList<ShareFileMetadata> _shareFiles; private readonly IList<string> _shareDirectories; public FileshareUploadException? UploadException { get; private set; } public FileshareDownloadException? DownloadException { get; private set; } public FileShareClient(IOptions<FileShareConfiguration> options) { _shareClient = new ShareClient(options.Value.ConnectionString, options.Value.ShareName); _shareFiles = new List<ShareFileMetadata>(); _shareDirectories = new List<string>(); Initialize(); } public FileShareClient(FileShareConfiguration configuration) { _shareClient = new ShareClient(configuration.ConnectionString, configuration.ShareName); _shareFiles = new List<ShareFileMetadata>(); _shareDirectories = new List<string>(); Initialize(); } public FileShareClient(string connectionString, string shareName) { _shareClient = new ShareClient(connectionString, shareName); _shareFiles = new List<ShareFileMetadata>(); _shareDirectories = new List<string>(); Initialize(); } private void Initialize() { _shareClient.CreateIfNotExists(); var remaining = new Queue<ShareDirectoryClient>(); remaining.Enqueue(_shareClient.GetRootDirectoryClient()); while (remaining.Count > 0) { var dir = remaining.Dequeue(); _shareDirectories.Add(HttpUtility.UrlDecode(dir.Path)); foreach (var item in dir.GetFilesAndDirectories()) { if (item.IsDirectory) remaining.Enqueue(dir.GetSubdirectoryClient(item.Name)); else if (item.FileSize != null) _shareFiles.Add(new ShareFileMetadata(item.Name, HttpUtility.UrlDecode(dir.Path) ?? string.Empty, item.FileSize.Value)); } } } public bool Exist(string filename) { return _shareFiles.Any(x => string.Equals(x.Name, Path.GetFileNameWithoutExtension(filename), StringComparison.InvariantCultureIgnoreCase)); } public IEnumerable<ShareFileMetadata> Search(string filename) { return _shareFiles.Where(x => x.Name.ToLowerInvariant() .Contains(Path.GetFileNameWithoutExtension(filename))); } public IEnumerable<ShareFileMetadata> FileItems { get { if (!_shareFiles.Any()) Initialize(); return _shareFiles; } } public IEnumerable<string> DirectoryItems { get { if (!_shareDirectories.Any()) Initialize(); return _shareDirectories; } } public bool TryDownload(ShareFileMetadata shareFile, out byte[] fileData) { try { fileData = DownloadAsync(shareFile) .GetAwaiter() .GetResult(); return true; } catch (Exception e) { DownloadException = new FileshareDownloadException($"The file '{shareFile.Name}{shareFile.Extension}' could not be downloaded", e); fileData = null!; return false; } } public async Task<byte[]> DownloadAsync(ShareFileMetadata shareFile) { var directory = _shareClient.GetDirectoryClient(shareFile.GetEncodedDirectoryPath); var download = await directory.GetFileClient(shareFile.Name) .DownloadAsync(); var stream = new MemoryStream(); try { await download.Value.Content.CopyToAsync(stream); return stream.ToArray(); } catch (Exception e) { throw new FileshareDownloadException($"The file '{shareFile.Name}{shareFile.Extension}' could not be downloaded", e); } } public async Task<bool> TryUploadAsync(byte[] fileData, string filename, string directoryPath) { try { await UploadAsync(fileData, filename, directoryPath); return true; } catch (Exception e) { UploadException = new FileshareUploadException($"The file '{filename}' could not be uploaded", e); return false; } } public async Task UploadAsync(byte[] fileData, string filename, string directoryPath) { var stream = new MemoryStream(fileData); var directory = _shareClient.GetDirectoryClient(directoryPath); try { await directory.GetFileClient(filename) .UploadAsync(stream); } catch (Exception e) { throw new FileshareUploadException($"The file '{filename}' could not be uploaded", e); } } } }
35.611111
172
0.567343
[ "MIT" ]
frankhaugen/Frank.Extensions
src/Frank.Libraries.AzureStorage/FileShare/FileShareClient.cs
5,771
C#
using ay.Controls; using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Media3D; namespace Ay.Framework.WPF.Controls.Transitions { // Base class for 3D transitions public abstract class Transition3D : Transition { static Transition3D() { Model3DGroup defaultLight = new Model3DGroup(); Vector3D direction = new Vector3D(1, 1, 1); direction.Normalize(); byte ambient = 108; // 108 is minimum for directional to be < 256 (for direction = [1,1,1]) byte directional = (byte)Math.Min((255 - ambient) / Vector3D.DotProduct(direction, new Vector3D(0, 0, 1)), 255); defaultLight.Children.Add(new AmbientLight(Color.FromRgb(ambient, ambient, ambient))); defaultLight.Children.Add(new DirectionalLight(Color.FromRgb(directional, directional, directional), direction)); defaultLight.Freeze(); LightProperty = DependencyProperty.Register("Light", typeof(Model3D), typeof(Transition3D), new UIPropertyMetadata(defaultLight)); } public double FieldOfView { get { return (double)GetValue(FieldOfViewProperty); } set { SetValue(FieldOfViewProperty, value); } } public static readonly DependencyProperty FieldOfViewProperty = DependencyProperty.Register("FieldOfView", typeof(double), typeof(Transition3D), new UIPropertyMetadata(20.0)); public Model3D Light { get { return (Model3D)GetValue(LightProperty); } set { SetValue(LightProperty, value); } } public static readonly DependencyProperty LightProperty; // Setup the Viewport 3D protected internal sealed override void BeginTransition(TransitionPresenter transitionElement, ContentPresenter oldContent, ContentPresenter newContent) { Viewport3D viewport = new Viewport3D(); viewport.IsHitTestVisible = false; viewport.Camera = CreateCamera(transitionElement, FieldOfView); viewport.ClipToBounds = false; ModelVisual3D light = new ModelVisual3D(); light.Content = Light; viewport.Children.Add(light); transitionElement.Children.Add(viewport); BeginTransition3D(transitionElement, oldContent, newContent, viewport); } protected virtual Camera CreateCamera(TransitionPresenter transitionElement, double fov) { Size size = transitionElement.RenderSize; return new PerspectiveCamera(new Point3D(size.Width / 2, size.Height / 2, -size.Width / Math.Tan(fov / 2 * Math.PI / 180) / 2), new Vector3D(0, 0, 1), new Vector3D(0, -1, 0), fov); } protected virtual void BeginTransition3D(TransitionPresenter transitionElement, ContentPresenter oldContent, ContentPresenter newContent, Viewport3D viewport) { EndTransition(transitionElement, oldContent, newContent); } // Generates a flat mesh starting at origin with sides equal to u and v vecotrs public static MeshGeometry3D CreateMesh(Point3D origin, Vector3D u, Vector3D v, int usteps, int vsteps, Rect textureBounds) { u = 1.0 / usteps * u; v = 1.0 / vsteps * v; MeshGeometry3D mesh = new MeshGeometry3D(); for (int i = 0; i <= usteps; i++) { for (int j = 0; j <= vsteps; j++) { mesh.Positions.Add(origin + i * u + j * v); mesh.TextureCoordinates.Add(new Point(textureBounds.X + textureBounds.Width * i / usteps, textureBounds.Y + textureBounds.Height * j / vsteps)); if (i > 0 && j > 0) { mesh.TriangleIndices.Add((i - 1) * (vsteps + 1) + (j - 1)); mesh.TriangleIndices.Add((i - 0) * (vsteps + 1) + (j - 0)); mesh.TriangleIndices.Add((i - 0) * (vsteps + 1) + (j - 1)); mesh.TriangleIndices.Add((i - 1) * (vsteps + 1) + (j - 1)); mesh.TriangleIndices.Add((i - 1) * (vsteps + 1) + (j - 0)); mesh.TriangleIndices.Add((i - 0) * (vsteps + 1) + (j - 0)); } } } return mesh; } } }
42.824074
166
0.573189
[ "MIT" ]
WertherHu/AYUI8Community
Ay/ay/SDK/ThreeLib/Transitions/Transition3D.cs
4,625
C#
using Xunit; namespace erp2018abp.Tests { public sealed class MultiTenantFactAttribute : FactAttribute { public MultiTenantFactAttribute() { if (!erp2018abpConsts.MultiTenancyEnabled) { Skip = "MultiTenancy is disabled."; } } } }
20
64
0.565625
[ "MIT" ]
vban528/erp2018abp
src/Tests/erp2018abp.Tests/MultiTenantFactAttribute.cs
322
C#
// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage( "Design", "CA1034:Nested types should not be visible", Justification = "Nested classes are used for methods in unit test classes.")] [assembly: SuppressMessage( "Design", "CA1062:Validate arguments of public methods", Justification = "Test methods are not under the same constraints as typical public methods.")] [assembly: SuppressMessage( "Naming", "CA1707:Identifiers should not contain underscores", Justification = "Allowed in test method names.")] [assembly: SuppressMessage( "Reliability", "CA2007:Consider calling ConfigureAwait on the awaited task", Justification = "Test methods will not be called outside of the scope of the project.")] [assembly: SuppressMessage( "Microsoft.CodeAnalysis.CSharp", "CS8604:Possible null reference argument.", Justification = "Necessary to add coverage for projects that do not use nullable reference types.")] [assembly: SuppressMessage( "Microsoft.CodeAnalysis.CSharp", "CS8625:Cannot convert null literal to non-nullable reference type.", Justification = "Necessary to add coverage for projects that do not use nullable reference types.")] [assembly: SuppressMessage( "StyleCop.CSharp.ReadabilityRules", "SA1118:Parameter should not span multiple lines", Justification = "This situation is hard to avoid with complex theory data.")]
47.914286
104
0.750745
[ "MIT" ]
lanceccraig/SpreadsheetIO
tests/TestingSuppressions.cs
1,677
C#
using System; using System.Collections.Generic; using System.Text; using System.IO; using Excel; using System.Data; namespace ExifRemover { class ExcelImporter { public void ImportListExcel(string filepath) { using (FileStream stream = File.Open(filepath, FileMode.Open, FileAccess.Read)) { IExcelDataReader excelReader = null; string curdir = Environment.CurrentDirectory; try { Environment.CurrentDirectory = System.IO.Path.GetDirectoryName(filepath); if (filepath.ToLower().EndsWith(".xls") || filepath.ToLower().EndsWith(".xlt")) { excelReader = ExcelReaderFactory.CreateBinaryReader(stream); } else if (filepath.ToLower().EndsWith(".xlsx")) { excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); } //excelReader.IsFirstRowAsColumnNames = chkHasHeaders.Checked; DataSet result = excelReader.AsDataSet(false); if (result.Tables.Count > 0) { for (int m = 0; m < result.Tables.Count; m++) { for (int k = 0; k < result.Tables[m].Rows.Count; k++) { if (result.Tables[m].Columns.Count > 0) { try { string file = result.Tables[m].Rows[k][0].ToString(); file = GetPart(file); file = Path.GetFullPath(file); frmMain.Instance.AddFile(file); } catch (Exception exk) { Module.ShowError(exk); } finally { } } } } } } finally { Environment.CurrentDirectory = curdir; if (excelReader != null) { excelReader.Close(); excelReader.Dispose(); } } } } private static string GetPart(string part) { if (part.StartsWith("\"")) { int epos = part.IndexOf("\"", 1); if (epos > 0) { part = part.Substring(1, epos - 1); } } else if (part.StartsWith("'")) { int epos = part.IndexOf("'", 1); if (epos > 0) { part = part.Substring(1, epos - 1); } } return part; } } }
32.556604
110
0.34164
[ "MIT" ]
fourDotsSoftware/ExifRemover
ExifRemover/ExcelImporter.cs
3,453
C#
// *********************************************************************** // Assembly : XLabs.Platform.WP81 // Author : XLabs Team // Created : 12-27-2015 // // Last Modified By : XLabs Team // Last Modified On : 01-04-2016 // *********************************************************************** // <copyright file="FileManager.cs" company="XLabs Team"> // Copyright (c) XLabs Team. All rights reserved. // </copyright> // <summary> // This project is licensed under the Apache 2.0 license // https://github.com/XLabs/Xamarin-Forms-Labs/blob/master/LICENSE // // XLabs is a open source project that aims to provide a powerfull and cross // platform set of controls tailored to work with Xamarin Forms. // </summary> // *********************************************************************** // #if !NETFX_CORE using System; using System.IO; using System.IO.IsolatedStorage; namespace XLabs.Platform.Services.IO { /// <summary> /// Class FileManager. /// </summary> public class FileManager : IFileManager { /// <summary> /// The isolated storage file /// </summary> private readonly IsolatedStorageFile isolatedStorageFile; /// <summary> /// Initialized new instance of <see cref="FileManager" /> using user store for application. /// </summary> public FileManager() : this(IsolatedStorageFile.GetUserStoreForApplication()) { } /// <summary> /// Initialized new instance of <see cref="FileManager" />. /// </summary> /// <param name="isolatedStorageFile">Isolated storage file to use.</param> public FileManager(IsolatedStorageFile isolatedStorageFile) { this.isolatedStorageFile = isolatedStorageFile; } /// <summary> /// Directories the exists. /// </summary> /// <param name="path">The path.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> public bool DirectoryExists(string path) { return this.isolatedStorageFile.DirectoryExists(path); } /// <summary> /// Creates the directory. /// </summary> /// <param name="path">The path.</param> public void CreateDirectory(string path) { this.isolatedStorageFile.CreateDirectory(path); } /// <summary> /// Opens the file. /// </summary> /// <param name="path">The path.</param> /// <param name="mode">The mode.</param> /// <param name="access">The access.</param> /// <returns>Stream.</returns> public Stream OpenFile(string path, FileMode mode, FileAccess access) { return this.isolatedStorageFile.OpenFile(path, (System.IO.FileMode)mode, (System.IO.FileAccess)access); } /// <summary> /// Opens the file. /// </summary> /// <param name="path">The path.</param> /// <param name="mode">The mode.</param> /// <param name="access">The access.</param> /// <param name="share">The share.</param> /// <returns>Stream.</returns> public Stream OpenFile(string path, FileMode mode, FileAccess access, FileShare share) { return this.isolatedStorageFile.OpenFile(path, (System.IO.FileMode)mode, (System.IO.FileAccess)access, (System.IO.FileShare)share); } /// <summary> /// Files the exists. /// </summary> /// <param name="path">The path.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> public bool FileExists(string path) { return this.isolatedStorageFile.FileExists(path); } /// <summary> /// Gets the last write time. /// </summary> /// <param name="path">The path.</param> /// <returns>DateTimeOffset.</returns> public DateTimeOffset GetLastWriteTime(string path) { return this.isolatedStorageFile.GetLastWriteTime(path); } /// <summary> /// Deletes the file. /// </summary> /// <param name="path">The path.</param> public void DeleteFile(string path) { this.isolatedStorageFile.DeleteFile(path); } /// <summary> /// Deletes the directory. /// </summary> /// <param name="path">The path.</param> public void DeleteDirectory(string path) { this.isolatedStorageFile.DeleteDirectory(path); } #if !WINDOWS_PHONE /// <summary> /// Copies a directory to another. /// </summary> /// <param name="source">Source directory.</param> /// <param name="destination">Destination directory. Created when necessary.</param> /// <exception cref="System.ArgumentException">Source directory does not exist</exception> /// <exception cref="ArgumentException">Exception is thrown if source directory doesn't exist.</exception> public static void CopyDirectory(DirectoryInfo source, DirectoryInfo destination) { if (!source.Exists) { throw new ArgumentException("Source directory does not exist"); } if (!destination.Exists) { destination.Create(); } foreach (var dir in source.GetDirectories()) { CopyDirectory(dir, new DirectoryInfo(Path.Combine(destination.FullName, dir.Name))); } foreach (var file in source.GetFiles()) { file.CopyTo(Path.Combine(destination.FullName, file.Name), true); } } #endif } } #endif
34.523529
143
0.548645
[ "Apache-2.0" ]
Bhekinkosi12/Xamarin-Forms-Labs
src/Platform/XLabs.Platform.Shared/Services/IO/FileManager.cs
5,869
C#
/** * @file * @author Mamadou Babaei <info@babaei.net> * @version 0.1.0 * * @section LICENSE * * (The MIT License) * * Copyright (c) 2018 - 2019 Mamadou Babaei * Copyright (c) 2018 - 2019 Seditious Games Studio * * 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. * * @section DESCRIPTION * * Build script for GodsOfDeceitVersion target. */ using UnrealBuildTool; public class GodsOfDeceitVersion : ModuleRules { public GUtils Utils; public GodsOfDeceitVersion(ReadOnlyTargetRules Target) : base(Target) { InitializeUtils(); Utils.Log.Start(); SetupBuildConfiguration(); AddEngineModules(); AddGameModules(); AddDefinitions(); Utils.BuildInfo.Print(); Utils.Log.Stop(); } private void InitializeUtils() { Utils = new GUtils(this, "GodsOfDeceitVersion"); /// Order matters, these modules must get initialized before the rest Utils.BuildPlatform = new GBuildPlatform(Utils); Utils.Path = new GPath(Utils); Utils.Log = new GLog(Utils); Utils.BuildConfiguration = new GBuildConfiguration(Utils); Utils.BuildInfo = new GBuildInfo(Utils); Utils.Definitions = new GDefinitions(Utils); Utils.EngineModules = new GEngineModules(Utils); Utils.GameModules = new GGameModules(Utils); Utils.Plugins = new GPlugins(Utils); Utils.ThirdParty = new GThirdParty(Utils); } private void AddDefinitions() { bool bShippingBuild = Utils.BuildPlatform.IsShippingBuild(); bool bWindowsBuild = Utils.BuildPlatform.IsWindowsBuild(); if (bWindowsBuild) { Utils.Definitions.DefinePublicly("_UNICODE"); Utils.Definitions.DefinePublicly("UNICODE"); Utils.Definitions.DefinePublicly("WIN32_LEAN_AND_MEAN"); } if (!bShippingBuild) { Utils.Definitions.DefinePublicly("GOD_LOGGING"); } Utils.Log.EmptyLine(); } private void AddEngineModules() { Utils.Log.Info("Setting up required engine modules for '{0}'...", Utils.ModuleName); Utils.EngineModules.AddCore(true); Utils.Log.EmptyLine(); } private void AddGameModules() { Utils.Log.Info("Setting up required game modules for '{0}'...", Utils.ModuleName); Utils.GameModules.AddInterop(false); Utils.GameModules.AddTypes(false); Utils.GameModules.AddVersionImpl(false); Utils.Log.EmptyLine(); } private void SetupBuildConfiguration() { Utils.Log.Info("Setting up build configuration for '{0}'...", Utils.ModuleName); bool bDebugBuild = Utils.BuildPlatform.IsDebugBuild(); Utils.BuildConfiguration.SetPCHUsage(PCHUsageMode.UseExplicitOrSharedPCHs); Utils.BuildConfiguration.SetUseRTTI(false); Utils.BuildConfiguration.SetEnableExceptions(false); Utils.BuildConfiguration.SetUseAVX(true); Utils.BuildConfiguration.SetEnableShadowVariableWarnings(true); Utils.BuildConfiguration.SetEnableUndefinedIdentifierWarnings(true); Utils.BuildConfiguration.SetFasterWithoutUnity(bDebugBuild); Utils.BuildConfiguration.SetOptimizeCode(bDebugBuild ? CodeOptimization.Never : CodeOptimization.Always); Utils.Log.EmptyLine(); } }
32.577778
113
0.687813
[ "MIT" ]
SeditiousGames/GodsOfDeceit
Source/GodsOfDeceitVersion/GodsOfDeceitVersion.Build.cs
4,398
C#
// Copyright (c) Arun Mahapatra. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Cliy.Template.Tests; using Boxed.DotnetNewTest; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Threading.Tasks; [TestClass] public class CliyTemplateTest : IDisposable { private const string TemplateSlnPath = "Cliy.sln"; private bool disposedValue; public CliyTemplateTest() => DotnetNew.InstallAsync<CliyTemplateTest>(TemplateSlnPath).Wait(); [TestMethod] public async Task DotnetRunWithDefaultArgumentsIsSuccessful() { await using var tempDirectory = TempDirectory.NewTempDirectory(); var project = await tempDirectory.DotnetNewAsync("cliy", "DefaultArguments"); await project.DotnetRestoreAsync(timeout: TimeSpan.FromMinutes(10)); await project.DotnetBuildAsync(); await project.DotnetTestAsync(); } protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { DotnetNew.UninstallAsync<CliyTemplateTest>(TemplateSlnPath).Wait(); } // TODO: free unmanaged resources (unmanaged objects) and override finalizer // TODO: set large fields to null disposedValue = true; } } public void Dispose() { // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method Dispose(disposing: true); GC.SuppressFinalize(this); } }
31.653846
102
0.658566
[ "MIT" ]
codito/cliy
test/CliyTemplateTest.cs
1,646
C#
using System.IO; using Zaabee.Extensions; namespace Zaabee.Binary { public static partial class BinaryHelper { public static MemoryStream Pack(object obj) => obj is null ? new MemoryStream() : BinarySerializer.Pack(obj); public static void Pack(object obj, Stream stream) { if (obj is null || stream is null) return; BinarySerializer.Pack(obj, stream); } public static T Unpack<T>(Stream stream) => stream.IsNullOrEmpty() ? (T) typeof(T).GetDefaultValue() : BinarySerializer.Unpack<T>(stream); public static object Unpack(Stream stream) => stream.IsNullOrEmpty() ? null : BinarySerializer.Unpack(stream); } }
31.869565
106
0.633015
[ "MIT" ]
Mutuduxf/Zaabee.Serializers
src/Zaabee.Binary/Binary.Helper.Stream.cs
735
C#
using ALE.ETLBox; using ALE.ETLBox.ConnectionManager; using ALE.ETLBox.ControlFlow; using ALE.ETLBox.DataFlow; using ALE.ETLBox.Helper; using ALE.ETLBox.Logging; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using Xunit; namespace ALE.ETLBoxTests.Performance { [Collection("Performance")] public class LeaveConnectionOpenTests { public string ConnectionStringParameter => Config.SqlConnection.RawConnectionString("Performance"); public LeaveConnectionOpenTests(PerformanceDatabaseFixture dbFixture) { } [Theory] [InlineData(1000,0.10)] public void TestLeaveOpenOnConnMan(int runs, double deviation) { //Arrange SqlConnectionManager conNormal = new SqlConnectionManager(ConnectionStringParameter); SqlConnectionManager conLeaveOpen = new SqlConnectionManager(ConnectionStringParameter) { LeaveOpen = true }; //Act var timeNormal = BigDataHelper.LogExecutionTime("Connection is cloned", () => { for (int i = 0; i < runs; i++) new SqlTask("Dummy", "WAITFOR DELAY '0:00:00.010'") { ConnectionManager = conNormal, DisableLogging = true } .ExecuteNonQuery(); }); var timeLeftOpen = BigDataHelper.LogExecutionTime("Connection is left open", () => { for (int i = 0; i < runs; i++) new SqlTask("Dummy", "WAITFOR DELAY '0:00:00.010'") { ConnectionManager = conLeaveOpen, DisableLogging = true } .ExecuteNonQuery(); }); //Assert Assert.True(timeLeftOpen < timeNormal); Assert.True(timeLeftOpen.TotalMilliseconds * (deviation + 1) > timeNormal.TotalMilliseconds); } } }
31.7
107
0.539883
[ "MIT" ]
HaSaM-cz/etlbox
TestsPerformance/src/LeaveConnectionOpenTests.cs
2,221
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 19.10.2021. using Microsoft.EntityFrameworkCore.Migrations.Operations; using NUnit.Framework; using xEFCore=Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D2.Migrations.Generations.SET001.DataTypes.Clr.Guid{ //////////////////////////////////////////////////////////////////////////////// using T_DATA=System.Guid; //////////////////////////////////////////////////////////////////////////////// //class TestSet_ERR002__bad_Precision public static class TestSet_ERR002__bad_Precision { private const string c_testTableName ="EFCORE_TTABLE_DUMMY"; private const string c_testColumnName ="MY_COLUMN"; //----------------------------------------------------------------------- [Test] public static void Test_0000__ValidForData() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), IsNullable = false, Precision = 0 }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_Precision_1 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__GUAD__as_bytes, 0); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0000__ValidForData //----------------------------------------------------------------------- [Test] public static void Test_0001__p123() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), IsNullable = false, Precision = 123 }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_Precision_1 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__GUAD__as_bytes, 123); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0001__p123 //----------------------------------------------------------------------- [Test] public static void Test_0002__m123() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), IsNullable = false, Precision = -123 }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_Precision_1 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__GUAD__as_bytes, -123); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0002__m123 };//class TestSet_ERR002__bad_Precision //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D2.Migrations.Generations.SET001.DataTypes.Clr.Guid
27.394089
122
0.639813
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D2/Migrations/Generations/SET001/DataTypes/Clr/Guid/TestSet_ERR002__bad_Precision.cs
5,563
C#
using Godot; using System.Collections.Generic; public class Game : Node2D { public List<string> Levels = new List<string>(); private PackedScene menuScene = null; private Transition transition = null; private Player player = null; private int currentId = -1; private Node currentLevel = null; public override void _Ready() { player = GetNode<Player>("Player"); menuScene = ResourceLoader.Load<PackedScene>("res://Scenes/Menu.tscn"); transition = GetNode<Transition>("Transition"); VisualServer.SetDefaultClearColor(new Color(0f, 0f, 0f, 1)); // add scenes Levels.Add("res://Scenes/Levels/Level_Cellar.tscn"); Levels.Add("res://Scenes/Levels/Level_Kitchen.tscn"); Levels.Add("res://Scenes/Levels/Level_GreatHall.tscn"); Levels.Add("res://Scenes/Levels/Level_Chimney.tscn"); Levels.Add("res://Scenes/Levels/Level_KingsHall.tscn"); LoadNextLevel(); } public void LoadNextLevel() { currentId++; if (currentId < Levels.Count) { var level = ResourceLoader.Load<PackedScene>(Levels[currentId]); if (currentLevel != null) { RemoveChild(currentLevel); (currentLevel as Node2D).QueueFree(); currentLevel = null; } currentLevel = level.Instance(); AddChild(currentLevel); } } public void GameOver() { GetTree().ChangeSceneTo(menuScene); } public void TogglePauseMode() { player.ToggleProcessing(); } public void ToggleMusic() { //AudioServer. } public void LoadEnding() { var error = GetTree().ChangeScene("res://Scenes/Levels/Level_End.tscn"); GD.Print(error); } }
24.421053
80
0.58944
[ "MIT" ]
Nimmda/LD46
Scripts/Game.cs
1,856
C#
/* Copyright (c) 2018, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 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 THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System.IO; using MatterHackers.Agg; using MatterHackers.Agg.UI; namespace MatterHackers.MatterControl { using System.Threading; using MatterHackers.Agg.Platform; using MatterHackers.DataConverters3D; using MatterHackers.PolygonMesh; using MatterHackers.PolygonMesh.Processors; using MatterHackers.RenderOpenGl; using MatterHackers.VectorMath; public class LogoSpinner { public Color MeshColor { get; set; } = Color.White; public bool SpinLogo { get; set; } = true; public LogoSpinner(GuiWidget widget, double scale = 1.6, double spinSpeed = 0.6, double yOffset = 0.5, double rotateX = -0.1) { // loading animation stuff LightingData lighting = new LightingData(); Mesh logoMesh; using (var logoStream = StaticData.Instance.OpenStream(Path.Combine("Stls", "MH Logo.stl"))) { logoMesh = StlProcessing.Load(logoStream, CancellationToken.None); } // Position var aabb = logoMesh.GetAxisAlignedBoundingBox(); logoMesh.Transform(Matrix4X4.CreateTranslation(-aabb.Center)); logoMesh.Transform(Matrix4X4.CreateScale(scale / aabb.XSize)); var anglePerDraw = 1 / MathHelper.Tau * spinSpeed; var angle = 0.0; widget.BeforeDraw += (s, e) => { var screenSpaceBounds = widget.TransformToScreenSpace(widget.LocalBounds); WorldView world = new WorldView(screenSpaceBounds.Width, screenSpaceBounds.Height); world.Translate(new Vector3(0, yOffset, 0)); world.Rotate(Quaternion.FromEulerAngles(new Vector3(rotateX, 0, 0))); GLHelper.SetGlContext(world, screenSpaceBounds, lighting); GLHelper.Render(logoMesh, this.MeshColor, Matrix4X4.CreateRotationY(angle), RenderTypes.Shaded); GLHelper.UnsetGlContext(); }; Animation spinAnimation = new Animation() { DrawTarget = widget, FramesPerSecond = 20 }; spinAnimation.Update += (s, time) => { if (this.SpinLogo) { angle += anglePerDraw; } }; spinAnimation.Start(); } } }
35.612245
127
0.759026
[ "BSD-2-Clause" ]
Bhalddin/MatterControl
MatterControlLib/ApplicationView/LogoSpinner.cs
3,492
C#
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System.IO; using System.Threading.Tasks; namespace OrderProcessor { public static class DeliveryOrderProcessor { [FunctionName("DeliveryOrderProcessor")] public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log, [CosmosDB(databaseName: "eShopByWebOrders", collectionName: "Orders", ConnectionStringSetting = "OrdersConnectionString")] IAsyncCollector<dynamic> documentsOut) { log.LogInformation($"OrderItemsReserver Started for OrderId: {req.Query["orderId"]}"); string orderId = req.Query["orderId"]; string orderDetails = await new StreamReader(req.Body).ReadToEndAsync(); string responseMessage = $"Order placed successfully. OrderId: {orderId}, OrderDetails: {orderDetails}"; dynamic data = JsonConvert.DeserializeObject(orderDetails); if (!string.IsNullOrEmpty(orderId)) { await documentsOut.AddAsync(new { id = orderId, data = data }); } return new OkObjectResult(responseMessage); } } }
36.04878
173
0.64276
[ "MIT" ]
BhuvanRam/AzureHomeTask
OrderProcessor/DeliveryOrderProcessor.cs
1,478
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.EntityFrameworkCore.Storage.ValueConversion; /// <summary> /// Converts strings to and from <see cref="bool" /> values. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-value-converters">EF Core value converters</see> for more information and examples. /// </remarks> public class StringToBoolConverter : ValueConverter<string, bool> { /// <summary> /// Creates a new instance of this converter. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-value-converters">EF Core value converters</see> for more information and examples. /// </remarks> public StringToBoolConverter() : this(null) { } /// <summary> /// Creates a new instance of this converter. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-value-converters">EF Core value converters</see> for more information and examples. /// </remarks> /// <param name="mappingHints"> /// Hints that can be used by the <see cref="ITypeMappingSource" /> to create data types with appropriate /// facets for the converted data. /// </param> public StringToBoolConverter(ConverterMappingHints? mappingHints) : base( v => Convert.ToBoolean(v), v => Convert.ToString(v), mappingHints) { } /// <summary> /// A <see cref="ValueConverterInfo" /> for the default use of this converter. /// </summary> public static ValueConverterInfo DefaultInfo { get; } = new(typeof(string), typeof(bool), i => new StringToBoolConverter(i.MappingHints)); }
37.122449
137
0.638813
[ "MIT" ]
Applesauce314/efcore
src/EFCore/Storage/ValueConversion/StringToBoolConverter.cs
1,819
C#
using Hybrid.Quartz.Dashboard.Models.Dtos; using Microsoft.AspNetCore.Mvc; using Quartz; using System.Threading.Tasks; namespace Hybrid.Quartz.Dashboard.Controllers { /// <summary> /// 定时任务 /// </summary> public class JobsController : QuartzBaseController { public IActionResult Index() { return View(); } public async Task<IActionResult> Details(string schedulerName, string jobGroup, string jobName) { IScheduler scheduler = await GetScheduler(schedulerName).ConfigureAwait(false); IJobDetail jobDetail = await scheduler.GetJobDetail(new JobKey(jobName, jobGroup)).ConfigureAwait(false); if (jobDetail == null) return View(null); return View(new JobDetailDto(jobDetail)); } public IActionResult Queued() { return View(); } public IActionResult Plan() { return View(); } public IActionResult Executing() { return View(); } public IActionResult Complete() { return View(); } public IActionResult Fail() { return View(); } public IActionResult Delete() { return View(); } public IActionResult Waiting() { return View(); } } }
22.107692
117
0.545581
[ "Apache-2.0" ]
ArcherTrister/ESoftor
src/Hybrid.Quartz/Dashboard/Controllers/JobsController.cs
1,447
C#
using UnityEngine; public class PortalCamera : MonoBehaviour { public Transform playerCamera; public Transform portal; public Transform otherPortal; void Update () { Vector3 playerOffsetFromPortal = playerCamera.position - otherPortal.position; transform.position = portal.position + playerOffsetFromPortal; float angularDifferenceBetweenPortalRotations = Quaternion.Angle(portal.rotation, otherPortal.rotation); Quaternion portalRotationalDifference = Quaternion.AngleAxis(angularDifferenceBetweenPortalRotations, Vector3.up); Vector3 newCameraDirection = portalRotationalDifference * playerCamera.forward; transform.rotation = Quaternion.LookRotation(newCameraDirection, Vector3.up); } }
37.95
122
0.774704
[ "MIT" ]
oddlord/gamedev-projects
unity/Portals/Assets/PortalCamera.cs
761
C#
/* * This file is part of LuaInterface. * * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Text; using System.Collections.Generic; using LuaCore = Lua.NET.Lua; namespace LuaInterface { public class LuaUserData : LuaBase { public LuaUserData(int reference, Lua interpreter) { _Reference = reference; _Interpreter = interpreter; } /* * Indexer for string fields of the userdata */ public object this[string field] { get { return _Interpreter.getObject(_Reference, field); } set { _Interpreter.setObject(_Reference, field, value); } } /* * Indexer for numeric fields of the userdata */ public object this[object field] { get { return _Interpreter.getObject(_Reference, field); } set { _Interpreter.setObject(_Reference, field, value); } } /* * Calls the userdata and returns its return values inside * an array */ public object[] Call(params object[] args) { return _Interpreter.callFunction(this, args); } /* * Pushes the userdata into the Lua stack */ internal void push(LuaCore.lua_State luaState) { LuaLib.lua_getref(luaState, _Reference); } public override string ToString() { return "userdata"; } } }
25.861702
80
0.70835
[ "MIT" ]
tstavrianos/Lua.NET
LuaInterface/LuaUserData.cs
2,433
C#
using UnityEngine; using UnityEngine.UI; namespace EcsLite.UI { [RequireComponent (typeof (ScrollRect))] public sealed class EcsUiScrollViewAction : EcsUiActionBase { ScrollRect _scrollView; void Awake() { _scrollView = GetComponent<ScrollRect>(); _scrollView.onValueChanged.AddListener(OnScrollViewValueChanged); } void OnScrollViewValueChanged(Vector2 value) { if (IsValidForEvent()) { ref var msg = ref Emitter.CreateEntity<EcsUiScrollViewEvent>(); msg.WidgetName = WidgetName; msg.Sender = _scrollView; msg.Value = value; } } } }
26.142857
79
0.579235
[ "MIT" ]
supremestranger/EcsLite-ui
Runtime/Actions/EcsUiScrollViewAction.cs
732
C#
using FluentAssertions; using System; using System.Linq; using Xunit; namespace PrettyConsoleHelper.Tests { public enum Season { Summer, Winter } public class InputHelperTests { readonly MockPrettyConsole _console = new(); readonly InputHelper _subject; public InputHelperTests() { _subject = new InputHelper(_console); } [Fact] public void GetEnumInput_ThrowsArgumentException_When_SentInType_IsNotAnEnum() { FluentActions.Invoking(() => _subject.GetEnumInput<int>()) .Should().ThrowExactly<ArgumentException>(); } [Fact] public void GetEnumInput_IsCaseInsensetive() { _console.ReturnValue = Season.Summer.ToString().ToLower(); var result = _subject.GetEnumInput<Season>(); result.Should().BeEquivalentTo(Season.Summer); } [Fact] public void GetIntInput_ReturnsParsedInput_WhenInValidRange() { int returnValue = 4; _console.ReturnValue = returnValue.ToString(); var result = _subject.GetIntInput(maxValue: 5, minValue: 2); result.Should().BeOfType(typeof(int)); result.Should().Be(returnValue); } [Fact] public void GetDateTime_ReturnsParesedInput_WhenValidRange() { DateTime dateTime = new(2022, 9, 10); _console.ReturnValue = dateTime.ToString(); var result = _subject.GetDateTime(minDateTime: new DateTime(2022, 1, 1), maxDateTime: new DateTime(2022, 12, 12)); result.Should().Be(dateTime); } [Fact] public void GetDateTime_ThrowsArgumentException_When_InvalidRange() { _subject.Invoking(_ => _.GetDateTime( minDateTime: new DateTime(2022, 12, 12), maxDateTime: new DateTime(2022, 1, 1))) .Should().ThrowExactly<ArgumentException>(); } [Fact] public void ParseOptions_DoesNotReturn_Options_When_ThereAreNoValues() { string[] options = { "-title", "-completed" }; var result = _subject.ParseOptions(options, options); result.Count.Should().Be(0); } [Fact] public void ParseOptions_Returns_OptionsWithValues() { string[] inputsWithoutOptions = { "clean room", "yes" }; string[] options = { "-title", "-completed" }; string[] inputs = { options[0], inputsWithoutOptions[0], options[1], inputsWithoutOptions[1] }; var result = _subject.ParseOptions(options, inputs); result.Count.Should().Be(options.Length); result[options[0]].Should().NotBeEmpty(); result[options[1]].Should().NotBeEmpty(); result[options[0]].Should().Be(inputsWithoutOptions[0]); result[options[1]].Should().Be(inputsWithoutOptions[1]); } [Fact] public void ParseOptions_Returns_Options_Without_PrefixAndToTitleCase() { string[] inputsWithoutOptions = { "clean room", "yep" }; string[] options = { "-title", "-completed" }; string[] inputs = { options[0], inputsWithoutOptions[0], options[1], inputsWithoutOptions[1]}; var result = _subject.ParseOptions(options, inputs, "-"); result.Count.Should().Be(options.Length); result.Keys.Should().Contain("Title"); } } }
31.5625
126
0.590382
[ "MIT" ]
chrisK00/PrettyConsoleHelper
PrettyConsoleHelper.Tests/InputHelperTests.cs
3,537
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Apps.AlertCenter.V1Beta1.Snippets { using Google.Apps.AlertCenter.V1Beta1; public sealed partial class GeneratedAlertCenterServiceClientStandaloneSnippets { /// <summary>Snippet for GetAlertMetadata</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void GetAlertMetadataRequestObject() { // Create client AlertCenterServiceClient alertCenterServiceClient = AlertCenterServiceClient.Create(); // Initialize request argument(s) GetAlertMetadataRequest request = new GetAlertMetadataRequest { CustomerId = "", AlertId = "", }; // Make the request AlertMetadata response = alertCenterServiceClient.GetAlertMetadata(request); } } }
37.55814
98
0.67678
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/apps/alertcenter/v1beta1/google-cloud-apps-alertcenter-v1beta1-csharp/Google.Apps.AlertCenter.V1Beta1.StandaloneSnippets/AlertCenterServiceClient.GetAlertMetadataRequestObjectSnippet.g.cs
1,615
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace Gui.Crm.Services.Hosts.WebApi.Migrations { public partial class Product_Filter : Migration { protected override void Up(MigrationBuilder migrationBuilder) { } protected override void Down(MigrationBuilder migrationBuilder) { } } }
19.666667
71
0.677966
[ "MIT" ]
xiillii/crm.services
src/hosts/Gui.Crm.Services.Hosts.WebApi/Migrations/20210418070313_Product_Filter.cs
356
C#
//---------------------------------------------- // Flip Web Apps: Game Framework // Copyright © 2016 Flip Web Apps / Mark Hewitt // // Please direct any bugs/comments/suggestions to http://www.flipwebapps.com // // The copyright owner grants to the end user a non-exclusive, worldwide, and perpetual license to this Asset // to integrate only as incorporated and embedded components of electronic games and interactive media and // distribute such electronic game and interactive media. End user may modify Assets. End user may otherwise // not reproduce, distribute, sublicense, rent, lease or lend the Assets. It is emphasized that the end // user shall not be entitled to distribute or transfer in any way (including, without, limitation by way of // sublicense) the Assets in any other way than as integrated components of electronic games and interactive media. // The above copyright notice and this permission notice must not be removed from any files. // 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. //---------------------------------------------- #if PLAYMAKER using BeautifulTransitions.Scripts.Transitions.Editor.PlayMakerActions.AbstractClasses; using BeautifulTransitions.Scripts.Transitions.PlayMakerActions.Screen; using HutongGames.PlayMakerEditor; using UnityEditor; namespace BeautifulTransitions.Scripts.Transitions.Editor.PlayMakerActions { [CustomActionEditor(typeof(BT_WipeScreen))] public class BT_WipeScreenEditor : PlayMakerTransitionScreenEditor { /// <summary> /// Override in subclasses to show GUI elements before content. /// </summary> /// <returns></returns> //protected override void ShowHeaderGUI() { } /// <summary> /// Override in subclasses to show GUI elements after content. /// </summary> /// <returns></returns> protected override void ShowFooterGUI() { base.ShowFooterGUI(); //var playMakerWipeScreen = target as PlayMakerWipeScreen; EditorGUILayout.LabelField("Wipe Screen Specific", EditorStyles.boldLabel); ShowSpecificSharedGUI(); EditField("Texture"); EditField("Color"); EditField("MaskTexture"); EditField("InvertMask"); EditField("Softness"); } } } #endif
47.762712
124
0.682399
[ "MIT" ]
Kaiweitu/eecs494_p3
Assets/FlipWebApps/BeautifulTransitions/Scripts/Transitions/Editor/PlayMakerActions/BT_WipeScreenEditor.cs
2,821
C#
namespace LTPTranslations.Data.Common.Models { using System; public interface IAuditInfo { DateTime CreatedOn { get; set; } DateTime? ModifiedOn { get; set; } } }
16.5
45
0.621212
[ "MIT" ]
AntoniyaIvanova/SoftUni
C#/C# Web/ASP.NET Core/Final Project/Data/LTPTranslations.Data.Common/Models/IAuditInfo.cs
200
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using log4net; using Manufacturing.Framework.Dto; namespace Manufacturing.DataCollector { public class MemoryRecordRepository : ILocalRecordRepository { private static readonly List<DatasourceRecord> Records = new List<DatasourceRecord>(); private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public void Push(DatasourceRecord record) { lock (Records) { Records.Add(record); } } public void Push(IEnumerable<DatasourceRecord> records) { lock (Records) { Records.AddRange(records); } } public void ProcessRecords(Action<IEnumerable<DatasourceRecord>> processor, int batchSize) { lock (Records) { var batch = Records.Take(batchSize); try { processor(batch); } catch (Exception ex) { Log.Error("Error processing record batch", ex); throw; } Records.RemoveRange(0, Math.Min(batchSize, Records.Count)); } } } }
26.884615
109
0.534335
[ "Apache-2.0" ]
ytechie/Manufacturing.DataCollector
MemoryRecordRepository.cs
1,400
C#
// ----------------------------------------------------------------------------- // Copyright (c) 2020 Paul C. // Licensed under the MPL 2.0 license. See LICENSE.txt for full information. // ----------------------------------------------------------------------------- namespace PoorMan.Mocks { using System; using System.Reflection; /// <summary> /// Represents a custom behavior that adds to existing behavior, and /// contains the options for running it. /// </summary> public class AddedBehavior : BehaviorOptions<Action<object[]>> { /// <summary> /// Initializes a new instance of the <see cref="AddedBehavior"/> class. /// </summary> /// <param name="behavior"> /// The added behavior action. /// </param> /// <param name="fullMemberName"> /// The name of the member being modified. This should be the /// full name so it can be used to uniquely identify the member. /// </param> public AddedBehavior( Action<object[]> behavior, string fullMemberName) : base(behavior, fullMemberName) { } /// <summary> /// Gets or sets a value indicating whether to run the added behavior /// before or after the member's default behavior. /// </summary> /// <value> /// <c>True</c> to run after the member's behavior, <c>false</c> /// to run before. /// </value> public bool RunAfter { get; set; } } }
35.75
84
0.502225
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
pcnova/poorman-mocks
Mocks/AddedBehavior.cs
1,575
C#
using ADP_HomeWork.DataBase.Tables; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace WCFService { [ServiceContract] public interface INewsService { [OperationContract] List<News> GetLast10(); [OperationContract] News GetSimilar(string title, string Abstract); [OperationContract] List<News> GetBestPositive(int n); [OperationContract] List<News> GetBestNegative(int n); [OperationContract] bool AddRank(int ID, int Rank); } }
19.205882
55
0.664625
[ "MIT" ]
Mohammed95m/ADP_HomeWork
WCFService/INewsService.cs
655
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text.RegularExpressions; using System.Threading.Tasks; using MapleFedNet.Model; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace MapleFedNet { public static class MastodonApi { public static MastodonApiConfigure ApiConfigure { get; } = new MastodonApiConfigure(); public static void Configure(Action<MastodonApiConfigure> config) { config?.Invoke(ApiConfigure); } } public class MastodonApiConfigure { public HttpMessageHandler HttpMessageHandler { get; set; } = new HttpClientHandler { MaxConnectionsPerServer = 20 }; } } namespace MapleFedNet.Common { internal class HttpHelper { public const string HTTPS = "https://"; public const string HTTP = "http://"; private HttpHelper() { } public static HttpHelper Instance { get; } = new HttpHelper(); private string UrlEncode(string url, IEnumerable<(string Key, string Value)> param) { return param != null ? $"{url}?{string.Join("&", param.Where(CheckForValue).Select(kvp => $"{kvp.Key}={kvp.Value}"))}" : url; } private bool CheckForValue<T>((string Key, T Value) kvp) { return !string.IsNullOrEmpty(kvp.Value?.ToString()) && (!int.TryParse(kvp.Value?.ToString(), out var intValue) || intValue > 0) && (!bool.TryParse(kvp.Value?.ToString(), out var boolValue) || boolValue); } public IEnumerable<(string, T)> ArrayEncode<T>(string paramName, params T[] values) { paramName = $"{paramName}[]"; return values.Select(value => (paramName, value)); } private HttpClient GetHttpClient(string token, string tokenType = "Bearer") { return string.IsNullOrEmpty(token) ? new HttpClient() : new HttpClient { DefaultRequestHeaders = {Authorization = new AuthenticationHeaderValue(tokenType, token)} }; } public async Task<string> GetAsync(string url, string token, params (string Key, string Value)[] param) { using (var client = GetHttpClient(token)) { return CheckForError(await client.GetStringAsync(UrlEncode(url, param))); } } public async Task<T> GetAsync<T>(string url, string token, params (string Key, string Value)[] param) { return JsonConvert.DeserializeObject<T>(await GetAsync(url, token, param)); } // public static async Task<MastodonList<T>> GetListAsync<T>(string url, string token, string max_id = "", // string since_id = "", params (string Key, string Value)[] param) // { // var p = new List<(string Key, string Value)> // { // (nameof(max_id), max_id.ToString()), // (nameof(since_id), since_id.ToString()) // }; // if (param != null) // p.AddRange(param); // return await GetListAsync<T>(url, token, p); // } internal async Task<MastodonList<T>> GetListAsync<T>(string url, string token, string max_id = "", string since_id = "", params (string Key, string Value)[] param) { var p = new List<(string Key, string Value)> { (nameof(max_id), max_id.ToString()), (nameof(since_id), since_id.ToString()) }; param = param != null ? param.Concat(p).ToArray() : p.ToArray(); using (var client = GetHttpClient(token)) using (var res = await client.GetAsync(UrlEncode(url, param))) { if (!res.Headers.TryGetValues("Link", out var values)) return new MastodonList<T>( JsonConvert.DeserializeObject<List<T>>(await res.Content.ReadAsStringAsync())) { MaxId = "", SinceId = "" }; var links = values.FirstOrDefault().Split(',').Select(s => Regex.Match(s, "<.*(max_id|since_id)=([0-9A-Za-z]*)(.*)>; rel=\"(.*)\"").Groups).ToList(); return new MastodonList<T>( JsonConvert.DeserializeObject<List<T>>(await res.Content.ReadAsStringAsync())) { MaxId = links.FirstOrDefault(m => m[1].Value == "max_id")?[2]?.Value, SinceId = links.FirstOrDefault(m => m[1].Value == "since_id")?[2]?.Value }; } } public async Task<T> PostAsync<T, TValue>(string url, string token, params (string Key, TValue Value)[] param) { return JsonConvert.DeserializeObject<T>(await PostAsync(url, token, param)); } public async Task<string> PostAsync<TValue>(string url, string token, params (string Key, TValue Value)[] param) { return await HttpMethodAsync(url, token, HttpMethod.Post, param); } public async Task<T> PutAsync<T, TValue>(string url, string token, params (string Key, TValue Value)[] param) { return JsonConvert.DeserializeObject<T>(await PutAsync(url, token, param)); } public async Task<string> PutAsync<TValue>(string url, string token, params (string Key, TValue Value)[] param) { return await HttpMethodAsync(url, token, HttpMethod.Put, param); } public async Task<T> DeleteAsync<T, TValue>(string url, string token, params (string Key, TValue Value)[] param) { return JsonConvert.DeserializeObject<T>(await DeleteAsync(url, token, param)); } public async Task<string> DeleteAsync<TValue>(string url, string token, params (string Key, TValue Value)[] param) { return await HttpMethodAsync(url, token, HttpMethod.Delete, param); } public async Task<string> PatchAsync<TValue>(string url, string token, params (string Key, TValue Value)[] param) { return await HttpMethodAsync(url, token, new HttpMethod("PATCH"), param); } private async Task<string> HttpMethodAsync<TValue>(string url, string token, HttpMethod method, params (string Key, TValue Value)[] param) { using (var client = GetHttpClient(token)) { if (param == null) param = new List<(string Key, TValue Value)>().ToArray(); if (param.Select(p => p.Value).Any(item => item is HttpContent)) using (var formData = new MultipartFormDataContent()) { foreach (var item in param) if (item.Value is StreamContent) formData.Add(item.Value as StreamContent, item.Key, "file"); else if (CheckForValue(item)) formData.Add(item.Value as HttpContent, item.Key); using (var res = await client.SendAsync(new HttpRequestMessage(method, url) {Content = formData})) { return CheckForError(await res.Content.ReadAsStringAsync()); } } client.Timeout = TimeSpan.FromSeconds(30); var items = param.Where(CheckForValue) .Select(item => new KeyValuePair<string, string>(item.Key, item.Value.ToString())); using (var formData = new FormUrlEncodedContent(items)) using (var res = await client.SendAsync(new HttpRequestMessage(method, url) {Content = formData})) { return CheckForError(await res.Content.ReadAsStringAsync()); } } } private string CheckForError(string json) { if (string.IsNullOrEmpty(json)) return json; if (json.StartsWith("<html>")) throw new MastodonException("Return json is not valid"); try { var jobj = JsonConvert.DeserializeObject<JObject>(json); if (jobj.TryGetValue("error", out var token)) throw new MastodonException(token.Value<string>()); } catch (InvalidCastException) { } return json; } } }
38.798246
114
0.54454
[ "MIT" ]
IsaacSchemm/MapleFedNet
MapleFedNet/Common/HttpHelper.cs
8,848
C#
using System; using System.Collections.Generic; namespace Dissonance.Engine { internal sealed class MessageManager : EngineModule { private static class MessageData<T> where T : struct { public static List<T>[] messagesByWorld = Array.Empty<List<T>>(); static MessageData() { ClearLists += Clear; } private static void Clear() { for (int i = WorldManager.DefaultWorldId; i < messagesByWorld.Length; i++) { messagesByWorld[i].Clear(); } } } private static event Action ClearLists; [HookPosition(1000)] protected override void FixedUpdate() { ClearMessages(); } [HookPosition(1000)] protected override void RenderUpdate() { ClearMessages(); } internal static void SendMessage<T>(int worldId, in T message) where T : struct { if (worldId >= MessageData<T>.messagesByWorld.Length) { Array.Resize(ref MessageData<T>.messagesByWorld, worldId + 1); MessageData<T>.messagesByWorld[worldId] = new List<T>(); } MessageData<T>.messagesByWorld[worldId].Add(message); } internal static MessageEnumerator<T> ReadMessages<T>(int worldId) where T : struct { if (worldId >= MessageData<T>.messagesByWorld.Length) { return default; } return new MessageEnumerator<T>(MessageData<T>.messagesByWorld[worldId]); } internal static void ClearMessages() { ClearLists?.Invoke(); } } }
21.446154
84
0.685796
[ "MIT" ]
Mirsario/DissonanceEngine
Src/Core/ECS/Messages/MessageManager.cs
1,396
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 WpfApplication2.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.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.516129
151
0.583178
[ "MIT" ]
mantamusica/interfacesDesign
UD2_InterfacesXML/Ejercicios basicos/WpfApplication2/Properties/Settings.Designer.cs
1,072
C#
using System; using System.Text; namespace S22.Imap.Auth.Sasl.Mechanisms.Ntlm { /// <summary> /// Represents an NTLM Type 1 Message. /// </summary> internal class Type1Message { /// <summary> /// The NTLM message signature which is always "NTLMSSP". /// </summary> static readonly string signature = "NTLMSSP"; /// <summary> /// The NTML message type which is always 1 for an NTLM Type 1 message. /// </summary> static readonly MessageType type = MessageType.Type1; /// <summary> /// The NTLM flags set on this instance. /// </summary> internal Flags Flags { get; set; } /// <summary> /// The supplied domain name as an array of bytes in the ASCII /// range. /// </summary> byte[] domain { get; set; } /// <summary> /// The offset within the message where the domain name data starts. /// </summary> int domainOffset { get { // We send a version 3 NTLM type 1 message. return 40; } } /// <summary> /// The supplied workstation name as an array of bytes in the /// ASCII range. /// </summary> byte[] workstation { get; set; } /// <summary> /// The offset within the message where the workstation name data starts. /// </summary> int workstationOffset { get { return domainOffset + domain.Length; } } /// <summary> /// The length of the supplied workstation name as a 16-bit short value. /// </summary> short workstationLength { get { return Convert.ToInt16(workstation.Length); } } /// <summary> /// Contains information about the client's OS version. /// </summary> OSVersion OSVersion { get; set; } /// <summary> /// Creates a new instance of the Type1Message class using the specified /// domain and workstation names. /// </summary> /// <param name="domain">The domain in which the client's workstation has /// membership.</param> /// <param name="workstation">The client's workstation name.</param> /// <exception cref="ArgumentNullException">Thrown if the domain or the /// workstation parameter is null.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown if the domain /// or the workstation name exceeds the maximum allowed string /// length.</exception> /// <remarks>The domain as well as the workstation name is restricted /// to ASCII characters and must not be longer than 65536 characters. /// </remarks> public Type1Message(string domain, string workstation) { // Fixme: Is domain mandatory? domain.ThrowIfNull("domain"); workstation.ThrowIfNull("workstation"); this.domain = Encoding.ASCII.GetBytes(domain); if (this.domain.Length >= Int16.MaxValue) { throw new ArgumentOutOfRangeException("The supplied domain name must " + "not be longer than " + Int16.MaxValue); } this.workstation = Encoding.ASCII.GetBytes(workstation); if (this.workstation.Length >= Int16.MaxValue) { throw new ArgumentOutOfRangeException("The supplied workstation name " + "must not be longer than " + Int16.MaxValue); } Flags = Flags.NegotiateUnicode | Flags.RequestTarget | Flags.NegotiateNTLM | Flags.NegotiateDomainSupplied | Flags.NegotiateWorkstationSupplied; // We spoof an OS version of Windows 7 Build 7601. OSVersion = new OSVersion(6, 1, 7601); } /// <summary> /// Serializes this instance of the Type1 class to an array of bytes. /// </summary> /// <returns>An array of bytes representing this instance of the Type1 /// class.</returns> public byte[] Serialize() { return new ByteBuilder() .Append(signature + "\0") .Append((int) type) .Append((int) Flags) .Append(new SecurityBuffer(domain, domainOffset).Serialize()) .Append(new SecurityBuffer(workstation, workstationOffset).Serialize()) .Append(OSVersion.Serialize()) .Append(domain) .Append(workstation) .ToArray(); } } }
28.518248
79
0.6688
[ "MIT" ]
AlexSte/S22.Imap
Auth/Sasl/Mechanisms/Ntlm/Type1Message.cs
3,909
C#
//****************************************************************************************************** // IBinaryImageParser.cs - Gbtc // // Copyright © 2012, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may // not use this file except in compliance with the License. You may obtain a copy of the License at: // // http://www.opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 01/14/2005 - J. Ritchie Carroll // Generated original version of source code. // 09/14/2009 - Stephen C. Wills // Added new header and license agreement. // 12/14/2012 - Starlynn Danyelle Gilliam // Modified Header. // //****************************************************************************************************** using System; namespace Gemstone.IO.Parsing { /// <summary> /// This interface represents the protocol independent representation of a streaming data parser. /// </summary> public interface IBinaryImageParser : IProvideStatus { /// <summary> /// Occurs when data image fails deserialization due to an exception. /// </summary> /// <remarks> /// <see cref="EventArgs{T}.Argument"/> is the remaining portion of the binary image that failed to parse. /// </remarks> event EventHandler<EventArgs<byte[]>> DataDiscarded; /// <summary> /// Occurs when an <see cref="Exception"/> is encountered while attempting to parse data. /// </summary> /// <remarks> /// <see cref="EventArgs{T}.Argument"/> is the <see cref="Exception"/> encountered while parsing data. /// </remarks> event EventHandler<EventArgs<Exception>> ParsingException; /// <summary> /// Start the streaming data parser. /// </summary> void Start(); /// <summary> /// Stops the streaming data parser. /// </summary> void Stop(); /// <summary> /// Gets or sets a boolean value that indicates whether the data parser is currently enabled. /// </summary> bool Enabled { get; set; } /// <summary> /// Gets the total number of buffer images processed so far. /// </summary> long TotalProcessedBuffers { get; } /// <summary> /// Writes a sequence of bytes onto the <see cref="IBinaryImageParser"/> stream for parsing. /// </summary> /// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param> /// <param name="count">The number of bytes to be written to the current stream.</param> void Write(byte[] buffer, int offset, int count); } }
43.182927
132
0.589099
[ "MIT" ]
gemstone/common
src/Gemstone/IO/Parsing/IBinaryImageParser.cs
3,544
C#
using System; using System.Threading; using Zero.Foundation.Aspect; using Zero.Foundation.Daemons; namespace Zero.Foundation.Unity { public class ExpireStaticLifetimeDaemon : ChokeableClass, IDaemonTask { public ExpireStaticLifetimeDaemon(IFoundation iFoundation) : base(iFoundation) { } #region Statics private static object _DaemonRoot = new object(); private static IDaemonTask _DaemonInstance; public static void EnsureDaemon() { try { if (_DaemonInstance == null) { lock (_DaemonRoot) { if (_DaemonInstance == null) { IFoundation iFoundation = CoreFoundation.Current; IDaemonManager daemonManager = iFoundation.GetDaemonManager(); IDaemonTask daemonTask = daemonManager.GetRegisteredDaemonTask(DAEMON_NAME); if (daemonTask == null) { ExpireStaticLifetimeDaemon daemon = new ExpireStaticLifetimeDaemon(iFoundation); DaemonConfig config = new DaemonConfig() { InstanceName = DAEMON_NAME, ContinueOnError = true, IntervalMilliSeconds = 15000, // clean up every 15 seconds StartDelayMilliSeconds = 15000, TaskConfiguration = string.Empty }; daemonManager.RegisterDaemon(config, daemon, true); _DaemonInstance = daemon; } else { // should be impossible [but other bad-actors] _DaemonInstance = daemonTask; } } } } } catch { // gulp } } #endregion #region IDaemonTask Members public const string DAEMON_NAME = "ExpireStaticLifetimeDaemon"; protected static bool _executing; public string DaemonName { get { return DAEMON_NAME; } protected set { } } public void Dispose() { } public void Execute(IFoundation iFoundation, CancellationToken token) { base.ExecuteMethod("Execute", delegate () { if (_executing) { return; } // safety try { _executing = true; this.CleanLifetime(); } finally { _executing = false; } }); } public DaemonSynchronizationPolicy SynchronizationPolicy { get { return DaemonSynchronizationPolicy.SingleAppDomain; } } #endregion #region Protected Methods protected void CleanLifetime() { base.ExecuteMethod("CleanLifetime", delegate () { try { ExpireStaticLifetimeManager.CleanExpiredValues(); } catch { // gulp } }); } #endregion } }
25.409091
104
0.48062
[ "MIT" ]
wmansfield/zero.foundation
Zero.Foundation.Core/Unity/ExpireStaticLifetimeDaemon.cs
3,354
C#