content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Text;
namespace StringSample
{
class Program
{
static void Main()
{
SimpleStrings();
UsingStringBuilder();
Console.ReadLine();
}
public static void UsingStringBuilder()
{
var greetingBuilder =
new StringBuilder("Hello from all the people at Wrox Press. ", 150);
greetingBuilder.Append("We do hope you enjoy this book as much as we " +
"enjoyed writing it");
Console.WriteLine("Not Encoded:\n" + greetingBuilder);
for (int i = 'z'; i >= 'a'; i--)
{
char old1 = (char)i;
char new1 = (char)(i + 1);
greetingBuilder = greetingBuilder.Replace(old1, new1);
}
for (int i = 'Z'; i >= 'A'; i--)
{
char old1 = (char)i;
char new1 = (char)(i + 1);
greetingBuilder = greetingBuilder.Replace(old1, new1);
}
Console.WriteLine("Encoded:\n" + greetingBuilder);
}
public static void SimpleStrings()
{
string greetingText = "Hello from all the people at Wrox Press. ";
greetingText += "We do hope you enjoy this book as much as we enjoyed writing it.";
Console.WriteLine("Not Encoded:\n" + greetingText);
for (int i = 'z'; i >= 'a'; i--)
{
char old1 = (char)i;
char new1 = (char)(i + 1);
greetingText = greetingText.Replace(old1, new1);
}
for (int i = 'Z'; i >= 'A'; i--)
{
char old1 = (char)i;
char new1 = (char)(i + 1);
greetingText = greetingText.Replace(old1, new1);
}
Console.WriteLine($"Encoded:\n {greetingText}");
}
}
}
| 28.850746 | 95 | 0.470771 | [
"MIT"
] | Bazzaware/ProfessionalCSharp7 | StringsAndRegularExpressions/StringSample/Program.cs | 1,935 | C# |
using UnityEngine;
using UnityEngine.UI;
public class MethodCalls : MonoBehaviour {
[SerializeField]
private Animator animator;
[SerializeField]
private Text output;
[SerializeField]
private InputField inputField;
private AnimationManager am;
private void Start() {
am = AnimationManager.instance;
}
public void PlayAnimationClicked() {
AnimationManager.AnimationError err = am.PlayAnimation(animator, inputField.text);
output.text = GetStringFromError(err);
}
public void GetCurrentAnimationLengthClicked() {
float length = am.GetCurrentAnimationLength(animator);
output.text = "Length of the currently playing animation in seconds: " + length;
}
private string GetStringFromError(AnimationManager.AnimationError err) {
string warning = "";
switch (err) {
case AnimationManager.AnimationError.OK:
warning = "Succesfully executed playing animation.";
break;
case AnimationManager.AnimationError.ALREADY_PLAYING:
warning = "Method is already playing.";
break;
case AnimationManager.AnimationError.DOES_NOT_EXIST:
warning = "Given Animation Name does not exist on the given Animator.";
break;
default:
// Invalid AnimationManager.AnimationError argument.
break;
}
return warning;
}
}
| 30 | 90 | 0.636667 | [
"MIT"
] | MathewHDYT/Unity-Animation-Manager | Example Project/Assets/Scripts/MethodCalls.cs | 1,500 | C# |
using UnityEngine;
using KBEngine;
using System;
using System.Collections;
namespace KBEngine
{
/*
KBEngine的数学相关模块
*/
public class KBEMath
{
public static float int82angle(SByte angle, bool half)
{
float halfv = 128f;
if(half == true)
halfv = 254f;
halfv = ((float)angle) * ((float)System.Math.PI / halfv);
return halfv;
}
public static bool almostEqual(float f1, float f2, float epsilon)
{
return Math.Abs( f1 - f2 ) < epsilon;
}
}
}
| 14.59375 | 66 | 0.674518 | [
"MIT"
] | 15951836388/m2client-u3d | Assets/Scripts/kbengine_unity3d_plugins-0.9.6/Math.cs | 483 | C# |
namespace Auction.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
using System.Linq;
using Data;
using Models;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity;
public sealed class Configuration : DbMigrationsConfiguration<Auction.Data.AuctionContext>
{
private const string DefaultAdminEmail = "admin@admin.com";
private const string DefaultAdminFullName = "Admin";
private const string DefaultAdminPhoneNumber = "07001700";
private const string DefaultAdminPassword = "123456";
private const string AdministratorRoleName = "Administrator";
private const string UserRoleName = "User";
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(AuctionContext context)
{
CreateRoles(context);
if (!context.Users.Any())
{
CreateRoles(context);
var adminEmail = DefaultAdminEmail;
var adminUsername = adminEmail;
var adminFullName = DefaultAdminFullName;
var adminPhoneNumber = DefaultAdminPhoneNumber;
var adminPassword = DefaultAdminPassword;
var adminRole = AdministratorRoleName;
CreateAdminUser(context, adminEmail, adminUsername, adminFullName, adminPhoneNumber, adminPassword, adminRole);
}
if (!context.Categories.Any())
{
AddCategories(context);
}
}
private void CreateRoles(AuctionContext context)
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
roleManager.Create(new IdentityRole(AdministratorRoleName));
roleManager.Create(new IdentityRole(UserRoleName));
context.SaveChanges();
}
private void CreateAdminUser(AuctionContext context, string adminEmail, string adminUsername, string adminFullName, string adminPhoneNumber, string adminPassword, string adminRole)
{
var adminUser = new User
{
UserName = adminUsername,
Email = adminEmail,
FullName = adminFullName,
PhoneNumber = adminPhoneNumber
};
var userStore = new UserStore<User>(context);
var userManager = new UserManager<User>(userStore);
userManager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = false,
RequireDigit = false,
RequireLowercase = false,
RequireUppercase = false
};
var userCreateResult = userManager.Create(adminUser, adminPassword);
if (!userCreateResult.Succeeded)
{
throw new Exception(string.Join("; ", userCreateResult.Errors));
}
var addAdminRoleResult = userManager.AddToRole(adminUser.Id, adminRole);
if (!addAdminRoleResult.Succeeded)
{
throw new Exception(string.Join("; ", addAdminRoleResult.Errors));
}
context.SaveChanges();
}
private void AddCategories(AuctionContext context)
{
context.Categories.Add(new Category { Name = "Home" });
context.Categories.Add(new Category { Name = "Office" });
context.Categories.Add(new Category { Name = "Clothes" });
context.Categories.Add(new Category { Name = "Technology" });
context.SaveChanges();
}
}
}
| 35.663551 | 188 | 0.600629 | [
"MIT"
] | JozefinaNikolova/AuctionWebsite | Auction/Auction.Data/Migrations/Configuration.cs | 3,816 | C# |
//
// Copyright 2013 Carbonfrost Systems, Inc. (http://carbonfrost.com)
//
// 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.Reflection;
namespace Carbonfrost.Commons.Core.Runtime {
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class ProviderRegistrationAttribute : Attribute {
private readonly IProviderRegistration registration;
internal static readonly ProviderRegistrationAttribute Default
= new ProviderRegistrationAttribute(ProviderRegistrationType.Default);
internal IProviderRegistration Registration {
get {
return this.registration;
}
}
public Type Type {
get {
switch (KnownType) {
case ProviderRegistrationType.Custom:
return registration.GetType();
case ProviderRegistrationType.Default:
case ProviderRegistrationType.Explicit:
default:
return null;
}
}
}
public ProviderRegistrationType KnownType {
get {
if (registration == ProviderRegistration.Default)
return ProviderRegistrationType.Default;
if (registration == ProviderRegistration.Explicit)
return ProviderRegistrationType.Explicit;
else
return ProviderRegistrationType.Custom;
}
}
public ProviderRegistrationAttribute(Type type) {
if (type == null)
throw new ArgumentNullException("type");
if (!typeof(IProviderRegistration).GetTypeInfo().IsAssignableFrom(type))
throw Failure.NotAssignableFrom("type", typeof(IProviderRegistration), type);
this.registration = (IProviderRegistration) Activator.CreateInstance(type);
}
public ProviderRegistrationAttribute(ProviderRegistrationType knownType) {
if (knownType == ProviderRegistrationType.Custom)
throw RuntimeFailure.UseProviderRegistrationAttributeOverload("knownType", knownType);
this.registration = ProviderRegistration.FromKind(knownType);
}
}
}
| 34.634146 | 102 | 0.639085 | [
"Apache-2.0"
] | Carbonfrost/f-core | dotnet/src/Carbonfrost.Commons.Core/Runtime/ProviderRegistrationAttribute.cs | 2,840 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Traders Dynamic Index")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Traders Dynamic Index")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("35f19c43-c7cc-4f53-b8e0-61caaf9cd8e8")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | 30 | 56 | 0.760417 | [
"MIT"
] | Mikai47/cAlgoBot | Sources/Indicators/Traders Dynamic Index/Traders Dynamic Index/Properties/AssemblyInfo.cs | 482 | C# |
namespace EnvironmentAssessment.Common.VimApi
{
public class UnsupportedVmxLocation : VmConfigFault
{
}
}
| 15.571429 | 52 | 0.807339 | [
"MIT"
] | octansIt/environmentassessment | EnvironmentAssessment.Wizard/Common/VimApi/U/UnsupportedVmxLocation.cs | 109 | C# |
// The MIT License (MIT)
//
// Copyright (c) 2014-2017, Institute for Software & Systems Engineering
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace Tests.Analysis.Invariants.Violated
{
using SafetySharp.Modeling;
using Shouldly;
internal class ArrayComponents : AnalysisTestObject
{
protected override void Check()
{
var c1 = new C();
var c2 = new C();
var d = new D { C = new[] { c1, c2 } };
CheckInvariant(c1.F != 3, d).ShouldBe(false);
CheckInvariant(c2.F != 3, d).ShouldBe(false);
}
private class C : Component
{
public int F;
}
private class D : Component
{
public C[] C;
public override void Update()
{
Choose(C[0], C[1]).F = 3;
}
}
}
} | 31.781818 | 80 | 0.711098 | [
"MIT"
] | isse-augsburg/ssharp | SafetySharpTests/Analysis/Invariants/Violated/array components.cs | 1,750 | C# |
using System;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
namespace DataAPI.Client
{
internal class DataApiHttpClientProxy : IHttpClientProxy
{
private bool IgnoreSslNameMismatch { get; }
private HttpClientHandler httpClientHandler;
public HttpClient Client { get; private set; }
public bool UseActiveDirectoryAuthorization
{
get => httpClientHandler.UseDefaultCredentials;
set
{
if(value == httpClientHandler.UseDefaultCredentials)
return;
Client.Dispose();
httpClientHandler.Dispose();
InitializeNewHttpClientHandler(value);
CreateNewClient();
}
}
public DataApiHttpClientProxy(bool useActiveDirectory, bool ignoreSslNameMismatch = false)
{
if(ignoreSslNameMismatch)
Console.WriteLine("WARNING: SSL name mismatch is ignored. This is a security hazard!!!");
IgnoreSslNameMismatch = ignoreSslNameMismatch;
InitializeNewHttpClientHandler(useActiveDirectory);
CreateNewClient();
}
private void InitializeNewHttpClientHandler(bool useActiveDirectory)
{
httpClientHandler = new HttpClientHandler
{
UseDefaultCredentials = useActiveDirectory,
ServerCertificateCustomValidationCallback = ValidateCertificate
};
}
private void CreateNewClient()
{
Client = new HttpClient(httpClientHandler);
}
private bool ValidateCertificate(HttpRequestMessage requestMessage, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors errors)
{
if(IgnoreSslNameMismatch && errors == SslPolicyErrors.RemoteCertificateNameMismatch)
return true;
return errors == SslPolicyErrors.None;
}
public void Dispose()
{
httpClientHandler.Dispose();
Client.Dispose();
}
}
}
| 33.044776 | 147 | 0.602529 | [
"MIT"
] | mindleaving/dataapi | DataAPI.Client/DataApiHttpClientProxy.cs | 2,216 | C# |
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.TextMate
{
[TestFixture]
internal class TextEditorModelTests
{
[Test]
public void Lines_Should_Have_Valid_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
}
[Test]
public void Lines_Should_Have_Valid_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Length()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", textEditorModel.GetLineText(2));
Assert.AreEqual("birdie", textEditorModel.GetLineText(3));
}
[Test]
public void Removing_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Document_Lines_Count_Should_Match_Model_Lines_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Insert_Document_Line_Should_Insert_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Remove_Document_Line_Should_Remove_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Replace_Text_Of_Same_Length_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "P");
Assert.AreEqual("Puppy", textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
[Test]
public void Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
[Test]
public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.BeginUpdate();
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNotNull(textEditorModel.InvalidRange,
"InvalidRange should not be null");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
}
}
| 33.865385 | 84 | 0.592683 | [
"MIT"
] | AvaloniaEdit/AvaloniaEdit | test/AvaloniaEdit.Tests/TextMate/TextEditorModelTests.cs | 12,329 | C# |
// Generated class v2.13.0.0, don't modify
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
namespace NHtmlUnit.Javascript.Host.Svg
{
public partial class SVGFEOffsetElement : NHtmlUnit.Javascript.Host.Svg.SVGElement
{
static SVGFEOffsetElement()
{
ObjectWrapper.RegisterWrapperCreator((com.gargoylesoftware.htmlunit.javascript.host.svg.SVGFEOffsetElement o) =>
new SVGFEOffsetElement(o));
}
public SVGFEOffsetElement(com.gargoylesoftware.htmlunit.javascript.host.svg.SVGFEOffsetElement wrappedObject) : base(wrappedObject) {}
public new com.gargoylesoftware.htmlunit.javascript.host.svg.SVGFEOffsetElement WObj
{
get { return (com.gargoylesoftware.htmlunit.javascript.host.svg.SVGFEOffsetElement)WrappedObject; }
}
public SVGFEOffsetElement()
: this(new com.gargoylesoftware.htmlunit.javascript.host.svg.SVGFEOffsetElement()) {}
}
}
| 31.666667 | 141 | 0.719617 | [
"Apache-2.0"
] | timorzadir/NHtmlUnit | app/NHtmlUnit/Generated/Javascript/Host/Svg/SVGFEOffsetElement.cs | 1,045 | C# |
using System;
using System.Runtime.InteropServices;
namespace Ultraviolet.SDL2.Native
{
#pragma warning disable 1591
[StructLayout(LayoutKind.Sequential)]
public struct SDL_KeyboardEvent
{
public UInt32 type;
public UInt32 timestamp;
public UInt32 windowID;
public Byte state;
public Byte repeat;
public Byte padding2;
public Byte padding3;
public SDL_Keysym keysym;
}
#pragma warning restore 1591
} | 24.05 | 41 | 0.683992 | [
"Apache-2.0",
"MIT"
] | MicroWorldwide/ultraviolet | Source/Ultraviolet.SDL2/Shared/Native/SDL_KeyboardEvent.cs | 483 | C# |
using Microsoft.VisualStudio.Services.Licensing;
using TfsCmdlets.Cmdlets.Identity;
using Microsoft.VisualStudio.Services.Licensing.Client;
namespace TfsCmdlets.Controllers.Identity.User
{
[CmdletController(typeof(AccountEntitlement))]
partial class GetUserController
{
protected override IEnumerable Run()
{
var client = GetClient<AccountLicensingHttpClient>();
if (Current)
{
var user = Data.GetItem<Models.Identity>(new { Identity = User });
yield return user;
yield break;
}
foreach (var input in User)
{
var user = input switch
{
string s when s.IsGuid() => new Guid(s),
_ => input
};
switch (user)
{
case AccountEntitlement entitlement:
{
yield return entitlement;
break;
}
case WebApiIdentity i:
{
yield return client.GetAccountEntitlementAsync(i.Id).GetResult("Error getting account entitlement");
break;
}
case WebApiIdentityRef ir:
{
yield return client.GetAccountEntitlementAsync(ir.Id).GetResult("Error getting account entitlement");
break;
}
case Guid g:
{
yield return client.GetAccountEntitlementAsync(g).GetResult("Error getting account entitlement");
break;
}
case string s:
{
foreach (var u in client.GetAccountEntitlementsAsync()
.GetResult("Error getting account entitlements")
.Where(u => u.User.DisplayName.IsLike(s) || u.User.UniqueName.IsLike(s)))
{
yield return u;
}
break;
}
default:
{
Logger.LogError(new ArgumentException($"Invalid or non-existent user {user}"));
break;
}
}
}
}
}
} | 36.887324 | 129 | 0.415808 | [
"MIT"
] | igoravl/tfscmdlets | CSharp/TfsCmdlets/Controllers/Identity/User/GetUserController.cs | 2,619 | C# |
using System;
using System.Threading;
using EasyNetQ.AmqpExceptions;
using EasyNetQ.Events;
using EasyNetQ.Logging;
using EasyNetQ.Sprache;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RabbitMQ.Client.Exceptions;
namespace EasyNetQ.Producer
{
public class PersistentChannel : IPersistentChannel
{
private const int MinRetryTimeoutMs = 50;
private const int MaxRetryTimeoutMs = 5000;
private readonly ConnectionConfiguration configuration;
private readonly IPersistentConnection connection;
private readonly IEventBus eventBus;
private readonly ILog logger = LogProvider.For<PersistentChannel>();
private IModel internalChannel;
public PersistentChannel(
IPersistentConnection connection,
ConnectionConfiguration configuration,
IEventBus eventBus
)
{
Preconditions.CheckNotNull(connection, "connection");
Preconditions.CheckNotNull(configuration, "configuration");
Preconditions.CheckNotNull(eventBus, "eventBus");
this.connection = connection;
this.configuration = configuration;
this.eventBus = eventBus;
WireUpEvents();
}
public void InvokeChannelAction(Action<IModel> channelAction)
{
Preconditions.CheckNotNull(channelAction, "channelAction");
var timeout = configuration.Timeout.Equals(0)
? TimeBudget.Infinite()
: TimeBudget.Start(TimeSpan.FromSeconds(configuration.Timeout));
var retryTimeoutMs = MinRetryTimeoutMs;
while (!timeout.IsExpired())
{
try
{
var channel = OpenChannel();
channelAction(channel);
return;
}
catch (OperationInterruptedException exception)
{
CloseChannel();
if (NeedRethrow(exception))
{
throw;
}
}
catch (EasyNetQException)
{
CloseChannel();
}
Thread.Sleep(retryTimeoutMs);
retryTimeoutMs = Math.Min(retryTimeoutMs * 2, MaxRetryTimeoutMs);
}
logger.Error("Channel action timed out");
throw new TimeoutException("The operation requested on PersistentChannel timed out");
}
public void Dispose()
{
CloseChannel();
}
private void WireUpEvents()
{
eventBus.Subscribe<ConnectionDisconnectedEvent>(OnConnectionDisconnected);
eventBus.Subscribe<ConnectionCreatedEvent>(ConnectionOnConnected);
}
private void OnConnectionDisconnected(ConnectionDisconnectedEvent @event)
{
CloseChannel();
}
private void ConnectionOnConnected(ConnectionCreatedEvent @event)
{
try
{
OpenChannel();
}
catch (OperationInterruptedException)
{
}
catch (EasyNetQException)
{
}
}
private IModel OpenChannel()
{
IModel channel;
lock (this)
{
if (internalChannel != null)
{
return internalChannel;
}
channel = connection.CreateModel();
WireUpChannelEvents(channel);
eventBus.Publish(new PublishChannelCreatedEvent(channel));
internalChannel = channel;
}
logger.Debug("Persistent channel connected");
return channel;
}
private void WireUpChannelEvents(IModel channel)
{
if (configuration.PublisherConfirms)
{
channel.ConfirmSelect();
channel.BasicAcks += OnAck;
channel.BasicNacks += OnNack;
}
channel.BasicReturn += OnReturn;
}
private void OnReturn(object sender, BasicReturnEventArgs args)
{
eventBus.Publish(new ReturnedMessageEvent(args.Body.ToArray(),
new MessageProperties(args.BasicProperties),
new MessageReturnedInfo(args.Exchange, args.RoutingKey, args.ReplyText)));
}
private void OnAck(object sender, BasicAckEventArgs args)
{
eventBus.Publish(MessageConfirmationEvent.Ack((IModel) sender, args.DeliveryTag, args.Multiple));
}
private void OnNack(object sender, BasicNackEventArgs args)
{
eventBus.Publish(MessageConfirmationEvent.Nack((IModel) sender, args.DeliveryTag, args.Multiple));
}
private void CloseChannel()
{
lock (this)
{
if (internalChannel == null)
{
return;
}
if (configuration.PublisherConfirms)
{
internalChannel.BasicAcks -= OnAck;
internalChannel.BasicNacks -= OnNack;
}
internalChannel.BasicReturn -= OnReturn;
internalChannel = null;
}
logger.Debug("Persistent channel disconnected");
}
private static bool NeedRethrow(OperationInterruptedException exception)
{
try
{
var amqpException = AmqpExceptionGrammar.ParseExceptionString(exception.Message);
return amqpException.Code != AmqpException.ConnectionClosed;
}
catch (ParseException)
{
return true;
}
}
}
}
| 29.645 | 110 | 0.547141 | [
"MIT"
] | Pliner/EasyNetQ | Source/EasyNetQ/Producer/PersistentChannel.cs | 5,931 | C# |
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.4
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
namespace libsbml {
using System;
using System.Runtime.InteropServices;
/**
* @sbmlpackage{core}
*
@htmlinclude pkg-marker-core.html Representation of MIRIAM-compliant model history data.
*
* @htmlinclude not-sbml-warning.html
*
* The SBML specification beginning with Level 2 Version 2 defines
* a standard approach to recording optional model history and model creator
* information in a form that complies with MIRIAM (<a target='_blank'
* href='http://www.nature.com/nbt/journal/v23/n12/abs/nbt1156.html'>'Minimum
* Information Requested in the Annotation of biochemical Models'</a>,
* <i>Nature Biotechnology</i>, vol. 23, no. 12, Dec. 2005). LibSBML
* provides the ModelHistory class as a convenient high-level interface for
* working with model history data.
*
* Model histories in SBML consist of one or more <em>model creators</em>,
* a single date of @em creation, and one or more @em modification dates.
* The overall XML form of this data takes the following form:
*
<pre class='fragment'>
<dc:creator>
<rdf:Bag>
<rdf:li rdf:parseType='Resource'>
<span style='background-color: #d0eed0'>+++</span>
<vCard:N rdf:parseType='Resource'>
<vCard:Family><span style='background-color: #bbb'>family name</span></vCard:Family>
<vCard:Given><span style='background-color: #bbb'>given name</span></vCard:Given>
</vCard:N>
<span style='background-color: #d0eed0'>+++</span>
<span style='border-bottom: 2px dotted #888'><vCard:EMAIL><span style='background-color: #bbb'>email address</span></vCard:EMAIL></span>
<span style='background-color: #d0eed0'>+++</span>
<span style='border-bottom: 2px dotted #888'><vCard:ORG rdf:parseType='Resource'></span>
<span style='border-bottom: 2px dotted #888'><vCard:Orgname><span style='background-color: #bbb'>organization name</span></vCard:Orgname></span>
<span style='border-bottom: 2px dotted #888'></vCard:ORG></span>
<span style='background-color: #d0eed0'>+++</span>
</rdf:li>
<span style='background-color: #edd'>...</span>
</rdf:Bag>
</dc:creator>
<dcterms:created rdf:parseType='Resource'>
<dcterms:W3CDTF><span style='background-color: #bbb'>creation date</span></dcterms:W3CDTF>
</dcterms:created>
<dcterms:modified rdf:parseType='Resource'>
<dcterms:W3CDTF><span style='background-color: #bbb'>modification date</span></dcterms:W3CDTF>
</dcterms:modified>
<span style='background-color: #edd'>...</span>
</pre>
*
* In the template above, the <span style='border-bottom: 2px dotted #888'>underlined</span>
* portions are optional, the symbol
* <span class='code' style='background-color: #d0eed0'>+++</span> is a placeholder
* for either no content or valid XML content that is not defined by
* the annotation scheme, and the ellipses
* <span class='code' style='background-color: #edd'>...</span>
* are placeholders for zero or more elements of the same form as the
* immediately preceding element. The various placeholders for content, namely
* <span class='code' style='background-color: #bbb'>family name</span>,
* <span class='code' style='background-color: #bbb'>given name</span>,
* <span class='code' style='background-color: #bbb'>email address</span>,
* <span class='code' style='background-color: #bbb'>organization</span>,
* <span class='code' style='background-color: #bbb'>creation date</span>, and
* <span class='code' style='background-color: #bbb'>modification date</span>
* are data that can be filled in using the various methods on
* the ModelHistory class described below.
*
* @see ModelCreator
* @see Date
*/
public class ModelHistory : IDisposable {
private HandleRef swigCPtr;
protected bool swigCMemOwn;
internal ModelHistory(IntPtr cPtr, bool cMemoryOwn)
{
swigCMemOwn = cMemoryOwn;
swigCPtr = new HandleRef(this, cPtr);
}
internal static HandleRef getCPtr(ModelHistory obj)
{
return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
}
internal static HandleRef getCPtrAndDisown (ModelHistory obj)
{
HandleRef ptr = new HandleRef(null, IntPtr.Zero);
if (obj != null)
{
ptr = obj.swigCPtr;
obj.swigCMemOwn = false;
}
return ptr;
}
~ModelHistory() {
Dispose();
}
public virtual void Dispose() {
lock(this) {
if (swigCPtr.Handle != IntPtr.Zero) {
if (swigCMemOwn) {
swigCMemOwn = false;
libsbmlPINVOKE.delete_ModelHistory(swigCPtr);
}
swigCPtr = new HandleRef(null, IntPtr.Zero);
}
GC.SuppressFinalize(this);
}
}
public static bool operator==(ModelHistory lhs, ModelHistory rhs)
{
if((Object)lhs == (Object)rhs)
{
return true;
}
if( ((Object)lhs == null) || ((Object)rhs == null) )
{
return false;
}
return (getCPtr(lhs).Handle.ToString() == getCPtr(rhs).Handle.ToString());
}
public static bool operator!=(ModelHistory lhs, ModelHistory rhs)
{
return !(lhs == rhs);
}
public override bool Equals(Object sb)
{
if ( ! (sb is ModelHistory) )
{
return false;
}
return this == (ModelHistory)sb;
}
public override int GetHashCode()
{
return swigCPtr.Handle.ToInt32();
}
/**
* Creates a new ModelHistory object.
*/ public
ModelHistory() : this(libsbmlPINVOKE.new_ModelHistory__SWIG_0(), true) {
}
/**
* Copy constructor; creates a copy of this ModelHistory object.
*
* @param orig the object to copy.
*
* @throws @if python ValueError @else SBMLConstructorException @endif
* Thrown if the argument @p orig is @c null.
*/ public
ModelHistory(ModelHistory orig) : this(libsbmlPINVOKE.new_ModelHistory__SWIG_1(ModelHistory.getCPtr(orig)), true) {
if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve();
}
/**
* Creates and returns a copy of this ModelHistory object
*
* @return a (deep) copy of this ModelHistory object.
*/ public
ModelHistory clone() {
IntPtr cPtr = libsbmlPINVOKE.ModelHistory_clone(swigCPtr);
ModelHistory ret = (cPtr == IntPtr.Zero) ? null : new ModelHistory(cPtr, true);
return ret;
}
/**
* Returns the 'creation date' portion of this ModelHistory object.
*
* @return a Date object representing the creation date stored in
* this ModelHistory object.
*/ public
Date getCreatedDate() {
IntPtr cPtr = libsbmlPINVOKE.ModelHistory_getCreatedDate(swigCPtr);
Date ret = (cPtr == IntPtr.Zero) ? null : new Date(cPtr, false);
return ret;
}
/**
* Returns the 'modified date' portion of this ModelHistory object.
*
* Note that in the MIRIAM format for annotations, there can be multiple
* modification dates. The libSBML ModelHistory class supports this by
* storing a list of 'modified date' values. If this ModelHistory object
* contains more than one 'modified date' value in the list, this method
* will return the first one in the list.
*
* @return a Date object representing the date of modification
* stored in this ModelHistory object.
*/ public
Date getModifiedDate() {
IntPtr cPtr = libsbmlPINVOKE.ModelHistory_getModifiedDate__SWIG_0(swigCPtr);
Date ret = (cPtr == IntPtr.Zero) ? null : new Date(cPtr, false);
return ret;
}
/**
* Predicate returning @c true or @c false depending on whether this
* ModelHistory's 'creation date' is set.
*
* @return @c true if the creation date value of this ModelHistory is
* set, @c false otherwise.
*/ public
bool isSetCreatedDate() {
bool ret = libsbmlPINVOKE.ModelHistory_isSetCreatedDate(swigCPtr);
return ret;
}
/**
* Predicate returning @c true or @c false depending on whether this
* ModelHistory's 'modified date' is set.
*
* @return @c true if the modification date value of this ModelHistory
* object is set, @c false otherwise.
*/ public
bool isSetModifiedDate() {
bool ret = libsbmlPINVOKE.ModelHistory_isSetModifiedDate(swigCPtr);
return ret;
}
/**
* Sets the creation date of this ModelHistory object.
*
* @param date a Date object representing the date to which the 'created
* date' portion of this ModelHistory should be set.
*
* @return integer value indicating success/failure of the
* function. @if clike The value is drawn from the
* enumeration #OperationReturnValues_t. @endif The possible values
* returned by this function are:
* @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink
* @li @link libsbmlcs.libsbml.LIBSBML_INVALID_OBJECT LIBSBML_INVALID_OBJECT @endlink
*/ public
int setCreatedDate(Date date) {
int ret = libsbmlPINVOKE.ModelHistory_setCreatedDate(swigCPtr, Date.getCPtr(date));
return ret;
}
/**
* Sets the modification date of this ModelHistory object.
*
* @param date a Date object representing the date to which the 'modified
* date' portion of this ModelHistory should be set.
*
* @return integer value indicating success/failure of the
* function. @if clike The value is drawn from the
* enumeration #OperationReturnValues_t. @endif The possible values
* returned by this function are:
* @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink
* @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_FAILED LIBSBML_OPERATION_FAILED @endlink
* @li @link libsbmlcs.libsbml.LIBSBML_INVALID_OBJECT LIBSBML_INVALID_OBJECT @endlink
*/ public
int setModifiedDate(Date date) {
int ret = libsbmlPINVOKE.ModelHistory_setModifiedDate(swigCPtr, Date.getCPtr(date));
return ret;
}
/**
* Adds a copy of a Date object to the list of 'modified date' values
* stored in this ModelHistory object.
*
* In the MIRIAM format for annotations, there can be multiple
* modification dates. The libSBML ModelHistory class supports this by
* storing a list of 'modified date' values.
*
* @param date a Date object representing the 'modified date' that should
* be added to this ModelHistory object.
*
* @return integer value indicating success/failure of the
* function. @if clike The value is drawn from the
* enumeration #OperationReturnValues_t. @endif The possible values
* returned by this function are:
* @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink
* @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_FAILED LIBSBML_OPERATION_FAILED @endlink
* @li @link libsbmlcs.libsbml.LIBSBML_INVALID_OBJECT LIBSBML_INVALID_OBJECT @endlink
*/ public
int addModifiedDate(Date date) {
int ret = libsbmlPINVOKE.ModelHistory_addModifiedDate(swigCPtr, Date.getCPtr(date));
return ret;
}
/**
* Returns the list of 'modified date' values (as Date objects) stored in
* this ModelHistory object.
*
* In the MIRIAM format for annotations, there can be multiple
* modification dates. The libSBML ModelHistory class supports this by
* storing a list of 'modified date' values.
*
* @return the list of modification dates for this ModelHistory object.
*/ public
DateList getListModifiedDates() {
IntPtr cPtr = libsbmlPINVOKE.ModelHistory_getListModifiedDates(swigCPtr);
return (cPtr == IntPtr.Zero) ? null : new DateList(cPtr, true);
}
/**
* Get the nth Date object in the list of 'modified date' values stored
* in this ModelHistory object.
*
* In the MIRIAM format for annotations, there can be multiple
* modification dates. The libSBML ModelHistory class supports this by
* storing a list of 'modified date' values.
*
* @return the nth Date in the list of ModifiedDates of this
* ModelHistory.
*/ public
Date getModifiedDate(long n) {
IntPtr cPtr = libsbmlPINVOKE.ModelHistory_getModifiedDate__SWIG_1(swigCPtr, n);
Date ret = (cPtr == IntPtr.Zero) ? null : new Date(cPtr, false);
return ret;
}
/**
* Get the number of Date objects in this ModelHistory object's list of
* 'modified dates'.
*
* In the MIRIAM format for annotations, there can be multiple
* modification dates. The libSBML ModelHistory class supports this by
* storing a list of 'modified date' values.
*
* @return the number of ModifiedDates in this ModelHistory.
*/ public
long getNumModifiedDates() { return (long)libsbmlPINVOKE.ModelHistory_getNumModifiedDates(swigCPtr); }
/**
* Adds a copy of a ModelCreator object to the list of 'model creator'
* values stored in this ModelHistory object.
*
* In the MIRIAM format for annotations, there can be multiple model
* creators. The libSBML ModelHistory class supports this by storing a
* list of 'model creator' values.
*
* @param mc the ModelCreator to add
*
* @return integer value indicating success/failure of the
* function. @if clike The value is drawn from the
* enumeration #OperationReturnValues_t. @endif The possible values
* returned by this function are:
* @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink
* @li @link libsbmlcs.libsbml.LIBSBML_INVALID_OBJECT LIBSBML_INVALID_OBJECT @endlink
* @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_FAILED LIBSBML_OPERATION_FAILED @endlink
*/ public
int addCreator(ModelCreator mc) {
int ret = libsbmlPINVOKE.ModelHistory_addCreator(swigCPtr, ModelCreator.getCPtr(mc));
return ret;
}
/**
* Returns the list of ModelCreator objects stored in this ModelHistory
* object.
*
* In the MIRIAM format for annotations, there can be multiple model
* creators. The libSBML ModelHistory class supports this by storing a
* list of 'model creator' values.
*
* @return the list of ModelCreator objects.
*/ public
ModelCreatorList getListCreators() {
IntPtr cPtr = libsbmlPINVOKE.ModelHistory_getListCreators(swigCPtr);
return (cPtr == IntPtr.Zero) ? null : new ModelCreatorList(cPtr, true);
}
/**
* Get the nth ModelCreator object stored in this ModelHistory object.
*
* In the MIRIAM format for annotations, there can be multiple model
* creators. The libSBML ModelHistory class supports this by storing a
* list of 'model creator' values.
*
* @return the nth ModelCreator object.
*/ public
ModelCreator getCreator(long n) {
IntPtr cPtr = libsbmlPINVOKE.ModelHistory_getCreator(swigCPtr, n);
ModelCreator ret = (cPtr == IntPtr.Zero) ? null : new ModelCreator(cPtr, false);
return ret;
}
/**
* Get the number of ModelCreator objects stored in this ModelHistory
* object.
*
* In the MIRIAM format for annotations, there can be multiple model
* creators. The libSBML ModelHistory class supports this by storing a
* list of 'model creator' values.
*
* @return the number of ModelCreators objects.
*/ public
long getNumCreators() { return (long)libsbmlPINVOKE.ModelHistory_getNumCreators(swigCPtr); }
/**
* Predicate returning @c true if all the required elements for this
* ModelHistory object have been set.
*
* The required elements for a ModelHistory object are 'created
* name', 'modified date', and at least one 'model creator'.
*
* @return a bool value indicating whether all the required
* elements for this object have been defined.
*/ public
bool hasRequiredAttributes() {
bool ret = libsbmlPINVOKE.ModelHistory_hasRequiredAttributes(swigCPtr);
return ret;
}
/** */ /* libsbml-internal */ public
bool hasBeenModified() {
bool ret = libsbmlPINVOKE.ModelHistory_hasBeenModified(swigCPtr);
return ret;
}
/** */ /* libsbml-internal */ public
void resetModifiedFlags() {
libsbmlPINVOKE.ModelHistory_resetModifiedFlags(swigCPtr);
}
}
}
| 35.145923 | 164 | 0.696361 | [
"Apache-2.0"
] | 0u812/roadrunner | third_party/libSBML-5.10.0-Source/src/bindings/csharp/csharp-files-win/ModelHistory.cs | 16,378 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2016-11-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Container for the parameters to the CreateNetworkInterfacePermission operation.
/// Grants an AWS-authorized account permission to attach the specified network interface
/// to an instance in their account.
///
///
/// <para>
/// You can grant permission to a single AWS account only, and only one account at a time.
/// </para>
/// </summary>
public partial class CreateNetworkInterfacePermissionRequest : AmazonEC2Request
{
private string _awsAccountId;
private string _awsService;
private string _networkInterfaceId;
private InterfacePermissionType _permission;
/// <summary>
/// Gets and sets the property AwsAccountId.
/// <para>
/// The AWS account ID.
/// </para>
/// </summary>
public string AwsAccountId
{
get { return this._awsAccountId; }
set { this._awsAccountId = value; }
}
// Check to see if AwsAccountId property is set
internal bool IsSetAwsAccountId()
{
return this._awsAccountId != null;
}
/// <summary>
/// Gets and sets the property AwsService.
/// <para>
/// The AWS service. Currently not supported.
/// </para>
/// </summary>
public string AwsService
{
get { return this._awsService; }
set { this._awsService = value; }
}
// Check to see if AwsService property is set
internal bool IsSetAwsService()
{
return this._awsService != null;
}
/// <summary>
/// Gets and sets the property NetworkInterfaceId.
/// <para>
/// The ID of the network interface.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string NetworkInterfaceId
{
get { return this._networkInterfaceId; }
set { this._networkInterfaceId = value; }
}
// Check to see if NetworkInterfaceId property is set
internal bool IsSetNetworkInterfaceId()
{
return this._networkInterfaceId != null;
}
/// <summary>
/// Gets and sets the property Permission.
/// <para>
/// The type of permission to grant.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public InterfacePermissionType Permission
{
get { return this._permission; }
set { this._permission = value; }
}
// Check to see if Permission property is set
internal bool IsSetPermission()
{
return this._permission != null;
}
}
} | 30.00813 | 101 | 0.599837 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/EC2/Generated/Model/CreateNetworkInterfacePermissionRequest.cs | 3,691 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using Service.ClientProfile.Postgres;
namespace Service.ClientProfile.Postgres.Migrations
{
[DbContext(typeof(DatabaseContext))]
[Migration("20211102112423_version_5")]
partial class version_5
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasDefaultSchema("clientprofiles")
.HasAnnotation("Relational:MaxIdentifierLength", 63)
.HasAnnotation("ProductVersion", "5.0.11")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
modelBuilder.Entity("Service.ClientProfile.Domain.Models.Blocker", b =>
{
b.Property<int>("BlockerId")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<int>("BlockedOperationType")
.HasColumnType("integer");
b.Property<string>("ClientProfileClientId")
.HasColumnType("character varying(128)");
b.Property<DateTime>("ExpiryTime")
.HasColumnType("timestamp without time zone");
b.Property<string>("Reason")
.HasColumnType("text");
b.HasKey("BlockerId");
b.HasIndex("ClientProfileClientId");
b.ToTable("blockers");
});
modelBuilder.Entity("Service.ClientProfile.Domain.Models.ClientProfile", b =>
{
b.Property<string>("ClientId")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<bool>("KYCPassed")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(false);
b.Property<DateTime>("LastChangeTimestamp")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("timestamp without time zone");
b.Property<bool>("PhoneConfirmed")
.HasColumnType("boolean");
b.Property<string>("ReferralCode")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("ReferrerClientId")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<int>("Status2FA")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValue(0);
b.HasKey("ClientId");
b.HasIndex("ClientId");
b.HasIndex("ReferralCode");
b.HasIndex("ReferrerClientId");
b.ToTable("profiles");
});
modelBuilder.Entity("Service.ClientProfile.Domain.Models.Blocker", b =>
{
b.HasOne("Service.ClientProfile.Domain.Models.ClientProfile", null)
.WithMany("Blockers")
.HasForeignKey("ClientProfileClientId");
});
modelBuilder.Entity("Service.ClientProfile.Domain.Models.ClientProfile", b =>
{
b.Navigation("Blockers");
});
#pragma warning restore 612, 618
}
}
}
| 37.45045 | 128 | 0.532115 | [
"MIT"
] | MyJetWallet/Service.ClientProfile | Service.ClientProfile.Postgres/Migrations/20211102112423_version_5.Designer.cs | 4,159 | C# |
using Greg.Xrm.Logging;
namespace Greg.Xrm.EnvironmentSolutionsComparer.Views.Solutions.ComponentResolution
{
public class ResolverForRibbonCustomizations : ResolverCommon
{
public ResolverForRibbonCustomizations(ILog log)
: base(log)
{
this.LabelExtractor = entity =>
{
var label = entity.GetAttributeValue<string>("entity");
if (string.IsNullOrWhiteSpace(label))
{
label = "Application ribbon";
}
return label;
};
}
public override SolutionComponentType ComponentType => SolutionComponentType.RibbonCustomization;
public override string ComponentName => "ribboncustomization";
public override string ComponentLabelField => "entity";
}
}
| 24.821429 | 99 | 0.746763 | [
"MIT"
] | neronotte/Greg.Xrm | src/Greg.Xrm.EnvironmentSolutionsComparer/Views/Solutions/ComponentResolution/ResolverForRibbonCustomizations.cs | 697 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the kinesisanalytics-2015-08-14.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.KinesisAnalytics.Model
{
/// <summary>
/// For an application output, describes the AWS Lambda function configured as its destination.
/// </summary>
public partial class LambdaOutputDescription
{
private string _resourceARN;
private string _roleARN;
/// <summary>
/// Gets and sets the property ResourceARN.
/// <para>
/// Amazon Resource Name (ARN) of the destination Lambda function.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=2048)]
public string ResourceARN
{
get { return this._resourceARN; }
set { this._resourceARN = value; }
}
// Check to see if ResourceARN property is set
internal bool IsSetResourceARN()
{
return this._resourceARN != null;
}
/// <summary>
/// Gets and sets the property RoleARN.
/// <para>
/// ARN of the IAM role that Amazon Kinesis Analytics can assume to write to the destination
/// function.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=2048)]
public string RoleARN
{
get { return this._roleARN; }
set { this._roleARN = value; }
}
// Check to see if RoleARN property is set
internal bool IsSetRoleARN()
{
return this._roleARN != null;
}
}
} | 29.974359 | 114 | 0.622327 | [
"Apache-2.0"
] | FoxBearBear/aws-sdk-net | sdk/src/Services/KinesisAnalytics/Generated/Model/LambdaOutputDescription.cs | 2,338 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
// TODO: Remove IfDef
#if NETSTANDARD
using Microsoft.Azure.Commands.Common.Authentication.Abstractions.Core;
using Microsoft.Azure.Commands.Profile.Models.Core;
#endif
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure.Commands.Profile.Models;
using Microsoft.Azure.Commands.ScenarioTest;
using Microsoft.Azure.ServiceManagement.Common.Models;
using Microsoft.WindowsAzure.Commands.Common;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using System;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Azure.Commands.Profile.Test
{
public class CommonDataCmdletTests
{
public CommonDataCmdletTests(ITestOutputHelper output)
{
TestExecutionHelpers.SetUpSessionAndProfile();
XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
#if !NETSTANDARD
ServiceManagementProfileProvider.InitializeServiceManagementProfile();
#endif
}
public static AzureRmProfile CreateAzureRMProfile(string storageAccount)
{
var tenantId = Guid.NewGuid();
var subscriptionId = Guid.NewGuid();
var context = new PSAzureContext()
{
Account = new PSAzureRmAccount
{
Id = "user@contoso.com",
Type = "User"
},
Environment = (PSAzureEnvironment)AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud],
Subscription =
new PSAzureSubscription
{
CurrentStorageAccount = storageAccount,
Id = subscriptionId.ToString(),
Name = "Test Subscription 1",
TenantId = tenantId.ToString()
},
Tenant = new PSAzureTenant
{
Id = tenantId.ToString()
}
};
return new AzureRmProfile() { DefaultContext = context };
}
public static IAzureContextContainer CreateAzureSMProfile(string storageAccount)
{
#if !NETSTANDARD
var profile = new AzureSMProfile();
var client = new ProfileClient(profile);
var tenantId = Guid.NewGuid();
var subscriptionId = Guid.NewGuid();
var account = new AzureAccount
{
Id = "user@contoso.com",
Type = AzureAccount.AccountType.User
};
account.SetProperty(AzureAccount.Property.Tenants, tenantId.ToString());
account.SetProperty(AzureAccount.Property.Subscriptions, subscriptionId.ToString());
var subscription = new AzureSubscription()
{
Id = subscriptionId.ToString(),
Name = "Test Subscription 1",
};
subscription.SetEnvironment(EnvironmentName.AzureCloud);
subscription.SetAccount(account.Id);
subscription.SetTenant(tenantId.ToString());
subscription.SetStorageAccount(storageAccount);
client.AddOrSetAccount(account);
client.AddOrSetSubscription(subscription);
client.SetSubscriptionAsDefault(subscriptionId, account.Id);
return profile;
#else
return null;
#endif
}
private static void RunDataProfileTest(IAzureContextContainer rmProfile, IAzureContextContainer smProfile, Action testAction)
{
AzureSession.Instance.DataStore = new MemoryDataStore();
var savedRmProfile = AzureRmProfileProvider.Instance.Profile;
#if !NETSTANDARD
var savedSmProfile = AzureSMProfileProvider.Instance.Profile;
#endif
try
{
AzureRmProfileProvider.Instance.Profile = rmProfile;
#if !NETSTANDARD
AzureSMProfileProvider.Instance.Profile = smProfile;
#endif
testAction();
}
finally
{
AzureRmProfileProvider.Instance.Profile = savedRmProfile;
#if !NETSTANDARD
AzureSMProfileProvider.Instance.Profile = savedSmProfile;
#endif
}
}
#if !NETSTANDARD
[Theory,
InlineData(null, null),
InlineData("", null),
InlineData("AccountName=myAccount", "AccountName=myAccount")]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void CanClearStorageAccountForSMProfile(string connectionString, string expected)
{
RunDataProfileTest(
CreateAzureRMProfile(null),
CreateAzureSMProfile(connectionString),
() =>
{
Assert.Equal(expected, AzureSMProfileProvider.Instance.Profile.DefaultContext.GetCurrentStorageAccountName());
GeneralUtilities.ClearCurrentStorageAccount(true);
Assert.True(string.IsNullOrEmpty(AzureSMProfileProvider.Instance.Profile.DefaultContext.GetCurrentStorageAccountName()));
});
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void CanClearStorageAccountForEmptyProfile()
{
var rmProfile = new AzureRmProfile();
rmProfile.DefaultContext = new AzureContext(null, null, null, null);
RunDataProfileTest(
rmProfile,
new AzureSMProfile(),
() =>
{
GeneralUtilities.ClearCurrentStorageAccount(true);
Assert.True(string.IsNullOrEmpty(AzureSMProfileProvider.Instance.Profile.DefaultContext.GetCurrentStorageAccountName()));
});
}
#endif
[Theory,
InlineData(null, null),
InlineData("", null),
InlineData("AccountName=myAccount", "AccountName=myAccount")]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void CanClearStorageAccountForRMProfile(string connectionString, string expected)
{
RunDataProfileTest(
CreateAzureRMProfile(connectionString),
CreateAzureSMProfile(null),
() =>
{
Assert.Equal(expected, AzureRmProfileProvider.Instance.Profile.DefaultContext.GetCurrentStorageAccountName());
GeneralUtilities.ClearCurrentStorageAccount();
Assert.True(string.IsNullOrEmpty(AzureRmProfileProvider.Instance.Profile.DefaultContext.GetCurrentStorageAccountName()));
});
}
}
}
| 41.55914 | 143 | 0.603881 | [
"MIT"
] | Acidburn0zzz/azure-powershell | src/ResourceManager/Profile/Commands.Profile.Test/CommonDataCmdletTests.cs | 7,547 | 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.
// Modifications copyright (c) 2021 Sharafeev Ravil
using System;
using Telegram.Bot.Host.Middleware;
namespace Telegram.Bot.Host.ApplicationBuilder
{
public interface IApplicationBuilder
{
IServiceProvider ApplicationServices { get; set; }
IApplicationBuilder Use(Func<BotUpdateDelegate, BotUpdateDelegate> middleware);
IApplicationBuilder New();
BotUpdateDelegate Build();
}
} | 31.210526 | 111 | 0.743676 | [
"Apache-2.0"
] | SharafeevRavil/Telegram.Bot.Host | Telegram.Bot.Host/ApplicationBuilder/IApplicationBuilder.cs | 593 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.Pkcs.Tests
{
public static class TimestampTokenTests
{
[Theory]
[InlineData(nameof(TimestampTokenTestData.FreeTsaDotOrg1))]
[InlineData(nameof(TimestampTokenTestData.Symantec1))]
[InlineData(nameof(TimestampTokenTestData.DigiCert1))]
public static void ParseDocument(string testDataName)
{
TimestampTokenTestData testData = TimestampTokenTestData.GetTestData(testDataName);
TestParseDocument(testData.FullTokenBytes, testData, testData.FullTokenBytes.Length);
}
[Theory]
[InlineData(nameof(TimestampTokenTestData.FreeTsaDotOrg1))]
[InlineData(nameof(TimestampTokenTestData.Symantec1))]
[InlineData(nameof(TimestampTokenTestData.DigiCert1))]
public static void ParseDocument_ExcessData(string testDataName)
{
TimestampTokenTestData testData = TimestampTokenTestData.GetTestData(testDataName);
int baseLen = testData.FullTokenBytes.Length;
byte[] tooMuchData = new byte[baseLen + 30];
testData.FullTokenBytes.CopyTo(tooMuchData);
// Look like an octet string of the remainder of the payload. Should be ignored.
tooMuchData[baseLen] = 0x04;
tooMuchData[baseLen + 1] = 28;
TestParseDocument(tooMuchData, testData, baseLen);
}
private static void TestParseDocument(
ReadOnlyMemory<byte> tokenBytes,
TimestampTokenTestData testData,
int? expectedBytesRead)
{
int bytesRead;
Rfc3161TimestampToken token;
Assert.True(
Rfc3161TimestampToken.TryDecode(tokenBytes, out token, out bytesRead),
"Rfc3161TimestampToken.TryDecode");
if (expectedBytesRead != null)
{
Assert.Equal(expectedBytesRead.Value, bytesRead);
}
Assert.NotNull(token);
TimestampTokenInfoTests.AssertEqual(testData, token.TokenInfo);
SignedCms signedCms = token.AsSignedCms();
Assert.NotNull(signedCms);
Assert.Equal(Oids.TstInfo, signedCms.ContentInfo.ContentType.Value);
Assert.Equal(
testData.TokenInfoBytes.ByteArrayToHex(),
signedCms.ContentInfo.Content.ByteArrayToHex());
if (testData.EmbeddedSigningCertificate != null)
{
Assert.NotNull(signedCms.SignerInfos[0].Certificate);
Assert.Equal(
testData.EmbeddedSigningCertificate.Value.ByteArrayToHex(),
signedCms.SignerInfos[0].Certificate.RawData.ByteArrayToHex());
// Assert.NoThrow
signedCms.CheckSignature(true);
}
else
{
Assert.Null(signedCms.SignerInfos[0].Certificate);
using (var signerCert = new X509Certificate2(testData.ExternalCertificateBytes))
{
// Assert.NoThrow
signedCms.CheckSignature(
new X509Certificate2Collection(signerCert),
true);
}
}
X509Certificate2 returnedCert;
ReadOnlySpan<byte> messageContentSpan = testData.MessageContent.Span;
X509Certificate2Collection candidates = null;
if (testData.EmbeddedSigningCertificate != null)
{
Assert.True(
token.VerifySignatureForData(messageContentSpan, out returnedCert),
"token.VerifySignatureForData(correct)");
Assert.NotNull(returnedCert);
Assert.Equal(signedCms.SignerInfos[0].Certificate, returnedCert);
}
else
{
candidates = new X509Certificate2Collection
{
new X509Certificate2(testData.ExternalCertificateBytes),
};
Assert.False(
token.VerifySignatureForData(messageContentSpan, out returnedCert),
"token.VerifySignatureForData(correct, no cert)");
Assert.Null(returnedCert);
Assert.True(
token.VerifySignatureForData(messageContentSpan, out returnedCert, candidates),
"token.VerifySignatureForData(correct, certs)");
Assert.NotNull(returnedCert);
Assert.Equal(candidates[0], returnedCert);
}
X509Certificate2 previousCert = returnedCert;
Assert.False(
token.VerifySignatureForData(messageContentSpan.Slice(1), out returnedCert, candidates),
"token.VerifySignatureForData(incorrect)");
Assert.Null(returnedCert);
byte[] messageHash = testData.HashBytes.ToArray();
Assert.False(
token.VerifySignatureForHash(messageHash, HashAlgorithmName.MD5, out returnedCert, candidates),
"token.VerifyHash(correct, MD5)");
Assert.Null(returnedCert);
Assert.False(
token.VerifySignatureForHash(messageHash, new Oid(Oids.Md5), out returnedCert, candidates),
"token.VerifyHash(correct, Oid(MD5))");
Assert.Null(returnedCert);
Assert.True(
token.VerifySignatureForHash(messageHash, new Oid(testData.HashAlgorithmId), out returnedCert, candidates),
"token.VerifyHash(correct, Oid(algId))");
Assert.NotNull(returnedCert);
Assert.Equal(previousCert, returnedCert);
messageHash[0] ^= 0xFF;
Assert.False(
token.VerifySignatureForHash(messageHash, new Oid(testData.HashAlgorithmId), out returnedCert, candidates),
"token.VerifyHash(incorrect, Oid(algId))");
Assert.Null(returnedCert);
}
[Fact]
public static void TryDecode_Fails_SignedCmsOfData()
{
Assert.False(
Rfc3161TimestampToken.TryDecode(
SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber,
out Rfc3161TimestampToken token,
out int bytesRead),
"Rfc3161TimestampToken.TryDecode");
Assert.Equal(0, bytesRead);
Assert.Null(token);
}
[Fact]
public static void TryDecode_Fails_Empty()
{
Assert.False(
Rfc3161TimestampToken.TryDecode(
ReadOnlyMemory<byte>.Empty,
out Rfc3161TimestampToken token,
out int bytesRead),
"Rfc3161TimestampToken.TryDecode");
Assert.Equal(0, bytesRead);
Assert.Null(token);
}
[Fact]
public static void TryDecode_Fails_EnvelopedCms()
{
byte[] encodedMessage =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818013"
+ "dc0eb2984a445d04a1f6246b8fe41f1d24507548d449d454d5bb5e0638d75ed101bf78c0155a5d208eb746755fbccbc86923"
+ "8443760a9ae94770d6373e0197be23a6a891f0c522ca96b3e8008bf23547474b7e24e7f32e8134df3862d84f4dea2470548e"
+ "c774dd74f149a56cdd966e141122900d00ad9d10ea1848541294a1302b06092a864886f70d010701301406082a864886f70d"
+ "030704089c8119f6cf6b174c8008bcea3a10d0737eb9").HexToByteArray();
Assert.False(
Rfc3161TimestampToken.TryDecode(
encodedMessage,
out Rfc3161TimestampToken token,
out int bytesRead),
"Rfc3161TimestampToken.TryDecode");
Assert.Equal(0, bytesRead);
Assert.Null(token);
}
[Fact]
public static void TryDecode_Fails_MalformedToken()
{
ContentInfo contentInfo = new ContentInfo(
new Oid(Oids.TstInfo, Oids.TstInfo),
new byte[] { 1 });
SignedCms cms = new SignedCms(contentInfo);
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
{
cms.ComputeSignature(new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, cert));
}
Assert.False(
Rfc3161TimestampToken.TryDecode(
cms.Encode(),
out Rfc3161TimestampToken token,
out int bytesRead),
"Rfc3161TimestampToken.TryDecode");
Assert.Equal(0, bytesRead);
Assert.Null(token);
}
[Theory]
[InlineData(X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashNoName)]
[InlineData(X509IncludeOption.None, SigningCertificateOption.ValidHashNoName)]
[InlineData(X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashWithName)]
[InlineData(X509IncludeOption.None, SigningCertificateOption.ValidHashWithName)]
public static void MatchV1(X509IncludeOption includeOption, SigningCertificateOption v1Option)
{
CustomBuild_CertMatch(
Certificates.ValidLookingTsaCert,
new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero),
v1Option,
SigningCertificateOption.Omit,
includeOption: includeOption);
}
[Theory]
[InlineData(X509IncludeOption.WholeChain)]
[InlineData(X509IncludeOption.None)]
public static void CertHashMismatchV1(X509IncludeOption includeOption)
{
CustomBuild_CertMismatch(
Certificates.ValidLookingTsaCert,
new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero),
SigningCertificateOption.InvalidHashNoName,
SigningCertificateOption.Omit,
includeOption: includeOption);
}
[Theory]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.SubjectKeyIdentifier)]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.SubjectKeyIdentifier)]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.IssuerAndSerialNumber)]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.IssuerAndSerialNumber)]
public static void CertMismatchIssuerAndSerialV1(
X509IncludeOption includeOption,
SigningCertificateOption v1Option,
SubjectIdentifierType identifierType)
{
CustomBuild_CertMismatch(
Certificates.ValidLookingTsaCert,
new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero),
v1Option,
SigningCertificateOption.Omit,
includeOption: includeOption,
identifierType: identifierType);
}
[Theory]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashNoName,
null)]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashNoName,
null)]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithName,
"MD5")]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithName,
"MD5")]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithName,
"SHA1")]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithName,
"SHA1")]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithName,
"SHA384")]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithName,
"SHA384")]
public static void MatchV2(
X509IncludeOption includeOption,
SigningCertificateOption v2Option,
string hashAlgName)
{
CustomBuild_CertMatch(
Certificates.ValidLookingTsaCert,
new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero),
SigningCertificateOption.Omit,
v2Option,
hashAlgName == null ? default(HashAlgorithmName) : new HashAlgorithmName(hashAlgName),
includeOption);
}
[Theory]
[InlineData(X509IncludeOption.WholeChain, null)]
[InlineData(X509IncludeOption.None, null)]
[InlineData(X509IncludeOption.WholeChain, "MD5")]
[InlineData(X509IncludeOption.None, "MD5")]
[InlineData(X509IncludeOption.WholeChain, "SHA1")]
[InlineData(X509IncludeOption.None, "SHA1")]
[InlineData(X509IncludeOption.WholeChain, "SHA384")]
[InlineData(X509IncludeOption.None, "SHA384")]
public static void CertHashMismatchV2(X509IncludeOption includeOption, string hashAlgName)
{
CustomBuild_CertMismatch(
Certificates.ValidLookingTsaCert,
new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero),
SigningCertificateOption.Omit,
SigningCertificateOption.InvalidHashNoName,
hashAlgName == null ? default(HashAlgorithmName) : new HashAlgorithmName(hashAlgName),
includeOption: includeOption);
}
[Theory]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.SubjectKeyIdentifier,
null)]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.SubjectKeyIdentifier,
null)]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.SubjectKeyIdentifier,
"SHA384")]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.SubjectKeyIdentifier,
"SHA384")]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.IssuerAndSerialNumber,
null)]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.IssuerAndSerialNumber,
null)]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.IssuerAndSerialNumber,
"SHA384")]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithInvalidName,
SubjectIdentifierType.IssuerAndSerialNumber,
"SHA384")]
public static void CertMismatchIssuerAndSerialV2(
X509IncludeOption includeOption,
SigningCertificateOption v2Option,
SubjectIdentifierType identifierType,
string hashAlgName)
{
CustomBuild_CertMismatch(
Certificates.ValidLookingTsaCert,
new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero),
SigningCertificateOption.Omit,
v2Option,
hashAlgName == null ? default(HashAlgorithmName) : new HashAlgorithmName(hashAlgName),
includeOption: includeOption,
identifierType: identifierType);
}
[Theory]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.ValidHashNoName,
null)]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.ValidHashNoName,
"SHA512")]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.ValidHashNoName,
null)]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.ValidHashNoName,
"SHA512")]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.ValidHashWithName,
null)]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.ValidHashWithName,
"SHA384")]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.ValidHashWithName,
null)]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.ValidHashWithName,
"SHA384")]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithName,
SigningCertificateOption.ValidHashNoName,
null)]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithName,
SigningCertificateOption.ValidHashNoName,
"SHA512")]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithName,
SigningCertificateOption.ValidHashNoName,
null)]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithName,
SigningCertificateOption.ValidHashNoName,
"SHA512")]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithName,
SigningCertificateOption.ValidHashWithName,
null)]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithName,
SigningCertificateOption.ValidHashWithName,
"SHA384")]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithName,
SigningCertificateOption.ValidHashWithName,
null)]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithName,
SigningCertificateOption.ValidHashWithName,
"SHA384")]
public static void CertMatchV1AndV2(
X509IncludeOption includeOption,
SigningCertificateOption v1Option,
SigningCertificateOption v2Option,
string hashAlgName)
{
CustomBuild_CertMatch(
Certificates.ValidLookingTsaCert,
new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero),
v1Option,
v2Option,
hashAlgName == null ? default(HashAlgorithmName) : new HashAlgorithmName(hashAlgName),
includeOption);
}
[Theory]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.InvalidHashNoName,
SigningCertificateOption.ValidHashWithName,
SubjectIdentifierType.IssuerAndSerialNumber,
null)]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithInvalidSerial,
SigningCertificateOption.ValidHashWithName,
SubjectIdentifierType.IssuerAndSerialNumber,
"SHA384")]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.ValidHashWithInvalidName,
SigningCertificateOption.InvalidHashNoName,
SubjectIdentifierType.SubjectKeyIdentifier,
null)]
[InlineData(
X509IncludeOption.None,
SigningCertificateOption.ValidHashWithName,
SigningCertificateOption.InvalidHashNoName,
SubjectIdentifierType.SubjectKeyIdentifier,
"SHA512")]
[InlineData(
X509IncludeOption.WholeChain,
SigningCertificateOption.InvalidHashWithInvalidSerial,
SigningCertificateOption.ValidHashNoName,
SubjectIdentifierType.IssuerAndSerialNumber,
null)]
public static void CertMismatchV1OrV2(
X509IncludeOption includeOption,
SigningCertificateOption v1Option,
SigningCertificateOption v2Option,
SubjectIdentifierType identifierType,
string hashAlgName)
{
CustomBuild_CertMismatch(
Certificates.ValidLookingTsaCert,
new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero),
v1Option,
v2Option,
hashAlgName == null ? default(HashAlgorithmName) : new HashAlgorithmName(hashAlgName),
includeOption: includeOption,
identifierType: identifierType);
}
[Theory]
[InlineData(X509IncludeOption.WholeChain)]
[InlineData(X509IncludeOption.None)]
public static void TimestampTooOld(X509IncludeOption includeOption)
{
CertLoader loader = Certificates.ValidLookingTsaCert;
DateTimeOffset referenceTime;
using (X509Certificate2 cert = loader.GetCertificate())
{
referenceTime = cert.NotBefore.AddSeconds(-1);
}
CustomBuild_CertMismatch(
loader,
referenceTime,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.Omit,
includeOption: includeOption);
}
[Theory]
[InlineData(X509IncludeOption.WholeChain)]
[InlineData(X509IncludeOption.None)]
public static void TimestampTooNew(X509IncludeOption includeOption)
{
CertLoader loader = Certificates.ValidLookingTsaCert;
DateTimeOffset referenceTime;
using (X509Certificate2 cert = loader.GetCertificate())
{
referenceTime = cert.NotAfter.AddSeconds(1);
}
CustomBuild_CertMismatch(
loader,
referenceTime,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.Omit,
includeOption: includeOption);
}
[Theory]
[InlineData(X509IncludeOption.WholeChain)]
[InlineData(X509IncludeOption.None)]
public static void NoEkuExtension(X509IncludeOption includeOption)
{
CertLoader loader = Certificates.RSA2048SignatureOnly;
DateTimeOffset referenceTime;
using (X509Certificate2 cert = loader.GetCertificate())
{
referenceTime = cert.NotAfter.AddDays(-1);
Assert.Equal(0, cert.Extensions.OfType<X509EnhancedKeyUsageExtension>().Count());
}
CustomBuild_CertMismatch(
loader,
referenceTime,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.Omit,
includeOption: includeOption);
}
[Theory]
[InlineData(X509IncludeOption.WholeChain)]
[InlineData(X509IncludeOption.None)]
public static void TwoEkuExtensions(X509IncludeOption includeOption)
{
CertLoader loader = Certificates.TwoEkuTsaCert;
DateTimeOffset referenceTime;
using (X509Certificate2 cert = loader.GetCertificate())
{
referenceTime = cert.NotAfter.AddDays(-1);
var ekuExts = cert.Extensions.OfType<X509EnhancedKeyUsageExtension>().ToList();
Assert.Equal(2, ekuExts.Count);
// Make sure we're validating that "early success" doesn't happen.
Assert.Contains(
Oids.TimeStampingPurpose,
ekuExts[0].EnhancedKeyUsages.OfType<Oid>().Select(o => o.Value));
}
CustomBuild_CertMismatch(
loader,
referenceTime,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.Omit,
includeOption: includeOption);
}
[Theory]
[InlineData(X509IncludeOption.WholeChain)]
[InlineData(X509IncludeOption.None)]
public static void NonCriticalEkuExtension(X509IncludeOption includeOption)
{
CertLoader loader = Certificates.NonCriticalTsaEku;
DateTimeOffset referenceTime;
using (X509Certificate2 cert = loader.GetCertificate())
{
referenceTime = cert.NotAfter.AddDays(-1);
var ekuExts = cert.Extensions.OfType<X509EnhancedKeyUsageExtension>().ToList();
Assert.Equal(1, ekuExts.Count);
Assert.False(ekuExts[0].Critical, "ekuExts[0].Critical");
}
CustomBuild_CertMismatch(
loader,
referenceTime,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.Omit,
includeOption: includeOption);
}
[Theory]
[InlineData(X509IncludeOption.WholeChain)]
[InlineData(X509IncludeOption.None)]
public static void NoTsaEku(X509IncludeOption includeOption)
{
CertLoader loader = Certificates.TlsClientServerCert;
DateTimeOffset referenceTime;
using (X509Certificate2 cert = loader.GetCertificate())
{
referenceTime = cert.NotAfter.AddDays(-1);
}
CustomBuild_CertMismatch(
loader,
referenceTime,
SigningCertificateOption.ValidHashNoName,
SigningCertificateOption.Omit,
includeOption: includeOption);
}
private static void CustomBuild_CertMatch(
CertLoader loader,
DateTimeOffset referenceTime,
SigningCertificateOption v1Option,
SigningCertificateOption v2Option,
HashAlgorithmName v2AlgorithmName = default,
X509IncludeOption includeOption = default,
SubjectIdentifierType identifierType = SubjectIdentifierType.IssuerAndSerialNumber)
{
byte[] tokenBytes = BuildCustomToken(
loader,
referenceTime,
v1Option,
v2Option,
v2AlgorithmName,
includeOption,
identifierType);
Rfc3161TimestampToken token;
Assert.True(Rfc3161TimestampToken.TryDecode(tokenBytes, out token, out int bytesRead));
Assert.Equal(tokenBytes.Length, bytesRead);
Assert.NotNull(token);
Assert.Equal(referenceTime, token.TokenInfo.Timestamp);
using (X509Certificate2 cert = Certificates.ValidLookingTsaCert.GetCertificate())
{
Assert.True(
token.VerifySignatureForHash(
token.TokenInfo.GetMessageHash().Span,
token.TokenInfo.HashAlgorithmId,
out X509Certificate2 signer,
new X509Certificate2Collection(cert)));
Assert.Equal(cert, signer);
}
}
private static void CustomBuild_CertMismatch(
CertLoader loader,
DateTimeOffset referenceTime,
SigningCertificateOption v1Option,
SigningCertificateOption v2Option,
HashAlgorithmName v2AlgorithmName = default,
X509IncludeOption includeOption = default,
SubjectIdentifierType identifierType = SubjectIdentifierType.IssuerAndSerialNumber)
{
byte[] tokenBytes = BuildCustomToken(
loader,
referenceTime,
v1Option,
v2Option,
v2AlgorithmName,
includeOption,
identifierType);
Rfc3161TimestampToken token;
bool willParse = includeOption == X509IncludeOption.None;
if (willParse && identifierType == SubjectIdentifierType.IssuerAndSerialNumber)
{
// Because IASN matches against the ESSCertId(V2) directly it will reject the token.
switch (v1Option)
{
case SigningCertificateOption.ValidHashWithInvalidName:
case SigningCertificateOption.ValidHashWithInvalidSerial:
case SigningCertificateOption.InvalidHashWithInvalidName:
case SigningCertificateOption.InvalidHashWithInvalidSerial:
willParse = false;
break;
}
switch (v2Option)
{
case SigningCertificateOption.ValidHashWithInvalidName:
case SigningCertificateOption.ValidHashWithInvalidSerial:
case SigningCertificateOption.InvalidHashWithInvalidName:
case SigningCertificateOption.InvalidHashWithInvalidSerial:
willParse = false;
break;
}
}
if (willParse)
{
Assert.True(Rfc3161TimestampToken.TryDecode(tokenBytes, out token, out int bytesRead));
Assert.NotNull(token);
Assert.Equal(tokenBytes.Length, bytesRead);
using (X509Certificate2 cert = loader.GetCertificate())
{
Assert.False(
token.VerifySignatureForHash(
token.TokenInfo.GetMessageHash().Span,
token.TokenInfo.HashAlgorithmId,
out X509Certificate2 signer,
new X509Certificate2Collection(cert)));
Assert.Null(signer);
}
}
else
{
Assert.False(Rfc3161TimestampToken.TryDecode(tokenBytes, out token, out int bytesRead));
Assert.Null(token);
Assert.Equal(0, bytesRead);
}
}
private static byte[] BuildCustomToken(
CertLoader cert,
DateTimeOffset timestamp,
SigningCertificateOption v1Option,
SigningCertificateOption v2Option,
HashAlgorithmName v2DigestAlg=default,
X509IncludeOption includeOption=X509IncludeOption.ExcludeRoot,
SubjectIdentifierType identifierType=SubjectIdentifierType.IssuerAndSerialNumber)
{
long accuracyMicroSeconds = (long)(TimeSpan.FromMinutes(1).TotalMilliseconds * 1000);
byte[] serialNumber = BitConverter.GetBytes(DateTimeOffset.UtcNow.Ticks);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(serialNumber);
}
Rfc3161TimestampTokenInfo info = new Rfc3161TimestampTokenInfo(
new Oid("0.0", "0.0"),
new Oid(Oids.Sha384),
new byte[384 / 8],
serialNumber,
timestamp,
accuracyMicroSeconds,
isOrdering: true);
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.TstInfo, Oids.TstInfo), info.Encode());
SignedCms cms = new SignedCms(contentInfo);
using (X509Certificate2 tsaCert = cert.TryGetCertificateWithPrivateKey())
{
CmsSigner signer = new CmsSigner(identifierType, tsaCert)
{
IncludeOption = includeOption
};
if (v1Option != SigningCertificateOption.Omit)
{
ExpandOption(v1Option, out bool validHash, out bool skipIssuerSerial, out bool validName, out bool validSerial);
// simple SigningCertificate
byte[] signingCertificateV1Bytes =
"301A3018301604140000000000000000000000000000000000000000".HexToByteArray();
if (validHash)
{
byte[] hash = SHA1.HashData(tsaCert.RawData);
Buffer.BlockCopy(
hash,
0,
signingCertificateV1Bytes,
signingCertificateV1Bytes.Length - hash.Length,
hash.Length);
}
if (!skipIssuerSerial)
{
byte[] footer = BuildIssuerAndSerialNumber(tsaCert, validName, validSerial);
signingCertificateV1Bytes[1] += (byte)footer.Length;
signingCertificateV1Bytes[3] += (byte)footer.Length;
signingCertificateV1Bytes[5] += (byte)footer.Length;
Assert.InRange(signingCertificateV1Bytes[1], 0, 127);
signingCertificateV1Bytes = signingCertificateV1Bytes.Concat(footer).ToArray();
}
signer.SignedAttributes.Add(
new AsnEncodedData("1.2.840.113549.1.9.16.2.12", signingCertificateV1Bytes));
}
if (v2Option != SigningCertificateOption.Omit)
{
byte[] attrBytes;
byte[] algBytes = Array.Empty<byte>();
byte[] hashBytes;
byte[] issuerNameBytes = Array.Empty<byte>();
if (v2DigestAlg != default)
{
switch (v2DigestAlg.Name)
{
case "MD5":
algBytes = "300C06082A864886F70D02050500".HexToByteArray();
break;
case "SHA1":
algBytes = "300906052B0E03021A0500".HexToByteArray();
break;
case "SHA256":
// Invalid under DER, because it's the default.
algBytes = "300D06096086480165030402010500".HexToByteArray();
break;
case "SHA384":
algBytes = "300D06096086480165030402020500".HexToByteArray();
break;
case "SHA512":
algBytes = "300D06096086480165030402030500".HexToByteArray();
break;
default:
throw new NotSupportedException(v2DigestAlg.Name);
}
}
else
{
v2DigestAlg = HashAlgorithmName.SHA256;
}
hashBytes = tsaCert.GetCertHash(v2DigestAlg);
ExpandOption(v2Option, out bool validHash, out bool skipIssuerSerial, out bool validName, out bool validSerial);
if (!validHash)
{
hashBytes[0] ^= 0xFF;
}
if (!skipIssuerSerial)
{
issuerNameBytes = BuildIssuerAndSerialNumber(tsaCert, validName, validSerial);
}
// hashBytes hasn't been wrapped in an OCTET STRING yet, so add 2 more.
int payloadSize = algBytes.Length + hashBytes.Length + issuerNameBytes.Length + 2;
Assert.InRange(payloadSize, 0, 123);
attrBytes = new byte[payloadSize + 6];
int index = 0;
// SEQUENCE (SigningCertificateV2)
attrBytes[index++] = 0x30;
attrBytes[index++] = (byte)(payloadSize + 4);
// SEQUENCE OF => certs
attrBytes[index++] = 0x30;
attrBytes[index++] = (byte)(payloadSize + 2);
// SEQUENCE (ESSCertIdV2)
attrBytes[index++] = 0x30;
attrBytes[index++] = (byte)payloadSize;
Buffer.BlockCopy(algBytes, 0, attrBytes, index, algBytes.Length);
index += algBytes.Length;
// OCTET STRING (Hash)
attrBytes[index++] = 0x04;
attrBytes[index++] = (byte)hashBytes.Length;
Buffer.BlockCopy(hashBytes, 0, attrBytes, index, hashBytes.Length);
index += hashBytes.Length;
Buffer.BlockCopy(issuerNameBytes, 0, attrBytes, index, issuerNameBytes.Length);
signer.SignedAttributes.Add(
new AsnEncodedData("1.2.840.113549.1.9.16.2.47", attrBytes));
}
cms.ComputeSignature(signer);
}
return cms.Encode();
}
private static byte[] BuildIssuerAndSerialNumber(X509Certificate2 tsaCert, bool validName, bool validSerial)
{
byte[] issuerNameBytes;
if (validName)
{
issuerNameBytes = tsaCert.IssuerName.RawData;
}
else
{
issuerNameBytes = new X500DistinguishedName("CN=No Match").RawData;
}
byte[] serialBytes = tsaCert.GetSerialNumber();
if (validSerial)
{
Array.Reverse(serialBytes);
}
else
{
// If the byte sequence was a palindrome it's still a match,
// so flip some bits.
serialBytes[0] ^= 0x7F;
}
if (issuerNameBytes.Length + serialBytes.Length > 80)
{
throw new NotSupportedException(
"Issuer name and serial length are bigger than this code can handle");
}
// SEQUENCE
// SEQUENCE
// CONTEXT-SPECIFIC 4
// [IssuerName]
// INTEGER
// [SerialNumber, big endian]
byte[] issuerAndSerialNumber = new byte[issuerNameBytes.Length + serialBytes.Length + 8];
issuerAndSerialNumber[0] = 0x30;
issuerAndSerialNumber[1] = (byte)(issuerAndSerialNumber.Length - 2);
issuerAndSerialNumber[2] = 0x30;
issuerAndSerialNumber[3] = (byte)(issuerNameBytes.Length + 2);
issuerAndSerialNumber[4] = 0xA4;
issuerAndSerialNumber[5] = (byte)(issuerNameBytes.Length);
Buffer.BlockCopy(issuerNameBytes, 0, issuerAndSerialNumber, 6, issuerNameBytes.Length);
issuerAndSerialNumber[issuerNameBytes.Length + 6] = 0x02;
issuerAndSerialNumber[issuerNameBytes.Length + 7] = (byte)serialBytes.Length;
Buffer.BlockCopy(serialBytes, 0, issuerAndSerialNumber, issuerNameBytes.Length + 8, serialBytes.Length);
return issuerAndSerialNumber;
}
private static void ExpandOption(
SigningCertificateOption option,
out bool validHash,
out bool skipIssuerSerial,
out bool validName,
out bool validSerial)
{
Assert.NotEqual(SigningCertificateOption.Omit, option);
validHash = option < SigningCertificateOption.InvalidHashNoName;
skipIssuerSerial =
option == SigningCertificateOption.ValidHashNoName ||
option == SigningCertificateOption.InvalidHashNoName;
if (skipIssuerSerial)
{
validName = validSerial = false;
}
else
{
validName =
option == SigningCertificateOption.ValidHashWithName ||
option == SigningCertificateOption.InvalidHashWithName ||
option == SigningCertificateOption.ValidHashWithInvalidSerial ||
option == SigningCertificateOption.InvalidHashWithInvalidSerial;
validSerial =
option == SigningCertificateOption.ValidHashWithName ||
option == SigningCertificateOption.InvalidHashWithName ||
option == SigningCertificateOption.ValidHashWithInvalidName ||
option == SigningCertificateOption.InvalidHashWithInvalidName;
}
}
public enum SigningCertificateOption
{
Omit,
ValidHashNoName,
ValidHashWithName,
ValidHashWithInvalidName,
ValidHashWithInvalidSerial,
InvalidHashNoName,
InvalidHashWithName,
InvalidHashWithInvalidName,
InvalidHashWithInvalidSerial,
}
}
}
| 39.222222 | 132 | 0.579519 | [
"MIT"
] | 333fred/runtime | src/libraries/System.Security.Cryptography.Pkcs/tests/Rfc3161/TimestampTokenTests.cs | 42,713 | C# |
/*
Copyright (c) 2017, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Collections.Generic;
using MatterHackers.Agg.Image;
namespace MatterHackers.MatterControl.Library
{
public interface ILibraryWritableContainer : ILibraryContainer, IContentStore
{
event EventHandler<LibraryItemChangedEventArgs> ItemContentChanged;
void Add(IEnumerable<ILibraryItem> items);
void Remove(IEnumerable<ILibraryItem> items);
/// <summary>
/// Move the given items from the source container to this container
/// </summary>
/// <param name="items">The items to move</param>
/// <param name="sourceContainer">The current parent container</param>
void Move(IEnumerable<ILibraryItem> items, ILibraryWritableContainer sourceContainer);
void SetThumbnail(ILibraryItem item, int width, int height, ImageBuffer imageBuffer);
bool AllowAction(ContainerActions containerActions);
}
}
| 42.178571 | 88 | 0.800593 | [
"BSD-2-Clause"
] | EastBenchTech/MatterControl | MatterControlLib/Library/Interfaces/ILibraryWritableContainer.cs | 2,364 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Numerics;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
namespace Tetris.domain
{
// Authors: DeAngelo Wilson, Name2
// Description: A class which stores all the current blocks placed onto a grid and Converts gameShapes to be Blocks on the grid
// Called on by the Movement Manager and GameManager
public class BlockGrid
{
//2D dimensional array of different width/height
// - Vacant coordinates MUST be null
public readonly Block[][] grid;
//NOTE: Grid access --> grid[x][y] || grid[col][row]
private readonly int row_count;
private readonly int col_count;
private List<Block> blocks;
// Author: DeAngelo Wilson
public BlockGrid(int maxX, int maxY)
{
row_count = maxY;
col_count = maxX;
blocks = new List<Block>(row_count * col_count);
//Must initialize directly in constructor -- bc readonly
grid = new Block[maxX][];
InitializeBlockGrid(maxX, maxY);
}
public void Draw()
{
foreach (Block block in blocks)
{
block.Draw();
}
}
// Author: DeAngelo
public void PlaceShape(GameShape toPlace)
{
//TODO:: prevent duplicate placing
//for each block of the GameShape-- place onto grid + add to list
foreach (Block block in toPlace.GetBlocks())
{
if (grid[block.GetX()][block.GetY()] != null)
{
throw new DuplicateNameException("PlaceShape:: block cannot be placed, position (" + block.GetX() + ", " + block.GetY() + ") already occupied");
}
Block blockCopy = block.Copy();
grid[block.GetX()][block.GetY()] = blockCopy;
blocks.Add(blockCopy);
}
toPlace.GameShapePlaced();
}
// Author: DeAngelo Wilson
public void RemoveLines(List<int> toRemove)
{
//given a list of row indexes toRemove -- remove row + move all above blocks down 1
int count = 0;
toRemove.Sort();
//Note:: there is an animation for this ==> pauses game time, all completed lines flash --> then destroyed
//remove the completed line
foreach (int row in toRemove)
{
int newRow = row - count;
for (int col = 0; col < col_count; col++)
{
//remove + destroy all blocks in row
blocks.Remove(grid[col][newRow]);
grid[col][newRow] = null;
}
//shift every row above, down by 1... (way less optimized than below RemoveLines, but clean & working)
ShiftGridBlocksDown(newRow + 1, 1);
count++;
}
}
//// Author: DeAngelo Wilson
//public void RemoveLines(List<int> toRemove)
//{
// //given a list of row indexes toRemove -- remove row + move all above blocks down 1
// int maxIndex = -1;
// //Note:: there is an animation for this ==> pauses game time, all completed lines flash --> then destroyed
// //remove the completed line
// foreach (int row in toRemove)
// {
// for (int col = 0; col < col_count; col++)
// {
// //remove + destroy all blocks in row
// blocks.Remove(grid[col][row]);
// grid[col][row] = null;
// }
// //
// if (maxIndex < row)
// {
// maxIndex = row;
// }
// }
// //shift every row above (+ 1) the highest line index removed
// ShiftGridBlocksDown(maxIndex + 1, toRemove.Count);
//}
private void ShiftGridBlocksDown(int lowestRow, int shift)
{
if (shift == 0) return;
//for all blocks above or equal (higher index) to lowestRow -- shift down by shift amount (total lines cleared)
for (int col = 0; col < col_count; col++)
{
for (int row = lowestRow; row < row_count; row++)
{
//shift block down
if (grid[col][row] != null)
{
ShiftBlockDown(col, row, shift);
}
}
}
}
private void ShiftBlockDown(int col, int row, int shift)
{
//move coords of block down
grid[col][row].ApplyOffset(Constants.DOWN_OFFSET * shift);
//move block down in grid
grid[col][row - shift] = grid[col][row];
grid[col][row] = null;
}
// Author: DeAngelo Wilson
public List<int> GetCompletedLines()
{
List<int> completedLineIndex = new List<int>();
for (int row = 0; row < row_count; row++)
{
int rowBlockCount = 0;
for (int col = 0; col < col_count; col++)
{
if (grid[col][row] != null)
{
rowBlockCount++;
}
}
if (rowBlockCount == col_count)
{
completedLineIndex.Add(row);
}
}
return completedLineIndex;
}
public List<int> GetCompletedLines(GameShape placedShape)
{
List<int> completedLineIndex = new List<int>();
List<int> rowIndexes = GetGameShapeRowIndexes(placedShape);
foreach (int row in rowIndexes)
{
int rowBlockCount = 0;
for (int col = 0; col < col_count; col++)
{
if (grid[col][row] != null)
{
rowBlockCount++;
}
}
//
if (rowBlockCount == col_count)
{
completedLineIndex.Add(row);
}
}
return completedLineIndex;
}
private List<int> GetGameShapeRowIndexes(GameShape gameShape)
{
List<int> rowIndexes = new List<int>();
//for each block of the GameShape-- store row index
foreach (Block block in gameShape.GetBlocks())
{
if (!rowIndexes.Contains(block.GetY()))
{
rowIndexes.Add(block.GetY());
}
}
return rowIndexes;
}
// Author: DeAngelo Wilson
public List<Vector2> GetVacantCoordinates()
{
List<Vector2> coords = new List<Vector2>();
for (int col = 0; col < col_count; col++)
{
for (int row = 0; row < row_count; row++)
{
if (grid[col][row] == null)
{
coords.Add(new Vector2( col, row));
}
}
}
return coords;
}
// Author: DeAngelo Wilson
public List<Vector2> GetOccupiedCoordinates()
{
List<Vector2> coords = new List<Vector2>();
//return cords of every block in stored 'blocks' List
foreach (Block block in blocks)
{
coords.Add(new Vector2(block.GetX(), block.GetY()));
}
return coords;
}
//Author: DeAngelo Wilson
private void InitializeBlockGrid(int cols, int rows)
{
//Initialize Block grid
for (int i = 0; i < cols; i++)
{
grid[i] = new Block[rows];
}
for (int col = 0; col < cols; col++)
{
for (int row = 0; row < rows; row++)
{
grid[col][row] = null;
}
}
}
public int GetGridRowCount()
{
return row_count;
}
public int GetGridColumnCount()
{
return col_count;
}
}
}
| 31.455516 | 165 | 0.451295 | [
"Apache-2.0"
] | shade219/Tetris | Tetris/domain/BlockGrid.cs | 8,841 | C# |
using System;
namespace ADOUtils
{
public class Connection : IConnection
{
private readonly Action _action;
public Connection(Action action = null)
{
_action = action ?? delegate {};
}
public virtual void Close()
{
_action.Invoke();
}
public virtual void Dispose()
{
_action.Invoke();
}
}
} | 14.583333 | 42 | 0.608571 | [
"Apache-2.0"
] | gimmi/adoutils | src/ADOUtils/Connection.cs | 352 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net.Http;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using SF.Sys.Entities;
using SF.Sys.Services;
using SF.Sys.Collections.Generic;
using SF.Sys.Reflection;
using SF.Utils.TableExports;
using SF.Sys.Comments;
using SF.Sys.Linq.Expressions;
using SF.Sys.Annotations;
using SF.Sys.Auth;
using SF.Sys.Clients;
namespace SF.Sys.BackEndConsole.Front
{
public class BackEndConsoleExportService : IBackEndConsoleExportService
{
IServiceMetadata ServiceMetadata { get; }
IServiceInvokerProvider ServiceInvokerProvider { get; }
IServiceProvider ServiceProvider { get; }
IAuthService AuthService { get; }
IAccessToken AccessToken { get; }
NamedServiceResolver<ITableExporterFactory> ExporterFactoryResolver { get; }
IAccessTokenValidator AccessTokenValidator { get; }
SF.Sys.NetworkService.Metadata.Library NetLibrary { get; }
public BackEndConsoleExportService(
IServiceProvider ServiceProvider,
IServiceMetadata ServiceMetadata,
IServiceInvokerProvider ServiceInvokerProvider,
IAuthService AuthService,
IAccessToken AccessToken,
IAccessTokenValidator AccessTokenValidator,
SF.Sys.NetworkService.Metadata.Library NetLibrary,
NamedServiceResolver<ITableExporterFactory> ExporterFactoryResolver
)
{
this.NetLibrary = NetLibrary;
this.AccessTokenValidator = AccessTokenValidator;
this.AccessToken = AccessToken;
this.AuthService = AuthService;
this.ServiceProvider = ServiceProvider;
this.ServiceMetadata = ServiceMetadata;
this.ServiceInvokerProvider = ServiceInvokerProvider;
this.ExporterFactoryResolver = ExporterFactoryResolver;
}
class ExportContext
{
public ExportMode Mode { get; set; }
/// <summary>
/// 服务
/// </summary>
[Required]
public string Service { get; set; }
/// <summary>
/// 方法
/// </summary>
[Required]
public string Method { get; set; }
/// <summary>
/// 格式
/// </summary>
[Required]
public string Format { get; set; }
/// <summary>
/// 参数
/// </summary>
public string Argument { get; set; }
/// <summary>
/// 标题
/// </summary>
public string Title { get; set; }
public IServiceInvoker Invoker { get; set; }
}
IEnumerable<string> GetServiceNames(string Name)
{
yield return Name;
yield return "I" + Name;
yield return "I" + Name+"Service";
}
public async Task<HttpResponseMessage> Export(
ExportMode Mode,
string Service,
string Method,
string Format,
string Argument,
string Title,
string Token
)
{
var (svcType, mthd) = NetLibrary.FindMethod(Service, Method);
if (svcType == null || mthd == null)
throw new PublicArgumentException($"找不到服务{Service}或方法{Method}");
var invoker = ServiceInvokerProvider.Resolve(svcType.GetSysType(), mthd.GetSysMethod());
var user = Token != null ? await AccessTokenValidator.Validate(Token) : AccessToken.User;
if (user==null || !user.Identity.IsAuthenticated || !AuthService.Authorize(
user,
invoker.ServiceDeclaration.ServiceName,
invoker.Method.Name,
null))
throw new PublicDeniedException("您无权访问此接口");
var ctx = new ExportContext
{
Method=Method,
Format=Format,
Mode=Mode,
Service=Service,
Title=Title,
Argument=Argument,
Invoker=invoker
};
switch (Mode)
{
case ExportMode.Table:
return await ExportQueryResult(ctx);
default:
throw new NotSupportedException("不支持指定的类型:" + Mode);
}
}
class Exporter : IDisposable
{
ITableExporter exporter;
public string FileExtension { get; }
MemoryStream stream { get; }
public Exporter(
NamedServiceResolver<ITableExporterFactory> Resolver,
ExportContext ctx,
Column[] columns
)
{
stream = new MemoryStream();
this.exporter = Resolver(ctx.Format).Create(
stream,
ctx.Title,
columns
);
ContentType = exporter.ContentType;
FileExtension = exporter.FileExtension;
}
public void AddRow(object[] rows)
{
exporter.AddRow(rows);
}
public byte[] GetBytes()
{
if (exporter != null)
{
exporter.Dispose();
exporter = null;
}
return stream.ToArray();
}
public string ContentType { get; }
public void Dispose()
{
if (exporter != null)
exporter.Dispose();
if (stream != null)
stream.Dispose();
}
}
Exporter CreateExporter(ExportContext ctx, Column[] columns)
{
return new Exporter(ExporterFactoryResolver, ctx, columns);
}
MethodInfo ExportMethodInfo { get; } =
typeof(BackEndConsoleExportService).GetMethodExt(
nameof(ExportQueryResultTyped),
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod,
typeof(ExportContext),
typeof(Type),
typeof(bool)
).IsNotNull();
Task<HttpResponseMessage> ExportQueryResult(ExportContext ctx)
{
var invoker = ctx.Invoker;
var args = invoker.Method.GetParameters();
if (args.Length != 1 || !typeof(IPagingArgument).IsAssignableFrom(args[0].ParameterType))
throw new PublicNotSupportedException("接口方法不支持导出,参数必须为QueryArgument的子类");
var resultType = invoker.Method.ReturnType.GetGenericArgumentTypeAsTask() ?? invoker.Method.ReturnType;
Type resultItemType;
bool isEnumerable = false;
if (resultType.IsGeneric() && resultType.GetGenericTypeDefinition() == typeof(QueryResult<>))
resultItemType = resultType.GetGenericArguments()[0];
else
{
resultItemType = resultType.AllInterfaces().Select(i => i.GetGenericArgumentTypeAsEnumerable()).FirstOrDefault(i => i != null);
isEnumerable = true;
}
if (resultItemType==null)
throw new PublicNotSupportedException("接口方法不支持导出,返回类型不是QueryResult<>或IEnumerable<>类型");
return (Task < HttpResponseMessage > )ExportMethodInfo.MakeGenericMethod(resultItemType).Invoke(
this,
new object[] {
ctx,
resultItemType,
isEnumerable
}
);
}
async Task<HttpResponseMessage> ExportQueryResultTyped<T>(ExportContext ctx, Type type,bool isEnumerable)
{
var parameter = ctx.Invoker.Method.GetParameters()[0];
var arg = (IPagingArgument)(Json.DefaultSerializer.Deserialize(
ctx.Argument,
parameter.ParameterType
) ?? Activator.CreateInstance(parameter.ParameterType));
var title = ctx.Title = ctx.Title ?? type.Comment().Title;
var props = (
from t in ADT.Link.ToEnumerable(type, t => t.BaseType).Reverse()
from prop in t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty).Where(p=>p.DeclaringType==t)
let tablevisible = prop.GetCustomAttribute<TableVisibleAttribute>(true) as TableVisibleAttribute
where tablevisible != null
orderby tablevisible.Order
select new
{
col = new Column
{
Name = prop.Comment().Title ?? prop.Name,
Type = prop.PropertyType
},
prop = prop
}
).ToArray();
using (var exporter = CreateExporter(ctx, props.Select(p => p.col).ToArray()))
{
if (isEnumerable)
{
var re = (IEnumerable<T>)await ctx.Invoker.InvokeAsync(ServiceProvider, new[] { arg });
foreach (var item in re)
exporter.AddRow(props.Select(p => p.prop.GetValue(item)).ToArray());
}
else
{
var pageCount = 1000;
var offset = 0;
for (; ; )
{
arg.Paging = new Paging
{
Count = pageCount,
Offset = offset
};
var re = (QueryResult<T>)await ctx.Invoker.InvokeAsync(ServiceProvider, new[] { arg });
var count = 0;
foreach (var item in re.Items)
{
exporter.AddRow(props.Select(p => p.prop.GetValue(item)).ToArray());
count++;
}
if (count < pageCount)
break;
offset += count;
}
}
var ctn = new System.Net.Http.ByteArrayContent(
exporter.GetBytes()
);
ctn.Headers.ContentType=new System.Net.Http.Headers.MediaTypeHeaderValue(exporter.ContentType);
ctn.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = title + DateTime.Now.ToString("-yyyyMMddHHmm") + "." + exporter.FileExtension
};
return new HttpResponseMessage(System.Net.HttpStatusCode.OK)
{
Content = ctn
};
}
}
}
}
| 27.950166 | 133 | 0.686557 | [
"Apache-2.0"
] | etechi/ServiceFramework | Projects/Server/Common/SF.Common.BackEndConsoleServices.Implements/Front/BackEndConsoleExportService.cs | 8,553 | C# |
using System.Collections.Generic;
namespace WinRTXamlToolkit.Controls
{
public sealed partial class AutoCompleteTextBox
{
/// <summary>
/// Provides a shared interface for all autocomplete distance scoring and suggestion providing algorithms.
/// </summary>
public interface IAutoCompletable
{
/// <summary>
/// Gets a list of suggested word completions for the specified word, given a dictionary of words.
/// </summary>
/// <param name="wordToSuggest">Word/string to get suggestions for.</param>
/// <param name="suggestionDictionary">Dictionary of words to select suggestions from.</param>
/// <returns>A list of suggestions.</returns>
IList<string> GetSuggestedWords(string wordToSuggest, ICollection<string> suggestionDictionary);
}
}
}
| 41.318182 | 115 | 0.633663 | [
"MIT"
] | JUV-Studios/WinRTXamlToolk | WinRTXamlToolkit/Controls/AutoCompleteTextBox/Algorithm/IAutoCompletable.cs | 911 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace RemoteDeploy
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 25.703704 | 70 | 0.645533 | [
"MIT"
] | ErikXu/remote-deploy | src/RemoteDeploy/Program.cs | 694 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace SketchPad2
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
// Launch in fullscreen by default
ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.FullScreen;
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (e.PrelaunchActivated == false)
{
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
| 39.07619 | 99 | 0.620278 | [
"MIT"
] | djeedai/skescher | skescher/App.xaml.cs | 4,105 | C# |
using System;
using System.Linq;
using System.Collections.Generic;
namespace ABC086C
{
class Program
{
static void Main(string[] args)
{
var n = int.Parse(Console.ReadLine());
var plan = Enumerable.Range(0, n).Select(i =>
{
var input = Console.ReadLine().Split().Select(int.Parse).ToArray();
return (t: input[0], x: input[1], y: input[2]);
}).ToList();
plan.Insert(0, (0, 0, 0));
for (int i = 0; i < plan.Count - 1; i++)
{
var prev = plan[i];
var next = plan[i + 1];
var dt = next.t - prev.t;
var dist = Math.Abs(next.x - prev.x) + Math.Abs(next.y - prev.y);
if (dt < dist || dt % 2 != dist % 2)
{
Console.WriteLine("No");
return;
}
}
Console.WriteLine("Yes");
}
}
}
| 25.666667 | 83 | 0.420579 | [
"MIT"
] | KoyashiroKohaku/AtCoder | csharp/abs/11_ABC086C/Program.cs | 1,001 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace NModbusTCP.Pages
{
public class ErrorModel : PageModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
| 25.791667 | 92 | 0.696284 | [
"MIT"
] | tilizi/NModbus | NModbusTCP/Pages/Error.cshtml.cs | 619 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsKernelBrowserUI
{
class CTLCodeUtility
{
public static int GetCTLCode(DeviceType deviceType, int Function, MethodType Method, AccessType Access)
{
return ((int)deviceType << 16) | ((int)Access << 14) | (Function << 2) | (int)Method;
}
}
enum DeviceType : int
{
FILE_DEVICE_UNKNOWN = 0x00000022
}
enum MethodType : int
{
METHOD_BUFFERED = 0,
METHOD_IN_DIRECT = 1,
METHOD_OUT_DIRECT = 2,
METHOD_NEITHER = 3,
}
enum AccessType : int
{
FILE_ANY_ACCESS = 0,
FILE_READ_ACCESS = 1,// file & pipe
FILE_WRITE_ACCESS = 2, // file & pipe
}
}
| 22.694444 | 111 | 0.607099 | [
"MIT"
] | tlsnns/WindowsKernelBrowser | src/WindowsKernelBrowser/WindowsKernelBrowserUI/CTLCodeUtility.cs | 819 | C# |
using System;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Owin;
using BugTrackerUI.Models;
namespace BugTrackerUI
{
public partial class Startup
{
// For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
// Enables the application to remember the second login verification factor such as phone or email.
// Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
// This is similar to the RememberMe option when you log in.
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
//app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
//{
// ClientId = "",
// ClientSecret = ""
//});
}
}
} | 50.867647 | 160 | 0.658861 | [
"MIT"
] | VeronikaDmytryk/BugTracker | BugTrackerApp/BugTrackerUI/App_Start/Startup.Auth.cs | 3,461 | 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("TransferViewTemplate")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HP Inc.")]
[assembly: AssemblyProduct("TransferViewTemplate")]
[assembly: AssemblyCopyright("Copyright © HP Inc. 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d38b45d3-413f-4134-818b-754a0e7920bf")]
// 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.432432 | 84 | 0.750352 | [
"MIT"
] | angelrps/ARP_Toolkit | 2020/TransferViewTemplates/VS_TransferViewTemplate/Properties/AssemblyInfo.cs | 1,425 | C# |
using System;
namespace NeoBoilerplate.Domain.Common
{
public class AuditableEntity
{
public string? CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
public string? LastModifiedBy { get; set; }
public DateTime? LastModifiedDate { get; set; }
}
}
| 23.769231 | 55 | 0.640777 | [
"Apache-2.0"
] | NeoShivam/NeoBoilerplate-v6.0 | src/Core/NeoBoilerplate.Domain/Common/AuditableEntity.cs | 311 | C# |
/*******************************************************************************
* Copyright 2009-2019 Amazon Services. 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://aws.amazon.com/apache2.0
* 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.
*******************************************************************************
* List Financial Events By Next Token Request
* API Version: 2015-05-01
* Library Version: 2019-02-25
* Generated: Wed Mar 13 08:17:08 PDT 2019
*/
using AmazonAccess.Services.Common;
namespace AmazonAccess.Services.Finances.Model
{
public class ListFinancialEventsByNextTokenRequest : AbstractMwsObject
{
private string _sellerId;
private string _mwsAuthToken;
private string _nextToken;
/// <summary>
/// Gets and sets the SellerId property.
/// </summary>
public string SellerId
{
get { return this._sellerId; }
set { this._sellerId = value; }
}
/// <summary>
/// Sets the SellerId property.
/// </summary>
/// <param name="sellerId">SellerId property.</param>
/// <returns>this instance.</returns>
public ListFinancialEventsByNextTokenRequest WithSellerId( string sellerId )
{
this._sellerId = sellerId;
return this;
}
/// <summary>
/// Checks if SellerId property is set.
/// </summary>
/// <returns>true if SellerId property is set.</returns>
public bool IsSetSellerId()
{
return this._sellerId != null;
}
/// <summary>
/// Gets and sets the MWSAuthToken property.
/// </summary>
public string MWSAuthToken
{
get { return this._mwsAuthToken; }
set { this._mwsAuthToken = value; }
}
/// <summary>
/// Sets the MWSAuthToken property.
/// </summary>
/// <param name="mwsAuthToken">MWSAuthToken property.</param>
/// <returns>this instance.</returns>
public ListFinancialEventsByNextTokenRequest WithMWSAuthToken( string mwsAuthToken )
{
this._mwsAuthToken = mwsAuthToken;
return this;
}
/// <summary>
/// Checks if MWSAuthToken property is set.
/// </summary>
/// <returns>true if MWSAuthToken property is set.</returns>
public bool IsSetMWSAuthToken()
{
return this._mwsAuthToken != null;
}
/// <summary>
/// Gets and sets the NextToken property.
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
/// <summary>
/// Sets the NextToken property.
/// </summary>
/// <param name="nextToken">NextToken property.</param>
/// <returns>this instance.</returns>
public ListFinancialEventsByNextTokenRequest WithNextToken( string nextToken )
{
this._nextToken = nextToken;
return this;
}
/// <summary>
/// Checks if NextToken property is set.
/// </summary>
/// <returns>true if NextToken property is set.</returns>
public bool IsSetNextToken()
{
return this._nextToken != null;
}
public override void ReadFragmentFrom( IMwsReader reader )
{
_sellerId = reader.Read< string >( "SellerId" );
_mwsAuthToken = reader.Read< string >( "MWSAuthToken" );
_nextToken = reader.Read< string >( "NextToken" );
}
public override void WriteFragmentTo( IMwsWriter writer )
{
writer.Write( "SellerId", _sellerId );
writer.Write( "MWSAuthToken", _mwsAuthToken );
writer.Write( "NextToken", _nextToken );
}
public override void WriteTo( IMwsWriter writer )
{
writer.Write( "http://mws.amazonservices.com/Finances/2015-05-01", "ListFinancialEventsByNextTokenRequest", this );
}
public ListFinancialEventsByNextTokenRequest( string nextToken ) : base() {
this._nextToken = nextToken;
}
public ListFinancialEventsByNextTokenRequest() : base()
{
}
}
} | 28.41844 | 118 | 0.662091 | [
"BSD-3-Clause"
] | skuvault-integrations/amazonAccess | src/AmazonAccess/Services/Finances/Model/ListFinancialEventsByNextTokenRequest.cs | 4,007 | C# |
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Harrison314.EntityFrameworkCore.Encryption
{
public class DbContextEncryptedProviderOptions<TDbContext>
where TDbContext : DbContext
{
public Func<IServiceProvider, TDbContext>? DbContextFactory
{
get;
set;
}
public Action<TDbContext>? DbContextCreanup
{
get;
set;
}
public TimeSpan? EncryptionContextExpirtaion
{
get;
set;
}
public DbContextEncryptedProviderOptions()
{
this.DbContextFactory = null;
this.DbContextCreanup = null;
this.EncryptionContextExpirtaion = null;
}
}
}
| 22.307692 | 67 | 0.604598 | [
"MIT"
] | harrison314/Harrison314.EntityFrameworkCore.Encryption | src/src/Harrison314.EntityFrameworkCore.Encryption/DbContextEncryptedProviderOptions.cs | 872 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
namespace MessengerLibrary
{
public class Message
{
public DateTime TimeSend { get; set; }
public string Text { get; set; }
public int Sender { get; set; }
public string Sender_Nickname { get; set; }
public Message(DateTime timesend, string text, int sender, string sender_nickname)
{
this.TimeSend = timesend;
this.Text = text;
this.Sender = sender;
this.Sender_Nickname = sender_nickname;
}
public Message() { }
/// <summary>
/// Преобразует объект в Json
/// </summary>
/// <returns></returns>
public string ToJson() =>
JsonSerializer.Serialize(this, new JsonSerializerOptions() { WriteIndented = true });
/// <summary>
/// реобразует из Json в объект
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static Message FromJson(string value) =>
JsonSerializer.Deserialize<Message>(value, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
/// <summary>
/// Преобразует объект в Json и сохраняет в файл
/// </summary>
/// <param name="path"></param>
public void ToJsonFile(string path) =>
File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), path), this.ToJson());
/// <summary>
/// Считывает из файла json и преобразует в объект
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static Message FromJsonFile(string path) =>
FromJson(File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), path)));
}
}
| 33.714286 | 123 | 0.592691 | [
"Apache-2.0"
] | atom20000/Messenger | MessengerLibrary/Message.cs | 1,995 | C# |
using UnityEditor;
using UnityEngine;
using System.Collections;
class CreatePrefabFromSelected : ScriptableObject
{
const string menuTitle = "GameObject/Create Prefab From Selected";
/// <summary>
/// Creates a prefab from the selected game object.
/// </summary>
[MenuItem(menuTitle)]
static void CreatePrefab()
{
var objs = Selection.gameObjects;
string pathBase = EditorUtility.SaveFolderPanel("Choose save folder", "Assets", "");
if (!string.IsNullOrEmpty(pathBase))
{
pathBase = pathBase.Remove(0, pathBase.IndexOf("Assets")) + "/";
foreach (var go in objs)
{
string localPath = pathBase + go.name + ".prefab";
if (AssetDatabase.LoadAssetAtPath(localPath, typeof(GameObject)))
{
if (EditorUtility.DisplayDialog("Are you sure?",
"The prefab already exists. Do you want to overwrite it?",
"Yes",
"No"))
CreateNew(go, localPath);
}
else
CreateNew(go, localPath);
}
}
}
static void CreateNew(GameObject obj, string localPath)
{
Object prefab = PrefabUtility.CreatePrefab(localPath, obj);
PrefabUtility.ReplacePrefab(obj, prefab, ReplacePrefabOptions.ConnectToPrefab);
AssetDatabase.Refresh();
}
/// <summary>
/// Validates the menu.
/// </summary>
/// <remarks>The item will be disabled if no game object is selected.</remarks>
[MenuItem(menuTitle, true)]
static bool ValidateCreatePrefab()
{
return Selection.activeGameObject != null;
}
} | 30.586207 | 92 | 0.568771 | [
"MIT"
] | DennisTDev/HackPrinceton | Assets/Editor/Procedural Low Poly Cities/Editor/CreatePrefabFromSelected.cs | 1,776 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Web;
using AutoMapper;
using NHS111.Business.ITKDispatcher.Api.ITKDispatcherSOAPService;
using NHS111.Business.ITKDispatcher.Api.Mappings;
using StructureMap;
using StructureMap.Graph;
using AutoMapperWebConfiguration = NHS111.Business.ITKDispatcher.Api.Mappings.AutoMapperWebConfiguration;
namespace NHS111.Business.ITKDispatcher.Api.IoC
{
public class ItkDispatcherApiRegistry : Registry
{
public ItkDispatcherApiRegistry()
{
var configuration = new Configuration.Configuration();
For<MessageEngine>().Use(new MessageEngineClient(new BasicHttpBinding(BasicHttpSecurityMode.Transport), new EndpointAddress(configuration.EsbEndpointUrl)));
For<IMappingEngine>().Use(() => Mapper.Engine);
AutoMapperWebConfiguration.Configure();
Scan(scan =>
{
scan.TheCallingAssembly();
scan.WithDefaultConventions();
});
}
}
} | 35.7 | 168 | 0.710551 | [
"Apache-2.0"
] | NHSChoices/nhs111-online | NHS111/NHS111.Business.ITKDispatcher.Api/IoC/ItkDispatcherApiRegistry.cs | 1,073 | C# |
/*
* Copyright (c) 2019-2021 Angouri.
* AngouriMath is licensed under MIT.
* Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
* Website: https://am.angouri.org.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using AngouriMath.Core;
using AngouriMath.Core.HashCode;
using AngouriMath.Extensions;
namespace AngouriMath
{
partial record Entity
{
#pragma warning disable CS1591 // TODO: add docs for records' arguments
/// <summary>
/// That is a node which equals Expression if Predicate is true, otherwise <see cref="MathS.NaN"/>
/// </summary>
public sealed partial record Providedf(Entity Expression, Entity Predicate) : Entity
{
internal Providedf New(Entity expression, Entity predicate)
=> ReferenceEquals(expression, Expression) && ReferenceEquals(predicate, Predicate) ? this :
new Providedf(expression, predicate);
/// <inheritdoc/>
public override Entity Replace(Func<Entity, Entity> func)
=> func(New(func(Expression), func(Predicate)));
internal override Priority Priority => Priority.Provided;
/// <inheritdoc/>
protected override Entity[] InitDirectChildren() => new[] { Expression, Predicate };
}
/// <summary>
/// This is a node which defined on different subsets differently. When evaluating, it will turn
/// into a particular case once all cases' predicates before are false, and this case's predicate is true.
///
/// That is, the order counts. An example:
/// Piecewise(a provided false, b provided true, c provided true)
/// Will be evaluated into b,
///
/// Piecewise(a provided false, b provided c, c provided false)
/// Will remain as it is (although unreachable cases will be removed)
/// </summary>
public sealed partial record Piecewise : Entity, IEquatable<Piecewise>
{
public IEnumerable<Providedf> Cases => cases;
private readonly IEnumerable<Providedf> cases = Enumerable.Empty<Providedf>();
// internal override Priority Priority => Priority.Provided;
/// <inheritdoc/>
protected override Entity[] InitDirectChildren() => Cases.Select(c => (c.Expression, c.Predicate)).ConcatTuples().ToArray();
internal Piecewise New(IEnumerable<Providedf> newCases)
=> (Cases, newCases).SequencesAreEqualReferences() ? this : new Piecewise(newCases);
/// <summary>
/// Creates an instance of Piecewise
/// </summary>
/// <param name="cases">
/// This is an ordered sequence of <see cref="Providedf"/>
/// </param>
public Piecewise(IEnumerable<Providedf> cases)
=> this.cases = cases;
public Piecewise Apply(Func<Providedf, Providedf> func)
=> New(Cases.Select(func));
internal override Priority Priority => Priority.Leaf;
/// <inheritdoc/>
public override Entity Replace(Func<Entity, Entity> func)
=> func(New(Cases.Select(c => c.New(func(c.Expression), func(c.Predicate)))));
/// <summary>
/// Checks that two Piecewise are equal
/// If one is not Piecewise, the method returns false
/// </summary>
public bool Equals(Piecewise other)
{
if (other is null)
return false;
if (Cases.Count() != other.Cases.Count())
return false;
foreach (var (l, r) in (Cases, other.Cases).Zip())
if (l != r)
return false;
return true;
}
/// <inheritdoc/>
public override int GetHashCode()
=> Cases.HashCodeOfSequence(HashCodeFunctional.HashCodeShifts.Piecewise);
/// <summary>
/// Applies the given transformation to every expression of each case
/// Predicates, however, remain unchanged
/// </summary>
public Piecewise ApplyToValues(Func<Entity, Entity> transformation)
=> Cases.Select(c => c.New(transformation(c.Expression), c.Predicate)).ToPiecewise();
}
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
}
}
| 40.553571 | 136 | 0.590929 | [
"MIT"
] | KuhakuPixel/AngouriMath | Sources/AngouriMath/Core/Entity/Omni/Entity.Piecewise.cs | 4,544 | C# |
using System;
using System.Collections.Generic;
namespace ExtremeAndy.CombinatoryFilters
{
public interface IFilterNode : IEquatable<IFilterNode>
{
bool IsCollapsed { get; }
/// <summary>
/// As for <see cref="IEquatable{T}.Equals"/>, but uses an unordered set comparison
/// operation which ignores duplicates and order of nodes.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
bool IsEquivalentTo(IFilterNode other);
IFilterNode Collapse();
/// <summary>
/// Returns <see langword="true" /> if the filter is will always evaluate to <see langword="true" />
/// regardless of the input, i.e. the filter is trivial and will include everything.
///
/// Returns <see langword="false" /> if it is not known whether the filter will evaluate to <see langword="true" />
/// until an input is tested.
///
/// Note that <see cref="IsTrue"/> returning <see langword="false" /> does *not* automatically imply that
/// <see cref="IsFalse"/> will return <see langword="true" />.
/// </summary>
/// <returns></returns>
bool IsTrue();
/// <summary>
/// Returns <see langword="true" /> if the filter is will always evaluate to <see langword="false" />
/// regardless of the input, i.e. the filter is trivial and will include nothing.
///
/// Returns <see langword="false" /> if it is not known whether the filter will evaluate to <see langword="false" />
/// until an input is tested.
///
/// Note that <see cref="IsFalse"/> returning <see langword="false" /> does *not* automatically imply that
/// <see cref="IsTrue"/> will return <see langword="true" />.
/// </summary>
/// <returns></returns>
bool IsFalse();
}
public interface IFilterNode<out TFilter> : IFilterNode
{
TResult Aggregate<TResult>(
Func<TResult[], CombinationOperator, TResult> combine,
Func<TResult, TResult> invert,
Func<ILeafFilterNode<TFilter>, TResult> transform);
TResult Match<TResult>(
Func<ICombinationFilterNode<TFilter>, TResult> combine,
Func<IInvertedFilterNode<TFilter>, TResult> invert,
Func<ILeafFilterNode<TFilter>, TResult> transform);
IFilterNode<TResultFilter> Map<TResultFilter>(Func<TFilter, TResultFilter> mapFunc)
where TResultFilter : IFilter;
IFilterNode<TResultFilter> Bind<TResultFilter>(Func<TFilter, IFilterNode<TResultFilter>> bindFunc)
where TResultFilter : IFilter;
/// <summary>
/// Sort the nodes according to the supplied <see cref="FilterNodeComparer{TFilter}"/>.
/// </summary>
IFilterNode<TFilter> Sort(IComparer<IFilterNode<TFilter>> comparer);
IFilterNode<TFilter> Collapse();
bool Any(Func<TFilter, bool> predicate);
bool All(Func<TFilter, bool> predicate);
}
} | 40.342105 | 124 | 0.615134 | [
"MIT"
] | extremeandy/CombinatoryFilters | src/IFilterNode.cs | 3,068 | C# |
using System;
using System.Collections;
using System.Linq;
using Jint.Native;
using Jint.Native.Array;
using Jint.Runtime.Descriptors;
using Jint.Runtime.Descriptors.Specialized;
using Jint.Runtime.Interop;
namespace Knyaz.Optimus.Scripting.Jint.Internal
{
using Engine = global::Jint.Engine;
/// <summary>
/// List to JS Array adapter
/// </summary>
internal class ListAdapterEx : ArrayInstance, IObjectWrapper
{
private readonly Engine _engine;
private readonly IList _list;
public ListAdapterEx(Engine engine, IList list)
: base(engine)
{
_engine = engine;
_list = list is Array ? list.Cast<object>().ToList() : list;
Prototype = engine.Array;
}
public override void Put(string propertyName, JsValue value, bool throwOnError)
{
if (int.TryParse(propertyName, out var index))
{
//todo: resize the list if index is greater then count
if (_list.Count > index)
_list[index] = value.ToObject();
}
//base.Put(propertyName, value, throwOnError);
}
public override JsValue Get(string propertyName)
{
int index;
if (int.TryParse(propertyName, out index))
{
return _list.Count > index ? JsValue.FromObject(_engine, _list[index]) : JsValue.Undefined;
}
return base.Get(propertyName);
}
public override PropertyDescriptor GetOwnProperty(string propertyName)
{
if (Properties.ContainsKey(propertyName))
return Properties[propertyName];
if (propertyName == "length")
{
var p = new PropertyDescriptor(
new ClrFunctionInstance(_engine, (value, values) => _list.Count),
new ClrFunctionInstance(_engine, (value, values) =>
{
//todo: resize list
return value;
}));
Properties.Add(propertyName, p);
}
if (Target is Array)
{
return base.GetOwnProperty(propertyName);
}
var index = 0u;
if (uint.TryParse(propertyName, out index))
{
return new IndexDescriptor(Engine, propertyName, Target);
}
return base.GetOwnProperty(propertyName);
}
public object Target { get { return _list; } }
}
} | 23.5 | 95 | 0.690039 | [
"MIT"
] | RusKnyaz/Optimus | source/Knyaz.Optimus.Scripting.Jint/Internal/ListAdapter.cs | 2,070 | C# |
// Copyright © 2021 Matan Brightbert
//
// 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.Windows;
namespace Scrupdate.Classes.Objects
{
public class Settings
{
// Classes /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public class CachedSettings
{
// Enums ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public enum ProgramFilteringOption
{
Unknown,
All,
OnlyUpdates,
OnlyUpToDate,
OnlyAutomaticallyAdded,
OnlyManuallyAdded,
OnlyInstalled,
OnlyUninstalled,
OnlyValid,
OnlyInvalid,
OnlyNotChecked,
OnlyNotConfigured
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Properties //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public WindowState? LastWindowState { get; set; }
public Size? LastWindowSize { get; set; }
public Point? LastWindowLocation { get; set; }
public string LastHashOfAllInstalledPrograms { get; set; }
public bool LastProgramFilteringState { get; set; }
public ProgramFilteringOption LastProgramFilteringOption { get; set; }
public bool LastShowHiddenProgramsState { get; set; }
public DateTime LastProgramUpdatesCheckTime { get; set; }
public DateTime LastProgramUpdatesScheduledCheckAttemptionTime { get; set; }
public string LastChecksumOfInstalledGoogleChromeBrowserExecutableFile { get; set; }
public string LastDefaultChromeDriverUserAgentString { get; set; }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Constructors ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public CachedSettings()
{
LastWindowState = null;
LastWindowSize = null;
LastWindowLocation = null;
LastHashOfAllInstalledPrograms = "";
LastProgramFilteringState = false;
LastProgramFilteringOption = ProgramFilteringOption.Unknown;
LastShowHiddenProgramsState = false;
LastProgramUpdatesCheckTime = new DateTime();
LastProgramUpdatesScheduledCheckAttemptionTime = new DateTime();
LastChecksumOfInstalledGoogleChromeBrowserExecutableFile = "";
LastDefaultChromeDriverUserAgentString = "";
}
public CachedSettings(WindowState? lastWindowState, Size? lastWindowSize, Point? lastWindowLocation, string lastHashOfAllInstalledPrograms, bool lastProgramFilteringState, ProgramFilteringOption lastProgramFilteringOption, bool lastShowHiddenProgramsState, DateTime lastProgramUpdatesCheckTime, DateTime lastProgramUpdatesScheduledCheckAttemptionTime, string lastChecksumOfInstalledGoogleChromeBrowserExecutableFile, string lastDefaultChromeDriverUserAgentString)
{
LastWindowState = lastWindowState;
LastWindowSize = lastWindowSize;
LastWindowLocation = lastWindowLocation;
LastHashOfAllInstalledPrograms = lastHashOfAllInstalledPrograms;
LastProgramFilteringState = lastProgramFilteringState;
LastProgramFilteringOption = lastProgramFilteringOption;
LastShowHiddenProgramsState = lastShowHiddenProgramsState;
LastProgramUpdatesCheckTime = lastProgramUpdatesCheckTime;
LastProgramUpdatesScheduledCheckAttemptionTime = lastProgramUpdatesScheduledCheckAttemptionTime;
LastChecksumOfInstalledGoogleChromeBrowserExecutableFile = lastChecksumOfInstalledGoogleChromeBrowserExecutableFile;
LastDefaultChromeDriverUserAgentString = lastDefaultChromeDriverUserAgentString;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
public class GlobalSettings
{
// Enums ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public enum WeekDays
{
None = 0,
Sunday = 1,
Monday = (1 << 1),
Tuesday = (1 << 2),
Wednesday = (1 << 3),
Thursday = (1 << 4),
Friday = (1 << 5),
Saturday = (1 << 6)
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Properties //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public bool EnableScanningForInstalledPrograms { get; set; }
public bool ScanForInstalledProgramsAutomaticallyOnStart { get; set; }
public bool RememberLastProgramListOptions { get; set; }
public bool EnableScheduledCheckForProgramUpdates { get; set; }
public WeekDays ProgramUpdatesScheduledCheckDays { get; set; }
public int ProgramUpdatesScheduledCheckHour { get; set; }
public bool IncludeHiddenProgramsInProgramUpdatesScheduledCheckResults { get; set; }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Constructors ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public GlobalSettings()
{
EnableScanningForInstalledPrograms = true;
ScanForInstalledProgramsAutomaticallyOnStart = true;
RememberLastProgramListOptions = false;
EnableScheduledCheckForProgramUpdates = false;
ProgramUpdatesScheduledCheckDays = WeekDays.None;
ProgramUpdatesScheduledCheckHour = 0;
IncludeHiddenProgramsInProgramUpdatesScheduledCheckResults = false;
}
public GlobalSettings(bool enableScanningForInstalledPrograms, bool scanForInstalledProgramsAutomaticallyOnStart, bool rememberLastProgramListOptions, bool enableScheduledCheckForProgramUpdates, WeekDays programUpdatesScheduledCheckDays, int programUpdatesScheduledCheckHour, bool includeHiddenProgramsInProgramUpdatesScheduledCheckResults)
{
EnableScanningForInstalledPrograms = enableScanningForInstalledPrograms;
ScanForInstalledProgramsAutomaticallyOnStart = scanForInstalledProgramsAutomaticallyOnStart;
RememberLastProgramListOptions = rememberLastProgramListOptions;
EnableScheduledCheckForProgramUpdates = enableScheduledCheckForProgramUpdates;
ProgramUpdatesScheduledCheckDays = programUpdatesScheduledCheckDays;
ProgramUpdatesScheduledCheckHour = programUpdatesScheduledCheckHour;
IncludeHiddenProgramsInProgramUpdatesScheduledCheckResults = includeHiddenProgramsInProgramUpdatesScheduledCheckResults;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
public class AppearanceSettings
{
// Properties //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public double WindowsScalingFactor { get; set; }
public int MinimumVersionSegments { get; set; }
public int MaximumVersionSegments { get; set; }
public bool RemoveTrailingZeroSegmentsOfVersions { get; set; }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Constructors ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public AppearanceSettings()
{
WindowsScalingFactor = 0.0D;
MinimumVersionSegments = 2;
MaximumVersionSegments = 4;
RemoveTrailingZeroSegmentsOfVersions = true;
}
public AppearanceSettings(double windowsScalingFactor, int minimumVersionSegments, int maximumVersionSegments, bool removeTrailingZeroSegmentsOfVersions)
{
WindowsScalingFactor = windowsScalingFactor;
MinimumVersionSegments = minimumVersionSegments;
MaximumVersionSegments = maximumVersionSegments;
RemoveTrailingZeroSegmentsOfVersions = removeTrailingZeroSegmentsOfVersions;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
public class ChromeDriverSettings
{
// Enums ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public enum ChromeDriverPageLoadTimeout
{
NoTimeout,
After1Seconds,
After3Seconds,
After5Seconds,
After10Seconds,
After15Seconds,
After30Seconds,
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Properties //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public ChromeDriverPageLoadTimeout PageLoadTimeout { get; set; }
public bool UseCustomUserAgentString { get; set; }
public string CustomUserAgentString { get; set; }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Constructors ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public ChromeDriverSettings()
{
PageLoadTimeout = ChromeDriverPageLoadTimeout.After15Seconds;
UseCustomUserAgentString = false;
CustomUserAgentString = "";
}
public ChromeDriverSettings(ChromeDriverPageLoadTimeout pageLoadTimeout, bool useCustomUserAgentString, string customUserAgentString)
{
PageLoadTimeout = pageLoadTimeout;
UseCustomUserAgentString = useCustomUserAgentString;
CustomUserAgentString = customUserAgentString;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Properties //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public CachedSettings Cached { get; set; }
public GlobalSettings Global { get; set; }
public AppearanceSettings Appearance { get; set; }
public ChromeDriverSettings ChromeDriver { get; set; }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Constructors ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public Settings()
{
Cached = new CachedSettings();
Global = new GlobalSettings();
Appearance = new AppearanceSettings();
ChromeDriver = new ChromeDriverSettings();
}
public Settings(CachedSettings cached, GlobalSettings global, AppearanceSettings appearance, ChromeDriverSettings chromeDriver)
{
Cached = cached;
Global = global;
Appearance = appearance;
ChromeDriver = chromeDriver;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
| 59.040486 | 475 | 0.434959 | [
"Apache-2.0",
"MIT"
] | matanbright/Scrupdate | Scrupdate/Classes/Objects/Settings.cs | 14,586 | C# |
using System;
using System.Collections.Generic;
using SciChart.UI.Bootstrap.Utility;
namespace SciChart.UI.Bootstrap
{
public class AttributedTypeDiscoveryService : IAttributedTypeDiscoveryService
{
private static ILogFacade Log = LogManagerFacade.GetLogger(typeof(AttributedTypeDiscoveryService));
private static readonly IDictionary<Type, IEnumerable<Type>> CachedTypesByAttributeType = new Dictionary<Type, IEnumerable<Type>>();
private readonly IAssemblyDiscovery _assemblyDiscovery;
public AttributedTypeDiscoveryService(IAssemblyDiscovery assemblyDiscovery)
{
_assemblyDiscovery = assemblyDiscovery;
}
public IEnumerable<Type> DiscoverAttributedTypes<T>() where T : Attribute
{
var attributeType = typeof(T);
if (CachedTypesByAttributeType.ContainsKey(attributeType))
return CachedTypesByAttributeType[attributeType];
Log.InfoFormat("Discovering Types with Attribute {0}", attributeType);
var allTypes = new List<Type>();
foreach (var assembly in _assemblyDiscovery.GetAssemblies())
{
allTypes.AddRange(ReflectionUtil.DiscoverTypesWithAttribute(attributeType, assembly));
}
var attributedTypes = allTypes.ToArray();
CachedTypesByAttributeType.Add(attributeType, attributedTypes);
return attributedTypes;
}
}
} | 37.74359 | 140 | 0.693614 | [
"Apache-2.0"
] | ABTSoftware/SciChart.Wpf.UI | SciChart.UI.Bootstrap/AttributedTypeDiscoveryService.cs | 1,474 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// O código foi gerado por uma ferramenta.
// Versão de Tempo de Execução:4.0.30319.42000
//
// As alterações ao arquivo poderão causar comportamento incorreto e serão perdidas se
// o código for gerado novamente.
// </auto-generated>
//------------------------------------------------------------------------------
namespace TesteSession.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.1.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;
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
[global::System.Configuration.DefaultSettingValueAttribute("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Agenda;Integrated Security=Tru" +
"e")]
public string AgendaConnectionString {
get {
return ((string)(this["AgendaConnectionString"]));
}
}
}
}
| 44.973684 | 153 | 0.623757 | [
"MIT"
] | vilsonmoro/curso-csharp | windowsForms/TesteSession/Properties/Settings.Designer.cs | 1,720 | C# |
namespace MainApp.Samples
{
public class SampleDto
{
public int Value { get; set; }
}
} | 15.428571 | 38 | 0.583333 | [
"MIT"
] | antosubash/abp-add-module-bug | src/MainApp.Application.Contracts/Samples/SampleDto.cs | 110 | 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("azure-sql-cs")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("azure-sql-cs")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c4b2cd69-be82-4d5e-8c59-0e612a8faeae")]
// 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.742305 | [
"MIT"
] | firehouse/azure-camp-dec | demo/sql-demo/azure-sql-cs/azure-sql-cs/Properties/AssemblyInfo.cs | 1,400 | C# |
using System;
using JetBrains.Annotations;
namespace CSharp.Rop.GenericResult
{
public static partial class ResultExtensions
{
public static TK Match<TK, T>(this Result<T> result, [NotNull] Func<T, TK> onSuccessHasValue, [NotNull] Func<TK> onSuccessIsNone, [NotNull] Func<Error, TK> onFailure)
{
return result.IsFailure ? onFailure(result.Error)
: result.HasValue ? onSuccessHasValue(result.Value)
: onSuccessIsNone();
}
public static T Match<T>(this Result result, [NotNull] Func<T> onSuccess, [NotNull] Func<Error, T> onFailure)
{
return result.IsSuccess
? onSuccess()
: onFailure(result.Error);
}
public static void Match<T>(this Result<T> result, [NotNull] Action<T> onSuccessHasValue, [NotNull] Action onSuccessIsNone, [NotNull] Action<Error> onFailure)
{
if (result.IsFailure)
onFailure(result.Error);
else if (result.HasValue)
onSuccessHasValue(result.Value);
else
onSuccessIsNone();
}
public static void Match(this Result result, [NotNull] Action onSuccess, [NotNull] Action<Error> onFailure)
{
if (result.IsSuccess)
onSuccess();
else
onFailure(result.Error);
}
}
}
| 34.512195 | 174 | 0.584452 | [
"MIT"
] | rferstl/CSharp.Rop.Generic.Result | CSharp.Rop.GenericResult/Result/Match.cs | 1,415 | 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.
// </auto-generated>
//------------------------------------------------------------------------------
namespace admin.Settings {
public partial class Advanced {
/// <summary>
/// TabMenu control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::admin.Settings.Menu TabMenu;
/// <summary>
/// rblWwwSubdomain control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RadioButtonList rblWwwSubdomain;
/// <summary>
/// cbEnableCompression control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox cbEnableCompression;
/// <summary>
/// cbEnableOptimization control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox cbEnableOptimization;
/// <summary>
/// cbCompressWebResource control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox cbCompressWebResource;
/// <summary>
/// cbEnableOpenSearch control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox cbEnableOpenSearch;
/// <summary>
/// cbRequireSslForMetaWeblogApi control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox cbRequireSslForMetaWeblogApi;
/// <summary>
/// cbEnableErrorLogging control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox cbEnableErrorLogging;
/// <summary>
/// txtGalleryFeed control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtGalleryFeed;
/// <summary>
/// cbEnablePasswordReset control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox cbEnablePasswordReset;
/// <summary>
/// cbEnableSelfRegistration control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox cbEnableSelfRegistration;
/// <summary>
/// ddlSelfRegistrationInitialRole control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddlSelfRegistrationInitialRole;
/// <summary>
/// cbCreateBlogOnSelfRegistration control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox cbCreateBlogOnSelfRegistration;
/// <summary>
/// txtRemoteTimeout control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtRemoteTimeout;
/// <summary>
/// txtRemoteMaxFileSize control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtRemoteMaxFileSize;
/// <summary>
/// cbAllowRemoteFileDownloads control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox cbAllowRemoteFileDownloads;
/// <summary>
/// btnDownloadArchive control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnDownloadArchive;
/// <summary>
/// ddlProvider control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddlProvider;
/// <summary>
/// btnChangeProvider control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnChangeProvider;
/// <summary>
/// hdnProvider control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.HiddenField hdnProvider;
/// <summary>
/// providerError control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label providerError;
}
}
| 37.04878 | 96 | 0.564714 | [
"MIT"
] | blee-usa/BlogEngine28 | admin/Settings/Advanced.aspx.designer.cs | 7,597 | C# |
/*
MIT License
Copyright (c) 2019
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Linq;
using Adventure.GameEngine.Interfaces;
using Adventure.TextProcessing.Interfaces;
using Adventure.TextProcessing.Synonyms;
using DefaultEcs;
using JetBrains.Annotations;
namespace Adventure.GameEngine
{
/// <summary>
/// An adventure game is comprised of multiple rooms that are linked together that the player can navigate around.
/// This class represents one of those rooms and the exits that link to other rooms.
/// </summary>
[PublicAPI]
public abstract class Room : IRoom
{
private readonly IRoomExits _roomExits;
private string _description;
public Entity Self { get; }
/// <summary>
/// The name of the room.
/// </summary>
public string Name { get; }
/// <summary>
/// The description that is returned when the LightsOn flag us set to False.
/// </summary>
public string LightsOffDescription { get; }
/// <summary>
/// An internal reference to the main Game object.
/// </summary>
public IGame Game => Self.Get<IGame>();
/// <summary>
/// A list of objects that have been dropped in a room.
/// </summary>
public IDroppedObjects DroppedObjects { get; }
/// <summary>
/// This flag indicates if the lights are on in the room. You can use this as a game play mechanic so metaphorically
/// dim the lights.
/// </summary>
public bool LightsOn { get; set;}
/// <summary>
/// Gets or sets the visited rooms.
/// </summary>
/// <value>The visited rooms.</value>
public IVisitedRooms VisitedRooms => Game.VisitedRooms;
///// <summary>
///// Default Constructor to setup the initial room state.
///// </summary>
//public Room()
//{
// Name = string.Empty;
// Description = string.Empty;
// LightsOn = true;
// DroppedObjects = new DroppedObjects(Game);
//}
///// <summary>
///// Constructor to setup the initial room state.
///// </summary>
///// <param name="game">An instance of the main Game object.</param>
//public Room(IGame game)
//{
// Name = string.Empty;
// Description = string.Empty;
// Game = game;
// LightsOn = true;
// DroppedObjects = new DroppedObjects(Game);
//}
///// <summary>
///// Constructor to setup the initial room state.
///// </summary>
///// <param name="roomExits">This object contains the references to the exits for the room which define what
///// rooms the exits point too.</param>
///// <param name="game">An instance of the main Game object.</param>
//public Room(IRoomExits roomExits, IGame game)
//{
// Name = string.Empty;
// Description = string.Empty;
// _roomExits = roomExits;
// Game = game;
// LightsOn = true;
// DroppedObjects = new DroppedObjects(Game);
//}
/// <summary>
/// Constructor to setup the initial room state.
/// </summary>
/// <param name="name">Name of the room.</param>
/// <param name="description">Description of the room.</param>
/// <param name="self">Reference to the game object.</param>
/// <exception cref="ArgumentNullException">If the name or description are null or empty then throw
/// an ArgumentNullException.</exception>
protected Room(string name, string description, Entity self)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException(nameof(Name), "The room name can not be empty.");
if (string.IsNullOrEmpty(description))
throw new ArgumentNullException(nameof(Description), "The room description can not be empty.");
Name = name;
Description = description;
Self = self;
LightsOn = true;
DroppedObjects = new DroppedObjects(Game);
_roomExits = new RoomExits(self);
}
/// <summary>
/// Get and Set the description for the room. The Getter will return a descriptin based on whether the lightsOn
/// flag is set.
/// </summary>
public string Description
{
get => !LightsOn ? LightsOffDescription : _description;
set => _description = value;
}
/// <summary>
/// Add an exit to the the room by specifying the direction and the room to exit too.
/// </summary>
/// <param name="direction">The direction that the exit is linked too.</param>
/// <param name="roomEnt">The room that the exit leads too.</param>
/// <param name="withExit">If this is set to True, then the room you specify will have an exit back to this current
/// room.</param>
public void AddExit(Direction direction, Entity roomEnt, bool withExit = true)
{
_roomExits.AddExit(direction, roomEnt);
if (!withExit)
return;
var room = roomEnt.Get<IRoom>();
switch (direction)
{
case Direction.North:
room.AddExit(Direction.South, Self, false);
break;
case Direction.South:
room.AddExit(Direction.North, Self, false);
break;
case Direction.East:
room.AddExit(Direction.West, Self, false);
break;
case Direction.West:
room.AddExit(Direction.East, Self, false);
break;
case Direction.NorthEast:
room.AddExit(Direction.SouthWest, Self, false);
break;
case Direction.SouthEast:
room.AddExit(Direction.NorthWest, Self, false);
break;
case Direction.NorthWest:
room.AddExit(Direction.SouthEast, Self, false);
break;
case Direction.SouthWest:
room.AddExit(Direction.NorthEast, Self, false);
break;
case Direction.Up:
room.AddExit(Direction.Down, Self, false);
break;
case Direction.Down:
room.AddExit(Direction.Up, Self, false);
break;
default:
throw new ArgumentOutOfRangeException(nameof(direction), direction, null);
}
}
/// <summary>
/// Add an exit by specifying a DoorWay object.
/// </summary>
/// <param name="doorway">A doorway definition object.</param>
/// <param name="room">The room that the exit leads too.</param>
/// <param name="withExit">If this is set to True, then the room you specify will have an exit back to this current
/// room.</param>
public void AddExit(DoorWay doorway, Entity room, bool withExit = true)
{
_roomExits.AddExit(doorway, room);
if (!withExit)
{
return;
}
DoorWay door;
switch (doorway.Direction)
{
case Direction.North:
door = DoorWay.FromDirection(Self, Direction.South);
break;
case Direction.South:
door = DoorWay.FromDirection(Self, Direction.North);
break;
case Direction.East:
door = DoorWay.FromDirection(Self, Direction.West);
break;
case Direction.West:
door = DoorWay.FromDirection(Self, Direction.East);
break;
case Direction.NorthEast:
door = DoorWay.FromDirection(Self, Direction.SouthWest);
break;
case Direction.SouthEast:
door = DoorWay.FromDirection(Self, Direction.NorthWest);
break;
case Direction.NorthWest:
door = DoorWay.FromDirection(Self, Direction.SouthEast);
break;
case Direction.SouthWest:
door = DoorWay.FromDirection(Self, Direction.NorthEast);
break;
case Direction.Up:
door = DoorWay.FromDirection(Self, Direction.Down);
break;
case Direction.Down:
door = DoorWay.FromDirection(Self, Direction.Up);
break;
default:
throw new ArgumentOutOfRangeException();
}
room.Get<IRoom>().AddExit(door, Self, false);
}
/// <summary>
/// Return a door way assigned to this room for a specific direction.
/// </summary>
/// <param name="direction">The direction to get the door way for.</param>
/// <returns>The doorway assigned to the room for the specified direction.</returns>
public DoorWay GetDoorWay(Direction direction)
{
return _roomExits.GetDoorWay(direction);
}
/// <summary>
/// Set whether you want the door locked for a specific direction.
/// </summary>
/// <param name="locked">True if you want to door locked, or False otherwise.</param>
/// <param name="direction">The direction you want to set the door lock for.</param>
public void SetDoorLock(bool locked, Direction direction)
{
_roomExits.SetDoorLock(locked, direction);
}
/// <summary>
/// Goto a room by specifying the direction noun, ie north, south, northeast etc.
/// </summary>
/// <returns>The room description message to display when switching rooms.</returns>
/// <param name="noun">Direction noun, ie north, south, northeast etc.</param>
public string GotoRoom(string noun)
{
if (string.IsNullOrEmpty(noun))
{
throw new ArgumentNullException(nameof(noun));
}
var direction = (Direction)Enum.Parse(typeof(Direction), noun, true);
var roomEnt = _roomExits.GetRoomForExit(direction);
if (!roomEnt.IsAlive)
return "There is no exit to the " + noun.ToLower() + ".";
var room = roomEnt.Get<IRoom>();
if (_roomExits.IsDoorLocked(direction))
return "The door is locked.";
Game.CurrentRoom = roomEnt;
Game.NumberOfMoves++;
Game.VisitedRooms.AddVisitedRoom(roomEnt);
if (string.IsNullOrEmpty(Game.Parser.Nouns.GetNounForSynonym(room.Name.ToLower())))
Game.Parser.Nouns.Add(room.Name.ToLower(), room.Name.ToLower());
var roomDescription = room.Description;
if (room.DroppedObjects.DroppedObjectsList.Count > 0)
roomDescription += "\r\n";
return room.DroppedObjects.DroppedObjectsList.Aggregate(roomDescription, (current, item) => current + ("\r\nThere is a " + item.Get<IObject>().Name + " on the floor."));
}
/// <summary>
/// The ProcessCommand method is called by the main game once the parser has run. This method will handle the following
/// functions:
/// - Navigation between rooms.
/// - Examining the room.
/// - Taking an object.
/// - Dropping an object.
/// - Giving hints.
///
/// If you want to add custom logic for a room you should create a superclass of Room and the override ProcessCommand
/// to add in customer handlers.
///
/// </summary>
/// <param name="command">The command object that was created by the parser.</param>
/// <returns>A text string to return to main caller.</returns>
public virtual string ProcessCommand(ICommand command)
{
if (command == null)
{
throw new ArgumentNullException(nameof(command));
}
switch (command.Verb)
{
case VerbCodes.Go:
{
try
{
return GotoRoom(command.Noun);
}
catch (ArgumentException)
{
Console.WriteLine();
return "Oops";
}
}
case VerbCodes.Look:
{
if (string.IsNullOrEmpty(command.Noun))
{
string roomDescription = Description;
if (DroppedObjects.DroppedObjectsList.Count > 0)
{
roomDescription += "\r\n";
foreach (var item in DroppedObjects.DroppedObjectsList)
{
roomDescription += "\r\nThere is a " + item.Get<IObject>().Name + " on the floor.";
}
}
return roomDescription;
}
if (Game.Player.Inventory.Exists(command.Noun))
{
var inventoryObject = Game.Player.Inventory.Get(command.Noun).Get<IObject>();
return !string.IsNullOrEmpty(inventoryObject.LongDescription) ? inventoryObject.LongDescription : inventoryObject.Description;
}
break;
}
case VerbCodes.NoCommand:
break;
case VerbCodes.Take:
if (string.IsNullOrEmpty(command.Noun))
{
return "You can't take that.";
}
if (DroppedObjects.PickUpDroppedObject(command.Noun))
{
return "You pick up the " + command.Noun + ".";
}
else
{
return "You can not pick up a " + command.Noun + ".";
}
case VerbCodes.Use:
if (string.IsNullOrEmpty(command.Noun))
{
return "You can't use that.";
}
if (!Game.Player.Inventory.Exists(command.Noun))
{
return "You do not have a " + command.Noun + ".";
}
break;
case VerbCodes.Drop:
if (string.IsNullOrEmpty(command.Noun))
{
return "You can't drop that.";
}
if (DroppedObjects.DropObject(command.Noun))
{
return "You drop the " + command.Noun + ".";
}
else
{
return "You do not have a " + command.Noun + " to drop.";
}
case VerbCodes.Hint:
if (Game.HintSystemEnabled)
{
switch (Game.Difficulty)
{
case DifficultyEnum.Easy:
return "There are no more hints available.";
case DifficultyEnum.Medium:
return "There are no more hints available.";
case DifficultyEnum.Hard:
return "Hints are not allowed for the Hard difficulty.";
default:
throw new ArgumentOutOfRangeException();
}
}
break;
case VerbCodes.Visit:
if (Game.VisitedRooms.CheckRoomVisited(command.Noun))
{
var roomEnt = Game.VisitedRooms.GetRoomInstance(command.Noun);
Game.CurrentRoom = roomEnt;
var room = roomEnt.Get<IRoom>();
var roomDescription = room.Description;
if (room.DroppedObjects.DroppedObjectsList.Count <= 0) return roomDescription;
roomDescription += "\r\n";
roomDescription = room.DroppedObjects.DroppedObjectsList
.Aggregate(roomDescription, (current, item) => current + ("\r\nThere is a " + item.Get<IObject>().Name + " on the floor."));
return roomDescription;
}
else
return "You can not visit this room as you have not previously been there.";
case VerbCodes.Eat:
if (string.IsNullOrEmpty(command.Noun))
return "I'm not hungry.";
if (!Game.Player.Inventory.Exists(command.Noun)) return "I'm not hungry.";
var consumableObjectEnt = Game.Player.Inventory.Get(command.Noun);
var consumableObject = consumableObjectEnt.Get<IObject>();
if (consumableObject.Edible)
{
if (!Game.Player.Inventory.RemoveObject(command.Noun)) return "I'm not hungry.";
var reply = consumableObject.EatenMessage;
foreach (var stat in consumableObject.StatsAdjustment)
{
Game.Player.PlayerStats.AddTo(stat.StatToModify, stat.PointsToApply);
reply += "\r\n" + "Player " +
stat.StatToModify.ToUpper() + " increased by " +
stat.PointsToApply + " points to : " + Game.Player.PlayerStats.Get(stat.StatToModify);
}
return reply;
}
else
{
return "You can't eat a " + command.Noun + ".";
}
default:
throw new ArgumentOutOfRangeException();
}
return string.Empty;
}
}
}
| 39.908367 | 181 | 0.508785 | [
"MIT"
] | Tauron1990/TextAdventure | Alt/Temp1/Room.cs | 20,034 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
namespace MedabotsRandomizer
{
public class BattleWrapper : Wrapper<Battle>
{
public BattleWrapper(int id, int memory_location, byte[] data) : base(id, memory_location, data)
{
}
public string FightId => ((byte)id).ToString("X2");
public string Memory_Location => (memory_location + 0x8000000).ToString("X8");
public string Character => IdTranslator.IdToCharacter(content.characterId);
public string Bot_1 => IdTranslator.IdToBot(content.bots[0].head);
public string Bot_2 => IdTranslator.IdToBot(content.bots[1].head);
public string Bot_3 => IdTranslator.IdToBot(content.bots[2].head);
}
}
| 34.863636 | 104 | 0.688396 | [
"MIT"
] | STulling/Medabots-Randomizer | MedabotsRandomizer/Wrappers/BattleWrapper.cs | 769 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HandyControl.Tools.Extension;
using me.cqp.luohuaming.CustomGacha.UI.Command;
using me.cqp.luohuaming.CustomGacha.UI.View;
using PublicInfos;
namespace me.cqp.luohuaming.CustomGacha.UI.ViewModel
{
class NewPoolStepViewModel : NotifyicationObject, IDialogResultable<Pool>
{
public NewPoolStepViewModel()
{
EditPool = new Pool() { GUID=Guid.NewGuid().ToString() };
Result = new Pool();
NextCmd = new DelegateCommand
{
ExecuteAction=new Action<object>(nextCmd)
};
PrevCmd = new DelegateCommand
{
ExecuteAction=new Action<object>(prevCmd)
};
CloseWithoutPool = new DelegateCommand
{
ExecuteAction=new Action<object>(closeWithoutPool)
};
}
private int stepIndex;
public int StepIndex
{
get { return stepIndex; }
set
{
stepIndex = value;
this.RaisePropertyChanged("StepIndex");
}
}
private Pool editpool;
public Pool EditPool
{
get { return editpool; }
set
{
editpool = value;
this.RaisePropertyChanged("EditPool");
}
}
public Pool Result { get; set; }
public Action CloseAction { get; set; }
public DelegateCommand CloseCmd => new Lazy<DelegateCommand>(() => new DelegateCommand { ExecuteAction = closeAction }).Value;
private void closeAction(object permerter)
{
CloseAction?.Invoke();
}
public DelegateCommand PrevCmd { get; set; }
private void prevCmd(object permerter)
{
NewPoolStep.stepBar_Export.Prev();
}
public DelegateCommand CloseWithoutPool { get; set; }
private void closeWithoutPool(object permerter)
{
Result = null;
CloseCmd.Execute(null);
}
public DelegateCommand NextCmd { get; set; }
private void nextCmd(object permerter)
{
NewPoolStep.stepBar_Export.Next();
}
}
}
| 29.772152 | 134 | 0.56165 | [
"Apache-2.0"
] | Hellobaka/CustomGacha | me.cqp.luohuaming.CustomGacha.UI/ViewModel/NewPoolStepViewModel.cs | 2,354 | C# |
using System;
using Xunit;
namespace GraphQL.EntityFrameworkCore.Helpers.Tests
{
public class ResolveFieldContextExtensionsTests
{
[Fact]
public void Should_ThrowException_When_TryingToGetServiceWhenRequestServicesIsNotSet()
{
var context = new ResolveFieldContext<object>();
Assert.Throws<Exception>(() => context.GetService<ResolveFieldContextExtensionsTests>());
Assert.Throws<Exception>(() => context.GetService(typeof(ResolveFieldContextExtensionsTests)));
}
}
} | 32.294118 | 107 | 0.704918 | [
"MIT"
] | ganhammar/GraphQL.EntityFrameworkCore.Helpers | tests/src/GraphQL.EntityFrameworkCore.Helpers.Tests/ResolveFieldContextExtensionsTests.cs | 549 | C# |
using System.Diagnostics.CodeAnalysis;
using KLineEdCmdApp.Controller.Base;
using KLineEdCmdApp.Model;
using MxReturnCode;
using KLineEdCmdApp.Utils;
using KLineEdCmdApp.View.Base;
namespace KLineEdCmdApp.View
{
[SuppressMessage("ReSharper", "ArrangeStaticMemberQualifier")]
public class MsgLineView : BaseView
{
public MsgLineView(IMxConsole console) : base(console)
{
}
public override MxReturnCode<bool> Setup(CmdLineParamsApp param)
{
var rc = new MxReturnCode<bool>("MsgLineView.ApplySettings");
if (param == null)
rc.SetError(1130101, MxError.Source.Param, $"param is null", MxMsgs.MxErrBadMethodParam);
else
{
var rcBase = base.Setup(param);
rc += rcBase;
if (rcBase.IsSuccess(true))
{
var rcColour = Console.SetColour(MsgLineInfoForeGndColour, MsgLineInfoBackGndColour);
rc += rcColour;
if (rcColour.IsSuccess(true))
{
var rcClear = ClearLine(KLineEditor.MsgLineRowIndex, KLineEditor.MsgLineLeftCol);
rc += rcClear;
if (rcClear.IsSuccess(true))
{
Ready = true;
rc.SetResult(true);
}
}
}
}
return rc;
}
public override void OnUpdate(NotificationItem notificationItem)
{
var rc = new MxReturnCode<bool>("MsgLineView.OnUpdate");
base.OnUpdate(notificationItem);
if (IsErrorState() == false)
{
ChapterModel.ChangeHint change = (ChapterModel.ChangeHint) notificationItem.Change;
if ((change != ChapterModel.ChangeHint.All) && (change != ChapterModel.ChangeHint.MsgLine))
rc.SetResult(true);
else
{
ChapterModel model = notificationItem.Data as ChapterModel;
if (model == null)
rc.SetError(1130201, MxError.Source.Program, "model is null", MxMsgs.MxErrInvalidCondition);
else
{
if (string.IsNullOrEmpty(model.MsgLine))
DisplayMsg(MxReturnCodeUtils.MsgClass.Info, "");
else
DisplayMsg(BaseEditingController.GetMsgClass(model.MsgLine), model.MsgLine); //Msg is formatted in BaseEditingController.ErrorProcessing()
rc.SetResult(true);
}
}
}
OnUpdateDone(rc, false);
}
}
}
| 37.773333 | 166 | 0.517826 | [
"MIT"
] | wpqs/GenDotNetCmdApps | KLineEd/KLineEdCmdApp/View/MsgLineView.cs | 2,835 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/winioctl.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop.Windows;
/// <include file='STORAGE_DISK_HEALTH_STATUS.xml' path='doc/member[@name="STORAGE_DISK_HEALTH_STATUS"]/*' />
public enum STORAGE_DISK_HEALTH_STATUS
{
/// <include file='STORAGE_DISK_HEALTH_STATUS.xml' path='doc/member[@name="STORAGE_DISK_HEALTH_STATUS.DiskHealthUnknown"]/*' />
DiskHealthUnknown = 0,
/// <include file='STORAGE_DISK_HEALTH_STATUS.xml' path='doc/member[@name="STORAGE_DISK_HEALTH_STATUS.DiskHealthUnhealthy"]/*' />
DiskHealthUnhealthy,
/// <include file='STORAGE_DISK_HEALTH_STATUS.xml' path='doc/member[@name="STORAGE_DISK_HEALTH_STATUS.DiskHealthWarning"]/*' />
DiskHealthWarning,
/// <include file='STORAGE_DISK_HEALTH_STATUS.xml' path='doc/member[@name="STORAGE_DISK_HEALTH_STATUS.DiskHealthHealthy"]/*' />
DiskHealthHealthy,
/// <include file='STORAGE_DISK_HEALTH_STATUS.xml' path='doc/member[@name="STORAGE_DISK_HEALTH_STATUS.DiskHealthMax"]/*' />
DiskHealthMax,
}
| 48.269231 | 145 | 0.758566 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | sources/Interop/Windows/Windows/um/winioctl/STORAGE_DISK_HEALTH_STATUS.cs | 1,257 | C# |
#region License
/*
* Copyright 2019 Jiruffe
*
* 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.
*/
#endregion
using System;
using System.Linq;
using System.Text;
namespace Jiruffe.CSiraffe.Utility {
internal static class StringExtensionMethods{
#region Escape Unescape
internal static string Escape(this string str) {
StringBuilder sb = new StringBuilder();
foreach (var c in str) {
if (Constants.Characters.ESCAPABLE_CHARACTER.Contains(c)) {
sb.Append(Constants.Characters.ESCAPE_SYMBOL);
sb.Append(Constants.Characters.ESCAPE_CHARACTER[c]);
} else if (c < Constants.Characters.VISIBLE_ASCII_CHARACTER_WITH_MIN_CODE || c > Constants.Characters.VISIBLE_ASCII_CHARACTER_WITH_MAX_CODE) {
sb.Append(Constants.Characters.ESCAPE_SYMBOL);
sb.Append(Constants.Characters.UNICODE_SYMBOL);
sb.Append(Constants.Characters.DIGIT_TO_HEX_CHARACTER[(((uint)c) >> 12) & 0xf]);
sb.Append(Constants.Characters.DIGIT_TO_HEX_CHARACTER[(((uint)c) >> 8) & 0xf]);
sb.Append(Constants.Characters.DIGIT_TO_HEX_CHARACTER[(((uint)c) >> 4) & 0xf]);
sb.Append(Constants.Characters.DIGIT_TO_HEX_CHARACTER[c & 0xf]);
} else {
sb.Append(c);
}
}
return sb.ToString();
}
internal static string Unescape(this string str) {
StringBuilder sb = new StringBuilder();
for (var i = 0; i < str.Length; i++) {
var c = str[i];
if (Constants.Characters.ESCAPE_SYMBOL == c && i < str.Length - 1) {
c = str[++i];
if (Constants.Characters.UNESCAPABLE_CHARACTER.Contains(c)) {
sb.Append(Constants.Characters.UNESCAPE_CHARACTER[c]);
} else if (Constants.Characters.UNICODE_SYMBOL == c && i < str.Length - 4) {
int d = 0;
for (int j = 0; j < 4; j++) {
d = (d << 4) + Constants.Characters.HEX_CHARACTER_TO_DIGIT[str[++i]];
}
sb.Append((char)d);
} else {
sb.Append(Constants.Characters.ESCAPE_SYMBOL);
sb.Append(c);
}
} else {
sb.Append(c);
}
}
return sb.ToString();
}
#endregion
#region SurroundedWith
internal static bool SurroundedWith(this string str, string value) {
return str.StartsWith(value) && str.EndsWith(value);
}
internal static bool SurroundedWith(this string str, char value) {
return str.StartsWith(value) && str.EndsWith(value);
}
#endregion
#region Numberic
internal static bool IsNumberic(this string str) {
foreach (var c in str) {
if ('0' > c || '9' < c) {
return false;
}
}
return true;
}
internal static bool IsBCPLStyleNumeric(this string str) {
if (str.StartsWith('-')) {
str = str.Substring(1);
}
int len = str.Length;
if (len < 2) {
return false;
}
char c0 = str[0];
char c1 = str[1];
if (c0 == '0') {
if (c1 == 'x' && len >= 3) {
for (int i = 2; i < len; i++) {
char c = str[i];
if (!('0' <= c && '9' >= c) && !('a' <= c && 'f' >= c) && !('A' <= c && 'F' >= c)) {
return false;
}
}
return true;
} else if (c1 == 'b' && len >= 3) {
for (int i = 2; i < len; i++) {
char c = str[i];
if ('0' != c && '1' != c) {
return false;
}
}
return true;
} else {
for (int i = 1; i < len; i++) {
char c = str[i];
if ('0' > c || '7' < c)
{
return false;
}
}
return true;
}
}
return false;
}
internal static bool IsRealNumber(this string str) {
if (str.StartsWith('-')) {
str = str.Substring(1);
}
if (0 >= str.Length) {
return false;
}
int index = str.IndexOf('.');
if (index < 0) {
return str.IsNumberic();
} else {
return str.Substring(0, index).IsNumberic() && str.Substring(index + 1).IsNumberic();
}
}
internal static bool IsScientificNotationNumber(this string str) {
int index = str.IndexOf('E');
return str.Substring(0, index).IsRealNumber() && str.Substring(index + 1).IsRealNumber();
}
internal static bool CouldCastToNumber(this string str) {
if (str is null) {
return false;
}
return str.IsRealNumber() || str.IsScientificNotationNumber() || str.IsBCPLStyleNumeric();
}
internal static object ToNumber(this string str) {
if (!str.CouldCastToNumber()) {
return default(int);
}
if (str.IsRealNumber()) {
if (str.Contains('.')) {
return double.Parse(str);
}
return long.Parse(str);
}
if (str.IsScientificNotationNumber()) {
int index = str.IndexOf('E');
return double.Parse(str.Substring(0, index)) * Math.Pow(10, double.Parse(str.Substring(index + 1)));
}
if (str.IsBCPLStyleNumeric()) {
long positive_rst;
bool negative = false;
if (str.StartsWith('-')) {
negative = true;
str = str.Substring(1);
}
if (str.StartsWith("0x")) {
positive_rst = Convert.ToInt64(str.Substring(2), 16);
} else if (str.StartsWith("0b")) {
positive_rst = Convert.ToInt64(str.Substring(2), 2);
} else {
positive_rst = Convert.ToInt64(str.Substring(1), 8);
}
return negative ? -positive_rst : positive_rst;
}
return default(int);
}
#endregion
}
}
| 30.276 | 158 | 0.45792 | [
"Apache-2.0"
] | jiruffe/csiraffe | Jiruffe.CSiraffe/Utility/StringExtensionMethods.cs | 7,571 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was not generated by a tool. but for stylecop suppression.
// </auto-generated>
//------------------------------------------------------------------------------
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using StrixIT.Platform.Core;
using StrixIT.Platform.Web;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace StrixIT.Platform.Modules.Membership.Tests
{
[TestClass]
public class AuthorizationAttributeTests
{
#region Private Fields
private Mock<IUserContext> _userContextMock;
#endregion Private Fields
#region Public Methods
[TestCleanup]
public void Cleanup()
{
StrixPlatform.Environment = null;
}
[TestInitialize]
public void Init()
{
_userContextMock = TestHelpers.MockUserContext();
StrixPlatform.Environment = new DefaultEnvironment();
}
[TestMethod]
public void SkipAuthorizationShouldNotSkipWhenNotAnonymousAllowed()
{
var attribute = new StrixAuthorizationAttribute();
List<Mock> mocks;
var context = GetAuthorizationContext(out mocks);
var request = mocks.First(m => m.GetType() == typeof(Mock<HttpRequestBase>)) as Mock<HttpRequestBase>;
request.Setup(r => r.Headers).Returns(new NameValueCollection());
attribute.OnAuthorization(context);
Assert.AreEqual(typeof(HttpUnauthorizedResult), context.Result.GetType());
}
[TestMethod]
public void SkipAuthorizationShouldSkipWhenAnonymousAllowedOnAction()
{
var attribute = new StrixAuthorizationAttribute();
List<Mock> mocks;
var context = GetAuthorizationContext(out mocks);
var request = mocks.First(m => m.GetType() == typeof(Mock<HttpRequestBase>)) as Mock<HttpRequestBase>;
request.Setup(r => r.Headers).Returns(new NameValueCollection());
var actionDescriptor = mocks.First(m => m.GetType() == typeof(Mock<ActionDescriptor>)) as Mock<ActionDescriptor>;
actionDescriptor.Setup(a => a.GetCustomAttributes(typeof(AllowAnonymousAttribute), It.IsAny<bool>())).Returns(new object[] { new AllowAnonymousAttribute() });
attribute.OnAuthorization(context);
var cache = mocks.First(m => m.GetType() == typeof(Mock<HttpCachePolicyBase>)) as Mock<HttpCachePolicyBase>;
cache.Verify(c => c.SetProxyMaxAge(It.IsAny<TimeSpan>()), Times.Once());
}
[TestMethod]
public void SkipAuthorizationShouldSkipWhenAnonymousAllowedOnController()
{
var attribute = new StrixAuthorizationAttribute();
List<Mock> mocks;
var context = GetAuthorizationContext(out mocks);
var request = mocks.First(m => m.GetType() == typeof(Mock<HttpRequestBase>)) as Mock<HttpRequestBase>;
request.Setup(r => r.Headers).Returns(new NameValueCollection());
var controllerDescriptor = mocks.First(m => m.GetType() == typeof(Mock<ControllerDescriptor>)) as Mock<ControllerDescriptor>;
controllerDescriptor.Setup(a => a.GetCustomAttributes(typeof(AllowAnonymousAttribute), It.IsAny<bool>())).Returns(new object[] { new AllowAnonymousAttribute() });
attribute.OnAuthorization(context);
var cache = mocks.First(m => m.GetType() == typeof(Mock<HttpCachePolicyBase>)) as Mock<HttpCachePolicyBase>;
cache.Verify(c => c.SetProxyMaxAge(It.IsAny<TimeSpan>()), Times.Once());
}
[TestMethod]
public void UnauthorizedAjaxRequestShouldSetStatusCodeTo401AndEndResponse()
{
var attribute = new StrixAuthorizationAttribute();
List<Mock> mocks;
var context = GetAuthorizationContext(out mocks);
attribute.OnAuthorization(context);
var result = context.Result as HttpStatusCodeResult;
Assert.IsNotNull(result);
Assert.AreEqual(401, result.StatusCode);
}
[TestMethod]
public void UserWithoutRequiredPermissionShouldNotBeAuthorized()
{
var attribute = new StrixAuthorizationAttribute { Permissions = "View users" };
List<Mock> mocks;
var context = GetAuthorizationContext(out mocks);
var identity = mocks.First(m => m.GetType() == typeof(Mock<IIdentity>)) as Mock<IIdentity>;
identity.Setup(i => i.Name).Returns("Administrator");
_userContextMock.Setup(m => m.HasPermission(new string[] { "View users" })).Returns(false);
attribute.OnAuthorization(context);
var result = context.Result as HttpStatusCodeResult;
Assert.IsNotNull(result);
Assert.AreEqual(401, result.StatusCode);
}
[TestMethod]
public void UserWithoutRequiredRoleShouldNotBeAuthorized()
{
var attribute = new StrixAuthorizationAttribute { Roles = "Administrator" };
List<Mock> mocks;
var context = GetAuthorizationContext(out mocks);
var identity = mocks.First(m => m.GetType() == typeof(Mock<IIdentity>)) as Mock<IIdentity>;
identity.Setup(i => i.Name).Returns("Editor");
_userContextMock.Setup(m => m.IsInRoles(new string[] { "Administrator" })).Returns(false);
attribute.OnAuthorization(context);
var result = context.Result as HttpStatusCodeResult;
Assert.IsNotNull(result);
Assert.AreEqual(401, result.StatusCode);
}
[TestMethod]
public void UserWithRequiredPermissionShouldBeAuthorized()
{
var attribute = new StrixAuthorizationAttribute { Permissions = "View users" };
List<Mock> mocks;
var context = GetAuthorizationContext(out mocks);
var identity = mocks.First(m => m.GetType() == typeof(Mock<IIdentity>)) as Mock<IIdentity>;
identity.Setup(i => i.Name).Returns("Administrator");
_userContextMock.Setup(m => m.HasPermission(new string[] { "View users" })).Returns(true);
attribute.OnAuthorization(context);
var cache = mocks.First(m => m.GetType() == typeof(Mock<HttpCachePolicyBase>)) as Mock<HttpCachePolicyBase>;
cache.Verify(c => c.SetProxyMaxAge(It.IsAny<TimeSpan>()), Times.Once());
}
[TestMethod]
public void UserWithRequiredRoleShouldBeAuthorized()
{
var attribute = new StrixAuthorizationAttribute { Roles = "Administrator" };
List<Mock> mocks;
var context = GetAuthorizationContext(out mocks);
var identity = mocks.First(m => m.GetType() == typeof(Mock<IIdentity>)) as Mock<IIdentity>;
identity.Setup(i => i.Name).Returns("Administrator");
_userContextMock.Setup(m => m.IsInRoles(new string[] { "Administrator" })).Returns(true);
attribute.OnAuthorization(context);
var cache = mocks.First(m => m.GetType() == typeof(Mock<HttpCachePolicyBase>)) as Mock<HttpCachePolicyBase>;
cache.Verify(c => c.SetProxyMaxAge(It.IsAny<TimeSpan>()), Times.Once());
}
#endregion Public Methods
#region Private Methods
private AuthorizationContext GetAuthorizationContext(out List<Mock> mocks)
{
mocks = new List<Mock>();
var identity = new Mock<IIdentity>();
mocks.Add(identity);
var principal = new Mock<IPrincipal>();
principal.Setup(p => p.Identity).Returns(identity.Object);
mocks.Add(principal);
var headers = new NameValueCollection();
headers.Add("X-Requested-With", "XMLHttpRequest");
var request = new Mock<HttpRequestBase>();
request.Setup(r => r.Headers).Returns(headers);
mocks.Add(request);
var cache = new Mock<HttpCachePolicyBase>();
mocks.Add(cache);
var response = new Mock<HttpResponseBase>();
response.Setup(r => r.Cache).Returns(cache.Object);
mocks.Add(response);
var httpContext = new Mock<HttpContextBase>();
httpContext.Setup(h => h.Items).Returns(new Dictionary<string, string>());
httpContext.Setup(h => h.User).Returns(principal.Object);
httpContext.Setup(h => h.Request).Returns(request.Object);
httpContext.Setup(h => h.Response).Returns(response.Object);
mocks.Add(httpContext);
var routeData = new RouteData();
var requestContext = new RequestContext(httpContext.Object, routeData);
var controller = new UserController(new Mock<IUserService>().Object);
var controllerContext = new ControllerContext(requestContext, controller);
var controllerDescriptor = new Mock<ControllerDescriptor>();
mocks.Add(controllerDescriptor);
var actionDescriptor = new Mock<ActionDescriptor>();
actionDescriptor.Setup(a => a.ControllerDescriptor).Returns(controllerDescriptor.Object);
mocks.Add(actionDescriptor);
var context = new AuthorizationContext(controllerContext, actionDescriptor.Object);
return context;
}
#endregion Private Methods
}
} | 48.25 | 174 | 0.627254 | [
"Apache-2.0"
] | StrixIT/StrixIT.Platform.Modules.Membership | StrixIT.Platform.Modules.Membership.Tests/Attributes/AuthorizationAttributeTests.cs | 9,652 | 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 databrew-2017-07-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.GlueDataBrew.Model
{
/// <summary>
/// This is the response object from the ListJobRuns operation.
/// </summary>
public partial class ListJobRunsResponse : AmazonWebServiceResponse
{
private List<JobRun> _jobRuns = new List<JobRun>();
private string _nextToken;
/// <summary>
/// Gets and sets the property JobRuns.
/// <para>
/// A list of job runs that have occurred for the specified job.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public List<JobRun> JobRuns
{
get { return this._jobRuns; }
set { this._jobRuns = value; }
}
// Check to see if JobRuns property is set
internal bool IsSetJobRuns()
{
return this._jobRuns != null && this._jobRuns.Count > 0;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// A token generated by DataBrew that specifies where to continue pagination if a previous
/// request was truncated. To obtain the next set of pages, pass in the NextToken from
/// the response object of the previous page call.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=2000)]
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
}
} | 32.2125 | 107 | 0.605355 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/GlueDataBrew/Generated/Model/ListJobRunsResponse.cs | 2,577 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: DataStructures.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace CoreML.Specification {
/// <summary>Holder for reflection information generated from DataStructures.proto</summary>
public static partial class DataStructuresReflection {
#region Descriptor
/// <summary>File descriptor for DataStructures.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static DataStructuresReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChREYXRhU3RydWN0dXJlcy5wcm90bxIUQ29yZU1MLlNwZWNpZmljYXRpb24a",
"EkZlYXR1cmVUeXBlcy5wcm90byJ8ChBTdHJpbmdUb0ludDY0TWFwEjwKA21h",
"cBgBIAMoCzIvLkNvcmVNTC5TcGVjaWZpY2F0aW9uLlN0cmluZ1RvSW50NjRN",
"YXAuTWFwRW50cnkaKgoITWFwRW50cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVl",
"GAIgASgDOgI4ASJ8ChBJbnQ2NFRvU3RyaW5nTWFwEjwKA21hcBgBIAMoCzIv",
"LkNvcmVNTC5TcGVjaWZpY2F0aW9uLkludDY0VG9TdHJpbmdNYXAuTWFwRW50",
"cnkaKgoITWFwRW50cnkSCwoDa2V5GAEgASgDEg0KBXZhbHVlGAIgASgJOgI4",
"ASJ+ChFTdHJpbmdUb0RvdWJsZU1hcBI9CgNtYXAYASADKAsyMC5Db3JlTUwu",
"U3BlY2lmaWNhdGlvbi5TdHJpbmdUb0RvdWJsZU1hcC5NYXBFbnRyeRoqCghN",
"YXBFbnRyeRILCgNrZXkYASABKAkSDQoFdmFsdWUYAiABKAE6AjgBInwKEElu",
"dDY0VG9Eb3VibGVNYXASPAoDbWFwGAEgAygLMi8uQ29yZU1MLlNwZWNpZmlj",
"YXRpb24uSW50NjRUb0RvdWJsZU1hcC5NYXBFbnRyeRoqCghNYXBFbnRyeRIL",
"CgNrZXkYASABKAMSDQoFdmFsdWUYAiABKAE6AjgBIh4KDFN0cmluZ1ZlY3Rv",
"chIOCgZ2ZWN0b3IYASADKAkiHQoLSW50NjRWZWN0b3ISDgoGdmVjdG9yGAEg",
"AygDIh4KDERvdWJsZVZlY3RvchIOCgZ2ZWN0b3IYASADKAFCAkgDUABiBnBy",
"b3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::CoreML.Specification.FeatureTypesReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::CoreML.Specification.StringToInt64Map), global::CoreML.Specification.StringToInt64Map.Parser, new[]{ "Map" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, }),
new pbr::GeneratedClrTypeInfo(typeof(global::CoreML.Specification.Int64ToStringMap), global::CoreML.Specification.Int64ToStringMap.Parser, new[]{ "Map" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, }),
new pbr::GeneratedClrTypeInfo(typeof(global::CoreML.Specification.StringToDoubleMap), global::CoreML.Specification.StringToDoubleMap.Parser, new[]{ "Map" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, }),
new pbr::GeneratedClrTypeInfo(typeof(global::CoreML.Specification.Int64ToDoubleMap), global::CoreML.Specification.Int64ToDoubleMap.Parser, new[]{ "Map" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, }),
new pbr::GeneratedClrTypeInfo(typeof(global::CoreML.Specification.StringVector), global::CoreML.Specification.StringVector.Parser, new[]{ "Vector" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::CoreML.Specification.Int64Vector), global::CoreML.Specification.Int64Vector.Parser, new[]{ "Vector" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::CoreML.Specification.DoubleVector), global::CoreML.Specification.DoubleVector.Parser, new[]{ "Vector" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
///*
/// A mapping from a string
/// to a 64-bit integer.
/// </summary>
public sealed partial class StringToInt64Map : pb::IMessage<StringToInt64Map> {
private static readonly pb::MessageParser<StringToInt64Map> _parser = new pb::MessageParser<StringToInt64Map>(() => new StringToInt64Map());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<StringToInt64Map> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::CoreML.Specification.DataStructuresReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public StringToInt64Map() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public StringToInt64Map(StringToInt64Map other) : this() {
map_ = other.map_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public StringToInt64Map Clone() {
return new StringToInt64Map(this);
}
/// <summary>Field number for the "map" field.</summary>
public const int MapFieldNumber = 1;
private static readonly pbc::MapField<string, long>.Codec _map_map_codec
= new pbc::MapField<string, long>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForInt64(16), 10);
private readonly pbc::MapField<string, long> map_ = new pbc::MapField<string, long>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::MapField<string, long> Map {
get { return map_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as StringToInt64Map);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(StringToInt64Map other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!Map.Equals(other.Map)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= Map.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
map_.WriteTo(output, _map_map_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += map_.CalculateSize(_map_map_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(StringToInt64Map other) {
if (other == null) {
return;
}
map_.Add(other.map_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
map_.AddEntriesFrom(input, _map_map_codec);
break;
}
}
}
}
}
/// <summary>
///*
/// A mapping from a 64-bit integer
/// to a string.
/// </summary>
public sealed partial class Int64ToStringMap : pb::IMessage<Int64ToStringMap> {
private static readonly pb::MessageParser<Int64ToStringMap> _parser = new pb::MessageParser<Int64ToStringMap>(() => new Int64ToStringMap());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Int64ToStringMap> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::CoreML.Specification.DataStructuresReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Int64ToStringMap() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Int64ToStringMap(Int64ToStringMap other) : this() {
map_ = other.map_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Int64ToStringMap Clone() {
return new Int64ToStringMap(this);
}
/// <summary>Field number for the "map" field.</summary>
public const int MapFieldNumber = 1;
private static readonly pbc::MapField<long, string>.Codec _map_map_codec
= new pbc::MapField<long, string>.Codec(pb::FieldCodec.ForInt64(8), pb::FieldCodec.ForString(18), 10);
private readonly pbc::MapField<long, string> map_ = new pbc::MapField<long, string>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::MapField<long, string> Map {
get { return map_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Int64ToStringMap);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Int64ToStringMap other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!Map.Equals(other.Map)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= Map.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
map_.WriteTo(output, _map_map_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += map_.CalculateSize(_map_map_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Int64ToStringMap other) {
if (other == null) {
return;
}
map_.Add(other.map_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
map_.AddEntriesFrom(input, _map_map_codec);
break;
}
}
}
}
}
/// <summary>
///*
/// A mapping from a string
/// to a double-precision floating point number.
/// </summary>
public sealed partial class StringToDoubleMap : pb::IMessage<StringToDoubleMap> {
private static readonly pb::MessageParser<StringToDoubleMap> _parser = new pb::MessageParser<StringToDoubleMap>(() => new StringToDoubleMap());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<StringToDoubleMap> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::CoreML.Specification.DataStructuresReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public StringToDoubleMap() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public StringToDoubleMap(StringToDoubleMap other) : this() {
map_ = other.map_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public StringToDoubleMap Clone() {
return new StringToDoubleMap(this);
}
/// <summary>Field number for the "map" field.</summary>
public const int MapFieldNumber = 1;
private static readonly pbc::MapField<string, double>.Codec _map_map_codec
= new pbc::MapField<string, double>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForDouble(17), 10);
private readonly pbc::MapField<string, double> map_ = new pbc::MapField<string, double>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::MapField<string, double> Map {
get { return map_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as StringToDoubleMap);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(StringToDoubleMap other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!Map.Equals(other.Map)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= Map.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
map_.WriteTo(output, _map_map_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += map_.CalculateSize(_map_map_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(StringToDoubleMap other) {
if (other == null) {
return;
}
map_.Add(other.map_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
map_.AddEntriesFrom(input, _map_map_codec);
break;
}
}
}
}
}
/// <summary>
///*
/// A mapping from a 64-bit integer
/// to a double-precision floating point number.
/// </summary>
public sealed partial class Int64ToDoubleMap : pb::IMessage<Int64ToDoubleMap> {
private static readonly pb::MessageParser<Int64ToDoubleMap> _parser = new pb::MessageParser<Int64ToDoubleMap>(() => new Int64ToDoubleMap());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Int64ToDoubleMap> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::CoreML.Specification.DataStructuresReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Int64ToDoubleMap() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Int64ToDoubleMap(Int64ToDoubleMap other) : this() {
map_ = other.map_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Int64ToDoubleMap Clone() {
return new Int64ToDoubleMap(this);
}
/// <summary>Field number for the "map" field.</summary>
public const int MapFieldNumber = 1;
private static readonly pbc::MapField<long, double>.Codec _map_map_codec
= new pbc::MapField<long, double>.Codec(pb::FieldCodec.ForInt64(8), pb::FieldCodec.ForDouble(17), 10);
private readonly pbc::MapField<long, double> map_ = new pbc::MapField<long, double>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::MapField<long, double> Map {
get { return map_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Int64ToDoubleMap);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Int64ToDoubleMap other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!Map.Equals(other.Map)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= Map.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
map_.WriteTo(output, _map_map_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += map_.CalculateSize(_map_map_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Int64ToDoubleMap other) {
if (other == null) {
return;
}
map_.Add(other.map_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
map_.AddEntriesFrom(input, _map_map_codec);
break;
}
}
}
}
}
/// <summary>
///*
/// A vector of strings.
/// </summary>
public sealed partial class StringVector : pb::IMessage<StringVector> {
private static readonly pb::MessageParser<StringVector> _parser = new pb::MessageParser<StringVector>(() => new StringVector());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<StringVector> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::CoreML.Specification.DataStructuresReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public StringVector() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public StringVector(StringVector other) : this() {
vector_ = other.vector_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public StringVector Clone() {
return new StringVector(this);
}
/// <summary>Field number for the "vector" field.</summary>
public const int VectorFieldNumber = 1;
private static readonly pb::FieldCodec<string> _repeated_vector_codec
= pb::FieldCodec.ForString(10);
private readonly pbc::RepeatedField<string> vector_ = new pbc::RepeatedField<string>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<string> Vector {
get { return vector_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as StringVector);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(StringVector other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!vector_.Equals(other.vector_)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= vector_.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
vector_.WriteTo(output, _repeated_vector_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += vector_.CalculateSize(_repeated_vector_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(StringVector other) {
if (other == null) {
return;
}
vector_.Add(other.vector_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
vector_.AddEntriesFrom(input, _repeated_vector_codec);
break;
}
}
}
}
}
/// <summary>
///*
/// A vector of 64-bit integers.
/// </summary>
public sealed partial class Int64Vector : pb::IMessage<Int64Vector> {
private static readonly pb::MessageParser<Int64Vector> _parser = new pb::MessageParser<Int64Vector>(() => new Int64Vector());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Int64Vector> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::CoreML.Specification.DataStructuresReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Int64Vector() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Int64Vector(Int64Vector other) : this() {
vector_ = other.vector_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Int64Vector Clone() {
return new Int64Vector(this);
}
/// <summary>Field number for the "vector" field.</summary>
public const int VectorFieldNumber = 1;
private static readonly pb::FieldCodec<long> _repeated_vector_codec
= pb::FieldCodec.ForInt64(10);
private readonly pbc::RepeatedField<long> vector_ = new pbc::RepeatedField<long>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<long> Vector {
get { return vector_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Int64Vector);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Int64Vector other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!vector_.Equals(other.vector_)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= vector_.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
vector_.WriteTo(output, _repeated_vector_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += vector_.CalculateSize(_repeated_vector_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Int64Vector other) {
if (other == null) {
return;
}
vector_.Add(other.vector_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10:
case 8: {
vector_.AddEntriesFrom(input, _repeated_vector_codec);
break;
}
}
}
}
}
/// <summary>
///*
/// A vector of double-precision floating point numbers.
/// </summary>
public sealed partial class DoubleVector : pb::IMessage<DoubleVector> {
private static readonly pb::MessageParser<DoubleVector> _parser = new pb::MessageParser<DoubleVector>(() => new DoubleVector());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<DoubleVector> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::CoreML.Specification.DataStructuresReflection.Descriptor.MessageTypes[6]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DoubleVector() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DoubleVector(DoubleVector other) : this() {
vector_ = other.vector_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DoubleVector Clone() {
return new DoubleVector(this);
}
/// <summary>Field number for the "vector" field.</summary>
public const int VectorFieldNumber = 1;
private static readonly pb::FieldCodec<double> _repeated_vector_codec
= pb::FieldCodec.ForDouble(10);
private readonly pbc::RepeatedField<double> vector_ = new pbc::RepeatedField<double>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<double> Vector {
get { return vector_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as DoubleVector);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(DoubleVector other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!vector_.Equals(other.vector_)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= vector_.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
vector_.WriteTo(output, _repeated_vector_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += vector_.CalculateSize(_repeated_vector_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(DoubleVector other) {
if (other == null) {
return;
}
vector_.Add(other.vector_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10:
case 9: {
vector_.AddEntriesFrom(input, _repeated_vector_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| 35.379894 | 224 | 0.684094 | [
"MIT"
] | jstedfast/CoreML | CoreML/DataStructures.cs | 33,434 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
namespace KeyMan.Core
{
public class CryptoManager
{
public static CryptoKeyPair GenerateKeyPair(int keySize = 1024)
{
var cryptoKeyPair = new CryptoKeyPair {Id = Guid.NewGuid()};
var rsaProvider = new RSACryptoServiceProvider(keySize, new CspParameters(1));
cryptoKeyPair.PublicKeyEncodedString = Convert.ToBase64String(rsaProvider.ExportCspBlob(false));
cryptoKeyPair.PrivateKeyEncodedString = Convert.ToBase64String(rsaProvider.ExportCspBlob(true));
return cryptoKeyPair;
}
public static byte[] GenerateSalt(int saltLength)
{
var salt = new byte[saltLength];
using (var random = new RNGCryptoServiceProvider())
{
random.GetNonZeroBytes(salt);
}
return salt;
}
public static byte[] CreateSymmetricKey(string password, int keyBytes = 32, int iterations = 300)
{
var keyGenerator = new Rfc2898DeriveBytes(password, GenerateSalt(32), iterations);
return keyGenerator.GetBytes(keyBytes);
}
}
} | 31.897436 | 108 | 0.644695 | [
"MIT"
] | ballance/KeyMan | KeyMan.Core/CryptoManager.cs | 1,244 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using NetTopologySuite.Geometries;
using RTools_NTS.Util;
namespace NetTopologySuite.IO
{
/// <summary>
/// Reads a sequence of {@link Geometry}s in WKBHex format
/// from a text file.
/// Each WKBHex geometry must be on a single line
/// The geometries in the file may be separated by any amount
/// of whitespace and newlines.
/// </summary>
/// <author>Martin Davis</author>
public class WKBHexFileReader
{
private readonly WKBReader _wkbReader;
/// <summary>
/// Creates a new <see cref="WKBHexFileReader"/> given the
/// <see cref="WKBReader"/> to use to parse the geometries.
/// </summary>
/// <param name="wkbReader">The geometry reader to use</param>
public WKBHexFileReader(WKBReader wkbReader)
{
if (wkbReader == null)
throw new ArgumentNullException("wkbReader");
Limit = -1;
_wkbReader = wkbReader;
}
/// <summary>
/// Gets or sets a value indicating the maximum number of geometries to read
/// </summary>
public int Limit { get; set; }
/// <summary>
/// Gets or sets the number of geometries to skip before storing.
/// </summary>
public int Offset { get; set; }
/// <summary>
/// Reads a sequence of geometries.<br/>
/// If an <see cref="Offset"/> is specified, geometries read up to the offset count are skipped.
/// If a <see cref="Limit"/> is specified, no more than <see cref="Limit"/> geometries are read.
/// </summary>
/// <param name="file">The path to the file</param>
/// <exception cref="ArgumentNullException">Thrown if no filename was specified</exception>
/// <exception cref="FileNotFoundException">Thrown if the filename specified does not exist</exception>
/// <exception cref="IOException">Thrown if an I/O exception was encountered</exception>
/// <exception cref="ParseException">Thrown if an error occurred reading a geometry</exception>
public ReadOnlyCollection<Geometry> Read(string file)
{
if (string.IsNullOrEmpty(file))
throw new ArgumentNullException("file");
// do this here so that constructors don't throw exceptions
using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read))
{
return Read(stream);
}
}
/// <summary>
/// Reads a sequence of geometries.<br/>
/// If an <see cref="Offset"/> is specified, geometries read up to the offset count are skipped.
/// If a <see cref="Limit"/> is specified, no more than <see cref="Limit"/> geometries are read.
/// </summary>
/// <param name="stream">The path to the file</param>
/// <exception cref="ArgumentNullException">Thrown if no stream was passed</exception>
/// <exception cref="ArgumentException">Thrown if passed stream is not readable or seekable</exception>
/// <exception cref="IOException">Thrown if an I/O exception was encountered</exception>
/// <exception cref="ParseException">Thrown if an error occured reading a geometry</exception>
public ReadOnlyCollection<Geometry> Read(Stream stream)
{
if (stream == null)
throw new ArgumentNullException("stream");
if (!stream.CanRead)
throw new Exception("Stream must be readable");
if (!stream.CanSeek)
throw new Exception("Stream must be seekable");
using (var sr = new StreamReader(stream))
{
return Read(sr);
}
}
/// <summary>
/// Reads a sequence of geometries.<br/>
/// If an <see cref="Offset"/> is specified, geometries read up to the offset count are skipped.
/// If a <see cref="Limit"/> is specified, no more than <see cref="Limit"/> geometries are read.
/// </summary>
/// <param name="streamReader">The stream reader to use.</param>
/// <exception cref="IOException">Thrown if an I/O exception was encountered</exception>
/// <exception cref="ParseException">Thrown if an error occured reading a geometry</exception>
private ReadOnlyCollection<Geometry> Read(StreamReader streamReader)
{
var geoms = new List<Geometry>();
int count = 0;
while (!IsAtEndOfFile(streamReader) && !IsAtLimit(geoms))
{
string line = streamReader.ReadLine();
if (string.IsNullOrEmpty(line)) continue;
var g = _wkbReader.Read(WKBReader.HexToBytes(line));
if (count >= Offset)
geoms.Add(g);
count++;
}
return geoms.AsReadOnly();
}
/// <summary>
/// Tests if reader has reached limit
/// </summary>
/// <param name="geoms">A collection of already read geometries</param>
/// <returns><value>true</value> if <see cref="Limit"/> number of geometries has been read.</returns>
private bool IsAtLimit(List<Geometry> geoms)
{
if (Limit < 0)
return false;
return geoms.Count >= Limit;
}
/// <summary>
/// Tests if reader is at EOF.
/// </summary>
private static bool IsAtEndOfFile(StreamReader bufferedReader)
{
long position = bufferedReader.BaseStream.Position;
var tokenizer = new StreamTokenizer(bufferedReader);
Token t;
if (!tokenizer.NextToken(out t) || t is EofToken)
return true;
bufferedReader.BaseStream.Seek(position, SeekOrigin.Begin);
return false;
}
}
}
| 40.288591 | 111 | 0.588372 | [
"EPL-1.0"
] | m1dst/NetTopologySuite | src/NetTopologySuite/IO/WKBHexFileReader.cs | 6,005 | C# |
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Google.Protobuf;
namespace mlagentsdev
{
/// <summary>
/// The batcher is an RL specific class that makes sure that the information each object in
/// Unity (Academy and Brains) wants to send to External is appropriately batched together
/// and sent only when necessary.
///
/// The Batcher will only send a Message to the Communicator when either :
/// 1 - The academy is done
/// 2 - At least one brain has data to send
///
/// At each step, the batcher will keep track of the brains that queried the batcher for that
/// step. The batcher can only send the batched data when all the Brains have queried the
/// Batcher.
/// </summary>
public class Batcher
{
/// The default number of agents in the scene
private const int NumAgents = 32;
/// Keeps track of which brains have data to send on the current step
Dictionary<string, bool> m_hasData =
new Dictionary<string, bool>();
/// Keeps track of which brains queried the batcher on the current step
Dictionary<string, bool> m_hasQueried =
new Dictionary<string, bool>();
/// Keeps track of the agents of each brain on the current step
Dictionary<string, List<Agent>> m_currentAgents =
new Dictionary<string, List<Agent>>();
/// The Communicator of the batcher, sends a message at most once per step
Communicator m_communicator;
/// The current UnityRLOutput to be sent when all the brains queried the batcher
CommunicatorObjects.UnityRLOutput m_currentUnityRLOutput =
new CommunicatorObjects.UnityRLOutput();
/// Keeps track of the done flag of the Academy
bool m_academyDone;
/// Keeps track of last CommandProto sent by External
CommunicatorObjects.CommandProto m_command;
/// Keeps track of last EnvironmentParametersProto sent by External
CommunicatorObjects.EnvironmentParametersProto m_environmentParameters;
/// Keeps track of last training mode sent by External
bool m_isTraining;
/// Keeps track of the number of messages received
private ulong m_messagesReceived;
/// <summary>
/// Initializes a new instance of the Batcher class.
/// </summary>
/// <param name="communicator">The communicator to be used by the batcher.</param>
public Batcher(Communicator communicator)
{
this.m_communicator = communicator;
}
/// <summary>
/// Sends the academy parameters through the Communicator.
/// Is used by the academy to send the AcademyParameters to the communicator.
/// </summary>
/// <returns>The External Initialization Parameters received.</returns>
/// <param name="academyParameters">The Unity Initialization Parameters to be sent.</param>
public CommunicatorObjects.UnityRLInitializationInput SendAcademyParameters(
CommunicatorObjects.UnityRLInitializationOutput academyParameters)
{
CommunicatorObjects.UnityInput input;
var initializationInput = new CommunicatorObjects.UnityInput();
try
{
initializationInput = m_communicator.Initialize(
new CommunicatorObjects.UnityOutput
{
RlInitializationOutput = academyParameters
},
out input);
}
catch
{
throw new UnityAgentsException(
"The Communicator was unable to connect. Please make sure the External " +
"process is ready to accept communication with Unity.");
}
var firstRlInput = input.RlInput;
m_command = firstRlInput.Command;
m_environmentParameters = firstRlInput.EnvironmentParameters;
m_isTraining = firstRlInput.IsTraining;
return initializationInput.RlInitializationInput;
}
/// <summary>
/// Registers the done flag of the academy to the next output to be sent
/// to the communicator.
/// </summary>
/// <param name="done">If set to <c>true</c>
/// The academy done state will be sent to External at the next Exchange.</param>
public void RegisterAcademyDoneFlag(bool done)
{
m_academyDone = done;
}
/// <summary>
/// Gets the command. Is used by the academy to get reset or quit signals.
/// </summary>
/// <returns>The current command.</returns>
public CommunicatorObjects.CommandProto GetCommand()
{
return m_command;
}
/// <summary>
/// Gets the number of messages received so far. Can be used to check for new messages.
/// </summary>
/// <returns>The number of messages received since start of the simulation</returns>
public ulong GetNumberMessageReceived()
{
return m_messagesReceived;
}
/// <summary>
/// Gets the environment parameters. Is used by the academy to update
/// the environment parameters.
/// </summary>
/// <returns>The environment parameters.</returns>
public CommunicatorObjects.EnvironmentParametersProto GetEnvironmentParameters()
{
return m_environmentParameters;
}
/// <summary>
/// Gets the last training_mode flag External sent
/// </summary>
/// <returns><c>true</c>, if training mode is requested, <c>false</c> otherwise.</returns>
public bool GetIsTraining()
{
return m_isTraining;
}
/// <summary>
/// Adds the brain to the list of brains which will be sending information to External.
/// </summary>
/// <param name="brainKey">Brain key.</param>
public void SubscribeBrain(string brainKey)
{
m_hasQueried[brainKey] = false;
m_hasData[brainKey] = false;
m_currentAgents[brainKey] = new List<Agent>(NumAgents);
m_currentUnityRLOutput.AgentInfos.Add(
brainKey,
new CommunicatorObjects.UnityRLOutput.Types.ListAgentInfoProto());
}
/// <summary>
/// Sends the brain info. If at least one brain has an agent in need of
/// a decision or if the academy is done, the data is sent via
/// Communicator. Else, a new step is realized. The data can only be
/// sent once all the brains that subscribed to the batcher have tried
/// to send information.
/// </summary>
/// <param name="brainKey">Brain key.</param>
/// <param name="agentInfo">Agent info.</param>
public void SendBrainInfo(
string brainKey, Dictionary<Agent, AgentInfo> agentInfo)
{
// If no communicator is initialized, the Batcher will not transmit
// BrainInfo
if (m_communicator == null)
{
return;
}
// The brain tried called GiveBrainInfo, update m_hasQueried
m_hasQueried[brainKey] = true;
// Populate the currentAgents dictionary
m_currentAgents[brainKey].Clear();
foreach (Agent agent in agentInfo.Keys)
{
m_currentAgents[brainKey].Add(agent);
}
// If at least one agent has data to send, then append data to
// the message and update hasSentState
if (m_currentAgents[brainKey].Count > 0)
{
foreach (Agent agent in m_currentAgents[brainKey])
{
CommunicatorObjects.AgentInfoProto agentInfoProto = agentInfo[agent].ToProto();
m_currentUnityRLOutput.AgentInfos[brainKey].Value.Add(agentInfoProto);
}
m_hasData[brainKey] = true;
}
// If any agent needs to send data, then the whole message
// must be sent
if (m_hasQueried.Values.All(x => x))
{
if (m_hasData.Values.Any(x => x) || m_academyDone)
{
m_currentUnityRLOutput.GlobalDone = m_academyDone;
SendBatchedMessageHelper();
}
// The message was just sent so we must reset hasSentState and
// triedSendState
foreach (string k in m_currentAgents.Keys)
{
m_hasData[k] = false;
m_hasQueried[k] = false;
}
}
}
/// <summary>
/// Helper method that sends the curent UnityRLOutput, receives the next UnityInput and
/// Applies the appropriate AgentAction to the agents.
/// </summary>
void SendBatchedMessageHelper()
{
var input = m_communicator.Exchange(
new CommunicatorObjects.UnityOutput
{
RlOutput = m_currentUnityRLOutput
});
m_messagesReceived += 1;
foreach (string k in m_currentUnityRLOutput.AgentInfos.Keys)
{
m_currentUnityRLOutput.AgentInfos[k].Value.Clear();
}
if (input == null)
{
m_command = CommunicatorObjects.CommandProto.Quit;
return;
}
CommunicatorObjects.UnityRLInput rlInput = input.RlInput;
if (rlInput == null)
{
m_command = CommunicatorObjects.CommandProto.Quit;
return;
}
m_command = rlInput.Command;
m_environmentParameters = rlInput.EnvironmentParameters;
m_isTraining = rlInput.IsTraining;
if (rlInput.AgentActions == null)
{
return;
}
foreach (var brainName in rlInput.AgentActions.Keys)
{
if (!m_currentAgents[brainName].Any())
{
continue;
}
if (!rlInput.AgentActions[brainName].Value.Any())
{
continue;
}
for (var i = 0; i < m_currentAgents[brainName].Count; i++)
{
var agent = m_currentAgents[brainName][i];
var action = rlInput.AgentActions[brainName].Value[i];
agent.UpdateVectorAction(action.VectorActions.ToArray());
agent.UpdateMemoriesAction(action.Memories.ToList());
agent.UpdateTextAction(action.TextActions);
agent.UpdateValueAction(action.Value);
agent.UpdateCustomAction(action.CustomAction);
}
}
}
}
}
| 37.986348 | 99 | 0.573854 | [
"Apache-2.0"
] | vkakerbeck/ml-agents-dev | UnitySDK/Assets/ML-Agents/Scripts/Batcher.cs | 11,132 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace TNBCSurvey.Models
{
public class SurveyAnswer
{
[Key]
public int Answer_SID { get; set; }
[Required]
public int Client_SID { get; set; }
[Required]
[StringLength(6)]
public string Question_Period { get; set; }
[Required]
public int Question_SID { get; set; }
[Required]
[StringLength(1000)]
public string Answer_Text { get; set; }
}
} | 25.48 | 52 | 0.637363 | [
"MIT"
] | hca-foundation/newbeginnings | visualstudio/NewBeginningsSurvey/TNBCSurvey/Models/SurveyAnswer.cs | 639 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using PrintNodeNet.Http;
namespace PrintNodeNet
{
public sealed class PrintNodePrinter
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("computer")]
public PrintNodeComputer Computer { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("capabilities")]
public PrintNodePrinterCapabilities Capabilities { get; set; }
[JsonProperty("default")]
public string Default { get; set; }
[JsonProperty("createTimeStamp")]
public DateTime CreateTimeStamp { get; set; }
[JsonProperty("state")]
public string State { get; set; }
public static async Task<IEnumerable<PrintNodePrinter>> ListAsync(PrintNodeRequestOptions options = null)
{
var response = await PrintNodeApiHelper.Get("/printers", options);
return JsonConvert.DeserializeObject<List<PrintNodePrinter>>(response);
}
public static async Task<PrintNodePrinter> GetAsync(long id, PrintNodeRequestOptions options = null)
{
var response = await PrintNodeApiHelper.Get($"/printers/{id}", options);
var list = JsonConvert.DeserializeObject<List<PrintNodePrinter>>(response);
return list.FirstOrDefault();
}
public async Task<long> AddPrintJob(PrintNodePrintJob job, PrintNodeRequestOptions options = null)
{
job.PrinterId = Id;
var response = await PrintNodeApiHelper.Post("/printjobs", job, options);
return JsonConvert.DeserializeObject<long>(response);
}
}
}
| 31.096774 | 114 | 0.626037 | [
"MIT"
] | Ben52/printnode-net | PrintNodePrinter.cs | 1,930 | C# |
namespace XamarinShot.Models
{
using ARKit;
using Foundation;
using System;
using UIKit;
public class KeyPositionAnchor : ARAnchor
{
public KeyPositionAnchor(UIImage image, OpenTK.NMatrix4 transform, ARWorldMappingStatus mappingStatus) : base("KeyPosition", transform)
{
this.Image = image;
this.MappingStatus = mappingStatus;
}
// this is guaranteed to be called with something of the same class
public KeyPositionAnchor(ARAnchor anchor) : base(anchor)
{
var other = anchor as KeyPositionAnchor;
this.Image = other.Image;
this.MappingStatus = other.MappingStatus;
}
[Export("initWithCoder:")]
public KeyPositionAnchor(NSCoder coder) : base(coder)
{
if (coder.DecodeObject("image") is UIImage image)
{
this.Image = image;
var mappingValue = coder.DecodeInt("mappingStatus");
this.MappingStatus = (ARWorldMappingStatus)mappingValue;
}
else
{
throw new Exception();
}
}
public UIImage Image { get; private set; }
public ARWorldMappingStatus MappingStatus { get; private set; }
public override void EncodeTo(NSCoder encoder)
{
base.EncodeTo(encoder);
encoder.Encode(this.Image, "image");
encoder.Encode((int)this.MappingStatus, "mappingStatus");
}
public override NSObject Copy(NSZone zone)
{
// required by objc method override
var copy = base.Copy(zone) as KeyPositionAnchor;
copy.Image = this.Image;
copy.MappingStatus = this.MappingStatus;
return copy;
}
[Export("supportsSecureCoding")]
public static bool SupportsSecureCoding => true;
}
} | 30.777778 | 143 | 0.580712 | [
"MIT"
] | Art-Lav/ios-samples | ios12/XamarinShot/XamarinShot/Core/World Map Loading/KeyPositionAnchor.cs | 1,941 | C# |
/* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2016 Ingo Herbote
* http://www.yetanotherforum.net/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace YAF.Core
{
#region Using
using YAF.Core.Services;
using YAF.Types;
using YAF.Types.Constants;
using YAF.Types.Interfaces;
#endregion
/// <summary>
/// The i permissions extensions.
/// </summary>
public static class IPermissionsExtensions
{
#region Public Methods
/// <summary>
/// The check.
/// </summary>
/// <param name="permissions">
/// The permissions.
/// </param>
/// <param name="permission">
/// The permission.
/// </param>
/// <returns>
/// The check.
/// </returns>
public static bool Check([NotNull] this IPermissions permissions, int permission)
{
CodeContracts.VerifyNotNull(permissions, "permissions");
return permissions.Check((ViewPermissions)permission);
}
/// <summary>
/// The handle request.
/// </summary>
/// <param name="permissions">
/// The permissions.
/// </param>
/// <param name="permission">
/// The permission.
/// </param>
public static void HandleRequest([NotNull] this IPermissions permissions, int permission)
{
CodeContracts.VerifyNotNull(permissions, "permissions");
permissions.HandleRequest((ViewPermissions)permission);
}
#endregion
}
} | 29.443038 | 94 | 0.654342 | [
"Apache-2.0"
] | hismightiness/YAFNET | yafsrc/YAF.Core/Extensions/IPermissionsExtensions.cs | 2,249 | 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 grafana-2020-08-18.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.ManagedGrafana.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.ManagedGrafana.Model.Internal.MarshallTransformations
{
/// <summary>
/// IdpMetadata Marshaller
/// </summary>
public class IdpMetadataMarshaller : IRequestMarshaller<IdpMetadata, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(IdpMetadata requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetUrl())
{
context.Writer.WritePropertyName("url");
context.Writer.Write(requestObject.Url);
}
if(requestObject.IsSetXml())
{
context.Writer.WritePropertyName("xml");
context.Writer.Write(requestObject.Xml);
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static IdpMetadataMarshaller Instance = new IdpMetadataMarshaller();
}
} | 32.102941 | 105 | 0.666972 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/ManagedGrafana/Generated/Model/Internal/MarshallTransformations/IdpMetadataMarshaller.cs | 2,183 | C# |
/*
* Copyright 2010-2013 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.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using Amazon.Runtime;
namespace Amazon.DirectConnect.Model
{
/// <summary>
/// Returns information about the DeleteConnectionResult response and response metadata.
/// </summary>
public class DeleteConnectionResponse : AmazonWebServiceResponse
{
private DeleteConnectionResult deleteConnectionResult;
/// <summary>
/// Gets and sets the DeleteConnectionResult property.
/// A connection represents the physical network connection between the Direct Connect location and the customer.
/// </summary>
public DeleteConnectionResult DeleteConnectionResult
{
get
{
if(this.deleteConnectionResult == null)
{
this.deleteConnectionResult = new DeleteConnectionResult();
}
return this.deleteConnectionResult;
}
set { this.deleteConnectionResult = value; }
}
}
}
| 32.784314 | 121 | 0.666866 | [
"Apache-2.0"
] | mahanthbeeraka/dataservices-sdk-dotnet | AWSSDK/Amazon.DirectConnect/Model/DeleteConnectionResponse.cs | 1,672 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Diagnostics.Tracing.Session;
namespace JitBench
{
public class TestRun
{
public TestRun()
{
Benchmarks = new List<Benchmark>();
Configurations = new List<BenchmarkConfiguration>();
BenchmarkRunResults = new List<BenchmarkRunResult>();
MetricNames = new List<string>();
}
public bool UseExistingSetup { get; set; }
public string DotnetFrameworkVersion { get; set; }
public string DotnetSdkVersion { get; set; }
public string PrivateCoreCLRBinDir { get; set; }
public Architecture Architecture { get; set; }
public string OutputDir { get; set; }
public int Iterations { get; set; }
public List<Benchmark> Benchmarks { get; }
public List<BenchmarkConfiguration> Configurations { get; private set; }
public List<string> MetricNames { get; private set; }
public string BenchviewRunId { get; set; }
public DotNetInstallation DotNetInstallation { get; private set; }
public List<BenchmarkRunResult> BenchmarkRunResults { get; private set; }
public void Run(ITestOutputHelper output)
{
CheckConfiguration();
SetupBenchmarks(output).Wait();
RunBenchmarks(output);
WriteBenchmarkResults(output);
}
public void CheckConfiguration()
{
ValidateOutputDir();
ValidateMetrics();
}
private void ValidateMetrics()
{
var validCollectionOptions = new[] {
"default",
"gcapi",
"stopwatch",
"BranchMispredictions",
"CacheMisses",
"InstructionRetired",
};
var reducedList = MetricNames.Distinct(StringComparer.OrdinalIgnoreCase);
var isSubset = !reducedList.Except(validCollectionOptions, StringComparer.OrdinalIgnoreCase).Any();
if (!isSubset)
{
var errorMessage = $"Valid collection metrics are: {string.Join("|", validCollectionOptions)}";
throw new InvalidOperationException(errorMessage);
}
MetricNames = reducedList.Count() > 0 ? new List<string>(reducedList) : new List<string> { "stopwatch" };
if (MetricNames.Any(n => !n.Equals("stopwatch")))
{
if (TraceEventSession.IsElevated() != true)
{
throw new UnauthorizedAccessException("The application is required to run as Administrator in order to capture kernel data");
}
}
}
private void ValidateOutputDir()
{
if (string.IsNullOrWhiteSpace(OutputDir))
throw new InvalidOperationException("The output directory name cannot be null, empty or white space.");
if (OutputDir.Any(c => Path.GetInvalidPathChars().Contains(c)))
throw new InvalidOperationException($"Specified output directory {OutputDir} contains invalid path characters.");
OutputDir = Path.IsPathRooted(OutputDir) ? OutputDir : Path.GetFullPath(OutputDir);
if (OutputDir.Length > 80)
{
throw new InvalidOperationException($"The output directory path {OutputDir} is too long (>80 characters). Tests writing here may trigger errors because of path length limits");
}
try
{
Directory.CreateDirectory(OutputDir);
}
catch (IOException e)
{
throw new Exception($"Unable to create output directory {OutputDir}: {e.Message}", e);
}
}
public void WriteConfiguration(ITestOutputHelper output)
{
output.WriteLine("");
output.WriteLine(" === CONFIGURATION ===");
output.WriteLine("");
output.WriteLine("DotnetFrameworkVersion: " + DotnetFrameworkVersion);
output.WriteLine("DotnetSdkVersion: " + DotnetSdkVersion);
output.WriteLine("PrivateCoreCLRBinDir: " + PrivateCoreCLRBinDir);
output.WriteLine("Architecture: " + Architecture);
output.WriteLine("OutputDir: " + OutputDir);
output.WriteLine("Iterations: " + Iterations);
output.WriteLine("UseExistingSetup: " + UseExistingSetup);
output.WriteLine("Configurations: " + string.Join(",", Configurations.Select(c => c.Name)));
}
async Task SetupBenchmarks(ITestOutputHelper output)
{
output.WriteLine("");
output.WriteLine(" === SETUP ===");
output.WriteLine("");
if(UseExistingSetup)
{
output.WriteLine("UseExistingSetup is TRUE. Setup will be skipped.");
}
await PrepareDotNet(output);
foreach (Benchmark benchmark in Benchmarks)
{
if(!benchmark.IsArchitectureSupported(Architecture))
{
output.WriteLine("Benchmark " + benchmark.Name + " does not support architecture " + Architecture + ". Skipping setup.");
continue;
}
await benchmark.Setup(DotNetInstallation, OutputDir, UseExistingSetup, output);
}
}
async Task PrepareDotNet(ITestOutputHelper output)
{
if (!UseExistingSetup)
{
DotNetSetup setup = new DotNetSetup(Path.Combine(OutputDir, ".dotnet"))
.WithSdkVersion(DotnetSdkVersion)
.WithArchitecture(Architecture);
if(DotnetFrameworkVersion != "use-sdk")
{
setup.WithFrameworkVersion(DotnetFrameworkVersion);
}
if (PrivateCoreCLRBinDir != null)
{
setup.WithPrivateRuntimeBinaryOverlay(PrivateCoreCLRBinDir);
}
DotNetInstallation = await setup.Run(output);
}
else
{
DotNetInstallation = new DotNetInstallation(Path.Combine(OutputDir, ".dotnet"), DotnetFrameworkVersion, DotnetSdkVersion, Architecture);
}
}
void RunBenchmarks(ITestOutputHelper output)
{
output.WriteLine("");
output.WriteLine(" === EXECUTION ===");
output.WriteLine("");
foreach (Benchmark benchmark in Benchmarks)
{
if (!benchmark.IsArchitectureSupported(Architecture))
{
output.WriteLine("Benchmark " + benchmark.Name + " does not support architecture " + Architecture + ". Skipping run.");
continue;
}
BenchmarkRunResults.AddRange(benchmark.Run(this, output));
}
}
public void WriteBenchmarkResults(ITestOutputHelper output)
{
output.WriteLine("");
output.WriteLine(" === RESULTS ===");
output.WriteLine("");
WriteBenchmarkResultsTable((b, m) => b.GetDefaultDisplayMetrics().Any(metric => metric.Equals(m)), output);
}
void WriteBenchmarkResultsTable(Func<Benchmark,Metric, bool> primaryMetricSelector, ITestOutputHelper output)
{
List<ResultTableRowModel> rows = BuildRowModels(primaryMetricSelector);
List<ResultTableColumn> columns = BuildColumns();
List<List<string>> formattedCells = new List<List<string>>();
List<string> headerCells = new List<string>();
foreach(var column in columns)
{
headerCells.Add(column.Heading);
}
formattedCells.Add(headerCells);
foreach(var row in rows)
{
List<string> rowFormattedCells = new List<string>();
foreach(var column in columns)
{
rowFormattedCells.Add(column.CellFormatter(row));
}
formattedCells.Add(rowFormattedCells);
}
StringBuilder headerRow = new StringBuilder();
StringBuilder headerRowUnderline = new StringBuilder();
StringBuilder rowFormat = new StringBuilder();
for (int j = 0; j < columns.Count; j++)
{
int columnWidth = Enumerable.Range(0, formattedCells.Count).Select(i => formattedCells[i][j].Length).Max();
int hw = headerCells[j].Length;
headerRow.Append(headerCells[j].PadLeft(hw + (columnWidth - hw) / 2).PadRight(columnWidth + 2));
headerRowUnderline.Append(new string('-', columnWidth) + " ");
rowFormat.Append("{" + j + "," + columnWidth + "} ");
}
output.WriteLine(headerRow.ToString());
output.WriteLine(headerRowUnderline.ToString());
for(int i = 1; i < formattedCells.Count; i++)
{
output.WriteLine(string.Format(rowFormat.ToString(), formattedCells[i].ToArray()));
}
}
List<ResultTableRowModel> BuildRowModels(Func<Benchmark, Metric, bool> primaryMetricSelector)
{
List<ResultTableRowModel> rows = new List<ResultTableRowModel>();
foreach (Benchmark benchmark in Benchmarks)
{
BenchmarkRunResult canonResult = BenchmarkRunResults.Where(r => r.Benchmark == benchmark).FirstOrDefault();
if (canonResult == null || canonResult.IterationResults == null || canonResult.IterationResults.Count == 0)
{
continue;
}
IterationResult canonIteration = canonResult.IterationResults[0];
foreach (Metric metric in canonIteration.Measurements.Keys)
{
if (primaryMetricSelector(benchmark, metric))
{
rows.Add(new ResultTableRowModel() { Benchmark = benchmark, Metric = metric });
}
}
}
return rows;
}
List<ResultTableColumn> BuildColumns()
{
List<ResultTableColumn> columns = new List<ResultTableColumn>();
ResultTableColumn benchmarkColumn = new ResultTableColumn();
benchmarkColumn.Heading = "Benchmark";
benchmarkColumn.CellFormatter = row => row.Benchmark.Name;
columns.Add(benchmarkColumn);
ResultTableColumn metricNameColumn = new ResultTableColumn();
metricNameColumn.Heading = "Metric";
metricNameColumn.CellFormatter = row => $"{row.Metric.Name} ({row.Metric.Unit})";
columns.Add(metricNameColumn);
foreach(BenchmarkConfiguration config in Configurations)
{
ResultTableColumn column = new ResultTableColumn();
column.Heading = config.Name;
column.CellFormatter = row =>
{
var runResult = BenchmarkRunResults.Where(r => r.Benchmark == row.Benchmark && r.Configuration == config).Single();
var measurements = runResult.IterationResults.Skip(1).Select(r => r.Measurements.Where(kv => kv.Key.Equals(row.Metric)).Single()).Select(kv => kv.Value);
double median = measurements.Median();
double q1 = measurements.Quartile1();
double q3 = measurements.Quartile3();
int digits = Math.Min(Math.Max(0, (int)Math.Ceiling(-Math.Log10(q3-q1) + 1)), 15);
return $"{Math.Round(median, digits)} ({Math.Round(q1, digits)}-{Math.Round(q3, digits)})";
};
columns.Add(column);
}
return columns;
}
class ResultTableRowModel
{
public Benchmark Benchmark;
public Metric Metric;
}
class ResultTableColumn
{
public string Heading;
public Func<ResultTableRowModel, string> CellFormatter;
}
}
}
| 42.863014 | 192 | 0.562081 | [
"MIT"
] | 3F/coreclr | tests/src/performance/Scenario/JitBench/Runner/TestRun.cs | 12,518 | 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("Htk")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Htk")]
[assembly: AssemblyCopyright("Copyright © mjt 2011-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("fb592f89-31d4-4b8f-9dc4-8bc859002f43")]
// 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.486486 | 84 | 0.74261 | [
"MIT"
] | bosoni/htk | Htk/Properties/AssemblyInfo.cs | 1,390 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace _6.ReverseAndExcludeE
{
class Program
{
static void Main(string[] args)
{
List<int> numbers = Console.ReadLine()
.Split(" ", StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToList();
int numberToDivide = int.Parse(Console.ReadLine());
numbers.Reverse();
Predicate<int> divide = n => n % numberToDivide != 0;
numbers = numbers.FindAll(divide);
Console.WriteLine(string.Join(" ", numbers));
}
}
}
| 23.071429 | 66 | 0.555728 | [
"MIT"
] | deedeedextor/Software-University | C#Advanced/C#Advanced/FunctionalProgrammingLE/6.ReverseAndExcludeE/Program.cs | 648 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace fart
{
class Program
{
static void Main(string[] args)
{
int i = 255;
byte b;
checked { b = (byte)i; } // bu satır veri kaybı kontrolu sağlamaktadır...
Console.WriteLine(i);
Console.Read();
}
}
}
| 15.214286 | 85 | 0.549296 | [
"MIT"
] | Mikotochan/csders | Checked/checked.cs | 430 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace BarCodeDemo.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("BarCodeDemo.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 38.597222 | 177 | 0.603095 | [
"MIT"
] | SaLaaRHuSyN/BarCodeDemo | BarCodeDemo/Properties/Resources.Designer.cs | 2,781 | C# |
using System;
namespace winPEAS.Wifi.NativeWifiApi
{
/// <summary>
/// Defines flags passed to <see cref="WlanGetAvailableNetworkList"/>.
/// </summary>
[Flags]
public enum WlanGetAvailableNetworkFlags
{
/// <summary>
/// No additional flags
/// </summary>
None = 0,
/// <summary>
/// Include all ad-hoc network profiles in the available network list, including profiles that are not visible.
/// </summary>
IncludeAllAdhocProfiles = 0x00000001,
/// <summary>
/// Include all hidden network profiles in the available network list, including profiles that are not visible.
/// </summary>
IncludeAllManualHiddenProfiles = 0x00000002
}
[Flags]
public enum WlanProfileFlags
{
// When getting profiles, the absence of the "User" or "GroupPolicy" flags implies that the profile
// is an "AllUser" profile. This can also be viewed as having no flag -- hence "None" and "AllUser"
// are equivalent
None = 0,
AllUser = 0,
GroupPolicy = 1,
User = 2,
GetPlaintextKey = 4
}
/// <summary>
/// Defines the access mask of an all-user profile.
/// </summary>
[Flags]
public enum WlanAccess
{
/// <summary>
/// The user can view profile permissions.
/// </summary>
ReadAccess = 0x00020000 | 0x0001,
/// <summary>
/// The user has read access, and the user can also connect to and disconnect from a network using the profile.
/// </summary>
ExecuteAccess = ReadAccess | 0x0020,
/// <summary>
/// The user has execute access and the user can also modify and delete permissions associated with a profile.
/// </summary>
WriteAccess = ReadAccess | ExecuteAccess | 0x0002 | 0x00010000 | 0x00040000
}
/// <summary>
/// Specifies where the notification comes from.
/// </summary>
[Flags]
public enum WlanNotificationSource
{
None = 0,
/// <summary>
/// All notifications, including those generated by the 802.1X module.
/// </summary>
All = 0X0000FFFF,
/// <summary>
/// Notifications generated by the auto configuration module.
/// </summary>
ACM = 0X00000008,
/// <summary>
/// Notifications generated by MSM.
/// </summary>
MSM = 0X00000010,
/// <summary>
/// Notifications generated by the security module.
/// </summary>
Security = 0X00000020,
/// <summary>
/// Notifications generated by independent hardware vendors (IHV).
/// </summary>
IHV = 0X00000040
}
/// <summary>
/// Defines connection parameter flags.
/// </summary>
[Flags]
public enum WlanConnectionFlags
{
/// <summary>
/// Connect to the destination network even if the destination is a hidden network. A hidden network does not broadcast its SSID. Do not use this flag if the destination network is an ad-hoc network.
/// <para>If the profile specified by <see cref="WlanConnectionParameters.profile"/> is not <c>null</c>, then this flag is ignored and the nonBroadcast profile element determines whether to connect to a hidden network.</para>
/// </summary>
HiddenNetwork = 0x00000001,
/// <summary>
/// Do not form an ad-hoc network. Only join an ad-hoc network if the network already exists. Do not use this flag if the destination network is an infrastructure network.
/// </summary>
AdhocJoinOnly = 0x00000002,
/// <summary>
/// Ignore the privacy bit when connecting to the network. Ignoring the privacy bit has the effect of ignoring whether packets are encryption and ignoring the method of encryption used. Only use this flag when connecting to an infrastructure network using a temporary profile.
/// </summary>
IgnorePrivacyBit = 0x00000004,
/// <summary>
/// Exempt EAPOL traffic from encryption and decryption. This flag is used when an application must send EAPOL traffic over an infrastructure network that uses Open authentication and WEP encryption. This flag must not be used to connect to networks that require 802.1X authentication. This flag is only valid when <see cref="WlanConnectionParameters.wlanConnectionMode"/> is set to <see cref="WlanConnectionMode.TemporaryProfile"/>. Avoid using this flag whenever possible.
/// </summary>
EapolPassthrough = 0x00000008
}
/// <summary>
/// Indicates the state of an interface.
/// </summary>
/// <remarks>
/// Corresponds to the native <c>WLAN_INTERFACE_STATE</c> type.
/// </remarks>
public enum WlanInterfaceState
{
/// <summary>
/// The interface is not ready to operate.
/// </summary>
NotReady = 0,
/// <summary>
/// The interface is connected to a network.
/// </summary>
Connected = 1,
/// <summary>
/// The interface is the first node in an ad hoc network. No peer has connected.
/// </summary>
AdHocNetworkFormed = 2,
/// <summary>
/// The interface is disconnecting from the current network.
/// </summary>
Disconnecting = 3,
/// <summary>
/// The interface is not connected to any network.
/// </summary>
Disconnected = 4,
/// <summary>
/// The interface is attempting to associate with a network.
/// </summary>
Associating = 5,
/// <summary>
/// Auto configuration is discovering the settings for the network.
/// </summary>
Discovering = 6,
/// <summary>
/// The interface is in the process of authenticating.
/// </summary>
Authenticating = 7
}
/// <summary>
/// Defines an 802.11 PHY and media type.
/// </summary>
/// <remarks>
/// Corresponds to the native <c>DOT11_PHY_TYPE</c> type.
/// </remarks>
public enum Dot11PhyType : uint
{
/// <summary>
/// Specifies an unknown or uninitialized PHY type.
/// </summary>
Unknown = 0,
/// <summary>
/// Specifies any PHY type.
/// </summary>
Any = Unknown,
/// <summary>
/// Specifies a frequency-hopping spread-spectrum (FHSS) PHY. Bluetooth devices can use FHSS or an adaptation of FHSS.
/// </summary>
FHSS = 1,
/// <summary>
/// Specifies a direct sequence spread spectrum (DSSS) PHY.
/// </summary>
DSSS = 2,
/// <summary>
/// Specifies an infrared (IR) baseband PHY.
/// </summary>
IrBaseband = 3,
/// <summary>
/// Specifies an orthogonal frequency division multiplexing (OFDM) PHY. 802.11a devices can use OFDM.
/// </summary>
OFDM = 4,
/// <summary>
/// Specifies a high-rate DSSS (HRDSSS) PHY.
/// </summary>
HRDSSS = 5,
/// <summary>
/// Specifies an extended rate PHY (ERP). 802.11g devices can use ERP.
/// </summary>
ERP = 6,
/// <summary>
/// Specifies the start of the range that is used to define PHY types that are developed by an independent hardware vendor (IHV).
/// </summary>
IHV_Start = 0x80000000,
/// <summary>
/// Specifies the end of the range that is used to define PHY types that are developed by an independent hardware vendor (IHV).
/// </summary>
IHV_End = 0xffffffff
}
/// <summary>
/// Defines a basic service set (BSS) network type.
/// </summary>
/// <remarks>
/// Corresponds to the native <c>DOT11_BSS_TYPE</c> type.
/// </remarks>
public enum Dot11BssType
{
/// <summary>
/// Specifies an infrastructure BSS network.
/// </summary>
Infrastructure = 1,
/// <summary>
/// Specifies an independent BSS (IBSS) network.
/// </summary>
Independent = 2,
/// <summary>
/// Specifies either infrastructure or IBSS network.
/// </summary>
Any = 3
}
/// <summary>
/// Defines the mode of connection.
/// </summary>
/// <remarks>
/// Corresponds to the native <c>WLAN_CONNECTION_MODE</c> type.
/// </remarks>
public enum WlanConnectionMode
{
/// <summary>
/// A profile will be used to make the connection.
/// </summary>
Profile = 0,
/// <summary>
/// A temporary profile will be used to make the connection.
/// </summary>
TemporaryProfile,
/// <summary>
/// Secure discovery will be used to make the connection.
/// </summary>
DiscoverySecure,
/// <summary>
/// Unsecure discovery will be used to make the connection.
/// </summary>
DiscoveryUnsecure,
/// <summary>
/// A connection will be made automatically, generally using a persistent profile.
/// </summary>
Auto,
/// <summary>
/// Not used.
/// </summary>
Invalid
}
}
| 35.645038 | 482 | 0.579934 | [
"MIT"
] | 0rlixxx/PEASS-ng | winPEAS/winPEASexe/winPEAS/Wifi/NativeWifiApi/Enums.cs | 9,341 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Shapes.Library
{
public class ColoredCircle : Circle
{
public String Color
{
get;
set;
}
//overridde on the derived class's method will replace parent class impemention of method
//proper way to method override
public override double CalculateArea()
{
Console.WriteLine("Calculating area of a colored circle");
//base = super
return base.CalculateArea();
}
//if parent does not allow override, we can still add method with same name
//method hidding, does not replace original on object
//that original will run if access is through variable of type circle
//dont do this!!!!
public new double GetPerimeter()
{
return 10;
}
// c# perfecrs composition over inharitance
//if inharet, prefers ectenstion over modifiation
}
}
| 28 | 97 | 0.598456 | [
"MIT"
] | aopdaca/antonio-code | 1-csharp/Shapes/Shapes.Library/ColoredCircle.cs | 1,038 | C# |
using FluentValidation;
using ConversorMoeda.Application.Commands;
namespace ConversorMoeda.Application.Validators
{
public class ConverterMoedaCommandValidator: AbstractValidator<LiveMoedaCommand>
{
public ConverterMoedaCommandValidator()
{
RuleFor(x => x).Custom((model, context) =>
{
if (model.Source == null || model.Target == null)
context.AddFailure("Inform Source and Target to convert");
});
RuleFor(x => x.Value)
.NotEqual(0)
.WithMessage("Value shoud not be zero!");
}
}
}
| 29.363636 | 84 | 0.575851 | [
"MIT"
] | Agnei/CurrencyConvertion | src/Application/ConversorMoeda.Application/Validators/ConverterMoedaCommandValidator.cs | 648 | C# |
using HMUI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BeatSaberMultiplayer.Interop
{
internal interface IDismissable
{
FlowCoordinator ParentFlowCoordinator { get; set; }
void Dismiss(bool immediately);
}
}
| 20.0625 | 59 | 0.738318 | [
"MIT"
] | andruzzzhka/BeatSaberMultiplayer | BeatSaberMultiplayer/Interop/IDismissable.cs | 323 | C# |
using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using Tortuga.Chain.CommandBuilders;
using Tortuga.Chain.Core;
using Tortuga.Chain.Materializers;
using Tortuga.Chain.Metadata;
namespace Tortuga.Chain.SqlServer.CommandBuilders
{
/// <summary>
/// Use for table-valued functions.
/// </summary>
/// <seealso cref="TableDbCommandBuilder{OleDbCommand, OleDbParameter, SqlServerLimitOption}" />
internal class OleDbSqlServerTableFunction : TableDbCommandBuilder<OleDbCommand, OleDbParameter, SqlServerLimitOption>
{
readonly object? m_FunctionArgumentValue;
readonly TableFunctionMetadata<SqlServerObjectName, OleDbType> m_Table;
object? m_ArgumentValue;
FilterOptions m_FilterOptions;
object? m_FilterValue;
SqlServerLimitOption m_LimitOptions;
int? m_Seed;
string? m_SelectClause;
int? m_Skip;
IEnumerable<SortExpression> m_SortExpressions = Enumerable.Empty<SortExpression>();
int? m_Take;
string? m_WhereClause;
/// <summary>
/// Initializes a new instance of the <see cref="OleDbSqlServerTableFunction" /> class.
/// </summary>
/// <param name="dataSource">The data source.</param>
/// <param name="tableFunctionName">Name of the table function.</param>
/// <param name="functionArgumentValue">The function argument.</param>
public OleDbSqlServerTableFunction(OleDbSqlServerDataSourceBase dataSource, SqlServerObjectName tableFunctionName, object? functionArgumentValue) : base(dataSource)
{
m_Table = dataSource.DatabaseMetadata.GetTableFunction(tableFunctionName);
m_FunctionArgumentValue = functionArgumentValue;
}
/// <summary>
/// Gets the data source.
/// </summary>
/// <value>The data source.</value>
public new OleDbSqlServerDataSourceBase DataSource
{
get { return (OleDbSqlServerDataSourceBase)base.DataSource; }
}
/// <summary>
/// Returns the row count using a <c>SELECT Count(*)</c> style query.
/// </summary>
/// <returns></returns>
public override ILink<long> AsCount()
{
m_SelectClause = "COUNT_BIG(*)";
return ToInt64();
}
/// <summary>
/// Returns the row count for a given column. <c>SELECT Count(columnName)</c>
/// </summary>
/// <param name="columnName">Name of the column.</param>
/// <param name="distinct">if set to <c>true</c> use <c>SELECT COUNT(DISTINCT columnName)</c>.</param>
/// <returns></returns>
public override ILink<long> AsCount(string columnName, bool distinct = false)
{
var column = m_Table.Columns[columnName];
if (distinct)
m_SelectClause = $"COUNT_BIG(DISTINCT {column.QuotedSqlName})";
else
m_SelectClause = $"COUNT_BIG({column.QuotedSqlName})";
return ToInt64();
}
/// <summary>
/// Prepares the command for execution by generating any necessary SQL.
/// </summary>
/// <param name="materializer">The materializer.</param>
/// <returns>
/// ExecutionToken<TCommand>.
/// </returns>
/// <exception cref="NotImplementedException"></exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
public override CommandExecutionToken<OleDbCommand, OleDbParameter> Prepare(Materializer<OleDbCommand, OleDbParameter> materializer)
{
if (materializer == null)
throw new ArgumentNullException(nameof(materializer), $"{nameof(materializer)} is null.");
var sqlBuilder = m_Table.CreateSqlBuilder(StrictMode);
sqlBuilder.ApplyRulesForSelect(DataSource);
if (m_FunctionArgumentValue != null)
sqlBuilder.ApplyArgumentValue(DataSource, m_FunctionArgumentValue);
if (m_SelectClause == null)
{
var desired = materializer.DesiredColumns();
if (desired == Materializer.AutoSelectDesiredColumns)
desired = Materializer.AllColumns;
sqlBuilder.ApplyDesiredColumns(desired);
}
//Support check
if (!Enum.IsDefined(typeof(SqlServerLimitOption), m_LimitOptions))
throw new NotSupportedException($"SQL Server does not support limit option {(LimitOptions)m_LimitOptions}");
if (m_LimitOptions == SqlServerLimitOption.TableSampleSystemRows || m_LimitOptions == SqlServerLimitOption.TableSampleSystemPercentage)
throw new NotSupportedException($"SQL Server does not support limit option {(LimitOptions)m_LimitOptions} with table-valued functions");
if (m_Seed.HasValue)
throw new NotSupportedException($"SQL Server does not setting a random seed for table-valued functions");
//Validation
if (m_Skip < 0)
throw new InvalidOperationException($"Cannot skip {m_Skip} rows");
if (m_Skip > 0 && !m_SortExpressions.Any())
throw new InvalidOperationException($"Cannot perform a Skip operation with out a sort expression.");
if (m_Skip > 0 && m_LimitOptions != SqlServerLimitOption.Rows)
throw new InvalidOperationException($"Cannot perform a Skip operation with limit option {m_LimitOptions}");
if (m_Take <= 0)
throw new InvalidOperationException($"Cannot take {m_Take} rows");
if ((m_LimitOptions == SqlServerLimitOption.RowsWithTies || m_LimitOptions == SqlServerLimitOption.PercentageWithTies) && !m_SortExpressions.Any())
throw new InvalidOperationException($"Cannot perform a WITH TIES operation without sorting.");
//SQL Generation
List<OleDbParameter> parameters;
var sql = new StringBuilder();
string? topClause = null;
switch (m_LimitOptions)
{
case SqlServerLimitOption.Rows:
if (!m_SortExpressions.Any())
topClause = $"TOP ({m_Take}) ";
break;
case SqlServerLimitOption.Percentage:
topClause = $"TOP ({m_Take}) PERCENT ";
break;
case SqlServerLimitOption.PercentageWithTies:
topClause = $"TOP ({m_Take}) PERCENT WITH TIES ";
break;
case SqlServerLimitOption.RowsWithTies:
topClause = $"TOP ({m_Take}) WITH TIES ";
break;
}
if (m_SelectClause != null)
sql.Append($"SELECT {topClause} {m_SelectClause} ");
else
sqlBuilder.BuildSelectClause(sql, "SELECT " + topClause, null, null);
sqlBuilder.BuildAnonymousFromFunctionClause(sql, $" FROM {m_Table.Name.ToQuotedString()} (", " ) ");
if (m_FilterValue != null)
{
sql.Append(" WHERE " + sqlBuilder.ApplyAnonymousFilterValue(m_FilterValue, m_FilterOptions));
sqlBuilder.BuildAnonymousSoftDeleteClause(sql, " AND (", DataSource, ") ");
parameters = sqlBuilder.GetParameters();
}
else if (!string.IsNullOrWhiteSpace(m_WhereClause))
{
sql.Append(" WHERE " + m_WhereClause);
sqlBuilder.BuildAnonymousSoftDeleteClause(sql, " AND (", DataSource, ") ");
parameters = SqlBuilder.GetParameters<OleDbParameter>(m_ArgumentValue);
parameters.AddRange(sqlBuilder.GetParameters());
}
else
{
sqlBuilder.BuildAnonymousSoftDeleteClause(sql, " WHERE ", DataSource, null);
parameters = sqlBuilder.GetParameters();
}
sqlBuilder.BuildOrderByClause(sql, " ORDER BY ", m_SortExpressions, null);
switch (m_LimitOptions)
{
case SqlServerLimitOption.Rows:
if (m_SortExpressions.Any())
{
sql.Append(" OFFSET @offset_row_count_expression ROWS ");
parameters.Add(new OleDbParameter("@offset_row_count_expression", m_Skip ?? 0));
if (m_Take.HasValue)
{
sql.Append(" FETCH NEXT @fetch_row_count_expression ROWS ONLY");
parameters.Add(new OleDbParameter("@fetch_row_count_expression", m_Take));
}
}
//else
//{
// parameters.Add(new OleDbParameter("@fetch_row_count_expression", m_Take));
//}
break;
case SqlServerLimitOption.Percentage:
case SqlServerLimitOption.PercentageWithTies:
case SqlServerLimitOption.RowsWithTies:
break;
}
sql.Append(";");
return new OleDbCommandExecutionToken(DataSource, "Query Function " + m_Table.Name, sql.ToString(), parameters);
}
/// <summary>
/// Returns the column associated with the column name.
/// </summary>
/// <param name="columnName">Name of the column.</param>
/// <returns></returns>
/// <remarks>
/// If the column name was not found, this will return null
/// </remarks>
public override ColumnMetadata? TryGetColumn(string columnName)
{
return m_Table.Columns.TryGetColumn(columnName);
}
/// <summary>
/// Returns a list of columns known to be non-nullable.
/// </summary>
/// <returns>
/// If the command builder doesn't know which columns are non-nullable, an empty list will be returned.
/// </returns>
/// <remarks>
/// This is used by materializers to skip IsNull checks.
/// </remarks>
public override IReadOnlyList<ColumnMetadata> TryGetNonNullableColumns() => m_Table.NullableColumns;
/// <summary>
/// Adds (or replaces) the filter on this command builder.
/// </summary>
/// <param name="filterValue">The filter value.</param>
/// <param name="filterOptions">The filter options.</param>
/// <returns>TableDbCommandBuilder<OleDbCommand, OleDbParameter, SqlServerLimitOption>.</returns>
protected override TableDbCommandBuilder<OleDbCommand, OleDbParameter, SqlServerLimitOption> OnWithFilter(object filterValue, FilterOptions filterOptions = FilterOptions.None)
{
m_FilterValue = filterValue;
m_WhereClause = null;
m_ArgumentValue = null;
m_FilterOptions = filterOptions;
return this;
}
/// <summary>
/// Adds (or replaces) the filter on this command builder.
/// </summary>
/// <param name="whereClause">The where clause.</param>
/// <param name="argumentValue">The argument value.</param>
/// <returns></returns>
protected override TableDbCommandBuilder<OleDbCommand, OleDbParameter, SqlServerLimitOption> OnWithFilter(string whereClause, object? argumentValue)
{
m_FilterValue = null;
m_WhereClause = whereClause;
m_ArgumentValue = argumentValue;
return this;
}
/// <summary>
/// Adds sorting to the command builder.
/// </summary>
/// <param name="sortExpressions">The sort expressions.</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
protected override TableDbCommandBuilder<OleDbCommand, OleDbParameter, SqlServerLimitOption> OnWithSorting(IEnumerable<SortExpression> sortExpressions)
{
if (sortExpressions == null)
throw new ArgumentNullException(nameof(sortExpressions), $"{nameof(sortExpressions)} is null.");
m_SortExpressions = sortExpressions;
return this;
}
/// <summary>
/// Adds limits to the command builder.
/// </summary>
/// <param name="skip">The number of rows to skip.</param>
/// <param name="take">Number of rows to take.</param>
/// <param name="limitOptions">The limit options.</param>
/// <param name="seed">The seed for repeatable reads. Only applies to random sampling</param>
/// <returns></returns>
protected override TableDbCommandBuilder<OleDbCommand, OleDbParameter, SqlServerLimitOption> OnWithLimits(int? skip, int? take, SqlServerLimitOption limitOptions, int? seed)
{
m_Seed = seed;
m_Skip = skip;
m_Take = take;
m_LimitOptions = limitOptions;
return this;
}
/// <summary>
/// Adds limits to the command builder.
/// </summary>
/// <param name="skip">The number of rows to skip.</param>
/// <param name="take">Number of rows to take.</param>
/// <param name="limitOptions">The limit options.</param>
/// <param name="seed">The seed for repeatable reads. Only applies to random sampling</param>
/// <returns></returns>
protected override TableDbCommandBuilder<OleDbCommand, OleDbParameter, SqlServerLimitOption> OnWithLimits(int? skip, int? take, LimitOptions limitOptions, int? seed)
{
m_Seed = seed;
m_Skip = skip;
m_Take = take;
m_LimitOptions = (SqlServerLimitOption)limitOptions;
return this;
}
}
}
| 36.615625 | 177 | 0.716907 | [
"MIT"
] | TortugaResearch/Chain | Tortuga.Chain/Tortuga.Chain.SqlServer.OleDb/SqlServer/CommandBuilders/OleDbSqlServerTableFunction.cs | 11,719 | 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("PB-February-2016-1-Hungry-Garfield")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PB-February-2016-1-Hungry-Garfield")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("48efbb7e-4f43-4056-a96e-673d8a9a2913")]
// 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.810811 | 84 | 0.748607 | [
"MIT"
] | jeliozver/SoftUni-Work | Programming-Basics-May-2017/Old-Format-Exams/PB-February-2016-1-Hungry-Garfield/Properties/AssemblyInfo.cs | 1,439 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Discount.Grpc.Repositories;
using Discount.Grpc.Services;
namespace Discount.Grpc
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IDiscountRepository, DiscountRepository>();
services.AddAutoMapper(typeof(Startup));
services.AddGrpc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<DiscountService>();
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
});
});
}
}
}
| 35.104167 | 215 | 0.653412 | [
"MIT"
] | CodeWithKashif/AspNetMicroservices | src/Services/Discount/Discount.Grpc/Startup.cs | 1,687 | C# |
namespace Vidzy.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class EnhanceVideosTable : DbMigration
{
public override void Up()
{
Sql("ALTER TABLE dbo.Videos DROP CONSTRAINT DF__Videos__Classifi__07F6335A");
DropForeignKey("dbo.Videos", "Genre_Id", "dbo.Genres");
DropIndex("dbo.Videos", new[] { "Genre_Id" });
RenameColumn(table: "dbo.Videos", name: "Genre_Id", newName: "GenreId");
AlterColumn("dbo.Videos", "Name", c => c.String(nullable: false, maxLength: 255));
AlterColumn("dbo.Videos", "Classification", c => c.Byte(nullable: false));
AlterColumn("dbo.Videos", "GenreId", c => c.Byte(nullable: false));
CreateIndex("dbo.Videos", "GenreId");
AddForeignKey("dbo.Videos", "GenreId", "dbo.Genres", "Id", cascadeDelete: true);
}
public override void Down()
{
DropForeignKey("dbo.Videos", "GenreId", "dbo.Genres");
DropIndex("dbo.Videos", new[] { "GenreId" });
AlterColumn("dbo.Videos", "GenreId", c => c.Byte());
AlterColumn("dbo.Videos", "Classification", c => c.Int(nullable: false));
AlterColumn("dbo.Videos", "Name", c => c.String());
RenameColumn(table: "dbo.Videos", name: "GenreId", newName: "Genre_Id");
CreateIndex("dbo.Videos", "Genre_Id");
AddForeignKey("dbo.Videos", "Genre_Id", "dbo.Genres", "Id");
}
}
}
| 45.294118 | 94 | 0.575974 | [
"MIT"
] | tuvshinot/csharp | Entity/LoadingsAndExercise/Vidzy/Migrations/201510110403407_EnhanceVideosTable.cs | 1,540 | C# |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.Reflection;
using System.Threading;
using log4net;
using Nini.Config;
namespace OpenSim
{
/// <summary>
/// Consoleless OpenSim region server
/// </summary>
public class OpenSimBackground : OpenSim
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private ManualResetEvent WorldHasComeToAnEnd = new ManualResetEvent(false);
public OpenSimBackground(IConfigSource configSource) : base(configSource)
{
}
/// <summary>
/// Performs initialisation of the scene, such as loading configuration from disk.
/// </summary>
public override void Startup()
{
m_gui = false;
base.Startup();
m_log.InfoFormat("[OPENSIM MAIN]: Startup complete, serving {0} region{1}",
m_clientServers.Count.ToString(), m_clientServers.Count > 1 ? "s" : "");
WorldHasComeToAnEnd.WaitOne();
}
/// <summary>
/// Performs any last-minute sanity checking and shuts down the region server
/// </summary>
public override void Shutdown()
{
WorldHasComeToAnEnd.Set();
m_log.Info("[OPENSIM MAIN]: World has come to an end");
base.Shutdown();
}
}
} | 40.671233 | 111 | 0.684406 | [
"BSD-3-Clause"
] | WhiteCoreSim/WhiteCore-Merger | OpenSim/Region/Application/OpenSimBackground.cs | 2,969 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeetCode754
{
class Program
{
static void Main(string[] args)
{
}
}
public class Solution
{
public int ReachNumber(int target)
{
target = Math.Abs(target);
var sum = 0;
var result = 0;
while (sum < target)
{
result++;
sum += result;
}
var delta = sum - target;
if (delta % 2 == 0)
{
return result;
}
else
{
if (result % 2 == 0)
{
return result + 1;
}
else
{
return result + 2;
}
}
}
}
}
| 19.744681 | 42 | 0.372845 | [
"MIT"
] | Armin1995/LeetCode | LeetCode754/Program.cs | 930 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using PaymentAutomationLC.Data;
namespace PaymentAutomationLC.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20200524232201_ApplicationUser")]
partial class ApplicationUser
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.1")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderDisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("RoleId")
.HasColumnType("nvarchar(450)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Name")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("PaymentAutomationLC.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("DateAdded")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<string>("FirstName")
.HasColumnType("nvarchar(max)");
b.Property<string>("LastName")
.HasColumnType("nvarchar(max)");
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<string>("NormalizedEmail")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<int?>("PaymentProfileID")
.HasColumnType("int");
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(max)");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("bit");
b.Property<string>("UserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.HasIndex("PaymentProfileID");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("PaymentAutomationLC.Models.Article", b =>
{
b.Property<int>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ArticleTitle")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("DateWritten")
.HasColumnType("datetime2");
b.Property<int>("PageViews")
.HasColumnType("int");
b.Property<int>("PaymentID")
.HasColumnType("int");
b.Property<string>("Writer")
.HasColumnType("nvarchar(max)");
b.HasKey("ID");
b.HasIndex("PaymentID");
b.ToTable("Articles");
});
modelBuilder.Entity("PaymentAutomationLC.Models.Payment", b =>
{
b.Property<int>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("MonthYear")
.HasColumnType("nvarchar(max)");
b.HasKey("ID");
b.ToTable("Payments");
});
modelBuilder.Entity("PaymentAutomationLC.Models.PaymentProfile", b =>
{
b.Property<int>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<double>("ArticleBonus")
.HasColumnType("float");
b.Property<int>("MinimumPVForBonus")
.HasColumnType("int");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<double>("PayPerArticle")
.HasColumnType("float");
b.HasKey("ID");
b.ToTable("PaymentProfiles");
});
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("PaymentAutomationLC.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("PaymentAutomationLC.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("PaymentAutomationLC.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("PaymentAutomationLC.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("PaymentAutomationLC.Models.ApplicationUser", b =>
{
b.HasOne("PaymentAutomationLC.Models.PaymentProfile", "PaymentProfile")
.WithMany()
.HasForeignKey("PaymentProfileID");
});
modelBuilder.Entity("PaymentAutomationLC.Models.Article", b =>
{
b.HasOne("PaymentAutomationLC.Models.Payment", "Payment")
.WithMany("Articles")
.HasForeignKey("PaymentID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 37.62234 | 125 | 0.467553 | [
"MIT"
] | robin-j9/PaymentAutomationLC | PaymentAutomationLC/Data/Migrations/20200524232201_ApplicationUser.Designer.cs | 14,148 | C# |
using RbarExample.Entities;
using System;
using System.Linq;
namespace RbarExample.DataAccess.Repositories
{
public interface IItemRepository
{
Item Get(Guid itemId);
IQueryable<Item> Items { get; }
void Update(Item item);
}
}
| 17.625 | 46 | 0.634752 | [
"MIT"
] | RePierre/orm-rbar-example | src/RbarExample/DataAccess/Repositories/IItemRepository.cs | 284 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ASTRA.EMSG.Business.Services.Administration;
using ASTRA.EMSG.Business.Services.Common;
using ASTRA.EMSG.Common.Enums;
using ASTRA.EMSG.Web.Infrastructure.Security;
namespace ASTRA.EMSG.Web.Areas.Administration.Controllers
{
[AccessRights(Rolle.Applikationsadministrator)]
public class GlobalResourceController : Controller
{
private readonly ISessionService sessionService;
private readonly IGlobalResourceHandlerService globalResourceHandlerService;
public GlobalResourceController(
ISessionService sessionService,
IGlobalResourceHandlerService globalResourceHandlerService)
{
this.sessionService = sessionService;
this.globalResourceHandlerService = globalResourceHandlerService;
}
public ActionResult Index()
{
return View();
}
public ActionResult Upload(IEnumerable<HttpPostedFileBase> uploadFiles)
{
var httpPostedFileBase = uploadFiles.First();
sessionService.LastUploadErrorList = globalResourceHandlerService.UploadResource(httpPostedFileBase.InputStream, httpPostedFileBase.FileName);
return Content("");
}
public ActionResult GetLastUploadResult()
{
return PartialView("UploadResult", sessionService.LastUploadErrorList);
}
public ActionResult GetGlobalResources()
{
return File(globalResourceHandlerService.DownloadResources(), "application/x-compressed", "GetGlobalResources.zip");
}
}
}
| 34.285714 | 154 | 0.708929 | [
"BSD-3-Clause"
] | astra-emsg/ASTRA.EMSG | Master/ASTRA.EMSG.Web/Areas/Administration/Controllers/GlobalResourceController.cs | 1,682 | C# |
namespace Deloitte.Labs
{
using Microsoft.Xrm.Sdk;
using System.IO;
public class Import : IImport
{
private Super _super;
public void SetImport(Super pSuper)
{
_super = pSuper;
}
public void ImportaData()
{
string[] files = Common.GetFileOnFolder(_super);
foreach (var file in files)
{
var _lines = File.ReadAllText(file);
EntityCollection _object = Newtonsoft.Json.JsonConvert.DeserializeObject<EntityCollection>(_lines);
}
}
}
} | 24.08 | 115 | 0.553156 | [
"MIT"
] | Atili0/dlabs_alm | Deloitte.Labs.Common/Import.cs | 604 | C# |
using System;
namespace Automation.Concord
{
public enum MessageType
{
Unknown,
AlarmTrouble,
ArmingLevel,
AutomationEventLost,
ClearAutomationDynamicImage,
DynamicDataRefreshRequest,
EntryExitDelay,
EquipmentListComplete,
EquipmentListLightToSensor,
EquipmentListOutput,
EquipmentListPartition,
EquipmentListScheduledEvent,
EquipmentListSchedule,
EquipmentListSuperBusDevice,
EquipmentListSuperBusDeviceCapabilities,
EquipmentListUser,
EquipmentListZone,
FeatureState,
FullEquipmentListRequest,
Keyfob,
Keypress,
//Keypressed,
LightsState,
PanelType,
Reserved,
SingleEquipmentListRequest,
SirenGo,
SirenSetup,
SirenStop,
SirenSynchronize,
Temperature,
TimeAndDate,
TouchpadDisplay,
UserLights,
ZoneStatus
}
}
| 21.0625 | 48 | 0.615232 | [
"MIT"
] | markberndt/concord2mqtt | Concord/Enums/MessageType.cs | 1,013 | C# |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using Org.Apache.REEF.Common.Tasks;
namespace Org.Apache.REEF.Tests.Functional.Common.Task
{
public abstract class ExceptionTask : ITask
{
private readonly Exception _exToThrow;
protected ExceptionTask(Exception exToThrow)
{
_exToThrow = exToThrow;
}
public byte[] Call(byte[] memento)
{
throw _exToThrow;
}
public void Dispose()
{
}
}
} | 32.097561 | 64 | 0.669453 | [
"Apache-2.0"
] | AI-ML-Projects/reef | lang/cs/Org.Apache.REEF.Tests/Functional/Common/Task/ExceptionTask.cs | 1,278 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using StakeApp.Data.DatabaseContexts.ApplicationDbContext;
namespace StakeApp.Data.Migrations.ApplicationDb
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20200930131618_added columns to property entity")]
partial class addedcolumnstopropertyentity
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.8")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("StakeApp.Data.Entities.Contact", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<DateTime>("CreateAt")
.HasColumnType("datetime2");
b.Property<DateTime>("DeletedAt")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("LocalGovernmentArea")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<string>("state")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Contacts");
});
modelBuilder.Entity("StakeApp.Data.Entities.Property", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("Address")
.HasColumnType("nvarchar(max)");
b.Property<string>("ContactPhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreateAt")
.HasColumnType("datetime2");
b.Property<DateTime>("DeletedAt")
.HasColumnType("datetime2");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("ImageUrl")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<int>("NumberOfBaths")
.HasColumnType("int");
b.Property<int>("NumberOfRooms")
.HasColumnType("int");
b.Property<int>("NumberOfToilets")
.HasColumnType("int");
b.Property<double>("Price")
.HasColumnType("float");
b.Property<string>("Title")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Properties");
});
#pragma warning restore 612, 618
}
}
}
| 34.759615 | 117 | 0.51397 | [
"MIT"
] | Logic2114/stake-app | src/StakeApp.Data/Migrations/ApplicationDb/20200930131618_added columns to property entity.Designer.cs | 3,617 | 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: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Npoi.Ooxml")]
[assembly: AssemblyTrademark("")]
// 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("a2173a8b-1b9d-496d-b049-9010b0c49b23")]
[assembly: InternalsVisibleTo("Npoi.Core.TestCases")]
[assembly: InternalsVisibleTo("Npoi.Core.Ooxml.TestCases")] | 44.428571 | 84 | 0.783494 | [
"Apache-2.0"
] | Arch/Npoi.Core | src/Npoi.Core.Ooxml/Properties/AssemblyInfo.cs | 935 | C# |
namespace Commerce.Host
{
/// <summary>
/// Represents options for the product service.
/// </summary>
public class ProductServiceOptions
{
/// <summary>
/// Gets or sets the kind of service to use. "Memory", or "Production".
/// </summary>
public string Service { get; set; }
}
} | 26 | 80 | 0.568047 | [
"MIT"
] | Omegapoint/tdd2-net | Source/Commerce.Host/ProductServiceOptions.cs | 340 | C# |
#region License
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#endregion
using System;
using System.Collections.Generic;
using Gremlin.Net.Structure;
using Gremlin.Net.Structure.IO.GraphSON;
using Moq;
using Newtonsoft.Json.Linq;
using Xunit;
namespace Gremlin.Net.UnitTest.Structure.IO.GraphSON
{
public class GraphSONReaderTests
{
/// <summary>
/// Parameters for each test supporting multiple versions of GraphSON
/// </summary>
public static IEnumerable<object[]> Versions => new []
{
new object[] { 2 },
new object[] { 3 }
};
/// <summary>
/// Parameters for each collections test supporting multiple versions of GraphSON
/// </summary>
public static IEnumerable<object[]> VersionsSupportingCollections => new []
{
new object[] { 3 }
};
private GraphSONReader CreateStandardGraphSONReader(int version)
{
if (version == 3)
{
return new GraphSON3Reader();
}
return new GraphSON2Reader();
}
[Fact]
public void ShouldDeserializeWithCustomDeserializerForNewType()
{
var deserializerByGraphSONType = new Dictionary<string, IGraphSONDeserializer>
{
{"NS:TestClass", new TestGraphSONDeserializer()}
};
var reader = new GraphSON2Reader(deserializerByGraphSONType);
var graphSON = "{\"@type\":\"NS:TestClass\",\"@value\":\"test\"}";
var jObject = JObject.Parse(graphSON);
var readObj = reader.ToObject(jObject);
Assert.Equal("test", readObj.Value);
}
[Fact]
public void ShouldDeserializeWithCustomDeserializerForCommonType()
{
var customSerializerMock = new Mock<IGraphSONDeserializer>();
var overrideTypeString = "g:Int64";
var customSerializerByType = new Dictionary<string, IGraphSONDeserializer>
{
{overrideTypeString, customSerializerMock.Object}
};
var reader = new GraphSON2Reader(customSerializerByType);
reader.ToObject(JObject.Parse($"{{\"@type\":\"{overrideTypeString}\",\"@value\":12}}"));
customSerializerMock.Verify(m => m.Objectify(It.IsAny<JToken>(), It.IsAny<GraphSONReader>()));
}
[Theory, MemberData(nameof(Versions))]
public void ShouldDeserializeDateToDateTimeOffset(int version)
{
var graphSon = "{\"@type\":\"g:Date\",\"@value\":1475583442552}";
var reader = CreateStandardGraphSONReader(version);
DateTimeOffset deserializedValue = reader.ToObject(JObject.Parse(graphSon));
var expectedDateTimeOffset = TestUtils.FromJavaTime(1475583442552);
Assert.Equal(expectedDateTimeOffset, deserializedValue);
}
[Theory, MemberData(nameof(Versions))]
public void ShouldDeserializeDictionary(int version)
{
var serializedDict = "{\"age\":[{\"@type\":\"g:Int32\",\"@value\":29}],\"name\":[\"marko\"]}";
var reader = CreateStandardGraphSONReader(version);
var jObject = JObject.Parse(serializedDict);
var deserializedDict = reader.ToObject(jObject);
var expectedDict = new Dictionary<string, dynamic>
{
{"age", new List<object> {29}},
{"name", new List<object> {"marko"}}
};
Assert.Equal(expectedDict, deserializedDict);
}
[Theory, MemberData(nameof(Versions))]
public void ShouldDeserializeEdge(int version)
{
var graphSon =
"{\"@type\":\"g:Edge\", \"@value\":{\"id\":{\"@type\":\"g:Int64\",\"@value\":17},\"label\":\"knows\",\"inV\":\"x\",\"outV\":\"y\",\"inVLabel\":\"xLab\",\"properties\":{\"aKey\":\"aValue\",\"bKey\":true}}}";
var reader = CreateStandardGraphSONReader(version);
Edge readEdge = reader.ToObject(JObject.Parse(graphSon));
Assert.Equal((long) 17, readEdge.Id);
Assert.Equal("knows", readEdge.Label);
Assert.Equal(new Vertex("x", "xLabel"), readEdge.InV);
Assert.Equal(new Vertex("y"), readEdge.OutV);
}
[Theory, MemberData(nameof(Versions))]
public void ShouldDeserializeInt(int version)
{
var serializedValue = "{\"@type\":\"g:Int32\",\"@value\":5}";
var reader = CreateStandardGraphSONReader(version);
var jObject = JObject.Parse(serializedValue);
var deserializedValue = reader.ToObject(jObject);
Assert.Equal(5, deserializedValue);
}
[Theory, MemberData(nameof(Versions))]
public void ShouldDeserializeLong(int version)
{
var serializedValue = "{\"@type\":\"g:Int64\",\"@value\":5}";
var reader = CreateStandardGraphSONReader(version);
var jObject = JObject.Parse(serializedValue);
var deserializedValue = reader.ToObject(jObject);
Assert.Equal((long) 5, deserializedValue);
}
[Theory, MemberData(nameof(Versions))]
public void ShouldDeserializeFloat(int version)
{
var serializedValue = "{\"@type\":\"g:Float\",\"@value\":31.3}";
var reader = CreateStandardGraphSONReader(version);
var jObject = JObject.Parse(serializedValue);
var deserializedValue = reader.ToObject(jObject);
Assert.Equal((float) 31.3, deserializedValue);
}
[Theory, MemberData(nameof(Versions))]
public void ShouldDeserializeDouble(int version)
{
var serializedValue = "{\"@type\":\"g:Double\",\"@value\":31.2}";
var reader = CreateStandardGraphSONReader(version);
var jObject = JObject.Parse(serializedValue);
var deserializedValue = reader.ToObject(jObject);
Assert.Equal(31.2, deserializedValue);
}
[Theory, MemberData(nameof(Versions))]
public void ShouldDeserializeDecimal(int version)
{
var serializedValue = "{\"@type\":\"gx:BigDecimal\",\"@value\":-8.201}";
var reader = CreateStandardGraphSONReader(version);
var jObject = JObject.Parse(serializedValue);
decimal deserializedValue = reader.ToObject(jObject);
Assert.Equal(-8.201M, deserializedValue);
}
[Theory, MemberData(nameof(Versions))]
public void ShouldDeserializeDecimalValueAsString(int version)
{
var serializedValue = "{\"@type\":\"gx:BigDecimal\",\"@value\":\"7.50\"}";
var reader = CreateStandardGraphSONReader(version);
var jObject = JObject.Parse(serializedValue);
decimal deserializedValue = reader.ToObject(jObject);
Assert.Equal(7.5M, deserializedValue);
}
[Theory, MemberData(nameof(Versions))]
public void ShouldDeserializeList(int version)
{
var serializedValue = "[{\"@type\":\"g:Int32\",\"@value\":5},{\"@type\":\"g:Int32\",\"@value\":6}]";
var reader = CreateStandardGraphSONReader(version);
var jObject = JArray.Parse(serializedValue);
var deserializedValue = reader.ToObject(jObject);
Assert.Equal(new List<object> {5, 6}, deserializedValue);
}
[Fact]
public void ShouldDeserializePathFromGraphSON2()
{
var graphSon =
"{\"@type\":\"g:Path\",\"@value\":{\"labels\":[[\"a\"],[\"b\",\"c\"],[]],\"objects\":[{\"@type\":\"g:Vertex\",\"@value\":{\"id\":{\"@type\":\"g:Int32\",\"@value\":1},\"label\":\"person\",\"properties\":{\"name\":[{\"@type\":\"g:VertexProperty\",\"@value\":{\"id\":{\"@type\":\"g:Int64\",\"@value\":0},\"value\":\"marko\",\"label\":\"name\"}}],\"age\":[{\"@type\":\"g:VertexProperty\",\"@value\":{\"id\":{\"@type\":\"g:Int64\",\"@value\":1},\"value\":{\"@type\":\"g:Int32\",\"@value\":29},\"label\":\"age\"}}]}}},{\"@type\":\"g:Vertex\",\"@value\":{\"id\":{\"@type\":\"g:Int32\",\"@value\":3},\"label\":\"software\",\"properties\":{\"name\":[{\"@type\":\"g:VertexProperty\",\"@value\":{\"id\":{\"@type\":\"g:Int64\",\"@value\":4},\"value\":\"lop\",\"label\":\"name\"}}],\"lang\":[{\"@type\":\"g:VertexProperty\",\"@value\":{\"id\":{\"@type\":\"g:Int64\",\"@value\":5},\"value\":\"java\",\"label\":\"lang\"}}]}}},\"lop\"]}}";
var reader = CreateStandardGraphSONReader(2);
Path readPath = reader.ToObject(JObject.Parse(graphSon));
Assert.Equal("path[v[1], v[3], lop]", readPath.ToString());
Assert.Equal(new Vertex(1), readPath[0]);
Assert.Equal(new Vertex(1), readPath["a"]);
Assert.Equal("lop", readPath[2]);
Assert.Equal(3, readPath.Count);
}
[Fact]
public void ShouldDeserializePathFromGraphSON3()
{
var graphSon = "{\"@type\":\"g:Path\",\"@value\":{" +
"\"labels\":{\"@type\":\"g:List\",\"@value\":[{\"@type\":\"g:Set\",\"@value\":[\"z\"]}]}," +
"\"objects\":{\"@type\":\"g:List\",\"@value\":[{\"@type\":\"g:Vertex\",\"@value\":{\"id\":{\"@type\":\"g:Int64\",\"@value\":5},\"label\":\"\"}}]}}}";
var reader = CreateStandardGraphSONReader(3);
Path readPath = reader.ToObject(JObject.Parse(graphSon));
Assert.Equal("path[v[5]]", readPath.ToString());
Assert.Equal(new Vertex(5L), readPath[0]);
Assert.Equal(new Vertex(5L), readPath["z"]);
Assert.Equal(1, readPath.Count);
}
[Theory, MemberData(nameof(Versions))]
public void ShouldDeserializePropertyWithEdgeElement(int version)
{
var graphSon =
"{\"@type\":\"g:Property\",\"@value\":{\"key\":\"aKey\",\"value\":{\"@type\":\"g:Int64\",\"@value\":17},\"element\":{\"@type\":\"g:Edge\",\"@value\":{\"id\":{\"@type\":\"g:Int64\",\"@value\":122},\"label\":\"knows\",\"inV\":\"x\",\"outV\":\"y\",\"inVLabel\":\"xLab\"}}}}";
var reader = CreateStandardGraphSONReader(version);
Property readProperty = reader.ToObject(JObject.Parse(graphSon));
Assert.Equal("aKey", readProperty.Key);
Assert.Equal((long) 17, readProperty.Value);
Assert.Equal(typeof(Edge), readProperty.Element.GetType());
var edge = readProperty.Element as Edge;
Assert.Equal((long) 122, edge.Id);
Assert.Equal("knows", edge.Label);
Assert.Equal("x", edge.InV.Id);
Assert.Equal("y", edge.OutV.Id);
}
[Theory, MemberData(nameof(Versions))]
public void ShouldDeserializeTimestampToDateTimeOffset(int version)
{
var graphSon = "{\"@type\":\"g:Timestamp\",\"@value\":1475583442558}";
var reader = CreateStandardGraphSONReader(version);
DateTimeOffset deserializedValue = reader.ToObject(JObject.Parse(graphSon));
var expectedDateTimeOffset = TestUtils.FromJavaTime(1475583442558);
Assert.Equal(expectedDateTimeOffset, deserializedValue);
}
[Theory, MemberData(nameof(Versions))]
public void ShouldDeserializeGuid(int version)
{
var graphSon = "{\"@type\":\"g:UUID\",\"@value\":\"41d2e28a-20a4-4ab0-b379-d810dede3786\"}";
var reader = CreateStandardGraphSONReader(version);
Guid readGuid = reader.ToObject(JObject.Parse(graphSon));
Assert.Equal(Guid.Parse("41d2e28a-20a4-4ab0-b379-d810dede3786"), readGuid);
}
[Theory, MemberData(nameof(Versions))]
public void ShouldDeserializeVertexProperty(int version)
{
var graphSon =
"{\"@type\":\"g:VertexProperty\",\"@value\":{\"id\":\"anId\",\"label\":\"aKey\",\"value\":true,\"vertex\":{\"@type\":\"g:Int32\",\"@value\":9}}}";
var reader = CreateStandardGraphSONReader(version);
VertexProperty readVertexProperty = reader.ToObject(JObject.Parse(graphSon));
Assert.Equal("anId", readVertexProperty.Id);
Assert.Equal("aKey", readVertexProperty.Label);
Assert.True(readVertexProperty.Value);
Assert.NotNull(readVertexProperty.Vertex);
}
[Theory, MemberData(nameof(Versions))]
public void ShouldDeserializeVertexPropertyWithLabel(int version)
{
var graphSon =
"{\"@type\":\"g:VertexProperty\", \"@value\":{\"id\":{\"@type\":\"g:Int32\",\"@value\":1},\"label\":\"name\",\"value\":\"marko\"}}";
var reader = CreateStandardGraphSONReader(version);
VertexProperty readVertexProperty = reader.ToObject(JObject.Parse(graphSon));
Assert.Equal(1, readVertexProperty.Id);
Assert.Equal("name", readVertexProperty.Label);
Assert.Equal("marko", readVertexProperty.Value);
Assert.Null(readVertexProperty.Vertex);
}
[Theory, MemberData(nameof(Versions))]
public void ShouldDeserializeVertex(int version)
{
var graphSon = "{\"@type\":\"g:Vertex\", \"@value\":{\"id\":{\"@type\":\"g:Float\",\"@value\":45.23}}}";
var reader = CreateStandardGraphSONReader(version);
var readVertex = reader.ToObject(JObject.Parse(graphSon));
Assert.Equal(new Vertex(45.23f), readVertex);
}
[Theory, MemberData(nameof(Versions))]
public void ShouldDeserializeVertexWithEdges(int version)
{
var graphSon =
"{\"@type\":\"g:Vertex\", \"@value\":{\"id\":{\"@type\":\"g:Int32\",\"@value\":1},\"label\":\"person\",\"outE\":{\"created\":[{\"id\":{\"@type\":\"g:Int32\",\"@value\":9},\"inV\":{\"@type\":\"g:Int32\",\"@value\":3},\"properties\":{\"weight\":{\"@type\":\"g:Double\",\"@value\":0.4}}}],\"knows\":[{\"id\":{\"@type\":\"g:Int32\",\"@value\":7},\"inV\":{\"@type\":\"g:Int32\",\"@value\":2},\"properties\":{\"weight\":{\"@type\":\"g:Double\",\"@value\":0.5}}},{\"id\":{\"@type\":\"g:Int32\",\"@value\":8},\"inV\":{\"@type\":\"g:Int32\",\"@value\":4},\"properties\":{\"weight\":{\"@type\":\"g:Double\",\"@value\":1.0}}}]},\"properties\":{\"name\":[{\"id\":{\"@type\":\"g:Int64\",\"@value\":0},\"value\":\"marko\"}],\"age\":[{\"id\":{\"@type\":\"g:Int64\",\"@value\":1},\"value\":{\"@type\":\"g:Int32\",\"@value\":29}}]}}}";
var reader = CreateStandardGraphSONReader(version);
var readVertex = reader.ToObject(JObject.Parse(graphSon));
Assert.Equal(new Vertex(1), readVertex);
Assert.Equal("person", readVertex.Label);
Assert.Equal(typeof(int), readVertex.Id.GetType());
}
[Theory, MemberData(nameof(VersionsSupportingCollections))]
public void ShouldDeserializeEmptyGList(int version)
{
var graphSon =
"{\"@type\":\"g:List\", \"@value\": []}";
var reader = CreateStandardGraphSONReader(version);
var deserializedValue = reader.ToObject(JObject.Parse(graphSon));
Assert.Equal(new object[0], deserializedValue);
}
[Theory, MemberData(nameof(VersionsSupportingCollections))]
public void ShouldDeserializeGList(int version)
{
const string json = "{\"@type\":\"g:List\", \"@value\": [{\"@type\": \"g:Int32\", \"@value\": 1}," +
"{\"@type\": \"g:Int32\", \"@value\": 2}, {\"@type\": \"g:Int32\", \"@value\": 3}]}";
var reader = CreateStandardGraphSONReader(version);
var deserializedValue = reader.ToObject(JObject.Parse(json));
Assert.Equal((IList<object>)new object[] { 1, 2, 3}, deserializedValue);
}
[Theory, MemberData(nameof(VersionsSupportingCollections))]
public void ShouldDeserializeGSet(int version)
{
const string json = "{\"@type\":\"g:Set\", \"@value\": [{\"@type\": \"g:Int32\", \"@value\": 1}," +
"{\"@type\": \"g:Int32\", \"@value\": 2}, {\"@type\": \"g:Int32\", \"@value\": 3}]}";
var reader = CreateStandardGraphSONReader(version);
var deserializedValue = reader.ToObject(JObject.Parse(json));
Assert.Equal((ISet<object>)new HashSet<object>{ 1, 2, 3}, deserializedValue);
}
[Theory, MemberData(nameof(VersionsSupportingCollections))]
public void ShouldDeserializeGMap(int version)
{
const string json = "{\"@type\":\"g:Map\", \"@value\": [\"a\",{\"@type\": \"g:Int32\", \"@value\": 1}, " +
"\"b\", {\"@type\": \"g:Int32\", \"@value\": 2}]}";
var reader = CreateStandardGraphSONReader(version);
var deserializedValue = reader.ToObject(JObject.Parse(json));
Assert.Equal(new Dictionary<object, object>{ { "a", 1 }, { "b", 2 }}, deserializedValue);
}
[Fact]
public void ShouldDeserializeTraverser()
{
dynamic d = JObject.Parse("{\"@type\":\"g:Traverser\",\"@value\":1}");
Assert.NotNull(d);
Assert.Equal("g:Traverser", (string)d["@type"]);
}
}
internal class TestGraphSONDeserializer : IGraphSONDeserializer
{
public dynamic Objectify(JToken graphsonObject, GraphSONReader reader)
{
return new TestClass {Value = graphsonObject.ToString()};
}
}
} | 44.507212 | 939 | 0.565703 | [
"Apache-2.0"
] | alexdrenea/tinkerpop | gremlin-dotnet/test/Gremlin.Net.UnitTest/Structure/IO/GraphSON/GraphSONReaderTests.cs | 18,517 | C# |
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Core.Arango.Protocol;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Core.Arango
{
public partial class ArangoContext
{
public async Task<JObject> ExecuteTransactionAsync(ArangoHandle database, ArangoTransaction request,
CancellationToken cancellationToken = default)
{
return await SendAsync<JObject>(HttpMethod.Post,
$"{Server}/_db/{DbName(database)}/_api/transaction",
JsonConvert.SerializeObject(request, JsonSerializerSettings), cancellationToken: cancellationToken);
}
public async Task<ArangoHandle> BeginTransactionAsync(ArangoHandle database, ArangoTransaction request,
CancellationToken cancellationToken = default)
{
var res = await SendAsync<JObject>(HttpMethod.Post,
$"{Server}/_db/{DbName(database)}/_api/transaction/begin",
JsonConvert.SerializeObject(request, JsonSerializerSettings), cancellationToken: cancellationToken);
var transaction = res.GetValue("result").Value<string>("id");
return new ArangoHandle(database, transaction);
}
public async Task CommitTransactionAsync(ArangoHandle database,
CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(database.Transaction))
throw new ArangoException("no transaction handle");
await SendAsync<JObject>(HttpMethod.Put,
$"{Server}/_db/{DbName(database)}/_api/transaction/{database.Transaction}",
cancellationToken: cancellationToken);
}
public async Task AbortTransactionAsync(ArangoHandle database, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(database.Transaction))
throw new ArangoException("no transaction handle");
await SendAsync<JObject>(HttpMethod.Delete,
$"{Server}/_db/{DbName(database)}/_api/transaction/{database.Transaction}",
cancellationToken: cancellationToken);
}
}
} | 42.576923 | 117 | 0.672087 | [
"MIT"
] | JTOne123/ArangoDB | Core.Arango/ArangoContext.Transaction.cs | 2,216 | C# |
using System;
using ColossalFramework.UI;
using CustomizeItExtended.GUI;
using CustomizeItExtended.GUI.Citizens;
using CustomizeItExtended.Internal.Citizens;
using UnityEngine;
namespace CustomizeItExtended.Extensions
{
public static class CitizenExtensions
{
public static UICitizenPanelWrapper GenerateCitizenPanel(this Citizen citizen, uint citizenID)
{
try
{
CustomizeItExtendedCitizenTool.instance.SelectedCitizen = citizenID;
UiUtils.DeepDestroy(UIView.Find("CustomizeItExtendedCitizenPanelWrapper"));
return UIView.GetAView().AddUIComponent(typeof(UICitizenPanelWrapper)) as UICitizenPanelWrapper;
}
catch (Exception e)
{
Debug.Log($"{e.Message} - {e.StackTrace}");
return null;
}
}
}
} | 31.571429 | 112 | 0.651584 | [
"MIT"
] | Celisuis/CustomizeItEnhanced | CustomizeItExtended/Extensions/CitizenExtensions.cs | 886 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Linq;
using System.Text;
namespace Microsoft.DiaSymReader.Tools
{
internal static class PdbToXmlApp
{
internal sealed class Args
{
public readonly string InputPath;
public readonly string OutputPath;
public readonly PdbToXmlOptions Options;
public readonly bool Delta;
public Args(string inputPath, string outputPath, bool delta, PdbToXmlOptions options)
{
InputPath = inputPath;
OutputPath = outputPath;
Delta = delta;
Options = options;
}
}
public static int Main(string[] args)
{
Args parsedArgs;
try
{
parsedArgs = ParseArgs(args);
}
catch (InvalidDataException e)
{
Console.Error.WriteLine("Usage: Pdb2Xml <PEFile | DeltaPdb> [/out <output file>] [/tokens] [/methodSpans] [/delta] [/srcsvr] [/sources] [/native]");
Console.Error.WriteLine();
Console.Error.WriteLine(e.Message);
return 1;
}
try
{
Convert(parsedArgs);
Console.WriteLine($"PDB dump written to {parsedArgs.OutputPath}");
return 0;
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
return 2;
}
}
// internal for testing
internal static Args ParseArgs(string[] args)
{
string? inputPath = null;
string? outputPath = null;
bool delta = false;
var options = PdbToXmlOptions.ResolveTokens | PdbToXmlOptions.IncludeModuleDebugInfo;
int i = 0;
while (i < args.Length)
{
var arg = args[i++];
string ReadValue() => (i < args.Length) ? args[i++] : throw new InvalidDataException(string.Format("Missing value for option '{0}'", arg));
switch (arg)
{
case "/out":
outputPath = ReadValue();
break;
case "/delta":
delta = true;
break;
case "/tokens":
options |= PdbToXmlOptions.IncludeTokens;
break;
case "/methodSpans":
options |= PdbToXmlOptions.IncludeMethodSpans;
break;
case "/srcsvr":
options |= PdbToXmlOptions.IncludeSourceServerInformation;
break;
case "/sources":
options |= PdbToXmlOptions.IncludeEmbeddedSources;
break;
case "/native":
options |= PdbToXmlOptions.UseNativeReader;
break;
default:
if (inputPath == null)
{
inputPath = arg;
}
else
{
throw new InvalidDataException((arg.StartsWith("/", StringComparison.Ordinal) ?
string.Format("Unrecognized option: '{0}'", arg) :
"Only one input file path can be specified"));
}
break;
}
}
if (inputPath == null)
{
throw new InvalidDataException("Missing input file path.");
}
if (outputPath == null)
{
try
{
outputPath = Path.ChangeExtension(inputPath, "xml");
}
catch (Exception e)
{
throw new InvalidDataException(e.Message);
}
}
return new Args(
inputPath: inputPath,
outputPath: outputPath,
delta: delta,
options: options);
}
public static void Convert(Args args)
{
string? peFile;
string? pdbFile;
if (args.Delta)
{
peFile = null;
pdbFile = args.InputPath;
}
else
{
peFile = args.InputPath;
pdbFile = Path.ChangeExtension(args.InputPath, ".pdb");
}
if (peFile != null && !File.Exists(peFile))
{
throw new FileNotFoundException($"File not found: {peFile}");
}
if (!File.Exists(pdbFile))
{
throw new FileNotFoundException($"PDB File not found: {pdbFile}");
}
if (args.Delta)
{
GenXmlFromDeltaPdb(pdbFile, args.OutputPath);
}
else
{
GenXmlFromPdb(peFile!, pdbFile, args.OutputPath, args.Options);
}
}
public static void GenXmlFromPdb(string exePath, string pdbPath, string outPath, PdbToXmlOptions options)
{
using var peStream = new FileStream(exePath, FileMode.Open, FileAccess.Read);
using var pdbStream = new FileStream(pdbPath, FileMode.Open, FileAccess.Read);
using var dstFileStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite);
using var sw = new StreamWriter(dstFileStream, Encoding.UTF8);
PdbToXmlConverter.ToXml(sw, pdbStream, peStream, options);
}
public static void GenXmlFromDeltaPdb(string pdbPath, string outPath)
{
using var deltaPdb = new FileStream(pdbPath, FileMode.Open, FileAccess.Read);
// There is no easy way to enumerate all method tokens that are present in the PDB.
// So dump the first 255 method tokens (the ones that are not present will be skipped):
File.WriteAllText(outPath, PdbToXmlConverter.DeltaPdbToXml(deltaPdb, Enumerable.Range(0x06000001, 255)));
}
}
} | 33.523077 | 164 | 0.478507 | [
"Apache-2.0"
] | akoeplinger/symreader-converter | src/Pdb2Xml/PdbToXml.cs | 6,537 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using Xunit;
namespace System.Reflection.Emit.Tests
{
public class MethodBuilderToString1
{
private const string TestDynamicAssemblyName = "TestDynamicAssembly";
private const string TestDynamicModuleName = "TestDynamicModule";
private const string TestDynamicTypeName = "TestDynamicType";
private const AssemblyBuilderAccess TestAssemblyBuilderAccess = AssemblyBuilderAccess.Run;
private const TypeAttributes TestTypeAttributes = TypeAttributes.Abstract;
private const MethodAttributes TestMethodAttributes = MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual;
private const int MinStringLength = 1;
private const int MaxStringLength = 128;
private readonly RandomDataGenerator _generator = new RandomDataGenerator();
private readonly byte[] _defaultILArray = new byte[] {
0x00,
0x72,
0x01,
0x00,
0x00,
0x70,
0x28,
0x04,
0x00,
0x00,
0x0a,
0x00,
0x2a
};
private TypeBuilder GetTestTypeBuilder()
{
AssemblyName assemblyName = new AssemblyName(TestDynamicAssemblyName);
AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(
assemblyName, TestAssemblyBuilderAccess);
ModuleBuilder moduleBuilder = TestLibrary.Utilities.GetModuleBuilder(assemblyBuilder, "Module1");
return moduleBuilder.DefineType(TestDynamicTypeName, TestTypeAttributes);
}
[Fact]
public void TestWithAllFieldsSet()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
ILGenerator ilgen = builder.GetILGenerator();
ilgen.Emit(OpCodes.Ret);
string[] typeParamNames = { "T" };
GenericTypeParameterBuilder[] typeParameters =
builder.DefineGenericParameters(typeParamNames);
GenericTypeParameterBuilder desiredReturnType = typeParameters[0];
builder.SetSignature(desiredReturnType.AsType(), null, null, null, null, null);
string actualString = builder.ToString();
string desiredString = GetDesiredMethodToString(builder);
Assert.NotNull(actualString);
Assert.Contains(desiredString, actualString);
}
[Fact]
public void TestWithNameAndAttributeSet()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.Public);
string actualString = builder.ToString();
string desiredString = GetDesiredMethodToString(builder);
Assert.NotNull(actualString);
Assert.Contains(desiredString, actualString);
}
[Fact]
public void TestWithNameAttributeAndSignatureSet()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetSignature(typeof(void), null, null, null, null, null);
string actualString = builder.ToString();
string desiredString = GetDesiredMethodToString(builder);
Assert.NotNull(actualString);
Assert.Contains(desiredString, actualString);
}
private string GetDesiredMethodToString(MethodBuilder builder)
{
// Avoid use string.Format or StringBuilder
return "Name: " + builder.Name + " " + Environment.NewLine +
"Attributes: " + ((int)builder.Attributes).ToString() + Environment.NewLine +
"Method Signature: ";
}
}
}
| 40.587719 | 141 | 0.648801 | [
"MIT"
] | 690486439/corefx | src/System.Reflection.Emit/tests/MethodBuilder/MethodBuilderToString.cs | 4,627 | C# |
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Threading.Tasks;
using Voltaic;
namespace Wumpus.Server.Binders
{
public class VoltaicUtf8StringModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
throw new ArgumentNullException(nameof(bindingContext));
var modelName = bindingContext.FieldName ?? bindingContext.ModelMetadata.ParameterName;
var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
if (valueProviderResult == ValueProviderResult.None)
return Task.CompletedTask;
bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);
var value = valueProviderResult.FirstValue;
if (string.IsNullOrEmpty(value))
return Task.CompletedTask;
bindingContext.Result = ModelBindingResult.Success(new Utf8String(value));
return Task.CompletedTask;
}
}
}
| 34.645161 | 99 | 0.68622 | [
"MIT"
] | Aux/Wumpus.Net | test/Wumpus.Net.Tests.Server/Binders/VoltaicUtf8StringModelBinder.cs | 1,076 | C# |
using Alturos.Yolo.LearningImage.Helper;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Alturos.Yolo.LearningImage.Model
{
public class AnnotationPackage
{
public string ExternalId { get; set; }
public string PackagePath { get; set; }
public string DisplayName { get; set; }
public long TotalBytes { get; set; }
public bool Downloading { get; set; }
public double DownloadProgress { get; set; }
public long TransferredBytes { get; set; }
public bool Extracted { get; set; }
public bool IsDirty { get; set; }
public bool IsAnnotated { get; set; }
public double AnnotationPercentage { get; set; }
public List<AnnotationImage> Images { get; set; }
public List<string> Tags { get; set; }
private FileInfo[] _files;
public void PrepareImages()
{
if (this.Images == null)
{
this.Images = new List<AnnotationImage>();
}
if (this._files == null)
{
var allowedExtensions = new[] { ".png", ".jpg", ".bmp" };
this._files = Directory.GetFiles(this.PackagePath)
.Where(file => allowedExtensions.Any(file.ToLower().EndsWith))
.Select(o => new FileInfo(o))
.OrderBy(o => o.Name.GetFirstNumber())
.ToArray();
}
var query = from file in this._files
join image in this.Images on file.Name equals image.ImageName into j1
from annotationImage in j1.DefaultIfEmpty(new AnnotationImage())
select new AnnotationImage
{
BoundingBoxes = annotationImage?.BoundingBoxes,
ImageName = file.Name,
ImagePath = file.FullName,
Package = this
};
this.Images = query.ToList();
}
public void UpdateAnnotationStatus(AnnotationImage annotationImage)
{
if (!this.Images.Contains(annotationImage))
{
this.Images.Add(annotationImage);
}
var annotationPercentage = this.Images.Count(o => o.BoundingBoxes != null) / (double)this.Images.Count * 100.0;
this.AnnotationPercentage = annotationPercentage;
this.IsAnnotated = annotationPercentage >= 100;
}
public string DirtyDisplayName
{
get
{
// An asterisk is commonly attached to filenames when they are dirty
return $"{this.DisplayName}{(this.IsDirty ? "*" : "")}";
}
}
}
}
| 33.916667 | 123 | 0.527905 | [
"MIT"
] | LKneringer/Alturos.Yolo | src/Alturos.Yolo.LearningImage/Model/AnnotationPackage.cs | 2,851 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.