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 |
|---|---|---|---|---|---|---|---|---|
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/websecurityscanner/v1/finding_type_stats.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.WebSecurityScanner.V1 {
/// <summary>Holder for reflection information generated from google/cloud/websecurityscanner/v1/finding_type_stats.proto</summary>
public static partial class FindingTypeStatsReflection {
#region Descriptor
/// <summary>File descriptor for google/cloud/websecurityscanner/v1/finding_type_stats.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static FindingTypeStatsReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cjtnb29nbGUvY2xvdWQvd2Vic2VjdXJpdHlzY2FubmVyL3YxL2ZpbmRpbmdf",
"dHlwZV9zdGF0cy5wcm90bxIiZ29vZ2xlLmNsb3VkLndlYnNlY3VyaXR5c2Nh",
"bm5lci52MSI/ChBGaW5kaW5nVHlwZVN0YXRzEhQKDGZpbmRpbmdfdHlwZRgB",
"IAEoCRIVCg1maW5kaW5nX2NvdW50GAIgASgFQokCCiZjb20uZ29vZ2xlLmNs",
"b3VkLndlYnNlY3VyaXR5c2Nhbm5lci52MUIVRmluZGluZ1R5cGVTdGF0c1By",
"b3RvUAFaVGdvb2dsZS5nb2xhbmcub3JnL2dlbnByb3RvL2dvb2dsZWFwaXMv",
"Y2xvdWQvd2Vic2VjdXJpdHlzY2FubmVyL3YxO3dlYnNlY3VyaXR5c2Nhbm5l",
"cqoCIkdvb2dsZS5DbG91ZC5XZWJTZWN1cml0eVNjYW5uZXIuVjHKAiJHb29n",
"bGVcQ2xvdWRcV2ViU2VjdXJpdHlTY2FubmVyXFYx6gIlR29vZ2xlOjpDbG91",
"ZDo6V2ViU2VjdXJpdHlTY2FubmVyOjpWMWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.WebSecurityScanner.V1.FindingTypeStats), global::Google.Cloud.WebSecurityScanner.V1.FindingTypeStats.Parser, new[]{ "FindingType", "FindingCount" }, null, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// A FindingTypeStats resource represents stats regarding a specific FindingType
/// of Findings under a given ScanRun.
/// </summary>
public sealed partial class FindingTypeStats : pb::IMessage<FindingTypeStats>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<FindingTypeStats> _parser = new pb::MessageParser<FindingTypeStats>(() => new FindingTypeStats());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<FindingTypeStats> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.WebSecurityScanner.V1.FindingTypeStatsReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FindingTypeStats() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FindingTypeStats(FindingTypeStats other) : this() {
findingType_ = other.findingType_;
findingCount_ = other.findingCount_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FindingTypeStats Clone() {
return new FindingTypeStats(this);
}
/// <summary>Field number for the "finding_type" field.</summary>
public const int FindingTypeFieldNumber = 1;
private string findingType_ = "";
/// <summary>
/// Output only. The finding type associated with the stats.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string FindingType {
get { return findingType_; }
set {
findingType_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "finding_count" field.</summary>
public const int FindingCountFieldNumber = 2;
private int findingCount_;
/// <summary>
/// Output only. The count of findings belonging to this finding type.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int FindingCount {
get { return findingCount_; }
set {
findingCount_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as FindingTypeStats);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(FindingTypeStats other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (FindingType != other.FindingType) return false;
if (FindingCount != other.FindingCount) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (FindingType.Length != 0) hash ^= FindingType.GetHashCode();
if (FindingCount != 0) hash ^= FindingCount.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (FindingType.Length != 0) {
output.WriteRawTag(10);
output.WriteString(FindingType);
}
if (FindingCount != 0) {
output.WriteRawTag(16);
output.WriteInt32(FindingCount);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (FindingType.Length != 0) {
output.WriteRawTag(10);
output.WriteString(FindingType);
}
if (FindingCount != 0) {
output.WriteRawTag(16);
output.WriteInt32(FindingCount);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (FindingType.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(FindingType);
}
if (FindingCount != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(FindingCount);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(FindingTypeStats other) {
if (other == null) {
return;
}
if (other.FindingType.Length != 0) {
FindingType = other.FindingType;
}
if (other.FindingCount != 0) {
FindingCount = other.FindingCount;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
FindingType = input.ReadString();
break;
}
case 16: {
FindingCount = input.ReadInt32();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
FindingType = input.ReadString();
break;
}
case 16: {
FindingCount = input.ReadInt32();
break;
}
}
}
}
#endif
}
#endregion
}
#endregion Designer generated code
| 34.907407 | 242 | 0.676711 | [
"Apache-2.0"
] | Global19/google-cloud-dotnet | apis/Google.Cloud.WebSecurityScanner.V1/Google.Cloud.WebSecurityScanner.V1/FindingTypeStats.cs | 9,425 | C# |
// Copyright (c) Microsoft. All Rights Reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Sarif.Readers;
namespace Microsoft.CodeAnalysis.Sarif
{
/// <summary>
/// Defines methods to support the comparison of objects of type Artifact for equality.
/// </summary>
[GeneratedCode("Microsoft.Json.Schema.ToDotNet", "1.1.3.0")]
internal sealed class ArtifactEqualityComparer : IEqualityComparer<Artifact>
{
internal static readonly ArtifactEqualityComparer Instance = new ArtifactEqualityComparer();
public bool Equals(Artifact left, Artifact right)
{
if (ReferenceEquals(left, right))
{
return true;
}
if (ReferenceEquals(left, null) || ReferenceEquals(right, null))
{
return false;
}
if (!Message.ValueComparer.Equals(left.Description, right.Description))
{
return false;
}
if (!ArtifactLocation.ValueComparer.Equals(left.Location, right.Location))
{
return false;
}
if (left.ParentIndex != right.ParentIndex)
{
return false;
}
if (left.Offset != right.Offset)
{
return false;
}
if (left.Length != right.Length)
{
return false;
}
if (left.Roles != right.Roles)
{
return false;
}
if (left.MimeType != right.MimeType)
{
return false;
}
if (!ArtifactContent.ValueComparer.Equals(left.Contents, right.Contents))
{
return false;
}
if (left.Encoding != right.Encoding)
{
return false;
}
if (left.SourceLanguage != right.SourceLanguage)
{
return false;
}
if (!object.ReferenceEquals(left.Hashes, right.Hashes))
{
if (left.Hashes == null || right.Hashes == null || left.Hashes.Count != right.Hashes.Count)
{
return false;
}
foreach (var value_0 in left.Hashes)
{
string value_1;
if (!right.Hashes.TryGetValue(value_0.Key, out value_1))
{
return false;
}
if (value_0.Value != value_1)
{
return false;
}
}
}
if (left.LastModifiedTimeUtc != right.LastModifiedTimeUtc)
{
return false;
}
if (!object.ReferenceEquals(left.Properties, right.Properties))
{
if (left.Properties == null || right.Properties == null || left.Properties.Count != right.Properties.Count)
{
return false;
}
foreach (var value_2 in left.Properties)
{
SerializedPropertyInfo value_3;
if (!right.Properties.TryGetValue(value_2.Key, out value_3))
{
return false;
}
if (!SerializedPropertyInfo.ValueComparer.Equals(value_2.Value, value_3))
{
return false;
}
}
}
return true;
}
public int GetHashCode(Artifact obj)
{
if (ReferenceEquals(obj, null))
{
return 0;
}
int result = 17;
unchecked
{
if (obj.Description != null)
{
result = (result * 31) + obj.Description.ValueGetHashCode();
}
if (obj.Location != null)
{
result = (result * 31) + obj.Location.ValueGetHashCode();
}
result = (result * 31) + obj.ParentIndex.GetHashCode();
result = (result * 31) + obj.Offset.GetHashCode();
result = (result * 31) + obj.Length.GetHashCode();
result = (result * 31) + obj.Roles.GetHashCode();
if (obj.MimeType != null)
{
result = (result * 31) + obj.MimeType.GetHashCode();
}
if (obj.Contents != null)
{
result = (result * 31) + obj.Contents.ValueGetHashCode();
}
if (obj.Encoding != null)
{
result = (result * 31) + obj.Encoding.GetHashCode();
}
if (obj.SourceLanguage != null)
{
result = (result * 31) + obj.SourceLanguage.GetHashCode();
}
if (obj.Hashes != null)
{
// Use xor for dictionaries to be order-independent.
int xor_0 = 0;
foreach (var value_4 in obj.Hashes)
{
xor_0 ^= value_4.Key.GetHashCode();
if (value_4.Value != null)
{
xor_0 ^= value_4.Value.GetHashCode();
}
}
result = (result * 31) + xor_0;
}
result = (result * 31) + obj.LastModifiedTimeUtc.GetHashCode();
if (obj.Properties != null)
{
// Use xor for dictionaries to be order-independent.
int xor_1 = 0;
foreach (var value_5 in obj.Properties)
{
xor_1 ^= value_5.Key.GetHashCode();
if (value_5.Value != null)
{
xor_1 ^= value_5.Value.GetHashCode();
}
}
result = (result * 31) + xor_1;
}
}
return result;
}
}
} | 30.668224 | 123 | 0.428767 | [
"MIT"
] | Microsoft/sarif-sdk | src/Sarif/Autogenerated/ArtifactEqualityComparer.cs | 6,563 | C# |
namespace mmoManager
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class Character
{
public int CharacterID { get; set; }
public int AccountID { get; set; }
[Required]
[StringLength(50)]
public string CharName { get; set; }
[Required]
[StringLength(50)]
public string CharClass { get; set; }
public int CharLevel { get; set; }
[Required]
[StringLength(50)]
public string CharGuild { get; set; }
public virtual Account Account { get; set; }
}
}
| 23.03125 | 55 | 0.614654 | [
"MIT"
] | Tidogo/mmoManager | Character.cs | 737 | C# |
using System.Text.RegularExpressions;
namespace Aliencube.AzureFunctions.Extensions.OpenApi.Configurations
{
/// <summary>
/// This represents the entity for route constraint filter.
/// </summary>
public class RouteConstraintFilter
{
/// <summary>
/// Initializes a new instance of the <see cref="RouteConstraintFilter"/> class.
/// </summary>
public RouteConstraintFilter()
{
this.Filter = new Regex(this.Pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
/// <summary>
/// Gets the pattern.
/// </summary>
public virtual string Pattern { get; } = @"^(\{[^\{\:]+)(\:.+)(\})$";
/// <summary>
/// Gets the replacement.
/// </summary>
public virtual string Replacement { get; } = "$1$3";
/// <summary>
/// Gets the <see cref="Regex"/> instance as filter.
/// </summary>
public virtual Regex Filter { get; }
}
} | 30.424242 | 99 | 0.559761 | [
"MIT"
] | Bpflugrad/AzureFunctions.Extensions | src/Aliencube.AzureFunctions.Extensions.OpenApi/Configurations/RouteConstraintFilter.cs | 1,006 | C# |
using Microsoft.Win32;
using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Path = System.IO.Path;
namespace Blide
{
/*
This tool lets you create botlists easier
Notes:
--------------------------
remove:
uhrzeit
Prime Gaming
Abonnent
Abzeichen)
Moderator
Badge)
GLHF Pledge
Subscriber
\r\n
00:00AbostatusModNAME:message \r\n
Chatterino:
between 00:00 and next :
-> :xxSTRING:
---------------------------
*/
public partial class Botlist : UserControl
{
MainWindow wnd = (MainWindow)Application.Current.MainWindow;
Boolean useTimestamps = false;
Boolean chatterino = false;
string clipboardtext = "";
string[] emotes = new string[] { "PrideShrug", "PrideFloat", "PridePog", "PrideCute", "PrideLaugh", "PrideUwu", "PrideWave", "PrideUnicorn", "PrideDragon", "PrideToucan", "PrideLGBTea", "PridePenguin", "PrideFlower", "PrideLion", "PrideHeartR", "PrideHeartL", "PrideRise", "PrideWorld", "PrideCrown", "PrideKoala", "PrideHeyyy", "PrideLove", "PrideStrong", "PridePaint", "HyperTiger", "HyperLost", "HyperCrate", "HyperCooldown", "HyperJump", "HyperSlam", "HyperReveal", "HyperHex", "HyperCheese", "HyperParkour", "HyperHaste", "HyperMine", "HyperGravity", "HyperMayhem", "HyperCrown", "KPOPselfie", "KPOPTT", "KPOPmerch", "KPOPvictory", "KPOPheart", "KPOPlove", "KPOPglow", "KPOPfan", "KPOPdance", "KPOPcheer", "HypeSideeye", "SirUwU", "SirPrise", "SirSad", "SirMad", "SirSword", "SirShield", "ALLINTOVOTE", "ShowOfHands", "FootGoal", "FootYellow", "FootBall", "BlackLivesMatter", "SingsMic", "SingsNote", "PorscheWIN", "BOP", "VirtualHug", "ExtraLife", "TwitchSings", "SoonerLater", "HolidayTree", "HolidaySanta", "HolidayPresent", "HolidayOrnament", "FBChallenge", "FBPenalty", "PixelBob", "GunRun", "HolidayCookie", "HolidayLog", "FBCatch", "FBBlock", "FBSpiral", "FBPass", "FBRun", "GenderFluidPride", "NonBinaryPride", "MaxLOL", "IntersexPride", "TwitchRPG", "PansexualPride", "AsexualPride", "MercyWing2", "PinkMercy", "BisexualPride", "LesbianPride", "GayPride", "TransgenderPride", "MercyWing1", "PartyHat", "EarthDay", "TombRaid", "PopCorn", "FBtouchdown", "PurpleStar", "GreenTeam", "RedTeam", "TPFufun", "TwitchVotes", "DarkMode", "HSWP", "TPcrunchyroll", "HSCheers", "TwitchUnity", "PowerUpL", "Squid4", "PowerUpR", "Squid3", "LUL", "Squid2", "EntropyWins", "Squid1", "SabaPing", "BegWan", "BigPhish", "TearGlove", "TehePelo", "InuyoFace", "TwitchLit", "Kappu", "CarlSmile", "KonCha", "CrreamAwk", "PunOko", "ThankEgg", "PartyTime", "MorphinTime", "RlyTho", "TheIlluminati", "UWot", "TBAngel", "YouDontSay", "MVGame", "KAPOW", "NinjaGrumpy", "ItsBoshyTime", "CoolStoryBob", "TriHard", "SuperVinlin", "FreakinStinkin", "Poooound", "CurseLit", "UncleNox", "RaccAttack", "StrawBeary", "PrimeMe", "BrainSlug", "BatChest", "WTRuck", "TooSpicy", "Jebaited", "DogFace", "BlargNaut", "TakeNRG", "DatSheffy", "UnSane", "copyThis", "pastaThat", "imGlitch", "GivePLZ", "TheTarFu", "PicoMause", "TinyFace", "DrinkPurple", "DxCat", "RuleFive", "FutureMan", "OpieOP", "DoritosChip", "PJSugar", "VoteYea", "VoteNay", "ChefFrank", "StinkyCheese", "NomNom", "SmoocherZ", "cmonBruh", "KappaWealth", "OhMyDog", "OSFrog", "SeriousSloth", "KomodoHype", "VoHiYo", "MikeHogu", "KappaClaus", "KappaRoss", "MingLee", "SeemsGood", "twitchRaid", "KappaPride", "bleedPurple", "CoolCat", "DendiFace", "NotLikeThis", "riPepperonis", "duDudu", "ShadyLulu", "ArgieB8", "CorgiDerp", "PraiseIt", "TTours", "mcaT", "BuddhaBar", "WutFace", "PRChase", "Mau5", "HeyGuys", "NotATK", "PermaSmug", "panicBasket", "BabyRage", "HassaanChop", "TheThing", "EleGiggle", "EleGiggle", "PanicVis", "ANELE", "BrokeBack", "PipeHype", "YouWHY", "RitzMitz", "GrammarKing", "RalpherZ", "TF2John", "SoBayed", "ThunBeast", "BigBrother", "WholeWheat", "Keepo", "DAESuppy", "Kippa", "FailFish", "PogChamp", "OneHand", "PMSTwin", "FUNgineer", "DBstyle", "AsianGlow", "ResidentSleeper", "4Head", "BibleThump", "HotPokket", "ShazBotstix", "FrankerZ", "SMOrc", "ArsonNoSexy", "PunchTrees", "SSSsss", "Kreygasm", "KevinTurtle", "PJSalt", "SwiftRage", "DansGame", "GingerPower", "BCWarrior", "StoneLightning", "TheRinger", "RedCoat", "Kappa", "JonCarnage", "MrDestructoid", "OptimizePrime", "JKanStyle", "PedoBear", "RebeccaBlack", "CiGrip", "DatSauce", "ForeverAlone", "GabeN", "HailHelix", "HerbPerve", "iDog", "rStrike", "ShoopDaWhoop", "SwedSwag", "M&Mjc", "bttvNice", "TopHam", "TwaT", "WatChuSay", "SavageJerky", "Zappa", "tehPoleCat", "AngelThump", "HHydro", "TaxiBro", "BroBalt", "ButterSauce", "BaconEffect", "SuchFraud", "CandianRage", "She'llBeRight", "D:", "VisLaud", "KaRappa", "YetiZ", "miniJulia", "FishMoley", "Hhhehehe", "KKona", "PoleDoge", "sosGame", "CruW", "RarePepe", "iamsocal", "haHAA", "FeelsBirthdayMan", "RonSmug", "KappaCool", "FeelsBadMan", "BasedGod", "bUrself", "ConcernDoge", "FeelsGoodMan", "FireSpeed", "NaM", "SourPls", "LuL", "SaltyCorn", "FCreep", "monkaS", "VapeNation", "ariW", "notsquishY", "FeelsAmazingMan", "DuckerZ", "FeelsPumpkinMan", "SqShy", "Wowee", "WubTF", "cvR", "cvL", "cvHazmat", "cvMask" };
public Botlist()
{
InitializeComponent();
}
private void Bu1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (Bu1.Toggled1 == true)
{
useTimestamps = true;
}
else
{
useTimestamps = false;
}
}
private void Bu2_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (Bu2.Toggled1 == true)
{
chatterino = true;
}
else
{
chatterino = false;
}
}
//:xxSTRING:asdasd:xx:xxString:asdasd:xx:xxString
private void ExtractButton_Click(object sender, RoutedEventArgs e)
{
char[] numbers = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', };
string[] toRemove = { "turbo", "Turbo", "verschenkt", "Gaming", "zeichen)", "bonennt", "Moderator", "Badge", "Pledge", "ubscriber", "nkabos", "VIP", "fiziert", "cheer 1,000,000", "cheer 900,000", "cheer 800,000", "cheer 700,000", "cheer 600,000", "cheer 500,000", "cheer 400,000", "cheer 300,000", "cheer 200,000", "cheer 100,000", "cheer 75,000", "cheer 50,000", "cheer 25,000", "cheer 10,000", "cheer 5,000", "cheer 1,000", "cheer 1.000.000", "cheer 900.000", "cheer 800.000", "cheer 700.000", "cheer 600.000", "cheer 500.000", "cheer 400.000", "cheer 300.000", "cheer 200.000", "cheer 100.000", "cheer 75.000", "cheer 50.000", "cheer 25.000", "cheer 10.000", "cheer 5.000", "cheer 1.000", "cheer 100", "cheer 1", "Leader 1", "Leader 2", "Leader 3", "Brawlhalla", "Founder", "Horde", "1979 Revolution", "60 Seconds!", "H1Z1", "Battle Chef Brigade", "Battlerite", "Charity 2018", "Brawlhalla", "Broken Age", "Strike Back", "Cry HD Collection", "Devilian", "Duelyst", "Innerspace", "Access Pass 2018", "Access Pass 2019", "Access Pass 2020", " Ranger", "Staff", " Gift Subs", "Subscriber", "The Surge", "badge", "AutoMod", "TwitchCon 2017", "TwitchCon 2018", "Amsterdam 2020", "TwitchCon 2020", "EU 2019", "gelöscht", "Gifter", ")" };
string stringBuilder = "";
if (chatterino)
{
char[] temp = usernames.Text.ToCharArray();
for (int i = 0; i < temp.Length; i++)
{
if (numbers.Contains(temp[i]) && numbers.Contains(temp[i + 1]) && temp[i + 2] == ':' && numbers.Contains(temp[i + 3]) && numbers.Contains(temp[i + 4])) //if zz:zz -> danach name bis :
{
int j = i + 6;
while (temp[j] != ':')
{
stringBuilder = stringBuilder + temp[j] + "";
j++;
}
stringBuilder = stringBuilder + ";";
i = i + 5;
}
if (numbers.Contains(temp[i]) && temp[i + 1] == ':' && numbers.Contains(temp[i + 2]) && numbers.Contains(temp[i + 3])) //if z:zz -> danach name bis :
{
int j = i + 5;
while (temp[j] != ':')
{
stringBuilder = stringBuilder + temp[j] + "";
j++;
}
stringBuilder = stringBuilder + ";";
i = i + 4;
}
}
}
else if (useTimestamps)
{
string[] lines = usernames.Text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); //devide in lines
for (int i = 0; i < lines.Length; i++) // every line
{
if (lines[i] != null && lines[i].Length > 4)
{
lines[i] = lines[i].Remove(0, 4); //remove timestamp
if (lines[i].Contains("VerifiziertStreamElement")) { lines[i] = ""; }
if (lines[i].Contains("aboniert"))
{
lines[i] = "";
lines[i - 1] = "";
lines[i + 1] = "";
lines[i + 2] = "";
}
for (int r = 0; r < toRemove.Length; r++)
{
lines[i] = getAfter(lines[i], toRemove[r]);
}
if (lines[i].Contains(":"))
{
lines[i] = lines[i].Substring(0, lines[i].IndexOf(":", 0)); // clear everything after :
}
}
}
for (int j = 0; j < lines.Length; j++)
{
if (lines[j] != "" && lines[j] != null)
{
if (emotes.Contains(lines[j]) || emotes.Contains(lines[j].Remove(0, 1)) || emotes.Contains(lines[j].Remove(lines[j].Length - 1)))
{
lines[j] = "";
}
}
stringBuilder = stringBuilder + lines[j] + ";";
}
}
else
{
string[] lines = usernames.Text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); //devide in lines
for (int i = 0; i < lines.Length; i++) // every line
{
if (lines[i] != null)
{
if (lines[i].Contains("Streamelements")) { lines[i] = ""; }
if (lines[i].Contains("VerifiziertStreamElement")) { lines[i] = ""; }
for (int r = 0; r < toRemove.Length; r++)
{
lines[i] = getAfter(lines[i], toRemove[r]);
}
if (lines[i].Contains(":"))
{
lines[i] = lines[i].Substring(0, lines[i].IndexOf(":", 0)); // clear everything after :
}
}
}
for (int j = 0; j < lines.Length; j++)
{
if (lines[j] != "" && lines[j] != null)
{
if (emotes.Contains(lines[j]) || emotes.Contains(lines[j].Remove(0, 1)) || emotes.Contains(lines[j].Remove(lines[j].Length - 1)))
{
lines[j] = "";
}
}
stringBuilder = stringBuilder + lines[j] + ";";
}
}
string stringBuilderA = stringBuilder.Replace(";", "\n");
string[] noDuplicates = RemoveDuplicates(stringBuilderA.Split('\n'));
string stringBuilderANoDuplicates = string.Join("\n", noDuplicates);
usernames.Text = stringBuilderANoDuplicates;
}
public string[] RemoveDuplicates(string[] myList)
{
System.Collections.ArrayList newList = new System.Collections.ArrayList();
foreach (string str in myList)
if (!newList.Contains(str))
newList.Add(str);
return (string[])newList.ToArray(typeof(string));
}
public string getAfter(string strSource, string strStart)
{
if (strSource.Contains(strStart))
{
int Start;
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
return strSource.Remove(0, Start);
}
return strSource;
}
private void SaveAsButton_Click(object sender, RoutedEventArgs e)
{
//string writer:
string usernamesfinal = usernames.Text;
usernamesfinal = usernamesfinal.Replace("\r\n", ";");
//get broadcaster name
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string[] lines = System.IO.File.ReadAllLines(Path.Combine(docPath, "BlideSettings.txt"));
string broadcaster = lines[1];
//choose folder
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Text file (*.txt)|*.txt";
saveFileDialog.FileName = "" + DateTime.Now.ToString(@"MM.dd.yyyy") + "_" + broadcaster + "_" + "botlist";
saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (saveFileDialog.ShowDialog() == true) { File.WriteAllText(saveFileDialog.FileName, usernamesfinal); }
}
private void SaveImportButton_Click(object sender, RoutedEventArgs e)
{
//string writer:
string usernamesfinal = usernames.Text;
usernamesfinal = usernamesfinal.Replace("\r\n", ";");
//get broadcaster name
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string[] lines = System.IO.File.ReadAllLines(Path.Combine(docPath, "BlideSettings.txt"));
string broadcaster = lines[1];
//choose folder
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Text file (*.txt)|*.txt";
saveFileDialog.FileName = "" + DateTime.Now.ToString(@"MM.dd.yyyy") + "_" + broadcaster + "_" + "botlist";
saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (
saveFileDialog.ShowDialog() == true)
{
File.WriteAllText(saveFileDialog.FileName, usernamesfinal);
wnd.import("" + saveFileDialog.FileName);
}
}
private void LoadClipboardButton_Click(object sender, RoutedEventArgs e)
{
clipboardtext = Clipboard.GetText();
usernames.Text = clipboardtext;
}
private void replaceButton_Click(object sender, RoutedEventArgs e)
{
if (toReplace.Text != "" && toReplace.Text != null && replacement.Text != null)
{
usernames.Text = usernames.Text.Replace(toReplace.Text, replacement.Text);
}
}
}
}
| 52.697987 | 4,400 | 0.531457 | [
"MIT"
] | Blideapp/Blide | blide/Botlist.xaml.cs | 15,707 | C# |
/*
* MailSlurp API
*
* MailSlurp is an API for sending and receiving emails from dynamically allocated email addresses. It's designed for developers and QA teams to test applications, process inbound emails, send templated notifications, attachments, and more. ## Resources - [Homepage](https://www.mailslurp.com) - Get an [API KEY](https://app.mailslurp.com/sign-up/) - Generated [SDK Clients](https://www.mailslurp.com/docs/) - [Examples](https://github.com/mailslurp/examples) repository
*
* The version of the OpenAPI document: 6.5.2
*
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Xunit;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using mailslurp.Api;
using mailslurp.Model;
using mailslurp.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace mailslurp.Test
{
/// <summary>
/// Class for testing InboxRulesetTestResult
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class InboxRulesetTestResultTests : IDisposable
{
// TODO uncomment below to declare an instance variable for InboxRulesetTestResult
//private InboxRulesetTestResult instance;
public InboxRulesetTestResultTests()
{
// TODO uncomment below to create an instance of InboxRulesetTestResult
//instance = new InboxRulesetTestResult();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of InboxRulesetTestResult
/// </summary>
[Fact]
public void InboxRulesetTestResultInstanceTest()
{
// TODO uncomment below to test "IsInstanceOfType" InboxRulesetTestResult
//Assert.IsInstanceOfType<InboxRulesetTestResult> (instance, "variable 'instance' is a InboxRulesetTestResult");
}
/// <summary>
/// Test the property 'Matches'
/// </summary>
[Fact]
public void MatchesTest()
{
// TODO unit test for the property 'Matches'
}
/// <summary>
/// Test the property 'RulesetMatches'
/// </summary>
[Fact]
public void RulesetMatchesTest()
{
// TODO unit test for the property 'RulesetMatches'
}
}
}
| 31.55 | 472 | 0.646989 | [
"MIT"
] | mailslurp/mailslurp-client-csharp | src/mailslurp.Test/Model/InboxRulesetTestResultTests.cs | 2,524 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.ReverseProxy.Utilities
{
internal sealed class Clock : IClock
{
private readonly ValueStopwatch _stopwatch = ValueStopwatch.StartNew();
public long TickCount => Environment.TickCount64;
public Task Delay(TimeSpan delay, CancellationToken cancellationToken) =>
Task.Delay(delay, cancellationToken);
public Task Delay(int millisecondsDelay, CancellationToken cancellationToken) =>
Task.Delay(millisecondsDelay, cancellationToken);
public TimeSpan GetStopwatchTime() => _stopwatch.Elapsed;
}
}
| 29.44 | 88 | 0.726902 | [
"MIT"
] | akramtexas/reverse-proxy | src/ReverseProxy/Utilities/Clock.cs | 736 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HelloBlueteraWpf")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HelloBlueteraWpf")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 43.482143 | 99 | 0.694456 | [
"MIT"
] | ioteratech/bluetera-windows-sdk | source/examples/HelloBlueteraWpf/Properties/AssemblyInfo.cs | 2,383 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace HFEA.Connector.Contracts.Centre
{
public class Licence
{
//
// Summary:
// End Date
[JsonProperty("endDate")]
public DateTime? EndDate { get; set; }
//
// Summary:
// License Id
[JsonProperty("id")]
public int Id { get; set; }
//
// Summary:
// Licence Holder
[JsonProperty("licenceHolder")]
public string LicenceHolder { get; set; }
//
// Summary:
// Licence Number Formatted
[JsonProperty("licenceNoFormatted")]
public string LicenceNoFormatted { get; set; }
//
// Summary:
// Licence Type
[JsonProperty("licenceType")]
public string LicenceType { get; set; }
//
// Summary:
// Licence Type ID
[JsonProperty("licenceTypeID")]
public int LicenceTypeID { get; set; }
//
// Summary:
// Person Responsible
[JsonProperty("personResponsible")]
public string PersonResponsible { get; set; }
//
// Summary:
// Role Details
[JsonProperty("roles")]
public List<RoleDetail> Roles { get; set; }
//
// Summary:
// Start Date
[JsonProperty("startDate")]
public DateTime StartDate { get; set; }
//
// Summary:
// Licenced treatments performed at the centre
[JsonProperty("treatments")]
public List<string> Treatments { get; set; }
}
}
| 27.163934 | 58 | 0.515389 | [
"BSD-3-Clause"
] | hfea/Website-Public | Source/HFEA.API.Connector/Source/HFEA.Connector.Contracts/Centre/Licence.cs | 1,659 | C# |
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
namespace AddInsShare.Common
{
/// <summary>
/// Dependency Object extensions
/// </summary>
public static class DependencyObjectExtensions
{
/// <summary>
/// Returns the template element of the given name within the Control.
/// </summary>
public static T FindTemplateName<T>(this Control control, string name) where T : FrameworkElement
{
ControlTemplate template = control.Template;
if (template != null)
{
return template.FindName(name, control) as T;
}
return null;
}
/// <summary>
/// Searches the subtree of an element (including that element)
/// for an element of a particluar type.
/// </summary>
public static T FindElement<T>(this DependencyObject element) where T : FrameworkElement
{
T correctlyTyped = element as T;
if (correctlyTyped != null)
{
return correctlyTyped;
}
if (element != null)
{
int numChildren = VisualTreeHelper.GetChildrenCount(element);
for (int i = 0; i < numChildren; i++)
{
T child = FindElement<T>(VisualTreeHelper.GetChild(element, i) as FrameworkElement);
if (child != null)
{
return child;
}
}
// Popups continue in another window, jump to that tree
Popup popup = element as Popup;
if (popup != null)
{
return FindElement<T>(popup.Child as FrameworkElement);
}
}
return null;
}
/// <summary>
/// This method locates the first visual parent of the given Type.
/// </summary>
/// <param name="fe">Framework Element</param>
/// <param name="lookForType">Specific type to look for</param>
/// <returns>Visual Parent</returns>
public static DependencyObject FindVisualParent(this DependencyObject fe, Type lookForType)
{
fe = VisualTreeHelper.GetParent(fe);
while (fe != null)
{
if (lookForType.IsInstanceOfType(fe))
return fe;
fe = VisualTreeHelper.GetParent(fe);
}
return null;
}
/// <summary>
/// This method locates the first visual parent of the given Type.
/// </summary>
/// <typeparam name="T">Type to search for</typeparam>
/// <param name="fe">Framework Element</param>
/// <returns>Visual Parent</returns>
public static T FindVisualParent<T>(this DependencyObject fe) where T : DependencyObject
{
fe = VisualTreeHelper.GetParent(fe);
while (fe != null)
{
var correctlyTyped = fe as T;
if (correctlyTyped != null)
return correctlyTyped;
fe = VisualTreeHelper.GetParent(fe);
}
return null;
}
/// <summary>
/// This method locates the first visual child of the given Type.
/// </summary>
/// <typeparam name="T">Type to search for</typeparam>
/// <param name="fe">Framework Element</param>
/// <returns>Visual Child</returns>
public static T FindVisualChild<T>(this DependencyObject fe) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(fe); i++)
{
DependencyObject dpo = VisualTreeHelper.GetChild(fe, i);
if (dpo == null)
break;
var tChild = dpo as T;
if (tChild != null)
return tChild;
var tdp = FindVisualChild<T>(dpo);
if (tdp != null)
return tdp;
}
return null;
}
/// <summary>
/// This method locates a visual child by NAME of the given Type.
/// </summary>
/// <typeparam name="T">Type to search for</typeparam>
/// <param name="fe">Framework Element</param>
/// <param name="name">Name to look for (assigned to Name property)</param>
/// <returns>Visual Child or null</returns>
public static T FindVisualChildByName<T>(this DependencyObject fe, string name) where T : DependencyObject
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(fe); i++)
{
var child = VisualTreeHelper.GetChild(fe, i);
var controlName = child.GetValue(FrameworkElement.NameProperty) as string;
if (controlName == name)
return child as T;
var result = FindVisualChildByName<T>(child, name);
if (result != null)
return result;
}
return null;
}
/// <summary>
/// A simple iterator method to expose the visual tree to LINQ (parent to child).
/// </summary>
/// <param name="start">Starting root</param>
/// <param name="predicate">Predicate called for each item to provide filter (can be null)</param>
/// <returns>Enumerable list of visuals</returns>
public static IEnumerable<T> EnumerateVisualTree<T>(this DependencyObject start, Predicate<T> predicate) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(start); i++)
{
var rawChild = VisualTreeHelper.GetChild(start, i);
var child = rawChild as T;
if (child != null && (predicate == null || predicate(child)))
{
yield return child;
foreach (var childOfChild in EnumerateVisualTree(child, predicate))
yield return childOfChild;
}
else if (child == null)
{
foreach (var childOfChild in EnumerateVisualTree(rawChild, predicate))
yield return childOfChild;
}
}
}
/// <summary>
/// A simple iterator method to expose the visual tree to LINQ going backwards (child to parent)
/// </summary>
/// <param name="start">Starting child</param>
/// <param name="predicate">Predicate called for each item to provide filter (can be null)</param>
/// <returns>Enumerable list of visuals</returns>
public static IEnumerable<T> ReverseEnumerateVisualTree<T>(this DependencyObject start, Predicate<T> predicate) where T : DependencyObject
{
for (;;)
{
var parent = VisualTreeHelper.GetParent(start);
if (parent == null)
break;
var tParent = parent as T;
if ((predicate == null || predicate(tParent)))
yield return tParent;
start = parent;
}
}
/// <summary>
/// This enumerates the children of the given starting DPO.
/// </summary>
/// <param name="fe">Start</param>
/// <returns>Collection of children (enumerator)</returns>
public static IEnumerable<DependencyObject> VisualChildren(this DependencyObject fe)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(fe); i++)
yield return VisualTreeHelper.GetChild(fe, i);
}
}
}
| 37.600939 | 146 | 0.531527 | [
"Apache-2.0"
] | tmatinde/route-monitor-for-geoevent | DashboardAddIns/AddInsShare/Common/DependencyObjectExtensions.cs | 8,011 | C# |
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using MArchive.DataContext;
using MArchive.Domain.Lookup;
using MArchiveLibrary.Repository;
using MArchiveLibrary.ObjectMapping;
using MArchiveLibrary.ExtendedDataContext;
namespace MArchive.BL {
public class DirectorBL : BLBase {
private const string CacheAreaKey = "MArchive_Director";
public static DirectorDO Save ( DirectorDO inputDO, int userID ) {
Repository<INF_Director> rep = new Repository<INF_Director> ( MArchiveDataContextProvider.Instance );
INF_Director objectToAdd = null;
if ( inputDO.ID == 0 ) {
objectToAdd = new INF_Director ( );
ObjectMapper.MapObjects ( inputDO, objectToAdd, AuditInfo.Fields );
rep.InsertOnSubmit ( objectToAdd );
} else {
objectToAdd = rep.GetAll ( ).Single ( x => x.ID == inputDO.ID );
ObjectMapper.MapObjects ( inputDO, objectToAdd, AuditInfo.Fields );
}
rep.DCP.CommitChanges(userID);
InvalidateCache(CacheAreaKey);
ObjectMapper.MapObjects ( objectToAdd, inputDO );
return inputDO;
}
internal static DirectorDO GetDOByID( int ID ) {
return GetAllDO( ).Single( q => q.ID == ID );
}
public static List<DirectorDO> GetAllDO ( ) {
return Mapper.Map<List<INF_Director>, List<DirectorDO>>( GetAll( ).ToList( ) );
}
public static List<INF_Director> GetAll() {
string functionName = "GetAll";
if (ReadCache<List<INF_Director>>(CacheAreaKey, functionName) != null) { return ReadCache<List<INF_Director>>(CacheAreaKey, functionName); }
Repository<INF_Director> rep = new Repository<INF_Director> ( MArchiveDataContextProvider.Instance );
var list = rep.GetAll().ToList();
WriteCache(CacheAreaKey, functionName, list);
return list;
}
}
} | 33.759259 | 152 | 0.696105 | [
"MIT"
] | chakian/movie-archive | MArchive.BL/DirectorBL.cs | 1,825 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using SimpleEssentials.IO.Readers;
using SimpleEssentials.IO.Types;
using SimpleEssentials.IO.Writers;
namespace SimpleEssentials.IO
{
public interface IFileHandler : IHandler
{
IFile Create(string fileName, IFolder parentFolder);
bool Write(IFile file, string content, bool append);
void Write<T>(IFile file, T obj, IFileWriter fileWriter, bool append);
void Write<T>(IFile file, IEnumerable<T> obj, IFileWriter fileWriter, bool append);
string Read(IFile file);
T Read<T>(IFile file, IFileReader fileReader);
IEnumerable<T> ReadAll<T>(IFile file, IFileReader fileReader);
IEnumerable<T> ReadBy<T>(IFile file, Func<T, bool> predicate, IFileReader fileReader);
}
} | 38.5 | 94 | 0.724911 | [
"MIT"
] | JTOne123/SimpleEssentials | SimpleEssentials.Standard/IO/IFileHandler.cs | 849 | C# |
using System.Collections.Generic;
namespace ProfitManager.Models
{
public interface IProfitSaleProvider
{
List<ProfitModel> GetSales(int parentId);
}
} | 19.222222 | 49 | 0.722543 | [
"MIT"
] | VisualAcademy/EntityFrameworkCore | ProfitManager/ProfitManager/Models/IProfitSaleProvider.cs | 175 | 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 Xunit;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests
{
/// <summary>
/// Contains those unit tests for the IdentifiersShouldNotMatchKeywords analyzer that
/// pertain to the TypeRule, which applies to the names of types.
/// </summary>
public partial class IdentifiersShouldNotMatchKeywordsTests
{
[Fact]
public void CSharpDiagnosticForKeywordNamedPublicType()
{
VerifyCSharp(@"
public class @class {}
",
GetCSharpResultAt(2, 14, IdentifiersShouldNotMatchKeywordsAnalyzer.TypeRule, "class", "class"));
}
[Fact]
public void BasicDiagnosticForKeywordNamedPublicType()
{
VerifyBasic(@"
Public Class [Class]
End Class
",
GetBasicResultAt(2, 14, IdentifiersShouldNotMatchKeywordsAnalyzer.TypeRule, "Class", "Class"));
}
[Fact]
public void CSharpNoDiagnosticForCaseSensitiveKeywordNamedPublicTypeWithDifferentCasing()
{
VerifyCSharp(@"
public class iNtErNaL {}
");
}
[Fact]
public void BasicNoDiagnosticForCaseSensitiveKeywordNamedPublicTypeWithDifferentCasing()
{
VerifyBasic(@"
Public Class iNtErNaL
End Class");
}
[Fact]
public void CSharpDiagnosticForCaseInsensitiveKeywordNamedPublicType()
{
VerifyCSharp(@"
public struct aDdHaNdLeR {}
",
GetCSharpResultAt(2, 15, IdentifiersShouldNotMatchKeywordsAnalyzer.TypeRule, "aDdHaNdLeR", "AddHandler"));
}
[Fact]
public void BasicDiagnosticForCaseInsensitiveKeywordNamedPublicType()
{
VerifyBasic(@"
Public Structure [aDdHaNdLeR]
End Structure",
GetBasicResultAt(2, 18, IdentifiersShouldNotMatchKeywordsAnalyzer.TypeRule, "aDdHaNdLeR", "AddHandler"));
}
[Fact]
public void CSharpNoDiagnosticForKeywordNamedInternalype()
{
VerifyCSharp(@"
internal class @class {}
");
}
[Fact]
public void BasicNoDiagnosticForKeywordNamedInternalType()
{
VerifyBasic(@"
Friend Class [Class]
End Class
");
}
[Fact]
public void CSharpNoDiagnosticForNonKeywordNamedPublicType()
{
VerifyCSharp(@"
public class classic {}
");
}
[Fact]
public void BasicNoDiagnosticForNonKeywordNamedPublicType()
{
VerifyBasic(@"
Public Class Classic
End Class
");
}
[Fact]
public void CSharpDiagnosticForKeywordNamedPublicTypeInNamespace()
{
VerifyCSharp(@"
namespace N
{
public enum @enum {}
}
",
GetCSharpResultAt(4, 17, IdentifiersShouldNotMatchKeywordsAnalyzer.TypeRule, "enum", "enum"));
}
[Fact]
public void BasicDiagnosticForKeywordNamedPublicTypeInNamespace()
{
VerifyBasic(@"
Namespace N
Public Enum [Enum]
X
End Enum
End Namespace
",
GetBasicResultAt(3, 17, IdentifiersShouldNotMatchKeywordsAnalyzer.TypeRule, "Enum", "Enum"));
}
[Fact]
public void CSharpDiagnosticForKeywordNamedProtectedTypeNestedInPublicClass()
{
VerifyCSharp(@"
public class C
{
protected class @protected {}
}
",
GetCSharpResultAt(4, 21, IdentifiersShouldNotMatchKeywordsAnalyzer.TypeRule, "C.protected", "protected"));
}
[Fact]
public void BasicDiagnosticForKeywordNamedProtectedTypeNestedInPublicClass()
{
VerifyBasic(@"
Public Class C
Protected Class [Protected]
End Class
End Class
",
GetBasicResultAt(3, 21, IdentifiersShouldNotMatchKeywordsAnalyzer.TypeRule, "C.Protected", "Protected"));
}
}
}
| 26.646667 | 161 | 0.636477 | [
"Apache-2.0"
] | RikkiGibson/roslyn-analyzers | src/Microsoft.CodeQuality.Analyzers/UnitTests/ApiDesignGuidelines/IdentifiersShouldNotMatchKeywordsTypeRuleTests.cs | 3,999 | C# |
using ShineEngine;
/// <summary>
/// 场景推送基类(generated by shine)
/// </summary>
public class SceneSResponse:SceneBaseResponse
{
/// <summary>
/// 数据类型ID
/// </summary>
public const int dataID=SceneBaseResponseType.SceneS;
public SceneSResponse()
{
_dataID=SceneBaseResponseType.SceneS;
setNeedRelease();
}
/// <summary>
/// 执行
/// </summary>
protected override void execute()
{
}
/// <summary>
/// 获取数据类名
/// </summary>
public override string getDataClassName()
{
return "SceneSResponse";
}
/// <summary>
/// 读取字节流(完整版)
/// </summary>
protected override void toReadBytesFull(BytesReadStream stream)
{
base.toReadBytesFull(stream);
stream.startReadObj();
stream.endReadObj();
}
}
| 16.291667 | 65 | 0.622762 | [
"Apache-2.0"
] | hw233/home3 | core/client/game/src/commonGame/net/sceneBaseResponse/base/SceneSResponse.cs | 834 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ProjetoIntegrador.Model
{
using System;
using System.Collections.Generic;
public partial class comentario
{
public int id_comentario { get; set; }
public int id_post { get; set; }
public int id_usuarioremetente { get; set; }
public System.DateTime datacomentario { get; set; }
public string comentariocontent { get; set; }
public virtual post post { get; set; }
public virtual usuario usuario { get; set; }
}
}
| 34.481481 | 85 | 0.542427 | [
"MIT"
] | uaijoaopaulo/ProjetoIntegradorUNAMED | ProjetoIntegrador/Model/comentario.cs | 931 | C# |
namespace ClassLib102
{
public class Class004
{
public static string Property => "ClassLib102";
}
}
| 15 | 55 | 0.633333 | [
"MIT"
] | 333fred/performance | src/scenarios/weblarge2.0/src/ClassLib102/Class004.cs | 120 | C# |
/*
* The MIT License
*
* Copyright 2019 Palmtree Software.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Globalization;
using System.Numerics;
using System.Collections.Generic;
using System.Linq;
namespace Palmtree.Math.Core.Sint.CodeGen.TestPattern
{
class TEST_PMC_ParseX
: TestPatternBase
{
private string _id;
private IEnumerable<InputTestData> _string_source;
private IEnumerable<InputTestData> _style_source;
private IDictionary<string, NumberStyles> _style_converter;
public TEST_PMC_ParseX()
{
_id = "ParseX";
var b = "123456789abcdef0";
b = b + b;
b = b + b;
b = b + b;
b = b + b;
b = b + b;
b = b + b;
_string_source = new[]
{
"{0}{1}",
" {0}{1}",
"{0}{1} ",
" {0}{1} ",
}
.SelectMany(item => new[]
{
b.Substring(0, 4),
b.Substring(0, 7),
b.Substring(5, 8),
b.Substring(10, 9),
b.Substring(0, 15),
b.Substring(5, 16),
b.Substring(10, 17),
b.Substring(0, 31),
b.Substring(5, 32),
b.Substring(10, 33),
b.Substring(0, 63),
b.Substring(5, 64),
b.Substring(10, 65),
b.Substring(0, 127),
b.Substring(5, 128),
b.Substring(10, 129),
}, (format, i) => new { format, i })
.SelectMany(item => new[]
{
"",
"0",
"00",
"0000",
"00000000",
"0000000000000000",
"00000000000000000000000000000000",
"f",
"ff",
"ffff",
"ffffffff",
"ffffffffffffffff",
"ffffffffffffffffffffffffffffffff",
}, (item, zero) => new { item.format, item.i, zero })
.Select(item => string.Format(item.format, item.zero, item.i))
.SelectMany(item => new[] { item.ToLower(), item.ToUpper() })
.Distinct()
.OrderBy(item => item.Length)
.ThenBy(item => item)
.Zip(Enumerable.Range(1, int.MaxValue),
(s, index) => new InputTestData(_id, s, index))
.ToArray();
_style_source = new[]
{
"PMC_NUMBER_STYLE_ALLOW_HEX_SPECIFIER",
"PMC_NUMBER_STYLE_ALLOW_HEX_SPECIFIER|PMC_NUMBER_STYLE_ALLOW_TRAILING_WHITE",
"PMC_NUMBER_STYLE_ALLOW_HEX_SPECIFIER|PMC_NUMBER_STYLE_ALLOW_LEADING_WHITE",
"PMC_NUMBER_STYLE_ALLOW_HEX_SPECIFIER|PMC_NUMBER_STYLE_ALLOW_LEADING_WHITE|PMC_NUMBER_STYLE_ALLOW_TRAILING_WHITE",
}
.Zip(Enumerable.Range(1, int.MaxValue),
(s, index) => new InputTestData(_id, s, index))
.ToArray();
_style_converter = new Dictionary<string, NumberStyles>();
_style_converter["PMC_NUMBER_STYLE_ALLOW_HEX_SPECIFIER"] = NumberStyles.AllowHexSpecifier;
_style_converter["PMC_NUMBER_STYLE_ALLOW_LEADING_WHITE"] = NumberStyles.AllowLeadingWhite;
_style_converter["PMC_NUMBER_STYLE_ALLOW_TRAILING_WHITE"] = NumberStyles.AllowTrailingWhite;
}
protected override string Id
{
get
{
return (_id);
}
}
protected override IEnumerable<TestTerm> CreateTestTerms(IEnumerable<InputTestData> in_source)
{
var source = _string_source
.SelectMany(str => _style_source, (str, style) => new { str, style })
.Select(item =>
{
var styles = item.style.StringValue.Split('|').Select(name => _style_converter[name]).Aggregate((x, y) => (x | y));
try
{
BigInteger x;
var ret = BigInteger.TryParse(item.str.StringValue, styles, null, out x);
if (ret)
return (new
{
item.str,
item.style,
desired_result_code = new OutputTestData(_id, new[] { item.str, item.style }, false, true, PMC_STATUS_CODE.PMC_STATUS_OK),
desired_value = new OutputTestData(_id, new[] { item.str, item.style }, true, true, x),
});
else
return (new
{
item.str,
item.style,
desired_result_code = new OutputTestData(_id, new[] { item.str, item.style }, false, true, PMC_STATUS_CODE.PMC_STATUS_PARSING_ERROR),
desired_value = new OutputTestData(_id, new[] { item.str, item.style }, false, false, x),
});
}
catch (ArgumentException)
{
return (new
{
item.str,
item.style,
desired_result_code = new OutputTestData(_id, new[] { item.str, item.style }, false, true, PMC_STATUS_CODE.PMC_STATUS_ARGUMENT_ERROR),
desired_value = new OutputTestData(_id, new[] { item.str, item.style }, false, false, BigInteger.Zero),
});
}
});
return (source
.Zip(Enumerable.Range(1, int.MaxValue),
(item, index) => new { index, item.str, item.style, item.desired_result_code, item.desired_value })
.Select(item => new TestTerm(_id,
item.index,
new[] { item.str, item.style },
new[] { item.desired_result_code, item.desired_value },
string.Format("TEST_{0}(env, ep, {1}, {2}, {3}, {4}, {5});",
_id, item.index,
item.str.StringValue.ToQuotedWideCharString(),
item.style.StringValue,
item.desired_result_code.PMC_STATUS_CODEValue,
item.desired_value.BufferParam))));
}
}
} | 44.320442 | 165 | 0.488532 | [
"MIT"
] | rougemeilland/Palmtree.Math.Core.Sint | Palmtree.Math.Core.Sint.CodeGen.TestPattern/TEST_ParseX.cs | 8,024 | C# |
using System;
using Xunit;
using Sample.MergeIntervals;
namespace Sample.Tests{
public class UnitTest_MergeIntervals{
[Theory]
[InlineData(0,0)]
public void checkResult(int n,int expected){
Assert.Equal(expected,mergeIntervals.naive(n));
}
}
}
| 21.214286 | 59 | 0.649832 | [
"MIT"
] | zcemycl/algoTest | cs/sample/Sample.Tests/MergeIntervals/testMergeIntervals.cs | 297 | C# |
using Recoil.net.DevTools.Converters;
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace Recoil.net.DevTools.Converters
{
/// <summary>
/// Convertert to convert from null to visibility
/// </summary>
public class NullToVisibilityConverter : IValueConverter
{
public static NullToVisibilityConverter CollapsedWhenNull { get; }
public static NullToVisibilityConverter CollapsedWhenNotNull { get; }
public static NullToVisibilityConverter HiddenWhenNull { get; }
public static NullToVisibilityConverter HiddenWhenNotNull { get; }
/// <summary>
/// Gets if the converter is inverted
/// </summary>
public bool Inverted { get; }
/// <summary>
/// Gets the state what happens when it's not visible
/// </summary>
public Visibility NonVisibleState { get; }
static NullToVisibilityConverter()
{
CollapsedWhenNull = new NullToVisibilityConverter(false, Visibility.Collapsed);
CollapsedWhenNotNull = new NullToVisibilityConverter(true, Visibility.Collapsed);
HiddenWhenNull = new NullToVisibilityConverter(false, Visibility.Hidden);
HiddenWhenNotNull = new NullToVisibilityConverter(true, Visibility.Hidden);
}
public NullToVisibilityConverter(bool inverted, Visibility visibility)
{
Inverted = inverted;
NonVisibleState = visibility;
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool isVisible = value != null;
if (Inverted)
{
isVisible = !isVisible;
}
return isVisible ? Visibility.Visible : NonVisibleState;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| 28.721311 | 97 | 0.750571 | [
"Apache-2.0"
] | ByronMayne/Recoil.Net | src/Recoil.net.DevTools/Converters/NullToVisibilityConverter.cs | 1,754 | C# |
//-----------------------------------------------------------------------
// <copyright file="ComponentServices.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright>
//-----------------------------------------------------------------------
namespace MSBuild.ExtensionPack.Computer
{
using System;
using System.EnterpriseServices;
using System.Globalization;
using System.Linq;
using COMAdmin;
using Microsoft.Build.Framework;
using Microsoft.Win32;
internal enum CSActivation
{
/// <summary>
/// Inproc
/// </summary>
Inproc = 0,
/// <summary>
/// Local
/// </summary>
Local = 1
}
/// <summary>
/// <b>Valid TaskActions are:</b>
/// <para><i>AddComponent</i> (<b>Required: </b>Path, ApplicationName <b>Optional: </b>Activation, Identity, UserPassword, Framework)</para>
/// <para><i>AddNativeComponent</i> (<b>Required: </b>Path, ApplicationName <b>Optional: </b>Activation, Identity, UserPassword, Framework)</para>
/// <para><i>CheckApplicationExists</i> (<b>Required: </b> ApplicationName <b>Output: </b>Exists)</para>
/// <para><i>CreateApplication</i> (<b>Required: </b> ApplicationName <b>Optional: </b>Activation, EnforceAccessChecks, Identity, UserPassword)</para>
/// <para><i>DeleteApplication</i> (<b>Required: </b>ApplicationName)</para>
/// <para><i>RemoveComponent</i> (<b>Required: </b>Path <b>Optional: </b>Framework)</para>
/// <para><i>SetConstructor</i> (<b>Required: </b>ApplicationName, ComponentName, ConstructorString)</para>
/// <para><i>SetAccessIisIntrinsicProperties</i> (<b>Required: </b>ApplicationName, ComponentName <b>Optional: </b>AllowIntrinsicIisProperties)</para>
/// <para><i>SetTransactionSupport</i> (<b>Required: </b>ApplicationName, ComponentName, Transaction)</para>
/// <para><i>ShutDownApplication</i> (<b>Required: </b>ApplicationName)</para>
/// <para><i>UpdateApplication</i> (<b>Required: </b>ApplicationName <b>Optional: </b>Activation, Identity, UserPassword)</para>
/// <para><b>Remote Execution Support:</b> No</para>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <Target Name="Default">
/// <!--- Add a component -->
/// <MSBuild.ExtensionPack.Computer.ComponentServices TaskAction="AddComponent" Path="C:\Projects\CodePlex\MSBuildExtensionPack\Solutions\Main3.5\SampleScratchpad\SampleBuildBinaries\EntServices.dll" ApplicationName="MyApplication" Identity="Interactive User"/>
/// <!-- Check it exists -->
/// <MSBuild.ExtensionPack.Computer.ComponentServices TaskAction="CheckApplicationExists" ApplicationName="MyApplication">
/// <Output TaskParameter="Exists" PropertyName="DoI"/>
/// </MSBuild.ExtensionPack.Computer.ComponentServices>
/// <Message Text="Exists: $(DoI)"/>
/// <!--- Remove the component -->
/// <MSBuild.ExtensionPack.Computer.ComponentServices TaskAction="RemoveComponent" Path="C:\Projects\CodePlex\MSBuildExtensionPack\Solutions\Main3.5\SampleScratchpad\SampleBuildBinaries\EntServices.dll" ApplicationName="MyApplication"/>
/// <!-- Check it exists again-->
/// <MSBuild.ExtensionPack.Computer.ComponentServices TaskAction="CheckApplicationExists" ApplicationName="MyApplication">
/// <Output TaskParameter="Exists" PropertyName="DoI"/>
/// </MSBuild.ExtensionPack.Computer.ComponentServices>
/// <Message Text="Exists: $(DoI)"/>
/// <!--- Add a component -->
/// <MSBuild.ExtensionPack.Computer.ComponentServices TaskAction="AddComponent" Path="C:\Projects\CodePlex\MSBuildExtensionPack\Solutions\Main3.5\SampleScratchpad\SampleBuildBinaries\EntServices.dll" ApplicationName="MyApplication" Identity="Interactive User"/>
/// <!-- Check it exists -->
/// <MSBuild.ExtensionPack.Computer.ComponentServices TaskAction="CheckApplicationExists" ApplicationName="MyApplication">
/// <Output TaskParameter="Exists" PropertyName="DoI"/>
/// </MSBuild.ExtensionPack.Computer.ComponentServices>
/// <Message Text="Exists: $(DoI)"/>
/// <!-- Various quick tasks -->
/// <MSBuild.ExtensionPack.Computer.ComponentServices TaskAction="ShutDownApplication" ApplicationName="MyApplication"/>
/// <MSBuild.ExtensionPack.Computer.ComponentServices TaskAction="UpdateApplication" Activation="Inproc" ApplicationName="MyApplication"/>
/// <MSBuild.ExtensionPack.Computer.ComponentServices TaskAction="SetTransactionSupport" Transaction="RequiresNew" ComponentName="BankComponent.Account" ApplicationName="MyApplication"/>
/// <MSBuild.ExtensionPack.Computer.ComponentServices TaskAction="SetConstructor" ComponentName="BankComponent.Account" ApplicationName="MyApplication" ConstructorString="demo"/>
/// <MSBuild.ExtensionPack.Computer.ComponentServices TaskAction="SetConstructor" ComponentName="BankComponent.Account" ApplicationName="MyApplication" ConstructorString=""/>
/// <MSBuild.ExtensionPack.Computer.ComponentServices TaskAction="DeleteApplication" ApplicationName="MyApplication"/>
/// </Target>
/// </Project>
/// ]]></code>
/// </example>
public class ComponentServices : BaseTask
{
private ShellWrapper shellWrapper;
private string framework = "v2.0.50727";
private CSActivation activation = CSActivation.Local;
private string pathToFramework;
private TransactionOption compTransaction = TransactionOption.NotSupported;
private bool enforceAccessChecks = true;
/// <summary>
/// Gets whether the application exists.
/// </summary>
[Output]
public bool Exists { get; set; }
/// <summary>
/// Sets the name of the COM+ component
/// </summary>
public string ComponentName { get; set; }
/// <summary>
/// Sets the Transaction support for the component. Supports: Ignored, None [Default], Supported, Required, RequiresNew
/// </summary>
public string Transaction
{
get { return this.compTransaction.ToString(); }
set { this.compTransaction = (TransactionOption)Enum.Parse(typeof(TransactionOption), value); }
}
/// <summary>
/// Sets the constructor string for the specified COM+ component. If empty, then the constructor support is removed
/// </summary>
public string ConstructorString { get; set; }
/// <summary>
/// Sets the name of the COM+ Application.
/// </summary>
public string ApplicationName { get; set; }
/// <summary>
/// Sets the path to the DLL to be added to the application
/// </summary>
public string Path { get; set; }
/// <summary>
/// Sets the process identity for the application. Specify a valid user account or "Interactive User" to have the application assume the identity of the current logged-on user.
/// </summary>
public string Identity { get; set; }
/// <summary>
/// Sets the version of the .NET FrameWork. Defaults to "v2.0.50727"
/// </summary>
public string Framework
{
get { return this.framework; }
set { this.framework = value; }
}
/// <summary>
/// Sets the type of activation for the application. Defaults to "Local". Supports: Local (server application), Inproc (library application)
/// </summary>
public string Activation { get; set; }
/// <summary>
/// Sets whether or not component services enforces access checks for this application. Defaults to "True". Supports: True (Enforce access checks), False
/// </summary>
public bool EnforceAccessChecks
{
get { return this.enforceAccessChecks; }
set { this.enforceAccessChecks = value; }
}
/// <summary>
/// Sets whether or not component services allows access to Intrinsic IIS properties, used for Windows 2003
/// components on Windows 2008 and later. Defaults to "False". Supports: True, False (allow access to Intrinsic IIS properties)
/// </summary>
public bool AllowIntrinsicIisProperties { get; set; }
protected override void InternalExecute()
{
if (!string.IsNullOrEmpty(this.Activation))
{
this.activation = (CSActivation)Enum.Parse(typeof(CSActivation), this.Activation, true);
}
this.GetPathToFramework();
switch (this.TaskAction)
{
case "AddComponent":
this.AddComponent();
break;
case "AddNativeComponent":
this.AddNativeComponent();
break;
case "SetTransactionSupport":
this.SetTransactionSupport();
break;
case "SetConstructor":
this.SetConstructor();
break;
case "SetAccessIisIntrinsicProperties":
this.SetAccessIisIntrinsicProperties();
break;
case "DeleteApplication":
this.DeleteApplication();
break;
case "ShutDownApplication":
this.ShutDownApplication();
break;
case "StartApplication":
this.StartApplication();
break;
case "UpdateApplication":
this.UpdateApplication();
break;
case "CheckApplicationExists":
this.Exists = this.CheckApplicationExists();
break;
case "RemoveComponent":
this.RemoveComponent();
break;
case "CreateApplication":
this.CreateApplication();
break;
default:
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
return;
}
}
private static COMAdminCatalogCollection GetApplications()
{
var objAdmin = new COMAdmin.COMAdminCatalog();
var objCollection = (COMAdmin.COMAdminCatalogCollection)objAdmin.GetCollection("Applications");
objCollection.Populate();
return objCollection;
}
private bool IsValidAssemblyFile(string path)
{
try
{
System.Reflection.Assembly.LoadFrom(path);
return true;
}
catch (BadImageFormatException)
{
Log.LogError("The Assembly is not a valid .Net assembly");
return false;
}
}
private bool CheckApplicationExists()
{
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Checking whether Application exists: {0}", this.ApplicationName));
COMAdminCatalogCollection appCollection = GetApplications();
if (appCollection.Cast<COMAdminCatalogObject>().Any(app => app.Name.ToString() == this.ApplicationName))
{
this.Exists = true;
return true;
}
return false;
}
private void GetPathToFramework()
{
RegistryKey runtimeKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework");
if (runtimeKey != null)
{
this.pathToFramework = Convert.ToString(runtimeKey.GetValue("InstallRoot"), CultureInfo.CurrentCulture);
runtimeKey.Close();
}
}
private void SetTransactionSupport()
{
if (!this.CheckApplicationExists())
{
return;
}
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "SetTransactionSupport on Component: {0}", this.ComponentName));
COMAdminCatalogCollection appCollection = GetApplications();
foreach (COMAdmin.COMAdminCatalogObject app in appCollection)
{
if (app.Name.ToString() == this.ApplicationName)
{
COMAdmin.ICatalogCollection componentCollection = (COMAdmin.ICatalogCollection)appCollection.GetCollection("Components", app.Key);
componentCollection.Populate();
foreach (COMAdmin.COMAdminCatalogObject component in componentCollection)
{
if (component.Name.ToString() == this.ComponentName)
{
if (!string.IsNullOrEmpty(this.Transaction))
{
component.set_Value("Transaction", this.compTransaction);
}
componentCollection.SaveChanges();
break;
}
}
break;
}
}
appCollection.SaveChanges();
}
private void SetConstructor()
{
if (!this.CheckApplicationExists())
{
return;
}
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "SetConstructor on Component: {0}", this.ComponentName));
COMAdminCatalogCollection appCollection = GetApplications();
foreach (COMAdmin.COMAdminCatalogObject app in appCollection)
{
if (app.Name.ToString() == this.ApplicationName)
{
COMAdmin.ICatalogCollection componentCollection = (COMAdmin.ICatalogCollection)appCollection.GetCollection("Components", app.Key);
componentCollection.Populate();
foreach (COMAdmin.COMAdminCatalogObject component in componentCollection)
{
if (component.Name.ToString() == this.ComponentName)
{
component.set_Value("ConstructionEnabled", !string.IsNullOrEmpty(this.ConstructorString));
component.set_Value("ConstructorString", this.ConstructorString ?? string.Empty);
componentCollection.SaveChanges();
break;
}
}
break;
}
}
appCollection.SaveChanges();
}
private void SetAccessIisIntrinsicProperties()
{
if (!this.CheckApplicationExists())
{
return;
}
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "SetAccessIisIntrinsicProperties on Component: {0}", this.ComponentName));
COMAdminCatalogCollection appCollection = GetApplications();
foreach (COMAdmin.COMAdminCatalogObject app in appCollection)
{
if (app.Name.ToString() == this.ApplicationName)
{
COMAdmin.ICatalogCollection componentCollection = (COMAdmin.ICatalogCollection)appCollection.GetCollection("Components", app.Key);
componentCollection.Populate();
foreach (COMAdmin.COMAdminCatalogObject component in componentCollection)
{
if (component.Name.ToString() == this.ComponentName)
{
component.set_Value("IISIntrinsics", this.AllowIntrinsicIisProperties);
componentCollection.SaveChanges();
break;
}
}
break;
}
}
appCollection.SaveChanges();
}
private void UpdateApplication()
{
if (!this.CheckApplicationExists())
{
return;
}
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Updating: {0}", this.ApplicationName));
COMAdminCatalogCollection appCollection = GetApplications();
foreach (COMAdmin.COMAdminCatalogObject app in appCollection)
{
if (app.Name.ToString() == this.ApplicationName)
{
if (!string.IsNullOrEmpty(this.Identity))
{
app.set_Value("Identity", this.Identity);
app.set_Value("Password", this.UserPassword ?? string.Empty);
}
app.set_Value("Activation", this.activation.ToString());
app.set_Value("ApplicationAccessChecksEnabled", this.EnforceAccessChecks);
appCollection.SaveChanges();
break;
}
}
}
private void StartApplication()
{
if (this.CheckApplicationExists())
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Starting Application: {0}", this.ApplicationName));
COMAdmin.COMAdminCatalog f = new COMAdminCatalog();
f.StartApplication(this.ApplicationName);
}
}
private void ShutDownApplication()
{
if (this.CheckApplicationExists())
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Stopping Application: {0}", this.ApplicationName));
COMAdmin.COMAdminCatalog f = new COMAdminCatalog();
f.ShutdownApplication(this.ApplicationName);
}
}
private void RemoveComponent()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Removing Component: {0}", this.Path));
if (System.IO.File.Exists(this.Path) == false)
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Path not found: {0}", this.Path));
return;
}
if (this.IsValidAssemblyFile(this.Path))
{
string args = string.Format(CultureInfo.CurrentCulture, @"/quiet /u ""{0}""", this.Path);
this.shellWrapper = new ShellWrapper(System.IO.Path.Combine(System.IO.Path.Combine(this.pathToFramework, this.framework), "regsvcs.exe"), args);
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Executing {0} with {1}", this.shellWrapper.Executable, this.shellWrapper.Arguments));
if (this.shellWrapper.Execute() != 0)
{
this.Log.LogError("Shell execute failed: " + this.shellWrapper.StandardOutput);
}
}
}
private void DeleteApplication()
{
if (!this.CheckApplicationExists())
{
return;
}
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Deleting Application: {0}", this.ApplicationName));
COMAdminCatalogCollection appCollection = GetApplications();
int i = 0;
foreach (COMAdmin.COMAdminCatalogObject cat in appCollection)
{
if (cat.Name.ToString() == this.ApplicationName)
{
appCollection.Remove(i);
appCollection.SaveChanges();
break;
}
i++;
}
}
private void CreateApplication()
{
if (this.CheckApplicationExists())
{
return;
}
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Creating Application: {0}", this.ApplicationName));
COMAdminCatalogCollection appCollection = GetApplications();
COMAdminCatalogObject app = (COMAdminCatalogObject)appCollection.Add();
app.set_Value("Name", this.ApplicationName);
if (!string.IsNullOrEmpty(this.Identity))
{
app.set_Value("Identity", this.Identity);
app.set_Value("Password", this.UserPassword ?? string.Empty);
}
app.set_Value("Activation", this.activation.ToString());
app.set_Value("ApplicationAccessChecksEnabled", this.EnforceAccessChecks);
appCollection.SaveChanges();
}
private void AddComponent()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Adding Component: {0} to Application: {1}", this.Path, this.ApplicationName));
if (System.IO.File.Exists(this.Path) == false)
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Path not found: {0}", this.Path));
return;
}
if (this.IsValidAssemblyFile(this.Path))
{
this.shellWrapper = new ShellWrapper(System.IO.Path.Combine(System.IO.Path.Combine(this.pathToFramework, this.framework), "regsvcs.exe"), string.IsNullOrEmpty(this.ApplicationName) ? string.Format(CultureInfo.CurrentCulture, @"/quiet ""{0}""", this.Path) : string.Format(CultureInfo.CurrentCulture, @"/quiet ""{0}"" ""{1}""", this.Path, this.ApplicationName));
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Executing {0} with {1}", this.shellWrapper.Executable, this.shellWrapper.Arguments));
if (this.shellWrapper.Execute() != 0)
{
this.Log.LogError("Shell execute failed: " + this.shellWrapper.StandardOutput);
}
}
}
private void AddNativeComponent()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Adding Native Component: {0} to Application: {1}", this.Path, this.ApplicationName));
if (System.IO.File.Exists(this.Path) == false)
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Path not found: {0}", this.Path));
return;
}
COMAdminCatalogCollection appCollection = GetApplications();
bool appExists = false;
foreach (COMAdmin.COMAdminCatalogObject app in appCollection)
{
if (app.Name.ToString() == this.ApplicationName)
{
appExists = true;
var cat = new COMAdminCatalog();
cat.InstallComponent(app.Key.ToString(), this.Path, string.Empty, string.Empty);
break;
}
}
if (!appExists)
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Application not found: {0}", this.ApplicationName));
}
}
}
} | 46.893333 | 377 | 0.562655 | [
"MIT"
] | BlackFrog1/MSBuildExtensionPack | Releases/4.0.9.0/Main/Framework/Computer/ComponentServices.cs | 24,619 | C# |
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Laurus.ProdTest.Core;
namespace Laurus.ProdTest.UnitTests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void RunDiscovery()
{
//var disco = new Core.Discovery();
//var devices = disco.DiscoverDevices();
//Assert.IsFalse(devices.First().DeviceName.Equals("tyDisc"));
}
[TestMethod]
public void Discover_Connect_Read()
{
//var disco = new Core.Discovery();
//var devices = disco.DiscoverDevices();
//var connection = new Core.Connection();
//var stream = connection.Connect(devices.First());
//var bytes = connection.Read(stream);
//Assert.IsTrue(bytes.Any());
}
[TestMethod]
public void VerifyRegexValid()
{
//string addr = "F4:FC:32:1B:1F:16";
//Assert.IsTrue(addr.IsBluetoothAddress());
}
[TestMethod]
public void VerifyRegexNotAddr()
{
//string addr = "tyDisc";
//Assert.IsFalse(addr.IsBluetoothAddress());
}
}
}
| 27.340426 | 74 | 0.564202 | [
"MIT"
] | thebeekeeper/Laurus.ProdTest | Laurus.ProdTest.UnitTests/UnitTest1.cs | 1,287 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Negocio
{
public class clFornecedores
{
//propriedades
public string banco { get; set; }
public int CodigoFornecedor { get; set; }
public string NomeDaEmpresa { get; set; }
public string NomeDoContato { get; set; }
public string Endereco { get; set; }
public string Bairro { get; set; }
public string Numero { get; set; }
public string Cidade { get; set; }
public string Estado { get; set; }
public string CEP { get; set; }
public string Telefone { get; set; }
public string CPF { get; set; }
public void Gravar()
{
//variável utilizada para "concatenar" texto de forma estruturada
StringBuilder strQuery = new StringBuilder();
//montagem do INSERT
strQuery.Append("INSERT INTO tbFornecedores");
strQuery.Append(" ( ");
strQuery.Append(" NomeDaEmpresa ");
strQuery.Append(", NomeDoContato ");
strQuery.Append(", Endereco ");
strQuery.Append(", Bairro ");
strQuery.Append(", Numero ");
strQuery.Append(", Cidade ");
strQuery.Append(", Estado ");
strQuery.Append(", CEP ");
strQuery.Append(", Telefone ");
strQuery.Append(", CPF ");
strQuery.Append(" ) ");
strQuery.Append(" VALUES ( ");
strQuery.Append(" '" + NomeDaEmpresa + "'");
strQuery.Append(",'" + NomeDoContato + "'");
strQuery.Append(",'" + Endereco + "'");
strQuery.Append(",'" + Bairro + "'");
strQuery.Append(",'" + Numero + "'");
strQuery.Append(",'" + Cidade + "'");
strQuery.Append(",'" + Estado + "'");
strQuery.Append(",'" + CEP + "'");
strQuery.Append(",'" + Telefone + "'");
strQuery.Append(",'" + CPF + "'");
strQuery.Append(" ); ");
//instancia a classe clAcessoDB e executa o comando
clAcessoDB clAcessoDB = new clAcessoDB();
clAcessoDB.vConexao = banco;
clAcessoDB.ExecutaComando(strQuery.ToString());
}
public void Alterar()
{
StringBuilder strQuery = new StringBuilder();
//montagem de update
strQuery.Append("UPDATE tbFornecedores");
strQuery.Append(" SET ");
strQuery.Append(" NomeDaEmpresa = '" + NomeDaEmpresa + "'");
strQuery.Append(", NomeDoContato = '" + NomeDoContato + "'");
strQuery.Append(", Endereco = '" + Endereco + "'");
strQuery.Append(", Bairro = '" + Bairro + "'");
strQuery.Append(", Numero = '" + Numero + "'");
strQuery.Append(", Cidade = '" + Cidade + "'");
strQuery.Append(", Estado = '" + Estado + "'");
strQuery.Append(", Cep = '" + CEP + "'");
strQuery.Append(", Telefone = '" + Telefone + "'");
strQuery.Append(", CPF = '" + CPF + "'");
strQuery.Append(" WHERE ");
strQuery.Append(" CodigoFornecedor = " + CodigoFornecedor);
//instancia a classe clAcessoDB e executa o comando
clAcessoDB clAcessoDB = new clAcessoDB();
clAcessoDB.vConexao = banco;
clAcessoDB.ExecutaComando(strQuery.ToString());
}
public void Excluir()
{
StringBuilder strQuery = new StringBuilder();
//montagem do delete
strQuery.Append(" DELETE FROM tbFornecedores ");
strQuery.Append(" WHERE ");
strQuery.Append(" CodigoFornecedor = " + CodigoFornecedor);
//instancia a classe clAcessoDB e executa o comando
clAcessoDB clAcessoDB = new clAcessoDB();
clAcessoDB.vConexao = banco;
clAcessoDB.ExecutaComando(strQuery.ToString());
}
public DataSet Pesquisar(string Campo, string Filtro)
{
StringBuilder strQuery = new StringBuilder();
//montagem do select
strQuery.Append(" SELECT * ");
strQuery.Append(" FROM tbFornecedores ");
if (Campo != string.Empty && Filtro != string.Empty)
{
strQuery.Append(" WHERE ");
strQuery.Append(Campo + " LIKE '" + "%" + Filtro + "%" + "'");
}
strQuery.Append(" ORDER BY CodigoFornecedor ");
//executa o comando
clAcessoDB clAcessoDB = new clAcessoDB();
clAcessoDB.vConexao = banco;
return clAcessoDB.RetornaDataSet(strQuery.ToString());
}
public SqlDataReader PesquisarCodigo(int CodigoFornecedor)
{
StringBuilder strQuery = new StringBuilder();
//montagem do select
strQuery.Append(" SELECT * ");
strQuery.Append(" FROM tbFornecedores ");
strQuery.Append(" WHERE ");
strQuery.Append(" CodigoFornecedor = " + CodigoFornecedor);
//executa o comando
clAcessoDB clAcessoDB = new clAcessoDB();
clAcessoDB.vConexao = banco;
return clAcessoDB.RetornaDataReader(strQuery.ToString());
}
public SqlDataReader PesquisarCPF(string CPF)
{
StringBuilder strQuery = new StringBuilder();
//montagem do select
strQuery.Append(" SELECT * ");
strQuery.Append(" FROM tbFornecedores ");
strQuery.Append(" WHERE ");
strQuery.Append(" CPF = '" + CPF + "'");
//executa o comando
clAcessoDB clAcessoDB = new clAcessoDB();
clAcessoDB.vConexao = banco;
return clAcessoDB.RetornaDataReader(strQuery.ToString());
}
}
}
| 37.791411 | 79 | 0.524513 | [
"MIT"
] | ricardohtakuno/Cadastro_de_Cliente | Dados do Cliente/AcessoDB/clFornecedores.cs | 6,163 | C# |
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
namespace JwtBlogArtikelApi.Models
{
[Index(nameof(Mail), IsUnique = true)]
public class Email
{
public int Id { get; set; }
public bool? Activated { get; set; } = false;
public bool? NewsSignup { get; set; } = false;
[JsonIgnore]
public User? User { get; set; } = null;
public string Mail { get; set; }
}
}
| 27.444444 | 54 | 0.635628 | [
"Apache-2.0"
] | alexander-lawaetz/final-exam | JwtBlogArtikelApi/JwtBlogArtikelApi/Models/Email.cs | 496 | C# |
// -----------------------------------------------------------------------
// <copyright file="ExcelFormatHelper.cs" company="">
// Copyright 2014 Alexander Soffronow Pagonidis
// </copyright>
// -----------------------------------------------------------------------
using System.Collections.Generic;
using OfficeOpenXml;
namespace QPAS
{
/// <summary>
/// Give this class a worksheet with a row of formatted cells.
/// It saves that formatting and then applies it to an entire columnar range.
/// Used to grab formatting from a template and then apply it to data.
/// </summary>
public class ExcelFormatHelper
{
private readonly Dictionary<int, string> _formats;
private readonly int _startRow;
private readonly int _startCol;
public ExcelFormatHelper(string addressStart, int columns, ExcelWorksheet ws)
{
var startCell = ws.Cells[addressStart];
_startCol = startCell.Start.Column;
_startRow = startCell.Start.Row;
_formats = new Dictionary<int, string>();
for (int i = 0; i < columns; i++)
{
int col = _startCol + i;
_formats.Add(col, ws.Cells[_startRow, col].Style.Numberformat.Format);
}
}
public void Apply(ExcelWorksheet ws, int rows)
{
for (int i = 0; i < _formats.Count; i++)
{
ws.Cells[_startRow, _startCol, _startRow + rows, _startCol + i].Style.Numberformat.Format = _formats[i];
}
}
}
}
| 32.9375 | 120 | 0.543327 | [
"BSD-3-Clause"
] | esusini/QPAS | QPAS/Utilities/ExcelFormatHelper.cs | 1,583 | C# |
public class Torpedo : Missile
{
void Awake()
{
seekBehavior = new SeekWithSonar();
}
}
| 13.625 | 43 | 0.568807 | [
"MIT"
] | PacktPublishing/Hands-On-Game-Development-Patterns-with-Unity-2018 | Assets/Patterns/Strategy/Torpedo.cs | 111 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using UnityEngine;
namespace BDFramework.Http
{
public class HttpClient : WebClient
{
public HttpClient()
{
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = WebRequest.Create(address);
request.Timeout = 8000;
return request;
}
}
}
| 19.357143 | 64 | 0.638376 | [
"Apache-2.0"
] | HugoFang/BDFramework.Core | Assets/Code/BDFramework/Core/HttpMgr/HttpClient.cs | 544 | 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.Sfn
{
/// <summary>
/// Provides a Step Function State Machine resource
///
///
///
/// > This content is derived from https://github.com/terraform-providers/terraform-provider-aws/blob/master/website/docs/r/sfn_state_machine.html.markdown.
/// </summary>
public partial class StateMachine : Pulumi.CustomResource
{
/// <summary>
/// The date the state machine was created.
/// </summary>
[Output("creationDate")]
public Output<string> CreationDate { get; private set; } = null!;
/// <summary>
/// The Amazon States Language definition of the state machine.
/// </summary>
[Output("definition")]
public Output<string> Definition { get; private set; } = null!;
/// <summary>
/// The name of the state machine.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The Amazon Resource Name (ARN) of the IAM role to use for this state machine.
/// </summary>
[Output("roleArn")]
public Output<string> RoleArn { get; private set; } = null!;
/// <summary>
/// The current status of the state machine. Either "ACTIVE" or "DELETING".
/// </summary>
[Output("status")]
public Output<string> Status { get; private set; } = null!;
/// <summary>
/// Key-value mapping of resource tags
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, object>?> Tags { get; private set; } = null!;
/// <summary>
/// Create a StateMachine resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public StateMachine(string name, StateMachineArgs args, CustomResourceOptions? options = null)
: base("aws:sfn/stateMachine:StateMachine", name, args ?? ResourceArgs.Empty, MakeResourceOptions(options, ""))
{
}
private StateMachine(string name, Input<string> id, StateMachineState? state = null, CustomResourceOptions? options = null)
: base("aws:sfn/stateMachine:StateMachine", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing StateMachine resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static StateMachine Get(string name, Input<string> id, StateMachineState? state = null, CustomResourceOptions? options = null)
{
return new StateMachine(name, id, state, options);
}
}
public sealed class StateMachineArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The Amazon States Language definition of the state machine.
/// </summary>
[Input("definition", required: true)]
public Input<string> Definition { get; set; } = null!;
/// <summary>
/// The name of the state machine.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The Amazon Resource Name (ARN) of the IAM role to use for this state machine.
/// </summary>
[Input("roleArn", required: true)]
public Input<string> RoleArn { get; set; } = null!;
[Input("tags")]
private InputMap<object>? _tags;
/// <summary>
/// Key-value mapping of resource tags
/// </summary>
public InputMap<object> Tags
{
get => _tags ?? (_tags = new InputMap<object>());
set => _tags = value;
}
public StateMachineArgs()
{
}
}
public sealed class StateMachineState : Pulumi.ResourceArgs
{
/// <summary>
/// The date the state machine was created.
/// </summary>
[Input("creationDate")]
public Input<string>? CreationDate { get; set; }
/// <summary>
/// The Amazon States Language definition of the state machine.
/// </summary>
[Input("definition")]
public Input<string>? Definition { get; set; }
/// <summary>
/// The name of the state machine.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The Amazon Resource Name (ARN) of the IAM role to use for this state machine.
/// </summary>
[Input("roleArn")]
public Input<string>? RoleArn { get; set; }
/// <summary>
/// The current status of the state machine. Either "ACTIVE" or "DELETING".
/// </summary>
[Input("status")]
public Input<string>? Status { get; set; }
[Input("tags")]
private InputMap<object>? _tags;
/// <summary>
/// Key-value mapping of resource tags
/// </summary>
public InputMap<object> Tags
{
get => _tags ?? (_tags = new InputMap<object>());
set => _tags = value;
}
public StateMachineState()
{
}
}
}
| 35.748663 | 163 | 0.57801 | [
"ECL-2.0",
"Apache-2.0"
] | Dominik-K/pulumi-aws | sdk/dotnet/Sfn/StateMachine.cs | 6,685 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.ComponentModel.Design
{
public class DesignerTransactionCloseEventArgs : EventArgs
{
/// <summary>
/// Creates a new event args. Commit is true if the transaction is committed. This
/// defaults the LastTransaction property to true.
/// </summary>
[Obsolete("This constructor is obsolete. Use DesignerTransactionCloseEventArgs(bool, bool) instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public DesignerTransactionCloseEventArgs(bool commit) : this(commit, lastTransaction: true)
{
}
/// <summary>
/// Creates a new event args. Commit is true if the transaction is committed, and
/// lastTransaction is true if this is the last transaction to close.
/// </summary>
public DesignerTransactionCloseEventArgs(bool commit, bool lastTransaction)
{
TransactionCommitted = commit;
LastTransaction = lastTransaction;
}
public bool TransactionCommitted { get; }
public bool LastTransaction { get; }
}
}
| 38.53125 | 156 | 0.667478 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerTransactionCloseEventArgs.cs | 1,233 | C# |
using System;
using System.Transactions;
using Abp.Data;
using Abp.Dependency;
using Abp.Domain.Uow;
using Abp.EntityFrameworkCore;
using Abp.Extensions;
using Abp.MultiTenancy;
using Microsoft.EntityFrameworkCore;
namespace Abp.Zero.EntityFrameworkCore
{
public abstract class AbpZeroDbMigrator<TDbContext> : IAbpZeroDbMigrator, ITransientDependency
where TDbContext : DbContext
{
private readonly IUnitOfWorkManager _unitOfWorkManager;
private readonly IDbPerTenantConnectionStringResolver _connectionStringResolver;
private readonly IDbContextResolver _dbContextResolver;
protected AbpZeroDbMigrator(
IUnitOfWorkManager unitOfWorkManager,
IDbPerTenantConnectionStringResolver connectionStringResolver,
IDbContextResolver dbContextResolver)
{
_unitOfWorkManager = unitOfWorkManager;
_connectionStringResolver = connectionStringResolver;
_dbContextResolver = dbContextResolver;
}
public void CreateOrMigrateForHost()
{
CreateOrMigrateForHost(null);
}
public virtual void CreateOrMigrateForHost(Action<TDbContext> seedAction)
{
CreateOrMigrate(null, seedAction);
}
public void CreateOrMigrateForTenant(AbpTenantBase tenant)
{
CreateOrMigrateForTenant(tenant, null);
}
public virtual void CreateOrMigrateForTenant(AbpTenantBase tenant, Action<TDbContext> seedAction)
{
if (tenant.ConnectionString.IsNullOrEmpty())
{
return;
}
CreateOrMigrate(tenant, seedAction);
}
protected virtual void CreateOrMigrate(AbpTenantBase tenant, Action<TDbContext> seedAction)
{
var args = new DbPerTenantConnectionStringResolveArgs(
tenant == null ? (int?) null : (int?) tenant.Id,
tenant == null ? MultiTenancySides.Host : MultiTenancySides.Tenant
);
args["DbContextType"] = typeof(TDbContext);
args["DbContextConcreteType"] = typeof(TDbContext);
var nameOrConnectionString = ConnectionStringHelper.GetConnectionString(
_connectionStringResolver.GetNameOrConnectionString(args)
);
using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.Suppress))
{
using (var dbContext = _dbContextResolver.Resolve<TDbContext>(nameOrConnectionString, null))
{
dbContext.Database.Migrate();
seedAction?.Invoke(dbContext);
_unitOfWorkManager.Current.SaveChanges();
uow.Complete();
}
}
}
}
}
| 34.487805 | 108 | 0.64215 | [
"MIT"
] | muyumuqing/Abp.Zero3 | src/Abp.Zero.EntityFrameworkCore/Zero/EntityFrameworkCore/AbpZeroDbMigrator.cs | 2,830 | C# |
using Projecto.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Projecto.ViewModels
{
public class ProjectAssignmentsViewModel
{
public string ProjectName { get; set; }
public IEnumerable<UserInfo> Users { get; set; }
public IEnumerable<AssigneeInfo> Assignees { get; set; }
public class UserInfo
{
public int Id { get; set; }
public string Name { get; set; }
}
public class AssigneeInfo : IEquatable<AssigneeInfo>
{
public int Id { get; set; }
public int RoleId { get; set; }
public string Role { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int AssignmentId { get; set; }
public bool Equals(AssigneeInfo other) => Id == other.Id;
}
}
}
| 27.647059 | 69 | 0.582979 | [
"Apache-2.0"
] | medvedbeast/Projecto | projecto/ViewModels/Project/ProjectAssignmentsViewModel.cs | 942 | C# |
namespace AzureFromTheTrenches.Commanding.Abstractions
{
public interface ICommandAuditSerializer
{
string Serialize(ICommand command);
}
}
| 20.125 | 55 | 0.73913 | [
"MIT"
] | cjrpriest/AzureFromTheTrenches.Commanding | Source/AzureFromTheTrenches.Commanding.Abstractions/ICommandAuditSerializer.cs | 163 | C# |
using Net.LawORM.Entity.Base;
using System;
namespace BuroAsistan.Source.BO
{
internal class Person : BaseBO
{
private int _OBJID;
public int OBJID
{
set { _OBJID = value; OnPropertyChanged("OBJID"); }
get { return _OBJID; }
}
private string _FirstName;
public string FirstName
{
set { _FirstName = value; OnPropertyChanged("FirstName"); }
get { return _FirstName; }
}
private string _ForeName;
public string ForeName
{
set { _ForeName = value; OnPropertyChanged("ForeName"); }
get { return _ForeName; }
}
private string _LastName;
public string LastName
{
set { _LastName = value; OnPropertyChanged("LastName"); }
get { return _LastName; }
}
private string _IdentityNo;
public string IdentityNo
{
set { _IdentityNo = value; OnPropertyChanged("IdentityNo"); }
get { return _IdentityNo; }
}
private DateTime _CreationTime;
public DateTime CreationTime
{
set { _CreationTime = value; OnPropertyChanged("CreationTime"); }
get { return _CreationTime; }
}
private string _Adress;
public string Adress
{
set { _Adress = value; OnPropertyChanged("Adress"); }
get { return _Adress; }
}
private string _Details;
public string Details
{
set { _Details = value; OnPropertyChanged("Details"); }
get { return _Details; }
}
private int _IsActive;
public int IsActive
{
set { _IsActive = value; OnPropertyChanged("IsActive"); }
get { return _IsActive; }
}
public override string GetTableName()
{
return "Person";
}
public override string GetIdColumn()
{
return "OBJID";
}
}
} | 22.977778 | 77 | 0.526596 | [
"Apache-2.0"
] | mustafasacli/BuroAsistan.Repo | BuroAsistan/BuroAsistan/Source/BO/Person.cs | 2,068 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
using HealthKit;
namespace HKWork
{
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
private HKHealthStore healthKitStore = new HKHealthStore ();
public override UIWindow Window {
get;
set;
}
public override void OnActivated (UIApplication application)
{
ValidateAuthorization ();
}
private void ValidateAuthorization ()
{
//Request / Validate that the app has permission to store heart-rate data
var heartRateId = HKQuantityTypeIdentifierKey.HeartRate;
var heartRateType = HKObjectType.GetQuantityType (heartRateId);
var typesToWrite = new NSSet (new [] { heartRateType });
//We aren't reading any data for this sample
var typesToRead = new NSSet ();
healthKitStore.RequestAuthorizationToShare (
typesToWrite,
typesToRead,
ReactToHealthCarePermissions);
}
//Note that this will be called on a background thread
void ReactToHealthCarePermissions (bool success, NSError error)
{
/*
* The success and error arguments specify whether the user interacted
* with the permissions dialog. This sample doesn't use that information.
*/
//Instead, the important thing is to confirm that we can write heart-rate data
var access = healthKitStore.GetAuthorizationStatus (HKObjectType.GetQuantityType (HKQuantityTypeIdentifierKey.HeartRate));
if (access.HasFlag (HKAuthorizationStatus.SharingAuthorized)) {
HeartRateModel.Instance.Enabled = true;
} else {
HeartRateModel.Instance.Enabled = false;
}
}
}
}
| 27.483333 | 125 | 0.742874 | [
"MIT"
] | Art-Lav/ios-samples | ios8/IntroToHealthKit/HKWork/AppDelegate.cs | 1,649 | C# |
[TrackClipTypeAttribute] // RVA: 0x12DC50 Offset: 0x12DD51 VA: 0x12DC50
[TrackBindingTypeAttribute] // RVA: 0x12DC50 Offset: 0x12DD51 VA: 0x12DC50
[TrackColorAttribute] // RVA: 0x12DC50 Offset: 0x12DD51 VA: 0x12DC50
[Serializable]
public class CinemachineTrack : TrackAsset // TypeDefIndex: 4729
{
// Methods
// RVA: 0x1A28110 Offset: 0x1A28211 VA: 0x1A28110 Slot: 24
public override Playable CreateTrackMixer(PlayableGraph graph, GameObject go, int inputCount) { }
// RVA: 0x1A281D0 Offset: 0x1A282D1 VA: 0x1A281D0
public void .ctor() { }
}
| 34.375 | 98 | 0.763636 | [
"MIT"
] | SinsofSloth/RF5-global-metadata | _no_namespace/CinemachineTrack.cs | 550 | C# |
/* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. 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.Runtime.Serialization;
using OpenSearch.Net;
namespace Osc
{
[StringEnum]
public enum SynonymFormat
{
[EnumMember(Value = "solr")]
Solr,
[EnumMember(Value = "wordnet")]
WordNet
}
}
| 29.790698 | 64 | 0.75566 | [
"Apache-2.0"
] | Bit-Quill/opensearch-net | src/Osc/Analysis/TokenFilters/Synonym/SynonymFormat.cs | 1,281 | C# |
using System;
using JetBrains.Annotations;
using OpenTK.Audio.OpenAL;
namespace Bearded.Audio;
/// <summary>
/// Generic OpenAL exception.
/// </summary>
[PublicAPI]
public class ALException : Exception
{
/// <summary>
/// The OpenAL error type.
/// </summary>
public ALError Type { get; }
/// <summary>
/// Creates a new instance.
/// </summary>
/// <param name="type">The OpenAL error type.</param>
/// <param name="message">The exception message.</param>
protected ALException(ALError type, string message) : base(message)
{
Type = type;
}
}
| 21.607143 | 71 | 0.626446 | [
"MIT"
] | beardgame/audio | src/Bearded.Audio/Core/exceptions/ALException.cs | 607 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using TaskMAN.Data;
using TaskMAN.Models;
namespace TaskMAN.Pages.TaskEntries
{
public class DeleteModel : PageModel
{
private readonly TaskMAN.Data.TaskMANContext _context;
public DeleteModel(TaskMAN.Data.TaskMANContext context)
{
_context = context;
}
[BindProperty]
public TaskEntry TaskEntry { get; set; }
public async Task<IActionResult> OnGetAsync(int? id)
{
if (id == null)
{
return NotFound();
}
TaskEntry = await _context.TaskEntry.FirstOrDefaultAsync(m => m.ID == id);
if (TaskEntry == null)
{
return NotFound();
}
return Page();
}
public async Task<IActionResult> OnPostAsync(int? id)
{
if (id == null)
{
return NotFound();
}
TaskEntry = await _context.TaskEntry.FindAsync(id);
if (TaskEntry != null)
{
_context.TaskEntry.Remove(TaskEntry);
await _context.SaveChangesAsync();
}
return RedirectToPage("./Index");
}
}
}
| 24.016667 | 86 | 0.553088 | [
"Apache-2.0"
] | leftidev/TaskMAN | TaskMAN/Pages/TaskEntries/Delete.cshtml.cs | 1,443 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace RWLayout.alpha2.FastAccess
{
public partial class Dynamic
{
public static Func<TInstance, TResult> InstanceRetMethod<TInstance, TResult>(string methodName, BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) where TInstance : class
{
var method = typeof(TInstance).GetMethod(methodName, bindingAttr);
return InstanceRetMethod<TInstance, TResult>(method);
}
public static Func<TInstance, TArg0, TResult> InstanceRetMethod<TInstance, TArg0, TResult>(string methodName, BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) where TInstance : class
{
var method = typeof(TInstance).GetMethod(methodName, bindingAttr);
return InstanceRetMethod<TInstance, TArg0, TResult>(method);
}
public static Func<TInstance, TArg0, TArg1, TResult> InstanceRetMethod<TInstance, TArg0, TArg1, TResult>(string methodName, BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) where TInstance : class
{
var method = typeof(TInstance).GetMethod(methodName, bindingAttr);
return InstanceRetMethod<TInstance, TArg0, TArg1, TResult>(method);
}
public static Func<TInstance, TArg0, TArg1, TArg2, TResult> InstanceRetMethod<TInstance, TArg0, TArg1, TArg2, TResult>(string methodName, BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) where TInstance : class
{
var method = typeof(TInstance).GetMethod(methodName, bindingAttr);
return InstanceRetMethod<TInstance, TArg0, TArg1, TArg2, TResult>(method);
}
public static Func<TInstance, TArg0, TArg1, TArg2, TArg3, TResult> InstanceRetMethod<TInstance, TArg0, TArg1, TArg2, TArg3, TResult>(string methodName, BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) where TInstance : class
{
var method = typeof(TInstance).GetMethod(methodName, bindingAttr);
return InstanceRetMethod<TInstance, TArg0, TArg1, TArg2, TArg3, TResult>(method);
}
public static Func<TInstance, TArg0, TArg1, TArg2, TArg3, TArg4, TResult> InstanceRetMethod<TInstance, TArg0, TArg1, TArg2, TArg3, TArg4, TResult>(string methodName, BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) where TInstance : class
{
var method = typeof(TInstance).GetMethod(methodName, bindingAttr);
return InstanceRetMethod<TInstance, TArg0, TArg1, TArg2, TArg3, TArg4, TResult>(method);
}
public static Func<TInstance, TResult> InstanceRetMethod<TInstance, TResult>(MethodInfo method) where TInstance : class
{
return CreateMethodCaller<Func<TInstance, TResult>>(method);
}
public static Func<TInstance, TArg0, TResult> InstanceRetMethod<TInstance, TArg0, TResult>(MethodInfo method) where TInstance : class
{
return CreateMethodCaller<Func<TInstance, TArg0, TResult>>(method);
}
public static Func<TInstance, TArg0, TArg1, TResult> InstanceRetMethod<TInstance, TArg0, TArg1, TResult>(MethodInfo method) where TInstance : class
{
return CreateMethodCaller<Func<TInstance, TArg0, TArg1, TResult>>(method);
}
public static Func<TInstance, TArg0, TArg1, TArg2, TResult> InstanceRetMethod<TInstance, TArg0, TArg1, TArg2, TResult>(MethodInfo method) where TInstance : class
{
return CreateMethodCaller<Func<TInstance, TArg0, TArg1, TArg2, TResult>>(method);
}
public static Func<TInstance, TArg0, TArg1, TArg2, TArg3, TResult> InstanceRetMethod<TInstance, TArg0, TArg1, TArg2, TArg3, TResult>(MethodInfo method) where TInstance : class
{
return CreateMethodCaller<Func<TInstance, TArg0, TArg1, TArg2, TArg3, TResult>>(method);
}
public static Func<TInstance, TArg0, TArg1, TArg2, TArg3, TArg4, TResult> InstanceRetMethod<TInstance, TArg0, TArg1, TArg2, TArg3, TArg4, TResult>(MethodInfo method) where TInstance : class
{
return CreateMethodCaller<Func<TInstance, TArg0, TArg1, TArg2, TArg3, TArg4, TResult>>(method);
}
}
}
| 54.698795 | 294 | 0.707048 | [
"MIT"
] | krypt-lynx/RWLayout | Source/RWLayout/FastAccess/Dynamic+InstanceRetMethod.cs | 4,542 | C# |
using UnityEngine;
namespace SBaier.Input.Test
{
public class TestSelectionAction : MonoBehaviour
{
[SerializeField]
private Selectable _selectable = null;
[SerializeField]
private MeshRenderer _meshRenderer = null;
[SerializeField]
private Material _notSelected = null;
[SerializeField]
private Material _selected = null;
protected virtual void Start()
{
_selectable.OnSelect += onSelect;
_selectable.OnDeselect += onDeselect;
}
protected virtual void OnDestroy()
{
_selectable.OnSelect -= onSelect;
_selectable.OnDeselect -= onDeselect;
}
private void onSelect(SelectableInputEventArgs args)
{
_meshRenderer.material = _selected;
Debug.Log($"Selected at {args.RaycastHit.Point}");
}
private void onDeselect()
{
_meshRenderer.material = _notSelected;
Debug.Log($"Deselected");
}
}
} | 20.428571 | 54 | 0.724942 | [
"MIT"
] | BlackLambert/unity-sbaier-input | Input/Assets/Script/SelectorTest/TestSelectionAction.cs | 860 | C# |
using System;
namespace TALib
{
public static partial class Core
{
public static RetCode HtDcPhase(double[] inReal, int startIdx, int endIdx, double[] outReal, out int outBegIdx,
out int outNbElement)
{
outBegIdx = outNbElement = 0;
if (startIdx < 0 || endIdx < 0 || endIdx < startIdx)
{
return RetCode.OutOfRangeStartIndex;
}
if (inReal == null || outReal == null)
{
return RetCode.BadParam;
}
int lookbackTotal = HtDcPhaseLookback();
if (startIdx < lookbackTotal)
{
startIdx = lookbackTotal;
}
if (startIdx > endIdx)
{
return RetCode.Success;
}
const int smoothPriceSize = 50;
var smoothPrice = new double[smoothPriceSize];
const double rad2Deg = 180.0 / Math.PI;
const double constDeg2RadBy360 = 2.0 * Math.PI;
outBegIdx = startIdx;
int trailingWMAIdx = startIdx - lookbackTotal;
int today = trailingWMAIdx;
double tempReal = inReal[today++];
double periodWMASub = tempReal;
double periodWMASum = tempReal;
tempReal = inReal[today++];
periodWMASub += tempReal;
periodWMASum += tempReal * 2.0;
tempReal = inReal[today++];
periodWMASub += tempReal;
periodWMASum += tempReal * 3.0;
double trailingWMAValue = default;
var i = 34;
do
{
tempReal = inReal[today++];
DoPriceWma(inReal, ref trailingWMAIdx, ref periodWMASub, ref periodWMASum, ref trailingWMAValue, tempReal, out _);
} while (--i != 0);
int hilbertIdx = default;
int smoothPriceIdx = default;
var hilbertVariables = InitHilbertVariables<double>();
int outIdx = default;
double prevI2, prevQ2, re, im, i1ForOddPrev3, i1ForEvenPrev3, i1ForOddPrev2, i1ForEvenPrev2, smoothPeriod, dcPhase;
double period = prevI2 = prevQ2 =
re = im = i1ForOddPrev3 = i1ForEvenPrev3 = i1ForOddPrev2 = i1ForEvenPrev2 = smoothPeriod = dcPhase = default;
while (today <= endIdx)
{
double i2;
double q2;
double adjustedPrevPeriod = 0.075 * period + 0.54;
DoPriceWma(inReal, ref trailingWMAIdx, ref periodWMASub, ref periodWMASum, ref trailingWMAValue, inReal[today],
out var smoothedValue);
smoothPrice[smoothPriceIdx] = smoothedValue;
if (today % 2 == 0)
{
DoHilbertEven(hilbertVariables, "detrender", smoothedValue, hilbertIdx, adjustedPrevPeriod);
DoHilbertEven(hilbertVariables, "q1", hilbertVariables["detrender"], hilbertIdx, adjustedPrevPeriod);
DoHilbertEven(hilbertVariables, "jI", i1ForEvenPrev3, hilbertIdx, adjustedPrevPeriod);
DoHilbertEven(hilbertVariables, "jQ", hilbertVariables["q1"], hilbertIdx, adjustedPrevPeriod);
if (++hilbertIdx == 3)
{
hilbertIdx = 0;
}
q2 = 0.2 * (hilbertVariables["q1"] + hilbertVariables["jI"]) + 0.8 * prevQ2;
i2 = 0.2 * (i1ForEvenPrev3 - hilbertVariables["jQ"]) + 0.8 * prevI2;
i1ForOddPrev3 = i1ForOddPrev2;
i1ForOddPrev2 = hilbertVariables["detrender"];
}
else
{
DoHilbertOdd(hilbertVariables, "detrender", smoothedValue, hilbertIdx, adjustedPrevPeriod);
DoHilbertOdd(hilbertVariables, "q1", hilbertVariables["detrender"], hilbertIdx, adjustedPrevPeriod);
DoHilbertOdd(hilbertVariables, "jI", i1ForOddPrev3, hilbertIdx, adjustedPrevPeriod);
DoHilbertOdd(hilbertVariables, "jQ", hilbertVariables["q1"], hilbertIdx, adjustedPrevPeriod);
q2 = 0.2 * (hilbertVariables["q1"] + hilbertVariables["jI"]) + 0.8 * prevQ2;
i2 = 0.2 * (i1ForOddPrev3 - hilbertVariables["jQ"]) + 0.8 * prevI2;
i1ForEvenPrev3 = i1ForEvenPrev2;
i1ForEvenPrev2 = hilbertVariables["detrender"];
}
re = 0.2 * (i2 * prevI2 + q2 * prevQ2) + 0.8 * re;
im = 0.2 * (i2 * prevQ2 - q2 * prevI2) + 0.8 * im;
prevQ2 = q2;
prevI2 = i2;
tempReal = period;
if (!im.Equals(0.0) && !re.Equals(0.0))
{
period = 360.0 / (Math.Atan(im / re) * rad2Deg);
}
double tempReal2 = 1.5 * tempReal;
if (period > tempReal2)
{
period = tempReal2;
}
tempReal2 = 0.67 * tempReal;
if (period < tempReal2)
{
period = tempReal2;
}
if (period < 6.0)
{
period = 6.0;
}
else if (period > 50.0)
{
period = 50.0;
}
period = 0.2 * period + 0.8 * tempReal;
smoothPeriod = 0.33 * period + 0.67 * smoothPeriod;
double dcPeriod = smoothPeriod + 0.5;
int dcPeriodInt = (int) dcPeriod;
double realPart = default;
double imagPart = default;
int idx = smoothPriceIdx;
for (i = 0; i < dcPeriodInt; i++)
{
tempReal = i * constDeg2RadBy360 / dcPeriodInt;
tempReal2 = smoothPrice[idx];
realPart += Math.Sin(tempReal) * tempReal2;
imagPart += Math.Cos(tempReal) * tempReal2;
if (idx == 0)
{
idx = smoothPriceSize - 1;
}
else
{
idx--;
}
}
tempReal = Math.Abs(imagPart);
if (tempReal > 0.0)
{
dcPhase = Math.Atan(realPart / imagPart) * rad2Deg;
}
else if (tempReal <= 0.01)
{
if (realPart < 0.0)
{
dcPhase -= 90.0;
}
else if (realPart > 0.0)
{
dcPhase += 90.0;
}
}
dcPhase += 90.0;
dcPhase += 360.0 / smoothPeriod;
if (imagPart < 0.0)
{
dcPhase += 180.0;
}
if (dcPhase > 315.0)
{
dcPhase -= 360.0;
}
if (today >= startIdx)
{
outReal[outIdx++] = dcPhase;
}
if (++smoothPriceIdx > smoothPriceSize - 1)
{
smoothPriceIdx = 0;
}
today++;
}
outNbElement = outIdx;
return RetCode.Success;
}
public static RetCode HtDcPhase(decimal[] inReal, int startIdx, int endIdx, decimal[] outReal, out int outBegIdx,
out int outNbElement)
{
outBegIdx = outNbElement = 0;
if (startIdx < 0 || endIdx < 0 || endIdx < startIdx)
{
return RetCode.OutOfRangeStartIndex;
}
if (inReal == null || outReal == null)
{
return RetCode.BadParam;
}
int lookbackTotal = HtDcPhaseLookback();
if (startIdx < lookbackTotal)
{
startIdx = lookbackTotal;
}
if (startIdx > endIdx)
{
return RetCode.Success;
}
const int smoothPriceSize = 50;
var smoothPrice = new decimal[smoothPriceSize];
const decimal rad2Deg = 180m / DecimalMath.PI;
const decimal constDeg2RadBy360 = 2m * DecimalMath.PI;
outBegIdx = startIdx;
int trailingWMAIdx = startIdx - lookbackTotal;
int today = trailingWMAIdx;
decimal tempReal = inReal[today++];
decimal periodWMASub = tempReal;
decimal periodWMASum = tempReal;
tempReal = inReal[today++];
periodWMASub += tempReal;
periodWMASum += tempReal * 2m;
tempReal = inReal[today++];
periodWMASub += tempReal;
periodWMASum += tempReal * 3m;
decimal trailingWMAValue = default;
var i = 34;
do
{
tempReal = inReal[today++];
DoPriceWma(inReal, ref trailingWMAIdx, ref periodWMASub, ref periodWMASum, ref trailingWMAValue, tempReal, out _);
} while (--i != 0);
int hilbertIdx = default;
int smoothPriceIdx = default;
var hilbertVariables = InitHilbertVariables<decimal>();
int outIdx = default;
decimal prevI2, prevQ2, re, im, i1ForOddPrev3, i1ForEvenPrev3, i1ForOddPrev2, i1ForEvenPrev2, smoothPeriod, dcPhase;
decimal period = prevI2 = prevQ2 =
re = im = i1ForOddPrev3 = i1ForEvenPrev3 = i1ForOddPrev2 = i1ForEvenPrev2 = smoothPeriod = dcPhase = default;
while (today <= endIdx)
{
decimal i2;
decimal q2;
decimal adjustedPrevPeriod = 0.075m * period + 0.54m;
DoPriceWma(inReal, ref trailingWMAIdx, ref periodWMASub, ref periodWMASum, ref trailingWMAValue, inReal[today],
out var smoothedValue);
smoothPrice[smoothPriceIdx] = smoothedValue;
if (today % 2 == 0)
{
DoHilbertEven(hilbertVariables, "detrender", smoothedValue, hilbertIdx, adjustedPrevPeriod);
DoHilbertEven(hilbertVariables, "q1", hilbertVariables["detrender"], hilbertIdx, adjustedPrevPeriod);
DoHilbertEven(hilbertVariables, "jI", i1ForEvenPrev3, hilbertIdx, adjustedPrevPeriod);
DoHilbertEven(hilbertVariables, "jQ", hilbertVariables["q1"], hilbertIdx, adjustedPrevPeriod);
if (++hilbertIdx == 3)
{
hilbertIdx = 0;
}
q2 = 0.2m * (hilbertVariables["q1"] + hilbertVariables["jI"]) + 0.8m * prevQ2;
i2 = 0.2m * (i1ForEvenPrev3 - hilbertVariables["jQ"]) + 0.8m * prevI2;
i1ForOddPrev3 = i1ForOddPrev2;
i1ForOddPrev2 = hilbertVariables["detrender"];
}
else
{
DoHilbertOdd(hilbertVariables, "detrender", smoothedValue, hilbertIdx, adjustedPrevPeriod);
DoHilbertOdd(hilbertVariables, "q1", hilbertVariables["detrender"], hilbertIdx, adjustedPrevPeriod);
DoHilbertOdd(hilbertVariables, "jI", i1ForOddPrev3, hilbertIdx, adjustedPrevPeriod);
DoHilbertOdd(hilbertVariables, "jQ", hilbertVariables["q1"], hilbertIdx, adjustedPrevPeriod);
q2 = 0.2m * (hilbertVariables["q1"] + hilbertVariables["jI"]) + 0.8m * prevQ2;
i2 = 0.2m * (i1ForOddPrev3 - hilbertVariables["jQ"]) + 0.8m * prevI2;
i1ForEvenPrev3 = i1ForEvenPrev2;
i1ForEvenPrev2 = hilbertVariables["detrender"];
}
re = 0.2m * (i2 * prevI2 + q2 * prevQ2) + 0.8m * re;
im = 0.2m * (i2 * prevQ2 - q2 * prevI2) + 0.8m * im;
prevQ2 = q2;
prevI2 = i2;
tempReal = period;
if (im != Decimal.Zero && re != Decimal.Zero)
{
period = 360m / (DecimalMath.Atan(im / re) * rad2Deg);
}
decimal tempReal2 = 1.5m * tempReal;
if (period > tempReal2)
{
period = tempReal2;
}
tempReal2 = 0.67m * tempReal;
if (period < tempReal2)
{
period = tempReal2;
}
if (period < 6m)
{
period = 6m;
}
else if (period > 50m)
{
period = 50m;
}
period = 0.2m * period + 0.8m * tempReal;
smoothPeriod = 0.33m * period + 0.67m * smoothPeriod;
decimal dcPeriod = smoothPeriod + 0.5m;
int dcPeriodInt = (int) dcPeriod;
decimal realPart = default;
decimal imagPart = default;
int idx = smoothPriceIdx;
for (i = 0; i < dcPeriodInt; i++)
{
tempReal = i * constDeg2RadBy360 / dcPeriodInt;
tempReal2 = smoothPrice[idx];
realPart += DecimalMath.Sin(tempReal) * tempReal2;
imagPart += DecimalMath.Cos(tempReal) * tempReal2;
if (idx == 0)
{
idx = smoothPriceSize - 1;
}
else
{
idx--;
}
}
tempReal = Math.Abs(imagPart);
if (tempReal > Decimal.Zero)
{
dcPhase = DecimalMath.Atan(realPart / imagPart) * rad2Deg;
}
else if (tempReal <= 0.01m)
{
if (realPart < Decimal.Zero)
{
dcPhase -= 90m;
}
else if (realPart > Decimal.Zero)
{
dcPhase += 90m;
}
}
dcPhase += 90m;
dcPhase += 360m / smoothPeriod;
if (imagPart < Decimal.Zero)
{
dcPhase += 180m;
}
if (dcPhase > 315m)
{
dcPhase -= 360m;
}
if (today >= startIdx)
{
outReal[outIdx++] = dcPhase;
}
if (++smoothPriceIdx > smoothPriceSize - 1)
{
smoothPriceIdx = 0;
}
today++;
}
outNbElement = outIdx;
return RetCode.Success;
}
public static int HtDcPhaseLookback() => (int) Globals.UnstablePeriod[(int) FuncUnstId.HtDcPhase] + 63;
}
}
| 35.398618 | 130 | 0.456942 | [
"BSD-3-Clause"
] | DamianManelski/TA-Lib.NetStandard2.0 | src/TALib.NETCore/TAFunc/TA_HtDcPhase.cs | 15,363 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.CognitiveServices.Vision.Face
{
using Models;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for PersonGroupPerson.
/// </summary>
public static partial class PersonGroupPersonExtensions
{
/// <summary>
/// Create a new person in a specified person group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// Id referencing a particular person group.
/// </param>
/// <param name='name'>
/// User defined name, maximum length is 128.
/// </param>
/// <param name='userData'>
/// User specified data. Length should not exceed 16KB.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Person> CreateAsync(this IPersonGroupPerson operations, string personGroupId, string name = default(string), string userData = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(personGroupId, name, userData, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List all persons in a person group, and retrieve person information
/// (including personId, name, userData and persistedFaceIds of registered
/// faces of the person).
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// Id referencing a particular person group.
/// </param>
/// <param name='start'>
/// Starting person id to return (used to list a range of persons).
/// </param>
/// <param name='top'>
/// Number of persons to return starting with the person id indicated by the
/// 'start' parameter.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<Person>> ListAsync(this IPersonGroupPerson operations, string personGroupId, string start = default(string), int? top = default(int?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(personGroupId, start, top, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete an existing person from a person group. Persisted face images of the
/// person will also be deleted.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// Id referencing a particular person group.
/// </param>
/// <param name='personId'>
/// Id referencing a particular person.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IPersonGroupPerson operations, string personGroupId, System.Guid personId, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(personGroupId, personId, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Retrieve a person's information, including registered persisted faces, name
/// and userData.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// Id referencing a particular person group.
/// </param>
/// <param name='personId'>
/// Id referencing a particular person.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Person> GetAsync(this IPersonGroupPerson operations, string personGroupId, System.Guid personId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(personGroupId, personId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Update name or userData of a person.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// Id referencing a particular person group.
/// </param>
/// <param name='personId'>
/// Id referencing a particular person.
/// </param>
/// <param name='name'>
/// User defined name, maximum length is 128.
/// </param>
/// <param name='userData'>
/// User specified data. Length should not exceed 16KB.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdateAsync(this IPersonGroupPerson operations, string personGroupId, System.Guid personId, string name = default(string), string userData = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdateWithHttpMessagesAsync(personGroupId, personId, name, userData, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Delete a face from a person. Relative image for the persisted face will
/// also be deleted.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// Id referencing a particular person group.
/// </param>
/// <param name='personId'>
/// Id referencing a particular person.
/// </param>
/// <param name='persistedFaceId'>
/// Id referencing a particular persistedFaceId of an existing face.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteFaceAsync(this IPersonGroupPerson operations, string personGroupId, System.Guid personId, System.Guid persistedFaceId, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteFaceWithHttpMessagesAsync(personGroupId, personId, persistedFaceId, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Retrieve information about a persisted face (specified by persistedFaceId,
/// personId and its belonging personGroupId).
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// Id referencing a particular person group.
/// </param>
/// <param name='personId'>
/// Id referencing a particular person.
/// </param>
/// <param name='persistedFaceId'>
/// Id referencing a particular persistedFaceId of an existing face.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PersistedFace> GetFaceAsync(this IPersonGroupPerson operations, string personGroupId, System.Guid personId, System.Guid persistedFaceId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetFaceWithHttpMessagesAsync(personGroupId, personId, persistedFaceId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Update a person persisted face's userData field.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// Id referencing a particular person group.
/// </param>
/// <param name='personId'>
/// Id referencing a particular person.
/// </param>
/// <param name='persistedFaceId'>
/// Id referencing a particular persistedFaceId of an existing face.
/// </param>
/// <param name='userData'>
/// User-provided data attached to the face. The size limit is 1KB.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdateFaceAsync(this IPersonGroupPerson operations, string personGroupId, System.Guid personId, System.Guid persistedFaceId, string userData = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdateFaceWithHttpMessagesAsync(personGroupId, personId, persistedFaceId, userData, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Add a representative face to a person for identification. The input face is
/// specified as an image with a targetFace rectangle.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// Id referencing a particular person group.
/// </param>
/// <param name='personId'>
/// Id referencing a particular person.
/// </param>
/// <param name='url'>
/// Publicly reachable URL of an image
/// </param>
/// <param name='userData'>
/// User-specified data about the face for any purpose. The maximum length is
/// 1KB.
/// </param>
/// <param name='targetFace'>
/// A face rectangle to specify the target face to be added to a person in the
/// format of "targetFace=left,top,width,height". E.g.
/// "targetFace=10,10,100,100". If there is more than one face in the image,
/// targetFace is required to specify which face to add. No targetFace means
/// there is only one face detected in the entire image.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PersistedFace> AddPersonFaceFromUrlAsync(this IPersonGroupPerson operations, string personGroupId, System.Guid personId, string url, string userData = default(string), IList<int> targetFace = default(IList<int>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.AddPersonFaceFromUrlWithHttpMessagesAsync(personGroupId, personId, url, userData, targetFace, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Add a representative face to a person for identification. The input face is
/// specified as an image with a targetFace rectangle.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='personGroupId'>
/// Id referencing a particular person group.
/// </param>
/// <param name='personId'>
/// Id referencing a particular person.
/// </param>
/// <param name='image'>
/// An image stream.
/// </param>
/// <param name='userData'>
/// User-specified data about the face for any purpose. The maximum length is
/// 1KB.
/// </param>
/// <param name='targetFace'>
/// A face rectangle to specify the target face to be added to a person in the
/// format of "targetFace=left,top,width,height". E.g.
/// "targetFace=10,10,100,100". If there is more than one face in the image,
/// targetFace is required to specify which face to add. No targetFace means
/// there is only one face detected in the entire image.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PersistedFace> AddPersonFaceFromStreamAsync(this IPersonGroupPerson operations, string personGroupId, System.Guid personId, Stream image, string userData = default(string), IList<int> targetFace = default(IList<int>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.AddPersonFaceFromStreamWithHttpMessagesAsync(personGroupId, personId, image, userData, targetFace, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| 49.248366 | 320 | 0.569608 | [
"MIT"
] | Skycloudmedua/azure-sdk-for-net | src/SDKs/CognitiveServices/dataPlane/Vision/Face/Face/Generated/PersonGroupPersonExtensions.cs | 15,070 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AttackOpponentFighterController : FighterController
{
public override string Identifier {
get
{
return "ATTACK";
}
}
public override void Awake()
{
base.Awake();
healthChangeAction = UIController.Instance.UpdateOpponentHealth;
}
public override BattleAction GetAction(Dictionary<int, FighterController> fighters, Dictionary<int, BattleAction> previousFigherActions)
{
if (Target < 0)
Target = getTarget(fighters);
ActionType action = ActionType.ATTACK;
return new BattleAction(action, Target);
}
private int getTarget(Dictionary<int, FighterController> fighters)
{
foreach (KeyValuePair<int, FighterController> entry in fighters)
{
if (entry.Value == this)
continue;
return entry.Key;
}
return 0;
}
}
| 22.847826 | 140 | 0.629876 | [
"Apache-2.0"
] | dennisfokker/NeuralCompanion | Assets/Scripts/Controllers/FighterControllers/AttackOpponentFighterController.cs | 1,053 | C# |
namespace EFDatatable
{
/// <summary>
/// Define a command.
/// </summary>
public class Command
{
/// <summary>
/// Gets the title.
/// </summary>
/// <value>
/// The title.
/// </value>
public string Title { get; private set; }
/// <summary>
/// Gets the on click.
/// </summary>
/// <value>
/// The on click.
/// </value>
public string OnClick { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="Command"/> class.
/// </summary>
/// <param name="title">The title.</param>
/// <param name="onClick">The on click.</param>
public Command(string title, string onClick)
{
Title = title;
OnClick = onClick;
}
}
}
| 25.5 | 74 | 0.461361 | [
"MIT"
] | JTOne123/EFDatatable | EFDatatable/Models/Command.cs | 869 | 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.Globalization;
using NuGet.Shared;
namespace NuGet.Frameworks
{
/// <summary>
/// Internal cache key used to store framework compatibility.
/// </summary>
internal class CompatibilityCacheKey : IEquatable<CompatibilityCacheKey>
{
public NuGetFramework Target
{
get { return _target; }
}
public NuGetFramework Candidate
{
get { return _candidate; }
}
private readonly NuGetFramework _target;
private readonly NuGetFramework _candidate;
private readonly int _hashCode;
public CompatibilityCacheKey(NuGetFramework target, NuGetFramework candidate)
{
if (target == null)
{
throw new ArgumentNullException("target");
}
if (candidate == null)
{
throw new ArgumentNullException("candidate");
}
_target = target;
_candidate = candidate;
// This is designed to be cached, just get the hash up front
var combiner = new HashCodeCombiner();
combiner.AddObject(target);
combiner.AddObject(candidate);
_hashCode = combiner.CombinedHash;
}
public override int GetHashCode()
{
return _hashCode;
}
public bool Equals(CompatibilityCacheKey other)
{
if (other == null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Target.Equals(other.Target)
&& Candidate.Equals(other.Candidate);
}
public override bool Equals(object obj)
{
return Equals(obj as CompatibilityCacheKey);
}
public override string ToString()
{
return string.Format(
CultureInfo.CurrentCulture,
"{0} -> {1}",
Target.DotNetFrameworkName,
Candidate.DotNetFrameworkName);
}
}
}
| 26.632184 | 111 | 0.550712 | [
"Apache-2.0"
] | 0xced/NuGet.Client | src/NuGet.Core/NuGet.Frameworks/CompatibilityCacheKey.cs | 2,317 | C# |
using System;
namespace JS_Test.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Describes a type model.
/// </summary>
public abstract class ModelDescription
{
public string Documentation { get; set; }
public Type ModelType { get; set; }
public string Name { get; set; }
}
} | 20.625 | 50 | 0.615152 | [
"Apache-2.0"
] | alleks8/Chess | JS_Test/Areas/HelpPage/ModelDescriptions/ModelDescription.cs | 330 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using NLog;
namespace TTController.Service.Manager
{
public sealed class TimerManager : IDisposable
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly List<Timer> _timers;
public TimerManager()
{
Logger.Info("Creating Timer Manager...");
_timers = new List<Timer>();
}
public void RegisterTimer(int interval, Func<bool> callback)
{
if (interval <= 0)
return;
var timer = new Timer(interval)
{
UseThreadSpinWait = false
};
timer.Elapsed += (sender, args) =>
{
if (!(sender is Timer _this))
return;
if (!callback())
_this.Stop();
};
_timers.Add(timer);
}
public void Start()
{
Logger.Info("Starting {0} timers...", _timers.Count);
foreach (var timer in _timers)
timer.Start();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
Logger.Info("Disposing Timer Manager...");
Logger.Info("Stopping {0} timers...", _timers.Count);
Parallel.ForEach(_timers, t => t.Stop());
_timers.Clear();
}
#region Timer
/// <summary>
/// Hight precision non overlapping timer
/// Came from
/// https://stackoverflow.com/a/41697139/548894
/// </summary>
/// <remarks>
/// This implementation guaranteed that Elapsed events
/// are not overlapped with different threads.
/// Which is important, because a state of the event handler attached to Elapsed,
/// may be left unprotected of multi threaded access
/// </remarks>
public class Timer
{
/// <summary>
/// Tick time length in [ms]
/// </summary>
public static readonly double TickLength = 1000f / Stopwatch.Frequency;
/// <summary>
/// Tick frequency
/// </summary>
public static readonly double Frequency = Stopwatch.Frequency;
/// <summary>
/// True if the system/operating system supports HighResolution timer
/// </summary>
public static readonly bool IsHighResolution = Stopwatch.IsHighResolution;
/// <summary>
/// Invoked when the timer is elapsed
/// </summary>
public event EventHandler<TimerElapsedEventArgs> Elapsed;
/// <summary>
/// The interval of timer ticks [ms]
/// </summary>
private volatile float _interval;
/// <summary>
/// The timer is running
/// </summary>
private volatile bool _isRunning;
/// <summary>
/// Execution thread
/// </summary>
private Thread _thread;
/// <summary>
/// Creates a timer with 1 [ms] interval
/// </summary>
public Timer() : this(1f)
{
}
/// <summary>
/// Creates timer with interval in [ms]
/// </summary>
/// <param name="interval">Interval time in [ms]</param>
public Timer(float interval)
{
Interval = interval;
}
/// <summary>
/// The interval of a timer in [ms]
/// </summary>
public float Interval
{
get => _interval;
set
{
if (value < 0f || Single.IsNaN(value))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_interval = value;
}
}
/// <summary>
/// True when timer is running
/// </summary>
public bool IsRunning => _isRunning;
/// <summary>
/// If true, sets the execution thread to ThreadPriority.Highest
/// (works after the next Start())
/// </summary>
/// <remarks>
/// It might help in some cases and get things worse in others.
/// It suggested that you do some studies if you apply
/// </remarks>
public bool UseHighPriorityThread { get; set; } = false;
/// <summary>
/// If true, uses <see cref="Thread.SpinWait(int)"/> to
/// make the timer delay as close to 0 [ms] as possible
/// </summary>
/// <remarks>
/// Trades precision for cpu usage
/// </remarks>
public bool UseThreadSpinWait { get; set; } = true;
/// <summary>
/// Starts the timer
/// </summary>
public void Start()
{
if (_isRunning) return;
_isRunning = true;
_thread = new Thread(ExecuteTimer)
{
IsBackground = true,
};
if (UseHighPriorityThread)
{
_thread.Priority = ThreadPriority.Highest;
}
_thread.Start();
}
/// <summary>
/// Stops the timer
/// </summary>
/// <remarks>
/// This function is waiting an executing thread (which do to stop and join.
/// </remarks>
public void Stop(bool joinThread = true)
{
_isRunning = false;
// Even if _thread.Join may take time it is guaranteed that
// Elapsed event is never called overlapped with different threads
if (joinThread && Thread.CurrentThread != _thread)
{
_thread.Join();
}
}
private void ExecuteTimer()
{
float nextTrigger = 0f;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while (_isRunning)
{
nextTrigger += _interval;
double elapsed;
while (true)
{
elapsed = ElapsedHiRes(stopwatch);
double diff = nextTrigger - elapsed;
if (diff <= 0f)
break;
if (UseThreadSpinWait && diff < 1f)
Thread.SpinWait(10);
else if (UseThreadSpinWait && diff < 5f)
Thread.SpinWait(100);
else if (diff < 15f)
Thread.Sleep(1);
else
Thread.Sleep(10);
if (!_isRunning)
return;
}
double delay = elapsed - nextTrigger;
Elapsed?.Invoke(this, new TimerElapsedEventArgs(delay));
if (!_isRunning)
return;
// restarting the timer in every hour to prevent precision problems
if (stopwatch.Elapsed.TotalHours >= 1d)
{
stopwatch.Restart();
nextTrigger = 0f;
}
}
stopwatch.Stop();
}
private static double ElapsedHiRes(Stopwatch stopwatch)
{
return stopwatch.ElapsedTicks * TickLength;
}
}
public class TimerElapsedEventArgs : EventArgs
{
/// <summary>/// Real timer delay in [ms]/// </summary>
public double Delay { get; }
internal TimerElapsedEventArgs(double delay)
{
Delay = delay;
}
}
#endregion
}
}
| 30.435252 | 90 | 0.451011 | [
"MIT"
] | Operation760/TTController | Source/TTController.Service/Manager/TimerManager.cs | 8,461 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PKMDS_CS;
namespace PKMDS_Save_Editor
{
public partial class frmPKMViewer : Form
{
public PKMDS.Pokemon SharedPokemon = new PKMDS.Pokemon();
private PKMDS.Pokemon TempPokemon = new PKMDS.Pokemon();
public PKMDS.PartyPokemon SharedPartyPokemon = new PKMDS.PartyPokemon();
private bool UISet = false;
private bool PokemonSet = false;
//private bool IsParty = false;
public frmPKMViewer()
{
PKMDS.SQL.OpenDB(Properties.Settings.Default.veekunpokedex);
InitializeComponent();
SetUI();
}
public void SetPokemon(PKMDS.Pokemon pkm)
{
PokemonSet = false;
this.SharedPokemon = pkm.Clone();
this.TempPokemon = pkm.Clone();
//this.IsParty = false;
}
public void SetPokemon(PKMDS.PartyPokemon ppkm)
{
PokemonSet = false;
//SetPokemon(ppkm.PokemonData);
this.SharedPokemon = ppkm.PokemonData.Clone();
this.TempPokemon = ppkm.PokemonData.Clone();
//this.IsParty = true;
}
private void frmPKMViewer_Load(object sender, EventArgs e)
{
try
{
tcTabs.TabPages.Remove(tcTabs.TabPages["tpRibbon"]);
tcTabs.TabPages.Remove(tcTabs.TabPages["tpMisc"]);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
ClearForm();
DisplayPokemon(TempPokemon);
}
private void DisplayPokemon(PKMDS.Pokemon pkm)
{
UpdateFormIcon();
UpdateCommonInfo();
UpdateBasicInfo();
UpdateStatsInfo();
UpdateMovesInfo();
UpdateOriginsInfo();
UpdateRibbonsInfo();
UpdateMiscInfo();
PokemonSet = true;
}
private void ClearForm()
{
btnApply.Enabled = false;
cbHeldItem.SelectedIndex = -1;
//cbHeldItem.SelectedValue = 0;
pbHeldItem.Image = null;
pbGender.Image = null;
//pbType1.Image = null;
//pbType2.Image = null;
//pbShiny.Image = null;
//pbPokerus.Image = null;
cbForm.Items.Clear();
cbForm.Text = "";
}
private void UpdateFormIcon()
{
System.Drawing.Bitmap icon = (System.Drawing.Bitmap)(TempPokemon.Icon);
this.Icon = Icon.FromHandle(icon.GetHicon());
}
#region UpdateCommonInfo
private void UpdateCommonInfo()
{
UpdateSprite();
UpdateGenderPic();
UpdateMarkings();
UpdateHeldItem();
UpdateShiny();
UpdateBall();
UpdatePokerus();
UpdateSpecies();
UpdateLevel();
UpdateForm();
}
private void UpdateSprite()
{
pbSprite.Image = TempPokemon.Sprite;
}
private void UpdateGenderPic()
{
pbGender.Image = TempPokemon.GenderIcon;
}
private void UpdateMarkings()
{
pbCircle.Image = TempPokemon.GetMarkingImage(0);
pbTriangle.Image = TempPokemon.GetMarkingImage(1);
pbSquare.Image = TempPokemon.GetMarkingImage(2);
pbHeart.Image = TempPokemon.GetMarkingImage(3);
pbStar.Image = TempPokemon.GetMarkingImage(4);
pbDiamond.Image = TempPokemon.GetMarkingImage(5);
}
private void UpdateHeldItem()
{
cbHeldItem.SelectedValue = TempPokemon.ItemID;
pbHeldItem.Image = ((PKMDS.Item)(cbHeldItem.SelectedItem)).ItemImage;
lblHeldItemFlavor.Text = ((PKMDS.Item)(cbHeldItem.SelectedItem)).ItemFlavor;
}
private void UpdateShiny()
{
pbShiny.Image = TempPokemon.ShinyIcon;
}
private void UpdateBall()
{
pbBall.Image = TempPokemon.BallPic;
cbBall.SelectedValue = TempPokemon.BallID;
}
private void UpdatePokerus()
{
pbPokerus.Image = TempPokemon.PokerusIcon;
cbPKRSStrain.SelectedIndex = TempPokemon.PokerusStrain;
cbPKRSDays.SelectedIndex = TempPokemon.PokerusDays;
}
private void UpdateSpecies()
{
cbSpecies.SelectedValue = TempPokemon.SpeciesID;
numSpecies.Value = (Decimal)(TempPokemon.SpeciesID);
}
private void UpdateLevel()
{
numLevel.Value = TempPokemon.Level;
}
private void UpdateForm()
{
SetForms();
if (cbForm.Enabled)
{
if (cbForm.Items.Count < TempPokemon.FormID)
{
TempPokemon.FormID = 0;
cbForm.SelectedIndex = -1;
cbForm.Text = "";
}
else
{
cbForm.SelectedIndex = TempPokemon.FormID;
}
}
}
#endregion
#region UpdateBasicInfo
private void UpdateBasicInfo()
{
UpdateNickname();
UpdateOTGender();
UpdateOTName();
UpdateTIDSID();
UpdateTypes();
UpdateAbility();
UpdateEXP();
}
private void UpdateNickname()
{
txtNickname.Text = TempPokemon.Nickname;
chkNicknamed.Checked = TempPokemon.IsNicknamed;
}
private void UpdateOTGender()
{
if (TempPokemon.OTGenderID == 1)
{
rbOTFemale.Checked = true;
}
else
{
rbOTMale.Checked = true;
}
}
private void UpdateOTName()
{
txtOTName.Text = TempPokemon.OTName;
if (TempPokemon.OTGenderID == 0)
{
txtOTName.ForeColor = Color.Blue;
}
else
{
txtOTName.ForeColor = Color.Red;
}
}
private void UpdateTIDSID()
{
numTID.Value = TempPokemon.TID;
numSID.Value = TempPokemon.SID;
}
private void UpdateTypes()
{
pbType1.Image = TempPokemon.GetTypePic(1);
pbType2.Image = TempPokemon.GetTypePic(2);
}
private void UpdateAbility()
{
cbAbility.SelectedValue = TempPokemon.AbilityID;
lblAbilityFlavor.Text = ((PKMDS.Ability)(cbAbility.SelectedItem)).AbilityFlavor;
}
private void UpdateEXP()
{
numEXP.Value = TempPokemon.EXP;
txtTNL.Text = TempPokemon.TNL.ToString();
if (TempPokemon.TNL == 0)
{
pbTNL.Minimum = 0;
pbTNL.Maximum = 1;
pbTNL.Value = 0;
txtTNL.Text = (0).ToString();
txtTNLPercent.Visible = false;
}
else
{
pbTNL.Minimum = 0;
pbTNL.Maximum = (int)((int)(TempPokemon.EXPAtGivenLevel(TempPokemon.Level + 1)) - TempPokemon.EXPAtCurLevel); // (int)(TempPokemon.EXPAtGivenLevel(TempPokemon.Level + 1));
pbTNL.Value = (int)(TempPokemon.EXP - TempPokemon.EXPAtCurLevel);
txtTNL.Text = TempPokemon.TNL.ToString();
txtTNLPercent.Visible = true;
int percent = (100 * pbTNL.Value) / pbTNL.Maximum;
txtTNLPercent.Text = percent.ToString("0") + "%";
}
}
#endregion
#region UpdateStatsInfo
private void UpdateStatsInfo()
{
UpdateIVs();
UpdateEVs();
UpdateTotalEVs();
UpdateNature();
UpdateCalculatedStats();
UpdateTameness();
UpdateCharacteristic();
}
private void UpdateIVs()
{
numHPIV.Value = TempPokemon.GetIV(0);
numAtkIV.Value = TempPokemon.GetIV(1);
numDefIV.Value = TempPokemon.GetIV(2);
numSpAtkIV.Value = TempPokemon.GetIV(3);
numSpDefIV.Value = TempPokemon.GetIV(4);
numSpeedIV.Value = TempPokemon.GetIV(5);
SetControlFont(ref numHPIV, numHPIV.Value == numHPIV.Maximum);
SetControlFont(ref numAtkIV, numAtkIV.Value == numAtkIV.Maximum);
SetControlFont(ref numDefIV, numDefIV.Value == numDefIV.Maximum);
SetControlFont(ref numSpAtkIV, numSpAtkIV.Value == numSpAtkIV.Maximum);
SetControlFont(ref numSpDefIV, numSpDefIV.Value == numSpDefIV.Maximum);
SetControlFont(ref numSpeedIV, numSpeedIV.Value == numSpeedIV.Maximum);
}
private void UpdateEVs()
{
numHPEV.Value = TempPokemon.GetEV(0);
numAtkEV.Value = TempPokemon.GetEV(1);
numDefEV.Value = TempPokemon.GetEV(2);
numSpAtkEV.Value = TempPokemon.GetEV(3);
numSpDefEV.Value = TempPokemon.GetEV(4);
numSpeedEV.Value = TempPokemon.GetEV(5);
SetControlFont(ref numHPEV, numHPEV.Value >= 252M);
SetControlFont(ref numAtkEV, numAtkEV.Value >= 252M);
SetControlFont(ref numDefEV, numDefEV.Value >= 252M);
SetControlFont(ref numSpAtkEV, numSpAtkEV.Value >= 252M);
SetControlFont(ref numSpDefEV, numSpDefEV.Value >= 252M);
SetControlFont(ref numSpeedEV, numSpeedEV.Value >= 252M);
}
private void UpdateTotalEVs()
{
int totalEVs =
((int)(numHPEV.Value) +
(int)(numAtkEV.Value) +
(int)(numDefEV.Value) +
(int)(numSpAtkEV.Value) +
(int)(numSpDefEV.Value) +
(int)(numSpeedEV.Value));
txtTotalEVs.Text = totalEVs.ToString();
SetControlFont(ref txtTotalEVs, totalEVs >= 510);
}
private void UpdateNature()
{
cbNature.SelectedValue = TempPokemon.NatureID;
int inc = TempPokemon.NatureIncrease - 1;
int dec = TempPokemon.NatureDecrease - 1;
Color statcolor = new Color();
Label[] statlbls =
{
lblHPStats,
lblAtkStats,
lblDefStats,
lblSpAtkStats,
lblSpDefStats,
lblSpeedStats
};
for (int i = 0; i < 6; i++)
{
statcolor = Color.Black;
if (inc == i)
{
if (dec == i)
{
statcolor = Color.Black;
}
else
{
statcolor = Color.Red;
}
}
if (dec == i)
{
if (inc == i)
{
statcolor = Color.Black;
}
else
{
statcolor = Color.Blue;
}
}
statlbls[i].ForeColor = statcolor;
}
}
private void UpdateCalculatedStats()
{
int[] calcstats = TempPokemon.GetStats;
txtCalcHP.Text = calcstats[0].ToString();
txtCalcAtk.Text = calcstats[1].ToString();
txtCalcDef.Text = calcstats[2].ToString();
txtCalcSpAtk.Text = calcstats[3].ToString();
txtCalcSpDef.Text = calcstats[4].ToString();
txtCalcSpeed.Text = calcstats[5].ToString();
}
private void UpdateTameness()
{
numTameness.Value = TempPokemon.Tameness;
SetControlFont(ref numTameness, numTameness.Value == numTameness.Maximum);
}
private void UpdateCharacteristic()
{
lblCharacteristic.Text = TempPokemon.Characteristic;
}
#endregion
#region UpdateMovesInfo
private void UpdateMovesInfo()
{
UpdateMove1();
UpdateMove2();
UpdateMove3();
UpdateMove4();
}
private void AutosizeFont(ref System.Windows.Forms.Label ctrl)
{
// while ((Decimal)(ctrl.Width) > (Decimal)(System.Windows.Forms.TextRenderer.MeasureText(ctrl.Text,
//new Font(ctrl.Font.FontFamily, ctrl.Font.Size, ctrl.Font.Style)).Width) / 1.00M)
// {
// ctrl.Font = new Font(ctrl.Font.FontFamily, ctrl.Font.Size + 0.5f, ctrl.Font.Style);
// }
while ((Decimal)(ctrl.Width) < (Decimal)(System.Windows.Forms.TextRenderer.MeasureText(ctrl.Text,
new Font(ctrl.Font.FontFamily, ctrl.Font.Size, ctrl.Font.Style)).Width) / 1.90M)
{
ctrl.Font = new Font(ctrl.Font.FontFamily, ctrl.Font.Size - 0.5f, ctrl.Font.Style);
}
}
private void UpdateMove1()
{
UInt16 moveid = TempPokemon.GetMoveIDs[0];
cbMove1.SelectedValue = moveid;
PKMDS.Move move = (PKMDS.Move)(cbMove1.SelectedItem);
lblMove1Flavor.Text = move.MoveFlavor;
if ((move.MoveAccuracy != 0) && (move.MoveAccuracy != 1))
{
lblMove1Accuracy.Text = move.MoveAccuracy.ToString("0") + "%";
}
else
{
lblMove1Accuracy.Text = "-";
}
if ((move.MovePower != 0) && (move.MovePower != 1))
{
lblMove1Power.Text = move.MovePower.ToString();
}
else
{
lblMove1Power.Text = "-";
}
numMove1PP.Value = TempPokemon.GetMovePP(0);
numMove1PPUps.Value = TempPokemon.GetMovePPUp(0);
txtMove1MaxPP.Text = (move.MoveBasePP + (numMove1PPUps.Value * (move.MoveBasePP / 5))).ToString("0");
pbMove1Type.Image = move.MoveTypeImage;
pbMove1Category.Image = move.MoveCategoryImage;
AutosizeFont(ref lblMove1Flavor);
}
private void UpdateMove2()
{
UInt16 moveid = TempPokemon.GetMoveIDs[1];
if (moveid == 0)
{
cbMove2.SelectedIndex = -1;
numMove2PPUps.Enabled = false;
numMove2PP.Enabled = false;
lblMove2Accuracy.Text = "";
lblMove2Flavor.Text = "";
lblMove2Power.Text = "";
numMove2PP.Value = 0M;
numMove2PPUps.Value = 0M;
txtMove2MaxPP.Text = "";
pbMove2Type.Image = null;
pbMove2Category.Image = null;
}
else
{
cbMove2.SelectedValue = moveid;
numMove2PPUps.Enabled = true;
numMove2PP.Enabled = true;
PKMDS.Move move = (PKMDS.Move)(cbMove2.SelectedItem);
lblMove2Flavor.Text = move.MoveFlavor;
if ((move.MoveAccuracy != 0) && (move.MoveAccuracy != 1))
{
lblMove2Accuracy.Text = move.MoveAccuracy.ToString("0") + "%";
}
else
{
lblMove2Accuracy.Text = "-";
}
if ((move.MovePower != 0) && (move.MovePower != 1))
{
lblMove2Power.Text = move.MovePower.ToString();
}
else
{
lblMove2Power.Text = "-";
}
numMove2PP.Value = TempPokemon.GetMovePP(1);
numMove2PPUps.Value = TempPokemon.GetMovePPUp(1);
txtMove2MaxPP.Text = (move.MoveBasePP + (numMove2PPUps.Value * (move.MoveBasePP / 5))).ToString("0");
pbMove2Type.Image = move.MoveTypeImage;
pbMove2Category.Image = move.MoveCategoryImage;
AutosizeFont(ref lblMove2Flavor);
}
}
private void UpdateMove3()
{
UInt16 moveid = TempPokemon.GetMoveIDs[2];
if (moveid == 0)
{
cbMove3.SelectedIndex = -1;
numMove3PPUps.Enabled = false;
numMove3PP.Enabled = false;
lblMove3Accuracy.Text = "";
lblMove3Flavor.Text = "";
lblMove3Power.Text = "";
numMove3PP.Value = 0M;
numMove3PPUps.Value = 0M;
txtMove3MaxPP.Text = "";
pbMove3Type.Image = null;
pbMove3Category.Image = null;
}
else
{
cbMove3.SelectedValue = moveid;
numMove3PPUps.Enabled = true;
numMove3PP.Enabled = true;
PKMDS.Move move = (PKMDS.Move)(cbMove3.SelectedItem);
lblMove3Flavor.Text = move.MoveFlavor;
if ((move.MoveAccuracy != 0) && (move.MoveAccuracy != 1))
{
lblMove3Accuracy.Text = move.MoveAccuracy.ToString("0") + "%";
}
else
{
lblMove3Accuracy.Text = "-";
}
if ((move.MovePower != 0) && (move.MovePower != 1))
{
lblMove3Power.Text = move.MovePower.ToString();
}
else
{
lblMove3Power.Text = "-";
}
numMove3PP.Value = TempPokemon.GetMovePP(2);
numMove3PPUps.Value = TempPokemon.GetMovePPUp(2);
txtMove3MaxPP.Text = (move.MoveBasePP + (numMove3PPUps.Value * (move.MoveBasePP / 5))).ToString("0");
pbMove3Type.Image = move.MoveTypeImage;
pbMove3Category.Image = move.MoveCategoryImage;
AutosizeFont(ref lblMove3Flavor);
}
}
private void UpdateMove4()
{
UInt16 moveid = TempPokemon.GetMoveIDs[3];
if (moveid == 0)
{
cbMove4.SelectedIndex = -1;
numMove4PPUps.Enabled = false;
numMove4PP.Enabled = false;
lblMove4Accuracy.Text = "";
lblMove4Flavor.Text = "";
lblMove4Power.Text = "";
numMove4PP.Value = 0M;
numMove4PPUps.Value = 0M;
txtMove4MaxPP.Text = "";
pbMove4Type.Image = null;
pbMove4Category.Image = null;
}
else
{
cbMove4.SelectedValue = moveid;
numMove4PPUps.Enabled = true;
numMove4PP.Enabled = true;
PKMDS.Move move = (PKMDS.Move)(cbMove4.SelectedItem);
lblMove4Flavor.Text = move.MoveFlavor;
if ((move.MoveAccuracy != 0) && (move.MoveAccuracy != 1))
{
lblMove4Accuracy.Text = move.MoveAccuracy.ToString("0") + "%";
}
else
{
lblMove4Accuracy.Text = "-";
}
if ((move.MovePower != 0) && (move.MovePower != 1))
{
lblMove4Power.Text = move.MovePower.ToString();
}
else
{
lblMove4Power.Text = "-";
}
numMove4PP.Value = TempPokemon.GetMovePP(3);
numMove4PPUps.Value = TempPokemon.GetMovePPUp(3);
txtMove4MaxPP.Text = (move.MoveBasePP + (numMove4PPUps.Value * (move.MoveBasePP / 5))).ToString("0");
pbMove4Type.Image = move.MoveTypeImage;
pbMove4Category.Image = move.MoveCategoryImage;
AutosizeFont(ref lblMove4Flavor);
}
}
#endregion
#region UpdateOriginsInfo
private void UpdateOriginsInfo()
{
numMetLevel.Value = (Decimal)(TempPokemon.MetLevel);
cbIsEgg.Checked = TempPokemon.IsEgg;
UpdateHatchSteps();
cbNsPokemon.Checked = TempPokemon.IsNsPokemon;
cbFateful.Checked = TempPokemon.IsFateful;
cbGame.SelectedValue = (Byte)(TempPokemon.HometownID);
cbCountry.SelectedValue = (Byte)(TempPokemon.LanguageID);
cbMetLocation.SelectedValue = TempPokemon.MetLocationID;
dtMetDate.Value = TempPokemon.MetDate;
cbMetAsEgg.Checked = TempPokemon.MetAsEgg;
cbEggLocation.Enabled = false;
dtEggDate.Enabled = false;
if (TempPokemon.MetAsEgg)
{
cbEggLocation.Enabled = true;
cbEggLocation.SelectedValue = TempPokemon.EggLocationID;
dtEggDate.Enabled = true;
dtEggDate.Value = TempPokemon.EggDate;
}
}
#endregion
#region UpdateRibbonsInfo
private void UpdateRibbonsInfo()
{
// TODO: Ribbons
}
#endregion
#region UpdateMiscInfo
private void UpdateMiscInfo()
{
// TODO: Misc
}
#endregion
private void SetControlFont(ref NumericUpDown control, bool bold = false)
{
if (bold)
{
control.Font = new Font(control.Font, FontStyle.Bold);
}
else
{
control.Font = new Font(control.Font, FontStyle.Regular);
}
}
private void SetControlFont(ref TextBox control, bool bold = false)
{
if (bold)
{
control.Font = new Font(control.Font, FontStyle.Bold);
}
else
{
control.Font = new Font(control.Font, FontStyle.Regular);
}
}
private void SetUI()
{
SetItems();
SetAbilities();
SetSpecies();
SetBalls();
SetNatures();
SetLocations();
SetMoves();
SetHometowns();
SetCountries();
UISet = true;
}
private void SetForms()
{
cbForm.Items.Clear();
if (TempPokemon.SpeciesID != 0)
{
string[] formnames = PKMDS.GetPKMFormNames(TempPokemon.SpeciesID);
if (formnames.Length != 0)
{
if (!((formnames.Length == 1) && (formnames[0] == "")))
{
cbForm.Items.AddRange(PKMDS.GetPKMFormNames(TempPokemon.SpeciesID));
cbForm.Enabled = true;
}
else
{
cbForm.Enabled = false;
}
}
else
{
cbForm.Enabled = false;
}
}
}
private void SetItems()
{
List<PKMDS.Item> items = new List<PKMDS.Item>();
PKMDS.Item item = new PKMDS.Item();
items.Add(item);
for (UInt16 itemindex = 0; itemindex <= 0x027E; itemindex++)
{
item = new PKMDS.Item(itemindex);
if ((item.ItemName != "") & (item.ItemName != null))
{
items.Add(item);
}
}
cbHeldItem.DataSource = items;
cbHeldItem.DisplayMember = "ItemName";
cbHeldItem.ValueMember = "ItemID";
}
private void SetAbilities()
{
List<PKMDS.Ability> abilities = new List<PKMDS.Ability>();
PKMDS.Ability ability = new PKMDS.Ability();
for (UInt16 abilityindex = 0; abilityindex <= 164; abilityindex++)
{
ability = new PKMDS.Ability(abilityindex);
if ((ability.AbilityName != "") & (ability.AbilityName != null) & (ability.AbilityID != 0))
{
abilities.Add(ability);
}
}
cbAbility.DataSource = abilities;
cbAbility.DisplayMember = "AbilityName";
cbAbility.ValueMember = "AbilityID";
}
private void SetSpecies()
{
List<PKMDS.Species> species_l = new List<PKMDS.Species>();
PKMDS.Species species = new PKMDS.Species();
for (UInt16 speciesindex = 0; speciesindex <= 649; speciesindex++)
{
species = new PKMDS.Species(speciesindex);
if ((species.SpeciesName != "") & (species.SpeciesName != null) & (species.SpeciesID != 0))
{
species_l.Add(species);
}
}
cbSpecies.DataSource = species_l;
cbSpecies.DisplayMember = "SpeciesName";
cbSpecies.ValueMember = "SpeciesID";
}
private void SetBalls()
{
List<PKMDS.Ball> balls = new List<PKMDS.Ball>();
PKMDS.Ball ball = new PKMDS.Ball();
for (Byte ballindex = 0; ballindex <= 25; ballindex++)
{
ball = new PKMDS.Ball(ballindex);
if ((ball.BallName != "") & (ball.BallName != null))
{
balls.Add(ball);
}
}
cbBall.DataSource = balls;
cbBall.DisplayMember = "BallName";
cbBall.ValueMember = "BallID";
}
private void SetNatures()
{
List<PKMDS.Nature> natures = new List<PKMDS.Nature>();
PKMDS.Nature nature = new PKMDS.Nature();
for (Byte natureindex = 0; natureindex <= 24; natureindex++)
{
nature = new PKMDS.Nature(natureindex);
if ((nature.NatureName != "") & (nature.NatureName != null))
{
natures.Add(nature);
}
}
cbNature.DataSource = natures;
cbNature.DisplayMember = "NatureName";
cbNature.ValueMember = "NatureID";
}
private void SetLocations()
{
List<PKMDS.Location> metlocations = new List<PKMDS.Location>();
List<PKMDS.Location> egglocations = new List<PKMDS.Location>();
PKMDS.Location location = new PKMDS.Location();
for (UInt16 locationindex = 0; locationindex <= 153; locationindex++)
{
location = new PKMDS.Location(locationindex);
if ((location.LocationName != "") & (location.LocationName != null) & (location.LocationID != 0))
{
metlocations.Add(location);
egglocations.Add(location);
}
}
location = new PKMDS.Location(2000);
metlocations.Add(location);
egglocations.Add(location);
location = new PKMDS.Location(30001);
metlocations.Add(location);
egglocations.Add(location);
location = new PKMDS.Location(30012);
metlocations.Add(location);
egglocations.Add(location);
location = new PKMDS.Location(30013);
metlocations.Add(location);
egglocations.Add(location);
location = new PKMDS.Location(30015);
metlocations.Add(location);
egglocations.Add(location);
location = new PKMDS.Location(40001);
metlocations.Add(location);
egglocations.Add(location);
location = new PKMDS.Location(40069);
metlocations.Add(location);
egglocations.Add(location);
location = new PKMDS.Location(60002);
metlocations.Add(location);
egglocations.Add(location);
cbMetLocation.DataSource = metlocations;
cbMetLocation.DisplayMember = "LocationName";
cbMetLocation.ValueMember = "LocationID";
cbEggLocation.DataSource = egglocations;
cbEggLocation.DisplayMember = "LocationName";
cbEggLocation.ValueMember = "LocationID";
}
private void SetMoves()
{
List<PKMDS.Move> moves1 = new List<PKMDS.Move>();
List<PKMDS.Move> moves2 = new List<PKMDS.Move>();
List<PKMDS.Move> moves3 = new List<PKMDS.Move>();
List<PKMDS.Move> moves4 = new List<PKMDS.Move>();
PKMDS.Move move = new PKMDS.Move();
for (UInt16 moveindex = 0; moveindex <= 559; moveindex++)
{
move = new PKMDS.Move(moveindex);
if ((move.MoveName != "") & (move.MoveName != null) & (move.MoveID != 0))
{
moves1.Add(move);
}
moves2.Add(move);
moves3.Add(move);
moves4.Add(move);
}
cbMove1.DataSource = moves1;
cbMove1.DisplayMember = "MoveName";
cbMove1.ValueMember = "MoveID";
cbMove2.DataSource = moves2;
cbMove2.DisplayMember = "MoveName";
cbMove2.ValueMember = "MoveID";
cbMove3.DataSource = moves3;
cbMove3.DisplayMember = "MoveName";
cbMove3.ValueMember = "MoveID";
cbMove4.DataSource = moves4;
cbMove4.DisplayMember = "MoveName";
cbMove4.ValueMember = "MoveID";
}
private void SetHometowns()
{
List<PKMDS.Hometown> hometowns = new List<PKMDS.Hometown>();
PKMDS.Hometown hometown = new PKMDS.Hometown();
for (Byte hometownindex = 0; hometownindex <= 25; hometownindex++)
{
if ((hometownindex != 6) ||
(hometownindex != 9) ||
(hometownindex != 13) ||
(hometownindex != 14) ||
(hometownindex != 16) ||
(hometownindex != 17) ||
(hometownindex != 18) ||
(hometownindex != 19))
{
hometown = new PKMDS.Hometown(hometownindex);
if ((hometown.HometownName != "") & (hometown.HometownName != null) & (hometown.HometownID != 0))
{
hometowns.Add(hometown);
}
}
}
cbGame.DataSource = hometowns;
cbGame.DisplayMember = "HometownName";
cbGame.ValueMember = "HometownID";
}
private void SetCountries()
{
List<PKMDS.Country> countries = new List<PKMDS.Country>();
PKMDS.Country country = new PKMDS.Country();
for (Byte countryindex = 0; countryindex <= 8; countryindex++)
{
if (countryindex != 6)
{
country = new PKMDS.Country(countryindex);
if ((country.CountryName != "") & (country.CountryName != null) & (country.CountryID != 0))
{
countries.Add(country);
}
}
}
cbCountry.DataSource = countries;
cbCountry.DisplayMember = "CountryName";
cbCountry.ValueMember = "CountryID";
}
private void btnSave_Click(object sender, EventArgs e)
{
TempPokemon.FixChecksum();
this.SharedPokemon = this.TempPokemon.Clone();
this.SharedPartyPokemon = new PKMDS.PartyPokemon();
this.SharedPartyPokemon.PokemonData = this.TempPokemon.Clone();
this.Close();
}
private void btnApply_Click(object sender, EventArgs e)
{
TempPokemon.FixChecksum();
this.SharedPokemon = this.TempPokemon.Clone();
this.SharedPartyPokemon = new PKMDS.PartyPokemon();
this.SharedPartyPokemon.PokemonData = this.TempPokemon.Clone();
CheckApplyButton();
}
private void btnExport_Click(object sender, EventArgs e)
{
fileSave.FileName = "";
if (fileSave.ShowDialog() != DialogResult.Cancel)
{
if (fileSave.FileName != "")
{
TempPokemon.WriteToFile(fileSave.FileName, System.IO.Path.GetExtension(fileSave.FileName).ToLower() == ".ek5");
}
}
}
private void CheckApplyButton()
{
btnApply.Enabled = TempPokemon.IsModified;
}
private void pbCircle_Click(object sender, EventArgs e)
{
TempPokemon.SetMarking(0, !(TempPokemon.GetMarking(0)));
pbCircle.Image = TempPokemon.GetMarkingImage(0);
CheckApplyButton();
}
private void pbTriangle_Click(object sender, EventArgs e)
{
TempPokemon.SetMarking(1, !(TempPokemon.GetMarking(1)));
pbTriangle.Image = TempPokemon.GetMarkingImage(1);
CheckApplyButton();
}
private void pbSquare_Click(object sender, EventArgs e)
{
TempPokemon.SetMarking(2, !(TempPokemon.GetMarking(2)));
pbSquare.Image = TempPokemon.GetMarkingImage(2);
CheckApplyButton();
}
private void pbHeart_Click(object sender, EventArgs e)
{
TempPokemon.SetMarking(3, !(TempPokemon.GetMarking(3)));
pbHeart.Image = TempPokemon.GetMarkingImage(3);
CheckApplyButton();
}
private void pbStar_Click(object sender, EventArgs e)
{
TempPokemon.SetMarking(4, !(TempPokemon.GetMarking(4)));
pbStar.Image = TempPokemon.GetMarkingImage(4);
CheckApplyButton();
}
private void pbDiamond_Click(object sender, EventArgs e)
{
TempPokemon.SetMarking(5, !(TempPokemon.GetMarking(5)));
pbDiamond.Image = TempPokemon.GetMarkingImage(5);
CheckApplyButton();
}
private void frmPKMViewer_FormClosing(object sender, FormClosingEventArgs e)
{
if (TempPokemon.IsModified)
{
if (MessageBox.Show("Cancel changes?", "Close", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
{
e.Cancel = true;
}
}
}
private void cbHeldItem_SelectedIndexChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
if (cbHeldItem.SelectedIndex != -1)
{
TempPokemon.ItemID = (UInt16)(cbHeldItem.SelectedValue);
pbHeldItem.Image = ((PKMDS.Item)(cbHeldItem.SelectedItem)).ItemImage;
lblHeldItemFlavor.Text = ((PKMDS.Item)(cbHeldItem.SelectedItem)).ItemFlavor;
CheckApplyButton();
}
}
}
private void chkNicknamed_CheckedChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.IsNicknamed = chkNicknamed.Checked;
CheckApplyButton();
}
}
private void txtNickname_TextChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
if (txtNickname.Text.Length != 0)
{
TempPokemon.Nickname = txtNickname.Text;
chkNicknamed.Checked = true;
CheckApplyButton();
}
}
}
private void txtOTName_TextChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
if (txtOTName.Text.Length != 0)
{
TempPokemon.OTName = txtOTName.Text;
CheckApplyButton();
}
}
}
private void numTID_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.TID = (UInt16)(numTID.Value);
UpdateSprite();
UpdateShiny();
CheckApplyButton();
}
}
private void numSID_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SID = (UInt16)(numSID.Value);
UpdateSprite();
UpdateShiny();
CheckApplyButton();
}
}
private void rbOTMale_CheckedChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
if (rbOTMale.Checked)
{
TempPokemon.OTGenderID = 0;
txtOTName.ForeColor = Color.Blue;
}
CheckApplyButton();
}
}
private void rbOTFemale_CheckedChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
if (rbOTFemale.Checked)
{
TempPokemon.OTGenderID = 1;
txtOTName.ForeColor = Color.Red;
}
CheckApplyButton();
}
}
private void cbAbility_SelectedIndexChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
if (cbAbility.SelectedIndex != -1)
{
TempPokemon.AbilityID = (UInt16)(cbAbility.SelectedValue);
lblAbilityFlavor.Text = ((PKMDS.Ability)(cbAbility.SelectedItem)).AbilityFlavor;
CheckApplyButton();
}
}
}
private void numEXP_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.EXP = (UInt32)(numEXP.Value);
UISet = false;
UpdateLevel();
UpdateEXP();
UISet = true;
UpdateCalculatedStats();
CheckApplyButton();
}
}
private void cbBall_SelectedIndexChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
if (cbBall.SelectedIndex != -1)
{
TempPokemon.BallID = (Byte)(cbBall.SelectedValue);
UpdateBall();
CheckApplyButton();
}
}
}
private void cbSpecies_SelectedIndexChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
if (cbSpecies.SelectedIndex != -1)
{
TempPokemon.SpeciesID = (UInt16)(cbSpecies.SelectedValue);
numSpecies.Value = (Decimal)(TempPokemon.SpeciesID);
UpdateForm();
if (!cbForm.Enabled)
{
TempPokemon.FormID = 0;
}
UpdateSprite();
UpdateFormIcon();
UpdateTypes();
UpdateGenderPic();
UISet = false;
UpdateLevel();
UISet = true;
UpdateCalculatedStats();
CheckApplyButton();
}
}
}
private void numSpecies_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet && ((int)(numSpecies.Value - 1)) != cbSpecies.SelectedIndex)
{
cbSpecies.SelectedIndex = (int)(numSpecies.Value - 1);
}
}
private void cbForm_SelectedIndexChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.FormID = (Byte)(cbForm.SelectedIndex);
UpdateSprite();
UpdateFormIcon();
UpdateTypes();
UpdateCalculatedStats();
CheckApplyButton();
}
}
private void numLevel_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.Level = (int)(numLevel.Value);
UISet = false;
UpdateEXP();
UISet = true;
UpdateCalculatedStats();
CheckApplyButton();
}
}
private void numHPIV_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SetIV(0, (int)(numHPIV.Value));
SetControlFont(ref numHPIV, numHPIV.Value == numHPIV.Maximum);
UpdateCharacteristic();
UpdateCalculatedStats();
CheckApplyButton();
}
}
private void numAtkIV_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SetIV(1, (int)(numAtkIV.Value));
SetControlFont(ref numAtkIV, numAtkIV.Value == numAtkIV.Maximum);
UpdateCharacteristic();
UpdateCalculatedStats();
CheckApplyButton();
}
}
private void numDefIV_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SetIV(2, (int)(numDefIV.Value));
SetControlFont(ref numDefIV, numDefIV.Value == numDefIV.Maximum);
UpdateCharacteristic();
UpdateCalculatedStats();
CheckApplyButton();
}
}
private void numSpAtkIV_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SetIV(3, (int)(numSpAtkIV.Value));
SetControlFont(ref numSpAtkIV, numSpAtkIV.Value == numSpAtkIV.Maximum);
UpdateCharacteristic();
UpdateCalculatedStats();
CheckApplyButton();
}
}
private void numSpDefIV_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SetIV(4, (int)(numSpDefIV.Value));
SetControlFont(ref numSpDefIV, numSpDefIV.Value == numSpDefIV.Maximum);
UpdateCharacteristic();
UpdateCalculatedStats();
CheckApplyButton();
}
}
private void numSpeedIV_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SetIV(5, (int)(numSpeedIV.Value));
SetControlFont(ref numSpeedIV, numSpeedIV.Value == numSpeedIV.Maximum);
UpdateCharacteristic();
UpdateCalculatedStats();
CheckApplyButton();
}
}
private void numHPEV_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SetEV(0, (int)(numHPEV.Value));
SetControlFont(ref numHPEV, numHPEV.Value >= 252M);
UpdateTotalEVs();
UpdateCalculatedStats();
CheckApplyButton();
}
}
private void numAtkEV_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SetEV(1, (int)(numAtkEV.Value));
SetControlFont(ref numAtkEV, numAtkEV.Value >= 252M);
UpdateTotalEVs();
UpdateCalculatedStats();
CheckApplyButton();
}
}
private void numDefEV_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SetEV(2, (int)(numDefEV.Value));
SetControlFont(ref numDefEV, numDefEV.Value >= 252M);
UpdateTotalEVs();
UpdateCalculatedStats();
CheckApplyButton();
}
}
private void numSpAtkEV_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SetEV(3, (int)(numSpAtkEV.Value));
SetControlFont(ref numSpAtkEV, numSpAtkEV.Value >= 252M);
UpdateTotalEVs();
UpdateCalculatedStats();
CheckApplyButton();
}
}
private void numSpDefEV_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SetEV(4, (int)(numSpDefEV.Value));
SetControlFont(ref numSpDefEV, numSpDefEV.Value >= 252M);
UpdateTotalEVs();
UpdateCalculatedStats();
CheckApplyButton();
}
}
private void numSpeedEV_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SetEV(5, (int)(numSpeedEV.Value));
SetControlFont(ref numSpeedEV, numSpeedEV.Value >= 252M);
UpdateTotalEVs();
UpdateCalculatedStats();
CheckApplyButton();
}
}
private void cbNature_SelectedIndexChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.NatureID = (Byte)(cbNature.SelectedValue);
UpdateNature();
UpdateCalculatedStats();
CheckApplyButton();
}
}
private void numTameness_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.Tameness = (int)(numTameness.Value);
SetControlFont(ref numTameness, numTameness.Value == numTameness.Maximum);
UpdateHatchSteps();
CheckApplyButton();
}
}
private void cbMove1_SelectedIndexChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SetMoveID(0, (UInt16)(cbMove1.SelectedValue));
numMove1PP.Value = (Decimal)(((PKMDS.Move)(cbMove1.SelectedItem)).MoveBasePP);
UpdateMove1();
CheckApplyButton();
}
}
private void cbMove2_SelectedIndexChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
if (cbMove2.SelectedValue == null)
{
TempPokemon.SetMoveID(1, 0);
numMove2PPUps.Enabled = false;
numMove2PP.Enabled = false;
}
else
{
TempPokemon.SetMoveID(1, (UInt16)(cbMove2.SelectedValue));
numMove2PPUps.Enabled = true;
numMove2PP.Enabled = true;
numMove2PP.Value = (Decimal)(((PKMDS.Move)(cbMove2.SelectedItem)).MoveBasePP);
}
UpdateMove2();
CheckApplyButton();
}
}
private void cbMove3_SelectedIndexChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
if (cbMove3.SelectedValue == null)
{
TempPokemon.SetMoveID(2, 0);
numMove3PPUps.Enabled = false;
numMove3PP.Enabled = false;
}
else
{
TempPokemon.SetMoveID(2, (UInt16)(cbMove3.SelectedValue));
numMove3PPUps.Enabled = true;
numMove3PP.Enabled = true;
numMove3PP.Value = (Decimal)(((PKMDS.Move)(cbMove3.SelectedItem)).MoveBasePP);
}
UpdateMove3();
CheckApplyButton();
}
}
private void cbMove4_SelectedIndexChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
if (cbMove4.SelectedValue == null)
{
TempPokemon.SetMoveID(3, 0);
numMove4PPUps.Enabled = false;
numMove4PP.Enabled = false;
}
else
{
TempPokemon.SetMoveID(3, (UInt16)(cbMove4.SelectedValue));
numMove4PPUps.Enabled = true;
numMove4PP.Enabled = true;
numMove4PP.Value = (Decimal)(((PKMDS.Move)(cbMove4.SelectedItem)).MoveBasePP);
}
UpdateMove4();
CheckApplyButton();
}
}
private void numMove1PPUps_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SetMovePPUp(0, (int)(numMove1PPUps.Value));
PKMDS.Move move = ((PKMDS.Move)(cbMove1.SelectedItem));
if (move != null)
{
txtMove1MaxPP.Text = (move.MoveBasePP + (numMove1PPUps.Value * (move.MoveBasePP / 5))).ToString("0");
}
CheckApplyButton();
}
}
private void numMove1PP_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SetMovePP(0, (int)(numMove1PP.Value));
CheckApplyButton();
}
}
private void numMove2PPUps_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SetMovePPUp(1, (int)(numMove2PPUps.Value));
PKMDS.Move move = ((PKMDS.Move)(cbMove2.SelectedItem));
if (move != null)
{
txtMove2MaxPP.Text = (move.MoveBasePP + (numMove2PPUps.Value * (move.MoveBasePP / 5))).ToString("0");
}
CheckApplyButton();
}
}
private void numMove2PP_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SetMovePP(1, (int)(numMove2PP.Value));
CheckApplyButton();
}
}
private void numMove3PPUps_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SetMovePPUp(2, (int)(numMove3PPUps.Value));
PKMDS.Move move = ((PKMDS.Move)(cbMove3.SelectedItem));
if (move != null)
{
txtMove3MaxPP.Text = (move.MoveBasePP + (numMove3PPUps.Value * (move.MoveBasePP / 5))).ToString("0");
}
CheckApplyButton();
}
}
private void numMove3PP_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SetMovePP(2, (int)(numMove3PP.Value));
CheckApplyButton();
}
}
private void numMove4PPUps_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SetMovePPUp(3, (int)(numMove4PPUps.Value));
PKMDS.Move move = ((PKMDS.Move)(cbMove4.SelectedItem));
if (move != null)
{
txtMove4MaxPP.Text = (move.MoveBasePP + (numMove4PPUps.Value * (move.MoveBasePP / 5))).ToString("0");
}
CheckApplyButton();
}
}
private void numMove4PP_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.SetMovePP(3, (int)(numMove4PP.Value));
CheckApplyButton();
}
}
private void cbMetLocation_SelectedIndexChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.MetLocationID = (UInt16)(cbMetLocation.SelectedValue);
CheckApplyButton();
}
}
private void dtMetDate_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.MetDate = dtMetDate.Value;
CheckApplyButton();
}
}
private void cbEggLocation_SelectedIndexChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.EggLocationID = (UInt16)(cbEggLocation.SelectedValue);
CheckApplyButton();
}
}
private void dtEggDate_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.EggDate = dtEggDate.Value;
CheckApplyButton();
}
}
private void cbMetAsEgg_CheckedChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
if (cbMetAsEgg.Checked)
{
cbEggLocation.Enabled = true;
dtEggDate.Enabled = true;
TempPokemon.EggDate = dtEggDate.Value;
}
else
{
cbEggLocation.Enabled = false;
dtEggDate.Enabled = false;
TempPokemon.SetNoEggDate();
}
CheckApplyButton();
}
}
private void numMetLevel_ValueChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.MetLevel = (Byte)(numMetLevel.Value);
CheckApplyButton();
}
}
private void cbGame_SelectedIndexChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.HometownID = (Byte)(cbGame.SelectedValue);
CheckApplyButton();
}
}
private void cbCountry_SelectedIndexChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.LanguageID = (Byte)(cbCountry.SelectedValue);
CheckApplyButton();
}
}
private void cbIsEgg_CheckedChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.IsEgg = cbIsEgg.Checked;
UpdateHatchSteps();
cbMetAsEgg.Checked = true;
cbEggLocation.SelectedIndex = 0;
dtEggDate.Value = System.DateTime.Today;
UpdateSprite();
UpdateFormIcon();
CheckApplyButton();
}
}
private void UpdateHatchSteps()
{
if (TempPokemon.IsEgg)
{
txtMinHatchSteps.Enabled = true;
txtMinHatchSteps.Text = (255 * TempPokemon.Tameness).ToString("N0");
}
else
{
txtMinHatchSteps.Enabled = false;
txtMinHatchSteps.Text = "";
}
}
private void cbNsPokemon_CheckedChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.IsNsPokemon = cbNsPokemon.Checked;
CheckApplyButton();
}
}
private void cbFateful_CheckedChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.IsFateful = cbFateful.Checked;
CheckApplyButton();
}
}
private void cbPKRSStrain_SelectedIndexChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.PokerusStrain = cbPKRSStrain.SelectedIndex;
UpdatePokerus();
CheckApplyButton();
}
}
private void cbPKRSDays_SelectedIndexChanged(object sender, EventArgs e)
{
if (UISet && PokemonSet)
{
TempPokemon.PokerusDays = cbPKRSDays.SelectedIndex;
UpdatePokerus();
CheckApplyButton();
}
}
}
}
| 36.462174 | 187 | 0.493784 | [
"Unlicense"
] | codemonkey85/PKMDS-Save-Editor-Build | PKMDS-Save-Editor/PKMDS-Save-Editor/PKMDS-Save-Editor/frmPKMViewer.cs | 57,357 | C# |
namespace BookShop.Data
{
internal static class DataSettings
{
internal const string DefaultConnection = @"Server=.\SQLEXPRESS;Database=BookShop;Integrated Security=True";
}
}
| 24.625 | 116 | 0.720812 | [
"MIT"
] | stanislavstoyanov99/SoftUni-Software-Engineering | DB-with-C#/Labs-And-Homeworks/Entity Framework Core/07. Advanced Querying - Exercise/BookShop.Data/DataSettings.cs | 199 | C# |
// <auto-generated />
using System;
using API.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace API.Migrations
{
[DbContext(typeof(StoreContext))]
partial class StoreContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "5.0.15");
modelBuilder.Entity("API.Entities.Basket", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("BuyerId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Baskets");
});
modelBuilder.Entity("API.Entities.BasketItem", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("BasketId")
.HasColumnType("INTEGER");
b.Property<int>("ProductId")
.HasColumnType("INTEGER");
b.Property<int>("Quantity")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("BasketId");
b.HasIndex("ProductId");
b.ToTable("BasketItems");
});
modelBuilder.Entity("API.Entities.OrderAggregate.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("BuyerId")
.HasColumnType("TEXT");
b.Property<long>("DeliveryFee")
.HasColumnType("INTEGER");
b.Property<DateTime>("OrderDate")
.HasColumnType("TEXT");
b.Property<int>("OrderStatus")
.HasColumnType("INTEGER");
b.Property<long>("Subtotal")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("Orders");
});
modelBuilder.Entity("API.Entities.OrderAggregate.OrderItem", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<int?>("OrderId")
.HasColumnType("INTEGER");
b.Property<long>("Price")
.HasColumnType("INTEGER");
b.Property<int>("Quantity")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("OrderId");
b.ToTable("OrderItem");
});
modelBuilder.Entity("API.Entities.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Brand")
.HasColumnType("TEXT");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<string>("PictureUrl")
.HasColumnType("TEXT");
b.Property<long>("Price")
.HasColumnType("INTEGER");
b.Property<int>("QuantityInStock")
.HasColumnType("INTEGER");
b.Property<string>("Type")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Products");
});
modelBuilder.Entity("API.Entities.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles");
b.HasData(
new
{
Id = 1,
ConcurrencyStamp = "33c7b040-8885-493f-8dff-b1908a17ae4f",
Name = "Member",
NormalizedName = "MEMBER"
},
new
{
Id = 2,
ConcurrencyStamp = "a7148d63-b7d6-43c4-83f6-3ecb210a24f7",
Name = "Admin",
NormalizedName = "ADMIN"
});
});
modelBuilder.Entity("API.Entities.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("AccessFailedCount")
.HasColumnType("INTEGER");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<bool>("EmailConfirmed")
.HasColumnType("INTEGER");
b.Property<bool>("LockoutEnabled")
.HasColumnType("INTEGER");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("TEXT");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("PasswordHash")
.HasColumnType("TEXT");
b.Property<string>("PhoneNumber")
.HasColumnType("TEXT");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("INTEGER");
b.Property<string>("SecurityStamp")
.HasColumnType("TEXT");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("INTEGER");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("API.Entities.UserAddress", b =>
{
b.Property<int>("Id")
.HasColumnType("INTEGER");
b.Property<string>("Address1")
.HasColumnType("TEXT");
b.Property<string>("Address2")
.HasColumnType("TEXT");
b.Property<string>("City")
.HasColumnType("TEXT");
b.Property<string>("Country")
.HasColumnType("TEXT");
b.Property<string>("FullName")
.HasColumnType("TEXT");
b.Property<string>("State")
.HasColumnType("TEXT");
b.Property<string>("Zip")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("UserAddress");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<int>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ClaimType")
.HasColumnType("TEXT");
b.Property<string>("ClaimValue")
.HasColumnType("TEXT");
b.Property<int>("RoleId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<int>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ClaimType")
.HasColumnType("TEXT");
b.Property<string>("ClaimValue")
.HasColumnType("TEXT");
b.Property<int>("UserId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<int>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("TEXT");
b.Property<string>("ProviderKey")
.HasColumnType("TEXT");
b.Property<string>("ProviderDisplayName")
.HasColumnType("TEXT");
b.Property<int>("UserId")
.HasColumnType("INTEGER");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<int>", b =>
{
b.Property<int>("UserId")
.HasColumnType("INTEGER");
b.Property<int>("RoleId")
.HasColumnType("INTEGER");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<int>", b =>
{
b.Property<int>("UserId")
.HasColumnType("INTEGER");
b.Property<string>("LoginProvider")
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<string>("Value")
.HasColumnType("TEXT");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("API.Entities.BasketItem", b =>
{
b.HasOne("API.Entities.Basket", "Basket")
.WithMany("Items")
.HasForeignKey("BasketId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("API.Entities.Product", "Product")
.WithMany()
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Basket");
b.Navigation("Product");
});
modelBuilder.Entity("API.Entities.OrderAggregate.Order", b =>
{
b.OwnsOne("API.Entities.OrderAggregate.ShippingAddress", "ShippingAddress", b1 =>
{
b1.Property<int>("OrderId")
.HasColumnType("INTEGER");
b1.Property<string>("Address1")
.HasColumnType("TEXT");
b1.Property<string>("Address2")
.HasColumnType("TEXT");
b1.Property<string>("City")
.HasColumnType("TEXT");
b1.Property<string>("Country")
.HasColumnType("TEXT");
b1.Property<string>("FullName")
.HasColumnType("TEXT");
b1.Property<string>("State")
.HasColumnType("TEXT");
b1.Property<string>("Zip")
.HasColumnType("TEXT");
b1.HasKey("OrderId");
b1.ToTable("Orders");
b1.WithOwner()
.HasForeignKey("OrderId");
});
b.Navigation("ShippingAddress");
});
modelBuilder.Entity("API.Entities.OrderAggregate.OrderItem", b =>
{
b.HasOne("API.Entities.OrderAggregate.Order", null)
.WithMany("OrderItems")
.HasForeignKey("OrderId");
b.OwnsOne("API.Entities.OrderAggregate.ProductItemOrdered", "ItemOrdered", b1 =>
{
b1.Property<int>("OrderItemId")
.HasColumnType("INTEGER");
b1.Property<string>("Name")
.HasColumnType("TEXT");
b1.Property<int>("ProductId")
.HasColumnType("INTEGER");
b1.Property<string>("ProductUrl")
.HasColumnType("TEXT");
b1.HasKey("OrderItemId");
b1.ToTable("OrderItem");
b1.WithOwner()
.HasForeignKey("OrderItemId");
});
b.Navigation("ItemOrdered");
});
modelBuilder.Entity("API.Entities.UserAddress", b =>
{
b.HasOne("API.Entities.User", null)
.WithOne("Address")
.HasForeignKey("API.Entities.UserAddress", "Id")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<int>", b =>
{
b.HasOne("API.Entities.Role", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<int>", b =>
{
b.HasOne("API.Entities.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<int>", b =>
{
b.HasOne("API.Entities.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<int>", b =>
{
b.HasOne("API.Entities.Role", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("API.Entities.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<int>", b =>
{
b.HasOne("API.Entities.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("API.Entities.Basket", b =>
{
b.Navigation("Items");
});
modelBuilder.Entity("API.Entities.OrderAggregate.Order", b =>
{
b.Navigation("OrderItems");
});
modelBuilder.Entity("API.Entities.User", b =>
{
b.Navigation("Address");
});
#pragma warning restore 612, 618
}
}
}
| 34.168807 | 101 | 0.405649 | [
"MIT"
] | szerem/learn-to-build-an-e-commerce-store-with-dotnet-react-redux | ReStore/API/Migrations/StoreContextModelSnapshot.cs | 18,624 | C# |
namespace ForumSystem.Data.Common.Models
{
using System;
public interface IAuditInfo
{
DateTime CreatedOn { get; set; }
DateTime? ModifiedOn { get; set; }
}
}
| 16.166667 | 42 | 0.613402 | [
"MIT"
] | Avanguarde/csharp-web | 2020-Jan-Season/ASP-NET-Core/ForumSystem/Data/ForumSystem.Data.Common/Models/IAuditInfo.cs | 196 | C# |
using UnityEngine;
using XNodeEditor;
namespace PofyTools
{
[CustomNodeGraphEditor(typeof(CategoryGraph))]
public class CategoryGraphEditor : NodeGraphEditor
{
private CategoryGraph _catGraph;
/// <summary>
/// Overriding GetNodeMenuName lets you control if and how nodes are categorized.
/// In this example we are sorting out all node types that are not in the XNode.Examples namespace.
/// </summary>
public override string GetNodeMenuName(System.Type type)
{
if (this._catGraph == null)
this._catGraph = this.target as CategoryGraph;
if (type.Namespace == "PofyTools")
{
//if (type == typeof(CategorySetNode) && this._catGraph.HasSetNode)
// return null;
return base.GetNodeMenuName(type).Replace("Pofy Tools/", "");
}
else
return null;
}
public override void OnGUI()
{
if (this._catGraph == null)
this._catGraph = this.target as CategoryGraph;
//if (this._catGraph.HasSetNode)
//{
// this._catGraph.SetNode.position = NodeEditorWindow.current.WindowToGridPosition(Vector2.zero);
//}
base.OnGUI();
}
}
} | 31.045455 | 112 | 0.560761 | [
"MIT"
] | PofyTeam/PofyTools | CategoryGraph/Editor/CategoryGraphEditor.cs | 1,368 | C# |
// -----------------------------------------------------------------------
// <copyright file="Snapshot.cs" company="RossKing">
// Copyright (c) RossKing. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Media.Metadata;
/// <summary>
/// The snapshot.
/// </summary>
internal class Snapshot
{
private readonly System.Drawing.Color[,] buffer;
/// <summary>
/// Initialises a new instance of the <see cref="Snapshot"/> class.
/// </summary>
/// <param name="height">The height.</param>
/// <param name="width">The width.</param>
internal Snapshot(int height, int width) => this.buffer = new System.Drawing.Color[height, width];
/// <summary>
/// Initialises a new instance of the <see cref="Snapshot"/> class.
/// </summary>
protected Snapshot()
: this(0, 0)
{
}
/// <summary>
/// Gets the width.
/// </summary>
internal int Width => this.buffer.GetLength(1);
/// <summary>
/// Gets the height.
/// </summary>
internal int Height => this.buffer.GetLength(0);
/// <summary>
/// Gets the value.
/// </summary>
/// <param name="row">The row.</param>
/// <param name="column">The column.</param>
/// <returns>The color.</returns>
internal virtual System.Drawing.Color this[int row, int column]
{
get => this.buffer[row, column];
set => this.buffer[row, column] = value;
}
/// <summary>
/// Creates a <see cref="Snapshot"/> from the source image.
/// </summary>
/// <param name="sourceImage">The source image.</param>
/// <returns>The snap shot.</returns>
internal static Snapshot FromImage(System.Drawing.Image sourceImage)
{
var snapshot = new Snapshot(sourceImage.Height, sourceImage.Width);
var bitmap = new System.Drawing.Bitmap(sourceImage);
for (var i = 0; i < bitmap.Height; i++)
{
for (var j = 0; j < bitmap.Width; j++)
{
snapshot[i, j] = bitmap.GetPixel(j, i);
}
}
return snapshot;
}
/// <summary>
/// Converts this instance to an image.
/// </summary>
/// <returns>The image.</returns>
internal System.Drawing.Image ToImage() => this.CreateBitmap();
/// <summary>
/// Sets all the pixels.
/// </summary>
/// <param name="colorToSet">The color to set.</param>
internal void SetAllPixels(System.Drawing.Color colorToSet)
{
for (var i = 0; i < this.Height; i++)
{
for (var j = 0; j < this.Width; j++)
{
this[i, j] = colorToSet;
}
}
}
private System.Drawing.Bitmap CreateBitmap()
{
var bitmap = new System.Drawing.Bitmap(this.Width, this.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
for (var i = 0; i < this.Height; i++)
{
for (var j = 0; j < this.Width; j++)
{
bitmap.SetPixel(j, i, this.buffer[i, j]);
}
}
return bitmap;
}
} | 29.308411 | 124 | 0.527423 | [
"MIT"
] | rsking/Media.Metadata | Media.Metadata.Core/Snapshot.cs | 3,138 | C# |
using System;
using System.Data;
using ServiceStack.OrmLite.Converters;
namespace ServiceStack.OrmLite.SqlServer.Converters
{
public class SqlServerBoolConverter : BoolConverter
{
public override string ColumnDefinition
{
get { return "BIT"; }
}
public override DbType DbType
{
get { return DbType.Boolean; }
}
public override object ToDbValue(Type fieldType, object value)
{
if (value is bool)
return value;
return 0 != (long)this.ConvertNumber(typeof(long), value);
}
public override string ToQuotedString(Type fieldType, object value)
{
var boolValue = (bool)value;
return base.DialectProvider.GetQuotedValue(boolValue ? 1 : 0, typeof(int));
}
public override object FromDbValue(Type fieldType, object value)
{
if (value is bool)
return value;
return 0 != (long)this.ConvertNumber(typeof(long), value);
}
}
} | 26.317073 | 87 | 0.582947 | [
"Apache-2.0"
] | 10by10pixel/YAFNET | yafsrc/ServiceStack/ServiceStack.OrmLite.SqlServer/Converters/SqlServerBoolConverter.cs | 1,081 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Dts.V20180330.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class ModifySubscribeNameResponse : AbstractModel
{
/// <summary>
/// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 30.340909 | 81 | 0.665169 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Dts/V20180330/Models/ModifySubscribeNameResponse.cs | 1,393 | C# |
using System.Collections.Generic;
using System.Security.Claims;
namespace DeviceManagement.Services
{
/// <summary>
/// Token service to generate token
/// </summary>
public interface ITokenService
{
/// <summary>
/// Generate access toke with the claims
/// </summary>
/// <param name="claims"></param>
/// <returns></returns>
string GenerateAccessToken(IEnumerable<Claim> claims);
/// <summary>
/// Generate refresh token
/// </summary>
/// <returns></returns>
string GenerateRefreshToken();
/// <summary>
/// Get principal from the expired token
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
ClaimsPrincipal GetPrincipalFromExpiredToken(string token);
/// <summary>
/// Get principal from the token
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
ClaimsPrincipal GetPrincipal(string token);
}
}
| 27.205128 | 67 | 0.562677 | [
"Apache-2.0"
] | jeevasusej/DeviceManagement | DeviceManagement/Service/ITokenService.cs | 1,063 | C# |
using Main;
using AI.ScriptBased;
using UnityEngine;
namespace ScriptBasedAI
{
class MoveTo : ScriptAction
{
private Vector3 m_TargetPos;
public MoveTo(Vector3 targetPos)
{
m_TargetPos = targetPos;
}
public override bool Update()
{
Tank t = (Tank) Agent;
if (Vector3.Distance(m_TargetPos, t.Position) < 1f)
{
return true;
}
t.Move(m_TargetPos);
return false;
}
}
class Fire : ScriptAction
{
public override bool Update()
{
Tank t = (Tank) Agent;
t.Fire();
return true;
}
}
class WaitForSeconds : ScriptAction
{
private float m_WaitingDuration;
private float m_ExpiredTime;
public WaitForSeconds(float waitingDuration)
{
m_WaitingDuration = waitingDuration;
}
public override void Init()
{
m_ExpiredTime = Time.time + m_WaitingDuration;
}
public override bool Update()
{
return Time.time >= m_ExpiredTime;
}
}
public class MyTank : Tank
{
private ScriptActionMachine m_Machine;
protected override void OnStart()
{
base.OnStart();
m_Machine = new ScriptActionMachine(this);
m_Machine.AddAction(new MoveTo(Vector3.zero));
m_Machine.AddAction(new WaitForSeconds(2f));
m_Machine.AddAction(new Fire());
m_Machine.AddAction(new MoveTo(Match.instance.GetRebornPos(Team)));
m_Machine.AddAction(new WaitForSeconds(3f));
}
protected override void OnUpdate()
{
m_Machine.Update();
}
public override string GetName()
{
return "ScriptBasedAITank";
}
}
} | 22.694118 | 79 | 0.536029 | [
"MIT"
] | dotlive/TankBattle | Assets/Scripts/ExampleAI/ScriptBasedAI/MyTank.cs | 1,931 | C# |
using System;
using System.Collections.Generic;
namespace Calculator.LinqLike
{
public static partial class Calculator
{
public static ILinqLikeCalculator<T> Create<T>(params T[] values) where T : struct, IConvertible
=> new RootLinqLikeCalculator<T>(values);
public static List<T> ToList<T>(this ILinqLikeCalculator<T> calculator)
where T : struct, IConvertible
{
var result = new List<T>();
var innerCalculator = calculator.GetCalculator();
while(innerCalculator.Next()) {
result.Add(innerCalculator.Current);
}
return result;
}
}
}
| 30 | 104 | 0.602899 | [
"MIT"
] | dcvsling/fluent-api-example | src/Calculator.LinqLike/Calculator.cs | 690 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("MoeMoonUI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MoeMoonUI")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("c3d08605-54d9-44f0-b476-fc248830399c")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 25.378378 | 56 | 0.713525 | [
"MIT"
] | yiyungent/demos | MoeMoon/MoeMoon/MoeMoonUI/Properties/AssemblyInfo.cs | 1,280 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using SQLite4Unity3d;
[Serializable]
public class Person
{
[PrimaryKey]
public string Name { get; set; }
public string Password { get; set; }
public int Score { get; set; }
public int LocationId { get; set; }
}
| 20.375 | 40 | 0.702454 | [
"MIT"
] | YinLam-Chan/SDV-NewGame | Assets/Scenes/Scripts/Models/DataServices/Person.cs | 328 | C# |
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using NeoSharp.Core.Blockchain.Repositories;
using NeoSharp.Core.Models;
using NeoSharp.Core.Models.OperationManger;
using NeoSharp.Core.Types;
using NeoSharp.TestHelpers;
using NeoSharp.Types;
namespace NeoSharp.Core.Test.Models
{
[TestClass]
public class UtTransactionOperationManager : TestBase
{
[TestMethod]
public void Verify_AttributeUsageECDH02()
{
var testee = AutoMockContainer.Create<TransactionOperationManager>();
var transaction = new EnrollmentTransaction
{
Attributes = new []
{
new TransactionAttribute
{
Usage = TransactionAttributeUsage.ECDH02
}
}
};
var result = testee.Verify(transaction);
result.Should().BeFalse();
}
[TestMethod]
public void Verify_WithInputsWithSamePrevHashAndPrevIndex()
{
var testee = AutoMockContainer.Create<TransactionOperationManager>();
var transaction = new Transaction
{
Attributes = new []
{
new TransactionAttribute
{
Usage = TransactionAttributeUsage.ContractHash
}
},
Inputs = new[]
{
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 1
},
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 1
}
}
};
var result = testee.Verify(transaction);
result.Should().BeFalse();
}
[TestMethod]
public void Verify_WithDoubleSpending()
{
var testee = AutoMockContainer.Create<TransactionOperationManager>();
var transaction = new Transaction
{
Attributes = new []
{
new TransactionAttribute
{
Usage = TransactionAttributeUsage.ContractHash
}
},
Inputs = new[]
{
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 1
},
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 2
}
}
};
this.AutoMockContainer.GetMock<ITransactionRepository>()
.Setup(b => b.IsDoubleSpend(transaction))
.Returns(true);
var result = testee.Verify(transaction);
result.Should().BeFalse();
}
[TestMethod]
public void Verify_WithStrangeAssetId()
{
var testee = AutoMockContainer.Create<TransactionOperationManager>();
var transaction = new Transaction
{
Attributes = new []
{
new TransactionAttribute
{
Usage = TransactionAttributeUsage.ContractHash
}
},
Inputs = new[]
{
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 1
},
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 2
}
},
Outputs = new[]
{
new TransactionOutput
{
AssetId = UInt256.Zero
}
}
};
this.AutoMockContainer
.GetMock<ITransactionRepository>()
.Setup(b => b.IsDoubleSpend(transaction))
.Returns(false);
this.AutoMockContainer
.GetMock<IAssetRepository>()
.Setup(b => b.GetAsset(It.IsAny<UInt256>()))
.ReturnsAsync(() => null);
var result = testee.Verify(transaction);
result.Should().BeFalse();
}
[TestMethod]
public void Verify_WithKnownAssetIdButNotGeverningAndNotUtility()
{
var testee = AutoMockContainer.Create<TransactionOperationManager>();
var transaction = new Transaction
{
Attributes = new []
{
new TransactionAttribute
{
Usage = TransactionAttributeUsage.ContractHash
}
},
Inputs = new[]
{
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 1
},
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 2
}
},
Outputs = new[]
{
new TransactionOutput
{
AssetId = UInt256.Zero
}
}
};
this.AutoMockContainer
.GetMock<ITransactionRepository>()
.Setup(b => b.IsDoubleSpend(transaction))
.Returns(false);
this.AutoMockContainer
.GetMock<IAssetRepository>()
.Setup(b => b.GetAsset(It.IsAny<UInt256>()))
.ReturnsAsync(() => new Asset
{
AssetType = AssetType.DutyFlag
});
var result = testee.Verify(transaction);
result.Should().BeFalse();
}
[TestMethod]
public void Verify_WithOutputValueDivisibleByAssetRule()
{
var testee = AutoMockContainer.Create<TransactionOperationManager>();
var transaction = new Transaction
{
Attributes = new []
{
new TransactionAttribute
{
Usage = TransactionAttributeUsage.ContractHash
}
},
Inputs = new[]
{
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 1
},
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 2
}
},
Outputs = new[]
{
new TransactionOutput
{
AssetId = UInt256.Zero,
Value = Fixed8.MaxValue
}
}
};
this.AutoMockContainer
.GetMock<ITransactionRepository>()
.Setup(b => b.IsDoubleSpend(transaction))
.Returns(false);
this.AutoMockContainer
.GetMock<IAssetRepository>()
.Setup(b => b.GetAsset(It.IsAny<UInt256>()))
.ReturnsAsync(() => new Asset
{
AssetType = AssetType.GoverningToken
});
var result = testee.Verify(transaction);
result.Should().BeFalse();
}
[TestMethod]
public void Verify_WithoutReferences()
{
var testee = AutoMockContainer.Create<TransactionOperationManager>();
var transaction = new Transaction
{
Attributes = new []
{
new TransactionAttribute
{
Usage = TransactionAttributeUsage.ContractHash
}
},
Inputs = new[]
{
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 1
},
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 2
}
},
Outputs = new[]
{
new TransactionOutput
{
AssetId = UInt256.Zero,
Value = Fixed8.One
}
}
};
var transactionModelMock = this.AutoMockContainer.GetMock<ITransactionRepository>();
transactionModelMock
.Setup(b => b.IsDoubleSpend(transaction))
.Returns(false);
transactionModelMock
.Setup(x => x.GetTransaction(It.IsAny<UInt256>()))
.ReturnsAsync(() => null);
this.AutoMockContainer
.GetMock<IAssetRepository>()
.Setup(b => b.GetAsset(It.IsAny<UInt256>()))
.ReturnsAsync(() => new Asset
{
AssetType = AssetType.GoverningToken
});
var result = testee.Verify(transaction);
result.Should().BeFalse();
}
[TestMethod]
public void Verify_WithMoreThanOneReferenceAmountGreaterThanZero()
{
var testee = AutoMockContainer.Create<TransactionOperationManager>();
var transaction = new Transaction
{
Attributes = new []
{
new TransactionAttribute
{
Usage = TransactionAttributeUsage.ContractHash
}
},
Inputs = new[]
{
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 1
},
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 2
}
},
Outputs = new[]
{
new TransactionOutput
{
AssetId = UInt256.Zero,
Value = Fixed8.One
}
}
};
var transactionOfPreviousHash = new Transaction
{
Outputs = new []
{
new TransactionOutput(), // it's not using the first because PrevIndex is 1
new TransactionOutput
{
AssetId = UInt256.Parse("1a259dba256600620c6c91094f3a300b30f0cbaecee19c6114deffd3288957d7"),
Value = Fixed8.One
},
new TransactionOutput
{
AssetId = UInt256.Parse("d4dab99ed65c3655a9619b215ab1988561b706b6e5196b6e0ada916aa6601622"),
Value = Fixed8.One
}
}
};
var transactionModelMock = this.AutoMockContainer.GetMock<ITransactionRepository>();
transactionModelMock
.Setup(b => b.IsDoubleSpend(transaction))
.Returns(false);
transactionModelMock
.Setup(x => x.GetTransaction(It.IsAny<UInt256>()))
.ReturnsAsync(() => transactionOfPreviousHash);
this.AutoMockContainer
.GetMock<IAssetRepository>()
.Setup(b => b.GetAsset(It.IsAny<UInt256>()))
.ReturnsAsync(() => new Asset
{
AssetType = AssetType.GoverningToken
});
var result = testee.Verify(transaction);
result.Should().BeFalse();
}
[TestMethod]
public void Verify_WithOnlyOneReferenceAmountGreaterThanZeroButItsNotUtilityToken()
{
var testee = AutoMockContainer.Create<TransactionOperationManager>();
var transaction = new Transaction
{
Attributes = new []
{
new TransactionAttribute
{
Usage = TransactionAttributeUsage.ContractHash
}
},
Inputs = new[]
{
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 1
},
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 2
}
},
Outputs = new[]
{
new TransactionOutput
{
AssetId = UInt256.Zero,
Value = Fixed8.One
}
}
};
var transactionOfPreviousHash = new Transaction
{
Outputs = new []
{
new TransactionOutput(), // it's not using the first because PrevIndex is 1
new TransactionOutput
{
AssetId = UInt256.Parse("1a259dba256600620c6c91094f3a300b30f0cbaecee19c6114deffd3288957d7"),
Value = Fixed8.One
},
new TransactionOutput
{
AssetId = UInt256.Parse("1a259dba256600620c6c91094f3a300b30f0cbaecee19c6114deffd3288957d7"),
Value = Fixed8.One
}
}
};
var transactionModelMock = this.AutoMockContainer.GetMock<ITransactionRepository>();
transactionModelMock
.Setup(b => b.IsDoubleSpend(transaction))
.Returns(false);
transactionModelMock
.Setup(x => x.GetTransaction(It.IsAny<UInt256>()))
.ReturnsAsync(() => transactionOfPreviousHash);
this.AutoMockContainer
.GetMock<IAssetRepository>()
.Setup(b => b.GetAsset(It.IsAny<UInt256>()))
.ReturnsAsync(() => new Asset
{
AssetType = AssetType.GoverningToken
});
this.AutoMockContainer
.GetMock<ITransactionContext>()
.SetupGet(x => x.UtilityTokenHash)
.Returns(UInt256.Parse("602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"));
var result = testee.Verify(transaction);
result.Should().BeFalse();
}
[TestMethod]
public void Verify_WithReferenceAmountZeroAndExistingSystemFee()
{
var testee = AutoMockContainer.Create<TransactionOperationManager>();
var transaction = new Transaction
{
Attributes = new []
{
new TransactionAttribute
{
Usage = TransactionAttributeUsage.ContractHash
}
},
Inputs = new[]
{
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 1
},
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 2
}
},
Outputs = new[]
{
new TransactionOutput
{
AssetId = UInt256.Zero,
Value = Fixed8.One
}
}
};
var transactionOfPreviousHash = new Transaction
{
Outputs = new []
{
new TransactionOutput(), // it's not using the first because PrevIndex is 1
new TransactionOutput
{
AssetId = UInt256.Parse("602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"),
Value = Fixed8.Zero
},
new TransactionOutput
{
AssetId = UInt256.Parse("602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"),
Value = Fixed8.Zero
}
}
};
var transactionModelMock = this.AutoMockContainer.GetMock<ITransactionRepository>();
transactionModelMock
.Setup(b => b.IsDoubleSpend(transaction))
.Returns(false);
transactionModelMock
.Setup(x => x.GetTransaction(It.IsAny<UInt256>()))
.ReturnsAsync(() => transactionOfPreviousHash);
this.AutoMockContainer
.GetMock<IAssetRepository>()
.Setup(b => b.GetAsset(It.IsAny<UInt256>()))
.ReturnsAsync(() => new Asset
{
AssetType = AssetType.GoverningToken
});
var transactionContextMock = this.AutoMockContainer.GetMock<ITransactionContext>();
transactionContextMock
.SetupGet(x => x.UtilityTokenHash)
.Returns(UInt256.Parse("602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"));
transactionContextMock
.Setup(x => x.GetSystemFee(It.IsAny<Transaction>()))
.Returns(Fixed8.One);
var result = testee.Verify(transaction);
result.Should().BeFalse();
}
[TestMethod]
public void Verify_WithReferenceAmountLessThanSystemFee()
{
var testee = AutoMockContainer.Create<TransactionOperationManager>();
var transaction = new Transaction
{
Attributes = new []
{
new TransactionAttribute
{
Usage = TransactionAttributeUsage.ContractHash
}
},
Inputs = new[]
{
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 1
},
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 2
}
},
Outputs = new[]
{
new TransactionOutput
{
AssetId = UInt256.Zero,
Value = Fixed8.One
}
}
};
var transactionOfPreviousHash = new Transaction
{
Outputs = new []
{
new TransactionOutput(), // it's not using the first because PrevIndex is 1
new TransactionOutput
{
AssetId = UInt256.Parse("602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"),
Value = Fixed8.One
},
new TransactionOutput
{
AssetId = UInt256.Parse("602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"),
Value = Fixed8.One
}
}
};
var transactionModelMock = this.AutoMockContainer.GetMock<ITransactionRepository>();
transactionModelMock
.Setup(b => b.IsDoubleSpend(transaction))
.Returns(false);
transactionModelMock
.Setup(x => x.GetTransaction(It.IsAny<UInt256>()))
.ReturnsAsync(() => transactionOfPreviousHash);
this.AutoMockContainer
.GetMock<IAssetRepository>()
.Setup(b => b.GetAsset(It.IsAny<UInt256>()))
.ReturnsAsync(() => new Asset
{
AssetType = AssetType.GoverningToken
});
var transactionContextMock = this.AutoMockContainer.GetMock<ITransactionContext>();
transactionContextMock
.SetupGet(x => x.UtilityTokenHash)
.Returns(UInt256.Parse("602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"));
transactionContextMock
.Setup(x => x.GetSystemFee(It.IsAny<Transaction>()))
.Returns(new Fixed8(300000000));
var result = testee.Verify(transaction);
result.Should().BeFalse();
}
[TestMethod]
public void Verify_ClaimTransacWithNegativeResultOfUtilityToken()
{
var testee = AutoMockContainer.Create<TransactionOperationManager>();
var transaction = new ClaimTransaction
{
Attributes = new []
{
new TransactionAttribute
{
Usage = TransactionAttributeUsage.ContractHash
}
},
Inputs = new[]
{
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 1
},
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 2
}
},
Outputs = new[]
{
new TransactionOutput
{
AssetId = UInt256.Zero,
Value = Fixed8.One
}
}
};
var transactionOfPreviousHash = new Transaction
{
Outputs = new []
{
new TransactionOutput(), // it's not using the first because PrevIndex is 1
new TransactionOutput
{
AssetId = UInt256.Parse("602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"),
Value = new Fixed8(-5)
}
}
};
var transactionModelMock = this.AutoMockContainer.GetMock<ITransactionRepository>();
transactionModelMock
.Setup(b => b.IsDoubleSpend(transaction))
.Returns(false);
transactionModelMock
.Setup(x => x.GetTransaction(It.IsAny<UInt256>()))
.ReturnsAsync(() => transactionOfPreviousHash);
this.AutoMockContainer
.GetMock<IAssetRepository>()
.Setup(b => b.GetAsset(It.IsAny<UInt256>()))
.ReturnsAsync(() => new Asset
{
AssetType = AssetType.GoverningToken
});
var transactionContextMock = this.AutoMockContainer.GetMock<ITransactionContext>();
transactionContextMock
.SetupGet(x => x.UtilityTokenHash)
.Returns(UInt256.Parse("602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"));
transactionContextMock
.Setup(x => x.GetSystemFee(It.IsAny<Transaction>()))
.Returns(Fixed8.Zero);
var result = testee.Verify(transaction);
result.Should().BeFalse();
}
[TestMethod]
public void Verify_NotMinerTransacWithNegativeResults()
{
var testee = AutoMockContainer.Create<TransactionOperationManager>();
var transaction = new EnrollmentTransaction
{
Attributes = new []
{
new TransactionAttribute
{
Usage = TransactionAttributeUsage.ContractHash
}
},
Inputs = new[]
{
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 1
},
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 2
}
},
Outputs = new[]
{
new TransactionOutput
{
AssetId = UInt256.Zero,
Value = Fixed8.One
}
}
};
var transactionOfPreviousHash = new Transaction
{
Outputs = new []
{
new TransactionOutput(), // it's not using the first because PrevIndex is 1
new TransactionOutput
{
AssetId = UInt256.Parse("602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"),
Value = Fixed8.One
},
new TransactionOutput
{
AssetId = UInt256.Parse("602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"),
Value = Fixed8.One
}
}
};
var transactionModelMock = this.AutoMockContainer.GetMock<ITransactionRepository>();
transactionModelMock
.Setup(b => b.IsDoubleSpend(transaction))
.Returns(false);
transactionModelMock
.Setup(x => x.GetTransaction(It.IsAny<UInt256>()))
.ReturnsAsync(() => transactionOfPreviousHash);
this.AutoMockContainer
.GetMock<IAssetRepository>()
.Setup(b => b.GetAsset(It.IsAny<UInt256>()))
.ReturnsAsync(() => new Asset
{
AssetType = AssetType.GoverningToken
});
var transactionContextMock = this.AutoMockContainer.GetMock<ITransactionContext>();
transactionContextMock
.SetupGet(x => x.UtilityTokenHash)
.Returns(UInt256.Parse("602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"));
transactionContextMock
.Setup(x => x.GetSystemFee(It.IsAny<Transaction>()))
.Returns(new Fixed8(190000000));
var result = testee.Verify(transaction);
result.Should().BeFalse();
}
[TestMethod]
public void Verify_WitnessVerifiedWrong()
{
var testee = AutoMockContainer.Create<TransactionOperationManager>();
var transaction = new EnrollmentTransaction
{
Attributes = new []
{
new TransactionAttribute
{
Usage = TransactionAttributeUsage.ContractHash
}
},
Inputs = new[]
{
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 1
},
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 2
}
},
Outputs = new[]
{
new TransactionOutput
{
AssetId = UInt256.Parse("1a259dba256600620c6c91094f3a300b30f0cbaecee19c6114deffd3288957d7"),
Value = new Fixed8(200000000)
}
},
Witness = new []
{
new Witness()
}
};
var transactionOfPreviousHash = new Transaction
{
Outputs = new []
{
new TransactionOutput(), // it's not using the first because PrevIndex is 1
new TransactionOutput
{
AssetId = UInt256.Parse("602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"),
Value = new Fixed8(200000000)
},
new TransactionOutput
{
AssetId = UInt256.Parse("1a259dba256600620c6c91094f3a300b30f0cbaecee19c6114deffd3288957d7"),
Value = new Fixed8(200000000)
}
}
};
var transactionModelMock = this.AutoMockContainer.GetMock<ITransactionRepository>();
transactionModelMock
.Setup(b => b.IsDoubleSpend(transaction))
.Returns(false);
transactionModelMock
.Setup(x => x.GetTransaction(It.IsAny<UInt256>()))
.ReturnsAsync(() => transactionOfPreviousHash);
this.AutoMockContainer
.GetMock<IAssetRepository>()
.Setup(b => b.GetAsset(It.IsAny<UInt256>()))
.ReturnsAsync(() => new Asset
{
AssetType = AssetType.GoverningToken
});
var transactionContextMock = this.AutoMockContainer.GetMock<ITransactionContext>();
transactionContextMock
.SetupGet(x => x.UtilityTokenHash)
.Returns(UInt256.Parse("602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"));
transactionContextMock
.Setup(x => x.GetSystemFee(It.IsAny<Transaction>()))
.Returns(new Fixed8(190000000));
this.AutoMockContainer
.GetMock<IWitnessOperationsManager>()
.Setup(x => x.Verify(It.IsAny<Witness>()))
.Returns(false);
var result = testee.Verify(transaction);
result.Should().BeFalse();
}
[TestMethod]
public void Verify_Success()
{
var testee = AutoMockContainer.Create<TransactionOperationManager>();
var transaction = new EnrollmentTransaction
{
Attributes = new []
{
new TransactionAttribute
{
Usage = TransactionAttributeUsage.ContractHash
}
},
Inputs = new[]
{
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 1
},
new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 2
}
},
Outputs = new[]
{
new TransactionOutput
{
AssetId = UInt256.Parse("1a259dba256600620c6c91094f3a300b30f0cbaecee19c6114deffd3288957d7"),
Value = new Fixed8(200000000)
}
},
Witness = new []
{
new Witness()
}
};
var transactionOfPreviousHash = new Transaction
{
Outputs = new []
{
new TransactionOutput(), // it's not using the first because PrevIndex is 1
new TransactionOutput
{
AssetId = UInt256.Parse("602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"),
Value = new Fixed8(200000000)
},
new TransactionOutput
{
AssetId = UInt256.Parse("1a259dba256600620c6c91094f3a300b30f0cbaecee19c6114deffd3288957d7"),
Value = new Fixed8(200000000)
}
}
};
var transactionModelMock = this.AutoMockContainer.GetMock<ITransactionRepository>();
transactionModelMock
.Setup(b => b.IsDoubleSpend(transaction))
.Returns(false);
transactionModelMock
.Setup(x => x.GetTransaction(It.IsAny<UInt256>()))
.ReturnsAsync(() => transactionOfPreviousHash);
this.AutoMockContainer
.GetMock<IAssetRepository>()
.Setup(b => b.GetAsset(It.IsAny<UInt256>()))
.ReturnsAsync(() => new Asset
{
AssetType = AssetType.GoverningToken
});
var transactionContextMock = this.AutoMockContainer.GetMock<ITransactionContext>();
transactionContextMock
.SetupGet(x => x.UtilityTokenHash)
.Returns(UInt256.Parse("602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"));
transactionContextMock
.Setup(x => x.GetSystemFee(It.IsAny<Transaction>()))
.Returns(new Fixed8(190000000));
this.AutoMockContainer
.GetMock<IWitnessOperationsManager>()
.Setup(x => x.Verify(It.IsAny<Witness>()))
.Returns(true);
var result = testee.Verify(transaction);
result.Should().BeTrue();
}
}
} | 34.887113 | 116 | 0.439952 | [
"MIT"
] | BSathvik/neo-sharp | test/NeoSharp.Core.Test/Models/UtTransactionVerifier.cs | 34,922 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using ewmsCsharp.Classes;
using ewmsCsharp.Interfaces;
namespace ewmsCsharp.Classes
{
public class Customer : Data, ICustomer, IDataImage
{
#region Public members
public DateTime BeginingServies { get => _beginingServies; set { _beginingServies = value; EditeDate_SetActual(); } }
public string PhoneNumber { get => _phoneNumber; set { _phoneNumber = value; EditeDate_SetActual(); } }
public string Address { get => _address; set { _address = value; EditeDate_SetActual(); } }
public bool IsImage { get => _isImage; set { _isImage = value; EditeDate_SetActual(); } }
#endregion
#region Private members
/// <summary>
/// Get Defult Values
/// </summary>
private DateTime _beginingServies = DateTime.MinValue;
private string _phoneNumber = string.Empty;
private string _address = string.Empty;
private bool _isImage = false; //IDataImage
#endregion
#region Constractors
public Customer(string id, string name) : base(id, name) { }
[JsonConstructor]
public Customer(string id, string name, DateTime beginingServies, string phoneNumber, string address, bool isImage) : this(id, name)
{
BeginingServies = beginingServies;
PhoneNumber = phoneNumber;
Address = address;
IsImage = isImage;
}
#endregion
#region Public methods
#region Overrides
public override string ToString()
{
return base.ToString()+
$"Begin Service: {BeginingServies}\t\tHasImage:{IsImage}\n" +
$"Phone Number: {PhoneNumber}\t\t Address: {Address}\n";
}
#endregion
#endregion
#region Private methods (empty)
#endregion
}
}
| 31.714286 | 140 | 0.623624 | [
"MIT"
] | w3arthur/CSharp-Reference | ewmsCsharpUnDevelopVersion/ewmsCsharp/Classes/Customer.cs | 2,000 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _01.House_Price
{
class Program
{
static void Main(string[] args)
{
decimal start = int.Parse(Console.ReadLine());
decimal end = int.Parse(Console.ReadLine());
decimal stop = int.Parse(Console.ReadLine());
decimal comb = 1;
for (int i = start; i <=end; i++)
{
for (int j = start; j <=end; j++)
{
Console.Write("<{0}-{1}>",i,j);
comb++;
if (comb>stop)
{
return;
}
}
}
}
}
}
| 23.382353 | 58 | 0.425157 | [
"MIT"
] | delian1986/C-SoftUni-repo | Programming Basics/exersiceForExam/november 20 evening/01. House Price/06.max_comb.cs | 797 | 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.Gcp.AccessContextManager.Inputs
{
public sealed class ServicePerimetersServicePerimeterSpecIngressPolicyIngressFromSourceGetArgs : Pulumi.ResourceArgs
{
/// <summary>
/// An `AccessLevel` resource name that allow resources within the
/// `ServicePerimeters` to be accessed from the internet. `AccessLevels` listed
/// must be in the same policy as this `ServicePerimeter`. Referencing a nonexistent
/// `AccessLevel` will cause an error. If no `AccessLevel` names are listed,
/// resources within the perimeter can only be accessed via Google Cloud calls
/// with request origins within the perimeter.
/// Example `accessPolicies/MY_POLICY/accessLevels/MY_LEVEL.`
/// If * is specified, then all IngressSources will be allowed.
/// </summary>
[Input("accessLevel")]
public Input<string>? AccessLevel { get; set; }
/// <summary>
/// A Google Cloud resource that is allowed to ingress the perimeter.
/// Requests from these resources will be allowed to access perimeter data.
/// Currently only projects are allowed. Format `projects/{project_number}`
/// The project may be in any Google Cloud organization, not just the
/// organization that the perimeter is defined in. `*` is not allowed, the case
/// of allowing all Google Cloud resources only is not supported.
/// </summary>
[Input("resource")]
public Input<string>? Resource { get; set; }
public ServicePerimetersServicePerimeterSpecIngressPolicyIngressFromSourceGetArgs()
{
}
}
}
| 45.113636 | 120 | 0.684635 | [
"ECL-2.0",
"Apache-2.0"
] | la3mmchen/pulumi-gcp | sdk/dotnet/AccessContextManager/Inputs/ServicePerimetersServicePerimeterSpecIngressPolicyIngressFromSourceGetArgs.cs | 1,985 | C# |
// <auto-generated />
using System;
using BaseModels;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace BaseModels.Migrations
{
[DbContext(typeof(GwDbContext))]
[Migration("20210106133059_ChangedItemIconName")]
partial class ChangedItemIconName
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseIdentityByDefaultColumns()
.HasAnnotation("Relational:MaxIdentifierLength", 63)
.HasAnnotation("ProductVersion", "5.0.1");
modelBuilder.Entity("BaseModels.Account", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.UseIdentityByDefaultColumn();
b.Property<string>("APIKey")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Accounts");
});
modelBuilder.Entity("BaseModels.Armor", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.UseIdentityByDefaultColumn();
b.Property<int>("Defense")
.HasColumnType("integer");
b.Property<string>("StatChoices")
.HasColumnType("text");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("text");
b.Property<string>("WeightClass")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Armors");
});
modelBuilder.Entity("BaseModels.BackItem", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.UseIdentityByDefaultColumn();
b.Property<string>("StatChoices")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("BackItems");
});
modelBuilder.Entity("BaseModels.Consumable", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.UseIdentityByDefaultColumn();
b.Property<int>("ApplyCount")
.HasColumnType("integer");
b.Property<int>("ColorId")
.HasColumnType("integer");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<int>("DurationMs")
.HasColumnType("integer");
b.Property<string>("ExtraRecipeIds")
.HasColumnType("text");
b.Property<int>("GuildUpgradeIds")
.HasColumnType("integer");
b.Property<string>("Icon")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<int>("RecipeId")
.HasColumnType("integer");
b.Property<string>("Skins")
.HasColumnType("text");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("text");
b.Property<string>("UnlockType")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Consumables");
});
modelBuilder.Entity("BaseModels.Container", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.UseIdentityByDefaultColumn();
b.Property<string>("Type")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Containers");
});
modelBuilder.Entity("BaseModels.GatheringTool", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.UseIdentityByDefaultColumn();
b.Property<string>("Type")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("GatheringTools");
});
modelBuilder.Entity("BaseModels.Gizmo", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.UseIdentityByDefaultColumn();
b.Property<int>("GuildUpgradeId")
.HasColumnType("integer");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("text");
b.Property<string>("VendorIds")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Gizmos");
});
modelBuilder.Entity("BaseModels.Item", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.UseIdentityByDefaultColumn();
b.Property<int?>("ArmorId")
.HasColumnType("integer");
b.Property<int?>("BackItemId")
.HasColumnType("integer");
b.Property<string>("ChatLink")
.HasColumnType("text");
b.Property<int?>("ConsumableId")
.HasColumnType("integer");
b.Property<int?>("ContainerId")
.HasColumnType("integer");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<string>("Flags")
.IsRequired()
.HasColumnType("text");
b.Property<string>("GameTypes")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("GatheringToolId")
.HasColumnType("integer");
b.Property<int?>("GizmoId")
.HasColumnType("integer");
b.Property<string>("Icon")
.HasColumnType("text");
b.Property<int>("Level")
.HasColumnType("integer");
b.Property<int?>("MiniatureId")
.HasColumnType("integer");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Rarity")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Restrictions")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("SalvageKitId")
.HasColumnType("integer");
b.Property<int?>("SkinId")
.HasColumnType("integer");
b.Property<int?>("TrinketId")
.HasColumnType("integer");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("UpgradeComponentId")
.HasColumnType("integer");
b.Property<int>("VendorValue")
.HasColumnType("integer");
b.Property<int?>("WeaponId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ArmorId");
b.HasIndex("BackItemId");
b.HasIndex("ConsumableId");
b.HasIndex("ContainerId");
b.HasIndex("GatheringToolId");
b.HasIndex("GizmoId");
b.HasIndex("MiniatureId");
b.HasIndex("SalvageKitId");
b.HasIndex("SkinId");
b.HasIndex("TrinketId");
b.HasIndex("UpgradeComponentId");
b.HasIndex("WeaponId");
b.ToTable("Items");
});
modelBuilder.Entity("BaseModels.Listing", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.UseIdentityByDefaultColumn();
b.Property<string>("BuyListing")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("ItemId")
.HasColumnType("integer");
b.Property<string>("SellListing")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ItemId");
b.ToTable("Listings");
});
modelBuilder.Entity("BaseModels.Miniature", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.UseIdentityByDefaultColumn();
b.Property<int>("MinipetId")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Miniatures");
});
modelBuilder.Entity("BaseModels.SalvageKit", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.UseIdentityByDefaultColumn();
b.Property<int>("Charges")
.HasColumnType("integer");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("SalvageKits");
});
modelBuilder.Entity("BaseModels.Skin", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.UseIdentityByDefaultColumn();
b.Property<string>("Description")
.HasColumnType("text");
b.Property<string>("Flags")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Icon")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Rarity")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Restrictions")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Skins");
});
modelBuilder.Entity("BaseModels.TPListing", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.UseIdentityByDefaultColumn();
b.Property<int>("Quantity")
.HasColumnType("integer");
b.Property<int>("UnitPrice")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("TPListings");
});
modelBuilder.Entity("BaseModels.Trinket", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.UseIdentityByDefaultColumn();
b.Property<string>("SecondarySuffixItemId")
.HasColumnType("text");
b.Property<string>("StatChoices")
.HasColumnType("text");
b.Property<int>("SuffixItemId")
.HasColumnType("integer");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Trinkets");
});
modelBuilder.Entity("BaseModels.UpgradeComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.UseIdentityByDefaultColumn();
b.Property<string>("Bonuses")
.HasColumnType("text");
b.Property<string>("Flags")
.HasColumnType("text");
b.Property<string>("InfusionUpgradeFlags")
.HasColumnType("text");
b.Property<string>("Suffix")
.HasColumnType("text");
b.Property<string>("Type")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("UpgradeComponents");
});
modelBuilder.Entity("BaseModels.Weapon", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.UseIdentityByDefaultColumn();
b.Property<string>("DamageType")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Defense")
.HasColumnType("integer");
b.Property<int>("MaxPower")
.HasColumnType("integer");
b.Property<int>("MinPower")
.HasColumnType("integer");
b.Property<string>("StatChoices")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Weapons");
});
modelBuilder.Entity("BaseModels.Item", b =>
{
b.HasOne("BaseModels.Armor", "Armor")
.WithMany()
.HasForeignKey("ArmorId");
b.HasOne("BaseModels.BackItem", "BackItem")
.WithMany()
.HasForeignKey("BackItemId");
b.HasOne("BaseModels.Consumable", "Consumable")
.WithMany()
.HasForeignKey("ConsumableId");
b.HasOne("BaseModels.Container", "Container")
.WithMany()
.HasForeignKey("ContainerId");
b.HasOne("BaseModels.GatheringTool", "GatheringTool")
.WithMany()
.HasForeignKey("GatheringToolId");
b.HasOne("BaseModels.Gizmo", "Gizmo")
.WithMany()
.HasForeignKey("GizmoId");
b.HasOne("BaseModels.Miniature", "Miniature")
.WithMany()
.HasForeignKey("MiniatureId");
b.HasOne("BaseModels.SalvageKit", "SalvageKit")
.WithMany()
.HasForeignKey("SalvageKitId");
b.HasOne("BaseModels.Skin", "Skin")
.WithMany()
.HasForeignKey("SkinId");
b.HasOne("BaseModels.Trinket", "Trinket")
.WithMany()
.HasForeignKey("TrinketId");
b.HasOne("BaseModels.UpgradeComponent", "UpgradeComponent")
.WithMany()
.HasForeignKey("UpgradeComponentId");
b.HasOne("BaseModels.Weapon", "Weapon")
.WithMany()
.HasForeignKey("WeaponId");
b.Navigation("Armor");
b.Navigation("BackItem");
b.Navigation("Consumable");
b.Navigation("Container");
b.Navigation("GatheringTool");
b.Navigation("Gizmo");
b.Navigation("Miniature");
b.Navigation("SalvageKit");
b.Navigation("Skin");
b.Navigation("Trinket");
b.Navigation("UpgradeComponent");
b.Navigation("Weapon");
});
modelBuilder.Entity("BaseModels.Listing", b =>
{
b.HasOne("BaseModels.Item", "Item")
.WithMany()
.HasForeignKey("ItemId");
b.Navigation("Item");
});
#pragma warning restore 612, 618
}
}
}
| 32.426343 | 79 | 0.404329 | [
"Apache-2.0"
] | DeKuczma/GW2-Trader | backend/Db_Models/Migrations/20210106133059_ChangedItemIconName.Designer.cs | 18,712 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query;
namespace Pomelo.EntityFrameworkCore.MySql.FunctionalTests
{
public class MySqlComplianceTest : RelationalComplianceTestBase
{
// TODO: Implement remaining 3.x tests.
protected override ICollection<Type> IgnoredTestBases { get; } = new HashSet<Type>
{
typeof(UdfDbFunctionTestBase<>),
typeof(TransactionInterceptionTestBase),
typeof(CommandInterceptionTestBase),
typeof(NorthwindQueryTaggingQueryTestBase<>),
// TODO: Reenable LoggingMySqlTest once its issue has been fixed in EF Core upstream.
typeof(LoggingTestBase),
typeof(LoggingRelationalTestBase<,>)
};
protected override Assembly TargetAssembly { get; } = typeof(MySqlComplianceTest).Assembly;
public override void All_test_bases_must_be_implemented()
{
base.All_test_bases_must_be_implemented();
}
}
}
| 34.09375 | 99 | 0.696609 | [
"MIT"
] | rodrigue10/Pomelo.EntityFrameworkCore.MySql | test/EFCore.MySql.FunctionalTests/MySqlComplianceTest.cs | 1,093 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.System;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace TranscendenceChat_UAP.Common
{
/// <summary>
/// NavigationHelper aids in navigation between pages. It provides commands used to
/// navigate back and forward as well as registers for standard mouse and keyboard
/// shortcuts used to go back and forward in Windows and the hardware back button in
/// Windows Phone. In addition it integrates SuspensionManger to handle process lifetime
/// management and state management when navigating between pages.
/// </summary>
/// <example>
/// To make use of NavigationHelper, follow these two steps or
/// start with a BasicPage or any other Page item template other than BlankPage.
///
/// 1) Create an instance of the NavigationHelper somewhere such as in the
/// constructor for the page and register a callback for the LoadState and
/// SaveState events.
/// <code>
/// public MyPage()
/// {
/// this.InitializeComponent();
/// var navigationHelper = new NavigationHelper(this);
/// this.navigationHelper.LoadState += navigationHelper_LoadState;
/// this.navigationHelper.SaveState += navigationHelper_SaveState;
/// }
///
/// private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
/// { }
/// private async void navigationHelper_SaveState(object sender, LoadStateEventArgs e)
/// { }
/// </code>
///
/// 2) Register the page to call into the NavigationHelper whenever the page participates
/// in navigation by overriding the <see cref="Windows.UI.Xaml.Controls.Page.OnNavigatedTo"/>
/// and <see cref="Windows.UI.Xaml.Controls.Page.OnNavigatedFrom"/> events.
/// <code>
/// protected override void OnNavigatedTo(NavigationEventArgs e)
/// {
/// navigationHelper.OnNavigatedTo(e);
/// }
///
/// protected override void OnNavigatedFrom(NavigationEventArgs e)
/// {
/// navigationHelper.OnNavigatedFrom(e);
/// }
/// </code>
/// </example>
[Windows.Foundation.Metadata.WebHostHidden]
public class NavigationHelper : DependencyObject
{
private Page Page { get; set; }
private Frame Frame { get { return this.Page.Frame; } }
/// <summary>
/// Initializes a new instance of the <see cref="NavigationHelper"/> class.
/// </summary>
/// <param name="page">A reference to the current page used for navigation.
/// This reference allows for frame manipulation and to ensure that keyboard
/// navigation requests only occur when the page is occupying the entire window.</param>
public NavigationHelper(Page page)
{
this.Page = page;
// When this page is part of the visual tree make two changes:
// 1) Map application view state to visual state for the page
// 2) Handle hardware navigation requests
this.Page.Loaded += (sender, e) =>
{
#if WINDOWS_PHONE_APP
Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
#else
// Keyboard and mouse navigation only apply when occupying the entire window
if (this.Page.ActualHeight == Window.Current.Bounds.Height &&
this.Page.ActualWidth == Window.Current.Bounds.Width)
{
// Listen to the window directly so focus isn't required
Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated +=
CoreDispatcher_AcceleratorKeyActivated;
Window.Current.CoreWindow.PointerPressed +=
this.CoreWindow_PointerPressed;
}
#endif
};
// Undo the same changes when the page is no longer visible
this.Page.Unloaded += (sender, e) =>
{
#if WINDOWS_PHONE_APP
Windows.Phone.UI.Input.HardwareButtons.BackPressed -= HardwareButtons_BackPressed;
#else
Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated -=
CoreDispatcher_AcceleratorKeyActivated;
Window.Current.CoreWindow.PointerPressed -=
this.CoreWindow_PointerPressed;
#endif
};
}
#region Navigation support
RelayCommand _goBackCommand;
RelayCommand _goForwardCommand;
/// <summary>
/// <see cref="RelayCommand"/> used to bind to the back Button's Command property
/// for navigating to the most recent item in back navigation history, if a Frame
/// manages its own navigation history.
///
/// The <see cref="RelayCommand"/> is set up to use the virtual method <see cref="GoBack"/>
/// as the Execute Action and <see cref="CanGoBack"/> for CanExecute.
/// </summary>
public RelayCommand GoBackCommand
{
get
{
if (_goBackCommand == null)
{
_goBackCommand = new RelayCommand(
() => this.GoBack(),
() => this.CanGoBack());
}
return _goBackCommand;
}
set
{
_goBackCommand = value;
}
}
/// <summary>
/// <see cref="RelayCommand"/> used for navigating to the most recent item in
/// the forward navigation history, if a Frame manages its own navigation history.
///
/// The <see cref="RelayCommand"/> is set up to use the virtual method <see cref="GoForward"/>
/// as the Execute Action and <see cref="CanGoForward"/> for CanExecute.
/// </summary>
public RelayCommand GoForwardCommand
{
get
{
if (_goForwardCommand == null)
{
_goForwardCommand = new RelayCommand(
() => this.GoForward(),
() => this.CanGoForward());
}
return _goForwardCommand;
}
}
/// <summary>
/// Virtual method used by the <see cref="GoBackCommand"/> property
/// to determine if the <see cref="Frame"/> can go back.
/// </summary>
/// <returns>
/// true if the <see cref="Frame"/> has at least one entry
/// in the back navigation history.
/// </returns>
public virtual bool CanGoBack()
{
return this.Frame != null && this.Frame.CanGoBack;
}
/// <summary>
/// Virtual method used by the <see cref="GoForwardCommand"/> property
/// to determine if the <see cref="Frame"/> can go forward.
/// </summary>
/// <returns>
/// true if the <see cref="Frame"/> has at least one entry
/// in the forward navigation history.
/// </returns>
public virtual bool CanGoForward()
{
return this.Frame != null && this.Frame.CanGoForward;
}
/// <summary>
/// Virtual method used by the <see cref="GoBackCommand"/> property
/// to invoke the <see cref="Windows.UI.Xaml.Controls.Frame.GoBack"/> method.
/// </summary>
public virtual void GoBack()
{
if (this.Frame != null && this.Frame.CanGoBack) this.Frame.GoBack();
}
/// <summary>
/// Virtual method used by the <see cref="GoForwardCommand"/> property
/// to invoke the <see cref="Windows.UI.Xaml.Controls.Frame.GoForward"/> method.
/// </summary>
public virtual void GoForward()
{
if (this.Frame != null && this.Frame.CanGoForward) this.Frame.GoForward();
}
#if WINDOWS_PHONE_APP
/// <summary>
/// Invoked when the hardware back button is pressed. For Windows Phone only.
/// </summary>
/// <param name="sender">Instance that triggered the event.</param>
/// <param name="e">Event data describing the conditions that led to the event.</param>
private void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
{
if (this.GoBackCommand.CanExecute(null))
{
e.Handled = true;
this.GoBackCommand.Execute(null);
}
}
#else
/// <summary>
/// Invoked on every keystroke, including system keys such as Alt key combinations, when
/// this page is active and occupies the entire window. Used to detect keyboard navigation
/// between pages even when the page itself doesn't have focus.
/// </summary>
/// <param name="sender">Instance that triggered the event.</param>
/// <param name="e">Event data describing the conditions that led to the event.</param>
private void CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher sender,
AcceleratorKeyEventArgs e)
{
var virtualKey = e.VirtualKey;
// Only investigate further when Left, Right, or the dedicated Previous or Next keys
// are pressed
if ((e.EventType == CoreAcceleratorKeyEventType.SystemKeyDown ||
e.EventType == CoreAcceleratorKeyEventType.KeyDown) &&
(virtualKey == VirtualKey.Left || virtualKey == VirtualKey.Right ||
(int)virtualKey == 166 || (int)virtualKey == 167))
{
var coreWindow = Window.Current.CoreWindow;
var downState = CoreVirtualKeyStates.Down;
bool menuKey = (coreWindow.GetKeyState(VirtualKey.Menu) & downState) == downState;
bool controlKey = (coreWindow.GetKeyState(VirtualKey.Control) & downState) == downState;
bool shiftKey = (coreWindow.GetKeyState(VirtualKey.Shift) & downState) == downState;
bool noModifiers = !menuKey && !controlKey && !shiftKey;
bool onlyAlt = menuKey && !controlKey && !shiftKey;
if (((int)virtualKey == 166 && noModifiers) ||
(virtualKey == VirtualKey.Left && onlyAlt))
{
// When the previous key or Alt+Left are pressed navigate back
e.Handled = true;
this.GoBackCommand.Execute(null);
}
else if (((int)virtualKey == 167 && noModifiers) ||
(virtualKey == VirtualKey.Right && onlyAlt))
{
// When the next key or Alt+Right are pressed navigate forward
e.Handled = true;
this.GoForwardCommand.Execute(null);
}
}
}
/// <summary>
/// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
/// page is active and occupies the entire window. Used to detect browser-style next and
/// previous mouse button clicks to navigate between pages.
/// </summary>
/// <param name="sender">Instance that triggered the event.</param>
/// <param name="e">Event data describing the conditions that led to the event.</param>
private void CoreWindow_PointerPressed(CoreWindow sender,
PointerEventArgs e)
{
var properties = e.CurrentPoint.Properties;
// Ignore button chords with the left, right, and middle buttons
if (properties.IsLeftButtonPressed || properties.IsRightButtonPressed ||
properties.IsMiddleButtonPressed)
return;
// If back or foward are pressed (but not both) navigate appropriately
bool backPressed = properties.IsXButton1Pressed;
bool forwardPressed = properties.IsXButton2Pressed;
if (backPressed ^ forwardPressed)
{
e.Handled = true;
if (backPressed) this.GoBackCommand.Execute(null);
if (forwardPressed) this.GoForwardCommand.Execute(null);
}
}
#endif
#endregion
#region Process lifetime management
private String _pageKey;
/// <summary>
/// Register this event on the current page to populate the page
/// with content passed during navigation as well as any saved
/// state provided when recreating a page from a prior session.
/// </summary>
public event LoadStateEventHandler LoadState;
/// <summary>
/// Register this event on the current page to preserve
/// state associated with the current page in case the
/// application is suspended or the page is discarded from
/// the navigaqtion cache.
/// </summary>
public event SaveStateEventHandler SaveState;
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// This method calls <see cref="LoadState"/>, where all page specific
/// navigation and process lifetime management logic should be placed.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property provides the group to be displayed.</param>
public void OnNavigatedTo(NavigationEventArgs e)
{
var frameState = SuspensionManager.SessionStateForFrame(this.Frame);
this._pageKey = "Page-" + this.Frame.BackStackDepth;
if (e.NavigationMode == NavigationMode.New)
{
// Clear existing state for forward navigation when adding a new page to the
// navigation stack
var nextPageKey = this._pageKey;
int nextPageIndex = this.Frame.BackStackDepth;
while (frameState.Remove(nextPageKey))
{
nextPageIndex++;
nextPageKey = "Page-" + nextPageIndex;
}
// Pass the navigation parameter to the new page
if (this.LoadState != null)
{
this.LoadState(this, new LoadStateEventArgs(e.Parameter, null));
}
}
else
{
// Pass the navigation parameter and preserved page state to the page, using
// the same strategy for loading suspended state and recreating pages discarded
// from cache
if (this.LoadState != null)
{
this.LoadState(this, new LoadStateEventArgs(e.Parameter, (Dictionary<String, Object>)frameState[this._pageKey]));
}
}
}
/// <summary>
/// Invoked when this page will no longer be displayed in a Frame.
/// This method calls <see cref="SaveState"/>, where all page specific
/// navigation and process lifetime management logic should be placed.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property provides the group to be displayed.</param>
public void OnNavigatedFrom(NavigationEventArgs e)
{
var frameState = SuspensionManager.SessionStateForFrame(this.Frame);
var pageState = new Dictionary<String, Object>();
if (this.SaveState != null)
{
this.SaveState(this, new SaveStateEventArgs(pageState));
}
frameState[_pageKey] = pageState;
}
#endregion
}
/// <summary>
/// Represents the method that will handle the <see cref="NavigationHelper.LoadState"/>event
/// </summary>
public delegate void LoadStateEventHandler(object sender, LoadStateEventArgs e);
/// <summary>
/// Represents the method that will handle the <see cref="NavigationHelper.SaveState"/>event
/// </summary>
public delegate void SaveStateEventHandler(object sender, SaveStateEventArgs e);
/// <summary>
/// Class used to hold the event data required when a page attempts to load state.
/// </summary>
public class LoadStateEventArgs : EventArgs
{
/// <summary>
/// The parameter value passed to <see cref="Frame.Navigate(Type, Object)"/>
/// when this page was initially requested.
/// </summary>
public Object NavigationParameter { get; private set; }
/// <summary>
/// A dictionary of state preserved by this page during an earlier
/// session. This will be null the first time a page is visited.
/// </summary>
public Dictionary<string, Object> PageState { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="LoadStateEventArgs"/> class.
/// </summary>
/// <param name="navigationParameter">
/// The parameter value passed to <see cref="Frame.Navigate(Type, Object)"/>
/// when this page was initially requested.
/// </param>
/// <param name="pageState">
/// A dictionary of state preserved by this page during an earlier
/// session. This will be null the first time a page is visited.
/// </param>
public LoadStateEventArgs(Object navigationParameter, Dictionary<string, Object> pageState)
: base()
{
this.NavigationParameter = navigationParameter;
this.PageState = pageState;
}
}
/// <summary>
/// Class used to hold the event data required when a page attempts to save state.
/// </summary>
public class SaveStateEventArgs : EventArgs
{
/// <summary>
/// An empty dictionary to be populated with serializable state.
/// </summary>
public Dictionary<string, Object> PageState { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="SaveStateEventArgs"/> class.
/// </summary>
/// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
public SaveStateEventArgs(Dictionary<string, Object> pageState)
: base()
{
this.PageState = pageState;
}
}
}
| 42.810502 | 133 | 0.585889 | [
"MIT"
] | tamifist/Transcendence | TranscendenceChat-UAP/TranscendenceChat-UAP/Common/NavigationHelper.cs | 18,753 | C# |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\Navigation\CrowdManager.h:113
namespace UnrealEngine
{
public partial class FCrowdAvoidanceSamplingPattern : NativeStructWrapper
{
public FCrowdAvoidanceSamplingPattern(IntPtr NativePointer, bool IsRef = false) : base(NativePointer, IsRef)
{
}
public FCrowdAvoidanceSamplingPattern() :
base(E_CreateStruct_FCrowdAvoidanceSamplingPattern(), false)
{
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_CreateStruct_FCrowdAvoidanceSamplingPattern();
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_FCrowdAvoidanceSamplingPattern_AddSample(IntPtr self, float angleInDegrees, float normalizedRadius);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_FCrowdAvoidanceSamplingPattern_AddSampleWithMirror(IntPtr self, float angleInDegrees, float normalizedRadius);
#endregion
#region ExternMethods
public void AddSample(float angleInDegrees, float normalizedRadius)
=> E_FCrowdAvoidanceSamplingPattern_AddSample(this, angleInDegrees, normalizedRadius);
public void AddSampleWithMirror(float angleInDegrees, float normalizedRadius)
=> E_FCrowdAvoidanceSamplingPattern_AddSampleWithMirror(this, angleInDegrees, normalizedRadius);
#endregion
public static implicit operator IntPtr(FCrowdAvoidanceSamplingPattern self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator FCrowdAvoidanceSamplingPattern(IntPtr adress)
{
return adress == IntPtr.Zero ? null : new FCrowdAvoidanceSamplingPattern(adress, false);
}
}
}
| 39.107143 | 142 | 0.792694 | [
"Apache-2.0"
] | mrkriv/UnrealDotNet | Plugins/UnrealDotNet/Source/UnrealEngineSharp/Generate/Struct/FCrowdAvoidanceSamplingPattern.cs | 2,190 | C# |
using System;
using UnityEngine;
using Valve.VR;
public class ViveStrokeReader : MonoBehaviour
{
private bool _isTriggerHeld = false;
private bool _areBristlesDown = false;
private bool _isTouchHeld = false;
private Vector2 _prevTouch = new Vector2(0, 0);
public float _moveThreshold = 0.005f;
private float _pressTime = 0f;
private const float LONG_PRESS_TIME = 1.2f;
private float _radiusScale = 0.15f;
private float _defaultScale = 0.02f;
private float _currentRadius = 0.02f;
// Hack to allow for a new position on first
private Vector3 _lastPos = new Vector3(-1000, -1000, -1000);
public GameObject _cursor;
public GameObject _model;
public ToolManager _toolManager;
private int _drawParentId;
public Transform _defaultDrawParent;
private Transform _drawParent;
public Transform DrawParent
{
get { return _drawParent; }
set { _drawParent = value; }
}
//Start Chandan Changes
//To read touchpad position values
public SteamVR_Action_Vector2 TouchpadAction;
//For TriggerHaptics
public SteamVR_Action_Vibration haptics;
//End Chandan Changes
private SteamVR_TrackedObject _trackedObj;
private bool _isPointerMode = false;
public bool IsPointerMode
{
get { return _isPointerMode; }
}
private bool _isSelectorMode = false;
public bool IsSelectorMode
{
get { return _isSelectorMode; }
set { _isSelectorMode = value; }
}
private bool CanDraw
{
get { return (!_isPointerMode && !_isSelectorMode); }
}
public bool IsBrushTool
{
get { return (ToolManager.isBrushTool); }
}
// REPLACE THIS WITH PROPERTY
public void SetPointerMode(bool setting)
{
_isPointerMode = setting;
}
void Awake()
{
try
{
_trackedObj = GetComponent<SteamVR_TrackedObject>();
_drawParent = _defaultDrawParent;
}
catch (Exception e)
{
Debug.LogException(e, this);
}
}
// Update is called once per frame
void Update()
{
try
{
// Might wanna do this less
_cursor.SetActive(!(_isPointerMode || _isSelectorMode));
_model.SetActive(_isPointerMode || _isSelectorMode);
// Only start drawing if not pointing at menu
if (SteamVR_Actions._default.GrabPinch.GetStateDown(SteamVR_Input_Sources.RightHand) && CanDraw && !IsBrushTool)
{
_isTriggerHeld = true;
_toolManager.StartStroke(DrawParent);
_pressTime = 0;
}
if (IsBrushTool && !SteamVR_Actions._default.GrabPinch.GetStateDown(SteamVR_Input_Sources.RightHand) && CanDraw)
{
if (BrushSensorPolling.IsBristleBent[0] || BrushSensorPolling.IsBristleBent[1] || BrushSensorPolling.IsBristleBent[2] ||
BrushSensorPolling.IsBristleBent[3] || BrushSensorPolling.IsBristleBent[4] || BrushSensorPolling.IsBristleBent[5])
{
_isTriggerHeld = true;
_areBristlesDown = true;
_toolManager.StartStroke(DrawParent);
_pressTime = 0;
}
else if(_areBristlesDown)
{
_isTriggerHeld = false;
_toolManager.EndStroke(DrawParent);
_areBristlesDown = false;
}
}
if (SteamVR_Actions._default.GrabPinch.GetStateUp(SteamVR_Input_Sources.RightHand) && _isTriggerHeld)
{
_isTriggerHeld = false;
_toolManager.EndStroke(DrawParent);
if (!_toolManager.IsStrokeTool && _pressTime > LONG_PRESS_TIME)
{
_toolManager.EndTriangle(DrawParent);
}
}
if (_isTriggerHeld || !_toolManager.IsStrokeTool)
{
// Make cursor point relative to current parent (Trackers / World Drawing)
Vector3 currentPos = DrawParent.InverseTransformPoint(_cursor.transform.position);
// We might need to add more sophisticated position smoothing than this
if (Vector3.Distance(currentPos, _lastPos) >= _moveThreshold)
{
_toolManager.UpdateStroke(currentPos, transform.rotation, _currentRadius);
_lastPos = currentPos;
}
}
if (_isTriggerHeld)
{
_pressTime += Time.deltaTime;
if (!_toolManager.IsStrokeTool && _pressTime > LONG_PRESS_TIME)
{
//Controller.TriggerHapticPulse(500, EVRButtonId.k_EButton_SteamVR_Trigger);
if (SteamVR_Actions._default.GrabPinch.GetStateDown(SteamVR_Input_Sources.RightHand))
{
Pulse(1, 50, 75, SteamVR_Input_Sources.RightHand);
}
}
}
// Radius Change
Vector2 touchpadValue = TouchpadAction.GetAxis(SteamVR_Input_Sources.RightHand);
bool currentTouch = touchpadValue != Vector2.zero ? true : false;
if (currentTouch && _isTouchHeld)
{
Vector2 axis = touchpadValue;
float dx = axis.x - _prevTouch.x;
// Use threshold
if (dx > 0.0001 || dx < -0.0001)
{
float newScale = _radiusScale + dx;
// Clamp scale so it doesn't break
if (newScale < 6.5f && newScale > 0.15f)
{
_radiusScale = newScale;
_currentRadius = _radiusScale * _defaultScale;
// Scale the cursor
float s = (_currentRadius) - _cursor.transform.localScale.x;
_cursor.transform.localScale += new Vector3(s, s, s);
}
}
_prevTouch = axis;
}
else if (currentTouch)
{
_prevTouch = touchpadValue;
}
_isTouchHeld = currentTouch;
}
catch (Exception e)
{
Debug.Log("!!!!!!!Exception occured!!!!!!!");
Debug.LogException(e, this);
}
}
public void Pulse(float duration, float frequency, float amplitude, SteamVR_Input_Sources source)
{
haptics.Execute(0, duration, frequency, amplitude, source); //0(First Parameter): duration after which haptics should start.
//print("Pulse from :------>" + source.ToString());
}
}
| 31.953271 | 136 | 0.561568 | [
"MIT"
] | THING-Lab/HapticVRWizard | HapticVRWizard/Assets/Scripts/Inputs/ViveStrokeReader.cs | 6,840 | C# |
using System;
using System.Linq;
using System.Reflection;
using EntitiesBT.Attributes.Editor;
using UnityEditor;
using UnityEngine;
using EntitiesBT.Variant;
namespace EntitiesBT.Editor
{
[CustomPropertyDrawer(typeof(VariantScriptableObjectValueAttribute))]
public class VariantScriptableObjectValueAttributeDrawer : PropertyDrawer
{
private object _scriptableObject;
private string[] _options = new string[0];
private Type _genericType;
private VariantScriptableObjectValueAttribute _attribute;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
if (property.propertyType == SerializedPropertyType.String)
{
if (_genericType == null) _genericType = this.GetGenericType();
if (_attribute == null) _attribute = (VariantScriptableObjectValueAttribute)attribute;
var scriptableObject = property.GetSiblingFieldValue(_attribute.ScriptableObjectFieldName);
if (!Equals(scriptableObject, _scriptableObject))
{
_scriptableObject = scriptableObject;
_options = scriptableObject == null
? new string[0]
: scriptableObject.GetType()
.GetFields(BindingFlags.Instance | BindingFlags.Public)
.Where(fi => fi.FieldType == _genericType)
.Select(fi => fi.Name)
.Concat(scriptableObject.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(pi => pi.PropertyType == _genericType && pi.CanRead)
.Select(pi => pi.Name)
)
.ToArray()
;
}
property.PopupFunc()(position, label.text, _options);
}
else
{
EditorGUI.PropertyField(position, property, label, true);
}
}
}
}
| 41.442308 | 107 | 0.564269 | [
"MIT"
] | r2d2m/EntitiesBT | Packages/variable.scriptable-object/Editor/VariantScriptableObjectValueAttributeDrawer.cs | 2,155 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace OnBackButtonPressed.UWP
{
public sealed partial class MainPage
{
public MainPage()
{
this.InitializeComponent();
LoadApplication(new OnBackButtonPressed.App());
}
}
}
| 23.535714 | 59 | 0.737481 | [
"MIT"
] | nuitsjp/XamarinSamples | OnBackButtonPressed/OnBackButtonPressed/OnBackButtonPressed.UWP/MainPage.xaml.cs | 661 | C# |
using System;
namespace Camus.Projects
{
public struct AssetBundleInfo : IEquatable<AssetBundleInfo>
{
public string Name
{
get;
}
public AssetBundleInfo(string name)
{
Name = name;
}
public bool Equals(AssetBundleInfo other)
{
return GetHashCode() == other.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (object.ReferenceEquals(this, obj))
{
return true;
}
if (this.GetType() != obj.GetType())
{
return false;
}
AssetBundleInfo other = (AssetBundleInfo) obj;
return this.Name == other.Name;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
public override string ToString()
{
return $"[AssetBundle] #{Name}";
}
}
}
| 20.166667 | 63 | 0.4573 | [
"MIT"
] | litsungyi/Camus | Scripts/Core/Projects/AssetBundleInfo.cs | 1,089 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PCControllerTest : Racer {
// [SerializeField]
// private float groundAcceleration = 0.5f; //7f is a default but overwriteable value
[SerializeField]
private float turnAcceleration = 0.5f;
[SerializeField]
private float brakeAcceleration = 0.1f;
[SerializeField]
private float jumpForce = 7f;
[SerializeField]
// private float airMaxSpeed = 6f;
// [SerializeField]
// private float airMaxAccel = .1f;
// [SerializeField]
// private float walkableAngle = 60f;
// private bool isFlying = false;
// private GameObject currentGround;
// Use this for initialization
// Update is called once per frame
void LateUpdate () {
isTurning = false;
Vector3 addForceRight = pcCamera.transform.right * turnAcceleration;
Vector3 addForceForward = pcCamera.transform.forward * turnAcceleration;
Vector3 previousVelocity = pcRigidbody.velocity.normalized;
currentVelocity = pcRigidbody.velocity;
currentRotation = Vector3.zero;
addForceForward.y = 0;
addForceRight.y = 0;
if (Input.GetKey(KeyCode.W))
{
currentRotation += addForceForward;
}
if (Input.GetKey(KeyCode.S) && currentRotation != Vector3.zero)
{
currentRotation -= currentRotation * brakeAcceleration;
}
if (Input.GetKey(KeyCode.D) && currentRotation != Vector3.zero)
{
currentRotation += addForceRight;
isTurning = true;
}
if (Input.GetKey(KeyCode.A) && currentRotation != Vector3.zero)
{
currentRotation -= addForceRight;
isTurning = true;
}
currentVelocity += currentRotation;
if (isTurning)
{
currentVelocity += previousVelocity*0.05f;
}
if (Input.GetKey (KeyCode.Space) && isGrounded)
{
currentVelocity.y = jumpForce;
}
if (isGrounded)
{
anim.SetFloat ("walkSpeed", currentVelocity.z);
}
// float moveHorizontal = Input.GetAxis ("Horizontal");
// float moveVertical = Input.GetAxis ("Vertical");
// Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
RotateDo (currentRotation);
pcRigidbody.velocity = currentVelocity;
// if (Input.GetKey (KeyCode.Space) && isGrounded) {
// pcRigidbody.velocity = new Vector3(pcRigidbody.velocity.x, pcRigidbody.velocity.y+jumpForce, pcRigidbody.velocity.z);
// }
//ground functions
// if(currentGround != null)
// {
// anim.SetBool ("Fly", false);
//
// if (pcRigidbody.velocity.x > 0.0f||pcRigidbody.velocity.z > 0.0f) {
// anim.SetBool ("Walk", true);
// }
//
// else {
// anim.SetBool ("Walk", false);
// }
// if ((Input.GetKey(KeyCode.W)) || (Input.GetKey(KeyCode.A)) || (Input.GetKey(KeyCode.S)) || (Input.GetKey(KeyCode.D)))
// {
// pcRigidbody.velocity = currentVelocity;
// }
//
// if ((Input.GetKey(KeyCode.Space)))
// {
//
// pcRigidbody.velocity = new Vector3(pcRigidbody.velocity.x, jumpForce, pcRigidbody.velocity.z);
//
//
// }
//
//
//// RotateDo ();
// }
// else //if not grounded
// {
// anim.SetBool ("Walk", false);
// anim.SetBool ("Fly", true);
// if ((Input.GetKey(KeyCode.W)) || (Input.GetKey(KeyCode.A)) || (Input.GetKey(KeyCode.S)) || (Input.GetKey(KeyCode.D)))
// {
// pcRigidbody.velocity = AirVelocityAccelerate(pcRigidbody, airMaxAccel, airMaxSpeed);
// }
//// RotateDo ();
//
//
// }
}
// private bool IsGrounded()
// { //our raycast will touch ground regardless of scale
// return Physics.Raycast(transform.position, Vector3.down, transform.localScale.y+.1f);
// }
// private Vector3 AirVelocityAccelerate(Rigidbody acceleratingBody, float maxAccel, float maxSpeed)
// {
//
// Vector3 calcVelocity;
// Vector3 dir = acceleratingBody.velocity;
// //cancle out Y velocity
// dir.y = 0;
// float Mag = dir.magnitude;
// dir = Vector3.Normalize(dir);
//
// //base next tick of acceleration on current momentum
// float currentAccel = maxAccel * (Mag / (maxSpeed + .11f));
// Mag += currentAccel;
// calcVelocity = transform.forward * Mathf.Min(Mag, maxSpeed) + new Vector3(0, acceleratingBody.velocity.y, 0);
//
// return calcVelocity;
// }
}
| 27.621302 | 132 | 0.592973 | [
"MIT"
] | n8sthegr8est/2020_Studios | 2020/Assets/Scripts/PCControllerTest.cs | 4,670 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System.Windows.Controls
{
public enum ClickMode
{
Release,
Press,
//Hover,
}
}
| 15.1875 | 33 | 0.662551 | [
"MIT"
] | Ref12/Grazor | src/Granular/Granular.Presentation/Controls/ClickMode.cs | 245 | 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("TrustStampTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("nunit.tests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// 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")]
| 36.941176 | 84 | 0.742834 | [
"MIT"
] | keutmann/TrustStamp | TrustStampTests/Properties/AssemblyInfo.cs | 1,259 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
namespace MatBlazor
{
/// <summary>
/// The autocomplete is a normal text input enhanced by a panel of suggested options.
/// </summary>
/// <typeparam name="TItem">Type of element type.</typeparam>
public class BaseMatAutocompleteList<TItem> : BaseMatInputComponent<TItem>
{
protected ClassMapper WrapperClassMapper = new ClassMapper();
protected const int DefaultsElementsInPopup = 10;
private bool isOpened;
private string stringValue;
private TItem _value;
public MatList ListRef;
protected IEnumerable<MatAutocompleteListItem<TItem>> GetFilteredCollection(
string searchText)
{
return this.Items.Select<TItem, MatAutocompleteListItem<TItem>>((Func<TItem, MatAutocompleteListItem<TItem>>)(x => new MatAutocompleteListItem<TItem>()
{
StringValue = this.ComputeStringValue(x),
Item = x
})).Where<MatAutocompleteListItem<TItem>>((Func<MatAutocompleteListItem<TItem>, bool>)(x =>
{
if (x == null)
return false;
return string.IsNullOrEmpty(searchText) || x.StringValue?.ToLowerInvariant().Contains(searchText.ToLowerInvariant()) == true;
})).Take<MatAutocompleteListItem<TItem>>(this.NumberOfElementsInPopup ?? 10);
}
protected bool IsShowingClearButton => this.ShowClearButton && !string.IsNullOrEmpty(this.StringValue);
public bool IsOpened
{
get => this.isOpened;
set
{
this.isOpened = value;
this.OnOpenedChanged.InvokeAsync(value);
this.StateHasChanged();
}
}
/// <summary>Maximum number of elements displayed in the popup</summary>
[Parameter]
public int? NumberOfElementsInPopup { get; set; }
/// <summary>The label of the TextField</summary>
[Parameter]
public string Label { get; set; }
/// <summary>
/// The Icon displayed as the leading icon for the TextField
/// </summary>
[Parameter]
public string Icon { get; set; }
/// <summary>The StringValue displayed in the TextField</summary>
[Parameter]
public string StringValue
{
get => this.stringValue;
set
{
if (stringValue == value)
return;
this.stringValue = value;
this.OnTextChanged.InvokeAsync(value);
}
}
/// <summary>
/// The value to be used to pre-select an item from the list
/// </summary>
[Parameter]
public override TItem Value
{
get => this._value;
set
{
this.StringValue = BaseMatAutocompleteList<TItem>.EqualValues(this.Value, default(TItem)) ? string.Empty : this.ComputeStringValue(this.Value);
if (BaseMatAutocompleteList<TItem>.EqualValues(value, this._value))
return;
this._value = value;
this.ValueChanged.InvokeAsync(this._value);
this.ListRef?.SetSelectedIndex(0);
}
}
private static bool EqualValues(TItem a1, TItem a2)
{
return EqualityComparer<TItem>.Default.Equals(a1, a2);
}
[Parameter]
public string HelperText { get; set; }
[Parameter]
public bool HelperTextPersistent { get; set; }
[Parameter]
public bool HelperTextValidation { get; set; }
/// <summary>
/// ItemTemplate is used to render the elements in the popup if no template is given then the string value of the objects is displayed..
/// </summary>
[Parameter]
public RenderFragment<TItem> ItemTemplate { get; set; }
/// <summary>
/// This function is used to select the string part from the item, used both for filtering and displaying if no ItemTemplate is defined.
/// </summary>
[Parameter]
public Func<TItem, string> CustomStringSelector { get; set; }
/// <summary>The collection which should be rendered and filtered</summary>
[Parameter]
public virtual IList<TItem> Items { get; set; }
/// <summary>
/// If this parameter is true then the style of the textbox is outlined see `MatTextfield`
/// </summary>
[Parameter]
public bool Outlined { get; set; }
/// <summary>
/// OnOpenedChanged is fired when the popup dialog is opened or close and the parameter indicates whenever is it open, the default value is false
/// </summary>
[Parameter]
public EventCallback<bool> OnOpenedChanged { get; set; }
/// <summary>
/// OnTextChanged is fired when the string value is changed(when an input occurs in the textfield or when an item is selected)
/// </summary>
[Parameter]
public EventCallback<string> OnTextChanged { get; set; }
/// <summary>
/// This value indicates if the clear button(using a trailing icon) should be displayed, which can clear the entire text and the selected value), the default value is false
/// </summary>
[Parameter]
public bool ShowClearButton { get; set; }
/// <summary>
/// This value indicates if the textfield and the dialog will be or not displayed in the full screen, the default value is false
/// </summary>
[Parameter]
public bool FullWidth { get; set; }
protected ClassMapper HelperTextClassMapper = new ClassMapper();
protected void OpenPopup()
{
this.IsOpened = true;
}
protected void ClosePopup()
{
this.IsOpened = false;
}
public void OnValueChanged(ChangeEventArgs ev)
{
this.StringValue = (string)ev.Value;
this.StateHasChanged();
}
public async void OnKeyDown(KeyboardEventArgs ev)
{
try
{
if (ev.Key == "ArrowDown" || ev.Key == "ArrowUp")
{
var currentIndex = await this.ListRef.GetSelectedIndex();
var nextIndex = ev.Key == "ArrowDown" ? currentIndex++ : currentIndex--;
await this.ListRef.SetSelectedIndex(currentIndex);
}
else
{
if (ev.Key != "Enter" && ev.Key != "Tab")
{
return;
}
var obj = await this.JsInvokeAsync<object>("matBlazor.matList.confirmSelection", (object)this.ListRef.Ref);
}
}
catch (Exception e)
{
}
}
public void ItemClicked(TItem selectedObject)
{
this.Value = selectedObject;
this.StateHasChanged();
}
public void ItemClicked(object selectedObject)
{
this.Value = (TItem)selectedObject;
this.StateHasChanged();
}
public void ClearText(MouseEventArgs e)
{
this.Value = default;
this.StringValue = string.Empty;
this.StateHasChanged();
}
public BaseMatAutocompleteList()
{
this.WrapperClassMapper.Add<ClassMapper>("mat-autocomplete-list").Add<ClassMapper>("mat-autocomplete-list-wrapper").If<ClassMapper>("mat-autocomplete-list-wrapper-fullwidth", (Func<bool>)(() => this.FullWidth));
HelperTextClassMapper
.Add("mdc-text-field-helper-text")
.If("mdc-text-field-helper-text--persistent", () => HelperTextPersistent)
.If("mdc-text-field-helper-text--validation-msg", () => HelperTextValidation);
}
private string ComputeStringValue(TItem obj)
{
Func<TItem, string> customStringSelector = this.CustomStringSelector;
return (customStringSelector != null ? customStringSelector(obj)?.TrimEnd() : (string)string.Empty);
}
}
}
| 36.025641 | 223 | 0.574021 | [
"MIT"
] | databinding-gmbh/MatBlazor | src/MatBlazor/Components/MatAutocompleteList/BaseMatAutocompleteList.cs | 8,432 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Xml.Linq;
namespace MS.Internal.Xml.Linq.ComponentModel
{
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification="False positive.")]
class XTypeDescriptionProvider<T> : TypeDescriptionProvider
{
public XTypeDescriptionProvider() : base(TypeDescriptor.GetProvider(typeof(T))) {
}
public override ICustomTypeDescriptor GetTypeDescriptor(Type type, object instance) {
return new XTypeDescriptor<T>(base.GetTypeDescriptor(type, instance));
}
}
class XTypeDescriptor<T> : CustomTypeDescriptor
{
public XTypeDescriptor(ICustomTypeDescriptor parent) : base(parent) {
}
public override PropertyDescriptorCollection GetProperties() {
return GetProperties(null);
}
public override PropertyDescriptorCollection GetProperties(Attribute[] attributes) {
PropertyDescriptorCollection properties = new PropertyDescriptorCollection(null);
if (attributes == null) {
if (typeof(T) == typeof(XElement)) {
properties.Add(new XElementAttributePropertyDescriptor());
properties.Add(new XElementDescendantsPropertyDescriptor());
properties.Add(new XElementElementPropertyDescriptor());
properties.Add(new XElementElementsPropertyDescriptor());
properties.Add(new XElementValuePropertyDescriptor());
properties.Add(new XElementXmlPropertyDescriptor());
}
else if (typeof(T) == typeof(XAttribute)) {
properties.Add(new XAttributeValuePropertyDescriptor());
}
}
foreach (PropertyDescriptor property in base.GetProperties(attributes)) {
properties.Add(property);
}
return properties;
}
}
abstract class XPropertyDescriptor<T, TProperty> : PropertyDescriptor where T : XObject
{
public XPropertyDescriptor(string name) : base(name, null) {
}
public override Type ComponentType {
get { return typeof(T); }
}
public override bool IsReadOnly {
get { return true; }
}
public override Type PropertyType {
get { return typeof(TProperty); }
}
public override bool SupportsChangeEvents {
get { return true; }
}
public override void AddValueChanged(object component, EventHandler handler) {
bool hasValueChangedHandler = GetValueChangedHandler(component) != null;
base.AddValueChanged(component, handler);
if (hasValueChangedHandler) return;
T c = component as T;
if (c != null && GetValueChangedHandler(component) != null) {
c.Changing += new EventHandler<XObjectChangeEventArgs>(OnChanging);
c.Changed += new EventHandler<XObjectChangeEventArgs>(OnChanged);
}
}
public override bool CanResetValue(object component) {
return false;
}
public override void RemoveValueChanged(object component, EventHandler handler) {
base.RemoveValueChanged(component, handler);
T c = component as T;
if (c != null && GetValueChangedHandler(component) == null) {
c.Changing -= new EventHandler<XObjectChangeEventArgs>(OnChanging);
c.Changed -= new EventHandler<XObjectChangeEventArgs>(OnChanged);
}
}
public override void ResetValue(object component) {
}
public override void SetValue(object component, object value) {
}
public override bool ShouldSerializeValue(object component) {
return false;
}
protected virtual void OnChanged(object sender, XObjectChangeEventArgs args) {
}
protected virtual void OnChanging(object sender, XObjectChangeEventArgs args) {
}
}
class XElementAttributePropertyDescriptor : XPropertyDescriptor<XElement, object>
{
XDeferredSingleton<XAttribute> value;
XAttribute changeState;
public XElementAttributePropertyDescriptor() : base("Attribute") {
}
public override object GetValue(object component) {
return value = new XDeferredSingleton<XAttribute>((e, n) => e.Attribute(n), component as XElement, null);
}
protected override void OnChanged(object sender, XObjectChangeEventArgs args) {
if (value == null) return;
switch (args.ObjectChange) {
case XObjectChange.Add:
XAttribute a = sender as XAttribute;
if (a != null && value.element == a.parent && value.name == a.Name) {
OnValueChanged(value.element, EventArgs.Empty);
}
break;
case XObjectChange.Remove:
a = sender as XAttribute;
if (a != null && changeState == a) {
changeState = null;
OnValueChanged(value.element, EventArgs.Empty);
}
break;
}
}
protected override void OnChanging(object sender, XObjectChangeEventArgs args) {
if (value == null) return;
switch (args.ObjectChange) {
case XObjectChange.Remove:
XAttribute a = sender as XAttribute;
changeState = a != null && value.element == a.parent && value.name == a.Name ? a : null;
break;
}
}
}
class XElementDescendantsPropertyDescriptor : XPropertyDescriptor<XElement, IEnumerable<XElement>>
{
XDeferredAxis<XElement> value;
XName changeState;
public XElementDescendantsPropertyDescriptor() : base("Descendants") {
}
public override object GetValue(object component) {
return value = new XDeferredAxis<XElement>((e, n) => n != null ? e.Descendants(n) : e.Descendants(), component as XElement, null);
}
protected override void OnChanged(object sender, XObjectChangeEventArgs args) {
if (value == null) return;
switch (args.ObjectChange) {
case XObjectChange.Add:
case XObjectChange.Remove:
XElement e = sender as XElement;
if (e != null && (value.name == e.Name || value.name == null)) {
OnValueChanged(value.element, EventArgs.Empty);
}
break;
case XObjectChange.Name:
e = sender as XElement;
if (e != null && value.element != e && value.name != null && (value.name == e.Name || value.name == changeState)) {
changeState = null;
OnValueChanged(value.element, EventArgs.Empty);
}
break;
}
}
protected override void OnChanging(object sender, XObjectChangeEventArgs args) {
if (value == null) return;
switch (args.ObjectChange) {
case XObjectChange.Name:
XElement e = sender as XElement;
changeState = e != null ? e.Name : null;
break;
}
}
}
class XElementElementPropertyDescriptor : XPropertyDescriptor<XElement, object>
{
XDeferredSingleton<XElement> value;
XElement changeState;
public XElementElementPropertyDescriptor() : base("Element") {
}
public override object GetValue(object component) {
return value = new XDeferredSingleton<XElement>((e, n) => e.Element(n), component as XElement, null);
}
protected override void OnChanged(object sender, XObjectChangeEventArgs args) {
if (value == null) return;
switch (args.ObjectChange) {
case XObjectChange.Add:
XElement e = sender as XElement;
if (e != null && value.element == e.parent && value.name == e.Name && value.element.Element(value.name) == e) {
OnValueChanged(value.element, EventArgs.Empty);
}
break;
case XObjectChange.Remove:
e = sender as XElement;
if (e != null && changeState == e) {
changeState = null;
OnValueChanged(value.element, EventArgs.Empty);
}
break;
case XObjectChange.Name:
e = sender as XElement;
if (e != null) {
if (value.element == e.parent && value.name == e.Name && value.element.Element(value.name) == e) {
OnValueChanged(value.element, EventArgs.Empty);
}
else if (changeState == e) {
changeState = null;
OnValueChanged(value.element, EventArgs.Empty);
}
}
break;
}
}
protected override void OnChanging(object sender, XObjectChangeEventArgs args) {
if (value == null) return;
switch (args.ObjectChange) {
case XObjectChange.Remove:
case XObjectChange.Name:
XElement e = sender as XElement;
changeState = e != null && value.element == e.parent && value.name == e.Name && value.element.Element(value.name) == e ? e : null;
break;
}
}
}
class XElementElementsPropertyDescriptor : XPropertyDescriptor<XElement, IEnumerable<XElement>>
{
XDeferredAxis<XElement> value;
object changeState;
public XElementElementsPropertyDescriptor() : base("Elements") {
}
public override object GetValue(object component) {
return value = new XDeferredAxis<XElement>((e, n) => n != null ? e.Elements(n) : e.Elements(), component as XElement, null);
}
protected override void OnChanged(object sender, XObjectChangeEventArgs args) {
if (value == null) return;
switch (args.ObjectChange) {
case XObjectChange.Add:
XElement e = sender as XElement;
if (e != null && value.element == e.parent && (value.name == e.Name || value.name == null)) {
OnValueChanged(value.element, EventArgs.Empty);
}
break;
case XObjectChange.Remove:
e = sender as XElement;
if (e != null && value.element == (changeState as XContainer) && (value.name == e.Name || value.name == null)) {
changeState = null;
OnValueChanged(value.element, EventArgs.Empty);
}
break;
case XObjectChange.Name:
e = sender as XElement;
if (e != null && value.element == e.parent && value.name != null && (value.name == e.Name || value.name == (changeState as XName))) {
changeState = null;
OnValueChanged(value.element, EventArgs.Empty);
}
break;
}
}
protected override void OnChanging(object sender, XObjectChangeEventArgs args) {
if (value == null) return;
switch (args.ObjectChange) {
case XObjectChange.Remove:
XElement e = sender as XElement;
changeState = e != null ? e.parent : null;
break;
case XObjectChange.Name:
e = sender as XElement;
changeState = e != null ? e.Name : null;
break;
}
}
}
class XElementValuePropertyDescriptor : XPropertyDescriptor<XElement, string>
{
XElement element;
public XElementValuePropertyDescriptor() : base("Value") {
}
public override bool IsReadOnly {
get { return false; }
}
public override object GetValue(object component) {
element = component as XElement;
if (element == null) return string.Empty;
return element.Value;
}
public override void SetValue(object component, object value) {
element = component as XElement;
if (element == null) return;
element.Value = value as string;
}
protected override void OnChanged(object sender, XObjectChangeEventArgs args) {
if (element == null) return;
switch (args.ObjectChange) {
case XObjectChange.Add:
case XObjectChange.Remove:
if (sender is XElement || sender is XText) {
OnValueChanged(element, EventArgs.Empty);
}
break;
case XObjectChange.Value:
if (sender is XText) {
OnValueChanged(element, EventArgs.Empty);
}
break;
}
}
}
class XElementXmlPropertyDescriptor : XPropertyDescriptor<XElement, string>
{
XElement element;
public XElementXmlPropertyDescriptor() : base("Xml") {
}
public override object GetValue(object component) {
element = component as XElement;
if (element == null) return string.Empty;
return element.ToString(SaveOptions.DisableFormatting);
}
protected override void OnChanged(object sender, XObjectChangeEventArgs args) {
if (element == null) return;
OnValueChanged(element, EventArgs.Empty);
}
}
class XAttributeValuePropertyDescriptor : XPropertyDescriptor<XAttribute, string>
{
XAttribute attribute;
public XAttributeValuePropertyDescriptor() : base("Value") {
}
public override bool IsReadOnly {
get { return false; }
}
public override object GetValue(object component) {
attribute = component as XAttribute;
if (attribute == null) return string.Empty;
return attribute.Value;
}
public override void SetValue(object component, object value) {
attribute = component as XAttribute;
if (attribute == null) return;
attribute.Value = value as string;
}
protected override void OnChanged(object sender, XObjectChangeEventArgs args) {
if (attribute == null) return;
if (args.ObjectChange == XObjectChange.Value) {
OnValueChanged(attribute, EventArgs.Empty);
}
}
}
class XDeferredAxis<T> : IEnumerable<T>, IEnumerable where T : XObject
{
Func<XElement, XName, IEnumerable<T>> func;
internal XElement element;
internal XName name;
public XDeferredAxis(Func<XElement, XName, IEnumerable<T>> func, XElement element, XName name) {
if (func == null) throw new ArgumentNullException("func");
if (element == null) throw new ArgumentNullException("element");
this.func = func;
this.element = element;
this.name = name;
}
public IEnumerator<T> GetEnumerator() {
return func(element, name).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
public IEnumerable<T> this[string expandedName] {
get {
if (expandedName == null) throw new ArgumentNullException("expandedName");
if (name == null) {
name = expandedName;
}
else if (name != expandedName) {
return Enumerable.Empty<T>();
}
return this;
}
}
}
class XDeferredSingleton<T> where T : XObject
{
Func<XElement, XName, T> func;
internal XElement element;
internal XName name;
public XDeferredSingleton(Func<XElement, XName, T> func, XElement element, XName name) {
if (func == null) throw new ArgumentNullException("func");
if (element == null) throw new ArgumentNullException("element");
this.func = func;
this.element = element;
this.name = name;
}
public T this[string expandedName] {
get {
if (expandedName == null) throw new ArgumentNullException("expandedName");
if (name == null) {
name = expandedName;
}
else if (name != expandedName) {
return null;
}
return func(element, name);
}
}
}
}
| 37.931034 | 153 | 0.546932 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/ndp/fx/src/XLinq/System/Xml/Linq/XComponentModel.cs | 17,600 | C# |
using System.Linq;
using Xunit;
namespace Xamarin.AndroidX.Migration.Tests
{
public class DependenciesTests : BaseTests
{
[Fact]
public void CanLoadJsonFile()
{
var tree = PackageDependencyTree.Load();
Assert.NotEmpty(tree.Packages);
Assert.NotNull(tree.Packages.FirstOrDefault(p => p.Id == "Xamarin.Google.Android.Material"));
var material = tree.GetOrCreate("Xamarin.Google.Android.Material");
Assert.Contains("Xamarin.AndroidX.AppCompat", material.Dependencies);
}
[Fact]
public void CanFlattenDependencies()
{
var tree = PackageDependencyTree.Load();
var flattened = tree.Flatten("Xamarin.AndroidX.Palette").ToArray();
Assert.Contains("Xamarin.AndroidX.Annotation", flattened);
Assert.Contains("Xamarin.AndroidX.MultiDex", flattened);
Assert.Equal(flattened, flattened.Distinct().ToArray());
}
[Fact]
public void FlattensNoDependenciesCorrectly()
{
var tree = PackageDependencyTree.Load();
var ids = new[]
{
"Xamarin.AndroidX.Annotation",
};
var expected = new[]
{
"Xamarin.AndroidX.Annotation",
"Xamarin.AndroidX.Migration",
"Xamarin.AndroidX.MultiDex",
};
var flattened = tree.Flatten(ids);
Assert.Equal(expected, flattened);
}
[Fact]
public void FlattensSingleDependencyCorrectly()
{
var tree = PackageDependencyTree.Load();
var ids = new[]
{
"Xamarin.AndroidX.Collection",
};
var expected = new[]
{
"Xamarin.AndroidX.Collection",
"Xamarin.AndroidX.Annotation",
"Xamarin.AndroidX.Migration",
"Xamarin.AndroidX.MultiDex",
};
var flattened = tree.Flatten(ids);
Assert.Equal(expected, flattened);
}
[Fact]
public void FlattensSharedDependencyCorrectly()
{
var tree = PackageDependencyTree.Load();
var ids = new[]
{
"Xamarin.AndroidX.Collection",
"Xamarin.AndroidX.CursorAdapter",
};
var expected = new[]
{
"Xamarin.AndroidX.Collection",
"Xamarin.AndroidX.CursorAdapter",
"Xamarin.AndroidX.Annotation",
"Xamarin.AndroidX.Migration",
"Xamarin.AndroidX.MultiDex",
};
var flattened = tree.Flatten(ids);
Assert.Equal(expected, flattened);
}
[Fact]
public void FlattensTripleDependencyCorrectly()
{
var tree = PackageDependencyTree.Load();
var ids = new[]
{
"Xamarin.AndroidX.VersionedParcelable",
};
var expected = new[]
{
"Xamarin.AndroidX.VersionedParcelable",
"Xamarin.AndroidX.Annotation",
"Xamarin.AndroidX.Collection",
"Xamarin.AndroidX.Migration",
"Xamarin.AndroidX.MultiDex",
};
var flattened = tree.Flatten(ids);
Assert.Equal(expected, flattened);
}
[Fact]
public void FlattensNoDependenciesCorrectlyWhenExcludingTopLevel()
{
var tree = PackageDependencyTree.Load();
var ids = new[]
{
"Xamarin.AndroidX.Annotation",
};
var expected = new[]
{
"Xamarin.AndroidX.Migration",
"Xamarin.AndroidX.MultiDex",
};
var flattened = tree.Flatten(ids, false);
Assert.Equal(expected, flattened);
}
[Fact]
public void FlattensSingleDependencyCorrectlyWhenExcludingTopLevel()
{
var tree = PackageDependencyTree.Load();
var ids = new[]
{
"Xamarin.AndroidX.Collection",
};
var expected = new[]
{
"Xamarin.AndroidX.Annotation",
"Xamarin.AndroidX.Migration",
"Xamarin.AndroidX.MultiDex",
};
var flattened = tree.Flatten(ids, false);
Assert.Equal(expected, flattened);
}
[Fact]
public void FlattensSharedDependencyCorrectlyWhenExcludingTopLevel()
{
var tree = PackageDependencyTree.Load();
var ids = new[]
{
"Xamarin.AndroidX.Collection",
"Xamarin.AndroidX.CursorAdapter",
};
var expected = new[]
{
"Xamarin.AndroidX.Annotation",
"Xamarin.AndroidX.Migration",
"Xamarin.AndroidX.MultiDex",
};
var flattened = tree.Flatten(ids, false);
Assert.Equal(expected, flattened);
}
[Fact]
public void CanReduceNoDependencyCorrectly()
{
var ids = new[]
{
"Xamarin.AndroidX.Annotation",
};
var expected = new[]
{
"Xamarin.AndroidX.Annotation",
};
var tree = PackageDependencyTree.Load();
var actual = tree.Reduce(ids);
Assert.Equal(expected, actual);
}
[Fact]
public void CanReduceSingleDependencyCorrectly()
{
var ids = new[]
{
"Xamarin.AndroidX.Annotation",
"Xamarin.AndroidX.Collection",
"Xamarin.AndroidX.CursorAdapter",
};
var expected = new[]
{
"Xamarin.AndroidX.Collection",
"Xamarin.AndroidX.CursorAdapter",
};
var tree = PackageDependencyTree.Load();
var actual = tree.Reduce(ids);
Assert.Equal(expected, actual);
}
[Fact]
public void FlattenThenReduceEndsUpInTheSamePlace()
{
var tree = PackageDependencyTree.Load();
var ids = new[] { "Xamarin.AndroidX.AppCompat" };
var flattened = tree.Flatten(ids);
Assert.NotEmpty(flattened);
Assert.NotEqual(ids, flattened);
var actual = tree.Reduce(flattened);
Assert.Equal(ids, actual);
}
[Fact]
public void XamarinFormsTopLevelPackagesExpandToAll()
{
var ids = new[]
{
"Xamarin.AndroidX.AppCompat",
"Xamarin.AndroidX.Browser",
"Xamarin.AndroidX.CardView",
"Xamarin.AndroidX.Legacy.Support.Core.Utils",
"Xamarin.AndroidX.Legacy.Support.V4",
"Xamarin.Google.Android.Material",
};
var expected = new[]
{
"Xamarin.AndroidX.Activity",
"Xamarin.AndroidX.Annotation",
"Xamarin.AndroidX.Annotation.Experimental",
"Xamarin.AndroidX.AppCompat",
"Xamarin.AndroidX.AppCompat.AppCompatResources",
"Xamarin.AndroidX.Arch.Core.Common",
"Xamarin.AndroidX.Arch.Core.Runtime",
"Xamarin.AndroidX.AsyncLayoutInflater",
"Xamarin.AndroidX.Browser",
"Xamarin.AndroidX.CardView",
"Xamarin.AndroidX.Collection",
"Xamarin.AndroidX.Concurrent.Futures",
"Xamarin.AndroidX.ConstraintLayout",
"Xamarin.AndroidX.ConstraintLayout.Core",
"Xamarin.AndroidX.CoordinatorLayout",
"Xamarin.AndroidX.Core",
"Xamarin.AndroidX.CursorAdapter",
"Xamarin.AndroidX.CustomView",
"Xamarin.AndroidX.DocumentFile",
"Xamarin.AndroidX.DrawerLayout",
"Xamarin.AndroidX.DynamicAnimation",
"Xamarin.AndroidX.Fragment",
"Xamarin.AndroidX.Interpolator",
"Xamarin.AndroidX.Legacy.Support.Core.UI",
"Xamarin.AndroidX.Legacy.Support.Core.Utils",
"Xamarin.AndroidX.Legacy.Support.V4",
"Xamarin.AndroidX.Lifecycle.Common",
"Xamarin.AndroidX.Lifecycle.LiveData.Core",
"Xamarin.AndroidX.Lifecycle.Runtime",
"Xamarin.AndroidX.Lifecycle.ViewModel",
"Xamarin.AndroidX.Lifecycle.ViewModelSavedState",
"Xamarin.AndroidX.Loader",
"Xamarin.AndroidX.LocalBroadcastManager",
"Xamarin.AndroidX.Media",
"Xamarin.AndroidX.Migration",
"Xamarin.AndroidX.MultiDex",
"Xamarin.AndroidX.Print",
"Xamarin.AndroidX.RecyclerView",
"Xamarin.AndroidX.SavedState",
"Xamarin.AndroidX.SlidingPaneLayout",
"Xamarin.AndroidX.SwipeRefreshLayout",
"Xamarin.AndroidX.Tracing.Tracing",
"Xamarin.AndroidX.Transition",
"Xamarin.AndroidX.VectorDrawable",
"Xamarin.AndroidX.VectorDrawable.Animated",
"Xamarin.AndroidX.VersionedParcelable",
"Xamarin.AndroidX.ViewPager",
"Xamarin.AndroidX.ViewPager2",
"Xamarin.Google.Android.Material",
"Xamarin.Google.Guava.ListenableFuture",
"Xamarin.Jetbrains.Annotations",
"Xamarin.Kotlin.StdLib",
"Xamarin.Kotlin.StdLib.Common",
};
var tree = PackageDependencyTree.Load();
var flattened = tree.Flatten(ids).ToList();
flattened.Sort();
Assert.Equal(expected, flattened.ToArray());
}
[Fact]
public void XamarinFormsTotalDependencyIsReduced()
{
var ids = new[]
{
"Xamarin.AndroidX.Arch.Core.Common",
"Xamarin.AndroidX.Arch.Core.Runtime",
"Xamarin.AndroidX.Lifecycle.Common",
"Xamarin.AndroidX.Lifecycle.LiveData.Core",
"Xamarin.AndroidX.Lifecycle.LiveData",
"Xamarin.AndroidX.Lifecycle.Runtime",
"Xamarin.AndroidX.Lifecycle.ViewModel",
"Xamarin.AndroidX.VectorDrawable.Animated",
"Xamarin.AndroidX.Annotation",
"Xamarin.AndroidX.AsyncLayoutInflater",
"Xamarin.AndroidX.Collection",
"Xamarin.AndroidX.Core",
"Xamarin.AndroidX.CoordinatorLayout",
"Xamarin.AndroidX.Legacy.Support.Core.UI",
"Xamarin.AndroidX.Legacy.Support.Core.Utils",
"Xamarin.AndroidX.CursorAdapter",
"Xamarin.AndroidX.Browser",
"Xamarin.AndroidX.CustomView",
"Xamarin.Google.Android.Material",
"Xamarin.AndroidX.DocumentFile",
"Xamarin.AndroidX.DrawerLayout",
"Xamarin.AndroidX.Fragment",
"Xamarin.AndroidX.Interpolator",
"Xamarin.AndroidX.Loader",
"Xamarin.AndroidX.LocalBroadcastManager",
"Xamarin.AndroidX.Media",
"Xamarin.AndroidX.Print",
"Xamarin.AndroidX.SlidingPaneLayout",
"Xamarin.AndroidX.SwipeRefreshLayout",
"Xamarin.AndroidX.Transition",
"Xamarin.AndroidX.Legacy.Support.V4",
"Xamarin.AndroidX.AppCompat",
"Xamarin.AndroidX.CardView",
"Xamarin.AndroidX.MediaRouter",
"Xamarin.AndroidX.Palette",
"Xamarin.AndroidX.RecyclerView",
"Xamarin.AndroidX.VectorDrawable",
"Xamarin.AndroidX.VersionedParcelable",
"Xamarin.AndroidX.ViewPager",
};
var expected = new[]
{
"Xamarin.AndroidX.Browser",
"Xamarin.AndroidX.Legacy.Support.V4",
"Xamarin.AndroidX.Lifecycle.LiveData",
"Xamarin.AndroidX.MediaRouter",
"Xamarin.Google.Android.Material",
};
var tree = PackageDependencyTree.Load();
var flattened = tree.Reduce(ids).ToList();
flattened.Sort();
Assert.Equal(expected, flattened.ToArray());
}
}
}
| 24.529262 | 96 | 0.690768 | [
"MIT"
] | 4brunu/XamarinAndroidX | tests/AndroidXMigrationTests/Tests/DependenciesTests.cs | 9,642 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AecCloud.Core.Domain.Projects
{
public class ProjectInvitation : Entity
{
/// <summary>
/// 项目ID
/// </summary>
public long ProjectId { get; set; }
/// <summary>
/// 发起邀请的用户ID
/// </summary>
public long InviterId { get; set; }
/// <summary>
/// 邀请为的参与方
/// </summary>
public long InviteePartId { get; set; }
/// <summary>
/// 接受邀请后的用户ID
/// </summary>
public long InviteeId { get; set; }
/// <summary>
/// 受邀请人的邮箱
/// </summary>
public string InviteeEmail { get; set; }
/// <summary>
/// 邀请时提供的信息
/// </summary>
public string InvitationMessage { get; set; }
/// <summary>
/// 被邀请人确认接受邀请的回复
/// </summary>
public string InviteeConfirmMessage { get; set; }
/// <summary>
/// 是否由项目内人员确认加入项目
/// </summary>
public bool Accepted { get; set; }
/// <summary>
/// 若没有参与方,则需要知道最后的确认人是谁
/// </summary>
public long AcceptedBy { get; set; }
public long BidProjectId { get; set; }
}
}
| 25.666667 | 57 | 0.509549 | [
"MIT"
] | FinchYang/test | AecPrivateCloud.ALL/Core/AecCloud.Core/Domain/Projects/ProjectInvitation.cs | 1,483 | C# |
using CommunicationProtocol.Serialization;
using System;
using System.Collections.Generic;
namespace CommunicationProtocol.Factories
{
public class SerializerFactory : Factory
{
private static SerializerFactory _instance;
public static SerializerFactory GetFactory()
{
if (_instance == null)
_instance = new SerializerFactory();
return _instance;
}
protected override void InitialiseListID()
{
dTypes = new List<Type>();
dTypes.Add(typeof(Tank));
dTypes.Add(typeof(Bullet));
dTypes.Add(typeof(Loot));
}
public new T CreateInstance<T>(int pID) where T : IBinarySerializable
{
return base.CreateInstance<T>(pID);
}
public new int GetID<T>(T pType) where T : IBinarySerializable
{
return base.GetID(pType);
}
}
}
| 25.513514 | 77 | 0.588983 | [
"Apache-2.0"
] | Nono02P/Communication-Protocol | CommunicationProtocol/Factories/SerializerFactory.cs | 946 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v7/resources/customer_extension_setting.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Ads.GoogleAds.V7.Resources {
/// <summary>Holder for reflection information generated from google/ads/googleads/v7/resources/customer_extension_setting.proto</summary>
public static partial class CustomerExtensionSettingReflection {
#region Descriptor
/// <summary>File descriptor for google/ads/googleads/v7/resources/customer_extension_setting.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static CustomerExtensionSettingReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CkJnb29nbGUvYWRzL2dvb2dsZWFkcy92Ny9yZXNvdXJjZXMvY3VzdG9tZXJf",
"ZXh0ZW5zaW9uX3NldHRpbmcucHJvdG8SIWdvb2dsZS5hZHMuZ29vZ2xlYWRz",
"LnY3LnJlc291cmNlcxo8Z29vZ2xlL2Fkcy9nb29nbGVhZHMvdjcvZW51bXMv",
"ZXh0ZW5zaW9uX3NldHRpbmdfZGV2aWNlLnByb3RvGjJnb29nbGUvYWRzL2dv",
"b2dsZWFkcy92Ny9lbnVtcy9leHRlbnNpb25fdHlwZS5wcm90bxofZ29vZ2xl",
"L2FwaS9maWVsZF9iZWhhdmlvci5wcm90bxoZZ29vZ2xlL2FwaS9yZXNvdXJj",
"ZS5wcm90bxocZ29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5wcm90byL2AwoYQ3Vz",
"dG9tZXJFeHRlbnNpb25TZXR0aW5nElAKDXJlc291cmNlX25hbWUYASABKAlC",
"OeBBBfpBMwoxZ29vZ2xlYWRzLmdvb2dsZWFwaXMuY29tL0N1c3RvbWVyRXh0",
"ZW5zaW9uU2V0dGluZxJbCg5leHRlbnNpb25fdHlwZRgCIAEoDjI+Lmdvb2ds",
"ZS5hZHMuZ29vZ2xlYWRzLnY3LmVudW1zLkV4dGVuc2lvblR5cGVFbnVtLkV4",
"dGVuc2lvblR5cGVCA+BBBRJNChRleHRlbnNpb25fZmVlZF9pdGVtcxgFIAMo",
"CUIv+kEsCipnb29nbGVhZHMuZ29vZ2xlYXBpcy5jb20vRXh0ZW5zaW9uRmVl",
"ZEl0ZW0SYAoGZGV2aWNlGAQgASgOMlAuZ29vZ2xlLmFkcy5nb29nbGVhZHMu",
"djcuZW51bXMuRXh0ZW5zaW9uU2V0dGluZ0RldmljZUVudW0uRXh0ZW5zaW9u",
"U2V0dGluZ0RldmljZTp66kF3CjFnb29nbGVhZHMuZ29vZ2xlYXBpcy5jb20v",
"Q3VzdG9tZXJFeHRlbnNpb25TZXR0aW5nEkJjdXN0b21lcnMve2N1c3RvbWVy",
"X2lkfS9jdXN0b21lckV4dGVuc2lvblNldHRpbmdzL3tleHRlbnNpb25fdHlw",
"ZX1CigIKJWNvbS5nb29nbGUuYWRzLmdvb2dsZWFkcy52Ny5yZXNvdXJjZXNC",
"HUN1c3RvbWVyRXh0ZW5zaW9uU2V0dGluZ1Byb3RvUAFaSmdvb2dsZS5nb2xh",
"bmcub3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvYWRzL2dvb2dsZWFkcy92Ny9y",
"ZXNvdXJjZXM7cmVzb3VyY2VzogIDR0FBqgIhR29vZ2xlLkFkcy5Hb29nbGVB",
"ZHMuVjcuUmVzb3VyY2VzygIhR29vZ2xlXEFkc1xHb29nbGVBZHNcVjdcUmVz",
"b3VyY2Vz6gIlR29vZ2xlOjpBZHM6Okdvb2dsZUFkczo6Vjc6OlJlc291cmNl",
"c2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Ads.GoogleAds.V7.Enums.ExtensionSettingDeviceReflection.Descriptor, global::Google.Ads.GoogleAds.V7.Enums.ExtensionTypeReflection.Descriptor, global::Google.Api.FieldBehaviorReflection.Descriptor, global::Google.Api.ResourceReflection.Descriptor, global::Google.Api.AnnotationsReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V7.Resources.CustomerExtensionSetting), global::Google.Ads.GoogleAds.V7.Resources.CustomerExtensionSetting.Parser, new[]{ "ResourceName", "ExtensionType", "ExtensionFeedItems", "Device" }, null, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// A customer extension setting.
/// </summary>
public sealed partial class CustomerExtensionSetting : pb::IMessage<CustomerExtensionSetting>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<CustomerExtensionSetting> _parser = new pb::MessageParser<CustomerExtensionSetting>(() => new CustomerExtensionSetting());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<CustomerExtensionSetting> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Ads.GoogleAds.V7.Resources.CustomerExtensionSettingReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CustomerExtensionSetting() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CustomerExtensionSetting(CustomerExtensionSetting other) : this() {
resourceName_ = other.resourceName_;
extensionType_ = other.extensionType_;
extensionFeedItems_ = other.extensionFeedItems_.Clone();
device_ = other.device_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CustomerExtensionSetting Clone() {
return new CustomerExtensionSetting(this);
}
/// <summary>Field number for the "resource_name" field.</summary>
public const int ResourceNameFieldNumber = 1;
private string resourceName_ = "";
/// <summary>
/// Immutable. The resource name of the customer extension setting.
/// CustomerExtensionSetting resource names have the form:
///
/// `customers/{customer_id}/customerExtensionSettings/{extension_type}`
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ResourceName {
get { return resourceName_; }
set {
resourceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "extension_type" field.</summary>
public const int ExtensionTypeFieldNumber = 2;
private global::Google.Ads.GoogleAds.V7.Enums.ExtensionTypeEnum.Types.ExtensionType extensionType_ = global::Google.Ads.GoogleAds.V7.Enums.ExtensionTypeEnum.Types.ExtensionType.Unspecified;
/// <summary>
/// Immutable. The extension type of the customer extension setting.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Ads.GoogleAds.V7.Enums.ExtensionTypeEnum.Types.ExtensionType ExtensionType {
get { return extensionType_; }
set {
extensionType_ = value;
}
}
/// <summary>Field number for the "extension_feed_items" field.</summary>
public const int ExtensionFeedItemsFieldNumber = 5;
private static readonly pb::FieldCodec<string> _repeated_extensionFeedItems_codec
= pb::FieldCodec.ForString(42);
private readonly pbc::RepeatedField<string> extensionFeedItems_ = new pbc::RepeatedField<string>();
/// <summary>
/// The resource names of the extension feed items to serve under the customer.
/// ExtensionFeedItem resource names have the form:
///
/// `customers/{customer_id}/extensionFeedItems/{feed_item_id}`
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<string> ExtensionFeedItems {
get { return extensionFeedItems_; }
}
/// <summary>Field number for the "device" field.</summary>
public const int DeviceFieldNumber = 4;
private global::Google.Ads.GoogleAds.V7.Enums.ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice device_ = global::Google.Ads.GoogleAds.V7.Enums.ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unspecified;
/// <summary>
/// The device for which the extensions will serve. Optional.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Ads.GoogleAds.V7.Enums.ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice Device {
get { return device_; }
set {
device_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as CustomerExtensionSetting);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(CustomerExtensionSetting other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ResourceName != other.ResourceName) return false;
if (ExtensionType != other.ExtensionType) return false;
if(!extensionFeedItems_.Equals(other.extensionFeedItems_)) return false;
if (Device != other.Device) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ResourceName.Length != 0) hash ^= ResourceName.GetHashCode();
if (ExtensionType != global::Google.Ads.GoogleAds.V7.Enums.ExtensionTypeEnum.Types.ExtensionType.Unspecified) hash ^= ExtensionType.GetHashCode();
hash ^= extensionFeedItems_.GetHashCode();
if (Device != global::Google.Ads.GoogleAds.V7.Enums.ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unspecified) hash ^= Device.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (ResourceName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ResourceName);
}
if (ExtensionType != global::Google.Ads.GoogleAds.V7.Enums.ExtensionTypeEnum.Types.ExtensionType.Unspecified) {
output.WriteRawTag(16);
output.WriteEnum((int) ExtensionType);
}
if (Device != global::Google.Ads.GoogleAds.V7.Enums.ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unspecified) {
output.WriteRawTag(32);
output.WriteEnum((int) Device);
}
extensionFeedItems_.WriteTo(output, _repeated_extensionFeedItems_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (ResourceName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ResourceName);
}
if (ExtensionType != global::Google.Ads.GoogleAds.V7.Enums.ExtensionTypeEnum.Types.ExtensionType.Unspecified) {
output.WriteRawTag(16);
output.WriteEnum((int) ExtensionType);
}
if (Device != global::Google.Ads.GoogleAds.V7.Enums.ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unspecified) {
output.WriteRawTag(32);
output.WriteEnum((int) Device);
}
extensionFeedItems_.WriteTo(ref output, _repeated_extensionFeedItems_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ResourceName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ResourceName);
}
if (ExtensionType != global::Google.Ads.GoogleAds.V7.Enums.ExtensionTypeEnum.Types.ExtensionType.Unspecified) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ExtensionType);
}
size += extensionFeedItems_.CalculateSize(_repeated_extensionFeedItems_codec);
if (Device != global::Google.Ads.GoogleAds.V7.Enums.ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unspecified) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Device);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(CustomerExtensionSetting other) {
if (other == null) {
return;
}
if (other.ResourceName.Length != 0) {
ResourceName = other.ResourceName;
}
if (other.ExtensionType != global::Google.Ads.GoogleAds.V7.Enums.ExtensionTypeEnum.Types.ExtensionType.Unspecified) {
ExtensionType = other.ExtensionType;
}
extensionFeedItems_.Add(other.extensionFeedItems_);
if (other.Device != global::Google.Ads.GoogleAds.V7.Enums.ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unspecified) {
Device = other.Device;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
ResourceName = input.ReadString();
break;
}
case 16: {
ExtensionType = (global::Google.Ads.GoogleAds.V7.Enums.ExtensionTypeEnum.Types.ExtensionType) input.ReadEnum();
break;
}
case 32: {
Device = (global::Google.Ads.GoogleAds.V7.Enums.ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice) input.ReadEnum();
break;
}
case 42: {
extensionFeedItems_.AddEntriesFrom(input, _repeated_extensionFeedItems_codec);
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
ResourceName = input.ReadString();
break;
}
case 16: {
ExtensionType = (global::Google.Ads.GoogleAds.V7.Enums.ExtensionTypeEnum.Types.ExtensionType) input.ReadEnum();
break;
}
case 32: {
Device = (global::Google.Ads.GoogleAds.V7.Enums.ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice) input.ReadEnum();
break;
}
case 42: {
extensionFeedItems_.AddEntriesFrom(ref input, _repeated_extensionFeedItems_codec);
break;
}
}
}
}
#endif
}
#endregion
}
#endregion Designer generated code
| 43.896359 | 355 | 0.709655 | [
"Apache-2.0"
] | deni-skaraudio/google-ads-dotnet | src/V7/Types/CustomerExtensionSetting.cs | 15,671 | C# |
namespace $rootnamespace$
{
public class $safeitemrootname$
{
public $fileinputname$ Model { get; }
public $fileinputname$ViewModel ViewModel { get; }
public $fileinputname$View View { get; }
public $safeitemrootname$($fileinputname$ model, $fileinputname$ViewModel viewModel, $fileinputname$View view)
{
Model = model;
ViewModel = viewModel;
View = view;
}
}
}
| 27.176471 | 118 | 0.593074 | [
"MIT"
] | IObsequious/Missing-Templates | src/ItemTemplates/Common/WPFInfrastructure/Infrastructure.cs | 464 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using IcgSoftware.Threema.CoreMsgApi.Results;
namespace IcgSoftware.Threema.CoreMsgApi.Com
{
[ComVisible(true)]
[Guid("4F376DEB-6F78-460A-836F-B38371712EFF")]
public interface ICryptToolWrapper
{
ArrayList EncryptTextMessage(string text, string senderPrivateKey, string recipientPublicKey);
ArrayList DecryptMessage(string box, string recipientPrivateKey, string senderPublicKey, string nonce);
string HashEmail(string email);
string HashPhoneNo(string phoneNo);
void GenerateKeyPair(string privateKeyPath, string publicKeyPath);
string DerivePublicKey(string privateKey);
}
}
| 32.333333 | 105 | 0.818299 | [
"MIT"
] | pt-icg/Threema-MsgApi-Net-Core | IcgSoftware.Threema.CoreMsgApi/Com/ICryptToolWrapper.cs | 778 | C# |
//
// System.DrawingCore.Drawing2D.PenAlignment.cs
//
// Author:
// Miguel de Icaza (miguel@ximian.com)
// Dennis Hayes (dennish@Raytek.com)
//
// (C) 2002/3 Ximian, Inc http://www.ximian.com
// Copyright (C) 2004,2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace System.DrawingCore.Drawing2D {
public enum PenAlignment {
Center = 0,
Inset = 1,
Outset = 2,
Left = 3,
Right =4
}
}
| 36.170732 | 73 | 0.734322 | [
"Apache-2.0"
] | JuanSGA24/Alejandria | source/Samples/deprecated/MyThaiStar/reporting/ZKWeb.System.Drawing/System.Drawing.Drawing2D/PenAlignment.cs | 1,483 | 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 GiauTM.CSharp.TikiRouter.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;
}
}
}
}
| 39.962963 | 151 | 0.584801 | [
"MIT"
] | giautm/dispatch-tool | Router/Properties/Settings.Designer.cs | 1,081 | C# |
namespace NextGenSoftware.OASIS.API.Core.Interfaces.STAR
{
public interface IPortalCore : ICelestialBodyCore
{
}
} | 16.125 | 56 | 0.728682 | [
"CC0-1.0"
] | NextGenSoftwareUK/Our-World-OASIS-API-HoloNET-HoloUnity-And-.NET-HDK | NextGenSoftware.OASIS.API.Core/Interfaces/STAR/CelestialBodies/IPortalCore.cs | 131 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Cwp.V20180228.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeBaselineBasicInfoResponse : AbstractModel
{
/// <summary>
/// 基线基础信息列表
/// 注意:此字段可能返回 null,表示取不到有效值。
/// </summary>
[JsonProperty("BaselineBasicInfoList")]
public BaselineBasicInfo[] BaselineBasicInfoList{ get; set; }
/// <summary>
/// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamArrayObj(map, prefix + "BaselineBasicInfoList.", this.BaselineBasicInfoList);
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 32.057692 | 102 | 0.656869 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Cwp/V20180228/Models/DescribeBaselineBasicInfoResponse.cs | 1,781 | C# |
using System;
using System.Collections.Generic;
namespace it
{
public readonly struct Question
{
public readonly string Text { get; }
public readonly string Answer { get; }
internal Question(string text, string answer)
=> (Text, Answer) = (text, answer);
}
} | 23 | 54 | 0.599379 | [
"MIT"
] | ellmaster/C-sharp-clipboardquestionanswer- | Question.cs | 324 | C# |
using System;
using System.Linq;
using UnityEngine.TestTools;
using UnityEngine.TestTools.TestRunner;
namespace UnityEditor.TestTools.TestRunner.Api
{
internal class TestLauncherFactory : ITestLauncherFactory
{
public TestLauncherBase GetLauncher(ExecutionSettings executionSettings)
{
var filters = GetFilters(executionSettings);
if (filters[0].testMode == TestMode.EditMode || filters[0].testMode == 0)
{
return GetEditModeLauncher(GetFilters(executionSettings), executionSettings.runSynchronously);
}
else
{
if (executionSettings.runSynchronously)
throw new NotSupportedException("Playmode tests cannot be run synchronously.");
var settings = PlaymodeTestsControllerSettings.CreateRunnerSettings(filters.Select(filter => filter.ToTestRunnerFilter()).ToArray());
return GetPlayModeLauncher(settings, executionSettings);
}
}
static Filter[] GetFilters(ExecutionSettings executionSettings)
{
if (executionSettings.filters != null && executionSettings.filters.Length > 0)
{
return executionSettings.filters;
}
return new[] {executionSettings.filter ?? new Filter()};
}
static TestLauncherBase GetEditModeLauncher(Filter[] filters, bool runSynchronously)
{
return GetEditModeLauncherForProvidedAssemblies(filters, TestPlatform.EditMode, runSynchronously);
}
static TestLauncherBase GetPlayModeLauncher(PlaymodeTestsControllerSettings settings, ExecutionSettings executionSettings)
{
if (executionSettings.targetPlatform != null)
{
return GetPlayerLauncher(settings, executionSettings);
}
if (PlayerSettings.runPlayModeTestAsEditModeTest)
{
return GetEditModeLauncherForProvidedAssemblies(executionSettings.filters, TestPlatform.PlayMode, false);
}
return GetPlayModeLauncher(settings);
}
static TestLauncherBase GetEditModeLauncherForProvidedAssemblies(Filter[] filters, TestPlatform testPlatform, bool runSynchronously)
{
return new EditModeLauncher(filters, testPlatform, runSynchronously);
}
static TestLauncherBase GetPlayModeLauncher(PlaymodeTestsControllerSettings settings)
{
return new PlaymodeLauncher(settings);
}
static TestLauncherBase GetPlayerLauncher(PlaymodeTestsControllerSettings settings, ExecutionSettings executionSettings)
{
return new PlayerLauncher(
settings,
executionSettings.targetPlatform.Value,
executionSettings.overloadTestRunSettings);
}
}
}
| 39.447368 | 150 | 0.640761 | [
"MIT"
] | FernandaDev/GlitchGarden | Glitch Garden/Library/PackageCache/com.unity.test-framework@1.1.3/UnityEditor.TestRunner/Api/TestLauncherFactory.cs | 2,998 | C# |
using System;
namespace AMS.API.Areas.HelpPage
{
/// <summary>
/// This represents an invalid sample on the help page. There's a display template named InvalidSample associated with this class.
/// </summary>
public class InvalidSample
{
public InvalidSample(string errorMessage)
{
if (errorMessage == null)
{
throw new ArgumentNullException("errorMessage");
}
ErrorMessage = errorMessage;
}
public string ErrorMessage { get; private set; }
public override bool Equals(object obj)
{
InvalidSample other = obj as InvalidSample;
return other != null && ErrorMessage == other.ErrorMessage;
}
public override int GetHashCode()
{
return ErrorMessage.GetHashCode();
}
public override string ToString()
{
return ErrorMessage;
}
}
} | 26.189189 | 134 | 0.572755 | [
"MIT"
] | vasylenkoArtem/AccountManagementSystem | Services/Application/AMS.API/Areas/HelpPage/SampleGeneration/InvalidSample.cs | 969 | C# |
namespace FairMark.DataContracts
{
using System;
/// <summary>
/// Custom <see cref="System.DateTime"/> wrapper class to work around serialization issues.
/// Some API methods assume that date+time fields look like this: "2018-12-12T00:00:00Z".
/// While some others assume that date+time fields look like this: "2018-12-12 00:00:00"
/// </summary>
public class CustomDateTimeSpace
{
/// <summary>
/// Real DateTime value.
/// </summary>
public DateTime? DateTime { get; set; }
/// <inheritdoc/>
public override string ToString() => // 2020-04-24 21:01:40
DateTime.HasValue ? DateTime.Value.ToString("s").Replace("T", " ") : null;
/// <summary>
/// Parses the given string.
/// </summary>
/// <param name="s">String to parse.</param>
/// <returns><see cref="CustomDateTimeSpace"/> instance.</returns>
public static CustomDateTimeSpace Parse(string s)
{
if (string.IsNullOrWhiteSpace(s) || "null".Equals(s, StringComparison.OrdinalIgnoreCase))
{
return new CustomDateTimeSpace();
}
return new CustomDateTimeSpace
{
DateTime = System.DateTime.ParseExact(s.Replace(" ", "T").TrimEnd('z', 'Z'), "s", null)
};
}
/// <summary>
/// Implicit conversion to the <see cref="DateTime"/> type.
/// </summary>
/// <param name="cd"><see cref="CustomDateTimeSpace"/> instance.</param>
public static implicit operator DateTime(CustomDateTimeSpace cd) =>
cd.DateTime ?? default(DateTime);
/// <summary>
/// Implicit conversion to the <see cref="Nullable{DateTime}"/> type.
/// </summary>
/// <param name="cd"><see cref="CustomDateTimeSpace"/> instance.</param>
public static implicit operator DateTime?(CustomDateTimeSpace cd) =>
cd.DateTime;
/// <summary>
/// Implicit conversion to the <see cref="string"/> type.
/// </summary>
/// <param name="cd"><see cref="CustomDateTimeSpace"/> instance.</param>
public static implicit operator string(CustomDateTimeSpace cd) =>
cd == null ? null : cd.ToString();
/// <summary>
/// Implicit conversion from the <see cref="Nullable{DateTime}"/> type.
/// </summary>
/// <param name="dt"><see cref="CustomDateTimeSpace"/> instance.</param>
public static implicit operator CustomDateTimeSpace(DateTime? dt) =>
new CustomDateTimeSpace { DateTime = dt };
/// <summary>
/// Implicit conversion from the <see cref="DateTime"/> type.
/// </summary>
/// <param name="dt"><see cref="CustomDateTimeSpace"/> instance.</param>
public static implicit operator CustomDateTimeSpace(DateTime dt) =>
new CustomDateTimeSpace { DateTime = dt };
}
}
| 39.8 | 103 | 0.580235 | [
"MIT"
] | FairMark/FairMarkClient | FairMark/DataContracts/CustomDateTimeSpace.cs | 2,987 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using ClientDependency.Core.Config;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.IO;
using Umbraco.Web.Controllers;
using Umbraco.Web.Features;
using Umbraco.Web.HealthCheck;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.Mvc;
using Umbraco.Web.PropertyEditors;
using Umbraco.Web.Trees;
using Constants = Umbraco.Core.Constants;
namespace Umbraco.Web.Editors
{
/// <summary>
/// Used to collect the server variables for use in the back office angular app
/// </summary>
internal class BackOfficeServerVariables
{
private readonly UrlHelper _urlHelper;
private readonly IRuntimeState _runtimeState;
private readonly UmbracoFeatures _features;
private readonly IGlobalSettings _globalSettings;
private readonly HttpContextBase _httpContext;
private readonly IOwinContext _owinContext;
internal BackOfficeServerVariables(UrlHelper urlHelper, IRuntimeState runtimeState, UmbracoFeatures features, IGlobalSettings globalSettings)
{
_urlHelper = urlHelper;
_runtimeState = runtimeState;
_features = features;
_globalSettings = globalSettings;
_httpContext = _urlHelper.RequestContext.HttpContext;
_owinContext = _httpContext.GetOwinContext();
}
/// <summary>
/// Returns the server variables for non-authenticated users
/// </summary>
/// <returns></returns>
internal Dictionary<string, object> BareMinimumServerVariables()
{
//this is the filter for the keys that we'll keep based on the full version of the server vars
var keepOnlyKeys = new Dictionary<string, string[]>
{
{"umbracoUrls", new[] {"authenticationApiBaseUrl", "serverVarsJs", "externalLoginsUrl", "currentUserApiBaseUrl"}},
{"umbracoSettings", new[] {"allowPasswordReset", "imageFileTypes", "maxFileSize", "loginBackgroundImage", "canSendRequiredEmail", "usernameIsEmail"}},
{"application", new[] {"applicationPath", "cacheBuster"}},
{"isDebuggingEnabled", new string[] { }},
{"features", new [] {"disabledFeatures"}}
};
//now do the filtering...
var defaults = GetServerVariables();
foreach (var key in defaults.Keys.ToArray())
{
if (keepOnlyKeys.ContainsKey(key) == false)
{
defaults.Remove(key);
}
else
{
var asDictionary = defaults[key] as IDictionary;
if (asDictionary != null)
{
var toKeep = keepOnlyKeys[key];
foreach (var k in asDictionary.Keys.Cast<string>().ToArray())
{
if (toKeep.Contains(k) == false)
{
asDictionary.Remove(k);
}
}
}
}
}
// TODO: This is ultra confusing! this same key is used for different things, when returning the full app when authenticated it is this URL but when not auth'd it's actually the ServerVariables address
// so based on compat and how things are currently working we need to replace the serverVarsJs one
((Dictionary<string, object>)defaults["umbracoUrls"])["serverVarsJs"] = _urlHelper.Action("ServerVariables", "BackOffice");
return defaults;
}
/// <summary>
/// Returns the server variables for authenticated users
/// </summary>
/// <returns></returns>
internal Dictionary<string, object> GetServerVariables()
{
var defaultVals = new Dictionary<string, object>
{
{
"umbracoUrls", new Dictionary<string, object>
{
// TODO: Add 'umbracoApiControllerBaseUrl' which people can use in JS
// to prepend their URL. We could then also use this in our own resources instead of
// having each url defined here explicitly - we can do that in v8! for now
// for umbraco services we'll stick to explicitly defining the endpoints.
{"externalLoginsUrl", _urlHelper.Action("ExternalLogin", "BackOffice")},
{"externalLinkLoginsUrl", _urlHelper.Action("LinkLogin", "BackOffice")},
{"manifestAssetList", _urlHelper.Action("GetManifestAssetList", "BackOffice")},
{"gridConfig", _urlHelper.Action("GetGridConfig", "BackOffice")},
// TODO: This is ultra confusing! this same key is used for different things, when returning the full app when authenticated it is this URL but when not auth'd it's actually the ServerVariables address
{"serverVarsJs", _urlHelper.Action("Application", "BackOffice")},
//API URLs
{
"packagesRestApiBaseUrl", Constants.PackageRepository.RestApiBaseUrl
},
{
"redirectUrlManagementApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<RedirectUrlManagementController>(
controller => controller.GetEnableState())
},
{
"tourApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TourController>(
controller => controller.GetTours())
},
{
"embedApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<RteEmbedController>(
controller => controller.GetEmbed("", 0, 0))
},
{
"userApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<UsersController>(
controller => controller.PostSaveUser(null))
},
{
"userGroupsApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<UserGroupsController>(
controller => controller.PostSaveUserGroup(null))
},
{
"contentApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ContentController>(
controller => controller.PostSave(null))
},
{
"mediaApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MediaController>(
controller => controller.GetRootMedia())
},
{
"imagesApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ImagesController>(
controller => controller.GetBigThumbnail(""))
},
{
"sectionApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<SectionController>(
controller => controller.GetSections())
},
{
"treeApplicationApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ApplicationTreeController>(
controller => controller.GetApplicationTrees(null, null, null, TreeUse.None))
},
{
"contentTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ContentTypeController>(
controller => controller.GetAllowedChildren(0))
},
{
"mediaTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MediaTypeController>(
controller => controller.GetAllowedChildren(0))
},
{
"macroRenderingApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MacroRenderingController>(
controller => controller.GetMacroParameters(0))
},
{
"macroApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MacrosController>(
controller => controller.Create(null))
},
{
"authenticationApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<AuthenticationController>(
controller => controller.PostLogin(null))
},
{
"currentUserApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<CurrentUserController>(
controller => controller.PostChangePassword(null))
},
{
"entityApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<EntityController>(
controller => controller.GetById(0, UmbracoEntityTypes.Media))
},
{
"dataTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<DataTypeController>(
controller => controller.GetById(0))
},
{
"dashboardApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<DashboardController>(
controller => controller.GetDashboard(null))
},
{
"logApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<LogController>(
controller => controller.GetPagedEntityLog(0, 0, 0, Core.Persistence.DatabaseModelDefinitions.Direction.Ascending, null))
},
{
"memberApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MemberController>(
controller => controller.GetByKey(Guid.Empty))
},
{
"packageInstallApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<PackageInstallController>(
controller => controller.Fetch(string.Empty))
},
{
"packageApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<PackageController>(
controller => controller.GetCreatedPackages())
},
{
"relationApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<RelationController>(
controller => controller.GetById(0))
},
{
"rteApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<RichTextPreValueController>(
controller => controller.GetConfiguration())
},
{
"stylesheetApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<StylesheetController>(
controller => controller.GetAll())
},
{
"memberTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MemberTypeController>(
controller => controller.GetAllTypes())
},
{
"memberGroupApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MemberGroupController>(
controller => controller.GetAllGroups())
},
{
"updateCheckApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<UpdateCheckController>(
controller => controller.GetCheck())
},
{
"tagApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TagsController>(
controller => controller.GetAllTags(null))
},
{
"templateApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TemplateController>(
controller => controller.GetById(0))
},
{
"memberTreeBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MemberTreeController>(
controller => controller.GetNodes("-1", null))
},
{
"mediaTreeBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MediaTreeController>(
controller => controller.GetNodes("-1", null))
},
{
"contentTreeBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ContentTreeController>(
controller => controller.GetNodes("-1", null))
},
{
"tagsDataBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TagsDataController>(
controller => controller.GetTags("", "", null))
},
{
"examineMgmtBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ExamineManagementController>(
controller => controller.GetIndexerDetails())
},
{
"healthCheckBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<HealthCheckController>(
controller => controller.GetAllHealthChecks())
},
{
"templateQueryApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TemplateQueryController>(
controller => controller.PostTemplateQuery(null))
},
{
"codeFileApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<CodeFileController>(
controller => controller.GetByPath("", ""))
},
{
"publishedStatusBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<PublishedStatusController>(
controller => controller.GetPublishedStatusUrl())
},
{
"dictionaryApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<DictionaryController>(
controller => controller.DeleteById(int.MaxValue))
},
{
"nuCacheStatusBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<NuCacheStatusController>(
controller => controller.GetStatus())
},
{
"helpApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<HelpController>(
controller => controller.GetContextHelpForPage("","",""))
},
{
"backOfficeAssetsApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<BackOfficeAssetsController>(
controller => controller.GetSupportedLocales())
},
{
"languageApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<LanguageController>(
controller => controller.GetAllLanguages())
},
{
"relationTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<RelationTypeController>(
controller => controller.GetById(1))
},
{
"logViewerApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<LogViewerController>(
controller => controller.GetNumberOfErrors(null, null))
}
}
},
{
"umbracoSettings", new Dictionary<string, object>
{
{"umbracoPath", _globalSettings.Path},
{"mediaPath", IOHelper.ResolveUrl(SystemDirectories.Media).TrimEnd('/')},
{"appPluginsPath", IOHelper.ResolveUrl(SystemDirectories.AppPlugins).TrimEnd('/')},
{
"imageFileTypes",
string.Join(",", Current.Configs.Settings().Content.ImageFileTypes)
},
{
"disallowedUploadFiles",
string.Join(",", Current.Configs.Settings().Content.DisallowedUploadFiles)
},
{
"allowedUploadFiles",
string.Join(",", Current.Configs.Settings().Content.AllowedUploadFiles)
},
{
"maxFileSize",
GetMaxRequestLength()
},
{"keepUserLoggedIn", Current.Configs.Settings().Security.KeepUserLoggedIn},
{"usernameIsEmail", Current.Configs.Settings().Security.UsernameIsEmail},
{"cssPath", IOHelper.ResolveUrl(SystemDirectories.Css).TrimEnd('/')},
{"allowPasswordReset", Current.Configs.Settings().Security.AllowPasswordReset},
{"loginBackgroundImage", Current.Configs.Settings().Content.LoginBackgroundImage},
{"showUserInvite", EmailSender.CanSendRequiredEmail},
{"canSendRequiredEmail", EmailSender.CanSendRequiredEmail},
}
},
{
"umbracoPlugins", new Dictionary<string, object>
{
// for each tree that is [PluginController], get
// alias -> areaName
// so that routing (route.js) can look for views
{ "trees", GetPluginTrees().ToArray() }
}
},
{
"isDebuggingEnabled", _httpContext.IsDebuggingEnabled
},
{
"application", GetApplicationState()
},
{
"externalLogins", new Dictionary<string, object>
{
{
"providers", _owinContext.Authentication.GetExternalAuthenticationTypes()
.Where(p => p.Properties.ContainsKey("UmbracoBackOffice"))
.Select(p => new
{
authType = p.AuthenticationType, caption = p.Caption,
// TODO: Need to see if this exposes any sensitive data!
properties = p.Properties
})
.ToArray()
}
}
},
{
"features", new Dictionary<string,object>
{
{
"disabledFeatures", new Dictionary<string,object>
{
{ "disableTemplates", _features.Disabled.DisableTemplates}
}
}
}
}
};
return defaultVals;
}
[DataContract]
private class PluginTree
{
[DataMember(Name = "alias")]
public string Alias { get; set; }
[DataMember(Name = "packageFolder")]
public string PackageFolder { get; set; }
}
private IEnumerable<PluginTree> GetPluginTrees()
{
// used to be (cached)
//var treeTypes = Current.TypeLoader.GetAttributedTreeControllers();
//
// ie inheriting from TreeController and marked with TreeAttribute
//
// do this instead
// inheriting from TreeControllerBase and marked with TreeAttribute
var trees = Current.Factory.GetInstance<TreeCollection>();
foreach (var tree in trees)
{
var treeType = tree.TreeControllerType;
// exclude anything marked with CoreTreeAttribute
var coreTree = treeType.GetCustomAttribute<CoreTreeAttribute>(false);
if (coreTree != null) continue;
// exclude anything not marked with PluginControllerAttribute
var pluginController = treeType.GetCustomAttribute<PluginControllerAttribute>(false);
if (pluginController == null) continue;
yield return new PluginTree { Alias = tree.TreeAlias, PackageFolder = pluginController.AreaName };
}
}
/// <summary>
/// Returns the server variables regarding the application state
/// </summary>
/// <returns></returns>
private Dictionary<string, object> GetApplicationState()
{
var app = new Dictionary<string, object>
{
// add versions - see UmbracoVersion for details & differences
// the complete application version (eg "8.1.2-alpha.25")
{ "version", UmbracoVersion.SemanticVersion.ToSemanticString() },
// the assembly version (eg "8.0.0")
{ "assemblyVersion", UmbracoVersion.AssemblyVersion.ToString() }
};
var version = _runtimeState.SemanticVersion.ToSemanticString();
//the value is the hash of the version, cdf version and the configured state
app.Add("cacheBuster", $"{version}.{_runtimeState.Level}.{ClientDependencySettings.Instance.Version}".GenerateHash());
//useful for dealing with virtual paths on the client side when hosted in virtual directories especially
app.Add("applicationPath", _httpContext.Request.ApplicationPath.EnsureEndsWith('/'));
//add the server's GMT time offset in minutes
app.Add("serverTimeOffset", Convert.ToInt32(DateTimeOffset.Now.Offset.TotalMinutes));
return app;
}
private static string GetMaxRequestLength()
{
return ConfigurationManager.GetSection("system.web/httpRuntime") is HttpRuntimeSection section
? section.MaxRequestLength.ToString()
: string.Empty;
}
}
}
| 51.33547 | 225 | 0.500895 | [
"MIT"
] | linuselander/Umbraco-CMS | src/Umbraco.Web/Editors/BackOfficeServerVariables.cs | 24,027 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Sample.Data.Migrations
{
public partial class CreateIdentitySchema : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(type: "nvarchar(450)", nullable: false),
Name = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(type: "nvarchar(450)", nullable: false),
UserName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
Email = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(type: "bit", nullable: false),
PasswordHash = table.Column<string>(type: "nvarchar(max)", nullable: true),
SecurityStamp = table.Column<string>(type: "nvarchar(max)", nullable: true),
ConcurrencyStamp = table.Column<string>(type: "nvarchar(max)", nullable: true),
PhoneNumber = table.Column<string>(type: "nvarchar(max)", nullable: true),
PhoneNumberConfirmed = table.Column<bool>(type: "bit", nullable: false),
TwoFactorEnabled = table.Column<bool>(type: "bit", nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
LockoutEnabled = table.Column<bool>(type: "bit", nullable: false),
AccessFailedCount = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
RoleId = table.Column<string>(type: "nvarchar(450)", nullable: false),
ClaimType = table.Column<string>(type: "nvarchar(max)", nullable: true),
ClaimValue = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserId = table.Column<string>(type: "nvarchar(450)", nullable: false),
ClaimType = table.Column<string>(type: "nvarchar(max)", nullable: true),
ClaimValue = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(type: "nvarchar(450)", nullable: false),
ProviderKey = table.Column<string>(type: "nvarchar(450)", nullable: false),
ProviderDisplayName = table.Column<string>(type: "nvarchar(max)", nullable: true),
UserId = table.Column<string>(type: "nvarchar(450)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(type: "nvarchar(450)", nullable: false),
RoleId = table.Column<string>(type: "nvarchar(450)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(type: "nvarchar(450)", nullable: false),
LoginProvider = table.Column<string>(type: "nvarchar(450)", nullable: false),
Name = table.Column<string>(type: "nvarchar(450)", nullable: false),
Value = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true,
filter: "[NormalizedName] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true,
filter: "[NormalizedUserName] IS NOT NULL");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}
| 45.477477 | 117 | 0.500396 | [
"MIT"
] | AmagiTech/SampleWeb | src/Sample.Data/Migrations/20220316182944_CreateIdentitySchema.cs | 10,098 | C# |
namespace ConstellationUnityEditor {
public interface ICopyable {
void Copy ();
void Paste ();
void Cut ();
}
} | 20.428571 | 36 | 0.566434 | [
"MIT"
] | ConstellationLanguage/Constellation | Constellation/Assets/Constellation/Editor/Scripts/Interfaces/ICopyable.cs | 143 | C# |
using System;
namespace Xamarin.Forms.TabView
{
public class TabTappedEventArgs : EventArgs
{
public int Position { get; set; }
}
} | 17 | 47 | 0.653595 | [
"MIT"
] | Redth/Xamarin.Forms.TabView | src/Xamarin.Forms.TabView/TabTappedEventArgs.cs | 155 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace PlayersAndMonsters.Models.Cards
{
public class TrapCard : Card
{
public TrapCard(string name)
: base(name, 120, 5)
{
}
}
}
| 16.666667 | 41 | 0.608 | [
"MIT"
] | Mithras11/C_Sharp-OOP-SoftUni | Exams/19.04.2019/PlayersAndMonsters/Models/Cards/TrapCard.cs | 252 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// The CaptureCollection lists the captured Capture numbers
// contained in a compiled Regex.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace Pchp.Library.PerlRegex
{
/*
* This collection returns the Captures for a group
* in the order in which they were matched (left to right
* or right to left). It is created by Group.Captures
*/
/// <summary>
/// Represents a sequence of capture substrings. The object is used
/// to return the set of captures done by a single capturing group.
/// </summary>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(RegexCollectionDebuggerProxy<Capture>))]
internal class CaptureCollection : IList<Capture>, IReadOnlyList<Capture>, IList
{
private readonly Group _group;
private readonly int _capcount;
private Capture[] _captures;
internal CaptureCollection(Group group)
{
_group = group;
_capcount = _group._capcount;
}
public bool IsReadOnly => true;
/// <summary>
/// Returns the number of captures.
/// </summary>
public int Count => _capcount;
/// <summary>
/// Returns a specific capture, by index, in this collection.
/// </summary>
public Capture this[int i] => GetCapture(i);
/// <summary>
/// Provides an enumerator in the same order as Item[].
/// </summary>
public IEnumerator GetEnumerator() => new Enumerator(this);
IEnumerator<Capture> IEnumerable<Capture>.GetEnumerator() => new Enumerator(this);
/// <summary>
/// Returns the set of captures for the group
/// </summary>
private Capture GetCapture(int i)
{
if (i == _capcount - 1 && i >= 0)
return _group;
if (i >= _capcount || i < 0)
throw new ArgumentOutOfRangeException(nameof(i));
// first time a capture is accessed, compute them all
if (_captures == null)
{
_captures = new Capture[_capcount];
for (int j = 0; j < _capcount - 1; j++)
{
_captures[j] = new Capture(_group._text, _group._caps[j * 2], _group._caps[j * 2 + 1]);
}
}
return _captures[i];
}
public bool IsSynchronized => false;
public object SyncRoot => _group;
public void CopyTo(Array array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
for (int i = arrayIndex, j = 0; j < Count; i++, j++)
{
array.SetValue(this[j], i);
}
}
public void CopyTo(Capture[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0 || arrayIndex > array.Length)
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
if (array.Length - arrayIndex < Count)
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
for (int i = arrayIndex, j = 0; j < Count; i++, j++)
{
array[i] = this[j];
}
}
int IList<Capture>.IndexOf(Capture item)
{
var comparer = EqualityComparer<Capture>.Default;
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(this[i], item))
return i;
}
return -1;
}
void IList<Capture>.Insert(int index, Capture item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void IList<Capture>.RemoveAt(int index)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
Capture IList<Capture>.this[int index]
{
get { return this[index]; }
set { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); }
}
void ICollection<Capture>.Add(Capture item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void ICollection<Capture>.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool ICollection<Capture>.Contains(Capture item) =>
((IList<Capture>)this).IndexOf(item) >= 0;
bool ICollection<Capture>.Remove(Capture item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
int IList.Add(object value)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void IList.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool IList.Contains(object value) =>
value is Capture && ((ICollection<Capture>)this).Contains((Capture)value);
int IList.IndexOf(object value) =>
value is Capture ? ((IList<Capture>)this).IndexOf((Capture)value) : -1;
void IList.Insert(int index, object value)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool IList.IsFixedSize => true;
void IList.Remove(object value)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void IList.RemoveAt(int index)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
object IList.this[int index]
{
get { return this[index]; }
set { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); }
}
private sealed class Enumerator : IEnumerator<Capture>
{
private readonly CaptureCollection _collection;
private int _index;
internal Enumerator(CaptureCollection collection)
{
Debug.Assert(collection != null, "collection cannot be null.");
_collection = collection;
_index = -1;
}
public bool MoveNext()
{
int size = _collection.Count;
if (_index >= size)
return false;
_index++;
return _index < size;
}
public Capture Current
{
get
{
if (_index < 0 || _index >= _collection.Count)
throw new InvalidOperationException(SR.EnumNotStarted);
return _collection[_index];
}
}
object IEnumerator.Current => Current;
void IEnumerator.Reset()
{
_index = -1;
}
void IDisposable.Dispose() { }
}
}
}
| 30.433884 | 107 | 0.554379 | [
"Apache-2.0"
] | Valks/peachpie | src/Peachpie.Library/PerlRegex/RegexCaptureCollection.cs | 7,365 | C# |
/* Copyright © 2021 Lee Kelleher.
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#if NET472
using System.ComponentModel;
namespace Umbraco.Core.IO
{
[EditorBrowsable(EditorBrowsableState.Never)]
public interface IIOHelper
{
string ResolveRelativeOrVirtualUrl(string path);
}
}
namespace Umbraco.Community.Contentment.Polyfill
{
[EditorBrowsable(EditorBrowsableState.Never)]
internal sealed class ContenmentIOHelper : Core.IO.IIOHelper
{
public string ResolveRelativeOrVirtualUrl(string path)
{
return Core.IO.IOHelper.ResolveUrl(path);
}
}
}
#endif
| 26.266667 | 70 | 0.705584 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | CarlSargunar/umbraco-contentment | src/Umbraco.Community.Contentment/Polyfill/IIOHelper.cs | 791 | C# |
#if WITH_EDITOR
#if PLATFORM_64BITS
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace UnrealEngine
{
[StructLayout(LayoutKind.Explicit,Size=12)]
public partial struct FCollisionProfileName
{
[FieldOffset(0)]
public FName Name;
}
}
#endif
#endif
| 16.263158 | 44 | 0.783172 | [
"MIT"
] | RobertAcksel/UnrealCS | Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile_Editor_64bits/FCollisionProfileName.cs | 309 | C# |
using System.Globalization;
using System.Threading.Tasks;
using Abp.Authorization;
using Abp.Configuration;
using Abp.Configuration.Startup;
using Abp.Extensions;
using Abp.Net.Mail;
using Abp.Runtime.Security;
using Abp.Runtime.Session;
using Abp.Timing;
using Abp.Zero.Configuration;
using Abp.Zero.Ldap.Configuration;
using Afonsoft.SetBox.Authorization;
using Afonsoft.SetBox.Configuration.Host.Dto;
using Afonsoft.SetBox.Configuration.Tenants.Dto;
using Afonsoft.SetBox.Security;
using Afonsoft.SetBox.Storage;
using Afonsoft.SetBox.Timing;
namespace Afonsoft.SetBox.Configuration.Tenants
{
[AbpAuthorize(AppPermissions.Pages_Administration_Tenant_Settings)]
public class TenantSettingsAppService : SettingsAppServiceBase, ITenantSettingsAppService
{
private readonly IMultiTenancyConfig _multiTenancyConfig;
private readonly ITimeZoneService _timeZoneService;
private readonly IBinaryObjectManager _binaryObjectManager;
private readonly IAbpZeroLdapModuleConfig _ldapModuleConfig;
public TenantSettingsAppService(
IAbpZeroLdapModuleConfig ldapModuleConfig,
IMultiTenancyConfig multiTenancyConfig,
ITimeZoneService timeZoneService,
IEmailSender emailSender,
IBinaryObjectManager binaryObjectManager) : base(emailSender)
{
_multiTenancyConfig = multiTenancyConfig;
_ldapModuleConfig = ldapModuleConfig;
_timeZoneService = timeZoneService;
_binaryObjectManager = binaryObjectManager;
}
#region Get Settings
public async Task<TenantSettingsEditDto> GetAllSettings()
{
var settings = new TenantSettingsEditDto
{
UserManagement = await GetUserManagementSettingsAsync(),
Security = await GetSecuritySettingsAsync(),
Billing = await GetBillingSettingsAsync(),
OtherSettings = await GetOtherSettingsAsync(),
Email = await GetEmailSettingsAsync()
};
if (!_multiTenancyConfig.IsEnabled || Clock.SupportsMultipleTimezone)
{
settings.General = await GetGeneralSettingsAsync();
}
if (_ldapModuleConfig.IsEnabled)
{
settings.Ldap = await GetLdapSettingsAsync();
}
else
{
settings.Ldap = new LdapSettingsEditDto { IsModuleEnabled = false };
}
return settings;
}
private async Task<LdapSettingsEditDto> GetLdapSettingsAsync()
{
return new LdapSettingsEditDto
{
IsModuleEnabled = true,
IsEnabled = await SettingManager.GetSettingValueForTenantAsync<bool>(LdapSettingNames.IsEnabled, AbpSession.GetTenantId()),
Domain = await SettingManager.GetSettingValueForTenantAsync(LdapSettingNames.Domain, AbpSession.GetTenantId()),
UserName = await SettingManager.GetSettingValueForTenantAsync(LdapSettingNames.UserName, AbpSession.GetTenantId()),
Password = await SettingManager.GetSettingValueForTenantAsync(LdapSettingNames.Password, AbpSession.GetTenantId()),
};
}
private async Task<TenantEmailSettingsEditDto> GetEmailSettingsAsync()
{
var useHostDefaultEmailSettings = await SettingManager.GetSettingValueForTenantAsync<bool>(AppSettings.Email.UseHostDefaultEmailSettings, AbpSession.GetTenantId());
if (useHostDefaultEmailSettings)
{
return new TenantEmailSettingsEditDto
{
UseHostDefaultEmailSettings = true
};
}
var smtpPassword = await SettingManager.GetSettingValueForTenantAsync(EmailSettingNames.Smtp.Password, AbpSession.GetTenantId());
return new TenantEmailSettingsEditDto
{
UseHostDefaultEmailSettings = false,
DefaultFromAddress = await SettingManager.GetSettingValueForTenantAsync(EmailSettingNames.DefaultFromAddress, AbpSession.GetTenantId()),
DefaultFromDisplayName = await SettingManager.GetSettingValueForTenantAsync(EmailSettingNames.DefaultFromDisplayName, AbpSession.GetTenantId()),
SmtpHost = await SettingManager.GetSettingValueForTenantAsync(EmailSettingNames.Smtp.Host, AbpSession.GetTenantId()),
SmtpPort = await SettingManager.GetSettingValueForTenantAsync<int>(EmailSettingNames.Smtp.Port, AbpSession.GetTenantId()),
SmtpUserName = await SettingManager.GetSettingValueForTenantAsync(EmailSettingNames.Smtp.UserName, AbpSession.GetTenantId()),
SmtpPassword = SimpleStringCipher.Instance.Decrypt(smtpPassword),
SmtpDomain = await SettingManager.GetSettingValueForTenantAsync(EmailSettingNames.Smtp.Domain, AbpSession.GetTenantId()),
SmtpEnableSsl = await SettingManager.GetSettingValueForTenantAsync<bool>(EmailSettingNames.Smtp.EnableSsl, AbpSession.GetTenantId()),
SmtpUseDefaultCredentials = await SettingManager.GetSettingValueForTenantAsync<bool>(EmailSettingNames.Smtp.UseDefaultCredentials, AbpSession.GetTenantId())
};
}
private async Task<GeneralSettingsEditDto> GetGeneralSettingsAsync()
{
var settings = new GeneralSettingsEditDto();
if (Clock.SupportsMultipleTimezone)
{
var timezone = await SettingManager.GetSettingValueForTenantAsync(TimingSettingNames.TimeZone, AbpSession.GetTenantId());
settings.Timezone = timezone;
settings.TimezoneForComparison = timezone;
}
var defaultTimeZoneId = await _timeZoneService.GetDefaultTimezoneAsync(SettingScopes.Tenant, AbpSession.TenantId);
if (settings.Timezone == defaultTimeZoneId)
{
settings.Timezone = string.Empty;
}
return settings;
}
private async Task<TenantUserManagementSettingsEditDto> GetUserManagementSettingsAsync()
{
return new TenantUserManagementSettingsEditDto
{
AllowSelfRegistration = await SettingManager.GetSettingValueAsync<bool>(AppSettings.UserManagement.AllowSelfRegistration),
IsNewRegisteredUserActiveByDefault = await SettingManager.GetSettingValueAsync<bool>(AppSettings.UserManagement.IsNewRegisteredUserActiveByDefault),
IsEmailConfirmationRequiredForLogin = await SettingManager.GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin),
UseCaptchaOnRegistration = await SettingManager.GetSettingValueAsync<bool>(AppSettings.UserManagement.UseCaptchaOnRegistration),
UseCaptchaOnLogin = await SettingManager.GetSettingValueAsync<bool>(AppSettings.UserManagement.UseCaptchaOnLogin),
IsCookieConsentEnabled = await SettingManager.GetSettingValueAsync<bool>(AppSettings.UserManagement.IsCookieConsentEnabled),
IsQuickThemeSelectEnabled = await SettingManager.GetSettingValueAsync<bool>(AppSettings.UserManagement.IsQuickThemeSelectEnabled),
SessionTimeOutSettings = new SessionTimeOutSettingsEditDto()
{
IsEnabled = await SettingManager.GetSettingValueAsync<bool>(AppSettings.UserManagement.SessionTimeOut.IsEnabled),
TimeOutSecond = await SettingManager.GetSettingValueAsync<int>(AppSettings.UserManagement.SessionTimeOut.TimeOutSecond),
ShowTimeOutNotificationSecond = await SettingManager.GetSettingValueAsync<int>(AppSettings.UserManagement.SessionTimeOut.ShowTimeOutNotificationSecond)
}
};
}
private async Task<SecuritySettingsEditDto> GetSecuritySettingsAsync()
{
var passwordComplexitySetting = new PasswordComplexitySetting
{
RequireDigit = await SettingManager.GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireDigit),
RequireLowercase = await SettingManager.GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireLowercase),
RequireNonAlphanumeric = await SettingManager.GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireNonAlphanumeric),
RequireUppercase = await SettingManager.GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireUppercase),
RequiredLength = await SettingManager.GetSettingValueAsync<int>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequiredLength)
};
var defaultPasswordComplexitySetting = new PasswordComplexitySetting
{
RequireDigit = await SettingManager.GetSettingValueForApplicationAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireDigit),
RequireLowercase = await SettingManager.GetSettingValueForApplicationAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireLowercase),
RequireNonAlphanumeric = await SettingManager.GetSettingValueForApplicationAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireNonAlphanumeric),
RequireUppercase = await SettingManager.GetSettingValueForApplicationAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireUppercase),
RequiredLength = await SettingManager.GetSettingValueForApplicationAsync<int>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequiredLength)
};
return new SecuritySettingsEditDto
{
UseDefaultPasswordComplexitySettings = passwordComplexitySetting.Equals(defaultPasswordComplexitySetting),
PasswordComplexity = passwordComplexitySetting,
DefaultPasswordComplexity = defaultPasswordComplexitySetting,
UserLockOut = await GetUserLockOutSettingsAsync(),
TwoFactorLogin = await GetTwoFactorLoginSettingsAsync(),
AllowOneConcurrentLoginPerUser = await GetOneConcurrentLoginPerUserSetting()
};
}
private async Task<TenantBillingSettingsEditDto> GetBillingSettingsAsync()
{
return new TenantBillingSettingsEditDto()
{
LegalName = await SettingManager.GetSettingValueAsync(AppSettings.TenantManagement.BillingLegalName),
Address = await SettingManager.GetSettingValueAsync(AppSettings.TenantManagement.BillingAddress),
TaxVatNo = await SettingManager.GetSettingValueAsync(AppSettings.TenantManagement.BillingTaxVatNo)
};
}
private async Task<TenantOtherSettingsEditDto> GetOtherSettingsAsync()
{
return new TenantOtherSettingsEditDto()
{
IsQuickThemeSelectEnabled = await SettingManager.GetSettingValueAsync<bool>(AppSettings.UserManagement.IsQuickThemeSelectEnabled)
};
}
private async Task<UserLockOutSettingsEditDto> GetUserLockOutSettingsAsync()
{
return new UserLockOutSettingsEditDto
{
IsEnabled = await SettingManager.GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.UserLockOut.IsEnabled),
MaxFailedAccessAttemptsBeforeLockout = await SettingManager.GetSettingValueAsync<int>(AbpZeroSettingNames.UserManagement.UserLockOut.MaxFailedAccessAttemptsBeforeLockout),
DefaultAccountLockoutSeconds = await SettingManager.GetSettingValueAsync<int>(AbpZeroSettingNames.UserManagement.UserLockOut.DefaultAccountLockoutSeconds)
};
}
private Task<bool> IsTwoFactorLoginEnabledForApplicationAsync()
{
return SettingManager.GetSettingValueForApplicationAsync<bool>(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEnabled);
}
private async Task<TwoFactorLoginSettingsEditDto> GetTwoFactorLoginSettingsAsync()
{
var settings = new TwoFactorLoginSettingsEditDto
{
IsEnabledForApplication = await IsTwoFactorLoginEnabledForApplicationAsync()
};
if (_multiTenancyConfig.IsEnabled && !settings.IsEnabledForApplication)
{
return settings;
}
settings.IsEnabled = await SettingManager.GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEnabled);
settings.IsRememberBrowserEnabled = await SettingManager.GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsRememberBrowserEnabled);
if (!_multiTenancyConfig.IsEnabled)
{
settings.IsEmailProviderEnabled = await SettingManager.GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEmailProviderEnabled);
settings.IsSmsProviderEnabled = await SettingManager.GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsSmsProviderEnabled);
settings.IsGoogleAuthenticatorEnabled = await SettingManager.GetSettingValueAsync<bool>(AppSettings.UserManagement.TwoFactorLogin.IsGoogleAuthenticatorEnabled);
}
return settings;
}
private async Task<bool> GetOneConcurrentLoginPerUserSetting()
{
return await SettingManager.GetSettingValueAsync<bool>(AppSettings.UserManagement.AllowOneConcurrentLoginPerUser);
}
#endregion
#region Update Settings
public async Task UpdateAllSettings(TenantSettingsEditDto input)
{
await UpdateUserManagementSettingsAsync(input.UserManagement);
await UpdateSecuritySettingsAsync(input.Security);
await UpdateBillingSettingsAsync(input.Billing);
await UpdateEmailSettingsAsync(input.Email);
//Time Zone
if (Clock.SupportsMultipleTimezone)
{
if (input.General.Timezone.IsNullOrEmpty())
{
var defaultValue = await _timeZoneService.GetDefaultTimezoneAsync(SettingScopes.Tenant, AbpSession.TenantId);
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), TimingSettingNames.TimeZone, defaultValue);
}
else
{
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), TimingSettingNames.TimeZone, input.General.Timezone);
}
}
if (!_multiTenancyConfig.IsEnabled)
{
await UpdateOtherSettingsAsync(input.OtherSettings);
input.ValidateHostSettings();
}
if (_ldapModuleConfig.IsEnabled)
{
await UpdateLdapSettingsAsync(input.Ldap);
}
}
private async Task UpdateOtherSettingsAsync(TenantOtherSettingsEditDto input)
{
await SettingManager.ChangeSettingForTenantAsync(
AbpSession.GetTenantId(),
AppSettings.UserManagement.IsQuickThemeSelectEnabled,
input.IsQuickThemeSelectEnabled.ToString().ToLowerInvariant()
);
}
private async Task UpdateBillingSettingsAsync(TenantBillingSettingsEditDto input)
{
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), AppSettings.TenantManagement.BillingLegalName, input.LegalName);
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), AppSettings.TenantManagement.BillingAddress, input.Address);
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), AppSettings.TenantManagement.BillingTaxVatNo, input.TaxVatNo);
}
private async Task UpdateLdapSettingsAsync(LdapSettingsEditDto input)
{
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), LdapSettingNames.IsEnabled, input.IsEnabled.ToString().ToLowerInvariant());
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), LdapSettingNames.Domain, input.Domain.IsNullOrWhiteSpace() ? null : input.Domain);
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), LdapSettingNames.UserName, input.UserName.IsNullOrWhiteSpace() ? null : input.UserName);
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), LdapSettingNames.Password, input.Password.IsNullOrWhiteSpace() ? null : input.Password);
}
private async Task UpdateEmailSettingsAsync(TenantEmailSettingsEditDto input)
{
if (_multiTenancyConfig.IsEnabled && !SetBoxConsts.AllowTenantsToChangeEmailSettings)
{
return;
}
var useHostDefaultEmailSettings = _multiTenancyConfig.IsEnabled && input.UseHostDefaultEmailSettings;
if (useHostDefaultEmailSettings)
{
var smtpPassword = await SettingManager.GetSettingValueForApplicationAsync(EmailSettingNames.Smtp.Password);
input = new TenantEmailSettingsEditDto
{
UseHostDefaultEmailSettings = true,
DefaultFromAddress = await SettingManager.GetSettingValueForApplicationAsync(EmailSettingNames.DefaultFromAddress),
DefaultFromDisplayName = await SettingManager.GetSettingValueForApplicationAsync(EmailSettingNames.DefaultFromDisplayName),
SmtpHost = await SettingManager.GetSettingValueForApplicationAsync(EmailSettingNames.Smtp.Host),
SmtpPort = await SettingManager.GetSettingValueForApplicationAsync<int>(EmailSettingNames.Smtp.Port),
SmtpUserName = await SettingManager.GetSettingValueForApplicationAsync(EmailSettingNames.Smtp.UserName),
SmtpPassword = SimpleStringCipher.Instance.Decrypt(smtpPassword),
SmtpDomain = await SettingManager.GetSettingValueForApplicationAsync(EmailSettingNames.Smtp.Domain),
SmtpEnableSsl = await SettingManager.GetSettingValueForApplicationAsync<bool>(EmailSettingNames.Smtp.EnableSsl),
SmtpUseDefaultCredentials = await SettingManager.GetSettingValueForApplicationAsync<bool>(EmailSettingNames.Smtp.UseDefaultCredentials)
};
}
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), AppSettings.Email.UseHostDefaultEmailSettings, useHostDefaultEmailSettings.ToString().ToLowerInvariant());
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), EmailSettingNames.DefaultFromAddress, input.DefaultFromAddress);
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), EmailSettingNames.DefaultFromDisplayName, input.DefaultFromDisplayName);
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), EmailSettingNames.Smtp.Host, input.SmtpHost);
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), EmailSettingNames.Smtp.Port, input.SmtpPort.ToString(CultureInfo.InvariantCulture));
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), EmailSettingNames.Smtp.UserName, input.SmtpUserName);
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), EmailSettingNames.Smtp.Password, SimpleStringCipher.Instance.Encrypt(input.SmtpPassword));
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), EmailSettingNames.Smtp.Domain, input.SmtpDomain);
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), EmailSettingNames.Smtp.EnableSsl, input.SmtpEnableSsl.ToString().ToLowerInvariant());
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), EmailSettingNames.Smtp.UseDefaultCredentials, input.SmtpUseDefaultCredentials.ToString().ToLowerInvariant());
}
private async Task UpdateUserManagementSettingsAsync(TenantUserManagementSettingsEditDto settings)
{
await SettingManager.ChangeSettingForTenantAsync(
AbpSession.GetTenantId(),
AppSettings.UserManagement.AllowSelfRegistration,
settings.AllowSelfRegistration.ToString().ToLowerInvariant()
);
await SettingManager.ChangeSettingForTenantAsync(
AbpSession.GetTenantId(),
AppSettings.UserManagement.IsNewRegisteredUserActiveByDefault,
settings.IsNewRegisteredUserActiveByDefault.ToString().ToLowerInvariant()
);
await SettingManager.ChangeSettingForTenantAsync(
AbpSession.GetTenantId(),
AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin,
settings.IsEmailConfirmationRequiredForLogin.ToString().ToLowerInvariant()
);
await SettingManager.ChangeSettingForTenantAsync(
AbpSession.GetTenantId(),
AppSettings.UserManagement.UseCaptchaOnRegistration,
settings.UseCaptchaOnRegistration.ToString().ToLowerInvariant()
);
await SettingManager.ChangeSettingForTenantAsync(
AbpSession.GetTenantId(),
AppSettings.UserManagement.UseCaptchaOnLogin,
settings.UseCaptchaOnLogin.ToString().ToLowerInvariant()
);
await SettingManager.ChangeSettingForTenantAsync(
AbpSession.GetTenantId(),
AppSettings.UserManagement.IsCookieConsentEnabled,
settings.IsCookieConsentEnabled.ToString().ToLowerInvariant()
);
await UpdateUserManagementSessionTimeOutSettingsAsync(settings.SessionTimeOutSettings);
}
private async Task UpdateUserManagementSessionTimeOutSettingsAsync(SessionTimeOutSettingsEditDto settings)
{
await SettingManager.ChangeSettingForTenantAsync(
AbpSession.GetTenantId(),
AppSettings.UserManagement.SessionTimeOut.IsEnabled,
settings.IsEnabled.ToString().ToLowerInvariant()
);
await SettingManager.ChangeSettingForTenantAsync(
AbpSession.GetTenantId(),
AppSettings.UserManagement.SessionTimeOut.TimeOutSecond,
settings.TimeOutSecond.ToString()
);
await SettingManager.ChangeSettingForTenantAsync(
AbpSession.GetTenantId(),
AppSettings.UserManagement.SessionTimeOut.ShowTimeOutNotificationSecond,
settings.ShowTimeOutNotificationSecond.ToString()
);
}
private async Task UpdateSecuritySettingsAsync(SecuritySettingsEditDto settings)
{
if (settings.UseDefaultPasswordComplexitySettings)
{
await UpdatePasswordComplexitySettingsAsync(settings.DefaultPasswordComplexity);
}
else
{
await UpdatePasswordComplexitySettingsAsync(settings.PasswordComplexity);
}
await UpdateUserLockOutSettingsAsync(settings.UserLockOut);
await UpdateTwoFactorLoginSettingsAsync(settings.TwoFactorLogin);
await UpdateOneConcurrentLoginPerUserSettingAsync(settings.AllowOneConcurrentLoginPerUser);
}
private async Task UpdatePasswordComplexitySettingsAsync(PasswordComplexitySetting settings)
{
await SettingManager.ChangeSettingForTenantAsync(
AbpSession.GetTenantId(),
AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireDigit,
settings.RequireDigit.ToString()
);
await SettingManager.ChangeSettingForTenantAsync(
AbpSession.GetTenantId(),
AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireLowercase,
settings.RequireLowercase.ToString()
);
await SettingManager.ChangeSettingForTenantAsync(
AbpSession.GetTenantId(),
AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireNonAlphanumeric,
settings.RequireNonAlphanumeric.ToString()
);
await SettingManager.ChangeSettingForTenantAsync(
AbpSession.GetTenantId(),
AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireUppercase,
settings.RequireUppercase.ToString()
);
await SettingManager.ChangeSettingForTenantAsync(
AbpSession.GetTenantId(),
AbpZeroSettingNames.UserManagement.PasswordComplexity.RequiredLength,
settings.RequiredLength.ToString()
);
}
private async Task UpdateUserLockOutSettingsAsync(UserLockOutSettingsEditDto settings)
{
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), AbpZeroSettingNames.UserManagement.UserLockOut.IsEnabled, settings.IsEnabled.ToString().ToLowerInvariant());
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), AbpZeroSettingNames.UserManagement.UserLockOut.DefaultAccountLockoutSeconds, settings.DefaultAccountLockoutSeconds.ToString());
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), AbpZeroSettingNames.UserManagement.UserLockOut.MaxFailedAccessAttemptsBeforeLockout, settings.MaxFailedAccessAttemptsBeforeLockout.ToString());
}
private async Task UpdateTwoFactorLoginSettingsAsync(TwoFactorLoginSettingsEditDto settings)
{
if (_multiTenancyConfig.IsEnabled &&
!await IsTwoFactorLoginEnabledForApplicationAsync()) //Two factor login can not be used by tenants if disabled by the host
{
return;
}
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEnabled, settings.IsEnabled.ToString().ToLowerInvariant());
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsRememberBrowserEnabled, settings.IsRememberBrowserEnabled.ToString().ToLowerInvariant());
if (!_multiTenancyConfig.IsEnabled)
{
//These settings can only be changed by host, in a multitenant application.
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEmailProviderEnabled, settings.IsEmailProviderEnabled.ToString().ToLowerInvariant());
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsSmsProviderEnabled, settings.IsSmsProviderEnabled.ToString().ToLowerInvariant());
await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), AppSettings.UserManagement.TwoFactorLogin.IsGoogleAuthenticatorEnabled, settings.IsGoogleAuthenticatorEnabled.ToString().ToLowerInvariant());
}
}
private async Task UpdateOneConcurrentLoginPerUserSettingAsync(bool allowOneConcurrentLoginPerUser)
{
if (_multiTenancyConfig.IsEnabled)
{
return;
}
await SettingManager.ChangeSettingForApplicationAsync(AppSettings.UserManagement.AllowOneConcurrentLoginPerUser, allowOneConcurrentLoginPerUser.ToString());
}
#endregion
#region Others
public async Task ClearLogo()
{
var tenant = await GetCurrentTenantAsync();
if (!tenant.HasLogo())
{
return;
}
var logoObject = await _binaryObjectManager.GetOrNullAsync(tenant.LogoId.Value);
if (logoObject != null)
{
await _binaryObjectManager.DeleteAsync(tenant.LogoId.Value);
}
tenant.ClearLogo();
}
public async Task ClearCustomCss()
{
var tenant = await GetCurrentTenantAsync();
if (!tenant.CustomCssId.HasValue)
{
return;
}
var cssObject = await _binaryObjectManager.GetOrNullAsync(tenant.CustomCssId.Value);
if (cssObject != null)
{
await _binaryObjectManager.DeleteAsync(tenant.CustomCssId.Value);
}
tenant.CustomCssId = null;
}
#endregion
}
} | 54.679174 | 232 | 0.703026 | [
"Apache-2.0"
] | afonsoft/SetBox-VideoPlayer | SetBoxWebUI_New/src/Afonsoft.SetBox.Application/Configuration/Tenants/TenantSettingsAppService.cs | 29,146 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.