content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Threading.Tasks; using ExamApp.Infrastructure.DTO; namespace ExamApp.Infrastructure.Services { public interface IJwtHandler { JwtDto CreateToken(Guid userId, string role); } }
20.272727
53
0.744395
[ "MIT" ]
UTPOrganization/ExamApp
src/ExamApp.Infrastructure/Services/IJwtHandler.cs
223
C#
using DevilDaggersCore.Game; using DevilDaggersCustomLeaderboards.Clients; using DevilDaggersCustomLeaderboards.Enumerators; using DevilDaggersCustomLeaderboards.Memory; using DevilDaggersCustomLeaderboards.Memory.Variables; using System; using Cmd = DevilDaggersCustomLeaderboards.Utils.ConsoleUtils; namespace DevilDaggersCustomLeaderboards.Utils { public static class GuiUtils { public static void WriteRecording() { Cmd.WriteLine($"Scanning process '{Scanner.Process?.ProcessName ?? "No process"}' ({Scanner.Process?.MainWindowTitle ?? "No title"})..."); Cmd.WriteLine(); Cmd.WriteLine("Player ID", Scanner.PlayerId); Cmd.WriteLine("Player Name", Scanner.PlayerName); Cmd.WriteLine(); #if DEBUG WriteDebug(); #endif if (Scanner.IsInGame) { Cmd.WriteLine("Player", Scanner.IsPlayerAlive ? "Alive" : (GameInfo.GetDeathByType(DevilDaggersCore.Game.GameVersion.V31, Scanner.DeathType)?.Name ?? "Invalid death type"), Scanner.IsPlayerAlive ? CustomColor.Gray : ColorUtils.GetDeathColor(Scanner.DeathType)); Cmd.WriteLine(); Cmd.WriteLine("Time", Scanner.Time.Value.ToString("0.0000")); Cmd.WriteLine(); Cmd.WriteLine("Hand", $"Level {GetHand(Scanner.LevelGems)}"); Cmd.WriteLine("Level 2", Scanner.LevelUpTime2.Value.ToString("0.0000")); Cmd.WriteLine("Level 3", Scanner.LevelUpTime3.Value.ToString("0.0000")); Cmd.WriteLine("Level 4", Scanner.LevelUpTime4.Value.ToString("0.0000")); Cmd.WriteLine(); WriteVariable("Gems Collected", Scanner.GemsCollected, CustomColor.Red); WriteVariable("Gems Despawned", Scanner.GemsDespawned, CustomColor.Red); WriteVariable("Gems Eaten", Scanner.GemsEaten, CustomColor.Green); WriteVariable("Gems Total", Scanner.GemsTotal, CustomColor.Red); Cmd.WriteLine("Gems In Arena", Math.Max(0, Scanner.GemsTotal - Scanner.GemsCollected - Scanner.GemsDespawned - Scanner.GemsEaten)); Cmd.WriteLine(); WriteVariable("Homing Stored", Scanner.HomingDaggers, CustomColor.Magenta); WriteVariable("Homing Eaten", Scanner.HomingDaggersEaten, CustomColor.Ghostpede); Cmd.WriteLine(); WriteEnemyHeaders("Enemies", "Alive", "Killed"); WriteEnemyVariables("Total", Scanner.EnemiesAlive, Scanner.EnemiesKilled, ColorUtils.Entangled); WriteEnemyVariables("Skull I", Scanner.Skull1sAlive, Scanner.Skull1sKilled, ColorUtils.Swarmed); WriteEnemyVariables("Skull II", Scanner.Skull2sAlive, Scanner.Skull2sKilled, ColorUtils.Impaled); WriteEnemyVariables("Skull III", Scanner.Skull3sAlive, Scanner.Skull3sKilled, ColorUtils.Gored); WriteEnemyVariables("Skull IV", Scanner.Skull4sAlive, Scanner.Skull4sKilled, ColorUtils.Opened); WriteEnemyVariables("Squid I", Scanner.Squid1sAlive, Scanner.Squid1sKilled, ColorUtils.Purged); WriteEnemyVariables("Squid II", Scanner.Squid2sAlive, Scanner.Squid2sKilled, ColorUtils.Desecrated); WriteEnemyVariables("Squid III", Scanner.Squid3sAlive, Scanner.Squid3sKilled, ColorUtils.Sacrificed); WriteEnemyVariables("Spiderling", Scanner.SpiderlingsAlive, Scanner.SpiderlingsKilled, ColorUtils.Infested); WriteEnemyVariables("Spider I", Scanner.Spider1sAlive, Scanner.Spider1sKilled, ColorUtils.Intoxicated); WriteEnemyVariables("Spider II", Scanner.Spider2sAlive, Scanner.Spider2sKilled, ColorUtils.Envenomated); WriteEnemyVariables("Spider Egg", Scanner.SpiderEggsAlive, Scanner.SpiderEggsKilled, ColorUtils.Intoxicated); WriteEnemyVariables("Centipede", Scanner.CentipedesAlive, Scanner.CentipedesKilled, ColorUtils.Eviscerated); WriteEnemyVariables("Gigapede", Scanner.GigapedesAlive, Scanner.GigapedesKilled, ColorUtils.Annihilated); WriteEnemyVariables("Ghostpede", Scanner.GhostpedesAlive, Scanner.GhostpedesKilled, ColorUtils.Haunted); WriteEnemyVariables("Thorn", Scanner.ThornsAlive, Scanner.ThornsKilled, ColorUtils.Entangled); WriteEnemyVariables("Leviathan", Scanner.LeviathansAlive, Scanner.LeviathansKilled, ColorUtils.Incarnated); WriteEnemyVariables("Orb", Scanner.OrbsAlive, Scanner.OrbsKilled, ColorUtils.Discarnated); Cmd.WriteLine(); WriteVariable("Daggers Hit", Scanner.DaggersHit, CustomColor.Green); WriteVariable("Daggers Fired", Scanner.DaggersFired, CustomColor.Yellow); Cmd.WriteLine("Accuracy", $"{(Scanner.DaggersFired == 0 ? 0 : Scanner.DaggersHit / (float)Scanner.DaggersFired * 100):0.00}%"); Cmd.WriteLine(); Cmd.WriteLine("Leviathan Down", Scanner.LeviathanDownTime.Value.ToString("0.0000")); Cmd.WriteLine("Orb Down", Scanner.OrbDownTime.Value.ToString("0.0000")); Cmd.WriteLine(); } else { Cmd.WriteLine("Not in game", string.Empty); for (int i = 0; i < 47; i++) Cmd.WriteLine(); } static int GetHand(int levelGems) { if (levelGems < 10) return 1; if (levelGems < 70) return 2; if (levelGems == 70) return 3; return 4; } static void WriteVariable<T>(object textLeft, AbstractVariable<T> variable, CustomColor foregroundColorModify, CustomColor foregroundColor = ColorUtils.ForegroundDefault, CustomColor backgroundColor = ColorUtils.BackgroundDefault) { Console.ForegroundColor = (ConsoleColor)foregroundColor; Console.BackgroundColor = (ConsoleColor)backgroundColor; Console.Write($"{textLeft,-Cmd.TextWidthLeft}"); if (variable.IsChanged) Console.ForegroundColor = (ConsoleColor)foregroundColorModify; Console.Write($"{variable,Cmd.TextWidthRight}"); Console.BackgroundColor = (ConsoleColor)backgroundColor; Console.WriteLine($"{new string(' ', Cmd.TextWidthFull)}"); } static void WriteEnemyHeaders(object textLeft, string variableHeaderLeft, string variableHeaderRight, CustomColor foregroundColor = ColorUtils.ForegroundDefault, CustomColor backgroundColor = ColorUtils.BackgroundDefault) { Console.ForegroundColor = (ConsoleColor)foregroundColor; Console.BackgroundColor = (ConsoleColor)backgroundColor; Console.Write($"{textLeft,-Cmd.TextWidthLeft}"); Console.Write($"{variableHeaderLeft,Cmd.TextWidthRight - Cmd.LeftMargin}"); Console.Write($"{variableHeaderRight,Cmd.TextWidthRight - Cmd.RightMargin}"); Console.WriteLine($"{new string(' ', Cmd.TextWidthFull)}"); } static void WriteEnemyVariables<T>(object textLeft, AbstractVariable<T> variableLeft, AbstractVariable<T> variableRight, CustomColor enemyColor, CustomColor foregroundColor = ColorUtils.ForegroundDefault, CustomColor backgroundColor = ColorUtils.BackgroundDefault) { Console.ForegroundColor = (ConsoleColor)enemyColor; Console.BackgroundColor = (ConsoleColor)backgroundColor; Console.Write($"{textLeft,-Cmd.TextWidthLeft}"); Console.ForegroundColor = (ConsoleColor)(variableLeft.IsChanged ? enemyColor : foregroundColor); Console.Write($"{variableLeft,Cmd.TextWidthRight - Cmd.LeftMargin}"); Console.ForegroundColor = (ConsoleColor)(variableRight.IsChanged ? enemyColor : foregroundColor); Console.Write($"{variableRight,Cmd.TextWidthRight - Cmd.RightMargin}"); Console.BackgroundColor = (ConsoleColor)backgroundColor; Console.WriteLine($"{new string(' ', Cmd.TextWidthFull)}"); } } #if DEBUG private static void WriteDebug() { Cmd.WriteLine("Is Player Alive", Scanner.IsPlayerAlive); Cmd.WriteLine("Is Replay", Scanner.IsReplay); Cmd.WriteLine("Is In-Game", Scanner.IsInGame); Cmd.WriteLine("Status", (Status)Scanner.Status.Value); Cmd.WriteLine("SurvivalHash", HashUtils.ByteArrayToHexString(Scanner.SurvivalHashMd5)); Cmd.WriteLine(); Cmd.WriteLine("Homing Max", Scanner.HomingMax); Cmd.WriteLine("Homing Max Time", Scanner.HomingMaxTime.Value.ToString("0.0000")); Cmd.WriteLine("Enemies Alive Max", Scanner.EnemiesAliveMax); Cmd.WriteLine("Enemies Alive Max Time", Scanner.EnemiesAliveMaxTime.Value.ToString("0.0000")); Cmd.WriteLine("Max Time", Scanner.MaxTime.Value.ToString("0.0000")); Cmd.WriteLine(); Cmd.WriteLine("Stats Base", Scanner.StatsBase); Cmd.WriteLine("Stats Count", Scanner.StatsCount); Cmd.WriteLine("Stats Loaded", Scanner.StatsLoaded); Cmd.WriteLine(); Cmd.WriteLine("Prohibited Mods", Scanner.ProhibitedMods); Cmd.WriteLine(); Cmd.WriteLine("Replay Base", Scanner.ReplayBase); Cmd.WriteLine("Replay Length", Scanner.ReplayLength); Cmd.WriteLine(); } #endif public static void WriteStats(GetCustomLeaderboard leaderboard, CustomEntry? entry) { if (entry == null) { // Should never happen. Cmd.WriteLine("Current player not found on the leaderboard."); return; } double accuracy = Scanner.DaggersFired == 0 ? 0 : Scanner.DaggersHit / (double)Scanner.DaggersFired; double accuracyOld = entry.DaggersFired == 0 ? 0 : entry.DaggersHit / (double)entry.DaggersFired; Cmd.Write($"{GameInfo.GetDeathByType(DevilDaggersCore.Game.GameVersion.V31, Scanner.DeathType)?.Name ?? "Invalid death type"}", ColorUtils.GetDeathColor(Scanner.DeathType)); Cmd.WriteLine(); Cmd.WriteLine(); int timeDiff = Scanner.Time.ConvertToTimeInt() - entry.Time; Cmd.Write($"{"Time",-Cmd.TextWidthLeft}"); Cmd.Write($"{Scanner.Time.Value,Cmd.TextWidthRight:0.0000}", ColorUtils.GetDaggerColor(Scanner.Time.ConvertToTimeInt(), leaderboard)); Cmd.WriteLine($" ({(timeDiff < 0 ? string.Empty : "+")}{timeDiff / 10000f:0.0000})", ColorUtils.Worse); #if DEBUG WriteDebug(); #endif WriteIntField("Gems Collected", Scanner.GemsCollected, Scanner.GemsCollected - entry.GemsCollected); WriteIntField("Gems Despawned", Scanner.GemsDespawned, Scanner.GemsDespawned - entry.GemsDespawned, true); WriteIntField("Gems Eaten", Scanner.GemsEaten, Scanner.GemsEaten - entry.GemsEaten, true); WriteIntField("Gems Total", Scanner.GemsTotal, Scanner.GemsTotal - entry.GemsTotal); WriteIntField("Enemies Killed", Scanner.EnemiesKilled, Scanner.EnemiesKilled - entry.EnemiesKilled); WriteIntField("Enemies Alive", Scanner.EnemiesAlive, Scanner.EnemiesAlive - entry.EnemiesAlive); WriteIntField("Daggers Fired", Scanner.DaggersFired, Scanner.DaggersFired - entry.DaggersFired); WriteIntField("Daggers Hit", Scanner.DaggersHit, Scanner.DaggersHit - entry.DaggersHit); WritePercentageField("Accuracy", accuracy, accuracy - accuracyOld); WriteIntField("Homing Stored", Scanner.HomingDaggers, Scanner.HomingDaggers - entry.HomingDaggers); WriteIntField("Homing Eaten", Scanner.HomingDaggersEaten, Scanner.HomingDaggersEaten - entry.HomingDaggersEaten); WriteTimeField("Level 2", Scanner.LevelUpTime2.ConvertToTimeInt(), Scanner.LevelUpTime2.ConvertToTimeInt() - entry.LevelUpTime2); WriteTimeField("Level 3", Scanner.LevelUpTime3.ConvertToTimeInt(), Scanner.LevelUpTime3.ConvertToTimeInt() - entry.LevelUpTime3); WriteTimeField("Level 4", Scanner.LevelUpTime4.ConvertToTimeInt(), Scanner.LevelUpTime4.ConvertToTimeInt() - entry.LevelUpTime4); static void WriteIntField(string fieldName, int value, int valueDiff, bool negate = false) { Cmd.Write($"{fieldName,-Cmd.TextWidthLeft}{value,Cmd.TextWidthRight}"); Cmd.WriteLine($" ({valueDiff:+0;-#})", ColorUtils.GetImprovementColor(valueDiff * (negate ? -1 : 1))); } static void WritePercentageField(string fieldName, double value, double valueDiff) { Cmd.Write($"{fieldName,-Cmd.TextWidthLeft}{value,Cmd.TextWidthRight:0.00%}"); Cmd.WriteLine($" ({(valueDiff < 0 ? string.Empty : "+")}{valueDiff:0.00%})", ColorUtils.GetImprovementColor(valueDiff)); } static void WriteTimeField(string fieldName, int value, int valueDiff) { Cmd.Write($"{fieldName,-Cmd.TextWidthLeft}{(value == 0 ? "N/A" : $"{value / 10000f:0.0000}"),Cmd.TextWidthRight:0.0000}"); if (value == 0 || valueDiff == value) Cmd.WriteLine(); else Cmd.WriteLine($" ({(valueDiff < 0 ? string.Empty : "+")}{valueDiff / 10000f:0.0000})", ColorUtils.GetImprovementColor(-valueDiff)); } } public static bool IsHighscore(this UploadSuccess us) => us.Rank != 0; public static void WriteLeaderboard(this UploadSuccess us, int currentPlayerId) { for (int i = 0; i < us.TotalPlayers; i++) { int spaceCountCurrent = (i + 1).ToString().Length; int spaceCountTotal = us.TotalPlayers.ToString().Length; CustomEntry entry = us.Entries[i]; CustomColor daggerColor = ColorUtils.GetDaggerColor(entry.Time, us.Leaderboard); bool isCurrentPlayer = entry.PlayerId == currentPlayerId; CustomColor foregroundColor = isCurrentPlayer ? ColorUtils.GetDaggerHighlightColor(daggerColor) : daggerColor; CustomColor backgroundColor = isCurrentPlayer ? daggerColor : ColorUtils.BackgroundDefault; Cmd.Write($"{new string(' ', spaceCountTotal - spaceCountCurrent)}{i + 1}. ", foregroundColor, backgroundColor); Cmd.Write($"{entry.PlayerName.Substring(0, Math.Min(entry.PlayerName.Length, Cmd.TextWidthLeft))}", foregroundColor, backgroundColor); Cmd.Write($"{entry.Time / 10000f,Cmd.TextWidthRight:0.0000}\n", foregroundColor, backgroundColor); } Console.BackgroundColor = (ConsoleColor)ColorUtils.BackgroundDefault; } public static void WriteHighscoreStats(this UploadSuccess us) { int deathType = us.Entries[us.Rank - 1].DeathType; double accuracy = us.DaggersFired == 0 ? 0 : us.DaggersHit / (double)us.DaggersFired; int shotsHitOld = us.DaggersHit - us.DaggersHitDiff; int shotsFiredOld = us.DaggersFired - us.DaggersFiredDiff; double accuracyOld = shotsFiredOld == 0 ? 0 : shotsHitOld / (double)shotsFiredOld; double accuracyDiff = accuracy - accuracyOld; Cmd.Write($"{GameInfo.GetDeathByType(DevilDaggersCore.Game.GameVersion.V31, deathType)?.Name ?? "Invalid death type"}", ColorUtils.GetDeathColor(deathType)); Cmd.WriteLine(); Cmd.WriteLine(); Cmd.Write($"{"Rank",-Cmd.TextWidthLeft}{$"{us.Rank} / {us.TotalPlayers}",Cmd.TextWidthRight}"); if (!us.IsNewPlayerOnThisLeaderboard) Cmd.Write($" ({us.RankDiff:+0;-#})", ColorUtils.GetImprovementColor(us.RankDiff)); Cmd.WriteLine(); float time = us.Time / 10000f; float timeDiff = us.TimeDiff / 10000f; Cmd.Write($"{"Time",-Cmd.TextWidthLeft}"); Cmd.Write($"{time,Cmd.TextWidthRight:0.0000}", ColorUtils.GetDaggerColor(us.Time, us.Leaderboard)); if (!us.IsNewPlayerOnThisLeaderboard) Cmd.Write($" ({(timeDiff < 0 ? string.Empty : "+")}{timeDiff:0.0000})", ColorUtils.Better); Cmd.WriteLine(); WriteIntField(!us.IsNewPlayerOnThisLeaderboard, "Gems Collected", us.GemsCollected, us.GemsCollectedDiff); WriteIntField(!us.IsNewPlayerOnThisLeaderboard, "Gems Despawned", us.GemsDespawned, us.GemsDespawnedDiff, true); WriteIntField(!us.IsNewPlayerOnThisLeaderboard, "Gems Eaten", us.GemsEaten, us.GemsEatenDiff, true); WriteIntField(!us.IsNewPlayerOnThisLeaderboard, "Gems Total", us.GemsTotal, us.GemsTotalDiff); WriteIntField(!us.IsNewPlayerOnThisLeaderboard, "Enemies Killed", us.EnemiesKilled, us.EnemiesKilledDiff); WriteIntField(!us.IsNewPlayerOnThisLeaderboard, "Enemies Alive", us.EnemiesAlive, us.EnemiesAliveDiff); WriteIntField(!us.IsNewPlayerOnThisLeaderboard, "Daggers Fired", us.DaggersFired, us.DaggersFiredDiff); WriteIntField(!us.IsNewPlayerOnThisLeaderboard, "Daggers Hit", us.DaggersHit, us.DaggersHitDiff); WritePercentageField(!us.IsNewPlayerOnThisLeaderboard, "Accuracy", accuracy, accuracyDiff); WriteIntField(!us.IsNewPlayerOnThisLeaderboard, "Homing Stored", us.HomingDaggers, us.HomingDaggersDiff); WriteIntField(!us.IsNewPlayerOnThisLeaderboard, "Homing Eaten", us.HomingDaggersEaten, us.HomingDaggersEatenDiff); WriteTimeField(!us.IsNewPlayerOnThisLeaderboard && us.LevelUpTime2 != us.LevelUpTime2Diff, "Level 2", us.LevelUpTime2, us.LevelUpTime2Diff); WriteTimeField(!us.IsNewPlayerOnThisLeaderboard && us.LevelUpTime3 != us.LevelUpTime3Diff, "Level 3", us.LevelUpTime3, us.LevelUpTime3Diff); WriteTimeField(!us.IsNewPlayerOnThisLeaderboard && us.LevelUpTime4 != us.LevelUpTime4Diff, "Level 4", us.LevelUpTime4, us.LevelUpTime4Diff); static void WriteTimeField(bool writeDifference, string fieldName, int value, int valueDiff) { Cmd.Write($"{fieldName,-Cmd.TextWidthLeft}{value / 10000f,Cmd.TextWidthRight:0.0000}"); if (writeDifference) Cmd.Write($" ({(valueDiff < 0 ? string.Empty : "+")}{valueDiff / 10000f:0.0000})", ColorUtils.GetImprovementColor(-valueDiff)); Cmd.WriteLine(); } static void WritePercentageField(bool writeDifference, string fieldName, double value, double valueDiff) { Cmd.Write($"{fieldName,-Cmd.TextWidthLeft}{value,Cmd.TextWidthRight:0.00%}"); if (writeDifference) Cmd.Write($" ({(valueDiff < 0 ? string.Empty : "+")}{valueDiff:0.00%})", ColorUtils.GetImprovementColor(valueDiff)); Cmd.WriteLine(); } static void WriteIntField(bool writeDifference, string fieldName, int value, int valueDiff, bool negate = false) { Cmd.Write($"{fieldName,-Cmd.TextWidthLeft}{value,Cmd.TextWidthRight}"); if (writeDifference) Cmd.Write($" ({valueDiff:+0;-#})", ColorUtils.GetImprovementColor(valueDiff * (negate ? -1 : 1))); Cmd.WriteLine(); } } } }
53.619497
267
0.746173
[ "Unlicense" ]
NoahStolk/DevilDaggersCustomLeaderboards
DevilDaggersCustomLeaderboards/Utils/GuiUtils.cs
17,051
C#
/* Copyright © Bryan Apellanes 2015 */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bam.Net.Analytics { public delegate void ActionChangedDelegate(ICrawler crawler, ActionChangedEventArgs args); }
20.428571
94
0.79021
[ "MIT" ]
BryanApellanes/bam.net.shared
Analytics/ActionChangedDelegate.cs
287
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("PatternMatching")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Release")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("PatternMatching")] [assembly: System.Reflection.AssemblyTitleAttribute("PatternMatching")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.541667
80
0.652959
[ "MIT" ]
Caarhus/CSharp-PatternMatching
obj/Release/netcoreapp3.1/PatternMatching.AssemblyInfo.cs
997
C#
#if !NETSTANDARD13 /* * 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 alexaforbusiness-2017-11-09.normal.json service model. */ using Amazon.Runtime; namespace Amazon.AlexaForBusiness.Model { /// <summary> /// Paginator for the ListSkills operation ///</summary> public interface IListSkillsPaginator { /// <summary> /// Enumerable containing all full responses for the operation /// </summary> IPaginatedEnumerable<ListSkillsResponse> Responses { get; } } } #endif
32.114286
114
0.704626
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/AlexaForBusiness/Generated/Model/_bcl45+netstandard/IListSkillsPaginator.cs
1,124
C#
namespace Domain.Abstractions.UseCases; public class GetQuestionsUseCase : IQuery<IEnumerable<GetQuestionsUseCase.Response>> { public GetQuestionsUseCase(int offset, int limit) { Offset = offset; Limit = limit; } public int Offset { get; } public int Limit { get; } public class Response { public Response(QuestionId questionId, string subject, string question, DateTime asked, string askedBy, DateTime lastActivity, AnswerQuestionStatus status) { if (string.IsNullOrEmpty(subject)) { throw new ArgumentException($"'{nameof(subject)}' cannot be null or empty.", nameof(subject)); } if (string.IsNullOrEmpty(question)) { throw new ArgumentException($"'{nameof(question)}' cannot be null or empty.", nameof(question)); } if (string.IsNullOrEmpty(askedBy)) { throw new ArgumentException($"'{nameof(askedBy)}' cannot be null or empty.", nameof(askedBy)); } QuestionId = questionId; Subject = subject; Question = question; Asked = asked; AskedBy = askedBy; LastActivity = lastActivity; Status = status; } public QuestionId QuestionId { get; } public string Subject { get; } public string Question { get; } public DateTime Asked { get; } public string AskedBy { get; } public DateTime LastActivity { get; } public AnswerQuestionStatus Status { get; } } }
32.078431
163
0.580073
[ "CC0-1.0" ]
arjangeertsema/hexagonal-architecture
Domain/Domain.Abstractions/UseCases/GetQuestionsUseCase.cs
1,636
C#
using MongoDB.Driver; namespace MontoDBRepository.RepositoryLayer.Context { public class ConnectionFactory { private readonly string _connectionString; public ConnectionFactory(string connectionString) { _connectionString = connectionString; } public IMongoClient GetClient() { var client = new MongoClient(_connectionString); return client; } public IMongoDatabase GetDataBase(IMongoClient mongoClient, string databaseName) { var database = mongoClient.GetDatabase(databaseName); return database; } public IMongoDatabase GetDataBase(string connectionString, string databaseName) { var client = new MongoClient(connectionString); var database = client.GetDatabase(databaseName); return database; } public IMongoDatabase GetDataBase(string databaseName) { var client = GetClient(); var database = client.GetDatabase(databaseName); return database; } } }
26.97619
88
0.622242
[ "MIT" ]
RafaCarva/Bill-Generator
BillGenerator.Repository/Context/ConnectionFactory.cs
1,135
C#
namespace FileIO.RecordIO.Interfaces { public interface IRecordAppender { void AppendRecord(IRecord record); void AppendRecord(double[] recordComponents); void AppendRecord(string[] recordComponents); } }
26.666667
53
0.7
[ "MIT" ]
D0M1N1KUS/FileMergeSort
SequentialFileSorting/FileIO/RecordIO/Interfaces/IRecordAppender.cs
240
C#
using System; namespace ToolKit.Validation { /// <summary> /// Provide common parameter checking. /// </summary> public static class Check { /// <summary> /// Check to validate that the string is not null or empty. /// </summary> /// <param name="value">The parameter's value.</param> /// <param name="parameterName">The parameter's string representation.</param> /// <returns>The value of the parameter if it is not <c>null</c> or empty.</returns> public static string NotEmpty(string value, string parameterName) { if (string.IsNullOrWhiteSpace(value)) { throw new ArgumentException(parameterName); } return value; } /// <summary> /// Check to validate that the string is not null or empty. /// </summary> /// <param name="value">The parameter's value.</param> /// <param name="parameterName">The parameter's string representation.</param> /// <param name="message">The exception message to use.</param> /// <returns>The value of the parameter if it is not <c>null</c> or empty.</returns> public static string NotEmpty(string value, string parameterName, string message) { if (string.IsNullOrWhiteSpace(value)) { throw new ArgumentException(message, parameterName); } return value; } /// <summary> /// Check to validate that the number is not negative. /// </summary> /// <param name="value">The parameter's value.</param> /// <param name="parameterName">The parameter name.</param> /// <returns>The value of the parameter if it is not negative.</returns> public static int NotNegative(int value, string parameterName) { if (value < 0) { throw new ArgumentException(parameterName); } return value; } /// <summary> /// Check to validate that the number is not negative. /// </summary> /// <param name="value">The parameter's value.</param> /// <param name="parameterName">The parameter name.</param> /// <param name="message">The exception message to use.</param> /// <returns>The value of the parameter if it is not negative.</returns> public static int NotNegative(int value, string parameterName, string message) { if (value < 0) { throw new ArgumentException(message, parameterName); } return value; } /// <summary> /// Check to validate that the parameter is not null. /// </summary> /// <typeparam name="T">The type of the parameter.</typeparam> /// <param name="value">The parameter's value.</param> /// <param name="parameterName">The parameter's string representation.</param> /// <returns>The value of the parameter if it is not <c>null</c>.</returns> public static T NotNull<T>(T value, string parameterName) where T : class => value ?? throw new ArgumentNullException(parameterName); /// <summary> /// Check to validate that the parameter is not null. /// </summary> /// <typeparam name="T">The type of the parameter.</typeparam> /// <param name="value">The parameter's value.</param> /// <param name="parameterName">The parameter's string representation.</param> /// <returns>The value of the parameter if it is not <c>null</c>.</returns> public static T? NotNull<T>(T? value, string parameterName) where T : struct { if (!value.HasValue) { throw new ArgumentNullException(parameterName); } return value; } } }
37.638095
92
0.569079
[ "Apache-2.0" ]
dcjulian29/toolkit
ToolKit/Validation/Check.cs
3,952
C#
namespace ApkShellext2 { partial class Preferences { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.pnlLeft = new System.Windows.Forms.TableLayoutPanel(); this.twLeft = new System.Windows.Forms.TreeView(); this.lblRenamePattern = new System.Windows.Forms.Label(); this.pnlRenaming = new System.Windows.Forms.TableLayoutPanel(); this.llbPatternVariables = new System.Windows.Forms.LinkLabel(); this.txtRenamePattern = new System.Windows.Forms.TextBox(); this.pnlRenamingReplace = new System.Windows.Forms.TableLayoutPanel(); this.ckReplaceSpace = new System.Windows.Forms.CheckBox(); this.txtReplaceWhiteSpace = new System.Windows.Forms.TextBox(); this.btnResetRenamePattern = new System.Windows.Forms.Button(); this.pnlIcon = new System.Windows.Forms.TableLayoutPanel(); this.ckShowIPA = new System.Windows.Forms.CheckBox(); this.ckShowOverlay = new System.Windows.Forms.CheckBox(); this.ckShowAppxIcon = new System.Windows.Forms.CheckBox(); this.ckStretchThumbnail = new System.Windows.Forms.CheckBox(); this.ckEnableThumbnail = new System.Windows.Forms.CheckBox(); this.ckAdaptiveIconSupport = new System.Windows.Forms.CheckBox(); this.btnClearCache = new System.Windows.Forms.Button(); this.pnlGeneral = new System.Windows.Forms.TableLayoutPanel(); this.lblCurrentVersion = new System.Windows.Forms.Label(); this.lblNewVer = new System.Windows.Forms.Label(); this.lblLanguage = new System.Windows.Forms.Label(); this.combLanguage = new System.Windows.Forms.ComboBox(); this.lblHelpTranslate = new System.Windows.Forms.LinkLabel(); this.btnUpdate = new System.Windows.Forms.Button(); this.ckAlwaysShowStore = new System.Windows.Forms.CheckBox(); this.ckShowMenuIcon = new System.Windows.Forms.CheckBox(); this.pnlRight = new System.Windows.Forms.TableLayoutPanel(); this.pnlButtons = new System.Windows.Forms.FlowLayoutPanel(); this.btnOK = new System.Windows.Forms.Button(); this.btnResetInfoTipPattern = new System.Windows.Forms.Button(); this.btnPatreon = new System.Windows.Forms.Button(); this.pnlContextMenu = new System.Windows.Forms.TableLayoutPanel(); this.ckShowGoogle = new System.Windows.Forms.CheckBox(); this.ckShowAmazon = new System.Windows.Forms.CheckBox(); this.ckShowMS = new System.Windows.Forms.CheckBox(); this.ckShowApple = new System.Windows.Forms.CheckBox(); this.ckShowAM = new System.Windows.Forms.CheckBox(); this.ckShowNewVersionInfo = new System.Windows.Forms.CheckBox(); this.pnlInfoTip = new System.Windows.Forms.TableLayoutPanel(); this.lblInfoTipPattern = new System.Windows.Forms.Label(); this.txtToolTipPattern = new System.Windows.Forms.TextBox(); this.llbInfoTipPattVar = new System.Windows.Forms.LinkLabel(); this.pnlMain = new System.Windows.Forms.TableLayoutPanel(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.pnlLeft.SuspendLayout(); this.pnlRenaming.SuspendLayout(); this.pnlRenamingReplace.SuspendLayout(); this.pnlIcon.SuspendLayout(); this.pnlGeneral.SuspendLayout(); this.pnlRight.SuspendLayout(); this.pnlButtons.SuspendLayout(); this.pnlContextMenu.SuspendLayout(); this.pnlInfoTip.SuspendLayout(); this.pnlMain.SuspendLayout(); this.SuspendLayout(); // // toolTip1 // this.toolTip1.AutomaticDelay = 0; this.toolTip1.AutoPopDelay = 0; this.toolTip1.InitialDelay = 0; this.toolTip1.IsBalloon = true; this.toolTip1.ReshowDelay = 0; this.toolTip1.ShowAlways = true; this.toolTip1.StripAmpersands = true; this.toolTip1.ToolTipIcon = System.Windows.Forms.ToolTipIcon.Info; this.toolTip1.ToolTipTitle = "ApkShellext2"; // // pictureBox1 // this.pictureBox1.Anchor = System.Windows.Forms.AnchorStyles.None; this.pictureBox1.Image = global::ApkShellext2.Properties.NonLocalizeResources.logo; this.pictureBox1.InitialImage = null; this.pictureBox1.Location = new System.Drawing.Point(40, 3); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(64, 64); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pictureBox1.TabIndex = 6; this.pictureBox1.TabStop = false; // // pnlLeft // this.pnlLeft.AutoSize = true; this.pnlLeft.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.pnlLeft.ColumnCount = 1; this.pnlLeft.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.pnlLeft.Controls.Add(this.pictureBox1, 0, 0); this.pnlLeft.Controls.Add(this.twLeft, 0, 1); this.pnlLeft.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlLeft.Location = new System.Drawing.Point(3, 3); this.pnlLeft.Name = "pnlLeft"; this.pnlLeft.RowCount = 2; this.pnlLeft.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlLeft.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlLeft.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.pnlLeft.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.pnlLeft.Size = new System.Drawing.Size(144, 447); this.pnlLeft.TabIndex = 16; // // twLeft // this.twLeft.BorderStyle = System.Windows.Forms.BorderStyle.None; this.twLeft.Dock = System.Windows.Forms.DockStyle.Fill; this.twLeft.HideSelection = false; this.twLeft.Location = new System.Drawing.Point(3, 73); this.twLeft.Name = "twLeft"; this.twLeft.Scrollable = false; this.twLeft.ShowPlusMinus = false; this.twLeft.Size = new System.Drawing.Size(138, 716); this.twLeft.TabIndex = 7; this.twLeft.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.twLeft_AfterSelect); // // lblRenamePattern // this.lblRenamePattern.AutoSize = true; this.lblRenamePattern.Location = new System.Drawing.Point(3, 0); this.lblRenamePattern.Name = "lblRenamePattern"; this.lblRenamePattern.Size = new System.Drawing.Size(87, 13); this.lblRenamePattern.TabIndex = 11; this.lblRenamePattern.Text = "Rename Pattern:"; // // pnlRenaming // this.pnlRenaming.AutoSize = true; this.pnlRenaming.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.pnlRenaming.ColumnCount = 1; this.pnlRenaming.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.pnlRenaming.Controls.Add(this.llbPatternVariables, 0, 3); this.pnlRenaming.Controls.Add(this.txtRenamePattern, 0, 1); this.pnlRenaming.Controls.Add(this.lblRenamePattern, 0, 0); this.pnlRenaming.Controls.Add(this.pnlRenamingReplace, 0, 2); this.pnlRenaming.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlRenaming.Location = new System.Drawing.Point(3, 3); this.pnlRenaming.Name = "pnlRenaming"; this.pnlRenaming.RowCount = 4; this.pnlRenaming.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlRenaming.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlRenaming.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlRenaming.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlRenaming.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.pnlRenaming.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.pnlRenaming.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.pnlRenaming.Size = new System.Drawing.Size(484, 84); this.pnlRenaming.TabIndex = 21; // // llbPatternVariables // this.llbPatternVariables.AutoSize = true; this.llbPatternVariables.Dock = System.Windows.Forms.DockStyle.Fill; this.llbPatternVariables.Location = new System.Drawing.Point(3, 71); this.llbPatternVariables.Name = "llbPatternVariables"; this.llbPatternVariables.Size = new System.Drawing.Size(478, 13); this.llbPatternVariables.TabIndex = 23; this.llbPatternVariables.TabStop = true; this.llbPatternVariables.Text = "Refer to wiki"; // // txtRenamePattern // this.txtRenamePattern.Dock = System.Windows.Forms.DockStyle.Fill; this.txtRenamePattern.Location = new System.Drawing.Point(3, 16); this.txtRenamePattern.Name = "txtRenamePattern"; this.txtRenamePattern.Size = new System.Drawing.Size(478, 20); this.txtRenamePattern.TabIndex = 15; this.txtRenamePattern.Text = "%label%_%versionName%_%versionCode%"; this.txtRenamePattern.TextChanged += new System.EventHandler(this.txtRename_TextChanged); // // pnlRenamingReplace // this.pnlRenamingReplace.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.pnlRenamingReplace.AutoSize = true; this.pnlRenamingReplace.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.pnlRenamingReplace.ColumnCount = 2; this.pnlRenamingReplace.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.pnlRenamingReplace.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.pnlRenamingReplace.Controls.Add(this.ckReplaceSpace, 0, 0); this.pnlRenamingReplace.Controls.Add(this.txtReplaceWhiteSpace, 1, 0); this.pnlRenamingReplace.Location = new System.Drawing.Point(3, 42); this.pnlRenamingReplace.Name = "pnlRenamingReplace"; this.pnlRenamingReplace.RowCount = 1; this.pnlRenamingReplace.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlRenamingReplace.Size = new System.Drawing.Size(478, 26); this.pnlRenamingReplace.TabIndex = 22; // // ckReplaceSpace // this.ckReplaceSpace.AutoSize = true; this.ckReplaceSpace.Location = new System.Drawing.Point(3, 3); this.ckReplaceSpace.Name = "ckReplaceSpace"; this.ckReplaceSpace.Size = new System.Drawing.Size(109, 17); this.ckReplaceSpace.TabIndex = 20; this.ckReplaceSpace.Text = "ckReplaceSpace"; this.ckReplaceSpace.UseVisualStyleBackColor = true; this.ckReplaceSpace.CheckedChanged += new System.EventHandler(this.ckReplaceSpace_CheckedChanged); // // txtReplaceWhiteSpace // this.txtReplaceWhiteSpace.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtReplaceWhiteSpace.Location = new System.Drawing.Point(118, 3); this.txtReplaceWhiteSpace.Name = "txtReplaceWhiteSpace"; this.txtReplaceWhiteSpace.Size = new System.Drawing.Size(357, 20); this.txtReplaceWhiteSpace.TabIndex = 22; this.txtReplaceWhiteSpace.TextChanged += new System.EventHandler(this.TxtReplaceWhiteSpace_TextChanged); // // btnResetRenamePattern // this.btnResetRenamePattern.AutoSize = true; this.btnResetRenamePattern.Location = new System.Drawing.Point(216, 3); this.btnResetRenamePattern.Name = "btnResetRenamePattern"; this.btnResetRenamePattern.Size = new System.Drawing.Size(119, 23); this.btnResetRenamePattern.TabIndex = 17; this.btnResetRenamePattern.Text = "ResetRenamePattern"; this.btnResetRenamePattern.Click += new System.EventHandler(this.btnResetRenamePattern_Click); // // pnlIcon // this.pnlIcon.AutoSize = true; this.pnlIcon.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.pnlIcon.ColumnCount = 1; this.pnlIcon.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.pnlIcon.Controls.Add(this.ckShowIPA, 0, 0); this.pnlIcon.Controls.Add(this.ckShowOverlay, 0, 2); this.pnlIcon.Controls.Add(this.ckShowAppxIcon, 0, 1); this.pnlIcon.Controls.Add(this.ckStretchThumbnail, 0, 4); this.pnlIcon.Controls.Add(this.ckEnableThumbnail, 0, 3); this.pnlIcon.Controls.Add(this.ckAdaptiveIconSupport, 0, 5); this.pnlIcon.Controls.Add(this.btnClearCache, 0, 6); this.pnlIcon.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlIcon.Location = new System.Drawing.Point(3, 172); this.pnlIcon.Name = "pnlIcon"; this.pnlIcon.RowCount = 7; this.pnlIcon.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlIcon.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlIcon.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlIcon.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlIcon.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlIcon.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlIcon.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlIcon.Size = new System.Drawing.Size(484, 167); this.pnlIcon.TabIndex = 22; // // ckShowIPA // this.ckShowIPA.AutoSize = true; this.ckShowIPA.Location = new System.Drawing.Point(3, 3); this.ckShowIPA.Name = "ckShowIPA"; this.ckShowIPA.Size = new System.Drawing.Size(97, 17); this.ckShowIPA.TabIndex = 10; this.ckShowIPA.Text = "Icon--ShowIPA"; this.ckShowIPA.UseVisualStyleBackColor = true; this.ckShowIPA.CheckedChanged += new System.EventHandler(this.ckShowIPA_CheckedChanged); // // ckShowOverlay // this.ckShowOverlay.AutoSize = true; this.ckShowOverlay.Location = new System.Drawing.Point(3, 49); this.ckShowOverlay.Name = "ckShowOverlay"; this.ckShowOverlay.Size = new System.Drawing.Size(101, 17); this.ckShowOverlay.TabIndex = 18; this.ckShowOverlay.Text = "ckShowOverlay"; this.ckShowOverlay.UseVisualStyleBackColor = true; this.ckShowOverlay.CheckedChanged += new System.EventHandler(this.ckShowOverlay_CheckedChanged); // // ckShowAppxIcon // this.ckShowAppxIcon.AutoSize = true; this.ckShowAppxIcon.Location = new System.Drawing.Point(3, 26); this.ckShowAppxIcon.Name = "ckShowAppxIcon"; this.ckShowAppxIcon.Size = new System.Drawing.Size(77, 17); this.ckShowAppxIcon.TabIndex = 20; this.ckShowAppxIcon.Text = "ShowAppx"; this.ckShowAppxIcon.UseVisualStyleBackColor = true; this.ckShowAppxIcon.CheckedChanged += new System.EventHandler(this.ckShowAppxIcon_CheckedChanged); // // ckStretchThumbnail // this.ckStretchThumbnail.AutoSize = true; this.ckStretchThumbnail.Location = new System.Drawing.Point(3, 95); this.ckStretchThumbnail.Name = "ckStretchThumbnail"; this.ckStretchThumbnail.Size = new System.Drawing.Size(121, 17); this.ckStretchThumbnail.TabIndex = 21; this.ckStretchThumbnail.Text = "ckStretchThumbnail"; this.ckStretchThumbnail.UseVisualStyleBackColor = true; this.ckStretchThumbnail.CheckedChanged += new System.EventHandler(this.ckStretchIcon_CheckedChanged); // // ckEnableThumbnail // this.ckEnableThumbnail.AutoSize = true; this.ckEnableThumbnail.Location = new System.Drawing.Point(3, 72); this.ckEnableThumbnail.Name = "ckEnableThumbnail"; this.ckEnableThumbnail.Size = new System.Drawing.Size(120, 17); this.ckEnableThumbnail.TabIndex = 22; this.ckEnableThumbnail.Text = "ckEnableThumbnail"; this.ckEnableThumbnail.UseVisualStyleBackColor = true; this.ckEnableThumbnail.CheckedChanged += new System.EventHandler(this.ckEnableThumbnail_CheckedChanged); // // ckAdaptiveIconSupport // this.ckAdaptiveIconSupport.AutoSize = true; this.ckAdaptiveIconSupport.Location = new System.Drawing.Point(3, 118); this.ckAdaptiveIconSupport.Name = "ckAdaptiveIconSupport"; this.ckAdaptiveIconSupport.Size = new System.Drawing.Size(101, 17); this.ckAdaptiveIconSupport.TabIndex = 24; this.ckAdaptiveIconSupport.Text = "ckAdaptiveIcon"; this.ckAdaptiveIconSupport.UseVisualStyleBackColor = true; this.ckAdaptiveIconSupport.CheckedChanged += new System.EventHandler(this.CkAdaptiveIconSupport_CheckedChanged); // // btnClearCache // this.btnClearCache.AutoSize = true; this.btnClearCache.Location = new System.Drawing.Point(3, 141); this.btnClearCache.Name = "btnClearCache"; this.btnClearCache.Size = new System.Drawing.Size(120, 23); this.btnClearCache.TabIndex = 23; this.btnClearCache.Text = "btnClearCache"; this.btnClearCache.UseVisualStyleBackColor = true; this.btnClearCache.Click += new System.EventHandler(this.btnClearCache_Click); // // pnlGeneral // this.pnlGeneral.AutoSize = true; this.pnlGeneral.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.pnlGeneral.ColumnCount = 1; this.pnlGeneral.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.pnlGeneral.Controls.Add(this.lblCurrentVersion, 0, 4); this.pnlGeneral.Controls.Add(this.lblNewVer, 0, 3); this.pnlGeneral.Controls.Add(this.lblLanguage, 0, 0); this.pnlGeneral.Controls.Add(this.combLanguage, 0, 1); this.pnlGeneral.Controls.Add(this.lblHelpTranslate, 0, 2); this.pnlGeneral.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlGeneral.Location = new System.Drawing.Point(0, 90); this.pnlGeneral.Margin = new System.Windows.Forms.Padding(0); this.pnlGeneral.Name = "pnlGeneral"; this.pnlGeneral.RowCount = 5; this.pnlGeneral.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlGeneral.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlGeneral.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlGeneral.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlGeneral.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlGeneral.Size = new System.Drawing.Size(490, 79); this.pnlGeneral.TabIndex = 21; // // lblCurrentVersion // this.lblCurrentVersion.AutoSize = true; this.lblCurrentVersion.Dock = System.Windows.Forms.DockStyle.Fill; this.lblCurrentVersion.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.lblCurrentVersion.Location = new System.Drawing.Point(3, 66); this.lblCurrentVersion.Name = "lblCurrentVersion"; this.lblCurrentVersion.Size = new System.Drawing.Size(484, 13); this.lblCurrentVersion.TabIndex = 11; this.lblCurrentVersion.Text = "Current version"; this.lblCurrentVersion.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // lblNewVer // this.lblNewVer.AutoSize = true; this.lblNewVer.Dock = System.Windows.Forms.DockStyle.Fill; this.lblNewVer.Location = new System.Drawing.Point(3, 53); this.lblNewVer.Name = "lblNewVer"; this.lblNewVer.Size = new System.Drawing.Size(484, 13); this.lblNewVer.TabIndex = 10; this.lblNewVer.Text = "About--NewVersion"; this.lblNewVer.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // lblLanguage // this.lblLanguage.AutoSize = true; this.lblLanguage.Location = new System.Drawing.Point(3, 0); this.lblLanguage.Name = "lblLanguage"; this.lblLanguage.Size = new System.Drawing.Size(101, 13); this.lblLanguage.TabIndex = 9; this.lblLanguage.Text = "General--Language:"; // // combLanguage // this.combLanguage.Dock = System.Windows.Forms.DockStyle.Fill; this.combLanguage.FormattingEnabled = true; this.combLanguage.Location = new System.Drawing.Point(3, 16); this.combLanguage.Name = "combLanguage"; this.combLanguage.Size = new System.Drawing.Size(484, 21); this.combLanguage.TabIndex = 8; this.combLanguage.SelectedIndexChanged += new System.EventHandler(this.combLanguage_SelectedIndexChanged); // // lblHelpTranslate // this.lblHelpTranslate.AutoSize = true; this.lblHelpTranslate.Location = new System.Drawing.Point(3, 40); this.lblHelpTranslate.Name = "lblHelpTranslate"; this.lblHelpTranslate.Size = new System.Drawing.Size(73, 13); this.lblHelpTranslate.TabIndex = 12; this.lblHelpTranslate.TabStop = true; this.lblHelpTranslate.Text = "HelpTranslate"; this.lblHelpTranslate.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lblHelpTranslate_LinkClicked); // // btnUpdate // this.btnUpdate.AutoSize = true; this.btnUpdate.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnUpdate.Location = new System.Drawing.Point(341, 3); this.btnUpdate.Name = "btnUpdate"; this.btnUpdate.Size = new System.Drawing.Size(67, 25); this.btnUpdate.TabIndex = 24; this.btnUpdate.Text = "update"; this.btnUpdate.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.btnUpdate.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this.btnUpdate.UseVisualStyleBackColor = true; this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click_1); // // ckAlwaysShowStore // this.ckAlwaysShowStore.AutoSize = true; this.ckAlwaysShowStore.Location = new System.Drawing.Point(3, 49); this.ckAlwaysShowStore.Name = "ckAlwaysShowStore"; this.ckAlwaysShowStore.Size = new System.Drawing.Size(115, 17); this.ckAlwaysShowStore.TabIndex = 17; this.ckAlwaysShowStore.Text = "alwaysShowStores"; this.ckAlwaysShowStore.UseVisualStyleBackColor = true; this.ckAlwaysShowStore.CheckedChanged += new System.EventHandler(this.ckShowPlay_CheckedChanged); // // ckShowMenuIcon // this.ckShowMenuIcon.AutoSize = true; this.ckShowMenuIcon.Location = new System.Drawing.Point(3, 3); this.ckShowMenuIcon.Name = "ckShowMenuIcon"; this.ckShowMenuIcon.Size = new System.Drawing.Size(151, 17); this.ckShowMenuIcon.TabIndex = 21; this.ckShowMenuIcon.Text = "ConMenu--showMenuIcon"; this.ckShowMenuIcon.UseVisualStyleBackColor = true; this.ckShowMenuIcon.CheckedChanged += new System.EventHandler(this.ckShowMenuIcon_CheckedChanged); // // pnlRight // this.pnlRight.AutoSize = true; this.pnlRight.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.pnlRight.ColumnCount = 1; this.pnlRight.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.pnlRight.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.pnlRight.Controls.Add(this.pnlButtons, 0, 7); this.pnlRight.Controls.Add(this.pnlIcon, 0, 3); this.pnlRight.Controls.Add(this.pnlGeneral, 0, 2); this.pnlRight.Controls.Add(this.pnlRenaming, 0, 0); this.pnlRight.Controls.Add(this.pnlContextMenu, 0, 4); this.pnlRight.Controls.Add(this.pnlInfoTip, 0, 6); this.pnlRight.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlRight.Location = new System.Drawing.Point(153, 3); this.pnlRight.Name = "pnlRight"; this.pnlRight.RowCount = 8; this.pnlRight.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlRight.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlRight.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlRight.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlRight.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlRight.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlRight.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlRight.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlRight.Size = new System.Drawing.Size(336, 447); this.pnlRight.TabIndex = 24; this.pnlRight.Visible = false; // // pnlButtons // this.pnlButtons.AutoSize = true; this.pnlButtons.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.pnlButtons.Controls.Add(this.btnOK); this.pnlButtons.Controls.Add(this.btnUpdate); this.pnlButtons.Controls.Add(this.btnResetRenamePattern); this.pnlButtons.Controls.Add(this.btnResetInfoTipPattern); this.pnlButtons.Controls.Add(this.btnPatreon); this.pnlButtons.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlButtons.FlowDirection = System.Windows.Forms.FlowDirection.RightToLeft; this.pnlButtons.Location = new System.Drawing.Point(3, 657); this.pnlButtons.Name = "pnlButtons"; this.pnlButtons.Size = new System.Drawing.Size(484, 62); this.pnlButtons.TabIndex = 21; // // btnOK // this.btnOK.AutoSize = true; this.btnOK.Dock = System.Windows.Forms.DockStyle.Right; this.btnOK.Location = new System.Drawing.Point(414, 3); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(67, 25); this.btnOK.TabIndex = 0; this.btnOK.Text = "OK"; this.btnOK.UseVisualStyleBackColor = true; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // btnResetInfoTipPattern // this.btnResetInfoTipPattern.AutoSize = true; this.btnResetInfoTipPattern.Location = new System.Drawing.Point(95, 3); this.btnResetInfoTipPattern.Name = "btnResetInfoTipPattern"; this.btnResetInfoTipPattern.Size = new System.Drawing.Size(115, 23); this.btnResetInfoTipPattern.TabIndex = 2; this.btnResetInfoTipPattern.Text = "ResetInfoTipPattern"; this.btnResetInfoTipPattern.UseVisualStyleBackColor = true; this.btnResetInfoTipPattern.Click += new System.EventHandler(this.btnResetTooltipPattern_Click); // // btnPatreon // this.btnPatreon.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnPatreon.Location = new System.Drawing.Point(361, 34); this.btnPatreon.Name = "btnPatreon"; this.btnPatreon.Size = new System.Drawing.Size(120, 25); this.btnPatreon.TabIndex = 25; this.btnPatreon.Text = "Support on Patron"; this.btnPatreon.UseVisualStyleBackColor = true; this.btnPatreon.Click += new System.EventHandler(this.BtnPatreon_Click); // // pnlContextMenu // this.pnlContextMenu.AutoSize = true; this.pnlContextMenu.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.pnlContextMenu.ColumnCount = 1; this.pnlContextMenu.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.pnlContextMenu.Controls.Add(this.ckShowMenuIcon, 0, 0); this.pnlContextMenu.Controls.Add(this.ckAlwaysShowStore, 0, 2); this.pnlContextMenu.Controls.Add(this.ckShowGoogle, 0, 3); this.pnlContextMenu.Controls.Add(this.ckShowAmazon, 0, 4); this.pnlContextMenu.Controls.Add(this.ckShowMS, 0, 6); this.pnlContextMenu.Controls.Add(this.ckShowApple, 0, 5); this.pnlContextMenu.Controls.Add(this.ckShowAM, 0, 7); this.pnlContextMenu.Controls.Add(this.ckShowNewVersionInfo, 0, 1); this.pnlContextMenu.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlContextMenu.Location = new System.Drawing.Point(3, 345); this.pnlContextMenu.Name = "pnlContextMenu"; this.pnlContextMenu.RowCount = 9; this.pnlContextMenu.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlContextMenu.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlContextMenu.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlContextMenu.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlContextMenu.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlContextMenu.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlContextMenu.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlContextMenu.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlContextMenu.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlContextMenu.Size = new System.Drawing.Size(484, 184); this.pnlContextMenu.TabIndex = 24; // // ckShowGoogle // this.ckShowGoogle.AutoSize = true; this.ckShowGoogle.Location = new System.Drawing.Point(3, 72); this.ckShowGoogle.Name = "ckShowGoogle"; this.ckShowGoogle.Size = new System.Drawing.Size(104, 17); this.ckShowGoogle.TabIndex = 22; this.ckShowGoogle.Text = "showGoogleplay"; this.ckShowGoogle.UseVisualStyleBackColor = true; this.ckShowGoogle.CheckedChanged += new System.EventHandler(this.ckbShowGoogle_CheckedChanged); // // ckShowAmazon // this.ckShowAmazon.AutoSize = true; this.ckShowAmazon.Location = new System.Drawing.Point(3, 95); this.ckShowAmazon.Name = "ckShowAmazon"; this.ckShowAmazon.Size = new System.Drawing.Size(63, 17); this.ckShowAmazon.TabIndex = 23; this.ckShowAmazon.Text = "amazon"; this.ckShowAmazon.UseVisualStyleBackColor = true; this.ckShowAmazon.CheckedChanged += new System.EventHandler(this.ckShowAmazon_CheckedChanged); // // ckShowMS // this.ckShowMS.AutoSize = true; this.ckShowMS.Location = new System.Drawing.Point(3, 141); this.ckShowMS.Name = "ckShowMS"; this.ckShowMS.Size = new System.Drawing.Size(39, 17); this.ckShowMS.TabIndex = 24; this.ckShowMS.Text = "ms"; this.ckShowMS.UseVisualStyleBackColor = true; this.ckShowMS.CheckedChanged += new System.EventHandler(this.ckShowMS_CheckedChanged); // // ckShowApple // this.ckShowApple.AutoSize = true; this.ckShowApple.Location = new System.Drawing.Point(3, 118); this.ckShowApple.Name = "ckShowApple"; this.ckShowApple.Size = new System.Drawing.Size(52, 17); this.ckShowApple.TabIndex = 25; this.ckShowApple.Text = "apple"; this.ckShowApple.UseVisualStyleBackColor = true; this.ckShowApple.CheckedChanged += new System.EventHandler(this.ckShowApple_CheckedChanged); // // ckShowAM // this.ckShowAM.AutoSize = true; this.ckShowAM.Location = new System.Drawing.Point(3, 164); this.ckShowAM.Name = "ckShowAM"; this.ckShowAM.Size = new System.Drawing.Size(96, 17); this.ckShowAM.TabIndex = 26; this.ckShowAM.Text = "showApkMirror"; this.ckShowAM.UseVisualStyleBackColor = true; this.ckShowAM.Visible = false; this.ckShowAM.CheckedChanged += new System.EventHandler(this.ckShowAM_CheckedChanged); // // ckShowNewVersionInfo // this.ckShowNewVersionInfo.AutoSize = true; this.ckShowNewVersionInfo.Location = new System.Drawing.Point(3, 26); this.ckShowNewVersionInfo.Name = "ckShowNewVersionInfo"; this.ckShowNewVersionInfo.Size = new System.Drawing.Size(128, 17); this.ckShowNewVersionInfo.TabIndex = 27; this.ckShowNewVersionInfo.Text = "ShowNewVersionInfo"; this.ckShowNewVersionInfo.UseVisualStyleBackColor = true; this.ckShowNewVersionInfo.CheckedChanged += new System.EventHandler(this.CkShowNewVersionInfo_CheckedChanged); // // pnlInfoTip // this.pnlInfoTip.AutoSize = true; this.pnlInfoTip.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.pnlInfoTip.ColumnCount = 1; this.pnlInfoTip.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.pnlInfoTip.Controls.Add(this.lblInfoTipPattern, 0, 0); this.pnlInfoTip.Controls.Add(this.txtToolTipPattern, 0, 1); this.pnlInfoTip.Controls.Add(this.llbInfoTipPattVar, 0, 7); this.pnlInfoTip.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlInfoTip.Location = new System.Drawing.Point(3, 535); this.pnlInfoTip.Name = "pnlInfoTip"; this.pnlInfoTip.RowCount = 8; this.pnlInfoTip.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlInfoTip.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlInfoTip.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlInfoTip.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlInfoTip.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlInfoTip.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlInfoTip.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlInfoTip.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.pnlInfoTip.Size = new System.Drawing.Size(484, 116); this.pnlInfoTip.TabIndex = 25; // // lblInfoTipPattern // this.lblInfoTipPattern.AutoSize = true; this.lblInfoTipPattern.Location = new System.Drawing.Point(3, 0); this.lblInfoTipPattern.Name = "lblInfoTipPattern"; this.lblInfoTipPattern.Size = new System.Drawing.Size(104, 13); this.lblInfoTipPattern.TabIndex = 0; this.lblInfoTipPattern.Text = "Info Tip Info Pattern:"; // // txtToolTipPattern // this.txtToolTipPattern.Dock = System.Windows.Forms.DockStyle.Fill; this.txtToolTipPattern.Location = new System.Drawing.Point(3, 16); this.txtToolTipPattern.Multiline = true; this.txtToolTipPattern.Name = "txtToolTipPattern"; this.txtToolTipPattern.Size = new System.Drawing.Size(478, 84); this.txtToolTipPattern.TabIndex = 1; this.txtToolTipPattern.TextChanged += new System.EventHandler(this.txtToolTipPattern_TextChanged); // // llbInfoTipPattVar // this.llbInfoTipPattVar.AutoSize = true; this.llbInfoTipPattVar.Dock = System.Windows.Forms.DockStyle.Fill; this.llbInfoTipPattVar.Location = new System.Drawing.Point(3, 103); this.llbInfoTipPattVar.Name = "llbInfoTipPattVar"; this.llbInfoTipPattVar.Size = new System.Drawing.Size(478, 13); this.llbInfoTipPattVar.TabIndex = 3; this.llbInfoTipPattVar.TabStop = true; this.llbInfoTipPattVar.Text = "refer to wiki"; this.llbInfoTipPattVar.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.llbInfoTipPattVar_LinkClicked); // // pnlMain // this.pnlMain.AutoSize = true; this.pnlMain.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.pnlMain.ColumnCount = 2; this.pnlMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 150F)); this.pnlMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.pnlMain.Controls.Add(this.pnlLeft, 0, 0); this.pnlMain.Controls.Add(this.pnlRight, 2, 0); this.pnlMain.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlMain.Location = new System.Drawing.Point(0, 0); this.pnlMain.Name = "pnlMain"; this.pnlMain.RowCount = 1; this.pnlMain.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.pnlMain.Size = new System.Drawing.Size(492, 453); this.pnlMain.TabIndex = 25; // // Preferences // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSize = true; this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.ClientSize = new System.Drawing.Size(492, 453); this.Controls.Add(this.pnlMain); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Name = "Preferences"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.TopMost = true; this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Preferences_FormClosed); this.Load += new System.EventHandler(this.Preferences_Load); this.ResizeBegin += new System.EventHandler(this.Preferences_ResizeBegin); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.pnlLeft.ResumeLayout(false); this.pnlLeft.PerformLayout(); this.pnlRenaming.ResumeLayout(false); this.pnlRenaming.PerformLayout(); this.pnlRenamingReplace.ResumeLayout(false); this.pnlRenamingReplace.PerformLayout(); this.pnlIcon.ResumeLayout(false); this.pnlIcon.PerformLayout(); this.pnlGeneral.ResumeLayout(false); this.pnlGeneral.PerformLayout(); this.pnlRight.ResumeLayout(false); this.pnlRight.PerformLayout(); this.pnlButtons.ResumeLayout(false); this.pnlButtons.PerformLayout(); this.pnlContextMenu.ResumeLayout(false); this.pnlContextMenu.PerformLayout(); this.pnlInfoTip.ResumeLayout(false); this.pnlInfoTip.PerformLayout(); this.pnlMain.ResumeLayout(false); this.pnlMain.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.TableLayoutPanel pnlLeft; private System.Windows.Forms.TreeView twLeft; private System.Windows.Forms.Label lblRenamePattern; private System.Windows.Forms.TableLayoutPanel pnlRenaming; private System.Windows.Forms.TableLayoutPanel pnlIcon; private System.Windows.Forms.TableLayoutPanel pnlGeneral; private System.Windows.Forms.CheckBox ckShowIPA; private System.Windows.Forms.CheckBox ckShowOverlay; private System.Windows.Forms.CheckBox ckAlwaysShowStore; private System.Windows.Forms.Label lblLanguage; private System.Windows.Forms.ComboBox combLanguage; private System.Windows.Forms.CheckBox ckShowAppxIcon; private System.Windows.Forms.CheckBox ckShowMenuIcon; private System.Windows.Forms.TableLayoutPanel pnlRight; private System.Windows.Forms.FlowLayoutPanel pnlButtons; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.TableLayoutPanel pnlContextMenu; private System.Windows.Forms.TableLayoutPanel pnlInfoTip; private System.Windows.Forms.TableLayoutPanel pnlMain; private System.Windows.Forms.CheckBox ckShowGoogle; private System.Windows.Forms.TextBox txtRenamePattern; private System.Windows.Forms.CheckBox ckShowAmazon; private System.Windows.Forms.CheckBox ckShowMS; private System.Windows.Forms.CheckBox ckShowApple; private System.Windows.Forms.Button btnResetRenamePattern; private System.Windows.Forms.Label lblInfoTipPattern; private System.Windows.Forms.TextBox txtToolTipPattern; private System.Windows.Forms.Button btnResetInfoTipPattern; private System.Windows.Forms.Label lblCurrentVersion; private System.Windows.Forms.Label lblNewVer; private System.Windows.Forms.CheckBox ckShowAM; private System.Windows.Forms.Button btnUpdate; private System.Windows.Forms.CheckBox ckReplaceSpace; private System.Windows.Forms.LinkLabel llbInfoTipPattVar; private System.Windows.Forms.CheckBox ckShowNewVersionInfo; private System.Windows.Forms.CheckBox ckStretchThumbnail; private System.Windows.Forms.LinkLabel lblHelpTranslate; private System.Windows.Forms.CheckBox ckEnableThumbnail; private System.Windows.Forms.Button btnClearCache; private System.Windows.Forms.CheckBox ckAdaptiveIconSupport; private System.Windows.Forms.LinkLabel llbPatternVariables; private System.Windows.Forms.TableLayoutPanel pnlRenamingReplace; private System.Windows.Forms.TextBox txtReplaceWhiteSpace; private System.Windows.Forms.Button btnPatreon; } }
57.191542
169
0.639816
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
404neko/apkshellext3
ApkShellext2/Preferences.Designer.cs
45,984
C#
using System; namespace com.GraphDefined.SMSApi.API.Action { public class BindContactToGroup : Rest<Response.Base> { public BindContactToGroup(Credentials Client, SMSAPIClient Proxy, String contactId, String groupId) : base(Client, Proxy) { ContactId = contactId; GroupId = groupId; } protected override string Resource { get { return "contacts/" + ContactId + "/groups/" + GroupId; } } protected override RequestMethods Method { get { return RequestMethods.PUT; } } public string ContactId { get; } public string GroupId { get; } } }
26
109
0.539788
[ "Apache-2.0" ]
GraphDefined/SMSAPI
smsapi/Actions/Contacts/BindContactToGroup.cs
754
C#
using NFluent; using NUnit.Framework; using pbrt.Spectrums; namespace Pbrt.Tests.Spectrums { [TestFixture] public class SpectrumTests { [Test] public void AddTest() { var spec1 = new Spectrum(new[] { 1.23f, 2.34f }); var spec2 = new Spectrum(new[] { 2f, 3f }); var spec = spec1 + spec2; Check.That(spec).IsEqualTo(new Spectrum(new[] { 3.23f, 5.34f })); } [Test] public void AddFloatTest() { var spec1 = new Spectrum(new[] { 1.23f, 2.34f }); var spec = spec1 + 1; Check.That(spec).IsEqualTo(new Spectrum(new[] { 2.23f, 3.34f })); } [Test] public void SubTest() { var spec1 = new Spectrum(new[] { 1.23f, 2.34f }); var spec2 = new Spectrum(new[] { 2f, 3f }); var spec = spec2 - spec1; Check.That(spec).IsEqualTo(new Spectrum(new[] { 0.77f, 0.6600001f })); } [Test] public void SubFloatTest() { var spec1 = new Spectrum(new[] { 1.23f, 2.34f }); var spec = spec1 - 1; Check.That(spec[0]).IsCloseTo( 0.23f, 1e-4); Check.That(spec[1]).IsCloseTo(1.34f, 1e-4); } [Test] public void DivTest() { var spec1 = new Spectrum(new[] { 1.23f, 2.34f }); var spec2 = new Spectrum(new[] { 2f, 3f }); var spec = spec1 / spec2; Check.That(spec).IsEqualTo(new Spectrum(new[] { 0.615f, 0.78f })); } [Test] public void MulTest() { var spec1 = new Spectrum(new[] { 1.23f, 2.34f }); var spec2 = new Spectrum(new[] { 2f, 3f }); var spec = spec1 * spec2; Check.That(spec).IsEqualTo(new Spectrum(new[] { 2.46f, 7.0199995f })); } [Test] public void MulFloatTest() { var spec1 = new Spectrum(new[] { 1.23f, 2.34f }); var spec = spec1 * 2; Check.That(spec).IsEqualTo(new Spectrum(new[] { 2.46f, 4.68f })); } [Test] public void DivFloatTest() { var spec1 = new Spectrum(new[] { 1.23f, 2.34f }); var spec = spec1 / 2; Check.That(spec).IsEqualTo(new Spectrum(new[] { 0.615f, 1.17f })); } [Test] public void InvDivFloatTest() { var spec1 = new Spectrum(new[] { 1.23f, 2.34f }); var spec = 2 / spec1; Check.That(spec).IsEqualTo(new Spectrum(new[] { 2 / 1.23f, 2 / 2.34f })); } [Test] public void NegTest() { var spec1 = new Spectrum(new[] { 1.23f, 2.34f }); var spec = -spec1; Check.That(spec).IsEqualTo(new Spectrum(new[] { -1.23f, -2.34f })); } [Test] public void FromSampledTest() { float[] lambdas = new[] { 500f, 400f, 600f, 700f }; float[] values = new[] { 2f, 1f, 2f, 1f }; var spec = Spectrum.FromSampledSpectrum(lambdas, values, lambdas.Length); float[] expected = { 1.025f, 1.075f, 1.125f, 1.175f, 1.225f, 1.275f, 1.325f, 1.375f, 1.425f, 1.475f, 1.525f, 1.575f, 1.625f, 1.675f, 1.725f, 1.775f, 1.825f, 1.875f, 1.925f, 1.975f, 2f, 2f, 2f, 2f, 2f, 2f, 2f, 2f, 2f, 2f, 2f, 2f, 2f, 2f, 2f, 2f, 2f, 2f, 2f, 2f, 1.975f, 1.925f, 1.875f, 1.825f, 1.775f, 1.725f, 1.675f, 1.625f, 1.575f, 1.525f, 1.475f, 1.425f, 1.375f, 1.325f, 1.275f, 1.225f, 1.175f, 1.125f, 1.075f, 1.025f }; for (int i = 0; i < spec.C.Length; i++) { Check.That(spec.C[i]).IsCloseTo(expected[i], 1e-3); } } [Test] public void LerpTest() { var spec1 = new Spectrum(new[] { 100, 400f }); var spec2 = new Spectrum(new[] { 200, 500f }); Check.That(Spectrum.Lerp(0, spec1, spec2)).IsEqualTo(new Spectrum(new[] { 100, 400f })); Check.That(Spectrum.Lerp(1, spec1, spec2)).IsEqualTo(new Spectrum(new[] { 200, 500f })); Check.That(Spectrum.Lerp(0.5f, spec1, spec2)).IsEqualTo(new Spectrum(new[] { 150, 450f })); } } }
33.684615
111
0.476821
[ "Unlicense" ]
fremag/pbrt
pbrt/Pbrt.Tests/Spectrums/SpectrumTests.cs
4,379
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 Dependencia_lineal.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.612903
151
0.584343
[ "MIT" ]
OctavioProgramador/Algebra-lineal
Calculadora de vectores/Dependencia lineal/Dependencia lineal/Properties/Settings.Designer.cs
1,075
C#
/* Copyright © 2013 Arjen Post (http://arjenpost.nl) License: http://www.apache.org/licenses/LICENSE-2.0 */ namespace DynamicMapper.Tests { using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Linq; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public partial class PerformanceTests { private static readonly PropertyInfo Int1Property = typeof(Entity).GetProperty("Int1"); private static readonly PropertyInfo Int2Property = typeof(Entity).GetProperty("Int2"); private static readonly PropertyInfo Int3Property = typeof(Entity).GetProperty("Int3"); private static readonly PropertyInfo Int4Property = typeof(Entity).GetProperty("Int4"); private static readonly PropertyInfo Int5Property = typeof(Entity).GetProperty("Int5"); private static readonly PropertyInfo String1Property = typeof(Entity).GetProperty("String1"); private static readonly PropertyInfo String2Property = typeof(Entity).GetProperty("String2"); private static readonly PropertyInfo String3Property = typeof(Entity).GetProperty("String3"); private static readonly PropertyInfo String4Property = typeof(Entity).GetProperty("String4"); private static readonly PropertyInfo String5Property = typeof(Entity).GetProperty("String5"); private static readonly PropertyInfo Double1Property = typeof(Entity).GetProperty("Double1"); private static readonly PropertyInfo Double2Property = typeof(Entity).GetProperty("Double2"); private static readonly PropertyInfo Double3Property = typeof(Entity).GetProperty("Double3"); private static readonly PropertyInfo Double4Property = typeof(Entity).GetProperty("Double4"); private static readonly PropertyInfo Double5Property = typeof(Entity).GetProperty("Double5"); private readonly Random random = new Random(); [TestMethod] public void PerformanceComparison() { var entityCount = 1000; var testCount = 10; var entities = Enumerable.Range(0, entityCount) .Select(index => CreateEntity()) .ToList(); var properties = new[] { typeof(Entity).GetProperty("Int1"), typeof(Entity).GetProperty("String2"), typeof(Entity).GetProperty("String4"), typeof(Entity).GetProperty("Double1"), typeof(Entity).GetProperty("Double2") }; // Warming up... NormalMap(entities[0], properties); long normalAverage = 0; Trace.WriteLine("--- Normal map method"); for (int i = 0; i < testCount; i++) { var stopwatch = Stopwatch.StartNew(); entities .ForEach(entity => { NormalMap(entity, properties); }); stopwatch.Stop(); normalAverage += stopwatch.ElapsedMilliseconds; Trace.WriteLine(string.Format("{0} entities in {1} ms.", entityCount, stopwatch.ElapsedMilliseconds)); } // Warming up... Mapper<Entity>.Map(entities[0], properties); Trace.WriteLine("--- DynamicMapper map method"); long dynamicAverage = 0; for (int i = 0; i < testCount; i++) { var stopwatch = Stopwatch.StartNew(); entities .ForEach(entity => { Mapper<Entity>.Map(entity, properties); }); stopwatch.Stop(); dynamicAverage += stopwatch.ElapsedMilliseconds; Trace.WriteLine(string.Format("{0} entities in {1} ms.", entityCount, stopwatch.ElapsedMilliseconds)); } Trace.WriteLine((double)dynamicAverage / normalAverage); } private dynamic NormalMap(Entity entity, ICollection<PropertyInfo> properties) { if (entity == null) { throw new ArgumentNullException("entity"); } if (properties == null) { throw new ArgumentNullException("properties"); } dynamic result = new ExpandoObject(); if (properties.Contains(Int1Property)) { result.Int1 = entity.Int1; } if (properties.Contains(Int2Property)) { result.Int2 = entity.Int2; } if (properties.Contains(Int3Property)) { result.Int3 = entity.Int3; } if (properties.Contains(Int4Property)) { result.Int4 = entity.Int4; } if (properties.Contains(Int5Property)) { result.Int5 = entity.Int5; } if (properties.Contains(String1Property)) { result.String1 = entity.String1; } if (properties.Contains(String2Property)) { result.String2 = entity.String2; } if (properties.Contains(String3Property)) { result.String3 = entity.String3; } if (properties.Contains(String4Property)) { result.String4 = entity.String4; } if (properties.Contains(String5Property)) { result.String5 = entity.String5; } if (properties.Contains(Double1Property)) { result.Double1 = entity.Double1; } if (properties.Contains(Double2Property)) { result.Double2 = entity.Double2; } if (properties.Contains(Double3Property)) { result.Double3 = entity.Double3; } if (properties.Contains(Double4Property)) { result.Double4 = entity.Double4; } if (properties.Contains(Double5Property)) { result.Double5 = entity.Double5; } return result; } private Entity CreateEntity() { var entity = new Entity() { Int1 = random.Next(), Int2 = random.Next(), Int3 = random.Next(), Int4 = random.Next(), Int5 = random.Next(), String1 = Guid.NewGuid().ToString(), String2 = Guid.NewGuid().ToString(), String3 = Guid.NewGuid().ToString(), String4 = Guid.NewGuid().ToString(), String5 = Guid.NewGuid().ToString(), Double1 = random.NextDouble(), Double2 = random.NextDouble(), Double3 = random.NextDouble(), Double4 = random.NextDouble(), Double5 = random.NextDouble() }; return entity; } } }
32.753363
118
0.537924
[ "Apache-2.0" ]
dotarj/DynamicMapper
DynamicMapper.Tests/PerformanceTests.cs
7,307
C#
using Adnc.Application.Shared; using Adnc.Infra.Core; using Autofac; using Microsoft.Extensions.Configuration; namespace Adnc.Cus.Application { /// <summary> /// Autofac注册 /// </summary> public sealed class AdncCusApplicationModule : AdncApplicationModule { /// <summary> /// 构造函数 /// </summary> public AdncCusApplicationModule(IConfiguration configuration, IServiceInfo serviceInfo) : base(typeof(AdncCusApplicationModule), configuration, serviceInfo) { } /// <summary> /// 注册方法 /// </summary> /// <param name="builder"></param> protected override void Load(ContainerBuilder builder) { base.Load(builder); } } }
25.833333
95
0.597419
[ "MIT" ]
AjuPrince/Adnc
src/ServerApi/Services/Adnc.Cus/Adnc.Cus.Application/AdncCusApplicationModule.cs
797
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace School_Programme { [Activity(Label = "School Programme", ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait)] public class ReviewLessons : Activity { private ActionBar bar; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.ReviewLessons); bar = this.ActionBar; bar.NavigationMode = ActionBarNavigationMode.Tabs; bar.SetTitle(Resource.String.ApplicationName); bar.SetIcon(Resource.Drawable.logo); bar.SetHomeButtonEnabled(true); bar.SetDisplayHomeAsUpEnabled(true); AddTab("Add Lessons", Resource.Drawable.AddLessonTab, new AddLessonsFragment()); AddTab("Remove Lessons", Resource.Drawable.RemoveLessonTab, new RemoveLessonsFragment()); AddTab("Postpone Lesson", Resource.Drawable.PostponeLessonTab, new PostponeLessonsFragment()); AddTab("Modify Lesson", Resource.Drawable.ModifyDataTab, new ModifyLessonFragment()); AddTab("View All Lessons", Resource.Drawable.ViewList, new ViewAllLessonsFragment()); } private void AddTab(string tabName, int iconRes, Fragment view) { var tab = bar.NewTab(); tab.SetText(tabName); tab.SetIcon(iconRes); tab.TabSelected += delegate (object sender, ActionBar.TabEventArgs e) { var fragment = this.FragmentManager.FindFragmentById(Resource.Id.FrameContainer); if (fragment != null) e.FragmentTransaction.Remove(fragment); e.FragmentTransaction.Add(Resource.Id.FrameContainer, view); }; tab.TabUnselected += delegate (object sender, ActionBar.TabEventArgs e) { e.FragmentTransaction.Remove(view); }; this.ActionBar.AddTab(tab); } public override bool OnOptionsItemSelected(IMenuItem menuItem) { if (menuItem.ItemId != Android.Resource.Id.Home) return base.OnOptionsItemSelected(menuItem); this.Finish(); return true; } } }
37.205882
109
0.63913
[ "CC0-1.0" ]
Konstantinos-Papanagnou/School-Programme
School Programme/Activities and fragments/ReviewLessons.cs
2,532
C#
using OpenNefia.Content.DebugView; using OpenNefia.Core.Game; using OpenNefia.Core.GameObjects; using OpenNefia.Core.Input; using OpenNefia.Core.Input.Binding; using OpenNefia.Core.IoC; using OpenNefia.Core.UserInterface; namespace OpenNefia.Content.GameObjects { public class DebugCommandsSystem : EntitySystem { [Dependency] private readonly IUserInterfaceManager _uiManager = default!; public override void Initialize() { CommandBinds.Builder .Bind(EngineKeyFunctions.ShowDebugView, InputCmdHandler.FromDelegate(ShowDebugView)) .Register<DebugCommandsSystem>(); } private TurnResult? ShowDebugView(IGameSessionManager? session) { if (session?.Player == null) return null; _uiManager.Query<DebugViewLayer>(); return TurnResult.NoResult; } } }
27.727273
100
0.671038
[ "MIT" ]
OpenNefia/OpenNefia
OpenNefia.Content/GameObjects/EntitySystems/Command/DebugCommandsSystem.cs
917
C#
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at subtext@googlegroups.com // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Globalization; using BlogML; using BlogML.Xml; using Subtext.Framework; using Subtext.Framework.Components; using Subtext.Framework.Providers; using Subtext.Framework.Routing; using Subtext.Framework.Services; namespace Subtext.ImportExport { public class BlogImportRepository : IBlogImportRepository { public BlogImportRepository(ISubtextContext context, ICommentService commentService, IEntryPublisher entryPublisher, IBlogMLImportMapper mapper) { SubtextContext = context; CommentService = commentService; EntryPublisher = entryPublisher; Mapper = mapper; } protected ObjectProvider Repository { get { return SubtextContext.Repository; } } public ISubtextContext SubtextContext { get; private set; } public IEntryPublisher EntryPublisher { get; private set; } public ICommentService CommentService { get; private set; } public IBlogMLImportMapper Mapper { get; private set; } public Blog Blog { get { return SubtextContext.Blog; } } protected UrlHelper Url { get { return SubtextContext.UrlHelper; } } public void CreateCategories(BlogMLBlog blog) { foreach(BlogMLCategory bmlCategory in blog.Categories) { LinkCategory category = Mapper.ConvertCategory(bmlCategory); Repository.CreateLinkCategory(category); } } public string CreateBlogPost(BlogMLBlog blog, BlogMLPost post) { Entry newEntry = Mapper.ConvertBlogPost(post, blog, Blog); newEntry.BlogId = Blog.Id; newEntry.Blog = Blog; var publisher = EntryPublisher as EntryPublisher; if(publisher != null) { var transform = publisher.Transformation as CompositeTextTransformation; if(transform != null) { transform.Clear(); } } return EntryPublisher.Publish(newEntry).ToString(CultureInfo.InvariantCulture); } public void CreateComment(BlogMLComment comment, string newPostId) { var newComment = Mapper.ConvertComment(comment, newPostId); CommentService.Create(newComment, false /*runfilters*/); } public void CreateTrackback(BlogMLTrackback trackback, string newPostId) { var pingTrack = Mapper.ConvertTrackback(trackback, newPostId); CommentService.Create(pingTrack, false /*runfilters*/); } public void SetExtendedProperties(BlogMLBlog.ExtendedPropertiesCollection extendedProperties) { if(extendedProperties != null && extendedProperties.Count > 0) { foreach(var extProp in extendedProperties) { if(BlogMLBlogExtendedProperties.CommentModeration.Equals(extProp.Key)) { bool modEnabled; if(bool.TryParse(extProp.Value, out modEnabled)) { Blog.ModerationEnabled = modEnabled; } } else if(BlogMLBlogExtendedProperties.EnableSendingTrackbacks.Equals(extProp.Key)) { bool tracksEnabled; if(bool.TryParse(extProp.Value, out tracksEnabled)) { Blog.TrackbacksEnabled = tracksEnabled; } } } Repository.UpdateBlog(Blog); } } public IDisposable SetupBlogForImport() { return new BlogImportSetup(Blog, Repository); } /// <summary> /// The physical path to the attachment directory. /// </summary> /// <remarks> /// The attachment is passed in to give the blog engine /// the opportunity to use attachment specific directories /// (ex. based on mime type) should it choose. /// </remarks> public string GetAttachmentDirectoryPath() { return Url.ImageDirectoryPath(Blog); } /// <summary> /// The url to the attachment directory /// </summary> /// <remarks> /// The attachment is passed in to give the blog engine /// the opportunity to use attachment specific directories /// (ex. based on mime type) should it choose. /// </remarks> public string GetAttachmentDirectoryUrl() { return Url.ImageDirectoryUrl(Blog); } } }
33.509091
152
0.565202
[ "MIT", "BSD-3-Clause" ]
Dashboard-X/SubText-2.5.2.0.src
Subtext.Framework/ImportExport/BlogImportRepository.cs
5,531
C#
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("PullBackStrategy")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("PullBackStrategy")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("35f19c43-c7cc-4f53-b8e0-61caaf9cd8e8")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
29.375
56
0.76383
[ "MIT" ]
Mikai47/cAlgoBot
Sources/Robots/PullBackStrategy/PullBackStrategy/Properties/AssemblyInfo.cs
472
C#
namespace Zinnia.Process.Moment { using UnityEngine; using Malimbe.MemberChangeMethod; using Malimbe.XmlDocumentationAttribute; using Malimbe.PropertySerializationAttribute; using Zinnia.Process.Moment.Collection; /// <summary> /// Iterates through a given <see cref="MomentProcess"/> collection and executes the <see cref="IProcessable.Process"/> method on the given Unity game loop moment. /// </summary> public class MomentProcessor : MonoBehaviour { /// <summary> /// The point in the Unity game loop when to execute the processes. /// </summary> public enum Moment { /// <summary> /// Never execute the processes. /// </summary> None, /// <summary> /// Execute the processes in the FixedUpdate physics part of the Unity game loop. /// </summary> FixedUpdate, /// <summary> /// Executes the processes in the Update game logic part of the Unity game loop. /// </summary> Update, /// <summary> /// Executes the processes in the LateUpdate game logic part of the Unity game loop. /// </summary> LateUpdate, /// <summary> /// Executes the processes in the camera PreCull scene rendering part of the Unity game loop. /// </summary> PreCull, /// <summary> /// Executes the processes in the camera PreRender scene rendering part of the Unity game loop. /// </summary> PreRender } /// <summary> /// The moment in which to process the given processes. /// </summary> [Serialized] [field: DocumentedByXml] public Moment ProcessMoment { get; set; } = Moment.PreRender; /// <summary> /// A collection of <see cref="MomentProcess"/> to process. /// </summary> [Serialized] [field: DocumentedByXml] public MomentProcessObservableList Processes { get; set; } protected virtual void OnEnable() { SubscribeMoment(); } protected virtual void OnDisable() { UnsubscribeMoment(); } protected virtual void FixedUpdate() { if (ProcessMoment == Moment.FixedUpdate) { Process(); } } protected virtual void Update() { if (ProcessMoment == Moment.Update) { Process(); } } protected virtual void LateUpdate() { if (ProcessMoment == Moment.LateUpdate) { Process(); } } protected virtual void OnCameraPreRender(Camera givenCamera) { Process(); } protected virtual void OnCameraPreCull(Camera givenCamera) { Process(); } /// <summary> /// Handles unsubscribing to the chosen subscribed moment event. /// </summary> protected virtual void UnsubscribeMoment() { switch (ProcessMoment) { case Moment.PreRender: Camera.onPreRender -= OnCameraPreRender; break; case Moment.PreCull: Camera.onPreCull -= OnCameraPreCull; break; } } /// <summary> /// Handles subscribing to the chosen moment to process event. /// </summary> protected virtual void SubscribeMoment() { switch (ProcessMoment) { case Moment.PreRender: Camera.onPreRender += OnCameraPreRender; break; case Moment.PreCull: Camera.onPreCull += OnCameraPreCull; break; } } /// <summary> /// Iterates through the given <see cref="MomentProcess"/> and calls <see cref="MomentProcess.Process"/> on each one. /// </summary> protected virtual void Process() { if (Processes == null) { return; } foreach (MomentProcess currentProcess in Processes.NonSubscribableElements) { currentProcess.Process(); } } /// <summary> /// Called before <see cref="ProcessMoment"/> has been changed. /// </summary> [CalledBeforeChangeOf(nameof(ProcessMoment))] protected virtual void OnBeforeProcessMomentChange() { UnsubscribeMoment(); } /// <summary> /// Called after <see cref="ProcessMoment"/> has been changed. /// </summary> [CalledAfterChangeOf(nameof(ProcessMoment))] protected virtual void OnAfterProcessMomentChange() { SubscribeMoment(); } } }
31.345238
168
0.50038
[ "MIT" ]
reznovVR/Zinnia.Unity
Runtime/Process/Moment/MomentProcessor.cs
5,268
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DotVVM.Framework.ViewModel; namespace DotVVM.Contrib.Samples.ViewModels { public class Switch_Sample1ViewModel : MasterViewModel { public bool SwitchValue { get; set; } public bool Enabled { get; set; } = true; public void SetValue() { SwitchValue = !SwitchValue; } } }
17.695652
55
0.690418
[ "Apache-2.0" ]
AMBULATUR/dotvvm-contrib
Controls/NoUiSlider/src/DotVVM.Contrib.Samples/ViewModels/Switch_Sample1ViewModel.cs
407
C#
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Configuration; using System.Threading; namespace Microsoft.Practices.EnterpriseLibrary.Common.Configuration { /// <summary> /// Provides validation for a <see cref="TimeSpan"/> object allowing non-negative spans and /// the value for <see cref="Timeout.InfiniteTimeSpan"/>. /// </summary> public class NonNegativeOrInfiniteTimeSpanValidator : TimeSpanValidator { /// <summary> /// Initializes a new instance of the <see cref="NonNegativeOrInfiniteTimeSpanValidator"/> class. /// </summary> public NonNegativeOrInfiniteTimeSpanValidator() : base(TimeSpan.Zero, TimeSpan.MaxValue) { } /// <summary> /// Determines whether the value of an object is valid. /// </summary> /// <param name="value">The value of an object.</param> public override void Validate(object value) { if (!(value is TimeSpan && ((TimeSpan)value) == Timeout.InfiniteTimeSpan)) { base.Validate(value); } } } }
33.162162
121
0.630807
[ "Apache-2.0" ]
EnterpriseLibrary/common-infrastructure
source/Src/Common/Configuration/NonNegativeOrInfiniteTimeSpanValidator.cs
1,227
C#
using Handelabra.Sentinels.Engine.Controller; using Handelabra.Sentinels.Engine.Model; namespace Fpe.Thief { public class TripwireTrapCardController : CardController { public TripwireCardController(Card card, TurnTakerController turnTakerController) : base(card, turnTakerController) { } public override void AddTriggers() { // When a target enters play... // ...{Thief} deals it 1 projectile damage. } } }
21.65
83
0.745958
[ "MIT" ]
FullPointerException/SotM-fantastical-fights
FantasticalFightsMod/Controller/Heroes/Thief/Cards/TripwireCardController.cs
433
C#
using System; using Mono.Linker.Tests.Cases.Expectations.Assertions; namespace Mono.Linker.Tests.Cases.Reflection { public class EventUsedViaReflection { public static void Main () { new Foo (); // Needed to avoid lazy body marking stubbing var eventInfo = typeof (Foo).GetEvent ("Event"); eventInfo.GetAddMethod (false); } [KeptMember (".ctor()")] class Foo { [Kept] [KeptBackingField] [KeptEventAddMethod] [KeptEventRemoveMethod] event EventHandler<EventArgs> Event; } } }
22.434783
60
0.705426
[ "MIT" ]
GrabYourPitchforks/linker
test/Mono.Linker.Tests.Cases/Reflection/EventUsedViaReflection.cs
518
C#
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Xml; using System.Xml.Serialization; namespace SwmSuite.Data.BusinessObjects { public class TaskCollection : BusinessObjectCollectionBase<Task> { /// <summary> /// Get a collection for a single task. /// </summary> /// <param name="task">The task to store into the collection.</param> /// <returns>A new TaskCollection containing the given task.</returns> public static TaskCollection FromSingleTask( Task task ) { TaskCollection tasks = new TaskCollection(); tasks.Add( task ); return tasks; } /// <summary> /// Deserializes the XML representation of an taskcollection to a new taskcollection. /// </summary> /// <param name="serialized">The XML representation of an taskcollection.</param> /// <returns>A new TaskCollection deserialized from the given XML string.</returns> public static TaskCollection Deserialize( string serialized ) { StringReader stringReader = new StringReader( serialized ); XmlReader reader = XmlReader.Create( stringReader ); XmlSerializer serializer = new XmlSerializer( typeof( TaskCollection ) ); TaskCollection toReturn = (TaskCollection)serializer.Deserialize( reader ); reader.Close(); stringReader.Close(); stringReader.Dispose(); return toReturn; } } }
31.581395
87
0.730486
[ "Unlicense" ]
Djohnnie/SwmSuite-Original
SwmSuite.Framework.BusinessObjects/TaskCollection.cs
1,360
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Okta.Idp { public static class GetMetadataSaml { /// <summary> /// Use this data source to retrieve SAML IdP metadata from Okta. /// /// {{% examples %}} /// ## Example Usage /// {{% example %}} /// /// ```csharp /// using Pulumi; /// using Okta = Pulumi.Okta; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var example = Output.Create(Okta.Idp.GetMetadataSaml.InvokeAsync(new Okta.Idp.GetMetadataSamlArgs /// { /// Id = "&lt;idp id&gt;", /// })); /// } /// /// } /// ``` /// {{% /example %}} /// {{% /examples %}} /// </summary> public static Task<GetMetadataSamlResult> InvokeAsync(GetMetadataSamlArgs? args = null, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetMetadataSamlResult>("okta:idp/getMetadataSaml:getMetadataSaml", args ?? new GetMetadataSamlArgs(), options.WithVersion()); } public sealed class GetMetadataSamlArgs : Pulumi.InvokeArgs { /// <summary> /// The id of the IdP to retrieve metadata for. /// </summary> [Input("idpId")] public string? IdpId { get; set; } public GetMetadataSamlArgs() { } } [OutputType] public sealed class GetMetadataSamlResult { /// <summary> /// whether assertions are signed. /// </summary> public readonly bool AssertionsSigned; /// <summary> /// whether authn requests are signed. /// </summary> public readonly bool AuthnRequestSigned; /// <summary> /// SAML request encryption certificate. /// </summary> public readonly string EncryptionCertificate; /// <summary> /// Entity URL for instance `https://www.okta.com/saml2/service-provider/sposcfdmlybtwkdcgtuf`. /// </summary> public readonly string EntityId; /// <summary> /// urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Post location from the SAML metadata. /// </summary> public readonly string HttpPostBinding; /// <summary> /// urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect location from the SAML metadata. /// </summary> public readonly string HttpRedirectBinding; /// <summary> /// The provider-assigned unique ID for this managed resource. /// </summary> public readonly string Id; public readonly string? IdpId; /// <summary> /// raw IdP metadata. /// </summary> public readonly string Metadata; /// <summary> /// SAML request signing certificate. /// </summary> public readonly string SigningCertificate; [OutputConstructor] private GetMetadataSamlResult( bool assertionsSigned, bool authnRequestSigned, string encryptionCertificate, string entityId, string httpPostBinding, string httpRedirectBinding, string id, string? idpId, string metadata, string signingCertificate) { AssertionsSigned = assertionsSigned; AuthnRequestSigned = authnRequestSigned; EncryptionCertificate = encryptionCertificate; EntityId = entityId; HttpPostBinding = httpPostBinding; HttpRedirectBinding = httpRedirectBinding; Id = id; IdpId = idpId; Metadata = metadata; SigningCertificate = signingCertificate; } } }
30.748148
179
0.56107
[ "ECL-2.0", "Apache-2.0" ]
brinnehlops/pulumi-okta
sdk/dotnet/Idp/GetMetadataSaml.cs
4,151
C#
using System; using System.Runtime.InteropServices; using CoreGraphics; using Foundation; using ObjCRuntime; namespace AppKit { public partial class NSSharingServiceDelegate { CGRect SourceFrameOnScreenForShareItem (NSSharingService sharingService, NSPasteboardWriting item) { return SourceFrameOnScreenForShareItem (sharingService, (INSPasteboardWriting)item); } NSImage TransitionImageForShareItem (NSSharingService sharingService, NSPasteboardWriting item, CGRect contentRect) { return TransitionImageForShareItem (sharingService, (INSPasteboardWriting)item, contentRect); } } }
30.2
117
0.827815
[ "BSD-3-Clause" ]
1975781737/xamarin-macios
src/AppKit/NSSharingServiceDelegate.cs
604
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager.Core; using Azure.ResourceManager.Network.Models; namespace Azure.ResourceManager.Network { internal partial class VirtualNetworkGatewayConnectionsRestOperations { private readonly string _userAgent; private readonly HttpPipeline _pipeline; private readonly Uri _endpoint; private readonly string _apiVersion; /// <summary> Initializes a new instance of VirtualNetworkGatewayConnectionsRestOperations. </summary> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="applicationId"> The application id to use for user agent. </param> /// <param name="endpoint"> server parameter. </param> /// <param name="apiVersion"> Api Version. </param> /// <exception cref="ArgumentNullException"> <paramref name="pipeline"/> or <paramref name="apiVersion"/> is null. </exception> public VirtualNetworkGatewayConnectionsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) { _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); _endpoint = endpoint ?? new Uri("https://management.azure.com"); _apiVersion = apiVersion ?? "2021-02-01"; _userAgent = Core.HttpMessageUtilities.GetUserAgentName(this, applicationId); } internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnectionData parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Put; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/connections/", false); uri.AppendPath(virtualNetworkGatewayConnectionName, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Creates or updates a virtual network gateway connection in the specified resource group. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The name of the virtual network gateway connection. </param> /// <param name="parameters"> Parameters supplied to the create or update virtual network gateway connection operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="virtualNetworkGatewayConnectionName"/> or <paramref name="parameters"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response> CreateOrUpdateAsync(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnectionData parameters, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); Argument.AssertNotNull(parameters, nameof(parameters)); using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 201: return message.Response; default: throw new RequestFailedException(message.Response); } } /// <summary> Creates or updates a virtual network gateway connection in the specified resource group. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The name of the virtual network gateway connection. </param> /// <param name="parameters"> Parameters supplied to the create or update virtual network gateway connection operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="virtualNetworkGatewayConnectionName"/> or <paramref name="parameters"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public Response CreateOrUpdate(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnectionData parameters, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); Argument.AssertNotNull(parameters, nameof(parameters)); using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 201: return message.Response; default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/connections/", false); uri.AppendPath(virtualNetworkGatewayConnectionName, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Gets the specified virtual network gateway connection by resource group. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The name of the virtual network gateway connection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<VirtualNetworkGatewayConnectionData>> GetAsync(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); using var message = CreateGetRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { VirtualNetworkGatewayConnectionData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = VirtualNetworkGatewayConnectionData.DeserializeVirtualNetworkGatewayConnectionData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((VirtualNetworkGatewayConnectionData)null, message.Response); default: throw new RequestFailedException(message.Response); } } /// <summary> Gets the specified virtual network gateway connection by resource group. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The name of the virtual network gateway connection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public Response<VirtualNetworkGatewayConnectionData> Get(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); using var message = CreateGetRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { VirtualNetworkGatewayConnectionData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = VirtualNetworkGatewayConnectionData.DeserializeVirtualNetworkGatewayConnectionData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((VirtualNetworkGatewayConnectionData)null, message.Response); default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Delete; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/connections/", false); uri.AppendPath(virtualNetworkGatewayConnectionName, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Deletes the specified virtual network Gateway connection. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The name of the virtual network gateway connection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response> DeleteAsync(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: case 204: return message.Response; default: throw new RequestFailedException(message.Response); } } /// <summary> Deletes the specified virtual network Gateway connection. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The name of the virtual network gateway connection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public Response Delete(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: case 204: return message.Response; default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateUpdateTagsRequest(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, TagsObject parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Patch; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/connections/", false); uri.AppendPath(virtualNetworkGatewayConnectionName, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Updates a virtual network gateway connection tags. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The name of the virtual network gateway connection. </param> /// <param name="parameters"> Parameters supplied to update virtual network gateway connection tags. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="virtualNetworkGatewayConnectionName"/> or <paramref name="parameters"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response> UpdateTagsAsync(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, TagsObject parameters, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); Argument.AssertNotNull(parameters, nameof(parameters)); using var message = CreateUpdateTagsRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw new RequestFailedException(message.Response); } } /// <summary> Updates a virtual network gateway connection tags. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The name of the virtual network gateway connection. </param> /// <param name="parameters"> Parameters supplied to update virtual network gateway connection tags. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="virtualNetworkGatewayConnectionName"/> or <paramref name="parameters"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public Response UpdateTags(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, TagsObject parameters, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); Argument.AssertNotNull(parameters, nameof(parameters)); using var message = CreateUpdateTagsRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateSetSharedKeyRequest(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Put; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/connections/", false); uri.AppendPath(virtualNetworkGatewayConnectionName, true); uri.AppendPath("/sharedkey", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The virtual network gateway connection name. </param> /// <param name="parameters"> Parameters supplied to the Begin Set Virtual Network Gateway connection Shared key operation throughNetwork resource provider. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="virtualNetworkGatewayConnectionName"/> or <paramref name="parameters"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response> SetSharedKeyAsync(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); Argument.AssertNotNull(parameters, nameof(parameters)); using var message = CreateSetSharedKeyRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 201: return message.Response; default: throw new RequestFailedException(message.Response); } } /// <summary> The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The virtual network gateway connection name. </param> /// <param name="parameters"> Parameters supplied to the Begin Set Virtual Network Gateway connection Shared key operation throughNetwork resource provider. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="virtualNetworkGatewayConnectionName"/> or <paramref name="parameters"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public Response SetSharedKey(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); Argument.AssertNotNull(parameters, nameof(parameters)); using var message = CreateSetSharedKeyRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 201: return message.Response; default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateGetSharedKeyRequest(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/connections/", false); uri.AppendPath(virtualNetworkGatewayConnectionName, true); uri.AppendPath("/sharedkey", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> The Get VirtualNetworkGatewayConnectionSharedKey operation retrieves information about the specified virtual network gateway connection shared key through Network resource provider. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The virtual network gateway connection shared key name. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<ConnectionSharedKey>> GetSharedKeyAsync(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); using var message = CreateGetSharedKeyRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ConnectionSharedKey value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ConnectionSharedKey.DeserializeConnectionSharedKey(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> The Get VirtualNetworkGatewayConnectionSharedKey operation retrieves information about the specified virtual network gateway connection shared key through Network resource provider. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The virtual network gateway connection shared key name. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public Response<ConnectionSharedKey> GetSharedKey(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); using var message = CreateGetSharedKeyRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ConnectionSharedKey value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ConnectionSharedKey.DeserializeConnectionSharedKey(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateListRequest(string subscriptionId, string resourceGroupName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/connections", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> The List VirtualNetworkGatewayConnections operation retrieves all the virtual network gateways connections created. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<VirtualNetworkGatewayConnectionListResult>> ListAsync(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); using var message = CreateListRequest(subscriptionId, resourceGroupName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { VirtualNetworkGatewayConnectionListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = VirtualNetworkGatewayConnectionListResult.DeserializeVirtualNetworkGatewayConnectionListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> The List VirtualNetworkGatewayConnections operation retrieves all the virtual network gateways connections created. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception> public Response<VirtualNetworkGatewayConnectionListResult> List(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); using var message = CreateListRequest(subscriptionId, resourceGroupName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { VirtualNetworkGatewayConnectionListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = VirtualNetworkGatewayConnectionListResult.DeserializeVirtualNetworkGatewayConnectionListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateResetSharedKeyRequest(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/connections/", false); uri.AppendPath(virtualNetworkGatewayConnectionName, true); uri.AppendPath("/sharedkey/reset", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> The VirtualNetworkGatewayConnectionResetSharedKey operation resets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The virtual network gateway connection reset shared key Name. </param> /// <param name="parameters"> Parameters supplied to the begin reset virtual network gateway connection shared key operation through network resource provider. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="virtualNetworkGatewayConnectionName"/> or <paramref name="parameters"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response> ResetSharedKeyAsync(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); Argument.AssertNotNull(parameters, nameof(parameters)); using var message = CreateResetSharedKeyRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw new RequestFailedException(message.Response); } } /// <summary> The VirtualNetworkGatewayConnectionResetSharedKey operation resets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The virtual network gateway connection reset shared key Name. </param> /// <param name="parameters"> Parameters supplied to the begin reset virtual network gateway connection shared key operation through network resource provider. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="virtualNetworkGatewayConnectionName"/> or <paramref name="parameters"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public Response ResetSharedKey(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); Argument.AssertNotNull(parameters, nameof(parameters)); using var message = CreateResetSharedKeyRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateStartPacketCaptureRequest(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, VpnPacketCaptureStartParameters parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/connections/", false); uri.AppendPath(virtualNetworkGatewayConnectionName, true); uri.AppendPath("/startPacketCapture", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); if (parameters != null) { request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; } message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Starts packet capture on virtual network gateway connection in the specified resource group. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The name of the virtual network gateway connection. </param> /// <param name="parameters"> Virtual network gateway packet capture parameters supplied to start packet capture on gateway connection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response> StartPacketCaptureAsync(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, VpnPacketCaptureStartParameters parameters = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); using var message = CreateStartPacketCaptureRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw new RequestFailedException(message.Response); } } /// <summary> Starts packet capture on virtual network gateway connection in the specified resource group. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The name of the virtual network gateway connection. </param> /// <param name="parameters"> Virtual network gateway packet capture parameters supplied to start packet capture on gateway connection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public Response StartPacketCapture(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, VpnPacketCaptureStartParameters parameters = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); using var message = CreateStartPacketCaptureRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateStopPacketCaptureRequest(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, VpnPacketCaptureStopParameters parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/connections/", false); uri.AppendPath(virtualNetworkGatewayConnectionName, true); uri.AppendPath("/stopPacketCapture", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Stops packet capture on virtual network gateway connection in the specified resource group. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The name of the virtual network gateway Connection. </param> /// <param name="parameters"> Virtual network gateway packet capture parameters supplied to stop packet capture on gateway connection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="virtualNetworkGatewayConnectionName"/> or <paramref name="parameters"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response> StopPacketCaptureAsync(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, VpnPacketCaptureStopParameters parameters, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); Argument.AssertNotNull(parameters, nameof(parameters)); using var message = CreateStopPacketCaptureRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw new RequestFailedException(message.Response); } } /// <summary> Stops packet capture on virtual network gateway connection in the specified resource group. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The name of the virtual network gateway Connection. </param> /// <param name="parameters"> Virtual network gateway packet capture parameters supplied to stop packet capture on gateway connection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="virtualNetworkGatewayConnectionName"/> or <paramref name="parameters"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public Response StopPacketCapture(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, VpnPacketCaptureStopParameters parameters, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); Argument.AssertNotNull(parameters, nameof(parameters)); using var message = CreateStopPacketCaptureRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateGetIkeSasRequest(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/connections/", false); uri.AppendPath(virtualNetworkGatewayConnectionName, true); uri.AppendPath("/getikesas", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Lists IKE Security Associations for the virtual network gateway connection in the specified resource group. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The name of the virtual network gateway Connection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response> GetIkeSasAsync(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); using var message = CreateGetIkeSasRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw new RequestFailedException(message.Response); } } /// <summary> Lists IKE Security Associations for the virtual network gateway connection in the specified resource group. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The name of the virtual network gateway Connection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public Response GetIkeSas(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); using var message = CreateGetIkeSasRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateResetConnectionRequest(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/connections/", false); uri.AppendPath(virtualNetworkGatewayConnectionName, true); uri.AppendPath("/resetconnection", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Resets the virtual network gateway connection specified. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The name of the virtual network gateway Connection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response> ResetConnectionAsync(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); using var message = CreateResetConnectionRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 202: return message.Response; default: throw new RequestFailedException(message.Response); } } /// <summary> Resets the virtual network gateway connection specified. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="virtualNetworkGatewayConnectionName"> The name of the virtual network gateway Connection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="virtualNetworkGatewayConnectionName"/> is an empty string, and was expected to be non-empty. </exception> public Response ResetConnection(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(virtualNetworkGatewayConnectionName, nameof(virtualNetworkGatewayConnectionName)); using var message = CreateResetConnectionRequest(subscriptionId, resourceGroupName, virtualNetworkGatewayConnectionName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 202: return message.Response; default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> The List VirtualNetworkGatewayConnections operation retrieves all the virtual network gateways connections created. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<VirtualNetworkGatewayConnectionListResult>> ListNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) { Argument.AssertNotNull(nextLink, nameof(nextLink)); Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceGroupName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { VirtualNetworkGatewayConnectionListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = VirtualNetworkGatewayConnectionListResult.DeserializeVirtualNetworkGatewayConnectionListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> The List VirtualNetworkGatewayConnections operation retrieves all the virtual network gateways connections created. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception> public Response<VirtualNetworkGatewayConnectionListResult> ListNextPage(string nextLink, string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) { Argument.AssertNotNull(nextLink, nameof(nextLink)); Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceGroupName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { VirtualNetworkGatewayConnectionListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = VirtualNetworkGatewayConnectionListResult.DeserializeVirtualNetworkGatewayConnectionListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } } }
73.495644
262
0.693365
[ "MIT" ]
KurnakovMaksim/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/RestOperations/VirtualNetworkGatewayConnectionsRestOperations.cs
75,921
C#
//////////////////////////////////////////////////////////////////////////////// // // MIT License // // Copyright (c) 2018-2019 Nuraga Wiswakarma // // 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 UnrealBuildTool; public class JSONSVGPlugin: ModuleRules { public JSONSVGPlugin(ReadOnlyTargetRules Target) : base(Target) { PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; PublicDependencyModuleNames.AddRange( new string[] { "Core", "CoreUObject", "Engine" }); PrivateDependencyModuleNames.AddRange( new string[] { "Json", "JsonUtilities" }); PrivateIncludePaths.Add("JSONSVGPlugin/Private"); } }
35.923077
80
0.63758
[ "MIT" ]
nwiswakarma/JSONSVGPlugin
Source/JSONSVGPlugin/JSONSVGPlugin.Build.cs
1,868
C#
// Copyright (c) Dolittle. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Machine.Specifications; namespace Dolittle.Runtime.Events.Store.Specs.for_UncommittedEvents { public class when_creating_with_events : given.events { static UncommittedEvents events; Because of = () => { events = new UncommittedEvents(new[] { event_one, event_two, event_three }); }; It should_not_be_empty = () => events.ShouldNotBeEmpty(); It should_have_events = () => events.HasEvents.ShouldBeTrue(); It should_have_a_count_of_three = () => events.Count.ShouldEqual(3); It should_have_the_first_event_at_index_zero = () => events[0].ShouldEqual(event_one); It should_have_the_second_event_at_index_one = () => events[1].ShouldEqual(event_two); It should_have_the_third_event_at_index_two = () => events[2].ShouldEqual(event_three); } }
40.2
101
0.696517
[ "MIT" ]
dolittle/Runtime
Specifications/Events.Store/for_UncommittedEvents/when_creating_with_events.cs
1,007
C#
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.IO; using Lucene.Net.Analysis.Payloads; using Lucene.Net.Index; namespace Lucene.Net.Analysis.Shingle.Codec { /// <summary> /// A full featured codec not to be used for something serious. /// /// It takes complete control of /// payload for weight /// and the bit flags for positioning in the matrix. /// /// Mainly exist for demonstrational purposes. /// </summary> public class SimpleThreeDimensionalTokenSettingsCodec : TokenSettingsCodec { /// <summary> /// /// </summary> /// <param name="token"></param> /// <returns>the token flags int value as TokenPosition</returns> public override TokenPositioner GetTokenPositioner(Token token) { switch (token.Flags) { case 0: return TokenPositioner.NewColumn; case 1: return TokenPositioner.NewRow; case 2: return TokenPositioner.SameRow; } throw new IOException("Unknown matrix positioning of token " + token); } /// <summary> /// Sets the TokenPositioner as token flags int value. /// </summary> /// <param name="token"></param> /// <param name="tokenPositioner"></param> public override void SetTokenPositioner(Token token, TokenPositioner tokenPositioner) { token.Flags = tokenPositioner.Index; } /// <summary> /// Returns a 32 bit float from the payload, or 1f it null. /// </summary> /// <param name="token"></param> /// <returns></returns> public override float GetWeight(Token token) { if (token.Payload == null || token.Payload.GetData() == null) return 1f; return PayloadHelper.DecodeFloat(token.Payload.GetData()); } /// <summary> /// Stores a 32 bit float in the payload, or set it to null if 1f; /// </summary> /// <param name="token"></param> /// <param name="weight"></param> public override void SetWeight(Token token, float weight) { token.Payload = weight == 1f ? null : new Payload(PayloadHelper.EncodeFloat(weight)); } } }
37.057471
98
0.592742
[ "Apache-2.0" ]
Anomalous-Software/Lucene.NET
src/contrib/Analyzers/Shingle/Codec/SimpleThreeDimensionalTokenSettingsCodec.cs
3,226
C#
using System; using System.Windows; using System.Windows.Input; using SZDC.Editor; using SZDC.Editor.TrainTimetables; using SZDC.Wpf.TrainGraph; namespace SZDC.Wpf.Editor { public static class ViewConnector { public static void Connect<TWindow, TDisposableContext>(IServiceProvider serviceProvider) where TWindow : Window, new() { var context = serviceProvider.GetService<TDisposableContext>(); var window = new TWindow {DataContext = context}; window.Show(); } public static void ConnectDynamic(IServiceProvider serviceProvider, ApplicationEditor applicationEditor) { var context = serviceProvider.GetService<DynamicTrainTimetable>(); var window = new DynamicTrainGraphWindow { DataContext = context, ApplicationEditor = applicationEditor }; window.Show(); } } public static class ProjectEditorCommands { public static ICommand OpenStaticTimetable { get; set; } public static ICommand OpenDynamicTimetable { get; set; } public static void Initialize(IServiceProvider serviceProvider) { OpenStaticTimetable = new Command(_ => true, _ => CreateStaticTimetable(serviceProvider)); OpenDynamicTimetable = new Command(_ => true, _ => CreateDynamicTimetable(serviceProvider)); } private static void CreateDynamicTimetable(IServiceProvider serviceProvider) { var projectEditor = serviceProvider.GetService<ApplicationEditor>(); var scopedTimetable = projectEditor.OpenDynamicTrainTimetable(); ViewConnector.ConnectDynamic(scopedTimetable, projectEditor); } private static void CreateStaticTimetable(IServiceProvider serviceProvider) { var projectEditor = serviceProvider.GetService<ApplicationEditor>(); var scopedTimetable = projectEditor.OpenStaticTrainTimetable(); ViewConnector.Connect<StaticTrainGraphWindow, StaticTrainTimetable>(scopedTimetable); } } }
36.821429
118
0.701746
[ "MIT" ]
Sykoj/GTTG
solution/SZDC.WPF/Editor/ProjectEditorCommands.cs
2,064
C#
#pragma checksum "..\..\..\App.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "52A334172092355AF129593D7411C0C0493900D1" //------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Forms.Integration; 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 HardwareInfo { /// <summary> /// App /// </summary> public partial class App : System.Windows.Application { private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; #line 5 "..\..\..\App.xaml" this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative); #line default #line hidden System.Uri resourceLocater = new System.Uri("/HardwareInfo;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.0.0.0")] public static void Main() { HardwareInfo.App app = new HardwareInfo.App(); app.InitializeComponent(); app.Run(); } } }
31.642857
121
0.593679
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
rong-xiaoli/HardwareInfo
HardwareInfo/obj/x86/Debug/App.g.cs
2,766
C#
#region Copyright // // DotNetNuke® - http://www.dotnetnuke.com // Copyright (c) 2002-2018 // by DotNetNuke Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion #region Usings using System; using System.Collections; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using DotNetNuke.Common; using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Users; using DotNetNuke.Security; using DotNetNuke.Security.Permissions; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.Localization; using DotNetNuke.UI.Skins.Controls; using DotNetNuke.Entities.Portals; using DotNetNuke.Common.Utilities; using Telerik.Web.UI; using DotNetNuke.Modules.Html.Components; #endregion namespace DotNetNuke.Modules.Html { /// <summary> /// The EditHtml PortalModuleBase is used to manage Html /// </summary> /// <remarks> /// </remarks> public partial class EditHtml : HtmlModuleBase { #region Private Members private readonly HtmlTextController _htmlTextController = new HtmlTextController(); private readonly HtmlTextLogController _htmlTextLogController = new HtmlTextLogController(); private readonly WorkflowStateController _workflowStateController = new WorkflowStateController(); #endregion #region Nested type: WorkflowType private enum WorkflowType { DirectPublish = 1, ContentStaging = 2 } #endregion #region Private Properties private int WorkflowID { get { int workflowID; if (ViewState["WorkflowID"] == null) { workflowID = _htmlTextController.GetWorkflow(ModuleId, TabId, PortalId).Value; ViewState.Add("WorkflowID", workflowID); } else { workflowID = int.Parse(ViewState["WorkflowID"].ToString()); } return workflowID; } } private string TempContent { get { var content = ""; if ((ViewState["TempContent"] != null)) { content = ViewState["TempContent"].ToString(); } return content; } set { ViewState["TempContent"] = value; } } private WorkflowType CurrentWorkflowType { get { var currentWorkflowType = default(WorkflowType); if (ViewState["_currentWorkflowType"] != null) { currentWorkflowType = (WorkflowType) Enum.Parse(typeof (WorkflowType), ViewState["_currentWorkflowType"].ToString()); } return currentWorkflowType; } set { ViewState["_currentWorkflowType"] = value; } } protected string CurrentView { get { if (phEdit.Visible) return "EditView"; else if (phPreview.Visible) return "PreviewView"; if (phHistory.Visible) return "HistoryView"; else return ""; } } #endregion #region Private Methods /// <summary> /// Displays the history of an html content item in a grid in the preview section. /// </summary> /// <param name = "htmlContent">Content of the HTML.</param> private void DisplayHistory(HtmlTextInfo htmlContent) { dnnSitePanelEditHTMLHistory.Visible = CurrentWorkflowType != WorkflowType.DirectPublish; fsEditHtmlHistory.Visible = CurrentWorkflowType != WorkflowType.DirectPublish; if (((CurrentWorkflowType == WorkflowType.DirectPublish))) { return; } var htmlLogging = _htmlTextLogController.GetHtmlTextLog(htmlContent.ItemID); dgHistory.DataSource = htmlLogging; dgHistory.DataBind(); dnnSitePanelEditHTMLHistory.Visible = htmlLogging.Count != 0; fsEditHtmlHistory.Visible = htmlLogging.Count != 0; } /// <summary> /// Displays the versions of the html content in the versions section /// </summary> private void DisplayVersions() { var versions = _htmlTextController.GetAllHtmlText(ModuleId); foreach (var item in versions) { item.StateName = GetLocalizedString(item.StateName); } dgVersions.DataSource = versions; dgVersions.DataBind(); phEdit.Visible = false; phPreview.Visible = false; phHistory.Visible = true; cmdEdit.Enabled = true; cmdPreview.Enabled = true; cmdHistory.Enabled = false; cmdMasterContent.Visible = false; ddlRender.Visible = false; } /// <summary> /// Displays the content of the master language if localized content is enabled. /// </summary> private void DisplayMasterLanguageContent() { //Get master language var objModule = ModuleController.Instance.GetModule(ModuleId, TabId, false); if (objModule.DefaultLanguageModule != null) { var masterContent = _htmlTextController.GetTopHtmlText(objModule.DefaultLanguageModule.ModuleID, false, WorkflowID); if (masterContent != null) { placeMasterContent.Controls.Add(new LiteralControl(HtmlTextController.FormatHtmlText(objModule.DefaultLanguageModule.ModuleID, FormatContent(masterContent.Content), Settings, PortalSettings, Page))); } } } /// <summary> /// Displays the html content in the preview section. /// </summary> /// <param name = "htmlContent">Content of the HTML.</param> private void DisplayContent(HtmlTextInfo htmlContent) { lblCurrentWorkflowInUse.Text = GetLocalizedString(htmlContent.WorkflowName); lblCurrentWorkflowState.Text = GetLocalizedString(htmlContent.StateName); lblCurrentVersion.Text = htmlContent.Version.ToString(); txtContent.Text = FormatContent(htmlContent.Content); phEdit.Visible = true; phPreview.Visible = false; phHistory.Visible = false; cmdEdit.Enabled = false; cmdPreview.Enabled = true; cmdHistory.Enabled = true; //DisplayMasterLanguageContent(); DisplayMasterContentButton(); ddlRender.Visible = true; } private void DisplayMasterContentButton() { var objModule = ModuleController.Instance.GetModule(ModuleId, TabId, false); if (objModule.DefaultLanguageModule != null) { cmdMasterContent.Visible = true; cmdMasterContent.Text = Localization.GetString("cmdShowMasterContent", LocalResourceFile); cmdMasterContent.Text = phMasterContent.Visible ? Localization.GetString("cmdHideMasterContent", LocalResourceFile) : Localization.GetString("cmdShowMasterContent", LocalResourceFile); } } /// <summary> /// Displays the content preview in the preview section /// </summary> /// <param name = "htmlContent">Content of the HTML.</param> private void DisplayPreview(HtmlTextInfo htmlContent) { lblPreviewVersion.Text = htmlContent.Version.ToString(); lblPreviewWorkflowInUse.Text = GetLocalizedString(htmlContent.WorkflowName); lblPreviewWorkflowState.Text = GetLocalizedString(htmlContent.StateName); litPreview.Text = HtmlTextController.FormatHtmlText(ModuleId, htmlContent.Content, Settings, PortalSettings, Page); phEdit.Visible = false; phPreview.Visible = true; phHistory.Visible = false; cmdEdit.Enabled = true; cmdPreview.Enabled = false; cmdHistory.Enabled = true; DisplayHistory(htmlContent); cmdMasterContent.Visible = false; ddlRender.Visible = false; } /// <summary> /// Displays the preview in the preview section /// </summary> /// <param name = "htmlContent">Content of the HTML.</param> private void DisplayPreview(string htmlContent) { litPreview.Text = HtmlTextController.FormatHtmlText(ModuleId, htmlContent, Settings, PortalSettings, Page); divPreviewVersion.Visible = false; divPreviewWorlflow.Visible = false; divPreviewWorkflowState.Visible = true; lblPreviewWorkflowState.Text = GetLocalizedString("EditPreviewState"); phEdit.Visible = false; phPreview.Visible = true; phHistory.Visible = false; cmdEdit.Enabled = true; cmdPreview.Enabled = false; cmdHistory.Enabled = true; cmdMasterContent.Visible = false; ddlRender.Visible = false; } private void DisplayEdit(string htmlContent) { txtContent.Text = htmlContent; phEdit.Visible = true; phPreview.Visible = false; phHistory.Visible = false; cmdEdit.Enabled = false; cmdPreview.Enabled = true; cmdHistory.Enabled = true; DisplayMasterContentButton(); ddlRender.Visible = true; } /// <summary> /// Displays the content but hide the editor if editing is locked from the current user /// </summary> /// <param name = "htmlContent">Content of the HTML.</param> /// <param name = "lastPublishedContent">Last content of the published.</param> private void DisplayLockedContent(HtmlTextInfo htmlContent, HtmlTextInfo lastPublishedContent) { txtContent.Visible = false; cmdSave.Visible = false; //cmdPreview.Enabled = false; divPublish.Visible = false; divSubmittedContent.Visible = true; lblCurrentWorkflowInUse.Text = GetLocalizedString(htmlContent.WorkflowName); lblCurrentWorkflowState.Text = GetLocalizedString(htmlContent.StateName); litCurrentContentPreview.Text = HtmlTextController.FormatHtmlText(ModuleId, htmlContent.Content, Settings, PortalSettings, Page); lblCurrentVersion.Text = htmlContent.Version.ToString(); DisplayVersions(); if ((lastPublishedContent != null)) { DisplayPreview(lastPublishedContent); //DisplayHistory(lastPublishedContent); } else { dnnSitePanelEditHTMLHistory.Visible = false; fsEditHtmlHistory.Visible = false; DisplayPreview(htmlContent.Content); } } /// <summary> /// Displays the initial content when a module is first added to the page. /// </summary> /// <param name = "firstState">The first state.</param> private void DisplayInitialContent(WorkflowStateInfo firstState) { cmdHistory.Enabled = false; txtContent.Text = GetLocalizedString("AddContent"); litPreview.Text = GetLocalizedString("AddContent"); lblCurrentWorkflowInUse.Text = firstState.WorkflowName; lblPreviewWorkflowInUse.Text = firstState.WorkflowName; divPreviewVersion.Visible = false; dnnSitePanelEditHTMLHistory.Visible = false; fsEditHtmlHistory.Visible = false; divCurrentWorkflowState.Visible = false; phCurrentVersion.Visible = false; divPreviewWorkflowState.Visible = false; lblPreviewWorkflowState.Text = firstState.StateName; } #endregion #region Private Functions /// <summary> /// Formats the content to make it html safe. /// </summary> /// <param name = "htmlContent">Content of the HTML.</param> /// <returns></returns> private string FormatContent(string htmlContent) { var strContent = HttpUtility.HtmlDecode(htmlContent); strContent = HtmlTextController.ManageRelativePaths(strContent, PortalSettings.HomeDirectory, "src", PortalId); strContent = HtmlTextController.ManageRelativePaths(strContent, PortalSettings.HomeDirectory, "background", PortalId); return HttpUtility.HtmlEncode(strContent); } /// <summary> /// Gets the localized string from a resource file if it exists. /// </summary> /// <param name = "str">The STR.</param> /// <returns></returns> private string GetLocalizedString(string str) { var localizedString = Localization.GetString(str, LocalResourceFile); return (string.IsNullOrEmpty(localizedString) ? str : localizedString); } /// <summary> /// Gets the latest html content of the module /// </summary> /// <returns></returns> private HtmlTextInfo GetLatestHTMLContent() { var htmlContent = _htmlTextController.GetTopHtmlText(ModuleId, false, WorkflowID); if (htmlContent == null) { htmlContent = new HtmlTextInfo(); htmlContent.ItemID = -1; htmlContent.StateID = _workflowStateController.GetFirstWorkflowStateID(WorkflowID); htmlContent.WorkflowID = WorkflowID; htmlContent.ModuleID = ModuleId; } return htmlContent; } /// <summary> /// Returns whether or not the user has review permissions to this module /// </summary> /// <param name = "htmlContent">Content of the HTML.</param> /// <returns></returns> private bool UserCanReview(HtmlTextInfo htmlContent) { return (htmlContent != null) && WorkflowStatePermissionController.HasWorkflowStatePermission(WorkflowStatePermissionController.GetWorkflowStatePermissions(htmlContent.StateID), "REVIEW"); } /// <summary> /// Gets the last published version of this module /// </summary> /// <param name = "publishedStateID">The published state ID.</param> /// <returns></returns> private HtmlTextInfo GetLastPublishedVersion(int publishedStateID) { return (from version in _htmlTextController.GetAllHtmlText(ModuleId) where version.StateID == publishedStateID orderby version.Version descending select version).ToList()[0]; } #endregion #region Event Handlers protected override void OnInit(EventArgs e) { base.OnInit(e); hlCancel.NavigateUrl = Globals.NavigateURL(); cmdEdit.Click += OnEditClick; cmdPreview.Click += OnPreviewClick; cmdHistory.Click += OnHistoryClick; cmdMasterContent.Click += OnMasterContentClick; ddlRender.SelectedIndexChanged += OnRenderSelectedIndexChanged; cmdSave.Click += OnSaveClick; dgHistory.RowDataBound += OnHistoryGridItemDataBound; dgVersions.RowCommand += OnVersionsGridItemCommand; dgVersions.RowDataBound += OnVersionsGridItemDataBound; dgVersions.PageIndexChanged += OnVersionsGridPageIndexChanged; } private void OnRenderSelectedIndexChanged(object sender, EventArgs e) { txtContent.ChangeMode(ddlRender.SelectedValue); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); try { var htmlContentItemID = -1; var htmlContent = _htmlTextController.GetTopHtmlText(ModuleId, false, WorkflowID); if ((htmlContent != null)) { htmlContentItemID = htmlContent.ItemID; } if (!Page.IsPostBack) { var workflowStates = _workflowStateController.GetWorkflowStates(WorkflowID); var maxVersions = _htmlTextController.GetMaximumVersionHistory(PortalId); var userCanEdit = UserInfo.IsSuperUser || PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName); lblMaxVersions.Text = maxVersions.ToString(); dgVersions.PageSize = Math.Min(Math.Max(maxVersions, 5), 10); //min 5, max 10 switch (workflowStates.Count) { case 1: CurrentWorkflowType = WorkflowType.DirectPublish; break; case 2: CurrentWorkflowType = WorkflowType.ContentStaging; break; } if (htmlContentItemID != -1) { DisplayContent(htmlContent); //DisplayPreview(htmlContent); DisplayHistory(htmlContent); } else { DisplayInitialContent(workflowStates[0] as WorkflowStateInfo); } divPublish.Visible = CurrentWorkflowType != WorkflowType.DirectPublish; phCurrentVersion.Visible = CurrentWorkflowType != WorkflowType.DirectPublish; phPreviewVersion.Visible = CurrentWorkflowType != WorkflowType.DirectPublish; //DisplayVersions(); BindRenderItems(); ddlRender.SelectedValue = txtContent.Mode; } } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } } protected void OnSaveClick(object sender, EventArgs e) { const bool redirect = true; try { // get content var htmlContent = GetLatestHTMLContent(); var aliases = from PortalAliasInfo pa in PortalAliasController.Instance.GetPortalAliasesByPortalId(PortalSettings.PortalId) select pa.HTTPAlias; string content; if (phEdit.Visible) content = txtContent.Text; else content = hfEditor.Value; if (Request.QueryString["nuru"] == null) { content = HtmlUtils.AbsoluteToRelativeUrls(content, aliases); } htmlContent.Content = content; var draftStateID = _workflowStateController.GetFirstWorkflowStateID(WorkflowID); var publishedStateID = _workflowStateController.GetLastWorkflowStateID(WorkflowID); switch (CurrentWorkflowType) { case WorkflowType.DirectPublish: _htmlTextController.UpdateHtmlText(htmlContent, _htmlTextController.GetMaximumVersionHistory(PortalId)); break; case WorkflowType.ContentStaging: if (chkPublish.Checked) { //if it's already published set it to draft if (htmlContent.StateID == publishedStateID) { htmlContent.StateID = draftStateID; } else { htmlContent.StateID = publishedStateID; //here it's in published mode } } else { //if it's already published set it back to draft if ((htmlContent.StateID != draftStateID)) { htmlContent.StateID = draftStateID; } } _htmlTextController.UpdateHtmlText(htmlContent, _htmlTextController.GetMaximumVersionHistory(PortalId)); break; } } catch (Exception exc) { Exceptions.LogException(exc); UI.Skins.Skin.AddModuleMessage(Page, "Error occurred: ", exc.Message, ModuleMessage.ModuleMessageType.RedError); return; } // redirect back to portal if (redirect) { Response.Redirect(Globals.NavigateURL(), true); } } protected void OnEditClick(object sender, EventArgs e) { try { DisplayEdit(hfEditor.Value); if (phMasterContent.Visible) DisplayMasterLanguageContent(); } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } } protected void OnPreviewClick(object sender, EventArgs e) { try { if (phEdit.Visible) hfEditor.Value = txtContent.Text; DisplayPreview(phEdit.Visible ? txtContent.Text : hfEditor.Value); } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } } private void OnHistoryClick(object sender, EventArgs e) { try { if (phEdit.Visible) hfEditor.Value = txtContent.Text; DisplayVersions(); } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } } private void OnMasterContentClick(object sender, EventArgs e) { try { phMasterContent.Visible = !phMasterContent.Visible; cmdMasterContent.Text = phMasterContent.Visible ? Localization.GetString("cmdHideMasterContent", LocalResourceFile) : Localization.GetString("cmdShowMasterContent", LocalResourceFile); if (phMasterContent.Visible) DisplayMasterLanguageContent(); } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } } protected void OnHistoryGridItemDataBound(object sender, GridViewRowEventArgs e) { var item = e.Row; if (item.RowType == DataControlRowType.DataRow) { //Localize columns item.Cells[2].Text = Localization.GetString(item.Cells[2].Text, LocalResourceFile); item.Cells[3].Text = Localization.GetString(item.Cells[3].Text, LocalResourceFile); } } protected void OnVersionsGridItemCommand(object source, GridViewCommandEventArgs e) { try { HtmlTextInfo htmlContent; //disable delete button if user doesn't have delete rights??? switch (e.CommandName.ToLowerInvariant()) { case "remove": htmlContent = GetHTMLContent(e); _htmlTextController.DeleteHtmlText(ModuleId, htmlContent.ItemID); break; case "rollback": htmlContent = GetHTMLContent(e); htmlContent.ItemID = -1; htmlContent.ModuleID = ModuleId; htmlContent.WorkflowID = WorkflowID; htmlContent.StateID = _workflowStateController.GetFirstWorkflowStateID(WorkflowID); _htmlTextController.UpdateHtmlText(htmlContent, _htmlTextController.GetMaximumVersionHistory(PortalId)); break; case "preview": htmlContent = GetHTMLContent(e); DisplayPreview(htmlContent); break; } if ((e.CommandName.ToLowerInvariant() != "preview")) { var latestContent = _htmlTextController.GetTopHtmlText(ModuleId, false, WorkflowID); if (latestContent == null) { DisplayInitialContent(_workflowStateController.GetWorkflowStates(WorkflowID)[0] as WorkflowStateInfo); } else { DisplayContent(latestContent); //DisplayPreview(latestContent); //DisplayVersions(); } } //Module failed to load } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } } private HtmlTextInfo GetHTMLContent(GridViewCommandEventArgs e) { return _htmlTextController.GetHtmlText(ModuleId, int.Parse(e.CommandArgument.ToString())); } protected void OnVersionsGridItemDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { var htmlContent = e.Row.DataItem as HtmlTextInfo; var createdBy = "Default"; if ((htmlContent.CreatedByUserID != -1)) { var createdByByUser = UserController.GetUserById(PortalId, htmlContent.CreatedByUserID); if (createdByByUser != null) { createdBy = createdByByUser.DisplayName; } } foreach (TableCell cell in e.Row.Cells) { foreach (Control cellControl in cell.Controls) { if (cellControl is ImageButton) { var imageButton = cellControl as ImageButton; imageButton.CommandArgument = htmlContent.ItemID.ToString(); switch (imageButton.CommandName.ToLowerInvariant()) { case "rollback": //hide rollback for the first item if (dgVersions.CurrentPageIndex == 0) { if ((e.Row.RowIndex == 0)) { imageButton.Visible = false; break; } } imageButton.Visible = true; break; case "remove": var msg = GetLocalizedString("DeleteVersion.Confirm"); msg = msg.Replace("[VERSION]", htmlContent.Version.ToString()).Replace("[STATE]", htmlContent.StateName).Replace("[DATECREATED]", htmlContent.CreatedOnDate.ToString()) .Replace("[USERNAME]", createdBy); imageButton.OnClientClick = "return confirm(\"" + msg + "\");"; //hide the delete button var showDelete = UserInfo.IsSuperUser || PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName); if (!showDelete) { showDelete = htmlContent.IsPublished == false; } imageButton.Visible = showDelete; break; } } } } } } protected void OnVersionsGridPageIndexChanged(object source, EventArgs e) { DisplayVersions(); } private void BindRenderItems() { if (txtContent.IsRichEditorAvailable) { ddlRender.Items.Add(new ListItem(LocalizeString("liRichText"), "RICH")); } ddlRender.Items.Add(new ListItem(LocalizeString("liBasicText"), "BASIC")); } #endregion } }
39.670013
220
0.528134
[ "MIT" ]
Abrahamberg/Dnn.Platform
DNN Platform/Modules/HTML/EditHtml.ascx.cs
31,618
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 serverlessrepo-2017-09-08.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ServerlessApplicationRepository.Model { /// <summary> /// This is the response object from the PutApplicationPolicy operation. /// </summary> public partial class PutApplicationPolicyResponse : AmazonWebServiceResponse { private List<ApplicationPolicyStatement> _statements = new List<ApplicationPolicyStatement>(); /// <summary> /// Gets and sets the property Statements. /// <para> /// An array of policy statements applied to the application. /// </para> /// </summary> public List<ApplicationPolicyStatement> Statements { get { return this._statements; } set { this._statements = value; } } // Check to see if Statements property is set internal bool IsSetStatements() { return this._statements != null && this._statements.Count > 0; } } }
33
113
0.659755
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/ServerlessApplicationRepository/Generated/Model/PutApplicationPolicyResponse.cs
1,881
C#
namespace ConoHaNet.Services.Compute { using System; using System.Collections.Concurrent; using Newtonsoft.Json; using OpenStack.ObjectModel; /// <summary> /// This enumeration is part of the <see href="http://docs.rackspace.com/servers/api/v2/cs-devguide/content/ch_extensions.html#diskconfig_attribute"><newTerm>disk configuration extension</newTerm></see>, /// which adds at attribute to images and servers to control how the disk is partitioned when /// servers are created, rebuilt, or resized. /// </summary> /// <remarks> /// This class functions as a strongly-typed enumeration of known disk configurations, /// with added support for unknown types returned by a server extension. /// </remarks> /// <seealso href="http://docs.rackspace.com/servers/api/v2/cs-devguide/content/ch_extensions.html#diskconfig_attribute">Disk Configuration Extension (Rackspace Next Generation Cloud Servers Developer Guide - API v2)</seealso> /// <threadsafety static="true" instance="false"/> [JsonConverter(typeof(DiskConfiguration.Converter))] public sealed class DiskConfiguration : ExtensibleEnum<DiskConfiguration> { private static readonly ConcurrentDictionary<string, DiskConfiguration> _types = new ConcurrentDictionary<string, DiskConfiguration>(StringComparer.OrdinalIgnoreCase); private static readonly DiskConfiguration _auto = FromName("AUTO"); private static readonly DiskConfiguration _manual = FromName("MANUAL"); /// <summary> /// Initializes a new instance of the <see cref="DiskConfiguration"/> class with the specified name. /// </summary> /// <inheritdoc/> private DiskConfiguration(string name) : base(name) { } /// <summary> /// Gets the <see cref="DiskConfiguration"/> instance with the specified name. /// </summary> /// <param name="name">The name.</param> /// <returns>The unique <see cref="DiskConfiguration"/> instance with the specified name.</returns> /// <exception cref="ArgumentNullException">If <paramref name="name"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentException">If <paramref name="name"/> is empty.</exception> public static DiskConfiguration FromName(string name) { if (name == null) throw new ArgumentNullException("name"); if (string.IsNullOrEmpty(name)) throw new ArgumentException("name cannot be empty"); return _types.GetOrAdd(name, i => new DiskConfiguration(i)); } /// <summary> /// Gets a <see cref="DiskConfiguration"/> representing automatic configuration. /// </summary> /// <remarks> /// The server is built with a single partition the size of the target flavor disk. The /// file system is automatically adjusted to fit the entire partition. This keeps things /// simple and automated. <see cref="Auto"/> is valid only for images and servers with a /// single partition that use the EXT3 file system. This is the default setting for /// applicable Rackspace base images. /// </remarks> public static DiskConfiguration Auto { get { return _auto; } } /// <summary> /// Gets a <see cref="DiskConfiguration"/> manual configuration. /// </summary> /// <remarks> /// The server is built using whatever partition scheme and file system is in the source /// image. If the target flavor disk is larger, the remaining disk space is left /// unpartitioned. This enables images to have non-EXT3 file systems, multiple partitions, /// and so on, and enables you to manage the disk configuration. /// </remarks> public static DiskConfiguration Manual { get { return _manual; } } /// <summary> /// Provides support for serializing and deserializing <see cref="DiskConfiguration"/> /// objects to JSON string values. /// </summary> /// <threadsafety static="true" instance="false"/> private sealed class Converter : ConverterBase { /// <inheritdoc/> protected override DiskConfiguration FromName(string name) { return DiskConfiguration.FromName(name); } } } }
44.533981
230
0.629387
[ "MIT" ]
crowdy/OpenStack-ConoHa
ConoHaNet.portable-net45/ConoHa/Services/Compute/DiskConfiguration.cs
4,589
C#
using System; namespace PreworkCodeChallenges { class Program { static void Main(string[] args) { bool displayMenu = true; while (displayMenu) { displayMenu = MainMenu(); } } private static bool MainMenu() { Console.Clear(); Console.WriteLine("1) Array Max Result"); Console.WriteLine("2) Leap Year Calculator"); Console.WriteLine("3) Perfect Sequence"); Console.WriteLine("4) Sum of Rows"); Console.WriteLine("5) Exit"); Console.Write("Choose an option: "); string result = Console.ReadLine(); if (result == "1") { CodeChallenge1(); return true; } else if (result == "2") { CodeChallenge2(); Console.ReadLine(); return true; } else if (result == "3") { Console.Clear(); int[] arr0 = { 2, 2 }; int[] arr1 = { 1, 3, 2 }; int[] arr2 = { 0, 0, 0, 0 }; int[] arr3 = { 4, 5, 6 }; int[] arr4 = { 0, 2, -2 }; CodeChallenge3(arr0); CodeChallenge3(arr1); CodeChallenge3(arr2); CodeChallenge3(arr3); CodeChallenge3(arr4); Console.ReadLine(); return true; } else if (result == "4") { int[,] myArray = new int[3, 5] { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 } }; CodeChallenge4(myArray); Console.ReadLine(); return true; } else { return false; } } private static void CodeChallenge1() { Console.Clear(); int[] numbers = new int[5]; int counter = 0; while (counter < 5) { counter = GetNumbers(counter, numbers); } ShowResult(numbers); } private static int GetNumbers(int counter, int[] numbers) { Console.Clear(); Console.Write("Please choose a number between 1 to 10. Same number can be chosen multiple times. ({0}/5): ", counter); string numberInput = Console.ReadLine(); if (int.TryParse(numberInput, out int number) && 0 < number && number < 10) { for (int i = 0; i < numbers.Length; i++) { if (numbers[i] == 0) { numbers[i] = number; break; } } counter++; if (counter < 5) { Console.Clear(); Console.WriteLine("You have entered '{0}'. Press 'Enter' to choose another number. ({1}/5).", number, counter); Console.ReadLine(); return counter; } else { Console.Clear(); Console.WriteLine("You have entered '{0}'. Press 'Enter' to continue. ({1}/5).", number, counter); Console.ReadLine(); return counter; } } else { Console.WriteLine("That was an invalid entry. Press 'Enter' to try again."); Console.ReadLine(); return counter; } } private static void ShowResult(int[] numbers) { Console.Clear(); Console.Write("You have entered [" + string.Join(", ", numbers) + "]. Please select a number from the list for a score: "); int selectedNumber = int.Parse(Console.ReadLine()); bool check = true; while (check) { int score = 1; bool one = false; foreach (var number in numbers) { if (selectedNumber == number) { score = score * number; one = true; } } if (one) { Console.WriteLine("Your score is {0}", score); Console.ReadLine(); check = false; } else { Console.Write("That was an invalid entry. Please select a number from [" + string.Join(", ", numbers) + "] for a score: "); selectedNumber = int.Parse(Console.ReadLine()); } } } private static void CodeChallenge2() { Console.Clear(); Console.Write("Please enter a year to evaluate if it is a leap in the format of YYYY: "); int year = int.Parse(Console.ReadLine()); string result = ((year % 4 == 0 && year % 100 != 0) || (year % 4 == 0 && year % 400 == 0)) ? $"Year {year} is a leap year!" : $"Year {year} is a NOT leap year."; Console.WriteLine(result); } private static void CodeChallenge3(int[] arr) { int product = 1; int sum = 0; foreach (var number in arr) { if (number >= 0) { product = product * number; sum += number; } } string result = (product == sum) ? "Yes" : "No"; Console.WriteLine("INPUT: [" + string.Join(", ", arr) + "]"); Console.WriteLine("OUTPUT: " + result); } private static void CodeChallenge4(int[,] arr) { Console.Clear(); int[] sums = new int[arr.GetLength(0)]; for (int i = 0; i < arr.GetLength(0); i++) { int sum = 0; for (int j = 0; j < arr.GetLength(1); j++) { sum += arr[i, j]; } sums[i] = sum; } Console.WriteLine("INPUT: int[,] myArray = new int[3, 5] { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 } }"); Console.WriteLine("OUTPUT: {" + string.Join(",", sums) + "}"); } } }
32.482759
173
0.402639
[ "MIT" ]
jeremymaya/Code-401-Prework-CodeChallenges
PreworkCodeChallenges/Program.cs
6,596
C#
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 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. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Grpc.Core { /// <summary> /// A stream of messages to be read. /// </summary> /// <typeparam name="T">The message type.</typeparam> public interface IAsyncStreamReader<T> : IAsyncEnumerator<T> { // TODO(jtattermusch): consider just using IAsyncEnumerator instead of this interface. } }
40.333333
94
0.75158
[ "BSD-3-Clause" ]
CharaD7/grpc
src/csharp/Grpc.Core/IAsyncStreamReader.cs
2,059
C#
using UnrealBuildTool; public class TearsInTheRain : ModuleRules { public TearsInTheRain(ReadOnlyTargetRules Target) : base(Target) { PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; PrivateDependencyModuleNames.Add("Core"); PrivateDependencyModuleNames.Add("Core"); } }
21.692308
65
0.794326
[ "Apache-2.0" ]
raimondsp20/TearsInTheRain
Intermediate/Source/TearsInTheRain.Build.cs
282
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 04.06.2021. using System; using System.Linq; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Funcs.EnumInt32.SET001.STD.HasFlag.Int16{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =TestEnum001; using T_DATA2 =System.Int16; using T_DATA1_U=TestEnum001; using T_DATA2_U=System.Int16; //////////////////////////////////////////////////////////////////////////////// //class TestSet_301__field__01__VV public static class TestSet_301__field__01__VV { private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2"; private const string c_NameOf__COL_DATA1 ="COL_INTEGER"; private const string c_NameOf__COL_DATA2 ="COL2_SMALLINT"; //----------------------------------------------------------------------- private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("TEST_ID")] public System.Int64? TEST_ID { get; set; } [Column(c_NameOf__COL_DATA1)] public T_DATA1 COL_DATA1 { get; set; } [Column(c_NameOf__COL_DATA2)] public T_DATA2 COL_DATA2 { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- private static xdb.OleDbConnection Helper__CreateCn() { return LocalCnHelper.CreateCn(); }//Helper__CreateCn //----------------------------------------------------------------------- private static bool HasFlag(this T_DATA1 obj,T_DATA2 value) { throw new InvalidOperationException("Incorrect usage of DUMMY HasFlag method!"); }//HasFlag //----------------------------------------------------------------------- [Test] public static void Test_0000___field__field() { using(var cn=Helper__CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA1_U c_value1=TestEnum001.Flag1|TestEnum001.Flag2; const T_DATA2_U c_value2=0; Assert.IsTrue (c_value1.HasFlag((TestEnum001)c_value2)); System.Int64 testID=Helper__InsertRow(db,c_value1,c_value2); var recs=db.testTable.Where(r => r.TEST_ID==testID && r.COL_DATA1.HasFlag(r.COL_DATA2)); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (c_value2, r.COL_DATA2); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(") AND (BIN_AND(").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).T(") = ").N("t",c_NameOf__COL_DATA2).T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_0000___field__field //----------------------------------------------------------------------- [Test] public static void Test_A001___field__field() { using(var cn=Helper__CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA1_U c_value1=TestEnum001.Flag1|TestEnum001.Flag2; const T_DATA2_U c_value2=(T_DATA2_U)(TestEnum001.Flag1|TestEnum001.Flag2); Assert.IsTrue (c_value1.HasFlag((TestEnum001)c_value2)); System.Int64 testID=Helper__InsertRow(db,c_value1,c_value2); var recs=db.testTable.Where(r => r.TEST_ID==testID && r.COL_DATA1.HasFlag(r.COL_DATA2)); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (c_value2, r.COL_DATA2); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(") AND (BIN_AND(").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).T(") = ").N("t",c_NameOf__COL_DATA2).T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_A001___field__field //----------------------------------------------------------------------- [Test] public static void Test_A002___field__const() { using(var cn=Helper__CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA1_U c_value1=TestEnum001.Flag1|TestEnum001.Flag2; const T_DATA2_U c_value2=(T_DATA2_U)(TestEnum001.Flag1|TestEnum001.Flag2); Assert.IsTrue (c_value1.HasFlag((TestEnum001)c_value2)); System.Int64 testID=Helper__InsertRow(db,c_value1,c_value2); var recs=db.testTable.Where(r => r.TEST_ID==testID && r.COL_DATA1.HasFlag(c_value2)); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (c_value2, r.COL_DATA2); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(") AND (BIN_AND(").N("t",c_NameOf__COL_DATA1).T(", 3) = 3)")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_A002___field__const //----------------------------------------------------------------------- [Test] public static void Test_A003___field__const2() { using(var cn=Helper__CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA1_U c_value1=TestEnum001.Flag1|TestEnum001.Flag2; const T_DATA2_U c_value2=(T_DATA2_U)(TestEnum001.Flag1|TestEnum001.Flag2); Assert.IsTrue (c_value1.HasFlag((TestEnum001)c_value2)); System.Int64 testID=Helper__InsertRow(db,c_value1,c_value2); var recs=db.testTable.Where(r => r.TEST_ID==testID && r.COL_DATA1.HasFlag((T_DATA2)(TestEnum001.Flag1|TestEnum001.Flag2))); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (c_value2, r.COL_DATA2); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(") AND (BIN_AND(").N("t",c_NameOf__COL_DATA1).T(", 3) = 3)")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_A003___field__const //----------------------------------------------------------------------- [Test] public static void Test_B001___field__field() { using(var cn=Helper__CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA1_U c_value1=TestEnum001.Flag1|TestEnum001.Flag2; const T_DATA2_U c_value2=(T_DATA2_U)(TestEnum001.Flag2|TestEnum001.Flag3); Assert.IsTrue (!c_value1.HasFlag((TestEnum001)c_value2)); System.Int64 testID=Helper__InsertRow(db,c_value1,c_value2); var recs=db.testTable.Where(r => r.TEST_ID==testID && r.COL_DATA1.HasFlag(r.COL_DATA2)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(") AND (BIN_AND(").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).T(") = ").N("t",c_NameOf__COL_DATA2).T(")")); }//using db tr.Rollback(); }//using tr }//using cn }//Test_B001___field__field //----------------------------------------------------------------------- [Test] public static void Test_B002___field__const() { using(var cn=Helper__CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA1_U c_value1=TestEnum001.Flag1|TestEnum001.Flag2; const T_DATA2_U c_value2=(T_DATA2_U)(TestEnum001.Flag2|TestEnum001.Flag3); Assert.IsTrue (!c_value1.HasFlag((TestEnum001)c_value2)); System.Int64 testID=Helper__InsertRow(db,c_value1,c_value2); var recs=db.testTable.Where(r => r.TEST_ID==testID && r.COL_DATA1.HasFlag(c_value2)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(") AND (BIN_AND(").N("t",c_NameOf__COL_DATA1).T(", 6) = 6)")); }//using db tr.Rollback(); }//using tr }//using cn }//Test_B002___field__const //----------------------------------------------------------------------- private static System.Int64 Helper__InsertRow(MyContext db, T_DATA1 valueOfColData1, T_DATA2 valueOfColData2) { var newRecord=new MyContext.TEST_RECORD(); newRecord.COL_DATA1=valueOfColData1; newRecord.COL_DATA2=valueOfColData2; db.testTable.Add(newRecord); db.SaveChanges(); db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL() .T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL() .T("RETURNING ").N("TEST_ID").EOL() .T("INTO ").P("p2").T(";")); Assert.IsTrue (newRecord.TEST_ID.HasValue); Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value); return newRecord.TEST_ID.Value; }//Helper__InsertRow };//class TestSet_301__field__01__VV //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Funcs.EnumInt32.SET001.STD.HasFlag.Int16
28.365688
195
0.571861
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Funcs/EnumInt32/SET001/STD/HasFlag/Int16/TestSet_301__field__01__VV.cs
12,566
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Utilities; namespace Microsoft.EntityFrameworkCore.Metadata { /// <summary> /// <para> /// Represents an entity in an <see cref="IConventionModel" />. /// </para> /// <para> /// This interface is used during model creation and allows the metadata to be modified. /// Once the model is built, <see cref="IEntityType" /> represents a read-only view of the same metadata. /// </para> /// </summary> public interface IConventionEntityType : IEntityType, IConventionTypeBase { /// <summary> /// Returns the configuration source for this entity type. /// </summary> /// <returns> The configuration source. </returns> ConfigurationSource GetConfigurationSource(); /// <summary> /// Gets the model this entity belongs to. /// </summary> new IConventionModel Model { get; } /// <summary> /// Gets the builder that can be used to configure this entity type. /// </summary> IConventionEntityTypeBuilder Builder { get; } /// <summary> /// Gets the base type of this entity type. Returns <c>null</c> if this is not a derived type in an inheritance hierarchy. /// </summary> new IConventionEntityType BaseType { get; } /// <summary> /// Gets the defining entity type. /// </summary> new IConventionEntityType DefiningEntityType { get; } /// <summary> /// Gets a value indicating whether the entity type has no keys. /// If <c>true</c> it will only be usable for queries. /// </summary> bool IsKeyless { get; } /// <summary> /// Sets the base type of this entity type. Returns <c>null</c> if this is not a derived type in an inheritance hierarchy. /// </summary> /// <param name="entityType"> The base entity type.</param> /// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param> void HasBaseType([CanBeNull] IConventionEntityType entityType, bool fromDataAnnotation = false); /// <summary> /// Sets a value indicating whether the entity type has no keys. /// When set to <c>true</c> it will only be usable for queries. /// <c>null</c> to reset to default. /// </summary> /// <param name="keyless"> A value indicating whether the entity type to has no keys. </param> /// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param> void HasNoKey(bool? keyless, bool fromDataAnnotation = false); /// <summary> /// Sets the primary key for this entity type. /// </summary> /// <param name="properties"> The properties that make up the primary key. </param> /// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param> /// <returns> The newly created key. </returns> IConventionKey SetPrimaryKey([CanBeNull] IReadOnlyList<IConventionProperty> properties, bool fromDataAnnotation = false); /// <summary> /// Gets primary key for this entity type. Returns <c>null</c> if no primary key is defined. /// </summary> /// <returns> The primary key, or <c>null</c> if none is defined. </returns> new IConventionKey FindPrimaryKey(); /// <summary> /// Returns the configuration source for the primary key. /// </summary> /// <returns> The configuration source for the primary key. </returns> ConfigurationSource? GetPrimaryKeyConfigurationSource(); /// <summary> /// Adds a new alternate key to this entity type. /// </summary> /// <param name="properties"> The properties that make up the alternate key. </param> /// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param> /// <returns> The newly created key. </returns> IConventionKey AddKey([NotNull] IReadOnlyList<IConventionProperty> properties, bool fromDataAnnotation = false); /// <summary> /// Gets the primary or alternate key that is defined on the given properties. /// Returns <c>null</c> if no key is defined for the given properties. /// </summary> /// <param name="properties"> The properties that make up the key. </param> /// <returns> The key, or <c>null</c> if none is defined. </returns> new IConventionKey FindKey([NotNull] IReadOnlyList<IProperty> properties); /// <summary> /// Gets the primary and alternate keys for this entity type. /// </summary> /// <returns> The primary and alternate keys. </returns> new IEnumerable<IConventionKey> GetKeys(); /// <summary> /// Removes a primary or alternate key from this entity type. /// </summary> /// <param name="key"> The key to be removed. </param> void RemoveKey([NotNull] IConventionKey key); /// <summary> /// Adds a new relationship to this entity type. /// </summary> /// <param name="properties"> The properties that the foreign key is defined on. </param> /// <param name="principalKey"> The primary or alternate key that is referenced. </param> /// <param name="principalEntityType"> /// The entity type that the relationship targets. This may be different from the type that <paramref name="principalKey" /> /// is defined on when the relationship targets a derived type in an inheritance hierarchy (since the key is defined on the /// base type of the hierarchy). /// </param> /// <param name="setComponentConfigurationSource"> /// Indicates whether the configuration source should be set for the properties, principal key and principal end. /// </param> /// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param> /// <returns> The newly created foreign key. </returns> IConventionForeignKey AddForeignKey( [NotNull] IReadOnlyList<IConventionProperty> properties, [NotNull] IConventionKey principalKey, [NotNull] IConventionEntityType principalEntityType, bool setComponentConfigurationSource = true, bool fromDataAnnotation = false); /// <summary> /// Gets the foreign key for the given properties that points to a given primary or alternate key. /// Returns <c>null</c> if no foreign key is found. /// </summary> /// <param name="properties"> The properties that the foreign key is defined on. </param> /// <param name="principalKey"> The primary or alternate key that is referenced. </param> /// <param name="principalEntityType"> /// The entity type that the relationship targets. This may be different from the type that <paramref name="principalKey" /> /// is defined on when the relationship targets a derived type in an inheritance hierarchy (since the key is defined on the /// base type of the hierarchy). /// </param> /// <returns> The foreign key, or <c>null</c> if none is defined. </returns> new IConventionForeignKey FindForeignKey( [NotNull] IReadOnlyList<IProperty> properties, [NotNull] IKey principalKey, [NotNull] IEntityType principalEntityType); /// <summary> /// Gets the foreign keys defined on this entity type. /// </summary> /// <returns> The foreign keys defined on this entity type. </returns> new IEnumerable<IConventionForeignKey> GetForeignKeys(); /// <summary> /// Removes a foreign key from this entity type. /// </summary> /// <param name="foreignKey"> The foreign key to be removed. </param> void RemoveForeignKey([NotNull] IConventionForeignKey foreignKey); /// <summary> /// Adds a new skip navigation properties to this entity type. /// </summary> /// <param name="name"> The name of the skip navigation property to add. </param> /// <param name="memberInfo"> /// <para> /// The corresponding CLR type member or <c>null</c> for a shadow property. /// </para> /// <para> /// An indexer with a <c>string</c> parameter and <c>object</c> return type can be used. /// </para> /// </param> /// <param name="targetEntityType"> The entity type that the skip navigation property will hold an instance(s) of.</param> /// <param name="foreignKey"> The foreign key to the association type. </param> /// <param name="collection"> Whether the navigation property is a collection property. </param> /// <param name="onPrincipal"> /// Whether the navigation property is defined on the principal side of the underlying foreign key. /// </param> /// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param> /// <returns> The newly created skip navigation property. </returns> IConventionSkipNavigation AddSkipNavigation( [NotNull] string name, [CanBeNull] MemberInfo memberInfo, [NotNull] IConventionEntityType targetEntityType, [CanBeNull] IConventionForeignKey foreignKey, bool collection, bool onPrincipal, bool fromDataAnnotation = false); /// <summary> /// Gets a skip navigation property on this entity type. Returns <c>null</c> if no navigation property is found. /// </summary> /// <param name="memberInfo"> The navigation property on the entity class. </param> /// <returns> The navigation property, or <c>null</c> if none is found. </returns> new IConventionSkipNavigation FindSkipNavigation([NotNull] MemberInfo memberInfo) => (IConventionSkipNavigation)((IEntityType)this).FindSkipNavigation(memberInfo); /// <summary> /// Gets a skip navigation property on this entity type. Returns <c>null</c> if no skip navigation property is found. /// </summary> /// <param name="name"> The name of the navigation property on the entity class. </param> /// <returns> The navigation property, or <c>null</c> if none is found. </returns> new IConventionSkipNavigation FindSkipNavigation([NotNull] string name); /// <summary> /// Gets a skip navigation property on this entity type. Does not return skip navigation properties defined on a base type. /// Returns <c>null</c> if no skip navigation property is found. /// </summary> /// <param name="name"> The name of the navigation property on the entity class. </param> /// <returns> The navigation property, or <c>null</c> if none is found. </returns> new IConventionSkipNavigation FindDeclaredSkipNavigation([NotNull] string name) => (IConventionSkipNavigation)((IEntityType)this).FindDeclaredSkipNavigation(name); /// <summary> /// <para> /// Gets all skip navigation properties declared on this entity type. /// </para> /// <para> /// This method does not return skip navigation properties declared declared on base types. /// It is useful when iterating over all entity types to avoid processing the same foreign key more than once. /// Use <see cref="GetSkipNavigations" /> to also return skip navigation properties declared on base types. /// </para> /// </summary> /// <returns> Declared foreign keys. </returns> new IEnumerable<IConventionSkipNavigation> GetDeclaredSkipNavigations() => ((IEntityType)this).GetDeclaredSkipNavigations().Cast<IConventionSkipNavigation>(); /// <summary> /// Gets all skip navigation properties on this entity type. /// </summary> /// <returns> All skip navigation properties on this entity type. </returns> new IEnumerable<IConventionSkipNavigation> GetSkipNavigations(); /// <summary> /// Removes a skip navigation property from this entity type. /// </summary> /// <param name="navigation"> The skip navigation to be removed. </param> void RemoveSkipNavigation([NotNull] IConventionSkipNavigation navigation); /// <summary> /// Adds an index to this entity type. /// </summary> /// <param name="properties"> The properties that are to be indexed. </param> /// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param> /// <returns> The newly created index. </returns> IConventionIndex AddIndex([NotNull] IReadOnlyList<IConventionProperty> properties, bool fromDataAnnotation = false); /// <summary> /// Gets the index defined on the given properties. Returns <c>null</c> if no index is defined. /// </summary> /// <param name="properties"> The properties to find the index on. </param> /// <returns> The index, or <c>null</c> if none is found. </returns> new IConventionIndex FindIndex([NotNull] IReadOnlyList<IProperty> properties); /// <summary> /// Gets the indexes defined on this entity type. /// </summary> /// <returns> The indexes defined on this entity type. </returns> new IEnumerable<IConventionIndex> GetIndexes(); /// <summary> /// Removes an index from this entity type. /// </summary> /// <param name="index"> The index to remove. </param> void RemoveIndex([NotNull] IConventionIndex index); /// <summary> /// Adds a property to this entity type. /// </summary> /// <param name="name"> The name of the property to add. </param> /// <param name="propertyType"> The type of value the property will hold. </param> /// <param name="memberInfo"> /// <para> /// The corresponding CLR type member or <c>null</c> for a shadow property. /// </para> /// <para> /// An indexer with a <c>string</c> parameter and <c>object</c> return type can be used. /// </para> /// </param> /// <param name="setTypeConfigurationSource"> Indicates whether the type configuration source should be set. </param> /// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param> /// <returns> The newly created property. </returns> IConventionProperty AddProperty( [NotNull] string name, [NotNull] Type propertyType, [CanBeNull] MemberInfo memberInfo, bool setTypeConfigurationSource = true, bool fromDataAnnotation = false); /// <summary> /// <para> /// Gets the property with a given name. Returns <c>null</c> if no property with the given name is defined. /// </para> /// <para> /// This API only finds scalar properties and does not find navigation properties. Use /// <see cref="ConventionEntityTypeExtensions.FindNavigation(IConventionEntityType, string)" /> to find /// a navigation property. /// </para> /// </summary> /// <param name="name"> The name of the property. </param> /// <returns> The property, or <c>null</c> if none is found. </returns> new IConventionProperty FindProperty([NotNull] string name); /// <summary> /// <para> /// Gets the properties defined on this entity type. /// </para> /// <para> /// This API only returns scalar properties and does not return navigation properties. Use /// <see cref="ConventionEntityTypeExtensions.GetNavigations(IConventionEntityType)" /> to get navigation /// properties. /// </para> /// </summary> /// <returns> The properties defined on this entity type. </returns> new IEnumerable<IConventionProperty> GetProperties(); /// <summary> /// Removes a property from this entity type. /// </summary> /// <param name="property"> The property to remove. </param> void RemoveProperty([NotNull] IConventionProperty property); /// <summary> /// Adds a <see cref="IConventionServiceProperty" /> to this entity type. /// </summary> /// <param name="memberInfo"> The <see cref="PropertyInfo" /> or <see cref="FieldInfo" /> of the property to add. </param> /// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param> /// <returns> The newly created property. </returns> IConventionServiceProperty AddServiceProperty([NotNull] MemberInfo memberInfo, bool fromDataAnnotation = false); /// <summary> /// <para> /// Gets the <see cref="IConventionServiceProperty" /> with a given name. /// Returns <c>null</c> if no property with the given name is defined. /// </para> /// <para> /// This API only finds service properties and does not find scalar or navigation properties. /// </para> /// </summary> /// <param name="name"> The name of the property. </param> /// <returns> The service property, or <c>null</c> if none is found. </returns> new IConventionServiceProperty FindServiceProperty([NotNull] string name); /// <summary> /// <para> /// Gets all the <see cref="IConventionServiceProperty" /> defined on this entity type. /// </para> /// <para> /// This API only returns service properties and does not return scalar or navigation properties. /// </para> /// </summary> /// <returns> The service properties defined on this entity type. </returns> new IEnumerable<IConventionServiceProperty> GetServiceProperties(); /// <summary> /// Removes an <see cref="IConventionServiceProperty" /> from this entity type. /// </summary> /// <param name="name"> The name of the property to remove. </param> /// <returns> The property that was removed. </returns> IConventionServiceProperty RemoveServiceProperty([NotNull] string name); } }
52.328877
136
0.614481
[ "Apache-2.0" ]
Tangtang1997/EntityFrameworkCore
src/EFCore/Metadata/IConventionEntityType.cs
19,571
C#
#if !WATCH using System; using XamCore.Foundation; using XamCore.CoreFoundation; using XamCore.ObjCRuntime; using XamCore.AudioToolbox; namespace XamCore.AVFoundation { public partial class AVPlayerItemVideoOutput { enum InitMode { PixelAttributes, OutputSettings } AVPlayerItemVideoOutput (NSDictionary data, AVPlayerItemVideoOutput.InitMode mode) : base (NSObjectFlag.Empty) { switch (mode) { case InitMode.PixelAttributes: InitializeHandle (_FromPixelBufferAttributes (data), "initWithPixelBufferAttributes:"); break; case InitMode.OutputSettings: InitializeHandle (_FromOutputSettings (data), "initWithOutputSettings:"); break; default: throw new ArgumentException (nameof (mode)); } } [DesignatedInitializer] [Advice ("Please use the constructor that uses one of the available StrongDictionaries. This constructor expects PixelBuffer attributes.")] protected AVPlayerItemVideoOutput (NSDictionary pixelBufferAttributes) : this (pixelBufferAttributes, InitMode.PixelAttributes) {} } } #endif
27.230769
141
0.774953
[ "BSD-3-Clause" ]
Acidburn0zzz/xamarin-macios
src/AVFoundation/AVPlayerItemVideoOutput.cs
1,062
C#
using System.IO; using System.Threading; using System.Threading.Tasks; using tusdotnet.Helpers; namespace tusdotnet.Models { internal class ClientDisconnectGuardedReadOnlyStream : ReadOnlyStream { internal CancellationToken CancellationToken { get; } private readonly CancellationTokenSource _cancellationTokenSource; /// <summary> /// Default ctor /// </summary> /// <param name="backingStream">The stream to guard against client disconnects</param> /// <param name="cancellationTokenSource">Token source to cancel when the client disconnects. Preferably use CancellationTokenSource.CreateLinkedTokenSource(RequestCancellationToken).</param> internal ClientDisconnectGuardedReadOnlyStream(Stream backingStream, CancellationTokenSource cancellationTokenSource) : base(backingStream) { CancellationToken = cancellationTokenSource.Token; _cancellationTokenSource = cancellationTokenSource; } public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { var result = await ClientDisconnectGuard.ReadStreamAsync(BackingStream, buffer, offset, count, cancellationToken); if (result.ClientDisconnected) { _cancellationTokenSource.Cancel(); return 0; } return result.BytesRead; } } }
37.15
199
0.689771
[ "MIT" ]
Badabum/tusdotnet
Source/tusdotnet/Models/ClientDisconnectGuardedReadOnlyStream.cs
1,488
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.AwsNative.MemoryDB.Outputs { [OutputType] public sealed class AuthenticationModeProperties { /// <summary> /// Passwords used for this user account. You can create up to two passwords for each user. /// </summary> public readonly ImmutableArray<string> Passwords; /// <summary> /// Type of authentication strategy for this user. /// </summary> public readonly Pulumi.AwsNative.MemoryDB.UserAuthenticationModePropertiesType? Type; [OutputConstructor] private AuthenticationModeProperties( ImmutableArray<string> passwords, Pulumi.AwsNative.MemoryDB.UserAuthenticationModePropertiesType? type) { Passwords = passwords; Type = type; } } }
30.972222
99
0.669058
[ "Apache-2.0" ]
AaronFriel/pulumi-aws-native
sdk/dotnet/MemoryDB/Outputs/AuthenticationModeProperties.cs
1,115
C#
using MyFileDB.Common.Services; namespace MyFileDB.Core.Messages { public class UpdateOneFileIdentityMessage : AFileIdentityMessage { public UpdateOneFileIdentityMessage(FileContent fileContent) { FileContent = fileContent; } public FileContent FileContent { get; private set; } } }
23.666667
69
0.659155
[ "MIT" ]
contactsamie/MyFileDB
MyFileDB.Core/Messages/UpdateOneFileIdentityMessage.cs
355
C#
namespace Niue.Alipay.Response { /// <summary> /// AlipayOpenPublicLabelUserCreateResponse. /// </summary> public class AlipayOpenPublicLabelUserCreateResponse : AopResponse { } }
20.4
70
0.691176
[ "MIT" ]
P79N6A/abp-ant-design-pro-vue
Niue.Alipay/Response/AlipayOpenPublicLabelUserCreateResponse.cs
204
C#
using System; using NetTopologySuite.Mathematics; using NUnit.Framework; namespace NetTopologySuite.Tests.NUnit.Mathematics { /// <summary> /// Tests basic arithmetic operations for <see cref="DD"/>s. /// </summary> /// <author>Martin Davis</author> public class DDBasicTest { [Test] public void TestNaN() { Assert.IsTrue(DD.IsNaN(DD.ValueOf(1) / DD.ValueOf(0))); Assert.IsTrue(DD.IsNaN(DD.ValueOf(1) * DD.NaN)); } [Test] public void TestAddMult2() { CheckAddMult2(new DD(3)); CheckAddMult2(DD.PI); } [Test] public void TestMultiplyDivide() { CheckMultiplyDivide(DD.PI, DD.E, 1e-30); CheckMultiplyDivide(DD.TwoPi, DD.E, 1e-30); CheckMultiplyDivide(DD.PiHalf, DD.E, 1e-30); CheckMultiplyDivide(new DD(39.4), new DD(10), 1e-30); } [Test] public void TestDivideMultiply() { CheckDivideMultiply(DD.PI, DD.E, 1e-30); CheckDivideMultiply(new DD(39.4), new DD(10), 1e-30); } [Test] public void TestSqrt() { // the appropriate error bound is determined empirically CheckSqrt(DD.PI, 1e-30); CheckSqrt(DD.E, 1e-30); CheckSqrt(new DD(999.0), 1e-28); } private void CheckSqrt(DD x, double errBound) { var sqrt = x.Sqrt(); var x2 = sqrt * sqrt; CheckErrorBound("Sqrt", x, x2, errBound); } [Test] public void TestTrunc() { CheckTrunc(DD.ValueOf(1e16) - DD.ValueOf(1), DD.ValueOf(1e16) - DD.ValueOf(1)); // the appropriate error bound is determined empirically CheckTrunc(DD.PI, DD.ValueOf(3)); CheckTrunc(DD.ValueOf(999.999), DD.ValueOf(999)); CheckTrunc(-DD.E, DD.ValueOf(-2)); CheckTrunc(DD.ValueOf(-999.999), DD.ValueOf(-999)); } private static void CheckTrunc(DD x, DD expected) { var trunc = x.Truncate(); bool isEqual = trunc.Equals(expected); Assert.True(isEqual); isEqual = trunc == expected; Assert.True(isEqual); } [Test] public void TestPow() { CheckPow(0, 3, 16*DD.Epsilon); CheckPow(14, 3, 16*DD.Epsilon); CheckPow(3, -5, 16*DD.Epsilon); CheckPow(-3, 5, 16*DD.Epsilon); CheckPow(-3, -5, 16*DD.Epsilon); CheckPow(0.12345, -5, 1e5*DD.Epsilon); } [Test] public void TestReciprocal() { // error bounds are chosen to be "close enough" (i.e. heuristically) // for some reason many reciprocals are exact CheckReciprocal(3.0, 0); CheckReciprocal(99.0, 1e-29); CheckReciprocal(999.0, 0); CheckReciprocal(314159269.0, 0); } /** * A basic test for determinant correctness */ [Test] public void TestDeterminant() { CheckDeterminant(3, 8, 4, 6, -14, 0); CheckDeterminantDD(3, 8, 4, 6, -14, 0); } [Test] public void TestDeterminantRobust() { CheckDeterminant(1.0e9, 1.0e9 - 1, 1.0e9 - 1, 1.0e9 - 2, -1, 0); CheckDeterminantDD(1.0e9, 1.0e9 - 1, 1.0e9 - 1, 1.0e9 - 2, -1, 0); } private void CheckDeterminant(double x1, double y1, double x2, double y2, double expected, double errBound) { var det = DD.Determinant(x1, y1, x2, y2); CheckErrorBound("Determinant", det, DD.ValueOf(expected), errBound); } private void CheckDeterminantDD(double x1, double y1, double x2, double y2, double expected, double errBound) { var det = DD.Determinant( DD.ValueOf(x1), DD.ValueOf(y1), DD.ValueOf(x2), DD.ValueOf(y2)); CheckErrorBound("Determinant", det, DD.ValueOf(expected), errBound); } [Test] public void TestBinom() { CheckBinomialSquare(100.0, 1.0); CheckBinomialSquare(1000.0, 1.0); CheckBinomialSquare(10000.0, 1.0); CheckBinomialSquare(100000.0, 1.0); CheckBinomialSquare(1000000.0, 1.0); CheckBinomialSquare(1e8, 1.0); CheckBinomialSquare(1e10, 1.0); CheckBinomialSquare(1e14, 1.0); // Following call will fail, because it requires 32 digits of precision // checkBinomialSquare(1e16, 1.0); CheckBinomialSquare(1e14, 291.0); CheckBinomialSquare(5e14, 291.0); CheckBinomialSquare(5e14, 345291.0); } private static void CheckAddMult2(DD dd) { var sum = dd + dd; var prod = dd * new DD(2.0); CheckErrorBound("AddMult2", sum, prod, 0.0); } private static void CheckMultiplyDivide(DD a, DD b, double errBound) { var a2 = a * b / b; CheckErrorBound("MultiplyDivide", a, a2, errBound); } private static void CheckDivideMultiply(DD a, DD b, double errBound) { var a2 = a / b * b; CheckErrorBound("DivideMultiply", a, a2, errBound); } private static DD Delta(DD x, DD y) { return (x - y).Abs(); } private static void CheckErrorBound(string tag, DD x, DD y, double errBound) { var err = (x - y).Abs(); //Console.WriteLine(tag + " err=" + err); bool isWithinEps = err.ToDoubleValue() <= errBound; if (!isWithinEps) { Assert.Warn($"checkErrorBound: {tag} val1 = {x} val2 = {y} err={err}"); Assert.Fail(); } } /// <summary> /// Computes (a+b)^2 in two different ways and compares the result. /// For correct results, a and b should be integers. /// </summary> private static void CheckBinomialSquare(double a, double b) { // binomial square var add = new DD(a); var bdd = new DD(b); var aPlusb = add + bdd; var abSq = aPlusb * aPlusb; // System.out.println("(a+b)^2 = " + abSq); // expansion var a2DD = add * add; var b2DD = bdd * bdd; var ab = add * bdd; var sum = b2DD + ab + ab; // System.out.println("2ab+b^2 = " + sum); var diff = abSq - a2DD; // System.out.println("(a+b)^2 - a^2 = " + diff); var delta = diff - sum; // System.Console.WriteLine("\nA = " + a + ", B = " + b); // System.Console.WriteLine("[DD] 2ab+b^2 = " + sum // + " (a+b)^2 - a^2 = " + diff // + " delta = " + delta); PrintBinomialSquareDouble(a, b); bool isSame = diff.Equals(sum); Assert.IsTrue(isSame); bool isDeltaZero = delta.IsZero; Assert.IsTrue(isDeltaZero); } private static void PrintBinomialSquareDouble(double a, double b) { double sum = 2*a*b + b*b; double diff = (a + b)*(a + b) - a*a; // Console.WriteLine("[double] 2ab+b^2= " + sum // + " (a+b)^2-a^2= " + diff // + " delta= " + (sum - diff)); } [Test] public void TestBinomial2() { CheckBinomial2(100.0, 1.0); CheckBinomial2(1000.0, 1.0); CheckBinomial2(10000.0, 1.0); CheckBinomial2(100000.0, 1.0); CheckBinomial2(1000000.0, 1.0); CheckBinomial2(1e8, 1.0); CheckBinomial2(1e10, 1.0); CheckBinomial2(1e14, 1.0); CheckBinomial2(1e14, 291.0); CheckBinomial2(5e14, 291.0); CheckBinomial2(5e14, 345291.0); } private static void CheckBinomial2(double a, double b) { // binomial product var add = new DD(a); var bdd = new DD(b); var aPlusb = add + bdd; var aSubb = add - bdd; var abProd = aPlusb * aSubb; // System.out.println("(a+b)^2 = " + abSq); // expansion var a2DD = add * add; var b2DD = bdd * bdd; // System.out.println("2ab+b^2 = " + sum); // this should equal b^2 var diff = -(abProd - a2DD); // System.out.println("(a+b)^2 - a^2 = " + diff); var delta = diff - b2DD; // System.Console.WriteLine("\nA = " + a + ", B = " + b); // System.Console.WriteLine("[DD] (a+b)(a-b) = " + abProd // + " -((a^2 - b^2) - a^2) = " + diff // + " delta = " + delta); // printBinomialSquareDouble(a,b); bool isSame = diff.Equals(b2DD); Assert.IsTrue(isSame); bool isDeltaZero = delta.IsZero; Assert.IsTrue(isDeltaZero); } private static void CheckReciprocal(double x, double errBound) { var xdd = new DD(x); var rr = xdd.Reciprocal().Reciprocal(); double err = (xdd - rr).ToDoubleValue(); // System.Console.WriteLine("DD Recip = " + xdd // + " DD delta= " + err // + " double recip delta= " + (x - 1.0/(1.0/x))); Assert.IsTrue(err <= errBound); } private static void CheckPow(double x, int exp, double errBound) { var xdd = new DD(x); var pow = xdd.Pow(exp); // System.Console.WriteLine("Pow(" + x + ", " + exp + ") = " + pow); var pow2 = SlowPow(xdd, exp); double err = (pow - pow2).ToDoubleValue(); bool isOK = err < errBound; if (!isOK) Console.WriteLine("Test slowPow value " + pow2); Assert.IsTrue(err <= errBound); } private static DD SlowPow(DD x, int exp) { if (exp == 0) return DD.ValueOf(1.0); int n = Math.Abs(exp); // MD - could use binary exponentiation for better precision & speed var pow = new DD(x); for (int i = 1; i < n; i++) { pow *= x; } if (exp < 0) { return pow.Reciprocal(); } return pow; } } }
32.138235
117
0.478631
[ "EPL-1.0" ]
gchling/NetTopologySuite
test/NetTopologySuite.Tests.NUnit/Mathematics/DDBasicTest.cs
10,929
C#
using FluentAssertions; using System; using Xunit; namespace Optsol.Components.Test.Unit.Shared.Extensions { public class UintExtensionsSpec { [Trait("Extensions", "UintExtensions")] [Fact(DisplayName = "Deve converter um uint em int")] public void Deve_Converter_Uint_Em_Int() { //Given uint @uint = 10; //When var uintToInt = @uint.ToInt(); //Then uintToInt.Should().BePositive(); } } }
21.541667
61
0.566731
[ "MIT" ]
carlosmachel/components-backend-core
test/Optsol.Components.Test.Unit/Shared/Extensions/UintExtensionsSpec.cs
519
C#
namespace EasyCaching.UnitTests { using Dapper; using EasyCaching.Core; using EasyCaching.SQLite; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.IO; using System.Linq; using System.Threading.Tasks; using Xunit; public class SQLiteCachingTest : BaseCachingProviderTest { private readonly ISQLiteDatabaseProvider _dbProvider; public SQLiteCachingTest() { IServiceCollection services = new ServiceCollection(); services.AddEasyCaching(x => x.UseSQLite(options => { options.DBConfig = new SQLiteDBOptions { FileName = "s1.db", CacheMode = Microsoft.Data.Sqlite.SqliteCacheMode.Default, OpenMode = Microsoft.Data.Sqlite.SqliteOpenMode.Memory, }; }) ); IServiceProvider serviceProvider = services.BuildServiceProvider(); var _dbProviders = serviceProvider.GetServices<ISQLiteDatabaseProvider>(); _dbProvider = _dbProviders.FirstOrDefault(); var conn = _dbProvider.GetConnection(); if (conn.State == System.Data.ConnectionState.Closed) { conn.Open(); } conn.Execute(ConstSQL.CREATESQL); _provider = new DefaultSQLiteCachingProvider(EasyCachingConstValue.DefaultSQLiteName, _dbProviders, new SQLiteOptions()); _defaultTs = TimeSpan.FromSeconds(30); } [Fact] protected override Task GetAsync_Parallel_Should_Succeed() { return Task.FromResult(1); } [Fact] protected override void Get_Parallel_Should_Succeed() { } } public class SQLiteCachingProviderWithFactoryTest : BaseCachingProviderWithFactoryTest { public SQLiteCachingProviderWithFactoryTest() { IServiceCollection services = new ServiceCollection(); services.AddEasyCaching(x => { x.UseSQLite(options => { options.DBConfig = new SQLiteDBOptions { FileName = "f0.db", CacheMode = Microsoft.Data.Sqlite.SqliteCacheMode.Default, OpenMode = Microsoft.Data.Sqlite.SqliteOpenMode.Memory, }; }).UseSQLite(options => { options.DBConfig = new SQLiteDBOptions { FileName = "f1.db", CacheMode = Microsoft.Data.Sqlite.SqliteCacheMode.Default, OpenMode = Microsoft.Data.Sqlite.SqliteOpenMode.Memory, }; }, SECOND_PROVIDER_NAME); }); IServiceProvider serviceProvider = services.BuildServiceProvider(); var factory = serviceProvider.GetService<IEasyCachingProviderFactory>(); _provider = factory.GetCachingProvider(EasyCachingConstValue.DefaultSQLiteName); _secondProvider = factory.GetCachingProvider(SECOND_PROVIDER_NAME); var _dbProviders = serviceProvider.GetServices<ISQLiteDatabaseProvider>(); foreach (var _dbProvider in _dbProviders) { var conn = _dbProvider.GetConnection(); if (conn.State == System.Data.ConnectionState.Closed) { conn.Open(); } conn.Execute(ConstSQL.CREATESQL); } _defaultTs = TimeSpan.FromSeconds(30); } } public class SQLiteCachingProviderUseEasyCachingTest : BaseUsingEasyCachingTest { private readonly IEasyCachingProvider _secondProvider; private const string SECOND_PROVIDER_NAME = "second"; public SQLiteCachingProviderUseEasyCachingTest() { IServiceCollection services = new ServiceCollection(); services.AddEasyCaching(option => { option.UseSQLite(config => { config.DBConfig = new SQLiteDBOptions { FileName = "use_0.db", }; }, EasyCachingConstValue.DefaultSQLiteName); option.UseSQLite(config => { config.DBConfig = new SQLiteDBOptions { FileName = "use_1.db", }; }, SECOND_PROVIDER_NAME); }); IServiceProvider serviceProvider = services.BuildServiceProvider(); var factory = serviceProvider.GetService<IEasyCachingProviderFactory>(); _provider = factory.GetCachingProvider(EasyCachingConstValue.DefaultSQLiteName); _secondProvider = factory.GetCachingProvider(SECOND_PROVIDER_NAME); var _dbProviders = serviceProvider.GetServices<ISQLiteDatabaseProvider>(); foreach (var _dbProvider in _dbProviders) { var conn = _dbProvider.GetConnection(); if (conn.State == System.Data.ConnectionState.Closed) { conn.Open(); } conn.Execute(ConstSQL.CREATESQL); } _defaultTs = TimeSpan.FromSeconds(30); } [Fact] public void Sec_Set_Value_And_Get_Cached_Value_Should_Succeed() { var cacheKey = Guid.NewGuid().ToString(); var cacheValue = "value"; _secondProvider.Set(cacheKey, cacheValue, _defaultTs); var val = _secondProvider.Get<string>(cacheKey); Assert.True(val.HasValue); Assert.Equal(cacheValue, val.Value); } [Fact] public async Task Sec_Set_Value_And_Get_Cached_Value_Async_Should_Succeed() { var cacheKey = Guid.NewGuid().ToString(); var cacheValue = "value"; await _secondProvider.SetAsync(cacheKey, cacheValue, _defaultTs); var val = await _secondProvider.GetAsync<string>(cacheKey); Assert.True(val.HasValue); Assert.Equal(cacheValue, val.Value); } } public class SQLiteCachingProviderUseEasyCachingWithConfigTest : BaseUsingEasyCachingTest { public SQLiteCachingProviderUseEasyCachingWithConfigTest() { IServiceCollection services = new ServiceCollection(); var appsettings = " { \"easycaching\": { \"sqlite\": { \"MaxRdSecond\": 600, \"dbconfig\": { \"FileName\": \"my.db\" } } } }"; var path = TestHelpers.CreateTempFile(appsettings); var directory = Path.GetDirectoryName(path); var fileName = Path.GetFileName(path); var configurationBuilder = new ConfigurationBuilder(); configurationBuilder.SetBasePath(directory); configurationBuilder.AddJsonFile(fileName); var config = configurationBuilder.Build(); services.AddEasyCaching(option => { option.UseSQLite(config, "mName"); }); IServiceProvider serviceProvider = services.BuildServiceProvider(); _provider = serviceProvider.GetService<IEasyCachingProvider>(); var _dbProviders = serviceProvider.GetServices<ISQLiteDatabaseProvider>(); foreach (var _dbProvider in _dbProviders) { var conn = _dbProvider.GetConnection(); if (conn.State == System.Data.ConnectionState.Closed) { conn.Open(); } conn.Execute(ConstSQL.CREATESQL); } _defaultTs = TimeSpan.FromSeconds(30); } [Fact] public void Provider_Information_Should_Be_Correct() { Assert.Equal(600, _provider.MaxRdSecond); //Assert.Equal(99, _provider.Order); Assert.Equal("mName", _provider.Name); } } }
36.281938
138
0.571151
[ "MIT" ]
KostaVlev/EasyCaching
test/EasyCaching.UnitTests/CachingTests/SQLiteCachingTest.cs
8,238
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("GapExample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("GapExample")] [assembly: AssemblyCopyright("Copyright © Microsoft 2011")] [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("9e27b972-0825-4386-ba17-63c695262c3d")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.083333
84
0.751276
[ "Unlicense", "MIT" ]
appsfactory/FoodAtHub
Other/PhoneGap/Windows Phone/example/Properties/AssemblyInfo.cs
1,374
C#
namespace Pets.Platform.Permissions.Core.Domain.SLAAggregate { public interface ISLARepository : IRepository<SLA> { SLA Add(SLA sla); void Update(SLA sla); Task<SLA> GetAsync(string slaId); Task<IEnumerable<SLA>> GetAsync(IEnumerable<string> slaIds); } }
25.083333
68
0.664452
[ "MIT" ]
11pets/Pets.Platform.Permissions
Pets.Platform.Permissions.Core/Domain/SLAAggregate/ISLARepository.cs
303
C#
using System.Threading.Tasks; using Samples.ViewModel; using Xamarin.Forms; namespace Samples.View { public class BasePage : ContentPage { public BasePage() { NavigationPage.SetBackButtonTitle(this, "Back"); } protected override void OnAppearing() { base.OnAppearing(); SetupBinding(BindingContext); } protected override void OnDisappearing() { TearDownBinding(BindingContext); base.OnDisappearing(); } protected void SetupBinding(object bindingContext) { if (bindingContext is BaseViewModel vm) { vm.DoDisplayAlert += OnDisplayAlert; vm.OnAppearing(); } } protected void TearDownBinding(object bindingContext) { if (bindingContext is BaseViewModel vm) { vm.OnDisappearing(); vm.DoDisplayAlert -= OnDisplayAlert; } } Task OnDisplayAlert(string message) { return DisplayAlert(Title, message, "OK"); } } }
22.634615
61
0.537808
[ "MIT" ]
AndreiMisiukevich/Essentials
Samples/Samples/View/BasePage.cs
1,179
C#
// -------------------------------------------------------------------------------------------------- // <auto-generated> // This code was generated by a tool. // Script: ./scripts/cldr-relative-time.csx // // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated. // </auto-generated> // -------------------------------------------------------------------------------------------------- using Alrev.Intl.Abstractions; using Alrev.Intl.Abstractions.PluralRules; using Alrev.Intl.Abstractions.RelativeTime; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; namespace Alrev.Intl.RelativeTime.Resources { /// <summary> /// Relative Time Units resource for 'Spanish (Latin America)' [es-419] /// </summary> public class Es419RelativeTimeResource : ReadOnlyDictionary<RelativeTimeUnitValues, IReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>>, IRelativeTimeUnitsResource { /// <summary> /// The <see cref="IIntlResource"/> culture /// </summary> public CultureInfo Culture { get; } /// <summary> /// The class constructor /// </summary> public Es419RelativeTimeResource() : base(new Dictionary<RelativeTimeUnitValues, IReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>>() { { RelativeTimeUnitValues.Year, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el año pasado" }, { 0, "este año" }, { 1, "el próximo año" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} año" }, { PluralRulesValues.Other, "hace {0} años" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} año" }, { PluralRulesValues.Other, "dentro de {0} años" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el año pasado" }, { 0, "este año" }, { 1, "el próximo año" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} a" }, { PluralRulesValues.Other, "hace {0} a" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} a" }, { PluralRulesValues.Other, "dentro de {0} a" } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el año pasado" }, { 0, "este año" }, { 1, "el próximo año" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} a" }, { PluralRulesValues.Other, "hace {0} a" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} a" }, { PluralRulesValues.Other, "dentro de {0} a" } }) } }) }, { RelativeTimeUnitValues.Quarter, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el trimestre pasado" }, { 0, "este trimestre" }, { 1, "el próximo trimestre" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} trimestre" }, { PluralRulesValues.Other, "hace {0} trimestres" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} trimestre" }, { PluralRulesValues.Other, "dentro de {0} trimestres" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el trimestre pasado" }, { 0, "este trimestre" }, { 1, "el próximo trimestre" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} trim." }, { PluralRulesValues.Other, "hace {0} trim." } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} trim." }, { PluralRulesValues.Other, "dentro de {0} trim." } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el trimestre pasado" }, { 0, "este trimestre" }, { 1, "el próximo trimestre" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} trim." }, { PluralRulesValues.Other, "hace {0} trim." } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} trim." }, { PluralRulesValues.Other, "dentro de {0} trim." } }) } }) }, { RelativeTimeUnitValues.Month, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el mes pasado" }, { 0, "este mes" }, { 1, "el próximo mes" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} mes" }, { PluralRulesValues.Other, "hace {0} meses" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} mes" }, { PluralRulesValues.Other, "dentro de {0} meses" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el mes pasado" }, { 0, "este mes" }, { 1, "el próximo mes" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} m" }, { PluralRulesValues.Other, "hace {0} m" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} m" }, { PluralRulesValues.Other, "dentro de {0} m" } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el mes pasado" }, { 0, "este mes" }, { 1, "el próximo mes" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} m" }, { PluralRulesValues.Other, "hace {0} m" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} m" }, { PluralRulesValues.Other, "dentro de {0} m" } }) } }) }, { RelativeTimeUnitValues.Week, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "la semana pasada" }, { 0, "esta semana" }, { 1, "la próxima semana" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} semana" }, { PluralRulesValues.Other, "hace {0} semanas" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} semana" }, { PluralRulesValues.Other, "dentro de {0} semanas" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "sem. pas." }, { 0, "esta sem." }, { 1, "próx. sem." } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} sem." }, { PluralRulesValues.Other, "hace {0} sem." } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} sem." }, { PluralRulesValues.Other, "dentro de {0} sem." } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "sem. pas." }, { 0, "esta sem." }, { 1, "próx. sem." } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} sem." }, { PluralRulesValues.Other, "hace {0} sem." } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} sem." }, { PluralRulesValues.Other, "dentro de {0} sem." } }) } }) }, { RelativeTimeUnitValues.Day, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -2, "anteayer" }, { -1, "ayer" }, { 0, "hoy" }, { 1, "mañana" }, { 2, "pasado mañana" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} día" }, { PluralRulesValues.Other, "hace {0} días" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} día" }, { PluralRulesValues.Other, "dentro de {0} días" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -2, "anteayer" }, { -1, "ayer" }, { 0, "hoy" }, { 1, "mañana" }, { 2, "pasado mañana" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} día" }, { PluralRulesValues.Other, "hace {0} días" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} día" }, { PluralRulesValues.Other, "dentro de {0} días" } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -2, "anteayer" }, { -1, "ayer" }, { 0, "hoy" }, { 1, "mañana" }, { 2, "pasado mañana" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} día" }, { PluralRulesValues.Other, "hace {0} días" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} día" }, { PluralRulesValues.Other, "dentro de {0} días" } }) } }) }, { RelativeTimeUnitValues.Sunday, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el domingo pasado" }, { 0, "este domingo" }, { 1, "el próximo domingo" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} domingo" }, { PluralRulesValues.Other, "hace {0} domingos" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "en {0} domingo" }, { PluralRulesValues.Other, "en {0} domingos" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el dom. pasado" }, { 0, "este dom." }, { 1, "el próximo dom." } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} dom." }, { PluralRulesValues.Other, "hace {0} dom." } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} dom." }, { PluralRulesValues.Other, "dentro de {0} dom." } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el DO pasado" }, { 0, "este DO" }, { 1, "el próximo DO" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} DO" }, { PluralRulesValues.Other, "hace {0} DO" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} DO" }, { PluralRulesValues.Other, "dentro de {0} DO" } }) } }) }, { RelativeTimeUnitValues.Monday, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el lunes pasado" }, { 0, "este lunes" }, { 1, "el próximo lunes" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} lunes" }, { PluralRulesValues.Other, "hace {0} lunes" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} lunes" }, { PluralRulesValues.Other, "dentro de {0} lunes" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el lun. pasado" }, { 0, "este lun." }, { 1, "el próximo lun." } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} lun." }, { PluralRulesValues.Other, "hace {0} lun." } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} lun." }, { PluralRulesValues.Other, "dentro de {0} lun." } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el LU pasado" }, { 0, "este LU" }, { 1, "el próximo LU" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} LU" }, { PluralRulesValues.Other, "hace {0} LU" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} LU" }, { PluralRulesValues.Other, "dentro de {0} LU" } }) } }) }, { RelativeTimeUnitValues.Tuesday, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el martes pasado" }, { 0, "este martes" }, { 1, "el próximo martes" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} martes" }, { PluralRulesValues.Other, "hace {0} martes" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} martes" }, { PluralRulesValues.Other, "en {0} martes" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el mar. pasado" }, { 0, "este mar." }, { 1, "el próximo mar." } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} mar." }, { PluralRulesValues.Other, "hace {0} mar." } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} mar." }, { PluralRulesValues.Other, "dentro de {0} mar." } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el MA pasado" }, { 0, "este MA" }, { 1, "el próximo MA" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} MA" }, { PluralRulesValues.Other, "hace {0} MA" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} MA" }, { PluralRulesValues.Other, "dentro de {0} MA" } }) } }) }, { RelativeTimeUnitValues.Wednesday, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el miércoles pasado" }, { 0, "este miércoles" }, { 1, "el próximo miércoles" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} miércoles" }, { PluralRulesValues.Other, "hace {0} miércoles" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} miércoles" }, { PluralRulesValues.Other, "dentro de {0} miércoles" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el mié. pasado" }, { 0, "este mié." }, { 1, "el próximo mié." } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} mié." }, { PluralRulesValues.Other, "hace {0} mié." } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} mié." }, { PluralRulesValues.Other, "dentro de {0} mié." } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el MI pasado" }, { 0, "este MI" }, { 1, "el próximo MI" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} MI" }, { PluralRulesValues.Other, "hace {0} MI" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} MI" }, { PluralRulesValues.Other, "dentro de {0} MI" } }) } }) }, { RelativeTimeUnitValues.Thursday, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el jueves pasado" }, { 0, "este jueves" }, { 1, "el próximo jueves" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} jueves" }, { PluralRulesValues.Other, "hace {0} jueves" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} jueves" }, { PluralRulesValues.Other, "dentro de {0} jueves" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el jue. pasado" }, { 0, "este jue." }, { 1, "el próximo jue." } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} jue." }, { PluralRulesValues.Other, "hace {0} jue." } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} jue." }, { PluralRulesValues.Other, "dentro de {0} jue." } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el JU pasado" }, { 0, "este JU" }, { 1, "el próximo JU" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} JU" }, { PluralRulesValues.Other, "hace {0} JU" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} JU" }, { PluralRulesValues.Other, "dentro de {0} JU" } }) } }) }, { RelativeTimeUnitValues.Friday, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el viernes pasado" }, { 0, "este viernes" }, { 1, "el próximo viernes" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} viernes" }, { PluralRulesValues.Other, "hace {0} viernes" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} viernes" }, { PluralRulesValues.Other, "dentro de {0} viernes" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el vie. pasado" }, { 0, "este vie." }, { 1, "el próximo vie." } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} viernes" }, { PluralRulesValues.Other, "hace {0} viernes" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} vie." }, { PluralRulesValues.Other, "dentro de {0} vie." } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el VI pasado" }, { 0, "este VI" }, { 1, "el próximo VI" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} viernes" }, { PluralRulesValues.Other, "hace {0} viernes" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} VI" }, { PluralRulesValues.Other, "dentro de {0} VI" } }) } }) }, { RelativeTimeUnitValues.Saturday, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el sábado pasado" }, { 0, "este sábado" }, { 1, "el próximo sábado" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} sábado" }, { PluralRulesValues.Other, "hace {0} sábados" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} sábado" }, { PluralRulesValues.Other, "dentro de {0} sábados" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el sáb. pasado" }, { 0, "este sáb." }, { 1, "el próximo sáb." } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} sáb." }, { PluralRulesValues.Other, "hace {0} sáb." } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} sáb." }, { PluralRulesValues.Other, "dentro de {0} sáb." } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "el SA pasado" }, { 0, "este SA" }, { 1, "el próximo SA" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} sábados" }, { PluralRulesValues.Other, "hace {0} sábados" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} SA" }, { PluralRulesValues.Other, "dentro de {0} SA" } }) } }) }, { RelativeTimeUnitValues.Hour, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { 0, "esta hora" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} hora" }, { PluralRulesValues.Other, "hace {0} horas" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} hora" }, { PluralRulesValues.Other, "dentro de {0} horas" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { 0, "esta hora" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} h" }, { PluralRulesValues.Other, "hace {0} h" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} h" }, { PluralRulesValues.Other, "dentro de {0} h" } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { 0, "esta hora" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} h" }, { PluralRulesValues.Other, "hace {0} h" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} h" }, { PluralRulesValues.Other, "dentro de {0} h" } }) } }) }, { RelativeTimeUnitValues.Minute, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { 0, "este minuto" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} minuto" }, { PluralRulesValues.Other, "hace {0} minutos" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} minuto" }, { PluralRulesValues.Other, "dentro de {0} minutos" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { 0, "este minuto" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} min" }, { PluralRulesValues.Other, "hace {0} min" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} min" }, { PluralRulesValues.Other, "dentro de {0} min" } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { 0, "este minuto" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} min" }, { PluralRulesValues.Other, "hace {0} min" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} min" }, { PluralRulesValues.Other, "dentro de {0} min" } }) } }) }, { RelativeTimeUnitValues.Second, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { 0, "ahora" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} segundo" }, { PluralRulesValues.Other, "hace {0} segundos" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} segundo" }, { PluralRulesValues.Other, "dentro de {0} segundos" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { 0, "ahora" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} s" }, { PluralRulesValues.Other, "hace {0} s" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} s" }, { PluralRulesValues.Other, "dentro de {0} s" } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { 0, "ahora" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "hace {0} s" }, { PluralRulesValues.Other, "hace {0} s" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "dentro de {0} s" }, { PluralRulesValues.Other, "dentro de {0} s" } }) } }) } }) { this.Culture = new CultureInfo("es-419"); } } }
57.257081
173
0.613447
[ "MIT" ]
pointnet/alrev-intl
packages/Alrev.Intl.RelativeTime/Resources/Es419RelativeTimeResource.intl.cs
26,375
C#
namespace MVC.Framework.Contracts.Generic { public interface IRenderable<TModel> : IRenderable { TModel Model { get; set; } } }
21.142857
54
0.655405
[ "MIT" ]
sevdalin/Software-University-SoftUni
C# Web Development Basics/09. Intro to MVC. Creating Application Server/MVC.Framework/Contracts/Generic/IRenderable.cs
150
C#
// AbstractPartyGameSession using ClubPenguin.Core; using ClubPenguin.Net; using ClubPenguin.PartyGames; using Disney.Kelowna.Common; using Disney.MobileNetwork; using System.Collections.Generic; using UnityEngine; public abstract class AbstractPartyGameSession : IPartyGameSession { private const float AUDIO_PREFAB_DESTROY_DELAY = 3f; protected GameObject audioPrefab; protected int partyGameId; private int id; private List<PartyGamePlayer> playersList; protected int sessionId => id; protected List<PartyGamePlayer> players => playersList; public void StartGame(int id, List<PartyGamePlayer> players, int partyGameId) { this.id = id; playersList = players; this.partyGameId = partyGameId; startGame(); } protected void loadAudioPrefab(PartyGameDefinition definition) { if (!string.IsNullOrEmpty(definition.AudioPrefab.Key)) { Content.LoadAsync(onAudioPrefabLoaded, definition.AudioPrefab); } } private void onAudioPrefabLoaded(string path, GameObject prefab) { audioPrefab = Object.Instantiate(prefab); audioPrefabLoaded(); } protected virtual void audioPrefabLoaded() { } public void EndGame(Dictionary<long, int> playerSessionIdToPlacement) { endGame(playerSessionIdToPlacement); if (audioPrefab != null) { Object.Destroy(audioPrefab, 3f); } destroy(); } public void HandleSessionMessage(PartyGameSessionMessageTypes type, string data) { handleSessionMessage(type, data); } protected abstract void handleSessionMessage(PartyGameSessionMessageTypes type, string data); protected abstract void startGame(); protected abstract void endGame(Dictionary<long, int> playerSessionIdToPlacement); protected abstract void destroy(); protected void sendSessionMessage(PartyGameSessionMessageTypes type, object data) { Service.Get<INetworkServicesManager>().PartyGameService.SendSessionMessage(id, (int)type, data); } protected PartyGameDefinition getPartyGameDefinition(int definitionId) { Dictionary<int, PartyGameDefinition> dictionary = Service.Get<IGameData>().Get<Dictionary<int, PartyGameDefinition>>(); if (!dictionary.ContainsKey(definitionId)) { } return dictionary[definitionId]; } }
24.617978
121
0.78366
[ "MIT" ]
smdx24/CPI-Source-Code
ClubPenguin.PartyGames/AbstractPartyGameSession.cs
2,191
C#
namespace BTCPayServer.Abstractions.Custodians; public class InvalidWithdrawalTargetException : CustodianApiException { public InvalidWithdrawalTargetException(ICustodian custodian, string paymentMethod, string targetAddress, CustodianApiException originalException) : base(403, "invalid-withdrawal-target", $"{custodian.Name} cannot withdraw {paymentMethod} to '{targetAddress}': {originalException.Message}") { } }
43.1
294
0.809745
[ "MIT" ]
Eskyee/btcpayjungleserver
BTCPayServer.Abstractions/Custodians/Client/Exception/InvalidWithdrawalTargetException.cs
431
C#
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Resources; using System.Globalization; using System.IO; using System.Security; using Microsoft.Build.Utilities; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using System.Reflection; using System.Diagnostics; #nullable disable namespace Microsoft.Build.Tasks.DataDriven { /// <summary> /// The top class that will take care of all the tasks that wrap tools. /// All tasks that wrap tools will derive from this class. /// Holds a Dictionary of all switches that have been set /// </summary> public abstract class DataDrivenToolTask : ToolTask { /// <summary> /// The dictionary that holds all set switches /// The string is the name of the property, and the ToolSwitch holds all of the relevant information /// i.e., switch, boolean value, type, etc. /// </summary> private Dictionary<string, ToolSwitch> activeToolSwitches = new Dictionary<string, ToolSwitch>(); /// <summary> /// The dictionary holds all of the legal values that are associated with a certain switch. /// For example, the key Optimization would hold another dictionary as the value, that had the string pairs /// "Disabled", "/Od"; "MaxSpeed", "/O1"; "MinSpace", "/O2"; "Full", "/Ox" in it. /// </summary> private Dictionary<string, Dictionary<string, string>> values = new Dictionary<string, Dictionary<string, string>>(); /// <summary> /// Any additional options (as a literal string) that may have been specified in the project file /// We eventually want to get rid of this /// </summary> private string additionalOptions = String.Empty; /// <summary> /// The prefix to append before all switches /// </summary> private char prefix = '/'; /// <summary> /// True if we returned our commands directly from the command line generation and do not need to use the /// response file (because the command-line is short enough) /// </summary> private bool skipResponseFileCommandGeneration; protected TaskLoggingHelper logPrivate; /// <summary> /// Default constructor /// </summary> protected DataDrivenToolTask(ResourceManager taskResources) : base(taskResources) { logPrivate = new TaskLoggingHelper(this); logPrivate.TaskResources = AssemblyResources.PrimaryResources; logPrivate.HelpKeywordPrefix = "MSBuild."; } #region Properties /// <summary> /// The list of all the switches that have been set /// </summary> protected Dictionary<string, ToolSwitch> ActiveToolSwitches { get { return activeToolSwitches; } } /// <summary> /// The additional options that have been set. These are raw switches that /// go last on the command line. /// </summary> public string AdditionalOptions { get { return additionalOptions; } set { additionalOptions = value; } } /// <summary> /// Overridden to use UTF16, which works better than UTF8 for older versions of CL, LIB, etc. /// </summary> protected override Encoding ResponseFileEncoding { get { return Encoding.Unicode; } } /// <summary> /// Ordered list of switches /// </summary> /// <returns>ArrayList of switches in declaration order</returns> protected virtual ArrayList SwitchOrderList { get { return null; } } #endregion #region ToolTask Members /// <summary> /// This method is called to find the tool if ToolPath wasn't specified. /// We just return the name of the tool so it can be found on the path. /// Deriving classes can choose to do something else. /// </summary> protected override string GenerateFullPathToTool() { #if WHIDBEY_BUILD // if we just have the file name, search for the file on the system path string actualPathToTool = NativeMethodsShared.FindOnPath(ToolName); // if we find the file if (actualPathToTool != null) { // point to it return actualPathToTool; } else { return ToolName; } #else return ToolName; #endif } /// <summary> /// Validates all of the set properties that have either a string type or an integer type /// </summary> /// <returns></returns> override protected bool ValidateParameters() { return !logPrivate.HasLoggedErrors && !Log.HasLoggedErrors; } #if WHIDBEY_BUILD /// <summary> /// Delete temporary file. If the delete fails for some reason (e.g. file locked by anti-virus) then /// the call will not throw an exception. Instead a warning will be logged, but the build will not fail. /// </summary> /// <param name="filename">File to delete</param> protected void DeleteTempFile(string fileName) { try { File.Delete(fileName); } catch (Exception e) // Catching Exception, but rethrowing unless it's an IO related exception. { if (ExceptionHandling.NotExpectedException(e)) throw; // Warn only -- occasionally temp files fail to delete because of virus checkers; we // don't want the build to fail in such cases Log.LogWarningWithCodeFromResources("Shared.FailedDeletingTempFile", fileName, e.Message); } } #endif #endregion /// <summary> /// For testing purposes only /// Returns the generated command line /// </summary> /// <returns></returns> internal string GetCommandLine_ForUnitTestsOnly() { return GenerateResponseFileCommands(); } protected override string GenerateCommandLineCommands() { string commands = GenerateCommands(); if (commands.Length < 32768) { skipResponseFileCommandGeneration = true; return commands; } skipResponseFileCommandGeneration = false; return null; } /// <summary> /// Creates the command line and returns it as a string by: /// 1. Adding all switches with the default set to the active switch list /// 2. Customizing the active switch list (overridden in derived classes) /// 3. Iterating through the list and appending switches /// </summary> /// <returns></returns> protected override string GenerateResponseFileCommands() { if (skipResponseFileCommandGeneration) { skipResponseFileCommandGeneration = false; return null; } else { return GenerateCommands(); } } /// <summary> /// Verifies that the required args are present. This function throws if we have missing required args /// </summary> /// <param name="property"></param> /// <returns></returns> protected virtual bool VerifyRequiredArgumentsArePresent(ToolSwitch property, bool bThrowOnError) { return true; } /// <summary> /// Verifies that the dependencies are present, and if the dependencies are present, or if the property /// doesn't have any dependencies, the switch gets emitted /// </summary> /// <param name="property"></param> /// <returns></returns> protected virtual bool VerifyDependenciesArePresent(ToolSwitch property) { // check the dependency if (property.Parents.Count > 0) { // has a dependency, now check to see whether at least one parent is set // if it is set, add to the command line // otherwise, ignore it bool isSet = false; foreach (string parentName in property.Parents) { isSet = isSet || HasSwitch(parentName); } return isSet; } else { // no dependencies to account for return true; } } /// <summary> /// A protected method to add the switches that are by default visible /// e.g., /nologo is true by default /// </summary> protected virtual void AddDefaultsToActiveSwitchList() { // do nothing } /// <summary> /// A method that will add the fallbacks to the active switch list if the actual property is not set /// </summary> protected virtual void AddFallbacksToActiveSwitchList() { // do nothing } /// <summary> /// To be overriden by custom code for individual tasks /// </summary> protected virtual void PostProcessSwitchList() { // do nothing } /// <summary> /// Generates a part of the command line depending on the type /// </summary> /// <remarks>Depending on the type of the switch, the switch is emitted with the proper values appended. /// e.g., File switches will append file names, directory switches will append filenames with "\" on the end</remarks> /// <param name="clb"></param> /// <param name="toolSwitch"></param> protected void GenerateCommandsAccordingToType(CommandLineBuilder clb, ToolSwitch toolSwitch, bool bRecursive) { // if this property has a parent skip printing it as it was printed as part of the parent prop printing if (toolSwitch.Parents.Count > 0 && !bRecursive) return; switch (toolSwitch.Type) { case ToolSwitchType.Boolean: EmitBooleanSwitch(clb, toolSwitch); break; case ToolSwitchType.String: EmitStringSwitch(clb, toolSwitch); break; case ToolSwitchType.StringArray: EmitStringArraySwitch(clb, toolSwitch); break; case ToolSwitchType.Integer: EmitIntegerSwitch(clb, toolSwitch); break; case ToolSwitchType.File: EmitFileSwitch(clb, toolSwitch); break; case ToolSwitchType.Directory: EmitDirectorySwitch(clb, toolSwitch); break; case ToolSwitchType.ITaskItem: EmitTaskItemSwitch(clb, toolSwitch); break; case ToolSwitchType.ITaskItemArray: EmitTaskItemArraySwitch(clb, toolSwitch); break; case ToolSwitchType.AlwaysAppend: EmitAlwaysAppendSwitch(clb, toolSwitch); break; default: // should never reach this point - if it does, there's a bug somewhere. ErrorUtilities.VerifyThrow(false, "InternalError"); break; } } /// <summary> /// Appends a literal string containing the verbatim contents of any /// "AdditionalOptions" parameter. This goes last on the command /// line in case it needs to cancel any earlier switch. /// Ideally this should never be needed because the MSBuild task model /// is to set properties, not raw switches /// </summary> /// <param name="cmdLine"></param> protected void BuildAdditionalArgs(CommandLineBuilder cmdLine) { // We want additional options to be last so that this can always override other flags. if ((cmdLine != null) && !String.IsNullOrEmpty(additionalOptions)) { cmdLine.AppendSwitch(additionalOptions); } } /// <summary> /// Emit a switch that's always appended /// </summary> private static void EmitAlwaysAppendSwitch(CommandLineBuilder clb, ToolSwitch toolSwitch) { clb.AppendSwitch(toolSwitch.Name); } /// <summary> /// Emit a switch that's an array of task items /// </summary> private static void EmitTaskItemArraySwitch(CommandLineBuilder clb, ToolSwitch toolSwitch) { if (String.IsNullOrEmpty(toolSwitch.Separator)) { foreach (ITaskItem itemName in toolSwitch.TaskItemArray) { clb.AppendSwitchIfNotNull(toolSwitch.SwitchValue, itemName.ItemSpec); } } else { clb.AppendSwitchIfNotNull(toolSwitch.SwitchValue, toolSwitch.TaskItemArray, toolSwitch.Separator); } } /// <summary> /// Emit a switch that's a scalar task item /// </summary> private static void EmitTaskItemSwitch(CommandLineBuilder clb, ToolSwitch toolSwitch) { if (!String.IsNullOrEmpty(toolSwitch.Name)) { clb.AppendSwitch(toolSwitch.Name + toolSwitch.Separator); } } /// <summary> /// Generates the command line for the tool. /// </summary> private string GenerateCommands() { // the next three methods are overridden by the base class // here it does nothing unless overridden AddDefaultsToActiveSwitchList(); AddFallbacksToActiveSwitchList(); PostProcessSwitchList(); #if WHIDBEY_BUILD CommandLineBuilder commandLineBuilder = new CommandLineBuilder(); #else CommandLineBuilder commandLineBuilder = new CommandLineBuilder(true /* quote hyphens */); #endif // iterates through the list of set toolswitches foreach (string propertyName in SwitchOrderList) { if (IsPropertySet(propertyName)) { ToolSwitch property = activeToolSwitches[propertyName]; // verify the dependencies if (VerifyDependenciesArePresent(property) && VerifyRequiredArgumentsArePresent(property, false)) { GenerateCommandsAccordingToType(commandLineBuilder, property, false); } } else if (String.Equals(propertyName, "AlwaysAppend", StringComparison.OrdinalIgnoreCase)) { commandLineBuilder.AppendSwitch(AlwaysAppend); } } // additional args should go on the end BuildAdditionalArgs(commandLineBuilder); return commandLineBuilder.ToString(); } /// <summary> /// Checks to see if the argument is required and whether an argument exists, and returns the /// argument or else fallback argument if it exists. /// /// These are the conditions to look at: /// /// ArgumentRequired ArgumentParameter FallbackArgumentParameter Result /// true isSet NA The value in ArgumentParameter gets returned /// true isNotSet isSet The value in FallbackArgumentParamter gets returned /// true isNotSet isNotSet An error occurs, as argumentrequired is true /// false isSet NA The value in ArgumentParameter gets returned /// false isNotSet isSet The value in FallbackArgumentParameter gets returned /// false isNotSet isNotSet The empty string is returned, as there are no arguments, and no arguments are required /// </summary> /// <param name="toolSwitch"></param> /// <returns></returns> protected virtual string GetEffectiveArgumentsValues(ToolSwitch toolSwitch) { //if (!toolSwitch.ArgumentRequired && !IsPropertySet(toolSwitch.ArgumentParameter) && // !IsPropertySet(toolSwitch.FallbackArgumentParameter)) //{ // return String.Empty; //} //// check to see if it has an argument //if (toolSwitch.ArgumentRequired) //{ // if (!IsPropertySet(toolSwitch.ArgumentParameter) && !IsPropertySet(toolSwitch.FallbackArgumentParameter)) // { // throw new ArgumentException(logPrivate.FormatResourceString("ArgumentRequired", toolSwitch.Name)); // } //} //// if it gets to here, the argument or the fallback is set //if (IsPropertySet(toolSwitch.ArgumentParameter)) //{ // return ActiveToolSwitches[toolSwitch.ArgumentParameter].ArgumentValue; //} //else //{ // return ActiveToolSwitches[toolSwitch.FallbackArgumentParameter].ArgumentValue; //} return "GetEffectiveArgumentValue not Impl"; } /// <summary> /// Appends the directory name to the end of a switch /// Ensure the name ends with a slash /// </summary> /// <remarks>For directory switches (e.g., TrackerLogDirectory), the toolSwitchName (if it exists) is emitted /// along with the FileName which is ensured to have a trailing slash</remarks> /// <param name="clb"></param> /// <param name="toolSwitch"></param> private static void EmitDirectorySwitch(CommandLineBuilder clb, ToolSwitch toolSwitch) { if (!String.IsNullOrEmpty(toolSwitch.SwitchValue)) { //clb.AppendSwitchIfNotNull(toolSwitch.Name + toolSwitch.Separator, EnsureTrailingSlash(toolSwitch.ArgumentValue)); clb.AppendSwitch(toolSwitch.SwitchValue + toolSwitch.Separator); } } /// <summary> /// Generates the switches that have filenames attached to the end /// </summary> /// <remarks>For file switches (e.g., PrecompiledHeaderFile), the toolSwitchName (if it exists) is emitted /// along with the FileName which may or may not have quotes</remarks> /// e.g., PrecompiledHeaderFile = "File" will emit /FpFile /// <param name="clb"></param> /// <param name="toolSwitch"></param> private static void EmitFileSwitch(CommandLineBuilder clb, ToolSwitch toolSwitch) { if (!String.IsNullOrEmpty(toolSwitch.Value)) { String str = toolSwitch.Value; str.Trim(); if (!str.StartsWith("\"")) { str = "\"" + str; if (str.EndsWith("\\") && !str.EndsWith("\\\\")) str += "\\\""; else str += "\""; } //we want quotes always, AppendSwitchIfNotNull will add them on as needed bases clb.AppendSwitchUnquotedIfNotNull(toolSwitch.SwitchValue + toolSwitch.Separator, str); } } /// <summary> /// Generates the commands for switches that have integers appended. /// </summary> /// <remarks>For integer switches (e.g., WarningLevel), the toolSwitchName is emitted /// with the appropriate integer appended, as well as any arguments /// e.g., WarningLevel = "4" will emit /W4</remarks> /// <param name="clb"></param> /// <param name="toolSwitch"></param> private void EmitIntegerSwitch(CommandLineBuilder clb, ToolSwitch toolSwitch) { if (toolSwitch.IsValid) { if (!String.IsNullOrEmpty(toolSwitch.Separator)) { clb.AppendSwitch(toolSwitch.SwitchValue + toolSwitch.Separator + toolSwitch.Number.ToString() + GetEffectiveArgumentsValues(toolSwitch)); } else { clb.AppendSwitch(toolSwitch.SwitchValue + toolSwitch.Number.ToString() + GetEffectiveArgumentsValues(toolSwitch)); } } } /// <summary> /// Generates the commands for the switches that may have an array of arguments /// The switch may be empty. /// </summary> /// <remarks>For stringarray switches (e.g., Sources), the toolSwitchName (if it exists) is emitted /// along with each and every one of the file names separately (if no separator is included), or with all of the /// file names separated by the separator. /// e.g., AdditionalIncludeDirectores = "@(Files)" where Files has File1, File2, and File3, the switch /// /IFile1 /IFile2 /IFile3 or the switch /IFile1;File2;File3 is emitted (the latter case has a separator /// ";" specified)</remarks> /// <param name="clb"></param> /// <param name="toolSwitch"></param> private static void EmitStringArraySwitch(CommandLineBuilder clb, ToolSwitch toolSwitch) { string[] ArrTrimStringList = new string [toolSwitch.StringList.Length]; for (int i=0; i<toolSwitch.StringList.Length; ++i) { //Make sure the file doesn't contain escaped " (\") if (toolSwitch.StringList[i].StartsWith("\"") && toolSwitch.StringList[i].EndsWith("\"")) { ArrTrimStringList[i] = toolSwitch.StringList[i].Substring(1, toolSwitch.StringList[i].Length - 2); } else { ArrTrimStringList[i] = toolSwitch.StringList[i]; } } if (String.IsNullOrEmpty(toolSwitch.Separator)) { foreach (string fileName in ArrTrimStringList) { clb.AppendSwitchIfNotNull(toolSwitch.SwitchValue, fileName); } } else { clb.AppendSwitchIfNotNull(toolSwitch.SwitchValue, ArrTrimStringList, toolSwitch.Separator); } } /// <summary> /// Generates the switches for switches that either have literal strings appended, or have /// different switches based on what the property is set to. /// </summary> /// <remarks>The string switch emits a switch that depends on what the parameter is set to, with and /// arguments /// e.g., Optimization = "Full" will emit /Ox, whereas Optimization = "Disabled" will emit /Od</remarks> /// <param name="clb"></param> /// <param name="toolSwitch"></param> private void EmitStringSwitch(CommandLineBuilder clb, ToolSwitch toolSwitch) { String strSwitch = String.Empty; strSwitch += toolSwitch.SwitchValue + toolSwitch.Separator; StringBuilder val = new StringBuilder(GetEffectiveArgumentsValues(toolSwitch)); String str = toolSwitch.Value; if (!toolSwitch.MultiValues) { str.Trim(); if (!str.StartsWith("\"")) { str = "\"" + str; if (str.EndsWith("\\") && !str.EndsWith("\\\\")) str += "\\\""; else str += "\""; } val.Insert(0, str); } if ((strSwitch.Length == 0) && (val.ToString().Length == 0)) return; clb.AppendSwitchUnquotedIfNotNull(strSwitch, val.ToString()); } /// <summary> /// Generates the switches that are nonreversible /// </summary> /// <remarks>A boolean switch is emitted if it is set to true. If it set to false, nothing is emitted. /// e.g. nologo = "true" will emit /Og, but nologo = "false" will emit nothing.</remarks> /// <param name="clb"></param> /// <param name="toolSwitch"></param> private void EmitBooleanSwitch(CommandLineBuilder clb, ToolSwitch toolSwitch) { if (toolSwitch.BooleanValue) { if (!String.IsNullOrEmpty(toolSwitch.SwitchValue)) { StringBuilder val = new StringBuilder(GetEffectiveArgumentsValues(toolSwitch)); val.Insert(0, toolSwitch.Separator); val.Insert(0, toolSwitch.TrueSuffix); val.Insert(0, toolSwitch.SwitchValue); clb.AppendSwitch(val.ToString()); } } else EmitReversibleBooleanSwitch(clb, toolSwitch); } /// <summary> /// Generates the command line for switches that are reversible /// </summary> /// <remarks>A reversible boolean switch will emit a certain switch if set to true, but emit that /// exact same switch with a flag appended on the end if set to false. /// e.g., GlobalOptimizations = "true" will emit /Og, and GlobalOptimizations = "false" will emit /Og-</remarks> /// <param name="clb"></param> /// <param name="toolSwitch"></param> private void EmitReversibleBooleanSwitch(CommandLineBuilder clb, ToolSwitch toolSwitch) { // if the value is set to true, append whatever the TrueSuffix is set to. // Otherwise, append whatever the FalseSuffix is set to. if (!String.IsNullOrEmpty(toolSwitch.ReverseSwitchValue)) { string suffix = (toolSwitch.BooleanValue) ? toolSwitch.TrueSuffix : toolSwitch.FalseSuffix; StringBuilder val = new StringBuilder(GetEffectiveArgumentsValues(toolSwitch)); val.Insert(0, suffix); val.Insert(0, toolSwitch.Separator); val.Insert(0, toolSwitch.TrueSuffix); val.Insert(0, toolSwitch.ReverseSwitchValue); clb.AppendSwitch(val.ToString()); } } /// <summary> /// Checks to make sure that a switch has either a '/' or a '-' prefixed. /// </summary> /// <param name="toolSwitch"></param> /// <returns></returns> private string Prefix(string toolSwitch) { if (!String.IsNullOrEmpty(toolSwitch)) { if (toolSwitch[0] != prefix) { return prefix + toolSwitch; } } return toolSwitch; } /// <summary> /// A method that will validate the integer type arguments /// If the min or max is set, and the value a property is set to is not within /// the range, the build fails /// </summary> /// <param name="switchName"></param> /// <param name="min"></param> /// <param name="max"></param> /// <param name="value"></param> /// <returns>The valid integer passed converted to a string form</returns> protected bool ValidateInteger(string switchName, int min, int max, int value) { if (value < min || value > max) { logPrivate.LogErrorFromResources("ArgumentOutOfRange", switchName, value); return false; } return true; } /// <summary> /// A method for the enumerated values a property can have /// This method checks the value a property is set to, and finds the corresponding switch /// </summary> /// <param name="propertyName"></param> /// <param name="switchMap"></param> /// <param name="value"></param> /// <returns>The switch that a certain value is mapped to</returns> protected string ReadSwitchMap(string propertyName, string[][] switchMap, string value) { if (switchMap != null) { for (int i = 0; i < switchMap.Length; ++i) { if (String.Equals(switchMap[i][0], value, StringComparison.CurrentCultureIgnoreCase)) { return switchMap[i][1]; } } logPrivate.LogErrorFromResources("ArgumentOutOfRange", propertyName, value); } return String.Empty; } /// <summary> /// Returns true if the property has a value in the list of active tool switches /// </summary> protected bool IsPropertySet(string propertyName) { if (!String.IsNullOrEmpty(propertyName)) { return activeToolSwitches.ContainsKey(propertyName); } else { return false; } } /// <summary> /// Returns true if the property is set to true. /// Returns false if the property is not set, or set to false. /// </summary> protected bool IsSetToTrue(string propertyName) { if (activeToolSwitches.ContainsKey(propertyName)) { return activeToolSwitches[propertyName].BooleanValue; } else { return false; } } /// <summary> /// Returns true if the property is set to false. /// Returns false if the property is not set, or set to true. /// </summary> protected bool IsExplicitlySetToFalse(string propertyName) { if (activeToolSwitches.ContainsKey(propertyName)) { return !activeToolSwitches[propertyName].BooleanValue; } else { return false; } } /// <summary> /// Checks to see if the switch name is empty /// </summary> /// <param name="propertyName"></param> /// <returns></returns> protected bool HasSwitch(string propertyName) { if (IsPropertySet(propertyName)) { return !String.IsNullOrEmpty(activeToolSwitches[propertyName].Name); } else { return false; } } /// <summary> /// If the given path doesn't have a trailing slash then add one. /// </summary> /// <param name="directoryName">The path to check.</param> /// <returns>A path with a slash.</returns> protected static string EnsureTrailingSlash(string directoryName) { ErrorUtilities.VerifyThrow(directoryName != null, "InternalError"); if (!String.IsNullOrEmpty(directoryName)) { char endingCharacter = directoryName[directoryName.Length - 1]; if (!(endingCharacter == Path.DirectorySeparatorChar || endingCharacter == Path.AltDirectorySeparatorChar) ) { directoryName += Path.DirectorySeparatorChar; } } return directoryName; } /// <summary> /// The string that is always appended on the command line. Overridden by deriving classes. /// </summary> protected virtual string AlwaysAppend { get { return String.Empty; } set { // do nothing } } } }
38.90866
166
0.547652
[ "MIT" ]
AlexanderSemenyak/msbuild
src/Tasks/DataDriven/DataDrivenToolTask.cs
32,802
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("ParkingValidation")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ParkingValidation")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("1eb65b8f-48ea-4436-a52a-bebe283c0e09")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.891892
84
0.749643
[ "MIT" ]
VeselinBPavlov/programming-fundamentals
18. Dictionaries and Lists - More Exercises/ParkingValidation/Properties/AssemblyInfo.cs
1,405
C#
using System; using Android.App; using Android.Content.PM; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; namespace Demo0607.Droid { [Activity(Label = "Demo0607", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); // This MobileServiceClient has been configured to communicate with the Azure Mobile App and // Azure Gateway using the application url. You're all set to start working with your Mobile App! Microsoft.WindowsAzure.MobileServices.MobileServiceClient ToyLibraryCarlsonClient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient( "https://toylibrarycarlson.azurewebsites.net"); global::Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App()); } } }
37.121212
183
0.707755
[ "MIT" ]
Shaw6157/ToyLibrary
Demo0607/Demo0607/Demo0607.Android/MainActivity.cs
1,227
C#
using UnityEngine; using System.Collections; using UnityEngine.UI; public class BulletText : MonoBehaviour { public GunHanddle gunHandle; public Text bulletText; // Use this for initialization void Start() { if (gunHandle == null) { gunHandle = FindObjectOfType(typeof(GunHanddle)) as GunHanddle; } } // Update is called once per frame void Update() { if (gunHandle == null || bulletText == null || gunHandle.CurrentGun == null) { return; } bulletText.text = string.Format("{0} / {1}", gunHandle.CurrentGun.Clip, gunHandle.CurrentGun.AmmoPack); } }
23.241379
112
0.605341
[ "MIT" ]
yantian001/3DSniper
Assets/Script/UI/BulletText.cs
676
C#
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; using System.Collections.Generic; using Stride.Core.Collections; using Stride.Core.Mathematics; namespace Stride.Input { /// <summary> /// Provides an interface for interacting with pointer devices, this can be a mouse, pen, touch screen, etc. /// </summary> public interface IPointerDevice : IInputDevice { /// <summary> /// The size of the surface used by the pointer, for a mouse this is the size of the window, for a touch device, the size of the touch area, etc. /// </summary> Vector2 SurfaceSize { get; } /// <summary> /// The aspect ratio of the touch surface area /// </summary> float SurfaceAspectRatio { get; } /// <summary> /// The index of the pointers that have been pressed since the last frame /// </summary> Core.Collections.IReadOnlySet<PointerPoint> PressedPointers { get; } /// <summary> /// The index of the pointers that have been released since the last frame /// </summary> Core.Collections.IReadOnlySet<PointerPoint> ReleasedPointers { get; } /// <summary> /// The index of the pointers that are down /// </summary> Core.Collections.IReadOnlySet<PointerPoint> DownPointers { get; } /// <summary> /// Raised when the surface size of this pointer changed /// </summary> event EventHandler<SurfaceSizeChangedEventArgs> SurfaceSizeChanged; } }
38.630435
163
0.647158
[ "MIT" ]
Alan-love/xenko
sources/engine/Stride.Input/IPointerDevice.cs
1,777
C#
using System.Threading.Tasks; using NUnit.Framework; using Senticode.Database.Tools.Interfaces; using Unity; namespace Senticode.Database.Tools.Tests.Framework { [TestFixture] public abstract class TestBase { protected IUnityContainer _container; public bool WithStrongContext { get; set; } public virtual async Task SetUp() { _container = new UnityContainer(); new TestInitializer().Initialize(_container); await AutoInitDatabase(); } private async Task AutoInitDatabase() { _container.Resolve<IConnectionManager>().GetDbStrongContext().Database.EnsureCreated(); await Task.CompletedTask; } public virtual void TearDown() { _container?.Dispose(); _container = null; } } }
24.771429
99
0.620531
[ "MIT" ]
Senticode/Senticode.Xamarin.Tools
tests/Senticode.Database.Tools.Tests/Framework/TestBase.cs
869
C#
using System; using Microsoft.Xna.Framework; using _4DMonoEngine.Core.Blocks; using _4DMonoEngine.Core.Utils; using _4DMonoEngine.Core.Utils.Noise; namespace _4DMonoEngine.Core.Generators.Structures { //TODO : refactor this into a proper structure system public class StructureGenerator { private ushort m_treeId; private readonly CellNoise2D m_cellNoise; private readonly SimplexNoise2D m_densityFunction; private float m_sampleScale; private float m_minSampleScale; public StructureGenerator(ulong seed) { m_treeId = BlockDictionary.Instance.GetBlockIdForName("Sand"); m_densityFunction = new SimplexNoise2D(seed); m_cellNoise = new CellNoise2D(seed); m_sampleScale = 64; m_minSampleScale = 4; } public CellNoise2D.VoroniData CalculateNearestSamplePosition(float x, float z) { //TODO : tweak magic numbers var scaleAdjustment = (int)MathHelper.Clamp(m_densityFunction.FractalBrownianMotion(x, z, 512, 0, 4) * 5, -1, 1); var finalScale = m_sampleScale - scaleAdjustment*(m_sampleScale - m_minSampleScale); var data = m_cellNoise.Voroni(x, z, finalScale); var centroid = new Vector2 { X = x + (float) Math.Round(data.Delta.X*finalScale, MidpointRounding.ToEven), Y = z + (float) Math.Round(data.Delta.Y*finalScale, MidpointRounding.ToEven) }; data.Delta = centroid; return data; } public void PopulateTree(int worldPositionX, int worldPositionZ, int groundLevel, Block[] blocks, MappingFunction mappingFunction) { var trunkHeight = 15 + groundLevel; for (var y = groundLevel; y < trunkHeight; y++) { blocks[mappingFunction(worldPositionX, y, worldPositionZ)] = new Block(m_treeId); } /* var radius = 3; for (var i = -radius; i < radius; i++) { for (var j = -radius; j < radius; j++) { var offset = ChunkCache.BlockIndexByWorldPosition(worldPositionX + i, worldPositionZ + j); for (var k = radius * 2; k > 0; k--) { ChunkCache.Blocks[offset + k + trunkHeight + 1] = new Block(BlockType.Leaves); } } }*/ } } }
39.46875
139
0.578781
[ "MIT" ]
HaKDMoDz/4DBlockEngine
Monogame/4DMonoEngine/Core/Generators/Structures/PlantPopulator.cs
2,528
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Inputs { public sealed class WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementSizeConstraintStatementFieldToMatchSingleQueryArgumentGetArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the query header to inspect. This setting must be provided as lower case characters. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; public WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementSizeConstraintStatementFieldToMatchSingleQueryArgumentGetArgs() { } } }
37.884615
187
0.744162
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementSizeConstraintStatementFieldToMatchSingleQueryArgumentGetArgs.cs
985
C#
using System; using System.Collections.Generic; using System.Text; using Sudoku.Core; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using CsvHelper; using Keras; using Keras.Models; using Python.Runtime; using Sudoku.Core; using Numpy; namespace CNNAlgorithm { class SudokuSolver : ISudokuSolver { private const string modelPath = @"..\..\..\..\SolverNeuralNet\Models\sudoku.model"; private static BaseModel model = NeuralNetHelper.LoadModel(modelPath); public Sudoku.Core.GrilleSudoku Solve(Sudoku.Core.GrilleSudoku s) { return NeuralNetHelper.SolveSudoku(s, model); } void ISudokuSolver.Solve(GrilleSudoku s) { throw new NotImplementedException(); } } public class SudokuSample { public Sudoku.Core.GrilleSudoku Quiz { get; set; } public Sudoku.Core.GrilleSudoku Solution { get; set; } } public class NeuralNetHelper { static NeuralNetHelper() { PythonEngine.PythonHome = @"C:\Users\sosth\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit)"; Setup.UseTfKeras(); } public static BaseModel LoadModel(string strpath) { return BaseModel.LoadModel(strpath); } public static NDarray GetFeatures(Sudoku.Core.GrilleSudoku objSudoku) { return Normalize(np.array(objSudoku.Cellules.ToArray()).reshape(9, 9)); } public static Sudoku.Core.GrilleSudoku GetSudoku(NDarray features) { return new Sudoku.Core.GrilleSudoku() { Cellules = features.flatten().astype(np.int32).GetData<int>().ToList() }; } public static NDarray Normalize(NDarray features) { return (features / 9) - 0.5; } public static NDarray DeNormalize(NDarray features) { return (features + 0.5) * 9; } public static Sudoku.Core.GrilleSudoku SolveSudoku(Sudoku.Core.GrilleSudoku s, BaseModel model) { var features = GetFeatures(s); while (true) { var output = model.Predict(features.reshape(1, 9, 9, 1)); output = output.squeeze(); var prediction = np.argmax(output, axis: 2).reshape(9, 9) + 1; var proba = np.around(np.max(output, axis: new[] { 2 }).reshape(9, 9), 2); features = DeNormalize(features); var mask = features.@equals(0); if (((int)mask.sum()) == 0) { break; } var probNew = proba * mask; var ind = (int)np.argmax(probNew); var (x, y) = ((ind / 9), ind % 9); var val = prediction[x][y]; features[x][y] = val; features = Normalize(features); } return GetSudoku(features); } } public class DataSetHelper { public static List<SudokuSample> ParseCSV(string path, int numSudokus) { var records = new List<SudokuSample>(); using (var compressedStream = File.OpenRead(path)) using (var decompressedStream = new GZipStream(compressedStream, CompressionMode.Decompress)) using (var reader = new StreamReader(decompressedStream)) using (var csv = new CsvReader(reader)) { csv.Configuration.Delimiter = ","; csv.Read(); csv.ReadHeader(); var currentNb = 0; while (csv.Read() && currentNb < numSudokus) { var record = new SudokuSample { Quiz = Sudoku.Core.GrilleSudoku.Parse(csv.GetField<string>("quizzes")), Solution = Sudoku.Core.GrilleSudoku.Parse(csv.GetField<string>("solutions")) }; records.Add(record); currentNb++; } } return records; } } }
22.74
120
0.673996
[ "MIT" ]
sosthenee/ECE-2021-FIN-E-Ing4-Finance-Gr02-IA1
CNNAlgorithm/SudokuSolver.cs
3,413
C#
using Prism.Mvvm; namespace Prism.Wpf.Tests.Mocks.ViewModels { public class MockViewModel : BindableBase { private int mockProperty; public int MockProperty { get { return this.mockProperty; } set { this.SetProperty(ref mockProperty, value); } } internal void InvokeOnPropertyChanged() { this.RaisePropertyChanged(nameof(MockProperty)); } } }
19
60
0.507519
[ "MIT" ]
Adam--/Prism
tests/Wpf/Prism.Wpf.Tests/Mocks/ViewModels/MockViewModel.cs
534
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("p02_BasicStackOperations")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("p02_BasicStackOperations")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("a93653c7-d031-4d28-bf23-42325faed879")] // 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.27027
84
0.752119
[ "Apache-2.0" ]
svetliub/Softuni-CSharp-Advanced
01_StacksAndQueues/p02_BasicStackOperations/Properties/AssemblyInfo.cs
1,419
C#
using System; using System.Collections.Generic; using System.Linq; namespace GitlabMindMapGenerator { public class GanttProjectBuilder : IBuilder { public List<Issue> Issues { get; set; } public string FilePath { get; set; } public GanntChartSetting GanntChartSetting { get; set; } public GitlabSettings GitlabSettings { get; set; } public GanttProjectBuilder( List<Issue> issues, string filePath, GitlabSettings gitlabSettings, GanntChartSetting ganntChartSetting ) { Issues = issues; FilePath = filePath; GanntChartSetting = ganntChartSetting; GitlabSettings = gitlabSettings; } public void Build() { GanttProjectWriter gantt = new GanttProjectWriter(FilePath); foreach(Issue issue in this.Issues) { AddTasks(issue, gantt.Tasks); } gantt.Write(); } public void AddTasks(Issue issue, List<GanttProjectTask> tasks) { GitlabLabelMappingSetting label = null; // get label issue if (GitlabSettings.LabelMapping != null) { label = GitlabSettings.LabelMapping.FirstOrDefault( map => issue.Labels.FirstOrDefault(label => label == map?.Label) != null ); } if (label == null || GanntChartSetting.IncludeIssuesLabels .FirstOrDefault(x => x == label.Label) == null) { return; } // TODO : Adjuste base time logic, for get the first date from project DateTime baseDate = System.DateTime.Now.Date; // TODO: Implements logic with DueDate from Issue (DueDate - Estimate) // TODO : Add other params GanttProjectTask task = new GanttProjectTask( issue.Title, id: issue.IID, complete: Convert.ToInt16(issue.TaskCompletionPercentage), startDate: issue.CustomProperties.StartDate ?? baseDate, thirdDate: issue.CustomProperties.DueDate ?? baseDate, webLink: issue.WebURL, expand: true ); tasks.Add(task); foreach(Issue childIssue in issue.Issues) { AddTasks(childIssue, task.Tasks); } } } }
31.225
92
0.55004
[ "MIT" ]
eduardoluizgs/Gitlab-MindMap-Generator
App/Builders/GanttProjectBuilder.cs
2,498
C#
using System; using System.Linq; using FluentAssertions; using NUnit.Framework; using Vostok.Clusterclient.Criteria; using Vostok.Clusterclient.Model; namespace Vostok.ClusterClient.Tests.Core.Criteria { public class RejectRedirectionsCriterion_Tests { private RejectRedirectionsCriterion criterion; [SetUp] public void SetUp() { criterion = new RejectRedirectionsCriterion(); } [TestCase(ResponseCode.MultipleChoices)] [TestCase(ResponseCode.MovedPermanently)] [TestCase(ResponseCode.Found)] [TestCase(ResponseCode.SeeOther)] [TestCase(ResponseCode.UseProxy)] [TestCase(ResponseCode.TemporaryRedirect)] public void Should_reject_given_response_code(ResponseCode code) { criterion.Decide(new Response(code)).Should().Be(ResponseVerdict.Reject); } [Test] public void Should_know_nothing_about_codes_which_are_not_redirections() { var codes = Enum.GetValues(typeof (ResponseCode)).Cast<ResponseCode>().Where(code => !code.IsRedirection()); foreach (var code in codes) { criterion.Decide(new Response(code)).Should().Be(ResponseVerdict.DontKnow); } } [Test] public void Should_know_nothing_about_not_modified_code() { criterion.Decide(new Response(ResponseCode.NotModified)).Should().Be(ResponseVerdict.DontKnow); } } }
30.42
120
0.65549
[ "MIT" ]
vostok-archives/clusterclient.prototype
Vostok.ClusterClient.Tests/Core/Criteria/RejectRedirectionsCriterion_Tests.cs
1,523
C#
using System; namespace Haruair.Command { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class Usage : Attribute { public string Description { get; private set; } public Usage(string description) { Description = description; } } }
14.894737
67
0.713781
[ "MIT" ]
haruair/csharp-command
src/Haruair.Command/Attributes/Usage.cs
285
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text.Shared.Extensions { internal static partial class ITextSnapshotExtensions { public static SnapshotPoint GetPoint(this ITextSnapshot snapshot, int position) => new SnapshotPoint(snapshot, position); public static SnapshotPoint GetPoint(this ITextSnapshot snapshot, int lineNumber, int columnIndex) => new SnapshotPoint(snapshot, snapshot.GetPosition(lineNumber, columnIndex)); /// <summary> /// Convert a <see cref="LinePositionSpan"/> to <see cref="TextSpan"/>. /// </summary> public static TextSpan GetTextSpan(this ITextSnapshot snapshot, LinePositionSpan span) { return TextSpan.FromBounds( GetPosition(snapshot, span.Start.Line, span.Start.Character), GetPosition(snapshot, span.End.Line, span.End.Character)); } public static int GetPosition(this ITextSnapshot snapshot, int lineNumber, int columnIndex) => TryGetPosition(snapshot, lineNumber, columnIndex).Value; public static int? TryGetPosition(this ITextSnapshot snapshot, int lineNumber, int columnIndex) { if (lineNumber < 0 || lineNumber >= snapshot.LineCount) { return null; } int end = snapshot.GetLineFromLineNumber(lineNumber).Start.Position + columnIndex; if (end < 0 || end > snapshot.Length) { return null; } return end; } public static bool TryGetPosition(this ITextSnapshot snapshot, int lineNumber, int columnIndex, out SnapshotPoint position) { int result = 0; position = new SnapshotPoint(); if (lineNumber < 0 || lineNumber >= snapshot.LineCount) { return false; } var line = snapshot.GetLineFromLineNumber(lineNumber); if (columnIndex < 0 || columnIndex >= line.Length) { return false; } result = line.Start.Position + columnIndex; position = new SnapshotPoint(snapshot, result); return true; } public static SnapshotSpan GetSpan(this ITextSnapshot snapshot, int start, int length) => new SnapshotSpan(snapshot, new Span(start, length)); public static SnapshotSpan GetSpanFromBounds(this ITextSnapshot snapshot, int start, int end) => new SnapshotSpan(snapshot, Span.FromBounds(start, end)); public static SnapshotSpan GetSpan(this ITextSnapshot snapshot, Span span) => new SnapshotSpan(snapshot, span); public static ITagSpan<TTag> GetTagSpan<TTag>(this ITextSnapshot snapshot, Span span, TTag tag) where TTag : ITag { return new TagSpan<TTag>(new SnapshotSpan(snapshot, span), tag); } public static SnapshotSpan GetSpan(this ITextSnapshot snapshot, int startLine, int startIndex, int endLine, int endIndex) { return TryGetSpan(snapshot, startLine, startIndex, endLine, endIndex).Value; } public static SnapshotSpan? TryGetSpan(this ITextSnapshot snapshot, int startLine, int startIndex, int endLine, int endIndex) { var startPosition = snapshot.TryGetPosition(startLine, startIndex); var endPosition = snapshot.TryGetPosition(endLine, endIndex); if (startPosition == null || endPosition == null) { return null; } return new SnapshotSpan(snapshot, Span.FromBounds(startPosition.Value, endPosition.Value)); } public static SnapshotSpan GetFullSpan(this ITextSnapshot snapshot) { Contract.ThrowIfNull(snapshot); return new SnapshotSpan(snapshot, new Span(0, snapshot.Length)); } public static NormalizedSnapshotSpanCollection GetSnapshotSpanCollection(this ITextSnapshot snapshot) { Contract.ThrowIfNull(snapshot); return new NormalizedSnapshotSpanCollection(snapshot.GetFullSpan()); } public static void GetLineAndColumn(this ITextSnapshot snapshot, int position, out int lineNumber, out int columnIndex) { var line = snapshot.GetLineFromPosition(position); lineNumber = line.LineNumber; columnIndex = position - line.Start.Position; } /// <summary> /// Returns the leading whitespace of the line located at the specified position in the given snapshot. /// </summary> public static string GetLeadingWhitespaceOfLineAtPosition(this ITextSnapshot snapshot, int position) { Contract.ThrowIfNull(snapshot); var line = snapshot.GetLineFromPosition(position); var linePosition = line.GetFirstNonWhitespacePosition(); if (!linePosition.HasValue) { return line.GetText(); } var lineText = line.GetText(); return lineText.Substring(0, linePosition.Value - line.Start); } public static bool AreOnSameLine(this ITextSnapshot snapshot, int x1, int x2) => snapshot.GetLineNumberFromPosition(x1) == snapshot.GetLineNumberFromPosition(x2); } }
39.475524
161
0.636315
[ "Apache-2.0" ]
DaiMichael/roslyn
src/EditorFeatures/Text/Shared/Extensions/ITextSnapshotExtensions.cs
5,647
C#
using System; using System.Reflection; namespace AMQP.ServiceFramework.Abstractions { public interface ICommandHandlerContext { string Queue { get; } string Topic { get; } MethodInfo TargetMethod { get; } Type DeclaringType { get; } Type ParameterType { get; } Type ParserType { get; } } }
23.4
44
0.626781
[ "MIT" ]
nevsnirG/AMQP.ServiceFramework
src/AMQP.ServiceFramework/Abstractions/ICommandHandlerContext.cs
353
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DisableObjectOnActive : MonoBehaviour { public GameObject objectToDisable; private void OnEnable() { objectToDisable.SetActive(false); } }
18.5
52
0.737452
[ "MIT" ]
SSSxCCC/AlphaZero-In-Unity
Unity Project/AlphaZero/Assets/Scripts/Common/UI/DisableObjectOnActive.cs
261
C#
#nullable enable using System; using System.Collections.Generic; using Microsoft.Extensions.Primitives; namespace Meziantou.Moneiz.Extensions { internal struct KeyValueAccumulator { private Dictionary<string, StringValues> _accumulator; private Dictionary<string, List<string>> _expandingAccumulator; public void Append(string key, string value) { if (_accumulator == null) { _accumulator = new Dictionary<string, StringValues>(StringComparer.OrdinalIgnoreCase); } if (_accumulator.TryGetValue(key, out var values)) { if (values.Count == 0) { // Marker entry for this key to indicate entry already in expanding list dictionary _expandingAccumulator[key].Add(value); } else if (values.Count == 1) { // Second value for this key _accumulator[key] = new string[] { values[0], value }; } else { // Third value for this key // Add zero count entry and move to data to expanding list dictionary _accumulator[key] = default; if (_expandingAccumulator == null) { _expandingAccumulator = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase); } // Already 3 entries so use starting allocated as 8; then use List's expansion mechanism for more var list = new List<string>(8); var array = values.ToArray(); list.Add(array[0]); list.Add(array[1]); list.Add(value); _expandingAccumulator[key] = list; } } else { // First value for this key _accumulator[key] = new StringValues(value); } ValueCount++; } public bool HasValues => ValueCount > 0; public int KeyCount => _accumulator?.Count ?? 0; public int ValueCount { get; private set; } public Dictionary<string, StringValues> GetResults() { if (_expandingAccumulator != null) { // Coalesce count 3+ multi-value entries into _accumulator dictionary foreach (var entry in _expandingAccumulator) { _accumulator[entry.Key] = new StringValues(entry.Value.ToArray()); } } return _accumulator ?? new Dictionary<string, StringValues>(0, StringComparer.OrdinalIgnoreCase); } } }
34.880952
120
0.502389
[ "MIT" ]
meziantou/meziantou.moneiz
src/Meziantou.Moneiz/Extensions/KeyValueAccumulator.cs
2,932
C#
/* Copyright (c) 2020 Denis Zykov This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. License: https://opensource.org/licenses/MIT */ using System; using System.Diagnostics; using JetBrains.Annotations; namespace deniszykov.BaseN { /// <summary> /// Converts bytes to Base32 string and vice versa conversion method. /// Reference: https://en.wikipedia.org/wiki/Base32 /// </summary> [UsedImplicitly(ImplicitUseTargetFlags.WithMembers)] public static class Base32Convert { /// <summary> /// Encode byte array to Base32 string. /// </summary> /// <param name="bytes">Byte array to encode.</param> /// <returns>Base32-encoded string.</returns> public static string ToString(byte[] bytes) { if (bytes == null) throw new ArgumentNullException(nameof(bytes)); return ToString(bytes, 0, bytes.Length); } /// <summary> /// Encode part of byte array to Base32 string. /// </summary> /// <param name="bytes">Byte array to encode.</param> /// <param name="offset">Encode start index in <paramref name="bytes"/>.</param> /// <param name="count">Number of bytes to encode in <paramref name="bytes"/>.</param> /// <returns>Base32-encoded string.</returns> public static string ToString(byte[] bytes, int offset, int count) { if (bytes == null) throw new ArgumentNullException(nameof(bytes)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); if (offset + count > bytes.Length) throw new ArgumentOutOfRangeException(nameof(count)); if (count == 0) return string.Empty; return BaseNEncoding.Base32.GetString(bytes, offset, count); } /// <summary> /// Encode byte array to Base32 char array. /// </summary> /// <param name="bytes">Byte array to encode.</param> /// <returns>Base32-encoded char array.</returns> public static char[] ToCharArray(byte[] bytes) { if (bytes == null) throw new ArgumentNullException(nameof(bytes)); return ToCharArray(bytes, 0, bytes.Length); } /// <summary> /// Encode part of byte array to Base32 char array. /// </summary> /// <param name="bytes">Byte array to encode.</param> /// <param name="offset">Encode start index in <paramref name="bytes"/>.</param> /// <param name="count">Number of bytes to encode in <paramref name="bytes"/>.</param> /// <returns>Base32-encoded char array.</returns> public static char[] ToCharArray(byte[] bytes, int offset, int count) { if (bytes == null) throw new ArgumentNullException(nameof(bytes)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); if (offset + count > bytes.Length) throw new ArgumentOutOfRangeException(nameof(count)); if (count == 0) return new char[0]; return BaseNEncoding.Base32.GetChars(bytes, offset, count); } /// <summary> /// Decode Base32 char array into byte array. /// </summary> /// <param name="base32Chars">Char array contains Base32 encoded bytes.</param> /// <returns>Decoded bytes.</returns> public static byte[] ToBytes(char[] base32Chars) { if (base32Chars == null) throw new ArgumentNullException(nameof(base32Chars)); return ToBytes(base32Chars, 0, base32Chars.Length); } /// <summary> /// Decode part of Base32 char array into byte array. /// </summary> /// <param name="base32Chars">Char array contains Base32 encoded bytes.</param> /// <param name="offset">Decode start index in <paramref name="base32Chars"/>.</param> /// <param name="count">Number of chars to decode in <paramref name="base32Chars"/>.</param> /// <returns>Decoded bytes.</returns> public static byte[] ToBytes(char[] base32Chars, int offset, int count) { if (base32Chars == null) throw new ArgumentNullException(nameof(base32Chars)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); if (offset + count > base32Chars.Length) throw new ArgumentOutOfRangeException(nameof(count)); if (count == 0) return new byte[0]; return BaseNEncoding.Base32.GetBytes(base32Chars, offset, count); } /// <summary> /// Decode Base32 string into byte array. /// </summary> /// <param name="base32String">Base32 string contains Base32 encoded bytes.</param> /// <returns>Decoded bytes.</returns> public static byte[] ToBytes(string base32String) { if (base32String == null) throw new ArgumentNullException(nameof(base32String)); return ToBytes(base32String, 0, base32String.Length); } /// <summary> /// Decode part of Base32 string into byte array. /// </summary> /// <param name="base32String">Base32 string contains Base32 encoded bytes.</param> /// <param name="offset">Decode start index in <paramref name="base32String"/>.</param> /// <param name="count">Number of chars to decode in <paramref name="base32String"/>.</param> /// <returns>Decoded bytes.</returns> public static byte[] ToBytes(string base32String, int offset, int count) { if (base32String == null) throw new ArgumentNullException(nameof(base32String)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); if (offset + count > base32String.Length) throw new ArgumentOutOfRangeException(nameof(count)); if (count == 0) return new byte[0]; return BaseNEncoding.Base32.GetBytes(base32String, offset, count); } /// <summary> /// Decode Base32 char array (in ASCII encoding) into byte array. /// </summary> /// <param name="base32Chars">Char array contains Base32 encoded bytes.</param> /// <returns>Decoded bytes.</returns> public static byte[] ToBytes(byte[] base32Chars) { if (base32Chars == null) throw new ArgumentNullException(nameof(base32Chars)); return ToBytes(base32Chars, 0, base32Chars.Length); } /// <summary> /// Decode part of Base32 char array (in ASCII encoding) into byte array. /// </summary> /// <param name="base32Chars">Char array contains Base32 encoded bytes.</param> /// <param name="offset">Decode start index in <paramref name="base32Chars"/>.</param> /// <param name="count">Number of chars to decode in <paramref name="base32Chars"/>.</param> /// <returns>Decoded bytes.</returns> public static byte[] ToBytes(byte[] base32Chars, int offset, int count) { if (base32Chars == null) throw new ArgumentNullException(nameof(base32Chars)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); if (offset + count > base32Chars.Length) throw new ArgumentOutOfRangeException(nameof(count)); if (count == 0) return new byte[0]; var encoder = (BaseNEncoder)BaseNEncoding.Base32.GetEncoder(); var outputCount = encoder.GetByteCount(base32Chars, offset, count, flush: true); var output = new byte[outputCount]; encoder.Convert(base32Chars, offset, count, output, 0, outputCount, true, out var inputUsed, out var outputUsed, out _); Debug.Assert(outputUsed == outputCount && inputUsed == count, "outputUsed == outputCount && inputUsed == count"); return output; } } }
41.430168
123
0.703614
[ "MIT" ]
deniszykov/BaseN
src/deniszykov.BaseN/Base32Convert.cs
7,418
C#
public enum ORIPOINT { CENTER, LEFT_UP, LEFT_BOTTOM, RIGHT_BOTTOM, RIGHT_UP, BOTTOM_CENTER, TOP_CENTER, LEFT_CENTER, RIGHT_CENTER }
14
21
0.642857
[ "MIT" ]
Jagerente/GucciGangMod
Source/ORIPOINT.cs
170
C#
// <auto-generated /> using System; using Geonorge.TiltaksplanApi.Infrastructure.DataModel; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Geonorge.TiltaksplanApi.Infrastructure.Migrations { [DbContext(typeof(MeasurePlanContext))] [Migration("20201209102105_RemoveIndexBetweenMeasureAndOrganization")] partial class RemoveIndexBetweenMeasureAndOrganization { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasDefaultSchema("dbo") .HasAnnotation("ProductVersion", "3.1.9") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Geonorge.TiltaksplanApi.Domain.Models.Activity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("ImplementationEnd") .HasColumnType("datetime2"); b.Property<DateTime>("ImplementationStart") .HasColumnType("datetime2"); b.Property<int>("MeasureId") .HasColumnType("int"); b.Property<int>("No") .ValueGeneratedOnAdd() .HasColumnType("int") .HasDefaultValue(0); b.Property<int>("Status") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("MeasureId"); b.ToTable("Activities"); }); modelBuilder.Entity("Geonorge.TiltaksplanApi.Domain.Models.ActivityTranslation", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("ActivityId") .HasColumnType("int"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("LanguageCulture") .IsRequired() .HasColumnType("nvarchar(450)"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("ActivityId"); b.HasIndex("LanguageCulture"); b.ToTable("ActivityTranslations"); }); modelBuilder.Entity("Geonorge.TiltaksplanApi.Domain.Models.Language", b => { b.Property<string>("Culture") .HasColumnType("nvarchar(450)"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Culture"); b.ToTable("Languages"); }); modelBuilder.Entity("Geonorge.TiltaksplanApi.Domain.Models.Measure", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("No") .ValueGeneratedOnAdd() .HasColumnType("int") .HasDefaultValue(0); b.Property<int>("OwnerId") .HasColumnType("int"); b.Property<int?>("Results") .HasColumnType("int"); b.Property<int?>("Status") .HasColumnType("int"); b.Property<int?>("TrafficLight") .HasColumnType("int"); b.Property<int?>("Volume") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("OwnerId"); b.ToTable("Measures"); }); modelBuilder.Entity("Geonorge.TiltaksplanApi.Domain.Models.MeasureTranslation", b => { b.Property<int>("MeasureId") .HasColumnType("int"); b.Property<string>("LanguageCulture") .HasColumnType("nvarchar(450)"); b.Property<string>("Comment") .HasColumnType("nvarchar(max)"); b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Progress") .HasColumnType("nvarchar(max)"); b.HasKey("MeasureId", "LanguageCulture"); b.HasIndex("LanguageCulture"); b.ToTable("MeasureTranslations"); }); modelBuilder.Entity("Geonorge.TiltaksplanApi.Domain.Models.Organization", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<long?>("OrgNumber") .HasColumnType("bigint"); b.HasKey("Id"); b.ToTable("Organizations"); }); modelBuilder.Entity("Geonorge.TiltaksplanApi.Domain.Models.Participant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("ActivityId") .HasColumnType("int"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<int?>("OrganizationId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("ActivityId"); b.HasIndex("OrganizationId"); b.ToTable("Participants"); }); modelBuilder.Entity("Geonorge.TiltaksplanApi.Domain.Models.Activity", b => { b.HasOne("Geonorge.TiltaksplanApi.Domain.Models.Measure", null) .WithMany("Activities") .HasForeignKey("MeasureId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("Geonorge.TiltaksplanApi.Domain.Models.ActivityTranslation", b => { b.HasOne("Geonorge.TiltaksplanApi.Domain.Models.Activity", null) .WithMany("Translations") .HasForeignKey("ActivityId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Geonorge.TiltaksplanApi.Domain.Models.Language", "Language") .WithMany() .HasForeignKey("LanguageCulture") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Geonorge.TiltaksplanApi.Domain.Models.Measure", b => { b.HasOne("Geonorge.TiltaksplanApi.Domain.Models.Organization", "Owner") .WithMany() .HasForeignKey("OwnerId") .OnDelete(DeleteBehavior.NoAction) .IsRequired(); }); modelBuilder.Entity("Geonorge.TiltaksplanApi.Domain.Models.MeasureTranslation", b => { b.HasOne("Geonorge.TiltaksplanApi.Domain.Models.Language", "Language") .WithMany() .HasForeignKey("LanguageCulture") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Geonorge.TiltaksplanApi.Domain.Models.Measure", null) .WithMany("Translations") .HasForeignKey("MeasureId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Geonorge.TiltaksplanApi.Domain.Models.Participant", b => { b.HasOne("Geonorge.TiltaksplanApi.Domain.Models.Activity", null) .WithMany("Participants") .HasForeignKey("ActivityId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Geonorge.TiltaksplanApi.Domain.Models.Organization", "Organization") .WithMany() .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
38.628676
125
0.485771
[ "MIT" ]
kartverket/Geonorge.TiltaksplanApi
src/Geonorge.TiltaksplanApi.Infrastructure/Migrations/20201209102105_RemoveIndexBetweenMeasureAndOrganization.Designer.cs
10,509
C#
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); var app = builder.Build(); // Configure the HTTP request pipeline. app.UseStaticFiles(); app.UseRouting(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
22
55
0.724432
[ "MIT" ]
EricCote/20486D-New
Allfiles/Mod11/Labfiles/01_Library_end/CrossSiteRequestForgeryAttack/Program.cs
354
C#
using System.Diagnostics; using Microsoft.AspNetCore.Mvc; using CoreUIStatic.Models; namespace CoreUIStatic.Controllers { public class CoreUIController : Controller { public IActionResult Index() { return View(); } public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
20.090909
112
0.628959
[ "MIT" ]
mrholek/CoreUI-NET
mvc_Starter/Controllers/CoreUIController.cs
444
C#
using System; #if WINDOWS_PHONE_APP using Windows.UI.Xaml; using Windows.UI.Xaml.Data; #else using System.Windows; using System.Windows.Data; #endif namespace Coligo.Platform.Converters { /// <summary> /// /// </summary> public class BoolToVisibilityInverter : IValueConverter { #if WINDOWS_PHONE_APP /// <summary> /// /// </summary> /// <param name="value"></param> /// <param name="targetType"></param> /// <param name="parameter"></param> /// <param name="language"></param> /// <returns></returns> public object Convert(object value, Type targetType, object parameter, string language) { return null; } /// <summary> /// /// </summary> /// <param name="value"></param> /// <param name="targetType"></param> /// <param name="parameter"></param> /// <param name="language"></param> /// <returns></returns> public object ConvertBack(object value, Type targetType, object parameter, string language) { return null; } #else /// <summary> /// Converts 'true' to Visibility.Visible otherwise Visibility.Collapsed. /// </summary> /// <param name="value"></param> /// <param name="targetType"></param> /// <param name="parameter"></param> /// <param name="culture"></param> /// <returns></returns> public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { bool result=false; if (value is bool) { result = (bool)value; } else if (value is string) { bool.TryParse((string)value, out result); } return result ? Visibility.Collapsed : Visibility.Visible; } /// <summary> /// Converts Visibility.Visible to 'true' otherwise 'false'. /// </summary> /// <param name="value"></param> /// <param name="targetType"></param> /// <param name="parameter"></param> /// <param name="culture"></param> /// <returns></returns> public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { bool result = false; if (value is Visibility) { result = (Visibility)value == Visibility.Collapsed; } else if (value is string) { Visibility parsed; Enum.TryParse<Visibility>((string)value, false, out parsed); result = parsed == Visibility.Collapsed; } return result; } #endif } }
28.50495
131
0.531087
[ "MIT" ]
johnds1974/Coligo.net
Src/Coligo.Platform/Converters/BoolToVisibilityInverter.cs
2,879
C#
using System; namespace dnsl48.SGF.Attributes { /// <summary> /// The label of a subject property. /// The label is the identity of the property defined by the SGF standard /// and being used in the SGF document as is. It is also being used by the /// parser to identify the property and apply the appropriate parsing logic /// to its values and parameters. /// </summary> /// <example> /// Smart Game Format defines the property "B" as "Execute a black move". /// Its label in this case is "B" and the description is "Execute a black move". /// See: https://www.red-bean.com/sgf/properties.html#B /// <see cref="dnsl48.SGF.Model.Property.Move.BlackMove" /> /// </example> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = true)] [Serializable] public class LabelAttribute : Attribute { private string _value; /// <summary> /// Initialize the attribute with the subject label /// </summary> /// <param name="value">The label string representation</param> public LabelAttribute(string value) => _value = value; /// <inheritdoc /> public override string ToString() { return _value; } } }
34.621622
88
0.631538
[ "Apache-2.0", "MIT" ]
dnsl48/sharp-sgf-tools
SGF/src/Attributes/LabelAttribute.cs
1,281
C#
using System; using System.Collections.Generic; using System.Linq; namespace Newcats.JobManager.Common.Util.Helper.CronHelper { public class TimeZoneUtil { private static readonly Dictionary<string, string> timeZoneIdAliases = new Dictionary<string, string>(); static TimeZoneUtil() { // Azure has had issues with having both formats timeZoneIdAliases["UTC"] = "Coordinated Universal Time"; timeZoneIdAliases["Coordinated Universal Time"] = "UTC"; // Mono differs in naming too... timeZoneIdAliases["Central European Standard Time"] = "CET"; timeZoneIdAliases["CET"] = "Central European Standard Time"; timeZoneIdAliases["Eastern Standard Time"] = "US/Eastern"; timeZoneIdAliases["US/Eastern"] = "Eastern Standard Time"; timeZoneIdAliases["Central Standard Time"] = "US/Central"; timeZoneIdAliases["US/Central"] = "Central Standard Time"; timeZoneIdAliases["US Central Standard Time"] = "US/Indiana-Stark"; timeZoneIdAliases["US/Indiana-Stark"] = "US Central Standard Time"; timeZoneIdAliases["Mountain Standard Time"] = "US/Mountain"; timeZoneIdAliases["US/Mountain"] = "Mountain Standard Time"; timeZoneIdAliases["US Mountain Standard Time"] = "US/Arizona"; timeZoneIdAliases["US/Arizona"] = "US Mountain Standard Time"; timeZoneIdAliases["Pacific Standard Time"] = "US/Pacific"; timeZoneIdAliases["US/Pacific"] = "Pacific Standard Time"; timeZoneIdAliases["Alaskan Standard Time"] = "US/Alaska"; timeZoneIdAliases["US/Alaska"] = "Alaskan Standard Time"; timeZoneIdAliases["Hawaiian Standard Time"] = "US/Hawaii"; timeZoneIdAliases["US/Hawaii"] = "Hawaiian Standard Time"; timeZoneIdAliases["China Standard Time"] = "Asia/Beijing"; timeZoneIdAliases["Asia/Shanghai"] = "China Standard Time"; timeZoneIdAliases["Asia/Beijing"] = "China Standard Time"; timeZoneIdAliases["Pakistan Standard Time"] = "Asia/Karachi"; timeZoneIdAliases["Asia/Karachi"] = "Pakistan Standard Time"; } public static Func<string, TimeZoneInfo> CustomResolver = id => null; /// <summary> /// TimeZoneInfo.ConvertTime is not supported under mono /// </summary> /// <param name="dateTimeOffset"></param> /// <param name="timeZoneInfo"></param> /// <returns></returns> public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo timeZoneInfo) { return TimeZoneInfo.ConvertTime(dateTimeOffset, timeZoneInfo); } /// <summary> /// TimeZoneInfo.GetUtcOffset(DateTimeOffset) is not supported under mono /// </summary> /// <param name="dateTimeOffset"></param> /// <param name="timeZoneInfo"></param> /// <returns></returns> public static TimeSpan GetUtcOffset(DateTimeOffset dateTimeOffset, TimeZoneInfo timeZoneInfo) { return timeZoneInfo.GetUtcOffset(dateTimeOffset); } public static TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfo timeZoneInfo) { // Unlike the default behavior of TimeZoneInfo.GetUtcOffset, it is prefered to choose // the DAYLIGHT time when the input is ambiguous, because the daylight instance is the // FIRST instance, and time moves in a forward direction. TimeSpan offset = timeZoneInfo.IsAmbiguousTime(dateTime) ? timeZoneInfo.GetAmbiguousTimeOffsets(dateTime).Max() : timeZoneInfo.GetUtcOffset(dateTime); return offset; } /// <summary> /// Tries to find time zone with given id, has ability do some fallbacks when necessary. /// </summary> /// <param name="id">System id of the time zone.</param> /// <returns></returns> public static TimeZoneInfo FindTimeZoneById(string id) { TimeZoneInfo info = null; try { info = TimeZoneInfo.FindSystemTimeZoneById(id); } catch (TimeZoneNotFoundException ex) { if (timeZoneIdAliases.TryGetValue(id, out var aliasedId)) { try { info = TimeZoneInfo.FindSystemTimeZoneById(aliasedId); } catch { } } if (info == null) { info = CustomResolver(id); } if (info == null) { // we tried our best throw new TimeZoneNotFoundException( $"Could not find time zone with id {id}, consider using Quartz.Plugins.TimeZoneConverter for resolving more time zones ids", ex); } } return info; } } }
39.06015
148
0.580558
[ "MIT" ]
newcatshuang/JobManager
src/Newcats.JobManager.Common/Util/Helper/CronHelper/TimeZoneUtil.cs
5,197
C#
using System.Linq; using System.Text; using System.Threading.Tasks; using Flurl.Http; using Newtonsoft.Json; namespace Tool { partial class Program { static async Task<string[]> GetJdCode(int id) { var sender = await $"https://union.jd.com/api/apiDoc/apiDocInfo?apiId={id}".PostJsonAsync(new object()); var @string = await sender.Content.ReadAsStringAsync(); var root = JsonConvert.DeserializeObject<JdRootObject>(@string); var className = string.Join("", root.Data.ApiName.Split('.').Select(UpperFirst)); var code = new StringBuilder(); code.AppendLine("using System.Threading.Tasks;"); code.AppendLine(); code.AppendLine("namespace Jd.Sdk.Apis"); code.AppendLine("{"); code.AppendLine(" /// <summary>"); code.AppendLine($" /// {root.Data.Caption}--请求参数"); code.AppendLine($" /// {root.Data.Description.Trim()}"); code.AppendLine($" /// {root.Data.ApiName.Trim()}"); code.AppendLine($" /// https://union.jd.com/openplatform/api/{id}"); code.AppendLine(" /// </summary>"); code.AppendLine($" public class {className}Request : JdBaseRequest"); code.AppendLine(" {"); code.AppendLine($" public {className}Request() {{ }}"); code.AppendLine(); code.AppendLine($" public {className}Request(string appKey, string appSecret, string accessToken = null) : base(appKey, appSecret, accessToken) {{ }}"); code.AppendLine(); code.AppendLine($" protected override string Method => \"{root.Data.ApiName}\";"); code.AppendLine(); var firstReq = root.Data.PLists.FirstOrDefault(x => x.DataType.EndsWith("Req")); if (firstReq == null) { firstReq = root.Data.PLists.First(x => x.DataName != "ROOT"); code.AppendLine(" /// <summary>"); code.AppendLine($" /// {(firstReq.IsRequired.Trim() == "true" ? "必填" : "不必填")}"); code.AppendLine($" /// 描述:{firstReq.Description.Trim()}"); code.AppendLine($" /// 例如:{firstReq.SampleValue.Trim()}"); code.AppendLine(" /// </summary>"); code.AppendLine($" public {SwitchType(firstReq.DataType)} {UpperFirst(firstReq.DataName)} {{ get; set; }}"); code.AppendLine(); } code.AppendLine($" protected override string ParamName => \"{firstReq.DataName}\";"); code.AppendLine(); var isPage = root.Data.SLists.Any(x => x.DataName == "hasMore") ? "JdBasePageResponse" : "JdBaseResponse"; var firstData = root.Data.SLists.FirstOrDefault(x => x.DataName == "data"); var isArray = string.Empty; if (firstData != default) { isArray = firstData.DataType.EndsWith("[]") ? $"<{className}Response[]>" : $"<{className}Response>"; } else { } code.AppendLine($" public async Task<{isPage}{isArray}> InvokeAsync()"); code.AppendLine($" => await PostAsync<{isPage}{isArray}>();"); code.AppendLine(); foreach (var item in root.Data.PLists.Where(x => x.DataName != "ROOT" && x.DataName != firstReq.DataName)) { GetJdParamStereoscopic(item, root.Data.PLists, className, " ", true, ref code); } code.AppendLine(" }"); code.AppendLine(); code.AppendLine(); code.AppendLine(); if (firstData != default) { code.AppendLine(" /// <summary>"); code.AppendLine($" /// {root.Data.Caption}--响应参数"); code.AppendLine($" /// {root.Data.Description.Trim()}"); code.AppendLine($" /// {root.Data.ApiName.Trim()}"); code.AppendLine(" /// </summary>"); code.AppendLine($" public class {className}Response"); code.AppendLine(" {"); foreach (var item in root.Data.SLists.Where(x => x.ParentId == firstData.NodeId)) { GetJdParamStereoscopic(item, root.Data.SLists, className, " ", false, ref code); } code.AppendLine(" }"); } else { code.AppendLine(" //--------------------------------------"); code.AppendLine(" // 返回值没有data内容,直接使用基础响应基类"); code.AppendLine(" //--------------------------------------"); } code.AppendLine("}"); return code.ToString().Split("\r\n"); } static void GetJdParamStereoscopic( JdPlist item, JdPlist[] all, string className, string spacing, bool isRequest, ref StringBuilder code) { code.AppendLine($"{spacing}/// <summary>"); if (isRequest) { code.AppendLine($"{spacing}/// {(item.IsRequired.Trim() == "true" ? "必填" : "不必填")}"); } code.AppendLine($"{spacing}/// 描述:{item.Description}"); code.AppendLine($"{spacing}/// 例如:{item.SampleValue}"); code.AppendLine($"{spacing}/// </summary>"); var currentNodes = all.Where(x => x.ParentId == item.NodeId).ToArray(); if (currentNodes.Any()) { var tempName = item.DataType.Replace("[]", "").ToLower(); var tempSymbol = item.DataType.EndsWith("[]") ? "[]" : ""; code.AppendLine($"{spacing}public {className}_{UpperFirst(tempName)}{tempSymbol} {UpperFirst(item.DataName)} {{ get; set; }}"); code.AppendLine($"{spacing}/// <summary>"); code.AppendLine($"{spacing}/// {item.Description}"); code.AppendLine($"{spacing}/// </summary>"); code.AppendLine($"{spacing}public class {className}_{UpperFirst(tempName)}"); code.AppendLine($"{spacing}{{"); foreach (var that in currentNodes) { GetJdParamStereoscopic(that, all, className, spacing + " ", isRequest, ref code); } code.AppendLine($"{spacing}}}"); } else { code.AppendLine($"{spacing}public {SwitchType(item.DataType)} {UpperFirst(item.DataName)} {{ get; set; }}"); } } } public class JdRootObject { public JdData Data { get; set; } } public class JdData { public string ApiName { get; set; } public string Caption { get; set; } public string Description { get; set; } public JdPlist[] PLists { get; set; } public JdPlist[] SLists { get; set; } } public class JdPlist { public int NodeId { get; set; } public int? ParentId { get; set; } public string DataName { get; set; } public string DataType { get; set; } public string IsRequired { get; set; } public string SampleValue { get; set; } public string Description { get; set; } } public class JdAllApi { public JdDatum[] Data { get; set; } } public class JdDatum { public JdApi[] Apis { get; set; } } public class JdApi { public int ApiId { get; set; } public string ApiName { get; set; } } }
40.91623
171
0.498273
[ "Apache-2.0" ]
asine/JD_PDD.SDK.CSharpe
src/Tool/JdRootobject.cs
7,911
C#
using System; using TrueCraft.API.Logic; namespace TrueCraft.Core.Logic.Blocks { public class WoodBlock : BlockProvider, IBurnableItem { public enum WoodType { Oak = 0, Spruce = 1, Birch = 2 } public static readonly byte BlockID = 0x11; public override byte ID { get { return 0x11; } } public override double BlastResistance { get { return 10; } } public override double Hardness { get { return 2; } } public override byte Luminance { get { return 0; } } public override string DisplayName { get { return "Wood"; } } public override bool Flammable { get { return true; } } public TimeSpan BurnTime { get { return TimeSpan.FromSeconds(15); } } public override SoundEffectClass SoundEffect { get { return SoundEffectClass.Wood; } } public override Tuple<int, int> GetTextureMap(byte metadata) { return new Tuple<int, int>(4, 1); } } }
24.8
77
0.550179
[ "MIT" ]
BinaryGears/TrueCraft
TrueCraft.Core/Logic/Blocks/WoodBlock.cs
1,116
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using manager.ioc; namespace attributeSystem.rts.twod { [System.Serializable] public class AttributesDictionary : CustomDict<string, IamAttribute> { public AttributesDictionary() : base() { } } [System.Serializable] public class AttributeContainerState { public Stats StatsBase = new Stats(); public enum ArmorTypes { Unarmed, BuildingLight, Building, BuildingHeavy, KavalleryLight, Kavallery, KavalleryHeavy, InfantryLight, Infantry, InfantryHeavy, Siege, Hero, } public enum DamageTypes { Magic, Unarmed, Blunt, Pierce, Slash, Siege, Hero, } public enum Boni { Health, Strength, HealthRegen, Mana, Magic, Intelligence, ManaRegen, Rage, Attack, Energy, WalkSpeed, RunSpeed, Dexterity, Armor, MagicResistence } [System.Serializable] public class Stats { public Basis basis; public FlatBonus flatBonus; public PercentageBonus percentageBonus; public ArmorTypes ArmorType; public DamageTypes DamageType; public uint current_Health; public uint current_Strength; public uint current_HealthRegen; public uint current_Mana; public uint current_Magic; public uint current_Intelligence; public uint current_ManaRegen; public uint current_Rage; public uint current_Attack; public uint current_Energy; public uint current_WalkSpeed; public uint current_RunSpeed; public uint current_Dexterity; public uint current_Armor; public uint current_MagicResistence; public Stats(Basis _BasisStats, FlatBonus _FlatBoni, PercentageBonus _PercentageBoni, ArmorTypes _ArmorType, DamageTypes _DamageType) { basis = _BasisStats; flatBonus = _FlatBoni; percentageBonus = _PercentageBoni; ArmorType = _ArmorType; DamageType = _DamageType; this.current_Health = max_Health; this.current_Strength = max_Strength; this.current_HealthRegen = max_HealthRegen; this.current_Mana = max_Mana; this.current_Magic = max_Magic; this.current_Intelligence = max_Intelligence; this.current_ManaRegen = max_ManaRegen; this.current_Rage = max_Rage; this.current_Attack = max_Attack; this.current_Energy = max_Energy; this.current_WalkSpeed = max_WalkSpeed; this.current_RunSpeed = max_RunSpeed; this.current_Dexterity = max_Dexterity; this.current_Armor = max_Armor; this.current_MagicResistence = max_MagicResistence; } public Stats() : this(new Basis(), new FlatBonus(), new PercentageBonus(), ArmorTypes.Infantry, DamageTypes.Slash) { } public Stats(Basis _BasisStats, ArmorTypes _ArmorType, DamageTypes _DamageType) : this(_BasisStats, new FlatBonus(), new PercentageBonus(), _ArmorType, _DamageType) { } public uint max_Health { get => (uint)((basis.Health + flatBonus.Health) * percentageBonus.Health); } public uint max_Strength { get => (uint)((basis.Strength + flatBonus.Strength) * percentageBonus.Strength); } public uint max_HealthRegen { get => (uint)((basis.HealthRegen + flatBonus.HealthRegen) * percentageBonus.HealthRegen); } public uint max_Mana { get => (uint)((basis.Mana + flatBonus.Mana) * percentageBonus.Mana); } public uint max_Magic { get => (uint)((basis.Magic + flatBonus.Magic) * percentageBonus.Magic); } public uint max_Intelligence { get => (uint)((basis.Intelligence + flatBonus.Intelligence) * percentageBonus.Intelligence); } public uint max_ManaRegen { get => (uint)((basis.ManaRegen + flatBonus.ManaRegen) * percentageBonus.ManaRegen); } public uint max_Rage { get => (uint)((basis.Rage + flatBonus.Rage) * percentageBonus.Rage); } public uint max_Attack { get => (uint)((basis.Attack + flatBonus.Attack) * percentageBonus.Attack); } public uint max_Energy { get => (uint)((basis.Energy + flatBonus.Energy) * percentageBonus.Energy); } public uint max_WalkSpeed { get => (uint)((basis.WalkSpeed + flatBonus.WalkSpeed) * percentageBonus.WalkSpeed); } public uint max_RunSpeed { get => (uint)((basis.RunSpeed + flatBonus.RunSpeed) * percentageBonus.RunSpeed); } public uint max_Dexterity { get => (uint)((basis.Dexterity + flatBonus.Dexterity) * percentageBonus.Dexterity); } public uint max_Armor { get => (uint)((basis.Armor + flatBonus.Armor) * percentageBonus.Armor); } public uint max_MagicResistence { get => (uint)((basis.MagicResistence + flatBonus.MagicResistence) * percentageBonus.MagicResistence); } } [System.Serializable] public class Basis { public uint Health = 1000; public uint Strength = 0; public uint HealthRegen = 1; public uint Mana = 400; public uint Magic = 0; public uint Intelligence = 0; public uint ManaRegen = 1; public uint Rage = 1000; public uint Attack = 5; public uint Energy = 1000; public uint WalkSpeed = 100; public uint RunSpeed = 500; public uint Dexterity = 0; public uint Armor = 0; public uint MagicResistence = 0; public Basis(uint _Health, uint _Strength, uint _HealthRegen, uint _Mana, uint _Magic, uint _Intelligence, uint _ManaRegen, uint _Rage, uint _Attack, uint _Energy, uint _WalkSpeed, uint _RunSpeed, uint _Dexterity, uint _Armor, uint _MagicResistence) { this.Health = _Health; this.Strength = _Strength; this.HealthRegen = _HealthRegen; this.Mana = _Mana; this.Magic = _Magic; this.Intelligence = _Intelligence; this.ManaRegen = _ManaRegen; this.Rage = _Rage; this.Attack = _Attack; this.Energy = _Energy; this.WalkSpeed = _WalkSpeed; this.RunSpeed = _RunSpeed; this.Dexterity = _Dexterity; this.Armor = _Armor; this.MagicResistence = _MagicResistence; } public Basis() : this(1000, 5, 0, 0, 0, 5, 0, 0, 5, 0, 200, 500, 5, 0, 0) { } public Basis(uint _Strength, uint _Intelligence, uint _Dexterity) : this(1000, _Strength, 0, 0, 0, _Intelligence, 0, 0, 5, 0, 200, 500, _Dexterity, 0, 0) { } } [System.Serializable] public class FlatBonus { Dictionary<string, int> health; Dictionary<string, int> strength; Dictionary<string, int> healthRegen; Dictionary<string, int> mana; Dictionary<string, int> magic; Dictionary<string, int> intelligence; Dictionary<string, int> manaRegen; Dictionary<string, int> rage; Dictionary<string, int> attack; Dictionary<string, int> energy; Dictionary<string, int> walkSpeed; Dictionary<string, int> runSpeed; Dictionary<string, int> dexterity; Dictionary<string, int> armor; Dictionary<string, int> magicResistence; public FlatBonus() { this.health = new Dictionary<string, int>(); this.strength = new Dictionary<string, int>(); this.healthRegen = new Dictionary<string, int>(); this.mana = new Dictionary<string, int>(); this.magic = new Dictionary<string, int>(); this.intelligence = new Dictionary<string,int>(); this.manaRegen = new Dictionary<string, int>(); this.rage = new Dictionary<string, int>(); this.attack = new Dictionary<string, int>(); this.energy = new Dictionary<string, int>(); this.walkSpeed = new Dictionary<string, int>(); this.runSpeed = new Dictionary<string, int>(); this.dexterity = new Dictionary<string, int>(); this.armor = new Dictionary<string, int>(); this.magicResistence = new Dictionary<string, int>(); } public int Health { get => sumOfBoni(health); } public int Strength { get => sumOfBoni(strength); } public int HealthRegen { get => sumOfBoni(healthRegen); } public int Mana { get => sumOfBoni(mana); } public int Magic { get => sumOfBoni(magic); } public int Intelligence { get => sumOfBoni(intelligence); } public int ManaRegen { get => sumOfBoni(manaRegen); } public int Rage { get => sumOfBoni(rage); } public int Attack { get => sumOfBoni(attack); } public int Energy { get => sumOfBoni(energy); } public int WalkSpeed { get => sumOfBoni(walkSpeed); } public int RunSpeed { get => sumOfBoni(runSpeed); } public int Dexterity { get => sumOfBoni(dexterity); } public int Armor { get => sumOfBoni(armor); } public int MagicResistence { get => sumOfBoni(magicResistence); } int sumOfBoni(Dictionary<string, int> _BonusValues) { int result = 0; foreach (KeyValuePair<string, int> value in _BonusValues) { result += value.Value; } return result; } } [System.Serializable] public class PercentageBonus { Dictionary<string, float> health; Dictionary<string, float> strength; Dictionary<string, float> healthRegen; Dictionary<string, float> mana; Dictionary<string, float> intelligence; Dictionary<string, float> manaRegen; Dictionary<string, float> magic; Dictionary<string, float> rage; Dictionary<string, float> attack; Dictionary<string, float> energy; Dictionary<string, float> walkSpeed; Dictionary<string, float> runSpeed; Dictionary<string, float> dexterity; Dictionary<string, float> armor; Dictionary<string, float> magicResistence; public PercentageBonus() { this.health = new Dictionary<string, float>(); this.strength = new Dictionary<string, float>(); this.healthRegen = new Dictionary<string, float>(); this.mana = new Dictionary<string, float>(); this.magic = new Dictionary<string, float>(); this.intelligence = new Dictionary<string, float>(); this.manaRegen = new Dictionary<string, float>(); this.rage = new Dictionary<string, float>(); this.attack = new Dictionary<string, float>(); this.energy = new Dictionary<string, float>(); this.walkSpeed = new Dictionary<string, float>(); this.runSpeed = new Dictionary<string, float>(); this.dexterity = new Dictionary<string, float>(); this.armor = new Dictionary<string, float>(); this.magicResistence = new Dictionary<string, float>(); } public float Health { get => concatinatePercentageBoni(health); } public float Strength { get => concatinatePercentageBoni(strength);} public float HealthRegen { get => concatinatePercentageBoni(healthRegen);} public float Mana { get => concatinatePercentageBoni(mana); } public float Magic { get => concatinatePercentageBoni(magic); } public float Intelligence { get => concatinatePercentageBoni(intelligence);} public float ManaRegen { get => concatinatePercentageBoni(manaRegen);} public float Rage { get => concatinatePercentageBoni(rage); } public float Attack { get => concatinatePercentageBoni(attack); } public float Energy { get => concatinatePercentageBoni(energy); } public float WalkSpeed { get => concatinatePercentageBoni(walkSpeed); } public float RunSpeed { get => concatinatePercentageBoni(runSpeed); } public float Dexterity { get => concatinatePercentageBoni(dexterity); } public float Armor { get => concatinatePercentageBoni(armor); } public float MagicResistence { get => concatinatePercentageBoni(magicResistence); } private void AddBonusIntoDict(string _BonusKey, float _Bonus, Dictionary<string, float> _Dict) { _Dict.Add(_BonusKey, _Bonus); } private void RemoveBonusFromDict(string _BonusKey, Dictionary<string, float> _Dict) { _Dict.Remove(_BonusKey); } /// <summary> /// Add a value from 1.0f and above for buff and a value between 0.0f and 1.0f for debuff. /// 0.2 == a debuff of 20% == 80% of current value /// 1.2 == a 20% buff == 120% of current value /// Adding severall buffs and debuffs scales cummulative /// </summary> /// <param name="_Type"></param> /// <param name="_BonusKey"></param> /// <param name="_Bonus"></param> public void AddBonus(Boni _Type, string _BonusKey, float _Bonus) { switch (_Type) { case Boni.Health: this.AddBonusIntoDict(_BonusKey, _Bonus, health); break; case Boni.Strength: this.AddBonusIntoDict(_BonusKey, _Bonus, strength); break; case Boni.HealthRegen: this.AddBonusIntoDict(_BonusKey, _Bonus, healthRegen); break; case Boni.Mana: this.AddBonusIntoDict(_BonusKey, _Bonus, mana); break; case Boni.Magic: this.AddBonusIntoDict(_BonusKey, _Bonus, magic); break; case Boni.Intelligence: this.AddBonusIntoDict(_BonusKey, _Bonus, intelligence); break; case Boni.ManaRegen: this.AddBonusIntoDict(_BonusKey, _Bonus, manaRegen); break; case Boni.Rage: this.AddBonusIntoDict(_BonusKey, _Bonus, rage); break; case Boni.Attack: this.AddBonusIntoDict(_BonusKey, _Bonus, attack); break; case Boni.Energy: this.AddBonusIntoDict(_BonusKey, _Bonus, energy); break; case Boni.WalkSpeed: this.AddBonusIntoDict(_BonusKey, _Bonus, walkSpeed); break; case Boni.RunSpeed: this.AddBonusIntoDict(_BonusKey, _Bonus, runSpeed); break; case Boni.Dexterity: this.AddBonusIntoDict(_BonusKey, _Bonus, dexterity); break; case Boni.Armor: this.AddBonusIntoDict(_BonusKey, _Bonus, armor); break; case Boni.MagicResistence: this.AddBonusIntoDict(_BonusKey, _Bonus, magicResistence); break; default: break; } } public void RemoveBonus(Boni _Type, string _BonusKey, float _Bonus) { switch (_Type) { case Boni.Health: this.RemoveBonusFromDict(_BonusKey, health); break; case Boni.Strength: this.RemoveBonusFromDict(_BonusKey, strength); break; case Boni.HealthRegen: this.RemoveBonusFromDict(_BonusKey, healthRegen); break; case Boni.Mana: this.RemoveBonusFromDict(_BonusKey, mana); break; case Boni.Magic: this.RemoveBonusFromDict(_BonusKey, magic); break; case Boni.Intelligence: this.RemoveBonusFromDict(_BonusKey, intelligence); break; case Boni.ManaRegen: this.RemoveBonusFromDict(_BonusKey, manaRegen); break; case Boni.Rage: this.RemoveBonusFromDict(_BonusKey, rage); break; case Boni.Attack: this.RemoveBonusFromDict(_BonusKey, attack); break; case Boni.Energy: this.RemoveBonusFromDict(_BonusKey, energy); break; case Boni.WalkSpeed: this.RemoveBonusFromDict(_BonusKey, walkSpeed); break; case Boni.RunSpeed: this.RemoveBonusFromDict(_BonusKey, runSpeed); break; case Boni.Dexterity: this.RemoveBonusFromDict(_BonusKey, dexterity); break; case Boni.Armor: this.RemoveBonusFromDict(_BonusKey, armor); break; case Boni.MagicResistence: this.RemoveBonusFromDict(_BonusKey, magicResistence); break; default: break; } } float concatinatePercentageBoni(Dictionary<string, float> _BonusValues) { float result = 1f; foreach (KeyValuePair<string, float> percent in _BonusValues) { if(percent.Value < 1.0f) { float debuff = 1.0f - percent.Value; // 0.0f to 0.99f debuff inverted value for better usage result *= debuff; } else { result *= percent.Value; // 1.0f or higher for buff } } return result; } } } public class AttributesContainer : MonoBehaviour { public AttributeContainerState State = new AttributeContainerState(); // command queue to execute dictionary public Queue<string> Commands = new Queue<string>(); [Header("Active Attributes e.g.abilities and spells")] public AttributesDictionary AttributesActives; // active usable like walk run cast attack stuff like this [Header("Passive Attributes e.g. Auras/Debuffs and damage calculators")] public AttributesDictionary AttributesPassives; // like buffs debuffs attributes like bleeding or maybe the calculation how damage is handled private List<string> removalListForPassives; public void addActive(string key, IamAttribute _Value) { // TODO } public void addPassive(string key, IamAttribute _Value) { // TODO } public void appendCommand(string appendedCommand) { // with shift then or something Commands.Enqueue(appendedCommand); } public void changeCommand(string newCommand) { // a new command to clear old ones Commands.Clear(); Commands.Enqueue(newCommand); } public void appendCommands(string[] appendedCommands) { // with shift then or something foreach (string command in appendedCommands) { Commands.Enqueue(command); } } public void changeCommands(string[] newCommands) { // a new command to clear old ones Commands.Clear(); foreach (string command in newCommands) { Commands.Enqueue(command); } } void handleActives() { if (Commands.Count > 0) { AttributesActives.TryGetValue(Commands.Peek(), out IamAttribute attribute); AttributeState state = attribute.UpdateLogic(this); switch (state) { case AttributeState.Done: { Commands.Dequeue(); break; } case AttributeState.InProgress: { break; } case AttributeState.Loop: { break; } default: break; } } } void handlePassives() { foreach (string attributeName in AttributesPassives.Keys) { IamAttribute temp; AttributesPassives.TryGetValue(attributeName, out temp); AttributeState state = temp.UpdateLogic(this); switch (state) { case AttributeState.Done: { removalListForPassives.Add(attributeName); break; } case AttributeState.InProgress: { break; } case AttributeState.Loop: { break; } default: break; } } foreach (string name in removalListForPassives) { AttributesPassives.Remove(name); } } void Update() { handleActives(); handlePassives(); } } }
40.371186
176
0.516436
[ "Apache-2.0" ]
rufreakde/attributeSystem.rts.twod
code/AttributesContainer.cs
23,821
C#
using System; using System.Threading.Tasks; using Dgraph.Transactions; using FluentAssertions; using FluentResults; using Grpc.Core; using NSubstitute; using NUnit.Framework; namespace Dgraph.tests.Transactions { public class TransactionFixture : TransactionFixtureBase { [Test] public async Task All_FailIfAlreadyCommitted() { var client = Substitute.For<IDgraphClientInternal>(); var txn = new Transaction(client); await txn.Commit(); var tests = GetAllTestFunctions(txn); foreach (var test in tests) { var result = await test(); result.IsFailed.Should().BeTrue(); } } [Test] public async Task All_FailIfDiscarded() { var client = Substitute.For<IDgraphClientInternal>(); var txn = new Transaction(client); await txn.Discard(); var tests = GetAllTestFunctions(txn); foreach (var test in tests) { var result = await test(); result.IsFailed.Should().BeTrue(); } } [Test] public void All_ExceptionIfDisposed() { var client = Substitute.For<IDgraphClientInternal>(); var txn = new Transaction(client); txn.Dispose(); var tests = GetAllTestFunctions(txn); foreach (var test in tests) { test.Should().Throw<ObjectDisposedException>(); } } [Test] public async Task All_FailIfTransactionError() { // force transaction into error state var client = Substitute.For<IDgraphClientInternal>(); client.DgraphExecute( Arg.Any<Func<Api.Dgraph.DgraphClient, Task<Result<Response>>>>(), Arg.Any<Func<RpcException, Result<Response>>>()).Returns( Results.Fail(new ExceptionalError( new RpcException(new Status(), "Something failed")))); var txn = new Transaction(client); var req = new RequestBuilder(). WithMutations(new MutationBuilder{ SetJson = "json" }); await txn.Mutate(req); var tests = GetAllTestFunctions(txn); foreach (var test in tests) { var result = await test(); result.IsFailed.Should().BeTrue(); } } } }
31.151899
81
0.558716
[ "Apache-2.0" ]
Aaronmsv/dgraph.net
source/Dgraph.tests/Transactions/TransactionFixture.cs
2,461
C#
using CleanArchitectureExample.Domain.Entities; using CleanArchitectureExample.Domain.Interfaces.Persistence.Repositories; using MediatR; using System; using System.Threading; using System.Threading.Tasks; namespace CleanArchitectureExample.Domain.RequestHandlers.AuthorsHandlers.Commands.AddAuthor { public class AddAuthorCommandHandler : IRequestHandler<AddAuthorCommand, AddAuthorCommandResponseViewModel> { private readonly IAuthorRepository _authorRepository; public AddAuthorCommandHandler(IAuthorRepository authorRepository) { _authorRepository = authorRepository; } public async Task<AddAuthorCommandResponseViewModel> Handle(AddAuthorCommand request, CancellationToken cancellationToken) { AddAuthorCommandResponseViewModel response = new AddAuthorCommandResponseViewModel(); Author author = new Author(Guid.NewGuid(), request.Name); if (!author.Validate()) return response; await _authorRepository.AddAuthor(author); response.AuthorId = author.AuthorId; response.Name = author.Name; return response; } } }
33.444444
130
0.723422
[ "MIT" ]
andresantarosa/CleanArchitectureExample
CleanArchitectureExample.Domain/RequestHandlers/AuthorsHandlers/Commands/AddAuthor/AddAuthorCommandHandler.cs
1,206
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34209 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ColorPicker.Demo.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ColorPicker.Demo.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
43.671875
182
0.613953
[ "MIT" ]
ChristianGreiner/bridge-hub
src/ColorPickerLibrary/ColorPicker.Demo/Properties/Resources.Designer.cs
2,797
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Options; using SendGrid; using SendGrid.Helpers.Mail; namespace WebPWrecover.Services { // This class is used by the application to send email for account confirmation and password reset. // For more details see https://go.microsoft.com/fwlink/?LinkID=532713 public class EmailSender : IEmailSender { public EmailSender(IOptions<AuthMessageSenderOptions> optionsAccessor) { Options = optionsAccessor.Value; } public AuthMessageSenderOptions Options { get; } public Task SendEmailAsync(string email, string subject, string message) { return Execute(Options.SendGridKey, subject, message, email); } public Task Execute(string apikey, string subject, string message, string email) { var client = new SendGridClient(apikey); var msg = new SendGridMessage() { From=new EmailAddress("953917332@qq.com"), Subject=subject, PlainTextContent=message, HtmlContent=message }; msg.AddTo(new EmailAddress(email)); return client.SendEmailAsync(msg); } } }
32.619048
104
0.623358
[ "Apache-2.0" ]
hangyejiadao/AspNetCore
WebPWrecover/WebPWrecover/Services/EmailSender.cs
1,370
C#
// ----------------------------------------------------------------------- // <copyright file="Switch.cs" company="Ubiquity.NET Contributors"> // Copyright (c) Ubiquity.NET Contributors. All rights reserved. // </copyright> // ----------------------------------------------------------------------- using System; using Ubiquity.NET.Llvm.Interop; using Ubiquity.NET.Llvm.Values; using static Ubiquity.NET.Llvm.Interop.NativeMethods; namespace Ubiquity.NET.Llvm.Instructions { /// <summary>Switch instruction</summary> public class Switch : Terminator { /// <summary>Gets the default <see cref="BasicBlock"/> for the switch</summary> public BasicBlock Default => BasicBlock.FromHandle( LLVMGetSwitchDefaultDest( ValueHandle ).ThrowIfInvalid( ) )!; /// <summary>Adds a new case to the <see cref="Switch"/> instruction</summary> /// <param name="onVal">Value for the case to match</param> /// <param name="destination">Destination <see cref="BasicBlock"/> if the case matches</param> public void AddCase( Value onVal, BasicBlock destination ) { if( onVal == null ) { throw new ArgumentNullException( nameof( onVal ) ); } if( destination == null ) { throw new ArgumentNullException( nameof( destination ) ); } LLVMAddCase( ValueHandle, onVal.ValueHandle, destination.BlockHandle ); } internal Switch( LLVMValueRef valueRef ) : base( valueRef ) { } } }
33.957447
121
0.561404
[ "Apache-2.0" ]
UbiquityDotNET/Llvm.NET
src/Ubiquity.NET.Llvm/Instructions/Switch.cs
1,598
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.Json; using System.Threading.Tasks; using GloboCrypto.Models.Data; using GloboCrypto.Models.Notifications; using GloboCrypto.WebAPI.Services.Coins; using GloboCrypto.WebAPI.Services.Data; using GloboCrypto.WebAPI.Services.Events; using WebPush; namespace GloboCrypto.WebAPI.Services.Notifications { public class NotificationService : INotificationService { private readonly ILocalDbService LocalDb; private readonly IEventService EventService; private readonly ICoinService CoinService; public NotificationService(ILocalDbService localDb, IEventService eventService, ICoinService coinService) { LocalDb = localDb; EventService = eventService; CoinService = coinService; } public async Task SendAsync(string coinId, string message) { var subject = "mailto:steve-reteamlabs@gmail.com"; var publicKey = "BBCdWc-g92B4hcMCLwlZAEs49k52NzvcJiLIfrkGmulGm2-HIcduBXbHvA7WwkbJLz3nCGwCjpI7pkZkF3Qt3So"; var privateKey = "WfeZokELwNc_uh0HxWGqPr_aAJ80FWNTvQdAO8bkfyo"; var coinInfo = await CoinService.GetCoinInfo(coinId); var subs = LocalDb.Query<NotificationSubscription>(sub => sub.CoinIds.Contains(coinId)).ToList(); foreach (var subscription in subs) { var pushSubscription = new PushSubscription(subscription.Url, subscription.P256dh, subscription.Auth); var vapidDetails = new VapidDetails(subject, publicKey, privateKey); var webPushClient = new WebPushClient(); try { var payload = JsonSerializer.Serialize(new { message, url = $"/", iconurl = coinInfo.LogoUrl, }); await webPushClient.SendNotificationAsync(pushSubscription, payload, vapidDetails); await EventService.LogCoinUpdateNotification(subscription.UserId, coinId); } catch (WebPushException ex) { await EventService.LogError("Error sending push notification", ex); } } } public async Task<NotificationSubscription> SubscribeAsync(string userId, NotificationSubscription subscription) { LocalDb.Delete<NotificationSubscription>(e => e.UserId == userId); subscription.UserId = userId; await Task.Run(() => LocalDb.Upsert(subscription)); await EventService.LogSubscription(userId); return subscription; } public async Task CheckAndNotifyAsync() { const string INTERVAL = "1d"; var allCoinIds = string.Join(",", LocalDb.All<NotificationSubscription>().Select(sub => string.Join(",", sub.CoinIds.ToArray()))); var uniqueCoinIds = string.Join(",", allCoinIds.Split(',').Distinct()); var allInfo = await CoinService.GetCoinPriceInfo(uniqueCoinIds, "GBP", INTERVAL); foreach (var coinPriceInfo in allInfo) { var priceChangePctRaw = coinPriceInfo.Intervals[INTERVAL].PriceChangePct; var priceChangePct = Math.Abs(float.Parse(coinPriceInfo.Intervals[INTERVAL].PriceChangePct)); if (priceChangePct > 0.05) { await SendAsync(coinPriceInfo.Id, $"{coinPriceInfo.Id} has changed {(priceChangePct * 100):0.00} in the last hour"); } } } public async Task UpdateSubscriptionAsync(string userId, string coinIds) { await Task.Run(() => { var subscription = LocalDb.Query<NotificationSubscription>(sub => sub.UserId == userId).FirstOrDefault(); if (subscription != null) { var coins = coinIds?.Split(',').ToList(); subscription.CoinIds = coins; LocalDb.Upsert(subscription); EventService.LogSubscriptionUpdate(userId); } }); } public async Task<IEnumerable<NotificationSubscription>> GetSubscriptions() { return await Task.Run(() => LocalDb.All<NotificationSubscription>()); } } }
40.330357
142
0.604826
[ "MIT" ]
steve-reteamlabs/GloboCrypto
GloboCrypto/GloboCrypto.WebAPI.Services/Notifications/NotificationService.cs
4,519
C#
using BalanceThings.Drawing; using BalanceThings.Physics; using FarseerPhysics; using FarseerPhysics.Dynamics; using FarseerPhysics.Factories; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; namespace BalanceThings.Items { class Hand : GameObject { internal Hand(World world, ContentManager contentManager, Vector2 position) : base(BodyFactory.CreateCapsule(world, ConvertUnits.ToSimUnits(6f), ConvertUnits.ToSimUnits(1f), 4, ConvertUnits.ToSimUnits(1f), 4, 1f, ConvertUnits.ToSimUnits(position)), new Sprite(contentManager.Load<Texture2D>("img/hand_default"), new Rectangle(6, 1, 2, 6), position, 1f, 0f)) { Body.BodyType = BodyType.Static; Body.IsKinematic = true; Body.Restitution = 0f; Body.Friction = 1f; } } }
36.32
126
0.685022
[ "Apache-2.0" ]
kevbot-git/BalanceThings
BalanceThings.Android/Items/Hand.cs
908
C#
using Newtonsoft.Json; namespace Microsoft.Azure.Devices.Applications.RemoteMonitoring.Common.Models { public class Telemetry { [JsonConstructor] public Telemetry() { } public Telemetry(string name, string displayName, string type) { Name = name; DisplayName = displayName; Type = type; } public string Name { get; set; } public string DisplayName { get; set; } public string Type { get; set; } public override string ToString() { return Newtonsoft.Json.JsonConvert.SerializeObject(this); } } }
24.071429
77
0.563798
[ "MIT" ]
Anchinga/TechnicalCommunityContent
IoT/Azure IoT Suite/Session 3 - Building Practical IoT Solutions/Solutions/Demo 3.2/Common/Models/Telemetry.cs
674
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.Sql { public static class GetJob { /// <summary> /// A job. /// API Version: 2020-08-01-preview. /// </summary> public static Task<GetJobResult> InvokeAsync(GetJobArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetJobResult>("azure-nextgen:sql:getJob", args ?? new GetJobArgs(), options.WithVersion()); } public sealed class GetJobArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the job agent. /// </summary> [Input("jobAgentName", required: true)] public string JobAgentName { get; set; } = null!; /// <summary> /// The name of the job to get. /// </summary> [Input("jobName", required: true)] public string JobName { get; set; } = null!; /// <summary> /// The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the server. /// </summary> [Input("serverName", required: true)] public string ServerName { get; set; } = null!; public GetJobArgs() { } } [OutputType] public sealed class GetJobResult { /// <summary> /// User-defined description of the job. /// </summary> public readonly string? Description; /// <summary> /// Resource ID. /// </summary> public readonly string Id; /// <summary> /// Resource name. /// </summary> public readonly string Name; /// <summary> /// Schedule properties of the job. /// </summary> public readonly Outputs.JobScheduleResponse? Schedule; /// <summary> /// Resource type. /// </summary> public readonly string Type; /// <summary> /// The job version number. /// </summary> public readonly int Version; [OutputConstructor] private GetJobResult( string? description, string id, string name, Outputs.JobScheduleResponse? schedule, string type, int version) { Description = description; Id = id; Name = name; Schedule = schedule; Type = type; Version = version; } } }
27.924528
147
0.552027
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Sql/GetJob.cs
2,960
C#
/* This file is auto-generated, do not edit */ using System; using System.Collections.Generic; using System.Net.Http; using Neurolib.ApiClient.Bindings; using Neurolib.ApiClient.Util; namespace Neurolib.ApiClient.ApiRequests { /// <summary>Item based recommendation</summary> /// <deprecated>Deprecated since version 2.0.0. Use RecommendItemsToItem request instead.</deprecated> /// <remarks>Recommends set of items that are somehow related to one given item, *X*. Typical scenario for using item-based recommendation is when user *A* is viewing *X*. Then you may display items to the user that he might be also interested in. Item-recommendation request gives you Top-N such items, optionally taking the target user *A* into account. /// It is also possible to use POST HTTP method (for example in case of very long ReQL filter) - query parameters then become body parameters. /// </remarks> [Obsolete("Deprecated since version 2.0.0. Use RecommendItemsToItem request instead.", false)] public class ItemBasedRecommendation : Request { private readonly string itemId; /// <summary>ID of the item for which the recommendations are to be generated.</summary> public string ItemId { get {return itemId;} } private readonly long count; /// <summary>Number of items to be recommended (N for the top-N recommendation).</summary> public long Count { get {return count;} } private readonly string targetUserId; /// <summary>ID of the user who will see the recommendations. /// Specifying the *targetUserId* is beneficial because: /// * It makes the recommendations personalized /// * Allows the calculation of Actions and Conversions in the graphical user interface, /// as Neurolib can pair the user who got recommendations and who afterwards viewed/purchased an item. /// For the above reasons, we encourage you to set the *targetUserId* even for anonymous/unregistered users (i.e. use their session ID). /// </summary> public string TargetUserId { get {return targetUserId;} } private readonly double? userImpact; /// <summary>If *targetUserId* parameter is present, the recommendations are biased towards the user given. Using *userImpact*, you may control this bias. For an extreme case of `userImpact=0.0`, the interactions made by the user are not taken into account at all (with the exception of history-based blacklisting), for `userImpact=1.0`, you'll get user-based recommendation. The default value is `0`. /// </summary> public double? UserImpact { get {return userImpact;} } private readonly string filter; /// <summary>Boolean-returning [ReQL](https://www.neurolib.io/pages/documentation) expression which allows you to filter recommended items based on the values of their attributes.</summary> public string Filter { get {return filter;} } private readonly string booster; /// <summary>Number-returning [ReQL](https://www.neurolib.io/pages/documentation) expression which allows you to boost recommendation rate of some items based on the values of their attributes.</summary> public string Booster { get {return booster;} } private readonly bool? allowNonexistent; /// <summary>Instead of causing HTTP 404 error, returns some (non-personalized) recommendations if either item of given *itemId* or user of given *targetUserId* does not exist in the database. It creates neither of the missing entities in the database.</summary> public bool? AllowNonexistent { get {return allowNonexistent;} } private readonly bool? cascadeCreate; /// <summary>If item of given *itemId* or user of given *targetUserId* doesn't exist in the database, it creates the missing enity/entities and returns some (non-personalized) recommendations. This allows for example rotations in the following recommendations for the user of given *targetUserId*, as the user will be already known to the system.</summary> public bool? CascadeCreate { get {return cascadeCreate;} } private readonly string scenario; /// <summary>Scenario defines a particular application of recommendations. It can be for example "homepage", "cart" or "emailing". You can see each scenario in the UI separately, so you can check how well each application performs. The AI which optimizes models in order to get the best results may optimize different scenarios separately, or even use different models in each of the scenarios.</summary> public string Scenario { get {return scenario;} } private readonly bool? returnProperties; /// <summary>With `returnProperties=true`, property values of the recommended items are returned along with their IDs in a JSON dictionary. The acquired property values can be used for easy displaying of the recommended items to the user. /// Example response: /// ``` /// [ /// { /// "itemId": "tv-178", /// "description": "4K TV with 3D feature", /// "categories": ["Electronics", "Televisions"], /// "price": 342, /// "url": "myshop.com/tv-178" /// }, /// { /// "itemId": "mixer-42", /// "description": "Stainless Steel Mixer", /// "categories": ["Home & Kitchen"], /// "price": 39, /// "url": "myshop.com/mixer-42" /// } /// ] /// ``` /// </summary> public bool? ReturnProperties { get {return returnProperties;} } private readonly string[] includedProperties; /// <summary>Allows to specify, which properties should be returned when `returnProperties=true` is set. The properties are given as a comma-separated list. /// Example response for `includedProperties=description,price`: /// ``` /// [ /// { /// "itemId": "tv-178", /// "description": "4K TV with 3D feature", /// "price": 342 /// }, /// { /// "itemId": "mixer-42", /// "description": "Stainless Steel Mixer", /// "price": 39 /// } /// ] /// ``` /// </summary> public string[] IncludedProperties { get {return includedProperties;} } private readonly double? diversity; /// <summary>**Expert option** Real number from [0.0, 1.0] which determines how much mutually dissimilar should the recommended items be. The default value is 0.0, i.e., no diversification. Value 1.0 means maximal diversification. /// </summary> public double? Diversity { get {return diversity;} } private readonly string minRelevance; /// <summary>**Expert option** If the *targetUserId* is provided: Specifies the threshold of how much relevant must the recommended items be to the user. Possible values one of: "low", "medium", "high". The default value is "low", meaning that the system attempts to recommend number of items equal to *count* at any cost. If there are not enough data (such as interactions or item properties), this may even lead to bestseller-based recommendations to be appended to reach the full *count*. This behavior may be suppressed by using "medium" or "high" values. In such case, the system only recommends items of at least the requested qualit, and may return less than *count* items when there is not enough data to fulfill it. /// </summary> public string MinRelevance { get {return minRelevance;} } private readonly double? rotationRate; /// <summary>**Expert option** If the *targetUserId* is provided: If your users browse the system in real-time, it may easily happen that you wish to offer them recommendations multiple times. Here comes the question: how much should the recommendations change? Should they remain the same, or should they rotate? Neurolib API allows you to control this per-request in backward fashion. You may penalize an item for being recommended in the near past. For the specific user, `rotationRate=1` means maximal rotation, `rotationRate=0` means absolutely no rotation. You may also use, for example `rotationRate=0.2` for only slight rotation of recommended items. Default: `0.01`. /// </summary> public double? RotationRate { get {return rotationRate;} } private readonly double? rotationTime; /// <summary>**Expert option** If the *targetUserId* is provided: Taking *rotationRate* into account, specifies how long time it takes to an item to recover from the penalization. For example, `rotationTime=7200.0` means that items recommended less than 2 hours ago are penalized. Default: `7200.0`. /// </summary> public double? RotationTime { get {return rotationTime;} } private readonly Dictionary<string, object> expertSettings; /// <summary>Dictionary of custom options. /// </summary> public Dictionary<string, object> ExpertSettings { get {return expertSettings;} } /// <summary>Construct the request</summary> /// <param name="itemId">ID of the item for which the recommendations are to be generated.</param> /// <param name="count">Number of items to be recommended (N for the top-N recommendation).</param> /// <param name="targetUserId">ID of the user who will see the recommendations. /// Specifying the *targetUserId* is beneficial because: /// * It makes the recommendations personalized /// * Allows the calculation of Actions and Conversions in the graphical user interface, /// as Neurolib can pair the user who got recommendations and who afterwards viewed/purchased an item. /// For the above reasons, we encourage you to set the *targetUserId* even for anonymous/unregistered users (i.e. use their session ID). /// </param> /// <param name="userImpact">If *targetUserId* parameter is present, the recommendations are biased towards the user given. Using *userImpact*, you may control this bias. For an extreme case of `userImpact=0.0`, the interactions made by the user are not taken into account at all (with the exception of history-based blacklisting), for `userImpact=1.0`, you'll get user-based recommendation. The default value is `0`. /// </param> /// <param name="filter">Boolean-returning [ReQL](https://www.neurolib.io/pages/documentation) expression which allows you to filter recommended items based on the values of their attributes.</param> /// <param name="booster">Number-returning [ReQL](https://www.neurolib.io/pages/documentation) expression which allows you to boost recommendation rate of some items based on the values of their attributes.</param> /// <param name="allowNonexistent">Instead of causing HTTP 404 error, returns some (non-personalized) recommendations if either item of given *itemId* or user of given *targetUserId* does not exist in the database. It creates neither of the missing entities in the database.</param> /// <param name="cascadeCreate">If item of given *itemId* or user of given *targetUserId* doesn't exist in the database, it creates the missing enity/entities and returns some (non-personalized) recommendations. This allows for example rotations in the following recommendations for the user of given *targetUserId*, as the user will be already known to the system.</param> /// <param name="scenario">Scenario defines a particular application of recommendations. It can be for example "homepage", "cart" or "emailing". You can see each scenario in the UI separately, so you can check how well each application performs. The AI which optimizes models in order to get the best results may optimize different scenarios separately, or even use different models in each of the scenarios.</param> /// <param name="returnProperties">With `returnProperties=true`, property values of the recommended items are returned along with their IDs in a JSON dictionary. The acquired property values can be used for easy displaying of the recommended items to the user. /// Example response: /// ``` /// [ /// { /// "itemId": "tv-178", /// "description": "4K TV with 3D feature", /// "categories": ["Electronics", "Televisions"], /// "price": 342, /// "url": "myshop.com/tv-178" /// }, /// { /// "itemId": "mixer-42", /// "description": "Stainless Steel Mixer", /// "categories": ["Home & Kitchen"], /// "price": 39, /// "url": "myshop.com/mixer-42" /// } /// ] /// ``` /// </param> /// <param name="includedProperties">Allows to specify, which properties should be returned when `returnProperties=true` is set. The properties are given as a comma-separated list. /// Example response for `includedProperties=description,price`: /// ``` /// [ /// { /// "itemId": "tv-178", /// "description": "4K TV with 3D feature", /// "price": 342 /// }, /// { /// "itemId": "mixer-42", /// "description": "Stainless Steel Mixer", /// "price": 39 /// } /// ] /// ``` /// </param> /// <param name="diversity">**Expert option** Real number from [0.0, 1.0] which determines how much mutually dissimilar should the recommended items be. The default value is 0.0, i.e., no diversification. Value 1.0 means maximal diversification. /// </param> /// <param name="minRelevance">**Expert option** If the *targetUserId* is provided: Specifies the threshold of how much relevant must the recommended items be to the user. Possible values one of: "low", "medium", "high". The default value is "low", meaning that the system attempts to recommend number of items equal to *count* at any cost. If there are not enough data (such as interactions or item properties), this may even lead to bestseller-based recommendations to be appended to reach the full *count*. This behavior may be suppressed by using "medium" or "high" values. In such case, the system only recommends items of at least the requested qualit, and may return less than *count* items when there is not enough data to fulfill it. /// </param> /// <param name="rotationRate">**Expert option** If the *targetUserId* is provided: If your users browse the system in real-time, it may easily happen that you wish to offer them recommendations multiple times. Here comes the question: how much should the recommendations change? Should they remain the same, or should they rotate? Neurolib API allows you to control this per-request in backward fashion. You may penalize an item for being recommended in the near past. For the specific user, `rotationRate=1` means maximal rotation, `rotationRate=0` means absolutely no rotation. You may also use, for example `rotationRate=0.2` for only slight rotation of recommended items. Default: `0.01`. /// </param> /// <param name="rotationTime">**Expert option** If the *targetUserId* is provided: Taking *rotationRate* into account, specifies how long time it takes to an item to recover from the penalization. For example, `rotationTime=7200.0` means that items recommended less than 2 hours ago are penalized. Default: `7200.0`. /// </param> /// <param name="expertSettings">Dictionary of custom options. /// </param> public ItemBasedRecommendation (string itemId, long count, string targetUserId = null, double? userImpact = null, string filter = null, string booster = null, bool? allowNonexistent = null, bool? cascadeCreate = null, string scenario = null, bool? returnProperties = null, string[] includedProperties = null, double? diversity = null, string minRelevance = null, double? rotationRate = null, double? rotationTime = null, Dictionary<string, object> expertSettings = null): base(HttpMethod.Post, 3000) { this.itemId = itemId; this.count = count; this.targetUserId = targetUserId; this.userImpact = userImpact; this.filter = filter; this.booster = booster; this.allowNonexistent = allowNonexistent; this.cascadeCreate = cascadeCreate; this.scenario = scenario; this.returnProperties = returnProperties; this.includedProperties = includedProperties; this.diversity = diversity; this.minRelevance = minRelevance; this.rotationRate = rotationRate; this.rotationTime = rotationTime; this.expertSettings = expertSettings; } /// <returns>URI to the endpoint including path parameters</returns> public override string Path() { return string.Format("/items/{0}/recomms/", ItemId); } /// <summary>Get query parameters</summary> /// <returns>Dictionary containing values of query parameters (name of parameter: value of the parameter)</returns> public override Dictionary<string, object> QueryParameters() { var parameters = new Dictionary<string, object>() { }; return parameters; } /// <summary>Get body parameters</summary> /// <returns>Dictionary containing values of body parameters (name of parameter: value of the parameter)</returns> public override Dictionary<string, object> BodyParameters() { var parameters = new Dictionary<string, object>() { {"count", this.Count} }; if (this.TargetUserId != null) parameters["targetUserId"] = this.TargetUserId; if (this.UserImpact.HasValue) parameters["userImpact"] = this.UserImpact.Value; if (this.Filter != null) parameters["filter"] = this.Filter; if (this.Booster != null) parameters["booster"] = this.Booster; if (this.AllowNonexistent.HasValue) parameters["allowNonexistent"] = this.AllowNonexistent.Value; if (this.CascadeCreate.HasValue) parameters["cascadeCreate"] = this.CascadeCreate.Value; if (this.Scenario != null) parameters["scenario"] = this.Scenario; if (this.ReturnProperties.HasValue) parameters["returnProperties"] = this.ReturnProperties.Value; if (this.IncludedProperties != null) parameters["includedProperties"] = string.Join(",", this.IncludedProperties); if (this.Diversity.HasValue) parameters["diversity"] = this.Diversity.Value; if (this.MinRelevance != null) parameters["minRelevance"] = this.MinRelevance; if (this.RotationRate.HasValue) parameters["rotationRate"] = this.RotationRate.Value; if (this.RotationTime.HasValue) parameters["rotationTime"] = this.RotationTime.Value; if (this.ExpertSettings != null) parameters["expertSettings"] = this.ExpertSettings; return parameters; } } }
64.86129
751
0.644402
[ "MIT" ]
neurolib-fr/net-api-client
Src/Neurolib.ApiClient/ApiRequests/ItemBasedRecommendation.cs
20,107
C#
using System.Linq; using NUnit.Framework; using TestCommon.Model; namespace Xtensive.Orm.BulkOperations.Tests { internal class Structures : AutoBuildTest { [Test] public void StructuresSet() { using (Session session = Domain.OpenSession()) { using (TransactionScope trx = session.OpenTransaction()) { var bar = new Bar(session) {Count = 5}; session.Query.All<Bar>().Set(a => a.Rectangle, new Rectangle(session) {BorderWidth = 1}).Update(); Assert.That(bar.Rectangle.BorderWidth, Is.EqualTo(1)); session.Query.All<Bar>().Set(a => a.Rectangle, new Rectangle(session)).Update(); Assert.That(bar.Rectangle.BorderWidth, Is.Null); session.Query.All<Bar>().Set( a => a.Rectangle, new Rectangle(session) {BorderWidth = 2, First = new Point(session) {X = 3, Y = 4}}).Update( ); Assert.That(bar.Rectangle.BorderWidth, Is.EqualTo(2)); Assert.That(bar.Rectangle.First.X, Is.EqualTo(3)); Assert.That(bar.Rectangle.First.Y, Is.EqualTo(4)); Assert.That(bar.Rectangle.Second.X, Is.Null); bar.Rectangle = new Rectangle(session); session.Query.All<Bar>().Set(a => a.Rectangle.First.X, 1).Update(); Assert.That(bar.Rectangle.First.X, Is.EqualTo(1)); Assert.That(bar.Rectangle.Second.X, Is.Null); bar.Rectangle = new Rectangle(session); /*var bar2 = new Bar(session); session.SaveChanges(); session.AssertCommandCount(Is.EqualTo(1), () => { session.Query.All<Bar>().Where(a => a.Id==bar2.Id).Set( a => a.Rectangle, a => session.Query.All<Bar>().Where(b => a.Id==bar.Id).Select(b => b.Rectangle).First()). Update(); }); Assert.That( bar2.Rectangle.First.X, Is.EqualTo(1)); Assert.That(bar2.Rectangle.Second.X, Is.Null); bar2.Remove();*/ session.Query.All<Bar>().Set(a => a.Rectangle.BorderWidth, a => a.Count * 2).Update(); Assert.That(bar.Rectangle.BorderWidth, Is.EqualTo(10)); bar.Rectangle = new Rectangle(session) {First = new Point(session) {X = 1, Y = 2}, Second = new Point(session) {X = 3, Y = 4}}; session.Query.All<Bar>().Set(a => a.Rectangle.BorderWidth, 1).Set( a => a.Rectangle.First, a => new Point(session) {X = 2}).Update(); Assert.That( bar.Rectangle, Is.EqualTo( new Rectangle(session) { BorderWidth = 1, First = new Point(session) {X = 2, Y = 2}, Second = new Point(session) {X = 3, Y = 4} })); bar.Rectangle = new Rectangle(session); bar.Rectangle = new Rectangle(session) {First = new Point(session) {X = 1, Y = 2}, Second = new Point(session) {X = 3, Y = 4}}; session.Query.All<Bar>().Set(a => a.Rectangle.BorderWidth, 1).Set( a => a.Rectangle.First, new Point(session) {X = 2}).Update(); Assert.That( bar.Rectangle, Is.EqualTo( new Rectangle(session) { BorderWidth = 1, First = new Point(session) {X = 2, Y = null}, Second = new Point(session) {X = 3, Y = 4} })); bar.Rectangle = new Rectangle(session); trx.Complete(); } } } [Test] public void StructuresUpdate() { using (Session session = Domain.OpenSession()) { using (TransactionScope trx = session.OpenTransaction()) { var bar = new Bar(session) {Count = 5}; session.Query.All<Bar>().Update( a => new Bar(null) {Rectangle = new Rectangle(session) {BorderWidth = 1}}); Assert.That(bar.Rectangle.BorderWidth, Is.EqualTo(1)); session.Query.All<Bar>().Update(a => new Bar(null) {Rectangle = new Rectangle(session)}); Assert.That(bar.Rectangle.BorderWidth, Is.Null); session.Query.All<Bar>().Update( a => new Bar(null) {Rectangle = new Rectangle(session) {BorderWidth = 2, First = new Point(session) {X = 3, Y = 4}}}); Assert.That(bar.Rectangle.BorderWidth, Is.EqualTo(2)); Assert.That(bar.Rectangle.First.X, Is.EqualTo(3)); Assert.That(bar.Rectangle.First.Y, Is.EqualTo(4)); Assert.That(bar.Rectangle.Second.X, Is.Null); bar.Rectangle = new Rectangle(session); session.Query.All<Bar>().Update( a => new Bar(null) {Rectangle = new Rectangle(session) {BorderWidth = a.Count * 2}}); Assert.That(bar.Rectangle.BorderWidth, Is.EqualTo(10)); bar.Rectangle = new Rectangle(session); bar.Rectangle = new Rectangle(session) {First = new Point(session) {X = 1, Y = 2}, Second = new Point(session) {X = 3, Y = 4}}; session.Query.All<Bar>().Update( a => new Bar(null) {Rectangle = new Rectangle(session) {BorderWidth = 1, First = new Point(session) {X = 2}}}); Assert.That( bar.Rectangle, Is.EqualTo( new Rectangle(session) { BorderWidth = 1, First = new Point(session) {X = 2, Y = 2}, Second = new Point(session) {X = 3, Y = 4} })); bar.Rectangle = new Rectangle(session); var rectangle = new Rectangle(session) {BorderWidth = 1, First = new Point(session) {X = 2}}; bar.Rectangle = new Rectangle(session) {First = new Point(session) {X = 1, Y = 2}, Second = new Point(session) {X = 3, Y = 4}}; session.Query.All<Bar>().Update(a => new Bar(null) {Rectangle = rectangle}); Assert.That(bar.Rectangle, Is.EqualTo(rectangle)); bar.Rectangle = new Rectangle(session); trx.Complete(); } } } } }
44.575758
137
0.559483
[ "MIT" ]
NekrasovSt/dataobjects-net
Extensions/Xtensive.Orm.BulkOperations.Tests/Structures.cs
5,886
C#
using UnityEngine; using System.Collections; public class Golem_Death_Fade_Out : MonoBehaviour { public float fadeOutDelay, fadeOutTime; void Start () { StartCoroutine (FadeOut ()); } IEnumerator FadeOut () { Renderer[] renderers = GetComponentsInChildren<Renderer> (); yield return new WaitForSeconds (fadeOutDelay); float a = fadeOutTime; while (a > 0) { for (int i = 0; i < renderers.Length; i++) { Color colorRef = renderers [i].material.color; colorRef.a -= Time.deltaTime / fadeOutTime; colorRef.a = Mathf.Clamp (colorRef.a, 0.0f, 1.0f); renderers [i].material.color = colorRef; } a -= Time.deltaTime; yield return null; } Invoke ("Death", 1); yield break; } void Death () { Destroy (this.gameObject); } }
20.945946
62
0.665806
[ "CC0-1.0" ]
RarCeth/FatalCore_MK_III
Assets/Golem_Death_Fade_Out.cs
777
C#
/* * Copyright (c) 2019 ETH Zürich, Educational Development and Technology (LET) * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ using System; using Microsoft.Win32; using SafeExamBrowser.Logging.Contracts; namespace SafeExamBrowser.Lockdown.FeatureConfigurations.RegistryConfigurations.UserHive { [Serializable] internal abstract class UserHiveConfiguration : RegistryConfiguration { protected string SID { get; } protected string UserName { get; } protected override RegistryKey RootKey => Registry.Users; public UserHiveConfiguration(Guid groupId, ILogger logger, string sid, string userName) : base(groupId, logger) { SID = sid ?? throw new ArgumentNullException(nameof(sid)); UserName = userName ?? throw new ArgumentNullException(nameof(userName)); } public override string ToString() { return $"{GetType().Name} ({Id}) for user '{UserName}'"; } protected override bool IsHiveAvailable(RegistryDataItem item) { var isAvailable = false; try { isAvailable = Registry.Users.OpenSubKey(SID) != null; } catch (Exception e) { logger.Error($"Failed to check availability of registry hive for item {item}!", e); } return isAvailable; } } }
27.039216
113
0.720812
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
junbaor/seb-win-refactoring
SafeExamBrowser.Lockdown/FeatureConfigurations/RegistryConfigurations/UserHive/UserHiveConfiguration.cs
1,382
C#
using System; using System.Collections.Generic; using System.Xml.Serialization; namespace Alipay.AopSdk.Core.Domain { /// <summary> /// AlipayMarketingCardConsumeSyncModel Data Structure. /// </summary> [Serializable] public class AlipayMarketingCardConsumeSyncModel : AopObject { /// <summary> /// 用户实际付的现金金额 1.针对预付卡面额的核销金额在use_benefit_list展现,作为权益金额 2.权益金额不叠加在该金额上 /// </summary> [XmlElement("act_pay_amount")] public string ActPayAmount { get; set; } /// <summary> /// 卡信息(交易后的实际卡信息) /// </summary> [XmlElement("card_info")] public MerchantCard CardInfo { get; set; } /// <summary> /// 获取权益列表 /// </summary> [XmlArray("gain_benefit_list")] [XmlArrayItem("benefit_info_detail")] public List<BenefitInfoDetail> GainBenefitList { get; set; } /// <summary> /// 备注信息,现有直接填写门店信息 /// </summary> [XmlElement("memo")] public string Memo { get; set; } /// <summary> /// 门店编号 /// </summary> [XmlElement("shop_code")] public string ShopCode { get; set; } /// <summary> /// 产生该笔交易时,用户出具的凭证类型 ALIPAY:支付宝电子卡 ENTITY:实体卡 OTHER:其他 /// </summary> [XmlElement("swipe_cert_type")] public string SwipeCertType { get; set; } /// <summary> /// 支付宝业务卡号,开卡接口中返回获取 /// </summary> [XmlElement("target_card_no")] public string TargetCardNo { get; set; } /// <summary> /// 卡号类型 BIZ_CARD:支付宝业务卡号 /// </summary> [XmlElement("target_card_no_type")] public string TargetCardNoType { get; set; } /// <summary> /// 交易金额:本次交易的实际总金额(可认为标价金额) /// </summary> [XmlElement("trade_amount")] public string TradeAmount { get; set; } /// <summary> /// 交易名称 为空时根据交易类型提供默认名称 /// </summary> [XmlElement("trade_name")] public string TradeName { get; set; } /// <summary> /// 支付宝交易号 /// </summary> [XmlElement("trade_no")] public string TradeNo { get; set; } /// <summary> /// 线下交易时间(是用户付款的交易时间) 当交易时间晚于上次消费记录同步时间,则会发生卡信息变更 /// </summary> [XmlElement("trade_time")] public string TradeTime { get; set; } /// <summary> /// 交易类型 开卡:OPEN 消费:TRADE 充值:DEPOSIT 退卡:RETURN /// </summary> [XmlElement("trade_type")] public string TradeType { get; set; } /// <summary> /// 实际消耗的权益 /// </summary> [XmlArray("use_benefit_list")] [XmlArrayItem("benefit_info_detail")] public List<BenefitInfoDetail> UseBenefitList { get; set; } } }
28
80
0.545714
[ "MIT" ]
leixf2005/Alipay.AopSdk.Core
Alipay.AopSdk.Core/Domain/AlipayMarketingCardConsumeSyncModel.cs
3,320
C#
using System; using UltimaOnline; namespace UltimaOnline.Engines.Quests.Hag { public class HangoverCure : Item { private int m_Uses; public override int LabelNumber { get { return 1055060; } } // Grizelda's Extra Strength Hangover Cure [CommandProperty(AccessLevel.GameMaster)] public int Uses { get { return m_Uses; } set { m_Uses = value; } } [Constructable] public HangoverCure() : base(0xE2B) { Weight = 1.0; Hue = 0x2D; m_Uses = 20; } public override void OnDoubleClick(Mobile from) { if (!IsChildOf(from.Backpack)) { SendLocalizedMessageTo(from, 1042038); // You must have the object in your backpack to use it. return; } if (m_Uses > 0) { from.PlaySound(0x2D6); from.SendLocalizedMessage(501206); // An awful taste fills your mouth. if (from.BAC > 0) { from.BAC = 0; from.SendLocalizedMessage(501204); // You are now sober! } m_Uses--; } else { Delete(); from.SendLocalizedMessage(501201); // There wasn't enough left to have any effect. } } public HangoverCure(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)1); // version writer.WriteEncodedInt(m_Uses); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); switch (version) { case 1: { m_Uses = reader.ReadEncodedInt(); break; } case 0: { m_Uses = 20; break; } } } } }
26
111
0.431624
[ "MIT" ]
netcode-gamer/game.ultimaonline.io
UltimaOnline.Data/Engines/Quests/Witch Apprentice/Items/HangoverCure.cs
2,340
C#