content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
//------------------------------------------------------------------------------
// <copyright file="QilTernary.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">Microsoft</owner>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Xml.Xsl.Qil {
/// <summary>
/// View over a Qil operator having three children.
/// </summary>
/// <remarks>
/// Don't construct QIL nodes directly; instead, use the <see cref="QilFactory">QilFactory</see>.
/// </remarks>
internal class QilTernary : QilNode {
private QilNode left, center, right;
//-----------------------------------------------
// Constructor
//-----------------------------------------------
/// <summary>
/// Construct a new node
/// </summary>
public QilTernary(QilNodeType nodeType, QilNode left, QilNode center, QilNode right) : base(nodeType) {
this.left = left;
this.center = center;
this.right = right;
}
//-----------------------------------------------
// IList<QilNode> methods -- override
//-----------------------------------------------
public override int Count {
get { return 3; }
}
public override QilNode this[int index] {
get {
switch (index) {
case 0: return this.left;
case 1: return this.center;
case 2: return this.right;
default: throw new IndexOutOfRangeException();
}
}
set {
switch (index) {
case 0: this.left = value; break;
case 1: this.center = value; break;
case 2: this.right = value; break;
default: throw new IndexOutOfRangeException();
}
}
}
//-----------------------------------------------
// QilTernary methods
//-----------------------------------------------
public QilNode Left {
get { return this.left; }
set { this.left = value; }
}
public QilNode Center {
get { return this.center; }
set { this.center = value; }
}
public QilNode Right {
get { return this.right; }
set { this.right = value; }
}
}
}
| 31.164706 | 111 | 0.413364 | [
"MIT"
] | Abdalla-rabie/referencesource | System.Data.SqlXml/System/Xml/Xsl/QIL/QilTernary.cs | 2,649 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class testnavmesh : MonoBehaviour {
[SerializeField] NavMeshBuildSource source;
public void Start()
{
source = BoxSource10x10();
}
// Make a build source for a box in local space
public NavMeshBuildSource BoxSource10x10()
{
var src = new NavMeshBuildSource();
src.transform = transform.localToWorldMatrix;
src.shape = NavMeshBuildSourceShape.Sphere;
src.size = new Vector3(10.0f, 10f, 10.0f);
return src;
}
}
| 26.458333 | 57 | 0.63937 | [
"MIT"
] | joansolroo/ProceduralWorlds | Assets/Navmesh/testnavmesh.cs | 637 | C# |
namespace YalvLib.Common
{
using System;
using System.Diagnostics;
using System.Windows.Input;
/// <summary>
/// A command whose sole purpose is to
/// relay its functionality to other
/// objects by invoking delegates. The
/// default return value for the CanExecute
/// method is 'true'.
///
/// Source: http://www.codeproject.com/Articles/31837/Creating-an-Internationalized-Wizard-in-WPF
/// </summary>
internal class RelayCommand<T> : ICommand
{
#region Fields
private readonly Action<T> mExecute = null;
private readonly Predicate<T> mCanExecute = null;
#endregion // Fields
#region Constructors
/// <summary>
/// Class constructor
/// </summary>
/// <param name="execute"></param>
public RelayCommand(Action<T> execute)
: this(execute, null)
{
}
/// <summary>
/// Creates a new command.
/// </summary>
/// <param name="execute">The execution logic.</param>
/// <param name="canExecute">The execution status logic.</param>
public RelayCommand(Action<T> execute, Predicate<T> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
this.mExecute = execute;
this.mCanExecute = canExecute;
}
#endregion // Constructors
#region events
/// <summary>
/// Eventhandler to re-evaluate whether this command can execute or not
/// </summary>
public event EventHandler CanExecuteChanged
{
add
{
if (this.mCanExecute != null)
CommandManager.RequerySuggested += value;
}
remove
{
if (this.mCanExecute != null)
CommandManager.RequerySuggested -= value;
}
}
#endregion
#region methods
/// <summary>
/// Determine whether this pre-requisites to execute this command are given or not.
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return this.mCanExecute == null ? true : this.mCanExecute((T)parameter);
}
/// <summary>
/// Execute the command method managed in this class.
/// </summary>
/// <param name="parameter"></param>
public void Execute(object parameter)
{
this.mExecute((T)parameter);
}
#endregion methods
}
}
| 29.402174 | 101 | 0.544917 | [
"MIT"
] | Dirkster99/YalvLib | src/YalvLib/Common/RelayCommand.cs | 2,707 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Xunit;
namespace Microsoft.EntityFrameworkCore.Metadata
{
public class SequenceTest
{
[Fact]
public void Can_be_created_with_default_values()
{
var sequence = new Model().Relational().GetOrAddSequence("Foo");
Assert.Equal("Foo", sequence.Name);
Assert.Null(sequence.Schema);
Assert.Equal(1, sequence.IncrementBy);
Assert.Equal(1, sequence.StartValue);
Assert.Null(sequence.MinValue);
Assert.Null(sequence.MaxValue);
Assert.Same(typeof(long), sequence.ClrType);
}
[Fact]
public void Can_be_created_with_specified_values()
{
var sequence = new Model().Relational().GetOrAddSequence("Foo", "Smoo");
sequence.StartValue = 1729;
sequence.IncrementBy = 11;
sequence.MinValue = 2001;
sequence.MaxValue = 2010;
sequence.ClrType = typeof(int);
Assert.Equal("Foo", sequence.Name);
Assert.Equal("Smoo", sequence.Schema);
Assert.Equal(11, sequence.IncrementBy);
Assert.Equal(1729, sequence.StartValue);
Assert.Equal(2001, sequence.MinValue);
Assert.Equal(2010, sequence.MaxValue);
Assert.Same(typeof(int), sequence.ClrType);
}
[Fact]
public void Can_only_be_created_for_byte_short_int_and_long()
{
var sequence = new Model().Relational().GetOrAddSequence("Foo");
sequence.ClrType = typeof(byte);
Assert.Same(typeof(byte), sequence.ClrType);
sequence.ClrType = typeof(short);
Assert.Same(typeof(short), sequence.ClrType);
sequence.ClrType = typeof(int);
Assert.Same(typeof(int), sequence.ClrType);
sequence.ClrType = typeof(long);
Assert.Same(typeof(long), sequence.ClrType);
Assert.Equal(
RelationalStrings.BadSequenceType,
Assert.Throws<ArgumentException>(
() => sequence.ClrType = typeof(decimal)).Message);
}
[Fact]
public void Can_get_model()
{
var model = new Model();
var sequence = model.Relational().GetOrAddSequence("Foo");
Assert.Same(model, sequence.Model);
}
[Fact]
public void Can_get_model_default_schema_if_sequence_schema_not_specified()
{
var model = new Model();
var sequence = model.Relational().GetOrAddSequence("Foo");
Assert.Null(sequence.Schema);
model.Relational().DefaultSchema = "db0";
Assert.Equal("db0", sequence.Schema);
}
[Fact]
public void Can_get_sequence_schema_if_specified_explicitly()
{
var model = new Model();
model.Relational().DefaultSchema = "db0";
var sequence = model.Relational().GetOrAddSequence("Foo", "db1");
Assert.Equal("db1", sequence.Schema);
}
[Fact]
public void Can_serialize_and_deserialize()
{
var model = new Model();
var sequence = model.Relational().GetOrAddSequence("Foo", "Smoo");
sequence.StartValue = 1729;
sequence.IncrementBy = 11;
sequence.MinValue = 2001;
sequence.MaxValue = 2010;
sequence.ClrType = typeof(int);
model.Relational().GetOrAddSequence("Foo", "Smoo");
Assert.Equal("Foo", sequence.Name);
Assert.Equal("Smoo", sequence.Schema);
Assert.Equal(11, sequence.IncrementBy);
Assert.Equal(1729, sequence.StartValue);
Assert.Equal(2001, sequence.MinValue);
Assert.Equal(2010, sequence.MaxValue);
Assert.Same(typeof(int), sequence.ClrType);
}
[Fact]
public void Can_serialize_and_deserialize_with_defaults()
{
var model = new Model();
model.Relational().GetOrAddSequence("Foo");
var sequence = model.Relational().GetOrAddSequence("Foo");
Assert.Equal("Foo", sequence.Name);
Assert.Null(sequence.Schema);
Assert.Equal(1, sequence.IncrementBy);
Assert.Equal(1, sequence.StartValue);
Assert.Null(sequence.MinValue);
Assert.Null(sequence.MaxValue);
Assert.Same(typeof(long), sequence.ClrType);
}
[Fact]
public void Can_serialize_and_deserialize_with_funky_names()
{
var model = new Model();
var sequence = model.Relational().GetOrAddSequence("'Foo'", "''S'''m'oo'''");
sequence.StartValue = 1729;
sequence.IncrementBy = 11;
sequence.ClrType = typeof(int);
sequence = model.Relational().GetOrAddSequence("'Foo'", "''S'''m'oo'''");
Assert.Equal("'Foo'", sequence.Name);
Assert.Equal("''S'''m'oo'''", sequence.Schema);
Assert.Equal(11, sequence.IncrementBy);
Assert.Equal(1729, sequence.StartValue);
Assert.Null(sequence.MinValue);
Assert.Null(sequence.MaxValue);
Assert.Same(typeof(int), sequence.ClrType);
}
[Fact]
public void Throws_on_bad_serialized_form()
{
var model = new Model();
var sequence = model.Relational().GetOrAddSequence("Foo", "Smoo");
sequence.StartValue = 1729;
sequence.IncrementBy = 11;
sequence.MinValue = 2001;
sequence.MaxValue = 2010;
sequence.ClrType = typeof(int);
var annotationName = RelationalAnnotationNames.SequencePrefix + "Smoo.Foo";
model[annotationName] = ((string)model[annotationName]).Replace("1", "Z");
Assert.Equal(
RelationalStrings.BadSequenceString,
Assert.Throws<ArgumentException>(
() => model.Relational().GetOrAddSequence("Foo", "Smoo").ClrType).Message);
}
}
}
| 35.467033 | 111 | 0.582804 | [
"Apache-2.0"
] | vadzimpm/EntityFramework | test/EFCore.Relational.Tests/Metadata/SequenceTest.cs | 6,455 | C# |
using microservice.toolkit.configurationmanager.extension;
using Microsoft.Extensions.Configuration;
using NUnit.Framework;
using System.Diagnostics.CodeAnalysis;
using System.IO;
namespace microservice.toolkit.configurationmanager.test
{
[ExcludeFromCodeCoverage]
public class ConfigurationManagerTest
{
private IConfiguration configurationManager;
[Test]
public void GetString()
{
var stringValue = this.configurationManager.GetString("stringValue");
Assert.AreEqual("Hello World!", stringValue);
}
[Test]
public void GetString_DefaultValue()
{
const string defaultValue = "Ciao Mondo!";
var stringValue = this.configurationManager.GetString("stringDefaultValue", defaultValue);
Assert.AreEqual(defaultValue, stringValue);
}
[Test]
public void GetInt()
{
var intValue = this.configurationManager.GetInt("intValue");
Assert.AreEqual(666, intValue);
}
[Test]
public void GetInt_Default()
{
var intValue = this.configurationManager.GetInt("intDefaultValue", 69);
Assert.AreEqual(69, intValue);
}
[Test]
public void GetBool()
{
var boolValue = this.configurationManager.GetBool("boolValue");
Assert.IsTrue(boolValue);
}
[Test]
public void GetBool_Default()
{
var boolValue = this.configurationManager.GetBool("boolDefaultValue", true);
Assert.IsTrue(boolValue);
}
[Test]
public void GetStringArray()
{
var stringArrayValue = this.configurationManager.GetStringArray("stringArrayValue");
Assert.AreEqual("Hello", stringArrayValue[0]);
Assert.AreEqual("World", stringArrayValue[1]);
Assert.AreEqual("!", stringArrayValue[2]);
}
[Test]
public void GetStringArray_Default()
{
var stringArrayValue =
this.configurationManager.GetStringArray("stringArrayDefaultValue", new[] { "Ciao", "Mondo", "!" });
Assert.AreEqual("Ciao", stringArrayValue[0]);
Assert.AreEqual("Mondo", stringArrayValue[1]);
Assert.AreEqual("!", stringArrayValue[2]);
}
[Test]
public void GetIntArray()
{
var intArrayValue = this.configurationManager.GetIntArray("intArrayValue");
Assert.AreEqual(1, intArrayValue[0]);
Assert.AreEqual(2, intArrayValue[1]);
Assert.AreEqual(3, intArrayValue[2]);
Assert.AreEqual(4, intArrayValue[3]);
}
[Test]
public void GetIntArray_Default()
{
var intArrayValue = this.configurationManager.GetIntArray("intArrayDefaultValue", new[] { 0, 9, 8, 7 });
Assert.AreEqual(0, intArrayValue[0]);
Assert.AreEqual(9, intArrayValue[1]);
Assert.AreEqual(8, intArrayValue[2]);
Assert.AreEqual(7, intArrayValue[3]);
}
#region SetUp & TearDown
[SetUp]
public void SetUp()
{
this.configurationManager = new ConfigurationBuilder()
.AddJsonFile(Path.Combine("data", "ConfigurationManagerTest.json"))
.Build();
}
[TearDown]
public void TearDown()
{
}
#endregion
}
} | 31.293103 | 117 | 0.568044 | [
"MIT"
] | MpStyle/microservicetoolk | microservice.toolkit.configurationmanager.test/ConfigurationManagerTest.cs | 3,630 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
namespace NetFabric.Hyperlinq
{
public static partial class ValueEnumerableExtensions
{
public static DistinctEnumerable<TEnumerable, TEnumerator, TSource> Distinct<TEnumerable, TEnumerator, TSource>(this TEnumerable source)
where TEnumerable : IValueEnumerable<TSource, TEnumerator>
where TEnumerator : struct, IEnumerator<TSource>
=> new(source);
public readonly partial struct DistinctEnumerable<TEnumerable, TEnumerator, TSource>
: IValueEnumerable<TSource, DistinctEnumerable<TEnumerable, TEnumerator, TSource>.DisposableEnumerator>
where TEnumerable : IValueEnumerable<TSource, TEnumerator>
where TEnumerator : struct, IEnumerator<TSource>
{
readonly TEnumerable source;
internal DistinctEnumerable(TEnumerable source)
=> this.source = source;
public Enumerator GetEnumerator()
=> new();
DisposableEnumerator IValueEnumerable<TSource, DisposableEnumerator>.GetEnumerator()
=> new();
IEnumerator<TSource> IEnumerable<TSource>.GetEnumerator()
// ReSharper disable once HeapView.BoxingAllocation
=> new DisposableEnumerator();
IEnumerator IEnumerable.GetEnumerator()
// ReSharper disable once HeapView.BoxingAllocation
=> new DisposableEnumerator();
public struct Enumerator
{
}
public struct DisposableEnumerator
: IEnumerator<TSource>
{
public readonly TSource Current => default!;
readonly TSource IEnumerator<TSource>.Current => default!;
readonly object? IEnumerator.Current => default;
public bool MoveNext()
=> false;
public readonly void Reset()
=> throw new NotSupportedException();
public void Dispose() { }
}
}
}
}
| 35.098361 | 144 | 0.609995 | [
"MIT"
] | Ashrafnet/NetFabric.Hyperlinq | NetFabric.Hyperlinq.SourceGenerator.UnitTests/TestData/Source/Distinct.ValueEnumerable.cs | 2,143 | 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 Lyra2.LyraShell.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Lyra2.LyraShell.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;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrow_down {
get {
object obj = ResourceManager.GetObject("arrow_down", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrow_down_down {
get {
object obj = ResourceManager.GetObject("arrow_down_down", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrow_down_over {
get {
object obj = ResourceManager.GetObject("arrow_down_over", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrow_up {
get {
object obj = ResourceManager.GetObject("arrow_up", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrow_up_down {
get {
object obj = ResourceManager.GetObject("arrow_up_down", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrow_up_over {
get {
object obj = ResourceManager.GetObject("arrow_up_over", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap button_enabled {
get {
object obj = ResourceManager.GetObject("button_enabled", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap button_pressed {
get {
object obj = ResourceManager.GetObject("button_pressed", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap button_rollover {
get {
object obj = ResourceManager.GetObject("button_rollover", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap clear_normal_16 {
get {
object obj = ResourceManager.GetObject("clear_normal_16", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap clear_pressed_16 {
get {
object obj = ResourceManager.GetObject("clear_pressed_16", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap InfoBackgroundImage {
get {
object obj = ResourceManager.GetObject("InfoBackgroundImage", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap lyra_menu {
get {
object obj = ResourceManager.GetObject("lyra_menu", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap next {
get {
object obj = ResourceManager.GetObject("next", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap pfeilDown {
get {
object obj = ResourceManager.GetObject("pfeilDown", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap pfeilUp {
get {
object obj = ResourceManager.GetObject("pfeilUp", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap prev {
get {
object obj = ResourceManager.GetObject("prev", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap right_pane_bg {
get {
object obj = ResourceManager.GetObject("right_pane_bg", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap scroll_bottom {
get {
object obj = ResourceManager.GetObject("scroll_bottom", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap scroll_down {
get {
object obj = ResourceManager.GetObject("scroll_down", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap scroll_down_bg {
get {
object obj = ResourceManager.GetObject("scroll_down_bg", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap scroll_top {
get {
object obj = ResourceManager.GetObject("scroll_top", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap scroll_up {
get {
object obj = ResourceManager.GetObject("scroll_up", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap scroll_up_bg {
get {
object obj = ResourceManager.GetObject("scroll_up_bg", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap splash2009 {
get {
object obj = ResourceManager.GetObject("splash2009", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap splash2012 {
get {
object obj = ResourceManager.GetObject("splash2012", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap splash2018 {
get {
object obj = ResourceManager.GetObject("splash2018", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap splash2020 {
get {
object obj = ResourceManager.GetObject("splash2020", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap TransparencyPreview {
get {
object obj = ResourceManager.GetObject("TransparencyPreview", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap undo_icon {
get {
object obj = ResourceManager.GetObject("undo_icon", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
| 39.607143 | 182 | 0.533745 | [
"MIT"
] | ogirard/lyra-legacy | LyraShell/Properties/Resources.Designer.cs | 14,419 | C# |
using System.Collections.Generic;
using System.Drawing;
using BizHawk.Emulation.Common;
using BizHawk.Emulation.Cores.Nintendo.GBA;
namespace BizHawk.Client.EmuHawk
{
[Schema("GBA")]
public class GBASchema : IVirtualPadSchema
{
public IEnumerable<PadSchema> GetPadSchemas(IEmulator core)
{
yield return StandardController();
yield return ConsoleButtons();
if (core is MGBAHawk)
{
yield return TiltControls();
}
}
private static PadSchema TiltControls()
{
return new PadSchema
{
DisplayName = "Tilt Controls",
IsConsole = false,
DefaultSize = new Size(256, 240),
MaxSize = new Size(256, 326),
Buttons = new[]
{
new PadSchema.ButtonSchema
{
Name = "Tilt X",
DisplayName = "Tilt X",
Location = new Point(10, 15),
Type = PadSchema.PadInputType.FloatSingle,
TargetSize = new Size(226, 69),
MinValue = short.MinValue,
MaxValue = short.MaxValue
},
new PadSchema.ButtonSchema
{
Name = "Tilt Y",
DisplayName = "Tilt Y",
Location = new Point(10, 94),
Type = PadSchema.PadInputType.FloatSingle,
TargetSize = new Size(226, 69),
MinValue = short.MinValue,
MaxValue = short.MaxValue
},
new PadSchema.ButtonSchema
{
Name = "Tilt Z",
DisplayName = "Tilt Z",
Location = new Point(10, 173),
Type = PadSchema.PadInputType.FloatSingle,
TargetSize = new Size(226, 69),
MinValue = short.MinValue,
MaxValue = short.MaxValue
},
new PadSchema.ButtonSchema
{
Name = "Light Sensor",
DisplayName = "Light Sensor",
Location = new Point(10, 252),
Type = PadSchema.PadInputType.FloatSingle,
TargetSize = new Size(226, 69),
MaxValue = byte.MaxValue
}
}
};
}
private static PadSchema StandardController()
{
return new PadSchema
{
IsConsole = false,
DefaultSize = new Size(194, 90),
Buttons = new[]
{
new PadSchema.ButtonSchema
{
Name = "Up",
DisplayName = "",
Icon = Properties.Resources.BlueUp,
Location = new Point(29, 17),
Type = PadSchema.PadInputType.Boolean
},
new PadSchema.ButtonSchema
{
Name = "Down",
DisplayName = "",
Icon = Properties.Resources.BlueDown,
Location = new Point(29, 61),
Type = PadSchema.PadInputType.Boolean
},
new PadSchema.ButtonSchema
{
Name = "Left",
DisplayName = "",
Icon = Properties.Resources.Back,
Location = new Point(17, 39),
Type = PadSchema.PadInputType.Boolean
},
new PadSchema.ButtonSchema
{
Name = "Right",
DisplayName = "",
Icon = Properties.Resources.Forward,
Location = new Point(39, 39),
Type = PadSchema.PadInputType.Boolean
},
new PadSchema.ButtonSchema
{
Name = "B",
DisplayName = "B",
Location = new Point(130, 39),
Type = PadSchema.PadInputType.Boolean
},
new PadSchema.ButtonSchema
{
Name = "A",
DisplayName = "A",
Location = new Point(154, 39),
Type = PadSchema.PadInputType.Boolean
},
new PadSchema.ButtonSchema
{
Name = "Select",
DisplayName = "s",
Location = new Point(64, 39),
Type = PadSchema.PadInputType.Boolean
},
new PadSchema.ButtonSchema
{
Name = "Start",
DisplayName = "S",
Location = new Point(86, 39),
Type = PadSchema.PadInputType.Boolean
},
new PadSchema.ButtonSchema
{
Name = "L",
DisplayName = "L",
Location = new Point(2, 12),
Type = PadSchema.PadInputType.Boolean
},
new PadSchema.ButtonSchema
{
Name = "R",
DisplayName = "R",
Location = new Point(166, 12),
Type = PadSchema.PadInputType.Boolean
}
}
};
}
private static PadSchema ConsoleButtons()
{
return new PadSchema
{
DisplayName = "Console",
IsConsole = true,
DefaultSize = new Size(75, 50),
Buttons = new[]
{
new PadSchema.ButtonSchema
{
Name = "Power",
DisplayName = "Power",
Location = new Point(10, 15),
Type = PadSchema.PadInputType.Boolean
}
}
};
}
}
}
| 24.398907 | 62 | 0.566629 | [
"MIT"
] | Asnivor/BizHawk | BizHawk.Client.EmuHawk/tools/VirtualPads/schema/GBASchema.cs | 4,467 | C# |
namespace BlogEngine.Core.Web.HttpHandlers
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Xml;
/// <summary>
/// Based on John Dyer's (http://johndyer.name/) extension.
/// </summary>
public class Sioc : IHttpHandler
{
#region Constants and Fields
/// <summary>
/// The xml namespaces.
/// </summary>
private static Dictionary<string, string> xmlNamespaces;
#endregion
#region Properties
/// <summary>
/// Gets a value indicating whether another request can use the <see cref = "T:System.Web.IHttpHandler"></see> instance.
/// </summary>
/// <value></value>
/// <returns>true if the <see cref = "T:System.Web.IHttpHandler"></see> instance is reusable; otherwise, false.</returns>
public bool IsReusable
{
get
{
return false;
}
}
/// <summary>
/// Gets SupportedNamespaces.
/// </summary>
private static Dictionary<string, string> SupportedNamespaces
{
get
{
return xmlNamespaces ??
(xmlNamespaces =
new Dictionary<string, string>
{
{ "foaf", "http://xmlns.com/foaf/0.1/" },
{ "rss", "http://purl.org/rss/1.0/" },
{ "admin", "http://webns.net/mvcb/" },
{ "dc", "http://purl.org/dc/elements/1.1/" },
{ "dcterms", "http://purl.org/dc/terms/" },
{ "rdfs", "http://www.w3.org/2000/01/rdf-schema#" },
{ "rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#" },
{ "content", "http://purl.org/rss/1.0/modules/content" },
{ "sioc", "http://rdfs.org/sioc/ns#" }
});
}
}
#endregion
#region Implemented Interfaces
#region IHttpHandler
/// <summary>
/// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"></see> interface.
/// </summary>
/// <param name="context">
/// An <see cref="T:System.Web.HttpContext"></see> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.
/// </param>
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/rdf+xml";
var siocType = context.Request["sioc_type"] + string.Empty;
var siocId = context.Request["sioc_id"] + string.Empty;
switch (siocType)
{
default:
// case "site":
var list = Post.Posts.ConvertAll(ConvertToIPublishable);
var max = Math.Min(BlogSettings.Instance.PostsPerFeed, list.Count);
list = list.GetRange(0, max);
WriteSite(context.Response.OutputStream, list);
break;
case "post":
Guid postId;
if (siocId.TryParse(out postId))
{
var post = Post.GetPost(postId);
if (post != null)
{
WritePub(context.Response.OutputStream, post);
}
}
break;
case "comment":
Guid commentId;
if (siocId.TryParse(out commentId))
{
// TODO: is it possible to get a single comment?
var comment = GetComment(commentId);
if (comment != null)
{
WritePub(context.Response.OutputStream, comment);
}
}
break;
case "user":
WriteAuthor(context.Response.OutputStream, siocId);
break;
/*
case "post":
generator.WriteSite(context.Response.OutputStream);
break;
*/
}
}
#endregion
#endregion
#region Methods
/// <summary>
/// Calculates the SHA1.
/// </summary>
/// <param name="text">
/// The text string.
/// </param>
/// <param name="enc">
/// The encoding.
/// </param>
/// <returns>
/// The hash string.
/// </returns>
private static string CalculateSha1(string text, Encoding enc)
{
var buffer = enc.GetBytes(text);
var cryptoTransformSha1 = new SHA1CryptoServiceProvider();
var hash = BitConverter.ToString(cryptoTransformSha1.ComputeHash(buffer)).Replace("-", string.Empty);
return hash.ToLower();
}
/// <summary>
/// Closes the writer.
/// </summary>
/// <param name="xmlWriter">
/// The XML writer.
/// </param>
private static void CloseWriter(XmlWriter xmlWriter)
{
xmlWriter.WriteEndElement(); // rdf:RDF
xmlWriter.WriteEndDocument();
xmlWriter.Close();
}
/// <summary>
/// Converts to publishable interface.
/// </summary>
/// <param name="item">
/// The publishable item.
/// </param>
/// <returns>
/// The publishable interface.
/// </returns>
private static IPublishable ConvertToIPublishable(IPublishable item)
{
return item;
}
/// <summary>
/// Gets the blog author URL.
/// </summary>
/// <param name="username">
/// The username.
/// </param>
/// <returns>
/// Blog author url.
/// </returns>
private static string GetBlogAuthorUrl(string username)
{
return string.Format("{0}author/{1}{2}", Utils.AbsoluteWebRoot, HttpUtility.UrlEncode(username), BlogConfig.FileExtension);
}
/// <summary>
/// Gets the comment.
/// </summary>
/// <param name="commentId">
/// The comment id.
/// </param>
/// <returns>
/// The comment.
/// </returns>
private static Comment GetComment(Guid commentId)
{
var posts = Post.Posts;
return posts.SelectMany(post => post.Comments).FirstOrDefault(comm => comm.Id == commentId);
}
/// <summary>
/// Gets the sioc author URL.
/// </summary>
/// <param name="username">
/// The username.
/// </param>
/// <returns>
/// The SIOC Author Url.
/// </returns>
private static string GetSiocAuthorUrl(string username)
{
return string.Format(
"{0}sioc.axd?sioc_type=user&sioc_id={1}", Utils.AbsoluteWebRoot, HttpUtility.UrlEncode(username));
}
/// <summary>
/// Gets the sioc authors URL.
/// </summary>
/// <returns>
/// The SIOC Author Url.
/// </returns>
private static string GetSiocAuthorsUrl()
{
return string.Format("{0}sioc.axd?sioc_type=site#authors", Utils.AbsoluteWebRoot);
}
/// <summary>
/// Gets the sioc blog URL.
/// </summary>
/// <returns>
/// The SIOC Blog Url.
/// </returns>
private static string GetSiocBlogUrl()
{
return string.Format("{0}sioc.axd?sioc_type=site#webblog", Utils.AbsoluteWebRoot);
}
/// <summary>
/// Gets the sioc comment URL.
/// </summary>
/// <param name="id">
/// The comment id.
/// </param>
/// <returns>
/// The SIOC Comment Url.
/// </returns>
private static string GetSiocCommentUrl(string id)
{
return string.Format("{0}sioc.axd?sioc_type=comment&sioc_id={1}", Utils.AbsoluteWebRoot, id);
}
/// <summary>
/// Gets the sioc post URL.
/// </summary>
/// <param name="id">
/// The SIOC post id.
/// </param>
/// <returns>
/// The SIOC Post Url.
/// </returns>
private static string GetSiocPostUrl(string id)
{
return string.Format("{0}sioc.axd?sioc_type=post&sioc_id={1}", Utils.AbsoluteWebRoot, id);
}
/*
/// <summary>
/// Gets the sioc site URL.
/// </summary>
/// <returns>
/// The SIOC Site Url.
/// </returns>
private static string GetSiocSiteUrl()
{
return string.Format("{0}sioc.axd?sioc_type=site", Utils.AbsoluteWebRoot);
}
*/
/// <summary>
/// Gets the writer.
/// </summary>
/// <param name="stream">
/// The stream.
/// </param>
/// <returns>
/// The Xml Writer.
/// </returns>
private static XmlWriter GetWriter(Stream stream)
{
var settings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true };
var xmlWriter = XmlWriter.Create(stream, settings);
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("rdf", "RDF", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
// "http://xmlns.com/foaf/0.1/");
foreach (var prefix in SupportedNamespaces.Keys)
{
xmlWriter.WriteAttributeString("xmlns", prefix, null, SupportedNamespaces[prefix]);
}
return xmlWriter;
}
/// <summary>
/// Writes the author.
/// </summary>
/// <param name="stream">
/// The stream.
/// </param>
/// <param name="authorName">
/// Name of the author.
/// </param>
private static void WriteAuthor(Stream stream, string authorName)
{
var xmlWriter = GetWriter(stream);
WriteFoafDocument(xmlWriter, "user", GetSiocAuthorUrl(authorName));
var user = Membership.GetUser(authorName);
var ap = AuthorProfile.GetProfile(authorName);
// FOAF:Person
xmlWriter.WriteStartElement("foaf", "Person", null);
xmlWriter.WriteAttributeString("rdf", "about", null, GetSiocAuthorUrl(authorName));
xmlWriter.WriteElementString("foaf", "Name", null, authorName);
if (ap != null && !ap.Private && ap.FirstName != String.Empty)
{
xmlWriter.WriteElementString("foaf", "firstName", null, ap.FirstName);
}
if (ap != null && !ap.Private && ap.LastName != String.Empty)
{
xmlWriter.WriteElementString("foaf", "surname", null, ap.LastName);
}
xmlWriter.WriteElementString(
"foaf", "mbox_sha1sum", null, (user != null) ? CalculateSha1(user.Email, Encoding.UTF8) : string.Empty);
xmlWriter.WriteStartElement("foaf", "homepage", null);
xmlWriter.WriteAttributeString("rdf", "resource", null, Utils.AbsoluteWebRoot.ToString());
xmlWriter.WriteEndElement(); // foaf:homepage
xmlWriter.WriteStartElement("foaf", "holdsAccount", null);
xmlWriter.WriteAttributeString("rdf", "resource", null, GetBlogAuthorUrl(authorName));
xmlWriter.WriteEndElement(); // foaf:holdsAccount
xmlWriter.WriteEndElement(); // foaf:Person
// SIOC:User
xmlWriter.WriteStartElement("sioc", "User", null);
xmlWriter.WriteAttributeString("rdf", "about", null, GetBlogAuthorUrl(authorName));
xmlWriter.WriteElementString("foaf", "accountName", null, authorName);
xmlWriter.WriteElementString("sioc", "name", null, authorName);
// xmlWriter.WriteElementString("dcterms", "created", null, "TODO:" + authorName);
xmlWriter.WriteEndElement(); // sioc:User
CloseWriter(xmlWriter);
}
/// <summary>
/// Writes the foaf document.
/// </summary>
/// <param name="xmlWriter">
/// The XML writer.
/// </param>
/// <param name="siocType">
/// Type of the sioc.
/// </param>
/// <param name="url">
/// The URL string.
/// </param>
private static void WriteFoafDocument(XmlWriter xmlWriter, string siocType, string url)
{
var title = string.Format("SIOC {0} profile for \"{1}\"", siocType, BlogSettings.Instance.Name);
const string Description =
"A SIOC profile describes the structure and contents of a weblog in a machine readable form. For more information please refer to http://sioc-project.org/.";
xmlWriter.WriteStartElement("foaf", "Document", null);
xmlWriter.WriteAttributeString("rdf", "about", null, Utils.AbsoluteWebRoot.ToString());
xmlWriter.WriteElementString("dc", "title", null, title);
xmlWriter.WriteElementString("dc", "description", null, Description);
xmlWriter.WriteElementString("foaf", "primaryTopic", null, url);
xmlWriter.WriteElementString(
"admin", "generatorAgent", null, string.Format("BlogEngine.NET{0}", BlogSettings.Instance.Version()));
xmlWriter.WriteEndElement(); // foaf:Document
}
/// <summary>
/// Writes the forum.
/// </summary>
/// <param name="xmlWriter">
/// The xml writer.
/// </param>
/// <param name="list">
/// The enumerable of publishable interface.
/// </param>
private static void WriteForum(XmlWriter xmlWriter, IEnumerable<IPublishable> list)
{
xmlWriter.WriteStartElement("sioc", "Forum", null);
xmlWriter.WriteAttributeString("rdf", "about", null, GetSiocBlogUrl());
xmlWriter.WriteElementString("sioc", "name", null, BlogSettings.Instance.Name);
xmlWriter.WriteStartElement("sioc", "link", null);
xmlWriter.WriteAttributeString("rdf", "resource", null, GetSiocBlogUrl());
xmlWriter.WriteEndElement();
foreach (var pub in list)
{
xmlWriter.WriteStartElement("sioc", "container_of", null);
xmlWriter.WriteStartElement("sioc", "Post", null);
xmlWriter.WriteAttributeString("rdf", "about", null, pub.AbsoluteLink.ToString());
xmlWriter.WriteAttributeString("dc", "title", null, pub.Title);
xmlWriter.WriteStartElement("rdfs", "seeAlso", null);
xmlWriter.WriteAttributeString("rdf", "resource", null, GetSiocPostUrl(pub.Id.ToString()));
xmlWriter.WriteEndElement(); // sioc:Post
xmlWriter.WriteEndElement(); // sioc:Post
xmlWriter.WriteEndElement(); // sioc:Forum
}
xmlWriter.WriteEndElement(); // sioc:Forum
}
/// <summary>
/// Writes an IPublishable to a stream.
/// </summary>
/// <param name="stream">
/// The stream.
/// </param>
/// <param name="pub">
/// The publishable interface.
/// </param>
private static void WritePub(Stream stream, IPublishable pub)
{
var xmlWriter = GetWriter(stream);
if (pub is Post)
{
WriteFoafDocument(xmlWriter, "post", pub.AbsoluteLink.ToString());
}
else
{
WriteFoafDocument(xmlWriter, "comment", pub.AbsoluteLink.ToString());
}
WriteSiocPost(xmlWriter, pub);
CloseWriter(xmlWriter);
}
/// <summary>
/// Writes SIOC post.
/// </summary>
/// <param name="xmlWriter">
/// The xml writer.
/// </param>
/// <param name="pub">
/// The publishable interface.
/// </param>
private static void WriteSiocPost(XmlWriter xmlWriter, IPublishable pub)
{
xmlWriter.WriteStartElement("sioc", "Post", null);
xmlWriter.WriteAttributeString("rdf", "about", null, pub.AbsoluteLink.ToString());
xmlWriter.WriteStartElement("sioc", "link", null);
xmlWriter.WriteAttributeString("rdf", "resource", null, pub.AbsoluteLink.ToString());
xmlWriter.WriteEndElement(); // sioc:link
xmlWriter.WriteStartElement("sioc", "has_container", null);
xmlWriter.WriteAttributeString("rdf", "resource", null, GetSiocBlogUrl());
xmlWriter.WriteEndElement(); // sioc:has_container
xmlWriter.WriteElementString("dc", "title", null, pub.Title);
// SIOC:USER
if (pub is Post)
{
xmlWriter.WriteStartElement("sioc", "has_creator", null);
xmlWriter.WriteStartElement("sioc", "User", null);
xmlWriter.WriteAttributeString("rdf", "about", null, GetBlogAuthorUrl(pub.Author));
xmlWriter.WriteStartElement("rdfs", "seeAlso", null);
xmlWriter.WriteAttributeString("rdf", "resource", null, GetSiocAuthorUrl(pub.Author));
xmlWriter.WriteEndElement(); // rdf:about
xmlWriter.WriteEndElement(); // sioc:User
xmlWriter.WriteEndElement(); // sioc:has_creator
}
// FOAF:maker
xmlWriter.WriteStartElement("foaf", "maker", null);
xmlWriter.WriteStartElement("foaf", "Person", null);
if (pub is Post)
{
xmlWriter.WriteAttributeString("rdf", "about", null, GetBlogAuthorUrl(pub.Author));
}
xmlWriter.WriteAttributeString("foaf", "name", null, pub.Author);
if (pub is Post)
{
var user = Membership.GetUser(pub.Author);
xmlWriter.WriteElementString(
"foaf",
"mbox_sha1sum",
null,
(user != null) ? CalculateSha1(user.Email, Encoding.UTF8) : string.Empty);
}
else
{
xmlWriter.WriteElementString(
"foaf", "mbox_sha1sum", null, CalculateSha1(((Comment)pub).Email, Encoding.UTF8));
}
xmlWriter.WriteStartElement("foaf", "homepage", null);
if (pub is Post)
{
xmlWriter.WriteAttributeString("rdf", "resource", null, Utils.AbsoluteWebRoot.ToString());
}
else
{
xmlWriter.WriteAttributeString("rdf", "resource", null, "TODO:");
}
xmlWriter.WriteEndElement(); // foaf:homepage
if (pub is Post)
{
xmlWriter.WriteStartElement("rdfs", "seeAlso", null);
xmlWriter.WriteAttributeString("rdf", "resource", null, GetSiocAuthorUrl(pub.Author));
xmlWriter.WriteEndElement(); // rdfs:seeAlso
}
xmlWriter.WriteEndElement(); // foaf:Person
xmlWriter.WriteEndElement(); // foaf:maker
// CONTENT
// xmlWriter.WriteElementString("dcterms", "created", null, DpUtility.ToW3cDateTime(pub.DateCreated));
xmlWriter.WriteElementString("sioc", "content", null, Utils.StripHtml(pub.Content));
xmlWriter.WriteElementString("content", "encoded", null, pub.Content);
// TOPICS
if (pub is Post)
{
// categories
foreach (var category in ((Post)pub).Categories)
{
xmlWriter.WriteStartElement("sioc", "topic", null);
xmlWriter.WriteAttributeString("rdfs", "label", null, category.Title);
xmlWriter.WriteAttributeString("rdf", "resource", null, category.AbsoluteLink.ToString());
xmlWriter.WriteEndElement(); // sioc:topic
}
// tags are also supposed to be treated as sioc:topic
foreach (var tag in ((Post)pub).Tags)
{
xmlWriter.WriteStartElement("sioc", "topic", null);
xmlWriter.WriteAttributeString("rdfs", "label", null, tag);
xmlWriter.WriteAttributeString("rdf", "resource", null, Utils.AbsoluteWebRoot + "?tag=/" + tag);
xmlWriter.WriteEndElement(); // sioc:topic
}
// COMMENTS
foreach (var comment in ((Post)pub).ApprovedComments)
{
xmlWriter.WriteStartElement("sioc", "has_reply", null);
xmlWriter.WriteStartElement("sioc", "Post", null);
xmlWriter.WriteAttributeString("rdf", "about", null, comment.AbsoluteLink.ToString());
xmlWriter.WriteStartElement("rdfs", "seeAlso", null);
xmlWriter.WriteAttributeString("rdf", "resource", null, GetSiocCommentUrl(comment.Id.ToString()));
xmlWriter.WriteEndElement(); // rdfs:seeAlso
xmlWriter.WriteEndElement(); // sioc:Post
xmlWriter.WriteEndElement(); // sioc:has_reply
}
// TODO: LINKS
var linkMatches = Regex.Matches(pub.Content, @"<a[^(href)]?href=""([^""]+)""[^>]?>([^<]+)</a>");
var linkPairs = new List<string>();
foreach (Match linkMatch in linkMatches)
{
var url = linkMatch.Groups[1].Value;
var text = linkMatch.Groups[2].Value;
if (url.IndexOf(Utils.AbsoluteWebRoot.ToString()) == 0)
{
continue;
}
var pair = url + "|" + text;
if (linkPairs.Contains(pair))
{
continue;
}
xmlWriter.WriteStartElement("sioc", "links_to", null);
xmlWriter.WriteAttributeString("rdf", "resource", null, url);
xmlWriter.WriteAttributeString("rdfs", "label", null, text);
xmlWriter.WriteEndElement(); // sioc:links_to
linkPairs.Add(pair);
}
}
xmlWriter.WriteEndElement(); // sioc:Post
}
/// <summary>
/// Writes sioc site.
/// </summary>
/// <param name="xmlWriter">
/// The xml writer.
/// </param>
private static void WriteSiocSite(XmlWriter xmlWriter)
{
xmlWriter.WriteStartElement("sioc", "Site", null);
xmlWriter.WriteAttributeString("rdf", "about", null, Utils.AbsoluteWebRoot.ToString());
xmlWriter.WriteElementString("dc", "title", null, BlogSettings.Instance.Name);
xmlWriter.WriteElementString("dc", "description", null, BlogSettings.Instance.Description);
xmlWriter.WriteElementString("sioc", "link", null, Utils.AbsoluteWebRoot.ToString());
xmlWriter.WriteElementString("sioc", "host_of", null, GetSiocBlogUrl());
xmlWriter.WriteElementString("sioc", "has_group", null, GetSiocAuthorsUrl());
xmlWriter.WriteEndElement(); // sioc:Site
}
/// <summary>
/// Writes site.
/// </summary>
/// <param name="stream">
/// The stream.
/// </param>
/// <param name="list">
/// The enumerable of IPublishable.
/// </param>
private static void WriteSite(Stream stream, IEnumerable<IPublishable> list)
{
var xmlWriter = GetWriter(stream);
WriteUserGroup(xmlWriter);
WriteFoafDocument(xmlWriter, "site", Utils.AbsoluteWebRoot.ToString());
WriteSiocSite(xmlWriter);
WriteForum(xmlWriter, list);
CloseWriter(xmlWriter);
}
/// <summary>
/// Writes the user group.
/// </summary>
/// <param name="xmlWriter">
/// The XML writer.
/// </param>
private static void WriteUserGroup(XmlWriter xmlWriter)
{
xmlWriter.WriteStartElement("sioc", "Usergroup", null);
xmlWriter.WriteAttributeString("rdf", "about", null, GetSiocAuthorsUrl());
xmlWriter.WriteElementString("dc", "title", null, "Authors at \"" + BlogSettings.Instance.Name + "\"");
int count;
var members = Membership.Provider.GetAllUsers(0, 999, out count);
foreach (MembershipUser user in members)
{
xmlWriter.WriteStartElement("sioc", "has_member", null);
xmlWriter.WriteStartElement("sioc", "User", null);
xmlWriter.WriteAttributeString("rdf", "about", null, GetBlogAuthorUrl(user.UserName));
xmlWriter.WriteAttributeString("rdfs", "label", null, user.UserName);
xmlWriter.WriteStartElement("sioc", "see_also", null);
xmlWriter.WriteAttributeString("rdf", "resource", null, GetSiocAuthorUrl(user.UserName));
xmlWriter.WriteEndElement(); // sioc:see_also
xmlWriter.WriteEndElement(); // sioc:User
xmlWriter.WriteEndElement(); // sioc:has_member
}
xmlWriter.WriteEndElement(); // foaf:Document
}
#endregion
}
} | 37.374823 | 207 | 0.521004 | [
"MIT"
] | mohanraod/mohansglobe | BlogEngine.NET-3.3.5.0/BlogEngine/BlogEngine.Core/Web/HttpHandlers/Sioc.cs | 26,426 | C# |
// Copyright (c) Richasy. All rights reserved.
namespace Richasy.Bili.Models.Enums
{
/// <summary>
/// Localized text resource name.
/// </summary>
public enum LanguageNames
{
#pragma warning disable SA1602 // Enumeration items should be documented
AppName,
AppDescription,
Confirm,
Cancel,
Navigation,
Popular,
Rank,
Partition,
SpecialColumn,
Live,
Personal,
DynamicFeed,
MyFavorite,
ViewLater,
ViewHistory,
HelpAndSupport,
PartitionLoading,
Recommend,
TenThousands,
Billion,
Hours,
Minutes,
Seconds,
ComprehensiveDynamics,
SelectSortType,
SortByDefault,
SortByNewest,
SortByPlay,
SortByReply,
SortByDanmaku,
SortByFavorite,
SortByLike,
SortByRead,
SearchTip,
SearchTipSlim,
SignInTitle,
UserName,
Password,
SignIn,
UserNameHolder,
PasswordHolder,
Captcha,
CaptchaHolder,
ValidUserNameOrPasswordTip,
CaptchaIsEmpty,
InputCaptchaTip,
InvalidUserNameOrPassword,
NeedQRLogin,
PasswordLoginTip,
QRLoginTip,
SwitchToPasswordLogin,
SwitchToQRLogin,
Refresh,
FailedToLoadQRCode,
QRCodeExpired,
LoginFailed,
PleaseSignIn,
Topic,
Bangumi,
DomesticAnime,
Documentary,
Movie,
TV,
SignOut,
MyWebPage,
Message,
WholePartitions,
Original,
Rookie,
Score,
RankRequestFailed,
PartitionRequestFailed,
RequestRecommendFailed,
RequestSubPartitionFailed,
RequestPopularFailed,
FollowLiveRoom,
SeeAll,
Total,
CategoriesReuqestFailed,
RequestArticleListFailed,
RequestLiveFailed,
RequestTabDetailFailed,
RequestPgcFailed,
ShowMore,
Index,
TimeChart,
RequestFeedDetailFailed,
AppTheme,
AppThemeDescription,
Generic,
Light,
Dark,
FollowSystem,
RestartWarning,
StartMethod,
StartMethodDescription,
Prelaunch,
PrelaunchDescription,
Startup,
StartupDescription,
StartupDisabledByUser,
StartupDisabledByPolicy,
LoggerModule,
LoggerModuleDescription,
LoggerFolder,
OpenFolder,
CleanLogger,
Clean,
Player,
PlayerMode,
PlayerModeDescription,
AutoPlayWhenLoaded,
DefaultPlayerDisplayMode,
Default,
FullScreenMode,
FullWindowMode,
PlayerControl,
PlayerControlDescription,
Prefer4K,
Prefer4KDescription,
PreferCodec,
PreferCodecDescription,
SingleFastForwardAndRewindSpan,
SingleFastForwardAndRewindSpanDescription,
MTCControlMode,
MTCControlModeDescription,
Automatic,
Manual,
RequestVideoFailed,
RelatedVideos,
Like,
Coin,
Favorite,
View,
Danmaku,
Share,
Reply,
H265,
H264,
Flv,
CompactOverlayMode,
ShowDanmaku,
HideDanmaku,
DanmakuPlaceholder,
DanmakuSendSettings,
DanmakuDisplaySettings,
Parts,
DanmakuOpacity,
DanmakuZoom,
DanmakuDensity,
DanmakuFont,
DanmakuMerge,
UseCloudShieldSettings,
Episodes,
Seasons,
Sections,
Detail,
PgcFollowing,
PgcNotFollow,
Chat,
BackToDefaultView,
DanmakuSwitch,
HotSearch,
FilterByTotalDuration,
FilterByLessThan10Min,
FilterByLessThan30Min,
FilterByLessThan60Min,
FilterByGreaterThan60Min,
Videos,
Search,
SortByFansLTH,
SortByFansHTL,
SortByLevelHTL,
SortByLevelLTH,
TotalUser,
UpMaster,
OfficialUser,
NormalUser,
Followed,
Follow,
User,
UserEmptySign,
FansCount,
FollowCount,
BeLikeCount,
UserHaveNoVideos,
RequestUserInformationFailed,
UserInformation,
NoSpecificData,
DanmakuStyle,
Stroke,
NoStroke,
Shadow,
DanmakuBold,
PlayLine,
Quality,
Viewer,
RequestLivePlayInformationFailed,
NoMessage,
NeedScaleToShowMessage,
RequestHistoryFailed,
Delete,
PreviousView,
DynamicCount,
Vip,
RequestFansFailed,
FansSuffix,
NoFans,
RequestFollowsFailed,
NoFollows,
FollowsSuffix,
RequestViewLaterFailed,
ClearViewLater,
NoViewLaterVideos,
FailedToClearViewLater,
FailedToRemoveVideoFromViewLater,
Remove,
AppTip,
ClearViewLaterWarning,
ClearHistory,
FailedToRemoveVideoFromHistory,
FailedToClearHisotry,
NoHistoryVideos,
ClearHistoryWarning,
AddToViewLater,
PlayCount,
DanmakuCount,
ReplyCount,
ChooseCoinNumber,
AlsoLike,
ChooseFavorite,
RequestFavoriteError,
RequestIndexFilterFailed,
PublishInInstalments,
PublishFinished,
RequestIndexResultFailed,
Updated,
NotUpdated,
RequestPgcTimeLineFailed,
RequestPlayListFailed,
PeopleCount,
OriginName,
Alias,
CastAndCrew,
Description,
RequestVideoFavoriteFailed,
Anime,
Cinema,
DefaultFavorite,
SeeDetail,
VideoCount,
FavoriteHaveNoVideos,
RequestAnimeFavoriteFailed,
RequestCinemaFavoriteFailed,
RequestArticleFavoriteFailed,
CollectTime,
LikeCount,
ReadCount,
DeleteFavorite,
UnFavorite,
DeleteFavoriteWarning,
UnFavoriteWarning,
RefreshCurrentSection,
RequestReplyFailed,
MoreReplyDisplay,
SortByHot,
NeedScaleToShowReply,
NoReply,
HotReply,
LastestReply,
ReplyPlaceholderText,
ReplyDetail,
Top,
ReplySomeone,
AddReplyFailed,
RequestDynamicFailed,
RequestArticleFailed,
DynamicNeedLoginFirst,
Login,
RequestMessageFailed,
AtMe,
ReplyMe,
LikeMe,
Lastest,
LikeMessageMultipleDescription,
LikeMessageSingleDescription,
AtMessageTypeDescription,
ReplyMessageTypeDescription,
MorePeople,
Standard,
Small,
FontSize,
Location,
ScrollDanmaku,
TopDanmaku,
BottomDanmaku,
White,
Red,
Orange,
Khaki,
Yellow,
Grass,
Green,
Blue,
Purple,
LightBlue,
Color,
IsNeedFeedback,
IsNeedFeedbackDescription,
AskIssue,
BiliHomePage,
ProjectHomePage,
RelatedProjects,
AddViewLaterSucceseded,
AddViewLaterFailed,
FollowRoom,
FailedToGetUserRelation,
NoRoomDescription,
LogEmptied,
FailedToClearLog,
AboutThisApp,
License,
UnknownError,
Aborted,
NetworkError,
DecodingError,
SourceNotSupported,
NoEpisode,
BackToPrevious,
NotSupportReplyType,
ForwardSkip,
BackSkip,
PlayPause,
DoubleClickBehavior,
DoubleClickBehaviorDescription,
PreferHighQuality,
PreferHighQualityDescription,
Download,
Copied,
Any,
DownloadType,
OnlyVideo,
OnlyAudio,
OnlySubtitle,
Full,
UseMp4Box,
UseMultiThread,
GenerateCommand,
DownloadTip,
AtLeastChooseOnePart,
ToggleDanmakuBarVisibility,
Subtitle,
ShowSubtitle,
SubtitleList,
InterfaceType,
None,
MobileApp,
TVApp,
InternationalApp,
FailedToLoadInteractionVideo,
InteractionEnd,
BackToStart,
PlaybackRate,
ContinuePreviousView,
#pragma warning restore SA1602 // Enumeration items should be documented
}
}
| 22.984127 | 72 | 0.568946 | [
"MIT"
] | ioQoi/Bili.Uwp | src/Models/Models.Enums/App/LanguageNames.cs | 8,690 | C# |
using ReactiveUI;
namespace Xune.ViewModels
{
public class ViewModelBase : ReactiveObject
{
}
} | 13.625 | 47 | 0.697248 | [
"MIT"
] | VitalElement/Xune | Xune.Desktop/ViewModels/ViewModelBase.cs | 111 | C# |
using System;
#if (NETFX_CORE || WINDOWS_UWP)
using Windows.UI.Xaml;
using Windows.UI.Xaml.Markup;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
#else
using System.Windows.Markup;
using System.Windows.Media.Animation;
#endif
namespace MahApps.Metro.IconPacks
{
public interface IPackIconExtension
{
double Width { get; set; }
double Height { get; set; }
PackIconFlipOrientation Flip { get; set; }
double RotationAngle { get; set; }
bool Spin { get; set; }
bool SpinAutoReverse { get; set; }
#if (NETFX_CORE || WINDOWS_UWP)
EasingFunctionBase SpinEasingFunction { get; set; }
#else
IEasingFunction SpinEasingFunction { get; set; }
#endif
double SpinDuration { get; set; }
}
public static class PackIconExtensionHelper
{
public static PackIconControlBase GetPackIcon<TPack, TKind>(this IPackIconExtension packIconExtension, TKind kind) where TPack : PackIconControlBase, new()
{
var packIcon = new TPack();
packIcon.SetKind(kind);
if (((BasePackIconExtension) packIconExtension).IsFieldChanged(BasePackIconExtension.ChangedFieldFlags.Width))
{
packIcon.Width = packIconExtension.Width;
}
if (((BasePackIconExtension) packIconExtension).IsFieldChanged(BasePackIconExtension.ChangedFieldFlags.Height))
{
packIcon.Height = packIconExtension.Height;
}
if (((BasePackIconExtension) packIconExtension).IsFieldChanged(BasePackIconExtension.ChangedFieldFlags.Flip))
{
packIcon.Flip = packIconExtension.Flip;
}
if (((BasePackIconExtension) packIconExtension).IsFieldChanged(BasePackIconExtension.ChangedFieldFlags.RotationAngle))
{
packIcon.RotationAngle = packIconExtension.RotationAngle;
}
if (((BasePackIconExtension) packIconExtension).IsFieldChanged(BasePackIconExtension.ChangedFieldFlags.Spin))
{
packIcon.Spin = packIconExtension.Spin;
}
if (((BasePackIconExtension) packIconExtension).IsFieldChanged(BasePackIconExtension.ChangedFieldFlags.SpinAutoReverse))
{
packIcon.SpinAutoReverse = packIconExtension.SpinAutoReverse;
}
if (((BasePackIconExtension) packIconExtension).IsFieldChanged(BasePackIconExtension.ChangedFieldFlags.SpinEasingFunction))
{
packIcon.SpinEasingFunction = packIconExtension.SpinEasingFunction;
}
if (((BasePackIconExtension) packIconExtension).IsFieldChanged(BasePackIconExtension.ChangedFieldFlags.SpinDuration))
{
packIcon.SpinDuration = packIconExtension.SpinDuration;
}
return packIcon;
}
}
#if (NETFX_CORE || WINDOWS_UWP)
[MarkupExtensionReturnType(ReturnType = typeof(PackIconBase))]
#else
[MarkupExtensionReturnType(typeof(PackIconBase))]
#endif
public abstract class BasePackIconExtension : MarkupExtension, IPackIconExtension
{
private double _width = 16d;
public double Width
{
get => _width;
set
{
if (Equals(_width, value))
{
return;
}
_width = value;
WriteFieldChangedFlag(ChangedFieldFlags.Width, true);
}
}
private double _height = 16d;
public double Height
{
get => _height;
set
{
if (Equals(_height, value))
{
return;
}
_height = value;
WriteFieldChangedFlag(ChangedFieldFlags.Height, true);
}
}
private PackIconFlipOrientation _flip = PackIconFlipOrientation.Normal;
public PackIconFlipOrientation Flip
{
get => _flip;
set
{
if (Equals(_flip, value))
{
return;
}
_flip = value;
WriteFieldChangedFlag(ChangedFieldFlags.Flip, true);
}
}
private double _rotationAngle = 0d;
public double RotationAngle
{
get => _rotationAngle;
set
{
if (Equals(_rotationAngle, value))
{
return;
}
_rotationAngle = value;
WriteFieldChangedFlag(ChangedFieldFlags.RotationAngle, true);
}
}
private bool _spin;
public bool Spin
{
get => _spin;
set
{
if (Equals(_spin, value))
{
return;
}
_spin = value;
WriteFieldChangedFlag(ChangedFieldFlags.Spin, true);
}
}
private bool _spinAutoReverse;
public bool SpinAutoReverse
{
get => _spinAutoReverse;
set
{
if (Equals(_spinAutoReverse, value))
{
return;
}
_spinAutoReverse = value;
WriteFieldChangedFlag(ChangedFieldFlags.SpinAutoReverse, true);
}
}
#if (NETFX_CORE || WINDOWS_UWP)
private EasingFunctionBase _spinEasingFunction = null;
public EasingFunctionBase SpinEasingFunction
#else
private IEasingFunction _spinEasingFunction = null;
public IEasingFunction SpinEasingFunction
#endif
{
get => _spinEasingFunction;
set
{
if (Equals(_spinEasingFunction, value))
{
return;
}
_spinEasingFunction = value;
WriteFieldChangedFlag(ChangedFieldFlags.SpinEasingFunction, true);
}
}
private double _spinDuration = 1d;
public double SpinDuration
{
get => _spinDuration;
set
{
if (Equals(_spinDuration, value))
{
return;
}
_spinDuration = value;
WriteFieldChangedFlag(ChangedFieldFlags.SpinDuration, true);
}
}
internal ChangedFieldFlags changedField; // Cache changed field bits
internal bool IsFieldChanged(ChangedFieldFlags reqFlag)
{
return (changedField & reqFlag) != 0;
}
internal void WriteFieldChangedFlag(ChangedFieldFlags reqFlag, bool set)
{
if (set)
{
changedField |= reqFlag;
}
else
{
changedField &= (~reqFlag);
}
}
[Flags]
internal enum ChangedFieldFlags : ushort
{
Width = 0x0001,
Height = 0x0002,
Flip = 0x0004,
RotationAngle = 0x0008,
Spin = 0x0010,
SpinAutoReverse = 0x0020,
SpinEasingFunction = 0x0040,
SpinDuration = 0x0080
}
}
} | 28.193916 | 163 | 0.540661 | [
"MIT"
] | CrimsonOrion/MahApps.Metro.IconPacks | src/MahApps.Metro.IconPacks.Core/PackIconExtension.cs | 7,417 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ObjectReferenceTypeThatChangesValue
{
public class Order
{
public string name;
}
class Program
{
static void Main(string[] args)
{
var order = new Order();
order.name = "Tuvshin";
var order1 = order;
order1.name = "Anu";
Console.WriteLine(order.name);
}
}
}
| 17.3 | 45 | 0.560694 | [
"MIT"
] | tuvshinot/csharp | csharp/ObjectInitializers/Program.cs | 521 | C# |
using System.Collections.Generic;
namespace SharpFont {
class CharacterMap {
Dictionary<CodePoint, int> table;
CharacterMap (Dictionary<CodePoint, int> table) {
this.table = table;
}
public int Lookup (CodePoint codePoint) {
int index;
if (table.TryGetValue(codePoint, out index))
return index;
return -1;
}
public static CharacterMap ReadCmap (DataReader reader, TableRecord[] tables) {
SfntTables.SeekToTable(reader, tables, FourCC.Cmap, required: true);
// skip version
var cmapOffset = reader.Position;
reader.Skip(sizeof(short));
// read all of the subtable headers
var subtableCount = reader.ReadUInt16BE();
var subtableHeaders = new CmapSubtableHeader[subtableCount];
for (int i = 0; i < subtableHeaders.Length; i++) {
subtableHeaders[i] = new CmapSubtableHeader {
PlatformID = reader.ReadUInt16BE(),
EncodingID = reader.ReadUInt16BE(),
Offset = reader.ReadUInt32BE()
};
}
// search for a "full" Unicode table first
var chosenSubtableOffset = 0u;
for (int i = 0; i < subtableHeaders.Length; i++) {
var platform = subtableHeaders[i].PlatformID;
var encoding = subtableHeaders[i].EncodingID;
if ((platform == PlatformID.Microsoft && encoding == WindowsEncoding.UnicodeFull) ||
(platform == PlatformID.Unicode && encoding == UnicodeEncoding.Unicode32)) {
chosenSubtableOffset = subtableHeaders[i].Offset;
break;
}
}
// if no full unicode table, just grab the first
// one that supports any flavor of Unicode
if (chosenSubtableOffset == 0) {
for (int i = 0; i < subtableHeaders.Length; i++) {
var platform = subtableHeaders[i].PlatformID;
var encoding = subtableHeaders[i].EncodingID;
if ((platform == PlatformID.Microsoft && encoding == WindowsEncoding.UnicodeBmp) ||
platform == PlatformID.Unicode) {
chosenSubtableOffset = subtableHeaders[i].Offset;
break;
}
}
}
// no unicode support at all is an error
if (chosenSubtableOffset == 0)
throw new InvalidFontException("Font does not support Unicode.");
// jump to our chosen table and find out what format it's in
reader.Seek(cmapOffset + chosenSubtableOffset);
var format = reader.ReadUInt16BE();
switch (format) {
case 4: return ReadCmapFormat4(reader);
default: throw new InvalidFontException("Unsupported cmap format.");
}
}
unsafe static CharacterMap ReadCmapFormat4 (DataReader reader) {
// skip over length and language
reader.Skip(sizeof(short) * 2);
// figure out how many segments we have
var segmentCount = reader.ReadUInt16BE() / 2;
if (segmentCount > MaxSegments)
throw new InvalidFontException("Too many cmap segments.");
// skip over searchRange, entrySelector, and rangeShift
reader.Skip(sizeof(short) * 3);
// read in segment ranges
var endCount = stackalloc int[segmentCount];
for (int i = 0; i < segmentCount; i++)
endCount[i] = reader.ReadUInt16BE();
reader.Skip(sizeof(short)); // padding
var startCount = stackalloc int[segmentCount];
for (int i = 0; i < segmentCount; i++)
startCount[i] = reader.ReadUInt16BE();
var idDelta = stackalloc int[segmentCount];
for (int i = 0; i < segmentCount; i++)
idDelta[i] = reader.ReadInt16BE();
// build table from each segment
var table = new Dictionary<CodePoint, int>();
for (int i = 0; i < segmentCount; i++) {
// read the "idRangeOffset" for the current segment
// if nonzero, we need to jump into the glyphIdArray to figure out the mapping
// the layout is bizarre; see the OpenType spec for details
var idRangeOffset = reader.ReadUInt16BE();
if (idRangeOffset != 0) {
var currentOffset = reader.Position;
reader.Seek(currentOffset + idRangeOffset - sizeof(ushort));
var end = endCount[i];
var delta = idDelta[i];
for (var codepoint = startCount[i]; codepoint <= end; codepoint++) {
var glyphId = reader.ReadUInt16BE();
if (glyphId != 0) {
var glyphIndex = (glyphId + delta) & 0xFFFF;
if (glyphIndex != 0)
table.Add((CodePoint)codepoint, glyphIndex);
}
}
reader.Seek(currentOffset);
}
else {
// otherwise, do a straight iteration through the segment
var end = endCount[i];
var delta = idDelta[i];
for (var codepoint = startCount[i]; codepoint <= end; codepoint++) {
var glyphIndex = (codepoint + delta) & 0xFFFF;
if (glyphIndex != 0)
table.Add((CodePoint)codepoint, glyphIndex);
}
}
}
return new CharacterMap(table);
}
const int MaxSegments = 1024;
struct CmapSubtableHeader {
public int PlatformID;
public int EncodingID;
public uint Offset;
}
}
}
| 40.434211 | 103 | 0.516433 | [
"MIT"
] | MikePopoloski/SharpFont | SharpFont/Internal/CharacterMap.cs | 6,148 | C# |
using System;
namespace CCTU.Entities
{
public interface IPessoaJuridica
{
/// <summary>
/// CNPJ da Empresa
/// </summary>
string CNPJ { get; set; }
/// <summary>
/// Nome da Empresa
/// </summary>
string Nome { get; set; }
/// <summary>
/// Nome fantasia da Empresa
/// </summary>
string NomeFantasia { get; set; }
/// <summary>
/// Inscrição municipal da empresa
/// </summary>
string InscricaoEstadual { get; set; }
/// <summary>
/// Data de fundação da empresa
/// </summary>
DateTime DataFundacao {get;set;}
}
}
| 21.090909 | 46 | 0.488506 | [
"Apache-2.0"
] | renanfactory/cerberus-pattern | CCUT/CCTU.Entities/IPessoaJuridica.cs | 702 | C# |
using Mirror;
namespace WeaverCommandTests.VirtualCommand
{
class VirtualCommand : NetworkBehaviour
{
[Command]
protected virtual void CmdDoSomething()
{
// do something
}
}
}
| 15.666667 | 47 | 0.591489 | [
"MIT"
] | 10allday/OpenMMO | Plugins/3rdParty/Mirror/Tests/Editor/Weaver/WeaverCommandTests~/VirtualCommand.cs | 237 | C# |
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace WebAPIApp.Areas.HelpPage.ModelDescriptions
{
public class EnumTypeModelDescription : ModelDescription
{
public EnumTypeModelDescription()
{
Values = new Collection<EnumValueDescription>();
}
public Collection<EnumValueDescription> Values { get; private set; }
}
} | 26.866667 | 76 | 0.707196 | [
"Apache-2.0"
] | iliantrifonov/TelerikAcademy | ASP.NETWebForms/01.IntroductionToASP.NET/WebAPIApp/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs | 403 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Compute.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Operation status response
/// </summary>
public partial class OperationStatusResponse
{
/// <summary>
/// Initializes a new instance of the OperationStatusResponse class.
/// </summary>
public OperationStatusResponse()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the OperationStatusResponse class.
/// </summary>
/// <param name="name">Operation ID</param>
/// <param name="status">Operation status</param>
/// <param name="startTime">Start time of the operation</param>
/// <param name="endTime">End time of the operation</param>
/// <param name="error">Api error</param>
public OperationStatusResponse(string name = default(string), string status = default(string), System.DateTime? startTime = default(System.DateTime?), System.DateTime? endTime = default(System.DateTime?), ApiError error = default(ApiError))
{
Name = name;
Status = status;
StartTime = startTime;
EndTime = endTime;
Error = error;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets operation ID
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; private set; }
/// <summary>
/// Gets operation status
/// </summary>
[JsonProperty(PropertyName = "status")]
public string Status { get; private set; }
/// <summary>
/// Gets start time of the operation
/// </summary>
[JsonProperty(PropertyName = "startTime")]
public System.DateTime? StartTime { get; private set; }
/// <summary>
/// Gets end time of the operation
/// </summary>
[JsonProperty(PropertyName = "endTime")]
public System.DateTime? EndTime { get; private set; }
/// <summary>
/// Gets api error
/// </summary>
[JsonProperty(PropertyName = "error")]
public ApiError Error { get; private set; }
}
}
| 32.940476 | 248 | 0.591977 | [
"MIT"
] | AzureAutomationTeam/azure-sdk-for-net | src/SDKs/Compute/Management.Compute/Generated/Models/OperationStatusResponse.cs | 2,767 | C# |
using System;
using System.IO;
namespace ConsoleApp159
{
class Program
{
public static void Main()
{
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (var variable in allDrives)
{
Console.WriteLine("Drive :: " + variable.Name);
Console.WriteLine(" Drive type :: "+ variable.DriveType);
if (variable.IsReady)
{
Console.WriteLine("Volume label :: " + variable.VolumeLabel);
Console.WriteLine("File System :: "+ variable.DriveFormat);
Console.WriteLine(" Available free space to current :: "+variable.AvailableFreeSpace);
Console.WriteLine(" Total Available space :: " +variable.TotalFreeSpace);
Console.WriteLine("Total size of drive "+variable.TotalSize);
}
}
}
}
}
| 28.785714 | 97 | 0.621588 | [
"MIT"
] | hraverkar/.NetFramework-Sys.IO-Topics | DriveInfo.cs | 806 | C# |
using System.Collections.Generic;
using System.Runtime.Serialization;
using UnityEngine;
public abstract class SerializableDictionaryBase<TKey, TValue, TValueStorage> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver
{
[SerializeField]
TKey[] m_keys;
[SerializeField]
TValueStorage[] m_values;
public SerializableDictionaryBase()
{
}
public SerializableDictionaryBase(IDictionary<TKey, TValue> dict) : base(dict.Count)
{
foreach (var kvp in dict)
{
this[kvp.Key] = kvp.Value;
}
}
protected SerializableDictionaryBase(SerializationInfo info, StreamingContext context) : base(info,context){}
protected abstract void SetValue(TValueStorage[] storage, int i, TValue value);
protected abstract TValue GetValue(TValueStorage[] storage, int i);
public void CopyFrom(IDictionary<TKey, TValue> dict)
{
this.Clear();
foreach (var kvp in dict)
{
this[kvp.Key] = kvp.Value;
}
}
public void OnAfterDeserialize()
{
if(m_keys != null && m_values != null && m_keys.Length == m_values.Length)
{
this.Clear();
int n = m_keys.Length;
for(int i = 0; i < n; ++i)
{
this[m_keys[i]] = GetValue(m_values, i);
}
m_keys = null;
m_values = null;
}
}
public void OnBeforeSerialize()
{
int n = this.Count;
m_keys = new TKey[n];
m_values = new TValueStorage[n];
int i = 0;
foreach(var kvp in this)
{
m_keys[i] = kvp.Key;
SetValue(m_values, i, kvp.Value);
++i;
}
}
}
public class SerializableDictionary<TKey, TValue> : SerializableDictionaryBase<TKey, TValue, TValue>
{
public SerializableDictionary()
{
}
public SerializableDictionary(IDictionary<TKey, TValue> dict) : base(dict)
{
}
protected SerializableDictionary(SerializationInfo info, StreamingContext context) : base(info,context){}
protected override TValue GetValue(TValue[] storage, int i)
{
return storage[i];
}
protected override void SetValue(TValue[] storage, int i, TValue value)
{
storage[i] = value;
}
}
public static class SerializableDictionary
{
public class Storage<T>
{
public T data;
}
}
public class SerializableDictionary<TKey, TValue, TValueStorage> : SerializableDictionaryBase<TKey, TValue, TValueStorage> where TValueStorage : SerializableDictionary.Storage<TValue>, new()
{
public SerializableDictionary()
{
}
public SerializableDictionary(IDictionary<TKey, TValue> dict) : base(dict)
{
}
protected SerializableDictionary(SerializationInfo info, StreamingContext context) : base(info,context){}
protected override TValue GetValue(TValueStorage[] storage, int i)
{
return storage[i].data;
}
protected override void SetValue(TValueStorage[] storage, int i, TValue value)
{
storage[i] = new TValueStorage();
storage[i].data = value;
}
}
| 22.201613 | 190 | 0.720305 | [
"MIT"
] | Light3039/Unity-Managers | Assets/3rd-Party/SerializableDictionary/SerializableDictionary.cs | 2,755 | C# |
using System.Collections;
using UnityEngine;
public class Bullet3 : MonoBehaviour
{
public GameObject bullet_prefab;
public Vector2 pullbackdirection;
public Vector3 u1;
public Vector3 u2;
public Vector3 u3;
public Vector3 u4;
public Vector3 u5;
public GameObject Gunfight;
private void Start()
{
Transform[] allChildren = ((GameObject)(GameObject)GameObject.Find("Tank")).transform.GetComponentsInChildren<Transform>();
foreach (Transform t in allChildren)
{
if (t != null && t.gameObject.name == "Gunfight")
{
Gunfight = t.gameObject;
// Debug.Log("ra roi ");
}
}
Vector3 mousePositionInWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
StartCoroutine(_Wait(0.000000000000001f));
}
// Update is called once per frame
private void Update()
{
}
private IEnumerator _Wait(float duration)
{
Vector3 mousePositionInWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
getRandomVector(mousePositionInWorld - Gunfight.transform.position);
var bullet2_1 = (GameObject)Instantiate(bullet_prefab, Gunfight.transform.position, Quaternion.identity);
bullet2_1.GetComponent<Bullet31>().directionvector = u1;
yield return new WaitForSeconds(duration); //Wait
var bullet2_2 = (GameObject)Instantiate(bullet_prefab, Gunfight.transform.position, Quaternion.identity);
bullet2_2.GetComponent<Bullet31>().directionvector = u2;
yield return new WaitForSeconds(duration); //Wait
var bullet2_3 = (GameObject)Instantiate(bullet_prefab, Gunfight.transform.position, Quaternion.identity);
bullet2_3.GetComponent<Bullet31>().directionvector = u3;
yield return new WaitForSeconds(duration); //Wait
var bullet2_4 = (GameObject)Instantiate(bullet_prefab, Gunfight.transform.position, Quaternion.identity);
bullet2_4.GetComponent<Bullet31>().directionvector = u4;
}
public Vector2 getnormalizedVector(Vector2 target)
{
float mauso = Mathf.Sqrt(target.x * target.x + target.y * target.y);
return new Vector2(target.x / mauso, target.y / mauso);
}
public void getRandomVector(Vector3 input)
{
float n = 0.3f;
u1 = new Vector3(input.x + n, input.y - n, input.z);
u2 = new Vector3(input.x + n, input.y + n, input.z);
u3 = new Vector3(input.x - n, input.y + n, input.z);
u4 = new Vector3(input.x - n, input.y - n, input.z);
u5 = new Vector3(input.x + n, input.y - n, input.z);
}
} | 36.506849 | 131 | 0.657786 | [
"Apache-2.0"
] | TrangNguyen702/DATN_Client | Assets/Scripts/GameScreen/Bullet3.cs | 2,667 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Windows.Forms
{
/// <summary>
/// Enum defining inclusion of special characters.
/// </summary>
public enum MaskFormat
{
IncludePrompt = 0x0001,
IncludeLiterals = 0x0002,
// both of the above
IncludePromptAndLiterals = 0x0003,
// Never include special characters.
ExcludePromptAndLiterals = 0x000
}
}
| 27.181818 | 71 | 0.667224 | [
"MIT"
] | 15835229565/winforms-1 | src/System.Windows.Forms/src/System/Windows/Forms/MaskFormat.cs | 600 | C# |
using System;
using Vlc.DotNet.Core.Interops.Signatures;
namespace Vlc.DotNet.Core.Interops
{
public sealed partial class VlcManager
{
public void ParseMediaAsync(VlcMediaInstance mediaPlayerInstance)
{
if (mediaPlayerInstance == IntPtr.Zero)
throw new ArgumentException("Media player instance is not initialized.");
GetInteropDelegate<ParseMediaAsync>().Invoke(mediaPlayerInstance);
}
}
}
| 29.25 | 89 | 0.683761 | [
"MIT"
] | CrookedFingerGuy/Vlc.DotNet | src/Vlc.DotNet.Core.Interops/VlcManager.ParseMediaAsync.cs | 470 | C# |
using System;
using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.EntityFrameworkCore;
using Microsoft.Identity.Web;
using TodoListAPI.Models;
using TodoListAPI.Services;
using TodoListAPI.Repository;
using TodoListAPI.BackGroundWorker;
using TodoListAPI.BackGroundWorker.MessageHandler;
using TodoListAPI.BackGroundWorker.Message;
namespace TodoListAPI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Setting configuration for protected web api
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(Configuration);
services.AddSingleton<IConfiguration>(Configuration);
// Uncomment this section if you would like to validate ID tokens for allowed tenantIds
// services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
// {
// options.Events.OnTokenValidated = async context =>
// {
// string[] allowedTenants = { /* list of tenant IDs */ };
// string tenantId = ((JwtSecurityToken)context.SecurityToken).Claims.FirstOrDefault(x => x.Type == "tid" || x.Type == "http://schemas.microsoft.com/identity/claims/tenantid")?.Value;
// if (!allowedTenants.Contains(tenantId))
// {
// throw new UnauthorizedAccessException("This tenant is not authorized");
// }
// };
// });
// Creating policies that wraps the authorization requirements
services.AddAuthorization();
services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList"));
services.AddSingleton<INotifier>(new Notifier());
services.AddSingleton<IGraphAuthService>(new GraphAuthService());
services.AddControllers();
// Allowing CORS for all domains and methods for the purpose of sample
services.AddCors(o => o.AddPolicy("default", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
services.AddHttpClient<IZoomAuthService, ZoomAuthService>();
services.AddHttpClient<IAADAuthService, AADAuthService>();
services.AddSingleton<IUserRepository>(new InMemoryUserRepository());
services.AddHttpClient<FetchZoomUserMessageHandler, FetchZoomUserMessageHandler>();
services.AddHttpClient<FetchZoomChannelsForUserHandler, FetchZoomChannelsForUserHandler>();
services.AddHttpClient<FetchParticipantsForZoomChannelHandler, FetchParticipantsForZoomChannelHandler>();
services.AddHttpClient<FetchChatMessageForChannelHandler, FetchChatMessageForChannelHandler>();
services.AddHttpClient<ImportChatMessagesIntoTeamsHandler, ImportChatMessagesIntoTeamsHandler>();
services.AddHttpClient<FetchGraphUserHandler, FetchGraphUserHandler>();
RegisterMessageHandlersWithNotifier(services);
}
private void RegisterMessageHandlersWithNotifier(IServiceCollection services)
{
var serviceProvider = services.BuildServiceProvider();
var notifier = serviceProvider.GetService<INotifier>();
notifier.AddMessageHandler(MessageConstants.ZoomLoginMessageType,
serviceProvider.GetService<FetchZoomUserMessageHandler>());
notifier.AddMessageHandler(MessageConstants.FetchZoomChannelsForUserMessageType,
serviceProvider.GetService<FetchZoomChannelsForUserHandler>());
notifier.AddMessageHandler(MessageConstants.FetchParticipantsForZoomChannelUserMessageType,
serviceProvider.GetService<FetchParticipantsForZoomChannelHandler>());
notifier.AddMessageHandler(MessageConstants.FetchChatMessagesForZoomChannel,
serviceProvider.GetService<FetchChatMessageForChannelHandler>());
notifier.AddMessageHandler(MessageConstants.ImportChatMessagesForZoomChannelIntoTeams,
serviceProvider.GetService<ImportChatMessagesIntoTeamsHandler>());
notifier.AddMessageHandler(MessageConstants.FetchAADUser,
serviceProvider.GetService<FetchGraphUserHandler>());
notifier.StartPolingAsync();
}
// 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())
{
// Since IdentityModel version 5.2.1 (or since Microsoft.AspNetCore.Authentication.JwtBearer version 2.2.0),
// Personal Identifiable Information is not written to the logs by default, to be compliant with GDPR.
// For debugging/development purposes, one can enable additional detail in exceptions by setting IdentityModelEventSource.ShowPII to true.
// Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
app.UseDeveloperExceptionPage();
}
else
{
Console.WriteLine("in prod" + Configuration["AppClientId"]);
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseCors("default");
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
} | 50.601563 | 203 | 0.666203 | [
"MIT"
] | VikneshMSFT/ms-identity-javascript-angular-spa-aspnet-webapi-multitenant | Chapter2/TodoListAPI/Startup.cs | 6,477 | C# |
//-----------------------------------------------------------------------
// <copyright company="CoApp Project">
// ResourceLib Original Code from http://resourcelib.codeplex.com
// Original Copyright (c) 2008-2009 Vestris Inc.
// Changes Copyright (c) 2011 Garrett Serack . All rights reserved.
// </copyright>
// <license>
// MIT License
// You may freely use and distribute this software under the terms of the following license agreement.
//
// 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
// </license>
//-----------------------------------------------------------------------
namespace ClrPlus.Windows.PeBinary.ResourceLib {
using System;
using System.IO;
using System.Runtime.InteropServices;
using Api.Enumerations;
using Api.Flags;
using Api.Structures;
/// <summary>
/// Standard accelerator.
/// </summary>
public class Accelerator {
private Accel _accel;
/// <summary>
/// String representation of the accelerator key.
/// </summary>
public string Key {
get {
var key = Enum.GetName(typeof (VirtualKeys), _accel.key);
return string.IsNullOrEmpty(key) ? ((char)_accel.key).ToString() : key;
}
}
/// <summary>
/// An unsigned integer value that identifies the accelerator.
/// </summary>
public UInt32 Command {
get {
return _accel.cmd;
}
set {
_accel.cmd = value;
}
}
/// <summary>
/// Read the accelerator.
/// </summary>
/// <param name="lpRes">Address in memory.</param>
internal IntPtr Read(IntPtr lpRes) {
_accel = (Accel)Marshal.PtrToStructure(lpRes, typeof (Accel));
return new IntPtr(lpRes.ToInt32() + Marshal.SizeOf(_accel));
}
/// <summary>
/// Write accelerator to a binary stream.
/// </summary>
/// <param name="w">Binary stream.</param>
internal void Write(BinaryWriter w) {
w.Write(_accel.fVirt);
w.Write(_accel.key);
w.Write(_accel.cmd);
ResourceUtil.PadToWORD(w);
}
/// <summary>
/// String representation of the accelerator.
/// </summary>
/// <returns>String representation of the accelerator.</returns>
public override string ToString() {
return string.Format("{0}, {1}, {2}", Key, Command, ResourceUtil.FlagsToString<AcceleratorVirtualKey>(_accel.fVirt).Replace(" |", ","));
}
}
} | 41.32967 | 149 | 0.584951 | [
"Apache-2.0"
] | Jaykul/clrplus | Windows.PeBinary/ResourceLib/Accelerator.cs | 3,763 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DalSic
{
public partial class SysUsuario
{
//Propiedad que utilizaremos para saber si el usuario tiene o no habilitado
//el acceso a una determinada pagina
public bool IsPageEnabled(string pageName)
{
if (!pageName.StartsWith("~"))
pageName = "~" + pageName;
//bool result = false;
System.Data.DataSet ds = SPs.UsrIsPerfilPageEnabled(pageName, this.SysPerfil.Nombre).GetDataSet();
System.Data.DataView dv = new System.Data.DataView(ds.Tables[0]);
//if (dv.Count > 0)
// result = true;
return (dv.Count > 0);
}
public bool IsActionEnabled(string actionName)
{
System.Data.DataSet ds = SPs.UsrIsPerfilActionEnabled(actionName, this.SysPerfil.Nombre).GetDataSet();
System.Data.DataView dv = new System.Data.DataView(ds.Tables[0]);
return (dv.Count > 0);
}
}
}
| 32.484848 | 114 | 0.603545 | [
"MIT"
] | saludnqn/Empadronamiento | DalSic/SysUsuario.cs | 1,074 | C# |
using DragonSpark.Compose;
using Syncfusion.Blazor;
using System.Threading.Tasks;
namespace DragonSpark.Syncfusion.Queries;
sealed class Sort<T> : IQuery<T>
{
public static Sort<T> Default { get; } = new Sort<T>();
Sort() {}
public ValueTask<Parameter<T>> Get(Parameter<T> parameter)
{
var (request, query, count) = parameter;
var data = request.Sorted?.Count > 0
? new(request, DataOperations.PerformSorting(query, request.Sorted), count)
: parameter;
var result = data.ToOperation();
return result;
}
} | 25 | 89 | 0.683636 | [
"MIT"
] | DragonSpark/Framework | DragonSpark.Syncfusion/Queries/Sort.cs | 552 | C# |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Reflection;
namespace Igor
{
public static class InspectableObjectHelper
{
public static FieldInfo LastControlIdField=typeof(EditorGUI).GetField("lastControlID", BindingFlags.Static|BindingFlags.NonPublic);
public static int GetLastControlId(){
if(LastControlIdField==null){
Debug.LogError("Compatibility with Unity broke: can't find lastControlId field in EditorGUI");
return 0;
}
return (int)LastControlIdField.GetValue(null);
}
public static bool KeyPressed<T>(this T s, string controlName,KeyCode key, T currentSetValue, out T fieldValue)
{
fieldValue = s;
if(GUI.GetNameOfFocusedControl()==controlName)
{
if ((Event.current.type == EventType.KeyUp) && (Event.current.keyCode == key))
{
return true;
}
return false;
}
else
{
fieldValue = currentSetValue;
return false;
}
}
}
}
| 23.243902 | 133 | 0.70829 | [
"MIT"
] | mikamikem/Igor | Modules/Utilities/NodeGraph/Editor/InspectableObjectHelper.cs | 955 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Text;
using Silk.NET.Core;
using Silk.NET.Core.Native;
using Silk.NET.Core.Attributes;
using Silk.NET.Core.Contexts;
using Silk.NET.Core.Loader;
#pragma warning disable 1591
namespace Silk.NET.OpenXR
{
[NativeName("Name", "XrExtent2Di")]
public unsafe partial struct Extent2Di
{
public Extent2Di
(
int? width = null,
int? height = null
) : this()
{
if (width is not null)
{
Width = width.Value;
}
if (height is not null)
{
Height = height.Value;
}
}
/// <summary></summary>
[NativeName("Type", "int32_t")]
[NativeName("Type.Name", "int32_t")]
[NativeName("Name", "width")]
public int Width;
/// <summary></summary>
[NativeName("Type", "int32_t")]
[NativeName("Type.Name", "int32_t")]
[NativeName("Name", "height")]
public int Height;
}
}
| 24.176471 | 71 | 0.575831 | [
"MIT"
] | Ar37-rs/Silk.NET | src/OpenXR/Silk.NET.OpenXR/Structs/Extent2Di.gen.cs | 1,233 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.SharePoint.Client.NetCore.Runtime
{
public class ClientObjectPrototype
{
private ClientQueryInternal m_query;
private bool m_childItem;
private Dictionary<string, ClientObjectPrototype> m_subObjectPrototypes;
private Dictionary<string, ClientObjectPrototype> m_subObjectCollectionProperties;
internal ClientQueryInternal Query
{
get
{
return this.m_query;
}
}
internal bool ChildItemPrototype
{
get
{
return this.m_childItem;
}
}
internal ClientObjectPrototype(ClientQueryInternal query, bool childItem)
{
this.m_query = query;
this.m_childItem = childItem;
}
public void Retrieve()
{
if (this.m_childItem)
{
this.Query.ChildItemQuery.SelectAllProperties();
return;
}
this.Query.SelectAllProperties();
}
public void Retrieve(params string[] propertyNames)
{
if (this.m_childItem)
{
for (int i = 0; i < propertyNames.Length; i++)
{
string propertyName = propertyNames[i];
this.Query.ChildItemQuery.Select(propertyName);
}
return;
}
for (int j = 0; j < propertyNames.Length; j++)
{
string propertyName2 = propertyNames[j];
this.Query.Select(propertyName2);
}
}
public ClientObjectPrototype<PropertyType> RetrieveObject<PropertyType>(string propertyName)
{
if (this.m_subObjectPrototypes == null)
{
this.m_subObjectPrototypes = new Dictionary<string, ClientObjectPrototype>();
}
ClientObjectPrototype clientObjectPrototype = null;
if (this.m_subObjectPrototypes.TryGetValue(propertyName, out clientObjectPrototype))
{
return (ClientObjectPrototype<PropertyType>)clientObjectPrototype;
}
bool flag = false;
ClientQueryInternal clientQueryInternal;
if (this.m_childItem)
{
clientQueryInternal = this.m_query.ChildItemQuery.GetSubQuery(propertyName);
}
else
{
clientQueryInternal = this.m_query.GetSubQuery(propertyName);
}
if (clientQueryInternal == null)
{
clientQueryInternal = new ClientQueryInternal(null, propertyName, true, this.m_query);
flag = true;
}
ClientObjectPrototype<PropertyType> clientObjectPrototype2 = new ClientObjectPrototype<PropertyType>(clientQueryInternal, false);
if (flag)
{
if (this.m_childItem)
{
this.m_query.ChildItemQuery.SelectSubQuery(clientQueryInternal);
}
else
{
this.m_query.SelectSubQuery(clientQueryInternal);
}
}
this.m_subObjectPrototypes[propertyName] = clientObjectPrototype2;
return clientObjectPrototype2;
}
public ClientObjectCollectionPrototype<ItemType> RetrieveCollectionObject<ItemType>(string propertyName)
{
if (this.m_subObjectCollectionProperties == null)
{
this.m_subObjectCollectionProperties = new Dictionary<string, ClientObjectPrototype>();
}
ClientObjectPrototype clientObjectPrototype = null;
if (this.m_subObjectCollectionProperties.TryGetValue(propertyName, out clientObjectPrototype))
{
return (ClientObjectCollectionPrototype<ItemType>)clientObjectPrototype;
}
bool flag = false;
ClientQueryInternal clientQueryInternal;
if (this.m_childItem)
{
clientQueryInternal = this.m_query.ChildItemQuery.GetSubQuery(propertyName);
}
else
{
clientQueryInternal = this.m_query.GetSubQuery(propertyName);
}
if (clientQueryInternal == null)
{
clientQueryInternal = new ClientQueryInternal(null, propertyName, true, this.m_query);
flag = true;
}
ClientObjectCollectionPrototype<ItemType> clientObjectCollectionPrototype = new ClientObjectCollectionPrototype<ItemType>(clientQueryInternal, false);
if (flag)
{
if (this.m_childItem)
{
this.m_query.ChildItemQuery.SelectSubQuery(clientQueryInternal);
}
else
{
this.m_query.SelectSubQuery(clientQueryInternal);
}
}
this.m_subObjectCollectionProperties[propertyName] = clientObjectCollectionPrototype;
return clientObjectCollectionPrototype;
}
}
public class ClientObjectPrototype<T> : ClientObjectPrototype
{
internal ClientObjectPrototype(ClientQueryInternal query, bool childItem) : base(query, childItem)
{
}
}
}
| 34.64375 | 162 | 0.567382 | [
"MIT"
] | OneBitSoftware/NetCore.CSOM | Microsoft.SharePoint.Client.NetCore/Runtime/ClientObjectPrototype.cs | 5,545 | C# |
/*
Copyright 2020 Micah Schuster
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 HOLDER 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.
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
/// <summary>
/// Instance of this GameManager object.
/// </summary>
private static GameManager _instance = null;
/// <summary>
/// Prefab GameObject that represents the pipe. Serialized.
/// </summary>
[SerializeField]
private GameObject pipePrefab;
[SerializeField]
private List<GameObject> buildingPrefabList;
/// <summary>
/// Object that contains the PlayerController script. Serialized.
/// </summary>
[SerializeField]
public PlayerController player;
/// <summary>
/// Y Rgane that the pipes can spawn over. Serialized.
/// </summary>
[SerializeField]
private float spawnRange = 3f;
/// <summary>
/// Starting time between pipe spawns. Serialized.
/// </summary>
[SerializeField]
private float timeBetweenSpawn = 3;
/// <summary>
/// Timer for spawn. Determines when new spawns will happen.
/// </summary>
private float spawnTime = 0;
private float timeBetweenBuildingSpawn = 2f;
private float buildingSpawnTime = 0f;
/// <summary>
/// Player state information, true for dead, false for alive.
/// </summary>
[System.NonSerialized]
public bool dead = false;
/// <summary>
/// State machine variable.
/// </summary>
private State state;
/// <summary>
/// Static variable that determines if the pipes will update their movement.
/// </summary>
[System.NonSerialized]
public bool moving = true;
private void Awake()
{
if (_instance == null)
{
_instance = this;
}
}
/// <summary>
/// Global entry point for the GameManager Singleton class.
/// </summary>
/// <returns>Singleton instance of the GameManager class</returns>
public static GameManager instance()
{
return _instance;
}
/// <summary>
/// Start is called before the first frame update
/// </summary>
void Start()
{
if (pipePrefab == null) Debug.LogError("PipePrefab not found!");
state = new Play();
}
/// <summary>
/// Update is called once per frame
/// </summary>
void Update()
{
//process the current state of the game every frame.
state = state.process();
}
public void spawnPipePair()
{
if (spawnTime <= 0)
{
spawnTime = timeBetweenSpawn;
//random y
float topYSpawn = Random.Range(-spawnRange, spawnRange);
float topYAngle = Random.Range(0f, 180f);
float xSpawn = 30f;
//actually do the spawn
Instantiate(pipePrefab, new Vector3(xSpawn, topYSpawn, -2.5f), Quaternion.Euler(0f, topYAngle, 0f));
float botYSpawn = topYSpawn - 2f - Random.Range(0f, 2f);
float botYAngle = Random.Range(0f, 180f);
Instantiate(pipePrefab, new Vector3(xSpawn, botYSpawn, -2.5f), Quaternion.Euler(180f, botYAngle, 0f));
//also spawn score plane here too!
}
else
{
spawnTime -= Time.deltaTime;
}
}
public void spawnBuilding()
{
if (buildingSpawnTime <= 0)
{
buildingSpawnTime = timeBetweenBuildingSpawn;
//random y
float ySpawn = -12f - Random.Range(0f, 1f);
float xSpawn = 30f;
GameObject chosenBuilding = buildingPrefabList[Random.Range(0, buildingPrefabList.Count)];
//actually do the spawn
Instantiate(chosenBuilding, new Vector3(xSpawn, ySpawn, -2.5f), Quaternion.Euler(0f, 90f, 0f));
}
else
{
buildingSpawnTime -= Time.deltaTime;
}
}
/// <summary>
/// Code to run when the game over is triggered.
/// </summary>
public void gameOver()
{
player.gameObject.SetActive(false);
this.moving = false;
}
/// <summary>
/// Code to run when the reset is triggered.
/// </summary>
public void reset()
{
this.dead = false;
this.moving = true;
Time.timeScale = 1f;
player.gameObject.SetActive(true);
player.transform.position = Vector3.zero;
}
/// <summary>
/// Code to run when the player object death is triggered.
/// </summary>
public void death()
{
GameManager.instance().gameOver();
Vector3 offset = new Vector3(3.4f, 0f, 1.13f);
GameObject go = Instantiate(player.deathEffect, player.transform.position, Quaternion.identity);
go.GetComponent<ParticleSystem>().Play();
}
}
| 29.317073 | 114 | 0.637438 | [
"BSD-2-Clause"
] | mdschuster/FlappyDroid | Assets/Scripts/GameManager.cs | 6,012 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using Xunit;
using Yarp.ReverseProxy.Common.Tests;
using Yarp.ReverseProxy.Configuration;
using Yarp.ReverseProxy.Model;
namespace Yarp.ReverseProxy.SessionAffinity.Tests
{
public class CookieSessionAffinityPolicyTests
{
private readonly SessionAffinityConfig _config = new SessionAffinityConfig
{
Enabled = true,
Policy = "Cookie",
FailurePolicy = "Return503",
AffinityKeyName = "My.Affinity",
Cookie = new SessionAffinityCookieConfig
{
Domain = "mydomain.my",
HttpOnly = false,
IsEssential = true,
MaxAge = TimeSpan.FromHours(1),
Path = "/some",
SameSite = SameSiteMode.Lax,
SecurePolicy = CookieSecurePolicy.Always,
}
};
private readonly IReadOnlyList<DestinationState> _destinations = new[] { new DestinationState("dest-A"), new DestinationState("dest-B"), new DestinationState("dest-C") };
[Fact]
public void FindAffinitizedDestination_AffinityKeyIsNotSetOnRequest_ReturnKeyNotSet()
{
var policy = new CookieSessionAffinityPolicy(
AffinityTestHelper.GetDataProtector().Object,
new ManualClock(),
AffinityTestHelper.GetLogger<CookieSessionAffinityPolicy>().Object);
Assert.Equal(SessionAffinityConstants.Policies.Cookie, policy.Name);
var context = new DefaultHttpContext();
context.Request.Headers["Cookie"] = new[] { $"Some-Cookie=ZZZ" };
var cluster = new ClusterState("cluster");
var affinityResult = policy.FindAffinitizedDestinations(context, cluster, _config, _destinations);
Assert.Equal(AffinityStatus.AffinityKeyNotSet, affinityResult.Status);
Assert.Null(affinityResult.Destinations);
}
[Fact]
public void FindAffinitizedDestination_AffinityKeyIsSetOnRequest_Success()
{
var policy = new CookieSessionAffinityPolicy(
AffinityTestHelper.GetDataProtector().Object,
new ManualClock(),
AffinityTestHelper.GetLogger<CookieSessionAffinityPolicy>().Object);
var context = new DefaultHttpContext();
var affinitizedDestination = _destinations[1];
context.Request.Headers["Cookie"] = GetCookieWithAffinity(affinitizedDestination);
var cluster = new ClusterState("cluster");
var affinityResult = policy.FindAffinitizedDestinations(context, cluster, _config, _destinations);
Assert.Equal(AffinityStatus.OK, affinityResult.Status);
Assert.Equal(1, affinityResult.Destinations.Count);
Assert.Same(affinitizedDestination, affinityResult.Destinations[0]);
}
[Fact]
public void AffinitizedRequest_CustomConfigAffinityKeyIsNotExtracted_SetKeyOnResponse()
{
var policy = new CookieSessionAffinityPolicy(
AffinityTestHelper.GetDataProtector().Object,
new ManualClock(),
AffinityTestHelper.GetLogger<CookieSessionAffinityPolicy>().Object);
var context = new DefaultHttpContext();
policy.AffinitizeResponse(context, new ClusterState("cluster"), _config, _destinations[1]);
var affinityCookieHeader = context.Response.Headers["Set-Cookie"];
Assert.Equal("My.Affinity=ZGVzdC1C; max-age=3600; domain=mydomain.my; path=/some; secure; samesite=lax", affinityCookieHeader);
}
[Fact]
public void AffinitizeRequest_CookieConfigSpecified_UseIt()
{
var policy = new CookieSessionAffinityPolicy(
AffinityTestHelper.GetDataProtector().Object,
new ManualClock(),
AffinityTestHelper.GetLogger<CookieSessionAffinityPolicy>().Object);
var context = new DefaultHttpContext();
policy.AffinitizeResponse(context, new ClusterState("cluster"), _config, _destinations[1]);
var affinityCookieHeader = context.Response.Headers["Set-Cookie"];
Assert.Equal("My.Affinity=ZGVzdC1C; max-age=3600; domain=mydomain.my; path=/some; secure; samesite=lax", affinityCookieHeader);
}
[Fact]
public void AffinitizedRequest_AffinityKeyIsExtracted_DoNothing()
{
var policy = new CookieSessionAffinityPolicy(
AffinityTestHelper.GetDataProtector().Object,
new ManualClock(),
AffinityTestHelper.GetLogger<CookieSessionAffinityPolicy>().Object);
var context = new DefaultHttpContext();
var affinitizedDestination = _destinations[0];
context.Request.Headers["Cookie"] = GetCookieWithAffinity(affinitizedDestination);
var cluster = new ClusterState("cluster");
var affinityResult = policy.FindAffinitizedDestinations(context, cluster, _config, _destinations);
Assert.Equal(AffinityStatus.OK, affinityResult.Status);
policy.AffinitizeResponse(context, cluster, _config, affinitizedDestination);
Assert.False(context.Response.Headers.ContainsKey("Cookie"));
}
private string[] GetCookieWithAffinity(DestinationState affinitizedDestination)
{
return new[] { $"Some-Cookie=ZZZ", $"{_config.AffinityKeyName}={affinitizedDestination.DestinationId.ToUTF8BytesInBase64()}" };
}
}
}
| 43.572519 | 178 | 0.656797 | [
"MIT"
] | BennyM/reverse-proxy | test/ReverseProxy.Tests/SessionAffinity/CookieSessionAffinityPolicyTests.cs | 5,708 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.RelatedAssemblyAttribute("BlazorApp.Pwa.Server.Views")]
// Generated by the MSBuild WriteCodeFragment class.
| 33.388889 | 108 | 0.539101 | [
"MIT"
] | firemanwayne/Blazor.Pwa | BlazorApp/Server/obj/Debug/net5.0/BlazorApp.Pwa.Server.RazorAssemblyInfo.cs | 601 | C# |
using System.Collections.Generic;
using ChartJS.NET.Infrastructure;
namespace ChartJS.NET.Charts.Doughnut
{
public class DoughnutChart : BaseChart<List<DoughnutChartData>, DoughnutChartOptions>
{
private readonly DoughnutChartOptions _chartOptions = new DoughnutChartOptions();
public override Enums.ChartTypes ChartType
{
get { return Enums.ChartTypes.Doughnut; }
}
public override DoughnutChartOptions ChartConfig
{
get { return _chartOptions; }
}
}
} | 27.45 | 89 | 0.679417 | [
"MIT"
] | nikspatel007/ChartJS.NET | ChartJS.NET/Charts/Doughnut/DoughnutChart.cs | 551 | C# |
using OnlineServices.Common.DataAccessHelpers;
using OnlineServices.Common.TranslationServices.TransfertObjects;
namespace OnlineServices.Common.FacilityServices.TransfertObjects
{
public class IssueTO : IEntity<int>
{
public int Id { get; set; }
public string Description { get; set; }
public MultiLanguageString Name { get; set; }
public bool Archived { get; set; }
public ComponentTypeTO ComponentType { get; set; }
}
}
| 31.8 | 65 | 0.704403 | [
"Apache-2.0"
] | EnriqueUbillus/OnlineServices | Cross-Cutting/OnlineServices.Common/FacilityServices/TransfertObjects/IssueTO.cs | 479 | C# |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
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.
*********************************************************************/
#region license
/*
DirectShowLib - Provide access to DirectShow interfaces via .NET
Copyright (C) 2006
http://sourceforge.net/projects/directshownet/
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#endregion
using System;
using System.Drawing;
using System.Runtime.InteropServices;
#if !USING_NET11
using System.Runtime.InteropServices.ComTypes;
#endif
namespace DirectShowLib.MultimediaStreaming
{
#region Declarations
/// <summary>
/// From unnamed enum
/// </summary>
[Flags]
public enum AMMStream
{
None = 0x0,
AddDefaultRenderer = 0x1,
CreatePeer = 0x2,
StopIfNoSamples = 0x4,
NoStall = 0x8
}
/// <summary>
/// From unnamed enum
/// </summary>
[Flags]
public enum AMMMultiStream
{
None = 0x0,
NoGraphThread = 0x1
}
/// <summary>
/// From unnamed enum
/// </summary>
[Flags]
public enum AMOpenModes
{
RenderTypeMask = 0x3,
RenderToExisting = 0,
RenderAllStreams = 0x1,
NoRender = 0x2,
NoClock = 0x4,
Run = 0x8
}
#endregion
#region Interfaces
[ComImport,
Guid("BEBE595D-9A6F-11D0-8FDE-00C04FD9189D"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAMMediaStream : IMediaStream
{
#region IMediaStream Methods
[PreserveSig]
new int GetMultiMediaStream(
[MarshalAs(UnmanagedType.Interface)] out IMultiMediaStream ppMultiMediaStream
);
[PreserveSig]
new int GetInformation(
out Guid pPurposeId,
out StreamType pType
);
[PreserveSig]
new int SetSameFormat(
[In, MarshalAs(UnmanagedType.Interface)] IMediaStream pStreamThatHasDesiredFormat,
[In] int dwFlags
);
[PreserveSig]
new int AllocateSample(
[In] int dwFlags,
[MarshalAs(UnmanagedType.Interface)] out IStreamSample ppSample
);
[PreserveSig]
new int CreateSharedSample(
[In, MarshalAs(UnmanagedType.Interface)] IStreamSample pExistingSample,
[In] int dwFlags,
[MarshalAs(UnmanagedType.Interface)] out IStreamSample ppNewSample
);
[PreserveSig]
new int SendEndOfStream(
int dwFlags
);
#endregion
[PreserveSig]
int Initialize(
[In, MarshalAs(UnmanagedType.IUnknown)] object pSourceObject,
[In] AMMStream dwFlags,
[In, MarshalAs(UnmanagedType.LPStruct)] Guid PurposeId,
[In] StreamType StreamType
);
[PreserveSig]
int SetState(
[In] FilterState State
);
[PreserveSig]
int JoinAMMultiMediaStream(
[In, MarshalAs(UnmanagedType.Interface)] IAMMultiMediaStream pAMMultiMediaStream
);
[PreserveSig]
int JoinFilter(
[In, MarshalAs(UnmanagedType.Interface)] IMediaStreamFilter pMediaStreamFilter
);
[PreserveSig]
int JoinFilterGraph(
[In, MarshalAs(UnmanagedType.Interface)] IFilterGraph pFilterGraph
);
}
[ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("BEBE595C-9A6F-11D0-8FDE-00C04FD9189D")]
public interface IAMMultiMediaStream : IMultiMediaStream
{
#region IMultiMediaStream Methods
[PreserveSig]
new int GetInformation(
out MMSSF pdwFlags,
out StreamType pStreamType
);
[PreserveSig]
new int GetMediaStream(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid idPurpose,
[MarshalAs(UnmanagedType.Interface)] out IMediaStream ppMediaStream
);
[PreserveSig]
new int EnumMediaStreams(
[In] int Index,
[MarshalAs(UnmanagedType.Interface)] out IMediaStream ppMediaStream
);
[PreserveSig]
new int GetState(
out StreamState pCurrentState
);
[PreserveSig]
new int SetState(
[In] StreamState NewState
);
[PreserveSig]
new int GetTime(
out long pCurrentTime
);
[PreserveSig]
new int GetDuration(
out long pDuration
);
[PreserveSig]
new int Seek(
[In] long SeekTime
);
[PreserveSig]
new int GetEndOfStreamEventHandle(
out IntPtr phEOS
);
#endregion
[PreserveSig]
int Initialize(
[In] StreamType StreamType,
[In] AMMMultiStream dwFlags,
[In, MarshalAs(UnmanagedType.Interface)] IGraphBuilder pFilterGraph
);
[PreserveSig]
int GetFilterGraph(
[MarshalAs(UnmanagedType.Interface)] out IGraphBuilder ppGraphBuilder
);
[PreserveSig]
int GetFilter(
[MarshalAs(UnmanagedType.Interface)] out IMediaStreamFilter ppFilter
);
[PreserveSig]
int AddMediaStream(
[In, MarshalAs(UnmanagedType.IUnknown)] object pStreamObject,
[In] DsGuid PurposeId,
[In] AMMStream dwFlags,
[Out] IMediaStream ppNewStream
);
[PreserveSig]
int OpenFile(
[In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName,
[In] AMOpenModes dwFlags
);
[PreserveSig]
int OpenMoniker(
#if USING_NET11
[In, MarshalAs(UnmanagedType.Interface)] UCOMIBindCtx pCtx,
[In, MarshalAs(UnmanagedType.Interface)] UCOMIMoniker pMoniker,
#else
[In, MarshalAs(UnmanagedType.Interface)] IBindCtx pCtx,
[In, MarshalAs(UnmanagedType.Interface)] IMoniker pMoniker,
#endif
[In] AMOpenModes dwFlags
);
[PreserveSig]
int Render(
[In] AMOpenModes dwFlags
);
}
[ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("AB6B4AFA-F6E4-11D0-900D-00C04FD9189D")]
public interface IAMMediaTypeStream : IMediaStream
{
#region IMediaStream Methods
[PreserveSig]
new int GetMultiMediaStream(
[MarshalAs(UnmanagedType.Interface)] out IMultiMediaStream ppMultiMediaStream
);
[PreserveSig]
new int GetInformation(
out Guid pPurposeId,
out StreamType pType
);
[PreserveSig]
new int SetSameFormat(
[In, MarshalAs(UnmanagedType.Interface)] IMediaStream pStreamThatHasDesiredFormat,
[In] int dwFlags
);
[PreserveSig]
new int AllocateSample(
[In] int dwFlags,
[MarshalAs(UnmanagedType.Interface)] out IStreamSample ppSample
);
[PreserveSig]
new int CreateSharedSample(
[In, MarshalAs(UnmanagedType.Interface)] IStreamSample pExistingSample,
[In] int dwFlags,
[MarshalAs(UnmanagedType.Interface)] out IStreamSample ppNewSample
);
[PreserveSig]
new int SendEndOfStream(
int dwFlags
);
#endregion
[PreserveSig]
int GetFormat(
[Out, MarshalAs(UnmanagedType.LPStruct)] AMMediaType pMediaType,
[In] int dwFlags
);
[PreserveSig]
int SetFormat(
[In, MarshalAs(UnmanagedType.LPStruct)] AMMediaType pMediaType,
[In] int dwFlags
);
[PreserveSig]
int CreateSample(
[In] int lSampleSize,
[In] IntPtr pbBuffer,
[In] int dwFlags,
[In, MarshalAs(UnmanagedType.IUnknown)] object pUnkOuter,
[MarshalAs(UnmanagedType.Interface)] out IAMMediaTypeSample ppAMMediaTypeSample
);
[PreserveSig]
int GetStreamAllocatorRequirements(
out AllocatorProperties pProps
);
[PreserveSig]
int SetStreamAllocatorRequirements(
[In, MarshalAs(UnmanagedType.LPStruct)] AllocatorProperties pProps
);
}
[ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("AB6B4AFB-F6E4-11D0-900D-00C04FD9189D")]
public interface IAMMediaTypeSample : IStreamSample
{
#region IStreamSample Methods
[PreserveSig]
new int GetMediaStream(
[MarshalAs(UnmanagedType.Interface)] out IMediaStream ppMediaStream
);
[PreserveSig]
new int GetSampleTimes(
out long pStartTime,
out long pEndTime,
out long pCurrentTime
);
[PreserveSig]
new int SetSampleTimes(
[In] DsLong pStartTime,
[In] DsLong pEndTime
);
[PreserveSig]
new int Update(
[In] SSUpdate dwFlags,
[In] IntPtr hEvent,
[In] IntPtr pfnAPC,
[In] IntPtr dwAPCData
);
[PreserveSig]
new int CompletionStatus(
[In] CompletionStatusFlags dwFlags,
[In] int dwMilliseconds
);
#endregion
[PreserveSig]
int SetPointer(
[In] IntPtr pBuffer,
[In] int lSize
);
[PreserveSig]
int GetPointer(
[Out] out IntPtr ppBuffer
);
[PreserveSig]
int GetSize();
[PreserveSig]
int GetTime(
out long pTimeStart,
out long pTimeEnd
);
[PreserveSig]
int SetTime(
[In] DsLong pTimeStart,
[In] DsLong pTimeEnd
);
[PreserveSig]
int IsSyncPoint();
[PreserveSig]
int SetSyncPoint(
[In, MarshalAs(UnmanagedType.Bool)] bool IsSyncPoint
);
[PreserveSig]
int IsPreroll();
[PreserveSig]
int SetPreroll(
[In, MarshalAs(UnmanagedType.Bool)] bool IsPreroll
);
[PreserveSig]
int GetActualDataLength();
[PreserveSig]
int SetActualDataLength(
int Size
);
[PreserveSig]
int GetMediaType(
out AMMediaType ppMediaType
);
[PreserveSig]
int SetMediaType(
[In, MarshalAs(UnmanagedType.LPStruct)] AMMediaType pMediaType
);
[PreserveSig]
int IsDiscontinuity();
[PreserveSig]
int SetDiscontinuity(
[In, MarshalAs(UnmanagedType.Bool)] bool Discontinuity
);
[PreserveSig]
int GetMediaTime(
out long pTimeStart,
out long pTimeEnd
);
[PreserveSig]
int SetMediaTime(
[In] DsLong pTimeStart,
[In] DsLong pTimeEnd
);
}
[ComImport,
Guid("BEBE595E-9A6F-11D0-8FDE-00C04FD9189D"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMediaStreamFilter : IBaseFilter
{
#region IPersist Methods
[PreserveSig]
new int GetClassID(
out Guid pClassID
);
#endregion
#region IMediaFilter Methods
[PreserveSig]
new int Stop();
[PreserveSig]
new int Pause();
[PreserveSig]
new int Run(
[In] long tStart
);
[PreserveSig]
new int GetState(
[In] int dwMilliSecsTimeout,
out FilterState State
);
[PreserveSig]
new int SetSyncSource(
[In, MarshalAs(UnmanagedType.Interface)] IReferenceClock pClock
);
[PreserveSig]
new int GetSyncSource(
[MarshalAs(UnmanagedType.Interface)] out IReferenceClock pClock
);
#endregion
#region IBaseFilter Methods
[PreserveSig]
new int EnumPins(
[MarshalAs(UnmanagedType.Interface)] out IEnumPins ppEnum
);
[PreserveSig]
new int FindPin(
[In, MarshalAs(UnmanagedType.LPWStr)] string Id,
[MarshalAs(UnmanagedType.Interface)] out IPin ppPin
);
[PreserveSig]
new int QueryFilterInfo(
out FilterInfo pInfo
);
[PreserveSig]
new int JoinFilterGraph(
[In, MarshalAs(UnmanagedType.Interface)] IFilterGraph pGraph,
[In, MarshalAs(UnmanagedType.LPWStr)] string pName
);
[PreserveSig]
new int QueryVendorInfo(
[MarshalAs(UnmanagedType.LPWStr)] out string pVendorInfo
);
#endregion
[PreserveSig]
int AddMediaStream(
[In, MarshalAs(UnmanagedType.Interface)] IAMMediaStream pAMMediaStream
);
[PreserveSig]
int GetMediaStream(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid idPurpose,
[MarshalAs(UnmanagedType.Interface)] out IMediaStream ppMediaStream
);
[PreserveSig]
int EnumMediaStreams(
[In] int Index,
[MarshalAs(UnmanagedType.Interface)] out IMediaStream ppMediaStream
);
[PreserveSig]
int SupportSeeking(
[In, MarshalAs(UnmanagedType.Bool)] bool bRenderer
);
[PreserveSig]
int ReferenceTimeToStreamTime(
[In, Out] ref long pTime
);
[PreserveSig]
int GetCurrentStreamTime(
out long pCurrentStreamTime
);
[PreserveSig]
int WaitUntil(
[In] long WaitStreamTime
);
[PreserveSig]
int Flush(
[In, MarshalAs(UnmanagedType.Bool)] bool bCancelEOS
);
[PreserveSig]
int EndOfStream();
}
#endregion
}
| 26.497529 | 94 | 0.581945 | [
"MIT"
] | AustralianDisabilityLimited/MultiversePlatform | client/Movie/Codecs/DirectShowLib/amstream.cs | 16,084 | C# |
using System;
using System.Xml.Serialization;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using JdSdk.Domain.Website.Order;
namespace JdSdk.Domain.Website.Response
{
[Serializable]
public class OrderCanBuyCityResponse : JdResponse
{
[JsonProperty("canbuyaddresses")]
public List<CanBuyAddress> CanBuyAddresses
{
get;
set;
}
}
}
| 19.347826 | 53 | 0.669663 | [
"Apache-2.0"
] | starpeng/JdSdk2 | Source/JdSdk/domain/website/response/OrderCanBuyCityResponse.cs | 451 | C# |
namespace HREngine.Bots
{
class Pen_EX1_009 : PenTemplate //angrychicken
{
// wutanfall:/ +5 angriff.
public override int getPlayPenalty(Playfield p, Minion m, Minion target, int choice, bool isLethal)
{
return 0;
}
}
} | 24.545455 | 107 | 0.611111 | [
"MIT"
] | chi-rei-den/Silverfish | penalties/Pen_EX1_009.cs | 270 | C# |
using DevCars.API.Persistence;
using DevCars.Domain.Repositories;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Threading;
using System.Threading.Tasks;
namespace DevCars.Application.Commands.DeleteCar
{
public class DeleteCarCommandHandler : IRequestHandler<DeleteCarCommand, Unit>
{
private readonly DevCarsDbContext _dbContext;
private ICarRepository _carRepository;
public DeleteCarCommandHandler(DevCarsDbContext dbContext, ICarRepository carRepository)
{
_dbContext = dbContext;
_carRepository = carRepository;
}
public async Task<Unit> Handle(DeleteCarCommand request, CancellationToken cancellationToken)
{
var car = await _dbContext.Cars.SingleOrDefaultAsync(c => c.Id == request.id);
car.SetAsSuspended();
await _carRepository.SaveChangesAsync();
return Unit.Value;
}
}
}
| 28.969697 | 101 | 0.699791 | [
"MIT"
] | VictorMello1993/DevCars | DevCars.API/DevCars.Application/Commands/DeleteCar/DeleteCarCommandHandler.cs | 958 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Core;
using Azure.ResourceManager.Network.Models;
using Azure.ResourceManager.Resources.Models;
namespace Azure.ResourceManager.Network
{
/// <summary> A Class representing a VirtualNetworkGatewayNatRule along with the instance operations that can be performed on it. </summary>
public partial class VirtualNetworkGatewayNatRule : ArmResource
{
private readonly ClientDiagnostics _clientDiagnostics;
private readonly VirtualNetworkGatewayNatRulesRestOperations _virtualNetworkGatewayNatRulesRestClient;
private readonly VirtualNetworkGatewayNatRuleData _data;
/// <summary> Initializes a new instance of the <see cref="VirtualNetworkGatewayNatRule"/> class for mocking. </summary>
protected VirtualNetworkGatewayNatRule()
{
}
/// <summary> Initializes a new instance of the <see cref = "VirtualNetworkGatewayNatRule"/> class. </summary>
/// <param name="options"> The client parameters to use in these operations. </param>
/// <param name="resource"> The resource that is the target of operations. </param>
internal VirtualNetworkGatewayNatRule(ArmResource options, VirtualNetworkGatewayNatRuleData resource) : base(options, new ResourceIdentifier(resource.Id))
{
HasData = true;
_data = resource;
_clientDiagnostics = new ClientDiagnostics(ClientOptions);
_virtualNetworkGatewayNatRulesRestClient = new VirtualNetworkGatewayNatRulesRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri);
}
/// <summary> Initializes a new instance of the <see cref="VirtualNetworkGatewayNatRule"/> class. </summary>
/// <param name="options"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal VirtualNetworkGatewayNatRule(ArmResource options, ResourceIdentifier id) : base(options, id)
{
_clientDiagnostics = new ClientDiagnostics(ClientOptions);
_virtualNetworkGatewayNatRulesRestClient = new VirtualNetworkGatewayNatRulesRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri);
}
/// <summary> Initializes a new instance of the <see cref="VirtualNetworkGatewayNatRule"/> class. </summary>
/// <param name="clientOptions"> The client options to build client context. </param>
/// <param name="credential"> The credential to build client context. </param>
/// <param name="uri"> The uri to build client context. </param>
/// <param name="pipeline"> The pipeline to build client context. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal VirtualNetworkGatewayNatRule(ArmClientOptions clientOptions, TokenCredential credential, Uri uri, HttpPipeline pipeline, ResourceIdentifier id) : base(clientOptions, credential, uri, pipeline, id)
{
_clientDiagnostics = new ClientDiagnostics(ClientOptions);
_virtualNetworkGatewayNatRulesRestClient = new VirtualNetworkGatewayNatRulesRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri);
}
/// <summary> Gets the resource type for the operations. </summary>
public static readonly ResourceType ResourceType = "Microsoft.Network/virtualNetworkGateways/natRules";
/// <summary> Gets the valid resource type for the operations. </summary>
protected override ResourceType ValidResourceType => ResourceType;
/// <summary> Gets whether or not the current instance has data. </summary>
public virtual bool HasData { get; }
/// <summary> Gets the data representing this Feature. </summary>
/// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
public virtual VirtualNetworkGatewayNatRuleData Data
{
get
{
if (!HasData)
throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
return _data;
}
}
/// <summary> Retrieves the details of a nat rule. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async virtual Task<Response<VirtualNetworkGatewayNatRule>> GetAsync(CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("VirtualNetworkGatewayNatRule.Get");
scope.Start();
try
{
var response = await _virtualNetworkGatewayNatRulesRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false);
return Response.FromValue(new VirtualNetworkGatewayNatRule(this, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Retrieves the details of a nat rule. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<VirtualNetworkGatewayNatRule> Get(CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("VirtualNetworkGatewayNatRule.Get");
scope.Start();
try
{
var response = _virtualNetworkGatewayNatRulesRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
if (response.Value == null)
throw _clientDiagnostics.CreateRequestFailedException(response.GetRawResponse());
return Response.FromValue(new VirtualNetworkGatewayNatRule(this, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Lists all available geo-locations. </summary>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> A collection of locations that may take multiple service requests to iterate over. </returns>
public async virtual Task<IEnumerable<Location>> GetAvailableLocationsAsync(CancellationToken cancellationToken = default)
{
return await ListAvailableLocationsAsync(ResourceType, cancellationToken).ConfigureAwait(false);
}
/// <summary> Lists all available geo-locations. </summary>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> A collection of locations that may take multiple service requests to iterate over. </returns>
public virtual IEnumerable<Location> GetAvailableLocations(CancellationToken cancellationToken = default)
{
return ListAvailableLocations(ResourceType, cancellationToken);
}
/// <summary> Deletes a nat rule. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async virtual Task<VirtualNetworkGatewayNatRuleDeleteOperation> DeleteAsync(bool waitForCompletion = true, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("VirtualNetworkGatewayNatRule.Delete");
scope.Start();
try
{
var response = await _virtualNetworkGatewayNatRulesRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
var operation = new VirtualNetworkGatewayNatRuleDeleteOperation(_clientDiagnostics, Pipeline, _virtualNetworkGatewayNatRulesRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name).Request, response);
if (waitForCompletion)
await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Deletes a nat rule. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual VirtualNetworkGatewayNatRuleDeleteOperation Delete(bool waitForCompletion = true, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("VirtualNetworkGatewayNatRule.Delete");
scope.Start();
try
{
var response = _virtualNetworkGatewayNatRulesRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
var operation = new VirtualNetworkGatewayNatRuleDeleteOperation(_clientDiagnostics, Pipeline, _virtualNetworkGatewayNatRulesRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name).Request, response);
if (waitForCompletion)
operation.WaitForCompletion(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| 56.138298 | 256 | 0.680121 | [
"MIT"
] | RecencyBias/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/VirtualNetworkGatewayNatRule.cs | 10,554 | C# |
// Copyright (c) Dominic Schira <domshyra@gmail.com>. All Rights Reserved.
using ExcelExtensions.Interfaces;
using ExcelExtensions.Interfaces.Export;
using ExcelExtensions.Models;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using static ExcelExtensions.Enums.Enums;
namespace ExcelExtensions.Providers.Export
{
public class Exporter : IExporter
{
private readonly IExtensions _excelProvider;
public Exporter(IExtensions excelProvider)
{
_excelProvider = excelProvider;
}
/// <inheritdoc/>
public void ExportTable<T>(ref ExcelWorksheet sheet, List<T> rows, List<Column> columnDefinitions, Style style, int headerRow = 1)
{
ExportColumns(ref sheet, rows, columnDefinitions, headerRow);
StyleTableHeaderRow(columnDefinitions, ref sheet, style, headerRow);
}
/// <inheritdoc/>
public void ExportColumns<T>(ref ExcelWorksheet sheet, List<T> rows, List<Column> columns, int headerRow = 1, string displayNameAdditionalText = null)
{
Type exportModelType = rows.GetType().GetGenericArguments().Single();
foreach (Column column in columns)
{
int rowNumber = headerRow;
rowNumber = SetTableHeaderRowNumber(sheet, displayNameAdditionalText, column, rowNumber);
foreach (var row in rows)
{
try
{
PropertyInfo propertyInfo = exportModelType.GetProperty(column.ModelProperty);
try
{
object value = propertyInfo.GetValue(row);
sheet.Cells[rowNumber++, _excelProvider.GetColumnNumber(column.ColumnLetter)].Value = value;
}
catch (NullReferenceException e)
{
//propertyInfo info is null
throw new NullReferenceException($"column.ModelProperty: [{column.ModelProperty}] failed to get propertyInfo. " +
$"Invalid object being cast. Type for {column.ModelProperty} is ${propertyInfo.PropertyType}", e);
}
}
catch (ArgumentNullException e)
{
//It is a null cell, leave it blank
Debug.WriteLine(e.Message);
}
}
FormatColumn(column, ref sheet);
}
}
/// <summary>
/// Sets the row number of the table once we find where all the header tiles are located
/// </summary>
/// <param name="sheet"></param>
/// <param name="displayNameAdditionalText"></param>
/// <param name="column"></param>
/// <param name="row"></param>
/// <returns></returns>
private int SetTableHeaderRowNumber(ExcelWorksheet sheet, string displayNameAdditionalText, Column column, int row)
{
if (string.IsNullOrEmpty(displayNameAdditionalText))
{
sheet.Cells[row++, _excelProvider.GetColumnNumber(column.ColumnLetter)].Value = column.HeaderTitle;
}
else
{
sheet.Cells[row++, _excelProvider.GetColumnNumber(column.ColumnLetter)].Value = $"{column.HeaderTitle} {displayNameAdditionalText}"; ;
}
return row;
}
/// <inheritdoc/>
public void FormatColumn(Column column, ref ExcelWorksheet sheet)
{
FormatColumn(ref sheet, column.ColumnLetter, column.Format, column.DecimalPrecision);
}
/// <inheritdoc/>
public void FormatColumn(ref ExcelWorksheet sheet, string column, FormatType formatter, int? decimalPrecision = null)
{
//Styling
if (formatter == FormatType.String)
{
sheet.Column(_excelProvider.GetColumnNumber(column)).Width = 21;
}
else if (formatter == FormatType.Currency)
{
if (decimalPrecision != null)
{
string formatString = "$#,##0";
formatString = _excelProvider.AddDecimalPlacesToFormat(decimalPrecision, formatString);
sheet.Column(_excelProvider.GetColumnNumber(column)).Style.Numberformat.Format = formatString;
}
else
{
sheet.Column(_excelProvider.GetColumnNumber(column)).Style.Numberformat.Format = "$#,##0.00";
}
sheet.Column(_excelProvider.GetColumnNumber(column)).Width = 17;
}
else if (formatter == FormatType.Date)
{
if (DateTimeFormatInfo.CurrentInfo != null)
{
sheet.Column(_excelProvider.GetColumnNumber(column)).Style.Numberformat.Format = DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
}
sheet.Column(_excelProvider.GetColumnNumber(column)).Width = 15;
}
else if (formatter == FormatType.Duration)
{
sheet.Column(_excelProvider.GetColumnNumber(column)).Style.Numberformat.Format = "[h]:mm:ss";
sheet.Column(_excelProvider.GetColumnNumber(column)).Width = 15;
}
else if (formatter == FormatType.Decimal)
{
if (decimalPrecision != null)
{
string formatString = "#,##0";
formatString = _excelProvider.AddDecimalPlacesToFormat(decimalPrecision, formatString);
sheet.Column(_excelProvider.GetColumnNumber(column)).Style.Numberformat.Format = formatString;
}
else
{
sheet.Column(_excelProvider.GetColumnNumber(column)).Style.Numberformat.Format = "#,##0.0000";
}
sheet.Column(_excelProvider.GetColumnNumber(column)).Width = 15;
}
else if (formatter == FormatType.Int)
{
sheet.Column(_excelProvider.GetColumnNumber(column)).Style.Numberformat.Format = "0";
sheet.Column(_excelProvider.GetColumnNumber(column)).Width = 13;
}
else if (formatter == FormatType.Percent)
{
if (decimalPrecision != null)
{
string formatString = "0";
formatString = _excelProvider.AddDecimalPlacesToFormat(decimalPrecision, formatString);
sheet.Column(_excelProvider.GetColumnNumber(column)).Style.Numberformat.Format = formatString += "%";
}
else
{
sheet.Column(_excelProvider.GetColumnNumber(column)).Style.Numberformat.Format = "0%";
}
sheet.Column(_excelProvider.GetColumnNumber(column)).Width = 13;
}
}
/// <inheritdoc/>
public void FormatColumnRange(ExcelWorksheet itemcodeSheet, string startColumn, string endColumn, FormatType format, int? decimalPrecision = null)
{
if (_excelProvider.GetColumnNumber(startColumn) > _excelProvider.GetColumnNumber(endColumn))
{
throw new ArgumentOutOfRangeException(nameof(startColumn), $"{nameof(startColumn)} must be less than {nameof(endColumn)}");
}
string currenctColumn = startColumn;
do
{
FormatColumn(ref itemcodeSheet, currenctColumn, format, decimalPrecision);
//if there is only one col, finish after the styling
if (startColumn == endColumn)
{
break;
}
currenctColumn = _excelProvider.GetColumnLetter(_excelProvider.GetColumnNumber(currenctColumn) + 1);
}
while (currenctColumn != endColumn);
}
/// <inheritdoc/>
public void StyleTableHeaderRow(List<Column> columns, ref ExcelWorksheet sheet, Style style, int? startrow = null)
{
int maxColumn = _excelProvider.FindMaxColumn(columns);
int row = startrow ?? 1;
sheet.Cells[row, 1, row, maxColumn].Style.Font.Bold = style.Bold;
sheet.Cells[row, 1, row, maxColumn].Style.Fill.PatternType = style.PatternType;
sheet.Cells[row, 1, row, maxColumn].Style.Fill.BackgroundColor.SetColor(style.BackgroundColor);
sheet.Cells[row, 1, row, maxColumn].Style.Font.Color.SetColor(style.Color);
}
}
}
| 43.563725 | 158 | 0.568246 | [
"MIT"
] | domshyra/ExcelExtensions | ExcelExtensions/Providers/Export/Exporter.cs | 8,889 | C# |
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using Bookify.API.Attributes;
using Bookify.Common.Commands.Auth;
using Bookify.Common.Filter;
using Bookify.Common.Models;
using Bookify.Common.Repositories;
namespace Bookify.API.Controllers
{
/// <summary>
///
/// </summary>
/// <seealso cref="Bookify.API.Controllers.BaseApiController" />
[RoutePrefix("feedbacks")]
public class BookFeedbackController : BaseApiController
{
private readonly IBookFeedbackRepository _bookFeedbackRepository;
private readonly IAuthenticationRepository _authRepository;
/// <summary>
/// Initializes a new instance of the <see cref="BookFeedbackController"/> class.
/// </summary>
/// <param name="bookFeedbackRepository">The book feedback repository.</param>
/// <param name="authRepository">The authentication repo.</param>
public BookFeedbackController(IBookFeedbackRepository bookFeedbackRepository, IAuthenticationRepository authRepository)
{
this._bookFeedbackRepository = bookFeedbackRepository;
this._authRepository = authRepository;
}
/// <summary>
/// Gets bookfeedbacks from the specified filter.
/// </summary>
/// <param name="filter">The filter.</param>
/// <response code="200" cref="Get">OK</response>
/// <response code="500">Internal Server Error</response>
/// <returns></returns>
[HttpGet]
[Route("")]
[ResponseType(typeof(IPaginatedEnumerable<BookFeedbackDto>))]
public async Task<IHttpActionResult> Get([FromUri]FeedbackFilter filter = null)
{
filter = filter ?? new FeedbackFilter();
return await this.Try(() => this._bookFeedbackRepository.GetByFilter(filter));
}
/// <summary>
/// Creates the bookfeedback for specified book identifier and command.
/// </summary>
/// <param name="id">The book identifier.</param>
/// <param name="command">The command.</param>
/// <response code="201" cref="Create">OK</response>
/// <response code="500">Internal Server Error</response>
/// <returns></returns>
[HttpPost]
[Auth]
[Route("{id}")]
[ResponseType(typeof(BookFeedbackDto))]
public async Task<IHttpActionResult> Create(int id, CreateFeedbackCommand command)
{
var personAuthDto = await this.GetAuthorizedMember(this._authRepository);
return await this.TryCreate(() => this._bookFeedbackRepository.CreateFeedback(id, personAuthDto.PersonDto.Id, command));
}
/// <summary>
/// Updates bookFeedBack from specified book identifier and command.
/// </summary>
/// <param name="id">The book identifier.</param>
/// <param name="command">The command.</param>
/// <response code="200" cref="Update">OK</response>
/// <response code="500">Internal Server Error</response>
/// <returns></returns>
[HttpPatch]
[Auth]
[Route("{id}")]
[ResponseType(typeof(BookFeedbackDto))]
public async Task<IHttpActionResult> Update(int id, EditFeedbackCommand command)
{
var personAuthDto = await this.GetAuthorizedMember(this._authRepository);
return await this.Try(() => this._bookFeedbackRepository.EditFeedback(id, personAuthDto.PersonDto.Id, command));
}
/// <summary>
/// Deletes the bookFeedback specified by book identifier and the current users identifier.
/// </summary>
/// <param name="id">The book identifier.</param>
/// <response code="200">OK</response>
/// <response code="500">Internal Server Error</response>
/// <returns></returns>
[HttpDelete]
[Auth]
[Route("{id}")]
public async Task<IHttpActionResult> Delete(int id)
{
var personAuthDto = await this.GetAuthorizedMember(this._authRepository);
return await this.Try(() => this._bookFeedbackRepository.DeleteFeedback(id, personAuthDto.PersonDto.Id));
}
}
}
| 41.490196 | 132 | 0.633743 | [
"MIT"
] | Falgantil/Bookify | Bookify/Bookify.API/Controllers/BookFeedbackController.cs | 4,234 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Examples.MediaApi.Domain.Tests
{
public class MediaRepositoryTests
{
[Fact]
public async Task GetAlbums_MapsData()
{
var handler = new MockHttpMessageHandler();
handler.AddMockJsonResponse("/albums", MockJsonData.Albums());
ICollection<Album> albums;
using (var httpClient = new HttpClient(handler))
{
var mediaRepository = new MediaRepository(httpClient);
albums = await mediaRepository.GetAlbumsAsync();
}
Assert.NotEmpty(albums);
var lastItem = albums.Last();
Assert.Equal(100, lastItem.Id);
Assert.Equal("enim repellat iste", lastItem.Title);
Assert.Equal(10, lastItem.UserId);
Assert.Null(lastItem.Photos);
}
[Fact]
public async Task GetPhotos_MapsData()
{
var handler = new MockHttpMessageHandler();
handler.AddMockJsonResponse("/photos", MockJsonData.Photos());
ICollection<Photo> photos;
using (var httpClient = new HttpClient(handler))
{
var mediaRepository = new MediaRepository(httpClient);
photos = await mediaRepository.GetPhotosAsync();
}
Assert.NotEmpty(photos);
var lastItem = photos.Last();
Assert.Equal(5000, lastItem.Id);
Assert.Equal("error quasi sunt cupiditate voluptate ea odit beatae", lastItem.Title);
Assert.Equal(new Uri("https://via.placeholder.com/600/6dd9cb"), lastItem.Url);
Assert.Equal(new Uri("https://via.placeholder.com/150/6dd9cb"), lastItem.ThumbnailUrl);
Assert.Equal(100, lastItem.AlbumId);
}
}
}
| 33.016949 | 99 | 0.602156 | [
"MIT"
] | HeyJoel/Examples.MediaApi | Examples.MediaApi.Domain.Tests/MediaRepositoryTests.cs | 1,950 | C# |
using System;
namespace AIR.SDK.Workflow.Tests.Data
{
[Serializable]
public class TInput
{
public string Value { get; set; }
}
[Serializable]
public class TOutput
{
public string Value { get; set; }
}
[Serializable]
public class TActivityInput
{
public string Value { get; set; }
}
[Serializable]
public class TActivityOutput
{
public string Value { get; set; }
}
}
| 13.62069 | 37 | 0.681013 | [
"Apache-2.0"
] | Bassist067/AIR.SDK | AIR.SDK.Workflow.Tests/Data/GlobalSampleObjects.cs | 397 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("YellowPages.Entities")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("YellowPages.Entities")]
[assembly: AssemblyCopyright("Copyright © Microsoft 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("6e4ada78-8985-4601-8021-9b538bead2ac")]
// 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")] | 39.742857 | 84 | 0.746945 | [
"MIT"
] | abusalehnayeem/YellowPages | YellowPages.Entities/Properties/AssemblyInfo.cs | 1,394 | C# |
using Ordering.Domain.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ordering.Domain.Entities
{
public class Order: EntityBase
{
public string UserName { get; set; }
public decimal TotalPrice { get; set; }
//Billing Address
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAdress { get; set; }
public string AddressLine { get; set; }
public string Country { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
//Payment
public string CardName { get; set; }
public string CardNumber { get; set; }
public string Expiration { get; set; }
public string CVV { get; set; }
public int PaymentMethod { get; set; }
}
}
| 18.333333 | 47 | 0.607487 | [
"MIT"
] | Azilen/gRPC-API-Performance-Improvement | src/Services/Ordering/Ordering.Domain/Entities/Order.cs | 937 | C# |
using UnityEngine;
public class ShapePattern : MonoBehaviour
{
public enum ShapeType
{
Sphere,
Cube
};
public enum Operation
{
None,
Blend,
Cut,
Mask
}
public ShapeType shapeType;
public Operation operation;
public Color colour = Color.white;
[Range(0,1)]
public float blendStrength;
[HideInInspector]
public int numChildren;
public Vector3 Position
{
get
{
return transform.position;
}
}
public Vector3 Scale
{
get
{
Vector3 parentScale = Vector3.one;
if (transform.parent != null && transform.parent.GetComponent<ShapePattern>() != null)
{
parentScale = transform.parent.GetComponent<ShapePattern>().Scale;
}
return Vector3.Scale(transform.localScale, parentScale);
}
}
}
| 19.612245 | 99 | 0.541103 | [
"MIT"
] | Sharanych/UnityShaders | Assets/Scripts/Raymarching/ComplexRaymarching/ShapePattern.cs | 961 | C# |
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Text;
namespace Backend.Services.Apis
{
public abstract class BaseController : ControllerBase
{
}
}
| 18.166667 | 58 | 0.720183 | [
"MIT"
] | mustaphakd/epidemie | src/backend/Backend.Services/Apis/BaseController.cs | 220 | 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("EveSSOAuthRouter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EveSSOAuthRouter")]
[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("8810fcdf-cd7d-449d-b474-71312095c2f3")]
// 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.972973 | 84 | 0.746619 | [
"MIT"
] | wanjizheng/ESISharp | EveSSOAuthRouter/Properties/AssemblyInfo.cs | 1,408 | C# |
using System;
public class InfinityHarvester : Harvester
{
private const int OreOutputDivider = 10;
private double durability;
public InfinityHarvester(int id, double oreOutput, double energyRequirement) : base(id, oreOutput, energyRequirement)
{
this.OreOutput /= OreOutputDivider;
}
public override double Durability
{
get => this.durability;
protected set => this.durability = Math.Max(0, value);
}
} | 24.421053 | 121 | 0.68319 | [
"MIT"
] | Shtereva/CSharp-OOP-Advanced | Exam Preparation II/BrokenSkeleton/Structure_Skeleton/Entities/Harvesters/InfinityHarvester.cs | 466 | C# |
/*
Haz un programa que calcule el resto de la división de 577 entre 13.
Haz la división a mano y comprueba el resultado.
*/
// Por Franco (...)
using System;
class Ejercicio4
{
static void Main()
{
int resultado;
resultado = 577 % 13;
Console.WriteLine(resultado);
}
}
| 14.947368 | 68 | 0.679577 | [
"MIT"
] | ncabanes/sv2021-programming | tema01-contactoConCSharp/004-Modulo.cs | 286 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Citrina
{
public class WallPostResponse
{
/// <summary>
/// Created post ID.
/// </summary>
public int? PostId { get; set; }
}
}
| 19.066667 | 42 | 0.573427 | [
"MIT"
] | khrabrovart/Citrina | src/Citrina/gen/Responses/Wall/WallPostResponse.cs | 286 | C# |
using System;
using System.ComponentModel;
using EfsTools.Attributes;
using EfsTools.Utils;
using Newtonsoft.Json;
namespace EfsTools.Items.Nv
{
[Serializable]
[NvItemId(5128)]
[Attributes(9)]
public class Bc0HdrP2RiseFallOff
{
[ElementsCount(16)]
[ElementType("uint8")]
[Description("")]
public byte[] Value { get; set; }
}
}
| 19.666667 | 42 | 0.600484 | [
"MIT"
] | HomerSp/EfsTools | EfsTools/Items/Nv/Bc0HdrP2RiseFallOffI.cs | 413 | C# |
using System.IO;
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class gameuiCharacterReplicaInitializedEvent : redEvent
{
public gameuiCharacterReplicaInitializedEvent(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| 23.4 | 125 | 0.754986 | [
"MIT"
] | Eingin/CP77Tools | CP77.CR2W/Types/cp77/gameuiCharacterReplicaInitializedEvent.cs | 337 | 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 lex-models-2017-04-19.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.LexModelBuildingService.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.LexModelBuildingService.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for GetUtterancesView operation
/// </summary>
public class GetUtterancesViewResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
GetUtterancesViewResponse response = new GetUtterancesViewResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("botName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.BotName = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("utterances", targetDepth))
{
var unmarshaller = new ListUnmarshaller<UtteranceList, UtteranceListUnmarshaller>(UtteranceListUnmarshaller.Instance);
response.Utterances = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("BadRequestException"))
{
return BadRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalFailureException"))
{
return InternalFailureExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("LimitExceededException"))
{
return LimitExceededExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonLexModelBuildingServiceException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static GetUtterancesViewResponseUnmarshaller _instance = new GetUtterancesViewResponseUnmarshaller();
internal static GetUtterancesViewResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static GetUtterancesViewResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 39.741935 | 206 | 0.643872 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/LexModelBuildingService/Generated/Model/Internal/MarshallTransformations/GetUtterancesViewResponseUnmarshaller.cs | 4,928 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace USFMToolsSharp.Models.Markers
{
/// <summary>
/// Parallel passage reference(s)
/// </summary>
public class RMarker : Marker
{
public override string Identifier => "r";
public override List<Type> AllowedContents => new List<Type>() {
typeof(TextBlock)
};
}
}
| 21.947368 | 73 | 0.594724 | [
"MIT"
] | BryanHo10/USFMToolsSharp | USFMToolsSharp/Models/Markers/RMarker.cs | 419 | C# |
using System;
using System.Collections.Generic;
using System.Data;
namespace Norm
{
public partial class Norm
{
public IAsyncEnumerable<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11)> ReadAsync<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(string command)
{
var t1 = TypeCache<T1>.GetMetadata();
var t2 = TypeCache<T2>.GetMetadata();
var t3 = TypeCache<T3>.GetMetadata();
var t4 = TypeCache<T4>.GetMetadata();
var t5 = TypeCache<T5>.GetMetadata();
var t6 = TypeCache<T6>.GetMetadata();
var t7 = TypeCache<T7>.GetMetadata();
var t8 = TypeCache<T8>.GetMetadata();
var t9 = TypeCache<T9>.GetMetadata();
var t10 = TypeCache<T10>.GetMetadata();
var t11 = TypeCache<T11>.GetMetadata();
if (t1.valueTuple && t2.valueTuple && t3.valueTuple && t4.valueTuple && t5.valueTuple && t6.valueTuple && t7.valueTuple && t8.valueTuple && t9.valueTuple && t10.valueTuple && t11.valueTuple)
{
return ReadAsync(command).MapValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(t1.type, t2.type, t3.type, t4.type, t5.type, t6.type, t7.type, t8.type, t9.type, t10.type, t11.type);
}
else if (!t1.simple && !t2.simple && !t3.simple && !t4.simple && !t5.simple && !t6.simple && !t7.simple && !t8.simple && !t9.simple && !t10.simple && !t11.simple)
{
return ReadAsync(command).Map<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(t1.type, t2.type, t3.type, t4.type, t5.type, t6.type, t7.type, t8.type, t9.type, t10.type, t11.type);
}
else if (t1.simple && t2.simple && t3.simple && t4.simple && t5.simple && t6.simple && t7.simple && t8.simple && t9.simple && t10.simple && t11.simple)
{
return ReadInternalAsync(command, async r => (
await r.GetFieldValueAsync<T1>(0, convertsDbNull),
await r.GetFieldValueAsync<T2>(1, convertsDbNull),
await r.GetFieldValueAsync<T3>(2, convertsDbNull),
await r.GetFieldValueAsync<T4>(3, convertsDbNull),
await r.GetFieldValueAsync<T5>(4, convertsDbNull),
await r.GetFieldValueAsync<T6>(5, convertsDbNull),
await r.GetFieldValueAsync<T7>(6, convertsDbNull),
await r.GetFieldValueAsync<T8>(7, convertsDbNull),
await r.GetFieldValueAsync<T9>(8, convertsDbNull),
await r.GetFieldValueAsync<T10>(9, convertsDbNull),
await r.GetFieldValueAsync<T11>(10, convertsDbNull)));
}
throw new NormMultipleMappingsException();
}
public IAsyncEnumerable<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11)> ReadFormatAsync<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(FormattableString command)
{
var t1 = TypeCache<T1>.GetMetadata();
var t2 = TypeCache<T2>.GetMetadata();
var t3 = TypeCache<T3>.GetMetadata();
var t4 = TypeCache<T4>.GetMetadata();
var t5 = TypeCache<T5>.GetMetadata();
var t6 = TypeCache<T6>.GetMetadata();
var t7 = TypeCache<T7>.GetMetadata();
var t8 = TypeCache<T8>.GetMetadata();
var t9 = TypeCache<T9>.GetMetadata();
var t10 = TypeCache<T10>.GetMetadata();
var t11 = TypeCache<T11>.GetMetadata();
if (t1.valueTuple && t2.valueTuple && t3.valueTuple && t4.valueTuple && t5.valueTuple && t6.valueTuple && t7.valueTuple && t8.valueTuple && t9.valueTuple && t10.valueTuple && t11.valueTuple)
{
return ReadFormatAsync(command).MapValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(t1.type, t2.type, t3.type, t4.type, t5.type, t6.type, t7.type, t8.type, t9.type, t10.type, t11.type);
}
else if (!t1.simple && !t2.simple && !t3.simple && !t4.simple && !t5.simple && !t6.simple && !t7.simple && !t8.simple && !t9.simple && !t10.simple && !t11.simple)
{
return ReadFormatAsync(command).Map<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(t1.type, t2.type, t3.type, t4.type, t5.type, t6.type, t7.type, t8.type, t9.type, t10.type, t11.type);
}
else if (t1.simple && t2.simple && t3.simple && t4.simple && t5.simple && t6.simple && t7.simple && t8.simple && t9.simple && t10.simple && t11.simple)
{
return ReadInternalAsync(command, async r => (
await r.GetFieldValueAsync<T1>(0, convertsDbNull),
await r.GetFieldValueAsync<T2>(1, convertsDbNull),
await r.GetFieldValueAsync<T3>(2, convertsDbNull),
await r.GetFieldValueAsync<T4>(3, convertsDbNull),
await r.GetFieldValueAsync<T5>(4, convertsDbNull),
await r.GetFieldValueAsync<T6>(5, convertsDbNull),
await r.GetFieldValueAsync<T7>(6, convertsDbNull),
await r.GetFieldValueAsync<T8>(7, convertsDbNull),
await r.GetFieldValueAsync<T9>(8, convertsDbNull),
await r.GetFieldValueAsync<T10>(9, convertsDbNull),
await r.GetFieldValueAsync<T11>(10, convertsDbNull)));
}
throw new NormMultipleMappingsException();
}
public IAsyncEnumerable<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11)> ReadAsync<T1, T2, T3, T4, T5, T6, T7, T8, T9,
T10, T11>(string command, params object[] parameters)
{
var t1 = TypeCache<T1>.GetMetadata();
var t2 = TypeCache<T2>.GetMetadata();
var t3 = TypeCache<T3>.GetMetadata();
var t4 = TypeCache<T4>.GetMetadata();
var t5 = TypeCache<T5>.GetMetadata();
var t6 = TypeCache<T6>.GetMetadata();
var t7 = TypeCache<T7>.GetMetadata();
var t8 = TypeCache<T8>.GetMetadata();
var t9 = TypeCache<T9>.GetMetadata();
var t10 = TypeCache<T10>.GetMetadata();
var t11 = TypeCache<T11>.GetMetadata();
if (t1.valueTuple && t2.valueTuple && t3.valueTuple && t4.valueTuple && t5.valueTuple && t6.valueTuple && t7.valueTuple && t8.valueTuple && t9.valueTuple && t10.valueTuple && t11.valueTuple)
{
return ReadAsync(command, parameters).MapValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(t1.type, t2.type, t3.type, t4.type, t5.type, t6.type, t7.type, t8.type, t9.type, t10.type, t11.type);
}
else if (!t1.simple && !t2.simple && !t3.simple && !t4.simple && !t5.simple && !t6.simple && !t7.simple && !t8.simple && !t9.simple && !t10.simple && !t11.simple)
{
return ReadAsync(command, parameters).Map<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(t1.type, t2.type, t3.type, t4.type, t5.type, t6.type, t7.type, t8.type, t9.type, t10.type, t11.type);
}
else if (t1.simple && t2.simple && t3.simple && t4.simple && t5.simple && t6.simple && t7.simple && t8.simple && t9.simple && t10.simple && t11.simple)
{
return ReadInternalAsync(command, async r => (
await r.GetFieldValueAsync<T1>(0, convertsDbNull),
await r.GetFieldValueAsync<T2>(1, convertsDbNull),
await r.GetFieldValueAsync<T3>(2, convertsDbNull),
await r.GetFieldValueAsync<T4>(3, convertsDbNull),
await r.GetFieldValueAsync<T5>(4, convertsDbNull),
await r.GetFieldValueAsync<T6>(5, convertsDbNull),
await r.GetFieldValueAsync<T7>(6, convertsDbNull),
await r.GetFieldValueAsync<T8>(7, convertsDbNull),
await r.GetFieldValueAsync<T9>(8, convertsDbNull),
await r.GetFieldValueAsync<T10>(9, convertsDbNull),
await r.GetFieldValueAsync<T11>(10, convertsDbNull)), parameters);
}
throw new NormMultipleMappingsException();
}
public IAsyncEnumerable<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11)> ReadAsync<T1, T2, T3, T4, T5, T6, T7, T8, T9,
T10, T11>(string command, params (string name, object value)[] parameters)
{
var t1 = TypeCache<T1>.GetMetadata();
var t2 = TypeCache<T2>.GetMetadata();
var t3 = TypeCache<T3>.GetMetadata();
var t4 = TypeCache<T4>.GetMetadata();
var t5 = TypeCache<T5>.GetMetadata();
var t6 = TypeCache<T6>.GetMetadata();
var t7 = TypeCache<T7>.GetMetadata();
var t8 = TypeCache<T8>.GetMetadata();
var t9 = TypeCache<T9>.GetMetadata();
var t10 = TypeCache<T10>.GetMetadata();
var t11 = TypeCache<T11>.GetMetadata();
if (t1.valueTuple && t2.valueTuple && t3.valueTuple && t4.valueTuple && t5.valueTuple && t6.valueTuple && t7.valueTuple && t8.valueTuple && t9.valueTuple && t10.valueTuple && t11.valueTuple)
{
return ReadAsync(command, parameters).MapValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(t1.type, t2.type, t3.type, t4.type, t5.type, t6.type, t7.type, t8.type, t9.type, t10.type, t11.type);
}
else if (!t1.simple && !t2.simple && !t3.simple && !t4.simple && !t5.simple && !t6.simple && !t7.simple && !t8.simple && !t9.simple && !t10.simple && !t11.simple)
{
return ReadAsync(command, parameters).Map<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(t1.type, t2.type, t3.type, t4.type, t5.type, t6.type, t7.type, t8.type, t9.type, t10.type, t11.type);
}
else if (t1.simple && t2.simple && t3.simple && t4.simple && t5.simple && t6.simple && t7.simple && t8.simple && t9.simple && t10.simple && t11.simple)
{
return ReadInternalAsync(command, async r => (
await r.GetFieldValueAsync<T1>(0, convertsDbNull),
await r.GetFieldValueAsync<T2>(1, convertsDbNull),
await r.GetFieldValueAsync<T3>(2, convertsDbNull),
await r.GetFieldValueAsync<T4>(3, convertsDbNull),
await r.GetFieldValueAsync<T5>(4, convertsDbNull),
await r.GetFieldValueAsync<T6>(5, convertsDbNull),
await r.GetFieldValueAsync<T7>(6, convertsDbNull),
await r.GetFieldValueAsync<T8>(7, convertsDbNull),
await r.GetFieldValueAsync<T9>(8, convertsDbNull),
await r.GetFieldValueAsync<T10>(9, convertsDbNull),
await r.GetFieldValueAsync<T11>(10, convertsDbNull)), parameters);
}
throw new NormMultipleMappingsException();
}
public IAsyncEnumerable<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11)> ReadAsync<T1, T2, T3, T4, T5, T6, T7, T8, T9,
T10, T11>(string command, params (string name, object value, DbType type)[] parameters)
{
var t1 = TypeCache<T1>.GetMetadata();
var t2 = TypeCache<T2>.GetMetadata();
var t3 = TypeCache<T3>.GetMetadata();
var t4 = TypeCache<T4>.GetMetadata();
var t5 = TypeCache<T5>.GetMetadata();
var t6 = TypeCache<T6>.GetMetadata();
var t7 = TypeCache<T7>.GetMetadata();
var t8 = TypeCache<T8>.GetMetadata();
var t9 = TypeCache<T9>.GetMetadata();
var t10 = TypeCache<T10>.GetMetadata();
var t11 = TypeCache<T11>.GetMetadata();
if (t1.valueTuple && t2.valueTuple && t3.valueTuple && t4.valueTuple && t5.valueTuple && t6.valueTuple && t7.valueTuple && t8.valueTuple && t9.valueTuple && t10.valueTuple && t11.valueTuple)
{
return ReadAsync(command, parameters).MapValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(t1.type, t2.type, t3.type, t4.type, t5.type, t6.type, t7.type, t8.type, t9.type, t10.type, t11.type);
}
else if (!t1.simple && !t2.simple && !t3.simple && !t4.simple && !t5.simple && !t6.simple && !t7.simple && !t8.simple && !t9.simple && !t10.simple && !t11.simple)
{
return ReadAsync(command, parameters).Map<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(t1.type, t2.type, t3.type, t4.type, t5.type, t6.type, t7.type, t8.type, t9.type, t10.type, t11.type);
}
else if (t1.simple && t2.simple && t3.simple && t4.simple && t5.simple && t6.simple && t7.simple && t8.simple && t9.simple && t10.simple && t11.simple)
{
return ReadInternalAsync(command, async r => (
await r.GetFieldValueAsync<T1>(0, convertsDbNull),
await r.GetFieldValueAsync<T2>(1, convertsDbNull),
await r.GetFieldValueAsync<T3>(2, convertsDbNull),
await r.GetFieldValueAsync<T4>(3, convertsDbNull),
await r.GetFieldValueAsync<T5>(4, convertsDbNull),
await r.GetFieldValueAsync<T6>(5, convertsDbNull),
await r.GetFieldValueAsync<T7>(6, convertsDbNull),
await r.GetFieldValueAsync<T8>(7, convertsDbNull),
await r.GetFieldValueAsync<T9>(8, convertsDbNull),
await r.GetFieldValueAsync<T10>(9, convertsDbNull),
await r.GetFieldValueAsync<T11>(10, convertsDbNull)), parameters);
}
throw new NormMultipleMappingsException();
}
public IAsyncEnumerable<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11)> ReadAsync<T1, T2, T3, T4, T5, T6, T7, T8, T9,
T10, T11>(string command, params (string name, object value, object type)[] parameters)
{
var t1 = TypeCache<T1>.GetMetadata();
var t2 = TypeCache<T2>.GetMetadata();
var t3 = TypeCache<T3>.GetMetadata();
var t4 = TypeCache<T4>.GetMetadata();
var t5 = TypeCache<T5>.GetMetadata();
var t6 = TypeCache<T6>.GetMetadata();
var t7 = TypeCache<T7>.GetMetadata();
var t8 = TypeCache<T8>.GetMetadata();
var t9 = TypeCache<T9>.GetMetadata();
var t10 = TypeCache<T10>.GetMetadata();
var t11 = TypeCache<T11>.GetMetadata();
if (t1.valueTuple && t2.valueTuple && t3.valueTuple && t4.valueTuple && t5.valueTuple && t6.valueTuple && t7.valueTuple && t8.valueTuple && t9.valueTuple && t10.valueTuple && t11.valueTuple)
{
return ReadAsync(command, parameters).MapValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(t1.type, t2.type, t3.type, t4.type, t5.type, t6.type, t7.type, t8.type, t9.type, t10.type, t11.type);
}
else if (!t1.simple && !t2.simple && !t3.simple && !t4.simple && !t5.simple && !t6.simple && !t7.simple && !t8.simple && !t9.simple && !t10.simple && !t11.simple)
{
return ReadAsync(command, parameters).Map<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(t1.type, t2.type, t3.type, t4.type, t5.type, t6.type, t7.type, t8.type, t9.type, t10.type, t11.type);
}
else if (t1.simple && t2.simple && t3.simple && t4.simple && t5.simple && t6.simple && t7.simple && t8.simple && t9.simple && t10.simple && t11.simple)
{
return ReadInternalUnknownParamsTypeAsync(command, async r => (
await r.GetFieldValueAsync<T1>(0, convertsDbNull),
await r.GetFieldValueAsync<T2>(1, convertsDbNull),
await r.GetFieldValueAsync<T3>(2, convertsDbNull),
await r.GetFieldValueAsync<T4>(3, convertsDbNull),
await r.GetFieldValueAsync<T5>(4, convertsDbNull),
await r.GetFieldValueAsync<T6>(5, convertsDbNull),
await r.GetFieldValueAsync<T7>(6, convertsDbNull),
await r.GetFieldValueAsync<T8>(7, convertsDbNull),
await r.GetFieldValueAsync<T9>(8, convertsDbNull),
await r.GetFieldValueAsync<T10>(9, convertsDbNull),
await r.GetFieldValueAsync<T11>(10, convertsDbNull)), parameters);
}
throw new NormMultipleMappingsException();
}
}
} | 66.789474 | 215 | 0.567437 | [
"MIT"
] | vb-consulting/Norm.net | Norm/ReadAsync/NormReadAsync11.cs | 16,499 | 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("ConvNetSharp.Volume.NetFramework")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ConvNetSharp.Volume.NetFramework")]
[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("5a39428e-b4ad-4799-a829-08646b4e1a14")]
// 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.702703 | 84 | 0.752095 | [
"MIT"
] | NickStrupat/ConvNetSharp | src/ConvNetSharp.Volume/Properties/AssemblyInfo.cs | 1,435 | C# |
using Backend.Fx.Environment.Authentication;
using Xunit;
namespace Backend.Fx.Tests.Environment.Authentication
{
public class TheSystemIdentity
{
[Fact]
public void HasAuthenticationTypeSystemInternal()
{
Assert.Equal("system internal", new SystemIdentity().AuthenticationType);
}
[Fact]
public void HasNameSystem()
{
Assert.Equal("SYSTEM", new SystemIdentity().Name);
}
[Fact]
public void IsAuthenticated()
{
Assert.True(new SystemIdentity().IsAuthenticated);
}
}
} | 23.653846 | 85 | 0.601626 | [
"MIT"
] | marcwittke/Backend.Fx | tests/Backend.Fx.Tests/Environment/Authentication/TheSystemIdentity.cs | 617 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Abp.Application.Services.Dto;
using Abp.Authorization.Roles;
using Abp.AutoMapper;
using DoAspnetboilerplateLdap.Authorization.Roles;
namespace DoAspnetboilerplateLdap.Roles.Dto
{
public class RoleDto : EntityDto<int>
{
[Required]
[StringLength(AbpRoleBase.MaxNameLength)]
public string Name { get; set; }
[Required]
[StringLength(AbpRoleBase.MaxDisplayNameLength)]
public string DisplayName { get; set; }
public string NormalizedName { get; set; }
[StringLength(Role.MaxDescriptionLength)]
public string Description { get; set; }
public List<string> GrantedPermissions { get; set; }
}
} | 29.074074 | 60 | 0.690446 | [
"MIT"
] | d-oit/DoAspnetboilerplateLdap | aspnet-core/src/DoAspnetboilerplateLdap.Application/Roles/Dto/RoleDto.cs | 785 | C# |
using System.IO.Abstractions;
using SJP.Schematic.Core;
namespace SJP.Schematic.DataAccess
{
/// <summary>
/// Defines generator for creating source code to work with a database entity.
/// </summary>
public interface IDatabaseEntityGenerator
{
/// <summary>
/// Gets the file path that the source code should be generated to.
/// </summary>
/// <param name="baseDirectory">The base directory.</param>
/// <param name="objectName">The name of the database object.</param>
/// <returns>A file path.</returns>
IFileInfo GetFilePath(IDirectoryInfo baseDirectory, Identifier objectName);
}
}
| 34.45 | 84 | 0.638607 | [
"MIT"
] | sjp/Schematic | src/SJP.Schematic.DataAccess/IDatabaseEntityGenerator.cs | 691 | C# |
using System.Runtime.InteropServices;
namespace Lunar.Native.Structs
{
[StructLayout(LayoutKind.Explicit, Size = 40)]
internal readonly struct LdrpTlsEntry32
{
[FieldOffset(0x0)]
internal readonly ListEntry32 EntryLinks;
[FieldOffset(0x8)]
private readonly ImageTlsDirectory32 TlsDirectory;
[FieldOffset(0x24)]
private readonly int Index;
internal LdrpTlsEntry32(ListEntry32 entryLinks, ImageTlsDirectory32 tlsDirectory, int index)
{
EntryLinks = entryLinks;
TlsDirectory = tlsDirectory;
Index = index;
}
}
[StructLayout(LayoutKind.Explicit, Size = 72)]
internal readonly struct LdrpTlsEntry64
{
[FieldOffset(0x0)]
internal readonly ListEntry64 EntryLinks;
[FieldOffset(0x10)]
private readonly ImageTlsDirectory64 TlsDirectory;
[FieldOffset(0x40)]
private readonly int Index;
internal LdrpTlsEntry64(ListEntry64 entryLinks, ImageTlsDirectory64 tlsDirectory, int index)
{
EntryLinks = entryLinks;
TlsDirectory = tlsDirectory;
Index = index;
}
}
} | 29.95 | 100 | 0.646912 | [
"MIT"
] | wisdark/Lunar | Lunar/Native/Structs/LdrpTlsEntry.cs | 1,200 | C# |
using System;
namespace PM.BO.Exceptions
{
public class TKUSB_INIT_EPNUM_ERR : Exception
{
private const string _message = "Error initializing the USB endpoint.";
private const short Code = -334;
public TKUSB_INIT_EPNUM_ERR() : base(_message) { }
public TKUSB_INIT_EPNUM_ERR(string message) : base (_message + "\nAdditional Information: " + message) { }
}
}
| 24.866667 | 108 | 0.731903 | [
"BSD-2-Clause"
] | addixon/ErgCompetePM | PM.BO/Exceptions/TKUSB_INIT_EPNUM_ERR.cs | 375 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: IEntityReferenceRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The interface IAgreementAcceptanceReferenceRequest.
/// </summary>
public partial interface IAgreementAcceptanceReferenceRequest : IBaseRequest
{
/// <summary>
/// Deletes the specified AgreementAcceptance reference.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Deletes the specified AgreementAcceptance reference and returns a <see cref="GraphResponse"/> object.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task of <see cref="GraphResponse"/> to await.</returns>
System.Threading.Tasks.Task<GraphResponse> DeleteResponseAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Puts the specified AgreementAcceptance reference.
/// </summary>
/// <param name="id">The AgreementAcceptance reference reference to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
System.Threading.Tasks.Task PutAsync(string id, CancellationToken cancellationToken = default);
/// <summary>
/// Puts the specified AgreementAcceptance reference and returns a <see cref="GraphResponse"/> object
/// </summary>
/// <param name="id">The AgreementAcceptance reference reference to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task of <see cref="GraphResponse"/> to await.</returns>
System.Threading.Tasks.Task<GraphResponse> PutResponseAsync(string id, CancellationToken cancellationToken = default);
}
}
| 50.288462 | 153 | 0.640535 | [
"MIT"
] | Aliases/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/IAgreementAcceptanceReferenceRequest.cs | 2,615 | C# |
using System;
namespace Game
{
class Program
{
static void Main(string[] args)
{
int capacity = int.Parse(Console.ReadLine());
Dictionary<String, CapacityList> players = new Dictionary<string, CapacityList>();
string command = "";
do
{
command = Console.ReadLine();
string[] commands = command.Split(' ').ToArray();
switch (commands[0])
{
case "Dice":
string player = commands[1];
int value1 = int.Parse(commands[2]);
int value2 = int.Parse(commands[3]);
if (players.ContainsKey(player))
{
players[player].Add(new Pair(value1, value2));
}
else
{
players.Add(player, new CapacityList(capacity));
players[player].Add(new Pair(value1, value2));
}
break;
case "CurrentPairSum":
string playerName = commands[1];
if (players.ContainsKey(playerName))
{
Console.WriteLine(players[playerName].Sum());
}
break;
case "CurrentStanding":
players = players.OrderBy(element => element.Value.Sum().Difference())
.ToDictionary(element => element.Key, element => element.Value);
foreach (var item in players)
{
Console.WriteLine(item.Key + " - " + item.Value.Sum());
}
break;
case "CurrentState":
string playerNameState = commands[1];
if (players.ContainsKey(playerNameState))
{
players[playerNameState].PrintCurrentState();
}
break;
case "Winner":
players = players.OrderBy(element => element.Value.Sum().Difference())
.ThenBy(element => element.Key)
.ToDictionary(element => element.Key, element => element.Value);
Console.WriteLine("{0} wins the game!", players.First().Key);
break;
}
} while (command != "End");
}
}
}
| 38.422535 | 94 | 0.399194 | [
"MIT"
] | CaptainUltra/IT-Career-Course | Year 1/Module 4 - Introduction to Algorithms and Data Structures/ExamPrep/Game/Program.cs | 2,730 | C# |
using System;
using System.Collections.Generic;
using Alipay.AopSdk.Core.Response;
namespace Alipay.AopSdk.Core.Request
{
/// <summary>
/// AOP API: alipay.commerce.data.monitordata.sync
/// </summary>
public class AlipayCommerceDataMonitordataSyncRequest : IAopRequest<AlipayCommerceDataMonitordataSyncResponse>
{
/// <summary>
/// 自助监控服务接口
/// </summary>
public string BizContent { get; set; }
#region IAopRequest Members
private bool needEncrypt=false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AopObject bizModel;
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return this.needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return this.notifyUrl;
}
public void SetReturnUrl(string returnUrl){
this.returnUrl = returnUrl;
}
public string GetReturnUrl(){
return this.returnUrl;
}
public void SetTerminalType(String terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return this.terminalType;
}
public void SetTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return this.terminalInfo;
}
public void SetProdCode(String prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return this.prodCode;
}
public string GetApiName()
{
return "alipay.commerce.data.monitordata.sync";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return this.apiVersion;
}
public IDictionary<string, string> GetParameters()
{
AopDictionary parameters = new AopDictionary();
parameters.Add("biz_content", this.BizContent);
return parameters;
}
public AopObject GetBizModel()
{
return this.bizModel;
}
public void SetBizModel(AopObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.917431 | 114 | 0.608746 | [
"MIT"
] | leixf2005/Alipay.AopSdk.Core | Alipay.AopSdk.Core/Request/AlipayCommerceDataMonitordataSyncRequest.cs | 2,623 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Newtonsoft.Json.Linq;
namespace StatCan.OrchardCore.Queries.GraphQL.ViewModels
{
public class AdminQueryViewModel
{
public string DecodedQuery { get; set; }
public string Parameters { get; set; } = "";
[BindNever]
public string RawGraphQL { get; set; }
[BindNever]
public TimeSpan Elapsed { get; set; } = TimeSpan.Zero;
[BindNever]
public IEnumerable<JObject> Documents { get; set; } = Enumerable.Empty<JObject>();
}
}
| 24.72 | 90 | 0.665049 | [
"MIT"
] | StatCan/StatCan.OrchardCore | src/Modules/StatCan.OrchardCore.Queries.GraphQL/ViewModels/AdminQueryViewModel.cs | 618 | C# |
using Neo.Lux.Cryptography;
using Neo.Lux.VM;
using Neo.Lux.Core;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using System.Reflection;
namespace Neo.Lux.Utils
{
public class ByteArrayComparer : IEqualityComparer<byte[]>
{
public bool Equals(byte[] left, byte[] right)
{
if (left == null || right == null)
{
return left == right;
}
return left.SequenceEqual(right);
}
public int GetHashCode(byte[] key)
{
if (key == null)
throw new ArgumentNullException("key");
return key.Sum(b => b);
}
}
public static class LuxUtils
{
public static BigInteger ToBigInteger(this decimal val, int places = 8)
{
while (places > 0)
{
val *= 10;
places--;
}
return (long)val;
}
public static decimal ToDecimal(this BigInteger val, int places = 8)
{
var result = (decimal)((long)val);
while (places > 0)
{
result /= 10m;
places--;
}
return result;
}
public static string ReverseHex(this string hex)
{
string result = "";
for (var i = hex.Length - 2; i >= 0; i -= 2)
{
result += hex.Substring(i, 2);
}
return result;
}
public static bool IsValidAddress(this string address)
{
if (string.IsNullOrEmpty(address))
{
return false;
}
if (address.Length != 34)
{
return false;
}
byte[] buffer;
try
{
buffer = Base58.Decode(address);
}
catch
{
return false;
}
if (buffer.Length < 4) return false;
byte[] checksum = buffer.Sha256(0, buffer.Length - 4).Sha256();
return buffer.Skip(buffer.Length - 4).SequenceEqual(checksum.Take(4));
}
public static byte[] ReadVarBytes(this BinaryReader reader, int max = 0X7fffffc7)
{
var len = (int)reader.ReadVarInt((ulong)max);
if (len == 0) return null;
return reader.ReadBytes(len);
}
public static ulong ReadVarInt(this BinaryReader reader, ulong max = ulong.MaxValue)
{
byte fb = reader.ReadByte();
ulong value;
if (fb == 0xFD)
value = reader.ReadUInt16();
else if (fb == 0xFE)
value = reader.ReadUInt32();
else if (fb == 0xFF)
value = reader.ReadUInt64();
else
value = fb;
if (value > max) throw new FormatException();
return value;
}
public static string ReadVarString(this BinaryReader reader)
{
return Encoding.UTF8.GetString(reader.ReadVarBytes());
}
public static void WriteVarBytes(this BinaryWriter writer, byte[] value)
{
if (value == null)
{
writer.WriteVarInt(0);
return;
}
writer.WriteVarInt(value.Length);
writer.Write(value);
}
public static void WriteVarInt(this BinaryWriter writer, long value)
{
if (value < 0)
throw new ArgumentOutOfRangeException();
if (value < 0xFD)
{
writer.Write((byte)value);
}
else if (value <= 0xFFFF)
{
writer.Write((byte)0xFD);
writer.Write((ushort)value);
}
else if (value <= 0xFFFFFFFF)
{
writer.Write((byte)0xFE);
writer.Write((uint)value);
}
else
{
writer.Write((byte)0xFF);
writer.Write(value);
}
}
public static void WriteVarString(this BinaryWriter writer, string value)
{
writer.WriteVarBytes(value != null ? Encoding.UTF8.GetBytes(value): null);
}
public static void WriteFixed(this BinaryWriter writer, decimal value)
{
long D = 100000000;
value *= D;
writer.Write((long)value);
}
public static decimal ReadFixed(this BinaryReader reader)
{
var val = reader.ReadInt64();
long D = 100000000;
decimal r = val;
r /= (decimal)D;
return r;
}
public static byte[] GetScriptHashFromAddress(this string address)
{
var temp = address.Base58CheckDecode();
temp = temp.SubArray(1, 20);
return temp;
}
public static string ByteToHex(this byte[] data)
{
string hex = BitConverter.ToString(data).Replace("-", "").ToLower();
return hex;
}
private static int BitLen(int w)
{
return (w < 1 << 15 ? (w < 1 << 7
? (w < 1 << 3 ? (w < 1 << 1
? (w < 1 << 0 ? (w < 0 ? 32 : 0) : 1)
: (w < 1 << 2 ? 2 : 3)) : (w < 1 << 5
? (w < 1 << 4 ? 4 : 5)
: (w < 1 << 6 ? 6 : 7)))
: (w < 1 << 11
? (w < 1 << 9 ? (w < 1 << 8 ? 8 : 9) : (w < 1 << 10 ? 10 : 11))
: (w < 1 << 13 ? (w < 1 << 12 ? 12 : 13) : (w < 1 << 14 ? 14 : 15)))) : (w < 1 << 23 ? (w < 1 << 19
? (w < 1 << 17 ? (w < 1 << 16 ? 16 : 17) : (w < 1 << 18 ? 18 : 19))
: (w < 1 << 21 ? (w < 1 << 20 ? 20 : 21) : (w < 1 << 22 ? 22 : 23))) : (w < 1 << 27
? (w < 1 << 25 ? (w < 1 << 24 ? 24 : 25) : (w < 1 << 26 ? 26 : 27))
: (w < 1 << 29 ? (w < 1 << 28 ? 28 : 29) : (w < 1 << 30 ? 30 : 31)))));
}
public static byte[] AddressToScriptHash(string s)
{
var bytes = s.Base58CheckDecode();
var data = bytes.Skip(1).Take(20).ToArray();
return data;
}
internal static int GetBitLength(this BigInteger i)
{
byte[] b = i.ToByteArray();
return (b.Length - 1) * 8 + BitLen(i.Sign > 0 ? b[b.Length - 1] : 255 - b[b.Length - 1]);
}
internal static int GetLowestSetBit(this BigInteger i)
{
if (i.Sign == 0)
return -1;
byte[] b = i.ToByteArray();
int w = 0;
while (b[w] == 0)
w++;
for (int x = 0; x < 8; x++)
if ((b[w] & 1 << x) > 0)
return x + w * 8;
throw new Exception();
}
internal static BigInteger Mod(this BigInteger x, BigInteger y)
{
x %= y;
if (x.Sign < 0)
x += y;
return x;
}
internal static BigInteger ModInverse(this BigInteger a, BigInteger n)
{
BigInteger i = n, v = 0, d = 1;
while (a > 0)
{
BigInteger t = i / a, x = a;
a = i % x;
i = x;
x = d;
d = v - t * x;
v = x;
}
v %= n;
if (v < 0) v = (v + n) % n;
return v;
}
internal static BigInteger NextBigInteger(this Random rand, int sizeInBits)
{
if (sizeInBits < 0)
throw new ArgumentException("sizeInBits must be non-negative");
if (sizeInBits == 0)
return 0;
byte[] b = new byte[sizeInBits / 8 + 1];
rand.NextBytes(b);
if (sizeInBits % 8 == 0)
b[b.Length - 1] = 0;
else
b[b.Length - 1] &= (byte)((1 << sizeInBits % 8) - 1);
return new BigInteger(b);
}
internal static bool TestBit(this BigInteger i, int index)
{
return (i & (BigInteger.One << index)) > BigInteger.Zero;
}
public static string ToHexString(this IEnumerable<byte> value)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in value)
sb.AppendFormat("{0:x2}", b);
return sb.ToString();
}
internal static long WeightedAverage<T>(this IEnumerable<T> source, Func<T, long> valueSelector, Func<T, long> weightSelector)
{
long sum_weight = 0;
long sum_value = 0;
foreach (T item in source)
{
long weight = weightSelector(item);
sum_weight += weight;
sum_value += valueSelector(item) * weight;
}
if (sum_value == 0) return 0;
return sum_value / sum_weight;
}
public static byte[] HexToBytes(this string value)
{
if (value == null || value.Length == 0)
return new byte[0];
if (value.Length % 2 == 1)
throw new FormatException();
if (value.StartsWith("0x"))
{
value = value.Substring(2);
}
byte[] result = new byte[value.Length / 2];
for (int i = 0; i < result.Length; i++)
result[i] = byte.Parse(value.Substring(i * 2, 2), NumberStyles.AllowHexSpecifier);
return result;
}
internal static BigInteger NextBigInteger(this RandomNumberGenerator rng, int sizeInBits)
{
if (sizeInBits < 0)
throw new ArgumentException("sizeInBits must be non-negative");
if (sizeInBits == 0)
return 0;
byte[] b = new byte[sizeInBits / 8 + 1];
rng.GetBytes(b);
if (sizeInBits % 8 == 0)
b[b.Length - 1] = 0;
else
b[b.Length - 1] &= (byte)((1 << sizeInBits % 8) - 1);
return new BigInteger(b);
}
public static Fixed8 Sum(this IEnumerable<Fixed8> source)
{
long sum = 0;
checked
{
foreach (Fixed8 item in source)
{
sum += item.value;
}
}
return new Fixed8(sum);
}
internal static IEnumerable<TResult> WeightedFilter<T, TResult>(this IList<T> source, double start, double end, Func<T, long> weightSelector, Func<T, long, TResult> resultSelector)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (start < 0 || start > 1) throw new ArgumentOutOfRangeException(nameof(start));
if (end < start || start + end > 1) throw new ArgumentOutOfRangeException(nameof(end));
if (weightSelector == null) throw new ArgumentNullException(nameof(weightSelector));
if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector));
if (source.Count == 0 || start == end) yield break;
double amount = source.Sum(weightSelector);
long sum = 0;
double current = 0;
foreach (T item in source)
{
if (current >= end) break;
long weight = weightSelector(item);
sum += weight;
double old = current;
current = sum / amount;
if (current <= start) continue;
if (old < start)
{
if (current > end)
{
weight = (long)((end - start) * amount);
}
else
{
weight = (long)((current - start) * amount);
}
}
else if (current > end)
{
weight = (long)((end - old) * amount);
}
yield return resultSelector(item, weight);
}
}
private static readonly DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static DateTime ToDateTime(this uint timestamp)
{
return unixEpoch.AddSeconds(timestamp);
}
public static DateTime ToDateTime(this ulong timestamp)
{
return unixEpoch.AddSeconds(timestamp);
}
public static uint ToTimestamp(this DateTime time)
{
return (uint)(time.ToUniversalTime() - unixEpoch).TotalSeconds;
}
public static object FromStackItem(this StackItem item)
{
if (item is VM.Types.Integer)
{
return item.GetBigInteger();
}
else
if (item is VM.Types.Boolean)
{
return item.GetBoolean();
}
else
if (item is VM.Types.ByteArray)
{
return item.GetByteArray();
}
else
{
throw new NotImplementedException();
}
}
public static StackItem ToStackItem(this object obj)
{
StackItem item;
if (obj == null)
{
item = new byte[0];
}
else
{
var type = obj.GetType();
if (obj is BigInteger)
{
item = (BigInteger)obj;
}
else
if (obj is byte)
{
item = new BigInteger((byte)obj);
}
else
if (obj is sbyte)
{
item = new BigInteger((sbyte)obj);
}
else
if (obj is int)
{
item = new BigInteger((int)obj);
}
else
if (obj is short)
{
item = new BigInteger((short)obj);
}
else
if (obj is ushort)
{
item = new BigInteger((ushort)obj);
}
else
if (obj is uint)
{
item = new BigInteger((uint)obj);
}
else
if (obj is long)
{
item = new BigInteger((long)obj);
}
else
if (obj is ulong)
{
item = new BigInteger((ulong)obj);
}
else
if (obj is byte[])
{
item = (byte[])obj;
}
else
if (obj is bool)
{
item = (bool)obj;
}
else
if (obj is string)
{
item = (byte[])System.Text.Encoding.UTF8.GetBytes((string)obj);
}
else
if (type.IsArray)
{
var items = new List<StackItem>();
var array = (Array)obj;
foreach (var val in array)
{
items.Add(val.ToStackItem());
}
item = new VM.Types.Array(items);
}
else
if (type.IsValueType && !type.IsEnum)
{
var items = new List<StackItem> ();
var fields = type.GetFields();
foreach (var field in fields){
object val = field.GetValue(obj);
items.Add(val.ToStackItem());
}
item = new VM.Types.Struct(items);
}
else
{
throw new Exception("something bad happened");
}
}
return item;
}
}
}
| 30.730129 | 188 | 0.426045 | [
"MIT"
] | CityOfZion/neo-lux | Neo.Lux/Utils/LuxUtils.cs | 16,627 | C# |
using UnityEngine;
using System.Collections;
/**
* This class will help destruct objects after a certain time.
*/
public class TimedObjectDestructor : MonoBehaviour {
public float timeOut = 1.0f;
public bool detachChildren = false;
// Use this for initialization
private void Awake () {
// invoke the DestroyNow function to run after timeOut seconds
Invoke ("DestroyNow", timeOut);
}
/**
* Destroy the game object(if it has children, detaches children first, no children in this game).
*/
private void DestroyNow ()
{
// detach the children before destroying if specified
if (detachChildren) {
transform.DetachChildren();
}
DestroyObject (gameObject);
}
}
| 23.066667 | 99 | 0.721098 | [
"MIT"
] | Yunxiang-Li/Unity3D_Roller-Ball-Game | Assets/Scripts/TimedObjectDestructor.cs | 694 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
namespace ReverseGeocode.Processors
{
internal class GpsCoordinate
: IEquatable<GpsCoordinate>
{
public double Latitude { get; set; }
public double Longitude { get; set; }
public override bool Equals(object obj)
{
return Equals(obj as GpsCoordinate);
}
public bool Equals([AllowNull] GpsCoordinate other)
{
return other != null &&
Latitude == other.Latitude &&
Longitude == other.Longitude;
}
public override int GetHashCode()
{
return HashCode.Combine(Latitude, Longitude);
}
}
} | 22.375 | 59 | 0.574022 | [
"MIT"
] | AerisG222/ReverseGeocode | src/ReverseGeocode/Processors/GpsCoordinate.cs | 716 | C# |
/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* 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.Security;
namespace Alphaleonis.Win32.Filesystem
{
public static partial class Path
{
/// <summary>[AlphaFS] Returns the directory information for the specified <paramref name="path"/> without the root and with a trailing <see cref="DirectorySeparatorChar"/> character.</summary>
/// <returns>
/// <para>The directory information for the specified <paramref name="path"/> without the root and with a trailing <see cref="DirectorySeparatorChar"/> character,</para>
/// <para>or <c>null</c> if <paramref name="path"/> is <c>null</c> or if <paramref name="path"/> is <c>null</c>.</para>
/// </returns>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The path.</param>
[SecurityCritical]
public static string GetSuffixedDirectoryNameWithoutRootTransacted(KernelTransaction transaction, string path)
{
return GetSuffixedDirectoryNameWithoutRootCore(transaction, path, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns the directory information for the specified <paramref name="path"/> without the root and with a trailing <see cref="DirectorySeparatorChar"/> character.</summary>
/// <returns>
/// <para>The directory information for the specified <paramref name="path"/> without the root and with a trailing <see cref="DirectorySeparatorChar"/> character,</para>
/// <para>or <c>null</c> if <paramref name="path"/> is <c>null</c> or if <paramref name="path"/> is <c>null</c>.</para>
/// </returns>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The path.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static string GetSuffixedDirectoryNameWithoutRootTransacted(KernelTransaction transaction, string path, PathFormat pathFormat)
{
return GetSuffixedDirectoryNameWithoutRootCore(transaction, path, pathFormat);
}
}
}
| 56.77193 | 199 | 0.708282 | [
"MIT"
] | DamirAinullin/AlphaFS | src/AlphaFS/Filesystem/Path Class/Path.GetSuffixedDirectoryNameWithoutRootTransacted.cs | 3,236 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.470)
// Version 5.470.0.0 www.ComponentFactory.com
// *****************************************************************************
using System.Drawing;
using System.ComponentModel;
namespace ComponentFactory.Krypton.Toolkit
{
/// <summary>
/// Implement storage for palette background details.
/// </summary>
public class PaletteBackColor1 : PaletteBack
{
#region Identity
/// <summary>
/// Initialize a new instance of the PaletteBackColor1 class.
/// </summary>
/// <param name="inherit">Source for inheriting defaulted values.</param>
/// <param name="needPaint">Delegate for notifying paint requests.</param>
public PaletteBackColor1(IPaletteBack inherit,
NeedPaintHandler needPaint)
: base(inherit, needPaint)
{
}
#endregion
#region PopulateFromBase
/// <summary>
/// Populate values from the base palette.
/// </summary>
/// <param name="state">Palette state to use when populating.</param>
public new void PopulateFromBase(PaletteState state)
{
// Get the values and set into storage
Color1 = GetBackColor1(state);
}
#endregion
#region Draw
/// <summary>
/// Gets a value indicating if background should be drawn.
/// </summary>
[Browsable(false)]
public new InheritBool Draw
{
get => base.Draw;
set => base.Draw = value;
}
#endregion
#region GraphicsHint
/// <summary>
/// Gets the graphics hint for drawing the background.
/// </summary>
[Browsable(false)]
public new PaletteGraphicsHint GraphicsHint
{
get => base.GraphicsHint;
set => base.GraphicsHint = value;
}
#endregion
#region Color2
/// <summary>
/// Gets and sets the second background color.
/// </summary>
[Browsable(false)]
public new Color Color2
{
get => base.Color2;
set => base.Color2 = value;
}
#endregion
#region ColorStyle
/// <summary>
/// Gets and sets the color drawing style.
/// </summary>
[Browsable(false)]
public new PaletteColorStyle ColorStyle
{
get => base.ColorStyle;
set => base.ColorStyle = value;
}
#endregion
#region ColorAlign
/// <summary>
/// Gets and set the color alignment.
/// </summary>
[Browsable(false)]
public new PaletteRectangleAlign ColorAlign
{
get => base.ColorAlign;
set => base.ColorAlign = value;
}
#endregion
#region ColorAngle
/// <summary>
/// Gets and sets the color angle.
/// </summary>
[Browsable(false)]
public new float ColorAngle
{
get => base.ColorAngle;
set => base.ColorAngle = value;
}
#endregion
#region Image
/// <summary>
/// Gets and sets the background image.
/// </summary>
[Browsable(false)]
public new Image Image
{
get => base.Image;
set => base.Image = value;
}
#endregion
#region ImageStyle
/// <summary>
/// Gets and sets the background image style.
/// </summary>
[Browsable(false)]
public new PaletteImageStyle ImageStyle
{
get => base.ImageStyle;
set => base.ImageStyle = value;
}
#endregion
#region ImageAlign
/// <summary>
/// Gets and set the image alignment.
/// </summary>
[Browsable(false)]
public new PaletteRectangleAlign ImageAlign
{
get => base.ImageAlign;
set => base.ImageAlign = value;
}
#endregion
}
}
| 30.185897 | 157 | 0.531535 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy-Archive/Krypton-NET-5.470 | Source/Krypton Components/ComponentFactory.Krypton.Toolkit/Palette Base/PaletteBack/PaletteBackColor1.cs | 4,712 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Library.API.Services;
using Library.API.Entities;
using Microsoft.EntityFrameworkCore;
using Library.API.Helpers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Diagnostics;
using NLog.Extensions.Logging;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Newtonsoft.Json.Serialization;
using System.Linq;
namespace Library.API
{
public class Startup
{
public static IConfigurationRoot Configuration;
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appSettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appSettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
// 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 http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(setupAction =>
{
setupAction.ReturnHttpNotAcceptable = true;
setupAction.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
setupAction.InputFormatters.Add(new XmlDataContractSerializerInputFormatter());
})
.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();
});
// register the DbContext on the container, getting the connection string from
// appSettings (note: use this during development; in a production environment,
// it's better to store the connection string in an environment variable)
var connectionString = Configuration["connectionStrings:libraryDBConnectionString"];
services.AddDbContext<LibraryContext>(o => o.UseSqlServer(connectionString));
// register the repository
services.AddScoped<ILibraryRepository, LibraryRepository>();
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddScoped<IUrlHelper>(implementationFactory =>
{
var actionContext = implementationFactory.GetService<IActionContextAccessor>()
.ActionContext;
return new UrlHelper(actionContext);
});
services.AddTransient<IPropertyMappingService, PropertyMappingService>();
services.AddTransient<ITypeHelperService, TypeHelperService>();
// services.AddScoped<IUrlHelper, UrlHelper>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory, LibraryContext libraryContext)
{
loggerFactory.AddConsole();
loggerFactory.AddDebug(LogLevel.Information);
// loggerFactory.AddProvider(new NLog.Extensions.Logging.NLogLoggerProvider());
loggerFactory.AddNLog();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(appBuilder =>
{
appBuilder.Run(async context =>
{
var exceptionHandlerFeature = context.Features.Get<IExceptionHandlerFeature>();
if (exceptionHandlerFeature != null)
{
var logger = loggerFactory.CreateLogger("Global exception logger");
logger.LogError(500,
exceptionHandlerFeature.Error,
exceptionHandlerFeature.Error.Message);
}
context.Response.StatusCode = 500;
await context.Response.WriteAsync("An unexpected fault happened. Try again later.");
});
});
}
AutoMapper.Mapper.Initialize(cfg =>
{
cfg.CreateMap<Entities.Author, Models.AuthorDto>()
.ForMember(dest => dest.Name, opt => opt.MapFrom(src =>
$"{src.FirstName} {src.LastName}"))
.ForMember(dest => dest.Age, opt => opt.MapFrom(src =>
src.DateOfBirth.GetCurrentAge(src.DateOfDeath)));
cfg.CreateMap<Entities.Book, Models.BookDto>();
cfg.CreateMap<Models.AuthorForCreationDto, Entities.Author>();
cfg.CreateMap<Models.AuthorForCreationWithDateOfDeathDto, Entities.Author>();
cfg.CreateMap<Models.BookForCreationDto, Entities.Book>();
cfg.CreateMap<Models.BookForUpdateDto, Entities.Book>();
cfg.CreateMap<Entities.Book, Models.BookForUpdateDto>();
});
libraryContext.EnsureSeedDataForContext();
app.UseMvc();
}
}
}
| 39.819444 | 121 | 0.616672 | [
"MIT"
] | codeyu/asp-dot-net-core-restful-api-building | 8-asp-dot-net-core-restful-api-building-m8-exercise-files/project-json-based/end/Library/src/Library.API/Startup.cs | 5,736 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.MakeLocalFunctionStatic;
using Microsoft.CodeAnalysis.CSharp.UseAutoProperty;
using Microsoft.CodeAnalysis.CSharp.UseLocalFunction;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.VisualBasic.UseAutoProperty;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics
{
public abstract partial class AbstractDiagnosticProviderBasedUserDiagnosticTest : AbstractUserDiagnosticTest
{
private readonly ConcurrentDictionary<Workspace, (DiagnosticAnalyzer, CodeFixProvider)> _analyzerAndFixerMap =
new ConcurrentDictionary<Workspace, (DiagnosticAnalyzer, CodeFixProvider)>();
internal abstract (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace);
internal virtual (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace, TestParameters parameters)
=> CreateDiagnosticProviderAndFixer(workspace);
private (DiagnosticAnalyzer, CodeFixProvider) GetOrCreateDiagnosticProviderAndFixer(
Workspace workspace, TestParameters parameters)
{
return parameters.fixProviderData == null
? _analyzerAndFixerMap.GetOrAdd(workspace, CreateDiagnosticProviderAndFixer)
: CreateDiagnosticProviderAndFixer(workspace, parameters);
}
internal virtual bool ShouldSkipMessageDescriptionVerification(DiagnosticDescriptor descriptor)
{
if (descriptor.CustomTags.Contains(WellKnownDiagnosticTags.NotConfigurable))
{
if (!descriptor.IsEnabledByDefault || descriptor.DefaultSeverity == DiagnosticSeverity.Hidden)
{
// The message only displayed if either enabled and not hidden, or configurable
return true;
}
}
return false;
}
[Fact]
public void TestSupportedDiagnosticsMessageTitle()
{
using (var workspace = new AdhocWorkspace())
{
var diagnosticAnalyzer = CreateDiagnosticProviderAndFixer(workspace).Item1;
if (diagnosticAnalyzer == null)
{
return;
}
foreach (var descriptor in diagnosticAnalyzer.SupportedDiagnostics)
{
if (descriptor.CustomTags.Contains(WellKnownDiagnosticTags.NotConfigurable))
{
// The title only displayed for rule configuration
continue;
}
Assert.NotEqual("", descriptor.Title?.ToString() ?? "");
}
}
}
[Fact]
public void TestSupportedDiagnosticsMessageDescription()
{
using (var workspace = new AdhocWorkspace())
{
var diagnosticAnalyzer = CreateDiagnosticProviderAndFixer(workspace).Item1;
if (diagnosticAnalyzer == null)
{
return;
}
foreach (var descriptor in diagnosticAnalyzer.SupportedDiagnostics)
{
if (ShouldSkipMessageDescriptionVerification(descriptor))
{
continue;
}
Assert.NotEqual("", descriptor.MessageFormat?.ToString() ?? "");
}
}
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/26717")]
public void TestSupportedDiagnosticsMessageHelpLinkUri()
{
using (var workspace = new AdhocWorkspace())
{
var diagnosticAnalyzer = CreateDiagnosticProviderAndFixer(workspace).Item1;
if (diagnosticAnalyzer == null)
{
return;
}
foreach (var descriptor in diagnosticAnalyzer.SupportedDiagnostics)
{
Assert.NotEqual("", descriptor.HelpLinkUri ?? "");
}
}
}
internal override async Task<IEnumerable<Diagnostic>> GetDiagnosticsAsync(
TestWorkspace workspace, TestParameters parameters)
{
var (analyzer, _) = GetOrCreateDiagnosticProviderAndFixer(workspace, parameters);
AddAnalyzerToWorkspace(workspace, analyzer, parameters);
var document = GetDocumentAndSelectSpan(workspace, out var span);
var allDiagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(document, span);
AssertNoAnalyzerExceptionDiagnostics(allDiagnostics);
return allDiagnostics;
}
internal override async Task<(ImmutableArray<Diagnostic>, ImmutableArray<CodeAction>, CodeAction actionToInvoke)> GetDiagnosticAndFixesAsync(
TestWorkspace workspace, TestParameters parameters)
{
var (analyzer, fixer) = GetOrCreateDiagnosticProviderAndFixer(workspace, parameters);
AddAnalyzerToWorkspace(workspace, analyzer, parameters);
string annotation = null;
if (!TryGetDocumentAndSelectSpan(workspace, out var document, out var span))
{
document = GetDocumentAndAnnotatedSpan(workspace, out annotation, out span);
}
var testDriver = new TestDiagnosticAnalyzerDriver(document.Project);
var filterSpan = parameters.includeDiagnosticsOutsideSelection ? (TextSpan?)null : span;
var diagnostics = (await testDriver.GetAllDiagnosticsAsync(document, filterSpan)).ToImmutableArray();
AssertNoAnalyzerExceptionDiagnostics(diagnostics);
if (fixer == null)
{
return (diagnostics, ImmutableArray<CodeAction>.Empty, null);
}
var ids = new HashSet<string>(fixer.FixableDiagnosticIds);
var dxs = diagnostics.Where(d => ids.Contains(d.Id)).ToList();
var (resultDiagnostics, codeActions, actionToInvoke) = await GetDiagnosticAndFixesAsync(
dxs, fixer, testDriver, document, span, annotation, parameters.index);
// If we are also testing non-fixable diagnostics,
// then the result diagnostics need to include all diagnostics,
// not just the fixable ones returned from GetDiagnosticAndFixesAsync.
if (parameters.retainNonFixableDiagnostics)
{
resultDiagnostics = diagnostics;
}
return (resultDiagnostics, codeActions, actionToInvoke);
}
private protected async Task TestDiagnosticInfoAsync(
string initialMarkup,
OptionsCollection options,
string diagnosticId,
DiagnosticSeverity diagnosticSeverity,
LocalizableString diagnosticMessage = null)
{
await TestDiagnosticInfoAsync(initialMarkup, null, null, options, diagnosticId, diagnosticSeverity, diagnosticMessage);
await TestDiagnosticInfoAsync(initialMarkup, GetScriptOptions(), null, options, diagnosticId, diagnosticSeverity, diagnosticMessage);
}
private protected async Task TestDiagnosticInfoAsync(
string initialMarkup,
ParseOptions parseOptions,
CompilationOptions compilationOptions,
OptionsCollection options,
string diagnosticId,
DiagnosticSeverity diagnosticSeverity,
LocalizableString diagnosticMessage = null)
{
var testOptions = new TestParameters(parseOptions, compilationOptions, options);
using (var workspace = CreateWorkspaceFromOptions(initialMarkup, testOptions))
{
var diagnostics = (await GetDiagnosticsAsync(workspace, testOptions)).ToImmutableArray();
diagnostics = diagnostics.WhereAsArray(d => d.Id == diagnosticId);
Assert.Equal(1, diagnostics.Count());
var hostDocument = workspace.Documents.Single(d => d.SelectedSpans.Any());
var expected = hostDocument.SelectedSpans.Single();
var actual = diagnostics.Single().Location.SourceSpan;
Assert.Equal(expected, actual);
Assert.Equal(diagnosticSeverity, diagnostics.Single().Severity);
if (diagnosticMessage != null)
{
Assert.Equal(diagnosticMessage, diagnostics.Single().GetMessage());
}
}
}
#pragma warning disable CS1574 // XML comment has cref attribute that could not be resolved
/// <summary>
/// The internal method <see cref="AnalyzerExecutor.IsAnalyzerExceptionDiagnostic(Diagnostic)"/> does
/// essentially this, but due to linked files between projects, this project cannot have internals visible
/// access to the Microsoft.CodeAnalysis project without the cascading effect of many extern aliases, so it
/// is re-implemented here in a way that is potentially overly aggressive with the knowledge that if this method
/// starts failing on non-analyzer exception diagnostics, it can be appropriately tuned or re-evaluated.
/// </summary>
private void AssertNoAnalyzerExceptionDiagnostics(IEnumerable<Diagnostic> diagnostics)
#pragma warning restore CS1574 // XML comment has cref attribute that could not be resolved
{
var analyzerExceptionDiagnostics = diagnostics.Where(diag => diag.Descriptor.CustomTags.Contains(WellKnownDiagnosticTags.AnalyzerException));
AssertEx.Empty(analyzerExceptionDiagnostics, "Found analyzer exception diagnostics");
}
// This region provides instances of code fix providers from Features layers, such that the corresponding
// analyzer has been ported to CodeStyle layer, but not the fixer.
// This enables porting the tests for the ported analyzer in CodeStyle layer.
#region CodeFixProvider Helpers
// https://github.com/dotnet/roslyn/issues/43056 blocks porting the fixer to CodeStyle layer.
protected static CodeFixProvider GetMakeLocalFunctionStaticCodeFixProvider() => new MakeLocalFunctionStaticCodeFixProvider();
// https://github.com/dotnet/roslyn/issues/43056 blocks porting the fixer to CodeStyle layer.
protected static CodeFixProvider GetCSharpUseLocalFunctionCodeFixProvider() => new CSharpUseLocalFunctionCodeFixProvider();
// https://github.com/dotnet/roslyn/issues/43091 blocks porting the fixer to CodeStyle layer.
protected static CodeFixProvider GetCSharpUseAutoPropertyCodeFixProvider() => new CSharpUseAutoPropertyCodeFixProvider();
// https://github.com/dotnet/roslyn/issues/43091 blocks porting the fixer to CodeStyle layer.
protected static CodeFixProvider GetVisualBasicUseAutoPropertyCodeFixProvider() => new VisualBasicUseAutoPropertyCodeFixProvider();
#endregion
}
}
| 47.437751 | 153 | 0.663986 | [
"MIT"
] | Dean-ZhenYao-Wang/roslyn | src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractDiagnosticProviderBasedUserDiagnosticTest.cs | 11,814 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.DataBoxEdge.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Kubernetes node IP configuration
/// </summary>
public partial class KubernetesIPConfiguration
{
/// <summary>
/// Initializes a new instance of the KubernetesIPConfiguration class.
/// </summary>
public KubernetesIPConfiguration()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the KubernetesIPConfiguration class.
/// </summary>
/// <param name="port">Port of the Kubernetes node.</param>
/// <param name="ipAddress">IP address of the Kubernetes node.</param>
public KubernetesIPConfiguration(string port = default(string), string ipAddress = default(string))
{
Port = port;
IpAddress = ipAddress;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets port of the Kubernetes node.
/// </summary>
[JsonProperty(PropertyName = "port")]
public string Port { get; private set; }
/// <summary>
/// Gets or sets IP address of the Kubernetes node.
/// </summary>
[JsonProperty(PropertyName = "ipAddress")]
public string IpAddress { get; set; }
}
}
| 31.116667 | 107 | 0.611141 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/databoxedge/Microsoft.Azure.Management.DataBoxEdge/src/Generated/Models/KubernetesIPConfiguration.cs | 1,867 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace StateMachineDesigner.Runtime
{
public class Transition
{
private class TrueCondition : ICondition
{
bool ICondition.Test()
{
return true;
}
}
private ICondition _condition;
private static ICondition TRUE = new TrueCondition();
public bool canInterrupt
{
get;
private set;
}
public bool canTransfer
{
get
{
return _condition.Test();
}
}
public Transition() : this(TRUE, false)
{
}
public Transition(ICondition condition) : this(condition, false)
{
}
public Transition(ICondition condition, bool canInterrupt)
{
_condition = condition;
this.canInterrupt = canInterrupt;
}
}
}
| 20.784314 | 73 | 0.49717 | [
"Apache-2.0"
] | xtaieer/StateMachineDesigner | Assets/Plugins/StateMachineDesigner/Runtime/Transition.cs | 1,062 | C# |
using System.Threading;
using System.Threading.Tasks;
using TypingRealm.Profiles.Activities;
using TypingRealm.Profiles.Api.Client;
namespace TypingRealm.RopeWar.Adapters
{
// TODO: Consider getting rid of this adapter now that we have ICharactersClient.
public sealed class CharacterStateServiceAdapter : ICharacterStateService
{
private readonly IActivitiesClient _activitiesClient;
public CharacterStateServiceAdapter(IActivitiesClient activitiesClient)
{
_activitiesClient = activitiesClient;
}
public async ValueTask<bool> CanJoinRopeWarContestAsync(string characterId, string contestId, CancellationToken cancellationToken)
{
var currentActivity = await _activitiesClient.GetCurrentActivityAsync(characterId, cancellationToken)
.ConfigureAwait(false);
return currentActivity != null
&& currentActivity.ActivityId == contestId
&& currentActivity.Type == ActivityType.RopeWar;
}
}
}
| 36.137931 | 138 | 0.716603 | [
"MIT"
] | ewancoder/typingrealm | TypingRealm.RopeWar/Adapters/CharacterStateServiceAdapter.cs | 1,050 | 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 Memory_Game.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 36.466667 | 152 | 0.566728 | [
"MIT"
] | gabi-sudo/Memory-Game | Memory Game/Properties/Settings.Designer.cs | 1,096 | C# |
namespace NewsSystem.Services.Sources.BgInstitutions
{
using System;
using System.Collections.Generic;
using System.Globalization;
using AngleSharp.Dom;
using NewsSystem.Common;
/// <summary>
/// Комисия за противодействие на корупцията и за отнемане на незаконно придобитото имущество.
/// </summary>
public class CiafGovernmentBgSource : BaseSource
{
public override string BaseUrl { get; } = "http://www.ciaf.government.bg/";
protected override bool UseProxy => true;
public override IEnumerable<RemoteNews> GetLatestPublications() =>
this.GetPublications("news/", "ul.listNews li h2 a", count: 5);
public override IEnumerable<RemoteNews> GetAllPublications()
{
for (var i = 1; i <= 45; i++)
{
var news = this.GetPublications($"news/?page={i}", "ul.listNews li h2 a");
Console.WriteLine($"Page {i} => {news.Count} news");
foreach (var remoteNews in news)
{
yield return remoteNews;
}
}
}
internal override string ExtractIdFromUrl(string url) => url.Split("-")[^1].TrimEnd('/');
protected override RemoteNews ParseDocument(IDocument document, string url)
{
var titleElement = document.QuerySelector(".detailNews h1");
if (titleElement == null)
{
return null;
}
var title = new CultureInfo("bg-BG", false).TextInfo.ToTitleCase(
titleElement.TextContent?.Trim()?.ToLower() ?? string.Empty);
var timeElement = document.QuerySelector(".detailNews .dateNews");
var timeAsString = timeElement.TextContent;
var time = DateTime.ParseExact(timeAsString, "dd.MM.yyyy | HH:mm", CultureInfo.InvariantCulture);
var contentElement = document.QuerySelector(".detailNews .txtNews");
contentElement.RemoveRecursively(document.QuerySelector(".detailNews .iconNews"));
contentElement.RemoveRecursively(document.QuerySelector(".detailNews a.view_more"));
this.NormalizeUrlsRecursively(contentElement);
var content = contentElement.InnerHtml.Trim();
var imageElement = document.QuerySelector(".detailNews .imgNews img");
var imageUrl = imageElement?.GetAttribute("src") ?? "/images/sources/ciaf.government.bg.png";
return new RemoteNews(title, content, time, imageUrl);
}
}
}
| 38.893939 | 109 | 0.615115 | [
"MIT"
] | eognianov/359.news | src/Services/NewsSystem.Services.Sources/BgInstitutions/CiafGovernmentBgSource.cs | 2,647 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("02. BigFactorial")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("02. BigFactorial")]
[assembly: System.Reflection.AssemblyTitleAttribute("02. BigFactorial")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 41.583333 | 80 | 0.647295 | [
"MIT"
] | georgivv7/C-Sharp-Fundamentals-SoftUni | ObjectsClasses-Lab/02. BigFactorial/obj/Debug/netcoreapp3.1/02. BigFactorial.AssemblyInfo.cs | 998 | C# |
using Microsoft.Phone.Controls;
namespace Mvvm.Views
{
public partial class CountryDetails : PhoneApplicationPage
{
public CountryDetails()
{
InitializeComponent();
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
}
}
} | 21.470588 | 95 | 0.583562 | [
"MIT"
] | SevdanurGENC/WindowsIsletimSistemleriTarihcesi | Mvvm/Views/CountryDetails.xaml.cs | 367 | 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 System;
using System.Management.Automation;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Commands.AnalysisServices.Dataplane;
using Microsoft.Azure.Commands.AnalysisServices.Dataplane.Models;
using Microsoft.Azure.Commands.Profile.Models.Core;
using Microsoft.Azure.ServiceManagement.Common.Models;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using Moq;
using Xunit;
using Xunit.Abstractions;
using System.Collections.Generic;
using System.Net.Http.Headers;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.WindowsAzure.Commands.Test.Utilities.Common;
namespace Microsoft.Azure.Commands.AnalysisServices.Test.InMemoryTests
{
public class DataPlaneCommandTests : RMTestBase
{
private const string testInstance = "asazure://westcentralus.asazure.windows.net/testserver";
private const string testToken = "eyJ0eXAiOi"
+ "JKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjFpOWlmMDllc0YzaU9sS0I2SW9meVVGSUxnQSIsImtpZC"
+ "I6IjFpOWlmMDllc0YzaU9sS0I2SW9meVVGSUxnQSJ9.eyJhdWQiOiJodHRwczovL21hbmFnZW1lbnQuY"
+ "29yZS53aW5kb3dzLm5ldC8iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLXBwZS5uZXQvMDQ1NDZiY"
+ "zAtYmMxOS00Y2I2LWIxNmQtNTc0OTQxNzFhNGJjLyIsImlhdCI6MTQ4MDU1NjY0MywibmJmIjoxNDgwN"
+ "TU2NjQzLCJleHAiOjE0ODA1NjA1NDMsImFjciI6IjEiLCJhbXIiOlsicHdkIl0sImFwcGlkIjoiMTk1M"
+ "GEyNTgtMjI3Yi00ZTMxLWE5Y2YtNzE3NDk1OTQ1ZmMyIiwiYXBwaWRhY3IiOiIwIiwiZV9leHAiOjEwO"
+ "DAwLCJmYW1pbHlfbmFtZSI6IlN1c21hbiIsImdpdmVuX25hbWUiOiJEZXJ5YSIsImdyb3VwcyI6WyI0Y"
+ "zNmNjNiNy1mZWU1LTQ1ZWItOTAwMy03YWQ1ZDM5MzMzMDIiXSwiaXBhZGRyIjoiMTY3LjIyMC4wLjExM"
+ "yIsIm5hbWUiOiJEZXJ5YSBTdXNtYW4iLCJvaWQiOiJhODMyOWI5OS01NGI1LTQwNDctOTU5NS1iNWZkN"
+ "2VhMzgyZjYiLCJwbGF0ZiI6IjMiLCJwdWlkIjoiMTAwMzAwMDA5QUJGRTQyRiIsInNjcCI6InVzZXJfa"
+ "W1wZXJzb25hdGlvbiIsInN1YiI6ImEyUE5ZZW9KSnk3VnFFVWVkb0ZxS0J6UUNjOWNUN2tCVWtSYm5BM"
+ "ldLcnciLCJ0aWQiOiIwNDU0NmJjMC1iYzE5LTRjYjYtYjE2ZC01NzQ5NDE3MWE0YmMiLCJ1bmlxdWVfb"
+ "mFtZSI6ImF6dGVzdDBAc3RhYmxldGVzdC5jY3NjdHAubmV0IiwidXBuIjoiYXp0ZXN0MEBzdGFibGV0Z"
+ "XN0LmNjc2N0cC5uZXQiLCJ2ZXIiOiIxLjAiLCJ3aWRzIjpbIjYyZTkwMzk0LTY5ZjUtNDIzNy05MTkwL"
+ "TAxMjE3NzE0NWUxMCJdfQ.W9eVq_TXGBjWCCl_tRGXM31OZn5G4UBIi6B9xZphvrpaAvu5tnzYm6XWah"
+ "jwA_iE1djOpZM3rxFxP4ZFecVyZGHYVddSJ0rg6vw-L4J5jIPDSojqiGoSLtU8yFxEDRaro0SM4LdQ_N"
+ "dF-oUwfUQGy88vLOejQdiKzfC-yFvtVSmYoyJSnkZLglDEbhySvLtjXGfpOgiyGLoncV5wTk6Vbf7VLe"
+ "65kxhZWVUbTHaPuEvg03ZQ3esDb6wxQewJPAL-GARg6S9wIN776Esw8-53AWhzFu0fIut-9FXGma6jV7"
+ "MYPoUUcFuQzLZgphecPyMPXSVhummVCdBwX9sizxnmFA";
public DataPlaneCommandTests(ITestOutputHelper output)
{
XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
SynchronizeAzureAzureAnalysisServer.DefaultRetryIntervalForPolling = TimeSpan.FromSeconds(0);
}
#region TestAuthentication
private class TestAuthenticationCmdlet : AsAzureDataplaneCmdletBase { }
// TODO: this needs a valid mocked context in order to test authentication.
//[Fact]
//[Trait(Category.AcceptanceType, Category.CheckIn)]
//public void Authentication_Succeeds()
//{
// var context = new PSAzureContext();
// TestAuthentication(context);
//}
/// <summary>
/// Assert that cmdlets will fail authentication when provided null context.
/// </summary>
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void Authentication_FailsFromNullContext()
{
Assert.Throws<TargetInvocationException>(() => TestAuthentication(null));
}
/// <summary>
/// Assert that cmdlets will fail authentication when provided bad context.
/// </summary>
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void Authentication_FailsFromBadContext()
{
Assert.Throws<TargetInvocationException>(() => TestAuthentication(new PSAzureContext()));
}
/// <summary>
/// Common code used for testing authentication.
/// </summary>
/// <param name="context"></param>
private void TestAuthentication(IAzureContext context)
{
var cmdlet = new TestAuthenticationCmdlet()
{
CurrentContext = context
};
cmdlet.InvokeBeginProcessing();
cmdlet.InvokeEndProcessing();
}
#endregion
#region TestRestart
/// <summary>
/// Assert that the restart cmdlet will fail if given a null instance.
/// </summary>
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void RestartAzureASInstance_NullInstanceThrows()
{
var restartCmdlet = CreateTestRestartCmdlet(null);
Assert.Throws<TargetInvocationException>(() => restartCmdlet.InvokeBeginProcessing());
}
/// <summary>
/// Assert that the restart cmdlet will fail if given a bad instance url.
/// </summary>
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void RestartAzureASInstance_InvalidInstanceThrows()
{
var restartCmdlet = CreateTestRestartCmdlet("https://bad.uri.com");
Assert.Throws<TargetInvocationException>(() => restartCmdlet.InvokeBeginProcessing());
}
/// <summary>
/// Assert that the restart cmdlet executes successfully.
/// </summary>
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void RestartAzureASInstance_Succeeds()
{
var restartCmdlet = CreateTestRestartCmdlet(testInstance);
// Set up mock http client
var mockHttpClient = new Mock<IAsAzureHttpClient>();
mockHttpClient
.Setup(m => m.CallPostAsync(It.IsAny<string>(), It.IsAny<HttpContent>()))
.Returns(Task<HttpResponseMessage>.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
restartCmdlet.AsAzureDataplaneClient = mockHttpClient.Object;
restartCmdlet.InvokeBeginProcessing();
restartCmdlet.ExecuteCmdlet();
restartCmdlet.InvokeEndProcessing();
}
/// <summary>
/// Create a properly mocked restart cmdlet.
/// </summary>
/// <param name="instance">The test server instance name.</param>
/// <returns>A properly mocked restart cmdlet.</returns>
private static RestartAzureAnalysisServer CreateTestRestartCmdlet(string instance)
{
var commandRuntimeMock = new Mock<ICommandRuntime>();
commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())).Returns(true);
var cmdlet = new RestartAzureAnalysisServer()
{
CommandRuntime = commandRuntimeMock.Object,
Instance = instance
};
return cmdlet;
}
#endregion
#region TestExportLog
/// <summary>
/// Assert that the export cmdlet works.
/// </summary>
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void ExportAzureASInstanceLogTest()
{
var commandRuntimeMock = new Mock<ICommandRuntime>();
commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())).Returns(true);
var mockHttpClient = new Mock<IAsAzureHttpClient>();
mockHttpClient
.Setup(m => m.CallGetAsync(It.IsAny<string>()))
.Returns(Task<HttpResponseMessage>.FromResult(
new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("MOCKED STREAM CONTENT")
}));
var exportCmdlet = new ExportAzureAnalysisServerLog()
{
CommandRuntime = commandRuntimeMock.Object,
Instance = testInstance,
OutputPath = System.IO.Path.GetTempFileName(),
AsAzureDataplaneClient = mockHttpClient.Object
};
try
{
exportCmdlet.InvokeBeginProcessing();
exportCmdlet.ExecuteCmdlet();
exportCmdlet.InvokeEndProcessing();
}
finally
{
if (System.IO.File.Exists(exportCmdlet.OutputPath))
{
System.IO.File.Delete(exportCmdlet.OutputPath);
}
}
}
#endregion
#region TestSync
/// <summary>
/// Assert that the sync cmdlet succeeds syncing a single db instance.
/// </summary>
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void SynchronizeAzureASInstance_SingleDB_Succeeds()
{
var syncCmdlet = CreateTestSyncCmdlet();
syncCmdlet.InvokeBeginProcessing();
syncCmdlet.ExecuteCmdlet();
syncCmdlet.InvokeEndProcessing();
}
/// <summary>
/// Assert that the sync cmdlet will fail after too many retries.
/// </summary>
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void SynchronizeAzureASInstance_FailsAfterTooManyRetries()
{
var syncCmdlet = CreateTestSyncCmdlet(tooManyRetries: true);
syncCmdlet.InvokeBeginProcessing();
Assert.Throws<SynchronizationFailedException>(() => syncCmdlet.ExecuteCmdlet());
syncCmdlet.InvokeEndProcessing();
}
/// <summary>
/// Create a properly mocked Sync cmdlet for testing.
/// </summary>
/// <param name="tooManyRetries">Flag to set the planned failures to be greater than the retry count.</param>
/// <returns>A properly mocked sync cmdlet for testing.</returns>
private SynchronizeAzureAzureAnalysisServer CreateTestSyncCmdlet(bool tooManyRetries = false)
{
// Set up mock http client
var mockHttpClient = new Mock<IAsAzureHttpClient>();
var postResponse = new HttpResponseMessage(HttpStatusCode.Accepted);
postResponse.Headers.Location = new Uri("https://done");
postResponse.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromMilliseconds(500));
postResponse.Headers.Add("x-ms-root-activity-id", Guid.NewGuid().ToString());
postResponse.Headers.Add("x-ms-current-utc-date", Guid.NewGuid().ToString());
mockHttpClient
.Setup(m => m.CallPostAsync(
It.IsAny<Uri>(),
It.Is<string>(s => s.Contains("sync")),
It.IsAny<Guid>(),
null))
.Returns(Task<Mock<HttpResponseMessage>>.FromResult(postResponse));
var getResponse = new HttpResponseMessage(HttpStatusCode.SeeOther);
getResponse.Headers.Location = new Uri("https://done");
getResponse.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromMilliseconds(500));
getResponse.Headers.Add("x-ms-root-activity-id", Guid.NewGuid().ToString());
getResponse.Headers.Add("x-ms-current-utc-date", Guid.NewGuid().ToString());
mockHttpClient
.Setup(m => m.CallGetAsync(
It.Is<Uri>(u => u.OriginalString.Contains("1")),
string.Empty,
It.IsAny<Guid>()))
.Returns(Task<HttpResponseMessage>.FromResult(getResponse));
var getResponseSucceed = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("{\n\"database\":\"db0\",\n\"syncstate\":\"Completed\"\n}", Encoding.UTF8, "application/json")
};
getResponseSucceed.Headers.Add("x-ms-root-activity-id", Guid.NewGuid().ToString());
getResponseSucceed.Headers.Add("x-ms-current-utc-date", Guid.NewGuid().ToString());
var getResponseError = new HttpResponseMessage(HttpStatusCode.InternalServerError);
getResponseError.Headers.Add("x-ms-root-activity-id", Guid.NewGuid().ToString());
getResponseError.Headers.Add("x-ms-current-utc-date", Guid.NewGuid().ToString());
var finalResponses = tooManyRetries ?
new Queue<HttpResponseMessage>(new[] { getResponseError, getResponseError, getResponseError, getResponseSucceed }) :
new Queue<HttpResponseMessage>(new[] { getResponseError, getResponseSucceed });
mockHttpClient
.Setup(m => m.CallGetAsync(
It.Is<Uri>(u => u.OriginalString.Contains("done")),
string.Empty,
It.IsAny<Guid>()))
.Returns(() => Task.FromResult(finalResponses.Dequeue()));
Mock<ICommandRuntime> commandRuntimeMock = new Mock<ICommandRuntime>();
commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())).Returns(true);
var cmdlet = new SynchronizeAzureAzureAnalysisServer()
{
CommandRuntime = commandRuntimeMock.Object,
Instance = testInstance + ":rw",
Database = "db0",
AsAzureDataplaneClient = mockHttpClient.Object
};
return cmdlet;
}
#endregion
}
}
| 47.215805 | 139 | 0.602356 | [
"MIT"
] | AlanFlorance/azure-powershell | src/AnalysisServices/AnalysisServices.Test/InMemoryTests/DataPlaneCommandTests.cs | 15,208 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace IcecatSharp.Infrastructure
{
public static class RequestEngine
{
private static void CreateFolderIfNeeded(string path)
{
if (Directory.Exists(path)) return;
Directory.CreateDirectory(path);
}
private static string GetValidFileName(string fileName)
{
return Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));
}
public static HttpClient CreateClient(IceCatAccessConfig config)
{
var authByteArray = Encoding.ASCII.GetBytes($"{config.Username}:{config.Password}");
var authString = Convert.ToBase64String(authByteArray);
var client = new HttpClient
{
BaseAddress = new Uri(config.BaseUrl)
};
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authString);
return client;
}
public static async Task<string> DownloadFileAsync(HttpClient client, string downloadUrl, string saveFilePath)
{
var saveDirectoryPath = Path.GetDirectoryName(saveFilePath);
CreateFolderIfNeeded(saveDirectoryPath);
var fileName = saveFilePath.Split('\\').Last().ToLower().Trim();
fileName = GetValidFileName(fileName);
var filePath = $"{saveDirectoryPath}\\{fileName}";
using (var response = await client.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead)
.ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
using (var contentStream = await response.Content.ReadAsStreamAsync())
using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
{
//Response.BufferOutput = false; // to prevent buffering
//var totalRead = 0L;
//var totalReads = 0L;
var buffer = new byte[8192];
var isMoreToRead = true;
do
{
var read = await contentStream.ReadAsync(buffer, 0, buffer.Length);
if (read == 0)
{
isMoreToRead = false;
}
else
{
await fileStream.WriteAsync(buffer, 0, read);
//totalRead += read;
//totalReads += 1;
//if (totalReads % 2000 == 0)
//{
// Console.WriteLine(string.Format("total bytes downloaded so far: {0:n0}", totalRead));
//}
}
}
while (isMoreToRead);
}
}
return filePath;
}
public static Task<string> DownloadFileToDirectoryAsync(HttpClient client, string downloadUrl, string saveDirectoryPath)
{
var fileName = downloadUrl.Split('/').Last().ToLower().Trim();
var filePath = $"{saveDirectoryPath}\\{fileName}";
return DownloadFileAsync(client, downloadUrl, filePath);
}
public static async Task<byte[]> GetAsByteAsync(HttpClient client, string url)
{
using (var response = await client.GetAsync(url).ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsByteArrayAsync();
}
}
public static async Task<string> GetAsStringAsync(HttpClient client, string url)
{
using (var response = await client.GetAsync(url).ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
}
}
| 36.923077 | 131 | 0.546759 | [
"MIT"
] | vinhch/IcecatSharp | src/IcecatSharp/Infrastructure/RequestEngine.cs | 4,322 | C# |
using System;
using System.Diagnostics;
namespace CORE_NAME
{
public class MathEx
{
public static bool Add(ref long aRef, long b)
{
long a = aRef;
C.ASSERTCOVERAGE(a == 0);
C.ASSERTCOVERAGE(a == 1);
C.ASSERTCOVERAGE(b == -1);
C.ASSERTCOVERAGE(b == 0);
if (b >= 0)
{
C.ASSERTCOVERAGE(a > 0 && long.MaxValue - a == b);
C.ASSERTCOVERAGE(a > 0 && long.MaxValue - a == b - 1);
if (a > 0 && long.MaxValue - a < b) return true;
aRef += b;
}
else
{
C.ASSERTCOVERAGE(a < 0 && -(a + long.MaxValue) == b + 1);
C.ASSERTCOVERAGE(a < 0 && -(a + long.MaxValue) == b + 2);
if (a < 0 && -(a + long.MaxValue) > b + 1) return true;
aRef += b;
}
return false;
}
public static bool Sub(ref long aRef, long b)
{
C.ASSERTCOVERAGE(b == long.MinValue + 1);
if (b == long.MinValue)
{
long a = aRef;
C.ASSERTCOVERAGE(a == -1);
C.ASSERTCOVERAGE(a == 0);
if (a >= 0) return true;
aRef -= b;
return false;
}
return Add(ref aRef, -b);
}
const long TWOPOWER32 = (((long)1) << 32);
const long TWOPOWER31 = (((long)1) << 31);
public static bool Mul(ref long aRef, long b)
{
long a = aRef;
long a1 = a / TWOPOWER32;
long a0 = a % TWOPOWER32;
long b1 = b / TWOPOWER32;
long b0 = b % TWOPOWER32;
if (a1 * b1 != 0) return true;
Debug.Assert(a1 * b0 == 0 || a0 * b1 == 0);
long r = a1 * b0 + a0 * b1;
C.ASSERTCOVERAGE(r == (-TWOPOWER31) - 1);
C.ASSERTCOVERAGE(r == (-TWOPOWER31));
C.ASSERTCOVERAGE(r == TWOPOWER31);
C.ASSERTCOVERAGE(r == TWOPOWER31 - 1);
if (r < (-TWOPOWER31) || r >= TWOPOWER31) return true;
r *= TWOPOWER32;
if (Add(ref r, a0 * b0)) return true;
aRef = r;
return false;
}
public static int Abs(int x)
{
if (x >= 0) return x;
if (x == (int)0x8000000) return 0x7fffffff;
return -x;
}
}
} | 33.773333 | 74 | 0.409791 | [
"MIT"
] | BclEx/GpuEx | src/Runtime.net/Runtime+Math.cs | 2,533 | C# |
namespace Projector.Specs
{
using System;
using NUnit.Framework;
[TestFixture]
public class NameRestrictionTests
{
// Other tests in xxxxCutTests
[Test]
public void OnNullTypeCut()
{
Assert.Throws<ArgumentNullException>
(
() => (null as ITypeCut).Named("A")
)
.ForParameter("cut");
}
[Test]
public void OnNullPropertyCut()
{
Assert.Throws<ArgumentNullException>
(
() => (null as IPropertyCut).Named("A")
)
.ForParameter("cut");
}
[Test]
public void Construct_NullName()
{
Assert.Throws<ArgumentNullException>
(
() => new NameRestriction(null, StringComparison.Ordinal)
)
.ForParameter("name");
}
[Test]
public void ToStringMethod()
{
var restriction = new NameRestriction("SomeName", StringComparison.Ordinal);
var text = restriction.ToString();
Assert.That(text, Is.EqualTo("name equals 'SomeName' via Ordinal comparison"));
}
}
}
| 23.615385 | 91 | 0.5057 | [
"Apache-2.0"
] | sharpjs/Projector | Projector.Tests/Specs/Restrictions/NameRestrictionTests.cs | 1,230 | C# |
using UnityEngine;
public abstract class Pig : MonoBehaviour
{
private EnemiesHolder _enemiesHolder;
protected bool IsActive;
private void Awake()
{
_enemiesHolder = transform.parent.GetComponent<EnemiesHolder>();
}
private void OnEnable()
{
_enemiesHolder.RoomChangeStatus += OnRoomChangeStatus;
}
private void OnDisable()
{
_enemiesHolder.RoomChangeStatus -= OnRoomChangeStatus;
}
private void OnRoomChangeStatus(bool roomStatus)
{
IsActive = roomStatus;
}
}
| 19.206897 | 72 | 0.667864 | [
"MIT"
] | wladweb/Kings-Pigs | Assets/Scripts/Pigs/Pig.cs | 559 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using Azure.Core;
namespace Azure.ResourceManager.Network.Models
{
/// <summary> VirtualHub route. </summary>
public partial class VirtualHubRoute
{
/// <summary> Initializes a new instance of VirtualHubRoute. </summary>
public VirtualHubRoute()
{
AddressPrefixes = new ChangeTrackingList<string>();
}
/// <summary> Initializes a new instance of VirtualHubRoute. </summary>
/// <param name="addressPrefixes"> List of all addressPrefixes. </param>
/// <param name="nextHopIPAddress"> NextHop ip address. </param>
internal VirtualHubRoute(IList<string> addressPrefixes, string nextHopIPAddress)
{
AddressPrefixes = addressPrefixes;
NextHopIPAddress = nextHopIPAddress;
}
/// <summary> List of all addressPrefixes. </summary>
public IList<string> AddressPrefixes { get; }
/// <summary> NextHop ip address. </summary>
public string NextHopIPAddress { get; set; }
}
}
| 32.486486 | 88 | 0.655574 | [
"MIT"
] | AikoBB/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/Models/VirtualHubRoute.cs | 1,202 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using LanguageExt;
namespace GoDaddy.Asherah.AppEncryption.Persistence
{
/// <summary>
/// Provides a volatile implementation of <see cref="IMetastore{T}"/> for values using a
/// <see cref="System.Data.DataTable"/>. NOTE: This should NEVER be used in a production environment.
/// </summary>
///
/// <typeparam name="T">The type of value to store and retrieve.</typeparam>
public class InMemoryMetastoreImpl<T> : IMetastore<T>
{
private readonly DataTable dataTable;
/// <summary>
/// Initializes a new instance of the <see cref="InMemoryMetastoreImpl{T}"/> class, with 3 columns.
/// <code>
/// keyId | created | value
/// ----- | ------- | ------
/// | |
/// | |
/// </code>
/// Uses 'keyId' and 'created' as the primary key.
/// </summary>
public InMemoryMetastoreImpl()
{
dataTable = new DataTable();
dataTable.Columns.Add("keyId", typeof(string));
dataTable.Columns.Add("created", typeof(DateTimeOffset));
dataTable.Columns.Add("value", typeof(T));
dataTable.PrimaryKey = new[] { dataTable.Columns["keyId"], dataTable.Columns["created"] };
}
/// <inheritdoc />
public virtual Option<T> Load(string keyId, DateTimeOffset created)
{
lock (dataTable)
{
List<DataRow> dataRows = dataTable.Rows.Cast<DataRow>()
.Where(row => row["keyId"].Equals(keyId)
&& row["created"].Equals(created))
.ToList();
if (!dataRows.Any())
{
return Option<T>.None;
}
return (T)dataRows.Single()["value"];
}
}
/// <summary>
/// Obtain the latest value associated with the keyId by ordering the datatable in ascending order.
/// </summary>
///
/// <param name="keyId">The keyId to lookup.</param>
/// <returns>The latest <see cref="T"/> value associated with the keyId, if any.</returns>
public virtual Option<T> LoadLatest(string keyId)
{
lock (dataTable)
{
List<DataRow> dataRows = dataTable.Rows.Cast<DataRow>()
.Where(row => row["keyId"].Equals(keyId))
.OrderBy(row => row["created"])
.ToList();
// Need to check if empty as Last will throw an exception instead of returning null
if (!dataRows.Any())
{
return Option<T>.None;
}
return (T)dataRows.Last()["value"];
}
}
/// <inheritdoc />
public virtual bool Store(string keyId, DateTimeOffset created, T value)
{
lock (dataTable)
{
List<DataRow> dataRows = dataTable.Rows.Cast<DataRow>()
.Where(row => row["keyId"].Equals(keyId)
&& row["created"].Equals(created))
.ToList();
if (dataRows.Any())
{
return false;
}
dataTable.Rows.Add(keyId, created, value);
return true;
}
}
}
}
| 34.881188 | 107 | 0.493613 | [
"MIT"
] | aka-bo/asherah | csharp/AppEncryption/AppEncryption/Persistence/InMemoryMetastoreImpl.cs | 3,523 | C# |
using System;
namespace CrystalQuartz.Web.DemoOwin.Areas.HelpPage
{
/// <summary>
/// This represents a preformatted text sample on the help page. There's a display template named TextSample associated with this class.
/// </summary>
public class TextSample
{
public TextSample(string text)
{
if (text == null)
{
throw new ArgumentNullException("text");
}
Text = text;
}
public string Text { get; private set; }
public override bool Equals(object obj)
{
TextSample other = obj as TextSample;
return other != null && Text == other.Text;
}
public override int GetHashCode()
{
return Text.GetHashCode();
}
public override string ToString()
{
return Text;
}
}
} | 24.378378 | 140 | 0.538803 | [
"MIT"
] | DHindemith/CrystalQuartz | src/CrystalQuartz.Web.DemoOwin/Areas/HelpPage/SampleGeneration/TextSample.cs | 902 | C# |
using System.IO;
namespace Symlinker
{
public class TargetNames
{
public TargetNames(string relativePath, string parentRootPath)
{
RelativePath = relativePath;
ParentRootPath = parentRootPath;
}
public string RelativePath { get; set; }
public string ParentRootPath { get; set; }
public string AbsolutePath
{
get
{
return Path.Combine(ParentRootPath, RelativePath);
}
}
}
} | 19.703704 | 70 | 0.548872 | [
"Apache-2.0"
] | fengyuan213/symlinker | Symlinker/TargetNames.cs | 534 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Framework")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Framework")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2009")]
[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("f92b0fd1-a64d-4e89-b360-2fd0a6c52768")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39 | 85 | 0.732194 | [
"Apache-2.0"
] | Anupam-/fubumvc-contrib | samples/FubuTask/src/Framework/Properties/AssemblyInfo.cs | 1,407 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PowerAppsPortalsFileSync.Model
{
public class WebSite
{
[JsonProperty("adx_websiteid")]
public Guid WebSiteId { get; set; }
[JsonProperty("adx_name")]
public string Name { get; set; }
}
}
| 20.210526 | 43 | 0.682292 | [
"MIT"
] | joriskalz/power-apps-portal-file-sync | PowerAppsPortalsFileSync/PowerAppsPortalsFileSync/Model/WebSite.cs | 386 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using static Dna.FrameworkDI;
namespace Dna
{
/// <summary>
/// <para>
/// Provides a thread-safe mechanism for starting and stopping the execution of an task
/// that can only have one instance of itself running regardless of the amount of times
/// start/stop is called and from what thread.
/// </para>
/// <para>
/// Supports cancellation requests via the <see cref="StopAsync"/> and the given task
/// will be provided with a cancellation token to monitor for when it should "stop"
/// </para>
/// </summary>
public abstract class SingleTaskWorker
{
#region Protected Members
/// <summary>
/// A flag indicating if the worker task is still running
/// </summary>
protected ManualResetEvent mWorkerFinishedEvent = new ManualResetEvent(true);
/// <summary>
/// The token used to cancel any ongoing work in order to shutdown
/// </summary>
protected CancellationTokenSource mCancellationToken = new CancellationTokenSource();
#endregion
#region Public Properties
/// <summary>
/// A unique ID for locking the starting and stopping calls of this class
/// </summary>
public string LockingKey { get; set; } = nameof(SingleTaskWorker) + Guid.NewGuid().ToString("N");
/// <summary>
/// The name that identifies this worker (used in unhandled exception logs to report source of an issue)
/// </summary>
public abstract string WorkerName { get; }
/// <summary>
/// Indicates if the service is shutting down and should finish what it's doing and save any important information/progress
/// </summary>
public bool Stopping => mCancellationToken.IsCancellationRequested;
/// <summary>
/// Indicates if the main worker task is running
/// </summary>
public bool IsRunning
{
// We are running if we haven't finished
get => !mWorkerFinishedEvent.WaitOne(0);
set
{
// If we are running...
if (value)
// Then we have not finished
mWorkerFinishedEvent.Reset();
// If we want to stop running...
else
// We should call ShutdownAsync instead
throw new InvalidOperationException($"Use {nameof(StopAsync)} instead");
}
}
#endregion
#region Constructor
/// <summary>
/// Default constructor
/// </summary>
public SingleTaskWorker()
{
}
#endregion
#region Startup / Shutdown
/// <summary>
/// Starts the given task running if it is not already running
/// </summary>
/// <returns></returns>
public Task<bool> StartAsync()
{
// Log it
Logger.LogTraceSource($"Start requested...");
// Make sure only one start or stop call runs at a time...
return AsyncLock.LockResultAsync(LockingKey, () =>
{
// If we are already running...
if (IsRunning)
{
// Log it
Logger.LogTraceSource($"Already started. Ignoring.");
// We are not starting a new task
return false;
}
// New cancellation token
mCancellationToken = new CancellationTokenSource();
// Flag that we are running
IsRunning = true;
// Log it
Logger.LogTraceSource($"Starting worker process...");
// Start the main task
RunWorkerTaskNoAwait();
// We have started a new task
return true;
});
}
/// <summary>
/// Requests that the given task should stop running, and awaits for it to finish
/// </summary>
/// <returns>Returns once the worker task has returned</returns>
public Task StopAsync()
{
// Make sure only one startup or shutdown call runs at a time...
return AsyncLock.LockAsync(LockingKey, async () =>
{
// If we are not running...
if (!IsRunning)
{
// Log it
Logger.LogTraceSource($"Already stopped. Ignoring.");
// Ignore
return;
}
// Log it
Logger.LogTraceSource($"Stop requested...");
// Flag main worker to shut down
mCancellationToken.Cancel();
// Wait for it to stop running
await mWorkerFinishedEvent.WaitOneAsync();
});
}
#endregion
#region Worker Task
/// <summary>
/// Runs the worker task and sets the IsRunning to false once complete
/// </summary>
/// <returns>Returns once the worker task has completed</returns>
protected void RunWorkerTaskNoAwait()
{
// IMPORTANT: Not awaiting a Task leads to swallowed exceptions
// so we try/catch the entire task and report any unhandled
// exceptions to the log
Task.Run(async () =>
{
try
{
// Log something
Logger.LogTraceSource($"Worker task started...");
// Run given task
await WorkerTaskAsync(mCancellationToken.Token);
}
// Swallow expected and normal task canceled exceptions
catch (TaskCanceledException) { }
catch (Exception ex)
{
// Unhandled exception
// Log it
Logger.LogCriticalSource($"Unhandled exception in single task worker '{WorkerName}'. {ex}");
}
finally
{
// Log it
Logger.LogTraceSource($"Worker task finished");
// Set finished event informing waiters we are finished working
mWorkerFinishedEvent.Set();
}
});
}
/// <summary>
/// The task that will be run by this worker
/// </summary>
protected virtual Task WorkerTaskAsync(CancellationToken cancellationToken)
{
return Task.FromResult(0);
}
#endregion
}
} | 32.645933 | 131 | 0.515756 | [
"MIT"
] | BowenA96/dna-framework | Source/Dna.Framework/Tasks/SingleTaskWorker.cs | 6,825 | C# |
using System;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using DynamicData.Kernel;
namespace DynamicData.Cache.Internal
{
internal class TransformAsync<TDestination, TSource, TKey>
{
private readonly IObservable<IChangeSet<TSource, TKey>> _source;
private readonly Func<TSource, Optional<TSource>, TKey, Task<TDestination>> _transformFactory;
private readonly IObservable<Func<TSource, TKey, bool>> _forceTransform;
private readonly Action<Error<TSource, TKey>> _exceptionCallback;
private readonly int _maximumConcurrency;
public TransformAsync(IObservable<IChangeSet<TSource, TKey>> source, Func<TSource, Optional<TSource>, TKey, Task<TDestination>> transformFactory, Action<Error<TSource, TKey>> exceptionCallback, int maximumConcurrency = 1, IObservable<Func<TSource, TKey, bool>> forceTransform = null)
{
_source = source;
_exceptionCallback = exceptionCallback;
_transformFactory = transformFactory;
_maximumConcurrency = maximumConcurrency;
_forceTransform = forceTransform;
}
public IObservable<IChangeSet<TDestination, TKey>> Run()
{
return Observable.Create<IChangeSet<TDestination, TKey>>(observer =>
{
var cache = new ChangeAwareCache<TransformedItemContainer, TKey>();
var transformer = _source.SelectTask(changes => DoTransform(cache, changes));
if (_forceTransform != null)
{
var locker = new object();
var forced = _forceTransform
.Synchronize(locker)
.SelectTask(shouldTransform => DoTransform(cache, shouldTransform));
transformer = transformer.Synchronize(locker).Merge(forced);
}
return transformer.SubscribeSafe(observer);
});
}
private async Task<IChangeSet<TDestination, TKey>> DoTransform(ChangeAwareCache<TransformedItemContainer, TKey> cache, Func<TSource, TKey, bool> shouldTransform)
{
var toTransform = cache.KeyValues
.Where(kvp => shouldTransform(kvp.Value.Source, kvp.Key))
.Select(kvp => new Change<TSource,TKey>(ChangeReason.Update, kvp.Key, kvp.Value.Source, kvp.Value.Source))
.ToArray();
var transformed = await toTransform.SelectParallel(Transform, _maximumConcurrency);
return ProcessUpdates(cache, transformed.ToArray());
}
private async Task<IChangeSet<TDestination, TKey>> DoTransform(ChangeAwareCache<TransformedItemContainer, TKey> cache, IChangeSet<TSource, TKey> changes )
{
var transformed = await changes.SelectParallel(Transform, _maximumConcurrency);
return ProcessUpdates(cache, transformed.ToArray());
}
private async Task<TransformResult> Transform(Change<TSource, TKey> change)
{
try
{
if (change.Reason == ChangeReason.Add || change.Reason == ChangeReason.Update)
{
var destination = await _transformFactory(change.Current, change.Previous, change.Key);
return new TransformResult(change, new TransformedItemContainer(change.Current, destination));
}
return new TransformResult(change);
}
catch (Exception ex)
{
//only handle errors if a handler has been specified
if (_exceptionCallback != null)
return new TransformResult(change, ex);
throw;
}
}
private IChangeSet<TDestination, TKey> ProcessUpdates(ChangeAwareCache<TransformedItemContainer, TKey> cache, TransformResult[] transformedItems)
{
//check for errors and callback if a handler has been specified
var errors = transformedItems.Where(t => !t.Success).ToArray();
if (errors.Any())
errors.ForEach(t => _exceptionCallback(new Error<TSource, TKey>(t.Error, t.Change.Current, t.Change.Key)));
foreach (var result in transformedItems.Where(t => t.Success))
{
TKey key = result.Key;
switch (result.Change.Reason)
{
case ChangeReason.Add:
case ChangeReason.Update:
cache.AddOrUpdate(result.Container.Value, key);
break;
case ChangeReason.Remove:
cache.Remove(key);
break;
case ChangeReason.Refresh:
cache.Refresh(key);
break;
}
}
var changes = cache.CaptureChanges();
var transformed = changes.Select(change => new Change<TDestination, TKey>(change.Reason,
change.Key,
change.Current.Destination,
change.Previous.Convert(x => x.Destination),
change.CurrentIndex,
change.PreviousIndex));
return new ChangeSet<TDestination, TKey>(transformed);
}
private sealed class TransformResult
{
public Change<TSource, TKey> Change { get; }
public Exception Error { get; }
public bool Success { get; }
public Optional<TransformedItemContainer> Container { get; }
public TKey Key { get; }
public TransformResult(Change<TSource, TKey> change, TransformedItemContainer container)
{
Change = change;
Container = container;
Success = true;
Key = change.Key;
}
public TransformResult(Change<TSource, TKey> change)
{
Change = change;
Container = Optional<TransformedItemContainer>.None;
Success = true;
Key = change.Key;
}
public TransformResult(Change<TSource, TKey> change, Exception error)
{
Change = change;
Error = error;
Success = false;
Key = change.Key;
}
}
private readonly struct TransformedItemContainer
{
public TSource Source { get; }
public TDestination Destination { get; }
public TransformedItemContainer(TSource source, TDestination destination)
{
Source = source;
Destination = destination;
}
}
}
} | 40.732143 | 291 | 0.571533 | [
"MIT"
] | Didovgopoly/DynamicData | DynamicData/Cache/Internal/TransformAsync.cs | 6,845 | C# |
using Windows.UI.Xaml.Controls;
using SamplesApp.Windows_UI_Xaml_Controls.Models;
using Uno.UI.Samples.Controls;
namespace SamplesApp.Windows_UI_Xaml_Controls.ListView
{
[SampleControlInfo("ListView", "HorizontalListViewImage", typeof(ImageListViewViewModel))]
public sealed partial class HorizontalListViewImage : UserControl
{
public HorizontalListViewImage()
{
this.InitializeComponent();
}
}
}
| 25.75 | 91 | 0.808252 | [
"Apache-2.0"
] | 06needhamt/uno | src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/ListView/HorizontalListViewImage.xaml.cs | 412 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Buffers;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if NETSTANDARD2_1_OR_GREATER
using CommunityToolkit.HighPerformance.Buffers.Internals;
#endif
using CommunityToolkit.HighPerformance.Helpers;
using CommunityToolkit.HighPerformance.Memory.Internals;
using CommunityToolkit.HighPerformance.Memory.Views;
using static CommunityToolkit.HighPerformance.Helpers.Internals.RuntimeHelpers;
#pragma warning disable CA2231
namespace CommunityToolkit.HighPerformance;
/// <summary>
/// <see cref="Memory2D{T}"/> represents a 2D region of arbitrary memory. It is to <see cref="Span2D{T}"/>
/// what <see cref="Memory{T}"/> is to <see cref="Span{T}"/>. For further details on how the internal layout
/// is structured, see the docs for <see cref="Span2D{T}"/>. The <see cref="Memory2D{T}"/> type can wrap arrays
/// of any rank, provided that a valid series of parameters for the target memory area(s) are specified.
/// </summary>
/// <typeparam name="T">The type of items in the current <see cref="Memory2D{T}"/> instance.</typeparam>
[DebuggerTypeProxy(typeof(MemoryDebugView2D<>))]
[DebuggerDisplay("{ToString(),raw}")]
public readonly struct Memory2D<T> : IEquatable<Memory2D<T>>
{
/// <summary>
/// The target <see cref="object"/> instance, if present.
/// </summary>
private readonly object? instance;
/// <summary>
/// The initial offset within <see cref="instance"/>.
/// </summary>
private readonly IntPtr offset;
/// <summary>
/// The height of the specified 2D region.
/// </summary>
private readonly int height;
/// <summary>
/// The width of the specified 2D region.
/// </summary>
private readonly int width;
/// <summary>
/// The pitch of the specified 2D region.
/// </summary>
private readonly int pitch;
/// <summary>
/// Initializes a new instance of the <see cref="Memory2D{T}"/> struct.
/// </summary>
/// <param name="array">The target array to wrap.</param>
/// <param name="height">The height of the resulting 2D area.</param>
/// <param name="width">The width of each row in the resulting 2D area.</param>
/// <exception cref="ArrayTypeMismatchException">
/// Thrown when <paramref name="array"/> doesn't match <typeparamref name="T"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// Thrown when either <paramref name="height"/> or <paramref name="width"/> are invalid.
/// </exception>
/// <remarks>The total area must match the length of <paramref name="array"/>.</remarks>
public Memory2D(T[] array, int height, int width)
: this(array, 0, height, width, 0)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Memory2D{T}"/> struct.
/// </summary>
/// <param name="array">The target array to wrap.</param>
/// <param name="offset">The initial offset within <paramref name="array"/>.</param>
/// <param name="height">The height of the resulting 2D area.</param>
/// <param name="width">The width of each row in the resulting 2D area.</param>
/// <param name="pitch">The pitch in the resulting 2D area.</param>
/// <exception cref="ArrayTypeMismatchException">
/// Thrown when <paramref name="array"/> doesn't match <typeparamref name="T"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when one of the input parameters is out of range.
/// </exception>
/// <exception cref="ArgumentException">
/// Thrown when the requested area is outside of bounds for <paramref name="array"/>.
/// </exception>
public Memory2D(T[] array, int offset, int height, int width, int pitch)
{
if (array.IsCovariant())
{
ThrowHelper.ThrowArrayTypeMismatchException();
}
if ((uint)offset > (uint)array.Length)
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForOffset();
}
if (height < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForHeight();
}
if (width < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForWidth();
}
if (pitch < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForPitch();
}
int area = OverflowHelper.ComputeInt32Area(height, width, pitch);
int remaining = array.Length - offset;
if (area > remaining)
{
ThrowHelper.ThrowArgumentException();
}
this.instance = array;
this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(offset));
this.height = height;
this.width = width;
this.pitch = pitch;
}
/// <summary>
/// Initializes a new instance of the <see cref="Memory2D{T}"/> struct wrapping a 2D array.
/// </summary>
/// <param name="array">The given 2D array to wrap.</param>
/// <exception cref="ArrayTypeMismatchException">
/// Thrown when <paramref name="array"/> doesn't match <typeparamref name="T"/>.
/// </exception>
public Memory2D(T[,]? array)
{
if (array is null)
{
this = default;
return;
}
if (array.IsCovariant())
{
ThrowHelper.ThrowArrayTypeMismatchException();
}
this.instance = array;
this.offset = GetArray2DDataByteOffset<T>();
this.height = array.GetLength(0);
this.width = array.GetLength(1);
this.pitch = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="Memory2D{T}"/> struct wrapping a 2D array.
/// </summary>
/// <param name="array">The given 2D array to wrap.</param>
/// <param name="row">The target row to map within <paramref name="array"/>.</param>
/// <param name="column">The target column to map within <paramref name="array"/>.</param>
/// <param name="height">The height to map within <paramref name="array"/>.</param>
/// <param name="width">The width to map within <paramref name="array"/>.</param>
/// <exception cref="ArrayTypeMismatchException">
/// Thrown when <paramref name="array"/> doesn't match <typeparamref name="T"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when either <paramref name="height"/>, <paramref name="width"/> or <paramref name="height"/>
/// are negative or not within the bounds that are valid for <paramref name="array"/>.
/// </exception>
public Memory2D(T[,]? array, int row, int column, int height, int width)
{
if (array is null)
{
if (row != 0 || column != 0 || height != 0 || width != 0)
{
ThrowHelper.ThrowArgumentException();
}
this = default;
return;
}
if (array.IsCovariant())
{
ThrowHelper.ThrowArrayTypeMismatchException();
}
int rows = array.GetLength(0);
int columns = array.GetLength(1);
if ((uint)row >= (uint)rows)
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForRow();
}
if ((uint)column >= (uint)columns)
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForColumn();
}
if ((uint)height > (uint)(rows - row))
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForHeight();
}
if ((uint)width > (uint)(columns - column))
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForWidth();
}
this.instance = array;
this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(row, column));
this.height = height;
this.width = width;
this.pitch = columns - width;
}
/// <summary>
/// Initializes a new instance of the <see cref="Memory2D{T}"/> struct wrapping a layer in a 3D array.
/// </summary>
/// <param name="array">The given 3D array to wrap.</param>
/// <param name="depth">The target layer to map within <paramref name="array"/>.</param>
/// <exception cref="ArrayTypeMismatchException">
/// Thrown when <paramref name="array"/> doesn't match <typeparamref name="T"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when a parameter is invalid.</exception>
public Memory2D(T[,,] array, int depth)
{
if (array.IsCovariant())
{
ThrowHelper.ThrowArrayTypeMismatchException();
}
if ((uint)depth >= (uint)array.GetLength(0))
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForDepth();
}
this.instance = array;
this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(depth, 0, 0));
this.height = array.GetLength(1);
this.width = array.GetLength(2);
this.pitch = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="Memory2D{T}"/> struct wrapping a layer in a 3D array.
/// </summary>
/// <param name="array">The given 3D array to wrap.</param>
/// <param name="depth">The target layer to map within <paramref name="array"/>.</param>
/// <param name="row">The target row to map within <paramref name="array"/>.</param>
/// <param name="column">The target column to map within <paramref name="array"/>.</param>
/// <param name="height">The height to map within <paramref name="array"/>.</param>
/// <param name="width">The width to map within <paramref name="array"/>.</param>
/// <exception cref="ArrayTypeMismatchException">
/// Thrown when <paramref name="array"/> doesn't match <typeparamref name="T"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when a parameter is invalid.</exception>
public Memory2D(T[,,] array, int depth, int row, int column, int height, int width)
{
if (array.IsCovariant())
{
ThrowHelper.ThrowArrayTypeMismatchException();
}
if ((uint)depth >= (uint)array.GetLength(0))
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForDepth();
}
int rows = array.GetLength(1);
int columns = array.GetLength(2);
if ((uint)row >= (uint)rows)
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForRow();
}
if ((uint)column >= (uint)columns)
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForColumn();
}
if ((uint)height > (uint)(rows - row))
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForHeight();
}
if ((uint)width > (uint)(columns - column))
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForWidth();
}
this.instance = array;
this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(depth, row, column));
this.height = height;
this.width = width;
this.pitch = columns - width;
}
#if NETSTANDARD2_1_OR_GREATER
/// <summary>
/// Initializes a new instance of the <see cref="Memory2D{T}"/> struct.
/// </summary>
/// <param name="memoryManager">The target <see cref="MemoryManager{T}"/> to wrap.</param>
/// <param name="height">The height of the resulting 2D area.</param>
/// <param name="width">The width of each row in the resulting 2D area.</param>
/// <exception cref="ArgumentException">
/// Thrown when either <paramref name="height"/> or <paramref name="width"/> are invalid.
/// </exception>
/// <remarks>The total area must match the length of <paramref name="memoryManager"/>.</remarks>
public Memory2D(MemoryManager<T> memoryManager, int height, int width)
: this(memoryManager, 0, height, width, 0)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Memory2D{T}"/> struct.
/// </summary>
/// <param name="memoryManager">The target <see cref="MemoryManager{T}"/> to wrap.</param>
/// <param name="offset">The initial offset within <paramref name="memoryManager"/>.</param>
/// <param name="height">The height of the resulting 2D area.</param>
/// <param name="width">The width of each row in the resulting 2D area.</param>
/// <param name="pitch">The pitch in the resulting 2D area.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when one of the input parameters is out of range.
/// </exception>
/// <exception cref="ArgumentException">
/// Thrown when the requested area is outside of bounds for <paramref name="memoryManager"/>.
/// </exception>
public Memory2D(MemoryManager<T> memoryManager, int offset, int height, int width, int pitch)
{
int length = memoryManager.GetSpan().Length;
if ((uint)offset > (uint)length)
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForOffset();
}
if (height < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForHeight();
}
if (width < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForWidth();
}
if (pitch < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForPitch();
}
if (width == 0 || height == 0)
{
this = default;
return;
}
int area = OverflowHelper.ComputeInt32Area(height, width, pitch);
int remaining = length - offset;
if (area > remaining)
{
ThrowHelper.ThrowArgumentException();
}
this.instance = memoryManager;
this.offset = (nint)(uint)offset;
this.height = height;
this.width = width;
this.pitch = pitch;
}
/// <summary>
/// Initializes a new instance of the <see cref="Memory2D{T}"/> struct.
/// </summary>
/// <param name="memory">The target <see cref="Memory{T}"/> to wrap.</param>
/// <param name="height">The height of the resulting 2D area.</param>
/// <param name="width">The width of each row in the resulting 2D area.</param>
/// <exception cref="ArgumentException">
/// Thrown when either <paramref name="height"/> or <paramref name="width"/> are invalid.
/// </exception>
/// <remarks>The total area must match the length of <paramref name="memory"/>.</remarks>
internal Memory2D(Memory<T> memory, int height, int width)
: this(memory, 0, height, width, 0)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Memory2D{T}"/> struct.
/// </summary>
/// <param name="memory">The target <see cref="Memory{T}"/> to wrap.</param>
/// <param name="offset">The initial offset within <paramref name="memory"/>.</param>
/// <param name="height">The height of the resulting 2D area.</param>
/// <param name="width">The width of each row in the resulting 2D area.</param>
/// <param name="pitch">The pitch in the resulting 2D area.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when one of the input parameters is out of range.
/// </exception>
/// <exception cref="ArgumentException">
/// Thrown when the requested area is outside of bounds for <paramref name="memory"/>.
/// </exception>
internal Memory2D(Memory<T> memory, int offset, int height, int width, int pitch)
{
if ((uint)offset > (uint)memory.Length)
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForOffset();
}
if (height < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForHeight();
}
if (width < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForWidth();
}
if (pitch < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForPitch();
}
if (width == 0 || height == 0)
{
this = default;
return;
}
int
area = OverflowHelper.ComputeInt32Area(height, width, pitch),
remaining = memory.Length - offset;
if (area > remaining)
{
ThrowHelper.ThrowArgumentException();
}
// Check if the Memory<T> instance wraps a string. This is possible in case
// consumers do an unsafe cast for the entire Memory<T> object, and while not
// really safe it is still supported in CoreCLR too, so we're following suit here.
if (typeof(T) == typeof(char) &&
MemoryMarshal.TryGetString(Unsafe.As<Memory<T>, Memory<char>>(ref memory), out string? text, out int textStart, out _))
{
ref char r0 = ref text.DangerousGetReferenceAt(textStart + offset);
this.instance = text;
this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(text, ref r0);
}
else if (MemoryMarshal.TryGetArray(memory, out ArraySegment<T> segment))
{
// Check if the input Memory<T> instance wraps an array we can access.
// This is fine, since Memory<T> on its own doesn't control the lifetime
// of the underlying array anyway, and this Memory2D<T> type would do the same.
// Using the array directly makes retrieving a Span2D<T> faster down the line,
// as we no longer have to jump through the boxed Memory<T> first anymore.
T[] array = segment.Array!;
this.instance = array;
this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(segment.Offset + offset));
}
else if (MemoryMarshal.TryGetMemoryManager<T, MemoryManager<T>>(memory, out MemoryManager<T>? memoryManager, out int memoryManagerStart, out _))
{
this.instance = memoryManager;
this.offset = (nint)(uint)(memoryManagerStart + offset);
}
else
{
ThrowHelper.ThrowArgumentExceptionForUnsupportedType();
this.instance = null;
this.offset = default;
}
this.height = height;
this.width = width;
this.pitch = pitch;
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref="Memory2D{T}"/> struct with the specified parameters.
/// </summary>
/// <param name="instance">The target <see cref="object"/> instance.</param>
/// <param name="offset">The initial offset within <see cref="instance"/>.</param>
/// <param name="height">The height of the 2D memory area to map.</param>
/// <param name="width">The width of the 2D memory area to map.</param>
/// <param name="pitch">The pitch of the 2D memory area to map.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private Memory2D(object instance, IntPtr offset, int height, int width, int pitch)
{
this.instance = instance;
this.offset = offset;
this.height = height;
this.width = width;
this.pitch = pitch;
}
/// <summary>
/// Creates a new <see cref="Memory2D{T}"/> instance from an arbitrary object.
/// </summary>
/// <param name="instance">The <see cref="object"/> instance holding the data to map.</param>
/// <param name="value">The target reference to point to (it must be within <paramref name="instance"/>).</param>
/// <param name="height">The height of the 2D memory area to map.</param>
/// <param name="width">The width of the 2D memory area to map.</param>
/// <param name="pitch">The pitch of the 2D memory area to map.</param>
/// <returns>A <see cref="Memory2D{T}"/> instance with the specified parameters.</returns>
/// <remarks>The <paramref name="value"/> parameter is not validated, and it's responsibility of the caller to ensure it's valid.</remarks>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when one of the input parameters is out of range.
/// </exception>
public static Memory2D<T> DangerousCreate(object instance, ref T value, int height, int width, int pitch)
{
if (height < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForHeight();
}
if (width < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForWidth();
}
if (pitch < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForPitch();
}
OverflowHelper.EnsureIsInNativeIntRange(height, width, pitch);
IntPtr offset = ObjectMarshal.DangerousGetObjectDataByteOffset(instance, ref value);
return new(instance, offset, height, width, pitch);
}
/// <summary>
/// Gets an empty <see cref="Memory2D{T}"/> instance.
/// </summary>
public static Memory2D<T> Empty => default;
/// <summary>
/// Gets a value indicating whether the current <see cref="Memory2D{T}"/> instance is empty.
/// </summary>
public bool IsEmpty
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => this.height == 0 || this.width == 0;
}
/// <summary>
/// Gets the length of the current <see cref="Memory2D{T}"/> instance.
/// </summary>
public nint Length
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (nint)(uint)this.height * (nint)(uint)this.width;
}
/// <summary>
/// Gets the height of the underlying 2D memory area.
/// </summary>
public int Height
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => this.height;
}
/// <summary>
/// Gets the width of the underlying 2D memory area.
/// </summary>
public int Width
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => this.width;
}
/// <summary>
/// Gets a <see cref="Span2D{T}"/> instance from the current memory.
/// </summary>
public Span2D<T> Span
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (this.instance is not null)
{
#if NETSTANDARD2_1_OR_GREATER
if (this.instance is MemoryManager<T> memoryManager)
{
ref T r0 = ref memoryManager.GetSpan().DangerousGetReference();
ref T r1 = ref Unsafe.Add(ref r0, this.offset);
return new(ref r1, this.height, this.width, this.pitch);
}
else
{
ref T r0 = ref ObjectMarshal.DangerousGetObjectDataReferenceAt<T>(this.instance, this.offset);
return new(ref r0, this.height, this.width, this.pitch);
}
#else
return new(this.instance, this.offset, this.height, this.width, this.pitch);
#endif
}
return default;
}
}
#if NETSTANDARD2_1_OR_GREATER
/// <summary>
/// Slices the current instance with the specified parameters.
/// </summary>
/// <param name="rows">The target range of rows to select.</param>
/// <param name="columns">The target range of columns to select.</param>
/// <exception cref="ArgumentException">
/// Thrown when either <paramref name="rows"/> or <paramref name="columns"/> are invalid.
/// </exception>
/// <returns>A new <see cref="Memory2D{T}"/> instance representing a slice of the current one.</returns>
public Memory2D<T> this[Range rows, Range columns]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
(int row, int height) = rows.GetOffsetAndLength(this.height);
(int column, int width) = columns.GetOffsetAndLength(this.width);
return Slice(row, column, height, width);
}
}
#endif
/// <summary>
/// Slices the current instance with the specified parameters.
/// </summary>
/// <param name="row">The target row to map within the current instance.</param>
/// <param name="column">The target column to map within the current instance.</param>
/// <param name="height">The height to map within the current instance.</param>
/// <param name="width">The width to map within the current instance.</param>
/// <exception cref="ArgumentException">
/// Thrown when either <paramref name="height"/>, <paramref name="width"/> or <paramref name="height"/>
/// are negative or not within the bounds that are valid for the current instance.
/// </exception>
/// <returns>A new <see cref="Memory2D{T}"/> instance representing a slice of the current one.</returns>
public Memory2D<T> Slice(int row, int column, int height, int width)
{
if ((uint)row >= Height)
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForRow();
}
if ((uint)column >= this.width)
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForColumn();
}
if ((uint)height > (Height - row))
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForHeight();
}
if ((uint)width > (this.width - column))
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForWidth();
}
int shift = ((this.width + this.pitch) * row) + column;
int pitch = this.pitch + (this.width - width);
IntPtr offset = this.offset + (shift * Unsafe.SizeOf<T>());
return new(this.instance!, offset, height, width, pitch);
}
/// <summary>
/// Copies the contents of this <see cref="Memory2D{T}"/> into a destination <see cref="Memory{T}"/> instance.
/// </summary>
/// <param name="destination">The destination <see cref="Memory{T}"/> instance.</param>
/// <exception cref="ArgumentException">
/// Thrown when <paramref name="destination" /> is shorter than the source <see cref="Memory2D{T}"/> instance.
/// </exception>
public void CopyTo(Memory<T> destination) => Span.CopyTo(destination.Span);
/// <summary>
/// Attempts to copy the current <see cref="Memory2D{T}"/> instance to a destination <see cref="Memory{T}"/>.
/// </summary>
/// <param name="destination">The target <see cref="Memory{T}"/> of the copy operation.</param>
/// <returns>Whether or not the operation was successful.</returns>
public bool TryCopyTo(Memory<T> destination) => Span.TryCopyTo(destination.Span);
/// <summary>
/// Copies the contents of this <see cref="Memory2D{T}"/> into a destination <see cref="Memory2D{T}"/> instance.
/// For this API to succeed, the target <see cref="Memory2D{T}"/> has to have the same shape as the current one.
/// </summary>
/// <param name="destination">The destination <see cref="Memory2D{T}"/> instance.</param>
/// <exception cref="ArgumentException">
/// Thrown when <paramref name="destination" /> is shorter than the source <see cref="Memory2D{T}"/> instance.
/// </exception>
public void CopyTo(Memory2D<T> destination) => Span.CopyTo(destination.Span);
/// <summary>
/// Attempts to copy the current <see cref="Memory2D{T}"/> instance to a destination <see cref="Memory2D{T}"/>.
/// For this API to succeed, the target <see cref="Memory2D{T}"/> has to have the same shape as the current one.
/// </summary>
/// <param name="destination">The target <see cref="Memory2D{T}"/> of the copy operation.</param>
/// <returns>Whether or not the operation was successful.</returns>
public bool TryCopyTo(Memory2D<T> destination) => Span.TryCopyTo(destination.Span);
/// <summary>
/// Creates a handle for the memory.
/// The GC will not move the memory until the returned <see cref="MemoryHandle"/>
/// is disposed, enabling taking and using the memory's address.
/// </summary>
/// <exception cref="ArgumentException">
/// An instance with non-primitive (non-blittable) members cannot be pinned.
/// </exception>
/// <returns>A <see cref="MemoryHandle"/> instance wrapping the pinned handle.</returns>
public unsafe MemoryHandle Pin()
{
if (this.instance is not null)
{
if (this.instance is MemoryManager<T> memoryManager)
{
return memoryManager.Pin();
}
GCHandle handle = GCHandle.Alloc(this.instance, GCHandleType.Pinned);
void* pointer = Unsafe.AsPointer(ref ObjectMarshal.DangerousGetObjectDataReferenceAt<T>(this.instance, this.offset));
return new(pointer, handle);
}
return default;
}
/// <summary>
/// Tries to get a <see cref="Memory{T}"/> instance, if the underlying buffer is contiguous and small enough.
/// </summary>
/// <param name="memory">The resulting <see cref="Memory{T}"/>, in case of success.</param>
/// <returns>Whether or not <paramref name="memory"/> was correctly assigned.</returns>
public bool TryGetMemory(out Memory<T> memory)
{
if (this.pitch == 0 &&
Length <= int.MaxValue)
{
// Empty Memory2D<T> instance
if (this.instance is null)
{
memory = default;
}
else if (typeof(T) == typeof(char) && this.instance.GetType() == typeof(string))
{
string text = Unsafe.As<string>(this.instance)!;
int index = text.AsSpan().IndexOf(in ObjectMarshal.DangerousGetObjectDataReferenceAt<char>(text, this.offset));
ReadOnlyMemory<char> temp = text.AsMemory(index, (int)Length);
// The string type could still be present if a user ends up creating a
// Memory2D<T> instance from a string using DangerousCreate. Similarly to
// how CoreCLR handles the equivalent case in Memory<T>, here we just do
// the necessary steps to still retrieve a Memory<T> instance correctly
// wrapping the target string. In this case, it is up to the caller
// to make sure not to ever actually write to the resulting Memory<T>.
memory = MemoryMarshal.AsMemory<T>(Unsafe.As<ReadOnlyMemory<char>, Memory<T>>(ref temp));
}
else if (this.instance is MemoryManager<T> memoryManager)
{
// If the object is a MemoryManager<T>, just slice it as needed
memory = memoryManager.Memory.Slice((int)(nint)this.offset, this.height * this.width);
}
else if (this.instance.GetType() == typeof(T[]))
{
// If it's a T[] array, also handle the initial offset
T[] array = Unsafe.As<T[]>(this.instance)!;
int index = array.AsSpan().IndexOf(ref ObjectMarshal.DangerousGetObjectDataReferenceAt<T>(array, this.offset));
memory = array.AsMemory(index, this.height * this.width);
}
#if NETSTANDARD2_1_OR_GREATER
else if (this.instance.GetType() == typeof(T[,]) ||
this.instance.GetType() == typeof(T[,,]))
{
// If the object is a 2D or 3D array, we can create a Memory<T> from the RawObjectMemoryManager<T> type.
// We just need to use the precomputed offset pointing to the first item in the current instance,
// and the current usable length. We don't need to retrieve the current index, as the manager just offsets.
memory = new RawObjectMemoryManager<T>(this.instance, this.offset, this.height * this.width).Memory;
}
#endif
else
{
// Reuse a single failure path to reduce
// the number of returns in the method
goto Failure;
}
return true;
}
Failure:
memory = default;
return false;
}
/// <summary>
/// Copies the contents of the current <see cref="Memory2D{T}"/> instance into a new 2D array.
/// </summary>
/// <returns>A 2D array containing the data in the current <see cref="Memory2D{T}"/> instance.</returns>
public T[,] ToArray() => Span.ToArray();
/// <inheritdoc/>
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj)
{
if (obj is Memory2D<T> memory)
{
return Equals(memory);
}
if (obj is ReadOnlyMemory2D<T> readOnlyMemory)
{
return readOnlyMemory.Equals(this);
}
return false;
}
/// <inheritdoc/>
public bool Equals(Memory2D<T> other)
{
return
this.instance == other.instance &&
this.offset == other.offset &&
this.height == other.height &&
this.width == other.width &&
this.pitch == other.pitch;
}
/// <inheritdoc/>
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
if (this.instance is not null)
{
return HashCode.Combine(
RuntimeHelpers.GetHashCode(this.instance),
this.offset,
this.height,
this.width,
this.pitch);
}
return 0;
}
/// <inheritdoc/>
public override string ToString()
{
return $"CommunityToolkit.HighPerformance.Memory2D<{typeof(T)}>[{this.height}, {this.width}]";
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="Memory2D{T}"/>
/// </summary>
public static implicit operator Memory2D<T>(T[,]? array) => new(array);
}
| 38.586636 | 152 | 0.610501 | [
"MIT"
] | CommunityToolkit/dotnet | CommunityToolkit.HighPerformance/Memory/Memory2D{T}.cs | 34,072 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using DreamWallHub.Infrastructure.Data.Identity;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace DreamWallHub.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class LogoutModel : PageModel
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger<LogoutModel> _logger;
public LogoutModel(SignInManager<ApplicationUser> signInManager, ILogger<LogoutModel> logger)
{
_signInManager = signInManager;
_logger = logger;
}
public void OnGet()
{
}
public async Task<IActionResult> OnPost(string returnUrl = null)
{
await _signInManager.SignOutAsync();
_logger.LogInformation("User logged out.");
if (returnUrl != null)
{
returnUrl = "/Home/Index";
return LocalRedirect(returnUrl);
}
else
{
return RedirectToPage();
}
}
}
}
| 27.847826 | 101 | 0.636222 | [
"MIT"
] | StrikeITBG/DreamWallHub | DreamWallHub/DreamWallHub/Areas/Identity/Pages/Account/Logout.cshtml.cs | 1,283 | C# |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: example.proto
#pragma warning disable 1591
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace Examples.GrpcConfiguration.Models {
public static partial class ExampleService
{
static readonly string __ServiceName = "ExampleService";
static readonly grpc::Marshaller<global::Examples.GrpcConfiguration.Models.MemberCondition> __Marshaller_MemberCondition = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Examples.GrpcConfiguration.Models.MemberCondition.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Examples.GrpcConfiguration.Models.Member> __Marshaller_Member = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Examples.GrpcConfiguration.Models.Member.Parser.ParseFrom);
static readonly grpc::Method<global::Examples.GrpcConfiguration.Models.MemberCondition, global::Examples.GrpcConfiguration.Models.Member> __Method_GetMember = new grpc::Method<global::Examples.GrpcConfiguration.Models.MemberCondition, global::Examples.GrpcConfiguration.Models.Member>(
grpc::MethodType.Unary,
__ServiceName,
"GetMember",
__Marshaller_MemberCondition,
__Marshaller_Member);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Examples.GrpcConfiguration.Models.ExampleReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of ExampleService</summary>
public abstract partial class ExampleServiceBase
{
public virtual global::System.Threading.Tasks.Task<global::Examples.GrpcConfiguration.Models.Member> GetMember(global::Examples.GrpcConfiguration.Models.MemberCondition request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for ExampleService</summary>
public partial class ExampleServiceClient : grpc::ClientBase<ExampleServiceClient>
{
/// <summary>Creates a new client for ExampleService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public ExampleServiceClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for ExampleService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public ExampleServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected ExampleServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected ExampleServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
public virtual global::Examples.GrpcConfiguration.Models.Member GetMember(global::Examples.GrpcConfiguration.Models.MemberCondition request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetMember(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::Examples.GrpcConfiguration.Models.Member GetMember(global::Examples.GrpcConfiguration.Models.MemberCondition request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetMember, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::Examples.GrpcConfiguration.Models.Member> GetMemberAsync(global::Examples.GrpcConfiguration.Models.MemberCondition request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetMemberAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::Examples.GrpcConfiguration.Models.Member> GetMemberAsync(global::Examples.GrpcConfiguration.Models.MemberCondition request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetMember, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override ExampleServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new ExampleServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(ExampleServiceBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_GetMember, serviceImpl.GetMember).Build();
}
}
}
#endregion
| 54.212121 | 297 | 0.752562 | [
"MIT"
] | mxProject/GrpcConfiguration | source/Examples.GrpcConfiguration.Models/Models/ExampleGrpc.cs | 5,367 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ExpenseApplication.Models
{
using System;
using System.Collections.Generic;
public partial class User
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public User()
{
this.AddExpense = new HashSet<AddExpense>();
}
public int userId { get; set; }
public string userName { get; set; }
public Nullable<int> password { get; set; }
public Nullable<int> rolesId { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<AddExpense> AddExpense { get; set; }
}
}
| 37.15625 | 128 | 0.579479 | [
"MIT"
] | Diavell/ExpenseApp | ExpenseApplication/ExpenseApplication/Models/User.cs | 1,189 | C# |
using System;
//Write a program that enters from the console a positive integer n and prints all the numbers from 1 to n, on a single line, separated by a space.
//Examples:
//n output
//3 1 2 3
//5 1 2 3 4 5
class Numbersfrom1ToN
{
static void Main()
{
Console.WriteLine("Enter a number for N:");
int counter = int.Parse(Console.ReadLine());
for (int i = 1; i <= counter; i++)
{
Console.Write("{0} ", i);
}
}
} | 21.818182 | 147 | 0.583333 | [
"MIT"
] | ivantchev/Loops-Homework | 01_Problem_Numbersfrom1ToN/01_Problem_Numbersfrom1ToN.cs | 482 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.