content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Coin : MonoBehaviour
{
[SerializeField] AudioClip coinPickupSFX;
[SerializeField] int pointsForCoin = 10;
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
Debug.Log("I collected a coin");
FindObjectOfType<GameSession>().AddToScore(pointsForCoin);
AudioSource.PlayClipAtPoint(coinPickupSFX, gameObject.transform.position);
Destroy(gameObject);
}
}
}
| 26.52381 | 86 | 0.664273 | [
"MIT"
] | arinjay97/side-scroller | Assets/Scripts/Coin.cs | 557 | C# |
using System;
using System.IO;
using System.Data;
using System.Collections.Generic;
using System.Collections;
using System.Text;
namespace Geomethod.Data
{
public class GmDataException : GmException
{
public GmDataException(string message) : base(message) { }
public GmDataException(string message, Exception innerException) : base(message, innerException) { }
}
public class DataUtils
{
public static string GetColumnList(IEnumerable<string> colNames, GetColumnListOptions opt)
{
string format=null;
switch (opt)
{
case GetColumnListOptions.Insert: format = "@{0}"; break;
case GetColumnListOptions.Update: format = "{0}=@{0}"; break;
}
StringBuilder sb = new StringBuilder(1 << 10);
foreach (string s in colNames)
{
if (sb.Length > 0) sb.Append(',');
if (format == null) sb.Append(s);
else sb.AppendFormat(format, s);
}
return sb.ToString();
}
}
}
| 23.589744 | 102 | 0.694565 | [
"MIT"
] | AlexAbramov/geomethod | Geomethod.Data/Utils/Utils.cs | 920 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using DocumentFormat.OpenXml.Packaging;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Xunit;
using Xunit.Abstractions;
namespace DocumentFormat.OpenXml.Tests
{
public class PartConstraintRuleTests
{
private readonly ITestOutputHelper _output;
private static readonly HashSet<Type> _abstractOpenXmlParts = new HashSet<Type>
{
typeof(OpenXmlPart),
typeof(ExtendedPart),
typeof(StylesPart),
typeof(CustomUIPart),
};
public PartConstraintRuleTests(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void AllExpectedParts()
{
var actual = typeof(OpenXmlPart)
.Assembly
.DefinedTypes
.Where(typeof(OpenXmlPart).IsAssignableFrom)
.Select(GetName)
.OrderBy(v => v, StringComparer.Ordinal)
.ToList();
var expected = _cachedConstraintData.Value
.Select(v => v.Key)
.Concat(_abstractOpenXmlParts.Select(GetName))
.OrderBy(v => v, StringComparer.Ordinal)
.ToList();
Assert.Equal(expected, actual, StringComparer.Ordinal);
}
[MemberData(nameof(GetOpenXmlParts))]
[Theory]
public void ValidatePart(OpenXmlPart part)
{
var data = GetConstraintData(part);
Assert.Same(part.PartConstraints, part.PartConstraints);
Assert.Same(part.DataPartReferenceConstraints, part.DataPartReferenceConstraints);
if (!part.PartConstraints.Any())
{
Assert.Same(PartConstraintCollection.Instance, part.PartConstraints);
}
if (!part.DataPartReferenceConstraints.Any())
{
Assert.Same(PartConstraintCollection.Instance, part.DataPartReferenceConstraints);
}
Assert.Equal(data.IsContentTypeFixed, part.IsContentTypeFixed);
Assert.Equal(data.RelationshipType, part.RelationshipType);
Assert.Equal(data.TargetFileExtension, part.TargetFileExtension);
Assert.Equal(data.TargetName, part.TargetName);
Assert.Equal(data.TargetPath, part.TargetPath);
if (part.IsContentTypeFixed)
{
Assert.Equal(data.ContentType, part.ContentType);
}
AssertDictionary(data.DataParts, part.DataPartReferenceConstraints);
AssertDictionary(data.Parts, part.PartConstraints);
}
[MemberData(nameof(GetOpenXmlParts))]
[Theory]
public void ValidateValid(OpenXmlPart part)
{
var availability = part.GetType().GetCustomAttribute<OfficeAvailabilityAttribute>().OfficeVersion;
var versions = Enum.GetValues(typeof(FileFormatVersions))
.Cast<FileFormatVersions>()
.Where(v => v != FileFormatVersions.None);
foreach (var version in versions)
{
Assert.Equal(version.AtLeast(availability), part.IsInVersion(version));
}
}
[Fact]
public void ExportData()
{
var result = GetParts()
.Select(t => new
{
Name = GetName(t.GetType()),
ContentType = t.IsContentTypeFixed ? t.ContentType : null,
IsContentTypeFixed = t.IsContentTypeFixed,
RelationshipType = t.RelationshipType,
TargetFileExtension = t.TargetFileExtension,
TargetName = t.TargetName,
TargetPath = t.TargetPath,
DataParts = t.DataPartReferenceConstraints,
Parts = t.PartConstraints,
})
.OrderBy(d => d.Name, StringComparer.Ordinal);
var data = JsonConvert.SerializeObject(result, Formatting.Indented, new StringEnumConverter());
_output.WriteLine(data);
}
public static IEnumerable<object[]> GetOpenXmlParts() => GetParts().Select(p => new[] { p });
private static IEnumerable<OpenXmlPart> GetParts()
{
return typeof(OpenXmlPart)
.Assembly
.GetTypes()
.Where(typeof(OpenXmlPart).IsAssignableFrom)
.Where(a => !_abstractOpenXmlParts.Contains(a))
.Select(a => (OpenXmlPart)Activator.CreateInstance(a, true));
}
private static string GetName(Type type) => type.FullName;
private static ConstraintData GetConstraintData(OpenXmlPart part) => _cachedConstraintData.Value[GetName(part.GetType())];
private static Lazy<Dictionary<string, ConstraintData>> _cachedConstraintData = new Lazy<Dictionary<string, ConstraintData>>(() =>
{
var names = typeof(PartConstraintRuleTests).Assembly.GetManifestResourceNames();
using (var stream = typeof(PartConstraintRuleTests).Assembly.GetManifestResourceStream("DocumentFormat.OpenXml.Packaging.Tests.data.PartConstraintData.json"))
using (var reader = new StreamReader(stream))
{
return JsonConvert.DeserializeObject<ConstraintData[]>(reader.ReadToEnd(), new StringEnumConverter())
.ToDictionary(t => t.Name, StringComparer.Ordinal);
}
});
private void AssertDictionary(IDictionary<string, PartConstraintRule2> expected, IReadOnlyDictionary<string, PartConstraintRule> actual)
{
Assert.Equal(expected.Count, actual.Count);
foreach (var key in expected.Keys)
{
Assert.Equal(expected[key], actual[key]);
}
}
#pragma warning disable CA1812
private class ConstraintData
{
public string Name { get; set; }
public string ContentType { get; set; }
public bool IsContentTypeFixed { get; set; }
public string RelationshipType { get; set; }
public string TargetFileExtension { get; set; }
public string TargetName { get; set; }
public string TargetPath { get; set; }
public IDictionary<string, PartConstraintRule2> DataParts { get; set; }
public IDictionary<string, PartConstraintRule2> Parts { get; set; }
}
#pragma warning restore CA1712
private class PartConstraintRule2
{
public string PartClassName { get; set; }
public string PartContentType { get; set; }
public bool MinOccursIsNonZero { get; set; }
public bool MaxOccursGreatThanOne { get; set; }
public FileFormatVersions FileFormat { get; set; }
public static implicit operator PartConstraintRule2(PartConstraintRule rule)
{
return new PartConstraintRule2
{
FileFormat = rule.FileFormat,
MaxOccursGreatThanOne = rule.MaxOccursGreatThanOne,
MinOccursIsNonZero = rule.MinOccursIsNonZero,
PartClassName = rule.PartClassName,
PartContentType = rule.PartContentType,
};
}
public override bool Equals(object obj)
{
if (obj is PartConstraintRule2 other)
{
return string.Equals(PartClassName, other.PartClassName, StringComparison.Ordinal)
&& string.Equals(PartContentType, other.PartContentType, StringComparison.Ordinal)
&& MinOccursIsNonZero == other.MinOccursIsNonZero
&& MaxOccursGreatThanOne == other.MaxOccursGreatThanOne
&& FileFormat == other.FileFormat;
}
return false;
}
public override int GetHashCode()
{
const int HashMultiplier = 31;
unchecked
{
int hash = 17;
hash = hash * HashMultiplier + StringComparer.Ordinal.GetHashCode(PartClassName);
hash = hash * HashMultiplier + StringComparer.Ordinal.GetHashCode(PartContentType);
hash = hash * HashMultiplier + MinOccursIsNonZero.GetHashCode();
hash = hash * HashMultiplier + MaxOccursGreatThanOne.GetHashCode();
hash = hash * HashMultiplier + FileFormat.GetHashCode();
return hash;
}
}
}
}
}
| 37.099174 | 170 | 0.586434 | [
"Apache-2.0"
] | Cristie/Open-XML-SDK | test/DocumentFormat.OpenXml.Packaging.Tests/PartConstraintRuleTests.cs | 8,980 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace College.Services
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
// Additional configuration is required to successfully run gRPC on macOS.
// For instructions on how to configure Kestrel and gRPC clients on macOS, visit https://go.microsoft.com/fwlink/?linkid=2099682
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 30.607143 | 136 | 0.652275 | [
"MIT"
] | jagratimodi/speaker_series_2021 | Year_2020/CSharpCorner/21Nov2020_gRPC_Session1/Source/College.gRPCServices/College.Services/Program.cs | 857 | C# |
using UnityEngine;
public interface IWeapon {
Transform Muzzle {
get;
}
bool Fire();
float GetFirerate();
float GetDamage();
float GetDPS();
void Reload();
}
| 10.15 | 26 | 0.566502 | [
"MIT"
] | Lomztein/Project-Incoming | Assets/Source/Interfaces/IWeapon.cs | 205 | C# |
using System;
using OvoGitTest.Helpers;
namespace OvoGitTest.Controllers
{
public class GitController
{
public string GetDockerFileContent(string customer, string personalAccessKey)
{
var gitClient = new GitClient();
var repo = gitClient.GetDeploymentRepo(customer, personalAccessKey);
var retVal = gitClient.GetDockerComposeFileContent(repo, personalAccessKey);
return retVal;
}
public void UpdateDockerFileContent(string fileContent, string customer, string personalAccessKey)
{
var gitClient = new GitClient();
var repo = gitClient.GetDeploymentRepo(customer, personalAccessKey);
gitClient.WriteDockerComposeFileContent(repo, fileContent, personalAccessKey);
}
public void UpdateEnvFileContent(string fileContent, string customer, string personalAccessKey)
{
var gitClient = new GitClient();
var repo = gitClient.GetDeploymentRepo(customer, personalAccessKey);
gitClient.WriteEnvFileContent(repo, fileContent, personalAccessKey);
}
public string CreateNewDeploymentRepo(string customer, string personalAccessKey)
{
var retVal = "";
return retVal;
}
public string GetEnvFileContent(string customer, string personalAccessKey)
{
var gitClient = new GitClient();
var repo = gitClient.GetDeploymentRepo(customer, personalAccessKey);
var retVal = gitClient.GetEnvFileContent(repo, personalAccessKey);
return retVal;
}
}
}
| 36.644444 | 106 | 0.661007 | [
"MIT"
] | henkhbs/libgit2sharp | OvoGitTest/Controllers/GitController.cs | 1,651 | C# |
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Serilog;
using Telegram.Bot.Framework.Abstractions;
using Telegram.Bot.Types.ReplyMarkups;
using WinTenDev.Zizi.Models.Enums;
using WinTenDev.Zizi.Services;
using WinTenDev.Zizi.Utils;
using WinTenDev.Zizi.Utils.Telegram;
using WinTenDev.Zizi.Utils.Text;
namespace WinTenDev.Zizi.Host.Handlers.Commands.Tags
{
public class FindTagCommand : IUpdateHandler
{
private readonly TelegramService _telegramService;
private readonly TagsService _tagsService;
public FindTagCommand(TelegramService telegramService, TagsService tagsService)
{
_tagsService = tagsService;
_telegramService = telegramService;
}
public async Task HandleAsync(IUpdateContext context, UpdateDelegate next, CancellationToken cancellationToken)
{
Log.Information("Finding tag on messages");
await _telegramService.AddUpdateContext(context);
var sw = Stopwatch.StartNew();
var message = _telegramService.MessageOrEdited;
var chatSettings = _telegramService.CurrentSetting;
var chatId = _telegramService.ChatId;
var msgText = _telegramService.MessageOrEdited.Text;
if (!chatSettings.EnableFindTags)
{
Log.Information("Find Tags is disabled in this Group!");
return;
}
Log.Information("Tags Received..");
var partsText = message.Text.Split(new char[] {' ', '\n', ','})
.Where(x => x.Contains("#")).ToArray();
var allTags = partsText.Length;
var limitedTags = partsText.Take(5).ToArray();
var limitedCount = limitedTags.Length;
Log.Debug("AllTags: {0}", allTags.ToJson(true));
Log.Debug("First 5: {0}", limitedTags.ToJson(true));
// int count = 1;
var tags = (await _tagsService.GetTagsByGroupAsync(chatId)).ToList();
foreach (var split in limitedTags)
{
Log.Information("Processing : {0} => ", split);
var trimTag = split.TrimStart('#');
var tagData = tags.FirstOrDefault(x => x.Tag == trimTag);
if (tagData == null)
{
Log.Debug("Tag {0} is not found.", trimTag);
continue;
}
Log.Debug("Data of tag: {0} => {1}", trimTag, tagData.ToJson(true));
var content = tagData.Content;
var buttonStr = tagData.BtnData;
var typeData = tagData.TypeData;
var idData = tagData.FileId;
InlineKeyboardMarkup buttonMarkup = null;
if (!buttonStr.IsNullOrEmpty())
{
buttonMarkup = buttonStr.ToReplyMarkup(2);
}
if (typeData != MediaType.Unknown)
{
await _telegramService.SendMediaAsync(idData, typeData, content, buttonMarkup);
}
else
{
await _telegramService.SendTextAsync(content, buttonMarkup);
}
}
if (allTags > limitedCount)
{
await _telegramService.SendTextAsync("Due performance reason, we limit 5 batch call tags");
}
Log.Information("Find Tags completed in {0}", sw.Elapsed);
sw.Stop();
}
private void ProcessingMessage()
{
}
}
} | 34.252336 | 119 | 0.565894 | [
"MIT"
] | WinTenDev/WinTenBot.NET | src/WinTenDev.Zizi.Host/Handlers/Commands/Tags/FindTagCommand.cs | 3,665 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "Data", menuName = "ScriptableObjects/BandMemberScriptableObject", order = 1)]
public class BandMemberScriptableObject : ScriptableObject
{
public MemberType memberType;
public StatBoosts statBoosts;
public AnimationFrames frames;
}
public enum MemberType { Vocalist, Guitarist, Bassist, Drummer };
[System.Serializable]
public struct StatBoosts
{
public bool talent;
public bool technical;
public bool finesse;
public bool hardiness;
}
[System.Serializable]
public struct AnimationFrames
{
public Sprite[] idle;
public Sprite[] walkUp;
public Sprite[] walkHorizontal;
public Sprite[] walkDown;
public Sprite[] GetFramesFromIndex(int index)
{
switch (index)
{
case 0:
return idle;
case 1:
return walkUp;
case 2:
return walkHorizontal;
case 3:
return walkDown;
default:
return null;
}
}
} | 22.098039 | 106 | 0.631766 | [
"MIT"
] | Quickkrueger/Weekly-Game-Jam-211 | Assets/Scripts/Characters/BandMembers/BandMemberScriptableObject.cs | 1,129 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ------------------------------------------------------------
namespace Microsoft.Azure.Cosmos.Query.Core.Pipeline.Distinct
{
using System;
using System.Collections.Generic;
using Microsoft.Azure.Cosmos.Core.Utf8;
using Microsoft.Azure.Cosmos.CosmosElements;
using Microsoft.Azure.Cosmos.CosmosElements.Numbers;
using Microsoft.Azure.Cosmos.Json;
internal static class DistinctHash
{
private static readonly UInt128 RootHashSeed = UInt128.Create(0xbfc2359eafc0e2b7, 0x8846e00284c4cf1f);
public static UInt128 GetHash(CosmosElement cosmosElement)
{
return GetHash(cosmosElement, RootHashSeed);
}
private static UInt128 GetHash(CosmosElement cosmosElement, UInt128 seed)
{
if (cosmosElement == null)
{
return GetUndefinedHash(seed);
}
return cosmosElement.Accept(CosmosElementHasher.Singleton, seed);
}
private static UInt128 GetUndefinedHash(UInt128 seed)
{
return seed;
}
private sealed class CosmosElementHasher : ICosmosElementVisitor<UInt128, UInt128>
{
public static readonly CosmosElementHasher Singleton = new CosmosElementHasher();
private static class HashSeeds
{
public static readonly UInt128 Null = UInt128.Create(0x1380f68bb3b0cfe4, 0x156c918bf564ee48);
public static readonly UInt128 False = UInt128.Create(0xc1be517fe893b40c, 0xe9fc8a4c531cd0dd);
public static readonly UInt128 True = UInt128.Create(0xf86d4abf9a412e74, 0x788488365c8a985d);
public static readonly UInt128 String = UInt128.Create(0x61f53f0a44204cfb, 0x09481be8ef4b56dd);
public static readonly UInt128 Array = UInt128.Create(0xfa573b014c4dc18e, 0xa014512c858eb115);
public static readonly UInt128 Object = UInt128.Create(0x77b285ac511aef30, 0x3dcf187245822449);
public static readonly UInt128 ArrayIndex = UInt128.Create(0xfe057204216db999, 0x5b1cc3178bd9c593);
public static readonly UInt128 PropertyName = UInt128.Create(0xc915dde058492a8a, 0x7c8be2eba72e4634);
public static readonly UInt128 Binary = UInt128.Create(0x54841d59fe1ea46c, 0xd4edb0ba5c59766b);
public static readonly UInt128 Guid = UInt128.Create(0x53b5b8939b790f4b, 0x7cc5e09441fd6cb1);
}
private static class RootCache
{
public static readonly UInt128 Null = MurmurHash3.Hash128(HashSeeds.Null, RootHashSeed);
public static readonly UInt128 False = MurmurHash3.Hash128(HashSeeds.False, RootHashSeed);
public static readonly UInt128 True = MurmurHash3.Hash128(HashSeeds.True, RootHashSeed);
public static readonly UInt128 String = MurmurHash3.Hash128(HashSeeds.String, RootHashSeed);
public static readonly UInt128 Array = MurmurHash3.Hash128(HashSeeds.Array, RootHashSeed);
public static readonly UInt128 Object = MurmurHash3.Hash128(HashSeeds.Object, RootHashSeed);
public static readonly UInt128 Binary = MurmurHash3.Hash128(HashSeeds.Binary, RootHashSeed);
public static readonly UInt128 Guid = MurmurHash3.Hash128(HashSeeds.Guid, RootHashSeed);
}
private CosmosElementHasher()
{
// Private constructor, since this is a singleton class.
}
public UInt128 Visit(CosmosArray cosmosArray, UInt128 seed)
{
// Start the array with a distinct hash, so that empty array doesn't hash to another value.
UInt128 hash = seed == RootHashSeed ? RootCache.Array : MurmurHash3.Hash128(HashSeeds.Array, seed);
// Incorporate all the array items into the hash.
for (int index = 0; index < cosmosArray.Count; index++)
{
CosmosElement arrayItem = cosmosArray[index];
// Order of array items matter in equality check, so we add the index just to be safe.
// For now we know that murmurhash will correctly give a different hash for
// [true, false, true] and [true, true, false]
// due to the way the seed works.
// But we add the index just incase that property does not hold in the future.
UInt128 arrayItemSeed = HashSeeds.ArrayIndex + index;
hash = MurmurHash3.Hash128(arrayItem.Accept(this, arrayItemSeed), hash);
}
return hash;
}
public UInt128 Visit(CosmosBinary cosmosBinary, UInt128 seed)
{
// Hash with binary seed to differntiate between empty binary and no binary.
UInt128 hash = seed == RootHashSeed ? RootCache.Binary : MurmurHash3.Hash128(HashSeeds.Binary, seed);
hash = MurmurHash3.Hash128(cosmosBinary.Value.Span, hash);
return hash;
}
public UInt128 Visit(CosmosBoolean cosmosBoolean, UInt128 seed)
{
if (seed == RootHashSeed)
{
return cosmosBoolean.Value ? RootCache.True : RootCache.False;
}
return MurmurHash3.Hash128(
cosmosBoolean.Value ? HashSeeds.True : HashSeeds.False,
seed);
}
public UInt128 Visit(CosmosGuid cosmosGuid, UInt128 seed)
{
UInt128 hash = seed == RootHashSeed ? RootCache.Guid : MurmurHash3.Hash128(HashSeeds.Guid, seed);
hash = MurmurHash3.Hash128(cosmosGuid.Value.ToByteArray(), hash);
return hash;
}
public UInt128 Visit(CosmosNull cosmosNull, UInt128 seed)
{
if (seed == RootHashSeed)
{
return RootCache.Null;
}
return MurmurHash3.Hash128(HashSeeds.Null, seed);
}
public UInt128 Visit(CosmosNumber cosmosNumber, UInt128 seed)
{
return cosmosNumber.Accept(CosmosNumberHasher.Singleton, seed);
}
public UInt128 Visit(CosmosObject cosmosObject, UInt128 seed)
{
// Start the object with a distinct hash, so that empty object doesn't hash to another value.
UInt128 hash = seed == RootHashSeed ? RootCache.Object : MurmurHash3.Hash128(HashSeeds.Object, seed);
//// Intermediate hashes of all the properties, which we don't want to xor with the final hash
//// otherwise the following will collide:
////{
//// "pet":{
//// "name":"alice",
//// "age":5
//// },
//// "pet2":{
//// "name":"alice",
//// "age":5
//// }
////}
////
////{
//// "pet":{
//// "name":"bob",
//// "age":5
//// },
//// "pet2":{
//// "name":"bob",
//// "age":5
//// }
////}
//// because they only differ on the name, but it gets repeated meaning that
//// hash({"name":"bob", "age":5}) ^ hash({"name":"bob", "age":5}) is the same as
//// hash({"name":"alice", "age":5}) ^ hash({"name":"alice", "age":5})
UInt128 intermediateHash = 0;
// Property order should not result in a different hash.
// This is consistent with equality comparison.
foreach (KeyValuePair<string, CosmosElement> kvp in cosmosObject)
{
UInt128 nameHash = MurmurHash3.Hash128(kvp.Key, MurmurHash3.Hash128(HashSeeds.String, HashSeeds.PropertyName));
UInt128 propertyHash = kvp.Value.Accept(this, nameHash);
//// xor is symmetric meaning that a ^ b = b ^ a
//// Which is great since now we can add the property hashes to the intermediate hash
//// in any order and get the same result, which upholds our definition of equality.
//// Note that we don't have to worry about a ^ a = 0 = b ^ b for duplicate property values,
//// since the hash of property values are seeded with the hash of property names,
//// which are unique within an object.
intermediateHash ^= propertyHash;
}
// Only if the object was not empty do we want to bring in the intermediate hash.
if (intermediateHash > 0)
{
hash = MurmurHash3.Hash128(intermediateHash, hash);
}
return hash;
}
public UInt128 Visit(CosmosString cosmosString, UInt128 seed)
{
UInt128 hash = seed == RootHashSeed ? RootCache.String : MurmurHash3.Hash128(HashSeeds.String, seed);
UtfAnyString utfAnyString = cosmosString.Value;
hash = utfAnyString.IsUtf8
? MurmurHash3.Hash128(utfAnyString.ToUtf8String().Span.Span, hash)
: MurmurHash3.Hash128(utfAnyString.ToString(), hash);
return hash;
}
}
private sealed class CosmosNumberHasher : ICosmosNumberVisitor<UInt128, UInt128>
{
public static readonly CosmosNumberHasher Singleton = new CosmosNumberHasher();
public static class HashSeeds
{
public static readonly UInt128 Number64 = UInt128.Create(0x2400e8b894ce9c2a, 0x790be1eabd7b9481);
public static readonly UInt128 Float32 = UInt128.Create(0x881c51c28fb61016, 0x1decd039cd24bd4b);
public static readonly UInt128 Float64 = UInt128.Create(0x62fb48cc659963a0, 0xe9e690779309c403);
public static readonly UInt128 Int8 = UInt128.Create(0x0007978411626daa, 0x89933677a85444b7);
public static readonly UInt128 Int16 = UInt128.Create(0xe7a19001d3211c09, 0x33e0ba9fb8bc7940);
public static readonly UInt128 Int32 = UInt128.Create(0x0320dc908e0d3e71, 0xf575de218f09ffa5);
public static readonly UInt128 Int64 = UInt128.Create(0xed93baf7fdc76638, 0x0d5733c37e079869);
public static readonly UInt128 UInt32 = UInt128.Create(0x78c441a2d2e9bb6e, 0xac88cb880ccda71d);
}
public static class RootCache
{
public static readonly UInt128 Number64 = MurmurHash3.Hash128(HashSeeds.Number64, RootHashSeed);
public static readonly UInt128 Float32 = MurmurHash3.Hash128(HashSeeds.Float32, RootHashSeed);
public static readonly UInt128 Float64 = MurmurHash3.Hash128(HashSeeds.Float64, RootHashSeed);
public static readonly UInt128 Int8 = MurmurHash3.Hash128(HashSeeds.Int8, RootHashSeed);
public static readonly UInt128 Int16 = MurmurHash3.Hash128(HashSeeds.Int16, RootHashSeed);
public static readonly UInt128 Int32 = MurmurHash3.Hash128(HashSeeds.Int32, RootHashSeed);
public static readonly UInt128 Int64 = MurmurHash3.Hash128(HashSeeds.Int64, RootHashSeed);
public static readonly UInt128 UInt32 = MurmurHash3.Hash128(HashSeeds.UInt32, RootHashSeed);
}
private CosmosNumberHasher()
{
// Private constructor, since this class is a singleton.
}
public UInt128 Visit(CosmosFloat32 cosmosFloat32, UInt128 seed)
{
UInt128 hash = seed == RootHashSeed ? RootCache.Float32 : MurmurHash3.Hash128(HashSeeds.Float32, seed);
float value = cosmosFloat32.GetValue();
// Normalize 0.0f and -0.0f value
// https://stackoverflow.com/questions/3139538/is-minus-zero-0-equivalent-to-zero-0-in-c-sharp
if (value == 0.0f)
{
value = 0;
}
hash = MurmurHash3.Hash128((UInt128)BitConverter.DoubleToInt64Bits(value), hash);
return hash;
}
public UInt128 Visit(CosmosFloat64 cosmosFloat64, UInt128 seed)
{
UInt128 hash = seed == RootHashSeed ? RootCache.Float64 : MurmurHash3.Hash128(HashSeeds.Float64, seed);
double value = cosmosFloat64.GetValue();
// Normalize 0.0 and -0.0 value
// https://stackoverflow.com/questions/3139538/is-minus-zero-0-equivalent-to-zero-0-in-c-sharp
if (value == 0.0)
{
value = 0;
}
hash = MurmurHash3.Hash128((UInt128)BitConverter.DoubleToInt64Bits(value), hash);
return hash;
}
public UInt128 Visit(CosmosInt16 cosmosInt16, UInt128 seed)
{
UInt128 hash = seed == RootHashSeed ? RootCache.Int16 : MurmurHash3.Hash128(HashSeeds.Int16, seed);
short value = cosmosInt16.GetValue();
hash = MurmurHash3.Hash128(value, hash);
return hash;
}
public UInt128 Visit(CosmosInt32 cosmosInt32, UInt128 seed)
{
UInt128 hash = seed == RootHashSeed ? RootCache.Int32 : MurmurHash3.Hash128(HashSeeds.Int32, seed);
int value = cosmosInt32.GetValue();
hash = MurmurHash3.Hash128(value, hash);
return hash;
}
public UInt128 Visit(CosmosInt64 cosmosInt64, UInt128 seed)
{
UInt128 hash = seed == RootHashSeed ? RootCache.Int64 : MurmurHash3.Hash128(HashSeeds.Int64, seed);
long value = cosmosInt64.GetValue();
hash = MurmurHash3.Hash128(value, hash);
return hash;
}
public UInt128 Visit(CosmosInt8 cosmosInt8, UInt128 seed)
{
UInt128 hash = seed == RootHashSeed ? RootCache.Int8 : MurmurHash3.Hash128(HashSeeds.Int8, seed);
sbyte value = cosmosInt8.GetValue();
hash = MurmurHash3.Hash128(value, hash);
return hash;
}
public UInt128 Visit(CosmosNumber64 cosmosNumber64, UInt128 seed)
{
UInt128 hash = seed == RootHashSeed ? RootCache.Number64 : MurmurHash3.Hash128(HashSeeds.Number64, seed);
Number64 value = cosmosNumber64.GetValue();
Number64.DoubleEx doubleExValue = Number64.ToDoubleEx(value);
return MurmurHash3.Hash128(doubleExValue, hash);
}
public UInt128 Visit(CosmosUInt32 cosmosUInt32, UInt128 seed)
{
UInt128 hash = seed == RootHashSeed ? RootCache.UInt32 : MurmurHash3.Hash128(HashSeeds.UInt32, seed);
uint value = cosmosUInt32.GetValue();
hash = MurmurHash3.Hash128(value, hash);
return hash;
}
}
}
}
| 48.670807 | 131 | 0.57574 | [
"MIT"
] | Arithmomaniac/azure-cosmos-dotnet-v3 | Microsoft.Azure.Cosmos/src/Query/Core/Pipeline/Distinct/DistinctHash.cs | 15,674 | C# |
namespace MoviesLibrary.Web.ViewModels.Account
{
public class FactorViewModel
{
public string Purpose { get; set; }
}
}
| 17.625 | 47 | 0.659574 | [
"MIT"
] | MystFan/Movies-Library | Source/MoviesLibrarySystem/Web/MoviesLibrary.Web.ViewModels/Account/FactorViewModel.cs | 143 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kernel.Module.Test.Common.Interfaces;
namespace Kernel.Module.TestModule2
{
public class MyInterfacedClassByInterfaceInheritence : IMyModuleInterfaceByInheritence
{
private string _last;
public string ToLower(string str)
{
_last =str.ToLower();
return _last;
}
public string Last
{
get { return _last; }
}
}
}
| 20.769231 | 90 | 0.642593 | [
"BSD-2-Clause"
] | KernelNO/Kernel.Module | Kernel.Module/Kernel.Module.TestModule2/MyInterfacedClassByInterfaceInheritence.cs | 542 | 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("Toolbelt.Selenium.Samples.NUnit")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Toolbelt.Selenium.Samples.NUnit")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bcab007e-6d4e-4114-bf31-ae127dae99bc")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.783784 | 84 | 0.747735 | [
"MIT"
] | MikeHanson/toolbelt.selenium | Toolbelt.Selenium.Samples.NUnit/Properties/AssemblyInfo.cs | 1,438 | C# |
using System;
using System.IO;
using System.Net;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Logging;
using Moq;
using Stratis.Bitcoin.Tests.Common.Logging;
using Xunit;
namespace Stratis.Bitcoin.Features.RPC.Tests
{
public class RPCMiddlewareTest : LogsTestBase
{
private Mock<IRPCAuthorization> authorization;
private Mock<RequestDelegate> delegateContext;
private DefaultHttpContext httpContext;
private RPCMiddleware middleware;
private HttpResponseFeature response;
private FeatureCollection featureCollection;
private HttpRequestFeature request;
public RPCMiddlewareTest()
{
this.httpContext = new DefaultHttpContext();
this.authorization = new Mock<IRPCAuthorization>();
this.delegateContext = new Mock<RequestDelegate>();
this.httpContext = new DefaultHttpContext();
this.response = new HttpResponseFeature();
this.request = new HttpRequestFeature();
this.response.Body = new MemoryStream();
this.featureCollection = new FeatureCollection();
this.middleware = new RPCMiddleware(this.delegateContext.Object, this.authorization.Object, this.LoggerFactory.Object);
}
[Fact]
public void InvokeValidAuthorizationReturns200()
{
this.SetupValidAuthorization();
this.InitializeFeatureContext();
this.middleware.InvokeAsync(this.httpContext).Wait();
Assert.Equal(StatusCodes.Status200OK, this.httpContext.Response.StatusCode);
}
[Fact]
public void InvokeUnauthorizedReturns401()
{
this.InitializeFeatureContext();
this.authorization.Setup(a => a.IsAuthorized(It.IsAny<IPAddress>()))
.Returns(false);
this.middleware.InvokeAsync(this.httpContext).Wait();
Assert.Equal(StatusCodes.Status401Unauthorized, this.httpContext.Response.StatusCode);
}
[Fact]
public void InvokeAuthorizedWithoutAuthorizationHeaderReturns401()
{
this.InitializeFeatureContext();
this.authorization.Setup(a => a.IsAuthorized(It.IsAny<IPAddress>()))
.Returns(true);
this.middleware.InvokeAsync(this.httpContext).Wait();
Assert.Equal(StatusCodes.Status401Unauthorized, this.httpContext.Response.StatusCode);
}
[Fact]
public void InvokeAuthorizedWithBearerAuthorizationHeaderReturns401()
{
this.request.Headers.Add("Authorization", "Bearer hiuehewuytwe");
this.InitializeFeatureContext();
this.authorization.Setup(a => a.IsAuthorized(It.IsAny<IPAddress>()))
.Returns(true);
this.middleware.InvokeAsync(this.httpContext).Wait();
Assert.Equal(StatusCodes.Status401Unauthorized, this.httpContext.Response.StatusCode);
}
[Fact]
public void InvokeAuthorizedWithEmptyAuthorizationHeaderReturns401()
{
this.request.Headers.Add("Authorization", "");
this.InitializeFeatureContext();
this.authorization.Setup(a => a.IsAuthorized(It.IsAny<IPAddress>()))
.Returns(true);
this.middleware.InvokeAsync(this.httpContext).Wait();
Assert.Equal(StatusCodes.Status401Unauthorized, this.httpContext.Response.StatusCode);
}
[Fact]
public void InvokeAuthorizedWithBasicAuthorizationHeaderForUnauthorizedUserReturns401()
{
var header = Convert.ToBase64String(Encoding.ASCII.GetBytes("MyUser"));
this.request.Headers.Add("Authorization", "Basic " + header);
this.InitializeFeatureContext();
this.authorization.Setup(a => a.IsAuthorized(It.IsAny<IPAddress>()))
.Returns(true);
this.authorization.Setup(a => a.IsAuthorized("MyUser"))
.Returns(false);
this.middleware.InvokeAsync(this.httpContext).Wait();
Assert.Equal(StatusCodes.Status401Unauthorized, this.httpContext.Response.StatusCode);
}
[Fact]
public void InvokeAuthorizedWithBasicAuthorizationHeaderWithInvalidEncodingReturns401()
{
this.request.Headers.Add("Authorization", "Basic kljseuhtiuorewytiuoer");
this.InitializeFeatureContext();
this.authorization.Setup(a => a.IsAuthorized(It.IsAny<IPAddress>()))
.Returns(true);
this.middleware.InvokeAsync(this.httpContext).Wait();
Assert.Equal(StatusCodes.Status401Unauthorized, this.httpContext.Response.StatusCode);
}
[Fact]
public void InvokeThrowsArgumentExceptionWritesArgumentError()
{
this.delegateContext.Setup(d => d(It.IsAny<DefaultHttpContext>()))
.Throws(new ArgumentException("Name is required."));
this.SetupValidAuthorization();
this.InitializeFeatureContext();
this.middleware.InvokeAsync(this.httpContext).Wait();
this.httpContext.Response.Body.Position = 0;
using (var reader = new StreamReader(this.httpContext.Response.Body))
{
var expected = string.Format("{{{0} \"result\": null,{0} \"error\": {{{0} \"code\": -1,{0} \"message\": \"Argument error: Name is required.\"{0} }}{0}}}", Environment.NewLine);
Assert.Equal(expected, reader.ReadToEnd());
Assert.Equal(StatusCodes.Status200OK, this.httpContext.Response.StatusCode);
}
}
[Fact]
public void InvokeThrowsFormatExceptionWritesArgumentError()
{
this.delegateContext.Setup(d => d(It.IsAny<DefaultHttpContext>()))
.Throws(new FormatException("Int x is invalid format."));
this.SetupValidAuthorization();
this.InitializeFeatureContext();
this.middleware.InvokeAsync(this.httpContext).Wait();
this.httpContext.Response.Body.Position = 0;
using (var reader = new StreamReader(this.httpContext.Response.Body))
{
var expected = string.Format("{{{0} \"result\": null,{0} \"error\": {{{0} \"code\": -1,{0} \"message\": \"Argument error: Int x is invalid format.\"{0} }}{0}}}", Environment.NewLine);
Assert.Equal(expected, reader.ReadToEnd());
Assert.Equal(StatusCodes.Status200OK, this.httpContext.Response.StatusCode);
}
}
[Fact]
public void Invoke404WritesMethodNotFoundError()
{
this.response.StatusCode = StatusCodes.Status404NotFound;
this.SetupValidAuthorization();
this.InitializeFeatureContext();
this.middleware.InvokeAsync(this.httpContext).Wait();
this.httpContext.Response.Body.Position = 0;
using (var reader = new StreamReader(this.httpContext.Response.Body))
{
var expected = string.Format("{{{0} \"result\": null,{0} \"error\": {{{0} \"code\": -32601,{0} \"message\": \"Method not found\"{0} }}{0}}}", Environment.NewLine);
Assert.Equal(expected, reader.ReadToEnd());
Assert.Equal(StatusCodes.Status404NotFound, this.httpContext.Response.StatusCode);
}
}
[Fact]
public void Invoke500WritesInternalErrorAndLogsResult()
{
this.response.StatusCode = StatusCodes.Status500InternalServerError;
this.SetupValidAuthorization();
this.InitializeFeatureContext();
this.middleware.InvokeAsync(this.httpContext).Wait();
this.httpContext.Response.Body.Position = 0;
using (var reader = new StreamReader(this.httpContext.Response.Body))
{
var expected = string.Format("{{{0} \"result\": null,{0} \"error\": {{{0} \"code\": -32603,{0} \"message\": \"Internal error\"{0} }}{0}}}", Environment.NewLine);
Assert.Equal(expected, reader.ReadToEnd());
Assert.Equal(StatusCodes.Status500InternalServerError, this.httpContext.Response.StatusCode);
this.AssertLog(this.Logger, LogLevel.Error, "Internal error while calling RPC Method");
}
}
[Fact]
public void InvokeThrowsUnhandledExceptionWritesInternalErrorAndLogsResult()
{
this.delegateContext.Setup(d => d(It.IsAny<DefaultHttpContext>()))
.Throws(new InvalidOperationException("Operation not valid."));
this.SetupValidAuthorization();
this.InitializeFeatureContext();
this.middleware.InvokeAsync(this.httpContext).Wait();
this.httpContext.Response.Body.Position = 0;
using (var reader = new StreamReader(this.httpContext.Response.Body))
{
var expected = string.Format("{{{0} \"result\": null,{0} \"error\": {{{0} \"code\": -32603,{0} \"message\": \"Internal error\"{0} }}{0}}}", Environment.NewLine);
Assert.Equal(expected, reader.ReadToEnd());
Assert.Equal(StatusCodes.Status200OK, this.httpContext.Response.StatusCode);
this.AssertLog<InvalidOperationException>(this.Logger, LogLevel.Error, "Operation not valid.", "Internal error while calling RPC Method");
}
}
private void SetupValidAuthorization()
{
var header = Convert.ToBase64String(Encoding.ASCII.GetBytes("MyUser"));
this.request.Headers.Add("Authorization", "Basic " + header);
this.authorization.Setup(a => a.IsAuthorized(It.IsAny<IPAddress>()))
.Returns(true);
this.authorization.Setup(a => a.IsAuthorized("MyUser"))
.Returns(true);
}
private void InitializeFeatureContext()
{
this.featureCollection.Set<IHttpRequestFeature>(this.request);
this.featureCollection.Set<IHttpResponseFeature>(this.response);
this.httpContext.Initialize(this.featureCollection);
}
}
}
| 42.652893 | 208 | 0.623619 | [
"MIT"
] | BreezeHub/StratisBitcoinFullNode | src/Stratis.Bitcoin.Features.RPC.Tests/RPCMiddlewareTest.cs | 10,324 | C# |
// ***********************************************************************
// Copyright (c) 2009 Charlie Poole
//
// 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.
// ***********************************************************************
#define PORTABLE
#define TIZEN
#define NUNIT_FRAMEWORK
#define NUNITLITE
#define NET_4_5
#define PARALLEL
using System;
using System.Collections.Generic;
namespace NUnit.Framework
{
/// <summary>
/// Used to mark a field, property or method providing a set of datapoints to
/// be used in executing any theories within the same fixture that require an
/// argument of the Type provided. The data source may provide an array of
/// the required Type or an <see cref="IEnumerable{T}"/>.
/// Synonymous with DatapointSourceAttribute.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class DatapointsAttribute : DatapointSourceAttribute
{
}
}
| 44.826087 | 139 | 0.696411 | [
"Apache-2.0",
"MIT"
] | AchoWang/TizenFX | test/Tizen.NUI.Tests/nunit.framework/Attributes/DatapointsAttribute.cs | 2,064 | C# |
//namespace Dna.Center.Service.Cqrs.Infra.Impl.EventPublishing
//{
// using System;
// using Castle.Core.Logging;
// using Messaging.RabbitMq.Api.Models;
// using Properties;
// using Service.Services;
// using Smi.Infra.EventPublishing;
// public class Publisher : IPublisher
// {
// private readonly IMessagingClientProvider messagingClientProvider;
// private readonly ILoggingService logger;
// private readonly bool IsEnable;
// public Publisher(IMessagingClientProvider messagingClientProvider, ILoggingService logger)
// {
// this.messagingClientProvider = messagingClientProvider;
// this.logger = logger;
// this.IsEnable = Settings.Default.DnaMessagePublishingEnable;
// if (IsEnable == false)
// {
// logger.LogAppStart("Publisher Ctor - Dna message publishing is not enabled");
// }
// }
// public void Publish(string topic, object @event)
// {
// if (IsEnable == false)
// {
// logger.LogInfoFormat("Dna message publishing is not enabled - Message not sent for topic : {0}", topic);
// return;
// }
// var messagingClient = messagingClientProvider.GetInstance();
// try
// {
// var message = new Message(topic, @event);
// message.Headers.Add(StandardHeaders.Domain, "Dna");
// message.Headers.Add(StandardHeaders.From, "Dna.Center");
// messagingClient.ProduceOnStandardExchange(message);
// }
// catch (Exception)
// {
// try
// {
// messagingClient.Dispose();
// }
// catch
// { // We don't want to throw the unable to dispose exception
// }
// throw;
// }
// }
// }
//} | 26.566667 | 110 | 0.667503 | [
"MIT"
] | gadjio/Smi-Playground | src/Smi.Infra/Impl/EventPublishing/Publisher.cs | 1,596 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.ServiceFabric.V20190601Preview.Inputs
{
/// <summary>
/// Defines a health policy used to evaluate the health of the cluster or of a cluster node.
/// </summary>
public sealed class ClusterHealthPolicyArgs : Pulumi.ResourceArgs
{
[Input("applicationHealthPolicies")]
private InputMap<Inputs.ApplicationHealthPolicyArgs>? _applicationHealthPolicies;
/// <summary>
/// Defines the application health policy map used to evaluate the health of an application or one of its children entities.
/// </summary>
public InputMap<Inputs.ApplicationHealthPolicyArgs> ApplicationHealthPolicies
{
get => _applicationHealthPolicies ?? (_applicationHealthPolicies = new InputMap<Inputs.ApplicationHealthPolicyArgs>());
set => _applicationHealthPolicies = value;
}
/// <summary>
/// The maximum allowed percentage of unhealthy applications before reporting an error. For example, to allow 10% of applications to be unhealthy, this value would be 10.
///
/// The percentage represents the maximum tolerated percentage of applications that can be unhealthy before the cluster is considered in error.
/// If the percentage is respected but there is at least one unhealthy application, the health is evaluated as Warning.
/// This is calculated by dividing the number of unhealthy applications over the total number of application instances in the cluster, excluding applications of application types that are included in the ApplicationTypeHealthPolicyMap.
/// The computation rounds up to tolerate one failure on small numbers of applications. Default percentage is zero.
/// </summary>
[Input("maxPercentUnhealthyApplications")]
public Input<int>? MaxPercentUnhealthyApplications { get; set; }
/// <summary>
/// The maximum allowed percentage of unhealthy nodes before reporting an error. For example, to allow 10% of nodes to be unhealthy, this value would be 10.
///
/// The percentage represents the maximum tolerated percentage of nodes that can be unhealthy before the cluster is considered in error.
/// If the percentage is respected but there is at least one unhealthy node, the health is evaluated as Warning.
/// The percentage is calculated by dividing the number of unhealthy nodes over the total number of nodes in the cluster.
/// The computation rounds up to tolerate one failure on small numbers of nodes. Default percentage is zero.
///
/// In large clusters, some nodes will always be down or out for repairs, so this percentage should be configured to tolerate that.
/// </summary>
[Input("maxPercentUnhealthyNodes")]
public Input<int>? MaxPercentUnhealthyNodes { get; set; }
public ClusterHealthPolicyArgs()
{
MaxPercentUnhealthyApplications = 0;
MaxPercentUnhealthyNodes = 0;
}
}
}
| 55.04918 | 243 | 0.707862 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/ServiceFabric/V20190601Preview/Inputs/ClusterHealthPolicyArgs.cs | 3,358 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace aws
{
[JsiiInterface(nativeType: typeof(IWafv2WebAclRuleStatementOrStatementStatementNotStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchMethod), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementOrStatementStatementNotStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchMethod")]
public interface IWafv2WebAclRuleStatementOrStatementStatementNotStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchMethod
{
[JsiiTypeProxy(nativeType: typeof(IWafv2WebAclRuleStatementOrStatementStatementNotStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchMethod), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementOrStatementStatementNotStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchMethod")]
internal sealed class _Proxy : DeputyBase, aws.IWafv2WebAclRuleStatementOrStatementStatementNotStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchMethod
{
private _Proxy(ByRefValue reference): base(reference)
{
}
}
}
}
| 58.9 | 316 | 0.85399 | [
"MIT"
] | scottenriquez/cdktf-alpha-csharp-testing | resources/.gen/aws/aws/IWafv2WebAclRuleStatementOrStatementStatementNotStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchMethod.cs | 1,178 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
using Nethereum.ABI.FunctionEncoding.Attributes;
using Nethereum.Hex.HexTypes;
namespace Nethereum.BlockchainStore.Search
{
public class FunctionIndexDefinition<TFunction> :
IndexDefinition<TFunction> where TFunction : class
{
public FunctionIndexDefinition(string indexName = null, bool addPresetTransactionFields = true):
base(indexName, addPresetTransactionFields)
{
var eventType = typeof(TFunction);
var functionAttribute = eventType.GetCustomAttribute<FunctionAttribute>();
var searchable = eventType.GetCustomAttribute<SearchIndex>();
IndexName = indexName ?? searchable?.Name ?? functionAttribute?.Name ?? eventType.Name;
}
protected override void LoadGenericBlockchainFields(Dictionary<string, SearchField> fields)
{
AddField(fields, PresetSearchFieldName.tx_uid, f =>
{
f.DataType = typeof(string);
f.IsKey = true;
f.IsSortable = true;
f.IsSearchable = true;
f.TxValueCallback = (tx) =>
$"{tx.BlockNumber.Value}_{tx.Transaction.TransactionIndex.Value}";
});
AddField(fields, PresetSearchFieldName.tx_hash, f =>
{
f.DataType = typeof(string);
f.IsSearchable = true;
f.IsFilterable = true;
f.IsSortable = true;
f.TxValueCallback = (tx) => tx.TransactionHash;
});
AddField(fields, PresetSearchFieldName.tx_index, f =>
{
f.DataType = typeof(HexBigInteger);
f.IsSortable = true;
f.IsFilterable = false;
f.TxValueCallback = (tx) => tx.Transaction.TransactionIndex;
});
AddField(fields, PresetSearchFieldName.tx_block_hash, f =>
{
f.DataType = typeof(string);
f.TxValueCallback = (tx) => tx.Transaction.BlockHash;
});
AddField(fields, PresetSearchFieldName.tx_block_number, f =>
{
f.DataType = typeof(HexBigInteger);
f.IsSearchable = true;
f.IsSortable = true;
f.IsFilterable = true;
f.IsFacetable = true;
f.TxValueCallback = (tx) => tx.Transaction.BlockNumber;
f.IsSuggester = true;
});
AddField(fields, PresetSearchFieldName.tx_block_timestamp, f =>
{
f.DataType = typeof(HexBigInteger);
f.IsSortable = true;
f.TxValueCallback = (tx) => tx.BlockTimestamp;
});
AddField(fields, PresetSearchFieldName.tx_value, f =>
{
f.DataType = typeof(HexBigInteger);
f.IsSortable = true;
f.TxValueCallback = (tx) => tx.Transaction.Value;
});
AddField(fields, PresetSearchFieldName.tx_from, f =>
{
f.DataType = typeof(string);
f.IsSearchable = true;
f.IsSortable = true;
f.IsFilterable = true;
f.IsFacetable = true;
f.TxValueCallback = (tx) => tx.Transaction.From?.ToLower();
});
AddField(fields, PresetSearchFieldName.tx_to, f =>
{
f.DataType = typeof(string);
f.IsSearchable = true;
f.IsSortable = true;
f.IsFilterable = true;
f.IsFacetable = true;
f.TxValueCallback = (tx) => tx.Transaction.To?.ToLower();
});
AddField(fields, PresetSearchFieldName.tx_gas, f =>
{
f.DataType = typeof(HexBigInteger);
f.IsSortable = true;
f.TxValueCallback = (tx) => tx.Transaction.Gas;
});
AddField(fields, PresetSearchFieldName.tx_gas_price, f =>
{
f.DataType = typeof(HexBigInteger);
f.IsSortable = true;
f.TxValueCallback = (tx) => tx.Transaction.GasPrice;
});
AddField(fields, PresetSearchFieldName.tx_input, f =>
{
f.DataType = typeof(string);
f.TxValueCallback = (tx) => tx.Transaction.Input;
});
AddField(fields, PresetSearchFieldName.tx_nonce, f =>
{
f.DataType = typeof(HexBigInteger);
f.IsSearchable = true;
f.IsSortable = true;
f.IsFilterable = true;
f.TxValueCallback = (tx) => tx.Transaction.Nonce;
});
}
}
} | 35.904412 | 104 | 0.522425 | [
"MIT"
] | ConsenSys/Nethereum.BlockchainProcessing | Storage/Nethereum.BlockchainStore.Search/FunctionIndexDefinition.cs | 4,885 | C# |
namespace MassTransit.Azure.ServiceBus.Core.Configuration
{
using System;
using System.Collections.Generic;
using Configurators;
using Registration;
public class ServiceBusRegistrationBusFactory :
TransportRegistrationBusFactory<IServiceBusReceiveEndpointConfigurator>
{
readonly ServiceBusBusConfiguration _busConfiguration;
readonly Action<IBusRegistrationContext, IServiceBusBusFactoryConfigurator> _configure;
public ServiceBusRegistrationBusFactory(Action<IBusRegistrationContext, IServiceBusBusFactoryConfigurator> configure)
: this(new ServiceBusBusConfiguration(new ServiceBusTopologyConfiguration(AzureBusFactory.MessageTopology)), configure)
{
}
ServiceBusRegistrationBusFactory(ServiceBusBusConfiguration busConfiguration,
Action<IBusRegistrationContext, IServiceBusBusFactoryConfigurator> configure)
: base(busConfiguration.HostConfiguration)
{
_configure = configure;
_busConfiguration = busConfiguration;
}
public override IBusInstance CreateBus(IBusRegistrationContext context, IEnumerable<IBusInstanceSpecification> specifications)
{
var configurator = new ServiceBusBusFactoryConfigurator(_busConfiguration);
return CreateBus(configurator, context, _configure, specifications);
}
}
}
| 38.27027 | 134 | 0.747881 | [
"ECL-2.0",
"Apache-2.0"
] | Aerodynamite/MassTrans | src/Transports/MassTransit.Azure.ServiceBus.Core/Configuration/Configuration/ServiceBusRegistrationBusFactory.cs | 1,416 | C# |
//
// @(#) IBackgroundCopyFile3.cs
//
// Project: usis.Net.Bits
// System: Microsoft Visual Studio 2017
// Author: Udo Schäfer
//
// Copyright (c) 2018 usis GmbH. All rights reserved.
using System.Runtime.InteropServices;
namespace usis.Net.Bits.Interop
{
// ------------------------------
// IBackgroundCopyFile3 interface
// ------------------------------
[ComImport]
[Guid(IID.IBackgroundCopyFile3)]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IBackgroundCopyFile3
{
#region IBackgroundCopyFile methods
// --------------------
// GetRemoteName method
// --------------------
[return: MarshalAs(UnmanagedType.LPWStr)]
string GetRemoteName();
// -------------------
// GetLocalName method
// -------------------
[return: MarshalAs(UnmanagedType.LPWStr)]
string GetLocalName();
// ------------------
// GetProgress method
// ------------------
BG_FILE_PROGRESS GetProgress();
#endregion IBackgroundCopyFile methods
#region IBackgroundCopyFile2 methods
// --------------------
// GetFileRanges method
// --------------------
void GetFileRanges(out uint rangeCount, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] out BG_FILE_RANGE[] ranges);
// --------------------
// SetRemoteName method
// --------------------
void SetRemoteName([MarshalAs(UnmanagedType.LPWStr)] string url);
#endregion IBackgroundCopyFile2 methods
// -----------------------
// GetTemporaryName method
// -----------------------
[return: MarshalAs(UnmanagedType.LPWStr)]
string GetTemporaryName();
// -------------------------
// SetValidationState method
// -------------------------
void SetValidationState([MarshalAs(UnmanagedType.Bool)] bool state);
// -------------------------
// GetValidationState method
// -------------------------
[return: MarshalAs(UnmanagedType.Bool)]
bool GetValidationState();
// ---------------------------
// IsDownloadedFromPeer method
// ---------------------------
[return: MarshalAs(UnmanagedType.Bool)]
bool IsDownloadedFromPeer();
}
}
// eof "IBackgroundCopyFile3.cs"
| 27.677419 | 132 | 0.463869 | [
"MIT"
] | usis-software/usis.Net.Bits | Interop/IBackgroundCopyFile3.cs | 2,577 | C# |
using Nixi.Injections;
using System.Collections.ObjectModel;
using UnityEngine.UI;
namespace ScriptExample.Fallen.Enumerables
{
public sealed class FallenEnumerablesReadOnlyCollection : MonoBehaviourInjectable
{
[NixInjectComponents]
public ReadOnlyCollection<Slider> Fallen;
}
} | 25.75 | 85 | 0.773463 | [
"MIT"
] | f-antoine/Nixi | Assets/ScriptExample/Fallen/Enumerables/FallenEnumerablesReadOnlyCollection.cs | 311 | C# |
using Newtonsoft.Json;
namespace PetGameBackend.Models.Requests.User
{
public class UserControllerRootGet
{
/// <summary>
/// GUID of the <see cref="User" /> as string
/// </summary>
[JsonProperty(nameof(UserIdentifier))]
public string UserIdentifier { get; set; }
}
} | 25.076923 | 57 | 0.607362 | [
"MIT"
] | KiaArmani/PetGameBackend | PetGameBackend/Models/Requests/User/UserControllerRootGet.cs | 328 | C# |
namespace Machete.HL7
{
using System;
using System.Runtime.Serialization;
[Serializable]
public class SegmentOutOfRangeException :
MacheteParserException
{
public SegmentOutOfRangeException()
{
}
public SegmentOutOfRangeException(string message)
: base(message)
{
}
#if !NETCORE
protected SegmentOutOfRangeException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
public SegmentOutOfRangeException(string message, Exception innerException)
: base(message, innerException)
{
}
}
} | 21.375 | 94 | 0.615497 | [
"Apache-2.0"
] | AreebaAroosh/Machete | src/Machete.HL7/SegmentOutOfRangeException.cs | 686 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace GameDatabase.Data.Migrations
{
public partial class NewGameColumns : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "DeveloperName",
table: "Games",
type: "nvarchar(max)",
nullable: false,
defaultValue: "");
migrationBuilder.AddColumn<string>(
name: "PublisherName",
table: "Games",
type: "nvarchar(max)",
nullable: false,
defaultValue: "");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "DeveloperName",
table: "Games");
migrationBuilder.DropColumn(
name: "PublisherName",
table: "Games");
}
}
}
| 28.333333 | 71 | 0.522549 | [
"MIT"
] | KonstantinKostenski/GamesDatabase | GameDatabase.Data/Migrations/20210318090914_NewGameColumns.cs | 1,022 | C# |
namespace Engine.Input
{
public enum MouseButton
{
Left,
Middle,
Right,
Button1,
Button2,
Button3,
Button4,
Button5,
Button6,
Button7,
Button8,
Button9,
LastButton
}
}
| 14.25 | 27 | 0.452632 | [
"MIT"
] | chances/UtilityGrid | Engine/Input/MouseButton.cs | 287 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour {
[SerializeField] GameObject deathFX;
[SerializeField] Transform parent;
[SerializeField] int scorePerHit = 12;
ScoreBoard scoreBoard;
private void Start()
{
scoreBoard = FindObjectOfType<ScoreBoard>();
}
private void OnParticleCollision(GameObject other)
{
scoreBoard.ScoreHit(scorePerHit);
GameObject fx = Instantiate(deathFX, transform.position, Quaternion.identity);
fx.transform.parent = parent;
Destroy(gameObject);
}
}
| 22.464286 | 86 | 0.694754 | [
"MIT"
] | Marian25/ArgonAssault | Assets/Scripts/Enemy.cs | 631 | C# |
namespace ResManagement.UserControls
{
partial class HistoryControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(HistoryControl));
this.HeaderLbl = new System.Windows.Forms.Label();
this.objectListView1 = new BrightIdeasSoftware.ObjectListView();
this.olvColumn1 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.olvColumn2 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.olvColumn3 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.olvColumn4 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.olvColumn5 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.domainUpDown1 = new System.Windows.Forms.DomainUpDown();
this.objectListView2 = new BrightIdeasSoftware.ObjectListView();
this.olvColumn8 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.olvColumn9 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.olvColumn10 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.olvColumn11 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.label1 = new System.Windows.Forms.Label();
this.panel1 = new System.Windows.Forms.Panel();
this.activeTableLbl = new System.Windows.Forms.Label();
this.bestSellerLbl = new System.Windows.Forms.Label();
this.mostSoldLbl = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.panel2 = new System.Windows.Forms.Panel();
this.totalIncomeLbl = new System.Windows.Forms.Label();
this.avgOrderLbl = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.objectListView3 = new BrightIdeasSoftware.ObjectListView();
this.olvColumn7 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.olvColumn12 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.olvColumn13 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.objectListView4 = new BrightIdeasSoftware.ObjectListView();
this.olvColumn6 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.olvColumn15 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.olvColumn16 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.pictureBox1 = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.objectListView1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.objectListView2)).BeginInit();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.objectListView3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.objectListView4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// HeaderLbl
//
this.HeaderLbl.BackColor = System.Drawing.Color.Transparent;
this.HeaderLbl.Font = new System.Drawing.Font("", 40F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.HeaderLbl.ForeColor = System.Drawing.SystemColors.Highlight;
this.HeaderLbl.Location = new System.Drawing.Point(273, 120);
this.HeaderLbl.Name = "HeaderLbl";
this.HeaderLbl.Size = new System.Drawing.Size(719, 63);
this.HeaderLbl.TabIndex = 37;
this.HeaderLbl.Text = "Orders List";
this.HeaderLbl.TextAlign = System.Drawing.ContentAlignment.TopCenter;
//
// objectListView1
//
this.objectListView1.AllColumns.Add(this.olvColumn1);
this.objectListView1.AllColumns.Add(this.olvColumn2);
this.objectListView1.AllColumns.Add(this.olvColumn3);
this.objectListView1.AllColumns.Add(this.olvColumn4);
this.objectListView1.AllColumns.Add(this.olvColumn5);
this.objectListView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.olvColumn1,
this.olvColumn2,
this.olvColumn3,
this.olvColumn4,
this.olvColumn5});
this.objectListView1.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F);
this.objectListView1.GridLines = true;
this.objectListView1.Location = new System.Drawing.Point(273, 186);
this.objectListView1.Name = "objectListView1";
this.objectListView1.ShowGroups = false;
this.objectListView1.Size = new System.Drawing.Size(719, 381);
this.objectListView1.TabIndex = 39;
this.objectListView1.UseCompatibleStateImageBehavior = false;
this.objectListView1.View = System.Windows.Forms.View.Details;
//
// olvColumn1
//
this.olvColumn1.AspectName = "TableID";
this.olvColumn1.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn1.Text = "TableID";
this.olvColumn1.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn1.Width = 82;
//
// olvColumn2
//
this.olvColumn2.AspectName = "Employee";
this.olvColumn2.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn2.Text = "Employee";
this.olvColumn2.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn2.Width = 221;
//
// olvColumn3
//
this.olvColumn3.AspectName = "ProductName";
this.olvColumn3.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn3.Text = "Product";
this.olvColumn3.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn3.Width = 205;
//
// olvColumn4
//
this.olvColumn4.AspectName = "Quantity";
this.olvColumn4.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn4.Text = "Quantity";
this.olvColumn4.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn4.Width = 99;
//
// olvColumn5
//
this.olvColumn5.AspectName = "Price";
this.olvColumn5.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn5.Text = "Price";
this.olvColumn5.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn5.Width = 89;
//
// domainUpDown1
//
this.domainUpDown1.Font = new System.Drawing.Font("Microsoft Sans Serif", 14F);
this.domainUpDown1.Location = new System.Drawing.Point(70, 186);
this.domainUpDown1.Name = "domainUpDown1";
this.domainUpDown1.Size = new System.Drawing.Size(143, 29);
this.domainUpDown1.TabIndex = 40;
this.domainUpDown1.Text = "Orders List";
this.domainUpDown1.SelectedItemChanged += new System.EventHandler(this.domainUpDown1_SelectedItemChanged);
//
// objectListView2
//
this.objectListView2.AllColumns.Add(this.olvColumn8);
this.objectListView2.AllColumns.Add(this.olvColumn9);
this.objectListView2.AllColumns.Add(this.olvColumn10);
this.objectListView2.AllColumns.Add(this.olvColumn11);
this.objectListView2.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.olvColumn8,
this.olvColumn9,
this.olvColumn10,
this.olvColumn11});
this.objectListView2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F);
this.objectListView2.GridLines = true;
this.objectListView2.Location = new System.Drawing.Point(273, 186);
this.objectListView2.Name = "objectListView2";
this.objectListView2.ShowGroups = false;
this.objectListView2.Size = new System.Drawing.Size(719, 381);
this.objectListView2.TabIndex = 41;
this.objectListView2.UseCompatibleStateImageBehavior = false;
this.objectListView2.View = System.Windows.Forms.View.Details;
//
// olvColumn8
//
this.olvColumn8.AspectName = "ProductName";
this.olvColumn8.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn8.Text = "Product";
this.olvColumn8.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn8.Width = 205;
//
// olvColumn9
//
this.olvColumn9.AspectName = "Quantity";
this.olvColumn9.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn9.Text = "Quantity";
this.olvColumn9.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn9.Width = 99;
//
// olvColumn10
//
this.olvColumn10.AspectName = "Price";
this.olvColumn10.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn10.Text = "Price";
this.olvColumn10.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn10.Width = 89;
//
// olvColumn11
//
this.olvColumn11.AspectName = "TableID";
this.olvColumn11.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn11.Text = "Sales";
this.olvColumn11.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// label1
//
this.label1.AutoSize = true;
this.label1.BackColor = System.Drawing.Color.Transparent;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 14F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline))));
this.label1.ForeColor = System.Drawing.SystemColors.Highlight;
this.label1.Location = new System.Drawing.Point(98, 237);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(90, 24);
this.label1.TabIndex = 42;
this.label1.Text = "Statistics";
//
// panel1
//
this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panel1.Controls.Add(this.activeTableLbl);
this.panel1.Controls.Add(this.bestSellerLbl);
this.panel1.Controls.Add(this.mostSoldLbl);
this.panel1.Controls.Add(this.label5);
this.panel1.Controls.Add(this.label3);
this.panel1.Controls.Add(this.label2);
this.panel1.Location = new System.Drawing.Point(28, 274);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(227, 139);
this.panel1.TabIndex = 43;
//
// activeTableLbl
//
this.activeTableLbl.BackColor = System.Drawing.Color.Transparent;
this.activeTableLbl.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold);
this.activeTableLbl.ForeColor = System.Drawing.SystemColors.Highlight;
this.activeTableLbl.Location = new System.Drawing.Point(-1, 114);
this.activeTableLbl.Name = "activeTableLbl";
this.activeTableLbl.Size = new System.Drawing.Size(228, 19);
this.activeTableLbl.TabIndex = 50;
this.activeTableLbl.Text = "Product";
this.activeTableLbl.TextAlign = System.Drawing.ContentAlignment.TopCenter;
//
// bestSellerLbl
//
this.bestSellerLbl.BackColor = System.Drawing.Color.Transparent;
this.bestSellerLbl.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold);
this.bestSellerLbl.ForeColor = System.Drawing.SystemColors.Highlight;
this.bestSellerLbl.Location = new System.Drawing.Point(-1, 68);
this.bestSellerLbl.Name = "bestSellerLbl";
this.bestSellerLbl.Size = new System.Drawing.Size(228, 19);
this.bestSellerLbl.TabIndex = 49;
this.bestSellerLbl.Text = "Product";
this.bestSellerLbl.TextAlign = System.Drawing.ContentAlignment.TopCenter;
//
// mostSoldLbl
//
this.mostSoldLbl.BackColor = System.Drawing.Color.Transparent;
this.mostSoldLbl.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold);
this.mostSoldLbl.ForeColor = System.Drawing.SystemColors.Highlight;
this.mostSoldLbl.Location = new System.Drawing.Point(-1, 29);
this.mostSoldLbl.Name = "mostSoldLbl";
this.mostSoldLbl.Size = new System.Drawing.Size(228, 19);
this.mostSoldLbl.TabIndex = 48;
this.mostSoldLbl.Text = "Product";
this.mostSoldLbl.TextAlign = System.Drawing.ContentAlignment.TopCenter;
//
// label5
//
this.label5.BackColor = System.Drawing.Color.Transparent;
this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline))), System.Drawing.GraphicsUnit.Point, ((byte)(177)));
this.label5.Location = new System.Drawing.Point(-1, 93);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(227, 21);
this.label5.TabIndex = 47;
this.label5.Text = "Most Active Table";
this.label5.TextAlign = System.Drawing.ContentAlignment.TopCenter;
//
// label3
//
this.label3.BackColor = System.Drawing.Color.Transparent;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline))), System.Drawing.GraphicsUnit.Point, ((byte)(177)));
this.label3.Location = new System.Drawing.Point(-1, 48);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(227, 20);
this.label3.TabIndex = 45;
this.label3.Text = "Best Seller";
this.label3.TextAlign = System.Drawing.ContentAlignment.TopCenter;
//
// label2
//
this.label2.BackColor = System.Drawing.Color.Transparent;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline))), System.Drawing.GraphicsUnit.Point, ((byte)(177)));
this.label2.Location = new System.Drawing.Point(-1, 9);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(227, 20);
this.label2.TabIndex = 44;
this.label2.Text = "Most Sold";
this.label2.TextAlign = System.Drawing.ContentAlignment.TopCenter;
//
// panel2
//
this.panel2.BackColor = System.Drawing.Color.Azure;
this.panel2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panel2.Controls.Add(this.totalIncomeLbl);
this.panel2.Controls.Add(this.avgOrderLbl);
this.panel2.Controls.Add(this.label7);
this.panel2.Controls.Add(this.label10);
this.panel2.Location = new System.Drawing.Point(28, 428);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(227, 139);
this.panel2.TabIndex = 49;
//
// totalIncomeLbl
//
this.totalIncomeLbl.Font = new System.Drawing.Font("Microsoft Sans Serif", 22F, System.Drawing.FontStyle.Bold);
this.totalIncomeLbl.ForeColor = System.Drawing.Color.DarkGreen;
this.totalIncomeLbl.Location = new System.Drawing.Point(-1, 92);
this.totalIncomeLbl.Name = "totalIncomeLbl";
this.totalIncomeLbl.Size = new System.Drawing.Size(228, 31);
this.totalIncomeLbl.TabIndex = 52;
this.totalIncomeLbl.Text = "123132123";
this.totalIncomeLbl.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// avgOrderLbl
//
this.avgOrderLbl.BackColor = System.Drawing.Color.Transparent;
this.avgOrderLbl.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold);
this.avgOrderLbl.ForeColor = System.Drawing.SystemColors.Highlight;
this.avgOrderLbl.Location = new System.Drawing.Point(-1, 40);
this.avgOrderLbl.Name = "avgOrderLbl";
this.avgOrderLbl.Size = new System.Drawing.Size(227, 19);
this.avgOrderLbl.TabIndex = 51;
this.avgOrderLbl.Text = "123123";
this.avgOrderLbl.TextAlign = System.Drawing.ContentAlignment.TopCenter;
//
// label7
//
this.label7.BackColor = System.Drawing.Color.Transparent;
this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline))), System.Drawing.GraphicsUnit.Point, ((byte)(177)));
this.label7.Location = new System.Drawing.Point(-1, 13);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(227, 27);
this.label7.TabIndex = 48;
this.label7.Text = "Average Product Cost:";
this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// label10
//
this.label10.BackColor = System.Drawing.Color.Transparent;
this.label10.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline))), System.Drawing.GraphicsUnit.Point, ((byte)(177)));
this.label10.Location = new System.Drawing.Point(-1, 65);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(227, 27);
this.label10.TabIndex = 46;
this.label10.Text = "Total Income";
this.label10.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// objectListView3
//
this.objectListView3.AllColumns.Add(this.olvColumn7);
this.objectListView3.AllColumns.Add(this.olvColumn12);
this.objectListView3.AllColumns.Add(this.olvColumn13);
this.objectListView3.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.olvColumn7,
this.olvColumn12,
this.olvColumn13});
this.objectListView3.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F);
this.objectListView3.GridLines = true;
this.objectListView3.Location = new System.Drawing.Point(273, 186);
this.objectListView3.Name = "objectListView3";
this.objectListView3.ShowGroups = false;
this.objectListView3.Size = new System.Drawing.Size(719, 381);
this.objectListView3.TabIndex = 50;
this.objectListView3.UseCompatibleStateImageBehavior = false;
this.objectListView3.View = System.Windows.Forms.View.Details;
//
// olvColumn7
//
this.olvColumn7.AspectName = "Employee";
this.olvColumn7.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn7.Text = "Employee";
this.olvColumn7.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn7.Width = 221;
//
// olvColumn12
//
this.olvColumn12.AspectName = "Quantity";
this.olvColumn12.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn12.Text = "Quantity";
this.olvColumn12.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn12.Width = 99;
//
// olvColumn13
//
this.olvColumn13.AspectName = "Price";
this.olvColumn13.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn13.Text = "Sales";
this.olvColumn13.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn13.Width = 89;
//
// objectListView4
//
this.objectListView4.AllColumns.Add(this.olvColumn6);
this.objectListView4.AllColumns.Add(this.olvColumn15);
this.objectListView4.AllColumns.Add(this.olvColumn16);
this.objectListView4.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.olvColumn6,
this.olvColumn15,
this.olvColumn16});
this.objectListView4.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F);
this.objectListView4.GridLines = true;
this.objectListView4.Location = new System.Drawing.Point(273, 186);
this.objectListView4.Name = "objectListView4";
this.objectListView4.ShowGroups = false;
this.objectListView4.Size = new System.Drawing.Size(719, 381);
this.objectListView4.TabIndex = 51;
this.objectListView4.UseCompatibleStateImageBehavior = false;
this.objectListView4.View = System.Windows.Forms.View.Details;
//
// olvColumn6
//
this.olvColumn6.AspectName = "TableID";
this.olvColumn6.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn6.Text = "TableID";
this.olvColumn6.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn6.Width = 84;
//
// olvColumn15
//
this.olvColumn15.AspectName = "Quantity";
this.olvColumn15.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn15.Text = "Quantity";
this.olvColumn15.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn15.Width = 124;
//
// olvColumn16
//
this.olvColumn16.AspectName = "Price";
this.olvColumn16.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn16.Text = "Sales";
this.olvColumn16.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.olvColumn16.Width = 217;
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Interval = 50;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// pictureBox1
//
this.pictureBox1.BackColor = System.Drawing.Color.Transparent;
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(70, 16);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(326, 138);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.pictureBox1.TabIndex = 52;
this.pictureBox1.TabStop = false;
//
// HistoryControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.Azure;
this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.panel2);
this.Controls.Add(this.panel1);
this.Controls.Add(this.label1);
this.Controls.Add(this.objectListView1);
this.Controls.Add(this.objectListView2);
this.Controls.Add(this.domainUpDown1);
this.Controls.Add(this.HeaderLbl);
this.Controls.Add(this.objectListView3);
this.Controls.Add(this.objectListView4);
this.Name = "HistoryControl";
this.Size = new System.Drawing.Size(1020, 598);
((System.ComponentModel.ISupportInitialize)(this.objectListView1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.objectListView2)).EndInit();
this.panel1.ResumeLayout(false);
this.panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.objectListView3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.objectListView4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label HeaderLbl;
private BrightIdeasSoftware.ObjectListView objectListView1;
private BrightIdeasSoftware.OLVColumn olvColumn1;
private BrightIdeasSoftware.OLVColumn olvColumn2;
private BrightIdeasSoftware.OLVColumn olvColumn3;
private BrightIdeasSoftware.OLVColumn olvColumn4;
private BrightIdeasSoftware.OLVColumn olvColumn5;
private System.Windows.Forms.DomainUpDown domainUpDown1;
private BrightIdeasSoftware.ObjectListView objectListView2;
private BrightIdeasSoftware.OLVColumn olvColumn8;
private BrightIdeasSoftware.OLVColumn olvColumn9;
private BrightIdeasSoftware.OLVColumn olvColumn10;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label activeTableLbl;
private System.Windows.Forms.Label bestSellerLbl;
private System.Windows.Forms.Label mostSoldLbl;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label totalIncomeLbl;
private System.Windows.Forms.Label avgOrderLbl;
private BrightIdeasSoftware.ObjectListView objectListView3;
private BrightIdeasSoftware.OLVColumn olvColumn7;
private BrightIdeasSoftware.OLVColumn olvColumn12;
private BrightIdeasSoftware.OLVColumn olvColumn13;
private BrightIdeasSoftware.ObjectListView objectListView4;
private BrightIdeasSoftware.OLVColumn olvColumn6;
private BrightIdeasSoftware.OLVColumn olvColumn15;
private BrightIdeasSoftware.OLVColumn olvColumn16;
private BrightIdeasSoftware.OLVColumn olvColumn11;
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.PictureBox pictureBox1;
}
}
| 56.133087 | 239 | 0.620917 | [
"Apache-2.0"
] | zdvir/ResManagementA | ResManagementA/UserControls/HistoryControl.Designer.cs | 30,370 | C# |
using DN.WebApi.Application.Catalog.Brands;
using DN.WebApi.Application.Wrapper;
using DN.WebApi.Infrastructure.Identity.Permissions;
using DN.WebApi.Shared.Authorization;
using Microsoft.AspNetCore.Mvc;
using NSwag.Annotations;
namespace DN.WebApi.Host.Controllers.Catalog;
public class BrandsController : VersionedApiController
{
[HttpPost("search")]
[MustHavePermission(FSHPermissions.Brands.Search)]
[OpenApiOperation("Search Brands using available Filters.", "")]
public Task<PaginatedResult<BrandDto>> SearchAsync(SearchBrandsRequest request)
{
return Mediator.Send(request);
}
[HttpPost]
[MustHavePermission(FSHPermissions.Brands.Register)]
public Task<Guid> CreateAsync(CreateBrandRequest request)
{
return Mediator.Send(request);
}
[HttpPut("{id:guid}")]
[MustHavePermission(FSHPermissions.Brands.Update)]
public async Task<ActionResult<Guid>> UpdateAsync(UpdateBrandRequest request, Guid id)
{
if (id != request.Id)
{
return BadRequest();
}
return Ok(await Mediator.Send(request));
}
[HttpDelete("{id:guid}")]
[MustHavePermission(FSHPermissions.Brands.Remove)]
public Task<Guid> DeleteAsync(Guid id)
{
return Mediator.Send(new DeleteBrandRequest(id));
}
[HttpPost("generate-random")]
public Task<string> GenerateRandomAsync(GenerateRandomBrandRequest request)
{
return Mediator.Send(request);
}
[HttpDelete("delete-random")]
[ApiConventionMethod(typeof(FSHApiConventions), nameof(FSHApiConventions.Delete))]
public Task<string> DeleteRandomAsync()
{
return Mediator.Send(new DeleteRandomBrandRequest());
}
} | 29.827586 | 90 | 0.706358 | [
"MIT"
] | AppSlope/dotnet-webapi-boilerplate | src/Host/Controllers/Catalog/BrandsController.cs | 1,732 | C# |
#region License
/*
Copyright (c) 2015 Betson Roy
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QueryMaster.GameServer
{
/// <summary>
/// Contains information of a player currently in server.
/// </summary>
[Serializable]
public class PlayerInfo : DataObject
{
/// <summary>
/// Name of the player.
/// </summary>
public string Name { get; internal set; }
/// <summary>
/// Player's score (usually "frags" or "kills".).
/// </summary>
public long Score { get; internal set; }
/// <summary>
/// Time player has been connected to the server.(returns TimeSpan instance).
/// </summary>
public TimeSpan Time { get; internal set; }
}
}
| 33.6 | 86 | 0.709957 | [
"MIT"
] | Freenex1911/QueryMaster | QueryMaster/GameServer/DataObjects/Player.cs | 1,850 | C# |
namespace MPT.CSI.Serialize.Models.Components.Design
{
public class WallDesignOverwrite : DesignOverwrites
{
}
}
| 18 | 55 | 0.730159 | [
"MIT"
] | MarkPThomas/MPT.Net | MPT/CSI/API/MPT.CSI.Serialize/Models/Components/Design/WallDesignOverwrite.cs | 128 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
using System;
using System.Collections.Generic;
namespace WebMail.Migrations
{
public partial class DraftsMigration2 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Attachment",
table: "Mails",
type: "TEXT",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "AttachmentName",
table: "Mails",
type: "TEXT",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Receiver",
table: "Mails",
type: "TEXT",
nullable: true);
migrationBuilder.CreateTable(
name: "Drafts",
columns: table => new
{
ID = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Attachment = table.Column<string>(type: "TEXT", nullable: true),
AttachmentName = table.Column<string>(type: "TEXT", nullable: true),
Body = table.Column<string>(type: "TEXT", nullable: true),
Date = table.Column<DateTimeOffset>(type: "TEXT", nullable: false),
Receiver = table.Column<string>(type: "TEXT", nullable: true),
Sender = table.Column<string>(type: "TEXT", nullable: true),
Title = table.Column<string>(type: "TEXT", nullable: true),
UniqueID = table.Column<uint>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Drafts", x => x.ID);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Drafts");
migrationBuilder.DropColumn(
name: "Attachment",
table: "Mails");
migrationBuilder.DropColumn(
name: "AttachmentName",
table: "Mails");
migrationBuilder.DropColumn(
name: "Receiver",
table: "Mails");
}
}
}
| 35.217391 | 88 | 0.499177 | [
"MIT"
] | Damenus/webmail | Migrations/20171203200656_DraftsMigration2.cs | 2,432 | C# |
using ConsoleGameEngine;
using System;
/// <summary>
/// Console Athlete components namespace
/// </summary>
namespace ConsoleAthlete.Components
{
/// <summary>
/// Health component
/// </summary>
public class HealthComponent : AComponent
{
/// <summary>
/// Health
/// </summary>
public float Health { get; set; }
/// <summary>
/// Is alive
/// </summary>
public bool IsAlive => (Health <= 0.0f);
/// <summary>
/// Constructor
/// </summary>
/// <param name="entity">Entity</param>
public HealthComponent(IEntity entity) : base(entity)
{
// ...
}
/// <summary>
/// Damage
/// </summary>
/// <param name="amount">Amount</param>
public void Damage(float amount)
{
Health -= Math.Abs(amount);
}
/// <summary>
/// Initialize
/// </summary>
public override void Init()
{
// ...
}
/// <summary>
/// Update
/// </summary>
public override void Update()
{
// ...
}
}
}
| 20.542373 | 61 | 0.44967 | [
"MIT"
] | BigETI/ConsoleAthlete | ConsoleAthlete/Components/HealthComponent.cs | 1,214 | C# |
using System.Collections.Generic;
using SitecoreCognitiveServices.Foundation.NexSDK.Session.Models;
namespace SitecoreCognitiveServices.Foundation.NexSDK.Contest.Models
{
public class ContestSelectionResponse : SessionResponse
{
public List<MetricSet> MetricSets { get; set; }
public class MetricSet
{
/// <summary>
/// Information about the data source preparations that were performed
/// </summary>
public string[] DataSetProperties { get; set; }
/// <summary>
/// Selection metrics used when determining which algorithms to run
/// </summary>
public Dictionary<string, double> Metrics { get; set; }
}
}
} | 32.652174 | 82 | 0.629827 | [
"MIT"
] | markstiles/SitecoreCognitiveServices.Core | src/Foundation/NexSDK/code/Contest/Models/ContestSelectionResponse.cs | 751 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.WindowsRuntime.Internal;
using System.Security;
using System.Threading;
using Windows.Foundation;
using Windows.Storage.Streams;
namespace System.Runtime.InteropServices.WindowsRuntime
{
/// <summary>
/// Contains an implementation of the WinRT IBuffer interface that conforms to all requirements on classes that implement that interface,
/// such as implementing additional interfaces.
/// </summary>
public sealed class WindowsRuntimeBuffer : IBuffer, IBufferByteAccess, IMarshal, IAgileObject
{
#region Constants
private const String WinTypesDLL = "WinTypes.dll";
private enum MSHCTX : int { Local = 0, NoSharedMem = 1, DifferentMachine = 2, InProc = 3, CrossCtx = 4 }
private enum MSHLFLAGS : int { Normal = 0, TableStrong = 1, TableWeak = 2, NoPing = 4 }
#endregion Constants
#region Static factory methods
[CLSCompliant(false)]
public static IBuffer Create(Int32 capacity)
{
if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity));
Contract.Ensures(Contract.Result<IBuffer>() != null);
Contract.Ensures(Contract.Result<IBuffer>().Length == unchecked((UInt32)0));
Contract.Ensures(Contract.Result<IBuffer>().Capacity == unchecked((UInt32)capacity));
Contract.EndContractBlock();
return new WindowsRuntimeBuffer(capacity);
}
[CLSCompliant(false)]
public static IBuffer Create(Byte[] data, Int32 offset, Int32 length, Int32 capacity)
{
if (data == null) throw new ArgumentNullException(nameof(data));
if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset));
if (length < 0) throw new ArgumentOutOfRangeException(nameof(length));
if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity));
if (data.Length - offset < length) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
if (data.Length - offset < capacity) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
if (capacity < length) throw new ArgumentException(SR.Argument_InsufficientBufferCapacity);
Contract.Ensures(Contract.Result<IBuffer>() != null);
Contract.Ensures(Contract.Result<IBuffer>().Length == unchecked((UInt32)length));
Contract.Ensures(Contract.Result<IBuffer>().Capacity == unchecked((UInt32)capacity));
Contract.EndContractBlock();
Byte[] underlyingData = new Byte[capacity];
Buffer.BlockCopy(data, offset, underlyingData, 0, length);
return new WindowsRuntimeBuffer(underlyingData, 0, length, capacity);
}
#endregion Static factory methods
#region Static fields and helpers
// This object handles IMarshal calls for us:
[ThreadStatic]
private static IMarshal s_winRtMarshalProxy = null;
private static void EnsureHasMarshalProxy()
{
if (s_winRtMarshalProxy != null)
return;
try
{
IMarshal proxy;
Int32 hr = Interop.mincore.RoGetBufferMarshaler(out proxy);
s_winRtMarshalProxy = proxy;
if (hr != HResults.S_OK)
{
Exception ex = new Exception(String.Format("{0} ({1}!RoGetBufferMarshaler)", SR.WinRtCOM_Error, WinTypesDLL));
ex.SetErrorCode(hr);
throw ex;
}
if (proxy == null)
throw new NullReferenceException(String.Format("{0} ({1}!RoGetBufferMarshaler)", SR.WinRtCOM_Error, WinTypesDLL));
}
catch (DllNotFoundException ex)
{
throw new NotImplementedException(SR.Format(SR.NotImplemented_NativeRoutineNotFound,
String.Format("{0}!RoGetBufferMarshaler", WinTypesDLL)),
ex);
}
}
#endregion Static fields and helpers
#region Fields
private Byte[] _data = null;
private Int32 _dataStartOffs = 0;
private Int32 _usefulDataLength = 0;
private Int32 _maxDataCapacity = 0;
private GCHandle _pinHandle;
// Pointer to data[dataStartOffs] when data is pinned:
private IntPtr _dataPtr = IntPtr.Zero;
#endregion Fields
#region Constructors
internal WindowsRuntimeBuffer(Int32 capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity));
Contract.EndContractBlock();
_data = new Byte[capacity];
_dataStartOffs = 0;
_usefulDataLength = 0;
_maxDataCapacity = capacity;
_dataPtr = IntPtr.Zero;
}
internal WindowsRuntimeBuffer(Byte[] data, Int32 offset, Int32 length, Int32 capacity)
{
if (data == null) throw new ArgumentNullException(nameof(data));
if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset));
if (length < 0) throw new ArgumentOutOfRangeException(nameof(length));
if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity));
if (data.Length - offset < length) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
if (data.Length - offset < capacity) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
if (capacity < length) throw new ArgumentException(SR.Argument_InsufficientBufferCapacity);
Contract.EndContractBlock();
_data = data;
_dataStartOffs = offset;
_usefulDataLength = length;
_maxDataCapacity = capacity;
_dataPtr = IntPtr.Zero;
}
#endregion Constructors
#region Helpers
internal void GetUnderlyingData(out Byte[] underlyingDataArray, out Int32 underlyingDataArrayStartOffset)
{
underlyingDataArray = _data;
underlyingDataArrayStartOffset = _dataStartOffs;
}
private unsafe Byte* PinUnderlyingData()
{
GCHandle gcHandle = default(GCHandle);
bool ptrWasStored = false;
IntPtr buffPtr;
try { }
finally
{
try
{
// Pin the the data array:
gcHandle = GCHandle.Alloc(_data, GCHandleType.Pinned);
buffPtr = gcHandle.AddrOfPinnedObject() + _dataStartOffs;
// Store the pin IFF it has not been assigned:
ptrWasStored = (Interlocked.CompareExchange(ref _dataPtr, buffPtr, IntPtr.Zero) == IntPtr.Zero);
}
finally
{
if (!ptrWasStored)
{
// There is a race with another thread also trying to create a pin and they were first
// in assigning to data pin. That's ok, just give it up.
// Unpin again (the pin from the other thread remains):
gcHandle.Free();
}
else
{
if (_pinHandle.IsAllocated)
_pinHandle.Free();
// Make sure we keep track of the handle
_pinHandle = gcHandle;
}
}
}
// Ok, now all is good:
return (Byte*)buffPtr;
}
~WindowsRuntimeBuffer()
{
if (_pinHandle.IsAllocated)
_pinHandle.Free();
}
#endregion Helpers
#region Implementation of Windows.Foundation.IBuffer
UInt32 IBuffer.Capacity
{
get { return unchecked((UInt32)_maxDataCapacity); }
}
UInt32 IBuffer.Length
{
get
{
return unchecked((UInt32)_usefulDataLength);
}
set
{
if (value > ((IBuffer)this).Capacity)
{
ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException(SR.Argument_BufferLengthExceedsCapacity, nameof(value));
ex.SetErrorCode(HResults.E_BOUNDS);
throw ex;
}
// Capacity is ensured to not exceed Int32.MaxValue, so Length is within this limit and this cast is safe:
Debug.Assert(((IBuffer)this).Capacity <= Int32.MaxValue);
_usefulDataLength = unchecked((Int32)value);
}
}
#endregion Implementation of Windows.Foundation.IBuffer
#region Implementation of IBufferByteAccess
unsafe IntPtr IBufferByteAccess.GetBuffer()
{
// Get pin handle:
IntPtr buffPtr = Volatile.Read(ref _dataPtr);
// If we are already pinned, return the pointer and have a nice day:
if (buffPtr != IntPtr.Zero)
return buffPtr;
// Ok, we we are not yet pinned. Let's do it.
return new IntPtr(PinUnderlyingData());
}
#endregion Implementation of IBufferByteAccess
#region Implementation of IMarshal
void IMarshal.DisconnectObject(UInt32 dwReserved)
{
EnsureHasMarshalProxy();
s_winRtMarshalProxy.DisconnectObject(dwReserved);
}
void IMarshal.GetMarshalSizeMax(ref Guid riid, IntPtr pv, UInt32 dwDestContext, IntPtr pvDestContext, UInt32 mshlflags, out UInt32 pSize)
{
EnsureHasMarshalProxy();
s_winRtMarshalProxy.GetMarshalSizeMax(ref riid, pv, dwDestContext, pvDestContext, mshlflags, out pSize);
}
void IMarshal.GetUnmarshalClass(ref Guid riid, IntPtr pv, UInt32 dwDestContext, IntPtr pvDestContext, UInt32 mshlFlags, out Guid pCid)
{
EnsureHasMarshalProxy();
s_winRtMarshalProxy.GetUnmarshalClass(ref riid, pv, dwDestContext, pvDestContext, mshlFlags, out pCid);
}
void IMarshal.MarshalInterface(IntPtr pStm, ref Guid riid, IntPtr pv, UInt32 dwDestContext, IntPtr pvDestContext, UInt32 mshlflags)
{
EnsureHasMarshalProxy();
s_winRtMarshalProxy.MarshalInterface(pStm, ref riid, pv, dwDestContext, pvDestContext, mshlflags);
}
void IMarshal.ReleaseMarshalData(IntPtr pStm)
{
EnsureHasMarshalProxy();
s_winRtMarshalProxy.ReleaseMarshalData(pStm);
}
void IMarshal.UnmarshalInterface(IntPtr pStm, ref Guid riid, out IntPtr ppv)
{
EnsureHasMarshalProxy();
s_winRtMarshalProxy.UnmarshalInterface(pStm, ref riid, out ppv);
}
#endregion Implementation of IMarshal
} // class WindowsRuntimeBuffer
} // namespace
// WindowsRuntimeBuffer.cs
| 35.796296 | 145 | 0.597689 | [
"MIT"
] | benjamin-bader/corefx | src/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBuffer.cs | 11,598 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using HttpServer.Headers;
namespace HttpServer.Authentication
{
/// <summary>
/// Implements basic authentication scheme.
/// </summary>
public class BasicAuthentication : IAuthenticator
{
private readonly IUserProvider _userProvider;
public BasicAuthentication(IUserProvider userProvider)
{
_userProvider = userProvider;
}
/// <summary>
/// Create a response that can be sent in the WWW-Authenticate header.
/// </summary>
/// <param name="realm">Realm that the user should authenticate in</param>
/// <param name="options">Not used by basic authentication</param>
/// <returns>A WWW-Authenticate header.</returns>
/// <exception cref="ArgumentNullException">Argument is <c>null</c>.</exception>
public IHeader CreateChallenge(string realm)
{
if (string.IsNullOrEmpty(realm))
throw new ArgumentNullException("realm");
return new StringHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
}
/// <summary>
/// An authentication response have been received from the web browser.
/// Check if it's correct
/// </summary>
/// <param name="header">Authorization header</param>
/// <param name="realm">Realm that should be authenticated</param>
/// <param name="httpVerb">GET/POST/PUT/DELETE etc.</param>
/// <returns>Authentication object that is stored for the request. A user class or something like that.</returns>
/// <exception cref="ArgumentException">if authenticationHeader is invalid</exception>
/// <exception cref="ArgumentNullException">If any of the paramters is empty or null.</exception>
public IAuthenticationUser Authenticate(AuthorizationHeader header, string realm, string httpVerb)
{
if (header == null)
throw new ArgumentNullException("realm");
if (string.IsNullOrEmpty(realm))
throw new ArgumentNullException("realm");
if (string.IsNullOrEmpty(httpVerb))
throw new ArgumentNullException("httpVerb");
/*
* To receive authorization, the client sends the userid and password,
separated by a single colon (":") character, within a base64 [7]
encoded string in the credentials.*/
string decoded = Encoding.UTF8.GetString(Convert.FromBase64String(header.Data));
int pos = decoded.IndexOf(':');
if (pos == -1)
throw new BadRequestException("Invalid basic authentication header, failed to find colon.");
string password = decoded.Substring(pos + 1, decoded.Length - pos - 1);
string userName = decoded.Substring(0, pos);
var user = _userProvider.Lookup(userName, realm);
if (user == null)
return null;
if (user.Password == null)
{
var ha1 = DigestAuthentication.GetHA1(realm, userName, password);
if (ha1 != user.HA1)
return null;
}
else
{
if (password != user.Password)
return null;
}
return user;
}
/// <summary>
/// Gets authenticator scheme
/// </summary>
/// <value></value>
/// <example>
/// digest
/// </example>
public string Scheme
{
get { return "basic"; }
}
}
}
| 37.20202 | 121 | 0.577518 | [
"MIT"
] | bhuebschen/feuerwehrcloud-deiva | webserver-69631/trunk/HttpServer/Authentication/BasicAuthentication.cs | 3,685 | C# |
#region Using directives
using System;
using System.Windows.Forms;
#endregion
namespace PixelCryptor.UI {
public partial class ScreenDecodeDestination : ScreenMaster {
#region String constants
private string cTooltipDestinationFolder = "Select a destination for the content of the package";
#endregion
#region Constructors
/// <summary>
/// Constructs a new DecodeDestination screen.
/// </summary>
public ScreenDecodeDestination() {
// Initialize basic screen elements
this.InitializeComponent();
// Bind the Tooltip
ttpTooltip.SetToolTip(this.lnkSelectDestinationFolder, cTooltipDestinationFolder);
}
#endregion
#region Events
private void lnkSelectDestinationFolder_Click(object sender, EventArgs e) {
// Show the destination selector
if (this.dlgSelectDestinationFolder.ShowDialog() == DialogResult.OK) {
// Update the project
this._project.DestinationFolderPath = this.dlgSelectDestinationFolder.SelectedPath;
// Update the UI
this.txtDestinationFolderPath.Text = this._project.DestinationFolderPath;
// Revalidate the screen
this.ValidateScreen();
}
}
#endregion
#region Methods
/// <summary>
/// Activates this screen.
/// </summary>
public override void Activate(CryptorProject project) {
// Call the base implementation
base.Activate(project);
// Set element value if possible
if (!String.IsNullOrEmpty(project.DestinationFolderPath))
this.txtDestinationFolderPath.Text = project.DestinationFolderPath;
else
this.txtDestinationFolderPath.Text = String.Empty;
}
/// <summary>
/// Deactivates this screen.
/// </summary>
public override CryptorProject Deactivate() {
// Clear the Textbox to prevent flickering
this.txtDestinationFolderPath.Text = String.Empty;
// Deactivate the screen
return base.Deactivate();
}
/// <summary>
/// Validates this screen.
/// </summary>
public override bool ValidateScreen() {
// The screen is valid, when a key is defined
bool isValid = !String.IsNullOrEmpty(this._project.DestinationFolderPath);
// Call the event
base.OnScreenValidated(isValid);
// Return the result
return isValid;
}
#endregion
}
}
| 26.722892 | 99 | 0.728584 | [
"Apache-2.0"
] | Zyphrax/PixelCryptor | PixelCryptor/UI/ScreenDecodeDestination.cs | 2,218 | C# |
// SPDX-License-Identifier: Apache-2.0
// Licensed to the Ed-Fi Alliance under one or more agreements.
// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
// See the LICENSE and NOTICES files in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
namespace EdFi.AnalyticsMiddleTier.Tests.Classes
{
[SuppressMessage("ReSharper", "UnusedMember.Global")]
public class GradingPeriodDim
{
public string GradingPeriodKey { get; set; } //(nvarchar(92), null)
public string GradingPeriodBeginDateKey { get; set; } //(nvarchar(30), null)
public string GradingPeriodEndDateKey { get; set; } //(nvarchar(30), null)
public string GradingPeriodDescription { get; set; } //(nvarchar(50), not null)
public int TotalInstructionalDays { get; set; } //(int, not null)
public int PeriodSequence { get; set; } //(int, null)
public int SchoolKey { get; set; } //(int, not null)
public string SchoolYear { get; set; } //(int, not null)
public DateTime LastModifiedDate { get; set; } //(datetime, not null)
}
} | 44.692308 | 87 | 0.679002 | [
"Apache-2.0"
] | ValerieRobateau/Ed-Fi-Analytics-Middle-Tier | src/EdFi.AnalyticsMiddleTier.Tests/Classes/GradingPeriodDim.cs | 1,164 | C# |
using MahApps.Metro.Controls;
using System.Diagnostics;
using System.Windows;
namespace Computer_Service
{
/// <summary>
/// Логика взаимодействия для MasterMain.xaml
/// </summary>
public partial class About : MetroWindow
{
public About()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void Image_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
Process.Start("https://vk.com/maks_ivanofff");
}
private void Image_MouseDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
Process.Start("https://www.facebook.com/profile.php?id=100008449293113");
}
private void Image_MouseDown_2(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
Process.Start("https://github.com/MaxIvanov44/ComputerService");
}
}
} | 27.621622 | 98 | 0.627202 | [
"Unlicense"
] | MaxIvanov44/ComputerService | Computer Service/Computer Service/Resources/About.xaml.cs | 1,047 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.UI.Xaml.Data
{
#if false || false || false || false || false
#if false || false || false || false || false
[global::Uno.NotImplemented]
#endif
public enum BindingMode
{
// Skipping already declared field Windows.UI.Xaml.Data.BindingMode.OneWay
// Skipping already declared field Windows.UI.Xaml.Data.BindingMode.OneTime
// Skipping already declared field Windows.UI.Xaml.Data.BindingMode.TwoWay
}
#endif
}
| 31.823529 | 77 | 0.737523 | [
"Apache-2.0"
] | 06needhamt/uno | src/Uno.UI/Generated/3.0.0.0/Windows.UI.Xaml.Data/BindingMode.cs | 541 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Ludoop.Backend.Tiles;
using Ludoop.View;
namespace Ludoop.Backend
{
public class Map : IName
{
/// <summary>
/// Array of Tile objects.
/// </summary>
public Tile[] Tiles;
/// <summary>
/// Flag for checking if map is a loop.
/// </summary>
bool isLoopMap;
/// <summary>
/// Class constructor.
/// </summary>
/// <param name="size">Size of the map.</param>
/// <param name="isLoopMap">Flag for checking if map is a loop.</param>
public Map(int size, bool isLoopMap)
{
this.Tiles = new Tile[size];
this.isLoopMap = isLoopMap;
this.Name = "Map";
for (int i = 0; i < Tiles.Length; i++)
{
Tile newTile = new DefaultTile(this, i);
newTile.Actor = new ConsoleTileActor(Game.GetConsoleActorMatrix(), newTile);
Tiles[i] = newTile;
}
}
/// <summary>
/// Method for replacing a specified map tile.
/// </summary>
/// <param name="tileIndex">Index of tile to set.</param>
/// <param name="tile">Instance of new tile</param>
public void SetTile(int tileIndex, Tile tile)
{
if (tileIndex >= 0 && tileIndex < Tiles.Length) //Check if tileIndex is a valid array index.
{
Tiles[tileIndex] = tile;
if (tileIndex != Tiles.Length - 1) //Check if tile is not last tile.
{
tile.NextTile = Tiles[tileIndex + 1];
}
else if (isLoopMap) //Else check if map is loopmap.
{
tile.NextTile = this.FirstTile;
}
if (tileIndex != 0) //Check if tile is not first tile.
{
tile.PrevTile = Tiles[tileIndex - 1];
}
else if (isLoopMap) //Else check if map is loopmap.
{
tile.PrevTile = this.LastTile;
}
}
}
//Getter and Setter for the last tile of the map.
public Tile LastTile
{
get { return this.Tiles[Tiles.Length - 1]; }
set { this.Tiles[Tiles.Length - 1] = value; }
}
//Getter and Setter for the first tile of the map.
public Tile FirstTile
{
get { return this.Tiles[0]; }
set { this.Tiles[0] = value; }
}
//Map name Getter and Setter.
public string Name { get; set; }
/// <summary>
/// Method for getting an info-string about all tiles.
/// </summary>
/// <returns></returns>
public string[] GetTilesInfo()
{
string[] tileInfo = new string[Tiles.Length];
int i = 0;
foreach (Tile tile in Tiles)
{
tileInfo[i] = GetTileInfo(tile.Index);
i++;
}
return tileInfo;
}
/// <summary>
/// Method for getting an info-string for a tile specified by index.
/// </summary>
/// <param name="index">Index of tile</param>
/// <returns></returns>
public string GetTileInfo(int index)
{
Tile tile = Tiles[index];
string strMap = tile.Map.Name;
string strIdx = tile.Index.ToString();
string strType = tile.TYPE.ToString();
string strPos = String.Format("[x:{0},y:{1},w:{2},h:{3}]", tile.Actor.X, tile.Actor.Y, tile.Actor.Width, tile.Actor.Height);
string strInfo = strMap + ":" + strIdx + ":" + strType + ":" + strPos;
if (tile is ITeam) //Check if should add Team Info.
{
string strTeam = Enum.GetName(typeof(PlayerTeam), ((ITeam)tile).Team);
strInfo += ":" + strTeam;
}
if (tile is ExitTile) //Check if should add ExitTile Destination Info.
{
Tile destinationTile = ((ExitTile)tile).DestinationTile;
strInfo += "\t->\t" + destinationTile.Map.GetTileInfo(destinationTile.Index);
}
return strInfo;
}
public Tile[] GetNextTilesOfType(TileType type)
{
List<Tile> tilesOfType = new List<Tile>();
foreach (Tile tile in this.Tiles)
{
if (tile.TYPE == type)
{
tilesOfType.Add(tile);
}
}
return tilesOfType.ToArray();
}
public Tile GetFirstTileOfTeam(Tile[] tiles, PlayerTeam team) {
foreach (Tile tile in tiles) {
if (tile is ITeam && ((ITeam)tile).Team == team) {
return tile;
}
}
return null;
}
}
}
| 34.020408 | 136 | 0.484103 | [
"MIT"
] | hanzzi/LudOOP | Piece/Piece/Backend/Map.cs | 5,003 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraScaler : MonoBehaviour
{
private Board board;
public float cameraOffset;
public float aspectRatio = 0.625f;
public float padding = 2;
public float yOffset = 1;
void Start() {
board = FindObjectOfType<Board>();
if(board!=null){
RepositionCamera(board.width-1, board.height-1);
}
}
void RepositionCamera(float x, float y){
Vector3 tempPosition = new Vector3(x/2, y/2 + yOffset, cameraOffset);
transform.position = tempPosition;
if (board.width >= board.height){
Camera.main.orthographicSize = (board.width/2 + padding)/aspectRatio;
}else{
Camera.main.orthographicSize = (board.height/2 + padding);
}
}
void Update(){}
}
| 29.586207 | 81 | 0.632867 | [
"Apache-2.0"
] | christrees/unity-catccc | catccc/Assets/Scripts/BaseGameScripts/CameraScaler.cs | 860 | C# |
/**
* 描述:
* 每帧在 UpdateSystem 后执行一次的系统
* @author ciao
* @create 2020-01-08 17:17
*/
namespace Entitas
{
public interface ILateUpdateSystem : Entitas.ISystem
{
void LateUpdate();
}
} | 14.928571 | 56 | 0.617225 | [
"MIT"
] | qinciao/Entitas-CSharp | Entitas/Entitas/Systems/Interfaces/ILateUpdateSystem.cs | 235 | C# |
using SecurityDoors.BLL.Interfaces;
using SecurityDoors.Core;
using System;
namespace SecurityDoors.BLL.Controllers
{
public class ConnectionSettings : IConnectionSettings
{
/// <summary>
/// IP адрес.
/// </summary>
public string IP { get; set; }
/// <summary>
/// Порт.
/// </summary>
public int? Port { get; set; }
/// <summary>
/// API порт.
/// </summary>
public int? PortAPI { get; set; }
/// <summary>
/// Секретный ключ.
/// </summary>
public string SecretKey { get; set; }
/// <summary>
/// Конструктор.
/// </summary>
public ConnectionSettings()
{
IP = Properties.Settings.Default.IP;
Port = Properties.Settings.Default.Port;
PortAPI = Properties.Settings.Default.PortApi;
SecretKey = Properties.Settings.Default.SecretKey;
}
/// <summary>
/// Конструктор с параметрами.
/// </summary>
/// <param name="ip">IP адрес.</param>
/// <param name="port">порт.</param>
/// <param name="portAPI">API порт.</param>
/// <param name="key">секретный ключ.</param>
public ConnectionSettings(string ip, int port, int portAPI, string key)
{
IP = ip;
Port = port;
PortAPI = portAPI;
SecretKey = key;
}
/// <inheritdoc/>
public string SaveProperties()
{
var checkResult = CheckSettings();
if (checkResult == null)
{
Properties.Settings.Default.IP = IP;
Properties.Settings.Default.Port = Port.Value;
Properties.Settings.Default.PortApi = PortAPI.Value;
Properties.Settings.Default.SecretKey = SecretKey;
Properties.Settings.Default.Save();
return Constants.SETTING_SAVE_SUCCESSED;
}
return checkResult;
}
/// <inheritdoc/>
public void SetDefaultProperties()
{
IP = Properties.Settings.Default.IP;
Port = Properties.Settings.Default.Port;
PortAPI = Properties.Settings.Default.PortApi;
SecretKey = Properties.Settings.Default.SecretKey;
}
/// <inheritdoc/>
public string CheckSettings()
{
if (string.IsNullOrEmpty(IP) || string.IsNullOrWhiteSpace(IP))
{
return new ArgumentException(Constants.SETTING_NULL, nameof(IP)).ToString();
}
if (Port == null)
{
return new ArgumentNullException(Constants.SETTING_NULL, nameof(Port)).ToString();
}
if (PortAPI == null)
{
return new ArgumentNullException(Constants.SETTING_NULL, nameof(PortAPI)).ToString();
}
if (string.IsNullOrEmpty(SecretKey))
{
return new ArgumentException(Constants.SETTING_NULL, nameof(SecretKey)).ToString();
}
return null;
}
/// <inheritdoc/>
public string CheckSettings(string ip, int? port, int? portApi, string secretKey)
{
if (string.IsNullOrEmpty(ip) || string.IsNullOrWhiteSpace(ip))
{
return new ArgumentException(Constants.SETTING_NULL, nameof(ip)).ToString();
}
if (port == null)
{
return new ArgumentNullException(Constants.SETTING_NULL, nameof(port)).ToString();
}
if (portApi == null)
{
return new ArgumentNullException(Constants.SETTING_NULL, nameof(portApi)).ToString();
}
if (string.IsNullOrEmpty(secretKey))
{
return new ArgumentException(Constants.SETTING_NULL, nameof(secretKey)).ToString();
}
return default;
}
}
}
| 29.904412 | 101 | 0.525695 | [
"MIT"
] | securedevteam/Security-Door-Modeling | SecurityDoors.BLL/Controllers/ConnectionSettings.cs | 4,155 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.452)
// Version 5.452.0.0 www.ComponentFactory.com
// *****************************************************************************
using System.Drawing;
using ComponentFactory.Krypton.Toolkit;
namespace ComponentFactory.Krypton.Navigator
{
/// <summary>
/// Navigator view element for drawing a stack check button for a krypton page.
/// </summary>
internal class ViewDrawNavCheckButtonStack : ViewDrawNavCheckButtonBase
{
#region Identity
/// <summary>
/// Initialize a new instance of the ViewDrawNavCheckButtonStack class.
/// </summary>
/// <param name="navigator">Owning navigator instance.</param>
/// <param name="page">Page this check button represents.</param>
/// <param name="orientation">Orientation for the check button.</param>
public ViewDrawNavCheckButtonStack(KryptonNavigator navigator,
KryptonPage page,
VisualOrientation orientation)
: base(navigator, page, orientation)
{
}
/// <summary>
/// Obtains the String representation of this instance.
/// </summary>
/// <returns>User readable name of the instance.</returns>
public override string ToString()
{
// Return the class name and instance identifier
return "ViewDrawNavCheckButtonStack:" + Id;
}
#endregion
#region UpdateButtonSpecMapping
/// <summary>
/// Update the button spec manager mapping to reflect current settings.
/// </summary>
public override void UpdateButtonSpecMapping()
{
// Define a default mapping for text color and recreate to use that new setting
ButtonSpecManager.SetRemapTarget(Navigator.Stack.CheckButtonStyle);
ButtonSpecManager.RecreateButtons();
}
#endregion
#region IContentValues
/// <summary>
/// Gets the content image.
/// </summary>
/// <param name="state">The state for which the image is needed.</param>
/// <returns>Image value.</returns>
public override Image GetImage(PaletteState state)
{
return Page.GetImageMapping(Navigator.Stack.StackMapImage);
}
/// <summary>
/// Gets the content short text.
/// </summary>
/// <returns>String value.</returns>
public override string GetShortText()
{
return Page.GetTextMapping(Navigator.Stack.StackMapText);
}
/// <summary>
/// Gets the content long text.
/// </summary>
/// <returns>String value.</returns>
public override string GetLongText()
{
return Page.GetTextMapping(Navigator.Stack.StackMapExtraText);
}
#endregion
}
}
| 39.277778 | 157 | 0.592079 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-NET-5.452 | Source/Krypton Components/ComponentFactory.Krypton.Navigator/View Draw/ViewDrawNavCheckButtonStack.cs | 3,538 | C# |
namespace Demo.WindowsForms
{
using System.Windows.Forms;
using GMap.NET.WindowsForms;
using System.Drawing;
using System;
using System.Globalization;
/// <summary>
/// custom map of GMapControl
/// </summary>
public class Map : GMapControl
{
public long ElapsedMilliseconds;
#if DEBUG
private int _counter;
readonly Font _debugFont = new Font(FontFamily.GenericSansSerif, 14, FontStyle.Regular);
readonly Font _debugFontSmall = new Font(FontFamily.GenericSansSerif, 12, FontStyle.Bold);
DateTime _start;
DateTime _end;
int _delta;
protected override void OnPaint(PaintEventArgs e)
{
_start = DateTime.Now;
base.OnPaint(e);
_end = DateTime.Now;
_delta = (int)(_end - _start).TotalMilliseconds;
}
/// <summary>
/// any custom drawing here
/// </summary>
/// <param name="g"></param>
protected override void OnPaintOverlays(Graphics g)
{
base.OnPaintOverlays(g);
g.DrawString(string.Format(CultureInfo.InvariantCulture, "{0:0.0}", Zoom) + "z, " + MapProvider + ", refresh: " + _counter++ + ", load: " + ElapsedMilliseconds + "ms, render: " + _delta + "ms", _debugFont, Brushes.Blue, _debugFont.Height, _debugFont.Height + 20);
//g.DrawString(ViewAreaPixel.Location.ToString(), DebugFontSmall, Brushes.Blue, DebugFontSmall.Height, DebugFontSmall.Height);
//string lb = ViewAreaPixel.LeftBottom.ToString();
//var lbs = g.MeasureString(lb, DebugFontSmall);
//g.DrawString(lb, DebugFontSmall, Brushes.Blue, DebugFontSmall.Height, Height - DebugFontSmall.Height * 2);
//string rb = ViewAreaPixel.RightBottom.ToString();
//var rbs = g.MeasureString(rb, DebugFontSmall);
//g.DrawString(rb, DebugFontSmall, Brushes.Blue, Width - rbs.Width - DebugFontSmall.Height, Height - DebugFontSmall.Height * 2);
//string rt = ViewAreaPixel.RightTop.ToString();
//var rts = g.MeasureString(rb, DebugFontSmall);
//g.DrawString(rt, DebugFontSmall, Brushes.Blue, Width - rts.Width - DebugFontSmall.Height, DebugFontSmall.Height);
}
#endif
}
}
| 35.725806 | 272 | 0.652822 | [
"MIT"
] | AkisKK/GMap.NET | Demo/Demo.WindowsForms/Source/Map.cs | 2,217 | C# |
using System.Configuration;
using System.Runtime.InteropServices;
namespace SynologyClient
{
public class AppSettingsClientConfig : ISynologyClientConfig
{
public AppSettingsClientConfig()
{
ApiBaseAddressAndPathNoTrailingSlash = ConfigurationManager.AppSettings.Get("Syno.ApiBaseAddress");
User = ConfigurationManager.AppSettings.Get("Syno.User");
Password = ConfigurationManager.AppSettings.Get("Syno.Pass");
if (string.IsNullOrWhiteSpace(ApiBaseAddressAndPathNoTrailingSlash) || string.IsNullOrWhiteSpace(User) ||
string.IsNullOrWhiteSpace(Password))
{
var machineconfig = RuntimeEnvironment.GetRuntimeDirectory() + "Config\\machine.config";
throw new SynologyClientException(
"Missing Credentials. Please enter the appSettings Syno.User, Syno.Pass, Syno.ApiBaseAddress keys and values in the app.config or machine config at " +
machineconfig);
}
}
public string ApiBaseAddressAndPathNoTrailingSlash { get; private set; }
public string User { get; private set; }
public string Password { get; private set; }
}
} | 44.214286 | 171 | 0.670436 | [
"Apache-2.0"
] | brunskillage/Synology.NET | SynologyClient/AppSettingsClientConfig.cs | 1,240 | C# |
using System;
using TrueCraft.Core.Logic.Items;
namespace TrueCraft.Core.Logic.Blocks
{
public class CobwebBlock : BlockProvider
{
public static readonly byte BlockID = 0x1E;
public override byte ID { get { return 0x1E; } }
public override double BlastResistance { get { return 20; } }
public override double Hardness { get { return 4; } }
public override byte Luminance { get { return 0; } }
public override bool Opaque { get { return false; } }
public override bool DiffuseSkyLight
{
get
{
return true;
}
}
public override ToolType EffectiveTools
{
get
{
return ToolType.Sword;
}
}
public override string DisplayName { get { return "Cobweb"; } }
public override Tuple<int, int> GetTextureMap(byte metadata)
{
return new Tuple<int, int>(11, 0);
}
protected override ItemStack[] GetDrop(BlockDescriptor descriptor, ItemStack item)
{
return new[] { new ItemStack(StringItem.ItemID, 1, descriptor.Metadata) };
}
}
} | 25.833333 | 90 | 0.551613 | [
"MIT"
] | mrj001/TrueCraft | TrueCraft.Core/Logic/Blocks/CobwebBlock.cs | 1,240 | C# |
using System;
using System.Reflection;
namespace
MacroAttributeGuards
{
public static class
MethodBaseExtensions
{
/// <summary>
/// Begin guarding arguments
/// </summary>
///
public static MethodGuard
Guard(this MethodBase method)
{
if (method == null) throw new ArgumentNullException(nameof(method));
return new MethodGuard(method);
}
}
}
| 13.344828 | 73 | 0.674419 | [
"MIT"
] | macro187/MacroAttributeGuards | MacroAttributeGuards/MethodBaseExtensions.cs | 389 | C# |
using System;
using netduino.helpers.Hardware;
using netduino.helpers.Fun;
using netduino.helpers.Helpers;
using SecretLabs.NETMF.Hardware;
namespace netduino.helpers.Fun {
public class ConsoleHardwareConfig {
public int Version { get; private set; }
public AnalogJoystick JoystickLeft { get; set; }
public AnalogJoystick JoystickRight { get; set; }
public Max72197221 Matrix { get; set; }
public PWM Speaker { get; set; }
public SDResourceLoader Resources { get; set; }
public PushButton LeftButton { get; set; }
public PushButton RightButton { get; set; }
public ConsoleHardwareConfig(object[] args) {
Version = (int)args[(int)CartridgeVersionInfo.LoaderArgumentsVersion100.Version];
if (100 == Version) {
JoystickLeft = (AnalogJoystick)args[(int)CartridgeVersionInfo.LoaderArgumentsVersion100.JoystickLeft];
JoystickRight = (AnalogJoystick)args[(int)CartridgeVersionInfo.LoaderArgumentsVersion100.JoystickRight];
Matrix = (Max72197221)args[(int)CartridgeVersionInfo.LoaderArgumentsVersion100.Matrix];
Speaker = (PWM)args[(int)CartridgeVersionInfo.LoaderArgumentsVersion100.Speaker];
Resources = (SDResourceLoader)args[(int)CartridgeVersionInfo.LoaderArgumentsVersion100.SDResourceLoader];
LeftButton = (PushButton)args[(int)CartridgeVersionInfo.LoaderArgumentsVersion100.ButtonLeft];
RightButton = (PushButton)args[(int)CartridgeVersionInfo.LoaderArgumentsVersion100.ButtonRight];
}
else {
throw new ArgumentException("args");
}
}
}
}
| 47.694444 | 121 | 0.682003 | [
"BSD-3-Clause"
] | Ledridge/netduinohelpers | Fun/ConsoleHardwareConfig.cs | 1,717 | C# |
using System;
using HanumanInstitute.OntraportApi.Converters;
namespace HanumanInstitute.OntraportApi.Models
{
/// <summary>
/// Forms are used to simply and easily gather information from your contacts.
/// </summary>
public class ApiForm : ApiObject
{
public ApiForm() : base("form_id")
{ }
/// <summary>
/// Returns a ApiProperty object to get or set an arbitrary name for the form.
/// </summary>
public ApiPropertyString FormNameField => _formNameField ??= new ApiPropertyString(this, FormNameKey);
private ApiPropertyString? _formNameField;
public const string FormNameKey = "formname";
/// <summary>
/// Gets or sets an arbitrary name for the form.
/// </summary>
public string? FormName { get => FormNameField.Value; set => FormNameField.Value = value; }
/// <summary>
/// Returns a ApiProperty object to get or set the type of form.
/// </summary>
public ApiProperty<FormType> TypeField => _typeField ??= new ApiPropertyIntEnum<FormType>(this, TypeKey);
private ApiProperty<FormType>? _typeField;
public const string TypeKey = "type";
/// <summary>
/// Gets or sets the type of form.
/// </summary>
public FormType? Type { get => TypeField.Value; set => TypeField.Value = value; }
/// <summary>
/// Returns a ApiProperty object to get or set the tags a contact should be added to upon form fillout.
/// </summary>
public ApiPropertyString TagsField => _tagsField ??= new ApiPropertyString(this, TagsKey);
private ApiPropertyString? _tagsField;
public const string TagsKey = "tags";
/// <summary>
/// Gets or sets the tags a contact should be added to upon form fillout.
/// </summary>
public string? Tags { get => TagsField.Value; set => TagsField.Value = value; }
/// <summary>
/// Returns a ApiProperty object to get or set the sequences a contact should be added to upon form fillout.
/// </summary>
public ApiPropertyString SequencesField => _sequencesField ??= new ApiPropertyString(this, SequencesKey);
private ApiPropertyString? _sequencesField;
public const string SequencesKey = "sequences";
/// <summary>
/// Gets or sets the sequences a contact should be added to upon form fillout.
/// </summary>
public string? Sequences { get => SequencesField.Value; set => SequencesField.Value = value; }
/// <summary>
/// Returns a ApiProperty object to get or set the URL for the thank you page the user is redirected to upon form fillout.
/// </summary>
public ApiPropertyString RedirectUrlField => _redirectUrlField ??= new ApiPropertyString(this, RedirectUrlKey);
private ApiPropertyString? _redirectUrlField;
public const string RedirectUrlKey = "redirect";
/// <summary>
/// Gets or sets the URL for the thank you page the user is redirected to upon form fillout.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1056:Uri properties should not be strings", Justification = "Reviewed: we only work with raw Ontraport data")]
public string? RedirectUrl { get => RedirectUrlField.Value; set => RedirectUrlField.Value = value; }
/// <summary>
/// Returns a ApiProperty object to get or set the ID of the user controlling the form.
/// </summary>
public ApiProperty<int> OwnerField => _ownerField ??= new ApiProperty<int>(this, OwnerKey);
private ApiProperty<int>? _ownerField;
public const string OwnerKey = "owner";
/// <summary>
/// Gets or sets the ID of the user controlling the form.
/// </summary>
public int? Owner { get => OwnerField.Value; set => OwnerField.Value = value; }
/// <summary>
/// Returns a ApiProperty object to get or set whether or not the form includes a Captcha.
/// </summary>
public ApiPropertyIntBool HasCatchaField => _hasCaptchaField ??= new ApiPropertyIntBool(this, HasCatchaKey);
private ApiPropertyIntBool? _hasCaptchaField;
public const string HasCatchaKey = "captcha";
/// <summary>
/// Gets or sets whether or not the form includes a Captcha.
/// </summary>
public bool? HasCatcha { get => HasCatchaField.Value; set => HasCatchaField.Value = value; }
/// <summary>
/// Returns a ApiProperty object to get or set the email address to send notififications when the form is filled out.
/// </summary>
public ApiPropertyString NotificationEmailField => _notificationEmailField ??= new ApiPropertyString(this, NotificationEmailKey);
private ApiPropertyString? _notificationEmailField;
public const string NotificationEmailKey = "notif";
/// <summary>
/// Gets or sets the email address to send notififications when the form is filled out.
/// </summary>
public string? NotificationEmail { get => NotificationEmailField.Value; set => NotificationEmailField.Value = value; }
/// <summary>
/// Returns a ApiProperty object to get or set the number of times the form has been filled out.
/// </summary>
public ApiProperty<int> FilloutsField => _filloutsField ??= new ApiProperty<int>(this, FilloutsKey);
private ApiProperty<int>? _filloutsField;
public const string FilloutsKey = "fillouts";
/// <summary>
/// Gets or sets the number of times the form has been filled out.
/// </summary>
public int? Fillouts { get => FilloutsField.Value; set => FilloutsField.Value = value; }
/// <summary>
/// Returns a ApiProperty object to get or set the JSON-encoded form data.
/// </summary>
public ApiPropertyString JsonRawDataField => _jsonRawDataField ??= new ApiPropertyString(this, JsonRawDataKey);
private ApiPropertyString? _jsonRawDataField;
public const string JsonRawDataKey = "json_raw_object";
/// <summary>
/// Gets or sets the JSON-encoded form data.
/// </summary>
public string? JsonRawData { get => JsonRawDataField.Value; set => JsonRawDataField.Value = value; }
/// <summary>
/// Returns a ApiProperty object to get or set whether or not the form has been deleted.
/// </summary>
public ApiPropertyIntBool DeletedField => _deletedField ??= new ApiPropertyIntBool(this, DeletedKey);
private ApiPropertyIntBool? _deletedField;
public const string DeletedKey = "deleted";
/// <summary>
/// Gets or sets whether or not the form has been deleted.
/// </summary>
public bool? Deleted { get => DeletedField.Value; set => DeletedField.Value = value; }
/// <summary>
/// Returns a ApiProperty object to get or set the ID of the object type associated with the form.
/// </summary>
public ApiProperty<int> ObjectTypeIdField => _objectTypeIdField ??= new ApiProperty<int>(this, ObjectTypeIdKey);
private ApiProperty<int>? _objectTypeIdField;
public const string ObjectTypeIdKey = "object_type_id";
/// <summary>
/// Gets or sets the ID of the object type associated with the form.
/// </summary>
public int? ObjectTypeId { get => ObjectTypeIdField.Value; set => ObjectTypeIdField.Value = value; }
/// <summary>
/// Returns a ApiProperty object to get or set whether or not the form has a responsive layout.
/// </summary>
public ApiPropertyIntBool ResponsiveLayoutField => _responsiveLayoutField ??= new ApiPropertyIntBool(this, ResponsiveLayoutKey);
private ApiPropertyIntBool? _responsiveLayoutField;
public const string ResponsiveLayoutKey = "responsive";
/// <summary>
/// Gets or sets whether or not the form has a responsive layout.
/// </summary>
public bool? ResponsiveLayout { get => ResponsiveLayoutField.Value; set => ResponsiveLayoutField.Value = value; }
/// <summary>
/// Returns a ApiProperty object to get or set the number of times the form has been visited.
/// </summary>
public ApiProperty<int> VisitsField => _visitsField ??= new ApiProperty<int>(this, VisitsKey);
private ApiProperty<int>? _visitsField;
public const string VisitsKey = "visits";
/// <summary>
/// Gets or sets the number of times the form has been visited.
/// </summary>
public int? Visits { get => VisitsField.Value; set => VisitsField.Value = value; }
/// <summary>
/// Returns a ApiProperty object to get or set the number of times unique visitors have visited the form.
/// </summary>
public ApiProperty<int> UniqueVisitsField => _uniqueVisitsField ??= new ApiProperty<int>(this, UniqueVisitsKey);
private ApiProperty<int>? _uniqueVisitsField;
public const string UniqueVisitsKey = "unique_visits";
/// <summary>
/// Gets or sets the number of times unique visitors have visited the form.
/// </summary>
public int? UniqueVisits { get => UniqueVisitsField.Value; set => UniqueVisitsField.Value = value; }
/// <summary>
/// Returns a ApiProperty object to get or set the date and time the form was created. Note that this field will not contain data for any forms created prior to November 7, 2017.
/// </summary>
public ApiPropertyDateTime DateCreatedField => _dateCreatedField ??= new ApiPropertyDateTime(this, DateCreatedKey);
private ApiPropertyDateTime? _dateCreatedField;
public const string DateCreatedKey = "date";
/// <summary>
/// Gets or sets the date and time the form was created. Note that this field will not contain data for any forms created prior to November 7, 2017.
/// </summary>
public DateTimeOffset? DateCreated { get => DateCreatedField.Value; set => DateCreatedField.Value = value; }
/// <summary>
/// Returns a ApiProperty object to get or set the date and time the form was last modified.
/// </summary>
public ApiPropertyDateTime DateModifiedField => _dateModifiedField ??= new ApiPropertyDateTime(this, DateModifiedKey);
private ApiPropertyDateTime? _dateModifiedField;
public const string DateModifiedKey = "dlm";
/// <summary>
/// Gets or sets the date and time the form was last modified.
/// </summary>
public DateTimeOffset? DateModified { get => DateModifiedField.Value; set => DateModifiedField.Value = value; }
public ApiPropertyString CampaignsField => _campaignsField ??= new ApiPropertyString(this, CampaignsKey);
private ApiPropertyString? _campaignsField;
public const string CampaignsKey = "campaigns";
public string? Campaigns { get => CampaignsField.Value; set => CampaignsField.Value = value; }
public ApiProperty<int> UniqueFilloutsField => _uniqueFilloutsField ??= new ApiProperty<int>(this, UniqueFilloutsKey);
private ApiProperty<int>? _uniqueFilloutsField;
public const string UniqueFilloutsKey = "unique_fillouts";
public int? UniqueFillouts { get => UniqueFilloutsField.Value; set => UniqueFilloutsField.Value = value; }
public ApiProperty<decimal> RevenueField => _revenueField ??= new ApiProperty<decimal>(this, RevenueKey);
private ApiProperty<decimal>? _revenueField;
public const string RevenueKey = "revenue";
public decimal? Revenue { get => RevenueField.Value; set => RevenueField.Value = value; }
public ApiProperty<int> UniqueConvertField => _uniqueConvertField ??= new ApiProperty<int>(this, UniqueConvertKey);
private ApiProperty<int>? _uniqueConvertField;
public const string UniqueConvertKey = "unique_convert";
public int? UniqueConvert { get => UniqueConvertField.Value; set => UniqueConvertField.Value = value; }
/// <summary>
/// The type of form.
/// </summary>
public enum FormType
{
SmartForm = 10,
ONTRAform = 11
}
}
}
| 53.154506 | 186 | 0.655713 | [
"BSD-2-Clause"
] | mysteryx93/OntraportApi.NET | OntraportApi/Models/ApiForm.cs | 12,387 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment5_3
{
public enum RoomType
{
Single,
Double,
Studio
}
interface IRoom
{
string RoomNumber { get; }
double Area { get; }
RoomType Type { get; }
double PricePerNight { get; }
string Description { get; }
}
}
| 17.28 | 37 | 0.592593 | [
"MIT"
] | HubUser99/Windows-Programming | Assignments/Assignment5/Assignment5_2/IRoom.cs | 434 | C# |
using System;
using System.Data.Entity;
using System.Linq;
using Gongchengshi.Collections.Generic;
namespace Gongchengshi.EF
{
public static class DbSetExtensions
{
static public T FirstOrAdd<T>(this DbSet<T> @this, Func<T, bool> predicate) where T : class, new()
{
return @this.FirstOr(predicate,
() =>
{
var x = new T();
@this.Add(x);
return x;
});
}
static public T FirstOrAdd<T>(this DbSet<T> @this, Func<T, bool> predicate, Func<T> initializer) where T : class
{
return @this.FirstOr(predicate,
() =>
{
var x = initializer();
@this.Add(x);
return x;
});
}
static public T FirstOrAdd<T>(this DbSet<T> @this, Func<T, bool> predicate, T item) where T : class
{
return @this.FirstOr(predicate,
() =>
{
@this.Add(item);
return item;
});
}
static public void IfNotContainsAdd<T>(this DbSet<T> @this, Func<T, bool> predicate, Func<T> initializer) where T : class
{
if (!@this.Any(predicate))
{
@this.Add(initializer());
}
}
}
}
| 34.176471 | 129 | 0.36833 | [
"MIT"
] | gongchengshi/DotNet-Common.EF | Common.EF/DbSetExtensions.cs | 1,745 | C# |
using System;
using System.Reflection;
using System.Resources;
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("Sage300MenuExtension")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Sage Software, Inc.")]
[assembly: AssemblyProduct("Sage300MenuExtension")]
[assembly: AssemblyCopyright("Copyright (c) 1994-2020 Sage Software, Inc. All rights reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
[assembly: NeutralResourcesLanguage("en-US")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2020.0.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
| 33.918919 | 98 | 0.743426 | [
"MIT"
] | PeterSorokac/Sage300-SDK | src/wizards/Sage300LanguageResourceWizard/Sage300LanguageResourceWizardMenuExtension/Properties/AssemblyInfo.cs | 1,257 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18034
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WindowsFormsApplication3.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.806452 | 151 | 0.586654 | [
"MIT"
] | pmabres/vbcsharpgames | Projects/WindowsFormsApplication3/WindowsFormsApplication3/Properties/Settings.Designer.cs | 1,081 | 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 Microsoft.AspNetCore.WebHooks.Metadata;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Methods to add services for the AzureContainerRegistry receiver.
/// </summary>
internal static class AzureContainerRegistryServiceCollectionSetup
{
/// <summary>
/// Add services for the AzureContainerRegistry receiver.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to update.</param>
public static void AddAzureContainerRegistryServices(IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
WebHookMetadata.Register<AzureContainerRegistryMetadata>(services);
}
}
}
| 34.448276 | 111 | 0.671672 | [
"Apache-2.0"
] | AhmadShabbir3518/WebHooks | src/Microsoft.AspNetCore.WebHooks.Receivers.AzureContainerRegistry/Extensions/AzureContainerRegistryServiceCollectionSetup.cs | 999 | C# |
using FamilyTree.Domain.Entities.Media;
using FamilyTree.Domain.Entities.Privacy;
using FamilyTree.Domain.Entities.Tree;
using FamilyTree.Domain.Entities.PersonContent;
using Microsoft.EntityFrameworkCore;
using System.Threading;
using System.Threading.Tasks;
using FamilyTree.Domain.Entities.Identity;
namespace FamilyTree.Application.Common.Interfaces
{
public interface IApplicationDbContext
{
DbSet<Profile> Profiles { get; set; }
DbSet<Person> People { get; set; }
DbSet<FamilyTie> FamilyTies { get; set; }
DbSet<FamilyTreeEntity> FamilyTrees { get; set; }
DbSet<DataCategory> DataCategories { get; set; }
DbSet<DataBlock> DataBlocks { get; set; }
DbSet<DataHolder> DataHolders { get; set; }
DbSet<PrivacyEntity> Privacies { get; set; }
DbSet<Image> Images { get; set; }
DbSet<DataBlockImage> DataBlockImages { get; set; }
DbSet<Video> Videos { get; set; }
DbSet<DataBlockVideo> DataBlockVideos { get; set; }
DbSet<Audio> Audios { get; set; }
DbSet<DataBlockAudio> DataBlockAudios { get; set; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
}
}
| 27.044444 | 72 | 0.685292 | [
"MIT"
] | VuacheslavSichkarenko/FamilyTree | FamilyTree.Application/Common/Interfaces/IApplicationDbContext.cs | 1,219 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using HomeAPI.Backend.Controllers;
using HomeAPI.Backend.Models.TimeSeries;
using HomeAPI.Backend.Options;
using HomeAPI.Backend.Providers.TimeSeries;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using NSubstitute;
using Xunit;
namespace HomeAPI.Backend.Tests.Controllers
{
public class TimeSeriesControllerTests
{
#region default data
PreconfiguredTimeSeries preconfiguredTimeSeries1 = new()
{
Elements = new()
{
new()
{
DisplayName = "xyz1",
MeasurementName = "temperature",
MeasurementLocation = "Room1"
}
}
};
PreconfiguredTimeSeries preconfiguredTimeSeries2 = new()
{
Elements = new()
{
new()
{
DisplayName = "xyz1",
MeasurementName = "temperature",
MeasurementLocation = "Room1"
},
new()
{
DisplayName = "xyz1",
MeasurementName = "temperature",
MeasurementLocation = "Room2"
}
}
};
PreconfiguredTimeSeries preconfiguredTimeSeries3 = new()
{
Elements = new()
{
new()
{
DisplayName = "xyz1",
MeasurementName = null,
MeasurementLocation = "Room1"
}
}
};
PreconfiguredTimeSeries preconfiguredTimeSeries4 = new()
{
Elements = new()
{
new()
{
DisplayName = "xyz1",
MeasurementName = "temperature",
MeasurementLocation = null
}
}
};
#endregion
#region GetTimeSeries
[Fact]
public async Task GetTimeSeries_InternalError()
{
TimeSeriesResponse response = new TimeSeriesResponse()
{
Status = TimeSeriesResponseStatus.InternalError,
TimeSeriesResult = new()
{
DisplayName = "xyz",
DataPoints = null
}
};
IInfluxDBProvider influxProvider = Substitute.For<IInfluxDBProvider>();
influxProvider.GetTimeSeriesAsync(Arg.Any<TimeSeriesRequest>(), Arg.Any<string>()).Returns(Task.FromResult(response));
var optionsMonitor = Substitute.For<IOptionsMonitor<PreconfiguredTimeSeries>>();
optionsMonitor.CurrentValue.Returns(preconfiguredTimeSeries1);
TimeSeriesController controller = new TimeSeriesController(influxProvider, optionsMonitor);
var result = await controller.GetTimeSeries("temperature", "Room1", TimeSeriesRange.OneDay);
Assert.IsType<NotFoundResult>(result.Result);
}
[Fact]
public async Task GetTimeSeries_BadRequest()
{
TimeSeriesResponse response = new TimeSeriesResponse()
{
Status = TimeSeriesResponseStatus.BadRequest,
TimeSeriesResult = new()
{
DisplayName = "xyz",
DataPoints = null
}
};
IInfluxDBProvider influxProvider = Substitute.For<IInfluxDBProvider>();
influxProvider.GetTimeSeriesAsync(Arg.Any<TimeSeriesRequest>(), Arg.Any<string>()).Returns(Task.FromResult(response));
var optionsMonitor = Substitute.For<IOptionsMonitor<PreconfiguredTimeSeries>>();
optionsMonitor.CurrentValue.Returns(preconfiguredTimeSeries1);
TimeSeriesController controller = new TimeSeriesController(influxProvider, optionsMonitor);
var result = await controller.GetTimeSeries("temperature", "Room1", TimeSeriesRange.OneDay);
Assert.IsType<BadRequestResult>(result.Result);
}
[Fact]
public async Task GetTimeSeries_MeasurementNameNull()
{
IInfluxDBProvider influxProvider = Substitute.For<IInfluxDBProvider>();
var optionsMonitor = Substitute.For<IOptionsMonitor<PreconfiguredTimeSeries>>();
TimeSeriesController controller = new TimeSeriesController(influxProvider, optionsMonitor);
var result = await controller.GetTimeSeries(null, "inside", TimeSeriesRange.OneMonth);
await influxProvider.DidNotReceive().GetTimeSeriesAsync(Arg.Any<TimeSeriesRequest>(), Arg.Any<string>());
Assert.IsType<BadRequestResult>(result.Result);
}
[Fact]
public async Task GetTimeSeries_MeasurementLocationNull()
{
IInfluxDBProvider influxProvider = Substitute.For<IInfluxDBProvider>();
var optionsMonitor = Substitute.For<IOptionsMonitor<PreconfiguredTimeSeries>>();
TimeSeriesController controller = new TimeSeriesController(influxProvider, optionsMonitor);
var result = await controller.GetTimeSeries("temperature", null, TimeSeriesRange.OneMonth);
await influxProvider.DidNotReceive().GetTimeSeriesAsync(Arg.Any<TimeSeriesRequest>(), Arg.Any<string>());
Assert.IsType<BadRequestResult>(result.Result);
}
[Fact]
public async Task GetTimeSeries_Success()
{
var dataPoints = new List<DataPoint>()
{
new DataPoint<float>(new DateTime(2020, 10, 30), 3.14f),
new DataPoint<float>(new DateTime(2020, 10, 31), 3.14f)
};
TimeSeriesResponse response = new TimeSeriesResponse()
{
Status = TimeSeriesResponseStatus.Success,
TimeSeriesResult = new()
{
DisplayName = "xyz",
DataPoints = dataPoints
}
};
IInfluxDBProvider influxProvider = Substitute.For<IInfluxDBProvider>();
influxProvider.GetTimeSeriesAsync(Arg.Any<TimeSeriesRequest>(), Arg.Any<string>()).Returns(Task.FromResult(response));
var optionsMonitor = Substitute.For<IOptionsMonitor<PreconfiguredTimeSeries>>();
optionsMonitor.CurrentValue.Returns(preconfiguredTimeSeries1);
TimeSeriesController controller = new TimeSeriesController(influxProvider, optionsMonitor);
var result = await controller.GetTimeSeries("temperature", "Room1", TimeSeriesRange.OneDay);
var okResult = Assert.IsType<OkObjectResult>(result.Result);
var resultObj = Assert.IsType<TimeSeriesResult>(okResult.Value);
Assert.Equal(dataPoints, resultObj.DataPoints);
}
#endregion
#region GetPreconfiguredTimeSeries
[Fact]
public async Task GetPreconfiguredTimeSeries_InternalError()
{
TimeSeriesResponse response1 = new TimeSeriesResponse()
{
Status = TimeSeriesResponseStatus.Success,
TimeSeriesResult = new()
{
DisplayName = "xyz",
DataPoints = new()
}
};
TimeSeriesResponse response2 = new TimeSeriesResponse()
{
Status = TimeSeriesResponseStatus.InternalError,
TimeSeriesResult = new()
{
DisplayName = "xyz",
DataPoints = null
}
};
IInfluxDBProvider influxProvider = Substitute.For<IInfluxDBProvider>();
influxProvider.GetTimeSeriesAsync(Arg.Any<TimeSeriesRequest>(), Arg.Any<string>()).Returns(Task.FromResult(response1), Task.FromResult(response2));
var optionsMonitor = Substitute.For<IOptionsMonitor<PreconfiguredTimeSeries>>();
optionsMonitor.CurrentValue.Returns(preconfiguredTimeSeries2);
TimeSeriesController controller = new TimeSeriesController(influxProvider, optionsMonitor);
var result = await controller.GetPreconfiguredTimeSeries(TimeSeriesRange.OneDay);
Assert.IsType<NotFoundResult>(result.Result);
}
[Fact]
public async Task GetPreconfiguredTimeSeries_BadRequest()
{
TimeSeriesResponse response1 = new TimeSeriesResponse()
{
Status = TimeSeriesResponseStatus.Success,
TimeSeriesResult = new()
{
DisplayName = "xyz",
DataPoints = new()
}
};
TimeSeriesResponse response2 = new TimeSeriesResponse()
{
Status = TimeSeriesResponseStatus.BadRequest,
TimeSeriesResult = new()
{
DisplayName = "xyz",
DataPoints = null
}
};
IInfluxDBProvider influxProvider = Substitute.For<IInfluxDBProvider>();
influxProvider.GetTimeSeriesAsync(Arg.Any<TimeSeriesRequest>(), Arg.Any<string>()).Returns(Task.FromResult(response1), Task.FromResult(response2));
var optionsMonitor = Substitute.For<IOptionsMonitor<PreconfiguredTimeSeries>>();
optionsMonitor.CurrentValue.Returns(preconfiguredTimeSeries2);
TimeSeriesController controller = new TimeSeriesController(influxProvider, optionsMonitor);
var result = await controller.GetPreconfiguredTimeSeries(TimeSeriesRange.OneDay);
Assert.IsType<BadRequestResult>(result.Result);
}
[Fact]
public async Task GetPreconfiguredTimeSeries_MeasurementNameNull()
{
IInfluxDBProvider influxProvider = Substitute.For<IInfluxDBProvider>();
var optionsMonitor = Substitute.For<IOptionsMonitor<PreconfiguredTimeSeries>>();
optionsMonitor.CurrentValue.Returns(preconfiguredTimeSeries3);
TimeSeriesController controller = new TimeSeriesController(influxProvider, optionsMonitor);
var result = await controller.GetPreconfiguredTimeSeries(TimeSeriesRange.OneMonth);
await influxProvider.DidNotReceive().GetTimeSeriesAsync(Arg.Any<TimeSeriesRequest>(), Arg.Any<string>());
Assert.IsType<BadRequestResult>(result.Result);
}
[Fact]
public async Task GetPreconfiguredTimeSeries_MeasurementLocationNull()
{
IInfluxDBProvider influxProvider = Substitute.For<IInfluxDBProvider>();
var optionsMonitor = Substitute.For<IOptionsMonitor<PreconfiguredTimeSeries>>();
optionsMonitor.CurrentValue.Returns(preconfiguredTimeSeries4);
TimeSeriesController controller = new TimeSeriesController(influxProvider, optionsMonitor);
var result = await controller.GetPreconfiguredTimeSeries(TimeSeriesRange.OneMonth);
await influxProvider.DidNotReceive().GetTimeSeriesAsync(Arg.Any<TimeSeriesRequest>(), Arg.Any<string>());
Assert.IsType<BadRequestResult>(result.Result);
}
[Fact]
public async Task GetPreconfiguredTimeSeries_Success()
{
var dataPoints1 = new List<DataPoint>()
{
new DataPoint<float>(new DateTime(2020, 10, 30), 3.14f),
new DataPoint<float>(new DateTime(2020, 10, 31), 3.14f)
};
var dataPoints2 = new List<DataPoint>()
{
new DataPoint<float>(new DateTime(2020, 1, 30), 3.14f),
new DataPoint<float>(new DateTime(2020, 1, 31), 3.14f)
};
TimeSeriesResponse response1 = new TimeSeriesResponse()
{
Status = TimeSeriesResponseStatus.Success,
TimeSeriesResult = new()
{
DisplayName = "xyz",
DataPoints = dataPoints1
}
};
TimeSeriesResponse response2 = new TimeSeriesResponse()
{
Status = TimeSeriesResponseStatus.Success,
TimeSeriesResult = new()
{
DisplayName = "xyz",
DataPoints = dataPoints2
}
};
IInfluxDBProvider influxProvider = Substitute.For<IInfluxDBProvider>();
influxProvider.GetTimeSeriesAsync(Arg.Any<TimeSeriesRequest>(), Arg.Any<string>()).Returns(Task.FromResult(response1), Task.FromResult(response2));
var optionsMonitor = Substitute.For<IOptionsMonitor<PreconfiguredTimeSeries>>();
optionsMonitor.CurrentValue.Returns(preconfiguredTimeSeries2);
TimeSeriesController controller = new TimeSeriesController(influxProvider, optionsMonitor);
var result = await controller.GetPreconfiguredTimeSeries(TimeSeriesRange.OneDay);
await influxProvider.Received(2).GetTimeSeriesAsync(Arg.Any<TimeSeriesRequest>(), Arg.Any<string>());
var okResult = Assert.IsType<OkObjectResult>(result.Result);
var resultObj = Assert.IsType<List<TimeSeriesResult>>(okResult.Value);
Assert.Equal(2, resultObj.Count);
Assert.Equal(dataPoints1, resultObj[0].DataPoints);
Assert.Equal(dataPoints2, resultObj[1].DataPoints);
}
#endregion
}
} | 33.381098 | 150 | 0.743082 | [
"MIT"
] | chwun/HomeAPI.Backend | HomeAPI.Backend.Tests/Controllers/TimeSeriesControllerTests.cs | 10,949 | C# |
/* Copyright 2010-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
#if NET452
using System.Runtime.Serialization;
#endif
using MongoDB.Bson;
namespace MongoDB.Driver
{
/// <summary>
/// Represents the result of a bulk write operation.
/// </summary>
#if NET452
[Serializable]
#endif
public abstract class BulkWriteResult
{
// fields
private readonly int _requestCount;
//constructors
/// <summary>
/// Initializes a new instance of the <see cref="BulkWriteResult"/> class.
/// </summary>
/// <param name="requestCount">The request count.</param>
protected BulkWriteResult(int requestCount)
{
_requestCount = requestCount;
}
// properties
/// <summary>
/// Gets the number of documents that were deleted.
/// </summary>
public abstract long DeletedCount { get; }
/// <summary>
/// Gets the number of documents that were inserted.
/// </summary>
public abstract long InsertedCount { get; }
/// <summary>
/// Gets a value indicating whether the bulk write operation was acknowledged.
/// </summary>
public abstract bool IsAcknowledged { get; }
/// <summary>
/// Gets a value indicating whether the modified count is available.
/// </summary>
/// <remarks>
/// The modified count is only available when all servers have been upgraded to 2.6 or above.
/// </remarks>
public abstract bool IsModifiedCountAvailable { get; }
/// <summary>
/// Gets the number of documents that were matched.
/// </summary>
public abstract long MatchedCount { get; }
/// <summary>
/// Gets the number of documents that were actually modified during an update.
/// </summary>
public abstract long ModifiedCount { get; }
/// <summary>
/// Gets the request count.
/// </summary>
public int RequestCount
{
get { return _requestCount; }
}
/// <summary>
/// Gets a list with information about each request that resulted in an upsert.
/// </summary>
public abstract IReadOnlyList<BulkWriteUpsert> Upserts { get; }
}
/// <summary>
/// Represents the result of a bulk write operation.
/// </summary>
/// <typeparam name="TDocument">The type of the document.</typeparam>
#if NET452
[Serializable]
#endif
public abstract class BulkWriteResult<TDocument> : BulkWriteResult
{
// private fields
private readonly IReadOnlyList<WriteModel<TDocument>> _processedRequests;
// constructors
/// <summary>
/// Initializes a new instance of the <see cref="BulkWriteResult" /> class.
/// </summary>
/// <param name="requestCount">The request count.</param>
/// <param name="processedRequests">The processed requests.</param>
protected BulkWriteResult(
int requestCount,
IEnumerable<WriteModel<TDocument>> processedRequests)
: base(requestCount)
{
_processedRequests = processedRequests.ToList();
}
// public properties
/// <summary>
/// Gets the processed requests.
/// </summary>
public IReadOnlyList<WriteModel<TDocument>> ProcessedRequests
{
get { return _processedRequests; }
}
// internal static methods
internal static BulkWriteResult<TDocument> FromCore(Core.Operations.BulkWriteOperationResult result)
{
if (result.IsAcknowledged)
{
return new Acknowledged(
result.RequestCount,
result.MatchedCount,
result.DeletedCount,
result.InsertedCount,
result.IsModifiedCountAvailable ? (long?)result.ModifiedCount : null,
result.ProcessedRequests.Select(r => WriteModel<TDocument>.FromCore(r)),
result.Upserts.Select(u => BulkWriteUpsert.FromCore(u)));
}
return new Unacknowledged(
result.RequestCount,
result.ProcessedRequests.Select(r => WriteModel<TDocument>.FromCore(r)));
}
internal static BulkWriteResult<TDocument> FromCore(Core.Operations.BulkWriteOperationResult result, IEnumerable<WriteModel<TDocument>> requests)
{
if (result.IsAcknowledged)
{
return new Acknowledged(
result.RequestCount,
result.MatchedCount,
result.DeletedCount,
result.InsertedCount,
result.IsModifiedCountAvailable ? (long?)result.ModifiedCount : null,
requests,
result.Upserts.Select(u => BulkWriteUpsert.FromCore(u)));
}
return new Unacknowledged(
result.RequestCount,
requests);
}
// nested classes
/// <summary>
/// Result from an acknowledged write concern.
/// </summary>
#if NET452
[Serializable]
#endif
public class Acknowledged : BulkWriteResult<TDocument>
{
// private fields
private readonly long _deletedCount;
private readonly long _insertedCount;
private readonly long _matchedCount;
private readonly long? _modifiedCount;
private readonly IReadOnlyList<BulkWriteUpsert> _upserts;
// constructors
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
/// <param name="requestCount">The request count.</param>
/// <param name="matchedCount">The matched count.</param>
/// <param name="deletedCount">The deleted count.</param>
/// <param name="insertedCount">The inserted count.</param>
/// <param name="modifiedCount">The modified count.</param>
/// <param name="processedRequests">The processed requests.</param>
/// <param name="upserts">The upserts.</param>
public Acknowledged(
int requestCount,
long matchedCount,
long deletedCount,
long insertedCount,
long? modifiedCount,
IEnumerable<WriteModel<TDocument>> processedRequests,
IEnumerable<BulkWriteUpsert> upserts)
: base(requestCount, processedRequests)
{
_matchedCount = matchedCount;
_deletedCount = deletedCount;
_insertedCount = insertedCount;
_modifiedCount = modifiedCount;
_upserts = upserts.ToList();
}
// public properties
/// <inheritdoc/>
public override long DeletedCount
{
get { return _deletedCount; }
}
/// <inheritdoc/>
public override long InsertedCount
{
get { return _insertedCount; }
}
/// <inheritdoc/>
public override bool IsAcknowledged
{
get { return true; }
}
/// <inheritdoc/>
public override bool IsModifiedCountAvailable
{
get { return _modifiedCount.HasValue; }
}
/// <inheritdoc/>
public override long MatchedCount
{
get { return _matchedCount; }
}
/// <inheritdoc/>
public override long ModifiedCount
{
get
{
if (!_modifiedCount.HasValue)
{
throw new NotSupportedException("ModifiedCount is not available.");
}
return _modifiedCount.Value;
}
}
/// <inheritdoc/>
public override IReadOnlyList<BulkWriteUpsert> Upserts
{
get { return _upserts; }
}
}
/// <summary>
/// Result from an unacknowledged write concern.
/// </summary>
#if NET452
[Serializable]
#endif
public class Unacknowledged : BulkWriteResult<TDocument>
{
// constructors
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
/// <param name="requestCount">The request count.</param>
/// <param name="processedRequests">The processed requests.</param>
public Unacknowledged(
int requestCount,
IEnumerable<WriteModel<TDocument>> processedRequests)
: base(requestCount, processedRequests)
{
}
// public properties
/// <inheritdoc/>
public override long DeletedCount
{
get { throw new NotSupportedException("Only acknowledged writes support the DeletedCount property."); }
}
/// <inheritdoc/>
public override long InsertedCount
{
get { throw new NotSupportedException("Only acknowledged writes support the InsertedCount property."); }
}
/// <inheritdoc/>
public override bool IsAcknowledged
{
get { return false; }
}
/// <inheritdoc/>
public override bool IsModifiedCountAvailable
{
get { throw new NotSupportedException("Only acknowledged writes support the IsModifiedCountAvailable property."); }
}
/// <inheritdoc/>
public override long MatchedCount
{
get { throw new NotSupportedException("Only acknowledged writes support the MatchedCount property."); }
}
/// <inheritdoc/>
public override long ModifiedCount
{
get { throw new NotSupportedException("Only acknowledged writes support the ModifiedCount property."); }
}
/// <inheritdoc/>
public override IReadOnlyList<BulkWriteUpsert> Upserts
{
get { throw new NotSupportedException("Only acknowledged writes support the Upserts property."); }
}
}
}
}
| 35.036254 | 154 | 0.541951 | [
"MIT"
] | naivetang/2019MiniGame22 | Server/ThirdParty/MongoDBDriver/MongoDB.Driver/BulkWriteResult.cs | 11,597 | C# |
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs.Extensions.CosmosDB;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Net.Http;
namespace CreateRating
{
public static class CreateRating
{
[FunctionName("CreateRating")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
[CosmosDB(
databaseName: "icecreamratings",
collectionName: "ratings",
ConnectionStringSetting = "CosmosDBConnection")] IAsyncCollector<ratingModel> ratingDoc,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
// Pull in data from Put query string
string userId = req.Query["userId"];
string productId = req.Query["productId"];
string locationName = req.Query["locationName"];
string rating = req.Query["rating"];
string userNotes = req.Query["userNotes"];
// Pull in data from Push request body
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
userId = userId ?? data?.userId;
productId = productId ?? data?.productId;
locationName = locationName ?? data?.locationName;
rating = rating ?? data?.rating;
userNotes = userNotes ?? data?.userNotes;
// Validate userId
if (string.IsNullOrEmpty(userId))
{
return new OkObjectResult("Please enter a valid userId");
}
// Call GetUser API to validate user
HttpClient userClient = new HttpClient();
HttpRequestMessage userRequest = new HttpRequestMessage(HttpMethod.Get, string.Format("https://serverlessohuser.trafficmanager.net/api/GetUser?userId={0}", userId));
// Read response from API
HttpResponseMessage userResponse = await userClient.SendAsync(userRequest);
var userContent = userResponse.Content.ReadAsStringAsync().Result;
dynamic userParameters = JsonConvert.DeserializeObject<userIdModel>(userContent);
log.LogInformation($"userContent: {userContent}");
log.LogInformation($"userName: {userParameters.userName}");
// Validate productId
if (string.IsNullOrEmpty(productId))
{
return new OkObjectResult("Please enter a valid productId");
}
// Call GetProduct API to validate productId
HttpClient productClient = new HttpClient();
HttpRequestMessage productRequest = new HttpRequestMessage(HttpMethod.Get, string.Format("https://serverlessohproduct.trafficmanager.net/api/GetProduct?productId={0}", productId));
// Read response from API
HttpResponseMessage productResponse = await productClient.SendAsync(productRequest);
var productContent = productResponse.Content.ReadAsStringAsync().Result;
dynamic productParameters = JsonConvert.DeserializeObject<productIdModel>(productContent);
// Validate rating
int numRating = Int32.Parse(rating);
if (numRating > 5)
{
return new OkObjectResult("Please enter a valid rating");
}
if (numRating < 1)
{
return new OkObjectResult("Please enter a valid rating");
}
// Create id GUID
Guid id = Guid.NewGuid();
string idStr = id.ToString();
// get current time
string currentDateTime = DateTime.UtcNow.ToString();
ratingModel newRating = new ratingModel();
// Create JSON object
newRating.id = idStr;
newRating.userId = userId;
newRating.productId = productId;
newRating.timeStamp = currentDateTime;
newRating.locationName = locationName;
newRating.rating = rating;
newRating.userNotes = userNotes;
// send data to cosmosdb
await ratingDoc.AddAsync(newRating);
//Return json object
string jsonString = JsonConvert.SerializeObject(newRating);
return new OkObjectResult($"{jsonString}");
}
}
}
public class userIdModel
{
public string userId { get; set; }
public string userName { get; set; }
public string fullName { get; set; }
}
public class productIdModel
{
public string productId { get; set; }
public string productName { get; set; }
public string productDescription { get; set; }
}
public class ratingModel
{
public string id { get; set; }
public string userId { get; set; }
public string productId { get; set; }
public string timeStamp { get; set; }
public string locationName { get; set; }
public string rating { get; set; }
public string userNotes { get; set; }
} | 37.914894 | 192 | 0.625889 | [
"MIT"
] | JimBlizzard/OHTeam8 | CreateRating/CreateRating/Function1.cs | 5,346 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using IVolunteerMVC.Models;
namespace IVolunteerMVC.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| 22.078947 | 112 | 0.599523 | [
"MIT"
] | Complustechwizards/IVolunteer | IVolunteerMVC/Controllers/HomeController.cs | 841 | C# |
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace Biztory.EnterpriseToolkit.TableauServerUnifiedApi.Rest.Model {
/// <summary>
///
/// </summary>
[DataContract]
public class QuerySiteResponseSite {
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// Gets or Sets ContentUrl
/// </summary>
[DataMember(Name="contentUrl", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "contentUrl")]
public string ContentUrl { get; set; }
/// <summary>
/// Gets or Sets AdminMode
/// </summary>
[DataMember(Name="adminMode", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "adminMode")]
public string AdminMode { get; set; }
/// <summary>
/// Gets or Sets UserQuota
/// </summary>
[DataMember(Name="userQuota", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "userQuota")]
public string UserQuota { get; set; }
/// <summary>
/// Gets or Sets StorageQuota
/// </summary>
[DataMember(Name="storageQuota", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "storageQuota")]
public string StorageQuota { get; set; }
/// <summary>
/// Gets or Sets DisableSubscriptions
/// </summary>
[DataMember(Name="disableSubscriptions", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "disableSubscriptions")]
public string DisableSubscriptions { get; set; }
/// <summary>
/// Gets or Sets RevisionHistoryEnabled
/// </summary>
[DataMember(Name="revisionHistoryEnabled", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "revisionHistoryEnabled")]
public string RevisionHistoryEnabled { get; set; }
/// <summary>
/// Gets or Sets RevisionLimit
/// </summary>
[DataMember(Name="revisionLimit", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "revisionLimit")]
public string RevisionLimit { get; set; }
/// <summary>
/// Gets or Sets State
/// </summary>
[DataMember(Name="state", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "state")]
public string State { get; set; }
/// <summary>
/// Gets or Sets Usage
/// </summary>
[DataMember(Name="usage", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "usage")]
public QuerySiteResponseSiteUsage Usage { get; set; }
/// <summary>
/// Get the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString() {
var sb = new StringBuilder();
sb.Append("class QuerySiteResponseSite {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" ContentUrl: ").Append(ContentUrl).Append("\n");
sb.Append(" AdminMode: ").Append(AdminMode).Append("\n");
sb.Append(" UserQuota: ").Append(UserQuota).Append("\n");
sb.Append(" StorageQuota: ").Append(StorageQuota).Append("\n");
sb.Append(" DisableSubscriptions: ").Append(DisableSubscriptions).Append("\n");
sb.Append(" RevisionHistoryEnabled: ").Append(RevisionHistoryEnabled).Append("\n");
sb.Append(" RevisionLimit: ").Append(RevisionLimit).Append("\n");
sb.Append(" State: ").Append(State).Append("\n");
sb.Append(" Usage: ").Append(Usage).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Get the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
}
| 32.976 | 90 | 0.643134 | [
"Apache-2.0"
] | biztory/tableau-performance-accelerator | tableau-server-api-unified/Rest/Model/QuerySiteResponseSite.cs | 4,124 | C# |
using MiauCore.IO.Models;
namespace MiauCore.IO.Areas.Admin.Models
{
public class User : IGenericEntity
{
public string IdentityId { get; set; }
public int Id { get; set; }
public string Login { get; set; }
public string Password { get; set; }
public string Email { get; set; }
}
} | 24 | 46 | 0.60119 | [
"MIT"
] | MIAUUUUUUU/Sticky.io | src/MiauCore.IO/Areas/Admin/Models/User.cs | 338 | C# |
/*
* Copyright 2022 Rapid Software LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*
*
* Product : Rapid SCADA
* Module : Administrator
* Summary : Represents references to the context menus
*
* Author : Mikhail Shiryaev
* Created : 2018
* Modified : 2021
*/
using System.Windows.Forms;
namespace Scada.Admin.App.Code
{
/// <summary>
/// Represents references to the context menus.
/// <para>Представляет ссылки на контекстные меню.</para>
/// </summary>
internal class ContextMenus
{
public ContextMenuStrip ProjectMenu { get; set; }
public ContextMenuStrip CnlTableMenu { get; set; }
public ContextMenuStrip DirectoryMenu { get; set; }
public ContextMenuStrip FileItemMenu { get; set; }
public ContextMenuStrip InstanceMenu { get; set; }
public ContextMenuStrip AppMenu { get; set; }
}
}
| 28.816327 | 75 | 0.688385 | [
"Apache-2.0"
] | chencai01/scada-v6 | ScadaAdmin/ScadaAdmin/ScadaAdmin/Code/ContextMenus.cs | 1,449 | C# |
using System;
namespace Rin.Core.Record
{
public interface ITimelineEvent
{
/// <summary>
/// Timeline event type name.
/// </summary>
string EventType { get; }
/// <summary>
/// Operation name.
/// </summary>
string Name { get; set; }
/// <summary>
/// Operation category.
/// </summary>
string Category { get; set; }
/// <summary>
/// Custom operation data.
/// </summary>
string? Data { get; set; }
/// <summary>
/// Timestamp of operation started at.
/// </summary>
DateTimeOffset Timestamp { get; set; }
}
}
| 20.939394 | 46 | 0.477569 | [
"MIT"
] | azyobuzin/Rin | src/Rin/Core/Record/ITimelineEvent.cs | 693 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ValkyrieWorkflowEngineLibrary.Database;
using ZMQ;
using ZMQ.ZMQExt;
namespace ValkyrieWorkflowEngineLibrary
{
/// <summary>
/// The primary class used to instantiate new workflows from a template
/// </summary>
public class ValkWFActivator
{
public static Context ActContext = null;
private static bool Stop = true;
private static bool Exit = false;
private static Socket ActivatorIntraComm;
private static Socket ActivatorControllerIntraComm;
private static Socket QueueComm;
private static Dictionary<int, ValkWF> WorkFlowTemplates = new Dictionary<int, ValkWF>();
//this will keep track of all the instances we've loaded, so that we can ignore duplicate requests
//list item is the instance_id, since it should be unique and fast to access;
private static List<int> LoadedInstances = new List<int>();
//all the loaded templates, index by wf_id
private static SortedDictionary<int, ValkWFStep> LoadedInstanceTemplates = new SortedDictionary<int, ValkWFStep>();
//all the -active- templates, indexed by type
private static SortedDictionary<string, int> LoadedActiveInstanceByType = new SortedDictionary<string, int>();
private static IDatabaseHandler dbHandler { get; set; }
public static void ActivateResponder(IDatabaseHandler _dbHandler)
{
dbHandler = _dbHandler;
if (ActContext == null)
throw new System.Exception("ActContext not set");
ActivatorIntraComm = ActContext.Socket(SocketType.REP);
ActivatorIntraComm.Bind("inproc://activator");
ActivatorIntraComm.Bind("tcp://*:5001");
ActivatorControllerIntraComm = ActContext.Socket(SocketType.REP);
ActivatorControllerIntraComm.Connect("inproc://activatorcontrol");
QueueComm = ActContext.Socket(SocketType.REQ);
QueueComm.Connect("tcp://127.0.0.1:5000");
PollItem[] Poller = new PollItem[1];
PollItem[] ControlPoller = new PollItem[1];
Poller[0] = ActivatorIntraComm.CreatePollItem(IOMultiPlex.POLLIN);
Poller[0].PollInHandler += new PollHandler(ValkWFActivator_PollInHandler);
ControlPoller[0] = ActivatorControllerIntraComm.CreatePollItem(IOMultiPlex.POLLIN);
ControlPoller[0].PollInHandler += new PollHandler(ValkWFActivatorCTRL_PollInHandler);
//load workflow templates
LoadWorkflowTemplates(dbHandler);
//main loop
while (!Exit)
{
//we may want a way to shut this down...
ActContext.Poll(ControlPoller, 1);
if (!Stop)
{
//block for a little while...
ActContext.Poll(Poller, 1000);
}
}
}
private static void LoadWorkflowTemplates(IDatabaseHandler dbHandler)
{
//WorkFlowTemplates
//list to store loads to help reduce recursive SQL queries
WFTemplateLoadingData loadingData = dbHandler.LoadWFTemplates();
LoadedActiveInstanceByType = loadingData.LoadedActiveInstanceByType;
for (int i = 0; i < loadingData.WFsToLoad.Count(); i++)
{
ValkWFStep CurrentStep = loadingData.WFsToLoad[i];
LoadChildren(CurrentStep, dbHandler);
loadingData.WFsToLoad[i] = CurrentStep;
LoadedInstanceTemplates[loadingData.WFsToLoad[i].WFTemplateID] = loadingData.WFsToLoad[i];
}
Console.WriteLine("Workflows Loaded");
}
private static void LoadChildren(ValkWFStep CurrentStep, IDatabaseHandler dbHandler)
{
List<ValkWFStep> Children = dbHandler.LoadChildSteps(CurrentStep);
//do children loading outside, here
for (int i = 0; i < Children.Count(); i++)
{
ValkWFStep substep = Children[i];
LoadChildren(substep, dbHandler);
Children[i] = substep;
}
CurrentStep.NextSteps = Children;
}
/// <summary>
/// Handles control messages
/// </summary>
/// <param name="socket"></param>
/// <param name="revents"></param>
static void ValkWFActivatorCTRL_PollInHandler(Socket socket, IOMultiPlex revents)
{
string Message = socket.Recv(Encoding.Unicode);
Console.WriteLine(Message);
socket.Send("OK:" + Message, Encoding.Unicode);
if (Message == "GO")
{
Stop = false;
}
else if (Message == "STOP")
{
Stop = true;
}
else if (Message == "EXIT")
{
Stop = true;
Exit = true;
}
}
static void ValkWFActivator_PollInHandler(Socket socket, IOMultiPlex revents)
{
//handle workflow instantiations
ValkQueueWFMessage WFMessage = socket.Recv<ValkQueueWFMessage>();
if (WFMessage.Command == ValkQueueWFMessage.WFCommand.WFC_LOAD)
{
ValkWFStep NewInstance = null;
//Console.WriteLine("Instance Insert Request Received: " + WFMessage.InstanceID + " " + WFMessage.InstanceKey);
if (!LoadedInstances.Contains(WFMessage.InstanceID))
{
LoadedInstances.Add(WFMessage.InstanceID);
SortedDictionary<int, ValkWFStep> ToInsert = new SortedDictionary<int, ValkWFStep>();
dbHandler.StartWFInstance(WFMessage.InstanceID);
if (LoadedActiveInstanceByType.ContainsKey(WFMessage.InstanceType))
{
NewInstance
= LoadedInstanceTemplates[LoadedActiveInstanceByType[WFMessage.InstanceType]].DeepClone<ValkWFStep>();
BuildInsertWFInstance(ToInsert, NewInstance, WFMessage.InstanceKey, true);
//Console.WriteLine(DateTime.Now.ToLongTimeString() + ": Created New Instance: " + WFMessage.InstanceKey);
}
else
{
//error, no WF of this type found active
}
if (ToInsert.Count > 0)
{
InsertWFInstance(ToInsert);
ValkQueueWFMessage QueueMessage = new ValkQueueWFMessage();
QueueMessage.InstanceID = WFMessage.InstanceID;
QueueMessage.InstanceKey = WFMessage.InstanceKey;
QueueMessage.InstanceType = WFMessage.InstanceType;
QueueMessage.Command = ValkQueueWFMessage.WFCommand.WFC_ACTIVATE;
QueueMessage.Step = NewInstance;
QueueComm.Send<ValkQueueWFMessage>(QueueMessage);
string reply = QueueComm.Recv(Encoding.Unicode);
}
socket.Send("OK", Encoding.Unicode);
}
else
{//else don't do anything, duplicate message
socket.Send("WARN-Duplicate Request", Encoding.Unicode);
}
}
else
{
//log error message
socket.Send("ERROR-Wrong Request Type", Encoding.Unicode);
}
}
static void InsertWFInstance(SortedDictionary<int, ValkWFStep> ToInsert)
{
dbHandler.InsertWFInstance(ToInsert);
}
/// <summary>
/// Creates all child-steps of a workflow instance (recursively) so that the entire flow can be inserted
/// prior to being set active.
/// </summary>
/// <param name="ToInsert"></param>
/// <param name="Step"></param>
/// <param name="InstanceID"></param>
/// <param name="insert"></param>
static void BuildInsertWFInstance(SortedDictionary<int, ValkWFStep> ToInsert, ValkWFStep Step, string InstanceID, bool insert)
{
Step.InstanceKey = InstanceID;
if (insert && !ToInsert.ContainsKey(Step.WFTemplateStepID))
{
ToInsert[Step.WFTemplateStepID] = Step;
}
else
{
insert = false;
}
for (int i = 0; i < Step.NextSteps.Count; i++)
{
ValkWFStep substep = Step.NextSteps[i];
BuildInsertWFInstance(ToInsert, substep, InstanceID, insert);
Step.NextSteps[i] = substep;
}
}
}
}
| 34.322115 | 128 | 0.715226 | [
"MIT"
] | jmlothian/ValkyrieWF | ValkyrieWorkflowEngineLibrary/ValkWFActivator.cs | 7,141 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Squidex.Domain.Apps.Core.Schemas;
using Squidex.Domain.Apps.Entities.Schemas.Commands;
namespace Squidex.Domain.Apps.Entities.Apps.Templates.Builders
{
public class BooleanFieldBuilder : FieldBuilder
{
public BooleanFieldBuilder(UpsertSchemaField field)
: base(field)
{
}
public BooleanFieldBuilder AsToggle()
{
Properties<BooleanFieldProperties>().Editor = BooleanFieldEditor.Toggle;
return this;
}
}
}
| 31.357143 | 84 | 0.495444 | [
"MIT"
] | Avd6977/squidex | src/Squidex.Domain.Apps.Entities/Apps/Templates/Builders/BooleanFieldBuilder.cs | 880 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the finspace-data-2020-07-13.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.FinSpaceData.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.FinSpaceData.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ChangesetInfo Object
/// </summary>
public class ChangesetInfoUnmarshaller : IUnmarshaller<ChangesetInfo, XmlUnmarshallerContext>, IUnmarshaller<ChangesetInfo, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
ChangesetInfo IUnmarshaller<ChangesetInfo, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public ChangesetInfo Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
ChangesetInfo unmarshalledObject = new ChangesetInfo();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("changesetArn", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ChangesetArn = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("changesetLabels", targetDepth))
{
var unmarshaller = new DictionaryUnmarshaller<string, string, StringUnmarshaller, StringUnmarshaller>(StringUnmarshaller.Instance, StringUnmarshaller.Instance);
unmarshalledObject.ChangesetLabels = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("changeType", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ChangeType = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("createTimestamp", targetDepth))
{
var unmarshaller = DateTimeUnmarshaller.Instance;
unmarshalledObject.CreateTimestamp = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("datasetId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.DatasetId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("errorInfo", targetDepth))
{
var unmarshaller = ErrorInfoUnmarshaller.Instance;
unmarshalledObject.ErrorInfo = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("formatParams", targetDepth))
{
var unmarshaller = new DictionaryUnmarshaller<string, string, StringUnmarshaller, StringUnmarshaller>(StringUnmarshaller.Instance, StringUnmarshaller.Instance);
unmarshalledObject.FormatParams = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("formatType", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.FormatType = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("id", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Id = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("sourceParams", targetDepth))
{
var unmarshaller = new DictionaryUnmarshaller<string, string, StringUnmarshaller, StringUnmarshaller>(StringUnmarshaller.Instance, StringUnmarshaller.Instance);
unmarshalledObject.SourceParams = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("sourceType", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.SourceType = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("status", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Status = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("updatedByChangesetId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.UpdatedByChangesetId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("updatesChangesetId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.UpdatesChangesetId = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static ChangesetInfoUnmarshaller _instance = new ChangesetInfoUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static ChangesetInfoUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 42.611765 | 180 | 0.588211 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/FinSpaceData/Generated/Model/Internal/MarshallTransformations/ChangesetInfoUnmarshaller.cs | 7,244 | C# |
using Quantum;
using Quantum.Operations;
using System;
using System.Numerics;
using System.Collections.Generic;
using System.Linq;
namespace QuantumConsole
{
public static class GroverExtension
{
// Oracle is working on input register x (of width n)
// and output register y (of width 1)
public static void Oracle (this QuantumComputer comp, int target, Register x, Register y)
{
var controlBits = new RegisterRef[x.Width];
for (int i = 0; i < x.Width; i++)
{
if ((target & (1 << i)) == 0)
{
x.SigmaX(i);
}
controlBits[i] = x[i];
}
comp.Toffoli(y[0], controlBits); // Toffoli(<target_bit>, ... <control_bits> ...)
for (int i = 0; i < x.Width; i++)
{
if ((target & (1 << i)) == 0)
{
x.SigmaX(i);
}
}
}
public static void InverseOracle (this QuantumComputer comp, int target, Register x, Register y)
{
comp.Oracle(target, x, y);
}
// Inversion is working on n-width register
public static void Inversion (this QuantumComputer comp, Register x)
{
for (int i = 0; i < x.Width; i++)
{
x.Hadamard(i);
x.SigmaX(i);
}
x.Hadamard(0);
if(x.Width == 2)
{
x.CNot(target: 0, control: 1);
}
else
{
int[] controlBits = Enumerable.Range(1, x.Width - 1).ToArray();
x.Toffoli(0, controlBits); // Toffoli(<target_bit>, ... <control_bits> ...)
}
x.Hadamard(0);
for (int i = 0; i < x.Width; i++)
{
x.SigmaX(i);
x.Hadamard(i);
}
}
public static void InverseInversion (this QuantumComputer comp, Register x)
{
comp.Inversion(x);
}
// single iteration of Grover's algorithm
public static void Grover (this QuantumComputer comp, int target, Register x, Register y)
{
comp.Oracle(target, x, y);
comp.Inversion(x);
}
public static void InverseGrover (this QuantumComputer comp, int target, Register x, Register y)
{
comp.Inversion(x);
comp.Oracle(target, x, y);
}
}
public class QuantumTest
{
public static void Main()
{
int number = 5;
int width = 4; // width of search space
double iterations = Math.PI/4 * Math.Sqrt(1 << width);
QuantumComputer comp = QuantumComputer.GetInstance();
// input register set to 0
Register x = comp.NewRegister(0, width);
// output 1-qubit-register, set to 1
Register y = comp.NewRegister(1, 1);
comp.Walsh(x);
comp.Hadamard(y[0]);
Console.WriteLine("Iterations needed: PI/4 * Sqrt(2^n) = {0}", iterations);
var probs = x.GetProbabilities();
for (ulong i = 0; i < Math.Pow(2, width); i++)
{
Console.Write(i + ",");
}
Console.WriteLine();
for (int i = 1; i <= iterations; i++)
{
// Console.WriteLine("Iteration #{0}", i);
comp.Oracle(number, x, y);
//these Hadamard gates are only for viewing purposes !
y.Hadamard(0);
// here we can view amplitudes in simulator
// Console.WriteLine("After Oracle:");
var amplitudes = x.GetAmplitudes();
for (ulong j = 0; j < Math.Pow(2, width); j++)
{
Console.Write(amplitudes[j].Real.ToString() + ",");
}
Console.WriteLine();
//going back to the algorithm
y.Hadamard(0);
comp.Inversion(x);
//these Hadamard gates are only for viewing purposes !
y.Hadamard(0);
// here we can view amplitudes in simulator
// Console.WriteLine("After Inverse:");
amplitudes = x.GetAmplitudes();
for (ulong j = 0; j < Math.Pow(2, width); j++)
{
Console.Write(amplitudes[j].Real.ToString() + ",");
}
Console.WriteLine();
//going back to the algorithm
y.Hadamard(0);
}
}
}
}
| 22.87037 | 98 | 0.591903 | [
"MIT"
] | Elrohil44/MwIP | Grover.cs | 3,707 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace MusicStructuriser
{
public class CMetaData
{
public string sTitle;
public string sAlbum;
public string sTrack;
public string sYear;
public string[] sArtists;
public string[] sAlbumArtists;
public string[] sComposers;
public Image image;
public string[] sGenres;
public CMetaData()
{
}
}
}
| 20.296296 | 38 | 0.633212 | [
"MIT"
] | Viperinius/Music-Structuriser | MusicStructuriser/MusicStructuriser/CMetaData.cs | 550 | C# |
using System;
using Xunit;
namespace BCLExtensions.Tests.ActionExtensions
{
public class AsActionUsingTests
{
[Fact]
public void SampleActionIsValid()
{
SampleAction(42);
}
[Fact]
public void ResultNotNull()
{
Action<int> function = SampleAction;
var action = function.AsActionUsing(12);
Assert.NotNull(action);
}
private void SampleAction(int parameter)
{
}
[Fact]
public void InternalFunctionExecutes()
{
bool internalFunctionWasCalled = false;
Action<int> action = parameter =>
{
internalFunctionWasCalled = true;
};
var result = action.AsActionUsing(12);
result();
Assert.True(internalFunctionWasCalled);
}
[Fact]
public void InternalFunctionCapturesCorrectParameter()
{
const int expectedParameter = 12;
int passedParameter = 0;
Action<int> action = parameter =>
{
passedParameter = parameter;
};
var result = action.AsActionUsing(expectedParameter);
result();
Assert.Equal(expectedParameter, passedParameter);
}
}
}
| 22.129032 | 65 | 0.524781 | [
"MIT"
] | JTOne123/BCLExtensions-1 | src/BCLExtensions.Tests/ActionExtensions/AsActionUsingTests.cs | 1,374 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Insights.V20210501Preview
{
public static class GetDiagnosticSetting
{
/// <summary>
/// The diagnostic setting resource.
/// </summary>
public static Task<GetDiagnosticSettingResult> InvokeAsync(GetDiagnosticSettingArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetDiagnosticSettingResult>("azure-native:insights/v20210501preview:getDiagnosticSetting", args ?? new GetDiagnosticSettingArgs(), options.WithVersion());
}
public sealed class GetDiagnosticSettingArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The name of the diagnostic setting.
/// </summary>
[Input("name", required: true)]
public string Name { get; set; } = null!;
/// <summary>
/// The identifier of the resource.
/// </summary>
[Input("resourceUri", required: true)]
public string ResourceUri { get; set; } = null!;
public GetDiagnosticSettingArgs()
{
}
}
[OutputType]
public sealed class GetDiagnosticSettingResult
{
/// <summary>
/// The resource Id for the event hub authorization rule.
/// </summary>
public readonly string? EventHubAuthorizationRuleId;
/// <summary>
/// The name of the event hub. If none is specified, the default event hub will be selected.
/// </summary>
public readonly string? EventHubName;
/// <summary>
/// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
/// </summary>
public readonly string Id;
/// <summary>
/// A string indicating whether the export to Log Analytics should use the default destination type, i.e. AzureDiagnostics, or use a destination type constructed as follows: <normalized service identity>_<normalized category name>. Possible values are: Dedicated and null (null is default.)
/// </summary>
public readonly string? LogAnalyticsDestinationType;
/// <summary>
/// The list of logs settings.
/// </summary>
public readonly ImmutableArray<Outputs.LogSettingsResponse> Logs;
/// <summary>
/// The full ARM resource ID of the Marketplace resource to which you would like to send Diagnostic Logs.
/// </summary>
public readonly string? MarketplacePartnerId;
/// <summary>
/// The list of metric settings.
/// </summary>
public readonly ImmutableArray<Outputs.MetricSettingsResponse> Metrics;
/// <summary>
/// The name of the resource
/// </summary>
public readonly string Name;
/// <summary>
/// The service bus rule Id of the diagnostic setting. This is here to maintain backwards compatibility.
/// </summary>
public readonly string? ServiceBusRuleId;
/// <summary>
/// The resource ID of the storage account to which you would like to send Diagnostic Logs.
/// </summary>
public readonly string? StorageAccountId;
/// <summary>
/// The system metadata related to this resource.
/// </summary>
public readonly Outputs.SystemDataResponse SystemData;
/// <summary>
/// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts"
/// </summary>
public readonly string Type;
/// <summary>
/// The full ARM resource ID of the Log Analytics workspace to which you would like to send Diagnostic Logs. Example: /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2
/// </summary>
public readonly string? WorkspaceId;
[OutputConstructor]
private GetDiagnosticSettingResult(
string? eventHubAuthorizationRuleId,
string? eventHubName,
string id,
string? logAnalyticsDestinationType,
ImmutableArray<Outputs.LogSettingsResponse> logs,
string? marketplacePartnerId,
ImmutableArray<Outputs.MetricSettingsResponse> metrics,
string name,
string? serviceBusRuleId,
string? storageAccountId,
Outputs.SystemDataResponse systemData,
string type,
string? workspaceId)
{
EventHubAuthorizationRuleId = eventHubAuthorizationRuleId;
EventHubName = eventHubName;
Id = id;
LogAnalyticsDestinationType = logAnalyticsDestinationType;
Logs = logs;
MarketplacePartnerId = marketplacePartnerId;
Metrics = metrics;
Name = name;
ServiceBusRuleId = serviceBusRuleId;
StorageAccountId = storageAccountId;
SystemData = systemData;
Type = type;
WorkspaceId = workspaceId;
}
}
}
| 38.584507 | 310 | 0.639898 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Insights/V20210501Preview/GetDiagnosticSetting.cs | 5,479 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Data.DataView;
using Microsoft.ML;
using Microsoft.ML.CommandLine;
using Microsoft.ML.Data;
using Microsoft.ML.EntryPoints;
using Microsoft.ML.Internal.Utilities;
using Microsoft.ML.Transforms.Conversions;
using Microsoft.ML.Transforms.Text;
[assembly: LoadableClass(WordHashBagProducingTransformer.Summary, typeof(IDataTransform), typeof(WordHashBagProducingTransformer), typeof(WordHashBagProducingTransformer.Arguments), typeof(SignatureDataTransform),
"Word Hash Bag Transform", "WordHashBagTransform", "WordHashBag")]
[assembly: LoadableClass(NgramHashExtractingTransformer.Summary, typeof(INgramExtractorFactory), typeof(NgramHashExtractingTransformer), typeof(NgramHashExtractingTransformer.NgramHashExtractorArguments),
typeof(SignatureNgramExtractorFactory), "Ngram Hash Extractor Transform", "NgramHashExtractorTransform", "NgramHash", NgramHashExtractingTransformer.LoaderSignature)]
[assembly: EntryPointModule(typeof(NgramHashExtractingTransformer.NgramHashExtractorArguments))]
namespace Microsoft.ML.Transforms.Text
{
public static class WordHashBagProducingTransformer
{
public sealed class Column : NgramHashExtractingTransformer.ColumnBase
{
internal static Column Parse(string str)
{
Contracts.AssertNonEmpty(str);
var res = new Column();
if (res.TryParse(str))
return res;
return null;
}
private protected override bool TryParse(string str)
{
Contracts.AssertNonEmpty(str);
// We accept N:B:S where N is the new column name, B is the number of bits,
// and S is source column names.
string extra;
if (!base.TryParse(str, out extra))
return false;
if (extra == null)
return true;
int bits;
if (!int.TryParse(extra, out bits))
return false;
HashBits = bits;
return true;
}
internal bool TryUnparse(StringBuilder sb)
{
Contracts.AssertValue(sb);
if (NgramLength != null || SkipLength != null || Seed != null ||
Ordered != null || InvertHash != null)
{
return false;
}
if (HashBits == null)
return TryUnparseCore(sb);
string extra = HashBits.Value.ToString();
return TryUnparseCore(sb, extra);
}
}
public sealed class Arguments : NgramHashExtractingTransformer.ArgumentsBase
{
[Argument(ArgumentType.Multiple | ArgumentType.Required, HelpText = "New column definition(s) (optional form: name:hashBits:srcs)",
Name = "Column", ShortName = "col", SortOrder = 1)]
public Column[] Columns;
}
private const string RegistrationName = "WordHashBagTransform";
internal const string Summary = "Produces a bag of counts of ngrams (sequences of consecutive words of length 1-n) in a given text. "
+ "It does so by hashing each ngram and using the hash value as the index in the bag.";
public static IDataTransform Create(IHostEnvironment env, Arguments args, IDataView input)
{
Contracts.CheckValue(env, nameof(env));
var h = env.Register(RegistrationName);
h.CheckValue(args, nameof(args));
h.CheckValue(input, nameof(input));
h.CheckUserArg(Utils.Size(args.Columns) > 0, nameof(args.Columns), "Columns must be specified");
// To each input column to the WordHashBagTransform, a tokenize transform is applied,
// followed by applying WordHashVectorizeTransform.
// Since WordHashBagTransform is a many-to-one column transform, for each
// WordHashBagTransform.Column we may need to define multiple tokenize transform columns.
// NgramHashExtractorTransform may need to define an identical number of HashTransform.Columns.
// The intermediate columns are dropped at the end of using a DropColumnsTransform.
IDataView view = input;
var uniqueSourceNames = NgramExtractionUtils.GenerateUniqueSourceNames(h, args.Columns, view.Schema);
Contracts.Assert(uniqueSourceNames.Length == args.Columns.Length);
var tokenizeColumns = new List<WordTokenizingTransformer.ColumnInfo>();
var extractorCols = new NgramHashExtractingTransformer.Column[args.Columns.Length];
var colCount = args.Columns.Length;
List<string> tmpColNames = new List<string>();
for (int iinfo = 0; iinfo < colCount; iinfo++)
{
var column = args.Columns[iinfo];
int srcCount = column.Source.Length;
var curTmpNames = new string[srcCount];
Contracts.Assert(uniqueSourceNames[iinfo].Length == args.Columns[iinfo].Source.Length);
for (int isrc = 0; isrc < srcCount; isrc++)
tokenizeColumns.Add(new WordTokenizingTransformer.ColumnInfo(curTmpNames[isrc] = uniqueSourceNames[iinfo][isrc], args.Columns[iinfo].Source[isrc]));
tmpColNames.AddRange(curTmpNames);
extractorCols[iinfo] =
new NgramHashExtractingTransformer.Column
{
Name = column.Name,
Source = curTmpNames,
HashBits = column.HashBits,
NgramLength = column.NgramLength,
Seed = column.Seed,
SkipLength = column.SkipLength,
Ordered = column.Ordered,
InvertHash = column.InvertHash,
FriendlyNames = args.Columns[iinfo].Source,
AllLengths = column.AllLengths
};
}
view = new WordTokenizingEstimator(env, tokenizeColumns.ToArray()).Fit(view).Transform(view);
var featurizeArgs =
new NgramHashExtractingTransformer.Arguments
{
AllLengths = args.AllLengths,
HashBits = args.HashBits,
NgramLength = args.NgramLength,
SkipLength = args.SkipLength,
Ordered = args.Ordered,
Seed = args.Seed,
Columns = extractorCols.ToArray(),
InvertHash = args.InvertHash
};
view = NgramHashExtractingTransformer.Create(h, featurizeArgs, view);
// Since we added columns with new names, we need to explicitly drop them before we return the IDataTransform.
return ColumnSelectingTransformer.CreateDrop(h, view, tmpColNames.ToArray());
}
}
/// <summary>
/// A transform that turns a collection of tokenized text (vector of ReadOnlyMemory) into numerical feature vectors
/// using the hashing trick.
/// </summary>
public static class NgramHashExtractingTransformer
{
public abstract class ColumnBase : ManyToOneColumn
{
[Argument(ArgumentType.AtMostOnce, HelpText = "Ngram length (stores all lengths up to the specified Ngram length)", ShortName = "ngram")]
public int? NgramLength;
[Argument(ArgumentType.AtMostOnce,
HelpText = "Maximum number of tokens to skip when constructing an ngram",
ShortName = "skips")]
public int? SkipLength;
[Argument(ArgumentType.AtMostOnce,
HelpText = "Number of bits to hash into. Must be between 1 and 30, inclusive.",
ShortName = "bits")]
public int? HashBits;
[Argument(ArgumentType.AtMostOnce, HelpText = "Hashing seed")]
public uint? Seed;
[Argument(ArgumentType.AtMostOnce, HelpText = "Whether the position of each source column should be included in the hash (when there are multiple source columns).", ShortName = "ord")]
public bool? Ordered;
[Argument(ArgumentType.AtMostOnce,
HelpText = "Limit the number of keys used to generate the slot name to this many. 0 means no invert hashing, -1 means no limit.",
ShortName = "ih")]
public int? InvertHash;
[Argument(ArgumentType.AtMostOnce,
HelpText = "Whether to include all ngram lengths up to " + nameof(NgramLength) + " or only " + nameof(NgramLength),
ShortName = "all", SortOrder = 4)]
public bool? AllLengths;
}
public sealed class Column : ColumnBase
{
// For all source columns, use these friendly names for the source
// column names instead of the real column names.
public string[] FriendlyNames;
internal static Column Parse(string str)
{
Contracts.AssertNonEmpty(str);
var res = new Column();
if (res.TryParse(str))
return res;
return null;
}
private protected override bool TryParse(string str)
{
Contracts.AssertNonEmpty(str);
// We accept N:B:S where N is the new column name, B is the number of bits,
// and S is source column names.
string extra;
if (!base.TryParse(str, out extra))
return false;
if (extra == null)
return true;
int bits;
if (!int.TryParse(extra, out bits))
return false;
HashBits = bits;
return true;
}
internal bool TryUnparse(StringBuilder sb)
{
Contracts.AssertValue(sb);
if (NgramLength != null || SkipLength != null || Seed != null ||
Ordered != null || InvertHash != null)
{
return false;
}
if (HashBits == null)
return TryUnparseCore(sb);
string extra = HashBits.Value.ToString();
return TryUnparseCore(sb, extra);
}
}
/// <summary>
/// This class is a merger of <see cref="HashingTransformer.Arguments"/> and
/// <see cref="NgramHashingTransformer.Arguments"/>, with the ordered option,
/// the rehashUnigrams option and the allLength option removed.
/// </summary>
public abstract class ArgumentsBase
{
[Argument(ArgumentType.AtMostOnce, HelpText = "Ngram length", ShortName = "ngram", SortOrder = 3)]
public int NgramLength = 1;
[Argument(ArgumentType.AtMostOnce,
HelpText = "Maximum number of tokens to skip when constructing an ngram",
ShortName = "skips", SortOrder = 4)]
public int SkipLength = 0;
[Argument(ArgumentType.AtMostOnce,
HelpText = "Number of bits to hash into. Must be between 1 and 30, inclusive.",
ShortName = "bits", SortOrder = 2)]
public int HashBits = 16;
[Argument(ArgumentType.AtMostOnce, HelpText = "Hashing seed")]
public uint Seed = 314489979;
[Argument(ArgumentType.AtMostOnce,
HelpText = "Whether the position of each source column should be included in the hash (when there are multiple source columns).",
ShortName = "ord")]
public bool Ordered = true;
[Argument(ArgumentType.AtMostOnce,
HelpText = "Limit the number of keys used to generate the slot name to this many. 0 means no invert hashing, -1 means no limit.",
ShortName = "ih")]
public int InvertHash;
[Argument(ArgumentType.AtMostOnce,
HelpText = "Whether to include all ngram lengths up to ngramLength or only ngramLength",
ShortName = "all", SortOrder = 4)]
public bool AllLengths = true;
}
internal static class DefaultArguments
{
public const int NgramLength = 1;
public const int SkipLength = 0;
public const int HashBits = 16;
public const uint Seed = 314489979;
public const bool Ordered = true;
public const int InvertHash = 0;
public const bool AllLengths = true;
}
[TlcModule.Component(Name = "NGramHash", FriendlyName = "NGram Hash Extractor Transform", Alias = "NGramHashExtractorTransform,NGramHashExtractor",
Desc = "Extracts NGrams from text and convert them to vector using hashing trick.")]
public sealed class NgramHashExtractorArguments : ArgumentsBase, INgramExtractorFactoryFactory
{
public INgramExtractorFactory CreateComponent(IHostEnvironment env, TermLoaderArguments loaderArgs)
{
return Create(env, this, loaderArgs);
}
}
public sealed class Arguments : ArgumentsBase
{
[Argument(ArgumentType.Multiple, HelpText = "New column definition(s) (optional form: name:srcs)", Name = "Column", ShortName = "col", SortOrder = 1)]
public Column[] Columns;
}
internal const string Summary = "A transform that turns a collection of tokenized text (vector of ReadOnlyMemory) into numerical feature vectors using the hashing trick.";
internal const string LoaderSignature = "NgramHashExtractor";
public static IDataTransform Create(IHostEnvironment env, Arguments args, IDataView input,
TermLoaderArguments termLoaderArgs = null)
{
Contracts.CheckValue(env, nameof(env));
var h = env.Register(LoaderSignature);
h.CheckValue(args, nameof(args));
h.CheckValue(input, nameof(input));
h.CheckUserArg(Utils.Size(args.Columns) > 0, nameof(args.Columns), "Columns must be specified");
// To each input column to the NgramHashExtractorArguments, a HashTransform using 31
// bits (to minimize collisions) is applied first, followed by an NgramHashTransform.
IDataView view = input;
List<ValueToKeyMappingTransformer.Column> termCols = null;
if (termLoaderArgs != null)
termCols = new List<ValueToKeyMappingTransformer.Column>();
var hashColumns = new List<HashingTransformer.ColumnInfo>();
var ngramHashColumns = new NgramHashingTransformer.ColumnInfo[args.Columns.Length];
var colCount = args.Columns.Length;
// The NGramHashExtractor has a ManyToOne column type. To avoid stepping over the source
// column name when a 'name' destination column name was specified, we use temporary column names.
string[][] tmpColNames = new string[colCount][];
for (int iinfo = 0; iinfo < colCount; iinfo++)
{
var column = args.Columns[iinfo];
h.CheckUserArg(!string.IsNullOrWhiteSpace(column.Name), nameof(column.Name));
h.CheckUserArg(Utils.Size(column.Source) > 0 &&
column.Source.All(src => !string.IsNullOrWhiteSpace(src)), nameof(column.Source));
int srcCount = column.Source.Length;
tmpColNames[iinfo] = new string[srcCount];
for (int isrc = 0; isrc < srcCount; isrc++)
{
var tmpName = input.Schema.GetTempColumnName(column.Source[isrc]);
tmpColNames[iinfo][isrc] = tmpName;
if (termLoaderArgs != null)
{
termCols.Add(
new ValueToKeyMappingTransformer.Column
{
Name = tmpName,
Source = column.Source[isrc]
});
}
hashColumns.Add(new HashingTransformer.ColumnInfo(tmpName, termLoaderArgs == null ? column.Source[isrc] : tmpName,
30, column.Seed ?? args.Seed, false, column.InvertHash ?? args.InvertHash));
}
ngramHashColumns[iinfo] =
new NgramHashingTransformer.ColumnInfo(column.Name, tmpColNames[iinfo],
column.NgramLength ?? args.NgramLength,
column.SkipLength ?? args.SkipLength,
column.AllLengths ?? args.AllLengths,
column.HashBits ?? args.HashBits,
column.Seed ?? args.Seed,
column.Ordered ?? args.Ordered,
column.InvertHash ?? args.InvertHash);
ngramHashColumns[iinfo].FriendlyNames = column.FriendlyNames;
}
if (termLoaderArgs != null)
{
h.Assert(Utils.Size(termCols) == hashColumns.Count);
var termArgs =
new ValueToKeyMappingTransformer.Options()
{
MaxNumTerms = int.MaxValue,
Term = termLoaderArgs.Term,
Terms = termLoaderArgs.Terms,
DataFile = termLoaderArgs.DataFile,
Loader = termLoaderArgs.Loader,
TermsColumn = termLoaderArgs.TermsColumn,
Sort = termLoaderArgs.Sort,
Columns = termCols.ToArray()
};
view = ValueToKeyMappingTransformer.Create(h, termArgs, view);
if (termLoaderArgs.DropUnknowns)
{
var missingDropColumns = new (string outputColumnName, string inputColumnName)[termCols.Count];
for (int iinfo = 0; iinfo < termCols.Count; iinfo++)
missingDropColumns[iinfo] = (termCols[iinfo].Name, termCols[iinfo].Name);
view = new MissingValueDroppingTransformer(h, missingDropColumns).Transform(view);
}
}
view = new HashingEstimator(h, hashColumns.ToArray()).Fit(view).Transform(view);
view = new NgramHashingEstimator(h, ngramHashColumns).Fit(view).Transform(view);
return ColumnSelectingTransformer.CreateDrop(h, view, tmpColNames.SelectMany(cols => cols).ToArray());
}
public static IDataTransform Create(NgramHashExtractorArguments extractorArgs, IHostEnvironment env, IDataView input,
ExtractorColumn[] cols, TermLoaderArguments termLoaderArgs = null)
{
Contracts.CheckValue(env, nameof(env));
var h = env.Register(LoaderSignature);
h.CheckValue(extractorArgs, nameof(extractorArgs));
h.CheckValue(input, nameof(input));
h.CheckUserArg(extractorArgs.SkipLength < extractorArgs.NgramLength, nameof(extractorArgs.SkipLength), "Should be less than " + nameof(extractorArgs.NgramLength));
h.CheckUserArg(Utils.Size(cols) > 0, nameof(Arguments.Columns), "Must be specified");
h.AssertValueOrNull(termLoaderArgs);
var extractorCols = new Column[cols.Length];
for (int i = 0; i < cols.Length; i++)
{
extractorCols[i] =
new Column
{
Name = cols[i].Name,
Source = cols[i].Source,
FriendlyNames = cols[i].FriendlyNames
};
}
var args = new Arguments
{
Columns = extractorCols,
NgramLength = extractorArgs.NgramLength,
SkipLength = extractorArgs.SkipLength,
HashBits = extractorArgs.HashBits,
InvertHash = extractorArgs.InvertHash,
Ordered = extractorArgs.Ordered,
Seed = extractorArgs.Seed,
AllLengths = extractorArgs.AllLengths
};
return Create(h, args, input, termLoaderArgs);
}
public static INgramExtractorFactory Create(IHostEnvironment env, NgramHashExtractorArguments extractorArgs,
TermLoaderArguments termLoaderArgs)
{
Contracts.CheckValue(env, nameof(env));
var h = env.Register(LoaderSignature);
h.CheckValue(extractorArgs, nameof(extractorArgs));
h.CheckValueOrNull(termLoaderArgs);
return new NgramHashExtractorFactory(extractorArgs, termLoaderArgs);
}
}
}
| 46.492375 | 213 | 0.582709 | [
"MIT"
] | Srisach/machinelearning | src/Microsoft.ML.Transforms/Text/WordHashBagProducingTransform.cs | 21,342 | C# |
using System.Text;
using AsimovDeploy.WinAgent.Framework.Models;
using NUnit.Framework;
using Shouldly;
namespace AsimovDeploy.WinAgent.Tests.ActionParameters
{
[TestFixture]
public class TextActionParameterTests
{
private TextActionParameter _textParam;
[TestFixtureSetUp]
public void Arrange()
{
_textParam = new TextActionParameter();
_textParam.Default = "testing value";
_textParam.Name = "tasks";
}
[Test]
public void can_get_descriptor()
{
var descriptor = _textParam.GetDescriptor();
((string) descriptor.name).ShouldBe("tasks");
((string) descriptor.type).ShouldBe("text");
((string) descriptor.@default).ShouldBe("testing value");
}
[Test]
public void can_apply_to_powershell_script()
{
var script = new StringBuilder();
_textParam.ApplyToPowershellScript(script, "some value");
script.ToString().ShouldContain("$tasks = \"some value\"");
}
}
} | 29.131579 | 71 | 0.601626 | [
"Apache-2.0"
] | BonnierNews/asimov-deploy-winagent | src/AsimovDeploy.WinAgent.Tests/ActionParameters/TextActionParameterTests.cs | 1,109 | C# |
using System;
using System.Windows.Forms;
using System.Diagnostics;
namespace dell_switch_input
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void bt_setDP_Click(object sender, EventArgs e)
{
setInput("DP");
}
private void setInput(string sInName)
{
Process p = new Process();
p.StartInfo.FileName = @"C:\\Program Files (x86)\\Dell\\Dell Display Manager\\ddm.exe";
p.StartInfo.Arguments = "/SetActiveInput " + sInName;
p.Start();
}
private void bt_setmDP_Click(object sender, EventArgs e)
{
setInput("mDP");
}
private void bt_setHDMI1_Click(object sender, EventArgs e)
{
setInput("HDMI1");
}
private void bt_setHDMI2_Click(object sender, EventArgs e)
{
setInput("HDMI2");
}
}
}
| 23.046512 | 99 | 0.543895 | [
"Unlicense"
] | dmitry-usov/dell-switch-input | Form1.cs | 993 | C# |
using System;
using System.Reactive;
namespace GitHub.ViewModels
{
/// <summary>
/// Represents a view model that has a "Cancel" signal.
/// </summary>
public interface IHasCancel
{
/// <summary>
/// Gets an observable which will emit a value when the view model is cancelled.
/// </summary>
IObservable<Unit> Cancel { get; }
}
}
| 22.823529 | 88 | 0.603093 | [
"MIT"
] | karimkkanji/VisualStudio | src/GitHub.Exports.Reactive/ViewModels/IHasCancel.cs | 390 | C# |
using Vernuntii.VersionIncrementing;
namespace Vernuntii.VersioningPresets
{
/// <summary>
/// The inbuilt presets.
/// </summary>
public enum InbuiltVersioningPreset
{
/// <summary>
/// Continous delivery preset consisting of
/// <br/> - FalsyMessageIndicator for major and minor,
/// <br/> - TruthyMessageIndicator for patch and
/// <br/> - <see cref="VersionIncrementMode.Consecutive"/>
/// </summary>
ContinousDelivery,
/// <summary>
/// Continous deployment preset consisting of
/// <br/> - FalsyMessageIndicator for major and minor,
/// <br/> - TruthyMessageIndicator for patch and
/// <br/> - <see cref="VersionIncrementMode.Successive"/>
/// </summary>
ContinousDeployment,
/// <summary>
/// Conventional commits preset consisting of
/// <br/> - ConventionalCommitsMessageIndicator for version core and
/// <br/> - <see cref="VersionIncrementMode.Consecutive"/>
/// </summary>
ConventionalCommitsDelivery,
/// <summary>
/// Conventional commits preset consisting of
/// <br/> - ConventionalCommitsMessageIndicator for version core and
/// <br/> - <see cref="VersionIncrementMode.Successive"/>
/// </summary>
ConventionalCommitsDeployment,
/// <summary>
/// Manual preset consisting of
/// <br/> - none message indicators and
/// <br/> - <see cref="VersionIncrementMode.None"/>
/// </summary>
Manual,
/// <summary>
/// Default preset is <see cref="ContinousDelivery"/>.
/// </summary>
Default
}
}
| 35.791667 | 76 | 0.583818 | [
"MIT"
] | Teneko-NET-Tools/Teneko.MessagesVersioning | src/Vernuntii.Abstractions/VersioningPresets/InbuiltVersioningPreset.cs | 1,720 | 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("5.ThreeInOne")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("5.ThreeInOne")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("39948e99-0996-473b-ad2c-48a1b5fb274b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.756757 | 84 | 0.743737 | [
"MIT"
] | Ico093/TelerikAcademy | C#2/Exams/C#Part2-11-February-2013/11Feb2013/5.ThreeInOne/Properties/AssemblyInfo.cs | 1,400 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NineSocket.Client.Config
{
public enum Constant
{
CODE_CONNECT_TO_SERVER_FAIL = 1
}
}
| 16.714286 | 39 | 0.735043 | [
"Apache-2.0"
] | babman92/NineSocket | NineSocket.Client/Config/Constant.cs | 236 | C# |
// Copyright (c) Josef Pihrt and Contributors. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslynator.CodeActions;
using Roslynator.CodeFixes;
using Roslynator.CSharp.Refactorings;
using Roslynator.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static Roslynator.CSharp.CSharpFactory;
namespace Roslynator.CSharp.CodeFixes
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(ConditionalExpressionCodeFixProvider))]
[Shared]
public sealed class ConditionalExpressionCodeFixProvider : BaseCodeFixProvider
{
public override ImmutableArray<string> FixableDiagnosticIds
{
get
{
return ImmutableArray.Create(
DiagnosticIdentifiers.UseCoalesceExpressionInsteadOfConditionalExpression,
DiagnosticIdentifiers.SimplifyConditionalExpression,
DiagnosticIdentifiers.UseConditionalAccessInsteadOfConditionalExpression,
DiagnosticIdentifiers.AvoidNestedConditionalOperators);
}
}
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false);
if (!TryFindFirstAncestorOrSelf(root, context.Span, out ConditionalExpressionSyntax conditionalExpression))
return;
Document document = context.Document;
foreach (Diagnostic diagnostic in context.Diagnostics)
{
switch (diagnostic.Id)
{
case DiagnosticIdentifiers.UseCoalesceExpressionInsteadOfConditionalExpression:
{
CodeAction codeAction = CodeAction.Create(
"Use coalesce expression",
ct =>
{
return SimplifyNullCheckRefactoring.RefactorAsync(
document,
conditionalExpression,
ct);
},
GetEquivalenceKey(diagnostic));
context.RegisterCodeFix(codeAction, diagnostic);
break;
}
case DiagnosticIdentifiers.SimplifyConditionalExpression:
{
CodeAction codeAction = CodeAction.Create(
"Simplify conditional expression",
ct => SimplifyConditionalExpressionAsync(document, conditionalExpression, ct),
GetEquivalenceKey(diagnostic));
context.RegisterCodeFix(codeAction, diagnostic);
break;
}
case DiagnosticIdentifiers.UseConditionalAccessInsteadOfConditionalExpression:
{
CodeAction codeAction = CodeAction.Create(
"Use conditional access",
ct =>
{
return SimplifyNullCheckRefactoring.RefactorAsync(
document,
conditionalExpression,
ct);
},
GetEquivalenceKey(diagnostic));
context.RegisterCodeFix(codeAction, diagnostic);
break;
}
case DiagnosticIdentifiers.AvoidNestedConditionalOperators:
{
SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);
(CodeAction codeAction, CodeAction recursiveCodeAction) = ConvertConditionalExpressionToIfElseRefactoring.ComputeRefactoring(
document,
conditionalExpression,
data: default,
recursiveData: new CodeActionData(ConvertConditionalExpressionToIfElseRefactoring.Title, GetEquivalenceKey(diagnostic)),
semanticModel,
context.CancellationToken);
if (recursiveCodeAction != null)
context.RegisterCodeFix(recursiveCodeAction, diagnostic);
break;
}
}
}
}
private static async Task<Document> SimplifyConditionalExpressionAsync(
Document document,
ConditionalExpressionSyntax conditionalExpression,
CancellationToken cancellationToken)
{
ConditionalExpressionInfo info = SyntaxInfo.ConditionalExpressionInfo(conditionalExpression);
ExpressionSyntax whenTrue = info.WhenTrue;
ExpressionSyntax whenFalse = info.WhenFalse;
SyntaxKind trueKind = whenTrue.Kind();
SyntaxKind falseKind = whenFalse.Kind();
ExpressionSyntax newNode = null;
if (trueKind == SyntaxKind.TrueLiteralExpression)
{
if (falseKind == SyntaxKind.FalseLiteralExpression)
{
// a ? true : false >>> a
newNode = CreateNewNode(conditionalExpression, info.Condition);
}
else
{
// a ? true : b >>> a || b
SyntaxTriviaList trailingTrivia = info
.QuestionToken
.LeadingTrivia
.AddRange(info.QuestionToken.TrailingTrivia)
.AddRange(whenTrue.GetLeadingTrivia())
.EmptyIfWhitespace();
newNode = LogicalOrExpression(
conditionalExpression.Condition.Parenthesize().AppendToTrailingTrivia(trailingTrivia),
Token(info.ColonToken.LeadingTrivia, SyntaxKind.BarBarToken, info.ColonToken.TrailingTrivia),
whenFalse.Parenthesize());
}
}
else if (trueKind == SyntaxKind.FalseLiteralExpression)
{
if (falseKind == SyntaxKind.TrueLiteralExpression)
{
// a ? false : true >>> !a
SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
newNode = CreateNewNode(conditionalExpression, SyntaxLogicalInverter.GetInstance(document).LogicallyInvert(info.Condition, semanticModel, cancellationToken));
}
else
{
// a ? false : b >>> !a && b
SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
ExpressionSyntax newCondition = SyntaxLogicalInverter.GetInstance(document).LogicallyInvert(conditionalExpression.Condition, semanticModel, cancellationToken);
SyntaxTriviaList trailingTrivia = info
.QuestionToken
.LeadingAndTrailingTrivia()
.AddRange(whenTrue.GetLeadingAndTrailingTrivia())
.EmptyIfWhitespace();
newNode = LogicalAndExpression(
newCondition.Parenthesize().AppendToTrailingTrivia(trailingTrivia),
Token(info.ColonToken.LeadingTrivia, SyntaxKind.AmpersandAmpersandToken, info.ColonToken.TrailingTrivia),
whenFalse.Parenthesize());
}
}
else if (falseKind == SyntaxKind.FalseLiteralExpression)
{
// a ? b : false >>> a && b
SyntaxTriviaList trailingTrivia = whenTrue
.GetTrailingTrivia()
.AddRange(info.ColonToken.LeadingTrivia)
.AddRange(info.ColonToken.TrailingTrivia)
.AddRange(whenFalse.GetLeadingTrivia())
.EmptyIfWhitespace()
.AddRange(whenFalse.GetTrailingTrivia());
newNode = LogicalAndExpression(
conditionalExpression.Condition.Parenthesize(),
Token(info.QuestionToken.LeadingTrivia, SyntaxKind.AmpersandAmpersandToken, info.QuestionToken.TrailingTrivia),
whenTrue.WithTrailingTrivia(trailingTrivia).Parenthesize());
}
else if (falseKind == SyntaxKind.TrueLiteralExpression)
{
// a ? b : true >>> !a || b
SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
ExpressionSyntax newCondition = SyntaxLogicalInverter.GetInstance(document).LogicallyInvert(conditionalExpression.Condition, semanticModel, cancellationToken);
SyntaxTriviaList trailingTrivia = whenTrue
.GetTrailingTrivia()
.AddRange(info.ColonToken.LeadingAndTrailingTrivia())
.AddRange(whenFalse.GetLeadingAndTrailingTrivia())
.EmptyIfWhitespace();
newNode = LogicalOrExpression(
newCondition.Parenthesize(),
Token(info.QuestionToken.LeadingTrivia, SyntaxKind.BarBarToken, info.QuestionToken.TrailingTrivia),
whenTrue.Parenthesize().WithTrailingTrivia(trailingTrivia));
}
newNode = newNode.Parenthesize();
return await document.ReplaceNodeAsync(conditionalExpression, newNode, cancellationToken).ConfigureAwait(false);
}
private static ExpressionSyntax CreateNewNode(
ConditionalExpressionSyntax conditionalExpression,
ExpressionSyntax newNode)
{
SyntaxTriviaList trailingTrivia = conditionalExpression
.DescendantTrivia(TextSpan.FromBounds(conditionalExpression.Condition.Span.End, conditionalExpression.Span.End))
.ToSyntaxTriviaList()
.EmptyIfWhitespace()
.AddRange(conditionalExpression.GetTrailingTrivia());
return newNode
.WithLeadingTrivia(conditionalExpression.GetLeadingTrivia())
.WithTrailingTrivia(trailingTrivia)
.WithSimplifierAnnotation();
}
}
}
| 46.415638 | 179 | 0.565919 | [
"Apache-2.0"
] | ProphetLamb-Organistion/Roslynator | src/Analyzers.CodeFixes/CSharp/CodeFixes/ConditionalExpressionCodeFixProvider.cs | 11,281 | C# |
// ------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Mono Runtime Version: 2.0.50727.1433
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
// ------------------------------------------------------------------------------
namespace Valve.VR
{
using System;
using UnityEngine;
public class SteamVR_Input_ActionSet_space : Valve.VR.SteamVR_ActionSet
{
public virtual SteamVR_Action_Boolean DeleterSelect
{
get
{
return SteamVR_Actions.space_DeleterSelect;
}
}
public virtual SteamVR_Action_Boolean DeleterDelete
{
get
{
return SteamVR_Actions.space_DeleterDelete;
}
}
}
}
| 25.891892 | 81 | 0.467641 | [
"BSD-3-Clause"
] | ValveSoftware/Moondust | Assets/SteamVR_Input/ActionSetClasses/SteamVR_Input_ActionSet_space.cs | 958 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Materia.Textures;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using Materia.Shaders;
namespace Materia.Imaging.GLProcessing
{
public class GrayscaleConvProcessor : ImageProcessor
{
public Vector4 Weight { get; set; }
GLShaderProgram shader;
public GrayscaleConvProcessor() : base()
{
shader = GetShader("image.glsl", "grayscaleconv.glsl");
}
public override void Process(int width, int height, GLTextuer2D tex, GLTextuer2D output)
{
base.Process(width, height, tex, output);
if (shader != null)
{
ResizeViewTo(tex, output, tex.Width, tex.Height, width, height);
tex = output;
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
Vector2 tiling = new Vector2(TileX, TileY);
Vector4 w = Weight;
shader.Use();
shader.SetUniform2("tiling", ref tiling);
shader.SetUniform("MainTex", 0);
shader.SetUniform4F("weight", ref w);
GL.ActiveTexture(TextureUnit.Texture0);
tex.Bind();
if (renderQuad != null)
{
renderQuad.Draw();
}
GLTextuer2D.Unbind();
output.Bind();
output.CopyFromFrameBuffer(width, height);
GLTextuer2D.Unbind();
}
}
}
}
| 28.54386 | 96 | 0.55378 | [
"MIT"
] | ykafia/Materia | Materia/Imaging/GLProcessing/GrayscaleConvProcessor.cs | 1,629 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NewSudoku.Services")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NewSudoku.Services")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("20d6fc60-379d-4167-9516-c71d76e1480b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | 38.971429 | 84 | 0.745601 | [
"MIT"
] | HristoSpasov/NewSudoku | NewSudoku.Services/Properties/AssemblyInfo.cs | 1,367 | C# |
using MediatR;
using Microsoft.Extensions.Logging;
using Opdex.Platform.Application.Abstractions.Commands.Deployers;
using Opdex.Platform.Application.Abstractions.EntryCommands.Transactions.TransactionLogs.MarketDeployers;
using Opdex.Platform.Application.Abstractions.Queries.Deployers;
using Opdex.Platform.Domain.Models.TransactionLogs.MarketDeployers;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Opdex.Platform.Application.EntryHandlers.Transactions.TransactionLogs.MarketDeployers;
public class ProcessSetPendingDeployerOwnershipLogCommandHandler : IRequestHandler<ProcessSetPendingDeployerOwnershipLogCommand, bool>
{
private readonly IMediator _mediator;
private readonly ILogger<ProcessSetPendingDeployerOwnershipLogCommandHandler> _logger;
public ProcessSetPendingDeployerOwnershipLogCommandHandler(IMediator mediator, ILogger<ProcessSetPendingDeployerOwnershipLogCommandHandler> logger)
{
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task<bool> Handle(ProcessSetPendingDeployerOwnershipLogCommand request, CancellationToken cancellationToken)
{
try
{
var deployer = await _mediator.Send(new RetrieveDeployerByAddressQuery(request.Log.Contract, findOrThrow: false));
if (deployer == null) return false;
if (request.BlockHeight < deployer.ModifiedBlock)
{
return true;
}
deployer.SetPendingOwnership(request.Log, request.BlockHeight);
return await _mediator.Send(new MakeDeployerCommand(deployer, request.BlockHeight)) > 0;
}
catch (Exception ex)
{
_logger.LogError(ex, $"Failure processing {nameof(SetPendingDeployerOwnershipLog)}");
return false;
}
}
} | 41.234043 | 151 | 0.752322 | [
"MIT"
] | Opdex/opdex-v1-api | src/Opdex.Platform.Application/EntryHandlers/Transactions/TransactionLogs/MarketDeployers/ProcessSetPendingDeployerOwnershipLogCommandHandler.cs | 1,938 | C# |
using System;
using System.Collections.Generic;
using Quidjibo.Commands;
namespace Quidjibo.Autofac.Tests.Samples
{
public class BasicCommand : IQuidjiboCommand
{
public Guid? CorrelationId { get; set; }
public Dictionary<string, string> Metadata { get; set; }
}
} | 24.416667 | 64 | 0.706485 | [
"Apache-2.0"
] | smiggleworth/Quidjibo | src/Quidjibo.Autofac.Tests/Samples/BasicCommand.cs | 293 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.ContainerService.V20210201.Inputs
{
public sealed class ManagedClusterPropertiesIdentityProfileArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The client id of the user assigned identity.
/// </summary>
[Input("clientId")]
public Input<string>? ClientId { get; set; }
/// <summary>
/// The object id of the user assigned identity.
/// </summary>
[Input("objectId")]
public Input<string>? ObjectId { get; set; }
/// <summary>
/// The resource id of the user assigned identity.
/// </summary>
[Input("resourceId")]
public Input<string>? ResourceId { get; set; }
public ManagedClusterPropertiesIdentityProfileArgs()
{
}
}
}
| 29.157895 | 89 | 0.629061 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/ContainerService/V20210201/Inputs/ManagedClusterPropertiesIdentityProfileArgs.cs | 1,108 | C# |
// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
#nullable enable
namespace SixLabors.ImageSharp.Web.Synchronization
{
/// <summary>
/// Represents a thread-safe collection of reference-counted key/value pairs that can be accessed by multiple
/// threads concurrently. Values that don't yet exist are automatically created using a caller supplied
/// value factory method, and when their final refcount is released they are removed from the dictionary.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The value for the dictionary.</typeparam>
public class RefCountedConcurrentDictionary<TKey, TValue>
where TKey : notnull
where TValue : class
{
private readonly ConcurrentDictionary<TKey, RefCountedValue> dictionary;
private readonly Func<TKey, TValue> valueFactory;
private readonly Action<TValue>? valueReleaser;
/// <summary>
/// Initializes a new instance of the <see cref="RefCountedConcurrentDictionary{TKey, TValue}"/> class that is empty,
/// has the default concurrency level, has the default initial capacity, and uses the default comparer for the key type.
/// </summary>
/// <param name="valueFactory">Factory method that generates a new <typeparamref name="TValue"/> for a given <typeparamref name="TKey"/>.</param>
/// <param name="valueReleaser">Optional callback that is used to cleanup <typeparamref name="TValue"/>s after their final ref count is released.</param>
public RefCountedConcurrentDictionary(Func<TKey, TValue> valueFactory, Action<TValue>? valueReleaser = null)
: this(new ConcurrentDictionary<TKey, RefCountedValue>(), valueFactory, valueReleaser)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RefCountedConcurrentDictionary{TKey, TValue}"/> class that is empty,
/// has the default concurrency level and capacity,, and uses the specified <see cref="IEqualityComparer{TKey}"/>.
/// </summary>
/// <param name="comparer">The <see cref="IEqualityComparer{TKey}"/> implementation to use when comparing keys.</param>
/// <param name="valueFactory">Factory method that generates a new <typeparamref name="TValue"/> for a given <typeparamref name="TKey"/>.</param>
/// <param name="valueReleaser">Optional callback that is used to cleanup <typeparamref name="TValue"/>s after their final ref count is released.</param>
public RefCountedConcurrentDictionary(IEqualityComparer<TKey> comparer, Func<TKey, TValue> valueFactory, Action<TValue>? valueReleaser)
: this(new ConcurrentDictionary<TKey, RefCountedValue>(comparer), valueFactory, valueReleaser)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RefCountedConcurrentDictionary{TKey, TValue}"/> class that is empty,
/// has the specified concurrency level and capacity, and uses the default comparer for the key type.
/// </summary>
/// <param name="concurrencyLevel">The estimated number of threads that will access the <see cref="RefCountedConcurrentDictionary{TKey, TValue}"/> concurrently</param>
/// <param name="capacity">The initial number of elements that the <see cref="RefCountedConcurrentDictionary{TKey, TValue}"/> can contain.</param>
/// <param name="valueFactory">Factory method that generates a new <typeparamref name="TValue"/> for a given <typeparamref name="TKey"/>.</param>
/// <param name="valueReleaser">Optional callback that is used to cleanup <typeparamref name="TValue"/>s after their final ref count is released.</param>
public RefCountedConcurrentDictionary(int concurrencyLevel, int capacity, Func<TKey, TValue> valueFactory, Action<TValue>? valueReleaser = null)
: this(new ConcurrentDictionary<TKey, RefCountedValue>(concurrencyLevel, capacity), valueFactory, valueReleaser)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RefCountedConcurrentDictionary{TKey, TValue}"/> class that is empty,
/// has the specified concurrency level, has the specified initial capacity, and uses the specified
/// <see cref="IEqualityComparer{TKey}"/>.
/// </summary>
/// <param name="concurrencyLevel">The estimated number of threads that will access the <see cref="RefCountedConcurrentDictionary{TKey, TValue}"/> concurrently</param>
/// <param name="capacity">The initial number of elements that the <see cref="RefCountedConcurrentDictionary{TKey, TValue}"/> can contain.</param>
/// <param name="comparer">The <see cref="IEqualityComparer{TKey}"/> implementation to use when comparing keys.</param>
/// <param name="valueFactory">Factory method that generates a new <typeparamref name="TValue"/> for a given <typeparamref name="TKey"/>.</param>
/// <param name="valueReleaser">Optional callback that is used to cleanup <typeparamref name="TValue"/>s after their final ref count is released.</param>
public RefCountedConcurrentDictionary(int concurrencyLevel, int capacity, IEqualityComparer<TKey> comparer, Func<TKey, TValue> valueFactory, Action<TValue>? valueReleaser)
: this(new ConcurrentDictionary<TKey, RefCountedValue>(concurrencyLevel, capacity, comparer), valueFactory, valueReleaser)
{
}
private RefCountedConcurrentDictionary(ConcurrentDictionary<TKey, RefCountedValue> dictionary, Func<TKey, TValue> valueFactory, Action<TValue>? valueReleaser)
{
Guard.NotNull(valueFactory, nameof(valueFactory));
this.dictionary = dictionary;
this.valueFactory = valueFactory;
this.valueReleaser = valueReleaser;
}
/// <summary>
/// Obtains a reference to the value corresponding to the specified key. If no such value exists in the
/// dictionary, then a new value is generated using the value factory method supplied in the constructor.
/// To prevent leaks, this reference MUST be released via <see cref="Release(TKey)"/>.
/// </summary>
/// <param name="key">The key of the element to add ref.</param>
/// <returns>The referenced object.</returns>
public TValue Get(TKey key)
{
while (true)
{
if (this.dictionary.TryGetValue(key, out RefCountedValue? refCountedValue))
{
// Increment ref count
if (this.dictionary.TryUpdate(key, new RefCountedValue(refCountedValue.Value, refCountedValue.RefCount + 1), refCountedValue))
{
return refCountedValue.Value;
}
}
else
{
// Add new value to dictionary
TValue value = this.valueFactory(key);
if (this.dictionary.TryAdd(key, new RefCountedValue(value, 1)))
{
return value;
}
else
{
this.valueReleaser?.Invoke(value);
}
}
}
}
/// <summary>
/// Releases a reference to the value corresponding to the specified key. If this reference was the last
/// remaining reference to the value, then the value is removed from the dictionary, and the optional value
/// releaser callback is invoked.
/// </summary>
/// <param name="key">THe key of the element to release.</param>
public void Release(TKey key)
{
while (true)
{
if (!this.dictionary.TryGetValue(key, out RefCountedValue? refCountedValue))
{
// This is BAD. It indicates a ref counting problem where someone is either double-releasing,
// or they're releasing a key that they never obtained in the first place!!
throw new InvalidOperationException($"Tried to release value that doesn't exist in the dictionary ({key})!");
}
// If we're releasing the last reference, then try to remove the value from the dictionary.
// Otherwise, try to decrement the reference count.
if (refCountedValue.RefCount == 1)
{
// Remove from dictionary. We use the ICollection<>.Remove() method instead of the ConcurrentDictionary.TryRemove()
// because this specific API will only succeed if the value hasn't been changed by another thread.
if (((ICollection<KeyValuePair<TKey, RefCountedValue>>)this.dictionary).Remove(new KeyValuePair<TKey, RefCountedValue>(key, refCountedValue)))
{
this.valueReleaser?.Invoke(refCountedValue.Value);
return;
}
}
else
{
// Decrement ref count
if (this.dictionary.TryUpdate(key, new RefCountedValue(refCountedValue.Value, refCountedValue.RefCount - 1), refCountedValue))
{
return;
}
}
}
}
/// <summary>
/// Get an enumeration over the contents of the dictionary for testing/debugging purposes
/// </summary>
internal IEnumerable<(TKey Key, TValue Value, int RefCount)> DebugGetContents() => new RefCountedDictionaryEnumerable(this);
/// <summary>
/// Internal class used for testing/debugging purposes
/// </summary>
private class RefCountedDictionaryEnumerable : IEnumerable<(TKey Key, TValue Value, int RefCount)>
{
private readonly RefCountedConcurrentDictionary<TKey, TValue> dictionary;
internal RefCountedDictionaryEnumerable(RefCountedConcurrentDictionary<TKey, TValue> dictionary)
=> this.dictionary = dictionary;
public IEnumerator<(TKey Key, TValue Value, int RefCount)> GetEnumerator()
=> new RefCountedDictionaryEnumerator(this.dictionary);
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
}
/// <summary>
/// Internal class used for testing/debugging purposes
/// </summary>
private class RefCountedDictionaryEnumerator : IEnumerator<(TKey Key, TValue Value, int RefCount)>
{
private readonly IEnumerator<KeyValuePair<TKey, RefCountedValue>> enumerator;
public RefCountedDictionaryEnumerator(RefCountedConcurrentDictionary<TKey, TValue> dictionary)
=> this.enumerator = dictionary.dictionary.GetEnumerator();
public (TKey Key, TValue Value, int RefCount) Current
{
get
{
KeyValuePair<TKey, RefCountedValue> keyValuePair = this.enumerator.Current;
return (keyValuePair.Key, keyValuePair.Value.Value, keyValuePair.Value.RefCount);
}
}
object IEnumerator.Current => this.Current;
public void Dispose() => this.enumerator.Dispose();
public bool MoveNext() => this.enumerator.MoveNext();
public void Reset() => this.enumerator.Reset();
}
/// <summary>
/// Simple immutable tuple that combines a <typeparamref name="TValue"/> instance with a ref count integer.
/// </summary>
private class RefCountedValue : IEquatable<RefCountedValue>
{
#pragma warning disable SA1401 // Fields should be private
public readonly TValue Value;
public readonly int RefCount;
#pragma warning restore SA1401 // Fields should be private
public RefCountedValue(TValue value, int refCount)
{
this.Value = value;
this.RefCount = refCount;
}
public bool Equals(
#if NET5_0_OR_GREATER
RefCountedValue? other)
#elif NETCOREAPP3_1_OR_GREATER
[System.Diagnostics.CodeAnalysis.AllowNull] RefCountedValue other)
#else
RefCountedValue other)
#endif
=> (other != null) && (this.RefCount == other.RefCount) && EqualityComparer<TValue>.Default.Equals(this.Value, other.Value);
public override bool Equals(object? obj)
=> (obj is RefCountedValue other) && this.Equals(other);
public override int GetHashCode()
=> HashCode.Combine(this.RefCount, this.Value);
}
}
}
| 52.615385 | 179 | 0.63181 | [
"Apache-2.0"
] | DonPangPang/ImageSharp.Web | src/ImageSharp.Web/Synchronization/RefCountedConcurrentDictionary.cs | 12,996 | C# |
using System;
using System.ComponentModel.DataAnnotations;
namespace BandRegister.Models
{
public class Band
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Members { get; set; }
[Required]
public decimal Honorarium { get; set; }
[Required]
public string Genre { get; set; }
}
}
| 18.26087 | 47 | 0.57381 | [
"MIT"
] | kovachevmartin/SoftUni | Tech-Module/Exams/PF-FinalExam-16Dec2018/P03/BandRegister/Models/Band.cs | 422 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using TwoFactorAuthentication.Mvc.Data;
namespace TwoFactorAuthentication.Mvc.Migrations
{
[DbContext(typeof(ApplicationContext))]
partial class ApplicationContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.0");
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasColumnType("TEXT")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("TEXT")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ClaimType")
.HasColumnType("TEXT");
b.Property<string>("ClaimValue")
.HasColumnType("TEXT");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ClaimType")
.HasColumnType("TEXT");
b.Property<string>("ClaimValue")
.HasColumnType("TEXT");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("TEXT");
b.Property<string>("ProviderKey")
.HasColumnType("TEXT");
b.Property<string>("ProviderDisplayName")
.HasColumnType("TEXT");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("TEXT");
b.Property<string>("RoleId")
.HasColumnType("TEXT");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("TEXT");
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("TwoFactorAuthentication.Mvc.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<int>("AccessFailedCount")
.HasColumnType("INTEGER");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed")
.HasColumnType("INTEGER");
b.Property<bool>("LockoutEnabled")
.HasColumnType("INTEGER");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("TEXT");
b.Property<string>("NormalizedEmail")
.HasColumnType("TEXT")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasColumnType("TEXT")
.HasMaxLength(256);
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")
.HasColumnType("TEXT")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("TwoFactorAuthentication.Mvc.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("TwoFactorAuthentication.Mvc.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("TwoFactorAuthentication.Mvc.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("TwoFactorAuthentication.Mvc.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 35.554717 | 95 | 0.451815 | [
"MIT"
] | flaviogf/Cursos | balta/aspnet_core_identity_introduction/TwoFactorAuthentication/TwoFactorAuthentication.Mvc/Migrations/ApplicationContextModelSnapshot.cs | 9,424 | C# |
// Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable IDE0079 // remove unnecessary pragmas
#pragma warning disable IDE1006 // parts of the code use IDL spelling
#pragma warning disable IDE0083 // pattern matching "that is not SomeType" requires net5.0 but we still support earlier versions
namespace Hazelcast.Testing.Remote
{
public enum Lang
{
JAVASCRIPT = 1,
GROOVY = 2,
PYTHON = 3,
RUBY = 4,
}
}
| 35.068966 | 129 | 0.735497 | [
"Apache-2.0"
] | Serdaro/hazelcast-csharp-client | src/Hazelcast.Net.Testing/Remote/Lang.cs | 1,017 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FlyingEnemy : Enemy,IDamageable{
public int Health { get; set; }
public Transform[] waypoints;
private int randomSpot;
private float waitTime;
public float startWaitTime;
[SerializeField]
private GameObject bloodEffectPrefab;
[SerializeField]
private GameObject deathEffectPrefab;
[SerializeField]
private float maxDistance;
public override void Init()
{
base.Init();
Health = base.health;
}
public override void Start()
{
base.Start();
randomSpot = Random.Range(0, waypoints.Length);
waitTime = startWaitTime;
}
//Prendre des dégats
public void TakeDamage(int damageAmount)
{
//Debug.Log("Damage Taken");
Health = Health - damageAmount;
GameObject effect = Instantiate(bloodEffectPrefab, transform.position, transform.rotation);
Destroy(effect, 0.5f);
//Debug.Log("is Hit is true now");
//anim.SetTrigger("HURT");
if (Health <= 0)
{
camRipple.RippleEffect();
FindObjectOfType<AudioManager>().Play("FlyingEnemyDeath");
GameObject effectD = Instantiate(deathEffectPrefab, transform.position, transform.rotation);
Destroy(effectD, 2.5f);
SpawnGems();
Destroy(this.gameObject, 0.3f);
}
}
public override void Update()
{
distance = Vector3.Distance(transform.position, player.transform.position);
if(distance > maxDistance)
{
Movement();
}
else{
Chase();
}
}
public override void Movement()
{
anim.SetBool("Done", true);
transform.position = Vector2.MoveTowards(transform.position, waypoints[randomSpot].position, speed * Time.deltaTime);
if (Vector2.Distance(transform.position, waypoints[randomSpot].position) < 0.2f)
{
if (waitTime <= 0)
{
randomSpot = Random.Range(0, waypoints.Length);
waitTime = startWaitTime;
}
else
{
waitTime -= Time.deltaTime;
}
}
}
public override void Chase()
{
anim.SetBool("Done", false);
transform.position = Vector2.MoveTowards(transform.position, player.transform.position, speed * Time.deltaTime);
}
} | 26.795699 | 125 | 0.593499 | [
"MIT"
] | JoeBens/Unity-Project | Mighty/Assets/Scripts/MonoBehaviour/Enemies/FlyingEnemy/FlyingEnemy.cs | 2,495 | C# |
/*----------------------------------------------------------------
* Copyright (c) ThoughtWorks, Inc.
* Licensed under the Apache License, Version 2.0
* See LICENSE.txt in the project root for license information.
*----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using Gauge.CSharp.Lib;
using Gauge.Dotnet.Extensions;
using Gauge.Dotnet.Models;
using Gauge.Dotnet.Wrappers;
namespace Gauge.Dotnet
{
public class AssemblyLoader : IAssemblyLoader
{
private const string GaugeLibAssembleName = "Gauge.CSharp.Lib";
private readonly IAssemblyWrapper _assemblyWrapper;
private readonly IReflectionWrapper _reflectionWrapper;
private Assembly _targetLibAssembly;
private readonly IActivatorWrapper _activatorWrapper;
private readonly IStepRegistry _registry;
public AssemblyLoader(IAssemblyWrapper assemblyWrapper, IEnumerable<string> assemblyLocations,
IReflectionWrapper reflectionWrapper, IActivatorWrapper activatorWrapper, IStepRegistry registry)
{
_assemblyWrapper = assemblyWrapper;
_reflectionWrapper = reflectionWrapper;
_activatorWrapper = activatorWrapper;
AssembliesReferencingGaugeLib = new List<Assembly>();
_registry = registry;
foreach (var location in assemblyLocations)
ScanAndLoad(location);
LoadTargetLibAssembly();
SetDefaultTypes();
}
public List<Assembly> AssembliesReferencingGaugeLib { get; }
public Type ScreenshotWriter { get; private set; }
public Type ClassInstanceManagerType { get; private set; }
public IEnumerable<MethodInfo> GetMethods(LibType type)
{
var attributeType = _targetLibAssembly.GetType(type.FullName());
bool MethodFilter(MethodInfo info)
{
return info.GetCustomAttributes(false)
.Any(attributeType.IsInstanceOfType);
}
IEnumerable<MethodInfo> MethodSelector(Type t)
{
return _reflectionWrapper.GetMethods(t).Where(MethodFilter);
}
return AssembliesReferencingGaugeLib.SelectMany(assembly => assembly.GetTypes().SelectMany(MethodSelector));
}
public Type GetLibType(LibType type)
{
return _targetLibAssembly.GetType(type.FullName());
}
public IStepRegistry GetStepRegistry()
{
var infos = GetMethods(LibType.Step);
foreach (var info in infos)
{
var stepTexts = info.GetCustomAttributes(GetLibType(LibType.Step))
.SelectMany(x => x.GetType().GetProperty("Names").GetValue(x, null) as string[]);
foreach (var stepText in stepTexts)
{
var stepValue = GetStepValue(stepText);
if (_registry.ContainsStep(stepValue))
{
_registry.MethodFor(stepValue).MethodInfo = info;
_registry.MethodFor(stepValue).ContinueOnFailure = info.IsRecoverableStep(this);
}
else
{
var hasAlias = stepTexts.Count() > 1;
var stepMethod = new GaugeMethod
{
Name = info.FullyQuallifiedName(),
ParameterCount = info.GetParameters().Length,
StepText = stepText,
HasAlias = hasAlias,
Aliases = stepTexts,
MethodInfo = info,
ContinueOnFailure = info.IsRecoverableStep(this),
StepValue = stepValue,
IsExternal = true,
};
_registry.AddStep(stepValue, stepMethod);
}
}
}
return _registry;
}
public object GetClassInstanceManager()
{
if (ClassInstanceManagerType == null) return null;
var classInstanceManager = _activatorWrapper.CreateInstance(ClassInstanceManagerType);
Logger.Debug("Loaded Instance Manager of Type:" + classInstanceManager.GetType().FullName);
_reflectionWrapper.InvokeMethod(ClassInstanceManagerType, classInstanceManager, "Initialize",
AssembliesReferencingGaugeLib);
return classInstanceManager;
}
private static string GetStepValue(string stepText)
{
return Regex.Replace(stepText, @"(<.*?>)", @"{}");
}
private void ScanAndLoad(string path)
{
Logger.Debug($"Loading assembly from : {path}");
var assembly = _assemblyWrapper.LoadFrom(path);
var isReferencingGaugeLib = assembly.GetReferencedAssemblies()
.Select(name => name.Name)
.Contains(GaugeLibAssembleName);
if (!isReferencingGaugeLib)
return;
AssembliesReferencingGaugeLib.Add(assembly);
try
{
if (ScreenshotWriter is null)
ScanForCustomScreenshotWriter(assembly.GetTypes());
if (ScreenshotWriter is null)
ScanForCustomScreengrabber(assembly.GetTypes());
if (ClassInstanceManagerType is null)
ScanForCustomInstanceManager(assembly.GetTypes());
}
catch (ReflectionTypeLoadException ex)
{
foreach (var e in ex.LoaderExceptions)
Logger.Error(e.ToString());
}
}
private void ScanForCustomScreenshotWriter(IEnumerable<Type> types)
{
var implementingTypes = types.Where(type =>
type.GetInterfaces().Any(t => t.FullName == "Gauge.CSharp.Lib.ICustomScreenshotWriter"));
ScreenshotWriter = implementingTypes.FirstOrDefault();
if (ScreenshotWriter is null) return;
var csg = (ICustomScreenshotWriter)_activatorWrapper.CreateInstance(ScreenshotWriter);
GaugeScreenshots.RegisterCustomScreenshotWriter(csg);
}
private void ScanForCustomScreengrabber(IEnumerable<Type> types)
{
var implementingTypes = types.Where(type =>
type.GetInterfaces().Any(t => t.FullName == "Gauge.CSharp.Lib.ICustomScreenshotGrabber"));
ScreenshotWriter = implementingTypes.FirstOrDefault();
if (ScreenshotWriter is null) return;
var csg = (ICustomScreenshotGrabber)_activatorWrapper.CreateInstance(ScreenshotWriter);
GaugeScreenshots.RegisterCustomScreenshotGrabber(csg);
}
private void ScanForCustomInstanceManager(IEnumerable<Type> types)
{
var implementingTypes = types.Where(type =>
type.GetInterfaces().Any(t => t.FullName == "Gauge.CSharp.Lib.IClassInstanceManager"));
ClassInstanceManagerType = implementingTypes.FirstOrDefault();
}
private void SetDefaultTypes()
{
ClassInstanceManagerType = ClassInstanceManagerType ??
_targetLibAssembly.GetType(LibType.DefaultClassInstanceManager.FullName());
ScreenshotWriter =
ScreenshotWriter ?? _targetLibAssembly.GetType(LibType.DefaultScreenshotWriter.FullName());
}
private void LoadTargetLibAssembly()
{
_targetLibAssembly = _assemblyWrapper.GetCurrentDomainAssemblies()
.First(x => string.CompareOrdinal(x.GetName().Name, GaugeLibAssembleName) == 0);
}
}
} | 40.06 | 120 | 0.58687 | [
"Apache-2.0"
] | aerotog/gauge-dotnet | src/AssemblyLoader.cs | 8,014 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace LagoVista.IoT.Runtime.Core.Models.PEM
{
public class MessageRawPayload
{
public byte[] MessageBuffer { get; set; }
}
}
| 18.166667 | 49 | 0.701835 | [
"MIT"
] | LagoVista/Runtime | src/LagoVista.IoT.Runtime.Core/Models/PEM/MessageRawPayload.cs | 220 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.ContainerRegistry.Latest.Inputs
{
/// <summary>
/// The platform properties against which the run has to happen.
/// </summary>
public sealed class PlatformPropertiesArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The OS architecture.
/// </summary>
[Input("architecture")]
public InputUnion<string, Pulumi.AzureNextGen.ContainerRegistry.Latest.Architecture>? Architecture { get; set; }
/// <summary>
/// The operating system type required for the run.
/// </summary>
[Input("os", required: true)]
public InputUnion<string, Pulumi.AzureNextGen.ContainerRegistry.Latest.OS> Os { get; set; } = null!;
/// <summary>
/// Variant of the CPU.
/// </summary>
[Input("variant")]
public InputUnion<string, Pulumi.AzureNextGen.ContainerRegistry.Latest.Variant>? Variant { get; set; }
public PlatformPropertiesArgs()
{
}
}
}
| 32.04878 | 120 | 0.642314 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/ContainerRegistry/Latest/Inputs/PlatformPropertiesArgs.cs | 1,314 | C# |
#region copyright
// ******************************************************************
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THE CODE 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 CODE OR THE USE OR OTHER DEALINGS IN THE CODE.
// ******************************************************************
#endregion
using System;
using System.Diagnostics;
using Inventory.Data;
using Inventory.Models;
using Inventory.Services;
namespace Inventory.ViewModels
{
public class ViewModelBase : ObservableObject
{
private Stopwatch _stopwatch = new Stopwatch();
public ViewModelBase(ICommonServices commonServices)
{
ContextService = commonServices.ContextService;
NavigationService = commonServices.NavigationService;
MessageService = commonServices.MessageService;
DialogService = commonServices.DialogService;
LogService = commonServices.LogService;
}
public IContextService ContextService { get; }
public INavigationService NavigationService { get; }
public IMessageService MessageService { get; }
public IDialogService DialogService { get; }
public ILogService LogService { get; }
public bool IsMainView => ContextService.IsMainView;
virtual public string Title => String.Empty;
public async void LogInformation(string source, string action, string message, string description)
{
await LogService.WriteAsync(LogType.Information, source, action, message, description);
}
public async void LogWarning(string source, string action, string message, string description)
{
await LogService.WriteAsync(LogType.Warning, source, action, message, description);
}
public void LogException(string source, string action, Exception exception)
{
LogError(source, action, exception.Message, exception.ToString());
}
public async void LogError(string source, string action, string message, string description)
{
await LogService.WriteAsync(LogType.Error, source, action, message, description);
}
public void StartStatusMessage(string message)
{
StatusMessage(message);
_stopwatch.Reset();
_stopwatch.Start();
}
public void EndStatusMessage(string message)
{
_stopwatch.Stop();
StatusMessage($"{message} ({_stopwatch.Elapsed.TotalSeconds:#0.000} seconds)");
}
public void StatusReady()
{
MessageService.Send(this, "StatusMessage", "Ready");
}
public void StatusMessage(string message)
{
MessageService.Send(this, "StatusMessage", message);
}
public void StatusError(string message)
{
MessageService.Send(this, "StatusError", message);
}
public void EnableThisView(string message = null)
{
message = message ?? "Ready";
MessageService.Send(this, "EnableThisView", message);
}
public void DisableThisView(string message)
{
MessageService.Send(this, "DisableThisView", message);
}
public void EnableOtherViews(string message = null)
{
message = message ?? "Ready";
MessageService.Send(this, "EnableOtherViews", message);
}
public void DisableOtherViews(string message)
{
MessageService.Send(this, "DisableOtherViews", message);
}
public void EnableAllViews(string message = null)
{
message = message ?? "Ready";
MessageService.Send(this, "EnableAllViews", message);
}
public void DisableAllViews(string message)
{
MessageService.Send(this, "DisableAllViews", message);
}
}
}
| 35.803279 | 106 | 0.623168 | [
"MIT"
] | DevX-Realtobiz/InventorySample | src/Inventory.ViewModels/Infrastructure/ViewModels/ViewModelBase.cs | 4,370 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Mis.Entities.Concrete;
namespace Mis.DataAccess.Concrete.Seeds
{
public class FromFactorSeed : IEntityTypeConfiguration<FromFactor>
{
public FromFactorSeed()
{
}
public void Configure(EntityTypeBuilder<FromFactor> builder)
{
/* Dummy Data */
builder.HasData(
new FromFactor { Id = 1, FromFactorName = "Tower" },
new FromFactor { Id = 2, FromFactorName = "Mid-Tower" }
);
}
}
}
| 25.791667 | 71 | 0.596123 | [
"MIT"
] | emreerdogancom/Mis | src/Mis.DataAccess/Concrete/Seeds/FromFactorSeed.cs | 621 | C# |
//---------------------------------------------------------
// <auto-generated>
// This code was generated by a tool. Changes to this
// file may cause incorrect behavior and will be lost
// if the code is regenerated.
//
// Generated on 2020 October 09 05:20:07 UTC
// </auto-generated>
//---------------------------------------------------------
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using static go.builtin;
using ptwo = go.p2_package;
using go;
#nullable enable
namespace go {
namespace cmd {
namespace api {
namespace testdata {
namespace src {
namespace pkg
{
public static partial class p1_package
{
[GeneratedCode("go2cs", "0.1.0.0")]
public partial struct URL
{
// Constructors
public URL(NilType _)
{
}
// Enable comparisons between nil and URL struct
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(URL value, NilType nil) => value.Equals(default(URL));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(URL value, NilType nil) => !(value == nil);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(NilType nil, URL value) => value == nil;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(NilType nil, URL value) => value != nil;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator URL(NilType nil) => default(URL);
}
[GeneratedCode("go2cs", "0.1.0.0")]
public static URL URL_cast(dynamic value)
{
return new URL();
}
}
}}}}}} | 31.433333 | 97 | 0.593319 | [
"MIT"
] | GridProtectionAlliance/go2cs | src/go-src-converted/cmd/api/testdata/src/pkg/p1/p1_URLStruct.cs | 1,886 | C# |
// <copyright file="Sniffer.cs" company="Rocket Robin">
// Copyright (c) Rocket Robin. All rights reserved.
// Licensed under the Apache v2 license. See LICENSE file in the project root for full license information.
// </copyright>
using System;
using System.Collections.Generic;
using System.Linq;
namespace Myrmec
{
/// <summary>
/// sniffer
/// </summary>
public class Sniffer
{
/// <summary>
/// You can get the file extention name detail in this wikipedia page.
/// </summary>
public const string FileExtentionHelpUrl = "https://en.wikipedia.org/wiki/List_of_file_signatures";
private Node _root;
/// <summary>
/// Initializes a new instance of the <see cref="Sniffer"/> class.
/// </summary>
public Sniffer()
{
_root = new Node()
{
Children = new SortedList<byte, Node>(128),
Depth = -1,
};
ComplexMetadata = new List<Metadata>(10);
}
/// <summary>
/// Gets or sets ComplexMetadatas.
/// </summary>
public List<Metadata> ComplexMetadata { get; set; }
/// <summary>
/// Add a record to matadata tree.
/// </summary>
/// <param name="data">file head.</param>
/// <param name="extentions">file extention list.</param>
public void Add(byte[] data, string[] extentions)
{
Add(data, _root, extentions, 0);
}
/// <summary>
///
/// </summary>
/// <param name="record"></param>
public void Add(Record record)
{
if (record.IsComplexMetadata)
{
ComplexMetadata.Add(record);
}
else
{
Add(record.Hex.GetByte(), record.Extentions.Split(',', ' '));
}
}
/// <summary>
/// Find extentions that match the file hex head.
/// </summary>
/// <param name="data">file hex head</param>
/// <param name="matchAll">match all result or only the first.</param>
/// <returns>matched result</returns>
public List<string> Match(byte[] data, bool matchAll = false)
{
List<string> extentionStore = new List<string>(4);
Match(data, 0, _root, extentionStore, matchAll);
if (matchAll || !extentionStore.Any())
{
// Match data from complex metadata.
extentionStore.AddRange(ComplexMetadata.Match(data, matchAll));
}
// Remove repeated extentions.
if (matchAll && extentionStore.Any())
{
extentionStore = extentionStore.Distinct().ToList();
}
return extentionStore;
}
private void Add(byte[] data, Node parent, string[] extentions, int depth)
{
Node current = null;
if (parent.Children == null)
{
parent.Children = new SortedList<byte, Node>(Convert.ToInt32(128 / Math.Pow(2, depth)));
}
// if not contains current byte index, create node and put it into children.
if (!parent.Children.ContainsKey(data[depth]))
{
current = new Node
{
Depth = depth,
Parent = parent
};
parent.Children.Add(data[depth], current);
}
else
{
if (!parent.Children.TryGetValue(data[depth], out current))
{
throw new Exception("No possibility, something fucked up...");
}
}
// last byte, put extentions into Extentions.
if (depth == (data.Length - 1))
{
if (current.Extentions == null)
{
current.Extentions = new List<string>(4);
}
current.Extentions.AddRange(extentions);
return;
}
Add(data, current, extentions, depth + 1);
}
private void Match(byte[] data, int depth, Node node, List<string> extentionStore, bool matchAll)
{
// if depth out of data.Length's index then data end.
if (data.Length == depth)
{
return;
}
node.Children.TryGetValue(data[depth], out Node current);
// can't find matched node, match ended.
if (current == null)
{
return;
}
// now extentions not null, this node is a final node and this is a result.
if (current.Extentions != null)
{
extentionStore.AddRange(current.Extentions);
// if only match first matched.
if (!matchAll)
{
return;
}
}
// children is null, match ended.
if (current.Children == null)
{
return;
}
// children not null, keep match.
Match(data, depth + 1, current, extentionStore, matchAll);
}
}
} | 30.382857 | 107 | 0.48975 | [
"Apache-2.0"
] | anuraj/myrmec | src/Myrmec/Sniffer.cs | 5,319 | C# |
using System;
using System.Collections.Generic;
using Liu.Domain.Core.Events;
namespace Liu.Infra.Data.Repository.EventSourcing
{
public interface IEventStoreRepository : IDisposable
{
void Store(StoredEvent theEvent);
IList<StoredEvent> All(Guid aggregateId);
}
} | 24.5 | 56 | 0.738095 | [
"MIT"
] | faugusto90/LiuProject | src/Liu.Infra.CrossCutting.IoC/Liu.Infra.Data/Repository/EventSourcing/IEventStoreRepository.cs | 296 | C# |
// <copyright file="XXHash.cs" company="Sedat Kapanoglu">
// Copyright (c) 2015-2021 Sedat Kapanoglu
// MIT License (see LICENSE file for details)
// </copyright>
using System;
using System.IO;
using System.Runtime.CompilerServices;
namespace HashDepot
{
/// <summary>
/// XXHash implementation.
/// </summary>
public static class XXHash
{
private const ulong prime64v1 = 11400714785074694791ul;
private const ulong prime64v2 = 14029467366897019727ul;
private const ulong prime64v3 = 1609587929392839161ul;
private const ulong prime64v4 = 9650029242287828579ul;
private const ulong prime64v5 = 2870177450012600261ul;
private const uint prime32v1 = 2654435761u;
private const uint prime32v2 = 2246822519u;
private const uint prime32v3 = 3266489917u;
private const uint prime32v4 = 668265263u;
private const uint prime32v5 = 374761393u;
/// <summary>
/// Generate a 32-bit xxHash value.
/// </summary>
/// <param name="buffer">Input buffer.</param>
/// <param name="seed">Optional seed.</param>
/// <returns>32-bit hash value.</returns>
public static unsafe uint Hash32(ReadOnlySpan<byte> buffer, uint seed = 0)
{
const int stripeLength = 16;
bool bigEndian = Bits.IsBigEndian;
int len = buffer.Length;
int remainingLen = len;
uint acc;
fixed (byte* inputPtr = buffer)
{
byte* pInput = inputPtr;
if (len >= stripeLength)
{
var (acc1, acc2, acc3, acc4) = initAccumulators32(seed);
do
{
acc = processStripe32(ref pInput, ref acc1, ref acc2, ref acc3, ref acc4, bigEndian);
remainingLen -= stripeLength;
}
while (remainingLen >= stripeLength);
}
else
{
acc = seed + prime32v5;
}
acc += (uint)len;
acc = processRemaining32(pInput, acc, remainingLen, bigEndian);
}
return avalanche32(acc);
}
/// <summary>
/// Generate a 32-bit xxHash value from a stream.
/// </summary>
/// <param name="stream">Input stream.</param>
/// <param name="seed">Optional seed.</param>
/// <returns>32-bit hash value.</returns>
public static unsafe uint Hash32(Stream stream, uint seed = 0)
{
const int stripeLength = 16;
const int readBufferSize = stripeLength * 1024; // 16kb read buffer - has to be stripe aligned
bool bigEndian = Bits.IsBigEndian;
var buffer = new byte[readBufferSize];
uint acc;
int readBytes = stream.Read(buffer, 0, readBufferSize);
int len = readBytes;
fixed (byte* inputPtr = buffer)
{
byte* pInput = inputPtr;
if (readBytes >= stripeLength)
{
var (acc1, acc2, acc3, acc4) = initAccumulators32(seed);
do
{
do
{
acc = processStripe32(
ref pInput,
ref acc1,
ref acc2,
ref acc3,
ref acc4,
bigEndian);
readBytes -= stripeLength;
}
while (readBytes >= stripeLength);
// read more if the alignment is still intact
if (readBytes == 0)
{
readBytes = stream.Read(buffer, 0, readBufferSize);
pInput = inputPtr;
len += readBytes;
}
}
while (readBytes >= stripeLength);
}
else
{
acc = seed + prime32v5;
}
acc += (uint)len;
acc = processRemaining32(pInput, acc, readBytes, bigEndian);
}
return avalanche32(acc);
}
/// <summary>
/// Generate a 64-bit xxHash value.
/// </summary>
/// <param name="buffer">Input buffer.</param>
/// <param name="seed">Optional seed.</param>
/// <returns>Computed 64-bit hash value.</returns>
public static unsafe ulong Hash64(ReadOnlySpan<byte> buffer, ulong seed = 0)
{
const int stripeLength = 32;
bool bigEndian = Bits.IsBigEndian;
int len = buffer.Length;
int remainingLen = len;
ulong acc;
fixed (byte* inputPtr = buffer)
{
byte* pInput = inputPtr;
if (len >= stripeLength)
{
var (acc1, acc2, acc3, acc4) = initAccumulators64(seed);
do
{
acc = processStripe64(ref pInput, ref acc1, ref acc2, ref acc3, ref acc4, bigEndian);
remainingLen -= stripeLength;
}
while (remainingLen >= stripeLength);
}
else
{
acc = seed + prime64v5;
}
acc += (ulong)len;
acc = processRemaining64(pInput, acc, remainingLen, bigEndian);
}
return avalanche64(acc);
}
/// <summary>
/// Generate a 64-bit xxHash value from a stream.
/// </summary>
/// <param name="stream">Input stream.</param>
/// <param name="seed">Optional seed.</param>
/// <returns>Computed 64-bit hash value.</returns>
public static unsafe ulong Hash64(Stream stream, ulong seed = 0)
{
const int stripeLength = 32;
const int readBufferSize = stripeLength * 1024; // 32kb buffer length
bool bigEndian = Bits.IsBigEndian;
ulong acc;
var buffer = new byte[readBufferSize];
int readBytes = stream.Read(buffer, 0, readBufferSize);
ulong len = (ulong)readBytes;
fixed (byte* inputPtr = buffer)
{
byte* pInput = inputPtr;
if (readBytes >= stripeLength)
{
var (acc1, acc2, acc3, acc4) = initAccumulators64(seed);
do
{
do
{
acc = processStripe64(
ref pInput,
ref acc1,
ref acc2,
ref acc3,
ref acc4,
bigEndian);
readBytes -= stripeLength;
}
while (readBytes >= stripeLength);
// read more if the alignment is intact
if (readBytes == 0)
{
readBytes = stream.Read(buffer, 0, readBufferSize);
pInput = inputPtr;
len += (ulong)readBytes;
}
}
while (readBytes >= stripeLength);
}
else
{
acc = seed + prime64v5;
}
acc += len;
acc = processRemaining64(pInput, acc, readBytes, bigEndian);
}
return avalanche64(acc);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe (ulong, ulong, ulong, ulong) initAccumulators64(ulong seed)
{
return (seed + prime64v1 + prime64v2, seed + prime64v2, seed, seed - prime64v1);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe ulong processStripe64(
ref byte* pInput,
ref ulong acc1,
ref ulong acc2,
ref ulong acc3,
ref ulong acc4,
bool bigEndian)
{
if (bigEndian)
{
processLaneBigEndian64(ref acc1, ref pInput);
processLaneBigEndian64(ref acc2, ref pInput);
processLaneBigEndian64(ref acc3, ref pInput);
processLaneBigEndian64(ref acc4, ref pInput);
}
else
{
processLane64(ref acc1, ref pInput);
processLane64(ref acc2, ref pInput);
processLane64(ref acc3, ref pInput);
processLane64(ref acc4, ref pInput);
}
ulong acc = Bits.RotateLeft(acc1, 1)
+ Bits.RotateLeft(acc2, 7)
+ Bits.RotateLeft(acc3, 12)
+ Bits.RotateLeft(acc4, 18);
mergeAccumulator64(ref acc, acc1);
mergeAccumulator64(ref acc, acc2);
mergeAccumulator64(ref acc, acc3);
mergeAccumulator64(ref acc, acc4);
return acc;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe void processLane64(ref ulong accn, ref byte* pInput)
{
ulong lane = *(ulong*)pInput;
accn = round64(accn, lane);
pInput += 8;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe void processLaneBigEndian64(ref ulong accn, ref byte* pInput)
{
ulong lane = *(ulong*)pInput;
lane = Bits.SwapBytes64(lane);
accn = round64(accn, lane);
pInput += 8;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe ulong processRemaining64(
byte* pInput,
ulong acc,
int remainingLen,
bool bigEndian)
{
for (ulong lane; remainingLen >= 8; remainingLen -= 8, pInput += 8)
{
lane = *(ulong*)pInput;
if (bigEndian)
{
lane = Bits.SwapBytes64(lane);
}
acc ^= round64(0, lane);
acc = Bits.RotateLeft(acc, 27) * prime64v1;
acc += prime64v4;
}
for (uint lane32; remainingLen >= 4; remainingLen -= 4, pInput += 4)
{
lane32 = *(uint*)pInput;
if (bigEndian)
{
lane32 = Bits.SwapBytes32(lane32);
}
acc ^= lane32 * prime64v1;
acc = Bits.RotateLeft(acc, 23) * prime64v2;
acc += prime64v3;
}
for (byte lane8; remainingLen >= 1; remainingLen--, pInput++)
{
lane8 = *pInput;
acc ^= lane8 * prime64v5;
acc = Bits.RotateLeft(acc, 11) * prime64v1;
}
return acc;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static ulong avalanche64(ulong acc)
{
acc ^= acc >> 33;
acc *= prime64v2;
acc ^= acc >> 29;
acc *= prime64v3;
acc ^= acc >> 32;
return acc;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static ulong round64(ulong accn, ulong lane)
{
accn += lane * prime64v2;
return Bits.RotateLeft(accn, 31) * prime64v1;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void mergeAccumulator64(ref ulong acc, ulong accn)
{
acc ^= round64(0, accn);
acc *= prime64v1;
acc += prime64v4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe (uint, uint, uint, uint) initAccumulators32(
uint seed)
{
return (seed + prime32v1 + prime32v2, seed + prime32v2, seed, seed - prime32v1);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe uint processStripe32(
ref byte* pInput,
ref uint acc1,
ref uint acc2,
ref uint acc3,
ref uint acc4,
bool bigEndian)
{
if (bigEndian)
{
processLaneBigEndian32(ref pInput, ref acc1);
processLaneBigEndian32(ref pInput, ref acc2);
processLaneBigEndian32(ref pInput, ref acc3);
processLaneBigEndian32(ref pInput, ref acc4);
}
else
{
processLane32(ref pInput, ref acc1);
processLane32(ref pInput, ref acc2);
processLane32(ref pInput, ref acc3);
processLane32(ref pInput, ref acc4);
}
return Bits.RotateLeft(acc1, 1)
+ Bits.RotateLeft(acc2, 7)
+ Bits.RotateLeft(acc3, 12)
+ Bits.RotateLeft(acc4, 18);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe void processLane32(ref byte* pInput, ref uint accn)
{
uint lane = *(uint*)pInput;
accn = round32(accn, lane);
pInput += 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe void processLaneBigEndian32(ref byte* pInput, ref uint accn)
{
uint lane = Bits.SwapBytes32(*(uint*)pInput);
accn = round32(accn, lane);
pInput += 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe uint processRemaining32(
byte* pInput,
uint acc,
int remainingLen,
bool bigEndian)
{
for (uint lane; remainingLen >= 4; remainingLen -= 4, pInput += 4)
{
lane = *(uint*)pInput;
if (bigEndian)
{
lane = Bits.SwapBytes32(lane);
}
acc += lane * prime32v3;
acc = Bits.RotateLeft(acc, 17) * prime32v4;
}
for (byte lane; remainingLen >= 1; remainingLen--, pInput++)
{
lane = *pInput;
acc += lane * prime32v5;
acc = Bits.RotateLeft(acc, 11) * prime32v1;
}
return acc;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe uint round32(uint accn, uint lane)
{
accn += lane * prime32v2;
accn = Bits.RotateLeft(accn, 13);
accn *= prime32v1;
return accn;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static uint avalanche32(uint acc)
{
acc ^= acc >> 15;
acc *= prime32v2;
acc ^= acc >> 13;
acc *= prime32v3;
acc ^= acc >> 16;
return acc;
}
}
}
| 33.636559 | 109 | 0.473052 | [
"MIT"
] | ssg/HashDepot | src/XXHash.cs | 15,641 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.System.Profile
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial class EducationSettings
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public static bool IsEducationEnvironment
{
get
{
throw new global::System.NotImplementedException("The member bool EducationSettings.IsEducationEnvironment is not implemented in Uno.");
}
}
#endif
// Forced skipping of method Windows.System.Profile.EducationSettings.IsEducationEnvironment.get
}
}
| 37.73913 | 140 | 0.748848 | [
"Apache-2.0"
] | Abhishek-Sharma-Msft/uno | src/Uno.UWP/Generated/3.0.0.0/Windows.System.Profile/EducationSettings.cs | 868 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.