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 |
|---|---|---|---|---|---|---|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Globalization;
using Xunit;
namespace System.Tests
{
public partial class Int64Tests
{
[Fact]
public static void Ctor_Empty()
{
var i = new long();
Assert.Equal(0, i);
}
[Fact]
public static void Ctor_Value()
{
long i = 41;
Assert.Equal(41, i);
}
[Fact]
public static void MaxValue()
{
Assert.Equal(0x7FFFFFFFFFFFFFFF, long.MaxValue);
}
[Fact]
public static void MinValue()
{
Assert.Equal(unchecked((long)0x8000000000000000), long.MinValue);
}
[Theory]
[InlineData((long)234, (long)234, 0)]
[InlineData((long)234, long.MinValue, 1)]
[InlineData((long)234, (long)-123, 1)]
[InlineData((long)234, (long)0, 1)]
[InlineData((long)234, (long)123, 1)]
[InlineData((long)234, (long)456, -1)]
[InlineData((long)234, long.MaxValue, -1)]
[InlineData((long)-234, (long)-234, 0)]
[InlineData((long)-234, (long)234, -1)]
[InlineData((long)-234, (long)-432, 1)]
[InlineData((long)234, null, 1)]
public void CompareTo_Other_ReturnsExpected(long i, object value, int expected)
{
if (value is long longValue)
{
Assert.Equal(expected, Math.Sign(i.CompareTo(longValue)));
}
Assert.Equal(expected, Math.Sign(i.CompareTo(value)));
}
[Theory]
[InlineData("a")]
[InlineData(234)]
public void CompareTo_ObjectNotLong_ThrowsArgumentException(object value)
{
AssertExtensions.Throws<ArgumentException>(null, () => ((long)123).CompareTo(value));
}
[Theory]
[InlineData((long)789, (long)789, true)]
[InlineData((long)789, (long)-789, false)]
[InlineData((long)789, (long)0, false)]
[InlineData((long)0, (long)0, true)]
[InlineData((long)-789, (long)-789, true)]
[InlineData((long)-789, (long)789, false)]
[InlineData((long)789, null, false)]
[InlineData((long)789, "789", false)]
[InlineData((long)789, 789, false)]
public static void Equals(long i1, object obj, bool expected)
{
if (obj is long)
{
long i2 = (long)obj;
Assert.Equal(expected, i1.Equals(i2));
Assert.Equal(expected, i1.GetHashCode().Equals(i2.GetHashCode()));
}
Assert.Equal(expected, i1.Equals(obj));
}
[Fact]
public void GetTypeCode_Invoke_ReturnsInt64()
{
Assert.Equal(TypeCode.Int64, ((long)1).GetTypeCode());
}
public static IEnumerable<object[]> ToString_TestData()
{
foreach (NumberFormatInfo defaultFormat in new[] { null, NumberFormatInfo.CurrentInfo })
{
yield return new object[] { long.MinValue, "G", defaultFormat, "-9223372036854775808" };
yield return new object[] { (long)-4567, "G", defaultFormat, "-4567" };
yield return new object[] { (long)0, "G", defaultFormat, "0" };
yield return new object[] { (long)4567, "G", defaultFormat, "4567" };
yield return new object[] { long.MaxValue, "G", defaultFormat, "9223372036854775807" };
yield return new object[] { (long)4567, "D", defaultFormat, "4567" };
yield return new object[] { long.MaxValue, "D99", defaultFormat, "000000000000000000000000000000000000000000000000000000000000000000000000000000009223372036854775807" };
yield return new object[] { (long)0x2468, "x", defaultFormat, "2468" };
yield return new object[] { (long)2468, "N", defaultFormat, string.Format("{0:N}", 2468.00) };
}
var customFormat = new NumberFormatInfo()
{
NegativeSign = "#",
NumberDecimalSeparator = "~",
NumberGroupSeparator = "*",
PositiveSign = "&",
NumberDecimalDigits = 2,
PercentSymbol = "@",
PercentGroupSeparator = ",",
PercentDecimalSeparator = ".",
PercentDecimalDigits = 5
};
yield return new object[] { (long)-2468, "N", customFormat, "#2*468~00" };
yield return new object[] { (long)2468, "N", customFormat, "2*468~00" };
yield return new object[] { (long)123, "E", customFormat, "1~230000E&002" };
yield return new object[] { (long)123, "F", customFormat, "123~00" };
yield return new object[] { (long)123, "P", customFormat, "12,300.00000 @" };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public static void ToString(long i, string format, IFormatProvider provider, string expected)
{
// Format is case insensitive
string upperFormat = format.ToUpperInvariant();
string lowerFormat = format.ToLowerInvariant();
string upperExpected = expected.ToUpperInvariant();
string lowerExpected = expected.ToLowerInvariant();
bool isDefaultProvider = (provider == null || provider == NumberFormatInfo.CurrentInfo);
if (string.IsNullOrEmpty(format) || format.ToUpperInvariant() == "G")
{
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString());
Assert.Equal(upperExpected, i.ToString((IFormatProvider)null));
}
Assert.Equal(upperExpected, i.ToString(provider));
}
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString(upperFormat));
Assert.Equal(lowerExpected, i.ToString(lowerFormat));
Assert.Equal(upperExpected, i.ToString(upperFormat, null));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, null));
}
Assert.Equal(upperExpected, i.ToString(upperFormat, provider));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, provider));
}
[Fact]
public static void ToString_InvalidFormat_ThrowsFormatException()
{
long i = 123;
Assert.Throws<FormatException>(() => i.ToString("Y")); // Invalid format
Assert.Throws<FormatException>(() => i.ToString("Y", null)); // Invalid format
}
public static IEnumerable<object[]> Parse_Valid_TestData()
{
NumberStyles defaultStyle = NumberStyles.Integer;
NumberFormatInfo emptyFormat = new NumberFormatInfo();
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.CurrencySymbol = "$";
yield return new object[] { "-9223372036854775808", defaultStyle, null, -9223372036854775808 };
yield return new object[] { "-123", defaultStyle, null, (long)-123 };
yield return new object[] { "0", defaultStyle, null, (long)0 };
yield return new object[] { "123", defaultStyle, null, (long)123 };
yield return new object[] { "+123", defaultStyle, null, (long)123 };
yield return new object[] { " 123 ", defaultStyle, null, (long)123 };
yield return new object[] { "9223372036854775807", defaultStyle, null, 9223372036854775807 };
yield return new object[] { "123", NumberStyles.HexNumber, null, (long)0x123 };
yield return new object[] { "abc", NumberStyles.HexNumber, null, (long)0xabc };
yield return new object[] { "ABC", NumberStyles.HexNumber, null, (long)0xabc };
yield return new object[] { "1000", NumberStyles.AllowThousands, null, (long)1000 };
yield return new object[] { "(123)", NumberStyles.AllowParentheses, null, (long)-123 }; // Parentheses = negative
yield return new object[] { "123", defaultStyle, emptyFormat, (long)123 };
yield return new object[] { "123", NumberStyles.Any, emptyFormat, (long)123 };
yield return new object[] { "12", NumberStyles.HexNumber, emptyFormat, (long)0x12 };
yield return new object[] { "$1,000", NumberStyles.Currency, customFormat, (long)1000 };
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void Parse(string value, NumberStyles style, IFormatProvider provider, long expected)
{
long result;
// If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.True(long.TryParse(value, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, long.Parse(value));
// If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (provider != null)
{
Assert.Equal(expected, long.Parse(value, provider));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.True(long.TryParse(value, style, provider ?? new NumberFormatInfo(), out result));
Assert.Equal(expected, result);
// If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (provider == null)
{
Assert.Equal(expected, long.Parse(value, style));
}
Assert.Equal(expected, long.Parse(value, style, provider ?? new NumberFormatInfo()));
}
public static IEnumerable<object[]> Parse_Invalid_TestData()
{
NumberStyles defaultStyle = NumberStyles.Integer;
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.CurrencySymbol = "$";
customFormat.NumberDecimalSeparator = ".";
yield return new object[] { null, defaultStyle, null, typeof(ArgumentNullException) };
yield return new object[] { "", defaultStyle, null, typeof(FormatException) };
yield return new object[] { " \t \n \r ", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "Garbage", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "abc", defaultStyle, null, typeof(FormatException) }; // Hex value
yield return new object[] { "1E23", defaultStyle, null, typeof(FormatException) }; // Exponent
yield return new object[] { "(123)", defaultStyle, null, typeof(FormatException) }; // Parentheses
yield return new object[] { 1000.ToString("C0"), defaultStyle, null, typeof(FormatException) }; // Currency
yield return new object[] { 1000.ToString("N0"), defaultStyle, null, typeof(FormatException) }; // Thousands
yield return new object[] { 678.90.ToString("F2"), defaultStyle, null, typeof(FormatException) }; // Decimal
yield return new object[] { "+-123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "-+123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "+abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "-abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "- 123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "+ 123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "abc", NumberStyles.None, null, typeof(FormatException) }; // Hex value
yield return new object[] { " 123 ", NumberStyles.None, null, typeof(FormatException) }; // Trailing and leading whitespace
yield return new object[] { "67.90", defaultStyle, customFormat, typeof(FormatException) }; // Decimal
yield return new object[] { "-9223372036854775809", defaultStyle, null, typeof(OverflowException) }; // < min value
yield return new object[] { "9223372036854775808", defaultStyle, null, typeof(OverflowException) }; // > max value
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType)
{
long result;
// If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.False(long.TryParse(value, out result));
Assert.Equal(default(long), result);
Assert.Throws(exceptionType, () => long.Parse(value));
// If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (provider != null)
{
Assert.Throws(exceptionType, () => long.Parse(value, provider));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.False(long.TryParse(value, style, provider ?? new NumberFormatInfo(), out result));
Assert.Equal(default(long), result);
// If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (provider == null)
{
Assert.Throws(exceptionType, () => long.Parse(value, style));
}
Assert.Throws(exceptionType, () => long.Parse(value, style, provider ?? new NumberFormatInfo()));
}
[Theory]
[InlineData(NumberStyles.HexNumber | NumberStyles.AllowParentheses, null)]
[InlineData(unchecked((NumberStyles)0xFFFFFC00), "style")]
public static void TryParse_InvalidNumberStyle_ThrowsArgumentException(NumberStyles style, string paramName)
{
long result = 0;
AssertExtensions.Throws<ArgumentException>(paramName, () => long.TryParse("1", style, null, out result));
Assert.Equal(default(long), result);
AssertExtensions.Throws<ArgumentException>(paramName, () => long.Parse("1", style));
AssertExtensions.Throws<ArgumentException>(paramName, () => long.Parse("1", style, null));
}
}
}
| 47.536508 | 185 | 0.589622 | [
"MIT"
] | BigBadBleuCheese/corefx | src/System.Runtime/tests/System/Int64Tests.cs | 14,974 | C# |
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
public static class DataUtil
{
public static void Serialize(object o, string filename)
{
BinaryFormatter fmt = new BinaryFormatter();
string path = Application.dataPath + $"/{filename}";
FileStream fs = new FileStream(path, FileMode.Create);
fmt.Serialize(fs, o);
fs.Close();
}
public static bool LoadSerialized<T>(string filename, out T o)
{
string path = Application.dataPath + $"/{filename}";
if (!File.Exists(path))
{
Debug.LogError($"Path: '{filename}' does not exist! Ignoring.");
o = default(T);
return false;
}
BinaryFormatter fmt = new BinaryFormatter();
FileStream fs = new FileStream(path, FileMode.Open);
o = (T) fmt.Deserialize(fs);
fs.Close();
return true;
}
public static bool Exists(string filename)
{
return File.Exists(Application.dataPath + $"/{filename}");
}
} | 24.704545 | 76 | 0.602576 | [
"MIT"
] | Telanoff/SpaceFighter | Assets/Scripts/Other/DataUtil.cs | 1,089 | C# |
/***************************************************************************\
The MIT License (MIT)
Copyright (c) 2016 senritsu (https://github.com/senritsu)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
\***************************************************************************/
namespace SharpRhythms.Parsers.Msd.Base
{
using System.Collections.Generic;
using System.Globalization;
using Abstractions.Timing;
using Sprache;
public static class MsdTagContentParser
{
private static readonly Parser<char> ListDelimiter = Parse.Char(',').Token();
private static readonly Parser<char> ComplexContentDelimiter = Parse.Char(':');
public static readonly Parser<string> ComplexContentPart =
Parse.AnyChar.Except(ComplexContentDelimiter)
.Many()
.Text()
.Then(
part =>
ComplexContentDelimiter.Select(d => d.ToString())
.Or(Parse.Return("").End())
.Then(x => Parse.Return(part))).Token();
public static Parser<TimeIndexedValue> TimeIndexedValue =
from time in Parse.DecimalInvariant
from equal in Parse.Char('=').Token()
from value in Parse.DecimalInvariant
select new TimeIndexedValue
{
Time = double.Parse(time, CultureInfo.InvariantCulture),
Value = double.Parse(value, CultureInfo.InvariantCulture)
};
public static Parser<List<T>> ListContent<T>(Parser<T> itemParser) => Utilities.ListOf(itemParser.Except(ListDelimiter), ListDelimiter);
public static Parser<List<string>> ComplexContent =
Utilities.ListOf(Parse.AnyChar.Except(ComplexContentDelimiter).Many().Text(), ComplexContentDelimiter);
public static Parser<bool> YesOrNo = Parse.String("YES").Return(true).XOr(Parse.String("NO").Return(false));
}
}
| 44.757576 | 144 | 0.652674 | [
"MIT"
] | senritsu/SharpRhythms | SharpRhythms/Parsers/Msd/Base/MsdTagContentParser.cs | 2,956 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class Tribe : MonoBehaviour
{
public int id;
public new string name;
System.DateTime created_at;
}
| 18.916667 | 34 | 0.762115 | [
"Apache-2.0",
"Unlicense",
"MIT"
] | Myfigt/Myfights | Assets/Scripts/Tribe.cs | 229 | C# |
// <copyright file="OfferingViewModel.cs" company="Dark Bond, Inc.">
// Copyright © 2016-2018 - Dark Bond, Inc. All Rights Reserved.
// </copyright>
// <author>Donald Roy Airey</author>
namespace DarkBond.SubscriptionManager.ViewModels.TreeViews
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Composition;
using DarkBond.SubscriptionManager.Common;
using DarkBond.SubscriptionManager.Common.Strings;
using DarkBond.ViewModels;
using DarkBond.ViewModels.Input;
/// <summary>
/// A navigation tree view item for the offering.
/// </summary>
public class OfferingViewModel : CommonTreeViewViewModel
{
/// <summary>
/// A table that drives the notifications when data model changes.
/// </summary>
private Dictionary<string, Action<OfferingRow>> notifyActions = new Dictionary<string, Action<OfferingRow>>();
/// <summary>
/// The offering row.
/// </summary>
private OfferingRow offeringRowField;
/// <summary>
/// Initializes a new instance of the <see cref="OfferingViewModel"/> class.
/// </summary>
/// <param name="compositionContext">The composition context.</param>
/// <param name="dataModel">The data model.</param>
/// <param name="subscriptionService">The subscription service.</param>
public OfferingViewModel(
CompositionContext compositionContext,
DataModel dataModel,
ISubscriptionService subscriptionService)
: base(compositionContext, dataModel, subscriptionService)
{
// Initialize the properties of this object.
this.ImageKey = ImageKeys.Product;
this.RootUri = new Uri(Properties.Resources.FrameUri);
}
/// <summary>
/// Maps the data model to the view model.
/// </summary>
/// <param name="offeringRow">The offering row.</param>
public void Map(OfferingRow offeringRow)
{
// Validate the parameter.
if (offeringRow == null)
{
throw new ArgumentNullException(nameof(offeringRow));
}
// Instruct the data model to notify this view model of relevant changes.
this.offeringRowField = offeringRow;
this.offeringRowField.PropertyChanged += this.OnOfferingRowChanged;
// This table drives the updating of the view model when the data model changes.
this.notifyActions.Add("OfferingId", this.UpdateIdentifier);
this.notifyActions.Add("Name", (c) => this.Header = c.Name);
// Initialize the view model with the data model.
foreach (string property in this.notifyActions.Keys)
{
this.notifyActions[property](this.offeringRowField);
}
}
/// <summary>
/// Creates a context menu for this item.
/// </summary>
/// <returns>The collection of menu items for the context menu.</returns>
protected override ObservableCollection<IDisposable> CreateContextMenuItems()
{
// Use the base class to create the common elements.
ObservableCollection<IDisposable> contextMenuViewItems = base.CreateContextMenuItems();
// New License Menu Item
MenuItemViewModel newLicenseMenuItem = this.CompositionContext.GetExport<MenuItemViewModel>();
newLicenseMenuItem.Command = new DelegateCommand(() => this.SubscriptionService.NavigateToProductLicense(this.offeringRowField.OfferingId));
newLicenseMenuItem.Header = Resources.NewLicense;
newLicenseMenuItem.ImageKey = ImageKeys.License;
contextMenuViewItems.Add(newLicenseMenuItem);
// Delete Product Menu Item
MenuItemViewModel deleteProductMenuItem = this.CompositionContext.GetExport<MenuItemViewModel>();
deleteProductMenuItem.Command = new DelegateCommand(
() => this.SubscriptionService.DeleteProductAsync(this.offeringRowField.OfferingId),
() => this.SubscriptionService.CanDeleteProduct(this.offeringRowField.OfferingId));
deleteProductMenuItem.Header = Resources.Delete;
deleteProductMenuItem.ImageKey = ImageKeys.Delete;
contextMenuViewItems.Add(deleteProductMenuItem);
// Product Properties Menu Item
MenuItemViewModel propertiesMenuItem = this.CompositionContext.GetExport<MenuItemViewModel>();
propertiesMenuItem.Command = new DelegateCommand(() => this.SubscriptionService.NavigateToProduct(this.offeringRowField.OfferingId));
propertiesMenuItem.Header = Resources.Properties;
propertiesMenuItem.ImageKey = ImageKeys.Properties;
contextMenuViewItems.Add(propertiesMenuItem);
// This is the context menu.
return contextMenuViewItems;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <param name="disposing">true to indicate that the object is being disposed, false to indicate that the object is being finalized.</param>
protected override void Dispose(bool disposing)
{
// Disconnect from the data model.
this.offeringRowField.PropertyChanged -= this.OnOfferingRowChanged;
// Allow the base class to finish the disposal.
base.Dispose(disposing);
}
/// <summary>
/// Handles a change to the data model offering row.
/// </summary>
/// <param name="sender">The object that originated the event.</param>
/// <param name="propertyChangedEventArgs">The event data.</param>
private void OnOfferingRowChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
{
Action<OfferingRow> notifyAction;
if (this.notifyActions.TryGetValue(propertyChangedEventArgs.PropertyName, out notifyAction))
{
notifyAction(this.offeringRowField);
}
}
/// <summary>
/// Update the unique identifier.
/// </summary>
/// <param name="offeringRow">The offering row.</param>
private void UpdateIdentifier(OfferingRow offeringRow)
{
// This is used to uniquely identify the object in a URL.
this.Identifier = offeringRow.OfferingId.ToString("N");
// This is used to uniquely identify the object in a ordered list.
this.SortKey = offeringRow.OfferingId;
}
}
} | 44.828947 | 152 | 0.646463 | [
"MIT"
] | DonaldAirey/dark-bond-main | Subscription Manager/DarkBond.SubscriptionManager.Infrastructure/View Models/Tree Views/OfferingViewModel.cs | 6,817 | C# |
// -----------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// -----------------------------------------------------------------------
using System;
using System.Globalization;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
using System.Reflection.Context.Custom;
namespace System.Reflection.Context.Virtual
{
partial class VirtualPropertyInfo
{
private class PropertyGetter : PropertyGetterBase
{
private readonly Func<object, object> _getter;
private readonly IEnumerable<Attribute> _attributes;
public PropertyGetter(VirtualPropertyBase property, Func<object, object> getter, IEnumerable<Attribute> getterAttributes)
: base(property)
{
Contract.Requires(null != getter);
_getter = getter;
_attributes = getterAttributes ?? CollectionServices.Empty<Attribute>();
}
public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
{
// invokeAttr, binder, and culture are ignored, similar to what runtime reflection does with the default binder.
if (parameters != null && parameters.Length > 0)
throw new TargetParameterCountException();
if (!ReflectedType.IsInstanceOfType(obj))
throw new ArgumentException();
return _getter(obj);
}
#region ICustomAttributeProvider implementation
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return CollectionServices.IEnumerableToArray(AttributeUtils.FilterCustomAttributes(_attributes, attributeType), attributeType);
}
public override object[] GetCustomAttributes(bool inherit)
{
return CollectionServices.IEnumerableToArray(_attributes, typeof(Attribute));
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CollectionServices.Empty<CustomAttributeData>();
}
public override bool IsDefined(Type attributeType, bool inherit)
{
return GetCustomAttributes(attributeType, inherit).Length > 0;
}
#endregion
}
}
}
| 38.707692 | 143 | 0.594595 | [
"MIT"
] | zhy29563/MyMEF | redist/src/InternalReflectionContext/System/Reflection/Context/Virtual/VirtualProperty.PropertyGetter.cs | 2,518 | C# |
// 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.
//
// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
//
// Author:
// Pedro Martínez Juliá <pedromj@gmail.com>
//
using System.ComponentModel;
using System.Collections;
using System.ComponentModel.Design.Serialization;
namespace System.Windows.Forms
{
[DesignerSerializerAttribute ("System.Windows.Forms.Design.DataGridViewRowCollectionCodeDomSerializer, " + Consts.AssemblySystem_Design,
"System.ComponentModel.Design.Serialization.CodeDomSerializer, " + Consts.AssemblySystem_Design)]
[ListBindable (false)]
public class DataGridViewRowCollection : IList, ICollection, IEnumerable
{
private ArrayList list;
private DataGridView dataGridView;
private bool raiseEvent = true;
public DataGridViewRowCollection (DataGridView dataGridView)
{
this.dataGridView = dataGridView;
list = new ArrayList ();
}
public int Count {
get { return list.Count; }
}
int ICollection.Count {
get { return Count; }
}
bool IList.IsFixedSize {
get { return list.IsFixedSize; }
}
bool IList.IsReadOnly {
get { return list.IsReadOnly; }
}
bool ICollection.IsSynchronized {
get { return list.IsSynchronized; }
}
object IList.this [int index] {
get {
return this[index];
}
set { list[index] = value as DataGridViewRow; }
}
public DataGridViewRow this [int index] {
get {
// Accessing a System.Windows.Forms.DataGridViewRow with this indexer causes the row to become unshared.
// To keep the row shared, use the System.Windows.Forms.DataGridViewRowCollection.SharedRow method.
// For more information, see Best Practices for Scaling the Windows Forms DataGridView Control.
DataGridViewRow row = (DataGridViewRow) list [index];
if (row.Index == -1) {
row = (DataGridViewRow) row.Clone ();
row.SetIndex (index);
list [index] = row;
}
return row;
}
}
object ICollection.SyncRoot {
get { return list.SyncRoot; }
}
public event CollectionChangeEventHandler CollectionChanged;
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public virtual int Add ()
{
return Add (dataGridView.RowTemplateFull as DataGridViewRow);
}
int IList.Add (object value)
{
return Add (value as DataGridViewRow);
}
private int AddCore (DataGridViewRow dataGridViewRow, bool sharable)
{
if (dataGridView.Columns.Count == 0)
throw new InvalidOperationException ("DataGridView has no columns.");
int result;
dataGridViewRow.SetDataGridView (dataGridView);
//
// Add the row just before the editing row (if there is an editing row).
//
int editing_index = -1;
if (DataGridView != null && DataGridView.EditingRow != null && DataGridView.EditingRow != dataGridViewRow) {
editing_index = list.Count - 1; // always the last row
DataGridView.EditingRow.SetIndex (list.Count);
}
if (editing_index >= 0) {
list.Insert (editing_index, dataGridViewRow);
result = editing_index;
} else {
result = list.Add (dataGridViewRow);
}
if (sharable && CanBeShared (dataGridViewRow)) {
dataGridViewRow.SetIndex (-1);
} else {
dataGridViewRow.SetIndex (result);
}
CompleteRowCells (dataGridViewRow);
for (int i = 0; i < dataGridViewRow.Cells.Count; i++) {
dataGridViewRow.Cells [i].SetOwningColumn (dataGridView.Columns [i]);
}
if (raiseEvent) {
OnCollectionChanged (new CollectionChangeEventArgs (CollectionChangeAction.Add, dataGridViewRow));
DataGridView.OnRowsAddedInternal (new DataGridViewRowsAddedEventArgs (result, 1));
}
return result;
}
// Complete the rows if they are incomplete.
private void CompleteRowCells (DataGridViewRow row)
{
if (row == null || DataGridView == null)
return;
if (row.Cells.Count < DataGridView.ColumnCount) {
for (int i = row.Cells.Count; i < DataGridView.ColumnCount; i++)
row.Cells.Add ((DataGridViewCell) DataGridView.Columns[i].CellTemplate.Clone ());
}
}
public virtual int Add (DataGridViewRow dataGridViewRow)
{
if (dataGridView.DataSource != null)
throw new InvalidOperationException ("DataSource of DataGridView is not null.");
return AddCore (dataGridViewRow, true);
}
private bool CanBeShared (DataGridViewRow row)
{
// We don't currently support shared rows
return false;
//foreach (DataGridViewCell cell in row.Cells) {
// if (cell.Value != null)
// return false;
// if (cell.ToolTipText != string.Empty)
// return false;
// if (cell.ContextMenuStrip != null)
// return false;
//}
//return true;
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public virtual int Add (int count)
{
if (count <= 0)
throw new ArgumentOutOfRangeException("Count is less than or equeal to 0.");
if (dataGridView.DataSource != null)
throw new InvalidOperationException("DataSource of DataGridView is not null.");
if (dataGridView.Columns.Count == 0)
throw new InvalidOperationException("DataGridView has no columns.");
raiseEvent = false;
int result = 0;
for (int i = 0; i < count; i++)
result = Add (dataGridView.RowTemplateFull as DataGridViewRow);
DataGridView.OnRowsAddedInternal (new DataGridViewRowsAddedEventArgs (result - count + 1, count));
raiseEvent = true;
return result;
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public virtual int Add (params object[] values)
{
if (values == null)
throw new ArgumentNullException("values is null.");
if (dataGridView.VirtualMode)
throw new InvalidOperationException("DataGridView is in virtual mode.");
DataGridViewRow row = (DataGridViewRow)dataGridView.RowTemplateFull;
int result = AddCore (row, false);
row.SetValues(values);
return result;
}
public virtual int AddCopies (int indexSource, int count)
{
raiseEvent = false;
int lastIndex = 0;
for (int i = 0; i < count; i++)
lastIndex = AddCopy(indexSource);
DataGridView.OnRowsAddedInternal (new DataGridViewRowsAddedEventArgs (lastIndex - count + 1, count));
raiseEvent = true;
return lastIndex;
}
public virtual int AddCopy (int indexSource)
{
return Add ((list [indexSource] as DataGridViewRow).Clone () as DataGridViewRow);
}
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public virtual void AddRange (params DataGridViewRow [] dataGridViewRows)
{
if (dataGridView.DataSource != null)
throw new InvalidOperationException ("DataSource of DataGridView is not null.");
int count = 0;
int lastIndex = -1;
raiseEvent = false;
foreach (DataGridViewRow row in dataGridViewRows) {
lastIndex = Add (row);
count++;
}
raiseEvent = true;
DataGridView.OnRowsAddedInternal (new DataGridViewRowsAddedEventArgs (lastIndex - count + 1, count));
OnCollectionChanged (new CollectionChangeEventArgs (CollectionChangeAction.Add, dataGridViewRows));
}
public virtual void Clear ()
{
int total = list.Count;
DataGridView.OnRowsPreRemovedInternal (new DataGridViewRowsRemovedEventArgs (0, total));
for (int i = 0; i < total; i++) {
DataGridViewRow row = (DataGridViewRow)list[0];
// We can exit because the NewRow is always last
if (row.IsNewRow)
break;
list.Remove (row);
ReIndex ();
}
DataGridView.OnRowsPostRemovedInternal (new DataGridViewRowsRemovedEventArgs (0, total));
OnCollectionChanged (new CollectionChangeEventArgs (CollectionChangeAction.Refresh, null));
}
internal void ClearInternal ()
{
list.Clear ();
}
bool IList.Contains (object value)
{
return Contains (value as DataGridViewRow);
}
public virtual bool Contains (DataGridViewRow dataGridViewRow)
{
return list.Contains (dataGridViewRow);
}
void ICollection.CopyTo (Array array, int index)
{
list.CopyTo (array, index);
}
public void CopyTo (DataGridViewRow[] array, int index)
{
list.CopyTo (array, index);
}
IEnumerator IEnumerable.GetEnumerator ()
{
return list.GetEnumerator ();
}
public int GetFirstRow (DataGridViewElementStates includeFilter)
{
for (int i = 0; i < list.Count; i++) {
DataGridViewRow row = (DataGridViewRow) list [i];
if ((row.State & includeFilter) != 0)
return i;
}
return -1;
}
public int GetFirstRow (DataGridViewElementStates includeFilter, DataGridViewElementStates excludeFilter)
{
for (int i = 0; i < list.Count; i++) {
DataGridViewRow row = (DataGridViewRow) list [i];
if (((row.State & includeFilter) != 0) && ((row.State & excludeFilter) == 0))
return i;
}
return -1;
}
public int GetLastRow (DataGridViewElementStates includeFilter)
{
for (int i = list.Count - 1; i >= 0; i--) {
DataGridViewRow row = (DataGridViewRow) list [i];
if ((row.State & includeFilter) != 0)
return i;
}
return -1;
}
public int GetNextRow (int indexStart, DataGridViewElementStates includeFilter)
{
for (int i = indexStart + 1; i < list.Count; i++) {
DataGridViewRow row = (DataGridViewRow) list [i];
if ((row.State & includeFilter) != 0)
return i;
}
return -1;
}
public int GetNextRow (int indexStart, DataGridViewElementStates includeFilter, DataGridViewElementStates excludeFilter)
{
for (int i = indexStart + 1; i < list.Count; i++) {
DataGridViewRow row = (DataGridViewRow) list [i];
if (((row.State & includeFilter) != 0) && ((row.State & excludeFilter) == 0))
return i;
}
return -1;
}
public int GetPreviousRow (int indexStart, DataGridViewElementStates includeFilter)
{
for (int i = indexStart - 1; i >= 0; i--) {
DataGridViewRow row = (DataGridViewRow) list [i];
if ((row.State & includeFilter) != 0)
return i;
}
return -1;
}
public int GetPreviousRow (int indexStart, DataGridViewElementStates includeFilter, DataGridViewElementStates excludeFilter)
{
for (int i = indexStart - 1; i >= 0; i--) {
DataGridViewRow row = (DataGridViewRow) list [i];
if (((row.State & includeFilter) != 0) && ((row.State & excludeFilter) == 0))
return i;
}
return -1;
}
public int GetRowCount (DataGridViewElementStates includeFilter)
{
int result = 0;
foreach (DataGridViewRow row in list)
if ((row.State & includeFilter) != 0)
result ++;
return result;
}
public int GetRowsHeight (DataGridViewElementStates includeFilter)
{
int result = 0;
foreach (DataGridViewRow row in list)
if ((row.State & includeFilter) != 0)
result += row.Height;
return result;
}
public virtual DataGridViewElementStates GetRowState (int rowIndex)
{
return (list [rowIndex] as DataGridViewRow).State;
}
int IList.IndexOf (object value)
{
return IndexOf (value as DataGridViewRow);
}
public int IndexOf (DataGridViewRow dataGridViewRow)
{
return list.IndexOf (dataGridViewRow);
}
void IList.Insert (int index, object value)
{
Insert (index, value as DataGridViewRow);
}
// FIXME: Do *not* allow insertation *after* the editing row!
public virtual void Insert (int rowIndex, DataGridViewRow dataGridViewRow)
{
dataGridViewRow.SetIndex (rowIndex);
dataGridViewRow.SetDataGridView (dataGridView);
CompleteRowCells (dataGridViewRow);
list.Insert (rowIndex, dataGridViewRow);
ReIndex ();
OnCollectionChanged (new CollectionChangeEventArgs (CollectionChangeAction.Add, dataGridViewRow));
if (raiseEvent)
DataGridView.OnRowsAddedInternal (new DataGridViewRowsAddedEventArgs (rowIndex, 1));
}
public virtual void Insert (int rowIndex, int count)
{
int index = rowIndex;
raiseEvent = false;
for (int i = 0; i < count; i++)
Insert (index++, dataGridView.RowTemplateFull);
DataGridView.OnRowsAddedInternal (new DataGridViewRowsAddedEventArgs (rowIndex, count));
raiseEvent = true;
}
public virtual void Insert (int rowIndex, params object[] values)
{
if (values == null)
throw new ArgumentNullException ("Values is null.");
if (dataGridView.VirtualMode || dataGridView.DataSource != null)
throw new InvalidOperationException ();
DataGridViewRow row = dataGridView.RowTemplateFull;
row.SetValues (values);
Insert (rowIndex, row);
}
public virtual void InsertCopies (int indexSource, int indexDestination, int count)
{
raiseEvent = false;
int index = indexDestination;
for (int i = 0; i < count; i++)
InsertCopy (indexSource, index++);
DataGridView.OnRowsAddedInternal (new DataGridViewRowsAddedEventArgs (indexDestination, count));
raiseEvent = true;
}
public virtual void InsertCopy (int indexSource, int indexDestination)
{
Insert (indexDestination, (list [indexSource] as DataGridViewRow).Clone());
}
public virtual void InsertRange (int rowIndex, params DataGridViewRow [] dataGridViewRows)
{
raiseEvent = false;
int index = rowIndex;
int count = 0;
foreach (DataGridViewRow row in dataGridViewRows) {
Insert (index++, row);
count++;
}
DataGridView.OnRowsAddedInternal (new DataGridViewRowsAddedEventArgs (rowIndex, count));
raiseEvent = true;
}
void IList.Remove (object value)
{
Remove (value as DataGridViewRow);
}
public virtual void Remove (DataGridViewRow dataGridViewRow)
{
if (dataGridViewRow.IsNewRow)
throw new InvalidOperationException ("Cannot delete the new row");
DataGridView.OnRowsPreRemovedInternal (new DataGridViewRowsRemovedEventArgs (dataGridViewRow.Index, 1));
list.Remove (dataGridViewRow);
ReIndex ();
OnCollectionChanged (new CollectionChangeEventArgs (CollectionChangeAction.Remove, dataGridViewRow));
DataGridView.OnRowsPostRemovedInternal (new DataGridViewRowsRemovedEventArgs (dataGridViewRow.Index, 1));
}
internal virtual void RemoveInternal (DataGridViewRow dataGridViewRow)
{
DataGridView.OnRowsPreRemovedInternal (new DataGridViewRowsRemovedEventArgs (dataGridViewRow.Index, 1));
list.Remove (dataGridViewRow);
ReIndex ();
OnCollectionChanged (new CollectionChangeEventArgs (CollectionChangeAction.Remove, dataGridViewRow));
DataGridView.OnRowsPostRemovedInternal (new DataGridViewRowsRemovedEventArgs (dataGridViewRow.Index, 1));
}
public virtual void RemoveAt (int index)
{
DataGridViewRow row = this [index];
Remove (row);
}
internal void RemoveAtInternal (int index)
{
DataGridViewRow row = this [index];
RemoveInternal (row);
}
public DataGridViewRow SharedRow (int rowIndex)
{
return (DataGridViewRow) list [rowIndex];
}
internal int SharedRowIndexOf (DataGridViewRow row)
{
return list.IndexOf (row);
}
protected DataGridView DataGridView {
get { return dataGridView; }
}
protected ArrayList List {
get { return list; }
}
protected virtual void OnCollectionChanged (CollectionChangeEventArgs e)
{
if (CollectionChanged != null)
CollectionChanged (this, e);
}
internal void AddInternal (DataGridViewRow dataGridViewRow, bool sharable)
{
raiseEvent = false;
AddCore (dataGridViewRow, sharable);
raiseEvent = true;
}
internal ArrayList RowIndexSortedArrayList {
get {
ArrayList result = (ArrayList) list.Clone();
result.Sort(new RowIndexComparator());
return result;
}
}
internal void ReIndex ()
{
for (int i = 0; i < Count; i++)
(list[i] as DataGridViewRow).SetIndex (i);
}
internal void Sort (IComparer comparer)
{
// Note: you will probably want to call
// invalidate after using this.
if (DataGridView != null && DataGridView.EditingRow != null)
list.Sort (0, Count - 1, comparer);
else
list.Sort (comparer);
for (int i = 0; i < list.Count; i++)
(list[i] as DataGridViewRow).SetIndex (i);
}
private class RowIndexComparator : IComparer
{
public int Compare (object o1, object o2)
{
DataGridViewRow row1 = (DataGridViewRow) o1;
DataGridViewRow row2 = (DataGridViewRow) o2;
if (row1.Index < row2.Index) {
return -1;
} else if (row1.Index > row2.Index) {
return 1;
} else {
return 0;
}
}
}
}
}
| 29.305743 | 137 | 0.698715 | [
"Apache-2.0"
] | CRivlaldo/mono | mcs/class/Managed.Windows.Forms/System.Windows.Forms/DataGridViewRowCollection.cs | 17,351 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AsyncGenerator.Tests.TryCatch.Input
{
public class VirtualAutoProperty
{
public virtual bool Success { get; set; }
public int Test()
{
return Success ? 1 : 0;
}
public void Test2()
{
Success = true;
}
public VirtualAutoProperty Create()
{
return new VirtualAutoProperty { Success = true };
}
}
}
| 15.827586 | 53 | 0.697168 | [
"MIT"
] | bubdm/AsyncGenerator | Source/AsyncGenerator.Tests/TryCatch/Input/VirtualAutoProperty.cs | 461 | C# |
using Microsoft.Azure.Commands.Resources.Models;
using Microsoft.Azure.Management.WebSites.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Microsoft.Azure.Commands.WebApps.Utilities
{
public static class CmdletHelpers
{
public static HashSet<string> SiteConfigParameters = new HashSet<string>
{
"DefaultDocuments",
"NetFrameworkVersion",
"PhpVersion",
"RequestTracingEnabled",
"HttpLoggingEnabled",
"DetailedErrorLoggingEnabled",
"HandlerMappings",
"ManagedPipelineMode",
"WebSocketsEnabled",
"Use32BitWorkerProcess",
"AutoSwapSlotName",
"NumberOfWorkers"
};
private static readonly Regex AppWithSlotNameRegex = new Regex(@"^(?<siteName>[^\(]+)\((?<slotName>[^\)]+)\)$");
private static readonly Regex WebAppResourceIdRegex =
new Regex(@"^\/subscriptions\/(?<subscriptionName>[^\/]+)\/resourceGroups\/(?<resourceGroupName>[^\/]+)\/providers\/Microsoft.Web\/sites\/(?<siteName>[^\/]+)$", RegexOptions.IgnoreCase);
private static readonly Regex WebAppSlotResourceIdRegex =
new Regex(@"^\/subscriptions\/(?<subscriptionName>[^\/]+)\/resourceGroups\/(?<resourceGroupName>[^\/]+)\/providers\/Microsoft.Web\/sites\/(?<siteName>[^\/]+)\/slots\/(?<slotName>[^\/]+)$", RegexOptions.IgnoreCase);
private static readonly Regex AppServicePlanResourceIdRegex =
new Regex(@"^\/subscriptions\/(?<subscriptionName>[^\/]+)\/resourceGroups\/(?<resourceGroupName>[^\/]+)\/providers\/Microsoft.Web\/serverFarms\/(?<serverFarmName>[^\/]+)$", RegexOptions.IgnoreCase);
private static readonly Dictionary<string, int> WorkerSizes = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase) { { "Small", 1 }, { "Medium", 2 }, { "Large", 3 }, { "ExtraLarge", 4 } };
private const string ProductionSlotName = "Production";
private const string FmtSiteWithSlotName = "{0}({1})";
public const string ApplicationServiceEnvironmentResourcesName = "hostingEnvironments";
private const string ApplicationServiceEnvironmentResourceIdFormat =
"/subscriptions/{0}/resourcegroups/{1}/providers/Microsoft.Web/{2}/{3}";
public static Dictionary<string, string> ConvertToStringDictionary(this Hashtable hashtable)
{
return hashtable == null ? null : hashtable.Cast<DictionaryEntry>()
.ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.ToString(), StringComparer.Ordinal);
}
public static Dictionary<string, ConnStringValueTypePair> ConvertToConnectionStringDictionary(this Hashtable hashtable)
{
return hashtable == null ? null : hashtable.Cast<DictionaryEntry>()
.ToDictionary(
kvp => kvp.Key.ToString(), kvp =>
{
var typeValuePair = new Hashtable((Hashtable)kvp.Value, StringComparer.OrdinalIgnoreCase);
#if !NETSTANDARD
var type = (DatabaseServerType?)Enum.Parse(typeof(DatabaseServerType), typeValuePair["Type"].ToString(), true);
#else
var type = (ConnectionStringType)Enum.Parse(typeof(ConnectionStringType), typeValuePair["Type"].ToString(), true);
#endif
return new ConnStringValueTypePair
{
Type = type,
Value = typeValuePair["Value"].ToString()
};
});
}
internal static bool ShouldUseDeploymentSlot(string webSiteName, string slotName, out string qualifiedSiteName)
{
bool result = false;
qualifiedSiteName = webSiteName;
#if !NETSTANDARD
var siteNamePattern = "{0}({1})";
#else
var siteNamePattern = "{0}/{1}";
#endif
if (!string.IsNullOrEmpty(slotName) && !string.Equals(slotName, "Production", StringComparison.OrdinalIgnoreCase))
{
result = true;
qualifiedSiteName = string.Format(siteNamePattern, webSiteName, slotName);
}
return result;
}
internal static HostingEnvironmentProfile CreateHostingEnvironmentProfile(string subscriptionId, string resourceGroupName, string aseResourceGroupName, string aseName)
{
var rg = string.IsNullOrEmpty(aseResourceGroupName) ? resourceGroupName : aseResourceGroupName;
var aseResourceId = CmdletHelpers.GetApplicationServiceEnvironmentResourceId(subscriptionId, rg, aseName);
return new HostingEnvironmentProfile(
aseResourceId,
CmdletHelpers.ApplicationServiceEnvironmentResourcesName,
aseName);
}
internal static string BuildMetricFilter(DateTime? startTime, DateTime? endTime, string timeGrain, IReadOnlyList<string> metricNames)
{
var dateTimeFormat = "yyyy-MM-ddTHH:mm:ssZ";
var filter = "";
if (metricNames != null && metricNames.Count > 0)
{
if (metricNames.Count == 1)
{
filter = "name.value eq '" + metricNames[0] + "'";
}
else
{
filter = "(name.value eq '" + string.Join("' or name.value eq '", metricNames) + "')";
}
}
if (startTime.HasValue)
{
filter += string.Format("and startTime eq {0}", startTime.Value.ToString(dateTimeFormat));
}
if (endTime.HasValue)
{
filter += string.Format("and endTime eq {0}", endTime.Value.ToString(dateTimeFormat));
}
if (!string.IsNullOrWhiteSpace(timeGrain))
{
filter += string.Format("and timeGrain eq duration'{0}'", timeGrain);
}
return filter;
}
internal static bool TryParseWebAppMetadataFromResourceId(string resourceId, out string resourceGroupName,
out string webAppName, out string slotName, bool failIfSlot = false)
{
var match = WebAppSlotResourceIdRegex.Match(resourceId);
if (match.Success)
{
resourceGroupName = match.Groups["resourceGroupName"].Value;
webAppName = match.Groups["siteName"].Value;
slotName = match.Groups["slotName"].Value;
return !failIfSlot & true;
}
match = WebAppResourceIdRegex.Match(resourceId);
if (match.Success)
{
resourceGroupName = match.Groups["resourceGroupName"].Value;
webAppName = match.Groups["siteName"].Value;
slotName = null;
return true;
}
resourceGroupName = null;
webAppName = null;
slotName = null;
return false;
}
internal static bool TryParseAppServicePlanMetadataFromResourceId(string resourceId, out string resourceGroupName,
out string appServicePlanName)
{
var match = AppServicePlanResourceIdRegex.Match(resourceId);
if (match.Success)
{
resourceGroupName = match.Groups["resourceGroupName"].Value;
appServicePlanName = match.Groups["serverFarmName"].Value;
return true;
}
resourceGroupName = null;
appServicePlanName = null;
return false;
}
internal static string GetSkuName(string tier, int workerSize)
{
string sku;
if (string.Equals("Shared", tier, StringComparison.OrdinalIgnoreCase))
{
sku = "D";
}
else
{
sku = string.Empty + tier[0];
}
sku += workerSize;
return sku;
}
internal static string GetSkuName(string tier, string workerSize)
{
string sku;
if (string.Equals("Shared", tier, StringComparison.OrdinalIgnoreCase))
{
sku = "D";
}
else
{
sku = string.Empty + tier[0];
}
sku += WorkerSizes[workerSize];
return sku;
}
internal static bool IsDeploymentSlot(string name)
{
return AppWithSlotNameRegex.IsMatch(name);
}
internal static bool TryParseAppAndSlotNames(string name, out string webAppName, out string slotName)
{
var match = AppWithSlotNameRegex.Match(name);
if (match.Success)
{
webAppName = match.Groups["siteName"].Value;
slotName = match.Groups["slotName"].Value;
return true;
}
webAppName = name;
slotName = null;
return false;
}
public static string GenerateSiteWithSlotName(string siteName, string slotName)
{
if (!string.IsNullOrEmpty(slotName) && !string.Equals(slotName, ProductionSlotName, StringComparison.OrdinalIgnoreCase))
{
return string.Format(FmtSiteWithSlotName, siteName, slotName);
}
return siteName;
}
internal static string GetApplicationServiceEnvironmentResourceId(string subscriptionId, string resourceGroupName, string applicationServiceEnvironmentName)
{
return string.Format(ApplicationServiceEnvironmentResourceIdFormat, subscriptionId, resourceGroupName, ApplicationServiceEnvironmentResourcesName,
applicationServiceEnvironmentName);
}
internal static HostNameSslState[] GetHostNameSslStatesFromSiteResponse(Site site, string hostName = null)
{
var hostNameSslState = new HostNameSslState[0];
if (site.HostNameSslStates != null)
{
hostNameSslState = site.HostNameSslStates.Where(h => h.SslState.HasValue && h.SslState.Value != SslState.Disabled).ToArray();
if (!string.IsNullOrEmpty(hostName))
{
hostNameSslState = hostNameSslState.Where(h => string.Equals(h.Name, hostName)).ToArray();
}
}
return hostNameSslState;
}
internal static string GetResourceGroupFromResourceId(string resourceId)
{
return new ResourceIdentifier(resourceId).ResourceGroupName;
}
internal static void ExtractWebAppPropertiesFromWebApp(Site webapp, out string resourceGroupName, out string webAppName, out string slot)
{
resourceGroupName = GetResourceGroupFromResourceId(webapp.Id);
string webAppNameTemp, slotNameTemp;
if (TryParseAppAndSlotNames(
#if !NETSTANDARD
webapp.SiteName,
#else
webapp.Name,
#endif
out webAppNameTemp,
out slotNameTemp))
{
webAppName = webAppNameTemp;
slot = slotNameTemp;
}
else
{
webAppName = webapp.Name;
slot = null;
}
}
internal static Certificate[] GetCertificates(ResourcesClient resourceClient, WebsitesClient websitesClient, string resourceGroupName, string thumbPrint)
{
var certificateResources = resourceClient.FilterPSResources(new BasePSResourceParameters()
{
ResourceType = "Microsoft.Web/Certificates"
}).ToArray();
if (!string.IsNullOrEmpty(resourceGroupName))
{
certificateResources = certificateResources.Where(c => string.Equals(c.ResourceGroupName, resourceGroupName, StringComparison.OrdinalIgnoreCase)).ToArray();
}
var certificates =
certificateResources.Select(
certificateResource =>
websitesClient.GetCertificate(certificateResource.ResourceGroupName, certificateResource.Name));
if (!string.IsNullOrEmpty(thumbPrint))
{
certificates = certificates.Where(c => string.Equals(c.Thumbprint, thumbPrint, StringComparison.OrdinalIgnoreCase)).ToList();
}
return certificates.ToArray();
}
}
}
| 40.374613 | 226 | 0.572502 | [
"MIT"
] | janaks09/azure-powershell | src/ResourceManager/Websites/Commands.Websites/Utilities/CmdletHelpers.cs | 12,721 | 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.Containers.ContainerRegistry
{
/// <summary> Manifest attributes. </summary>
public partial class AcrManifests
{
/// <summary> Initializes a new instance of AcrManifests. </summary>
internal AcrManifests()
{
ManifestsAttributes = new ChangeTrackingList<ManifestAttributesBase>();
}
/// <summary> Initializes a new instance of AcrManifests. </summary>
/// <param name="registry"> Registry name. </param>
/// <param name="imageName"> Image name. </param>
/// <param name="manifestsAttributes"> List of manifests. </param>
internal AcrManifests(string registry, string imageName, IReadOnlyList<ManifestAttributesBase> manifestsAttributes)
{
Registry = registry;
ImageName = imageName;
ManifestsAttributes = manifestsAttributes;
}
/// <summary> Registry name. </summary>
public string Registry { get; }
/// <summary> Image name. </summary>
public string ImageName { get; }
/// <summary> List of manifests. </summary>
public IReadOnlyList<ManifestAttributesBase> ManifestsAttributes { get; }
}
}
| 34.146341 | 123 | 0.648571 | [
"MIT"
] | isra-fel/azure-sdk-for-net | sdk/containerregistry/Azure.Containers.ContainerRegistry/src/Generated/Models/AcrManifests.cs | 1,400 | C# |
namespace XLabs.Forms.Controls
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Xamarin.Forms;
using XLabs.Exceptions;
/// <summary>
/// Low cost control to display a set of clickable items
/// </summary>
/// <typeparam name="T">The Type of viewmodel</typeparam>
public class RepeaterView<T> : StackLayout
where T : class
{
/// <summary>
/// Definition for <see cref="ItemTemplate"/>
/// </summary>
/// Element created at 15/11/2014,3:11 PM by Charles
public static readonly BindableProperty ItemTemplateProperty =
BindableProperty.Create<RepeaterView<T>, DataTemplate>(
p => p.ItemTemplate,
default(DataTemplate));
/// <summary>
/// Definition for <see cref="ItemsSource"/>
/// </summary>
/// Element created at 15/11/2014,3:11 PM by Charles
public static readonly BindableProperty ItemsSourceProperty =
BindableProperty.Create<RepeaterView<T>, IEnumerable<T>>(
p => p.ItemsSource,
Enumerable.Empty<T>(),
BindingMode.OneWay,
null,
ItemsChanged);
/// <summary>
/// Definition for <see cref="ItemClickCommand"/>
/// </summary>
/// Element created at 15/11/2014,3:11 PM by Charles
public static BindableProperty ItemClickCommandProperty =
BindableProperty.Create<RepeaterView<T>, ICommand>(x => x.ItemClickCommand, null);
/// <summary>
/// Definition for <see cref="TemplateSelector"/>
/// </summary>
/// Element created at 15/11/2014,3:12 PM by Charles
public static readonly BindableProperty TemplateSelectorProperty =
BindableProperty.Create<RepeaterView<T>, TemplateSelector>(
x => x.TemplateSelector,
default(TemplateSelector));
/// <summary>
/// Event delegate definition fo the <see cref="ItemCreated"/> event
/// </summary>
/// <param name="sender">The sender(this).</param>
/// <param name="args">The <see cref="RepeaterViewItemAddedEventArgs"/> instance containing the event data.</param>
/// Element created at 15/11/2014,3:12 PM by Charles
public delegate void RepeaterViewItemAddedEventHandler(
object sender,
RepeaterViewItemAddedEventArgs args);
/// <summary>Occurs when a view has been created.</summary>
/// Element created at 15/11/2014,3:13 PM by Charles
public event RepeaterViewItemAddedEventHandler ItemCreated;
/// <summary>
/// The Collection changed handler
/// </summary>
/// Element created at 15/11/2014,3:13 PM by Charles
private IDisposable _collectionChangedHandle;
/// <summary>
/// Initializes a new instance of the <see cref="RepeaterView{T}"/> class.
/// </summary>
/// Element created at 15/11/2014,3:13 PM by Charles
public RepeaterView()
{
Spacing = 0;
}
/// <summary>Gets or sets the items source.</summary>
/// <value>The items source.</value>
/// Element created at 15/11/2014,3:13 PM by Charles
public IEnumerable<T> ItemsSource
{
get { return (IEnumerable<T>)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
/// <summary>Gets or sets the template selector.</summary>
/// <value>The template selector.</value>
/// Element created at 15/11/2014,3:13 PM by Charles
public TemplateSelector TemplateSelector
{
get { return (TemplateSelector)GetValue(TemplateSelectorProperty); }
set { SetValue(TemplateSelectorProperty, value); }
}
/// <summary>Gets or sets the item click command.</summary>
/// <value>The item click command.</value>
/// Element created at 15/11/2014,3:13 PM by Charles
public ICommand ItemClickCommand
{
get { return (ICommand)this.GetValue(ItemClickCommandProperty); }
set { SetValue(ItemClickCommandProperty, value); }
}
/// <summary>
/// The item template property
/// This can be used on it's own or in combination with
/// the <see cref="TemplateSelector"/>
/// </summary>
/// Element created at 15/11/2014,3:10 PM by Charles
public DataTemplate ItemTemplate
{
get { return (DataTemplate)GetValue(ItemTemplateProperty); }
set { SetValue(ItemTemplateProperty, value); }
}
/// <summary>
/// Gives codebehind a chance to play with the
/// newly created view object :D
/// </summary>
/// <param name="view">The visual view object</param>
/// <param name="model">The item being added</param>
protected virtual void NotifyItemAdded(View view, T model)
{
if (ItemCreated != null)
{
ItemCreated(this, new RepeaterViewItemAddedEventArgs(view, model));
}
}
/// <summary>
/// Select a datatemplate dynamically
/// Prefer the TemplateSelector then the DataTemplate
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
protected virtual DataTemplate GetTemplateFor(Type type)
{
DataTemplate retTemplate = null;
if (TemplateSelector != null) retTemplate = TemplateSelector.TemplateFor(type);
return retTemplate ?? ItemTemplate;
}
/// <summary>
/// Creates a view based on the items type
/// While we do have T, T could very well be
/// a common superclass or an interface by
/// using the items actual type we support
/// both inheritance based polymorphism
/// and shape based polymorphism
///
/// </summary>
/// <param name="item"></param>
/// <returns>A View that has been initialized with <see cref="item"/> as it's BindingContext</returns>
/// <exception cref="InvalidVisualObjectException"></exception>Thrown when the matched datatemplate inflates to an object not derived from either
/// <see cref="Xamarin.Forms.View"/> or <see cref="Xamarin.Forms.ViewCell"/>
protected virtual View ViewFor(T item)
{
var template = GetTemplateFor(item.GetType());
var content = template.CreateContent();
if (!(content is View) && !(content is ViewCell)) throw new InvalidVisualObjectException(content.GetType());
var view = (content is View) ? content as View : ((ViewCell)content).View;
view.BindingContext = item;
view.GestureRecognizers.Add(
new TapGestureRecognizer { Command = ItemClickCommand, CommandParameter = item });
return view;
}
/// <summary>
/// Reset the collection of bound objects
/// Remove the old collection changed eventhandler (if any)
/// Create new cells for each new item
/// </summary>
/// <param name="bindable">The control</param>
/// <param name="oldValue">Previous bound collection</param>
/// <param name="newValue">New bound collection</param>
private static void ItemsChanged(
BindableObject bindable,
IEnumerable<T> oldValue,
IEnumerable<T> newValue)
{
var control = bindable as RepeaterView<T>;
if (control == null)
throw new Exception(
"Invalid bindable object passed to ReapterView::ItemsChanged expected a ReapterView<T> received a "
+ bindable.GetType().Name);
if (control._collectionChangedHandle != null)
{
control._collectionChangedHandle.Dispose();
}
control._collectionChangedHandle = new CollectionChangedHandle<View, T>(
control.Children,
newValue,
control.ViewFor,
(v, m, i) => control.NotifyItemAdded(v, m));
}
}
/// <summary>
/// Argument for the <see cref="RepeaterView{T}.ItemCreated"/> event
/// </summary>
/// Element created at 15/11/2014,3:13 PM by Charles
public class RepeaterViewItemAddedEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="RepeaterViewItemAddedEventArgs"/> class.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="model">The model.</param>
/// Element created at 15/11/2014,3:14 PM by Charles
public RepeaterViewItemAddedEventArgs(View view, object model)
{
View = view;
Model = model;
}
/// <summary>Gets or sets the view.</summary>
/// <value>The visual element.</value>
/// Element created at 15/11/2014,3:14 PM by Charles
public View View { get; set; }
/// <summary>Gets or sets the model.</summary>
/// <value>The original viewmodel.</value>
/// Element created at 15/11/2014,3:14 PM by Charles
public object Model { get; set; }
}
}
| 39.894515 | 153 | 0.587837 | [
"Apache-2.0"
] | DarkLotus/Xamarin-Forms-Labs | src/Forms/XLabs.Forms/Controls/RepeaterView.cs | 9,457 | C# |
using AntDesign;
using Maincotech.Cms.Dto;
using Maincotech.Data;
using Maincotech.Localization.Models;
using Maincotech.Logging;
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Maincotech.Cms.Pages.Admin.Category
{
public class CategoryViewModel : ReactiveObject
{
private static ILogger _Logger = AppRuntimeContext.Current.GetLogger<CategoryViewModel>();
private readonly Maincotech.Cms.Services.IAdminService _dataAdminService;
private readonly Maincotech.Localization.ILocalizationService _localizationService;
private bool _IsLoadingParents;
public bool IsLoadingParents
{
get => _IsLoadingParents;
set => this.RaiseAndSetIfChanged(ref _IsLoadingParents, value);
}
private bool _IsLoading;
public bool IsLoading
{
get => _IsLoading;
set => this.RaiseAndSetIfChanged(ref _IsLoading, value);
}
public CategoryViewModel()
{
_dataAdminService = AppRuntimeContext.Current.Resolve<Maincotech.Cms.Services.IAdminService>();
_localizationService = AppRuntimeContext.Current.Resolve<Maincotech.Localization.ILocalizationService>();
}
private string _Icon;
public string Icon
{
get => _Icon;
set => this.RaiseAndSetIfChanged(ref _Icon, value);
}
private string _Name;
public string Name
{
get => _Name;
set => this.RaiseAndSetIfChanged(ref _Name, value);
}
private string _Description;
public string Description
{
get => _Description;
set => this.RaiseAndSetIfChanged(ref _Description, value);
}
private Guid _Id;
public Guid Id
{
get => _Id;
set => this.RaiseAndSetIfChanged(ref _Id, value);
}
private string _ParentId;
public string ParentId
{
get => _ParentId;
set => this.RaiseAndSetIfChanged(ref _ParentId, value);
}
public async Task Load()
{
try
{
IsLoading = true;
var entity = await _dataAdminService.GetCategory(Id);
this.MergeDataFrom(entity.To<CategoryViewModel>());
}
finally
{
IsLoading = false;
}
}
public List<CascaderNode> PossibleParents { get; set; }
public async Task Save()
{
var entity = this.To<CategoryDto>();
await _dataAdminService.CreateOrUpdateCategory(entity);
}
public async Task LoadPossibleParents()
{
if (IsLoadingParents)
{
return;
}
try
{
IsLoadingParents = true;
SortGroup sortGroup = new SortGroup
{
SortRules = new List<SortRule>
{
new SortRule { Field = "Name", SortOrder = SortOrder.Ascending}
}
};
var filters = new FilterCondition();
var allCategories = (await _dataAdminService.GetCategories(sortGroup, filters)).ToList();
PossibleParents = TypeConverters.Convert(allCategories, Id);
//var categories = await _dataAdminService.GetCategories(idsShouldBeExcluded);
// PossibleParents.AddRange(categories);
}
finally
{
IsLoadingParents = false;
}
}
public string GetTermsOfName(string language)
{
var key = $"Category.{Id}.Name"; //TermsHelper.GenerateTermsKey(category, "Name");
var terms = _localizationService.GetTerms(key, language).GetAwaiter().GetResult();
return terms?.Value;
}
public void AddTermsOfName(string language, string terms)
{
var key = $"Category.{Id}.Name";
var entity = new Terms() { Id = Guid.NewGuid(), CultureCode = language, Value = terms, Key = key };
_localizationService.AddOrUpdateTerms(entity);
}
public void AddTermsOfDescription(string language, string terms)
{
var key = $"Category.{Id}.Description";
var entity = new Terms() { Id = Guid.NewGuid(), CultureCode = language, Value = terms, Key = key };
_localizationService.AddOrUpdateTerms(entity);
}
public string GetTermsOfDescription(string language)
{
var key = $"Category.{Id}.Description";
var terms = _localizationService.GetTerms(key, language).GetAwaiter().GetResult();
return terms?.Value;
}
}
} | 30.380368 | 117 | 0.568457 | [
"MIT"
] | maincotech/cms | src/Maincotech.Cms.Blazor/Pages/Admin/Category/CategoryViewModel.cs | 4,954 | C# |
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace TdLib
{
/// <summary>
/// Autogenerated TDLib APIs
/// </summary>
public static partial class TdApi
{
/// <summary>
/// Returns saved order info, if any
/// </summary>
public class GetSavedOrderInfo : Function<OrderInfo>
{
/// <summary>
/// Data type for serialization
/// </summary>
[JsonProperty("@type")]
public override string DataType { get; set; } = "getSavedOrderInfo";
/// <summary>
/// Extra data attached to the function
/// </summary>
[JsonProperty("@extra")]
public override string Extra { get; set; }
}
/// <summary>
/// Returns saved order info, if any
/// </summary>
public static Task<OrderInfo> GetSavedOrderInfoAsync(
this Client client)
{
return client.ExecuteAsync(new GetSavedOrderInfo
{
});
}
}
} | 25.113636 | 80 | 0.509502 | [
"MIT"
] | YogurtTheHorse/tdsharp | TDLib.Api/Functions/GetSavedOrderInfo.cs | 1,105 | C# |
namespace Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights.Common;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.Filtering;
using Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.Implementation;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.Implementation.QuickPulse;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.Implementation.QuickPulse.Helpers;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.Implementation.QuickPulse.PerfLib;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.Implementation.StandardPerformanceCollector;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.Implementation.WebAppPerformanceCollector;
/// <summary>
/// Telemetry module for collecting QuickPulse data.
/// </summary>
public sealed class QuickPulseTelemetryModule : ITelemetryModule, IDisposable
{
#if NETSTANDARD1_6
internal static IQuickPulseModuleScheduler moduleScheduler = QuickPulseTaskModuleScheduler.Instance;
#else
internal static IQuickPulseModuleScheduler moduleScheduler = QuickPulseThreadModuleScheduler.Instance;
#endif
private const int MaxSampleStorageSize = 10;
private const int TopCpuCount = 5;
private readonly object moduleInitializationLock = new object();
private readonly object telemetryProcessorsLock = new object();
private readonly object collectedSamplesLock = new object();
private readonly object performanceCollectorUpdateLock = new object();
private readonly LinkedList<QuickPulseDataSample> collectedSamples = new LinkedList<QuickPulseDataSample>();
private readonly LinkedList<IQuickPulseTelemetryProcessor> telemetryProcessors = new LinkedList<IQuickPulseTelemetryProcessor>();
private TelemetryConfiguration config;
private IQuickPulseServiceClient serviceClient;
private IQuickPulseModuleSchedulerHandle collectionThread;
private IQuickPulseModuleSchedulerHandle stateThread;
private Clock timeProvider;
private QuickPulseTimings timings;
private bool isInitialized = false;
private QuickPulseCollectionTimeSlotManager collectionTimeSlotManager = null;
private IQuickPulseDataAccumulatorManager dataAccumulatorManager = null;
private QuickPulseCollectionStateManager stateManager = null;
private IPerformanceCollector performanceCollector = null;
private IQuickPulseTopCpuCollector topCpuCollector = null;
private CollectionConfiguration collectionConfiguration;
/// <summary>
/// Initializes a new instance of the <see cref="QuickPulseTelemetryModule"/> class.
/// </summary>
public QuickPulseTelemetryModule()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="QuickPulseTelemetryModule"/> class. Internal constructor for unit tests only.
/// </summary>
/// <param name="collectionTimeSlotManager">Collection time slot manager.</param>
/// <param name="dataAccumulatorManager">Data hub to sink QuickPulse data to.</param>
/// <param name="serviceClient">QPS service client.</param>
/// <param name="performanceCollector">Performance counter collector.</param>
/// <param name="topCpuCollector">Top N CPU collector.</param>
/// <param name="timings">Timings for the module.</param>
internal QuickPulseTelemetryModule(
QuickPulseCollectionTimeSlotManager collectionTimeSlotManager,
QuickPulseDataAccumulatorManager dataAccumulatorManager,
IQuickPulseServiceClient serviceClient,
IPerformanceCollector performanceCollector,
IQuickPulseTopCpuCollector topCpuCollector,
QuickPulseTimings timings)
: this()
{
this.collectionTimeSlotManager = collectionTimeSlotManager;
this.dataAccumulatorManager = dataAccumulatorManager;
this.serviceClient = serviceClient;
this.performanceCollector = performanceCollector;
this.topCpuCollector = topCpuCollector;
this.timings = timings;
}
/// <summary>
/// Gets or sets the QuickPulse service endpoint to send to.
/// </summary>
/// <remarks>Loaded from configuration.</remarks>
public string QuickPulseServiceEndpoint { get; set; }
/// <summary>
/// Gets or sets a value indicating whether full telemetry items collection is disabled.
/// </summary>
/// <remarks>Loaded from configuration.</remarks>
public bool DisableFullTelemetryItems { get; set; }
/// <summary>
/// Gets or sets a value indicating whether top CPU processes collection is disabled.
/// </summary>
/// <remarks>Loaded from configuration.</remarks>
public bool DisableTopCpuProcesses { get; set; }
/// <summary>
/// Gets or sets the authentication API key.
/// Authentication API key is created in the Azure Portal for an application and ensures secure distribution of
/// the collection configuration when using QuickPulse.
/// </summary>
/// <remarks>Loaded from configuration.</remarks>
public string AuthenticationApiKey { get; set; }
/// <summary>
/// Disposes resources allocated by this type.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Initialize method is called after all configuration properties have been loaded from the configuration.
/// </summary>
/// <param name="configuration">TelemetryConfiguration passed to the module.</param>
public void Initialize(TelemetryConfiguration configuration)
{
if (!this.isInitialized)
{
lock (this.moduleInitializationLock)
{
if (!this.isInitialized)
{
QuickPulseEventSource.Log.ModuleIsBeingInitializedEvent(
this.QuickPulseServiceEndpoint,
this.DisableFullTelemetryItems,
this.DisableTopCpuProcesses,
this.AuthenticationApiKey);
QuickPulseEventSource.Log.TroubleshootingMessageEvent("Validating configuration...");
ValidateConfiguration(configuration);
this.config = configuration;
QuickPulseEventSource.Log.TroubleshootingMessageEvent("Initializing members...");
this.collectionTimeSlotManager = this.collectionTimeSlotManager ?? new QuickPulseCollectionTimeSlotManager();
this.performanceCollector = this.performanceCollector ??
(PerformanceCounterUtility.IsWebAppRunningInAzure() ? new WebAppPerformanceCollector() : (IPerformanceCollector)new StandardPerformanceCollector());
this.timeProvider = this.timeProvider ?? new Clock();
this.topCpuCollector = this.topCpuCollector
?? new QuickPulseTopCpuCollector(this.timeProvider, new QuickPulseProcessProvider(PerfLib.GetPerfLib()));
this.timings = timings ?? QuickPulseTimings.Default;
CollectionConfigurationError[] errors;
this.collectionConfiguration = new CollectionConfiguration(
new CollectionConfigurationInfo() { ETag = string.Empty },
out errors,
this.timeProvider);
this.dataAccumulatorManager = this.dataAccumulatorManager ?? new QuickPulseDataAccumulatorManager(this.collectionConfiguration);
this.InitializeServiceClient(configuration);
this.stateManager = new QuickPulseCollectionStateManager(
this.serviceClient,
this.timeProvider,
this.timings,
this.OnStartCollection,
this.OnStopCollection,
this.OnSubmitSamples,
this.OnReturnFailedSamples,
this.OnUpdatedConfiguration);
this.CreateStateThread();
this.isInitialized = true;
}
}
}
}
/// <summary>
/// Registers an instance of type <see cref="QuickPulseTelemetryProcessor"/> with this module.
/// </summary>
/// <remarks>This call is only necessary when the module is created in code and not in configuration.</remarks>
/// <param name="telemetryProcessor">QuickPulseTelemetryProcessor instance to be registered with the module.</param>
public void RegisterTelemetryProcessor(ITelemetryProcessor telemetryProcessor)
{
var quickPulseTelemetryProcessor = telemetryProcessor as IQuickPulseTelemetryProcessor;
if (quickPulseTelemetryProcessor == null)
{
throw new ArgumentNullException(nameof(telemetryProcessor), @"The argument must be of type QuickPulseTelemetryProcessor");
}
lock (this.telemetryProcessorsLock)
{
const int MaxTelemetryProcessorCount = 100;
if (!this.telemetryProcessors.Contains(quickPulseTelemetryProcessor))
{
this.telemetryProcessors.AddLast(quickPulseTelemetryProcessor);
if (this.telemetryProcessors.Count > MaxTelemetryProcessorCount)
{
this.telemetryProcessors.RemoveFirst();
}
QuickPulseEventSource.Log.ProcessorRegistered(this.telemetryProcessors.Count.ToString(CultureInfo.InvariantCulture));
}
}
}
[SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "Argument exceptions are valid.")]
private static void ValidateConfiguration(TelemetryConfiguration configuration)
{
if (configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}
if (configuration.TelemetryProcessors == null)
{
throw new ArgumentNullException(nameof(configuration.TelemetryProcessors));
}
}
private void UpdatePerformanceCollector(IEnumerable<Tuple<string, string>> performanceCountersToCollect, out CollectionConfigurationError[] errors)
{
// all counters that need to be collected according to the new configuration - remove duplicates
List<Tuple<string, string>> countersToCollect =
performanceCountersToCollect.GroupBy(counter => counter.Item1, StringComparer.Ordinal)
.Select(group => group.First())
.Concat(
QuickPulseDefaults.DefaultCountersToCollect.Select(defaultCounter => Tuple.Create(defaultCounter.Value, defaultCounter.Value)))
.ToList();
lock (this.performanceCollectorUpdateLock)
{
List<PerformanceCounterData> countersCurrentlyCollected = this.performanceCollector.PerformanceCounters.ToList();
IEnumerable<Tuple<string, string>> countersToRemove =
countersCurrentlyCollected.Where(
counter => !countersToCollect.Any(c => string.Equals(c.Item1, counter.ReportAs, StringComparison.Ordinal)))
.Select(counter => Tuple.Create(counter.ReportAs, counter.OriginalString));
IEnumerable<Tuple<string, string>> countersToAdd =
countersToCollect.Where(
counter => !countersCurrentlyCollected.Any(c => string.Equals(c.ReportAs, counter.Item1, StringComparison.Ordinal)));
// remove counters that should no longer be collected
foreach (var counter in countersToRemove)
{
this.performanceCollector.RemoveCounter(counter.Item2, counter.Item1);
}
var errorsList = new List<CollectionConfigurationError>();
// add counters that should now be collected
foreach (var counter in countersToAdd)
{
try
{
string error;
this.performanceCollector.RegisterCounter(counter.Item2, counter.Item1, true, out error, true);
if (!string.IsNullOrWhiteSpace(error))
{
errorsList.Add(
CollectionConfigurationError.CreateError(
CollectionConfigurationErrorType.PerformanceCounterParsing,
string.Format(CultureInfo.InvariantCulture, "Error parsing performance counter: '{0}'. {1}", counter, error),
null,
Tuple.Create("MetricId", counter.Item1)));
QuickPulseEventSource.Log.CounterParsingFailedEvent(error, counter.Item2);
continue;
}
QuickPulseEventSource.Log.CounterRegisteredEvent(counter.Item2);
}
catch (Exception e)
{
errorsList.Add(
CollectionConfigurationError.CreateError(
CollectionConfigurationErrorType.PerformanceCounterUnexpected,
string.Format(CultureInfo.InvariantCulture, "Unexpected error processing counter '{0}': {1}", counter, e.Message),
e,
Tuple.Create("MetricId", counter.Item1)));
QuickPulseEventSource.Log.CounterRegistrationFailedEvent(e.Message, counter.Item2);
}
}
errors = errorsList.ToArray();
}
}
private void CreateStateThread()
{
this.stateThread = QuickPulseTelemetryModule.moduleScheduler.Execute(this.StateThreadWorker);
}
private void InitializeServiceClient(TelemetryConfiguration configuration)
{
if (this.serviceClient != null)
{
// service client has been passed through a constructor, we don't need to do anything
return;
}
Uri serviceEndpointUri;
if (string.IsNullOrWhiteSpace(this.QuickPulseServiceEndpoint))
{
// endpoint is not specified in configuration, use the default one
serviceEndpointUri = QuickPulseDefaults.ServiceEndpoint;
}
else
{
// endpoint appears to have been specified in configuration, try using it
try
{
serviceEndpointUri = new Uri(this.QuickPulseServiceEndpoint);
}
catch (Exception e)
{
throw new ArgumentException(
string.Format(
CultureInfo.InvariantCulture,
"Error initializing QuickPulse module. QPS endpoint is not a correct URI: '{0}'",
this.QuickPulseServiceEndpoint),
e);
}
}
// create the default production implementation of the service client with the best service endpoint we could get
string instanceName = GetInstanceName(configuration);
string streamId = GetStreamId();
string machineName = Environment.MachineName;
var assemblyVersion = SdkVersionUtils.GetSdkVersion(null);
bool isWebApp = PerformanceCounterUtility.IsWebAppRunningInAzure();
int? processorCount = PerformanceCounterUtility.GetProcessorCount(isWebApp);
this.serviceClient = new QuickPulseServiceClient(
serviceEndpointUri,
instanceName,
streamId,
machineName,
assemblyVersion,
this.timeProvider,
isWebApp,
processorCount ?? 0);
QuickPulseEventSource.Log.TroubleshootingMessageEvent(
string.Format(
CultureInfo.InvariantCulture,
"Service client initialized. Endpoint: '{0}', instance name: '{1}', assembly version: '{2}'",
serviceEndpointUri,
instanceName,
assemblyVersion));
}
private static string GetInstanceName(TelemetryConfiguration configuration)
{
// we need to initialize an item to get instance information
var fakeItem = new EventTelemetry();
try
{
new TelemetryClient(configuration).Initialize(fakeItem);
}
catch (Exception)
{
// we don't care what happened there
}
return string.IsNullOrWhiteSpace(fakeItem.Context?.Cloud?.RoleInstance) ? Environment.MachineName : fakeItem.Context.Cloud.RoleInstance;
}
private static string GetStreamId()
{
return Guid.NewGuid().ToStringInvariant("N");
}
private static QuickPulseDataSample CreateDataSample(
QuickPulseDataAccumulator accumulator,
IEnumerable<Tuple<PerformanceCounterData, double>> perfData,
IEnumerable<Tuple<string, int>> topCpuData,
bool topCpuDataAccessDenied)
{
return new QuickPulseDataSample(
accumulator,
perfData.ToDictionary(tuple => tuple.Item1.ReportAs, tuple => tuple),
topCpuData,
topCpuDataAccessDenied);
}
private void StateThreadWorker(CancellationToken cancellationToken)
{
SdkInternalOperationsMonitor.Enter();
var stopwatch = new Stopwatch();
TimeSpan? timeToNextUpdate = null;
while (true)
{
var currentCallbackStarted = this.timeProvider.UtcNow;
try
{
if (cancellationToken.IsCancellationRequested)
{
SdkInternalOperationsMonitor.Exit();
return;
}
stopwatch.Restart();
timeToNextUpdate = this.stateManager.UpdateState(this.config.InstrumentationKey, this.AuthenticationApiKey);
QuickPulseEventSource.Log.StateTimerTickFinishedEvent(stopwatch.ElapsedMilliseconds);
}
catch (Exception e)
{
QuickPulseEventSource.Log.UnknownErrorEvent(e.ToInvariantString());
}
// the catastrophic fallback is for the case when we've catastrophically failed some place above
timeToNextUpdate = timeToNextUpdate ?? this.timings.CatastrophicFailureTimeout;
// try to factor in the time spend in this tick when scheduling the next one so that the average period is close to the intended
TimeSpan timeSpentInThisTick = this.timeProvider.UtcNow - currentCallbackStarted;
TimeSpan timeLeftUntilNextTick = timeToNextUpdate.Value - timeSpentInThisTick;
timeLeftUntilNextTick = timeLeftUntilNextTick > TimeSpan.Zero ? timeLeftUntilNextTick : TimeSpan.Zero;
try
{
Task.Delay(timeLeftUntilNextTick, cancellationToken).GetAwaiter().GetResult();
}
catch (OperationCanceledException)
{
}
}
}
private void CollectionThreadWorker(CancellationToken cancellationToken)
{
SdkInternalOperationsMonitor.Enter();
var stopwatch = new Stopwatch();
this.InitializeCollectionThread();
while (true)
{
try
{
if (cancellationToken.IsCancellationRequested)
{
this.CloseCollectionThread();
SdkInternalOperationsMonitor.Exit();
return;
}
stopwatch.Restart();
this.CollectData();
QuickPulseEventSource.Log.CollectionTimerTickFinishedEvent(stopwatch.ElapsedMilliseconds);
}
catch (Exception e)
{
QuickPulseEventSource.Log.UnknownErrorEvent(e.ToInvariantString());
}
DateTimeOffset nextTick = this.collectionTimeSlotManager.GetNextCollectionTimeSlot(this.timeProvider.UtcNow);
TimeSpan timeLeftUntilNextTick = nextTick - this.timeProvider.UtcNow;
timeLeftUntilNextTick = timeLeftUntilNextTick > TimeSpan.Zero ? timeLeftUntilNextTick : TimeSpan.Zero;
try
{
Task.Delay(timeLeftUntilNextTick, cancellationToken).GetAwaiter().GetResult();
}
catch (OperationCanceledException)
{
}
}
}
private void InitializeCollectionThread()
{
try
{
this.topCpuCollector.Initialize();
}
catch (Exception e)
{
// whatever happened, don't bring the thread down
QuickPulseEventSource.Log.UnknownErrorEvent(e.ToInvariantString());
}
}
private void CloseCollectionThread()
{
try
{
this.topCpuCollector.Close();
}
catch (Exception e)
{
// whatever happened, don't bring the thread down
QuickPulseEventSource.Log.UnknownErrorEvent(e.ToInvariantString());
}
}
private void CollectData()
{
var sample = this.CollectSample();
this.StoreSample(sample);
}
private void StoreSample(QuickPulseDataSample sample)
{
lock (this.collectedSamplesLock)
{
QuickPulseEventSource.Log.SampleStoredEvent(this.collectedSamples.Count + 1);
this.collectedSamples.AddLast(sample);
while (this.collectedSamples.Count > MaxSampleStorageSize)
{
this.collectedSamples.RemoveFirst();
}
}
}
private QuickPulseDataSample CollectSample()
{
// For AI data, all we have to do is lock the current accumulator in
// use the latest collection configuration info set by the state thread to create the new accumulator
QuickPulseDataAccumulator completeAccumulator = this.dataAccumulatorManager.CompleteCurrentDataAccumulator(this.collectionConfiguration);
// For performance collection, we have to read perf samples from Windows
List<Tuple<PerformanceCounterData, double>> perfData;
lock (this.performanceCollectorUpdateLock)
{
perfData =
this.performanceCollector.Collect(
(counterName, e) => QuickPulseEventSource.Log.CounterReadingFailedEvent(e.ToString(), counterName)).ToList();
}
// For top N CPU, we have to get data from the provider
IEnumerable<Tuple<string, int>> topCpuData = this.DisableTopCpuProcesses
? Enumerable.Empty<Tuple<string, int>>()
: this.topCpuCollector.GetTopProcessesByCpu(TopCpuCount);
return CreateDataSample(completeAccumulator, perfData, topCpuData, this.topCpuCollector.AccessDenied);
}
#region Callbacks from the state manager
private void OnStartCollection()
{
QuickPulseEventSource.Log.TroubleshootingMessageEvent("Starting collection...");
this.EndCollectionThread();
CollectionConfigurationError[] errors;
this.UpdatePerformanceCollector(this.collectionConfiguration.PerformanceCounters, out errors);
this.dataAccumulatorManager.CompleteCurrentDataAccumulator(this.collectionConfiguration);
lock (this.telemetryProcessorsLock)
{
foreach (var telemetryProcessor in this.telemetryProcessors)
{
telemetryProcessor.StartCollection(
this.dataAccumulatorManager,
this.serviceClient.ServiceUri,
this.config,
this.DisableFullTelemetryItems);
}
}
this.CreateCollectionThread();
}
private void CreateCollectionThread()
{
this.collectionThread = QuickPulseTelemetryModule.moduleScheduler.Execute(this.CollectionThreadWorker);
}
private void EndCollectionThread()
{
Interlocked.Exchange(ref this.collectionThread, null)?.Stop(wait: false);
}
private void OnStopCollection()
{
QuickPulseEventSource.Log.TroubleshootingMessageEvent("Stopping collection...");
this.EndCollectionThread();
lock (this.telemetryProcessorsLock)
{
foreach (var telemetryProcessor in this.telemetryProcessors)
{
telemetryProcessor.StopCollection();
}
}
lock (this.collectedSamplesLock)
{
this.collectedSamples.Clear();
}
}
private IList<QuickPulseDataSample> OnSubmitSamples()
{
IList<QuickPulseDataSample> samples;
lock (this.collectedSamplesLock)
{
samples = this.collectedSamples.ToList();
this.collectedSamples.Clear();
}
return samples;
}
private void OnReturnFailedSamples(IList<QuickPulseDataSample> samples)
{
// append the samples that failed to get sent out back to the beginning of the list
// these will be pushed out as newer samples arrive, so we'll never get more than a certain number
// even if the network is lagging behind
QuickPulseEventSource.Log.TroubleshootingMessageEvent("Returning samples...");
lock (this.collectedSamplesLock)
{
foreach (var sample in samples)
{
this.collectedSamples.AddFirst(sample);
}
while (this.collectedSamples.Count > MaxSampleStorageSize)
{
this.collectedSamples.RemoveFirst();
}
}
}
private CollectionConfigurationError[] OnUpdatedConfiguration(CollectionConfigurationInfo configurationInfo)
{
// we need to preserve the current quota for each document stream that still exists in the new configuration
CollectionConfigurationError[] errorsConfig;
var newCollectionConfiguration = new CollectionConfiguration(configurationInfo, out errorsConfig, this.timeProvider, this.collectionConfiguration?.DocumentStreams);
// the next accumulator that gets swapped in on the collection thread will be initialized with the new collection configuration
Interlocked.Exchange(ref this.collectionConfiguration, newCollectionConfiguration);
CollectionConfigurationError[] errorsPerformanceCounters;
this.UpdatePerformanceCollector(newCollectionConfiguration.PerformanceCounters, out errorsPerformanceCounters);
return errorsConfig.Concat(errorsPerformanceCounters).ToArray();
}
#endregion
/// <summary>
/// Dispose implementation.
/// </summary>
private void Dispose(bool disposing)
{
if (disposing)
{
Interlocked.Exchange(ref this.stateThread, null)?.Stop(wait: true);
Interlocked.Exchange(ref this.collectionThread, null)?.Stop(wait: true);
this.serviceClient.Dispose();
}
}
}
} | 42.495739 | 176 | 0.597085 | [
"MIT"
] | vijayraavi/ApplicationInsights-dotnet-server | Src/PerformanceCollector/Perf.Shared/QuickPulseTelemetryModule.cs | 29,919 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/d3d10.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="ID3D10Buffer" /> struct.</summary>
public static unsafe class ID3D10BufferTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="ID3D10Buffer" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(ID3D10Buffer).GUID, Is.EqualTo(IID_ID3D10Buffer));
}
/// <summary>Validates that the <see cref="ID3D10Buffer" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<ID3D10Buffer>(), Is.EqualTo(sizeof(ID3D10Buffer)));
}
/// <summary>Validates that the <see cref="ID3D10Buffer" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(ID3D10Buffer).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="ID3D10Buffer" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(ID3D10Buffer), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(ID3D10Buffer), Is.EqualTo(4));
}
}
}
}
| 35.807692 | 145 | 0.624597 | [
"MIT"
] | Perksey/terrafx.interop.windows | tests/Interop/Windows/um/d3d10/ID3D10BufferTests.cs | 1,864 | C# |
using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Security.Authentication;
using System.Text;
using System.Threading;
using System.Xml.Linq;
using Wexflow.Core;
namespace Wexflow.Tasks.HttpPut
{
public class HttpPut : Task
{
private const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
private const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
public string Url { get; private set; }
public NameValueCollection Params { get; private set; }
public HttpPut(XElement xe, Workflow wf) : base(xe, wf)
{
Url = GetSetting("url");
var parameters = GetSetting("params");
var parametersArray = parameters.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
Params = new NameValueCollection();
foreach (var param in parametersArray)
{
var paramKv = param.Split('=');
Params.Add(paramKv[0], paramKv[1]);
}
}
public override TaskStatus Run()
{
Info("Executing PUT request...");
var status = Status.Success;
try
{
using (var client = new WebClient())
{
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = Tls12;
var response = client.UploadValues(Url, "PUT", Params);
var responseString = Encoding.Default.GetString(response);
var destFile = Path.Combine(Workflow.WorkflowTempFolder, string.Format("HttpPut_{0:yyyy-MM-dd-HH-mm-ss-fff}.txt", DateTime.Now));
File.WriteAllText(destFile, responseString);
Files.Add(new FileInf(destFile, Id));
InfoFormat("PUT request {0} executed whith success -> {1}", Url, destFile);
}
}
catch (ThreadAbortException)
{
throw;
}
catch (Exception e)
{
ErrorFormat("An error occured while executing the PUT request {0}: {1}", Url, e.Message);
status = Status.Error;
}
Info("Task finished.");
return new TaskStatus(status);
}
}
}
| 36.552239 | 150 | 0.54512 | [
"MIT"
] | mohammad-matini/wexflow | src/dotnet-core/Wexflow.Tasks.HttpPut/HttpPut.cs | 2,451 | C# |
using System;
public class Pet : ISubject, ISubjectWithBirthdate
{
public Pet(string name, DateTime birthdate)
{
Name = name;
Birthdate = birthdate;
}
public string Name { get; set; }
public DateTime Birthdate { get; set; }
} | 18.928571 | 50 | 0.630189 | [
"MIT"
] | IvelinMarinov/SoftUni | 06. OOP Advanced - Jul2017/01. Interfaces and Abstraction - Exercise/06. Birthday Celebrations/Pet.cs | 267 | C# |
using System;
namespace Hydrogen.General.Model
{
public interface ILastModificationTime
{
DateTime LastModificationTime { get; set; }
}
} | 16.333333 | 45 | 0.748299 | [
"MIT"
] | clay-one/hydrogen | src/General/Model/ILastModificationTime.cs | 149 | C# |
/*
* ORY Oathkeeper
*
* ORY Oathkeeper is a reverse proxy that checks the HTTP Authorization for validity against a set of rules. This service uses Hydra to validate access tokens and policies.
*
* The version of the OpenAPI document: v0.0.0-alpha.38
* Contact: hi@ory.am
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Xunit;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Ory.Oathkeeper.Client.Api;
using Ory.Oathkeeper.Client.Model;
using Ory.Oathkeeper.Client.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace Ory.Oathkeeper.Client.Test.Model
{
/// <summary>
/// Class for testing OathkeeperGetWellKnownOK
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class OathkeeperGetWellKnownOKTests : IDisposable
{
// TODO uncomment below to declare an instance variable for OathkeeperGetWellKnownOK
//private OathkeeperGetWellKnownOK instance;
public OathkeeperGetWellKnownOKTests()
{
// TODO uncomment below to create an instance of OathkeeperGetWellKnownOK
//instance = new OathkeeperGetWellKnownOK();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of OathkeeperGetWellKnownOK
/// </summary>
[Fact]
public void OathkeeperGetWellKnownOKInstanceTest()
{
// TODO uncomment below to test "IsType" OathkeeperGetWellKnownOK
//Assert.IsType<OathkeeperGetWellKnownOK>(instance);
}
/// <summary>
/// Test the property 'Payload'
/// </summary>
[Fact]
public void PayloadTest()
{
// TODO unit test for the property 'Payload'
}
}
}
| 28.111111 | 172 | 0.653656 | [
"Apache-2.0"
] | GRoguelon/sdk | clients/oathkeeper/dotnet/src/Ory.Oathkeeper.Client.Test/Model/OathkeeperGetWellKnownOKTests.cs | 2,024 | C# |
using System;
using TicTacToe.Models;
using Xamarin.Forms;
using System.ComponentModel;
namespace TicTacToe
{
public partial class GamePage : ContentPage, INotifyPropertyChanged
{
public GameState Game;
public GamePage()
{
InitializeComponent();
NewGame();
}
public void OnNewGameTapped(object sender, EventArgs args)
{
NewGame();
}
public void NewGame()
{
Game = new GameState();
UpdateGameView();
}
public void Move(object sender, EventArgs args)
{
GameButton button = sender as GameButton;
if (Game.Squares[button.Location].CanInteract && Game.GameStatus == Status.InProgress)
{
Move move = new Move();
move.Player = Game.NextMove;
move.Location = button.Location;
Game.Moves.Add(move);
Game.UpdateState();
UpdateGameView();
}
}
public void UpdateGameView()
{
Game_Message.Text = Game.Message;
foreach (GameSquare g in Game.Squares)
{
switch (g.Location)
{
case 0:
Square_0.Text = g.Text; Square_0.BackgroundColor = g.SquareColor;
break;
case 1:
Square_1.Text = g.Text; Square_1.BackgroundColor = g.SquareColor;
break;
case 2:
Square_2.Text = g.Text; Square_2.BackgroundColor = g.SquareColor;
break;
case 3:
Square_3.Text = g.Text; Square_3.BackgroundColor = g.SquareColor;
break;
case 4:
Square_4.Text = g.Text; Square_4.BackgroundColor = g.SquareColor;
break;
case 5:
Square_5.Text = g.Text; Square_5.BackgroundColor = g.SquareColor;
break;
case 6:
Square_6.Text = g.Text; Square_6.BackgroundColor = g.SquareColor;
break;
case 7:
Square_7.Text = g.Text; Square_7.BackgroundColor = g.SquareColor;
break;
case 8:
Square_8.Text = g.Text; Square_8.BackgroundColor = g.SquareColor;
break;
default:
break;
}
}
}
}
}
| 32.357143 | 98 | 0.452171 | [
"MIT"
] | CrimsonKyle/TicTacToe | TicTacToe/Views/GamePage.xaml.cs | 2,720 | C# |
namespace Restaurant
{
using Restaurant.Core;
public class StartUp
{
public static void Main(string[] args)
{
Engine engine = new Engine();
engine.Run();
}
}
}
| 16.142857 | 46 | 0.513274 | [
"MIT"
] | vesy53/SoftUni | C# Advanced/C# OOP/LabAndExercises/04.InheritanceExercisePart2/Restaurant/StartUp.cs | 228 | C# |
using System;
using System.IO;
namespace ICSharpCode.SharpZipLib.Lzw
{
/// <summary>
/// This filter stream is used to decompress a LZW format stream.
/// Specifically, a stream that uses the LZC compression method.
/// This file format is usually associated with the .Z file extension.
///
/// See http://en.wikipedia.org/wiki/Compress
/// See http://wiki.wxwidgets.org/Development:_Z_File_Format
///
/// The file header consists of 3 (or optionally 4) bytes. The first two bytes
/// contain the magic marker "0x1f 0x9d", followed by a byte of flags.
///
/// Based on Java code by Ronald Tschalar, which in turn was based on the unlzw.c
/// code in the gzip package.
/// </summary>
/// <example> This sample shows how to unzip a compressed file
/// <code>
/// using System;
/// using System.IO;
///
/// using ICSharpCode.SharpZipLib.Core;
/// using ICSharpCode.SharpZipLib.LZW;
///
/// class MainClass
/// {
/// public static void Main(string[] args)
/// {
/// using (Stream inStream = new LzwInputStream(File.OpenRead(args[0])))
/// using (FileStream outStream = File.Create(Path.GetFileNameWithoutExtension(args[0]))) {
/// byte[] buffer = new byte[4096];
/// StreamUtils.Copy(inStream, outStream, buffer);
/// // OR
/// inStream.Read(buffer, 0, buffer.Length);
/// // now do something with the buffer
/// }
/// }
/// }
/// </code>
/// </example>
public class LzwInputStream : Stream
{
/// <summary>
/// Gets or sets a flag indicating ownership of underlying stream.
/// When the flag is true <see cref="Stream.Dispose()" /> will close the underlying stream also.
/// </summary>
/// <remarks>The default value is true.</remarks>
public bool IsStreamOwner { get; set; } = true;
/// <summary>
/// Creates a LzwInputStream
/// </summary>
/// <param name="baseInputStream">
/// The stream to read compressed data from (baseInputStream LZW format)
/// </param>
public LzwInputStream(Stream baseInputStream)
{
this.baseInputStream = baseInputStream;
}
/// <summary>
/// See <see cref="System.IO.Stream.ReadByte"/>
/// </summary>
/// <returns></returns>
public override int ReadByte()
{
int b = Read(one, 0, 1);
if (b == 1)
return (one[0] & 0xff);
return -1;
}
/// <summary>
/// Reads decompressed data into the provided buffer byte array
/// </summary>
/// <param name ="buffer">
/// The array to read and decompress data into
/// </param>
/// <param name ="offset">
/// The offset indicating where the data should be placed
/// </param>
/// <param name ="count">
/// The number of bytes to decompress
/// </param>
/// <returns>The number of bytes read. Zero signals the end of stream</returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (!headerParsed)
ParseHeader();
if (eof)
return 0;
int start = offset;
/* Using local copies of various variables speeds things up by as
* much as 30% in Java! Performance not tested in C#.
*/
int[] lTabPrefix = tabPrefix;
byte[] lTabSuffix = tabSuffix;
byte[] lStack = stack;
int lNBits = nBits;
int lMaxCode = maxCode;
int lMaxMaxCode = maxMaxCode;
int lBitMask = bitMask;
int lOldCode = oldCode;
byte lFinChar = finChar;
int lStackP = stackP;
int lFreeEnt = freeEnt;
byte[] lData = data;
int lBitPos = bitPos;
// empty stack if stuff still left
int sSize = lStack.Length - lStackP;
if (sSize > 0) {
int num = (sSize >= count) ? count : sSize;
Array.Copy(lStack, lStackP, buffer, offset, num);
offset += num;
count -= num;
lStackP += num;
}
if (count == 0) {
stackP = lStackP;
return offset - start;
}
// loop, filling local buffer until enough data has been decompressed
MainLoop:
do {
if (end < EXTRA) {
Fill();
}
int bitIn = (got > 0) ? (end - end % lNBits) << 3 :
(end << 3) - (lNBits - 1);
while (lBitPos < bitIn) {
#region A
// handle 1-byte reads correctly
if (count == 0) {
nBits = lNBits;
maxCode = lMaxCode;
maxMaxCode = lMaxMaxCode;
bitMask = lBitMask;
oldCode = lOldCode;
finChar = lFinChar;
stackP = lStackP;
freeEnt = lFreeEnt;
bitPos = lBitPos;
return offset - start;
}
// check for code-width expansion
if (lFreeEnt > lMaxCode) {
int nBytes = lNBits << 3;
lBitPos = (lBitPos - 1) +
nBytes - (lBitPos - 1 + nBytes) % nBytes;
lNBits++;
lMaxCode = (lNBits == maxBits) ? lMaxMaxCode :
(1 << lNBits) - 1;
lBitMask = (1 << lNBits) - 1;
lBitPos = ResetBuf(lBitPos);
goto MainLoop;
}
#endregion
#region B
// read next code
int pos = lBitPos >> 3;
int code = (((lData[pos] & 0xFF) |
((lData[pos + 1] & 0xFF) << 8) |
((lData[pos + 2] & 0xFF) << 16)) >>
(lBitPos & 0x7)) & lBitMask;
lBitPos += lNBits;
// handle first iteration
if (lOldCode == -1) {
if (code >= 256)
throw new LzwException("corrupt input: " + code + " > 255");
lFinChar = (byte)(lOldCode = code);
buffer[offset++] = lFinChar;
count--;
continue;
}
// handle CLEAR code
if (code == TBL_CLEAR && blockMode) {
Array.Copy(zeros, 0, lTabPrefix, 0, zeros.Length);
lFreeEnt = TBL_FIRST - 1;
int nBytes = lNBits << 3;
lBitPos = (lBitPos - 1) + nBytes - (lBitPos - 1 + nBytes) % nBytes;
lNBits = LzwConstants.INIT_BITS;
lMaxCode = (1 << lNBits) - 1;
lBitMask = lMaxCode;
// Code tables reset
lBitPos = ResetBuf(lBitPos);
goto MainLoop;
}
#endregion
#region C
// setup
int inCode = code;
lStackP = lStack.Length;
// Handle KwK case
if (code >= lFreeEnt) {
if (code > lFreeEnt) {
throw new LzwException("corrupt input: code=" + code +
", freeEnt=" + lFreeEnt);
}
lStack[--lStackP] = lFinChar;
code = lOldCode;
}
// Generate output characters in reverse order
while (code >= 256) {
lStack[--lStackP] = lTabSuffix[code];
code = lTabPrefix[code];
}
lFinChar = lTabSuffix[code];
buffer[offset++] = lFinChar;
count--;
// And put them out in forward order
sSize = lStack.Length - lStackP;
int num = (sSize >= count) ? count : sSize;
Array.Copy(lStack, lStackP, buffer, offset, num);
offset += num;
count -= num;
lStackP += num;
#endregion
#region D
// generate new entry in table
if (lFreeEnt < lMaxMaxCode) {
lTabPrefix[lFreeEnt] = lOldCode;
lTabSuffix[lFreeEnt] = lFinChar;
lFreeEnt++;
}
// Remember previous code
lOldCode = inCode;
// if output buffer full, then return
if (count == 0) {
nBits = lNBits;
maxCode = lMaxCode;
bitMask = lBitMask;
oldCode = lOldCode;
finChar = lFinChar;
stackP = lStackP;
freeEnt = lFreeEnt;
bitPos = lBitPos;
return offset - start;
}
#endregion
} // while
lBitPos = ResetBuf(lBitPos);
} while (got > 0); // do..while
nBits = lNBits;
maxCode = lMaxCode;
bitMask = lBitMask;
oldCode = lOldCode;
finChar = lFinChar;
stackP = lStackP;
freeEnt = lFreeEnt;
bitPos = lBitPos;
eof = true;
return offset - start;
}
/// <summary>
/// Moves the unread data in the buffer to the beginning and resets
/// the pointers.
/// </summary>
/// <param name="bitPosition"></param>
/// <returns></returns>
private int ResetBuf(int bitPosition)
{
int pos = bitPosition >> 3;
Array.Copy(data, pos, data, 0, end - pos);
end -= pos;
return 0;
}
private void Fill()
{
got = baseInputStream.Read(data, end, data.Length - 1 - end);
if (got > 0) {
end += got;
}
}
private void ParseHeader()
{
headerParsed = true;
byte[] hdr = new byte[LzwConstants.HDR_SIZE];
int result = baseInputStream.Read(hdr, 0, hdr.Length);
// Check the magic marker
if (result < 0)
throw new LzwException("Failed to read LZW header");
if (hdr[0] != (LzwConstants.MAGIC >> 8) || hdr[1] != (LzwConstants.MAGIC & 0xff)) {
throw new LzwException(String.Format(
"Wrong LZW header. Magic bytes don't match. 0x{0:x2} 0x{1:x2}",
hdr[0], hdr[1]));
}
// Check the 3rd header byte
blockMode = (hdr[2] & LzwConstants.BLOCK_MODE_MASK) > 0;
maxBits = hdr[2] & LzwConstants.BIT_MASK;
if (maxBits > LzwConstants.MAX_BITS) {
throw new LzwException("Stream compressed with " + maxBits +
" bits, but decompression can only handle " +
LzwConstants.MAX_BITS + " bits.");
}
if ((hdr[2] & LzwConstants.RESERVED_MASK) > 0) {
throw new LzwException("Unsupported bits set in the header.");
}
// Initialize variables
maxMaxCode = 1 << maxBits;
nBits = LzwConstants.INIT_BITS;
maxCode = (1 << nBits) - 1;
bitMask = maxCode;
oldCode = -1;
finChar = 0;
freeEnt = blockMode ? TBL_FIRST : 256;
tabPrefix = new int[1 << maxBits];
tabSuffix = new byte[1 << maxBits];
stack = new byte[1 << maxBits];
stackP = stack.Length;
for (int idx = 255; idx >= 0; idx--)
tabSuffix[idx] = (byte)idx;
}
#region Stream Overrides
/// <summary>
/// Gets a value indicating whether the current stream supports reading
/// </summary>
public override bool CanRead {
get {
return baseInputStream.CanRead;
}
}
/// <summary>
/// Gets a value of false indicating seeking is not supported for this stream.
/// </summary>
public override bool CanSeek {
get {
return false;
}
}
/// <summary>
/// Gets a value of false indicating that this stream is not writeable.
/// </summary>
public override bool CanWrite {
get {
return false;
}
}
/// <summary>
/// A value representing the length of the stream in bytes.
/// </summary>
public override long Length {
get {
return got;
}
}
/// <summary>
/// The current position within the stream.
/// Throws a NotSupportedException when attempting to set the position
/// </summary>
/// <exception cref="NotSupportedException">Attempting to set the position</exception>
public override long Position {
get {
return baseInputStream.Position;
}
set {
throw new NotSupportedException("InflaterInputStream Position not supported");
}
}
/// <summary>
/// Flushes the baseInputStream
/// </summary>
public override void Flush()
{
baseInputStream.Flush();
}
/// <summary>
/// Sets the position within the current stream
/// Always throws a NotSupportedException
/// </summary>
/// <param name="offset">The relative offset to seek to.</param>
/// <param name="origin">The <see cref="SeekOrigin"/> defining where to seek from.</param>
/// <returns>The new position in the stream.</returns>
/// <exception cref="NotSupportedException">Any access</exception>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException("Seek not supported");
}
/// <summary>
/// Set the length of the current stream
/// Always throws a NotSupportedException
/// </summary>
/// <param name="value">The new length value for the stream.</param>
/// <exception cref="NotSupportedException">Any access</exception>
public override void SetLength(long value)
{
throw new NotSupportedException("InflaterInputStream SetLength not supported");
}
/// <summary>
/// Writes a sequence of bytes to stream and advances the current position
/// This method always throws a NotSupportedException
/// </summary>
/// <param name="buffer">Thew buffer containing data to write.</param>
/// <param name="offset">The offset of the first byte to write.</param>
/// <param name="count">The number of bytes to write.</param>
/// <exception cref="NotSupportedException">Any access</exception>
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException("InflaterInputStream Write not supported");
}
/// <summary>
/// Writes one byte to the current stream and advances the current position
/// Always throws a NotSupportedException
/// </summary>
/// <param name="value">The byte to write.</param>
/// <exception cref="NotSupportedException">Any access</exception>
public override void WriteByte(byte value)
{
throw new NotSupportedException("InflaterInputStream WriteByte not supported");
}
/// <summary>
/// Closes the input stream. When <see cref="IsStreamOwner"></see>
/// is true the underlying stream is also closed.
/// </summary>
protected override void Dispose(bool disposing)
{
if (!isClosed) {
isClosed = true;
if (IsStreamOwner) {
baseInputStream.Dispose();
}
}
}
#endregion
#region Instance Fields
Stream baseInputStream;
/// <summary>
/// Flag indicating wether this instance has been closed or not.
/// </summary>
bool isClosed;
readonly byte[] one = new byte[1];
bool headerParsed;
// string table stuff
private const int TBL_CLEAR = 0x100;
private const int TBL_FIRST = TBL_CLEAR + 1;
private int[] tabPrefix;
private byte[] tabSuffix;
private readonly int[] zeros = new int[256];
private byte[] stack;
// various state
private bool blockMode;
private int nBits;
private int maxBits;
private int maxMaxCode;
private int maxCode;
private int bitMask;
private int oldCode;
private byte finChar;
private int stackP;
private int freeEnt;
// input buffer
private readonly byte[] data = new byte[1024 * 8];
private int bitPos;
private int end;
int got;
private bool eof;
private const int EXTRA = 64;
#endregion
}
}
| 26.110487 | 98 | 0.618662 | [
"MIT"
] | Acidburn0zzz/SharpZipLib | src/ICSharpCode.SharpZipLib/Lzw/LzwInputStream.cs | 13,945 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class specialNumbers
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
int[] arr = new int[n];
for (int i = 1; i < arr.Length + 1; i++)
{
int sumOfDigits = 0;
int digits = i;
while (digits != 0)
{
sumOfDigits += digits % 10;
digits = digits / 10;
}
bool special = (sumOfDigits == 5) || (sumOfDigits == 7) || (sumOfDigits == 11);
Console.WriteLine($@"{i} -> {special}");
}
}
}
| 20.941176 | 91 | 0.477528 | [
"MIT"
] | mlkumanova/Programming-Fundamentals | 1. Data Types and Variables/SpecialNumbers/specialNumbers.cs | 714 | C# |
using Abp.MultiTenancy;
using EntityModeler.Authorization.Users;
namespace EntityModeler.MultiTenancy
{
public class Tenant : AbpTenant<User>
{
public Tenant()
{
}
public Tenant(string tenancyName, string name)
: base(tenancyName, name)
{
}
}
}
| 18.444444 | 54 | 0.572289 | [
"MIT"
] | Ppiwow/EntityModeler | aspnet-core/src/EntityModeler.Core/MultiTenancy/Tenant.cs | 334 | C# |
using UnityEngine;
using System.Collections;
public class AutoRotatorScript : MonoBehaviour {
public float RotationSpeed = 10.0f;
// Update is called once per frame
void Update () {
transform.Rotate(Vector3.up, RotationSpeed * Time.deltaTime);
}
}
| 18.266667 | 69 | 0.70438 | [
"Apache-2.0"
] | sasoh/SumoSeptember | Sumo/Assets/Scripts/AutoRotatorScript.cs | 276 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class GroupPopulationCondition : GroupCondition
{
public const string Regex = @"^\s*group_population\s*" +
@":\s*(?<value>" + ModUtility.NumberRegexPart + @")\s*$";
public int MinPopulation;
public GroupPopulationCondition(Match match)
{
string valueStr = match.Groups["value"].Value;
int value;
if (!MathUtility.TryParseCultureInvariant(valueStr, out value))
{
throw new System.ArgumentException("GroupPopulationCondition: Min value can't be parsed into a valid integer point number: " + valueStr);
}
if (!value.IsInsideRange(1, int.MaxValue))
{
throw new System.ArgumentException("GroupPopulationCondition: Min value is outside the range of 1 and " + int.MaxValue + ": " + valueStr);
}
MinPopulation = value;
}
public override bool Evaluate(CellGroup group)
{
return group.Population >= MinPopulation;
}
public override string ToString()
{
return "'Group Population' Condition, Min Population: " + MinPopulation;
}
}
| 29.756098 | 150 | 0.658197 | [
"MIT"
] | Zematus/Worlds | Assets/Scripts/WorldEngine/Modding/Conditions/GroupPopulationCondition.cs | 1,222 | C# |
/*
* FactSet Funds API
*
* FactSet Mutual Funds data offers over 50 fund- and share class-specific data points for mutual funds listed in the United States. <p>FactSet Mutual Funds Reference provides fund-specific reference information as well as FactSet's proprietary classification system. It includes but is not limited to the following coverage * Fund descriptions * A seven-tier classification system * Leverage information * Fees and expenses * Portfolio managers FactSet Mutual Funds Time Series provides quantitative data items on a historical basis. It includes but is not limited to the following coverage * Net asset value * Fund flows * Assets under management * Total return
*
* The version of the OpenAPI document: 1.0.0
* Contact: api@factset.com
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = FactSet.SDK.FactSetFunds.Client.OpenAPIDateConverter;
namespace FactSet.SDK.FactSetFunds.Model
{
/// <summary>
/// FundsReturnsResponse
/// </summary>
[DataContract(Name = "fundsReturnsResponse")]
public partial class FundsReturnsResponse : IEquatable<FundsReturnsResponse>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="FundsReturnsResponse" /> class.
/// </summary>
/// <param name="data">Array of Returns Objects.</param>
public FundsReturnsResponse(List<Returns> data = default(List<Returns>))
{
this.Data = data;
}
/// <summary>
/// Array of Returns Objects
/// </summary>
/// <value>Array of Returns Objects</value>
[DataMember(Name = "data", EmitDefaultValue = false)]
public List<Returns> Data { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("class FundsReturnsResponse {\n");
sb.Append(" Data: ").Append(Data).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as FundsReturnsResponse);
}
/// <summary>
/// Returns true if FundsReturnsResponse instances are equal
/// </summary>
/// <param name="input">Instance of FundsReturnsResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(FundsReturnsResponse input)
{
if (input == null)
{
return false;
}
return
(
this.Data == input.Data ||
this.Data != null &&
input.Data != null &&
this.Data.SequenceEqual(input.Data)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Data != null)
{
hashCode = (hashCode * 59) + this.Data.GetHashCode();
}
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 36.659091 | 694 | 0.602191 | [
"Apache-2.0"
] | factset/enterprise-sdk | code/dotnet/FactSetFunds/v1/src/FactSet.SDK.FactSetFunds/Model/FundsReturnsResponse.cs | 4,839 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.RecoveryServices.V20210401.Outputs
{
/// <summary>
/// Container for SQL workloads under Azure Virtual Machines.
/// </summary>
[OutputType]
public sealed class AzureVMAppContainerProtectionContainerResponse
{
/// <summary>
/// Type of backup management for the container.
/// </summary>
public readonly string? BackupManagementType;
/// <summary>
/// Type of the container. The value of this property for: 1. Compute Azure VM is Microsoft.Compute/virtualMachines 2.
/// Classic Compute Azure VM is Microsoft.ClassicCompute/virtualMachines 3. Windows machines (like MAB, DPM etc) is
/// Windows 4. Azure SQL instance is AzureSqlContainer. 5. Storage containers is StorageContainer. 6. Azure workload
/// Backup is VMAppContainer
/// Expected value is 'VMAppContainer'.
/// </summary>
public readonly string ContainerType;
/// <summary>
/// Additional details of a workload container.
/// </summary>
public readonly Outputs.AzureWorkloadContainerExtendedInfoResponse? ExtendedInfo;
/// <summary>
/// Friendly name of the container.
/// </summary>
public readonly string? FriendlyName;
/// <summary>
/// Status of health of the container.
/// </summary>
public readonly string? HealthStatus;
/// <summary>
/// Time stamp when this container was updated.
/// </summary>
public readonly string? LastUpdatedTime;
/// <summary>
/// Re-Do Operation
/// </summary>
public readonly string? OperationType;
/// <summary>
/// Status of registration of the container with the Recovery Services Vault.
/// </summary>
public readonly string? RegistrationStatus;
/// <summary>
/// ARM ID of the virtual machine represented by this Azure Workload Container
/// </summary>
public readonly string? SourceResourceId;
/// <summary>
/// Workload type for which registration was sent.
/// </summary>
public readonly string? WorkloadType;
[OutputConstructor]
private AzureVMAppContainerProtectionContainerResponse(
string? backupManagementType,
string containerType,
Outputs.AzureWorkloadContainerExtendedInfoResponse? extendedInfo,
string? friendlyName,
string? healthStatus,
string? lastUpdatedTime,
string? operationType,
string? registrationStatus,
string? sourceResourceId,
string? workloadType)
{
BackupManagementType = backupManagementType;
ContainerType = containerType;
ExtendedInfo = extendedInfo;
FriendlyName = friendlyName;
HealthStatus = healthStatus;
LastUpdatedTime = lastUpdatedTime;
OperationType = operationType;
RegistrationStatus = registrationStatus;
SourceResourceId = sourceResourceId;
WorkloadType = workloadType;
}
}
}
| 35.505051 | 127 | 0.630441 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/RecoveryServices/V20210401/Outputs/AzureVMAppContainerProtectionContainerResponse.cs | 3,515 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TiendaEnLinea
{
public partial class Site_Mobile : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
} | 20.058824 | 64 | 0.668622 | [
"MIT"
] | JuanK-2003/Autentication_Bcrypt | Site.Mobile.Master.cs | 341 | C# |
// The MIT License (MIT)
//
// Copyright (c) 2018 - 2019 Lutando Ngqakaza
// https://github.com/Lutando/EventFly
//
//
// 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.ComponentModel;
using System.Threading.Tasks;
using EventFly.Aggregates;
using EventFly.Commands;
using EventFly.DependencyInjection;
using EventFly.TestFixture;
using EventFly.Tests.Data.Abstractions;
using EventFly.Tests.Data.Abstractions.Commands;
using EventFly.Tests.Data.Abstractions.Entities;
using EventFly.Tests.Data.Abstractions.Events;
using EventFly.Tests.Data.Abstractions.Events.Signals;
using EventFly.Tests.Data.Domain;
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Xunit.Abstractions;
namespace EventFly.Tests.Domain.Aggregates
{
[Category(Categories.Domain)]
[Collection(Collections.Only)]
public class AggregateTests : AggregateTestKit<TestContext>
{
public AggregateTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) { }
[Fact]
public void InitialState_AfterAggregateCreation_TestCreatedEventEmitted()
{
var eventProbe = CreateTestProbe("event-probe");
Sys.EventStream.Subscribe(eventProbe, typeof(IDomainEvent<TestAggregateId, TestCreatedEvent>));
var bus = Sys.GetExtension<ServiceProviderHolder>().ServiceProvider.GetRequiredService<ICommandBus>();
var aggregateId = TestAggregateId.New;
var commandId = CommandId.New;
var command = new CreateTestCommand(aggregateId, commandId);
bus.Publish(command).GetAwaiter().GetResult();
eventProbe.ExpectMsg<IDomainEvent<TestAggregateId, TestCreatedEvent>>(
x => x.AggregateEvent.TestAggregateId.Equals(aggregateId) &&
x.Metadata.ContainsKey("some-key"));
}
[Fact]
public async Task SendingCommand_ToAggregateRoot_ShouldReplyWithProperMessage()
{
var eventProbe = CreateTestProbe("event-probe");
Sys.EventStream.Subscribe(eventProbe, typeof(IDomainEvent<TestAggregateId, TestCreatedEvent>));
var bus = Sys.GetExtension<ServiceProviderHolder>().ServiceProvider.GetRequiredService<ICommandBus>();
var aggregateId = TestAggregateId.New;
var commandId = CommandId.New;
var command = new CreateTestCommand(aggregateId, commandId);
var result = (ITestExecutionResult)await bus.Publish(command);
result.IsSuccess.Should().BeTrue();
result.SourceId.Should().Be(command.Metadata.SourceId);
}
[Fact]
public void EventContainerMetadata_AfterAggregateCreation_TestCreatedEventEmitted()
{
var eventProbe = CreateTestProbe("event-probe");
Sys.EventStream.Subscribe(eventProbe, typeof(IDomainEvent<TestAggregateId, TestCreatedEvent>));
var bus = Sys.GetExtension<ServiceProviderHolder>().ServiceProvider.GetRequiredService<ICommandBus>();
var aggregateId = TestAggregateId.New;
var commandId = CommandId.New;
var command = new CreateTestCommand(aggregateId, commandId);
bus.Publish(command).GetAwaiter().GetResult();
eventProbe.ExpectMsg<IDomainEvent<TestAggregateId, TestCreatedEvent>>(
x => x.AggregateIdentity.Equals(aggregateId)
&& x.IdentityType == typeof(TestAggregateId)
&& x.EventType == typeof(TestCreatedEvent)
&& x.Metadata.EventName == "TestCreated"
&& x.Metadata.AggregateId == aggregateId.Value
&& x.Metadata.EventVersion == 1
&& x.Metadata.SourceId.Value == commandId.Value
&& x.Metadata.AggregateSequenceNumber == 1);
}
[Fact]
public void InitialState_AfterAggregateCreation_TestStateSignalled()
{
var eventProbe = CreateTestProbe("event-probe");
Sys.EventStream.Subscribe(eventProbe, typeof(IDomainEvent<TestAggregateId, TestStateSignalEvent>));
var bus = Sys.GetExtension<ServiceProviderHolder>().ServiceProvider.GetRequiredService<ICommandBus>();
var aggregateId = TestAggregateId.New;
var commandId = CommandId.New;
var command = new CreateTestCommand(aggregateId, commandId);
var nextCommand = new PublishTestStateCommand(aggregateId);
bus.Publish(command).GetAwaiter().GetResult();
bus.Publish(nextCommand).GetAwaiter().GetResult();
eventProbe.ExpectMsg<IDomainEvent<TestAggregateId, TestStateSignalEvent>>(
x => x.AggregateEvent.LastSequenceNr == 1
&& x.AggregateEvent.Version == 1
&& x.AggregateEvent.AggregateState.TestCollection.Count == 0);
}
[Fact]
public void TestCommand_AfterAggregateCreation_TestEventEmitted()
{
var eventProbe = CreateTestProbe("event-probe");
Sys.EventStream.Subscribe(eventProbe, typeof(IDomainEvent<TestAggregateId, TestAddedEvent>));
var bus = Sys.GetExtension<ServiceProviderHolder>().ServiceProvider.GetRequiredService<ICommandBus>();
var aggregateId = TestAggregateId.New;
var commandId = CommandId.New;
var command = new CreateTestCommand(aggregateId, commandId);
var testId = TestId.New;
var test = new Test(testId);
var nextCommandId = CommandId.New;
var nextCommand = new AddTestCommand(aggregateId, nextCommandId, test);
bus.Publish(command).GetAwaiter().GetResult();
bus.Publish(nextCommand).GetAwaiter().GetResult();
eventProbe.ExpectMsg<IDomainEvent<TestAggregateId, TestAddedEvent>>(x => x.AggregateEvent.Test.Equals(test));
}
[Fact]
public void TestCommandTwice_AfterAggregateCreation_TestEventEmitted()
{
var eventProbe = CreateTestProbe("event-probe");
Sys.EventStream.Subscribe(eventProbe, typeof(IDomainEvent<TestAggregateId, TestAddedEvent>));
var bus = Sys.GetExtension<ServiceProviderHolder>().ServiceProvider.GetRequiredService<ICommandBus>();
var aggregateId = TestAggregateId.New;
var commandId = CommandId.New;
var command = new CreateTestCommand(aggregateId, commandId);
var testId = TestId.New;
var test = new Test(testId);
var nextCommandId = CommandId.New;
var nextCommand = new AddTestCommand(aggregateId, nextCommandId, test);
var test2Id = TestId.New;
var test2 = new Test(test2Id);
var nextCommandId2 = CommandId.New;
var nextCommand2 = new AddTestCommand(aggregateId, nextCommandId2, test2);
bus.Publish(command).GetAwaiter().GetResult();
bus.Publish(nextCommand).GetAwaiter().GetResult();
bus.Publish(nextCommand2).GetAwaiter().GetResult();
eventProbe.ExpectMsg<IDomainEvent<TestAggregateId, TestAddedEvent>>(x => x.AggregateEvent.Test.Equals(test) && x.AggregateSequenceNumber == 2);
eventProbe.ExpectMsg<IDomainEvent<TestAggregateId, TestAddedEvent>>(x => x.AggregateEvent.Test.Equals(test2) && x.AggregateSequenceNumber == 3);
}
[Fact]
public void TestEventSourcing_AfterManyTests_TestStateSignalled()
{
var eventProbe = CreateTestProbe("event-probe");
Sys.EventStream.Subscribe(eventProbe, typeof(IDomainEvent<TestAggregateId, TestStateSignalEvent>));
var aggregateId = TestAggregateId.New;
var commandId = CommandId.New;
var bus = Sys.GetExtension<ServiceProviderHolder>().ServiceProvider.GetRequiredService<ICommandBus>();
var command = new CreateTestCommand(aggregateId, commandId);
bus.Publish(command).GetAwaiter().GetResult();
for (var i = 0; i < 5; i++)
{
var test = new Test(TestId.New);
var testCommandId = CommandId.New;
var testCommand = new AddTestCommand(aggregateId, testCommandId, test);
bus.Publish(testCommand).GetAwaiter().GetResult();
}
var poisonCommand = new PoisonTestAggregateCommand(aggregateId);
bus.Publish(poisonCommand).GetAwaiter().GetResult();
var reviveCommand = new PublishTestStateCommand(aggregateId);
bus.Publish(reviveCommand).GetAwaiter().GetResult();
eventProbe.ExpectMsg<IDomainEvent<TestAggregateId, TestStateSignalEvent>>(
x => x.AggregateEvent.LastSequenceNr == 6
&& x.AggregateEvent.Version == 6
&& x.AggregateEvent.AggregateState.TestCollection.Count == 5);
}
[Fact]
public void TestEventMultipleEmitSourcing_AfterManyMultiCreateCommand_EventsEmitted()
{
var eventProbe = CreateTestProbe("event-probe");
Sys.EventStream.Subscribe(eventProbe, typeof(IDomainEvent<TestAggregateId, TestCreatedEvent>));
Sys.EventStream.Subscribe(eventProbe, typeof(IDomainEvent<TestAggregateId, TestAddedEvent>));
var bus = Sys.GetExtension<ServiceProviderHolder>().ServiceProvider.GetRequiredService<ICommandBus>();
var aggregateId = TestAggregateId.New;
var commandId = CommandId.New;
var firstTest = new Test(TestId.New);
var secondTest = new Test(TestId.New);
var command = new CreateAndAddTwoTestsCommand(aggregateId, commandId, firstTest, secondTest);
bus.Publish(command).GetAwaiter().GetResult();
eventProbe.ExpectMsg<IDomainEvent<TestAggregateId, TestCreatedEvent>>();
eventProbe.ExpectMsg<IDomainEvent<TestAggregateId, TestAddedEvent>>();
eventProbe.ExpectMsg<IDomainEvent<TestAggregateId, TestAddedEvent>>();
}
[Fact]
public void TestEventMultipleEmitSourcing_AfterManyMultiCommand_TestStateSignalled()
{
var eventProbe = CreateTestProbe("event-probe");
Sys.EventStream.Subscribe(eventProbe, typeof(IDomainEvent<TestAggregateId, TestAddedEvent>));
Sys.EventStream.Subscribe(eventProbe, typeof(IDomainEvent<TestAggregateId, TestStateSignalEvent>));
var aggregateId = TestAggregateId.New;
var commandId = CommandId.New;
var bus = Sys.GetExtension<ServiceProviderHolder>().ServiceProvider.GetRequiredService<ICommandBus>();
var command = new CreateTestCommand(aggregateId, commandId);
bus.Publish(command).GetAwaiter().GetResult();
var test = new Test(TestId.New);
var testSourceId = CommandId.New;
var testCommand = new AddFourTestsCommand(aggregateId, testSourceId, test);
bus.Publish(testCommand).GetAwaiter().GetResult();
var poisonCommand = new PoisonTestAggregateCommand(aggregateId);
bus.Publish(poisonCommand).GetAwaiter().GetResult();
var reviveCommand = new PublishTestStateCommand(aggregateId);
bus.Publish(reviveCommand).GetAwaiter().GetResult();
eventProbe.ExpectMsg<IDomainEvent<TestAggregateId, TestAddedEvent>>();
eventProbe.ExpectMsg<IDomainEvent<TestAggregateId, TestAddedEvent>>();
eventProbe.ExpectMsg<IDomainEvent<TestAggregateId, TestAddedEvent>>();
eventProbe.ExpectMsg<IDomainEvent<TestAggregateId, TestAddedEvent>>();
eventProbe.ExpectMsg<IDomainEvent<TestAggregateId, TestStateSignalEvent>>(
x => x.AggregateEvent.LastSequenceNr == 5
&& x.AggregateEvent.Version == 5
&& x.AggregateEvent.AggregateState.TestCollection.Count == 4);
}
[Fact]
public void TestSnapShotting_AfterManyTests_TestStateSignalled()
{
var eventProbe = CreateTestProbe("event-probe");
Sys.EventStream.Subscribe(eventProbe, typeof(IDomainEvent<TestAggregateId, TestStateSignalEvent>));
var aggregateId = TestAggregateId.New;
var commandId = CommandId.New;
var bus = Sys.GetExtension<ServiceProviderHolder>().ServiceProvider.GetRequiredService<ICommandBus>();
var command = new CreateTestCommand(aggregateId, commandId);
bus.Publish(command).GetAwaiter().GetResult();
for (var i = 0; i < 10; i++)
{
var test = new Test(TestId.New);
var testCommandId = CommandId.New;
var testCommand = new AddTestCommand(aggregateId, testCommandId, test);
bus.Publish(testCommand).GetAwaiter().GetResult();
}
eventProbe.ExpectMsg<IDomainEvent<TestAggregateId, TestStateSignalEvent>>(
x => x.AggregateEvent.LastSequenceNr == 11
&& x.AggregateEvent.Version == 11
&& x.AggregateEvent.AggregateState.TestCollection.Count == 10
&& x.AggregateEvent.AggregateState.FromHydration);
}
[Fact]
public async Task InitialState_TestingSuccessCommand_SuccessResultReplied()
{
var aggregateId = TestAggregateId.New;
var commandId = CommandId.New;
var command = new TestSuccessExecutionResultCommand(aggregateId, commandId);
var bus = Sys.GetExtension<ServiceProviderHolder>().ServiceProvider.GetRequiredService<ICommandBus>();
await bus.Publish(command);
}
[Fact]
public async Task InitialState_TestingFailedCommand_SuccessResultReplied()
{
var aggregateId = TestAggregateId.New;
var commandId = CommandId.New;
var command = new TestFailedExecutionResultCommand(aggregateId, commandId);
var bus = Sys.GetExtension<ServiceProviderHolder>().ServiceProvider.GetRequiredService<ICommandBus>();
await bus.Publish(command);
}
[Fact]
public void TestDistinctCommand_AfterTwoHandles_CommandFails()
{
// TODO https://dev.azure.com/lutando/EventFly/_workitems/edit/25
/*
var probe = CreateTestProbe("event-probe");
var aggregateManager = Sys.ActorOf(Props.Create(() => new TestAggregateManager()), "test-aggregatemanager");
var aggregateId = TestAggregateId.New;
var createCommand = new CreateTestCommand(aggregateId);
aggregateManager.Tell(createCommand);
var command = new TestDistinctCommand(aggregateId, 10);
aggregateManager.Tell(command, probe);
probe.ExpectNoMsg();
aggregateManager.Tell(command, probe);
probe.ExpectMsg<FailedExecutionResult>(TimeSpan.FromHours(1));
*/
}
}
} | 48.123494 | 156 | 0.667021 | [
"MIT"
] | Sporteco/EventFly | test/EventFly.Tests/Domain/Aggregates/AggregateTests.cs | 15,977 | C# |
// Copyright 2007-2014 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Tests.Testing
{
using System.Linq;
using System.Threading.Tasks;
using MassTransit.Testing;
using NUnit.Framework;
using Shouldly;
[Explicit]
public class When_a_consumer_with_multiple_message_consumers_is_tested
{
IConsumerTest<IBusTestScenario, TwoMessageConsumer> _test;
[SetUp]
public void A_consumer_is_being_tested()
{
_test = TestFactory.ForConsumer<TwoMessageConsumer>()
.New(x =>
{
x.UseConsumerFactory(() => new TwoMessageConsumer());
x.Send(new A(), (scenario, context) => context.ResponseAddress = scenario.Bus.Address);
x.Send(new B(), (scenario, context) => context.ResponseAddress = scenario.Bus.Address);
});
_test.Execute();
}
[TearDown]
public void Teardown()
{
_test.Dispose();
_test = null;
}
[Test]
public void Should_have_sent_the_aa_response_from_the_consumer()
{
_test.Sent.Select<Aa>().Any().ShouldBe(true);
}
[Test]
public void Should_have_sent_the_bb_response_from_the_consumer()
{
_test.Sent.Select<Bb>().Any().ShouldBe(true);
}
[Test]
public void Should_have_called_the_consumer_a_method()
{
_test.Consumer.Received.Select<A>().Any().ShouldBe(true);
}
[Test]
public void Should_have_called_the_consumer_b_method()
{
_test.Consumer.Received.Select<B>().Any().ShouldBe(true);
}
class A
{
}
class Aa
{
}
class B
{
}
class Bb
{
}
class TwoMessageConsumer :
IConsumer<A>,
IConsumer<B>
{
public Task Consume(ConsumeContext<A> context)
{
return context.RespondAsync(new Aa());
}
public Task Consume(ConsumeContext<B> context)
{
return context.RespondAsync(new Bb());
}
}
}
} | 27.284404 | 108 | 0.550437 | [
"Apache-2.0"
] | Johavale19/Johanna | src/MassTransit.Tests/Testing/ConsumerMultiple_Specs.cs | 2,974 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Consumption.V20180630
{
public static class GetBudgetByResourceGroupName
{
/// <summary>
/// A budget resource.
/// </summary>
public static Task<GetBudgetByResourceGroupNameResult> InvokeAsync(GetBudgetByResourceGroupNameArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetBudgetByResourceGroupNameResult>("azure-nextgen:consumption/v20180630:getBudgetByResourceGroupName", args ?? new GetBudgetByResourceGroupNameArgs(), options.WithVersion());
}
public sealed class GetBudgetByResourceGroupNameArgs : Pulumi.InvokeArgs
{
/// <summary>
/// Budget Name.
/// </summary>
[Input("budgetName", required: true)]
public string BudgetName { get; set; } = null!;
/// <summary>
/// Azure Resource Group Name.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
public GetBudgetByResourceGroupNameArgs()
{
}
}
[OutputType]
public sealed class GetBudgetByResourceGroupNameResult
{
/// <summary>
/// The total amount of cost to track with the budget
/// </summary>
public readonly double Amount;
/// <summary>
/// The category of the budget, whether the budget tracks cost or usage.
/// </summary>
public readonly string Category;
/// <summary>
/// The current amount of cost which is being tracked for a budget.
/// </summary>
public readonly Outputs.CurrentSpendResponse CurrentSpend;
/// <summary>
/// eTag of the resource. To handle concurrent update scenario, this field will be used to determine whether the user is updating the latest version or not.
/// </summary>
public readonly string? ETag;
/// <summary>
/// May be used to filter budgets by resource group, resource, or meter.
/// </summary>
public readonly Outputs.FiltersResponse? Filters;
/// <summary>
/// Resource Id.
/// </summary>
public readonly string Id;
/// <summary>
/// Resource name.
/// </summary>
public readonly string Name;
/// <summary>
/// Dictionary of notifications associated with the budget. Budget can have up to five notifications.
/// </summary>
public readonly ImmutableDictionary<string, Outputs.NotificationResponse>? Notifications;
/// <summary>
/// The time covered by a budget. Tracking of the amount will be reset based on the time grain.
/// </summary>
public readonly string TimeGrain;
/// <summary>
/// Has start and end date of the budget. The start date must be first of the month and should be less than the end date. Budget start date must be on or after June 1, 2017. Future start date should not be more than three months. Past start date should be selected within the timegrain period. There are no restrictions on the end date.
/// </summary>
public readonly Outputs.BudgetTimePeriodResponse TimePeriod;
/// <summary>
/// Resource type.
/// </summary>
public readonly string Type;
[OutputConstructor]
private GetBudgetByResourceGroupNameResult(
double amount,
string category,
Outputs.CurrentSpendResponse currentSpend,
string? eTag,
Outputs.FiltersResponse? filters,
string id,
string name,
ImmutableDictionary<string, Outputs.NotificationResponse>? notifications,
string timeGrain,
Outputs.BudgetTimePeriodResponse timePeriod,
string type)
{
Amount = amount;
Category = category;
CurrentSpend = currentSpend;
ETag = eTag;
Filters = filters;
Id = id;
Name = name;
Notifications = notifications;
TimeGrain = timeGrain;
TimePeriod = timePeriod;
Type = type;
}
}
}
| 35.476563 | 345 | 0.619467 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Consumption/V20180630/GetBudgetByResourceGroupName.cs | 4,541 | 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.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The interface IWorkbookFormatProtectionRequestBuilder.
/// </summary>
public partial interface IWorkbookFormatProtectionRequestBuilder : IEntityRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
new IWorkbookFormatProtectionRequest Request();
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
new IWorkbookFormatProtectionRequest Request(IEnumerable<Option> options);
}
}
| 35.411765 | 153 | 0.571429 | [
"MIT"
] | MIchaelMainer/GraphAPI | src/Microsoft.Graph/Requests/Generated/IWorkbookFormatProtectionRequestBuilder.cs | 1,204 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using WealthManager.BL;
namespace WealthManager.SL
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IStock" in both code and config file together.
[ServiceContract]
public interface IStock
{
[OperationContract]
CStockList GetStocks();
[OperationContract]
void InsertStock(string description);
[OperationContract]
void InsertStockObj(CStock Stock);
[OperationContract]
void DeleteStock(Guid id);
[OperationContract]
void DeleteStockObj(CStock Stock);
}
}
| 26.806452 | 146 | 0.632972 | [
"MIT"
] | OneBadApple/Stocks | WealthManager.SL/IStock.cs | 833 | C# |
// Copyright (c) Dapplo and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
namespace Dapplo.HttpExtensions
{
/// <summary>
/// This interface extends the IHttpBehaviour but makes it possible to change the values.
/// A use-case would be to call Clone on the IHttpBehaviour and modify the settings, return/assign the new value to a
/// IHttpBehaviour
/// This would be needed to pass the IHttpBehaviour via a CallContext.
/// </summary>
public interface IChangeableHttpBehaviour : IHttpBehaviour
{
/// <summary>
/// The default encoding which is used wherever an encoding is specified.
/// The default is set to Encoding.UTF8
/// </summary>
new Encoding DefaultEncoding { get; set; }
/// <summary>
/// Action which is called to notify of download progress.
/// Only used when using non-string content like Bitmaps or MemoryStreams.
/// Also the UseProgressStream needs to be true for this download progress
/// </summary>
new Action<float> DownloadProgress { get; set; }
/// <summary>
/// This can be used to change the behaviour of Http operation, default is to read the complete response.
/// </summary>
new HttpCompletionOption HttpCompletionOption { get; set; }
/// <summary>
/// This is the list of IHttpContentConverters which is used when converting from/to HttpContent
/// </summary>
new IList<IHttpContentConverter> HttpContentConverters { get; set; }
/// <summary>
/// Pass your HttpSettings here, which will be used to create the HttpClient
/// If not specified, the HttpSettings.GlobalSettings will be used
/// </summary>
new IHttpSettings HttpSettings { get; set; }
/// <summary>
/// This is used to de- serialize Json, can be overwritten by your own implementation.
/// By default, also when empty, the SimpleJsonSerializer is used.
/// </summary>
new IJsonSerializer JsonSerializer { get; set; }
/// <summary>
/// An action which can modify the HttpClient which is generated in the HttpClientFactory.
/// Use cases for this, might be adding a header or other settings for specific cases
/// </summary>
new Action<HttpClient> OnHttpClientCreated { get; set; }
/// <summary>
/// An Func which can modify the HttpContent right before it's used to start the request.
/// This can be used to add a specific header, e.g. set a filename etc, or return a completely different HttpContent
/// type
/// </summary>
new Func<HttpContent, HttpContent> OnHttpContentCreated { get; set; }
/// <summary>
/// An Func which can modify or wrap the HttpMessageHandler which is generated in the HttpMessageHandlerFactory.
/// Use cases for this, might be if you have very specify settings which can't be set via the IHttpSettings
/// Or you want to add additional behaviour (extend DelegatingHandler!!) like the OAuthDelegatingHandler
/// </summary>
new Func<HttpMessageHandler, HttpMessageHandler> OnHttpMessageHandlerCreated { get; set; }
/// <summary>
/// An Func which can modify the HttpRequestMessage right before it's used to start the request.
/// This can be used to add a specific header, which should not be for all requests.
/// As the called func has access to HttpRequestMessage with the content, uri and method this is quite usefull, it can
/// return a completely different HttpRequestMessage
/// </summary>
new Func<HttpRequestMessage, HttpRequestMessage> OnHttpRequestMessageCreated { get; set; }
/// <summary>
/// Specify the buffer for reading operations
/// </summary>
new int ReadBufferSize { get; set; }
/// <summary>
/// If a request gets a response which has a HTTP status code which is an error, it would normally THROW an exception.
/// Sometimes you would still want the response, settings this to false would allow this.
/// This can be ignored for all HttpResponse returning methods.
/// </summary>
new bool ThrowOnError { get; set; }
/// <summary>
/// Action which is called to notify of upload progress.
/// Only used when using non-string content like Bitmaps or MemoryStreams.
/// Also the UseProgressStream needs to be true for this upload progress
/// </summary>
new Action<float> UploadProgress { get; set; }
/// <summary>
/// Whenever a post is made to upload memorystream or bitmaps, this value is used to decide:
/// true: ProgressStreamContent is used, instead of StreamContent
/// </summary>
new bool UseProgressStream { get; set; }
/// <summary>
/// This cookie container will be assed when creating the HttpMessageHandler and UseCookies is true
/// </summary>
new CookieContainer CookieContainer { get; set; }
/// <summary>
/// Check if the response has the expected content-type, when servers are used that are not following specifications
/// this should be set to false
/// </summary>
new bool ValidateResponseContentType { get; set; }
/// <inheritdoc cref="IHttpBehaviour" />
new IDictionary<string, IHttpRequestConfiguration> RequestConfigurations { get; set; }
}
} | 48.319672 | 130 | 0.639016 | [
"MIT"
] | dapplo/Dapplo.HttpExtensions | src/Dapplo.HttpExtensions/IChangeableHttpBehaviour.cs | 5,895 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace CenterComparing
{
/// <summary>
/// Interaction logic for ImgWindow.xaml
/// </summary>
public partial class ImgWindow : UserControl
{
public event Action<string> evtCurrentPos;
public event Action<string> evtDropFile;
public event Action<int, int> evtImgWidthHeight;
Point prePosition;
Point InnerRectFirstPos;
Point InnerRectLastPos;
public Rectangle OuterRect = null;
public Rectangle OuterRect_in = null;
public Rectangle InnerRect = null;
public Rectangle InnerRect_in = null;
public Ellipse InnerEllipse = null;
public Ellipse OuterEllipse = null;
BitmapImage OriginalImg;
public Line HLine = null;
public Line WLine = null;
public Label HLabel = null;
public Label WLabel = null;
int Margin = 10;
public bool UseLine = false;
public ImgWindow()
{
InitializeComponent();
}
public void SetImage(string path)
{
if (path == "NG")
{
MessageBox.Show("Selected file is not image file. Please select other image file.");
return;
}
ImgBack.Source = new BitmapImage(new Uri(path));
OriginalImg = new BitmapImage(new Uri(path));
evtImgWidthHeight((int)ImgBack.Source.Width, (int)ImgBack.Source.Height);
}
public void SetImage(BitmapSource src)
{
ImgBack.Source = src;
}
public void RemoveRect()
{
cvsMain.Children.Remove(OuterRect);
cvsMain.Children.Remove(OuterRect_in);
cvsMain.Children.Remove(InnerRect);
cvsMain.Children.Remove(InnerRect_in);
}
public void RemoveLine()
{
cvsMain.Children.Remove(HLine);
cvsMain.Children.Remove(WLine);
cvsMain.Children.Remove(HLabel);
cvsMain.Children.Remove(WLabel);
}
public void SetMargin(int num)
{
Margin = num;
}
public void Reset()
{
ImgBack.Source = OriginalImg;
}
public Config GetConfig(double resol , int thres , double wratio, double hratio ,bool useline)
{
if (useline
&& WLine != null
&& HLine != null
&& InnerRect != null
&& InnerRect_in != null)
{
var ltpos = new System.Drawing.Point((int)Math.Min(InnerRectFirstPos.X, InnerRectLastPos.X), (int)Math.Min(InnerRectFirstPos.Y, InnerRectLastPos.Y));
var rbpos = new System.Drawing.Point((int)Math.Max(InnerRectFirstPos.X, InnerRectLastPos.X), (int)Math.Max(InnerRectFirstPos.Y, InnerRectLastPos.Y));
var output = new Config()
{
BoxInnerLT = ltpos,
BoxInnerRB = rbpos,
HX1 = HLine.X1,
HY1 = HLine.Y1,
HX2 = HLine.X2,
HY2 = HLine.Y2,
WX1 = WLine.X1,
WY1 = WLine.Y1,
WX2 = WLine.X2,
WY2 = WLine.Y2,
InnerUp = Math.Max(InnerRect.Width * wratio, InnerRect.Height * hratio),
InnerDw = Math.Min(InnerRect_in.Width * wratio, InnerRect_in.Height * hratio) - 5,
Resolution = resol,
Threshold = thres,
UseLine = true
};
return output;
}
else if (OuterRect != null
&& OuterRect_in != null
&& InnerRect != null
&& InnerRect_in != null)
{
var output = new Config()
{
OuterUp = Math.Max(OuterRect.Width * wratio, OuterRect.Height * hratio),
OuterDw = Math.Min(OuterRect_in.Width * wratio, OuterRect_in.Height * hratio) - 5,
InnerUp = Math.Max(InnerRect.Width * wratio, InnerRect.Height * hratio),
InnerDw = Math.Min(InnerRect_in.Width * wratio, InnerRect_in.Height * hratio) - 5,
Resolution = resol,
Threshold = thres,
UseLine = false
};
return output;
}
return null;
}
private void cvsMain_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
prePosition = e.GetPosition(cvsMain);
cvsMain.CaptureMouse();
if (UseLine)
{
//Inner
if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
{
if (HLine == null)
{
cvsMain.Children.Remove(WLabel);
CreateLine(true);
CreateLineText(true);
}
}
else if (Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt)) // Outer
{
if (WLine == null)
{
cvsMain.Children.Remove(HLabel);
CreateLine(false);
CreateLineText(false);
}
}
else if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
{
if (InnerRect == null)
{
CreatRectangle(prePosition.X, prePosition.Y, false);
InnerRectFirstPos = e.GetPosition(cvsMain);
}
}
}
else
{
if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
{
if (InnerRect == null)
{
//InnerEllipse = CreateCircle(prePosition.X, prePosition.Y, false);
CreatRectangle(prePosition.X, prePosition.Y, false);
InnerRectFirstPos = e.GetPosition(cvsMain);
}
}
else if (Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt)) // Outer
{
if (OuterRect == null)
{
//OuterEllipse = CreateCircle(prePosition.X, prePosition.Y, true);
CreatRectangle(prePosition.X, prePosition.Y, true);
}
}
}
}
private void cvsMain_MouseMove(object sender, MouseEventArgs e)
{
Point posnow = e.GetPosition(cvsMain);
evtCurrentPos(string.Format("X : {0} , Y : {1}", Math.Round(posnow.X) , Math.Round(posnow.Y)));
if (e.MouseDevice.LeftButton == MouseButtonState.Pressed)
{
double left = prePosition.X;
double top = prePosition.Y;
if (prePosition.Y > posnow.Y)
top = posnow.Y;
if (prePosition.X > posnow.X)
left = posnow.X;
var dis = Distance(prePosition.X, posnow.X, prePosition.Y, posnow.Y);
if (!UseLine)
{
if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
{
if (InnerRect != null)
{
cvsMain.Children.Remove(InnerRect);
InnerRect.Width = Math.Abs(prePosition.X - posnow.X);
InnerRect.Height = Math.Abs(prePosition.Y - posnow.Y);
Canvas.SetLeft(InnerRect, left);
Canvas.SetTop(InnerRect, top);
cvsMain.Children.Add(InnerRect);
var innermargin = Margin / 2;
cvsMain.Children.Remove(InnerRect_in);
var w = Math.Abs(prePosition.X - posnow.X) - innermargin * 2;
var h = Math.Abs(prePosition.Y - posnow.Y) - innermargin * 2;
InnerRect_in.Width = w <= innermargin * 2 ? 0 : w;
InnerRect_in.Height = h <= innermargin * 2 ? 0 : h;
Canvas.SetLeft(InnerRect_in, left + innermargin);
Canvas.SetTop(InnerRect_in, top + innermargin);
cvsMain.Children.Add(InnerRect_in);
InnerRectLastPos = posnow;
}
}
else if (Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt)) // Outer
{
if (OuterRect != null)
{
cvsMain.Children.Remove(OuterRect);
OuterRect.Width = Math.Abs(prePosition.X - posnow.X);
OuterRect.Height = Math.Abs(prePosition.Y - posnow.Y);
Canvas.SetLeft(OuterRect, left);
Canvas.SetTop(OuterRect, top);
cvsMain.Children.Add(OuterRect);
cvsMain.Children.Remove(OuterRect_in);
var w = Math.Abs(prePosition.X - posnow.X) - Margin * 2;
var h = Math.Abs(prePosition.Y - posnow.Y) - Margin * 2;
OuterRect_in.Width = w <= Margin * 2 ? 0 : w;
OuterRect_in.Height = h <= Margin * 2 ? 0 : h;
Canvas.SetLeft(OuterRect_in, left + Margin);
Canvas.SetTop(OuterRect_in, top + Margin);
cvsMain.Children.Add(OuterRect_in);
}
}
}
else
{
if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
{
if (HLine != null)
{
cvsMain.Children.Remove(HLine);
HLine.X1 = Math.Abs(prePosition.X);
HLine.Y1 = Math.Abs(prePosition.Y);
HLine.X2 = Math.Abs(posnow.X);
HLine.Y2 = Math.Abs(posnow.Y);
cvsMain.Children.Add(HLine);
cvsMain.Children.Remove(HLabel);
Canvas.SetLeft(HLabel, posnow.X + 6);
Canvas.SetTop(HLabel, posnow.Y );
cvsMain.Children.Add(HLabel);
}
}
else if (Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt)) // Outer
{
if (WLine != null)
{
cvsMain.Children.Remove(WLine);
WLine.X1 = Math.Abs(prePosition.X);
WLine.Y1 = Math.Abs(prePosition.Y);
WLine.X2 = Math.Abs(posnow.X);
WLine.Y2 = Math.Abs(posnow.Y);
cvsMain.Children.Add(WLine);
cvsMain.Children.Remove(WLabel);
Canvas.SetLeft(WLabel, posnow.X + 6);
Canvas.SetTop(WLabel, posnow.Y );
cvsMain.Children.Add(WLabel);
}
}
else if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
{
if (InnerRect != null)
{
cvsMain.Children.Remove(InnerRect);
InnerRect.Width = Math.Abs(prePosition.X - posnow.X);
InnerRect.Height = Math.Abs(prePosition.Y - posnow.Y);
Canvas.SetLeft(InnerRect, left);
Canvas.SetTop(InnerRect, top);
cvsMain.Children.Add(InnerRect);
var innermargin = Margin / 2;
cvsMain.Children.Remove(InnerRect_in);
var w = Math.Abs(prePosition.X - posnow.X) - innermargin * 2;
var h = Math.Abs(prePosition.Y - posnow.Y) - innermargin * 2;
InnerRect_in.Width = w <= innermargin * 2 ? 0 : w;
InnerRect_in.Height = h <= innermargin * 2 ? 0 : h;
Canvas.SetLeft(InnerRect_in, left + innermargin);
Canvas.SetTop(InnerRect_in, top + innermargin);
cvsMain.Children.Add(InnerRect_in);
InnerRectLastPos = posnow;
}
}
}
}
}
private void cvsMain_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
//cvsMain.Children.Remove(currentRect);
cvsMain.ReleaseMouseCapture();
//SetRecrangleProperty();
//currentRect = null;
//cvsMain.Children.Remove(WLine);
//cvsMain.Children.Remove(HLine);
}
void SetRecrangleProperty()
{
OuterRect.Opacity = 1;
OuterRect.Fill = new SolidColorBrush(Colors.Transparent);
OuterRect.StrokeDashArray = new DoubleCollection();
OuterRect.Stroke = new SolidColorBrush(Colors.IndianRed);
}
void CreateLine(bool isHorizontal)
{
if (isHorizontal)
{
HLine = new Line();
HLine.StrokeThickness = 3;
HLine.Stroke = new SolidColorBrush(Colors.MediumPurple);
HLine.Opacity = 0.7;
DoubleCollection dashSize = new DoubleCollection();
dashSize.Add(1);
dashSize.Add(1);
HLine.StrokeDashArray = dashSize;
HLine.StrokeDashOffset = 0;
}
else
{
WLine = new Line();
WLine.StrokeThickness = 3;
WLine.Stroke = new SolidColorBrush(Colors.Orange);
WLine.Opacity = 0.7;
DoubleCollection dashSize = new DoubleCollection();
dashSize.Add(1);
dashSize.Add(1);
WLine.StrokeDashArray = dashSize;
WLine.StrokeDashOffset = 0;
}
}
void CreateLineText(bool isHorizontal)
{
if (isHorizontal)
{
HLabel = new Label();
HLabel.FontWeight = FontWeights.Bold;
HLabel.Content = "Vertical";
HLabel.Foreground = Brushes.Green;
}
else
{
WLabel = new Label();
WLabel.FontWeight = FontWeights.Bold;
WLabel.Content = "Horizontal";
WLabel.Foreground = Brushes.Green;
}
}
Ellipse CreateCircle(double l, double t, bool isouter)
{
Ellipse output = new Ellipse();
if (isouter)
{
output.Stroke = new SolidColorBrush(Colors.ForestGreen);
}
else
{
output.Stroke = new SolidColorBrush(Colors.OrangeRed);
}
output.StrokeThickness = 2;
output.Opacity = 0.7;
DoubleCollection dashSize = new DoubleCollection();
dashSize.Add(1);
dashSize.Add(1);
output.StrokeDashArray = dashSize;
output.StrokeDashOffset = 0;
output.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
output.VerticalAlignment = System.Windows.VerticalAlignment.Top;
return output;
}
void CreatRectangle(double l , double t , bool isOuter)
{
DoubleCollection dashSize = new DoubleCollection();
dashSize.Add(1);
dashSize.Add(1);
if (isOuter)
{
OuterRect = new Rectangle();
OuterRect.Stroke = new SolidColorBrush(Colors.ForestGreen);
OuterRect.StrokeThickness = 2;
OuterRect.Opacity = 0.8;
OuterRect.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
OuterRect.VerticalAlignment = System.Windows.VerticalAlignment.Top;
OuterRect_in = new Rectangle();
OuterRect_in.Stroke = new SolidColorBrush(Colors.ForestGreen);
OuterRect_in.StrokeThickness = 2;
OuterRect_in.Opacity = 0.5;
OuterRect_in.StrokeDashArray = dashSize;
OuterRect_in.StrokeDashOffset = 0;
OuterRect_in.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
OuterRect_in.VerticalAlignment = System.Windows.VerticalAlignment.Top;
}
else
{
InnerRect = new Rectangle();
InnerRect.Stroke = new SolidColorBrush(Colors.OrangeRed);
InnerRect.StrokeThickness = 2;
InnerRect.Opacity = 0.8;
InnerRect.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
InnerRect.VerticalAlignment = System.Windows.VerticalAlignment.Top;
InnerRect_in = new Rectangle();
InnerRect_in.Stroke = new SolidColorBrush(Colors.OrangeRed);
InnerRect_in.StrokeThickness = 2;
InnerRect_in.Opacity = 0.5;
InnerRect_in.StrokeDashArray = dashSize;
InnerRect_in.StrokeDashOffset = 0;
InnerRect_in.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
InnerRect_in.VerticalAlignment = System.Windows.VerticalAlignment.Top;
}
}
private void cvsMain_Drop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
evtDropFile(files.First());
}
double Distance(double x0, double y0, double x1, double y1)
{
var disdouble = Math.Pow((x0 - x1), 2) + Math.Pow((y0 - y1), 2);
var dis = Math.Sqrt(disdouble);
return dis;
}
}
}
| 38.161736 | 165 | 0.481187 | [
"Apache-2.0"
] | pimier15/CenterComparing | CenterComparing/CenterComparing/ImgWindow.xaml.cs | 19,350 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace RSSReader.iOS
{
public class Application
{
// This is the main entry point of the application.
static void Main(string[] args)
{
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
UIApplication.Main(args, null, "AppDelegate");
}
}
}
| 22.904762 | 91 | 0.632017 | [
"MIT"
] | ormaa/RSS-Reader_IOS-Android | iOS/Main.cs | 483 | 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.Storage.Internal;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Xunit;
namespace Microsoft.EntityFrameworkCore.Storage
{
public class RawSqlCommandBuilderTest
{
[ConditionalFact]
public virtual void Builds_RelationalCommand_without_optional_parameters()
{
var builder = CreateBuilder();
var command = builder.Build("SQL COMMAND TEXT");
Assert.Equal("SQL COMMAND TEXT", command.CommandText);
Assert.Equal(0, command.Parameters.Count);
}
private static RawSqlCommandBuilder CreateBuilder()
{
return new(
new RelationalCommandBuilderFactory(
new RelationalCommandBuilderDependencies(
new TestRelationalTypeMappingSource(
TestServiceFactory.Instance.Create<TypeMappingSourceDependencies>(),
TestServiceFactory.Instance.Create<RelationalTypeMappingSourceDependencies>()
)
)
),
new RelationalSqlGenerationHelper(new RelationalSqlGenerationHelperDependencies()),
new ParameterNameGeneratorFactory(new ParameterNameGeneratorDependencies())
);
}
[ConditionalFact]
public virtual void Builds_RelationalCommand_with_empty_parameter_list()
{
var builder = CreateBuilder();
var rawSqlCommand = builder.Build("SQL COMMAND TEXT", Array.Empty<object>());
Assert.Equal("SQL COMMAND TEXT", rawSqlCommand.RelationalCommand.CommandText);
Assert.Equal(0, rawSqlCommand.RelationalCommand.Parameters.Count);
Assert.Equal(0, rawSqlCommand.ParameterValues.Count);
}
[ConditionalFact]
public virtual void Builds_RelationalCommand_with_parameters()
{
var builder = CreateBuilder();
var rawSqlCommand = builder.Build(
"SQL COMMAND TEXT {0} {1} {2}",
new object[] { 1, 2L, "three" }
);
Assert.Equal(
"SQL COMMAND TEXT @p0 @p1 @p2",
rawSqlCommand.RelationalCommand.CommandText
);
Assert.Equal(3, rawSqlCommand.RelationalCommand.Parameters.Count);
Assert.Equal("p0", rawSqlCommand.RelationalCommand.Parameters[0].InvariantName);
Assert.Equal("p1", rawSqlCommand.RelationalCommand.Parameters[1].InvariantName);
Assert.Equal("p2", rawSqlCommand.RelationalCommand.Parameters[2].InvariantName);
Assert.Equal(3, rawSqlCommand.ParameterValues.Count);
Assert.Equal(1, rawSqlCommand.ParameterValues["p0"]);
Assert.Equal(2L, rawSqlCommand.ParameterValues["p1"]);
Assert.Equal("three", rawSqlCommand.ParameterValues["p2"]);
}
}
}
| 40.519481 | 111 | 0.633013 | [
"Apache-2.0"
] | belav/efcore | test/EFCore.Relational.Tests/Storage/RawSqlCommandBuilderTest.cs | 3,120 | 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.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.DotNet.UpgradeAssistant.Cli
{
internal class NonInteractiveUserInput : IUserInput
{
private readonly TimeSpan _waitPeriod;
public NonInteractiveUserInput(UpgradeOptions options)
{
_waitPeriod = TimeSpan.FromSeconds(options.NonInteractiveWait);
}
public bool IsInteractive => false;
public Task<string?> AskUserAsync(string currentPath)
{
throw new NotImplementedException("User input cannot be selected in non-interactive mode");
}
public Task<T> ChooseAsync<T>(string message, IEnumerable<T> commands, CancellationToken token)
where T : UpgradeCommand
=> Task.FromResult(commands.First(c => c.IsEnabled));
public async Task<bool> WaitToProceedAsync(CancellationToken token)
{
await Task.Delay(_waitPeriod, token);
return true;
}
}
}
| 30.025 | 103 | 0.680266 | [
"MIT"
] | Acidburn0zzz/upgrade-assistant | src/cli/Microsoft.DotNet.UpgradeAssistant.Cli/NonInteractiveUserInput.cs | 1,203 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace To_Do.Models.Identity
{
public class UserWithToken
{
public string UserId { get; set; }
public string Token { get; set; }
}
}
| 18.785714 | 42 | 0.680608 | [
"MIT"
] | mrsantons/ToDoDoDo | To-Do/To-Do/Models/Identity/UserWithtoken.cs | 265 | C# |
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace SharpDox.GUI.Controls.ConfigGrid
{
public partial class ConfigTextControl : UserControl
{
public static readonly DependencyProperty ConfigItemDisplayNameProperty = DependencyProperty.Register("ConfigItemDisplayName", typeof(string), typeof(ConfigTextControl));
public static readonly DependencyProperty ConfigItemValueProperty = DependencyProperty.Register("ConfigItemValue", typeof(string), typeof(ConfigTextControl));
public static readonly DependencyProperty WaterMarkTextProperty = DependencyProperty.Register("WaterMarkText", typeof(string), typeof(ConfigTextControl));
public static readonly DependencyProperty WaterMarkColorProperty = DependencyProperty.Register("WaterMarkColor", typeof(SolidColorBrush), typeof(ConfigTextControl));
public ConfigTextControl()
{
DataContext = this;
InitializeComponent();
}
public string ConfigItemDisplayName
{
get { return (string)GetValue(ConfigItemDisplayNameProperty); }
set { SetValue(ConfigItemDisplayNameProperty, value); }
}
public string ConfigItemValue
{
get { return (string)GetValue(ConfigItemValueProperty); }
set { SetValue(ConfigItemValueProperty, value); }
}
public string WaterMarkText
{
get { return (string)GetValue(WaterMarkTextProperty); }
set { SetValue(WaterMarkTextProperty, value); }
}
public SolidColorBrush WaterMarkColor
{
get { return (SolidColorBrush)GetValue(WaterMarkColorProperty); }
set { SetValue(WaterMarkColorProperty, value); }
}
}
}
| 39.911111 | 178 | 0.693764 | [
"MIT"
] | CoderGears/sharpDox | src/Shells/SharpDox.GUI/Controls/ConfigGrid/ConfigTextControl.xaml.cs | 1,798 | C# |
// Copyright (c) SimpleIdServer. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using MassTransit;
using SimpleIdServer.Scim.Domain;
using SimpleIdServer.Scim.Domains;
using SimpleIdServer.Scim.Exceptions;
using SimpleIdServer.Scim.Helpers;
using SimpleIdServer.Scim.Persistence;
using SimpleIdServer.Scim.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SimpleIdServer.Scim.Commands.Handlers
{
public class AddRepresentationCommandHandler : BaseCommandHandler, IAddRepresentationCommandHandler
{
private readonly ISCIMSchemaQueryRepository _scimSchemaQueryRepository;
private readonly ISCIMRepresentationQueryRepository _scimRepresentationQueryRepository;
private readonly ISCIMRepresentationHelper _scimRepresentationHelper;
private readonly ISCIMRepresentationCommandRepository _scimRepresentationCommandRepository;
private readonly IRepresentationReferenceSync _representationReferenceSync;
public AddRepresentationCommandHandler(
ISCIMSchemaQueryRepository scimSchemaQueryRepository,
ISCIMRepresentationQueryRepository scimRepresentationQueryRepository,
ISCIMRepresentationHelper scimRepresentationHelper,
ISCIMRepresentationCommandRepository scimRepresentationCommandRepository,
IRepresentationReferenceSync representationReferenceSync,
IBusControl busControl) : base(busControl)
{
_scimSchemaQueryRepository = scimSchemaQueryRepository;
_scimRepresentationQueryRepository = scimRepresentationQueryRepository;
_scimRepresentationHelper = scimRepresentationHelper;
_scimRepresentationCommandRepository = scimRepresentationCommandRepository;
_representationReferenceSync = representationReferenceSync;
}
public async Task<SCIMRepresentation> Handle(AddRepresentationCommand addRepresentationCommand)
{
var requestedSchemas = addRepresentationCommand.Representation.Schemas;
if (!requestedSchemas.Any())
{
throw new SCIMBadSyntaxException(string.Format(Global.AttributeMissing, StandardSCIMRepresentationAttributes.Schemas));
}
var schema = await _scimSchemaQueryRepository.FindRootSCIMSchemaByResourceType(addRepresentationCommand.ResourceType);
var allSchemas = new List<string> { schema.Id };
var requiredSchemas = new List<string> { schema.Id };
allSchemas.AddRange(schema.SchemaExtensions.Select(s => s.Schema));
requiredSchemas.AddRange(schema.SchemaExtensions.Where(s => s.Required).Select(s => s.Schema));
var missingRequiredSchemas = requiredSchemas.Where(s => !requestedSchemas.Contains(s));
if (missingRequiredSchemas.Any())
{
throw new SCIMBadSyntaxException(string.Format(Global.RequiredSchemasAreMissing, string.Join(",", missingRequiredSchemas)));
}
var unsupportedSchemas = requestedSchemas.Where(s => !allSchemas.Contains(s));
if (unsupportedSchemas.Any())
{
throw new SCIMBadSyntaxException(string.Format(Global.SchemasAreUnknown, string.Join(",", unsupportedSchemas)));
}
var schemas = await _scimSchemaQueryRepository.FindSCIMSchemaByIdentifiers(requestedSchemas);
var scimRepresentation = _scimRepresentationHelper.ExtractSCIMRepresentationFromJSON(addRepresentationCommand.Representation.Attributes, addRepresentationCommand.Representation.ExternalId, schema, schemas.Where(s => s.Id != schema.Id).ToList());
scimRepresentation.Id = Guid.NewGuid().ToString();
scimRepresentation.SetCreated(DateTime.UtcNow);
scimRepresentation.SetUpdated(DateTime.UtcNow);
scimRepresentation.SetVersion(0);
scimRepresentation.SetResourceType(addRepresentationCommand.ResourceType);
var uniqueServerAttributeIds = scimRepresentation.FlatAttributes.Where(s => s.IsLeaf()).Where(a => a.SchemaAttribute.MultiValued == false && a.SchemaAttribute.Uniqueness == SCIMSchemaAttributeUniqueness.SERVER);
var uniqueGlobalAttributes = scimRepresentation.FlatAttributes.Where(s => s.IsLeaf()).Where(a => a.SchemaAttribute.MultiValued == false && a.SchemaAttribute.Uniqueness == SCIMSchemaAttributeUniqueness.GLOBAL);
await CheckSCIMRepresentationExistsForGivenUniqueAttributes(uniqueServerAttributeIds, addRepresentationCommand.ResourceType);
await CheckSCIMRepresentationExistsForGivenUniqueAttributes(uniqueGlobalAttributes);
var references = await _representationReferenceSync.Sync(addRepresentationCommand.ResourceType, new SCIMRepresentation(), scimRepresentation, addRepresentationCommand.Location);
using (var transaction = await _scimRepresentationCommandRepository.StartTransaction())
{
await _scimRepresentationCommandRepository.Add(scimRepresentation);
foreach (var reference in references.Representations)
{
await _scimRepresentationCommandRepository.Update(reference);
}
await transaction.Commit();
}
await Notify(references);
scimRepresentation.ApplyEmptyArray();
return scimRepresentation;
}
private async Task CheckSCIMRepresentationExistsForGivenUniqueAttributes(IEnumerable<SCIMRepresentationAttribute> attributes, string endpoint = null)
{
foreach (var attribute in attributes)
{
SCIMRepresentation record = null;
switch (attribute.SchemaAttribute.Type)
{
case SCIMSchemaAttributeTypes.STRING:
record = await _scimRepresentationQueryRepository.FindSCIMRepresentationByAttribute(attribute.SchemaAttribute.Id, attribute.ValueString, endpoint);
break;
case SCIMSchemaAttributeTypes.INTEGER:
if (attribute.ValueInteger != null)
{
record = await _scimRepresentationQueryRepository.FindSCIMRepresentationByAttribute(attribute.SchemaAttribute.Id, attribute.ValueInteger.Value, endpoint);
}
break;
}
if (record != null)
{
throw new SCIMUniquenessAttributeException(string.Format(Global.AttributeMustBeUnique, attribute.SchemaAttribute.Name));
}
}
}
}
} | 57.352941 | 257 | 0.706081 | [
"Apache-2.0"
] | xinxin-sympli/SimpleIdServer | src/Scim/SimpleIdServer.Scim/Commands/Handlers/AddRepresentationCommandHandler.cs | 6,827 | C# |
// <copyright file="CommandLine.cs" company="Google Inc.">
// Copyright (C) 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
namespace GooglePlayServices
{
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System;
#if UNITY_EDITOR
using UnityEditor;
#endif // UNITY_EDITOR
using Google;
public static class CommandLine
{
/// <summary>
/// Result from Run().
/// </summary>
public class Result
{
/// String containing the standard output stream of the tool.
public string stdout;
/// String containing the standard error stream of the tool.
public string stderr;
/// Exit code returned by the tool when execution is complete.
public int exitCode;
/// String that can be used in an error message.
/// This contains:
/// * The command executed.
/// * Standard output string.
/// * Standard error string.
/// * Exit code.
public string message;
};
/// <summary>
/// Called when a RunAsync() completes.
/// </summary>
public delegate void CompletionHandler(Result result);
/// <summary>
/// Text and byte representations of an array of data.
/// </summary>
public class StreamData
{
/// <summary>
/// Handle to the stream this was read from.
/// e.g 0 for stdout, 1 for stderr.
/// </summary>
public int handle = 0;
/// <summary>
/// Text representation of "data".
/// </summary>
public string text = "";
/// <summary>
/// Array of bytes or "null" if no data is present.
/// </summary>
public byte[] data = null;
/// <summary>
/// Whether this marks the end of the stream.
/// </summary>
public bool end;
/// <summary>
/// Initialize this instance.
/// </summary>
/// <param name="handle">Stream identifier.</param>
/// <param name="text">String</param>
/// <param name="data">Bytes</param>
/// <param name="end">Whether this is the end of the stream.</param>
public StreamData(int handle, string text, byte[] data, bool end)
{
this.handle = handle;
this.text = text;
this.data = data;
this.end = end;
}
/// <summary>
/// Get an empty StreamData instance.
/// </summary>
public static StreamData Empty
{
get { return new StreamData(0, "", null, false); }
}
}
/// <summary>
/// Called when data is received from either the standard output or standard error
/// streams with a reference to the current standard input stream to enable simulated
/// interactive input.
/// </summary>
/// <param name="process">Executing process.</param>
/// <param name="stdin">Standard input stream.</param>
/// <param name="stream">Data read from the standard output or error streams.</param>
public delegate void IOHandler(Process process, StreamWriter stdin, StreamData streamData);
/// <summary>
/// Asynchronously execute a command line tool, calling the specified delegate on
/// completion.
/// NOTE: In batch mode this will be executed synchronously.
/// </summary>
/// <param name="toolPath">Tool to execute.</param>
/// <param name="arguments">String to pass to the tools' command line.</param>
/// <param name="completionDelegate">Called when the tool completes. This is always
/// called from the main thread.</param>
/// <param name="workingDirectory">Directory to execute the tool from.</param>
/// <param name="envVars">Additional environment variables to set for the command.</param>
/// <param name="ioHandler">Allows a caller to provide interactive input and also handle
/// both output and error streams from a single delegate.</param>
public static void RunAsync(
string toolPath, string arguments, CompletionHandler completionDelegate,
string workingDirectory = null,
Dictionary<string, string> envVars = null,
IOHandler ioHandler = null) {
Action action = () => {
Result result = Run(toolPath, arguments, workingDirectory, envVars: envVars,
ioHandler: ioHandler);
RunOnMainThread.Run(() => { completionDelegate(result);});
};
if (ExecutionEnvironment.InBatchMode) {
RunOnMainThread.Run(action);
} else {
Thread thread = new Thread(new ThreadStart(action));
thread.Start();
}
}
/// <summary>
/// Asynchronously reads binary data from a stream using a configurable buffer.
/// </summary>
private class AsyncStreamReader
{
/// <summary>
/// Delegate called when data is read from the stream.
/// <param name="streamData">Data read from the stream.</param>
/// </summary>
public delegate void Handler(StreamData streamData);
/// <summary>
/// Event which is signalled when data is received.
/// </summary>
public event Handler DataReceived;
// Signalled when a read completes.
private AutoResetEvent readEvent = null;
// Handle to the stream.
private int handle;
// Stream to read.
private Stream stream;
// Buffer used to read data from the stream.
private byte[] buffer;
// Whether reading is complete.
volatile bool complete = false;
/// <summary>
/// Initialize the reader.
/// </summary>
/// <param name="stream">Stream to read.</param>
/// <param name="bufferSize">Size of the buffer to read.</param>
public AsyncStreamReader(int handle, Stream stream, int bufferSize)
{
readEvent = new AutoResetEvent(false);
this.handle = handle;
this.stream = stream;
buffer = new byte[bufferSize];
}
/// <summary>
/// Get the handle of the stream associated with this reader.
/// </summary>
public int Handle
{
get
{
return handle;
}
}
/// <summary>
/// Start reading.
/// </summary>
public void Start()
{
if (!complete) (new Thread(new ThreadStart(Read))).Start();
}
/// <summary>
/// Read from the stream until the end is reached.
/// </summary>
private void Read()
{
while (!complete)
{
stream.BeginRead(
buffer, 0, buffer.Length, (asyncResult) => {
int bytesRead = stream.EndRead(asyncResult);
if (!complete)
{
complete = bytesRead == 0;
if (DataReceived != null)
{
byte[] copy = new byte[bytesRead];
Array.Copy(buffer, copy, copy.Length);
DataReceived(new StreamData(
handle, System.Text.Encoding.UTF8.GetString(copy), copy,
complete));
}
}
readEvent.Set();
}, null);
readEvent.WaitOne();
}
}
/// <summary>
/// Create a set of readers to read the specified streams, handles are assigned
/// based upon the index of each stream in the provided array.
/// </summary>
/// <param name="streams">Streams to read.</param>
/// <param name="bufferSize">Size of the buffer to use to read each stream.</param>
public static AsyncStreamReader[] CreateFromStreams(Stream[] streams, int bufferSize)
{
AsyncStreamReader[] readers = new AsyncStreamReader[streams.Length];
for (int i = 0; i < streams.Length; i++)
{
readers[i] = new AsyncStreamReader(i, streams[i], bufferSize);
}
return readers;
}
}
/// <summary>
/// Multiplexes data read from multiple AsyncStreamReaders onto a single thread.
/// </summary>
private class AsyncStreamReaderMultiplexer
{
/// Used to wait on items in the queue.
private AutoResetEvent queuedItem = null;
/// Queue of Data read from the readers.
private System.Collections.Queue queue = null;
/// Active stream handles.
private HashSet<int> activeStreams;
/// <summary>
/// Called when all streams reach the end or the reader is shut down.
/// </summary>
public delegate void CompletionHandler();
/// <summary>
/// Called when all streams reach the end or the reader is shut down.
/// </summary>
public event CompletionHandler Complete;
/// <summary>
/// Handler called from the multiplexer's thread.
/// </summary>
public event AsyncStreamReader.Handler DataReceived;
/// <summary>
/// Create the multiplexer and attach it to the specified handler.
/// </summary>
/// <param name="readers">Readers to read.</param>
/// <param name="handler">Called for queued data item.</param>
/// <param name="complete">Called when all readers complete.</param>
public AsyncStreamReaderMultiplexer(AsyncStreamReader[] readers,
AsyncStreamReader.Handler handler,
CompletionHandler complete = null)
{
queuedItem = new AutoResetEvent(false);
queue = System.Collections.Queue.Synchronized(new System.Collections.Queue());
activeStreams = new HashSet<int>();
foreach (AsyncStreamReader reader in readers)
{
reader.DataReceived += HandleRead;
activeStreams.Add(reader.Handle);
}
DataReceived += handler;
if (complete != null) Complete += complete;
(new Thread(new ThreadStart(PollQueue))).Start();
}
/// <summary>
/// Shutdown the multiplexer.
/// </summary>
public void Shutdown()
{
lock (activeStreams)
{
activeStreams.Clear();
}
queuedItem.Set();
}
// Handle stream read notification.
private void HandleRead(StreamData streamData)
{
queue.Enqueue(streamData);
queuedItem.Set();
}
// Poll the queue.
private void PollQueue()
{
while (activeStreams.Count > 0)
{
queuedItem.WaitOne();
while (queue.Count > 0)
{
StreamData data = (StreamData)queue.Dequeue();
if (data.end)
{
lock(activeStreams)
{
activeStreams.Remove(data.handle);
}
}
if (DataReceived != null) DataReceived(data);
}
}
if (Complete != null) Complete();
}
}
/// <summary>
/// Aggregates lines read by AsyncStreamReader.
/// </summary>
public class LineReader
{
// List of data keyed by stream handle.
private Dictionary<int, List<StreamData>> streamDataByHandle =
new Dictionary<int, List<StreamData>>();
/// <summary>
/// Event called with a new line of data.
/// </summary>
public event IOHandler LineHandler;
/// <summary>
/// Event called for each piece of data received.
/// </summary>
public event IOHandler DataHandler;
/// <summary>
/// Initialize the instance.
/// </summary>
/// <param name="handler">Called for each line read.</param>
public LineReader(IOHandler handler = null)
{
if (handler != null) LineHandler += handler;
}
/// <summary>
/// Retrieve the currently buffered set of data.
/// This allows the user to retrieve data before the end of a stream when
/// a newline isn't present.
/// </summary>
/// <param name="handle">Handle of the stream to query.</param>
/// <returns>List of data for the requested stream.</return>
public List<StreamData> GetBufferedData(int handle)
{
List<StreamData> handleData;
return streamDataByHandle.TryGetValue(handle, out handleData) ?
new List<StreamData>(handleData) : new List<StreamData>();
}
/// <summary>
/// Flush the internal buffer.
/// </summary>
public void Flush()
{
foreach (List<StreamData> handleData in streamDataByHandle.Values)
{
handleData.Clear();
}
}
/// <summary>
/// Aggregate the specified list of StringBytes into a single structure.
/// </summary>
/// <param name="handle">Stream handle.</param>
/// <param name="dataStream">Data to aggregate.</param>
public static StreamData Aggregate(List<StreamData> dataStream)
{
// Build a list of strings up to the newline.
List<string> stringList = new List<string>();
int byteArraySize = 0;
int handle = 0;
bool end = false;
foreach (StreamData sd in dataStream)
{
stringList.Add(sd.text);
byteArraySize += sd.data.Length;
handle = sd.handle;
end |= sd.end;
}
string concatenatedString = String.Join("", stringList.ToArray());
// Concatenate the list of bytes up to the StringBytes before the
// newline.
byte[] byteArray = new byte[byteArraySize];
int byteArrayOffset = 0;
foreach (StreamData sd in dataStream)
{
Array.Copy(sd.data, 0, byteArray, byteArrayOffset, sd.data.Length);
byteArrayOffset += sd.data.Length;
}
return new StreamData(handle, concatenatedString, byteArray, end);
}
/// <summary>
/// Delegate method which can be attached to AsyncStreamReader.DataReceived to
/// aggregate data until a new line is found before calling LineHandler.
/// </summary>
public void AggregateLine(Process process, StreamWriter stdin, StreamData data)
{
if (DataHandler != null) DataHandler(process, stdin, data);
bool linesProcessed = false;
if (data.data != null)
{
// Simplify line tracking by converting linefeeds to newlines.
data.text = data.text.Replace("\r\n", "\n").Replace("\r", "\n");
List<StreamData> aggregateList = GetBufferedData(data.handle);
aggregateList.Add(data);
bool complete = false;
while (!complete)
{
List<StreamData> newAggregateList = new List<StreamData>();
int textDataIndex = 0;
int aggregateListSize = aggregateList.Count;
complete = true;
foreach (StreamData textData in aggregateList)
{
bool end = data.end && (++textDataIndex == aggregateListSize);
newAggregateList.Add(textData);
int newlineOffset = textData.text.Length;
if (!end)
{
newlineOffset = textData.text.IndexOf("\n");
if (newlineOffset < 0) continue;
newAggregateList.Remove(textData);
}
StreamData concatenated = Aggregate(newAggregateList);
// Flush the aggregation list and store the overflow.
newAggregateList.Clear();
if (!end)
{
// Add the remaining line to the concatenated data.
concatenated.text += textData.text.Substring(0, newlineOffset + 1);
// Save the line after the newline in the buffer.
newAggregateList.Add(new StreamData(
data.handle, textData.text.Substring(newlineOffset + 1),
textData.data, false));
complete = false;
}
// Report the data.
if (LineHandler != null) LineHandler(process, stdin, concatenated);
linesProcessed = true;
}
aggregateList = newAggregateList;
}
streamDataByHandle[data.handle] = aggregateList;
}
// If no lines were processed call the handle to allow it to look ahead.
if (!linesProcessed && LineHandler != null)
{
LineHandler(process, stdin, StreamData.Empty);
}
}
}
/// <summary>
/// Execute a command line tool.
/// </summary>
/// <param name="toolPath">Tool to execute.</param>
/// <param name="arguments">String to pass to the tools' command line.</param>
/// <param name="workingDirectory">Directory to execute the tool from.</param>
/// <param name="envVars">Additional environment variables to set for the command.</param>
/// <param name="ioHandler">Allows a caller to provide interactive input and also handle
/// both output and error streams from a single delegate.</param>
/// <returns>CommandLineTool result if successful, raises an exception if it's not
/// possible to execute the tool.</returns>
public static Result Run(string toolPath, string arguments, string workingDirectory = null,
Dictionary<string, string> envVars = null,
IOHandler ioHandler = null) {
return RunViaShell(toolPath, arguments, workingDirectory: workingDirectory,
envVars: envVars, ioHandler: ioHandler, useShellExecution: false);
}
/// <summary>
/// Execute a command line tool.
/// </summary>
/// <param name="toolPath">Tool to execute. On Windows, if the path to this tool contains
/// single quotes (apostrophes) the tool will be executed via the shell.</param>
/// <param name="arguments">String to pass to the tools' command line.</param>
/// <param name="workingDirectory">Directory to execute the tool from.</param>
/// <param name="envVars">Additional environment variables to set for the command.</param>
/// <param name="ioHandler">Allows a caller to provide interactive input and also handle
/// both output and error streams from a single delegate. NOTE: This is ignored if
/// shell execution is enabled.</param>
/// <param name="useShellExecution">Execute the command via the shell. This disables
/// I/O redirection and causes a window to be popped up when the command is executed.
/// This uses file redirection to retrieve the standard output stream.
/// </param>
/// <param name="stdoutRedirectionInShellMode">Enables stdout and stderr redirection when
/// executing a command via the shell. This requires:
/// * cmd.exe (on Windows) or bash (on OSX / Linux) are in the path.
/// * Arguments containing whitespace are quoted.</param>
/// <returns>CommandLineTool result if successful, raises an exception if it's not
/// possible to execute the tool.</returns>
public static Result RunViaShell(
string toolPath, string arguments, string workingDirectory = null,
Dictionary<string, string> envVars = null,
IOHandler ioHandler = null, bool useShellExecution = false,
bool stdoutRedirectionInShellMode = true) {
System.Text.Encoding inputEncoding = Console.InputEncoding;
System.Text.Encoding outputEncoding = Console.OutputEncoding;
// Android SDK manager requires the input encoding to be set to
// UFT8 to pipe data to the tool.
// Cocoapods requires the output encoding to be set to UTF8 to
// retrieve output.
try {
Console.InputEncoding = System.Text.Encoding.UTF8;
Console.OutputEncoding = System.Text.Encoding.UTF8;
} catch (Exception e) {
UnityEngine.Debug.LogWarning(String.Format(
"Unable to set console input / output encoding to UTF8 (e.g en_US.UTF8-8). " +
"Some commands may fail. {0}", e));
}
// Mono 3.x on Windows can't execute tools with single quotes (apostrophes) in the path.
// The following checks for this condition and forces shell execution of tools in these
// paths which works fine as the shell tool should be in the system PATH.
if (UnityEngine.RuntimePlatform.WindowsEditor == UnityEngine.Application.platform &&
toolPath.Contains("\'")) {
useShellExecution = true;
stdoutRedirectionInShellMode = true;
}
string stdoutFileName = null;
string stderrFileName = null;
if (useShellExecution && stdoutRedirectionInShellMode) {
stdoutFileName = Path.GetTempFileName();
stderrFileName = Path.GetTempFileName();
string shellCmd ;
string shellArgPrefix;
string shellArgPostfix;
string escapedToolPath = toolPath;
if (UnityEngine.RuntimePlatform.WindowsEditor == UnityEngine.Application.platform) {
shellCmd = "cmd.exe";
shellArgPrefix = "/c \"";
shellArgPostfix = "\"";
} else {
shellCmd = "bash";
shellArgPrefix = "-l -c '";
shellArgPostfix = "'";
escapedToolPath = toolPath.Replace("'", "'\\''");
}
arguments = String.Format("{0}\"{1}\" {2} 1> {3} 2> {4}{5}", shellArgPrefix,
escapedToolPath, arguments, stdoutFileName,
stderrFileName, shellArgPostfix);
toolPath = shellCmd;
}
Process process = new Process();
process.StartInfo.UseShellExecute = useShellExecution;
process.StartInfo.Arguments = arguments;
if (useShellExecution) {
process.StartInfo.CreateNoWindow = false;
process.StartInfo.RedirectStandardOutput = false;
process.StartInfo.RedirectStandardError = false;
} else {
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
if (envVars != null) {
foreach (var env in envVars) {
process.StartInfo.EnvironmentVariables[env.Key] = env.Value;
}
}
}
process.StartInfo.RedirectStandardInput = !useShellExecution && (ioHandler != null);
process.StartInfo.FileName = toolPath;
process.StartInfo.WorkingDirectory = workingDirectory ?? Environment.CurrentDirectory;
process.Start();
// If an I/O handler was specified, call it with no data to provide a process and stdin
// handle before output data is sent to it.
if (ioHandler != null) ioHandler(process, process.StandardInput, StreamData.Empty);
List<string>[] stdouterr = new List<string>[] {
new List<string>(), new List<string>() };
if (useShellExecution) {
process.WaitForExit();
if (stdoutRedirectionInShellMode) {
stdouterr[0].Add(File.ReadAllText(stdoutFileName));
stdouterr[1].Add(File.ReadAllText(stderrFileName));
File.Delete(stdoutFileName);
File.Delete(stderrFileName);
}
} else {
AutoResetEvent complete = new AutoResetEvent(false);
// Read raw output from the process.
AsyncStreamReader[] readers = AsyncStreamReader.CreateFromStreams(
new Stream[] { process.StandardOutput.BaseStream,
process.StandardError.BaseStream }, 1);
new AsyncStreamReaderMultiplexer(
readers,
(StreamData data) => {
stdouterr[data.handle].Add(data.text);
if (ioHandler != null) ioHandler(process, process.StandardInput, data);
},
complete: () => { complete.Set(); });
foreach (AsyncStreamReader reader in readers) reader.Start();
process.WaitForExit();
// Wait for the reading threads to complete.
complete.WaitOne();
}
Result result = new Result();
result.stdout = String.Join("", stdouterr[0].ToArray());
result.stderr = String.Join("", stdouterr[1].ToArray());
result.exitCode = process.ExitCode;
result.message = FormatResultMessage(toolPath, arguments, result.stdout,
result.stderr, result.exitCode);
Console.InputEncoding = inputEncoding;
Console.OutputEncoding = outputEncoding;
return result;
}
/// <summary>
/// Split a string into lines using newline, carriage return or a combination of both.
/// </summary>
/// <param name="multilineString">String to split into lines</param>
public static string[] SplitLines(string multilineString)
{
return Regex.Split(multilineString, "\r\n|\r|\n");
}
/// <summary>
/// Format a command execution error message.
/// </summary>
/// <param name="toolPath">Tool executed.</param>
/// <param name="arguments">Arguments used to execute the tool.</param>
/// <param name="stdout">Standard output stream from tool execution.</param>
/// <param name="stderr">Standard error stream from tool execution.</param>
/// <param name="exitCode">Result of the tool.</param>
private static string FormatResultMessage(string toolPath, string arguments,
string stdout, string stderr,
int exitCode) {
return String.Format(
"{0} '{1} {2}'\n" +
"stdout:\n" +
"{3}\n" +
"stderr:\n" +
"{4}\n" +
"exit code: {5}\n",
exitCode == 0 ? "Successfully executed" : "Failed to run",
toolPath, arguments, stdout, stderr, exitCode);
}
#if UNITY_EDITOR
/// <summary>
/// Get an executable extension.
/// </summary>
/// <returns>Platform specific extension for executables.</returns>
public static string GetExecutableExtension()
{
return (UnityEngine.RuntimePlatform.WindowsEditor ==
UnityEngine.Application.platform) ? ".exe" : "";
}
/// <summary>
/// Locate an executable in the system path.
/// </summary>
/// <param name="exeName">Executable name without a platform specific extension like
/// .exe</param>
/// <returns>A string to the executable path if it's found, null otherwise.</returns>
public static string FindExecutable(string executable)
{
string which = (UnityEngine.RuntimePlatform.WindowsEditor ==
UnityEngine.Application.platform) ? "where" : "which";
try
{
Result result = Run(which, executable, Environment.CurrentDirectory);
if (result.exitCode == 0)
{
return SplitLines(result.stdout)[0];
}
}
catch (Exception e)
{
UnityEngine.Debug.Log("'" + which + "' command is not on path. " +
"Unable to find executable '" + executable +
"' (" + e.ToString() + ")");
}
return null;
}
#endif // UNITY_EDITOR
}
}
| 43.949246 | 100 | 0.51481 | [
"Apache-2.0"
] | harry-cpp/unity-jar-resolver | source/PlayServicesResolver/src/CommandLine.cs | 32,039 | C# |
#pragma checksum "C:\HolaWeb\HolaWeb.App\HolaWeb.App.Frontend\Pages\Saludos\Details.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "22cfad276551e2fa672c2db0268b7dd93e1199e9"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(HolaWeb.App.Frontend.Pages.Saludos.Pages_Saludos_Details), @"mvc.1.0.razor-page", @"/Pages/Saludos/Details.cshtml")]
namespace HolaWeb.App.Frontend.Pages.Saludos
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "C:\HolaWeb\HolaWeb.App\HolaWeb.App.Frontend\Pages\_ViewImports.cshtml"
using HolaWeb.App.Frontend;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"22cfad276551e2fa672c2db0268b7dd93e1199e9", @"/Pages/Saludos/Details.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"727676028a32bd1748031e664459573a646d94d0", @"/Pages/_ViewImports.cshtml")]
public class Pages_Saludos_Details : global::Microsoft.AspNetCore.Mvc.RazorPages.Page
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "./List", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("btn-default"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
#pragma warning restore 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral("<h2>");
#nullable restore
#line 5 "C:\HolaWeb\HolaWeb.App\HolaWeb.App.Frontend\Pages\Saludos\Details.cshtml"
Write(Model.Saludo.EnEspañol);
#line default
#line hidden
#nullable disable
WriteLiteral("</h2>\n<div>\n Id: ");
#nullable restore
#line 7 "C:\HolaWeb\HolaWeb.App\HolaWeb.App.Frontend\Pages\Saludos\Details.cshtml"
Write(Model.Saludo.Id);
#line default
#line hidden
#nullable disable
WriteLiteral("\n</div>\n<div>\n Ingles: ");
#nullable restore
#line 10 "C:\HolaWeb\HolaWeb.App\HolaWeb.App.Frontend\Pages\Saludos\Details.cshtml"
Write(Model.Saludo.EnIngles);
#line default
#line hidden
#nullable disable
WriteLiteral("\n</div>\n<div>\n Italiano: ");
#nullable restore
#line 13 "C:\HolaWeb\HolaWeb.App\HolaWeb.App.Frontend\Pages\Saludos\Details.cshtml"
Write(Model.Saludo.EnItaliano);
#line default
#line hidden
#nullable disable
WriteLiteral("\n</div>\n");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "22cfad276551e2fa672c2db0268b7dd93e1199e94555", async() => {
WriteLiteral("Lista de Saludos ");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<HolaWeb.App.Frontend.Pages.DetailsModel> Html { get; private set; }
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<HolaWeb.App.Frontend.Pages.DetailsModel> ViewData => (global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<HolaWeb.App.Frontend.Pages.DetailsModel>)PageContext?.ViewData;
public HolaWeb.App.Frontend.Pages.DetailsModel Model => ViewData.Model;
}
}
#pragma warning restore 1591
| 59.067797 | 349 | 0.75165 | [
"CC0-1.0"
] | felipeescallon/mision_tic_2022 | ciclo3_desarrollo_software/ucaldas/FRONTEND/sem5/HolaWeb.App/HolaWeb.App.Frontend/obj/Debug/netcoreapp3.1/Razor/Pages/Saludos/Details.cshtml.g.cs | 6,971 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Rhea.API.Models
{
/// <summary>
/// 校区类
/// </summary>
public class Campus
{
/// <summary>
/// 校区ID
/// </summary>
public int Id { get; set; }
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 备注
/// </summary>
public string Remark { get; set; }
/// <summary>
/// 最后编辑时间
/// </summary>
public DateTime LastUpdateTime { get; set; }
}
} | 18.878788 | 52 | 0.4687 | [
"BSD-3-Clause"
] | robertzml/Rhea | Rhea.API/Models/Campus.cs | 655 | C# |
//
// Copyright 2021 Dynatrace LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#pragma warning disable CS1591
namespace Dynatrace.OneAgent.Sdk.Api.Enums
{
/// <summary>
/// Encapsulates all well-known messaging destination types.
/// <see cref="IOneAgentSdk.CreateMessagingSystemInfo"/>
/// </summary>
public enum MessageDestinationType
{
QUEUE,
TOPIC
}
}
#pragma warning restore CS1591
| 30.612903 | 75 | 0.71549 | [
"Apache-2.0"
] | Dynatrace/OneAgent-SDK-for-dotnet | src/Api/Enums/MessageDestinationType.cs | 949 | C# |
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;
using Shared;
using CoreGraphics;
using Shared.DataBase;
namespace Mit4RobotApp
{
partial class VCOptionsMenu : UIViewController
{
public VCOptionsMenu(IntPtr handle) : base(handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
lblSlow.TextAlignment = UITextAlignment.Right;
lblFast.TextAlignment = UITextAlignment.Left;
GlobalSupport.GameSpeed = 1500;
lblSpeed.Text = "The gamespeed is: 2 seconds per move.";
sldrSpeed.Value = 2;
btnSave.TouchUpInside += (object sender, EventArgs e) =>
{
if (GlobalSupport.GameSpeed == 0)
{
GlobalSupport.GameSpeed = 500;
updateDatabase(GlobalSupport.GameSpeed);
}
else
{
updateDatabase(GlobalSupport.GameSpeed);
}
GlobalSupport.ShowPopupMessage("Options saved.");
};
sldrSpeed.ValueChanged += (object sender, EventArgs e) =>
{
lblSpeed.Text = "The gamespeed is: " + (sender as UISlider).Value.ToString() + " seconds per move.";
GlobalSupport.GameSpeed = (Int32)(((sender as UISlider).Value * 500) + 500);
};
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
UpdateGUI();
}
public override void DidRotate(UIInterfaceOrientation fromInterfaceOrientation)
{
base.DidRotate(fromInterfaceOrientation);
UpdateGUI();
}
public void UpdateGUI()
{
GlobalSupport.UpdateScreenSize(new CGRect(
0,
0,
UIScreen.MainScreen.Bounds.Width,
UIScreen.MainScreen.Bounds.Height));
scrollView.Frame = GlobalSupport.MainCGRect;
foreach (var item in scrollView.Subviews)
{
if (item is UILabel)
{
item.SizeToFit();
}
}
nfloat yCoordinate = 10;
lblFast.Frame = new CGRect(
10,
yCoordinate,
lblFast.Frame.Width,
GlobalSupport.ButtonHeight);
lblSlow.Frame = new CGRect(
GlobalSupport.ScreenWidth - lblSlow.Frame.Width - 5,
yCoordinate,
lblSlow.Frame.Width,
GlobalSupport.ButtonHeight);
sldrSpeed.Frame = new CGRect(
lblFast.Frame.X + lblFast.Frame.Width + 5,
yCoordinate,
GlobalSupport.ScreenWidth - lblFast.Frame.X - lblFast.Frame.Width - lblSlow.Bounds.Width - 15,
GlobalSupport.ButtonHeight);
yCoordinate += lblSlow.Frame.Height + 5;
lblSpeed.Frame = GlobalSupport.FullWidthCGRect(yCoordinate);
yCoordinate += lblSpeed.Frame.Height + 5;
btnSave.Frame = GlobalSupport.FullWidthCGRect(yCoordinate);
}
private void updateDatabase(int speed)
{
DataBase db = DataBase.Instance();
Settings settings = db.SelectFirst<Settings>();
if (settings != null)
{
settings.GameSpeed = speed;
db.Update(settings);
}
else
{
settings = new Settings();
settings.GameSpeed = speed;
db.Update(settings);
}
GlobalSupport.GameSpeed = settings.GameSpeed;
}
}
}
| 22.015152 | 104 | 0.686511 | [
"MIT"
] | ZuydUniversity/ProgramADroid | Mit4Robot/Mit4Robot_iOS/ViewControllers/Menus/VCOptionsMenu.cs | 2,906 | C# |
using System;
using Invenio.Core.Domain.Users;
using Invenio.Services.Tasks;
namespace Invenio.Services.Users
{
/// <summary>
/// Represents a task for deleting guest Users
/// </summary>
public partial class DeleteGuestsTask : ITask
{
private readonly IUserService _UserService;
private readonly UserSettings _UserSettings;
public DeleteGuestsTask(IUserService UserService, UserSettings UserSettings)
{
this._UserService = UserService;
this._UserSettings = UserSettings;
}
/// <summary>
/// Executes a task
/// </summary>
public void Execute()
{
var olderThanMinutes = _UserSettings.DeleteGuestTaskOlderThanMinutes;
// Default value in case 0 is returned. 0 would effectively disable this service and harm performance.
olderThanMinutes = olderThanMinutes == 0 ? 1440 : olderThanMinutes;
_UserService.DeleteGuestUsers(null, DateTime.UtcNow.AddMinutes(-olderThanMinutes), true);
}
}
}
| 31.705882 | 115 | 0.652134 | [
"MIT"
] | ipetk0v/InvenioReportingSystem | Libraries/Invenio.Services/Users/DeleteGuestsTask.cs | 1,080 | C# |
/*
╔══╗─ ╔╗─── ╔═══╗ ╔═══╗ ╔╗╔═╗ ╔═══╗
║╔╗║─ ║║─── ║╔═╗║ ║╔═╗║ ║║║╔╝ ║╔═╗║
║╚╝╚╗ ║║─── ║║─║║ ║║─╚╝ ║╚╝╝─ ║╚══╗
║╔═╗║ ║║─╔╗ ║║─║║ ║║─╔╗ ║╔╗║─ ╚══╗║
║╚═╝║ ║╚═╝║ ║╚═╝║ ║╚═╝║ ║║║╚╗ ║╚═╝║
╚═══╝ ╚═══╝ ╚═══╝ ╚═══╝ ╚╝╚═╝ ╚═══╝
* https://github.com/blocksteam/Blocks
* Contact Us: blocksteamcore@gmail.com
*/
namespace Blocks.Network.Bedrock.Raknet
{
/// <summary>
/// List of packet identifiers.
/// </summary>
public class PacketIdentifiers
{
public const byte UNCONNECTED_PING = 0x01;
public const byte UNCONNECTED_PONG = 0x1c;
}
}
| 27.875 | 56 | 0.345291 | [
"MIT"
] | BlocksTeam/Blocks | Blocks/Network/Bedrock/PacketIdentifiers.cs | 1,031 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MeritDemToStl")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MeritDemToStl")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 43.375 | 99 | 0.693701 | [
"MIT"
] | JamesLewisJr43/MeritDemToStl | MeritDemToStl/Properties/AssemblyInfo.cs | 2,432 | C# |
using System;
using System.IO;
using System.Collections.Generic;
using OpenTK;
namespace MyEngine
{
public partial class ObjLoader
{
public static Mesh Load(Resource resource, GameObject appendToGameObject=null)
{
var mesh = new ObjLoader().Parse(resource, appendToGameObject);
mesh.resource = resource;
return mesh;
}
static char[] splitCharacters = new char[] { ' ' };
static char[] trimCharacters = new char[] { ' ', '\t' };
List<Vector3> verticesObj = new List<Vector3>();
List<Vector3> normalsObj = new List<Vector3>();
List<Vector2> uvsObj = new List<Vector2>();
List<Vector3> verticesMesh = new List<Vector3>();
List<Vector3> normalsMesh = new List<Vector3>();
List<Vector2> uvsMesh = new List<Vector2>();
List<int> triangleIndiciesMesh = new List<int>();
bool gotUvs = false;
bool gotNormal = false;
Dictionary<string, int> objFaceToMeshIndicie = new Dictionary<string, int>();
MaterialLibrary materialLibrary;
MaterialPBR lastMaterial;
int failedParse = 0;
void Parse(ref string str, ref float t)
{
if (!float.TryParse(str, System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out t))
failedParse++;
}
Mesh Parse(Resource resource, GameObject appendToGameObject)
{
using (StreamReader textReader = new StreamReader(resource))
{
int i1, i2, i3, i4;
string line;
while ((line = textReader.ReadLine()) != null)
{
line = line.Trim(trimCharacters);
line = line.Replace(" ", " ");
string[] parameters = line.Split(splitCharacters);
switch (parameters[0])
{
case "p": // Point
break;
case "v": // Vertex
var v = Vector3.Zero;
Parse(ref parameters[1], ref v.X);
Parse(ref parameters[2], ref v.Y);
Parse(ref parameters[3], ref v.Z);
verticesObj.Add(v);
break;
case "vt": // TexCoord
gotUvs = true;
var vt = Vector2.Zero;
Parse(ref parameters[1], ref vt.X);
Parse(ref parameters[2], ref vt.Y);
uvsObj.Add(vt);
break;
case "vn": // Normal
gotNormal = true;
var vn = Vector3.Zero;
Parse(ref parameters[1], ref vn.X);
Parse(ref parameters[2], ref vn.Y);
Parse(ref parameters[3], ref vn.Z);
normalsObj.Add(vn);
break;
case "f":
switch (parameters.Length)
{
case 4:
i1 = ParseFaceParameter(parameters[1]);
i2 = ParseFaceParameter(parameters[2]);
i3 = ParseFaceParameter(parameters[3]);
triangleIndiciesMesh.Add(i1);
triangleIndiciesMesh.Add(i2);
triangleIndiciesMesh.Add(i3);
break;
case 5:
i1 = ParseFaceParameter(parameters[1]);
i2 = ParseFaceParameter(parameters[2]);
i3 = ParseFaceParameter(parameters[3]);
i4 = ParseFaceParameter(parameters[4]);
triangleIndiciesMesh.Add(i1);
triangleIndiciesMesh.Add(i2);
triangleIndiciesMesh.Add(i3);
triangleIndiciesMesh.Add(i1);
triangleIndiciesMesh.Add(i3);
triangleIndiciesMesh.Add(i4);
break;
}
break;
case "mtllib":
if (Resource.ResourceInFolderExists(resource, parameters[1]))
{
materialLibrary = new MaterialLibrary(Resource.GetResourceInFolder(resource, parameters[1]));
}
break;
case "usemtl":
if (materialLibrary!=null) lastMaterial = materialLibrary.GetMat(parameters[1]);
break;
}
}
textReader.Close();
}
if(appendToGameObject!=null) return EndObjPart(appendToGameObject);
Debug.Info("Loaded " + resource.originalPath + " vertices:" + verticesMesh.Count + " faces:" + triangleIndiciesMesh.Count / 3);
return EndMesh();
}
Mesh EndMesh()
{
var mesh = new Mesh();
mesh.vertices = verticesMesh.ToArray();
mesh.uvs = uvsMesh.ToArray();
mesh.triangleIndicies = triangleIndiciesMesh.ToArray();
if (failedParse > 0) Debug.Warning("Failed to parse data " + failedParse + " times");
failedParse = 0;
if (gotNormal) mesh.normals = normalsMesh.ToArray();
else mesh.RecalculateNormals();
return mesh;
}
Mesh EndObjPart(GameObject appendToGameObject)
{
var renderer = appendToGameObject.AddComponent<MeshRenderer>();
renderer.material = lastMaterial;
renderer.mesh = EndMesh();
return renderer.mesh;
}
static char[] faceParamaterSplitter = new char[] { '/' };
int ParseFaceParameter(string faceParameter)
{
Vector3 vertex = new Vector3();
Vector2 texCoord = new Vector2();
Vector3 normal = new Vector3();
string[] parameters = faceParameter.Split(faceParamaterSplitter);
int vertexIndex = int.Parse(parameters[0]);
if (vertexIndex < 0) vertexIndex = verticesObj.Count + vertexIndex;
else vertexIndex = vertexIndex - 1;
vertex = verticesObj[vertexIndex];
if (parameters.Length > 1)
{
int texCoordIndex = 0;
if (int.TryParse(parameters[1], out texCoordIndex))
{
if (texCoordIndex < 0) texCoordIndex = uvsObj.Count + texCoordIndex;
else texCoordIndex = texCoordIndex - 1;
texCoord = uvsObj[texCoordIndex];
}
}
if (parameters.Length > 2)
{
int normalIndex = 0;
if (int.TryParse(parameters[2], out normalIndex))
{
if (normalIndex < 0) normalIndex = normalsObj.Count + normalIndex;
else normalIndex = normalIndex - 1;
normal = normalsObj[normalIndex];
}
}
return FindOrAddObjVertex(ref faceParameter, ref vertex, ref texCoord, ref normal);
}
int FindOrAddObjVertex(ref string faceParamater, ref Vector3 vertex, ref Vector2 texCoord, ref Vector3 normal)
{
int index;
if (objFaceToMeshIndicie.TryGetValue(faceParamater, out index)) {
return index;
} else {
verticesMesh.Add(vertex);
uvsMesh.Add(texCoord);
normalsMesh.Add(normal);
index = verticesMesh.Count - 1;
objFaceToMeshIndicie[faceParamater]=index;
return index;
}
}
}
}
| 36.573913 | 139 | 0.464099 | [
"Unlicense"
] | aeroson/lego-game-and-Unity-like-engine | MyEngine/myengine/ObjLoader.cs | 8,414 | C# |
// Understanding the Addon System:
//
// 1. partial classes:
// The C# compiler will include all 'partial' classes of the same type into
// one big class. In other words, it's a way to split a big class into many
// smaller files.
//
// We use this for our addon system, so that a player addons can be in an
// extra file, but the compiler does throw them all into one class in the
// end. This also means that we never have to add addon scripts to all the
// right prefabs. The C# compiler does that for us automatically.
//
// Note: use [Header("MyAddon")] in front of your public variables so that
// you can find them easier in the Inspector.
//
// 2. hooks:
// The main classes have lots of places that we can hook into if necessary.
// So instead of having to modify Player.Awake in the main class, we can use
// the Awake_ hook below.
//
// All functions starting with Awake_ will be called there. So if one addon
// uses Awake_Loot and another addon uses Awake_Test, they are both called
// from Player.Awake automatically.
//
// If your addon is called 'Test', then your hook should be called Awake_Test
//
// 3. [SyncVar] Limit
// UNET has a 32 SyncVar per NetworkBehaviour limit. The current Player class
// leaves room for about 5 more [SyncVar]s. If you need more than that, check
// out my [SyncVar] limit workaround:
// https://forum.unity3d.com/threads/unet-32-syncvar-limit-workaround.473109/
//
// General workflow:
// Before this system, people simply modified uMMORPG's core files like
// Player.cs to their needs. With this system, you should start exactly the
// same way: open Player.cs and figure out where you want to add your modi-
// fications. But instead of adding them to Player.cs, you add them to your
// partial class below.
//
// For example: if you add a 'public int test' variable to the partial Player
// class below, it will be shown in all your Player prefabs automatically.
//
// Why:
// There are two main benefits of using this addon system:
// 1. Updates to the core files won't overwrite your modifications.
// 2. Sharing addons is way easier. All it takes is one addon script.
//
// The Partial + Hooks approach was the only solution for an addon system:
// - the only way to extend the item/skill/quest structs is with partial,
// so Unity components are out of the question
//
// Final Note:
// No addon system allows 100% modifications. There might be cases where you
// still have to modify the core scripts. If so, it's recommended to write
// down the necessary modifications for your addons in the comment section.
//
//
//
////////////////////////////////////////////////////////////////////////////////
// Example Addon
// Author: ...
//
// Description: ...
//
// Required Core modifications: ...
//
// Usage: ...
//
using System.Text;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
// entities ////////////////////////////////////////////////////////////////////
public partial class Player {
//[SyncVar] int test;
public partial class PlayerLevel {
}
void Awake_Example() {}
void OnStartLocalPlayer_Example() {}
void OnStartServer_Example() {}
void Start_Example() {}
void UpdateClient_Example() {}
void LateUpdate_Example() {}
void OnDestroy_Example() {}
[Server] void DealDamageAt_Example(HashSet<Entity> entities, int amount) {}
[Server] void OnDeath_Example() {}
[Client] void OnSelect_Example(Entity entity) {}
[Server] void OnLevelUp_Example() {}
[Server] void OnUseInventoryItem_Example(int index) {}
// you can use the drag and drop system too:
void OnDragAndDrop_InventorySlot_ExampleSlot(int[] slotIndices) {}
void OnDragAndClear_ExampleSlot(int slotIndex) {}
}
public partial class Monster {
void Awake_Example() {}
void OnStartServer_Example() {}
void Start_Example() {}
void UpdateClient_Example() {}
void LateUpdate_Example() {}
[Server] void OnAggro_Example(Entity entity) {}
[Server] void OnDeath_Example() {}
}
public partial class Npc {
void OnStartServer_Example() {}
void UpdateClient_Example() {}
}
public partial class Pet {
public partial class PetLevel {
}
void Awake_Example() {}
void OnStartServer_Example() {}
void Start_Example() {}
void UpdateClient_Example() {}
void LateUpdate_Example() {}
void OnDestroy_Example() {}
[Server] void OnLevelUp_Example() {}
[Server] void DealDamageAt_Example(HashSet<Entity> entities, int amount) {}
[Server] void OnAggro_Example(Entity entity) {}
[Server] void OnDeath_Example() {}
}
public partial class Entity {
void Awake_Example() {}
void OnStartServer_Example() {}
void Update_Example() {}
[Server] void DealDamageAt_Example(HashSet<Entity> entities, int amount) {}
}
// items ///////////////////////////////////////////////////////////////////////
public partial class ItemTemplate {
//[Header("My Addon")]
//public int addonVariable = 0;
}
// note: can't add variables yet without modifying original constructor
public partial struct Item {
//public int addonVariable {
// get { return template.addonVariable; }
//}
void ToolTip_Example(StringBuilder tip) {
//tip.Append("");
}
}
// skills //////////////////////////////////////////////////////////////////////
public partial class SkillTemplate {
//[Header("My Addon")]
//public int addonVariable = 0;
public partial struct SkillLevel {
// note: adding variables here will give lots of warnings, but it works.
//public int addonVariable;
}
}
// note: can't add variables yet without modifying original constructor
public partial struct Skill {
//public int addonVariable {
// get { return template.addonVariable; }
//}
void ToolTip_Example(StringBuilder tip) {
//tip.Append("");
}
}
// quests //////////////////////////////////////////////////////////////////////
public partial class QuestTemplate {
//[Header("My Addon")]
//public int addonVariable = 0;
}
// note: can't add variables yet without modifying original constructor
public partial struct Quest {
//public int addonVariable {
// get { return template.addonVariable; }
//}
void ToolTip_Example(StringBuilder tip) {
//tip.Append("");
}
}
// database ////////////////////////////////////////////////////////////////////
public partial class Database {
static void Initialize_Example() {
// it's usually best to create an extra table for your addon. example:
//ExecuteNonQuery(@"CREATE TABLE IF NOT EXISTS example (
// name TEXT NOT NULL PRIMARY KEY)");
}
static void CharacterLoad_Example(Player player) {}
static void CharacterSave_Example(Player player) {}
}
// networkmanager //////////////////////////////////////////////////////////////
public partial class NetworkManagerMMO {
void Start_Example() {}
void OnStartServer_Example() {}
void OnStopServer_Example() {}
void OnClientConnect_Example(NetworkConnection conn) {}
void OnServerLogin_Example(LoginMsg message) {}
void OnClientCharactersAvailable_Example(CharactersAvailableMsg message) {}
void OnServerAddPlayer_Example(string account, GameObject player, NetworkConnection conn, CharacterSelectMsg message) {}
void OnServerCharacterCreate_Example(CharacterCreateMsg message, Player player) {}
void OnServerCharacterDelete_Example(CharacterDeleteMsg message) {}
void OnServerDisconnect_Example(NetworkConnection conn) {}
void OnClientDisconnect_Example(NetworkConnection conn) {}
}
public partial class Chat {
void OnStartLocalPlayer_Example() {}
void OnSubmit_Example(string text) {}
}
// user interface //////////////////////////////////////////////////////////////
// all UI scripts are partial and provide Update hooks, so feel free to extend
// them here as well! for example:
public partial class UIChat {
void Update_Example() {}
}
| 35.504348 | 124 | 0.646828 | [
"MIT"
] | TUmedu/moonwaker | Assets/uMMORPG/Addons/AddonExample.cs | 8,168 | C# |
// ************************************************************************
//
// * Copyright 2017 OSIsoft, LLC
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// *
// * <http://www.apache.org/licenses/LICENSE-2.0>
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// ************************************************************************
using NUnit.Framework;
using OSIsoft.AF;
using OSIsoft.PIDevClub.PIWebApiClient.Api;
using OSIsoft.PIDevClub.PIWebApiClient.Model;
using System;
using System.Collections.Generic;
using System.Linq;
namespace OSIsoft.PIDevClub.PIWebApiClient.Test
{
/// <summary>
/// Class for testing ElementCategoryApi
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the API endpoint.
/// </remarks>
[TestFixture]
public class ElementCategoryApiTests : CommonApi
{
private IElementCategoryApi instance;
private string webId;
/// <summary>
/// Setup before each unit test
/// </summary>
[SetUp]
public void Init()
{
base.CommonInit();
instance = client.ElementCategory;
base.CreateSampleDatabaseForTests();
string path = Constants.AF_ELEMENT_CATEGORY_PATH;
string selectedFields = null;
webId = instance.GetByPath(path, selectedFields).WebId;
}
/// <summary>
/// Clean up after each unit test
/// </summary>
[TearDown]
public void Cleanup()
{
base.DeleteSampleDatabaseForTests();
}
/// <summary>
/// Test an instance of ElementCategoryApi
/// </summary>
[Test]
public void InstanceTest()
{
// TODO uncomment below to test 'IsInstanceOfType' ElementCategoryApi
Assert.IsInstanceOf(typeof(ElementCategoryApi), instance, "instance is a ElementCategoryApi");
}
/// <summary>
/// Test CreateSecurityEntry
/// </summary>
[Test]
public void CreateSecurityEntryTest()
{
PISecurityEntry securityEntry = new PISecurityEntry();
securityEntry.SecurityIdentityName = Constants.AF_SECURITY_IDENTITY_NAME;
securityEntry.AllowRights = new List<string>() { "ReadWrite", "Delete", "Execute", "Admin" };
securityEntry.DenyRights = new List<string>() { "ReadWriteData", "Subscribe", "SubscribeOthers", "Annotate", "None" };
bool? applyToChildren = null;
instance.CreateSecurityEntry(webId, securityEntry, applyToChildren);
var secEntry = instance.GetSecurityEntries(webId).Items.Where(m => m.Name == Constants.AF_SECURITY_IDENTITY_NAME).FirstOrDefault();
Assert.IsNotNull(secEntry);
}
/// <summary>
/// Test Delete
/// </summary>
[Test]
public void DeleteTest()
{
instance.Delete(webId);
AFDatabase db = StandardPISystem.Databases[Constants.AF_DATABASE_NAME];
db.Refresh();
AFCategory category = AFObject.FindObject(Constants.AF_ELEMENT_CATEGORY_PATH) as AFCategory;
Assert.IsNull(category);
DeleteSampleDatabaseForTests();
CreateSampleDatabaseForTests();
}
/// <summary>
/// Test DeleteSecurityEntry
/// </summary>
[Test]
public void DeleteSecurityEntryTest()
{
string name = Constants.AF_SECURITY_IDENTITY_NAME;
PISecurityEntry securityEntry = null;
try
{
securityEntry = instance.GetSecurityEntryByName(webId: webId, name: name);
}
catch (Exception)
{
if (securityEntry == null)
{
CreateSecurityEntryTest();
}
}
bool? applyToChildren = null;
instance.DeleteSecurityEntry(webId: webId, name: name, applyToChildren: applyToChildren);
var secEntry = instance.GetSecurityEntries(webId).Items.Where(m => m.Name == name).FirstOrDefault();
Assert.IsNull(secEntry);
}
/// <summary>
/// Test Get
/// </summary>
[Test]
public void GetTest()
{
string selectedFields = null;
var response = instance.Get(webId, selectedFields);
Assert.IsInstanceOf<PIElementCategory>(response, "response is PICategory");
}
/// <summary>
/// Test GetByPath
/// </summary>
[Test]
public void GetByPathTest()
{
string path = Constants.AF_ELEMENT_CATEGORY_PATH;
string selectedFields = null;
var response = instance.GetByPath(path, selectedFields);
Assert.IsInstanceOf<PIElementCategory>(response, "response is PICategory");
}
/// <summary>
/// Test GetSecurity
/// </summary>
[Test]
public void GetSecurityTest()
{
List<string> userIdentity = new List<string>() { @"marc\marc.adm", @"marc\marc.user" };
bool? forceRefresh = null;
string selectedFields = null;
var response = instance.GetSecurity(webId, userIdentity, forceRefresh, selectedFields);
Assert.IsInstanceOf<PIItemsSecurityRights>(response, "response is PIItemsSecurityRights");
}
/// <summary>
/// Test GetSecurityEntries
/// </summary>
[Test]
public void GetSecurityEntriesTest()
{
string nameFilter = null;
string selectedFields = null;
var response = instance.GetSecurityEntries(webId, nameFilter, selectedFields);
Assert.IsInstanceOf<PIItemsSecurityEntry>(response, "response is PIItemsSecurityEntry");
Assert.IsTrue(response.Items.Count > 0);
}
[Test]
public void GetSecurityEntriesTest1()
{
string selectedFields = null;
var response = instance.GetSecurityEntries(webId, "Administrators", selectedFields);
Assert.IsInstanceOf<PIItemsSecurityEntry>(response, "response is PIItemsSecurityEntry");
Assert.IsTrue(response.Items.Count > 0);
}
/// <summary>
/// Test GetSecurityEntryByName
/// </summary>
[Test]
public void GetSecurityEntryByNameTest()
{
string name = "Administrators";
string selectedFields = null;
var response = instance.GetSecurityEntryByName(webId: webId, name: name, selectedFields: selectedFields);
Assert.IsInstanceOf<PISecurityEntry>(response, "response is PISecurityEntry");
Assert.IsTrue(response.Name == name);
}
/// <summary>
/// Test Update
/// </summary>
[Test]
public void UpdateTest()
{
string path = Constants.AF_ELEMENT_CATEGORY_PATH;
PIElementCategory category = instance.GetByPath(path, null);
category.Id = null;
category.Description = "New element category description";
category.Links = null;
category.Path = null;
category.WebId = null;
instance.Update(webId, category);
StandardPISystem.Refresh();
AFCategory myCategory = AFObject.FindObject(path) as AFCategory;
myCategory.Refresh();
myCategory.Database.Refresh();
if (myCategory != null)
{
Assert.IsTrue(myCategory.Description == category.Description);
}
}
/// <summary>
/// Test UpdateSecurityEntry
/// </summary>
[Test]
public void UpdateSecurityEntryTest()
{
string name = Constants.AF_SECURITY_IDENTITY_NAME;
PISecurityEntry securityEntry = null;
try
{
securityEntry = instance.GetSecurityEntryByName(webId: webId, name: name);
}
catch (Exception)
{
if (securityEntry == null)
{
CreateSecurityEntryTest();
}
}
securityEntry = instance.GetSecurityEntryByName(webId: webId, name: name);
securityEntry.AllowRights = new List<string>() { "ReadWrite", "Delete", "Execute", "Admin", "Subscribe", "ReadWriteData" };
securityEntry.DenyRights = new List<string>() { "SubscribeOthers", "Annotate", "None" };
securityEntry.Name = null;
securityEntry.Links = null;
securityEntry.SecurityIdentityName = null;
bool? applyToChildren = null;
instance.UpdateSecurityEntry(webId: webId, name: name, securityEntry: securityEntry, applyToChildren: applyToChildren);
PISecurityEntry securityEntryUpdated = instance.GetSecurityEntryByName(webId: webId, name: name);
Assert.IsTrue(securityEntry.AllowRights.Count == securityEntryUpdated.AllowRights.Count);
}
}
}
| 37.187023 | 143 | 0.577338 | [
"Apache-2.0"
] | lydonchandra/PI-Web-API-Client-DotNet-Standard | src/OSIsoft.PIDevClub.PIWebApiClient/OSIsoft.PIDevClub.PIWebApiClient.Test/Api/ElementCategoryApiTests.cs | 9,743 | C# |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Text;
using System.Net;
using Microsoft.Extensions.Configuration;
namespace Ecore
{
public class ControllerBase
{
public static IConfigurationRoot Configuration;
protected Task SetTemplete(string patch, HttpResponse w)
{
string html = File.ReadAllText(@"./wwwroot/views/" + patch, Encoding.UTF8);
return w.WriteAsync(html);
}
protected object GetConfig(string key)
{
Configuration.Reload();
return Configuration[key];
}
protected string get_uft8(string unicodeString)
{
// return WebUtility.UrlDecode(unicodeString);
return Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(unicodeString));
}
}
}
| 26.625 | 87 | 0.646714 | [
"Apache-2.0"
] | secondlife2/Ecore | controllers/base.cs | 852 | C# |
using IntegrationTool.SDK;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IntegrationTool.Module.ConnectToSharepoint
{
public enum SharepointAuthenticationType
{
OnPremise,
SharepointOnline
}
public class ConnectToSharepointConfiguration : ConnectionConfigurationBase
{
public string SiteUrl { get; set; }
public SharepointAuthenticationType AuthenticationType { get; set; }
public bool UseIntegratedSecurity { get; set; }
public string Domain { get; set; }
public string User { get; set; }
public string Password { get; set; }
public ConnectToSharepointConfiguration()
{
UseIntegratedSecurity = true;
}
}
}
| 25.5 | 79 | 0.680147 | [
"MIT"
] | peterwidmer/IntegrationTool | IntegrationTool.Module.ConnectToSharepoint/ConnectToSharepointConfiguration.cs | 818 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\um\d3d12umddi.h(7702,9)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[StructLayout(LayoutKind.Sequential)]
public partial struct D3D12DDI_EXPORT_DESC_0054
{
[MarshalAs(UnmanagedType.LPWStr)]
public string Name;
[MarshalAs(UnmanagedType.LPWStr)]
public string ExportToRename;
public D3D12DDI_EXPORT_FLAGS Flags;
}
}
| 28.294118 | 88 | 0.683992 | [
"MIT"
] | Steph55/DirectN | DirectN/DirectN/Generated/D3D12DDI_EXPORT_DESC_0054.cs | 483 | C# |
#region Header
//
// CopyWallType.cs - duplicate a system type from on project to another to partially transfer project standards
//
// Copyright (C) 2011-2019 by Jeremy Tammik, Autodesk Inc. All rights reserved.
//
// Keywords: The Building Coder Revit API C# .NET add-in.
//
#endregion // Header
#region Namespaces
using System;
using System.Diagnostics;
using System.Reflection;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
#endregion // Namespaces
namespace BuildingCoder
{
[Transaction( TransactionMode.Manual )]
class CmdCopyWallType : IExternalCommand
{
/// <summary>
/// Source project to copy system type from.
/// </summary>
const string _source_project_path
= "Z:/a/case/sfdc/06676034/test/NewWallType.rvt";
/// <summary>
/// Source wall type name to copy.
/// </summary>
const string _wall_type_name = "NewWallType";
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements )
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Application app = uiapp.Application;
Document doc = uidoc.Document;
// Open source project
Document docHasFamily = app.OpenDocumentFile(
_source_project_path );
// Find system family to copy, e.g. using a named wall type
WallType wallType = null;
//WallTypeSet wallTypes = docHasFamily.WallTypes; // 2013
FilteredElementCollector wallTypes
= new FilteredElementCollector( docHasFamily ) // 2014
.OfClass( typeof( WallType ) );
int i = 0;
foreach( WallType wt in wallTypes )
{
string name = wt.Name;
Debug.Print( " {0} {1}", ++i, name );
if( name.Equals( _wall_type_name ) )
{
wallType = wt;
break;
}
}
if( null == wallType )
{
message = string.Format(
"Cannot find source wall type '{0}'"
+ " in source document '{1}'. ",
_wall_type_name, _source_project_path );
return Result.Failed;
}
// Create a new wall type in current document
using( Transaction t = new Transaction( doc ) )
{
t.Start( "Transfer Wall Type" );
WallType newWallType = null;
//WallTypeSet wallTypes = doc.WallTypes; // 2013
wallTypes = new FilteredElementCollector( doc )
.OfClass( typeof( WallType ) ); // 2014
foreach( WallType wt in wallTypes )
{
if( wt.Kind == wallType.Kind )
{
newWallType = wt.Duplicate( _wall_type_name )
as WallType;
Debug.Print( string.Format(
"New wall type '{0}' created.",
_wall_type_name ) );
break;
}
}
// Assign parameter values from source wall type:
#if COPY_INDIVIDUAL_PARAMETER_VALUE
// Example: individually copy the "Function" parameter value:
BuiltInParameter bip = BuiltInParameter.FUNCTION_PARAM;
string function = wallType.get_Parameter( bip ).AsString();
Parameter p = newWallType.get_Parameter( bip );
p.Set( function );
#endif // COPY_INDIVIDUAL_PARAMETER_VALUE
Parameter p = null;
foreach( Parameter p2 in newWallType.Parameters )
{
Definition d = p2.Definition;
if( p2.IsReadOnly )
{
Debug.Print( string.Format(
"Parameter '{0}' is read-only.", d.Name ) );
}
else
{
p = wallType.get_Parameter( d );
if( null == p )
{
Debug.Print( string.Format(
"Parameter '{0}' not found on source wall type.",
d.Name ) );
}
else
{
if( p.StorageType == StorageType.ElementId )
{
// Here you have to find the corresponding
// element in the target document.
Debug.Print( string.Format(
"Parameter '{0}' is an element id.",
d.Name ) );
}
else
{
if( p.StorageType == StorageType.Double )
{
p2.Set( p.AsDouble() );
}
else if( p.StorageType == StorageType.String )
{
p2.Set( p.AsString() );
}
else if( p.StorageType == StorageType.Integer )
{
p2.Set( p.AsInteger() );
}
Debug.Print( string.Format(
"Parameter '{0}' copied.", d.Name ) );
}
}
}
// Note:
// If a shared parameter parameter is attached,
// you need to create the shared parameter first,
// then copy the parameter value.
}
// If the system family type has some other properties,
// you need to copy them as well here. Reflection can
// be used to determine the available properties.
MemberInfo[] memberInfos = newWallType.GetType()
.GetMembers( BindingFlags.GetProperty );
foreach( MemberInfo m in memberInfos )
{
// Copy the writable property values here.
// As there are no property writable for
// Walltype, I ignore this process here.
}
t.Commit();
}
return Result.Succeeded;
}
}
}
| 28.70936 | 112 | 0.53466 | [
"MIT"
] | CADBIMDeveloper/the_building_coder_samples | BuildingCoder/BuildingCoder/CmdCopyWallType.cs | 5,828 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Reflection;
using Str.Common.Extensions;
namespace Str.MvvmCommon.Core {
[SuppressMessage("ReSharper", "MemberCanBePrivate.Global", Justification = "This is a library.")]
[SuppressMessage("ReSharper", "UnusedMember.Global", Justification = "This is a library.")]
[SuppressMessage("ReSharper", "ClassNeverInstantiated.Global", Justification = "This is a library.")]
public class ObservableObject : INotifyPropertyChanged {
#region INotifyPropertyChanged Implementation
public event PropertyChangedEventHandler? PropertyChanged;
#endregion INotifyPropertyChanged Implementation
#region Properties
public static bool IsDesignMode {
get {
using Process process = Process.GetCurrentProcess();
string name = process.ProcessName.ToLower().Trim();
return name == "devenv" || name == "xdesproc";
}
}
#endregion Properties
#region Protected Methods
protected void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpresssion) {
if (!(propertyExpresssion.Body is MemberExpression memberInfo)) throw new ArgumentException("The parameter is not a property.", nameof(propertyExpresssion));
PropertyInfo? propertyInfo = memberInfo.Member as PropertyInfo;
if (propertyInfo == null) throw new ArgumentException("The specified property does not exist.", nameof(propertyExpresssion));
OnPropertyChanged(new PropertyChangedEventArgs(propertyInfo.Name));
}
protected void RaisePropertyChanged() {
OnPropertyChanged(new PropertyChangedEventArgs(String.Empty));
}
protected bool SetField(ref double field, double value, params Expression<Func<double>>[] selectorArray) {
if (value.HasMinimalDifference(field)) return false;
field = value;
if (selectorArray.Length == 0) RaisePropertyChanged();
else selectorArray.ForEach(RaisePropertyChanged);
return true;
}
protected bool SetField<T1>(ref double field, double value, Expression<Func<double>> selector, Expression<Func<T1>> selector1) {
if (value.HasMinimalDifference(field)) return false;
field = value;
RaisePropertyChanged(selector);
RaisePropertyChanged(selector1);
return true;
}
protected bool SetField<T1, T2>(ref double field, double value, Expression<Func<double>> selector, Expression<Func<T1>> selector1, Expression<Func<T2>> selector2) {
if (value.HasMinimalDifference(field)) return false;
field = value;
RaisePropertyChanged(selector);
RaisePropertyChanged(selector1);
RaisePropertyChanged(selector2);
return true;
}
protected bool SetField<T1, T2, T3>(ref double field, double value, Expression<Func<double>> selector, Expression<Func<T1>> selector1, Expression<Func<T2>> selector2, Expression<Func<T3>> selector3) {
if (value.HasMinimalDifference(field)) return false;
field = value;
RaisePropertyChanged(selector);
RaisePropertyChanged(selector1);
RaisePropertyChanged(selector2);
RaisePropertyChanged(selector3);
return true;
}
protected bool SetField<T>(ref T field, T value, params Expression<Func<T>>[] selectorArray) {
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
if (selectorArray.Length == 0) RaisePropertyChanged();
else selectorArray.ForEach(RaisePropertyChanged);
return true;
}
protected bool SetField<T, T1>(ref T field, T value, Expression<Func<T>> selector, Expression<Func<T1>> selector1) {
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
RaisePropertyChanged(selector);
RaisePropertyChanged(selector1);
return true;
}
protected bool SetField<T, T1, T2>(ref T field, T value, Expression<Func<T>> selector, Expression<Func<T1>> selector1, Expression<Func<T2>> selector2) {
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
RaisePropertyChanged(selector);
RaisePropertyChanged(selector1);
RaisePropertyChanged(selector2);
return true;
}
protected bool SetField<T, T1, T2, T3>(ref T field, T value, Expression<Func<T>> selector, Expression<Func<T1>> selector1, Expression<Func<T2>> selector2, Expression<Func<T3>> selector3) {
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
RaisePropertyChanged(selector);
RaisePropertyChanged(selector1);
RaisePropertyChanged(selector2);
RaisePropertyChanged(selector3);
return true;
}
protected bool SetField<T, T1, T2, T3, T4>(ref T field, T value, Expression<Func<T>> selector, Expression<Func<T1>> selector1, Expression<Func<T2>> selector2, Expression<Func<T3>> selector3, Expression<Func<T4>> selector4) {
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
RaisePropertyChanged(selector);
RaisePropertyChanged(selector1);
RaisePropertyChanged(selector2);
RaisePropertyChanged(selector3);
RaisePropertyChanged(selector4);
return true;
}
protected bool SetField<T, T1, T2, T3, T4, T5>(ref T field, T value, Expression<Func<T>> selector, Expression<Func<T1>> selector1, Expression<Func<T2>> selector2, Expression<Func<T3>> selector3, Expression<Func<T4>> selector4, Expression<Func<T5>> selector5) {
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
RaisePropertyChanged(selector);
RaisePropertyChanged(selector1);
RaisePropertyChanged(selector2);
RaisePropertyChanged(selector3);
RaisePropertyChanged(selector4);
RaisePropertyChanged(selector5);
return true;
}
#endregion Protected Methods
#region Private Methods
private void OnPropertyChanged(PropertyChangedEventArgs pce) {
PropertyChanged?.Invoke(this, pce);
}
#endregion Private Methods
}
}
| 32.507853 | 264 | 0.711548 | [
"MIT"
] | stricq/STR.MvvmCommon | Str.MvvmCommon/Core/ObservableObject.cs | 6,211 | C# |
namespace UDBase.Controllers.LogSystem {
/// <summary>
/// Logger without any output for cases when you don't need any logs
/// </summary>
public sealed class EmptyLog : ILog {
public ULogger CreateLogger(ILogContext context) { return new ULogger(this, context); }
public void Assert(ILogContext context, string msg) { }
public void AssertFormat<T1>(ILogContext context, string msg, T1 arg1) { }
public void AssertFormat<T1, T2>(ILogContext context, string msg, T1 arg1, T2 arg2) { }
public void AssertFormat<T1, T2, T3>(ILogContext context, string msg, T1 arg1, T2 arg2, T3 arg3) { }
public void AssertFormat<T1, T2, T3, T4>(ILogContext context, string msg, T1 arg1, T2 arg2, T3 arg3, T4 arg4) { }
public void AssertFormat<T1, T2, T3, T4, T5>(ILogContext context, string msg, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) { }
public void AssertFormat(ILogContext context, string msg, params object[] args) { }
public void Error(ILogContext context, string msg) { }
public void ErrorFormat<T1>(ILogContext context, string msg, T1 arg1) { }
public void ErrorFormat<T1, T2>(ILogContext context, string msg, T1 arg1, T2 arg2) { }
public void ErrorFormat<T1, T2, T3>(ILogContext context, string msg, T1 arg1, T2 arg2, T3 arg3) { }
public void ErrorFormat<T1, T2, T3, T4>(ILogContext context, string msg, T1 arg1, T2 arg2, T3 arg3, T4 arg4) { }
public void ErrorFormat<T1, T2, T3, T4, T5>(ILogContext context, string msg, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) { }
public void ErrorFormat(ILogContext context, string msg, params object[] args) { }
public void Exception(ILogContext context, string msg) { }
public void ExceptionFormat<T1>(ILogContext context, string msg, T1 arg1) { }
public void ExceptionFormat<T1, T2>(ILogContext context, string msg, T1 arg1, T2 arg2) { }
public void ExceptionFormat<T1, T2, T3>(ILogContext context, string msg, T1 arg1, T2 arg2, T3 arg3) { }
public void ExceptionFormat<T1, T2, T3, T4>(ILogContext context, string msg, T1 arg1, T2 arg2, T3 arg3, T4 arg4) { }
public void ExceptionFormat<T1, T2, T3, T4, T5>(ILogContext context, string msg, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) { }
public void ExceptionFormat(ILogContext context, string msg, params object[] args) { }
public void Message(ILogContext context, string msg) { }
public void MessageFormat<T1>(ILogContext context, string msg, T1 arg1) { }
public void MessageFormat<T1, T2>(ILogContext context, string msg, T1 arg1, T2 arg2) { }
public void MessageFormat<T1, T2, T3>(ILogContext context, string msg, T1 arg1, T2 arg2, T3 arg3) { }
public void MessageFormat<T1, T2, T3, T4>(ILogContext context, string msg, T1 arg1, T2 arg2, T3 arg3, T4 arg4) { }
public void MessageFormat<T1, T2, T3, T4, T5>(ILogContext context, string msg, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) { }
public void MessageFormat(ILogContext context, string msg, params object[] args) { }
public void Warning(ILogContext context, string msg) { }
public void WarningFormat<T1>(ILogContext context, string msg, T1 arg1) { }
public void WarningFormat<T1, T2>(ILogContext context, string msg, T1 arg1, T2 arg2) { }
public void WarningFormat<T1, T2, T3>(ILogContext context, string msg, T1 arg1, T2 arg2, T3 arg3) { }
public void WarningFormat<T1, T2, T3, T4>(ILogContext context, string msg, T1 arg1, T2 arg2, T3 arg3, T4 arg4) { }
public void WarningFormat<T1, T2, T3, T4, T5>(ILogContext context, string msg, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) { }
public void WarningFormat(ILogContext context, string msg, params object[] args) { }
}
}
| 80.022222 | 131 | 0.720078 | [
"MIT"
] | KonH/UDBase | Scripts/Controllers/Log/EmptyLog.cs | 3,603 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering.PostProcessing;
public class PlayerLook : MonoBehaviour {
#region Field Of View
[Header("~ Field Of View <3")]
[Tooltip("Players default field of vision")]
public float fieldOfView;
[Tooltip("General rate of FOV change")]
public float normalRate;
[Tooltip("FOV when sliding down slope")]
public float slidingFOV;
[Tooltip("Rate that changes FOV to slidingFOV")]
public float slidingFOVRate;
[Tooltip("Rate that FOV returns to normal after stopping a slope slide")]
public float slideJumpFOVRate;
[Tooltip("FOV while sprinting")]
public float sprintFOV;
[Tooltip("Rate FOV changes while sprinting")]
public float sprintFOVRate;
private float FOV;
#endregion
#region Tilt
[Header("~ Tilt <3")]
[Tooltip("Angle player rotates while wall running")]
public float wallRunAngle;
[Tooltip("Rate that player tilts on a wall")]
public float wallTiltRate;
private float tilt;
#endregion
#region Sensitivity
[Header("~ Sensitivity <3")]
[Tooltip("Mouse X sensitivity")]
public float sensX;
[Tooltip("Mouse Y sensitivity")]
public float sensY;
private float mouseX;
private float mouseY;
#endregion
#region References
[Header("~ References <3")]
[SerializeField]
[Tooltip("Player Movement script")]
PlayerMovement pm;
[Tooltip("Player Camera (Component not GameObject")]
public Camera playerCamera;
[Tooltip("Player orientation object, child of player")]
public Transform orientation;
private float multiplier = 0.01f;
private float xRotation;
private float yRotation;
#endregion
public PostProcessVolume c_ProcessVolume;
public ColorGrading c_ColorGrading;
private void Awake() {
pm.GetComponent<PlayerMovement>();
}
private void Start() {
c_ColorGrading = ScriptableObject.CreateInstance<ColorGrading>();
if (c_ProcessVolume.profile.TryGetSettings<ColorGrading>(out ColorGrading cg)) {
c_ColorGrading = cg;
}
}
private void Update() {
if (!UIManager.paused) {
mouseX = Input.GetAxisRaw("Mouse X");
mouseY = Input.GetAxisRaw("Mouse Y");
yRotation += mouseX * sensX * multiplier;
xRotation -= mouseY * sensY * multiplier;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
playerCamera.transform.rotation = Quaternion.Euler(xRotation, yRotation, tilt);
orientation.transform.rotation = Quaternion.Euler(0, yRotation, 0);
playerCamera.fieldOfView = FOV;
}
}
public void OnLeftWallTilt() {
tilt = Mathf.Lerp(tilt, -wallRunAngle, Time.deltaTime * wallTiltRate);
}
public void OnRightWallTilt () {
tilt = Mathf.Lerp(tilt, wallRunAngle, Time.deltaTime * wallTiltRate);
}
public void NormalTilt() {
tilt = 0;
}
public void SlideFOV() {
FOV = Mathf.Lerp(FOV, slidingFOV, Time.deltaTime * slidingFOVRate);
}
public void SlopeJumpFOV() {
FOV = Mathf.Lerp(FOV, fieldOfView, Time.deltaTime * slideJumpFOVRate);
}
public void SprintFOV() {
FOV = Mathf.Lerp(FOV, sprintFOV, Time.deltaTime * sprintFOVRate);
}
public void NormalFOV() {
FOV = Mathf.Lerp(FOV, fieldOfView, Time.deltaTime * normalRate);
}
public void ReduceSaturation() {
c_ColorGrading.saturation.Override(-90);
}
public void RestoreSaturation() {
c_ColorGrading.saturation.Override(0);
}
}
| 29.645161 | 91 | 0.656964 | [
"MIT"
] | Joji-S/ParkourMovement | ParkourGame/Assets/Scripts/Player/PlayerLook.cs | 3,678 | C# |
#region License
// License for this implementation in C#:
// --------------------------------------
//
// Copyright (c) 2012 Govert van Drimmelen
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
//
// License from original C source version:
// ---------------------------------------
//
// Routines for Arbitrary Precision Floating-point Arithmetic
// and Fast Robust Geometric Predicates
// (predicates.c)
//
// May 18, 1996
//
// Placed in the public domain by
// Jonathan Richard Shewchuk
// School of Computer Science
// Carnegie Mellon University
// 5000 Forbes Avenue
// Pittsburgh, Pennsylvania 15213-3891
// jrs@cs.cmu.edu
//
// This file contains C implementation of algorithms for exact addition
// and multiplication of floating-point numbers, and predicates for
// robustly performing the orientation and incircle tests used in
// computational geometry. The algorithms and underlying theory are
// described in Jonathan Richard Shewchuk. "Adaptive Precision Floating-
// Point Arithmetic and Fast Robust Geometric Predicates." Technical
// Report CMU-CS-96-140, School of Computer Science, Carnegie Mellon
// University, Pittsburgh, Pennsylvania, May 1996. (Submitted to
// Discrete & Computational Geometry.)
//
// This file, the paper listed above, and other information are available
// from the Web page http://www.cs.cmu.edu/~quake/robust.html .
//
//-------------------------------------------------------------------------
#endregion
using System;
namespace RobustGeometry.Predicates
{
using EA = ExactArithmetic;
/// <summary>
/// Implements the four geometric predicates described by Shewchuck, and implemented in predicates.c.
/// For each predicate, exports a ~Fast version that is a non-robust implementation directly with double arithmetic,
/// an ~Exact version which completed the full calculation in exact arithmetic, and the preferred version which
/// implements the adaptive routines returning the correct sign and an approximate value.
/// </summary>
public static class GeometricPredicates
{
#region Error bounds
// epsilon is equal to Math.Pow(2.0, -53) and is the largest power of
// two that 1.0 + epsilon = 1.0.
// NOTE: Don't confuse this with double.Epsilon.
const double epsilon = 1.1102230246251565E-16;
// Error bounds for orientation and incircle tests.
const double resulterrbound = (3.0 + 8.0 * epsilon) * epsilon;
const double ccwerrboundA = (3.0 + 16.0 * epsilon) * epsilon;
const double ccwerrboundB = (2.0 + 12.0 * epsilon) * epsilon;
const double ccwerrboundC = (9.0 + 64.0 * epsilon) * epsilon * epsilon;
const double o3derrboundA = (7.0 + 56.0 * epsilon) * epsilon;
const double o3derrboundB = (3.0 + 28.0 * epsilon) * epsilon;
const double o3derrboundC = (26.0 + 288.0 * epsilon) * epsilon * epsilon;
const double iccerrboundA = (10.0 + 96.0 * epsilon) * epsilon;
const double iccerrboundB = (4.0 + 48.0 * epsilon) * epsilon;
const double iccerrboundC = (44.0 + 576.0 * epsilon) * epsilon * epsilon;
const double isperrboundA = (16.0 + 224.0 * epsilon) * epsilon;
const double isperrboundB = (5.0 + 72.0 * epsilon) * epsilon;
const double isperrboundC = (71.0 + 1408.0 * epsilon) * epsilon * epsilon;
#endregion
#region Orient2D
/// <summary>
/// Non-robust approximate 2D orientation test.
/// </summary>
/// <param name="pa">array with x and y coordinates of pa.</param>
/// <param name="pb">array with x and y coordinates of pb.</param>
/// <param name="pc">array with x and y coordinates of pc.</param>
/// <returns>a positive value if the points pa, pb, and pc occur
/// in counterclockwise order; a negative value if they occur in
/// clockwise order; and zero if they are collinear.
/// The result is also a rough aproximation of twice the signed
/// area of the triangle defined by the three points.</returns>
/// <remarks>The implementation computed the determinant using simple double arithmetic.</remarks>
public static double Orient2DFast(double[] pa, double[] pb, double[] pc)
{
double acx, bcx, acy, bcy;
acx = pa[0] - pc[0];
bcx = pb[0] - pc[0];
acy = pa[1] - pc[1];
bcy = pb[1] - pc[1];
return acx * bcy - acy * bcx;
}
internal static double Orient2DExact(double[] pa, double[] pb, double[] pc)
{
double axby1, axcy1, bxcy1, bxay1, cxay1, cxby1;
double axby0, axcy0, bxcy0, bxay0, cxay0, cxby0;
double[] aterms = new double[4];
double[] bterms = new double[4];
double[] cterms = new double[4];
double aterms3, bterms3, cterms3;
double[] v = new double[8];
double[] w = new double[12];
int vlength, wlength;
EA.TwoProduct(pa[0], pb[1], out axby1, out axby0);
EA.TwoProduct(pa[0], pc[1], out axcy1, out axcy0);
EA.TwoTwoDiff(axby1, axby0, axcy1, axcy0, out aterms3, out aterms[2], out aterms[1], out aterms[0]);
aterms[3] = aterms3;
EA.TwoProduct(pb[0], pc[1], out bxcy1, out bxcy0);
EA.TwoProduct(pb[0], pa[1], out bxay1, out bxay0);
EA.TwoTwoDiff(bxcy1, bxcy0, bxay1, bxay0, out bterms3, out bterms[2], out bterms[1], out bterms[0]);
bterms[3] = bterms3;
EA.TwoProduct(pc[0], pa[1], out cxay1, out cxay0);
EA.TwoProduct(pc[0], pb[1], out cxby1, out cxby0);
EA.TwoTwoDiff(cxay1, cxay0, cxby1, cxby0, out cterms3, out cterms[2], out cterms[1], out cterms[0]);
cterms[3] = cterms3;
vlength = EA.FastExpansionSumZeroElim(4, aterms, 4, bterms, v);
wlength = EA.FastExpansionSumZeroElim(vlength, v, 4, cterms, w);
// In S. predicates.c, this returns the largest component:
// return w[wlength - 1];
// However, this is not stable due to the expansions not being unique,
// So we return the summed estimate as the 'Exact' value.
return EA.Estimate(wlength, w);
}
internal static double Orient2DSlow(double[] pa, double[] pb, double[] pc)
{
double acx, acy, bcx, bcy;
double acxtail, acytail;
double bcxtail, bcytail;
double negate, negatetail;
double[] axby = new double[8];
double[] bxay = new double[8];
double axby7, bxay7;
double[] deter = new double[16];
int deterlen;
EA.TwoDiff(pa[0], pc[0], out acx, out acxtail);
EA.TwoDiff(pa[1], pc[1], out acy, out acytail);
EA.TwoDiff(pb[0], pc[0], out bcx, out bcxtail);
EA.TwoDiff(pb[1], pc[1], out bcy, out bcytail);
EA.TwoTwoProduct(acx, acxtail, bcy, bcytail,
out axby7, out axby[6], out axby[5], out axby[4],
out axby[3], out axby[2], out axby[1], out axby[0]);
axby[7] = axby7;
negate = -acy;
negatetail = -acytail;
EA.TwoTwoProduct(bcx, bcxtail, negate, negatetail,
out bxay7, out bxay[6], out bxay[5], out bxay[4],
out bxay[3], out bxay[2], out bxay[1], out bxay[0]);
bxay[7] = bxay7;
deterlen = EA.FastExpansionSumZeroElim(8, axby, 8, bxay, deter);
// In S. predicates.c, this returns the largest component:
// deter[deterlen - 1];
// However, this is not stable due to the expansions not being unique (even for ZeroElim),
// So we return the summed estimate as the 'Exact' value.
return EA.Estimate(deterlen, deter);
}
/// <summary>
/// Adaptive, robust 2D orientation test.
/// </summary>
/// <param name="pa">array with x and y coordinates of pa.</param>
/// <param name="pb">array with x and y coordinates of pb.</param>
/// <param name="pc">array with x and y coordinates of pc.</param>
/// <returns>a positive value if the points pa, pb, and pc occur
/// in counterclockwise order; a negative value if they occur in
/// clockwise order; and zero if they are collinear.
/// The result is also an aproximation of twice the signed
/// area of the triangle defined by the three points.</returns>
public static double Orient2D(double[] pa, double[] pb, double[] pc)
{
double detleft, detright, det;
double detsum, errbound;
detleft = (pa[0] - pc[0]) * (pb[1] - pc[1]);
detright = (pa[1] - pc[1]) * (pb[0] - pc[0]);
det = detleft - detright;
if (detleft > 0.0)
{
if (detright <= 0.0)
{
return det;
}
else
{
detsum = detleft + detright;
}
}
else if (detleft < 0.0)
{
if (detright >= 0.0)
{
return det;
}
else
{
detsum = -detleft - detright;
}
}
else
{
return det;
}
errbound = ccwerrboundA * detsum;
if ((det >= errbound) || (-det >= errbound))
{
return det;
}
return Orient2DAdapt(pa, pb, pc, detsum);
}
// Internal adaptive continuation
static double Orient2DAdapt(double[] pa, double[] pb, double[] pc, double detsum)
{
double acx, acy, bcx, bcy;
double acxtail, acytail, bcxtail, bcytail;
double detleft, detright;
double detlefttail, detrighttail;
double det, errbound;
double[] B = new double[4];
double[] C1 = new double[8];
double[] C2 = new double[12];
double[] D = new double[16];
double B3;
int C1length, C2length, Dlength;
double[] u = new double[4];
double u3;
double s1, t1;
double s0, t0;
acx = pa[0] - pc[0];
bcx = pb[0] - pc[0];
acy = pa[1] - pc[1];
bcy = pb[1] - pc[1];
EA.TwoProduct(acx, bcy, out detleft, out detlefttail);
EA.TwoProduct(acy, bcx, out detright, out detrighttail);
EA.TwoTwoDiff(detleft, detlefttail, detright, detrighttail,
out B3, out B[2], out B[1], out B[0]);
B[3] = B3;
det = EA.Estimate(4, B);
errbound = ccwerrboundB * detsum;
if ((det >= errbound) || (-det >= errbound))
{
return det;
}
EA.TwoDiffTail(pa[0], pc[0], acx, out acxtail);
EA.TwoDiffTail(pb[0], pc[0], bcx, out bcxtail);
EA.TwoDiffTail(pa[1], pc[1], acy, out acytail);
EA.TwoDiffTail(pb[1], pc[1], bcy, out bcytail);
if ((acxtail == 0.0) && (acytail == 0.0)
&& (bcxtail == 0.0) && (bcytail == 0.0))
{
return det;
}
errbound = ccwerrboundC * detsum + resulterrbound * Math.Abs(det);
det += (acx * bcytail + bcy * acxtail)
- (acy * bcxtail + bcx * acytail);
if ((det >= errbound) || (-det >= errbound))
{
return det;
}
EA.TwoProduct(acxtail, bcy, out s1, out s0);
EA.TwoProduct(acytail, bcx, out t1, out t0);
EA.TwoTwoDiff(s1, s0, t1, t0, out u3, out u[2], out u[1], out u[0]);
u[3] = u3;
C1length = EA.FastExpansionSumZeroElim(4, B, 4, u, C1);
EA.TwoProduct(acx, bcytail, out s1, out s0);
EA.TwoProduct(acy, bcxtail, out t1, out t0);
EA.TwoTwoDiff(s1, s0, t1, t0, out u3, out u[2], out u[1], out u[0]);
u[3] = u3;
C2length = EA.FastExpansionSumZeroElim(C1length, C1, 4, u, C2);
EA.TwoProduct(acxtail, bcytail, out s1, out s0);
EA.TwoProduct(acytail, bcxtail, out t1, out t0);
EA.TwoTwoDiff(s1, s0, t1, t0, out u3, out u[2], out u[1], out u[0]);
u[3] = u3;
Dlength = EA.FastExpansionSumZeroElim(C2length, C2, 4, u, D);
return (D[Dlength - 1]);
}
#endregion
#region Orient3D
/*****************************************************************************/
/* */
/* orient3dfast() Approximate 3D orientation test. Nonrobust. */
/* orient3dexact() Exact 3D orientation test. Robust. */
/* orient3dslow() Another exact 3D orientation test. Robust. */
/* orient3d() Adaptive exact 3D orientation test. Robust. */
/* */
/* Return a positive value if the point pd lies below the */
/* plane passing through pa, pb, and pc; "below" is defined so */
/* that pa, pb, and pc appear in counterclockwise order when */
/* viewed from above the plane. Returns a negative value if */
/* pd lies above the plane. Returns zero if the points are */
/* coplanar. The result is also a rough approximation of six */
/* times the signed volume of the tetrahedron defined by the */
/* four points. */
/* */
/* Only the first and last routine should be used; the middle two are for */
/* timings. */
/* */
/* The last three use exact arithmetic to ensure a correct answer. The */
/* result returned is the determinant of a matrix. In orient3d() only, */
/* this determinant is computed adaptively, in the sense that exact */
/* arithmetic is used only to the degree it is needed to ensure that the */
/* returned value has the correct sign. Hence, orient3d() is usually quite */
/* fast, but will run more slowly when the input points are coplanar or */
/* nearly so. */
/* */
/*****************************************************************************/
public static double Orient3DFast(double[] pa, double[] pb, double[] pc, double[] pd)
{
double adx, bdx, cdx;
double ady, bdy, cdy;
double adz, bdz, cdz;
adx = pa[0] - pd[0];
bdx = pb[0] - pd[0];
cdx = pc[0] - pd[0];
ady = pa[1] - pd[1];
bdy = pb[1] - pd[1];
cdy = pc[1] - pd[1];
adz = pa[2] - pd[2];
bdz = pb[2] - pd[2];
cdz = pc[2] - pd[2];
return adx * (bdy * cdz - bdz * cdy)
+ bdx * (cdy * adz - cdz * ady)
+ cdx * (ady * bdz - adz * bdy);
}
internal static double Orient3DExact(double[] pa, double[] pb, double[] pc, double[] pd)
{
double axby1, bxcy1, cxdy1, dxay1, axcy1, bxdy1;
double bxay1, cxby1, dxcy1, axdy1, cxay1, dxby1;
double axby0, bxcy0, cxdy0, dxay0, axcy0, bxdy0;
double bxay0, cxby0, dxcy0, axdy0, cxay0, dxby0;
double[] ab = new double[4];
double[] bc = new double[4];
double[] cd = new double[4];
double[] da = new double[4];
double[] ac = new double[4];
double[] bd = new double[4];
double[] temp8 = new double[8];
int templen;
double[] abc = new double[12];
double[] bcd = new double[12];
double[] cda = new double[12];
double[] dab = new double[12];
int abclen, bcdlen, cdalen, dablen;
double[] adet = new double[24];
double[] bdet = new double[24];
double[] cdet = new double[24];
double[] ddet = new double[24];
int alen, blen, clen, dlen;
double[] abdet = new double[48];
double[] cddet = new double[48];
int ablen, cdlen;
double[] deter = new double[96];
int deterlen;
int i;
EA.TwoProduct(pa[0], pb[1], out axby1, out axby0);
EA.TwoProduct(pb[0], pa[1], out bxay1, out bxay0);
EA.TwoTwoDiff(axby1, axby0, bxay1, bxay0, out ab[3], out ab[2], out ab[1], out ab[0]);
EA.TwoProduct(pb[0], pc[1], out bxcy1, out bxcy0);
EA.TwoProduct(pc[0], pb[1], out cxby1, out cxby0);
EA.TwoTwoDiff(bxcy1, bxcy0, cxby1, cxby0, out bc[3], out bc[2], out bc[1], out bc[0]);
EA.TwoProduct(pc[0], pd[1], out cxdy1, out cxdy0);
EA.TwoProduct(pd[0], pc[1], out dxcy1, out dxcy0);
EA.TwoTwoDiff(cxdy1, cxdy0, dxcy1, dxcy0, out cd[3], out cd[2], out cd[1], out cd[0]);
EA.TwoProduct(pd[0], pa[1], out dxay1, out dxay0);
EA.TwoProduct(pa[0], pd[1], out axdy1, out axdy0);
EA.TwoTwoDiff(dxay1, dxay0, axdy1, axdy0, out da[3], out da[2], out da[1], out da[0]);
EA.TwoProduct(pa[0], pc[1], out axcy1, out axcy0);
EA.TwoProduct(pc[0], pa[1], out cxay1, out cxay0);
EA.TwoTwoDiff(axcy1, axcy0, cxay1, cxay0, out ac[3], out ac[2], out ac[1], out ac[0]);
EA.TwoProduct(pb[0], pd[1], out bxdy1, out bxdy0);
EA.TwoProduct(pd[0], pb[1], out dxby1, out dxby0);
EA.TwoTwoDiff(bxdy1, bxdy0, dxby1, dxby0, out bd[3], out bd[2], out bd[1], out bd[0]);
templen = EA.FastExpansionSumZeroElim(4, cd, 4, da, temp8);
cdalen = EA.FastExpansionSumZeroElim(templen, temp8, 4, ac, cda);
templen = EA.FastExpansionSumZeroElim(4, da, 4, ab, temp8);
dablen = EA.FastExpansionSumZeroElim(templen, temp8, 4, bd, dab);
for (i = 0; i < 4; i++)
{
bd[i] = -bd[i];
ac[i] = -ac[i];
}
templen = EA.FastExpansionSumZeroElim(4, ab, 4, bc, temp8);
abclen = EA.FastExpansionSumZeroElim(templen, temp8, 4, ac, abc);
templen = EA.FastExpansionSumZeroElim(4, bc, 4, cd, temp8);
bcdlen = EA.FastExpansionSumZeroElim(templen, temp8, 4, bd, bcd);
alen = EA.ScaleExpansionZeroElim(bcdlen, bcd, pa[2], adet);
blen = EA.ScaleExpansionZeroElim(cdalen, cda, -pb[2], bdet);
clen = EA.ScaleExpansionZeroElim(dablen, dab, pc[2], cdet);
dlen = EA.ScaleExpansionZeroElim(abclen, abc, -pd[2], ddet);
ablen = EA.FastExpansionSumZeroElim(alen, adet, blen, bdet, abdet);
cdlen = EA.FastExpansionSumZeroElim(clen, cdet, dlen, ddet, cddet);
deterlen = EA.FastExpansionSumZeroElim(ablen, abdet, cdlen, cddet, deter);
// In S. predicates.c, this returns the largest component:
// deter[deterlen - 1];
// However, this is not stable due to the expansions not being unique (even for ZeroElim),
// So we return the summed estimate as the 'Exact' value.
return EA.Estimate(deterlen, deter);
}
internal static double Orient3DSlow(double[] pa, double[] pb, double[] pc, double[] pd)
{
double adx, ady, adz, bdx, bdy, bdz, cdx, cdy, cdz;
double adxtail, adytail, adztail;
double bdxtail, bdytail, bdztail;
double cdxtail, cdytail, cdztail;
double negate, negatetail;
double axby7, bxcy7, axcy7, bxay7, cxby7, cxay7;
double[] axby = new double[8];
double[] bxcy = new double[8];
double[] axcy = new double[8];
double[] bxay = new double[8];
double[] cxby = new double[8];
double[] cxay = new double[8];
double[] temp16 = new double[16];
double[] temp32 = new double[32];
double[] temp32t = new double[32];
int temp16len, temp32len, temp32tlen;
double[] adet = new double[64];
double[] bdet = new double[64];
double[] cdet = new double[64];
int alen, blen, clen;
double[] abdet = new double[128];
int ablen;
double[] deter = new double[192];
int deterlen;
EA.TwoDiff(pa[0], pd[0], out adx, out adxtail);
EA.TwoDiff(pa[1], pd[1], out ady, out adytail);
EA.TwoDiff(pa[2], pd[2], out adz, out adztail);
EA.TwoDiff(pb[0], pd[0], out bdx, out bdxtail);
EA.TwoDiff(pb[1], pd[1], out bdy, out bdytail);
EA.TwoDiff(pb[2], pd[2], out bdz, out bdztail);
EA.TwoDiff(pc[0], pd[0], out cdx, out cdxtail);
EA.TwoDiff(pc[1], pd[1], out cdy, out cdytail);
EA.TwoDiff(pc[2], pd[2], out cdz, out cdztail);
EA.TwoTwoProduct(adx, adxtail, bdy, bdytail,
out axby7, out axby[6], out axby[5], out axby[4],
out axby[3], out axby[2], out axby[1], out axby[0]);
axby[7] = axby7;
negate = -ady;
negatetail = -adytail;
EA.TwoTwoProduct(bdx, bdxtail, negate, negatetail,
out bxay7, out bxay[6], out bxay[5], out bxay[4],
out bxay[3], out bxay[2], out bxay[1], out bxay[0]);
bxay[7] = bxay7;
EA.TwoTwoProduct(bdx, bdxtail, cdy, cdytail,
out bxcy7, out bxcy[6], out bxcy[5], out bxcy[4],
out bxcy[3], out bxcy[2], out bxcy[1], out bxcy[0]);
bxcy[7] = bxcy7;
negate = -bdy;
negatetail = -bdytail;
EA.TwoTwoProduct(cdx, cdxtail, negate, negatetail,
out cxby7, out cxby[6], out cxby[5],out cxby[4],
out cxby[3], out cxby[2], out cxby[1], out cxby[0]);
cxby[7] = cxby7;
EA.TwoTwoProduct(cdx, cdxtail, ady, adytail,
out cxay7, out cxay[6], out cxay[5], out cxay[4],
out cxay[3], out cxay[2], out cxay[1], out cxay[0]);
cxay[7] = cxay7;
negate = -cdy;
negatetail = -cdytail;
EA.TwoTwoProduct(adx, adxtail, negate, negatetail,
out axcy7, out axcy[6], out axcy[5], out axcy[4],
out axcy[3], out axcy[2], out axcy[1], out axcy[0]);
axcy[7] = axcy7;
temp16len = EA.FastExpansionSumZeroElim(8, bxcy, 8, cxby, temp16);
temp32len = EA.ScaleExpansionZeroElim(temp16len, temp16, adz, temp32);
temp32tlen = EA.ScaleExpansionZeroElim(temp16len, temp16, adztail, temp32t);
alen = EA.FastExpansionSumZeroElim(temp32len, temp32, temp32tlen, temp32t, adet);
temp16len = EA.FastExpansionSumZeroElim(8, cxay, 8, axcy, temp16);
temp32len = EA.ScaleExpansionZeroElim(temp16len, temp16, bdz, temp32);
temp32tlen = EA.ScaleExpansionZeroElim(temp16len, temp16, bdztail, temp32t);
blen = EA.FastExpansionSumZeroElim(temp32len, temp32, temp32tlen, temp32t, bdet);
temp16len = EA.FastExpansionSumZeroElim(8, axby, 8, bxay, temp16);
temp32len = EA.ScaleExpansionZeroElim(temp16len, temp16, cdz, temp32);
temp32tlen = EA.ScaleExpansionZeroElim(temp16len, temp16, cdztail, temp32t);
clen = EA.FastExpansionSumZeroElim(temp32len, temp32, temp32tlen, temp32t, cdet);
ablen = EA.FastExpansionSumZeroElim(alen, adet, blen, bdet, abdet);
deterlen = EA.FastExpansionSumZeroElim(ablen, abdet, clen, cdet, deter);
// In S. predicates.c, this returns the largest component:
// deter[deterlen - 1];
// However, this is not stable due to the expansions not being unique (even for ZeroElim),
// So we return the summed estimate as the 'Exact' value.
return EA.Estimate(deterlen, deter);
}
public static double Orient3D(double[] pa, double[] pb, double[] pc, double[] pd)
{
double adx, bdx, cdx, ady, bdy, cdy, adz, bdz, cdz;
double bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady;
double det;
double permanent, errbound;
adx = pa[0] - pd[0];
bdx = pb[0] - pd[0];
cdx = pc[0] - pd[0];
ady = pa[1] - pd[1];
bdy = pb[1] - pd[1];
cdy = pc[1] - pd[1];
adz = pa[2] - pd[2];
bdz = pb[2] - pd[2];
cdz = pc[2] - pd[2];
bdxcdy = bdx * cdy;
cdxbdy = cdx * bdy;
cdxady = cdx * ady;
adxcdy = adx * cdy;
adxbdy = adx * bdy;
bdxady = bdx * ady;
det = adz * (bdxcdy - cdxbdy)
+ bdz * (cdxady - adxcdy)
+ cdz * (adxbdy - bdxady);
permanent = (Math.Abs(bdxcdy) + Math.Abs(cdxbdy)) * Math.Abs(adz)
+ (Math.Abs(cdxady) + Math.Abs(adxcdy)) * Math.Abs(bdz)
+ (Math.Abs(adxbdy) + Math.Abs(bdxady)) * Math.Abs(cdz);
errbound = o3derrboundA * permanent;
if ((det > errbound) || (-det > errbound))
{
return det;
}
return Orient3DAdapt(pa, pb, pc, pd, permanent);
}
// Adaptive continuation for Orient3D
static double Orient3DAdapt(double[] pa, double[] pb, double[] pc, double[] pd, double permanent)
{
double adx, bdx, cdx, ady, bdy, cdy, adz, bdz, cdz;
double det, errbound;
double bdxcdy1, cdxbdy1, cdxady1, adxcdy1, adxbdy1, bdxady1;
double bdxcdy0, cdxbdy0, cdxady0, adxcdy0, adxbdy0, bdxady0;
double[] bc = new double[4];
double[] ca = new double[4];
double[] ab = new double[4];
double bc3, ca3, ab3;
double[] adet = new double[8];
double[] bdet = new double[8];
double[] cdet = new double[8];
int alen, blen, clen;
double[] abdet = new double[16];
int ablen;
double[] finnow, finother, finswap;
double[] fin1 = new double[192];
double[] fin2 = new double[192];
int finlength;
double adxtail, bdxtail, cdxtail;
double adytail, bdytail, cdytail;
double adztail, bdztail, cdztail;
double at_blarge, at_clarge;
double bt_clarge, bt_alarge;
double ct_alarge, ct_blarge;
double[] at_b = new double[4];
double[] at_c = new double[4];
double[] bt_c = new double[4];
double[] bt_a = new double[4];
double[] ct_a = new double[4];
double[] ct_b = new double[4];
int at_blen, at_clen, bt_clen, bt_alen, ct_alen, ct_blen;
double bdxt_cdy1, cdxt_bdy1, cdxt_ady1;
double adxt_cdy1, adxt_bdy1, bdxt_ady1;
double bdxt_cdy0, cdxt_bdy0, cdxt_ady0;
double adxt_cdy0, adxt_bdy0, bdxt_ady0;
double bdyt_cdx1, cdyt_bdx1, cdyt_adx1;
double adyt_cdx1, adyt_bdx1, bdyt_adx1;
double bdyt_cdx0, cdyt_bdx0, cdyt_adx0;
double adyt_cdx0, adyt_bdx0, bdyt_adx0;
double[] bct = new double[8];
double[] cat = new double[8];
double[] abt = new double[8];
int bctlen, catlen, abtlen;
double bdxt_cdyt1, cdxt_bdyt1, cdxt_adyt1;
double adxt_cdyt1, adxt_bdyt1, bdxt_adyt1;
double bdxt_cdyt0, cdxt_bdyt0, cdxt_adyt0;
double adxt_cdyt0, adxt_bdyt0, bdxt_adyt0;
double[] u = new double[4];
double[] v = new double[12];
double[] w = new double[16];
double u3;
int vlength, wlength;
double negate;
adx = pa[0] - pd[0];
bdx = pb[0] - pd[0];
cdx = pc[0] - pd[0];
ady = pa[1] - pd[1];
bdy = pb[1] - pd[1];
cdy = pc[1] - pd[1];
adz = pa[2] - pd[2];
bdz = pb[2] - pd[2];
cdz = pc[2] - pd[2];
EA.TwoProduct(bdx, cdy, out bdxcdy1, out bdxcdy0);
EA.TwoProduct(cdx, bdy, out cdxbdy1, out cdxbdy0);
EA.TwoTwoDiff(bdxcdy1, bdxcdy0, cdxbdy1, cdxbdy0, out bc3, out bc[2], out bc[1], out bc[0]);
bc[3] = bc3;
alen = EA.ScaleExpansionZeroElim(4, bc, adz, adet);
EA.TwoProduct(cdx, ady, out cdxady1, out cdxady0);
EA.TwoProduct(adx, cdy, out adxcdy1, out adxcdy0);
EA.TwoTwoDiff(cdxady1, cdxady0, adxcdy1, adxcdy0, out ca3, out ca[2], out ca[1], out ca[0]);
ca[3] = ca3;
blen = EA.ScaleExpansionZeroElim(4, ca, bdz, bdet);
EA.TwoProduct(adx, bdy, out adxbdy1, out adxbdy0);
EA.TwoProduct(bdx, ady, out bdxady1, out bdxady0);
EA.TwoTwoDiff(adxbdy1, adxbdy0, bdxady1, bdxady0, out ab3, out ab[2], out ab[1], out ab[0]);
ab[3] = ab3;
clen = EA.ScaleExpansionZeroElim(4, ab, cdz, cdet);
ablen = EA.FastExpansionSumZeroElim(alen, adet, blen, bdet, abdet);
finlength = EA.FastExpansionSumZeroElim(ablen, abdet, clen, cdet, fin1);
det = EA.Estimate(finlength, fin1);
errbound = o3derrboundB * permanent;
if ((det >= errbound) || (-det >= errbound))
{
return det;
}
EA.TwoDiffTail(pa[0], pd[0], adx, out adxtail);
EA.TwoDiffTail(pb[0], pd[0], bdx, out bdxtail);
EA.TwoDiffTail(pc[0], pd[0], cdx, out cdxtail);
EA.TwoDiffTail(pa[1], pd[1], ady, out adytail);
EA.TwoDiffTail(pb[1], pd[1], bdy, out bdytail);
EA.TwoDiffTail(pc[1], pd[1], cdy, out cdytail);
EA.TwoDiffTail(pa[2], pd[2], adz, out adztail);
EA.TwoDiffTail(pb[2], pd[2], bdz, out bdztail);
EA.TwoDiffTail(pc[2], pd[2], cdz, out cdztail);
if ((adxtail == 0.0) && (bdxtail == 0.0) && (cdxtail == 0.0)
&& (adytail == 0.0) && (bdytail == 0.0) && (cdytail == 0.0)
&& (adztail == 0.0) && (bdztail == 0.0) && (cdztail == 0.0))
{
return det;
}
errbound = o3derrboundC * permanent + resulterrbound * Math.Abs(det);
det += (adz * ((bdx * cdytail + cdy * bdxtail)
- (bdy * cdxtail + cdx * bdytail))
+ adztail * (bdx * cdy - bdy * cdx))
+ (bdz * ((cdx * adytail + ady * cdxtail)
- (cdy * adxtail + adx * cdytail))
+ bdztail * (cdx * ady - cdy * adx))
+ (cdz * ((adx * bdytail + bdy * adxtail)
- (ady * bdxtail + bdx * adytail))
+ cdztail * (adx * bdy - ady * bdx));
if ((det >= errbound) || (-det >= errbound))
{
return det;
}
finnow = fin1;
finother = fin2;
if (adxtail == 0.0)
{
if (adytail == 0.0)
{
at_b[0] = 0.0;
at_blen = 1;
at_c[0] = 0.0;
at_clen = 1;
}
else
{
negate = -adytail;
EA.TwoProduct(negate, bdx, out at_blarge, out at_b[0]);
at_b[1] = at_blarge;
at_blen = 2;
EA.TwoProduct(adytail, cdx, out at_clarge, out at_c[0]);
at_c[1] = at_clarge;
at_clen = 2;
}
}
else
{
if (adytail == 0.0)
{
EA.TwoProduct(adxtail, bdy, out at_blarge, out at_b[0]);
at_b[1] = at_blarge;
at_blen = 2;
negate = -adxtail;
EA.TwoProduct(negate, cdy, out at_clarge, out at_c[0]);
at_c[1] = at_clarge;
at_clen = 2;
}
else
{
EA.TwoProduct(adxtail, bdy, out adxt_bdy1, out adxt_bdy0);
EA.TwoProduct(adytail, bdx, out adyt_bdx1, out adyt_bdx0);
EA.TwoTwoDiff(adxt_bdy1, adxt_bdy0, adyt_bdx1, adyt_bdx0,
out at_blarge, out at_b[2], out at_b[1], out at_b[0]);
at_b[3] = at_blarge;
at_blen = 4;
EA.TwoProduct(adytail, cdx, out adyt_cdx1, out adyt_cdx0);
EA.TwoProduct(adxtail, cdy, out adxt_cdy1, out adxt_cdy0);
EA.TwoTwoDiff(adyt_cdx1, adyt_cdx0, adxt_cdy1, adxt_cdy0,
out at_clarge, out at_c[2], out at_c[1], out at_c[0]);
at_c[3] = at_clarge;
at_clen = 4;
}
}
if (bdxtail == 0.0)
{
if (bdytail == 0.0)
{
bt_c[0] = 0.0;
bt_clen = 1;
bt_a[0] = 0.0;
bt_alen = 1;
}
else
{
negate = -bdytail;
EA.TwoProduct(negate, cdx, out bt_clarge, out bt_c[0]);
bt_c[1] = bt_clarge;
bt_clen = 2;
EA.TwoProduct(bdytail, adx, out bt_alarge, out bt_a[0]);
bt_a[1] = bt_alarge;
bt_alen = 2;
}
}
else
{
if (bdytail == 0.0)
{
EA.TwoProduct(bdxtail, cdy, out bt_clarge, out bt_c[0]);
bt_c[1] = bt_clarge;
bt_clen = 2;
negate = -bdxtail;
EA.TwoProduct(negate, ady, out bt_alarge, out bt_a[0]);
bt_a[1] = bt_alarge;
bt_alen = 2;
}
else
{
EA.TwoProduct(bdxtail, cdy, out bdxt_cdy1, out bdxt_cdy0);
EA.TwoProduct(bdytail, cdx, out bdyt_cdx1, out bdyt_cdx0);
EA.TwoTwoDiff(bdxt_cdy1, bdxt_cdy0, bdyt_cdx1, bdyt_cdx0,
out bt_clarge, out bt_c[2], out bt_c[1], out bt_c[0]);
bt_c[3] = bt_clarge;
bt_clen = 4;
EA.TwoProduct(bdytail, adx, out bdyt_adx1, out bdyt_adx0);
EA.TwoProduct(bdxtail, ady, out bdxt_ady1, out bdxt_ady0);
EA.TwoTwoDiff(bdyt_adx1, bdyt_adx0, bdxt_ady1, bdxt_ady0,
out bt_alarge, out bt_a[2], out bt_a[1], out bt_a[0]);
bt_a[3] = bt_alarge;
bt_alen = 4;
}
}
if (cdxtail == 0.0)
{
if (cdytail == 0.0)
{
ct_a[0] = 0.0;
ct_alen = 1;
ct_b[0] = 0.0;
ct_blen = 1;
}
else
{
negate = -cdytail;
EA.TwoProduct(negate, adx, out ct_alarge, out ct_a[0]);
ct_a[1] = ct_alarge;
ct_alen = 2;
EA.TwoProduct(cdytail, bdx, out ct_blarge, out ct_b[0]);
ct_b[1] = ct_blarge;
ct_blen = 2;
}
}
else
{
if (cdytail == 0.0)
{
EA.TwoProduct(cdxtail, ady, out ct_alarge, out ct_a[0]);
ct_a[1] = ct_alarge;
ct_alen = 2;
negate = -cdxtail;
EA.TwoProduct(negate, bdy, out ct_blarge, out ct_b[0]);
ct_b[1] = ct_blarge;
ct_blen = 2;
}
else
{
EA.TwoProduct(cdxtail, ady, out cdxt_ady1, out cdxt_ady0);
EA.TwoProduct(cdytail, adx, out cdyt_adx1, out cdyt_adx0);
EA.TwoTwoDiff(cdxt_ady1, cdxt_ady0, cdyt_adx1, cdyt_adx0,
out ct_alarge, out ct_a[2], out ct_a[1], out ct_a[0]);
ct_a[3] = ct_alarge;
ct_alen = 4;
EA.TwoProduct(cdytail, bdx, out cdyt_bdx1, out cdyt_bdx0);
EA.TwoProduct(cdxtail, bdy, out cdxt_bdy1, out cdxt_bdy0);
EA.TwoTwoDiff(cdyt_bdx1, cdyt_bdx0, cdxt_bdy1, cdxt_bdy0,
out ct_blarge, out ct_b[2], out ct_b[1], out ct_b[0]);
ct_b[3] = ct_blarge;
ct_blen = 4;
}
}
bctlen = EA.FastExpansionSumZeroElim(bt_clen, bt_c, ct_blen, ct_b, bct);
wlength = EA.ScaleExpansionZeroElim(bctlen, bct, adz, w);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, wlength, w, finother);
finswap = finnow; finnow = finother; finother = finswap;
catlen = EA.FastExpansionSumZeroElim(ct_alen, ct_a, at_clen, at_c, cat);
wlength = EA.ScaleExpansionZeroElim(catlen, cat, bdz, w);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, wlength, w, finother);
finswap = finnow; finnow = finother; finother = finswap;
abtlen = EA.FastExpansionSumZeroElim(at_blen, at_b, bt_alen, bt_a, abt);
wlength = EA.ScaleExpansionZeroElim(abtlen, abt, cdz, w);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, wlength, w, finother);
finswap = finnow; finnow = finother; finother = finswap;
if (adztail != 0.0)
{
vlength = EA.ScaleExpansionZeroElim(4, bc, adztail, v);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, vlength, v, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
if (bdztail != 0.0)
{
vlength = EA.ScaleExpansionZeroElim(4, ca, bdztail, v);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, vlength, v, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
if (cdztail != 0.0)
{
vlength = EA.ScaleExpansionZeroElim(4, ab, cdztail, v);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, vlength, v, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
if (adxtail != 0.0)
{
if (bdytail != 0.0)
{
EA.TwoProduct(adxtail, bdytail, out adxt_bdyt1, out adxt_bdyt0);
EA.TwoOneProduct(adxt_bdyt1, adxt_bdyt0, cdz, out u3, out u[2], out u[1], out u[0]);
u[3] = u3;
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, 4, u,
finother);
finswap = finnow; finnow = finother; finother = finswap;
if (cdztail != 0.0)
{
EA.TwoOneProduct(adxt_bdyt1, adxt_bdyt0, cdztail, out u3, out u[2], out u[1], out u[0]);
u[3] = u3;
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, 4, u,
finother);
finswap = finnow; finnow = finother; finother = finswap;
}
}
if (cdytail != 0.0)
{
negate = -adxtail;
EA.TwoProduct(negate, cdytail, out adxt_cdyt1, out adxt_cdyt0);
EA.TwoOneProduct(adxt_cdyt1, adxt_cdyt0, bdz, out u3, out u[2], out u[1], out u[0]);
u[3] = u3;
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, 4, u,
finother);
finswap = finnow; finnow = finother; finother = finswap;
if (bdztail != 0.0)
{
EA.TwoOneProduct(adxt_cdyt1, adxt_cdyt0, bdztail, out u3, out u[2], out u[1], out u[0]);
u[3] = u3;
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, 4, u,
finother);
finswap = finnow; finnow = finother; finother = finswap;
}
}
}
if (bdxtail != 0.0)
{
if (cdytail != 0.0)
{
EA.TwoProduct(bdxtail, cdytail, out bdxt_cdyt1, out bdxt_cdyt0);
EA.TwoOneProduct(bdxt_cdyt1, bdxt_cdyt0, adz, out u3, out u[2], out u[1], out u[0]);
u[3] = u3;
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, 4, u,
finother);
finswap = finnow; finnow = finother; finother = finswap;
if (adztail != 0.0)
{
EA.TwoOneProduct(bdxt_cdyt1, bdxt_cdyt0, adztail, out u3, out u[2], out u[1], out u[0]);
u[3] = u3;
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, 4, u,
finother);
finswap = finnow; finnow = finother; finother = finswap;
}
}
if (adytail != 0.0)
{
negate = -bdxtail;
EA.TwoProduct(negate, adytail, out bdxt_adyt1, out bdxt_adyt0);
EA.TwoOneProduct(bdxt_adyt1, bdxt_adyt0, cdz, out u3, out u[2], out u[1], out u[0]);
u[3] = u3;
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, 4, u,
finother);
finswap = finnow; finnow = finother; finother = finswap;
if (cdztail != 0.0)
{
EA.TwoOneProduct(bdxt_adyt1, bdxt_adyt0, cdztail, out u3, out u[2], out u[1], out u[0]);
u[3] = u3;
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, 4, u,
finother);
finswap = finnow; finnow = finother; finother = finswap;
}
}
}
if (cdxtail != 0.0)
{
if (adytail != 0.0)
{
EA.TwoProduct(cdxtail, adytail, out cdxt_adyt1, out cdxt_adyt0);
EA.TwoOneProduct(cdxt_adyt1, cdxt_adyt0, bdz, out u3, out u[2], out u[1], out u[0]);
u[3] = u3;
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, 4, u,
finother);
finswap = finnow; finnow = finother; finother = finswap;
if (bdztail != 0.0)
{
EA.TwoOneProduct(cdxt_adyt1, cdxt_adyt0, bdztail, out u3, out u[2], out u[1], out u[0]);
u[3] = u3;
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, 4, u, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
}
if (bdytail != 0.0)
{
negate = -cdxtail;
EA.TwoProduct(negate, bdytail, out cdxt_bdyt1, out cdxt_bdyt0);
EA.TwoOneProduct(cdxt_bdyt1, cdxt_bdyt0, adz, out u3, out u[2], out u[1], out u[0]);
u[3] = u3;
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, 4, u,
finother);
finswap = finnow; finnow = finother; finother = finswap;
if (adztail != 0.0)
{
EA.TwoOneProduct(cdxt_bdyt1, cdxt_bdyt0, adztail, out u3, out u[2], out u[1], out u[0]);
u[3] = u3;
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, 4, u, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
}
}
if (adztail != 0.0)
{
wlength = EA.ScaleExpansionZeroElim(bctlen, bct, adztail, w);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, wlength, w, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
if (bdztail != 0.0)
{
wlength = EA.ScaleExpansionZeroElim(catlen, cat, bdztail, w);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, wlength, w, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
if (cdztail != 0.0)
{
wlength = EA.ScaleExpansionZeroElim(abtlen, abt, cdztail, w);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, wlength, w, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
return finnow[finlength - 1];
}
#endregion
#region InCircle
/*****************************************************************************/
/* */
/* incirclefast() Approximate 2D incircle test. Nonrobust. */
/* incircleexact() Exact 2D incircle test. Robust. */
/* incircleslow() Another exact 2D incircle test. Robust. */
/* incircle() Adaptive exact 2D incircle test. Robust. */
/* */
/* Return a positive value if the point pd lies inside the */
/* circle passing through pa, pb, and pc; a negative value if */
/* it lies outside; and zero if the four points are cocircular.*/
/* The points pa, pb, and pc must be in counterclockwise */
/* order, or the sign of the result will be reversed. */
/* */
/* Only the first and last routine should be used; the middle two are for */
/* timings. */
/* */
/* The last three use exact arithmetic to ensure a correct answer. The */
/* result returned is the determinant of a matrix. In incircle() only, */
/* this determinant is computed adaptively, in the sense that exact */
/* arithmetic is used only to the degree it is needed to ensure that the */
/* returned value has the correct sign. Hence, incircle() is usually quite */
/* fast, but will run more slowly when the input points are cocircular or */
/* nearly so. */
/* */
/*****************************************************************************/
// |pax pay pax^2+pay^2 1|
// |pbx pby pbx^2+pby^2 1|
// |pcx pcy pcx^2+pcy^2 1|
// |pdx pdy pdx^2+pdy^2 1|
public static double InCircleFast(double[] pa, double[] pb, double[] pc, double[] pd)
{
double adx, ady, bdx, bdy, cdx, cdy;
double abdet, bcdet, cadet;
double alift, blift, clift;
adx = pa[0] - pd[0];
ady = pa[1] - pd[1];
bdx = pb[0] - pd[0];
bdy = pb[1] - pd[1];
cdx = pc[0] - pd[0];
cdy = pc[1] - pd[1];
abdet = adx * bdy - bdx * ady;
bcdet = bdx * cdy - cdx * bdy;
cadet = cdx * ady - adx * cdy;
alift = adx * adx + ady * ady;
blift = bdx * bdx + bdy * bdy;
clift = cdx * cdx + cdy * cdy;
return alift * bcdet + blift * cadet + clift * abdet;
}
internal static double InCircleExact(double[] pa, double[] pb, double[] pc, double[] pd)
{
double axby1, bxcy1, cxdy1, dxay1, axcy1, bxdy1;
double bxay1, cxby1, dxcy1, axdy1, cxay1, dxby1;
double axby0, bxcy0, cxdy0, dxay0, axcy0, bxdy0;
double bxay0, cxby0, dxcy0, axdy0, cxay0, dxby0;
double[] ab = new double[4];
double[] bc = new double[4];
double[] cd = new double[4];
double[] da = new double[4];
double[] ac = new double[4];
double[] bd = new double[4];
double[] temp8 = new double[8];
int templen;
double[] abc = new double[12];
double[] bcd = new double[12];
double[] cda = new double[12];
double[] dab = new double[12];
int abclen, bcdlen, cdalen, dablen;
double[] det24x = new double[24];
double[] det24y = new double[24];
double[] det48x = new double[48];
double[] det48y = new double[48];
int xlen, ylen;
double[] adet = new double[96];
double[] bdet = new double[96];
double[] cdet = new double[96];
double[] ddet = new double[96];
int alen, blen, clen, dlen;
double[] abdet = new double[192];
double[] cddet = new double[192];
int ablen, cdlen;
double[] deter = new double[384];
int deterlen;
int i;
EA.TwoProduct(pa[0], pb[1], out axby1, out axby0);
EA.TwoProduct(pb[0], pa[1], out bxay1, out bxay0);
EA.TwoTwoDiff(axby1, axby0, bxay1, bxay0, out ab[3], out ab[2], out ab[1], out ab[0]);
EA.TwoProduct(pb[0], pc[1], out bxcy1, out bxcy0);
EA.TwoProduct(pc[0], pb[1], out cxby1, out cxby0);
EA.TwoTwoDiff(bxcy1, bxcy0, cxby1, cxby0, out bc[3], out bc[2], out bc[1], out bc[0]);
EA.TwoProduct(pc[0], pd[1], out cxdy1, out cxdy0);
EA.TwoProduct(pd[0], pc[1], out dxcy1, out dxcy0);
EA.TwoTwoDiff(cxdy1, cxdy0, dxcy1, dxcy0, out cd[3], out cd[2], out cd[1], out cd[0]);
EA.TwoProduct(pd[0], pa[1], out dxay1, out dxay0);
EA.TwoProduct(pa[0], pd[1], out axdy1, out axdy0);
EA.TwoTwoDiff(dxay1, dxay0, axdy1, axdy0, out da[3], out da[2], out da[1], out da[0]);
EA.TwoProduct(pa[0], pc[1], out axcy1, out axcy0);
EA.TwoProduct(pc[0], pa[1], out cxay1, out cxay0);
EA.TwoTwoDiff(axcy1, axcy0, cxay1, cxay0, out ac[3], out ac[2], out ac[1], out ac[0]);
EA.TwoProduct(pb[0], pd[1], out bxdy1, out bxdy0);
EA.TwoProduct(pd[0], pb[1], out dxby1, out dxby0);
EA.TwoTwoDiff(bxdy1, bxdy0, dxby1, dxby0, out bd[3], out bd[2], out bd[1], out bd[0]);
templen = EA.FastExpansionSumZeroElim(4, cd, 4, da, temp8);
cdalen = EA.FastExpansionSumZeroElim(templen, temp8, 4, ac, cda);
templen = EA.FastExpansionSumZeroElim(4, da, 4, ab, temp8);
dablen = EA.FastExpansionSumZeroElim(templen, temp8, 4, bd, dab);
for (i = 0; i < 4; i++)
{
bd[i] = -bd[i];
ac[i] = -ac[i];
}
templen = EA.FastExpansionSumZeroElim(4, ab, 4, bc, temp8);
abclen = EA.FastExpansionSumZeroElim(templen, temp8, 4, ac, abc);
templen = EA.FastExpansionSumZeroElim(4, bc, 4, cd, temp8);
bcdlen = EA.FastExpansionSumZeroElim(templen, temp8, 4, bd, bcd);
xlen = EA.ScaleExpansionZeroElim(bcdlen, bcd, pa[0], det24x);
xlen = EA.ScaleExpansionZeroElim(xlen, det24x, pa[0], det48x);
ylen = EA.ScaleExpansionZeroElim(bcdlen, bcd, pa[1], det24y);
ylen = EA.ScaleExpansionZeroElim(ylen, det24y, pa[1], det48y);
alen = EA.FastExpansionSumZeroElim(xlen, det48x, ylen, det48y, adet);
xlen = EA.ScaleExpansionZeroElim(cdalen, cda, pb[0], det24x);
xlen = EA.ScaleExpansionZeroElim(xlen, det24x, -pb[0], det48x);
ylen = EA.ScaleExpansionZeroElim(cdalen, cda, pb[1], det24y);
ylen = EA.ScaleExpansionZeroElim(ylen, det24y, -pb[1], det48y);
blen = EA.FastExpansionSumZeroElim(xlen, det48x, ylen, det48y, bdet);
xlen = EA.ScaleExpansionZeroElim(dablen, dab, pc[0], det24x);
xlen = EA.ScaleExpansionZeroElim(xlen, det24x, pc[0], det48x);
ylen = EA.ScaleExpansionZeroElim(dablen, dab, pc[1], det24y);
ylen = EA.ScaleExpansionZeroElim(ylen, det24y, pc[1], det48y);
clen = EA.FastExpansionSumZeroElim(xlen, det48x, ylen, det48y, cdet);
xlen = EA.ScaleExpansionZeroElim(abclen, abc, pd[0], det24x);
xlen = EA.ScaleExpansionZeroElim(xlen, det24x, -pd[0], det48x);
ylen = EA.ScaleExpansionZeroElim(abclen, abc, pd[1], det24y);
ylen = EA.ScaleExpansionZeroElim(ylen, det24y, -pd[1], det48y);
dlen = EA.FastExpansionSumZeroElim(xlen, det48x, ylen, det48y, ddet);
ablen = EA.FastExpansionSumZeroElim(alen, adet, blen, bdet, abdet);
cdlen = EA.FastExpansionSumZeroElim(clen, cdet, dlen, ddet, cddet);
deterlen = EA.FastExpansionSumZeroElim(ablen, abdet, cdlen, cddet, deter);
// In S. predicates.c, this returns the largest component:
// deter[deterlen - 1];
// However, this is not stable due to the expansions not being unique (even for ZeroElim),
// So we return the summed estimate as the 'Exact' value.
return EA.Estimate(deterlen, deter);
}
internal static double InCircleSlow(double[] pa, double[] pb, double[] pc, double[] pd)
{
double adx, bdx, cdx, ady, bdy, cdy;
double adxtail, bdxtail, cdxtail;
double adytail, bdytail, cdytail;
double negate, negatetail;
double axby7, bxcy7, axcy7, bxay7, cxby7, cxay7;
double[] axby = new double[8];
double[] bxcy = new double[8];
double[] axcy = new double[8];
double[] bxay = new double[8];
double[] cxby = new double[8];
double[] cxay = new double[8];
double[] temp16 = new double[16];
int temp16len;
double[] detx = new double[32];
double[] detxx = new double[64];
double[] detxt = new double[32];
double[] detxxt = new double[64];
double[] detxtxt = new double[64];
int xlen, xxlen, xtlen, xxtlen, xtxtlen;
double[] x1 = new double[128];
double[] x2 = new double[192];
int x1len, x2len;
double[] dety = new double[32];
double[] detyy = new double[64];
double[] detyt = new double[32];
double[] detyyt = new double[64];
double[] detytyt = new double[64];
int ylen, yylen, ytlen, yytlen, ytytlen;
double[] y1 = new double[128];
double[] y2 = new double[192];
int y1len, y2len;
double[] adet = new double[384];
double[] bdet = new double[384];
double[] cdet = new double[384];
double[] abdet = new double[768];
double[] deter = new double[1152];
int alen, blen, clen, ablen, deterlen;
int i;
EA.TwoDiff(pa[0], pd[0], out adx, out adxtail);
EA.TwoDiff(pa[1], pd[1], out ady, out adytail);
EA.TwoDiff(pb[0], pd[0], out bdx, out bdxtail);
EA.TwoDiff(pb[1], pd[1], out bdy, out bdytail);
EA.TwoDiff(pc[0], pd[0], out cdx, out cdxtail);
EA.TwoDiff(pc[1], pd[1], out cdy, out cdytail);
EA.TwoTwoProduct(adx, adxtail, bdy, bdytail,
out axby7, out axby[6], out axby[5], out axby[4],
out axby[3], out axby[2], out axby[1], out axby[0]);
axby[7] = axby7;
negate = -ady;
negatetail = -adytail;
EA.TwoTwoProduct(bdx, bdxtail, negate, negatetail,
out bxay7, out bxay[6], out bxay[5], out bxay[4],
out bxay[3], out bxay[2], out bxay[1], out bxay[0]);
bxay[7] = bxay7;
EA.TwoTwoProduct(bdx, bdxtail, cdy, cdytail,
out bxcy7, out bxcy[6], out bxcy[5], out bxcy[4],
out bxcy[3], out bxcy[2], out bxcy[1], out bxcy[0]);
bxcy[7] = bxcy7;
negate = -bdy;
negatetail = -bdytail;
EA.TwoTwoProduct(cdx, cdxtail, negate, negatetail,
out cxby7, out cxby[6], out cxby[5], out cxby[4],
out cxby[3], out cxby[2], out cxby[1], out cxby[0]);
cxby[7] = cxby7;
EA.TwoTwoProduct(cdx, cdxtail, ady, adytail,
out cxay7, out cxay[6], out cxay[5], out cxay[4],
out cxay[3], out cxay[2], out cxay[1], out cxay[0]);
cxay[7] = cxay7;
negate = -cdy;
negatetail = -cdytail;
EA.TwoTwoProduct(adx, adxtail, negate, negatetail,
out axcy7, out axcy[6], out axcy[5], out axcy[4],
out axcy[3], out axcy[2], out axcy[1], out axcy[0]);
axcy[7] = axcy7;
temp16len = EA.FastExpansionSumZeroElim(8, bxcy, 8, cxby, temp16);
xlen = EA.ScaleExpansionZeroElim(temp16len, temp16, adx, detx);
xxlen = EA.ScaleExpansionZeroElim(xlen, detx, adx, detxx);
xtlen = EA.ScaleExpansionZeroElim(temp16len, temp16, adxtail, detxt);
xxtlen = EA.ScaleExpansionZeroElim(xtlen, detxt, adx, detxxt);
for (i = 0; i < xxtlen; i++)
{
detxxt[i] *= 2.0;
}
xtxtlen = EA.ScaleExpansionZeroElim(xtlen, detxt, adxtail, detxtxt);
x1len = EA.FastExpansionSumZeroElim(xxlen, detxx, xxtlen, detxxt, x1);
x2len = EA.FastExpansionSumZeroElim(x1len, x1, xtxtlen, detxtxt, x2);
ylen = EA.ScaleExpansionZeroElim(temp16len, temp16, ady, dety);
yylen = EA.ScaleExpansionZeroElim(ylen, dety, ady, detyy);
ytlen = EA.ScaleExpansionZeroElim(temp16len, temp16, adytail, detyt);
yytlen = EA.ScaleExpansionZeroElim(ytlen, detyt, ady, detyyt);
for (i = 0; i < yytlen; i++)
{
detyyt[i] *= 2.0;
}
ytytlen = EA.ScaleExpansionZeroElim(ytlen, detyt, adytail, detytyt);
y1len = EA.FastExpansionSumZeroElim(yylen, detyy, yytlen, detyyt, y1);
y2len = EA.FastExpansionSumZeroElim(y1len, y1, ytytlen, detytyt, y2);
alen = EA.FastExpansionSumZeroElim(x2len, x2, y2len, y2, adet);
temp16len = EA.FastExpansionSumZeroElim(8, cxay, 8, axcy, temp16);
xlen = EA.ScaleExpansionZeroElim(temp16len, temp16, bdx, detx);
xxlen = EA.ScaleExpansionZeroElim(xlen, detx, bdx, detxx);
xtlen = EA.ScaleExpansionZeroElim(temp16len, temp16, bdxtail, detxt);
xxtlen = EA.ScaleExpansionZeroElim(xtlen, detxt, bdx, detxxt);
for (i = 0; i < xxtlen; i++)
{
detxxt[i] *= 2.0;
}
xtxtlen = EA.ScaleExpansionZeroElim(xtlen, detxt, bdxtail, detxtxt);
x1len = EA.FastExpansionSumZeroElim(xxlen, detxx, xxtlen, detxxt, x1);
x2len = EA.FastExpansionSumZeroElim(x1len, x1, xtxtlen, detxtxt, x2);
ylen = EA.ScaleExpansionZeroElim(temp16len, temp16, bdy, dety);
yylen = EA.ScaleExpansionZeroElim(ylen, dety, bdy, detyy);
ytlen = EA.ScaleExpansionZeroElim(temp16len, temp16, bdytail, detyt);
yytlen = EA.ScaleExpansionZeroElim(ytlen, detyt, bdy, detyyt);
for (i = 0; i < yytlen; i++)
{
detyyt[i] *= 2.0;
}
ytytlen = EA.ScaleExpansionZeroElim(ytlen, detyt, bdytail, detytyt);
y1len = EA.FastExpansionSumZeroElim(yylen, detyy, yytlen, detyyt, y1);
y2len = EA.FastExpansionSumZeroElim(y1len, y1, ytytlen, detytyt, y2);
blen = EA.FastExpansionSumZeroElim(x2len, x2, y2len, y2, bdet);
temp16len = EA.FastExpansionSumZeroElim(8, axby, 8, bxay, temp16);
xlen = EA.ScaleExpansionZeroElim(temp16len, temp16, cdx, detx);
xxlen = EA.ScaleExpansionZeroElim(xlen, detx, cdx, detxx);
xtlen = EA.ScaleExpansionZeroElim(temp16len, temp16, cdxtail, detxt);
xxtlen = EA.ScaleExpansionZeroElim(xtlen, detxt, cdx, detxxt);
for (i = 0; i < xxtlen; i++)
{
detxxt[i] *= 2.0;
}
xtxtlen = EA.ScaleExpansionZeroElim(xtlen, detxt, cdxtail, detxtxt);
x1len = EA.FastExpansionSumZeroElim(xxlen, detxx, xxtlen, detxxt, x1);
x2len = EA.FastExpansionSumZeroElim(x1len, x1, xtxtlen, detxtxt, x2);
ylen = EA.ScaleExpansionZeroElim(temp16len, temp16, cdy, dety);
yylen = EA.ScaleExpansionZeroElim(ylen, dety, cdy, detyy);
ytlen = EA.ScaleExpansionZeroElim(temp16len, temp16, cdytail, detyt);
yytlen = EA.ScaleExpansionZeroElim(ytlen, detyt, cdy, detyyt);
for (i = 0; i < yytlen; i++)
{
detyyt[i] *= 2.0;
}
ytytlen = EA.ScaleExpansionZeroElim(ytlen, detyt, cdytail, detytyt);
y1len = EA.FastExpansionSumZeroElim(yylen, detyy, yytlen, detyyt, y1);
y2len = EA.FastExpansionSumZeroElim(y1len, y1, ytytlen, detytyt, y2);
clen = EA.FastExpansionSumZeroElim(x2len, x2, y2len, y2, cdet);
ablen = EA.FastExpansionSumZeroElim(alen, adet, blen, bdet, abdet);
deterlen = EA.FastExpansionSumZeroElim(ablen, abdet, clen, cdet, deter);
// In S. predicates.c, this returns the largest component:
// deter[deterlen - 1];
// However, this is not stable due to the expansions not being unique (even for ZeroElim),
// So we return the summed estimate as the 'Exact' value.
return EA.Estimate(deterlen, deter);
}
public static double InCircle(double[] pa, double[] pb, double[] pc, double[] pd)
{
double adx, bdx, cdx, ady, bdy, cdy;
double bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady;
double alift, blift, clift;
double det;
double permanent, errbound;
adx = pa[0] - pd[0];
bdx = pb[0] - pd[0];
cdx = pc[0] - pd[0];
ady = pa[1] - pd[1];
bdy = pb[1] - pd[1];
cdy = pc[1] - pd[1];
bdxcdy = bdx * cdy;
cdxbdy = cdx * bdy;
alift = adx * adx + ady * ady;
cdxady = cdx * ady;
adxcdy = adx * cdy;
blift = bdx * bdx + bdy * bdy;
adxbdy = adx * bdy;
bdxady = bdx * ady;
clift = cdx * cdx + cdy * cdy;
det = alift * (bdxcdy - cdxbdy)
+ blift * (cdxady - adxcdy)
+ clift * (adxbdy - bdxady);
permanent = (Math.Abs(bdxcdy) + Math.Abs(cdxbdy)) * alift
+ (Math.Abs(cdxady) + Math.Abs(adxcdy)) * blift
+ (Math.Abs(adxbdy) + Math.Abs(bdxady)) * clift;
errbound = iccerrboundA * permanent;
if ((det > errbound) || (-det > errbound))
{
return det;
}
return InCircleAdapt(pa, pb, pc, pd, permanent);
}
// Adaptive continuation of InCircle
static double InCircleAdapt(double[] pa, double[] pb, double[] pc, double[] pd, double permanent)
{
double adx, bdx, cdx, ady, bdy, cdy;
double det, errbound;
double bdxcdy1, cdxbdy1, cdxady1, adxcdy1, adxbdy1, bdxady1;
double bdxcdy0, cdxbdy0, cdxady0, adxcdy0, adxbdy0, bdxady0;
double[] bc = new double[4];
double[] ca = new double[4];
double[] ab = new double[4];
double bc3, ca3, ab3;
double[] axbc = new double[8];
double[] axxbc = new double[16];
double[] aybc = new double[8];
double[] ayybc = new double[16];
double[] adet = new double[32];
int axbclen, axxbclen, aybclen, ayybclen, alen;
double[] bxca = new double[8];
double[] bxxca = new double[16];
double[] byca = new double[8];
double[] byyca = new double[16];
double[] bdet = new double[32];
int bxcalen, bxxcalen, bycalen, byycalen, blen;
double[] cxab = new double[8];
double[] cxxab = new double[16];
double[] cyab = new double[8];
double[] cyyab = new double[16];
double[] cdet = new double[32];
int cxablen, cxxablen, cyablen, cyyablen, clen;
double[] abdet = new double[64];
int ablen;
double[] fin1 = new double[1152];
double[] fin2 = new double[1152];
double[] finnow, finother, finswap;
int finlength;
double adxtail, bdxtail, cdxtail, adytail, bdytail, cdytail;
double adxadx1, adyady1, bdxbdx1, bdybdy1, cdxcdx1, cdycdy1;
double adxadx0, adyady0, bdxbdx0, bdybdy0, cdxcdx0, cdycdy0;
double[] aa = new double[4];
double[] bb = new double[4];
double[] cc = new double[4];
double aa3, bb3, cc3;
double ti1, tj1;
double ti0, tj0;
double[] u = new double[4];
double[] v = new double[4];
double u3, v3;
double[] temp8 = new double[8];
double[] temp16a = new double[16];
double[] temp16b = new double[16];
double[] temp16c = new double[16];
double[] temp32a = new double[32];
double[] temp32b = new double[32];
double[] temp48 = new double[48];
double[] temp64 = new double[64];
int temp8len, temp16alen, temp16blen, temp16clen;
int temp32alen, temp32blen, temp48len, temp64len;
double[] axtbb = new double[8];
double[] axtcc = new double[8];
double[] aytbb = new double[8];
double[] aytcc = new double[8];
int axtbblen, axtcclen, aytbblen, aytcclen;
double[] bxtaa = new double[8];
double[] bxtcc = new double[8];
double[] bytaa = new double[8];
double[] bytcc = new double[8];
int bxtaalen, bxtcclen, bytaalen, bytcclen;
double[] cxtaa = new double[8];
double[] cxtbb = new double[8];
double[] cytaa = new double[8];
double[] cytbb = new double[8];
int cxtaalen, cxtbblen, cytaalen, cytbblen;
double[] axtbc = new double[8];
double[] aytbc = new double[8];
double[] bxtca = new double[8];
double[] bytca = new double[8];
double[] cxtab = new double[8];
double[] cytab = new double[8];
int axtbclen, aytbclen, bxtcalen, bytcalen, cxtablen, cytablen;
double[] axtbct = new double[16];
double[] aytbct = new double[16];
double[] bxtcat = new double[16];
double[] bytcat = new double[16];
double[] cxtabt = new double[16];
double[] cytabt = new double[16];
int axtbctlen, aytbctlen, bxtcatlen, bytcatlen, cxtabtlen, cytabtlen;
double[] axtbctt = new double[8];
double[] aytbctt = new double[8];
double[] bxtcatt = new double[8];
double[] bytcatt = new double[8];
double[] cxtabtt = new double[8];
double[] cytabtt = new double[8];
int axtbcttlen, aytbcttlen, bxtcattlen, bytcattlen, cxtabttlen, cytabttlen;
double[] abt = new double[8];
double[] bct = new double[8];
double[] cat = new double[8];
int abtlen, bctlen, catlen;
double[] abtt = new double[4];
double[] bctt = new double[4];
double[] catt = new double[4];
int abttlen, bcttlen, cattlen;
double abtt3, bctt3, catt3;
double negate;
// RobustGeometry.NET - Additional initialization, for C# compiler,
// to a value that should cause an error if used by accident.
axtbclen = 9999;
aytbclen = 9999;
bxtcalen = 9999;
bytcalen = 9999;
cxtablen = 9999;
cytablen = 9999;
adx = pa[0] - pd[0];
bdx = pb[0] - pd[0];
cdx = pc[0] - pd[0];
ady = pa[1] - pd[1];
bdy = pb[1] - pd[1];
cdy = pc[1] - pd[1];
EA.TwoProduct(bdx, cdy, out bdxcdy1, out bdxcdy0);
EA.TwoProduct(cdx, bdy, out cdxbdy1, out cdxbdy0);
EA.TwoTwoDiff(bdxcdy1, bdxcdy0, cdxbdy1, cdxbdy0, out bc3, out bc[2], out bc[1], out bc[0]);
bc[3] = bc3;
axbclen = EA.ScaleExpansionZeroElim(4, bc, adx, axbc);
axxbclen = EA.ScaleExpansionZeroElim(axbclen, axbc, adx, axxbc);
aybclen = EA.ScaleExpansionZeroElim(4, bc, ady, aybc);
ayybclen = EA.ScaleExpansionZeroElim(aybclen, aybc, ady, ayybc);
alen = EA.FastExpansionSumZeroElim(axxbclen, axxbc, ayybclen, ayybc, adet);
EA.TwoProduct(cdx, ady, out cdxady1, out cdxady0);
EA.TwoProduct(adx, cdy, out adxcdy1, out adxcdy0);
EA.TwoTwoDiff(cdxady1, cdxady0, adxcdy1, adxcdy0, out ca3, out ca[2], out ca[1], out ca[0]);
ca[3] = ca3;
bxcalen = EA.ScaleExpansionZeroElim(4, ca, bdx, bxca);
bxxcalen = EA.ScaleExpansionZeroElim(bxcalen, bxca, bdx, bxxca);
bycalen = EA.ScaleExpansionZeroElim(4, ca, bdy, byca);
byycalen = EA.ScaleExpansionZeroElim(bycalen, byca, bdy, byyca);
blen = EA.FastExpansionSumZeroElim(bxxcalen, bxxca, byycalen, byyca, bdet);
EA.TwoProduct(adx, bdy, out adxbdy1, out adxbdy0);
EA.TwoProduct(bdx, ady, out bdxady1, out bdxady0);
EA.TwoTwoDiff(adxbdy1, adxbdy0, bdxady1, bdxady0, out ab3, out ab[2], out ab[1], out ab[0]);
ab[3] = ab3;
cxablen = EA.ScaleExpansionZeroElim(4, ab, cdx, cxab);
cxxablen = EA.ScaleExpansionZeroElim(cxablen, cxab, cdx, cxxab);
cyablen = EA.ScaleExpansionZeroElim(4, ab, cdy, cyab);
cyyablen = EA.ScaleExpansionZeroElim(cyablen, cyab, cdy, cyyab);
clen = EA.FastExpansionSumZeroElim(cxxablen, cxxab, cyyablen, cyyab, cdet);
ablen = EA.FastExpansionSumZeroElim(alen, adet, blen, bdet, abdet);
finlength = EA.FastExpansionSumZeroElim(ablen, abdet, clen, cdet, fin1);
det = EA.Estimate(finlength, fin1);
errbound = iccerrboundB * permanent;
if ((det >= errbound) || (-det >= errbound))
{
return det;
}
EA.TwoDiffTail(pa[0], pd[0], adx, out adxtail);
EA.TwoDiffTail(pa[1], pd[1], ady, out adytail);
EA.TwoDiffTail(pb[0], pd[0], bdx, out bdxtail);
EA.TwoDiffTail(pb[1], pd[1], bdy, out bdytail);
EA.TwoDiffTail(pc[0], pd[0], cdx, out cdxtail);
EA.TwoDiffTail(pc[1], pd[1], cdy, out cdytail);
if ((adxtail == 0.0) && (bdxtail == 0.0) && (cdxtail == 0.0)
&& (adytail == 0.0) && (bdytail == 0.0) && (cdytail == 0.0))
{
return det;
}
errbound = iccerrboundC * permanent + resulterrbound * Math.Abs(det);
det += ((adx * adx + ady * ady) * ((bdx * cdytail + cdy * bdxtail)
- (bdy * cdxtail + cdx * bdytail))
+ 2.0 * (adx * adxtail + ady * adytail) * (bdx * cdy - bdy * cdx))
+ ((bdx * bdx + bdy * bdy) * ((cdx * adytail + ady * cdxtail)
- (cdy * adxtail + adx * cdytail))
+ 2.0 * (bdx * bdxtail + bdy * bdytail) * (cdx * ady - cdy * adx))
+ ((cdx * cdx + cdy * cdy) * ((adx * bdytail + bdy * adxtail)
- (ady * bdxtail + bdx * adytail))
+ 2.0 * (cdx * cdxtail + cdy * cdytail) * (adx * bdy - ady * bdx));
if ((det >= errbound) || (-det >= errbound))
{
return det;
}
finnow = fin1;
finother = fin2;
if ((bdxtail != 0.0) || (bdytail != 0.0)
|| (cdxtail != 0.0) || (cdytail != 0.0))
{
EA.Square(adx, out adxadx1, out adxadx0);
EA.Square(ady, out adyady1, out adyady0);
EA.TwoTwoSum(adxadx1, adxadx0, adyady1, adyady0, out aa3, out aa[2], out aa[1], out aa[0]);
aa[3] = aa3;
}
if ((cdxtail != 0.0) || (cdytail != 0.0)
|| (adxtail != 0.0) || (adytail != 0.0))
{
EA.Square(bdx, out bdxbdx1, out bdxbdx0);
EA.Square(bdy, out bdybdy1, out bdybdy0);
EA.TwoTwoSum(bdxbdx1, bdxbdx0, bdybdy1, bdybdy0, out bb3, out bb[2], out bb[1], out bb[0]);
bb[3] = bb3;
}
if ((adxtail != 0.0) || (adytail != 0.0)
|| (bdxtail != 0.0) || (bdytail != 0.0))
{
EA.Square(cdx, out cdxcdx1, out cdxcdx0);
EA.Square(cdy, out cdycdy1, out cdycdy0);
EA.TwoTwoSum(cdxcdx1, cdxcdx0, cdycdy1, cdycdy0, out cc3, out cc[2], out cc[1], out cc[0]);
cc[3] = cc3;
}
if (adxtail != 0.0)
{
axtbclen = EA.ScaleExpansionZeroElim(4, bc, adxtail, axtbc);
temp16alen = EA.ScaleExpansionZeroElim(axtbclen, axtbc, 2.0 * adx, temp16a);
axtcclen = EA.ScaleExpansionZeroElim(4, cc, adxtail, axtcc);
temp16blen = EA.ScaleExpansionZeroElim(axtcclen, axtcc, bdy, temp16b);
axtbblen = EA.ScaleExpansionZeroElim(4, bb, adxtail, axtbb);
temp16clen = EA.ScaleExpansionZeroElim(axtbblen, axtbb, -cdy, temp16c);
temp32alen = EA.FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32a);
temp48len = EA.FastExpansionSumZeroElim(temp16clen, temp16c, temp32alen, temp32a, temp48);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
if (adytail != 0.0)
{
aytbclen = EA.ScaleExpansionZeroElim(4, bc, adytail, aytbc);
temp16alen = EA.ScaleExpansionZeroElim(aytbclen, aytbc, 2.0 * ady, temp16a);
aytbblen = EA.ScaleExpansionZeroElim(4, bb, adytail, aytbb);
temp16blen = EA.ScaleExpansionZeroElim(aytbblen, aytbb, cdx, temp16b);
aytcclen = EA.ScaleExpansionZeroElim(4, cc, adytail, aytcc);
temp16clen = EA.ScaleExpansionZeroElim(aytcclen, aytcc, -bdx, temp16c);
temp32alen = EA.FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32a);
temp48len = EA.FastExpansionSumZeroElim(temp16clen, temp16c, temp32alen, temp32a, temp48);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
if (bdxtail != 0.0)
{
bxtcalen = EA.ScaleExpansionZeroElim(4, ca, bdxtail, bxtca);
temp16alen = EA.ScaleExpansionZeroElim(bxtcalen, bxtca, 2.0 * bdx, temp16a);
bxtaalen = EA.ScaleExpansionZeroElim(4, aa, bdxtail, bxtaa);
temp16blen = EA.ScaleExpansionZeroElim(bxtaalen, bxtaa, cdy, temp16b);
bxtcclen = EA.ScaleExpansionZeroElim(4, cc, bdxtail, bxtcc);
temp16clen = EA.ScaleExpansionZeroElim(bxtcclen, bxtcc, -ady, temp16c);
temp32alen = EA.FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32a);
temp48len = EA.FastExpansionSumZeroElim(temp16clen, temp16c, temp32alen, temp32a, temp48);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
if (bdytail != 0.0)
{
bytcalen = EA.ScaleExpansionZeroElim(4, ca, bdytail, bytca);
temp16alen = EA.ScaleExpansionZeroElim(bytcalen, bytca, 2.0 * bdy, temp16a);
bytcclen = EA.ScaleExpansionZeroElim(4, cc, bdytail, bytcc);
temp16blen = EA.ScaleExpansionZeroElim(bytcclen, bytcc, adx, temp16b);
bytaalen = EA.ScaleExpansionZeroElim(4, aa, bdytail, bytaa);
temp16clen = EA.ScaleExpansionZeroElim(bytaalen, bytaa, -cdx, temp16c);
temp32alen = EA.FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32a);
temp48len = EA.FastExpansionSumZeroElim(temp16clen, temp16c, temp32alen, temp32a, temp48);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
if (cdxtail != 0.0)
{
cxtablen = EA.ScaleExpansionZeroElim(4, ab, cdxtail, cxtab);
temp16alen = EA.ScaleExpansionZeroElim(cxtablen, cxtab, 2.0 * cdx, temp16a);
cxtbblen = EA.ScaleExpansionZeroElim(4, bb, cdxtail, cxtbb);
temp16blen = EA.ScaleExpansionZeroElim(cxtbblen, cxtbb, ady, temp16b);
cxtaalen = EA.ScaleExpansionZeroElim(4, aa, cdxtail, cxtaa);
temp16clen = EA.ScaleExpansionZeroElim(cxtaalen, cxtaa, -bdy, temp16c);
temp32alen = EA.FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32a);
temp48len = EA.FastExpansionSumZeroElim(temp16clen, temp16c, temp32alen, temp32a, temp48);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
if (cdytail != 0.0)
{
cytablen = EA.ScaleExpansionZeroElim(4, ab, cdytail, cytab);
temp16alen = EA.ScaleExpansionZeroElim(cytablen, cytab, 2.0 * cdy, temp16a);
cytaalen = EA.ScaleExpansionZeroElim(4, aa, cdytail, cytaa);
temp16blen = EA.ScaleExpansionZeroElim(cytaalen, cytaa, bdx, temp16b);
cytbblen = EA.ScaleExpansionZeroElim(4, bb, cdytail, cytbb);
temp16clen = EA.ScaleExpansionZeroElim(cytbblen, cytbb, -adx, temp16c);
temp32alen = EA.FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32a);
temp48len = EA.FastExpansionSumZeroElim(temp16clen, temp16c, temp32alen, temp32a, temp48);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
if ((adxtail != 0.0) || (adytail != 0.0))
{
if ((bdxtail != 0.0) || (bdytail != 0.0)
|| (cdxtail != 0.0) || (cdytail != 0.0))
{
EA.TwoProduct(bdxtail, cdy, out ti1, out ti0);
EA.TwoProduct(bdx, cdytail, out tj1, out tj0);
EA.TwoTwoSum(ti1, ti0, tj1, tj0, out u3, out u[2], out u[1], out u[0]);
u[3] = u3;
negate = -bdy;
EA.TwoProduct(cdxtail, negate, out ti1, out ti0);
negate = -bdytail;
EA.TwoProduct(cdx, negate, out tj1, out tj0);
EA.TwoTwoSum(ti1, ti0, tj1, tj0, out v3, out v[2], out v[1], out v[0]);
v[3] = v3;
bctlen = EA.FastExpansionSumZeroElim(4, u, 4, v, bct);
EA.TwoProduct(bdxtail, cdytail, out ti1, out ti0);
EA.TwoProduct(cdxtail, bdytail, out tj1, out tj0);
EA.TwoTwoDiff(ti1, ti0, tj1, tj0, out bctt3, out bctt[2], out bctt[1], out bctt[0]);
bctt[3] = bctt3;
bcttlen = 4;
}
else
{
bct[0] = 0.0;
bctlen = 1;
bctt[0] = 0.0;
bcttlen = 1;
}
if (adxtail != 0.0)
{
temp16alen = EA.ScaleExpansionZeroElim(axtbclen, axtbc, adxtail, temp16a);
axtbctlen = EA.ScaleExpansionZeroElim(bctlen, bct, adxtail, axtbct);
temp32alen = EA.ScaleExpansionZeroElim(axtbctlen, axtbct, 2.0 * adx, temp32a);
temp48len = EA.FastExpansionSumZeroElim(temp16alen, temp16a, temp32alen, temp32a, temp48);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother);
finswap = finnow; finnow = finother; finother = finswap;
if (bdytail != 0.0)
{
temp8len = EA.ScaleExpansionZeroElim(4, cc, adxtail, temp8);
temp16alen = EA.ScaleExpansionZeroElim(temp8len, temp8, bdytail, temp16a);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp16alen, temp16a, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
if (cdytail != 0.0)
{
temp8len = EA.ScaleExpansionZeroElim(4, bb, -adxtail, temp8);
temp16alen = EA.ScaleExpansionZeroElim(temp8len, temp8, cdytail, temp16a);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp16alen, temp16a, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
temp32alen = EA.ScaleExpansionZeroElim(axtbctlen, axtbct, adxtail, temp32a);
axtbcttlen = EA.ScaleExpansionZeroElim(bcttlen, bctt, adxtail, axtbctt);
temp16alen = EA.ScaleExpansionZeroElim(axtbcttlen, axtbctt, 2.0 * adx, temp16a);
temp16blen = EA.ScaleExpansionZeroElim(axtbcttlen, axtbctt, adxtail, temp16b);
temp32blen = EA.FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32b);
temp64len = EA.FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp64len, temp64, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
if (adytail != 0.0)
{
temp16alen = EA.ScaleExpansionZeroElim(aytbclen, aytbc, adytail, temp16a);
aytbctlen = EA.ScaleExpansionZeroElim(bctlen, bct, adytail, aytbct);
temp32alen = EA.ScaleExpansionZeroElim(aytbctlen, aytbct, 2.0 * ady, temp32a);
temp48len = EA.FastExpansionSumZeroElim(temp16alen, temp16a, temp32alen, temp32a, temp48);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother);
finswap = finnow; finnow = finother; finother = finswap;
temp32alen = EA.ScaleExpansionZeroElim(aytbctlen, aytbct, adytail, temp32a);
aytbcttlen = EA.ScaleExpansionZeroElim(bcttlen, bctt, adytail, aytbctt);
temp16alen = EA.ScaleExpansionZeroElim(aytbcttlen, aytbctt, 2.0 * ady, temp16a);
temp16blen = EA.ScaleExpansionZeroElim(aytbcttlen, aytbctt, adytail, temp16b);
temp32blen = EA.FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32b);
temp64len = EA.FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp64len, temp64, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
}
if ((bdxtail != 0.0) || (bdytail != 0.0))
{
if ((cdxtail != 0.0) || (cdytail != 0.0)
|| (adxtail != 0.0) || (adytail != 0.0))
{
EA.TwoProduct(cdxtail, ady, out ti1, out ti0);
EA.TwoProduct(cdx, adytail, out tj1, out tj0);
EA.TwoTwoSum(ti1, ti0, tj1, tj0, out u3, out u[2], out u[1], out u[0]);
u[3] = u3;
negate = -cdy;
EA.TwoProduct(adxtail, negate, out ti1, out ti0);
negate = -cdytail;
EA.TwoProduct(adx, negate, out tj1, out tj0);
EA.TwoTwoSum(ti1, ti0, tj1, tj0, out v3, out v[2], out v[1], out v[0]);
v[3] = v3;
catlen = EA.FastExpansionSumZeroElim(4, u, 4, v, cat);
EA.TwoProduct(cdxtail, adytail, out ti1, out ti0);
EA.TwoProduct(adxtail, cdytail, out tj1, out tj0);
EA.TwoTwoDiff(ti1, ti0, tj1, tj0, out catt3, out catt[2], out catt[1], out catt[0]);
catt[3] = catt3;
cattlen = 4;
}
else
{
cat[0] = 0.0;
catlen = 1;
catt[0] = 0.0;
cattlen = 1;
}
if (bdxtail != 0.0)
{
temp16alen = EA.ScaleExpansionZeroElim(bxtcalen, bxtca, bdxtail, temp16a);
bxtcatlen = EA.ScaleExpansionZeroElim(catlen, cat, bdxtail, bxtcat);
temp32alen = EA.ScaleExpansionZeroElim(bxtcatlen, bxtcat, 2.0 * bdx, temp32a);
temp48len = EA.FastExpansionSumZeroElim(temp16alen, temp16a, temp32alen, temp32a, temp48);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother);
finswap = finnow; finnow = finother; finother = finswap;
if (cdytail != 0.0)
{
temp8len = EA.ScaleExpansionZeroElim(4, aa, bdxtail, temp8);
temp16alen = EA.ScaleExpansionZeroElim(temp8len, temp8, cdytail, temp16a);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp16alen, temp16a, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
if (adytail != 0.0)
{
temp8len = EA.ScaleExpansionZeroElim(4, cc, -bdxtail, temp8);
temp16alen = EA.ScaleExpansionZeroElim(temp8len, temp8, adytail, temp16a);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp16alen, temp16a, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
temp32alen = EA.ScaleExpansionZeroElim(bxtcatlen, bxtcat, bdxtail, temp32a);
bxtcattlen = EA.ScaleExpansionZeroElim(cattlen, catt, bdxtail, bxtcatt);
temp16alen = EA.ScaleExpansionZeroElim(bxtcattlen, bxtcatt, 2.0 * bdx, temp16a);
temp16blen = EA.ScaleExpansionZeroElim(bxtcattlen, bxtcatt, bdxtail, temp16b);
temp32blen = EA.FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32b);
temp64len = EA.FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp64len, temp64, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
if (bdytail != 0.0)
{
temp16alen = EA.ScaleExpansionZeroElim(bytcalen, bytca, bdytail, temp16a);
bytcatlen = EA.ScaleExpansionZeroElim(catlen, cat, bdytail, bytcat);
temp32alen = EA.ScaleExpansionZeroElim(bytcatlen, bytcat, 2.0 * bdy, temp32a);
temp48len = EA.FastExpansionSumZeroElim(temp16alen, temp16a, temp32alen, temp32a, temp48);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother);
finswap = finnow; finnow = finother; finother = finswap;
temp32alen = EA.ScaleExpansionZeroElim(bytcatlen, bytcat, bdytail, temp32a);
bytcattlen = EA.ScaleExpansionZeroElim(cattlen, catt, bdytail, bytcatt);
temp16alen = EA.ScaleExpansionZeroElim(bytcattlen, bytcatt, 2.0 * bdy, temp16a);
temp16blen = EA.ScaleExpansionZeroElim(bytcattlen, bytcatt, bdytail, temp16b);
temp32blen = EA.FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32b);
temp64len = EA.FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp64len, temp64, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
}
if ((cdxtail != 0.0) || (cdytail != 0.0))
{
if ((adxtail != 0.0) || (adytail != 0.0)
|| (bdxtail != 0.0) || (bdytail != 0.0))
{
EA.TwoProduct(adxtail, bdy, out ti1, out ti0);
EA.TwoProduct(adx, bdytail, out tj1, out tj0);
EA.TwoTwoSum(ti1, ti0, tj1, tj0, out u3, out u[2], out u[1], out u[0]);
u[3] = u3;
negate = -ady;
EA.TwoProduct(bdxtail, negate, out ti1, out ti0);
negate = -adytail;
EA.TwoProduct(bdx, negate, out tj1, out tj0);
EA.TwoTwoSum(ti1, ti0, tj1, tj0, out v3, out v[2], out v[1], out v[0]);
v[3] = v3;
abtlen = EA.FastExpansionSumZeroElim(4, u, 4, v, abt);
EA.TwoProduct(adxtail, bdytail, out ti1, out ti0);
EA.TwoProduct(bdxtail, adytail, out tj1, out tj0);
EA.TwoTwoDiff(ti1, ti0, tj1, tj0, out abtt3, out abtt[2], out abtt[1], out abtt[0]);
abtt[3] = abtt3;
abttlen = 4;
}
else
{
abt[0] = 0.0;
abtlen = 1;
abtt[0] = 0.0;
abttlen = 1;
}
if (cdxtail != 0.0)
{
temp16alen = EA.ScaleExpansionZeroElim(cxtablen, cxtab, cdxtail, temp16a);
cxtabtlen = EA.ScaleExpansionZeroElim(abtlen, abt, cdxtail, cxtabt);
temp32alen = EA.ScaleExpansionZeroElim(cxtabtlen, cxtabt, 2.0 * cdx, temp32a);
temp48len = EA.FastExpansionSumZeroElim(temp16alen, temp16a, temp32alen, temp32a, temp48);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother);
finswap = finnow; finnow = finother; finother = finswap;
if (adytail != 0.0)
{
temp8len = EA.ScaleExpansionZeroElim(4, bb, cdxtail, temp8);
temp16alen = EA.ScaleExpansionZeroElim(temp8len, temp8, adytail, temp16a);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp16alen, temp16a, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
if (bdytail != 0.0)
{
temp8len = EA.ScaleExpansionZeroElim(4, aa, -cdxtail, temp8);
temp16alen = EA.ScaleExpansionZeroElim(temp8len, temp8, bdytail, temp16a);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp16alen, temp16a, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
temp32alen = EA.ScaleExpansionZeroElim(cxtabtlen, cxtabt, cdxtail, temp32a);
cxtabttlen = EA.ScaleExpansionZeroElim(abttlen, abtt, cdxtail, cxtabtt);
temp16alen = EA.ScaleExpansionZeroElim(cxtabttlen, cxtabtt, 2.0 * cdx, temp16a);
temp16blen = EA.ScaleExpansionZeroElim(cxtabttlen, cxtabtt, cdxtail, temp16b);
temp32blen = EA.FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32b);
temp64len = EA.FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp64len, temp64, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
if (cdytail != 0.0)
{
temp16alen = EA.ScaleExpansionZeroElim(cytablen, cytab, cdytail, temp16a);
cytabtlen = EA.ScaleExpansionZeroElim(abtlen, abt, cdytail, cytabt);
temp32alen = EA.ScaleExpansionZeroElim(cytabtlen, cytabt, 2.0 * cdy, temp32a);
temp48len = EA.FastExpansionSumZeroElim(temp16alen, temp16a, temp32alen, temp32a, temp48);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother);
finswap = finnow; finnow = finother; finother = finswap;
temp32alen = EA.ScaleExpansionZeroElim(cytabtlen, cytabt, cdytail, temp32a);
cytabttlen = EA.ScaleExpansionZeroElim(abttlen, abtt, cdytail, cytabtt);
temp16alen = EA.ScaleExpansionZeroElim(cytabttlen, cytabtt, 2.0 * cdy, temp16a);
temp16blen = EA.ScaleExpansionZeroElim(cytabttlen, cytabtt, cdytail, temp16b);
temp32blen = EA.FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32b);
temp64len = EA.FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64);
finlength = EA.FastExpansionSumZeroElim(finlength, finnow, temp64len, temp64, finother);
finswap = finnow; finnow = finother; finother = finswap;
}
}
return finnow[finlength - 1];
}
#endregion
#region InSphere
/*****************************************************************************/
/* */
/* inspherefast() Approximate 3D insphere test. Nonrobust. */
/* insphereexact() Exact 3D insphere test. Robust. */
/* insphereslow() Another exact 3D insphere test. Robust. */
/* insphere() Adaptive exact 3D insphere test. Robust. */
/* */
/* Return a positive value if the point pe lies inside the */
/* sphere passing through pa, pb, pc, and pd; a negative value */
/* if it lies outside; and zero if the five points are */
/* cospherical. The points pa, pb, pc, and pd must be ordered */
/* so that they have a positive orientation (as defined by */
/* orient3d()), or the sign of the result will be reversed. */
/* */
/* Only the first and last routine should be used; the middle two are for */
/* timings. */
/* */
/* The last three use exact arithmetic to ensure a correct answer. The */
/* result returned is the determinant of a matrix. In insphere() only, */
/* this determinant is computed adaptively, in the sense that exact */
/* arithmetic is used only to the degree it is needed to ensure that the */
/* returned value has the correct sign. Hence, insphere() is usually quite */
/* fast, but will run more slowly when the input points are cospherical or */
/* nearly so. */
/* */
/*****************************************************************************/
public static double InSphereFast(double[] pa, double[] pb, double[] pc, double[] pd, double[] pe)
{
double aex, bex, cex, dex;
double aey, bey, cey, dey;
double aez, bez, cez, dez;
double alift, blift, clift, dlift;
double ab, bc, cd, da, ac, bd;
double abc, bcd, cda, dab;
aex = pa[0] - pe[0];
bex = pb[0] - pe[0];
cex = pc[0] - pe[0];
dex = pd[0] - pe[0];
aey = pa[1] - pe[1];
bey = pb[1] - pe[1];
cey = pc[1] - pe[1];
dey = pd[1] - pe[1];
aez = pa[2] - pe[2];
bez = pb[2] - pe[2];
cez = pc[2] - pe[2];
dez = pd[2] - pe[2];
ab = aex * bey - bex * aey;
bc = bex * cey - cex * bey;
cd = cex * dey - dex * cey;
da = dex * aey - aex * dey;
ac = aex * cey - cex * aey;
bd = bex * dey - dex * bey;
abc = aez * bc - bez * ac + cez * ab;
bcd = bez * cd - cez * bd + dez * bc;
cda = cez * da + dez * ac + aez * cd;
dab = dez * ab + aez * bd + bez * da;
alift = aex * aex + aey * aey + aez * aez;
blift = bex * bex + bey * bey + bez * bez;
clift = cex * cex + cey * cey + cez * cez;
dlift = dex * dex + dey * dey + dez * dez;
return (dlift * abc - clift * dab) + (blift * cda - alift * bcd);
}
internal static double InSphereExact(double[] pa, double[] pb, double[] pc, double[] pd, double[] pe)
{
double axby1, bxcy1, cxdy1, dxey1, exay1;
double bxay1, cxby1, dxcy1, exdy1, axey1;
double axcy1, bxdy1, cxey1, dxay1, exby1;
double cxay1, dxby1, excy1, axdy1, bxey1;
double axby0, bxcy0, cxdy0, dxey0, exay0;
double bxay0, cxby0, dxcy0, exdy0, axey0;
double axcy0, bxdy0, cxey0, dxay0, exby0;
double cxay0, dxby0, excy0, axdy0, bxey0;
double[] ab = new double[4];
double[] bc = new double[4];
double[] cd = new double[4];
double[] de = new double[4];
double[] ea = new double[4];
double[] ac = new double[4];
double[] bd = new double[4];
double[] ce = new double[4];
double[] da = new double[4];
double[] eb = new double[4];
double[] temp8a = new double[8];
double[] temp8b = new double[8];
double[] temp16 = new double[16];
int temp8alen, temp8blen, temp16len;
double[] abc = new double[24];
double[] bcd = new double[24];
double[] cde = new double[24];
double[] dea = new double[24];
double[] eab = new double[24];
double[] abd = new double[24];
double[] bce = new double[24];
double[] cda = new double[24];
double[] deb = new double[24];
double[] eac = new double[24];
int abclen, bcdlen, cdelen, dealen, eablen;
int abdlen, bcelen, cdalen, deblen, eaclen;
double[] temp48a = new double[48];
double[] temp48b = new double[48];
int temp48alen, temp48blen;
double[] abcd = new double[96];
double[] bcde = new double[96];
double[] cdea = new double[96];
double[] deab = new double[96];
double[] eabc = new double[96];
int abcdlen, bcdelen, cdealen, deablen, eabclen;
double[] temp192 = new double[192];
double[] det384x = new double[384];
double[] det384y = new double[384];
double[] det384z = new double[384];
int xlen, ylen, zlen;
double[] detxy = new double[768];
int xylen;
double[] adet = new double[1152];
double[] bdet = new double[1152];
double[] cdet = new double[1152];
double[] ddet = new double[1152];
double[] edet = new double[1152];
int alen, blen, clen, dlen, elen;
double[] abdet = new double[2304];
double[] cddet = new double[2304];
double[] cdedet = new double[3456];
int ablen, cdlen;
double[] deter = new double[5760];
int deterlen;
int i;
EA.TwoProduct(pa[0], pb[1], out axby1, out axby0);
EA.TwoProduct(pb[0], pa[1], out bxay1, out bxay0);
EA.TwoTwoDiff(axby1, axby0, bxay1, bxay0, out ab[3], out ab[2], out ab[1], out ab[0]);
EA.TwoProduct(pb[0], pc[1], out bxcy1, out bxcy0);
EA.TwoProduct(pc[0], pb[1], out cxby1, out cxby0);
EA.TwoTwoDiff(bxcy1, bxcy0, cxby1, cxby0, out bc[3], out bc[2], out bc[1], out bc[0]);
EA.TwoProduct(pc[0], pd[1], out cxdy1, out cxdy0);
EA.TwoProduct(pd[0], pc[1], out dxcy1, out dxcy0);
EA.TwoTwoDiff(cxdy1, cxdy0, dxcy1, dxcy0, out cd[3], out cd[2], out cd[1], out cd[0]);
EA.TwoProduct(pd[0], pe[1], out dxey1, out dxey0);
EA.TwoProduct(pe[0], pd[1], out exdy1, out exdy0);
EA.TwoTwoDiff(dxey1, dxey0, exdy1, exdy0, out de[3], out de[2], out de[1], out de[0]);
EA.TwoProduct(pe[0], pa[1], out exay1, out exay0);
EA.TwoProduct(pa[0], pe[1], out axey1, out axey0);
EA.TwoTwoDiff(exay1, exay0, axey1, axey0, out ea[3], out ea[2], out ea[1], out ea[0]);
EA.TwoProduct(pa[0], pc[1], out axcy1, out axcy0);
EA.TwoProduct(pc[0], pa[1], out cxay1, out cxay0);
EA.TwoTwoDiff(axcy1, axcy0, cxay1, cxay0, out ac[3], out ac[2], out ac[1], out ac[0]);
EA.TwoProduct(pb[0], pd[1], out bxdy1, out bxdy0);
EA.TwoProduct(pd[0], pb[1], out dxby1, out dxby0);
EA.TwoTwoDiff(bxdy1, bxdy0, dxby1, dxby0, out bd[3], out bd[2], out bd[1], out bd[0]);
EA.TwoProduct(pc[0], pe[1], out cxey1, out cxey0);
EA.TwoProduct(pe[0], pc[1], out excy1, out excy0);
EA.TwoTwoDiff(cxey1, cxey0, excy1, excy0, out ce[3], out ce[2], out ce[1], out ce[0]);
EA.TwoProduct(pd[0], pa[1], out dxay1, out dxay0);
EA.TwoProduct(pa[0], pd[1], out axdy1, out axdy0);
EA.TwoTwoDiff(dxay1, dxay0, axdy1, axdy0, out da[3], out da[2], out da[1], out da[0]);
EA.TwoProduct(pe[0], pb[1], out exby1, out exby0);
EA.TwoProduct(pb[0], pe[1], out bxey1, out bxey0);
EA.TwoTwoDiff(exby1, exby0, bxey1, bxey0, out eb[3], out eb[2], out eb[1], out eb[0]);
temp8alen = EA.ScaleExpansionZeroElim(4, bc, pa[2], temp8a);
temp8blen = EA.ScaleExpansionZeroElim(4, ac, -pb[2], temp8b);
temp16len = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp8blen, temp8b, temp16);
temp8alen = EA.ScaleExpansionZeroElim(4, ab, pc[2], temp8a);
abclen = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp16len, temp16, abc);
temp8alen = EA.ScaleExpansionZeroElim(4, cd, pb[2], temp8a);
temp8blen = EA.ScaleExpansionZeroElim(4, bd, -pc[2], temp8b);
temp16len = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp8blen, temp8b, temp16);
temp8alen = EA.ScaleExpansionZeroElim(4, bc, pd[2], temp8a);
bcdlen = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp16len, temp16, bcd);
temp8alen = EA.ScaleExpansionZeroElim(4, de, pc[2], temp8a);
temp8blen = EA.ScaleExpansionZeroElim(4, ce, -pd[2], temp8b);
temp16len = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp8blen, temp8b, temp16);
temp8alen = EA.ScaleExpansionZeroElim(4, cd, pe[2], temp8a);
cdelen = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp16len, temp16, cde);
temp8alen = EA.ScaleExpansionZeroElim(4, ea, pd[2], temp8a);
temp8blen = EA.ScaleExpansionZeroElim(4, da, -pe[2], temp8b);
temp16len = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp8blen, temp8b, temp16);
temp8alen = EA.ScaleExpansionZeroElim(4, de, pa[2], temp8a);
dealen = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp16len, temp16, dea);
temp8alen = EA.ScaleExpansionZeroElim(4, ab, pe[2], temp8a);
temp8blen = EA.ScaleExpansionZeroElim(4, eb, -pa[2], temp8b);
temp16len = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp8blen, temp8b, temp16);
temp8alen = EA.ScaleExpansionZeroElim(4, ea, pb[2], temp8a);
eablen = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp16len, temp16, eab);
temp8alen = EA.ScaleExpansionZeroElim(4, bd, pa[2], temp8a);
temp8blen = EA.ScaleExpansionZeroElim(4, da, pb[2], temp8b);
temp16len = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp8blen, temp8b, temp16);
temp8alen = EA.ScaleExpansionZeroElim(4, ab, pd[2], temp8a);
abdlen = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp16len, temp16, abd);
temp8alen = EA.ScaleExpansionZeroElim(4, ce, pb[2], temp8a);
temp8blen = EA.ScaleExpansionZeroElim(4, eb, pc[2], temp8b);
temp16len = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp8blen, temp8b, temp16);
temp8alen = EA.ScaleExpansionZeroElim(4, bc, pe[2], temp8a);
bcelen = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp16len, temp16, bce);
temp8alen = EA.ScaleExpansionZeroElim(4, da, pc[2], temp8a);
temp8blen = EA.ScaleExpansionZeroElim(4, ac, pd[2], temp8b);
temp16len = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp8blen, temp8b, temp16);
temp8alen = EA.ScaleExpansionZeroElim(4, cd, pa[2], temp8a);
cdalen = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp16len, temp16, cda);
temp8alen = EA.ScaleExpansionZeroElim(4, eb, pd[2], temp8a);
temp8blen = EA.ScaleExpansionZeroElim(4, bd, pe[2], temp8b);
temp16len = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp8blen, temp8b, temp16);
temp8alen = EA.ScaleExpansionZeroElim(4, de, pb[2], temp8a);
deblen = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp16len, temp16, deb);
temp8alen = EA.ScaleExpansionZeroElim(4, ac, pe[2], temp8a);
temp8blen = EA.ScaleExpansionZeroElim(4, ce, pa[2], temp8b);
temp16len = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp8blen, temp8b, temp16);
temp8alen = EA.ScaleExpansionZeroElim(4, ea, pc[2], temp8a);
eaclen = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp16len, temp16, eac);
temp48alen = EA.FastExpansionSumZeroElim(cdelen, cde, bcelen, bce, temp48a);
temp48blen = EA.FastExpansionSumZeroElim(deblen, deb, bcdlen, bcd, temp48b);
for (i = 0; i < temp48blen; i++)
{
temp48b[i] = -temp48b[i];
}
bcdelen = EA.FastExpansionSumZeroElim(temp48alen, temp48a, temp48blen, temp48b, bcde);
xlen = EA.ScaleExpansionZeroElim(bcdelen, bcde, pa[0], temp192);
xlen = EA.ScaleExpansionZeroElim(xlen, temp192, pa[0], det384x);
ylen = EA.ScaleExpansionZeroElim(bcdelen, bcde, pa[1], temp192);
ylen = EA.ScaleExpansionZeroElim(ylen, temp192, pa[1], det384y);
zlen = EA.ScaleExpansionZeroElim(bcdelen, bcde, pa[2], temp192);
zlen = EA.ScaleExpansionZeroElim(zlen, temp192, pa[2], det384z);
xylen = EA.FastExpansionSumZeroElim(xlen, det384x, ylen, det384y, detxy);
alen = EA.FastExpansionSumZeroElim(xylen, detxy, zlen, det384z, adet);
temp48alen = EA.FastExpansionSumZeroElim(dealen, dea, cdalen, cda, temp48a);
temp48blen = EA.FastExpansionSumZeroElim(eaclen, eac, cdelen, cde, temp48b);
for (i = 0; i < temp48blen; i++)
{
temp48b[i] = -temp48b[i];
}
cdealen = EA.FastExpansionSumZeroElim(temp48alen, temp48a, temp48blen, temp48b, cdea);
xlen = EA.ScaleExpansionZeroElim(cdealen, cdea, pb[0], temp192);
xlen = EA.ScaleExpansionZeroElim(xlen, temp192, pb[0], det384x);
ylen = EA.ScaleExpansionZeroElim(cdealen, cdea, pb[1], temp192);
ylen = EA.ScaleExpansionZeroElim(ylen, temp192, pb[1], det384y);
zlen = EA.ScaleExpansionZeroElim(cdealen, cdea, pb[2], temp192);
zlen = EA.ScaleExpansionZeroElim(zlen, temp192, pb[2], det384z);
xylen = EA.FastExpansionSumZeroElim(xlen, det384x, ylen, det384y, detxy);
blen = EA.FastExpansionSumZeroElim(xylen, detxy, zlen, det384z, bdet);
temp48alen = EA.FastExpansionSumZeroElim(eablen, eab, deblen, deb, temp48a);
temp48blen = EA.FastExpansionSumZeroElim(abdlen, abd, dealen, dea, temp48b);
for (i = 0; i < temp48blen; i++)
{
temp48b[i] = -temp48b[i];
}
deablen = EA.FastExpansionSumZeroElim(temp48alen, temp48a, temp48blen, temp48b, deab);
xlen = EA.ScaleExpansionZeroElim(deablen, deab, pc[0], temp192);
xlen = EA.ScaleExpansionZeroElim(xlen, temp192, pc[0], det384x);
ylen = EA.ScaleExpansionZeroElim(deablen, deab, pc[1], temp192);
ylen = EA.ScaleExpansionZeroElim(ylen, temp192, pc[1], det384y);
zlen = EA.ScaleExpansionZeroElim(deablen, deab, pc[2], temp192);
zlen = EA.ScaleExpansionZeroElim(zlen, temp192, pc[2], det384z);
xylen = EA.FastExpansionSumZeroElim(xlen, det384x, ylen, det384y, detxy);
clen = EA.FastExpansionSumZeroElim(xylen, detxy, zlen, det384z, cdet);
temp48alen = EA.FastExpansionSumZeroElim(abclen, abc, eaclen, eac, temp48a);
temp48blen = EA.FastExpansionSumZeroElim(bcelen, bce, eablen, eab, temp48b);
for (i = 0; i < temp48blen; i++)
{
temp48b[i] = -temp48b[i];
}
eabclen = EA.FastExpansionSumZeroElim(temp48alen, temp48a, temp48blen, temp48b, eabc);
xlen = EA.ScaleExpansionZeroElim(eabclen, eabc, pd[0], temp192);
xlen = EA.ScaleExpansionZeroElim(xlen, temp192, pd[0], det384x);
ylen = EA.ScaleExpansionZeroElim(eabclen, eabc, pd[1], temp192);
ylen = EA.ScaleExpansionZeroElim(ylen, temp192, pd[1], det384y);
zlen = EA.ScaleExpansionZeroElim(eabclen, eabc, pd[2], temp192);
zlen = EA.ScaleExpansionZeroElim(zlen, temp192, pd[2], det384z);
xylen = EA.FastExpansionSumZeroElim(xlen, det384x, ylen, det384y, detxy);
dlen = EA.FastExpansionSumZeroElim(xylen, detxy, zlen, det384z, ddet);
temp48alen = EA.FastExpansionSumZeroElim(bcdlen, bcd, abdlen, abd, temp48a);
temp48blen = EA.FastExpansionSumZeroElim(cdalen, cda, abclen, abc, temp48b);
for (i = 0; i < temp48blen; i++)
{
temp48b[i] = -temp48b[i];
}
abcdlen = EA.FastExpansionSumZeroElim(temp48alen, temp48a, temp48blen, temp48b, abcd);
xlen = EA.ScaleExpansionZeroElim(abcdlen, abcd, pe[0], temp192);
xlen = EA.ScaleExpansionZeroElim(xlen, temp192, pe[0], det384x);
ylen = EA.ScaleExpansionZeroElim(abcdlen, abcd, pe[1], temp192);
ylen = EA.ScaleExpansionZeroElim(ylen, temp192, pe[1], det384y);
zlen = EA.ScaleExpansionZeroElim(abcdlen, abcd, pe[2], temp192);
zlen = EA.ScaleExpansionZeroElim(zlen, temp192, pe[2], det384z);
xylen = EA.FastExpansionSumZeroElim(xlen, det384x, ylen, det384y, detxy);
elen = EA.FastExpansionSumZeroElim(xylen, detxy, zlen, det384z, edet);
ablen = EA.FastExpansionSumZeroElim(alen, adet, blen, bdet, abdet);
cdlen = EA.FastExpansionSumZeroElim(clen, cdet, dlen, ddet, cddet);
cdelen = EA.FastExpansionSumZeroElim(cdlen, cddet, elen, edet, cdedet);
deterlen = EA.FastExpansionSumZeroElim(ablen, abdet, cdelen, cdedet, deter);
// In S. predicates.c, this returns the largest component:
// deter[deterlen - 1];
// However, this is not stable due to the expansions not being unique (even for ZeroElim),
// So we return the summed estimate as the 'Exact' value.
return EA.Estimate(deterlen, deter);
}
internal static double InSphereSlow(double[] pa, double[] pb, double[] pc, double[] pd, double[] pe)
{
double aex, bex, cex, dex, aey, bey, cey, dey, aez, bez, cez, dez;
double aextail, bextail, cextail, dextail;
double aeytail, beytail, ceytail, deytail;
double aeztail, beztail, ceztail, deztail;
double negate, negatetail;
double axby7, bxcy7, cxdy7, dxay7, axcy7, bxdy7;
double bxay7, cxby7, dxcy7, axdy7, cxay7, dxby7;
double[] axby = new double[8];
double[] bxcy = new double[8];
double[] cxdy = new double[8];
double[] dxay = new double[8];
double[] axcy = new double[8];
double[] bxdy = new double[8];
double[] bxay = new double[8];
double[] cxby = new double[8];
double[] dxcy = new double[8];
double[] axdy = new double[8];
double[] cxay = new double[8];
double[] dxby = new double[8];
double[] ab = new double[16];
double[] bc = new double[16];
double[] cd = new double[16];
double[] da = new double[16];
double[] ac = new double[16];
double[] bd = new double[16];
int ablen, bclen, cdlen, dalen, aclen, bdlen;
double[] temp32a = new double[32];
double[] temp32b = new double[32];
double[] temp64a = new double[64];
double[] temp64b = new double[64];
double[] temp64c = new double[64];
int temp32alen, temp32blen, temp64alen, temp64blen, temp64clen;
double[] temp128 = new double[128];
double[] temp192 = new double[192];
int temp128len, temp192len;
double[] detx = new double[384];
double[] detxx = new double[768];
double[] detxt = new double[384];
double[] detxxt = new double[768];
double[] detxtxt = new double[768];
int xlen, xxlen, xtlen, xxtlen, xtxtlen;
double[] x1 = new double[1536];
double[] x2 = new double[2304];
int x1len, x2len;
double[] dety = new double[384];
double[] detyy = new double[768];
double[] detyt = new double[384];
double[] detyyt = new double[768];
double[] detytyt = new double[768];
int ylen, yylen, ytlen, yytlen, ytytlen;
double[] y1 = new double[1536];
double[] y2 = new double[2304];
int y1len, y2len;
double[] detz = new double[384];
double[] detzz = new double[768];
double[] detzt = new double[384];
double[] detzzt = new double[768];
double[] detztzt = new double[768];
int zlen, zzlen, ztlen, zztlen, ztztlen;
double[] z1 = new double[1536];
double[] z2 = new double[2304];
int z1len, z2len;
double[] detxy = new double[4608];
int xylen;
double[] adet = new double[6912];
double[] bdet = new double[6912];
double[] cdet = new double[6912];
double[] ddet = new double[6912];
int alen, blen, clen, dlen;
double[] abdet = new double[13824];
double[] cddet = new double[13824];
double[] deter = new double[27648];
int deterlen;
int i;
EA.TwoDiff(pa[0], pe[0], out aex, out aextail);
EA.TwoDiff(pa[1], pe[1], out aey, out aeytail);
EA.TwoDiff(pa[2], pe[2], out aez, out aeztail);
EA.TwoDiff(pb[0], pe[0], out bex, out bextail);
EA.TwoDiff(pb[1], pe[1], out bey, out beytail);
EA.TwoDiff(pb[2], pe[2], out bez, out beztail);
EA.TwoDiff(pc[0], pe[0], out cex, out cextail);
EA.TwoDiff(pc[1], pe[1], out cey, out ceytail);
EA.TwoDiff(pc[2], pe[2], out cez, out ceztail);
EA.TwoDiff(pd[0], pe[0], out dex, out dextail);
EA.TwoDiff(pd[1], pe[1], out dey, out deytail);
EA.TwoDiff(pd[2], pe[2], out dez, out deztail);
EA.TwoTwoProduct(aex, aextail, bey, beytail,
out axby7, out axby[6], out axby[5], out axby[4],
out axby[3], out axby[2], out axby[1], out axby[0]);
axby[7] = axby7;
negate = -aey;
negatetail = -aeytail;
EA.TwoTwoProduct(bex, bextail, negate, negatetail,
out bxay7, out bxay[6], out bxay[5], out bxay[4],
out bxay[3], out bxay[2], out bxay[1], out bxay[0]);
bxay[7] = bxay7;
ablen = EA.FastExpansionSumZeroElim(8, axby, 8, bxay, ab);
EA.TwoTwoProduct(bex, bextail, cey, ceytail,
out bxcy7, out bxcy[6], out bxcy[5], out bxcy[4],
out bxcy[3], out bxcy[2], out bxcy[1], out bxcy[0]);
bxcy[7] = bxcy7;
negate = -bey;
negatetail = -beytail;
EA.TwoTwoProduct(cex, cextail, negate, negatetail,
out cxby7, out cxby[6], out cxby[5], out cxby[4],
out cxby[3], out cxby[2], out cxby[1], out cxby[0]);
cxby[7] = cxby7;
bclen = EA.FastExpansionSumZeroElim(8, bxcy, 8, cxby, bc);
EA.TwoTwoProduct(cex, cextail, dey, deytail,
out cxdy7, out cxdy[6], out cxdy[5], out cxdy[4],
out cxdy[3], out cxdy[2], out cxdy[1], out cxdy[0]);
cxdy[7] = cxdy7;
negate = -cey;
negatetail = -ceytail;
EA.TwoTwoProduct(dex, dextail, negate, negatetail,
out dxcy7, out dxcy[6], out dxcy[5], out dxcy[4],
out dxcy[3], out dxcy[2], out dxcy[1], out dxcy[0]);
dxcy[7] = dxcy7;
cdlen = EA.FastExpansionSumZeroElim(8, cxdy, 8, dxcy, cd);
EA.TwoTwoProduct(dex, dextail, aey, aeytail,
out dxay7, out dxay[6], out dxay[5], out dxay[4],
out dxay[3], out dxay[2], out dxay[1], out dxay[0]);
dxay[7] = dxay7;
negate = -dey;
negatetail = -deytail;
EA.TwoTwoProduct(aex, aextail, negate, negatetail,
out axdy7, out axdy[6], out axdy[5], out axdy[4],
out axdy[3], out axdy[2], out axdy[1], out axdy[0]);
axdy[7] = axdy7;
dalen = EA.FastExpansionSumZeroElim(8, dxay, 8, axdy, da);
EA.TwoTwoProduct(aex, aextail, cey, ceytail,
out axcy7, out axcy[6], out axcy[5], out axcy[4],
out axcy[3], out axcy[2], out axcy[1], out axcy[0]);
axcy[7] = axcy7;
negate = -aey;
negatetail = -aeytail;
EA.TwoTwoProduct(cex, cextail, negate, negatetail,
out cxay7, out cxay[6], out cxay[5], out cxay[4],
out cxay[3], out cxay[2], out cxay[1], out cxay[0]);
cxay[7] = cxay7;
aclen = EA.FastExpansionSumZeroElim(8, axcy, 8, cxay, ac);
EA.TwoTwoProduct(bex, bextail, dey, deytail,
out bxdy7, out bxdy[6], out bxdy[5], out bxdy[4],
out bxdy[3], out bxdy[2], out bxdy[1], out bxdy[0]);
bxdy[7] = bxdy7;
negate = -bey;
negatetail = -beytail;
EA.TwoTwoProduct(dex, dextail, negate, negatetail,
out dxby7, out dxby[6], out dxby[5], out dxby[4],
out dxby[3], out dxby[2], out dxby[1], out dxby[0]);
dxby[7] = dxby7;
bdlen = EA.FastExpansionSumZeroElim(8, bxdy, 8, dxby, bd);
temp32alen = EA.ScaleExpansionZeroElim(cdlen, cd, -bez, temp32a);
temp32blen = EA.ScaleExpansionZeroElim(cdlen, cd, -beztail, temp32b);
temp64alen = EA.FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64a);
temp32alen = EA.ScaleExpansionZeroElim(bdlen, bd, cez, temp32a);
temp32blen = EA.ScaleExpansionZeroElim(bdlen, bd, ceztail, temp32b);
temp64blen = EA.FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64b);
temp32alen = EA.ScaleExpansionZeroElim(bclen, bc, -dez, temp32a);
temp32blen = EA.ScaleExpansionZeroElim(bclen, bc, -deztail, temp32b);
temp64clen = EA.FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64c);
temp128len = EA.FastExpansionSumZeroElim(temp64alen, temp64a, temp64blen, temp64b, temp128);
temp192len = EA.FastExpansionSumZeroElim(temp64clen, temp64c, temp128len, temp128, temp192);
xlen = EA.ScaleExpansionZeroElim(temp192len, temp192, aex, detx);
xxlen = EA.ScaleExpansionZeroElim(xlen, detx, aex, detxx);
xtlen = EA.ScaleExpansionZeroElim(temp192len, temp192, aextail, detxt);
xxtlen = EA.ScaleExpansionZeroElim(xtlen, detxt, aex, detxxt);
for (i = 0; i < xxtlen; i++)
{
detxxt[i] *= 2.0;
}
xtxtlen = EA.ScaleExpansionZeroElim(xtlen, detxt, aextail, detxtxt);
x1len = EA.FastExpansionSumZeroElim(xxlen, detxx, xxtlen, detxxt, x1);
x2len = EA.FastExpansionSumZeroElim(x1len, x1, xtxtlen, detxtxt, x2);
ylen = EA.ScaleExpansionZeroElim(temp192len, temp192, aey, dety);
yylen = EA.ScaleExpansionZeroElim(ylen, dety, aey, detyy);
ytlen = EA.ScaleExpansionZeroElim(temp192len, temp192, aeytail, detyt);
yytlen = EA.ScaleExpansionZeroElim(ytlen, detyt, aey, detyyt);
for (i = 0; i < yytlen; i++)
{
detyyt[i] *= 2.0;
}
ytytlen = EA.ScaleExpansionZeroElim(ytlen, detyt, aeytail, detytyt);
y1len = EA.FastExpansionSumZeroElim(yylen, detyy, yytlen, detyyt, y1);
y2len = EA.FastExpansionSumZeroElim(y1len, y1, ytytlen, detytyt, y2);
zlen = EA.ScaleExpansionZeroElim(temp192len, temp192, aez, detz);
zzlen = EA.ScaleExpansionZeroElim(zlen, detz, aez, detzz);
ztlen = EA.ScaleExpansionZeroElim(temp192len, temp192, aeztail, detzt);
zztlen = EA.ScaleExpansionZeroElim(ztlen, detzt, aez, detzzt);
for (i = 0; i < zztlen; i++)
{
detzzt[i] *= 2.0;
}
ztztlen = EA.ScaleExpansionZeroElim(ztlen, detzt, aeztail, detztzt);
z1len = EA.FastExpansionSumZeroElim(zzlen, detzz, zztlen, detzzt, z1);
z2len = EA.FastExpansionSumZeroElim(z1len, z1, ztztlen, detztzt, z2);
xylen = EA.FastExpansionSumZeroElim(x2len, x2, y2len, y2, detxy);
alen = EA.FastExpansionSumZeroElim(z2len, z2, xylen, detxy, adet);
temp32alen = EA.ScaleExpansionZeroElim(dalen, da, cez, temp32a);
temp32blen = EA.ScaleExpansionZeroElim(dalen, da, ceztail, temp32b);
temp64alen = EA.FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64a);
temp32alen = EA.ScaleExpansionZeroElim(aclen, ac, dez, temp32a);
temp32blen = EA.ScaleExpansionZeroElim(aclen, ac, deztail, temp32b);
temp64blen = EA.FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64b);
temp32alen = EA.ScaleExpansionZeroElim(cdlen, cd, aez, temp32a);
temp32blen = EA.ScaleExpansionZeroElim(cdlen, cd, aeztail, temp32b);
temp64clen = EA.FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64c);
temp128len = EA.FastExpansionSumZeroElim(temp64alen, temp64a, temp64blen, temp64b, temp128);
temp192len = EA.FastExpansionSumZeroElim(temp64clen, temp64c, temp128len, temp128, temp192);
xlen = EA.ScaleExpansionZeroElim(temp192len, temp192, bex, detx);
xxlen = EA.ScaleExpansionZeroElim(xlen, detx, bex, detxx);
xtlen = EA.ScaleExpansionZeroElim(temp192len, temp192, bextail, detxt);
xxtlen = EA.ScaleExpansionZeroElim(xtlen, detxt, bex, detxxt);
for (i = 0; i < xxtlen; i++)
{
detxxt[i] *= 2.0;
}
xtxtlen = EA.ScaleExpansionZeroElim(xtlen, detxt, bextail, detxtxt);
x1len = EA.FastExpansionSumZeroElim(xxlen, detxx, xxtlen, detxxt, x1);
x2len = EA.FastExpansionSumZeroElim(x1len, x1, xtxtlen, detxtxt, x2);
ylen = EA.ScaleExpansionZeroElim(temp192len, temp192, bey, dety);
yylen = EA.ScaleExpansionZeroElim(ylen, dety, bey, detyy);
ytlen = EA.ScaleExpansionZeroElim(temp192len, temp192, beytail, detyt);
yytlen = EA.ScaleExpansionZeroElim(ytlen, detyt, bey, detyyt);
for (i = 0; i < yytlen; i++)
{
detyyt[i] *= 2.0;
}
ytytlen = EA.ScaleExpansionZeroElim(ytlen, detyt, beytail, detytyt);
y1len = EA.FastExpansionSumZeroElim(yylen, detyy, yytlen, detyyt, y1);
y2len = EA.FastExpansionSumZeroElim(y1len, y1, ytytlen, detytyt, y2);
zlen = EA.ScaleExpansionZeroElim(temp192len, temp192, bez, detz);
zzlen = EA.ScaleExpansionZeroElim(zlen, detz, bez, detzz);
ztlen = EA.ScaleExpansionZeroElim(temp192len, temp192, beztail, detzt);
zztlen = EA.ScaleExpansionZeroElim(ztlen, detzt, bez, detzzt);
for (i = 0; i < zztlen; i++)
{
detzzt[i] *= 2.0;
}
ztztlen = EA.ScaleExpansionZeroElim(ztlen, detzt, beztail, detztzt);
z1len = EA.FastExpansionSumZeroElim(zzlen, detzz, zztlen, detzzt, z1);
z2len = EA.FastExpansionSumZeroElim(z1len, z1, ztztlen, detztzt, z2);
xylen = EA.FastExpansionSumZeroElim(x2len, x2, y2len, y2, detxy);
blen = EA.FastExpansionSumZeroElim(z2len, z2, xylen, detxy, bdet);
temp32alen = EA.ScaleExpansionZeroElim(ablen, ab, -dez, temp32a);
temp32blen = EA.ScaleExpansionZeroElim(ablen, ab, -deztail, temp32b);
temp64alen = EA.FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64a);
temp32alen = EA.ScaleExpansionZeroElim(bdlen, bd, -aez, temp32a);
temp32blen = EA.ScaleExpansionZeroElim(bdlen, bd, -aeztail, temp32b);
temp64blen = EA.FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64b);
temp32alen = EA.ScaleExpansionZeroElim(dalen, da, -bez, temp32a);
temp32blen = EA.ScaleExpansionZeroElim(dalen, da, -beztail, temp32b);
temp64clen = EA.FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64c);
temp128len = EA.FastExpansionSumZeroElim(temp64alen, temp64a, temp64blen, temp64b, temp128);
temp192len = EA.FastExpansionSumZeroElim(temp64clen, temp64c, temp128len, temp128, temp192);
xlen = EA.ScaleExpansionZeroElim(temp192len, temp192, cex, detx);
xxlen = EA.ScaleExpansionZeroElim(xlen, detx, cex, detxx);
xtlen = EA.ScaleExpansionZeroElim(temp192len, temp192, cextail, detxt);
xxtlen = EA.ScaleExpansionZeroElim(xtlen, detxt, cex, detxxt);
for (i = 0; i < xxtlen; i++)
{
detxxt[i] *= 2.0;
}
xtxtlen = EA.ScaleExpansionZeroElim(xtlen, detxt, cextail, detxtxt);
x1len = EA.FastExpansionSumZeroElim(xxlen, detxx, xxtlen, detxxt, x1);
x2len = EA.FastExpansionSumZeroElim(x1len, x1, xtxtlen, detxtxt, x2);
ylen = EA.ScaleExpansionZeroElim(temp192len, temp192, cey, dety);
yylen = EA.ScaleExpansionZeroElim(ylen, dety, cey, detyy);
ytlen = EA.ScaleExpansionZeroElim(temp192len, temp192, ceytail, detyt);
yytlen = EA.ScaleExpansionZeroElim(ytlen, detyt, cey, detyyt);
for (i = 0; i < yytlen; i++)
{
detyyt[i] *= 2.0;
}
ytytlen = EA.ScaleExpansionZeroElim(ytlen, detyt, ceytail, detytyt);
y1len = EA.FastExpansionSumZeroElim(yylen, detyy, yytlen, detyyt, y1);
y2len = EA.FastExpansionSumZeroElim(y1len, y1, ytytlen, detytyt, y2);
zlen = EA.ScaleExpansionZeroElim(temp192len, temp192, cez, detz);
zzlen = EA.ScaleExpansionZeroElim(zlen, detz, cez, detzz);
ztlen = EA.ScaleExpansionZeroElim(temp192len, temp192, ceztail, detzt);
zztlen = EA.ScaleExpansionZeroElim(ztlen, detzt, cez, detzzt);
for (i = 0; i < zztlen; i++)
{
detzzt[i] *= 2.0;
}
ztztlen = EA.ScaleExpansionZeroElim(ztlen, detzt, ceztail, detztzt);
z1len = EA.FastExpansionSumZeroElim(zzlen, detzz, zztlen, detzzt, z1);
z2len = EA.FastExpansionSumZeroElim(z1len, z1, ztztlen, detztzt, z2);
xylen = EA.FastExpansionSumZeroElim(x2len, x2, y2len, y2, detxy);
clen = EA.FastExpansionSumZeroElim(z2len, z2, xylen, detxy, cdet);
temp32alen = EA.ScaleExpansionZeroElim(bclen, bc, aez, temp32a);
temp32blen = EA.ScaleExpansionZeroElim(bclen, bc, aeztail, temp32b);
temp64alen = EA.FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64a);
temp32alen = EA.ScaleExpansionZeroElim(aclen, ac, -bez, temp32a);
temp32blen = EA.ScaleExpansionZeroElim(aclen, ac, -beztail, temp32b);
temp64blen = EA.FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64b);
temp32alen = EA.ScaleExpansionZeroElim(ablen, ab, cez, temp32a);
temp32blen = EA.ScaleExpansionZeroElim(ablen, ab, ceztail, temp32b);
temp64clen = EA.FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64c);
temp128len = EA.FastExpansionSumZeroElim(temp64alen, temp64a, temp64blen, temp64b, temp128);
temp192len = EA.FastExpansionSumZeroElim(temp64clen, temp64c, temp128len, temp128, temp192);
xlen = EA.ScaleExpansionZeroElim(temp192len, temp192, dex, detx);
xxlen = EA.ScaleExpansionZeroElim(xlen, detx, dex, detxx);
xtlen = EA.ScaleExpansionZeroElim(temp192len, temp192, dextail, detxt);
xxtlen = EA.ScaleExpansionZeroElim(xtlen, detxt, dex, detxxt);
for (i = 0; i < xxtlen; i++)
{
detxxt[i] *= 2.0;
}
xtxtlen = EA.ScaleExpansionZeroElim(xtlen, detxt, dextail, detxtxt);
x1len = EA.FastExpansionSumZeroElim(xxlen, detxx, xxtlen, detxxt, x1);
x2len = EA.FastExpansionSumZeroElim(x1len, x1, xtxtlen, detxtxt, x2);
ylen = EA.ScaleExpansionZeroElim(temp192len, temp192, dey, dety);
yylen = EA.ScaleExpansionZeroElim(ylen, dety, dey, detyy);
ytlen = EA.ScaleExpansionZeroElim(temp192len, temp192, deytail, detyt);
yytlen = EA.ScaleExpansionZeroElim(ytlen, detyt, dey, detyyt);
for (i = 0; i < yytlen; i++)
{
detyyt[i] *= 2.0;
}
ytytlen = EA.ScaleExpansionZeroElim(ytlen, detyt, deytail, detytyt);
y1len = EA.FastExpansionSumZeroElim(yylen, detyy, yytlen, detyyt, y1);
y2len = EA.FastExpansionSumZeroElim(y1len, y1, ytytlen, detytyt, y2);
zlen = EA.ScaleExpansionZeroElim(temp192len, temp192, dez, detz);
zzlen = EA.ScaleExpansionZeroElim(zlen, detz, dez, detzz);
ztlen = EA.ScaleExpansionZeroElim(temp192len, temp192, deztail, detzt);
zztlen = EA.ScaleExpansionZeroElim(ztlen, detzt, dez, detzzt);
for (i = 0; i < zztlen; i++)
{
detzzt[i] *= 2.0;
}
ztztlen = EA.ScaleExpansionZeroElim(ztlen, detzt, deztail, detztzt);
z1len = EA.FastExpansionSumZeroElim(zzlen, detzz, zztlen, detzzt, z1);
z2len = EA.FastExpansionSumZeroElim(z1len, z1, ztztlen, detztzt, z2);
xylen = EA.FastExpansionSumZeroElim(x2len, x2, y2len, y2, detxy);
dlen = EA.FastExpansionSumZeroElim(z2len, z2, xylen, detxy, ddet);
ablen = EA.FastExpansionSumZeroElim(alen, adet, blen, bdet, abdet);
cdlen = EA.FastExpansionSumZeroElim(clen, cdet, dlen, ddet, cddet);
deterlen = EA.FastExpansionSumZeroElim(ablen, abdet, cdlen, cddet, deter);
// In S. predicates.c, this returns the largest component:
// deter[deterlen - 1];
// However, this is not stable due to the expansions not being unique (even for ZeroElim),
// So we return the summed estimate as the 'Exact' value.
return EA.Estimate(deterlen, deter);
}
public static double InSphere(double[] pa, double[] pb, double[] pc, double[] pd, double[] pe)
{
double aex, bex, cex, dex;
double aey, bey, cey, dey;
double aez, bez, cez, dez;
double aexbey, bexaey, bexcey, cexbey, cexdey, dexcey, dexaey, aexdey;
double aexcey, cexaey, bexdey, dexbey;
double alift, blift, clift, dlift;
double ab, bc, cd, da, ac, bd;
double abc, bcd, cda, dab;
double aezplus, bezplus, cezplus, dezplus;
double aexbeyplus, bexaeyplus, bexceyplus, cexbeyplus;
double cexdeyplus, dexceyplus, dexaeyplus, aexdeyplus;
double aexceyplus, cexaeyplus, bexdeyplus, dexbeyplus;
double det;
double permanent, errbound;
aex = pa[0] - pe[0];
bex = pb[0] - pe[0];
cex = pc[0] - pe[0];
dex = pd[0] - pe[0];
aey = pa[1] - pe[1];
bey = pb[1] - pe[1];
cey = pc[1] - pe[1];
dey = pd[1] - pe[1];
aez = pa[2] - pe[2];
bez = pb[2] - pe[2];
cez = pc[2] - pe[2];
dez = pd[2] - pe[2];
aexbey = aex * bey;
bexaey = bex * aey;
ab = aexbey - bexaey;
bexcey = bex * cey;
cexbey = cex * bey;
bc = bexcey - cexbey;
cexdey = cex * dey;
dexcey = dex * cey;
cd = cexdey - dexcey;
dexaey = dex * aey;
aexdey = aex * dey;
da = dexaey - aexdey;
aexcey = aex * cey;
cexaey = cex * aey;
ac = aexcey - cexaey;
bexdey = bex * dey;
dexbey = dex * bey;
bd = bexdey - dexbey;
abc = aez * bc - bez * ac + cez * ab;
bcd = bez * cd - cez * bd + dez * bc;
cda = cez * da + dez * ac + aez * cd;
dab = dez * ab + aez * bd + bez * da;
alift = aex * aex + aey * aey + aez * aez;
blift = bex * bex + bey * bey + bez * bez;
clift = cex * cex + cey * cey + cez * cez;
dlift = dex * dex + dey * dey + dez * dez;
det = (dlift * abc - clift * dab) + (blift * cda - alift * bcd);
aezplus = Math.Abs(aez);
bezplus = Math.Abs(bez);
cezplus = Math.Abs(cez);
dezplus = Math.Abs(dez);
aexbeyplus = Math.Abs(aexbey);
bexaeyplus = Math.Abs(bexaey);
bexceyplus = Math.Abs(bexcey);
cexbeyplus = Math.Abs(cexbey);
cexdeyplus = Math.Abs(cexdey);
dexceyplus = Math.Abs(dexcey);
dexaeyplus = Math.Abs(dexaey);
aexdeyplus = Math.Abs(aexdey);
aexceyplus = Math.Abs(aexcey);
cexaeyplus = Math.Abs(cexaey);
bexdeyplus = Math.Abs(bexdey);
dexbeyplus = Math.Abs(dexbey);
permanent = ((cexdeyplus + dexceyplus) * bezplus
+ (dexbeyplus + bexdeyplus) * cezplus
+ (bexceyplus + cexbeyplus) * dezplus)
* alift
+ ((dexaeyplus + aexdeyplus) * cezplus
+ (aexceyplus + cexaeyplus) * dezplus
+ (cexdeyplus + dexceyplus) * aezplus)
* blift
+ ((aexbeyplus + bexaeyplus) * dezplus
+ (bexdeyplus + dexbeyplus) * aezplus
+ (dexaeyplus + aexdeyplus) * bezplus)
* clift
+ ((bexceyplus + cexbeyplus) * aezplus
+ (cexaeyplus + aexceyplus) * bezplus
+ (aexbeyplus + bexaeyplus) * cezplus)
* dlift;
errbound = isperrboundA * permanent;
if ((det > errbound) || (-det > errbound))
{
return det;
}
return InSphereAdapt(pa, pb, pc, pd, pe, permanent);
}
// Adaptive continuation of InSphere
static double InSphereAdapt(double[] pa, double[] pb, double[] pc, double[] pd, double[] pe, double permanent)
{
double aex, bex, cex, dex, aey, bey, cey, dey, aez, bez, cez, dez;
double det, errbound;
double aexbey1, bexaey1, bexcey1, cexbey1;
double cexdey1, dexcey1, dexaey1, aexdey1;
double aexcey1, cexaey1, bexdey1, dexbey1;
double aexbey0, bexaey0, bexcey0, cexbey0;
double cexdey0, dexcey0, dexaey0, aexdey0;
double aexcey0, cexaey0, bexdey0, dexbey0;
double[] ab = new double[4];
double[] bc = new double[4];
double[] cd = new double[4];
double[] da = new double[4];
double[] ac = new double[4];
double[] bd = new double[4];
double ab3, bc3, cd3, da3, ac3, bd3;
double abeps, bceps, cdeps, daeps, aceps, bdeps;
double[] temp8a = new double[8];
double[] temp8b = new double[8];
double[] temp8c = new double[8];
double[] temp16 = new double[16];
double[] temp24 = new double[24];
double[] temp48 = new double[48];
int temp8alen, temp8blen, temp8clen, temp16len, temp24len, temp48len;
double[] xdet = new double[96];
double[] ydet = new double[96];
double[] zdet = new double[96];
double[] xydet = new double[192];
int xlen, ylen, zlen, xylen;
double[] adet = new double[288];
double[] bdet = new double[288];
double[] cdet = new double[288];
double[] ddet = new double[288];
int alen, blen, clen, dlen;
double[] abdet = new double[576];
double[] cddet = new double[576];
int ablen, cdlen;
double[] fin1 = new double[1152];
int finlength;
double aextail, bextail, cextail, dextail;
double aeytail, beytail, ceytail, deytail;
double aeztail, beztail, ceztail, deztail;
aex = pa[0] - pe[0];
bex = pb[0] - pe[0];
cex = pc[0] - pe[0];
dex = pd[0] - pe[0];
aey = pa[1] - pe[1];
bey = pb[1] - pe[1];
cey = pc[1] - pe[1];
dey = pd[1] - pe[1];
aez = pa[2] - pe[2];
bez = pb[2] - pe[2];
cez = pc[2] - pe[2];
dez = pd[2] - pe[2];
EA.TwoProduct(aex, bey, out aexbey1, out aexbey0);
EA.TwoProduct(bex, aey, out bexaey1, out bexaey0);
EA.TwoTwoDiff(aexbey1, aexbey0, bexaey1, bexaey0, out ab3, out ab[2], out ab[1], out ab[0]);
ab[3] = ab3;
EA.TwoProduct(bex, cey, out bexcey1, out bexcey0);
EA.TwoProduct(cex, bey, out cexbey1, out cexbey0);
EA.TwoTwoDiff(bexcey1, bexcey0, cexbey1, cexbey0, out bc3, out bc[2], out bc[1], out bc[0]);
bc[3] = bc3;
EA.TwoProduct(cex, dey, out cexdey1, out cexdey0);
EA.TwoProduct(dex, cey, out dexcey1, out dexcey0);
EA.TwoTwoDiff(cexdey1, cexdey0, dexcey1, dexcey0, out cd3, out cd[2], out cd[1], out cd[0]);
cd[3] = cd3;
EA.TwoProduct(dex, aey, out dexaey1, out dexaey0);
EA.TwoProduct(aex, dey, out aexdey1, out aexdey0);
EA.TwoTwoDiff(dexaey1, dexaey0, aexdey1, aexdey0, out da3, out da[2], out da[1], out da[0]);
da[3] = da3;
EA.TwoProduct(aex, cey, out aexcey1, out aexcey0);
EA.TwoProduct(cex, aey, out cexaey1, out cexaey0);
EA.TwoTwoDiff(aexcey1, aexcey0, cexaey1, cexaey0, out ac3, out ac[2], out ac[1], out ac[0]);
ac[3] = ac3;
EA.TwoProduct(bex, dey, out bexdey1, out bexdey0);
EA.TwoProduct(dex, bey, out dexbey1, out dexbey0);
EA.TwoTwoDiff(bexdey1, bexdey0, dexbey1, dexbey0, out bd3, out bd[2], out bd[1], out bd[0]);
bd[3] = bd3;
temp8alen = EA.ScaleExpansionZeroElim(4, cd, bez, temp8a);
temp8blen = EA.ScaleExpansionZeroElim(4, bd, -cez, temp8b);
temp8clen = EA.ScaleExpansionZeroElim(4, bc, dez, temp8c);
temp16len = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp8blen, temp8b, temp16);
temp24len = EA.FastExpansionSumZeroElim(temp8clen, temp8c, temp16len, temp16, temp24);
temp48len = EA.ScaleExpansionZeroElim(temp24len, temp24, aex, temp48);
xlen = EA.ScaleExpansionZeroElim(temp48len, temp48, -aex, xdet);
temp48len = EA.ScaleExpansionZeroElim(temp24len, temp24, aey, temp48);
ylen = EA.ScaleExpansionZeroElim(temp48len, temp48, -aey, ydet);
temp48len = EA.ScaleExpansionZeroElim(temp24len, temp24, aez, temp48);
zlen = EA.ScaleExpansionZeroElim(temp48len, temp48, -aez, zdet);
xylen = EA.FastExpansionSumZeroElim(xlen, xdet, ylen, ydet, xydet);
alen = EA.FastExpansionSumZeroElim(xylen, xydet, zlen, zdet, adet);
temp8alen = EA.ScaleExpansionZeroElim(4, da, cez, temp8a);
temp8blen = EA.ScaleExpansionZeroElim(4, ac, dez, temp8b);
temp8clen = EA.ScaleExpansionZeroElim(4, cd, aez, temp8c);
temp16len = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp8blen, temp8b, temp16);
temp24len = EA.FastExpansionSumZeroElim(temp8clen, temp8c, temp16len, temp16, temp24);
temp48len = EA.ScaleExpansionZeroElim(temp24len, temp24, bex, temp48);
xlen = EA.ScaleExpansionZeroElim(temp48len, temp48, bex, xdet);
temp48len = EA.ScaleExpansionZeroElim(temp24len, temp24, bey, temp48);
ylen = EA.ScaleExpansionZeroElim(temp48len, temp48, bey, ydet);
temp48len = EA.ScaleExpansionZeroElim(temp24len, temp24, bez, temp48);
zlen = EA.ScaleExpansionZeroElim(temp48len, temp48, bez, zdet);
xylen = EA.FastExpansionSumZeroElim(xlen, xdet, ylen, ydet, xydet);
blen = EA.FastExpansionSumZeroElim(xylen, xydet, zlen, zdet, bdet);
temp8alen = EA.ScaleExpansionZeroElim(4, ab, dez, temp8a);
temp8blen = EA.ScaleExpansionZeroElim(4, bd, aez, temp8b);
temp8clen = EA.ScaleExpansionZeroElim(4, da, bez, temp8c);
temp16len = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp8blen, temp8b, temp16);
temp24len = EA.FastExpansionSumZeroElim(temp8clen, temp8c, temp16len, temp16, temp24);
temp48len = EA.ScaleExpansionZeroElim(temp24len, temp24, cex, temp48);
xlen = EA.ScaleExpansionZeroElim(temp48len, temp48, -cex, xdet);
temp48len = EA.ScaleExpansionZeroElim(temp24len, temp24, cey, temp48);
ylen = EA.ScaleExpansionZeroElim(temp48len, temp48, -cey, ydet);
temp48len = EA.ScaleExpansionZeroElim(temp24len, temp24, cez, temp48);
zlen = EA.ScaleExpansionZeroElim(temp48len, temp48, -cez, zdet);
xylen = EA.FastExpansionSumZeroElim(xlen, xdet, ylen, ydet, xydet);
clen = EA.FastExpansionSumZeroElim(xylen, xydet, zlen, zdet, cdet);
temp8alen = EA.ScaleExpansionZeroElim(4, bc, aez, temp8a);
temp8blen = EA.ScaleExpansionZeroElim(4, ac, -bez, temp8b);
temp8clen = EA.ScaleExpansionZeroElim(4, ab, cez, temp8c);
temp16len = EA.FastExpansionSumZeroElim(temp8alen, temp8a, temp8blen, temp8b, temp16);
temp24len = EA.FastExpansionSumZeroElim(temp8clen, temp8c, temp16len, temp16, temp24);
temp48len = EA.ScaleExpansionZeroElim(temp24len, temp24, dex, temp48);
xlen = EA.ScaleExpansionZeroElim(temp48len, temp48, dex, xdet);
temp48len = EA.ScaleExpansionZeroElim(temp24len, temp24, dey, temp48);
ylen = EA.ScaleExpansionZeroElim(temp48len, temp48, dey, ydet);
temp48len = EA.ScaleExpansionZeroElim(temp24len, temp24, dez, temp48);
zlen = EA.ScaleExpansionZeroElim(temp48len, temp48, dez, zdet);
xylen = EA.FastExpansionSumZeroElim(xlen, xdet, ylen, ydet, xydet);
dlen = EA.FastExpansionSumZeroElim(xylen, xydet, zlen, zdet, ddet);
ablen = EA.FastExpansionSumZeroElim(alen, adet, blen, bdet, abdet);
cdlen = EA.FastExpansionSumZeroElim(clen, cdet, dlen, ddet, cddet);
finlength = EA.FastExpansionSumZeroElim(ablen, abdet, cdlen, cddet, fin1);
det = EA.Estimate(finlength, fin1);
errbound = isperrboundB * permanent;
if ((det >= errbound) || (-det >= errbound))
{
return det;
}
EA.TwoDiffTail(pa[0], pe[0], aex, out aextail);
EA.TwoDiffTail(pa[1], pe[1], aey, out aeytail);
EA.TwoDiffTail(pa[2], pe[2], aez, out aeztail);
EA.TwoDiffTail(pb[0], pe[0], bex, out bextail);
EA.TwoDiffTail(pb[1], pe[1], bey, out beytail);
EA.TwoDiffTail(pb[2], pe[2], bez, out beztail);
EA.TwoDiffTail(pc[0], pe[0], cex, out cextail);
EA.TwoDiffTail(pc[1], pe[1], cey, out ceytail);
EA.TwoDiffTail(pc[2], pe[2], cez, out ceztail);
EA.TwoDiffTail(pd[0], pe[0], dex, out dextail);
EA.TwoDiffTail(pd[1], pe[1], dey, out deytail);
EA.TwoDiffTail(pd[2], pe[2], dez, out deztail);
if ((aextail == 0.0) && (aeytail == 0.0) && (aeztail == 0.0)
&& (bextail == 0.0) && (beytail == 0.0) && (beztail == 0.0)
&& (cextail == 0.0) && (ceytail == 0.0) && (ceztail == 0.0)
&& (dextail == 0.0) && (deytail == 0.0) && (deztail == 0.0))
{
return det;
}
errbound = isperrboundC * permanent + resulterrbound * Math.Abs(det);
abeps = (aex * beytail + bey * aextail)
- (aey * bextail + bex * aeytail);
bceps = (bex * ceytail + cey * bextail)
- (bey * cextail + cex * beytail);
cdeps = (cex * deytail + dey * cextail)
- (cey * dextail + dex * ceytail);
daeps = (dex * aeytail + aey * dextail)
- (dey * aextail + aex * deytail);
aceps = (aex * ceytail + cey * aextail)
- (aey * cextail + cex * aeytail);
bdeps = (bex * deytail + dey * bextail)
- (bey * dextail + dex * beytail);
det += (((bex * bex + bey * bey + bez * bez)
* ((cez * daeps + dez * aceps + aez * cdeps)
+ (ceztail * da3 + deztail * ac3 + aeztail * cd3))
+ (dex * dex + dey * dey + dez * dez)
* ((aez * bceps - bez * aceps + cez * abeps)
+ (aeztail * bc3 - beztail * ac3 + ceztail * ab3)))
- ((aex * aex + aey * aey + aez * aez)
* ((bez * cdeps - cez * bdeps + dez * bceps)
+ (beztail * cd3 - ceztail * bd3 + deztail * bc3))
+ (cex * cex + cey * cey + cez * cez)
* ((dez * abeps + aez * bdeps + bez * daeps)
+ (deztail * ab3 + aeztail * bd3 + beztail * da3))))
+ 2.0 * (((bex * bextail + bey * beytail + bez * beztail)
* (cez * da3 + dez * ac3 + aez * cd3)
+ (dex * dextail + dey * deytail + dez * deztail)
* (aez * bc3 - bez * ac3 + cez * ab3))
- ((aex * aextail + aey * aeytail + aez * aeztail)
* (bez * cd3 - cez * bd3 + dez * bc3)
+ (cex * cextail + cey * ceytail + cez * ceztail)
* (dez * ab3 + aez * bd3 + bez * da3)));
if ((det >= errbound) || (-det >= errbound))
{
return det;
}
return InSphereExact(pa, pb, pc, pd, pe);
}
#endregion
}
}
| 51.963787 | 121 | 0.521268 | [
"MIT"
] | akopetsch/RobustGeometry.NET | RobustGeometry/Predicates/GeometricPredicates.cs | 156,413 | 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.
// Template Source: Templates\CSharp\Requests\IEntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The interface IWindowsInformationProtectionNetworkLearningSummaryRequest.
/// </summary>
public partial interface IWindowsInformationProtectionNetworkLearningSummaryRequest : IBaseRequest
{
/// <summary>
/// Creates the specified WindowsInformationProtectionNetworkLearningSummary using PUT.
/// </summary>
/// <param name="windowsInformationProtectionNetworkLearningSummaryToCreate">The WindowsInformationProtectionNetworkLearningSummary to create.</param>
/// <returns>The created WindowsInformationProtectionNetworkLearningSummary.</returns>
System.Threading.Tasks.Task<WindowsInformationProtectionNetworkLearningSummary> CreateAsync(WindowsInformationProtectionNetworkLearningSummary windowsInformationProtectionNetworkLearningSummaryToCreate); /// <summary>
/// Creates the specified WindowsInformationProtectionNetworkLearningSummary using PUT.
/// </summary>
/// <param name="windowsInformationProtectionNetworkLearningSummaryToCreate">The WindowsInformationProtectionNetworkLearningSummary to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created WindowsInformationProtectionNetworkLearningSummary.</returns>
System.Threading.Tasks.Task<WindowsInformationProtectionNetworkLearningSummary> CreateAsync(WindowsInformationProtectionNetworkLearningSummary windowsInformationProtectionNetworkLearningSummaryToCreate, CancellationToken cancellationToken);
/// <summary>
/// Deletes the specified WindowsInformationProtectionNetworkLearningSummary.
/// </summary>
/// <returns>The task to await.</returns>
System.Threading.Tasks.Task DeleteAsync();
/// <summary>
/// Deletes the specified WindowsInformationProtectionNetworkLearningSummary.
/// </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);
/// <summary>
/// Gets the specified WindowsInformationProtectionNetworkLearningSummary.
/// </summary>
/// <returns>The WindowsInformationProtectionNetworkLearningSummary.</returns>
System.Threading.Tasks.Task<WindowsInformationProtectionNetworkLearningSummary> GetAsync();
/// <summary>
/// Gets the specified WindowsInformationProtectionNetworkLearningSummary.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The WindowsInformationProtectionNetworkLearningSummary.</returns>
System.Threading.Tasks.Task<WindowsInformationProtectionNetworkLearningSummary> GetAsync(CancellationToken cancellationToken);
/// <summary>
/// Updates the specified WindowsInformationProtectionNetworkLearningSummary using PATCH.
/// </summary>
/// <param name="windowsInformationProtectionNetworkLearningSummaryToUpdate">The WindowsInformationProtectionNetworkLearningSummary to update.</param>
/// <returns>The updated WindowsInformationProtectionNetworkLearningSummary.</returns>
System.Threading.Tasks.Task<WindowsInformationProtectionNetworkLearningSummary> UpdateAsync(WindowsInformationProtectionNetworkLearningSummary windowsInformationProtectionNetworkLearningSummaryToUpdate);
/// <summary>
/// Updates the specified WindowsInformationProtectionNetworkLearningSummary using PATCH.
/// </summary>
/// <param name="windowsInformationProtectionNetworkLearningSummaryToUpdate">The WindowsInformationProtectionNetworkLearningSummary to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated WindowsInformationProtectionNetworkLearningSummary.</returns>
System.Threading.Tasks.Task<WindowsInformationProtectionNetworkLearningSummary> UpdateAsync(WindowsInformationProtectionNetworkLearningSummary windowsInformationProtectionNetworkLearningSummaryToUpdate, CancellationToken cancellationToken);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
IWindowsInformationProtectionNetworkLearningSummaryRequest Expand(string value);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
IWindowsInformationProtectionNetworkLearningSummaryRequest Expand(Expression<Func<WindowsInformationProtectionNetworkLearningSummary, object>> expandExpression);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
IWindowsInformationProtectionNetworkLearningSummaryRequest Select(string value);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
IWindowsInformationProtectionNetworkLearningSummaryRequest Select(Expression<Func<WindowsInformationProtectionNetworkLearningSummary, object>> selectExpression);
}
}
| 61.04717 | 248 | 0.724308 | [
"MIT"
] | AzureMentor/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/IWindowsInformationProtectionNetworkLearningSummaryRequest.cs | 6,471 | C# |
using System.Linq;
using NUnit.Framework;
using Rebus.Internals;
using Rebus.Tests.Contracts;
namespace Rebus.AzureServiceBus.Tests.Extensions
{
[TestFixture]
public class TestEnumerableExtensions : FixtureBase
{
[Test]
public void CanBatchWeighted()
{
var items = new[] { 1, 2, 10, 12, 5, 6, 7 };
var batches = items.BatchWeighted(i => i, maxWeight: 15).ToList();
Assert.That(batches.Count, Is.EqualTo(4));
Assert.That(batches[0], Is.EqualTo(new[] { 1, 2, 10 }));
Assert.That(batches[1], Is.EqualTo(new[] { 12 }));
Assert.That(batches[2], Is.EqualTo(new[] { 5, 6 }));
Assert.That(batches[3], Is.EqualTo(new[] { 7 }));
}
[Test]
public void CanBatchWeighted_IntentionallyExceed()
{
var items = new[] { 1, 16, 10, 18 };
var batches = items.BatchWeighted(i => i, maxWeight: 15).ToList();
Assert.That(batches.Count, Is.EqualTo(4));
Assert.That(batches[0], Is.EqualTo(new[] { 1 }));
Assert.That(batches[1], Is.EqualTo(new[] { 16 }));
Assert.That(batches[2], Is.EqualTo(new[] { 10 }));
Assert.That(batches[3], Is.EqualTo(new[] { 18 }));
}
[Test]
public void TryWithMessages()
{
var messages = Enumerable.Range(0, 1000)
.Select(n => new MessageWithText($"message {n}"));
var batches = messages.BatchWeighted(m => m.Text.Length, 1000).ToList();
Assert.That(batches.All(b => b.Sum(m => m.Text.Length) <= 1000), Is.True);
}
record MessageWithText(string Text);
}
} | 31.611111 | 86 | 0.547159 | [
"MIT"
] | kristofdegrave/Rebus.AzureServiceBus | Rebus.AzureServiceBus.Tests/Extensions/TestEnumerableExtensions.cs | 1,709 | C# |
using GSD.Common;
using GSD.Platform.Mac;
namespace GSD.PlatformLoader
{
public static class GSDPlatformLoader
{
public static void Initialize()
{
GSDPlatform.Register(new MacPlatform());
return;
}
}
} | 18.714286 | 52 | 0.603053 | [
"MIT"
] | derrickstolee/VFSForG | GSD/GSD.PlatformLoader/PlatformLoader.Mac.cs | 262 | C# |
/*
* Copyright (C) 2016 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
namespace com.opengamma.strata.measure.capfloor
{
using IborIndex = com.opengamma.strata.basics.index.IborIndex;
using MarketData = com.opengamma.strata.data.MarketData;
using MarketDataNotFoundException = com.opengamma.strata.data.MarketDataNotFoundException;
using IborCapletFloorletVolatilities = com.opengamma.strata.pricer.capfloor.IborCapletFloorletVolatilities;
/// <summary>
/// Market data for Ibor cap/floor.
/// <para>
/// This interface exposes the market data necessary for pricing Ibor caps/floors.
/// </para>
/// <para>
/// Implementations of this interface must be immutable.
/// </para>
/// </summary>
public interface IborCapFloorMarketData
{
/// <summary>
/// Gets the valuation date.
/// </summary>
/// <returns> the valuation date </returns>
//JAVA TO C# CONVERTER TODO TASK: There is no equivalent in C# to Java default interface methods:
// public default java.time.LocalDate getValuationDate()
// {
// return getMarketData().getValuationDate();
// }
//-------------------------------------------------------------------------
/// <summary>
/// Gets the lookup that provides access to cap/floor volatilities.
/// </summary>
/// <returns> the cap/floor lookup </returns>
IborCapFloorMarketDataLookup Lookup {get;}
/// <summary>
/// Gets the market data.
/// </summary>
/// <returns> the market data </returns>
MarketData MarketData {get;}
/// <summary>
/// Returns a copy of this instance with the specified market data.
/// </summary>
/// <param name="marketData"> the market data to use </param>
/// <returns> a market view based on the specified data </returns>
IborCapFloorMarketData withMarketData(MarketData marketData);
//-------------------------------------------------------------------------
/// <summary>
/// Gets the volatilities for the specified Ibor index.
/// <para>
/// If the index is not found, an exception is thrown.
///
/// </para>
/// </summary>
/// <param name="index"> the Ibor index </param>
/// <returns> the volatilities for the index </returns>
/// <exception cref="MarketDataNotFoundException"> if the index is not found </exception>
IborCapletFloorletVolatilities volatilities(IborIndex index);
}
} | 34.15493 | 108 | 0.646186 | [
"Apache-2.0"
] | ckarcz/Strata.ConvertedToCSharp | modules/measure/src/main/java/com/opengamma/strata/measure/capfloor/IborCapFloorMarketData.cs | 2,427 | C# |
using FacebookETL;
using FacebookUtillity;
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
namespace FacebookUtilityTest
{
class Program
{
static void Main(string[] args)
{
//string sqlConnectionString = "Server = tcp:modb1.database.windows.net,1433; Initial Catalog = fb; Persist Security Info = False; User ID = pbiadmin; Password = Corp123!; MultipleActiveResultSets = False; Encrypt = True; TrustServerCertificate = False; Connection Timeout = 30";
//string cognitiveKey = "8f5837f6f20c4374b93d171c490fa58c";
//string schema = "[fb]";
//string facebookClientId = "421651141539199";
//string facebookClientSecret = "511941c6bb0aa06afb250fc5c8628f95";
//string date = DateTime.Now.AddDays(-2).ToString();
//var test = MainETL.PopulateAll(sqlConnectionString, schema, cognitiveKey, facebookClientId, facebookClientSecret, date).Result;
string page = "";
string accessToken = "";
string sqlConn = "";
string schema = "";
string until = DateTime.UtcNow.AddDays(-2).ToString();
var test = PageAnalyticsETL.PopulateMeasures(page, accessToken, sqlConn, schema, until).Result;
}
}
}
| 39.515152 | 291 | 0.655675 | [
"MIT"
] | Bhaskers-Blu-Org2/BusinessPlatformApps | Functions/Code/Facebook/FacebookUtilityTest/Program.cs | 1,306 | C# |
using System;
using Sugar.Language.Parsing.Nodes.Enums;
namespace Sugar.Language.Parsing.Nodes.CtrlStatements
{
internal sealed class BreakNode : ControlStatement
{
public override NodeType NodeType => NodeType.Break;
public BreakNode()
{
}
public override string ToString() => $"Break Node";
}
}
| 18.684211 | 60 | 0.656338 | [
"MIT"
] | kokonut27/Sugar.lang | Sugar/Sugar.Language/Parsing/Nodes/CtrlStatements/BreakNode.cs | 357 | C# |
using System;
using Newtonsoft.Json;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// SpecEntity Data Structure.
/// </summary>
[Serializable]
public class SpecEntity : AlipayObject
{
/// <summary>
/// 新增不用传,修改必须传
/// </summary>
[JsonProperty("id")]
public string Id { get; set; }
/// <summary>
/// 门店ID
/// </summary>
[JsonProperty("shop_id")]
public string ShopId { get; set; }
/// <summary>
/// 规格名称
/// </summary>
[JsonProperty("spec_name")]
public string SpecName { get; set; }
/// <summary>
/// 是否为系统默认规格,同步时,默认为false,设置不生效,只有查询现实时用
/// </summary>
[JsonProperty("system")]
public bool System { get; set; }
}
}
| 22.513514 | 52 | 0.516206 | [
"MIT"
] | gebiWangshushu/payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/SpecEntity.cs | 931 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class CMSModules_DocumentTypes_Pages_Development_DocumentType_Edit_AllowedTypes {
/// <summary>
/// headParents control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.LocalizedHeading headParents;
/// <summary>
/// selParent control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMSAdminControls_UI_UniSelector_UniSelector selParent;
/// <summary>
/// headChildren control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.LocalizedHeading headChildren;
/// <summary>
/// uniSelector control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMSAdminControls_UI_UniSelector_UniSelector uniSelector;
}
| 32.58 | 96 | 0.589932 | [
"MIT"
] | BryanSoltis/KenticoMVCWidgetShowcase | CMS/CMSModules/DocumentTypes/Pages/Development/DocumentType_Edit_AllowedTypes.aspx.designer.cs | 1,631 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Nova.Pages.Configuration
{
/// <summary>
/// Lógica de interacción para UserRolPage.xaml
/// </summary>
public partial class UserRolPage : Page
{
string SelectedIndex = "";
public UserRolPage()
{
InitializeComponent();
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
//Start loading data
LoadData();
}
private async void LoadData()
{
//Set loading grid visibility
LoadingRolGrid.Visibility = Visibility.Visible;
RolSpinner.Spin = true;
IsEnabledControls(false);
//Refresh ROL list data
try
{
NovaAPI.APIRoles.userrols.Clear();
}
catch (Exception) { }
//Load rol data from API
bool RolData = await NovaAPI.APIRoles.GetValues("4", DataConfig.LocalAPI);
if (RolData)
{
//Set rol data to DataGrid
RolGrid.ItemsSource = NovaAPI.APIRoles.userrols;
RolGrid.Items.Refresh();
}
else
{
//Set loading grid visibility
LoadingRolGrid.Visibility = Visibility.Collapsed;
RolSpinner.Spin = false;
//On load error
MessageBox.Show($"Se produjo un error al cargar los datos, INFO: {Environment.NewLine}{NovaAPI.APIRoles.Message}");
RefreshBT.IsEnabled = true;
return;
}
await Task.Delay(100);
//Set loading grid visibility
LoadingRolGrid.Visibility = Visibility.Collapsed;
RolSpinner.Spin = false;
IsEnabledControls(true);
}
//Reset form data and visibility
private void ResetForm()
{
EditPermBT.IsEnabled = false;
RolNameTX.Clear();
RolDescriptTX.Clear();
SelectedIndex = "";
}
private void NewRolBT_Click(object sender, RoutedEventArgs e)
{
//From grid animation
if (FormGrid.Opacity == 0)
{
FormGrid.BeginStoryboard((Storyboard)Application.Current.TryFindResource("PopUpGrid"));
RolNameTX.Focus();
SaveBT.IsEnabled = true;
} else if(RolNameTX.Text.Length == 0)
{
FormGrid.BeginStoryboard((Storyboard)Application.Current.TryFindResource("FadeInGrid"));
SaveBT.IsEnabled = false;
}
//Clear rol values
if (RolNameTX.Text.Length > 0)
{
ResetForm();
}
}
private void EditRol_Click(object sender, RoutedEventArgs e)
{
//Get button control
Button Control = (Button)sender;
string rolid = NovaAPI.APIRoles.userrols.Find(x => x.rolid == Control.Tag.ToString()).rolid;
if (rolid == "1")
{
MessageBox.Show("No se puede editar el rol de administrador del sistema");
return;
}
if (FormGrid.Opacity == 0)
{
FormGrid.BeginStoryboard((Storyboard)Application.Current.TryFindResource("PopUpGrid"));
}
//Set rol information to controls
RolNameTX.Text = NovaAPI.APIRoles.userrols.Find(x => x.rolid == Control.Tag.ToString()).rolname;
RolDescriptTX.Text = NovaAPI.APIRoles.userrols.Find(x => x.rolid == Control.Tag.ToString()).roldescription;
EditPermBT.IsEnabled = true;
//Set selected rol id index for edition save
SelectedIndex = Control.Tag.ToString();
//Focus editable rol
RolNameTX.Focus();
SaveBT.IsEnabled = true;
}
private async void DeleteRol_Click(object sender, RoutedEventArgs e)
{
if (FormGrid.Opacity != 0)
{
ResetForm();
FormGrid.BeginStoryboard((Storyboard)Application.Current.TryFindResource("FadeInGrid"));
}
//Get button control
Button Control = (Button)sender;
//Get rol information
string rolname = NovaAPI.APIRoles.userrols.Find(x => x.rolid == Control.Tag.ToString()).rolname;
string rolid = NovaAPI.APIRoles.userrols.Find(x => x.rolid == Control.Tag.ToString()).rolid;
if (rolid == "1")
{
MessageBox.Show("No se puede eliminar el rol de administrador del sistema");
return;
}
if (MessageBox.Show($"A continuación se eliminara el rol '{rolname}{Environment.NewLine}¿Desea continuar?","Eliminar rol",MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
var Data = new rolData();
Data.id = rolid;
//Delete rol
string requestData = JsonConvert.SerializeObject(Data);
bool response = await NovaAPI.APIRoles.GetValues("3", DataConfig.LocalAPI, requestData);
if (response)
{
NovaAPI.APIRoles.userrols.Remove(NovaAPI.APIRoles.userrols.Find(x => x.rolid == rolid));
RolGrid.Items.Refresh();
} else
{
MessageBox.Show($"Error al eliminar el rol, INFO: {Environment.NewLine}{NovaAPI.APIRoles.Message}");
}
}
}
private async void SaveRolBT_Click(object sender, RoutedEventArgs e)
{
NewRolBT.Focus();
if (RolNameTX.Text.Length == 0 || RolNameTX.Text.Length < 5)
{
MessageBox.Show("El nombre del rol no puede estar en blanco o ser inferior a 5 caracteres");
RolNameTX.Focus();
return;
}
//Get rol parameters
var Data = new rolData();
Data.id = SelectedIndex;
Data.name = RolNameTX.Text;
Data.description = RolDescriptTX.Text;
//rol json data
string requestData = JsonConvert.SerializeObject(Data);
bool response;
//Modify / Create request
if (Data.id.Length > 0)
{
response = await NovaAPI.APIRoles.GetValues("2", DataConfig.LocalAPI, requestData);
} else
{
response = await NovaAPI.APIRoles.GetValues("1", DataConfig.LocalAPI, requestData);
}
//Request response
if (response)
{
if (Data.id.Length > 0)
{
//On role modified
NovaAPI.APIRoles.userrols.Find(x => x.rolid == Data.id).rolname = Data.name;
NovaAPI.APIRoles.userrols.Find(x => x.rolid == Data.id).roldescription = Data.description;
RolGrid.Items.Refresh();
FormGrid.BeginStoryboard((Storyboard)Application.Current.TryFindResource("FadeInGrid"));
ResetForm();
SaveBT.IsEnabled = false;
}
else
{
//On new rol created response
var newRol = new NovaAPI.APIRoles.Rols();
newRol.rolname = Data.name;
newRol.roldescription = Data.description;
newRol.rolid = NovaAPI.APIRoles.LastID;
newRol.usercount = "0";
//CREATE ROL DEFAULT PERMISSION DATA
FormGrid.BeginStoryboard((Storyboard)Application.Current.TryFindResource("FadeInGrid"));
ResetForm();
NovaAPI.APIRoles.userrols.Add(newRol);
//Reload rol data
LoadData();
SaveBT.IsEnabled = false;
}
}
else
{
MessageBox.Show($"Error al crear el rol, INFO: {Environment.NewLine}{NovaAPI.APIRoles.Message}");
}
}
private void RefreshBT_Click(object sender, RoutedEventArgs e)
{
if (FormGrid.Opacity == 1)
{
FormGrid.BeginStoryboard((Storyboard)Application.Current.TryFindResource("FadeInGrid"));
}
ResetForm();
LoadData();
SaveBT.IsEnabled = false;
}
private void IsEnabledControls(bool value)
{
if (value)
{
RefreshBT.IsEnabled = true;
NewRolBT.IsEnabled = true;
} else
{
RefreshBT.IsEnabled = false;
NewRolBT.IsEnabled = false;
}
}
//MoveFocus Function
private void MoveFocus(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
TraversalRequest tRequest = new TraversalRequest(FocusNavigationDirection.Next);
UIElement keyboardFocus = Keyboard.FocusedElement as UIElement;
if (keyboardFocus != null)
{
keyboardFocus.MoveFocus(tRequest);
}
e.Handled = true;
}
}
//ROL Edit permission
private void EditPermBT_Click(object sender, RoutedEventArgs e)
{
if (SelectedIndex != "")
{
TabControl.SetIsSelected(PermissionsTab, true);
}
}
//ROL data class
private class rolData {
public string id { get; set; }
public string name { get; set; }
public string description { get; set; }
}
#region Permissions tab
string RolID;
//Permissions Selected
private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.Source is TabControl)
{
if (PermissionsTab.IsSelected)
{
//Get rol index
string selection = SelectedIndex == "" ? "1" : SelectedIndex;
PermissionsGrid.IsEnabled = selection == "1" ? false : true; //Set disabled permission edit on administrator rol
PermissionsSaveBT.IsEnabled = selection == "1" ? false : true;
//Reset rol status form
PermissionsSaveBT.Background = (SolidColorBrush)Application.Current.TryFindResource("ConfigHeader");
FormGrid.BeginStoryboard((Storyboard)Application.Current.TryFindResource("FadeInGrid"));
ResetForm();
RolID = selection;
var Data = NovaAPI.APIRoles.userrols.Find(x => x.rolid == selection).RolData;
//Load permissions on selected rol or null rol
PermissionsGrid.ItemsSource = Data;
PermissionsGrid.Items.Refresh();
//Set rol name title
LabelTitle.Content = NovaAPI.APIRoles.userrols.Find(x => x.rolid == selection).rolname;
}
}
}
public class PermissionsModify
{
public string id { get; set; }
public object permissions { get; set; }
}
private async void PermissionsSaveBT_Click(object sender, RoutedEventArgs e)
{
PermissionsSaveBT.Background = (SolidColorBrush)Application.Current.TryFindResource("NormalBrush");
//Get permission data
var PermissionData = NovaAPI.APIRoles.userrols.Find(x => x.rolid == RolID).RolData;
//rol json data
PermissionsModify Modifier = new PermissionsModify()
{
id = RolID,
permissions = PermissionData
};
string requestData = JsonConvert.SerializeObject(Modifier);
//API Permission save
bool Response = await NovaAPI.APIPermissions.GetValues(null,"2", DataConfig.LocalAPI, requestData);
if (Response)
{
PermissionsSaveBT.Background = (SolidColorBrush)Application.Current.TryFindResource("PassBrush");
} else
{
PermissionsSaveBT.Background = (SolidColorBrush)Application.Current.TryFindResource("ErrorBrush");
MessageBox.Show($"Error al guardar la información de permisos, INFO:{Environment.NewLine}{NovaAPI.APIPermissions.Message}");
}
}
//Checks change status
private void Consult_Checked(object sender, RoutedEventArgs e)
{
var ConsultCheck = (CheckBox)sender;
var Parent = (StackPanel)VisualTreeHelper.GetParent(ConsultCheck);
MessageBox.Show(
NovaAPI.APIRoles.userrols.Find(x => x.rolid == RolID).RolData.Find(x => x.id == Convert.ToInt32(Parent.Tag.ToString())).permissions.create.ToString());
}
#endregion
private void Button_Click(object sender, RoutedEventArgs e)
{
var PermissionData = NovaAPI.APIRoles.userrols.Find(x => x.rolid == RolID).RolData;
for (int i = 0; i < PermissionData.Count; i++)
{
PermissionData[i].permissions.consult = ((Button)sender).Uid == "1" ? 1 : 0;
PermissionData[i].permissions.create = ((Button)sender).Uid == "1" ? 1 : 0;
PermissionData[i].permissions.delete = ((Button)sender).Uid == "1" ? 1 : 0;
}
PermissionsGrid.Items.Refresh();
}
}
}
| 33.537383 | 182 | 0.536157 | [
"MIT"
] | Lulzphantom/Nova-Pymes-Public | Nova/Pages/Configuration/UserRolPage.xaml.cs | 14,361 | C# |
using LuKaSo.Zonky.Models.Markets;
using System;
using System.Net.Http;
using System.Runtime.Serialization;
namespace LuKaSo.Zonky.Exceptions
{
[Serializable]
public class PrimaryMarketInvestmentException : Exception
{
/// <summary>
/// Primary market investment failed
/// The input is invalid.
/// Possible error codes are:
/// CAPTCHA_REQUIRED - Captcha verification is required
/// insufficientBalance - The user cannot invest because of a low wallet balance
/// cancelled - The loan has been canceled
/// withdrawn - The loan has been withdrawn by the borrower
/// reservedInvestmentOnly - The user cannot invest without a reservation. The whole remaining investment is reserved for other users.
/// overInvestment - The amount for investment is too high
/// multipleInvestment - The user has already invested to this loan. Try increasing the investment instead
/// alreadyCovered - The whole loan amount has been already covered
/// </summary>
/// <param name="investment"></param>
/// <param name="message"></param>
public PrimaryMarketInvestmentException(PrimaryMarketInvestment investment, HttpResponseMessage message) : base($"Buy primary market participation {investment.ToString()} failed \r\nServer return \r\n {message.ToString()} \r\n with content {message.Content.ReadAsStringAsync().GetAwaiter().GetResult()}")
{ }
/// <summary>
/// Primary market increase investment failed
/// The input is invalid.
/// Possible error codes are:
/// CAPTCHA_REQUIRED - Captcha verification is required
/// insufficientBalance - The user cannot invest because of a low wallet balance
/// cancelled - The loan has been canceled
/// withdrawn - The loan has been withdrawn by the borrower
/// reservedInvestmentOnly - The user cannot invest without a reservation. The whole remaining investment is reserved for other users.
/// overInvestment - The amount for investment is too high
/// multipleInvestment - The user has already invested to this loan. Try increasing the investment instead
/// alreadyCovered - The whole loan amount has been already covered
/// </summary>
/// <param name="investmentId"></param>
/// <param name="increaseInvestment"></param>
/// <param name="message"></param>
public PrimaryMarketInvestmentException(int investmentId, IncreasePrimaryMarketInvestment increaseInvestment, HttpResponseMessage message) : base($"Increase primary market participation id {investmentId} - {increaseInvestment.ToString()} failed \r\n Server return \r\n {message.ToString()} \r\n with content { message.Content.ReadAsStringAsync().GetAwaiter().GetResult()}")
{ }
protected PrimaryMarketInvestmentException(SerializationInfo info, StreamingContext context) : base(info, context)
{ }
}
}
| 57.884615 | 381 | 0.69402 | [
"MIT"
] | lkavale/LuKaSo.Zonky | src/LuKaSo.Zonky/Exceptions/PrimaryMarketInvestmentException.cs | 3,012 | C# |
using System;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Account;
namespace GrpcDemo.HttpApi.Client.ConsoleTestApp
{
public class ClientDemoService : ITransientDependency
{
private readonly IProfileAppService _profileAppService;
public ClientDemoService(IProfileAppService profileAppService)
{
_profileAppService = profileAppService;
}
public async Task RunAsync()
{
var output = await _profileAppService.GetAsync();
Console.WriteLine($"UserName : {output.UserName}");
Console.WriteLine($"Email : {output.Email}");
Console.WriteLine($"Name : {output.Name}");
Console.WriteLine($"Surname : {output.Surname}");
}
}
} | 30.923077 | 70 | 0.64801 | [
"MIT"
] | 271943794/abp-samples | GrpcDemo/test/GrpcDemo.HttpApi.Client.ConsoleTestApp/ClientDemoService.cs | 806 | C# |
using SlimDX;
using SlimDX.Direct3D11;
using SlimDX.DXGI;
using System;
using System.Drawing;
using Buffer = SlimDX.Direct3D11.Buffer;
using MapFlags = SlimDX.Direct3D11.MapFlags;
namespace MultiRes3d {
/// <summary>
/// Repräsentiert ein renderbares Progressive Mesh Objekt.
/// </summary>
public class PM : Entity, IDisposable {
bool disposed;
Buffer vertexBuffer, indexBuffer;
InputLayout inputLayout;
VertexBufferBinding vertexBufferBinding;
Viewport3d viewport3d;
Mesh mesh;
int numberOfSplits;
/// <summary>
/// Liefert die Anzahl der VertexSplit Einträge der PM.
/// </summary>
public int NumberOfSplits {
get {
return numberOfSplits;
}
}
/// <summary>
/// Der Index des zuletzt ausgeführten VertexSplits.
/// </summary>
public int CurrentSplit {
get {
return numberOfSplits - mesh.Splits.Count;
}
}
/// <summary>
/// Gibt den prozentualen "Fortschritt" der Progressive Mesh an.
/// </summary>
public double Progress {
get {
return NumberOfSplits == 0 ? 1.0 :
(CurrentSplit / (double) NumberOfSplits);
}
}
/// <summary>
/// Die momentane Anzahl der Vertices der Progressive Mesh.
/// </summary>
/// <remarks>
/// Die Angabe dieses Felds erhöht und vermindert sich entsprechend, wenn
/// der Detailgrad erhöht bzw. reduziert wird.
/// </remarks>
public int NumberOfVertices {
get {
return mesh.NumberOfVertices;
}
}
/// <summary>
/// Die momentane Anzahl der Facetten der Progressive Mesh.
/// </summary>
/// <remarks>
/// Die Angabe dieses Felds erhöht und vermindert sich entsprechend, wenn
/// der Detailgrad erhöht bzw. reduziert wird.
/// </remarks>
public int NumberOfFaces {
get {
return mesh.NumberOfFaces;
}
}
/// <summary>
/// Initialisiert eine neue Instanz der PM Klasse.
/// </summary>
/// <param name="viewport3d">
/// Das D3D11 Viewport3d Control für welche die Instanz erzeugt wird.
/// </param>
/// <param name="m">
/// Eine Mesh Instanz mit deren Daten die Progressiv Mesh initialisiert werden
/// soll.
/// </param>
public PM(Viewport3d viewport3d, Mesh m) : base() {
mesh = m;
numberOfSplits = mesh.Splits.Count;
this.viewport3d = viewport3d;
vertexBuffer = CreateVertexBuffer(m.Vertices.Length);
indexBuffer = CreateIndexBuffer(m.FlatFaces.Length);
inputLayout = CreateInputLayout();
vertexBufferBinding = new VertexBufferBinding(vertexBuffer, Vertex.Size, 0);
// Vertices und Indices in Grafikspeicher kopieren.
CopyData();
}
/// <summary>
/// "Entwickelt" die Progressive Mesh auf den angegebenen Prozentwert.
/// </summary>
/// <param name="percent">
/// Der Prozentwert auf den die Progressive Mesh entwickelt werden soll,
/// wobei 0.0 der Grundmesh entspricht und 1.0 der Mesh mit maximalem
/// Detailgrad.
/// </param>
public void ProgressTo(double percent) {
var delta = Math.Clamp(percent, 0, 1) - Progress;
var numOps = (int) numberOfSplits * Math.Abs(delta);
if (numOps == 0)
return;
for (int i = 0; i < numOps; i++) {
var r = delta > 0 ? mesh.PerformVertexSplit() :
mesh.PerformContraction();
if (!r)
break;
}
CopyData();
}
/// <summary>
/// Rendert die Instanz.
/// </summary>
/// <param name="context">
/// Der D3D11 Device Context.
/// </param>
/// <param name="effect">
/// Die Effekt Instanz zum Setzen der benötigten Shader Variablen.
/// </param>
public override void Render(DeviceContext context, BasicEffect effect) {
// D3D11 Input-Assembler konfigurieren.
ApplyRenderState(context, effect);
// Inhalt des Vertexbuffers rendern.
var tech = effect.ColorLitTech;
for (int i = 0; i < tech.Description.PassCount; i++) {
tech.GetPassByIndex(i).Apply(context);
context.DrawIndexed(mesh.NumberOfFaces * 3, 0, 0);
}
}
/// <summary>
/// Gibt die Resourcen der Instanz frei.
/// </summary>
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Gibt die Resourcen der Instanz frei.
/// </summary>
/// <param name="disposing">
/// true, um managed Resourcen freizugeben; andernfalls false.
/// </param>
protected virtual void Dispose(bool disposing) {
if (!disposed) {
// Merken, daß die Instanz freigegeben wurde.
disposed = true;
// Managed Resourcen freigeben.
if (disposing) {
if (vertexBuffer != null)
vertexBuffer.Dispose();
if (indexBuffer != null)
indexBuffer.Dispose();
if (inputLayout != null)
inputLayout.Dispose();
}
// Hier Unmanaged Resourcen freigeben.
}
}
/// <summary>
/// Kopiert die Vertices und Indices in den Videospeicher der Grafikkarte.
/// </summary>
void CopyData() {
// Vertexbuffer in Addressraum mappen.
var context = viewport3d.Context;
DataBox db = context.MapSubresource(vertexBuffer, MapMode.WriteDiscard,
MapFlags.None);
using (var ds = db.Data) {
ds.WriteRange<Vertex>(mesh.Vertices, 0, mesh.NumberOfVertices);
}
context.UnmapSubresource(vertexBuffer, 0);
// Indexbuffer in Addressraum mappen.
db = context.MapSubresource(indexBuffer, MapMode.WriteDiscard,
MapFlags.None);
using (var s = db.Data) {
s.WriteRange<uint>(mesh.FlatFaces, 0, mesh.NumberOfFaces * 3);
}
context.UnmapSubresource(indexBuffer, 0);
}
/// <summary>
/// Konfiguriert den InputAssembler des D3D11 Contexts, d.h. "verdrahtet"
/// die Vertex- u. Indexbuffer der PM so daß sie als Eingabe für die
/// Shader dienen.
/// </summary>
/// <param name="context">
/// Der D3D11 Context.
/// </param>
/// <param name="effect">
/// Die Effekt Instanz zum Setzen der benötigten Shader Variablen.
/// </param>
void ApplyRenderState(DeviceContext context, BasicEffect effect) {
context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
context.InputAssembler.InputLayout = inputLayout;
context.InputAssembler.SetVertexBuffers(0, vertexBufferBinding);
context.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0);
// Grundfarbe, die als Eingabewert bei der Lichtberechnung benutzt wird.
effect.SetColor(Color.Gray);
}
#region D3D11 Initialisierungen
/// <summary>
/// Erstellt den Vertexbuffer für die Vertex-Daten der Mesh.
/// </summary>
/// <param name="maxVertices">
/// Die max. Anzahl an Vertices, die im Buffer gespeichert werden sollen.
/// </param>
/// <returns>
/// Eine initialisierte Instanz der Buffer-Klasse, die den VertexBuffer
/// repräsentiert.
/// </returns>
Buffer CreateVertexBuffer(int maxVertices) {
var desc = new BufferDescription(Vertex.Size * maxVertices,
ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write,
ResourceOptionFlags.None, 0);
return new Buffer(viewport3d.Device, desc);
}
/// <summary>
/// Erstellt den Indexbuffer für die Indices der Facetten der Mesh.
/// </summary>
/// <param name="maxIndices">
/// Die max. Anzahl an Indices, die im Buffer gespeichert werden sollen.
/// </param>
/// <returns>
/// Eine initialisierte Instanz der Buffer-Klasse, die den IndexBuffer
/// repräsentiert.
/// </returns>
Buffer CreateIndexBuffer(int maxIndices) {
var desc = new BufferDescription(sizeof(uint) * maxIndices,
ResourceUsage.Dynamic, BindFlags.IndexBuffer, CpuAccessFlags.Write,
ResourceOptionFlags.None, 0);
return new Buffer(viewport3d.Device, desc);
}
/// <summary>
/// Erstellt das Input-Layout für den Input-Assembler.
/// </summary>
/// <returns>
/// Das Input-Layout.
/// </returns>
InputLayout CreateInputLayout() {
// Pro-Vertex Daten im Vertexbuffer.
var elements = new[] {
new InputElement("Position", 0, Format.R32G32B32_Float, 0, 0,
InputClassification.PerVertexData, 0),
new InputElement("Normal", 0, Format.R32G32B32_Float, 4 * 3, 0,
InputClassification.PerVertexData, 0)
};
// Input-Layout wird gegen die Signatur der Shader-Technique geprüft, um
// sicherzustellen, daß unsere Datenstruktur und die struct im Shader/Effect
// übereinstimmen.
var sig = viewport3d.Effect.ColorLitTech.GetPassByIndex(0).Description.Signature;
return new InputLayout(viewport3d.Device, sig, elements);
}
#endregion
}
}
| 30.555147 | 84 | 0.680183 | [
"MIT"
] | qwert9001/MultiRes3d | MultiRes3d/Datastructures/PM.cs | 8,334 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AcademyRPG
{
class Program
{
static Engine GetEngineInstance()
{
return new ExtendedEngine();
}
static void Main(string[] args)
{
//using (var sw = new StreamWriter("../../test.out.txt"))
//{
// Console.SetOut(sw);
Engine engine = GetEngineInstance();
string command = Console.ReadLine();
while (command != "end")
{
engine.ExecuteCommand(command);
command = Console.ReadLine();
}
//}
}
}
}
| 22.771429 | 69 | 0.484316 | [
"MIT"
] | evlogihr/TelerikAcademy-Exercises | Workshop-OOP-ExamPrep/AcademyRPG/Program.cs | 799 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Framework.Core
{
/// <summary>
/// Providers Extension Methods that are a special kind of static method,
/// but they are called as if they were instance methods on the extended type.
/// </summary>
public static partial class Extensions
{
#region| Methods |
#endregion
}
}
| 20 | 83 | 0.666667 | [
"MIT"
] | juninhodigital/Framework.Core | Framework.Core/Extensions/Extensions.File.cs | 422 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Xml.Linq;
using ClientDependency.Core.CompositeFiles.Providers;
using ClientDependency.Core.Config;
using Semver;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
namespace Umbraco.Core.Configuration
{
/// <summary>
/// A utility class for working with CDF config and cache files - use sparingly!
/// </summary>
public class ClientDependencyConfiguration
{
private readonly ILogger _logger;
private readonly string _fileName;
public ClientDependencyConfiguration(ILogger logger)
{
if (logger == null) throw new ArgumentNullException("logger");
_logger = logger;
_fileName = IOHelper.MapPath(string.Format("{0}/ClientDependency.config", SystemDirectories.Config));
}
/// <summary>
/// Changes the version number in ClientDependency.config to a hashed value for the version and the DateTime.Day
/// </summary>
/// <param name="version">The <see cref="SemVersion">version</see> of Umbraco we're upgrading to</param>
/// <param name="date">A <see cref="DateTime">date</see> value to use in the hash to prevent this method from updating the version on each startup</param>
/// <param name="dateFormat">Allows the developer to specify the <see cref="string">date precision</see> for the hash (i.e. "yyyyMMdd" would be a precision for the day)</param>
/// <returns>Boolean to indicate succesful update of the ClientDependency.config file</returns>
public bool UpdateVersionNumber(SemVersion version, DateTime date, string dateFormat)
{
var byteContents = Encoding.Unicode.GetBytes(version + date.ToString(dateFormat));
//This is a way to convert a string to a long
//see https://www.codeproject.com/Articles/34309/Convert-String-to-bit-Integer
//We could much more easily use MD5 which would create us an INT but since that is not compliant with
//hashing standards we have to use SHA
int intHash;
using (var hash = SHA256.Create())
{
var bytes = hash.ComputeHash(byteContents);
var longResult = new[] { 0, 8, 16, 24 }
.Select(i => BitConverter.ToInt64(bytes, i))
.Aggregate((x, y) => x ^ y);
//CDF requires an INT, and although this isn't fail safe, it will work for our purposes. We are not hashing for crypto purposes
//so there could be some collisions with this conversion but it's not a problem for our purposes
//It's also important to note that the long.GetHashCode() implementation in .NET is this: return (int) this ^ (int) (this >> 32);
//which means that this value will not change per appdomain like some GetHashCode implementations.
intHash = longResult.GetHashCode();
}
try
{
var clientDependencyConfigXml = XDocument.Load(_fileName, LoadOptions.PreserveWhitespace);
if (clientDependencyConfigXml.Root != null)
{
var versionAttribute = clientDependencyConfigXml.Root.Attribute("version");
//Set the new version to the hashcode of now
var oldVersion = versionAttribute.Value;
var newVersion = Math.Abs(intHash).ToString();
//don't update if it's the same version
if (oldVersion == newVersion)
return false;
versionAttribute.SetValue(newVersion);
clientDependencyConfigXml.Save(_fileName, SaveOptions.DisableFormatting);
_logger.Info<ClientDependencyConfiguration>(string.Format("Updated version number from {0} to {1}", oldVersion, newVersion));
return true;
}
}
catch (Exception ex)
{
_logger.Error<ClientDependencyConfiguration>("Couldn't update ClientDependency version number", ex);
}
return false;
}
/// <summary>
/// Changes the version number in ClientDependency.config to a random value to avoid stale caches
/// </summary>
/// <seealso cref="UpdateVersionNumber(SemVersion, DateTime, string)" />
[Obsolete("Use the UpdateVersionNumber method specifying the version, date and dateFormat instead")]
public bool IncreaseVersionNumber()
{
try
{
var clientDependencyConfigXml = XDocument.Load(_fileName, LoadOptions.PreserveWhitespace);
if (clientDependencyConfigXml.Root != null)
{
var versionAttribute = clientDependencyConfigXml.Root.Attribute("version");
//Set the new version to the hashcode of now
var oldVersion = versionAttribute.Value;
var newVersion = Math.Abs(DateTime.UtcNow.GetHashCode());
versionAttribute.SetValue(newVersion);
clientDependencyConfigXml.Save(_fileName, SaveOptions.DisableFormatting);
_logger.Info<ClientDependencyConfiguration>(string.Format("Updated version number from {0} to {1}", oldVersion, newVersion));
return true;
}
}
catch (Exception ex)
{
_logger.Error<ClientDependencyConfiguration>("Couldn't update ClientDependency version number", ex);
}
return false;
}
/// <summary>
/// Clears the temporary files stored for the ClientDependency folder
/// </summary>
/// <param name="currentHttpContext"></param>
public bool ClearTempFiles(HttpContextBase currentHttpContext)
{
var cdfTempDirectories = new HashSet<string>();
foreach (BaseCompositeFileProcessingProvider provider in ClientDependencySettings.Instance
.CompositeFileProcessingProviderCollection)
{
var path = provider.CompositeFilePath.FullName;
cdfTempDirectories.Add(path);
}
try
{
var fullPath = currentHttpContext.Server.MapPath(XmlFileMapper.FileMapVirtualFolder);
if (fullPath != null)
{
cdfTempDirectories.Add(fullPath);
}
}
catch (Exception ex)
{
//invalid path format or something... try/catch to be safe
LogHelper.Error<ClientDependencyConfiguration>("Could not get path from ClientDependency.config", ex);
}
var success = true;
foreach (var directory in cdfTempDirectories)
{
var directoryInfo = new DirectoryInfo(directory);
if (directoryInfo.Exists == false)
continue;
try
{
directoryInfo.Delete(true);
}
catch (Exception ex)
{
// Something could be locking the directory or the was another error, making sure we don't break the upgrade installer
LogHelper.Error<ClientDependencyConfiguration>("Could not clear temp files", ex);
success = false;
}
}
return success;
}
}
}
| 44.312849 | 185 | 0.578669 | [
"MIT"
] | AzzA-D/Umbraco-CMS | src/Umbraco.Core/Configuration/ClientDependencyConfiguration.cs | 7,934 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using NowPlayingV2.Updater;
namespace NowPlayingV2.UI
{
public partial class VersionInfoUI : UserControl
{
public VersionInfoUI()
{
InitializeComponent();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
var asm = System.Reflection.Assembly.GetExecutingAssembly();
var ver = asm.GetName().Version.ToString();
var builddate = Matsuri.BuildDate.GetBuildDateTime(asm).ToString("R");
VersionLabel.Content = $"Version: {ver}\nBuildDate: {builddate}";
}
private async void CheckUpdateButton_Click(object sender, RoutedEventArgs e)
{
try
{
CheckUpdateButton.Content = "アップデートを確認しています.....";
var vc = await VersionClass.GetUpdaterAsync();
if (vc.IsUpdateAvaliable())
{
//show updater screen
CheckUpdateButton.Content = "\u203Cアップデートが利用可能です";
CheckUpdateButton.Background =
new SolidColorBrush((Color) ColorConverter.ConvertFromString("#f5ad3b"));
//get parent Window
var window = Matsuri.SeaSlug.GetAncestorOfType<MetroWindow>(sender as Button);
var diagret = await window.ShowMessageAsync($"バージョン{vc.AppVersion}が利用可能です",
$"{vc.UpdateMessage}\n\nアップデートページを開きますか?", MessageDialogStyle.AffirmativeAndNegative);
if (diagret == MessageDialogResult.Affirmative)
{
Process.Start(vc.UpdateNotifyUrl);
}
}
else
{
//change text
CheckUpdateButton.Content = "\u2714最新版をご利用です";
CheckUpdateButton.Background =
new SolidColorBrush((Color) ColorConverter.ConvertFromString("#5abfb7"));
}
}
catch (Exception ex)
{
CheckUpdateButton.Content = "\u274Cアップデートを確認できませんでした";
CheckUpdateButton.Background =
new SolidColorBrush((Color) ColorConverter.ConvertFromString("#d7385f"));
Trace.WriteLine($"[UpdateChecker]Could not check update.(Err={ex.Message})");
}
}
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
}
}
} | 38.2875 | 110 | 0.594842 | [
"MIT"
] | WinterMagician-2ZGRG/NowPlayingV2 | NowPlayingV2/UI/VersionInfoUI.xaml.cs | 3,227 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq.Expressions;
using System.Threading.Tasks;
using AntDesign.Forms;
using AntDesign.Internal;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
namespace AntDesign
{
/// <summary>
/// Base class for any input control that optionally supports an <see cref="EditContext"/>.
/// reference:https://github.com/dotnet/aspnetcore/blob/master/src/Components/Web/src/Forms/InputBase.cs
/// </summary>
/// <typeparam name="TValue">the natural type of the input's value</typeparam>
public abstract class AntInputComponentBase<TValue> : AntDomComponentBase, IControlValueAccessor
{
private readonly EventHandler<ValidationStateChangedEventArgs> _validationStateChangedHandler;
private bool _previousParsingAttemptFailed;
private ValidationMessageStore _parsingValidationMessages;
private Type _nullableUnderlyingType;
[CascadingParameter(Name = "FormItem")]
private IFormItem FormItem { get; set; }
[CascadingParameter(Name = "Form")]
protected IForm Form { get; set; }
public string[] ValidationMessages { get; set; } = Array.Empty<string>();
private string _formSize;
[CascadingParameter(Name = "FormSize")]
public string FormSize
{
get
{
return _formSize;
}
set
{
_formSize = value;
Size = value;
}
}
/// <summary>
/// Gets or sets a collection of additional attributes that will be applied to the created element.
/// </summary>
[Parameter(CaptureUnmatchedValues = true)]
public IReadOnlyDictionary<string, object> AdditionalAttributes { get; set; }
private TValue _value;
/// <summary>
/// Gets or sets the value of the input. This should be used with two-way binding.
/// </summary>
/// <example>
/// @bind-Value="model.PropertyName"
/// </example>
[Parameter]
public TValue Value
{
get { return _value; }
set
{
var hasChanged = !EqualityComparer<TValue>.Default.Equals(value, Value);
if (hasChanged)
{
_value = value;
OnValueChange(value);
}
}
}
/// <summary>
/// Gets or sets a callback that updates the bound value.
/// </summary>
[Parameter]
public EventCallback<TValue> ValueChanged { get; set; }
/// <summary>
/// Gets or sets an expression that identifies the bound value.
/// </summary>
[Parameter]
public Expression<Func<TValue>> ValueExpression { get; set; }
[Parameter]
public string Size { get; set; } = AntSizeLDSType.Default;
/// <summary>
/// Gets the associated <see cref="EditContext"/>.
/// </summary>
protected EditContext EditContext { get; set; }
/// <summary>
/// Gets the <see cref="FieldIdentifier"/> for the bound value.
/// </summary>
internal FieldIdentifier FieldIdentifier { get; set; }
/// <summary>
/// Gets or sets the current value of the input.
/// </summary>
protected TValue CurrentValue
{
get => Value;
set
{
var hasChanged = !EqualityComparer<TValue>.Default.Equals(value, Value);
if (hasChanged)
{
Value = value;
ValueChanged.InvokeAsync(value);
if (_isNotifyFieldChanged)
{
EditContext?.NotifyFieldChanged(FieldIdentifier);
}
}
}
}
/// <summary>
/// Gets or sets the current value of the input, represented as a string.
/// </summary>
protected string CurrentValueAsString
{
get => FormatValueAsString(CurrentValue);
set
{
_parsingValidationMessages?.Clear();
bool parsingFailed;
if (_nullableUnderlyingType != null && string.IsNullOrEmpty(value))
{
// Assume if it's a nullable type, null/empty inputs should correspond to default(T)
// Then all subclasses get nullable support almost automatically (they just have to
// not reject Nullable<T> based on the type itself).
parsingFailed = false;
CurrentValue = default;
}
else if (TryParseValueFromString(value, out var parsedValue, out var validationErrorMessage))
{
parsingFailed = false;
CurrentValue = parsedValue;
}
else
{
parsingFailed = true;
if (EditContext != null)
{
if (_parsingValidationMessages == null)
{
_parsingValidationMessages = new ValidationMessageStore(EditContext);
}
_parsingValidationMessages.Add(FieldIdentifier, validationErrorMessage);
// Since we're not writing to CurrentValue, we'll need to notify about modification from here
EditContext.NotifyFieldChanged(FieldIdentifier);
}
}
// We can skip the validation notification if we were previously valid and still are
if ((parsingFailed || _previousParsingAttemptFailed) && EditContext != null)
{
EditContext.NotifyValidationStateChanged();
_previousParsingAttemptFailed = parsingFailed;
}
}
}
private TValue _firstValue;
private bool _isNotifyFieldChanged = true;
/// <summary>
/// Constructs an instance of <see cref="InputBase{TValue}"/>.
/// </summary>
protected AntInputComponentBase()
{
_validationStateChangedHandler = (sender, eventArgs) => StateHasChanged();
}
/// <summary>
/// Formats the value as a string. Derived classes can override this to determine the formating used for <see cref="CurrentValueAsString"/>.
/// </summary>
/// <param name="value">The value to format.</param>
/// <returns>A string representation of the value.</returns>
protected virtual string FormatValueAsString(TValue value)
=> value?.ToString();
/// <summary>
/// Parses a string to create an instance of <typeparamref name="TValue"/>. Derived classes can override this to change how
/// <see cref="CurrentValueAsString"/> interprets incoming values.
/// </summary>
/// <param name="value">The string value to be parsed.</param>
/// <param name="result">An instance of <typeparamref name="TValue"/>.</param>
/// <param name="validationErrorMessage">If the value could not be parsed, provides a validation error message.</param>
/// <returns>True if the value could be parsed; otherwise false.</returns>
protected virtual bool TryParseValueFromString(string value, out TValue result, out string validationErrorMessage)
{
var success = BindConverter.TryConvertTo<TValue>(
value, CultureInfo.CurrentCulture, out var parsedValue);
if (success)
{
result = parsedValue;
validationErrorMessage = null;
return true;
}
else
{
result = default;
validationErrorMessage = $"{FieldIdentifier.FieldName} field isn't valid.";
return false;
}
}
protected virtual void OnValueChange(TValue value)
{
}
protected override void OnInitialized()
{
base.OnInitialized();
FormItem?.AddControl(this);
Form?.AddControl(this);
_firstValue = Value;
}
/// <inheritdoc />
public override Task SetParametersAsync(ParameterView parameters)
{
parameters.SetParameterProperties(this);
if (EditContext == null)
{
// This is the first run
// Could put this logic in OnInit, but its nice to avoid forcing people who override OnInit to call base.OnInit()
if (Form?.EditContext == null)
{
return base.SetParametersAsync(ParameterView.Empty);
}
if (ValueExpression == null)
{
return base.SetParametersAsync(ParameterView.Empty);
}
EditContext = Form?.EditContext;
FieldIdentifier = FieldIdentifier.Create(ValueExpression);
_nullableUnderlyingType = Nullable.GetUnderlyingType(typeof(TValue));
EditContext.OnValidationStateChanged += _validationStateChangedHandler;
}
else if (Form?.EditContext != EditContext)
{
// Not the first run
// We don't support changing EditContext because it's messy to be clearing up state and event
// handlers for the previous one, and there's no strong use case. If a strong use case
// emerges, we can consider changing this.
throw new InvalidOperationException($"{GetType()} does not support changing the " +
$"{nameof(EditContext)} dynamically.");
}
// For derived components, retain the usual lifecycle with OnInit/OnParametersSet/etc.
return base.SetParametersAsync(ParameterView.Empty);
}
protected override void Dispose(bool disposing)
{
if (EditContext != null)
{
EditContext.OnValidationStateChanged -= _validationStateChangedHandler;
}
base.Dispose(disposing);
}
internal void ResetValue()
{
_isNotifyFieldChanged = false;
CurrentValue = _firstValue;
_isNotifyFieldChanged = true;
}
void IControlValueAccessor.Reset()
{
ResetValue();
}
}
}
| 35.496711 | 148 | 0.554722 | [
"MIT"
] | BlazorHub/ant-design-blazor | components/core/Base/AntInputComponentBase.cs | 10,793 | C# |
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype;
namespace Content.Server.Construction.Components
{
/// <summary>
/// Used for construction graphs in building computers.
/// </summary>
[RegisterComponent]
public sealed class ComputerBoardComponent : Component
{
[ViewVariables]
[DataField("prototype", customTypeSerializer:typeof(PrototypeIdSerializer<EntityPrototype>))]
public string? Prototype { get; private set; }
}
}
| 32 | 101 | 0.727941 | [
"MIT"
] | 14th-Batallion-Marine-Corps/14-Marine-Corps | Content.Server/Construction/Components/ComputerBoardComponent.cs | 546 | C# |
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Umbrella.Utilities.Encryption.Abstractions;
using Umbrella.Utilities.Extensions;
namespace Umbrella.Utilities.Encryption
{
//TODO: Add support for special chars, e.g. !@#$!&
public class SecureStringGenerator : ISecureStringGenerator
{
#region Private Static Members
private static readonly char[] m_LowerCaseLettersArray = new char[26]
{
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
};
private static readonly char[] m_UpperCaseLettersArray = m_LowerCaseLettersArray.Select(x => char.ToUpperInvariant(x)).ToArray();
#endregion
#region Private Members
private readonly ILogger Log;
#endregion
#region Constructors
public SecureStringGenerator(ILogger<SecureStringGenerator> logger)
{
Log = logger;
}
#endregion
#region IPasswordGenerator Members
public string Generate(int length = 8, int numbers = 1, int upperCaseLetters = 1)
{
try
{
// TODO: Replace these checks with new Guard statements. Move outside try...catch.
if (length < 1)
throw new ArgumentOutOfRangeException(nameof(length), "Must be greater than or equal to 1.");
if (numbers < 0)
throw new ArgumentOutOfRangeException(nameof(numbers), "Must be greater than or equal to 0.");
if (numbers > length)
throw new ArgumentOutOfRangeException(nameof(numbers), "Must be less than or equal to length.");
if (upperCaseLetters < 0)
throw new ArgumentOutOfRangeException(nameof(upperCaseLetters), "Must be greater than or equal to 0.");
if (upperCaseLetters > length)
throw new ArgumentOutOfRangeException(nameof(upperCaseLetters), "Must be less than or equal to length.");
if (numbers + upperCaseLetters > length)
throw new ArgumentOutOfRangeException($"{nameof(numbers)}, {nameof(upperCaseLetters)}", $"The sum of the {nameof(numbers)} and the {nameof(upperCaseLetters)} arguments is greater than the length.");
Span<char> password = stackalloc char[length];
int lowerCaseLettersLength = length - numbers - upperCaseLetters;
// TODO: Make the RNG provider a class member, implement IDisposable to clean it up, use RandomNumberGenerator class instead.
// Call RandomNumberGenerator.Create()
// We are building up a string here starting with lowercase letters, followed by uppercase and finally numbers.
using (RNGCryptoServiceProvider rngProvider = new RNGCryptoServiceProvider())
{
int idx = 0;
while (idx < lowerCaseLettersLength)
{
int index = GenerateRandomInteger(rngProvider, 0, 26);
char letter = m_LowerCaseLettersArray[index];
password[idx++] = letter;
}
while (idx < length - numbers)
{
int index = GenerateRandomInteger(rngProvider, 0, 26);
char letter = m_UpperCaseLettersArray[index];
password[idx++] = letter;
}
while (idx < length)
{
int number = GenerateRandomInteger(rngProvider, 0, 10);
password[idx++] = number.ToString()[0];
}
// Randomly shuffle the generated password
int n = password.Length;
while (n > 1)
{
int k = GenerateRandomInteger(rngProvider, 0, n--);
char temp = password[n];
password[n] = password[k];
password[k] = temp;
}
}
return password.ToString();
}
catch (Exception exc) when (Log.WriteError(exc, new { length, numbers }))
{
throw;
}
}
#if !AzureDevOps
[Obsolete]
[EditorBrowsable(EditorBrowsableState.Advanced)]
internal string GenerateOld(int length = 8, int numbers = 1, int upperCaseLetters = 1)
{
try
{
if (length < 1)
throw new ArgumentOutOfRangeException(nameof(length), "Must be greater than or equal to 1.");
if (numbers < 0)
throw new ArgumentOutOfRangeException(nameof(numbers), "Must be greater than or equal to 0.");
if (numbers > length)
throw new ArgumentOutOfRangeException(nameof(numbers), "Must be less than or equal to length.");
if (upperCaseLetters < 0)
throw new ArgumentOutOfRangeException(nameof(upperCaseLetters), "Must be greater than or equal to 0.");
if (upperCaseLetters > length)
throw new ArgumentOutOfRangeException(nameof(upperCaseLetters), "Must be less than or equal to length.");
if (numbers + upperCaseLetters > length)
throw new ArgumentOutOfRangeException($"{nameof(numbers)}, {nameof(upperCaseLetters)}", $"The sum of the {nameof(numbers)} and the {nameof(upperCaseLetters)} arguments is greater than the length.");
char[] password = new char[length];
int lowerCaseLettersLength = length - numbers - upperCaseLetters;
// We are building up a string here starting with lowercase letters, followed by uppercase and finally numbers.
using (RNGCryptoServiceProvider rngProvider = new RNGCryptoServiceProvider())
{
int idx = 0;
while (idx < lowerCaseLettersLength)
{
int index = GenerateRandomInteger(rngProvider, 0, 26);
char letter = m_LowerCaseLettersArray[index];
password[idx++] = letter;
}
while (idx < length - numbers)
{
int index = GenerateRandomInteger(rngProvider, 0, 26);
char letter = m_UpperCaseLettersArray[index];
password[idx++] = letter;
}
while (idx < length)
{
int number = GenerateRandomInteger(rngProvider, 0, 10);
password[idx++] = number.ToString().ToCharArray()[0];
}
// Randomly shuffle the generated password
int n = password.Length;
while (n > 1)
{
int k = GenerateRandomInteger(rngProvider, 0, n--);
char temp = password[n];
password[n] = password[k];
password[k] = temp;
}
}
return new string(password);
}
catch (Exception exc) when (Log.WriteError(exc, new { length, numbers }))
{
throw;
}
}
#endif
#endregion
#region Private Members
private int GenerateRandomInteger(RNGCryptoServiceProvider provider, int min, int max)
{
uint scale = uint.MaxValue;
while (scale == uint.MaxValue)
{
// TODO: Could use ArrayPool here.
// Get four random bytes.
byte[] four_bytes = new byte[4];
provider.GetBytes(four_bytes);
// Convert that into an uint.
scale = BitConverter.ToUInt32(four_bytes, 0);
}
// Add min to the scaled difference between max and min.
return (int)(min + (max - min) *
(scale / (double)uint.MaxValue));
}
#endregion
}
} | 40.089623 | 218 | 0.530298 | [
"MIT"
] | Zinofi/umbrella | Core/src/Umbrella.Utilities/Encryption/SecureStringGenerator.cs | 8,501 | C# |
using UnityEngine.Audio;
using UnityEngine;
[System.Serializable]
public class Sound {
public string name;
public AudioClip clip;
[Range(0f,1f)]
public float volume;
[Range(.1f,3f)]
public float pitch;
public bool loop;
[HideInInspector]
public AudioSource source;
}
| 9.8 | 28 | 0.710884 | [
"Apache-2.0"
] | Muhammad-Taimur/Dangerous-Lane-3D-Game | Assets/Sound.cs | 296 | 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 redshift-2012-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Redshift.Model
{
/// <summary>
/// Request would exceed the user's compute node quota. For information about increasing
/// your quota, go to <a href="https://docs.aws.amazon.com/redshift/latest/mgmt/amazon-redshift-limits.html">Limits
/// in Amazon Redshift</a> in the <i>Amazon Redshift Cluster Management Guide</i>.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public partial class ReservedNodeQuotaExceededException : AmazonRedshiftException
{
/// <summary>
/// Constructs a new ReservedNodeQuotaExceededException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public ReservedNodeQuotaExceededException(string message)
: base(message) {}
/// <summary>
/// Construct instance of ReservedNodeQuotaExceededException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public ReservedNodeQuotaExceededException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of ReservedNodeQuotaExceededException
/// </summary>
/// <param name="innerException"></param>
public ReservedNodeQuotaExceededException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of ReservedNodeQuotaExceededException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public ReservedNodeQuotaExceededException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of ReservedNodeQuotaExceededException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public ReservedNodeQuotaExceededException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the ReservedNodeQuotaExceededException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected ReservedNodeQuotaExceededException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
} | 49.190476 | 178 | 0.688448 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/Redshift/Generated/Model/ReservedNodeQuotaExceededException.cs | 6,198 | C# |
using ChocolArm64.Decoders;
using ChocolArm64.IntermediateRepresentation;
using ChocolArm64.State;
using ChocolArm64.Translation;
using System;
using System.Reflection.Emit;
namespace ChocolArm64.Instructions
{
static class InstEmit32Helper
{
public static bool IsThumb(OpCode64 op)
{
return op is OpCodeT16;
}
public static void EmitLoadFromRegister(ILEmitterCtx context, int register)
{
if (register == RegisterAlias.Aarch32Pc)
{
OpCode32 op = (OpCode32)context.CurrOp;
context.EmitLdc_I4((int)op.GetPc());
}
else
{
context.EmitLdint(InstEmit32Helper.GetRegisterAlias(context.Mode, register));
}
}
public static void EmitStoreToRegister(ILEmitterCtx context, int register)
{
if (register == RegisterAlias.Aarch32Pc)
{
context.EmitStoreContext();
EmitBxWritePc(context);
}
else
{
context.EmitStint(GetRegisterAlias(context.Mode, register));
}
}
public static void EmitBxWritePc(ILEmitterCtx context)
{
context.Emit(OpCodes.Dup);
context.EmitLdc_I4(1);
context.Emit(OpCodes.And);
context.Emit(OpCodes.Dup);
context.EmitStflg((int)PState.TBit);
ILLabel lblArmMode = new ILLabel();
ILLabel lblEnd = new ILLabel();
context.Emit(OpCodes.Brtrue_S, lblArmMode);
context.EmitLdc_I4(~1);
context.Emit(OpCodes.Br_S, lblEnd);
context.MarkLabel(lblArmMode);
context.EmitLdc_I4(~3);
context.MarkLabel(lblEnd);
context.Emit(OpCodes.And);
context.Emit(OpCodes.Conv_U8);
context.Emit(OpCodes.Ret);
}
public static int GetRegisterAlias(Aarch32Mode mode, int register)
{
//Only registers >= 8 are banked, with registers in the range [8, 12] being
//banked for the FIQ mode, and registers 13 and 14 being banked for all modes.
if ((uint)register < 8)
{
return register;
}
return GetBankedRegisterAlias(mode, register);
}
public static int GetBankedRegisterAlias(Aarch32Mode mode, int register)
{
switch (register)
{
case 8: return mode == Aarch32Mode.Fiq
? RegisterAlias.R8Fiq
: RegisterAlias.R8Usr;
case 9: return mode == Aarch32Mode.Fiq
? RegisterAlias.R9Fiq
: RegisterAlias.R9Usr;
case 10: return mode == Aarch32Mode.Fiq
? RegisterAlias.R10Fiq
: RegisterAlias.R10Usr;
case 11: return mode == Aarch32Mode.Fiq
? RegisterAlias.R11Fiq
: RegisterAlias.R11Usr;
case 12: return mode == Aarch32Mode.Fiq
? RegisterAlias.R12Fiq
: RegisterAlias.R12Usr;
case 13:
switch (mode)
{
case Aarch32Mode.User:
case Aarch32Mode.System: return RegisterAlias.SpUsr;
case Aarch32Mode.Fiq: return RegisterAlias.SpFiq;
case Aarch32Mode.Irq: return RegisterAlias.SpIrq;
case Aarch32Mode.Supervisor: return RegisterAlias.SpSvc;
case Aarch32Mode.Abort: return RegisterAlias.SpAbt;
case Aarch32Mode.Hypervisor: return RegisterAlias.SpHyp;
case Aarch32Mode.Undefined: return RegisterAlias.SpUnd;
default: throw new ArgumentException(nameof(mode));
}
case 14:
switch (mode)
{
case Aarch32Mode.User:
case Aarch32Mode.Hypervisor:
case Aarch32Mode.System: return RegisterAlias.LrUsr;
case Aarch32Mode.Fiq: return RegisterAlias.LrFiq;
case Aarch32Mode.Irq: return RegisterAlias.LrIrq;
case Aarch32Mode.Supervisor: return RegisterAlias.LrSvc;
case Aarch32Mode.Abort: return RegisterAlias.LrAbt;
case Aarch32Mode.Undefined: return RegisterAlias.LrUnd;
default: throw new ArgumentException(nameof(mode));
}
default: throw new ArgumentOutOfRangeException(nameof(register));
}
}
}
}
| 33.414966 | 93 | 0.525448 | [
"Unlicense"
] | huangweiboy/Ryujinx | ChocolArm64/Instructions/InstEmit32Helper.cs | 4,912 | 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("WeatherController")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("WeatherController")]
[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("3c90bd30-ebe0-4f45-96cb-387237451fe2")]
// 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.513514 | 84 | 0.750175 | [
"MIT"
] | arunsatyarth/SimpleWeatherApp | WeatherController/Properties/AssemblyInfo.cs | 1,428 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
namespace CaboodleES.Utils
{
/// <summary>
/// Table collection
/// </summary>
/// <typeparam name="T"></typeparam>
public class Table<T>
{
private T[] elements;
private int count;
public int Count { get { return count; } }
public Table()
{
elements = new T[32];
this.count = 0;
}
public T Get(int i)
{
if (i > elements.Length - 1) return default(T);
return elements[i];
}
public void Set(int i, T element)
{
if(i > elements.Length - 1)
{
Grow(i);
}
count++;
elements[i] = element;
}
public bool Has(int i)
{
if (i >= elements.Length) return false;
return elements[i] != null;
}
public void Remove(int i)
{
if (elements[i] != null)
{
elements[i] = default(T);
count--;
}
}
public void Clear()
{
elements = new T[32];
count = 0;
}
private void Grow(int min)
{
int mult = 2;
while((elements.Length * mult) < min)
mult += 2;
var old = elements;
elements = new T[elements.Length * mult];
Array.Copy(old, elements, old.Length);
}
}
}
| 21.121622 | 59 | 0.427383 | [
"MIT"
] | HellFire13/CaboodleES | CaboodleES/Source/CaboodleES/Utils/Table.cs | 1,565 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Routing;
using Autofac;
using Autofac.Integration.WebApi;
using CacheSharp.Redis;
using CacheSharp.WebApi.Example.Controllers;
using CacheSharp.WebApi.Example.Mocks;
namespace CacheSharp.WebApi.Example
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ConfigureDependencies();
GlobalConfiguration.Configure(WebApiConfig.Register);
}
private static void ConfigureDependencies()
{
var cache = new RedisCache();
cache.InitializeAsync(new Dictionary<string, string>
{
{"Endpoint", ConfigurationManager.AppSettings["Redis.Endpoint"]},
{"Key", ConfigurationManager.AppSettings["Redis.Key"]},
{"UseSsl", ConfigurationManager.AppSettings["Redis.UseSsl"]}
});
var builder = new ContainerBuilder();
builder.RegisterType<AccountService>().As<IAccountService>().SingleInstance();
builder.RegisterType<TransfersController>();
builder.RegisterInstance(cache).As<IAsyncCache>().SingleInstance();
builder.RegisterInstance(cache).As<ISyncCache>().SingleInstance();
var container = builder.Build();
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
}
}
}
| 31.679245 | 114 | 0.672424 | [
"MIT"
] | paulfryer/CacheSharp | CacheSharp.WebApi.Example/Global.asax.cs | 1,681 | C# |
using System;
using System.Linq;
using System.Collections.Generic;
namespace Proxy.Core {
public class Availabilities {
/**/
#region variables
/**/
public int Bikes;
public int Stands;
public int MechanicalBikes;
public int ElectricalBikes;
public int ElectricalInternalBatteryBikes;
public int ElectricalRemovableBatteryBikes;
/**/
#endregion
/**/
public Availabilities(int bikes, int stands, int mechanicalBikes, int electricalBikes, int electricalInternalBatteryBikes, int electricalRemovableBatteryBikes){
/**/
Bikes = bikes;
Stands = stands;
MechanicalBikes = mechanicalBikes;
ElectricalBikes = electricalBikes;
ElectricalInternalBatteryBikes = electricalInternalBatteryBikes;
ElectricalRemovableBatteryBikes = electricalRemovableBatteryBikes;
/**/
}
}
} | 32.566667 | 168 | 0.636643 | [
"MIT"
] | sana-dibe/eiin839 | project/Biking/Biking/Proxy/Core/Availabilities.cs | 979 | C# |
using System;
using System.Collections;
using System.Runtime.InteropServices;
namespace OrionSparkLedTestBed
{
public enum KeyboardNames
{
ESC = 0x01,
F1 = 0x3b,
F2 = 0x3c,
F3 = 0x3d,
F4 = 0x3e,
F5 = 0x3f,
F6 = 0x40,
F7 = 0x41,
F8 = 0x42,
F9 = 0x43,
F10 = 0x44,
F11 = 0x57,
F12 = 0x58,
PRINT_SCREEN = 0x137,
SCROLL_LOCK = 0x46,
PAUSE_BREAK = 0x145,
TILDE = 0x29,
ONE = 0x02,
TWO = 0x03,
THREE = 0x04,
FOUR = 0x05,
FIVE = 0x06,
SIX = 0x07,
SEVEN = 0x08,
EIGHT = 0x09,
NINE = 0x0A,
ZERO = 0x0B,
MINUS = 0x0C,
EQUALS = 0x0D,
BACKSPACE = 0x0E,
INSERT = 0x152,
HOME = 0x147,
PAGE_UP = 0x149,
NUM_LOCK = 0x45,
NUM_SLASH = 0x135,
NUM_ASTERISK = 0x37,
NUM_MINUS = 0x4A,
TAB = 0x0F,
Q = 0x10,
W = 0x11,
E = 0x12,
R = 0x13,
T = 0x14,
Y = 0x15,
U = 0x16,
I = 0x17,
O = 0x18,
P = 0x19,
OPEN_BRACKET = 0x1A,
CLOSE_BRACKET = 0x1B,
BACKSLASH = 0x2B,
KEYBOARD_DELETE = 0x153,
END = 0x14F,
PAGE_DOWN = 0x151,
NUM_SEVEN = 0x47,
NUM_EIGHT = 0x48,
NUM_NINE = 0x49,
NUM_PLUS = 0x4E,
CAPS_LOCK = 0x3A,
A = 0x1E,
S = 0x1F,
D = 0x20,
F = 0x21,
G = 0x22,
H = 0x23,
J = 0x24,
K = 0x25,
L = 0x26,
SEMICOLON = 0x27,
APOSTROPHE = 0x28,
ENTER = 0x1C,
NUM_FOUR = 0x4B,
NUM_FIVE = 0x4C,
NUM_SIX = 0x4D,
LEFT_SHIFT = 0x2A,
Z = 0x2C,
X = 0x2D,
C = 0x2E,
V = 0x2F,
B = 0x30,
N = 0x31,
M = 0x32,
COMMA = 0x33,
PERIOD = 0x34,
FORWARD_SLASH = 0x35,
RIGHT_SHIFT = 0x36,
ARROW_UP = 0x148,
NUM_ONE = 0x4F,
NUM_TWO = 0x50,
NUM_THREE = 0x51,
NUM_ENTER = 0x11C,
LEFT_CONTROL = 0x1D,
LEFT_WINDOWS = 0x15B,
LEFT_ALT = 0x38,
SPACE = 0x39,
RIGHT_ALT = 0x138,
RIGHT_WINDOWS = 0x15C,
APPLICATION_SELECT = 0x15D,
RIGHT_CONTROL = 0x11D,
ARROW_LEFT = 0x14B,
ARROW_DOWN = 0x150,
ARROW_RIGHT = 0x14D,
NUM_ZERO = 0x52,
NUM_PERIOD = 0x53,
};
public class LogitechGsdk
{
//LED SDK
private const int LOGI_DEVICETYPE_MONOCHROME_ORD = 0;
private const int LOGI_DEVICETYPE_RGB_ORD = 1;
private const int LOGI_DEVICETYPE_PERKEY_RGB_ORD = 2;
public const int LOGI_DEVICETYPE_MONOCHROME = (1 << LOGI_DEVICETYPE_MONOCHROME_ORD);
public const int LOGI_DEVICETYPE_RGB = (1 << LOGI_DEVICETYPE_RGB_ORD);
public const int LOGI_DEVICETYPE_PERKEY_RGB = (1 << LOGI_DEVICETYPE_PERKEY_RGB_ORD);
public const int LOGI_LED_BITMAP_WIDTH = 21;
public const int LOGI_LED_BITMAP_HEIGHT = 6;
public const int LOGI_LED_BITMAP_BYTES_PER_KEY = 4;
public const int LOGI_LED_BITMAP_SIZE = LOGI_LED_BITMAP_WIDTH * LOGI_LED_BITMAP_HEIGHT * LOGI_LED_BITMAP_BYTES_PER_KEY;
public const int LOGI_LED_DURATION_INFINITE = 0;
[DllImport("LogitechLed ", CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLedInit();
[DllImport("LogitechLed ", CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLedSetTargetDevice(int targetDevice);
[DllImport("LogitechLed ", CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLedGetSdkVersion(ref int majorNum, ref int minorNum, ref int buildNum);
[DllImport("LogitechLed ", CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLedSaveCurrentLighting();
[DllImport("LogitechLed ", CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLedSetLighting(int redPercentage, int greenPercentage, int bluePercentage);
[DllImport("LogitechLed ", CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLedRestoreLighting();
[DllImport("LogitechLed ", CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLedFlashLighting(int redPercentage, int greenPercentage, int bluePercentage, int milliSecondsDuration, int milliSecondsInterval);
[DllImport("LogitechLed ", CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLedPulseLighting(int redPercentage, int greenPercentage, int bluePercentage, int milliSecondsDuration, int milliSecondsInterval);
[DllImport("LogitechLed ", CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLedStopEffects();
[DllImport("LogitechLed ", CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLedSetLightingFromBitmap(byte[] bitmap);
[DllImport("LogitechLed ", CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLedSetLightingForKeyWithScanCode(int keyCode, int redPercentage, int greenPercentage, int bluePercentage);
[DllImport("LogitechLed ", CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLedSetLightingForKeyWithHidCode(int keyCode, int redPercentage, int greenPercentage, int bluePercentage);
[DllImport("LogitechLed ", CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLedSetLightingForKeyWithQuartzCode(int keyCode, int redPercentage, int greenPercentage, int bluePercentage);
[DllImport("LogitechLed ", CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLedSetLightingForKeyWithKeyName(KeyboardNames keyCode, int redPercentage, int greenPercentage, int bluePercentage);
[DllImport("LogitechLed ", CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLedSaveLightingForKey(KeyboardNames keyName);
[DllImport("LogitechLed ", CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLedRestoreLightingForKey(KeyboardNames keyName);
[DllImport("LogitechLed ", CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLedFlashSingleKey(KeyboardNames keyName, int redPercentage, int greenPercentage, int bluePercentage, int msDuration, int msInterval);
[DllImport("LogitechLed ", CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLedPulseSingleKey(KeyboardNames keyName, int startRedPercentage, int startGreenPercentage, int startBluePercentage, int finishRedPercentage, int finishGreenPercentage, int finishBluePercentage, int msDuration, bool isInfinite);
[DllImport("LogitechLed ", CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLedStopEffectsOnKey(KeyboardNames keyName);
[DllImport("LogitechLed ", CallingConvention = CallingConvention.Cdecl)]
public static extern void LogiLedShutdown();
}
}
| 37.306122 | 265 | 0.652626 | [
"MIT"
] | Eld1nH/spectrograph | Spectrograph/LogitechGsdk.cs | 7,314 | C# |
using DataReadWrite.Interface;
using JSONService;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LeavePlanForm
{
public partial class sprintPage : Form
{
UIMemberHelper memberHelper = new UIMemberHelper();
UIDisplayHelper displayHelper = new UIDisplayHelper();
public sprintPage()
{
InitializeComponent();
sprintComboList.DataSource = displayHelper.GetDisplayList();
}
// Displays formatted JSON Leave Plan
private void sprintDetailsButton_Click(object sender, EventArgs e)
{
int currentSprint = (sprintComboList.SelectedIndex) + 1;
displayLeavePlanBox.Text = displayHelper.GetDisplaySprintData(currentSprint);
}
private void removeMemberButton_Click(object sender, EventArgs e)
{
memberHelper.CheckAndRemoveMember((sprintComboList.SelectedIndex) + 1, memberNameTextbox.Text);
}
private void addMemberButton_Click(object sender, EventArgs e)
{
memberHelper.CheckAndAddMemeber((sprintComboList.SelectedIndex) + 1, memberNameTextbox.Text);
}
private void addLeaveButton_Click(object sender, EventArgs e)
{
memberHelper.CheckAndAddLeave(sprintComboList.SelectedIndex + 1, leaveNameTextbox.Text, leaveDate.Value);
}
private void removeLeaveButton_Click(object sender, EventArgs e)
{
memberHelper.CheckAndRemoveLeave(sprintComboList.SelectedIndex + 1, leaveNameTextbox.Text, leaveDate.Value);
}
private void displayMemberLeaveButton_Click(object sender, EventArgs e)
{
int currentSprint = (sprintComboList.SelectedIndex) + 1;
string toDisplay = displayHelper.GetDisplayMemberData(currentSprint, memberLeaveNameTextbox.Text);
if(toDisplay != "")
{
displayLeavePlanBox.Text = toDisplay;
}
}
}
}
| 32.608696 | 121 | 0.655556 | [
"MIT"
] | madhurmishra33/LeaveManagementApp | sprintPage.cs | 2,252 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Azure.Messaging.ServiceBus.Amqp;
using Azure.Messaging.ServiceBus.Primitives;
namespace Azure.Messaging.ServiceBus.Core
{
/// <summary>
/// Provides an abstraction for generalizing an Service Bus entity client so that a dedicated instance may provide operations
/// for a specific transport, such as AMQP or JMS. It is intended that the public <see cref="ServiceBusConnection" /> employ
/// a transport client via containment and delegate operations to it rather than understanding protocol-specific details
/// for different transports.
/// </summary>
///
internal abstract class TransportClient : IAsyncDisposable
{
/// <summary>
/// Indicates whether or not this client has been closed.
/// </summary>
///
/// <value>
/// <c>true</c> if the client is closed; otherwise, <c>false</c>.
/// </value>
///
public virtual bool IsClosed { get; }
/// <summary>
/// The endpoint for the Service Bus service to which the client is associated.
/// </summary>
///
public virtual Uri ServiceEndpoint { get; }
/// <summary>
/// Creates a producer strongly aligned with the active protocol and transport,
/// responsible for publishing <see cref="ServiceBusMessage" /> to the entity.
/// </summary>
/// <param name="entityPath"></param>
///
/// <param name="retryPolicy">The policy which governs retry behavior and try timeouts.</param>
///
/// <returns>A <see cref="TransportSender"/> configured in the requested manner.</returns>
///
public abstract TransportSender CreateSender(string entityPath, ServiceBusRetryPolicy retryPolicy);
/// <summary>
/// Creates a consumer strongly aligned with the active protocol and transport, responsible
/// for reading <see cref="ServiceBusMessage" /> from a specific Service Bus entity.
/// </summary>
/// <param name="entityPath"></param>
///
/// <param name="retryPolicy">The policy which governs retry behavior and try timeouts.</param>
/// <param name="receiveMode">The <see cref="ReceiveMode"/> used to specify how messages are received. Defaults to PeekLock mode.</param>
/// <param name="prefetchCount">Controls the number of events received and queued locally without regard to whether an operation was requested. If <c>null</c> a default will be used.</param>
/// <param name="identifier"></param>
/// <param name="sessionId"></param>
/// <param name="isSessionReceiver"></param>
///
/// <returns>A <see cref="TransportReceiver" /> configured in the requested manner.</returns>
///
public abstract TransportReceiver CreateReceiver(
string entityPath,
ServiceBusRetryPolicy retryPolicy,
ReceiveMode receiveMode,
uint prefetchCount,
string identifier,
string sessionId,
bool isSessionReceiver);
/// <summary>
/// Closes the connection to the transport client instance.
/// </summary>
///
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
public abstract Task CloseAsync(CancellationToken cancellationToken);
/// <summary>
/// Performs the task needed to clean up resources used by the client,
/// including ensuring that the client itself has been closed.
/// </summary>
///
/// <returns>A task to be resolved on when the operation has completed.</returns>
///
public virtual async ValueTask DisposeAsync() => await CloseAsync(CancellationToken.None).ConfigureAwait(false);
}
}
| 43.03125 | 199 | 0.635924 | [
"MIT"
] | Kishp01/azure-sdk-for-net | sdk/servicebus/Azure.Messaging.ServiceBus/src/Core/TransportClient.cs | 4,133 | C# |
using System.Web.Mvc;
namespace PizzaFactory.WebClient.Areas.Api
{
public class ApiAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Api";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Api_default",
"Api/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
} | 23.625 | 75 | 0.500882 | [
"MIT"
] | pavelhristov/PizzaFactory | PizzaFactory/PizzaFactory.WebClient/Areas/Api/ApiAreaRegistration.cs | 569 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ACTReorderList.UI.WebForms {
public partial class UsingSqlDataSource {
/// <summary>
/// ScriptManager control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.ScriptManager ScriptManager;
/// <summary>
/// SqlDataSource control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.SqlDataSource SqlDataSource;
/// <summary>
/// UpdatePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.UpdatePanel UpdatePanel;
/// <summary>
/// ReorderList control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::AjaxControlToolkit.ReorderList ReorderList;
}
}
| 33.769231 | 84 | 0.52221 | [
"MIT"
] | pedrofernandesfilho/ACTReorderList | src/UI/ACTReorderList.UI.WebForms/UsingSqlDataSource.aspx.designer.cs | 1,758 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.WafV2.Inputs
{
public sealed class RuleGroupRuleStatementSizeConstraintStatementFieldToMatchAllQueryArgumentsArgs : Pulumi.ResourceArgs
{
public RuleGroupRuleStatementSizeConstraintStatementFieldToMatchAllQueryArgumentsArgs()
{
}
}
}
| 30.35 | 124 | 0.762768 | [
"ECL-2.0",
"Apache-2.0"
] | Otanikotani/pulumi-aws | sdk/dotnet/WafV2/Inputs/RuleGroupRuleStatementSizeConstraintStatementFieldToMatchAllQueryArgumentsArgs.cs | 607 | C# |
using Lucene.Net.Analysis.TokenAttributes;
using System;
using System.IO;
using System.Text;
namespace Lucene.Net.Analysis.Wikipedia
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// JFlex-generated tokenizer that is aware of Wikipedia syntax.
/// </summary>
internal class WikipediaTokenizerImpl
{
/// <summary>This character denotes the end of file</summary>
public static readonly int YYEOF = -1;
/// <summary>initial size of the lookahead buffer</summary>
private static readonly int ZZ_BUFFERSIZE = 4096;
/// <summary>lexical states</summary>
public static readonly int YYINITIAL = 0;
public static readonly int CATEGORY_STATE = 2;
public static readonly int INTERNAL_LINK_STATE = 4;
public static readonly int EXTERNAL_LINK_STATE = 6;
public static readonly int TWO_SINGLE_QUOTES_STATE = 8;
public static readonly int THREE_SINGLE_QUOTES_STATE = 10;
public static readonly int FIVE_SINGLE_QUOTES_STATE = 12;
public static readonly int DOUBLE_EQUALS_STATE = 14;
public static readonly int DOUBLE_BRACE_STATE = 16;
public static readonly int STRING = 18;
/// <summary>
/// ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l
/// ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l
/// at the beginning of a line
/// l is of the form l = 2*k, k a non negative integer
/// </summary>
private static readonly int[] ZZ_LEXSTATE = {
0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7,
8, 8, 9, 9
};
/// <summary>
/// Translates characters to character classes
/// </summary>
private const string ZZ_CMAP_PACKED =
"\x0009\x0000\x0001\x0014\x0001\x0013\x0001\x0000\x0001\x0014\x0001\x0012\x0012\x0000\x0001\x0014\x0001\x0000\x0001\x000A" +
"\x0001\x002B\x0002\x0000\x0001\x0003\x0001\x0001\x0004\x0000\x0001\x000C\x0001\x0005\x0001\x0002\x0001\x0008\x000A\x000E" +
"\x0001\x0017\x0001\x0000\x0001\x0007\x0001\x0009\x0001\x000B\x0001\x002B\x0001\x0004\x0002\x000D\x0001\x0018\x0005\x000D" +
"\x0001\x0021\x0011\x000D\x0001\x0015\x0001\x0000\x0001\x0016\x0001\x0000\x0001\x0006\x0001\x0000\x0001\x0019\x0001\x0023" +
"\x0002\x000D\x0001\x001B\x0001\x0020\x0001\x001C\x0001\x0028\x0001\x0021\x0004\x000D\x0001\x0022\x0001\x001D\x0001\x0029" +
"\x0001\x000D\x0001\x001E\x0001\x002A\x0001\x001A\x0003\x000D\x0001\x0024\x0001\x001F\x0001\x000D\x0001\x0025\x0001\x0027" +
"\x0001\x0026\x0042\x0000\x0017\x000D\x0001\x0000\x001F\x000D\x0001\x0000\u0568\x000D\x000A\x000F\x0086\x000D\x000A\x000F" +
"\u026c\x000D\x000A\x000F\x0076\x000D\x000A\x000F\x0076\x000D\x000A\x000F\x0076\x000D\x000A\x000F\x0076\x000D\x000A\x000F" +
"\x0077\x000D\x0009\x000F\x0076\x000D\x000A\x000F\x0076\x000D\x000A\x000F\x0076\x000D\x000A\x000F\x00E0\x000D\x000A\x000F" +
"\x0076\x000D\x000A\x000F\u0166\x000D\x000A\x000F\x00B6\x000D\u0100\x000D\u0e00\x000D\u1040\x0000\u0150\x0011\x0060\x0000" +
"\x0010\x0011\u0100\x0000\x0080\x0011\x0080\x0000\u19c0\x0011\x0040\x0000\u5200\x0011\u0c00\x0000\u2bb0\x0010\u2150\x0000" +
"\u0200\x0011\u0465\x0000\x003B\x0011\x003D\x000D\x0023\x0000";
/// <summary>
/// Translates characters to character classes
/// </summary>
private static readonly char[] ZZ_CMAP = ZzUnpackCMap(ZZ_CMAP_PACKED);
/// <summary>
/// Translates DFA states to action switch labels.
/// </summary>
private static readonly int[] ZZ_ACTION = ZzUnpackAction();
private const string ZZ_ACTION_PACKED_0 =
"\x000A\x0000\x0004\x0001\x0004\x0002\x0001\x0003\x0001\x0004\x0001\x0001\x0002\x0005\x0001\x0006" +
"\x0001\x0005\x0001\x0007\x0001\x0005\x0002\x0008\x0001\x0009\x0001\x0005\x0001\x000A\x0001\x0009" +
"\x0001\x000B\x0001\x000C\x0001\x000D\x0001\x000E\x0001\x000D\x0001\x000F\x0001\x0010\x0001\x0008" +
"\x0001\x0011\x0001\x0008\x0004\x0012\x0001\x0013\x0001\x0014\x0001\x0015\x0001\x0016\x0003\x0000" +
"\x0001\x0017\x000C\x0000\x0001\x0018\x0001\x0019\x0001\x001A\x0001\x001B\x0001\x0009\x0001\x0000" +
"\x0001\x001C\x0001\x001D\x0001\x001E\x0001\x0000\x0001\x001F\x0001\x0000\x0001\x0020\x0003\x0000" +
"\x0001\x0021\x0001\x0022\x0002\x0023\x0001\x0022\x0002\x0024\x0002\x0000\x0001\x0023\x0001\x0000" +
"\x000C\x0023\x0001\x0022\x0003\x0000\x0001\x0009\x0001\x0025\x0003\x0000\x0001\x0026\x0001\x0027" +
"\x0005\x0000\x0001\x0028\x0004\x0000\x0001\x0028\x0002\x0000\x0002\x0028\x0002\x0000\x0001\x0009" +
"\x0005\x0000\x0001\x0019\x0001\x0022\x0001\x0023\x0001\x0029\x0003\x0000\x0001\x0009\x0002\x0000" +
"\x0001\x002A\x0018\x0000\x0001\x002B\x0002\x0000\x0001\x002C\x0001\x002D\x0001\x002E";
private static int[] ZzUnpackAction()
{
int[] result = new int[181];
int offset = 0;
offset = ZzUnpackAction(ZZ_ACTION_PACKED_0, offset, result);
return result;
}
private static int ZzUnpackAction(string packed, int offset, int[] result)
{
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.Length;
while (i < l)
{
int count = packed[i++];
int value = packed[i++];
do result[j++] = value; while (--count > 0);
}
return j;
}
/// <summary>
/// Translates a state to a row index in the transition table
/// </summary>
private static readonly int[] ZZ_ROWMAP = ZzUnpackRowMap();
private const string ZZ_ROWMAP_PACKED_0 =
"\x0000\x0000\x0000\x002C\x0000\x0058\x0000\x0084\x0000\x00B0\x0000\x00DC\x0000\u0108\x0000\u0134" +
"\x0000\u0160\x0000\u018c\x0000\u01b8\x0000\u01e4\x0000\u0210\x0000\u023c\x0000\u0268\x0000\u0294" +
"\x0000\u02c0\x0000\u02ec\x0000\u01b8\x0000\u0318\x0000\u0344\x0000\u01b8\x0000\u0370\x0000\u039c" +
"\x0000\u03c8\x0000\u03f4\x0000\u0420\x0000\u01b8\x0000\u0370\x0000\u044c\x0000\u0478\x0000\u01b8" +
"\x0000\u04a4\x0000\u04d0\x0000\u04fc\x0000\u0528\x0000\u0554\x0000\u0580\x0000\u05ac\x0000\u05d8" +
"\x0000\u0604\x0000\u0630\x0000\u065c\x0000\u01b8\x0000\u0688\x0000\u0370\x0000\u06b4\x0000\u06e0" +
"\x0000\u070c\x0000\u01b8\x0000\u01b8\x0000\u0738\x0000\u0764\x0000\u0790\x0000\u01b8\x0000\u07bc" +
"\x0000\u07e8\x0000\u0814\x0000\u0840\x0000\u086c\x0000\u0898\x0000\u08c4\x0000\u08f0\x0000\u091c" +
"\x0000\u0948\x0000\u0974\x0000\u09a0\x0000\u09cc\x0000\u09f8\x0000\u01b8\x0000\u01b8\x0000\u0a24" +
"\x0000\u0a50\x0000\u0a7c\x0000\u0a7c\x0000\u01b8\x0000\u0aa8\x0000\u0ad4\x0000\u0b00\x0000\u0b2c" +
"\x0000\u0b58\x0000\u0b84\x0000\u0bb0\x0000\u0bdc\x0000\u0c08\x0000\u0c34\x0000\u0c60\x0000\u0c8c" +
"\x0000\u0814\x0000\u0cb8\x0000\u0ce4\x0000\u0d10\x0000\u0d3c\x0000\u0d68\x0000\u0d94\x0000\u0dc0" +
"\x0000\u0dec\x0000\u0e18\x0000\u0e44\x0000\u0e70\x0000\u0e9c\x0000\u0ec8\x0000\u0ef4\x0000\u0f20" +
"\x0000\u0f4c\x0000\u0f78\x0000\u0fa4\x0000\u0fd0\x0000\u0ffc\x0000\u1028\x0000\u1054\x0000\u01b8" +
"\x0000\u1080\x0000\u10ac\x0000\u10d8\x0000\u1104\x0000\u01b8\x0000\u1130\x0000\u115c\x0000\u1188" +
"\x0000\u11b4\x0000\u11e0\x0000\u120c\x0000\u1238\x0000\u1264\x0000\u1290\x0000\u12bc\x0000\u12e8" +
"\x0000\u1314\x0000\u1340\x0000\u07e8\x0000\u0974\x0000\u136c\x0000\u1398\x0000\u13c4\x0000\u13f0" +
"\x0000\u141c\x0000\u1448\x0000\u1474\x0000\u14a0\x0000\u01b8\x0000\u14cc\x0000\u14f8\x0000\u1524" +
"\x0000\u1550\x0000\u157c\x0000\u15a8\x0000\u15d4\x0000\u1600\x0000\u162c\x0000\u01b8\x0000\u1658" +
"\x0000\u1684\x0000\u16b0\x0000\u16dc\x0000\u1708\x0000\u1734\x0000\u1760\x0000\u178c\x0000\u17b8" +
"\x0000\u17e4\x0000\u1810\x0000\u183c\x0000\u1868\x0000\u1894\x0000\u18c0\x0000\u18ec\x0000\u1918" +
"\x0000\u1944\x0000\u1970\x0000\u199c\x0000\u19c8\x0000\u19f4\x0000\u1a20\x0000\u1a4c\x0000\u1a78" +
"\x0000\u1aa4\x0000\u1ad0\x0000\u01b8\x0000\u01b8\x0000\u01b8";
private static int[] ZzUnpackRowMap()
{
int[] result = new int[181];
int offset = 0;
offset = ZzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result);
return result;
}
private static int ZzUnpackRowMap(string packed, int offset, int[] result)
{
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.Length;
while (i < l)
{
int high = packed[i++] << 16;
result[j++] = high | packed[i++];
}
return j;
}
/// <summary>
/// The transition table of the DFA
/// </summary>
private static readonly int[] ZZ_TRANS = ZzUnpackTrans();
private const string ZZ_TRANS_PACKED_0 =
"\x0001\x000B\x0001\x000C\x0005\x000B\x0001\x000D\x0001\x000B\x0001\x000E\x0003\x000B\x0001\x000F" +
"\x0001\x0010\x0001\x0011\x0001\x0012\x0001\x0013\x0003\x000B\x0001\x0014\x0002\x000B\x000D\x000F" +
"\x0001\x0015\x0002\x000B\x0003\x000F\x0001\x000B\x0007\x0016\x0001\x0017\x0005\x0016\x0004\x0018" +
"\x0005\x0016\x0001\x0019\x0001\x0016\x000D\x0018\x0003\x0016\x0003\x0018\x0008\x0016\x0001\x0017" +
"\x0005\x0016\x0004\x001A\x0005\x0016\x0001\x001B\x0001\x0016\x000D\x001A\x0003\x0016\x0003\x001A" +
"\x0001\x0016\x0007\x001C\x0001\x001D\x0005\x001C\x0004\x001E\x0001\x001C\x0001\x001F\x0002\x0016" +
"\x0001\x001C\x0001\x0020\x0001\x001C\x000D\x001E\x0003\x001C\x0001\x0021\x0002\x001E\x0002\x001C" +
"\x0001\x0022\x0005\x001C\x0001\x001D\x0005\x001C\x0004\x0023\x0004\x001C\x0001\x0024\x0002\x001C" +
"\x000D\x0023\x0003\x001C\x0003\x0023\x0008\x001C\x0001\x001D\x0005\x001C\x0004\x0025\x0004\x001C" +
"\x0001\x0024\x0002\x001C\x000D\x0025\x0003\x001C\x0003\x0025\x0008\x001C\x0001\x001D\x0005\x001C" +
"\x0004\x0025\x0004\x001C\x0001\x0026\x0002\x001C\x000D\x0025\x0003\x001C\x0003\x0025\x0008\x001C" +
"\x0001\x001D\x0001\x001C\x0001\x0027\x0003\x001C\x0004\x0028\x0007\x001C\x000D\x0028\x0003\x001C" +
"\x0003\x0028\x0008\x001C\x0001\x0029\x0005\x001C\x0004\x002A\x0007\x001C\x000D\x002A\x0001\x001C" +
"\x0001\x002B\x0001\x001C\x0003\x002A\x0001\x001C\x0001\x002C\x0001\x002D\x0005\x002C\x0001\x002E" +
"\x0001\x002C\x0001\x002F\x0003\x002C\x0004\x0030\x0004\x002C\x0001\x0031\x0002\x002C\x000D\x0030" +
"\x0002\x002C\x0001\x0032\x0003\x0030\x0001\x002C\x002D\x0000\x0001\x0033\x0032\x0000\x0001\x0034" +
"\x0004\x0000\x0004\x0035\x0007\x0000\x0006\x0035\x0001\x0036\x0006\x0035\x0003\x0000\x0003\x0035" +
"\x000A\x0000\x0001\x0037\x0023\x0000\x0001\x0038\x0001\x0039\x0001\x003A\x0001\x003B\x0002\x003C" +
"\x0001\x0000\x0001\x003D\x0003\x0000\x0001\x003D\x0001\x000F\x0001\x0010\x0001\x0011\x0001\x0012" +
"\x0007\x0000\x000D\x000F\x0003\x0000\x0003\x000F\x0003\x0000\x0001\x003E\x0001\x0000\x0001\x003F" +
"\x0002\x0040\x0001\x0000\x0001\x0041\x0003\x0000\x0001\x0041\x0003\x0010\x0001\x0012\x0007\x0000" +
"\x000D\x0010\x0003\x0000\x0003\x0010\x0002\x0000\x0001\x0038\x0001\x0042\x0001\x003A\x0001\x003B" +
"\x0002\x0040\x0001\x0000\x0001\x0041\x0003\x0000\x0001\x0041\x0001\x0011\x0001\x0010\x0001\x0011" +
"\x0001\x0012\x0007\x0000\x000D\x0011\x0003\x0000\x0003\x0011\x0003\x0000\x0001\x0043\x0001\x0000" +
"\x0001\x003F\x0002\x003C\x0001\x0000\x0001\x003D\x0003\x0000\x0001\x003D\x0004\x0012\x0007\x0000" +
"\x000D\x0012\x0003\x0000\x0003\x0012\x0016\x0000\x0001\x0044\x003B\x0000\x0001\x0045\x000E\x0000" +
"\x0001\x0034\x0004\x0000\x0004\x0035\x0007\x0000\x000D\x0035\x0003\x0000\x0003\x0035\x000E\x0000" +
"\x0004\x0018\x0007\x0000\x000D\x0018\x0003\x0000\x0003\x0018\x0017\x0000\x0001\x0046\x0022\x0000" +
"\x0004\x001A\x0007\x0000\x000D\x001A\x0003\x0000\x0003\x001A\x0017\x0000\x0001\x0047\x0022\x0000" +
"\x0004\x001E\x0007\x0000\x000D\x001E\x0003\x0000\x0003\x001E\x0014\x0000\x0001\x0016\x0025\x0000" +
"\x0004\x001E\x0007\x0000\x0002\x001E\x0001\x0048\x000A\x001E\x0003\x0000\x0003\x001E\x0002\x0000" +
"\x0001\x0049\x0037\x0000\x0004\x0023\x0007\x0000\x000D\x0023\x0003\x0000\x0003\x0023\x0016\x0000" +
"\x0001\x004A\x0023\x0000\x0004\x0025\x0007\x0000\x000D\x0025\x0003\x0000\x0003\x0025\x0016\x0000" +
"\x0001\x004B\x001F\x0000\x0001\x004C\x002F\x0000\x0004\x0028\x0007\x0000\x000D\x0028\x0003\x0000" +
"\x0003\x0028\x0009\x0000\x0001\x004D\x0004\x0000\x0004\x0035\x0007\x0000\x000D\x0035\x0003\x0000" +
"\x0003\x0035\x000E\x0000\x0004\x002A\x0007\x0000\x000D\x002A\x0003\x0000\x0003\x002A\x0027\x0000" +
"\x0001\x004C\x0006\x0000\x0001\x004E\x0033\x0000\x0001\x004F\x002F\x0000\x0004\x0030\x0007\x0000" +
"\x000D\x0030\x0003\x0000\x0003\x0030\x0016\x0000\x0001\x0050\x0023\x0000\x0004\x0035\x0007\x0000" +
"\x000D\x0035\x0003\x0000\x0003\x0035\x000C\x0000\x0001\x001C\x0001\x0000\x0004\x0051\x0001\x0000" +
"\x0003\x0052\x0003\x0000\x000D\x0051\x0003\x0000\x0003\x0051\x000C\x0000\x0001\x001C\x0001\x0000" +
"\x0004\x0051\x0001\x0000\x0003\x0052\x0003\x0000\x0003\x0051\x0001\x0053\x0009\x0051\x0003\x0000" +
"\x0003\x0051\x000E\x0000\x0001\x0054\x0001\x0000\x0001\x0054\x0008\x0000\x000D\x0054\x0003\x0000" +
"\x0003\x0054\x000E\x0000\x0001\x0055\x0001\x0056\x0001\x0057\x0001\x0058\x0007\x0000\x000D\x0055" +
"\x0003\x0000\x0003\x0055\x000E\x0000\x0001\x0059\x0001\x0000\x0001\x0059\x0008\x0000\x000D\x0059" +
"\x0003\x0000\x0003\x0059\x000E\x0000\x0001\x005A\x0001\x005B\x0001\x005A\x0001\x005B\x0007\x0000" +
"\x000D\x005A\x0003\x0000\x0003\x005A\x000E\x0000\x0001\x005C\x0002\x005D\x0001\x005E\x0007\x0000" +
"\x000D\x005C\x0003\x0000\x0003\x005C\x000E\x0000\x0001\x003D\x0002\x005F\x0008\x0000\x000D\x003D" +
"\x0003\x0000\x0003\x003D\x000E\x0000\x0001\x0060\x0002\x0061\x0001\x0062\x0007\x0000\x000D\x0060" +
"\x0003\x0000\x0003\x0060\x000E\x0000\x0004\x005B\x0007\x0000\x000D\x005B\x0003\x0000\x0003\x005B" +
"\x000E\x0000\x0001\x0063\x0002\x0064\x0001\x0065\x0007\x0000\x000D\x0063\x0003\x0000\x0003\x0063" +
"\x000E\x0000\x0001\x0066\x0002\x0067\x0001\x0068\x0007\x0000\x000D\x0066\x0003\x0000\x0003\x0066" +
"\x000E\x0000\x0001\x0069\x0001\x0061\x0001\x006A\x0001\x0062\x0007\x0000\x000D\x0069\x0003\x0000" +
"\x0003\x0069\x000E\x0000\x0001\x006B\x0002\x0056\x0001\x0058\x0007\x0000\x000D\x006B\x0003\x0000" +
"\x0003\x006B\x0018\x0000\x0001\x006C\x0001\x006D\x0034\x0000\x0001\x006E\x0017\x0000\x0004\x001E" +
"\x0007\x0000\x0002\x001E\x0001\x006F\x000A\x001E\x0003\x0000\x0003\x001E\x0002\x0000\x0001\x0070" +
"\x0041\x0000\x0001\x0071\x0001\x0072\x0020\x0000\x0004\x0035\x0007\x0000\x0006\x0035\x0001\x0073" +
"\x0006\x0035\x0003\x0000\x0003\x0035\x0002\x0000\x0001\x0074\x0033\x0000\x0001\x0075\x0039\x0000" +
"\x0001\x0076\x0001\x0077\x001C\x0000\x0001\x0078\x0001\x0000\x0001\x001C\x0001\x0000\x0004\x0051" +
"\x0001\x0000\x0003\x0052\x0003\x0000\x000D\x0051\x0003\x0000\x0003\x0051\x000E\x0000\x0004\x0079" +
"\x0001\x0000\x0003\x0052\x0003\x0000\x000D\x0079\x0003\x0000\x0003\x0079\x000A\x0000\x0001\x0078" +
"\x0001\x0000\x0001\x001C\x0001\x0000\x0004\x0051\x0001\x0000\x0003\x0052\x0003\x0000\x0008\x0051" +
"\x0001\x007A\x0004\x0051\x0003\x0000\x0003\x0051\x0002\x0000\x0001\x0038\x000B\x0000\x0001\x0054" +
"\x0001\x0000\x0001\x0054\x0008\x0000\x000D\x0054\x0003\x0000\x0003\x0054\x0003\x0000\x0001\x007B" +
"\x0001\x0000\x0001\x003F\x0002\x007C\x0006\x0000\x0001\x0055\x0001\x0056\x0001\x0057\x0001\x0058" +
"\x0007\x0000\x000D\x0055\x0003\x0000\x0003\x0055\x0003\x0000\x0001\x007D\x0001\x0000\x0001\x003F" +
"\x0002\x007E\x0001\x0000\x0001\x007F\x0003\x0000\x0001\x007F\x0003\x0056\x0001\x0058\x0007\x0000" +
"\x000D\x0056\x0003\x0000\x0003\x0056\x0003\x0000\x0001\x0080\x0001\x0000\x0001\x003F\x0002\x007E" +
"\x0001\x0000\x0001\x007F\x0003\x0000\x0001\x007F\x0001\x0057\x0001\x0056\x0001\x0057\x0001\x0058" +
"\x0007\x0000\x000D\x0057\x0003\x0000\x0003\x0057\x0003\x0000\x0001\x0081\x0001\x0000\x0001\x003F" +
"\x0002\x007C\x0006\x0000\x0004\x0058\x0007\x0000\x000D\x0058\x0003\x0000\x0003\x0058\x0003\x0000" +
"\x0001\x0082\x0002\x0000\x0001\x0082\x0007\x0000\x0001\x005A\x0001\x005B\x0001\x005A\x0001\x005B" +
"\x0007\x0000\x000D\x005A\x0003\x0000\x0003\x005A\x0003\x0000\x0001\x0082\x0002\x0000\x0001\x0082" +
"\x0007\x0000\x0004\x005B\x0007\x0000\x000D\x005B\x0003\x0000\x0003\x005B\x0003\x0000\x0001\x007C" +
"\x0001\x0000\x0001\x003F\x0002\x007C\x0006\x0000\x0001\x005C\x0002\x005D\x0001\x005E\x0007\x0000" +
"\x000D\x005C\x0003\x0000\x0003\x005C\x0003\x0000\x0001\x007E\x0001\x0000\x0001\x003F\x0002\x007E" +
"\x0001\x0000\x0001\x007F\x0003\x0000\x0001\x007F\x0003\x005D\x0001\x005E\x0007\x0000\x000D\x005D" +
"\x0003\x0000\x0003\x005D\x0003\x0000\x0001\x007C\x0001\x0000\x0001\x003F\x0002\x007C\x0006\x0000" +
"\x0004\x005E\x0007\x0000\x000D\x005E\x0003\x0000\x0003\x005E\x0003\x0000\x0001\x007F\x0002\x0000" +
"\x0002\x007F\x0001\x0000\x0001\x007F\x0003\x0000\x0001\x007F\x0003\x005F\x0008\x0000\x000D\x005F" +
"\x0003\x0000\x0003\x005F\x0003\x0000\x0001\x0043\x0001\x0000\x0001\x003F\x0002\x003C\x0001\x0000" +
"\x0001\x003D\x0003\x0000\x0001\x003D\x0001\x0060\x0002\x0061\x0001\x0062\x0007\x0000\x000D\x0060" +
"\x0003\x0000\x0003\x0060\x0003\x0000\x0001\x003E\x0001\x0000\x0001\x003F\x0002\x0040\x0001\x0000" +
"\x0001\x0041\x0003\x0000\x0001\x0041\x0003\x0061\x0001\x0062\x0007\x0000\x000D\x0061\x0003\x0000" +
"\x0003\x0061\x0003\x0000\x0001\x0043\x0001\x0000\x0001\x003F\x0002\x003C\x0001\x0000\x0001\x003D" +
"\x0003\x0000\x0001\x003D\x0004\x0062\x0007\x0000\x000D\x0062\x0003\x0000\x0003\x0062\x0003\x0000" +
"\x0001\x003C\x0001\x0000\x0001\x003F\x0002\x003C\x0001\x0000\x0001\x003D\x0003\x0000\x0001\x003D" +
"\x0001\x0063\x0002\x0064\x0001\x0065\x0007\x0000\x000D\x0063\x0003\x0000\x0003\x0063\x0003\x0000" +
"\x0001\x0040\x0001\x0000\x0001\x003F\x0002\x0040\x0001\x0000\x0001\x0041\x0003\x0000\x0001\x0041" +
"\x0003\x0064\x0001\x0065\x0007\x0000\x000D\x0064\x0003\x0000\x0003\x0064\x0003\x0000\x0001\x003C" +
"\x0001\x0000\x0001\x003F\x0002\x003C\x0001\x0000\x0001\x003D\x0003\x0000\x0001\x003D\x0004\x0065" +
"\x0007\x0000\x000D\x0065\x0003\x0000\x0003\x0065\x0003\x0000\x0001\x003D\x0002\x0000\x0002\x003D" +
"\x0001\x0000\x0001\x003D\x0003\x0000\x0001\x003D\x0001\x0066\x0002\x0067\x0001\x0068\x0007\x0000" +
"\x000D\x0066\x0003\x0000\x0003\x0066\x0003\x0000\x0001\x0041\x0002\x0000\x0002\x0041\x0001\x0000" +
"\x0001\x0041\x0003\x0000\x0001\x0041\x0003\x0067\x0001\x0068\x0007\x0000\x000D\x0067\x0003\x0000" +
"\x0003\x0067\x0003\x0000\x0001\x003D\x0002\x0000\x0002\x003D\x0001\x0000\x0001\x003D\x0003\x0000" +
"\x0001\x003D\x0004\x0068\x0007\x0000\x000D\x0068\x0003\x0000\x0003\x0068\x0003\x0000\x0001\x0083" +
"\x0001\x0000\x0001\x003F\x0002\x003C\x0001\x0000\x0001\x003D\x0003\x0000\x0001\x003D\x0001\x0069" +
"\x0001\x0061\x0001\x006A\x0001\x0062\x0007\x0000\x000D\x0069\x0003\x0000\x0003\x0069\x0003\x0000" +
"\x0001\x0084\x0001\x0000\x0001\x003F\x0002\x0040\x0001\x0000\x0001\x0041\x0003\x0000\x0001\x0041" +
"\x0001\x006A\x0001\x0061\x0001\x006A\x0001\x0062\x0007\x0000\x000D\x006A\x0003\x0000\x0003\x006A" +
"\x0003\x0000\x0001\x0081\x0001\x0000\x0001\x003F\x0002\x007C\x0006\x0000\x0001\x006B\x0002\x0056" +
"\x0001\x0058\x0007\x0000\x000D\x006B\x0003\x0000\x0003\x006B\x0019\x0000\x0001\x006D\x002C\x0000" +
"\x0001\x0085\x0034\x0000\x0001\x0086\x0016\x0000\x0004\x001E\x0007\x0000\x000D\x001E\x0003\x0000" +
"\x0001\x001E\x0001\x0087\x0001\x001E\x0019\x0000\x0001\x0072\x002C\x0000\x0001\x0088\x001D\x0000" +
"\x0001\x001C\x0001\x0000\x0004\x0051\x0001\x0000\x0003\x0052\x0003\x0000\x0003\x0051\x0001\x0089" +
"\x0009\x0051\x0003\x0000\x0003\x0051\x0002\x0000\x0001\x008A\x0042\x0000\x0001\x0077\x002C\x0000" +
"\x0001\x008B\x001C\x0000\x0001\x008C\x002A\x0000\x0001\x0078\x0003\x0000\x0004\x0079\x0007\x0000" +
"\x000D\x0079\x0003\x0000\x0003\x0079\x000A\x0000\x0001\x0078\x0001\x0000\x0001\x008D\x0001\x0000" +
"\x0004\x0051\x0001\x0000\x0003\x0052\x0003\x0000\x000D\x0051\x0003\x0000\x0003\x0051\x000E\x0000" +
"\x0001\x008E\x0001\x0058\x0001\x008E\x0001\x0058\x0007\x0000\x000D\x008E\x0003\x0000\x0003\x008E" +
"\x000E\x0000\x0004\x005E\x0007\x0000\x000D\x005E\x0003\x0000\x0003\x005E\x000E\x0000\x0004\x0062" +
"\x0007\x0000\x000D\x0062\x0003\x0000\x0003\x0062\x000E\x0000\x0004\x0065\x0007\x0000\x000D\x0065" +
"\x0003\x0000\x0003\x0065\x000E\x0000\x0004\x0068\x0007\x0000\x000D\x0068\x0003\x0000\x0003\x0068" +
"\x000E\x0000\x0001\x008F\x0001\x0062\x0001\x008F\x0001\x0062\x0007\x0000\x000D\x008F\x0003\x0000" +
"\x0003\x008F\x000E\x0000\x0004\x0058\x0007\x0000\x000D\x0058\x0003\x0000\x0003\x0058\x000E\x0000" +
"\x0004\x0090\x0007\x0000\x000D\x0090\x0003\x0000\x0003\x0090\x001B\x0000\x0001\x0091\x0031\x0000" +
"\x0001\x0092\x0018\x0000\x0004\x001E\x0006\x0000\x0001\x0093\x000D\x001E\x0003\x0000\x0002\x001E" +
"\x0001\x0094\x001B\x0000\x0001\x0095\x001A\x0000\x0001\x0078\x0001\x0000\x0001\x001C\x0001\x0000" +
"\x0004\x0051\x0001\x0000\x0003\x0052\x0003\x0000\x0008\x0051\x0001\x0096\x0004\x0051\x0003\x0000" +
"\x0003\x0051\x0002\x0000\x0001\x0097\x0044\x0000\x0001\x0098\x001E\x0000\x0004\x0099\x0007\x0000" +
"\x000D\x0099\x0003\x0000\x0003\x0099\x0003\x0000\x0001\x007B\x0001\x0000\x0001\x003F\x0002\x007C" +
"\x0006\x0000\x0001\x008E\x0001\x0058\x0001\x008E\x0001\x0058\x0007\x0000\x000D\x008E\x0003\x0000" +
"\x0003\x008E\x0003\x0000\x0001\x0083\x0001\x0000\x0001\x003F\x0002\x003C\x0001\x0000\x0001\x003D" +
"\x0003\x0000\x0001\x003D\x0001\x008F\x0001\x0062\x0001\x008F\x0001\x0062\x0007\x0000\x000D\x008F" +
"\x0003\x0000\x0003\x008F\x0003\x0000\x0001\x0082\x0002\x0000\x0001\x0082\x0007\x0000\x0004\x0090" +
"\x0007\x0000\x000D\x0090\x0003\x0000\x0003\x0090\x001C\x0000\x0001\x009A\x002D\x0000\x0001\x009B" +
"\x0016\x0000\x0001\x009C\x0030\x0000\x0004\x001E\x0006\x0000\x0001\x0093\x000D\x001E\x0003\x0000" +
"\x0003\x001E\x001C\x0000\x0001\x009D\x0019\x0000\x0001\x0078\x0001\x0000\x0001\x004C\x0001\x0000" +
"\x0004\x0051\x0001\x0000\x0003\x0052\x0003\x0000\x000D\x0051\x0003\x0000\x0003\x0051\x001C\x0000" +
"\x0001\x009E\x001A\x0000\x0001\x009F\x0002\x0000\x0004\x0099\x0007\x0000\x000D\x0099\x0003\x0000" +
"\x0003\x0099\x001D\x0000\x0001\x00A0\x0032\x0000\x0001\x00A1\x0010\x0000\x0001\x00A2\x003F\x0000" +
"\x0001\x00A3\x002B\x0000\x0001\x00A4\x001A\x0000\x0001\x001C\x0001\x0000\x0004\x0079\x0001\x0000" +
"\x0003\x0052\x0003\x0000\x000D\x0079\x0003\x0000\x0003\x0079\x001E\x0000\x0001\x00A5\x002B\x0000" +
"\x0001\x00A6\x001B\x0000\x0004\x00A7\x0007\x0000\x000D\x00A7\x0003\x0000\x0003\x00A7\x001E\x0000" +
"\x0001\x00A8\x002B\x0000\x0001\x00A9\x002C\x0000\x0001\x00AA\x0031\x0000\x0001\x00AB\x0009\x0000" +
"\x0001\x00AC\x000A\x0000\x0004\x00A7\x0007\x0000\x000D\x00A7\x0003\x0000\x0003\x00A7\x001F\x0000" +
"\x0001\x00AD\x002B\x0000\x0001\x00AE\x002C\x0000\x0001\x00AF\x0012\x0000\x0001\x000B\x0032\x0000" +
"\x0004\x00B0\x0007\x0000\x000D\x00B0\x0003\x0000\x0003\x00B0\x0020\x0000\x0001\x00B1\x002B\x0000" +
"\x0001\x00B2\x0023\x0000\x0001\x00B3\x0016\x0000\x0002\x00B0\x0001\x0000\x0002\x00B0\x0001\x0000" +
"\x0002\x00B0\x0002\x0000\x0005\x00B0\x0007\x0000\x000D\x00B0\x0003\x0000\x0004\x00B0\x0017\x0000" +
"\x0001\x00B4\x002B\x0000\x0001\x00B5\x0014\x0000";
private static int[] ZzUnpackTrans()
{
int[] result = new int[6908];
int offset = 0;
offset = ZzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result);
return result;
}
private static int ZzUnpackTrans(string packed, int offset, int[] result)
{
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.Length;
while (i < l)
{
int count = packed[i++];
int value = packed[i++];
value--;
do result[j++] = value; while (--count > 0);
}
return j;
}
/* error codes */
private static readonly int ZZ_UNKNOWN_ERROR = 0;
private static readonly int ZZ_NO_MATCH = 1;
private static readonly int ZZ_PUSHBACK_2BIG = 2;
/* error messages for the codes above */
private static readonly string[] ZZ_ERROR_MSG = {
"Unkown internal scanner error",
"Error: could not match input",
"Error: pushback value was too large"
};
/// <summary>
/// ZZ_ATTRIBUTE[aState] contains the attributes of state <c>aState</c>
/// </summary>
private static readonly int[] ZZ_ATTRIBUTE = ZzUnpackAttribute();
private const string ZZ_ATTRIBUTE_PACKED_0 =
"\x000A\x0000\x0001\x0009\x0007\x0001\x0001\x0009\x0002\x0001\x0001\x0009\x0005\x0001\x0001\x0009" +
"\x0003\x0001\x0001\x0009\x000B\x0001\x0001\x0009\x0005\x0001\x0002\x0009\x0003\x0000\x0001\x0009" +
"\x000C\x0000\x0002\x0001\x0002\x0009\x0001\x0001\x0001\x0000\x0002\x0001\x0001\x0009\x0001\x0000" +
"\x0001\x0001\x0001\x0000\x0001\x0001\x0003\x0000\x0007\x0001\x0002\x0000\x0001\x0001\x0001\x0000" +
"\x000D\x0001\x0003\x0000\x0001\x0001\x0001\x0009\x0003\x0000\x0001\x0001\x0001\x0009\x0005\x0000" +
"\x0001\x0001\x0004\x0000\x0001\x0001\x0002\x0000\x0002\x0001\x0002\x0000\x0001\x0001\x0005\x0000" +
"\x0001\x0009\x0003\x0001\x0003\x0000\x0001\x0001\x0002\x0000\x0001\x0009\x0018\x0000\x0001\x0001" +
"\x0002\x0000\x0003\x0009";
private static int[] ZzUnpackAttribute()
{
int[] result = new int[181];
int offset = 0;
offset = ZzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result);
return result;
}
private static int ZzUnpackAttribute(string packed, int offset, int[] result)
{
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.Length;
while (i < l)
{
int count = packed[i++];
int value = packed[i++];
do result[j++] = value; while (--count > 0);
}
return j;
}
/// <summary>the input device</summary>
private TextReader zzReader;
/// <summary>the current state of the DFA</summary>
private int zzState;
/// <summary>the current lexical state</summary>
private int zzLexicalState = YYINITIAL;
/// <summary>
/// this buffer contains the current text to be matched and is
/// the source of the YyText string
/// </summary>
private char[] zzBuffer = new char[ZZ_BUFFERSIZE];
/// <summary>the textposition at the last accepting state</summary>
private int zzMarkedPos;
/// <summary>the current text position in the buffer</summary>
private int zzCurrentPos;
/// <summary>startRead marks the beginning of the YyText string in the buffer</summary>
private int zzStartRead;
/// <summary>
/// endRead marks the last character in the buffer, that has been read
/// from input
/// </summary>
private int zzEndRead;
/// <summary>number of newlines encountered up to the start of the matched text</summary>
private int yyline;
/// <summary>the number of characters up to the start of the matched text</summary>
private int yychar;
#pragma warning disable 169, 414
/// <summary>
/// the number of characters from the last newline up to the start of the
/// matched text
/// </summary>
private int yycolumn;
/// <summary>
/// zzAtBOL == true <=> the scanner is currently at the beginning of a line
/// </summary>
private bool zzAtBOL = true;
/// <summary>zzAtEOF == true <=> the scanner is at the EOF</summary>
private bool zzAtEOF;
/// <summary>denotes if the user-EOF-code has already been executed</summary>
private bool zzEOFDone;
#pragma warning disable 169, 414
/* user code: */
public static readonly int ALPHANUM = WikipediaTokenizer.ALPHANUM_ID;
public static readonly int APOSTROPHE = WikipediaTokenizer.APOSTROPHE_ID;
public static readonly int ACRONYM = WikipediaTokenizer.ACRONYM_ID;
public static readonly int COMPANY = WikipediaTokenizer.COMPANY_ID;
public static readonly int EMAIL = WikipediaTokenizer.EMAIL_ID;
public static readonly int HOST = WikipediaTokenizer.HOST_ID;
public static readonly int NUM = WikipediaTokenizer.NUM_ID;
public static readonly int CJ = WikipediaTokenizer.CJ_ID;
public static readonly int INTERNAL_LINK = WikipediaTokenizer.INTERNAL_LINK_ID;
public static readonly int EXTERNAL_LINK = WikipediaTokenizer.EXTERNAL_LINK_ID;
public static readonly int CITATION = WikipediaTokenizer.CITATION_ID;
public static readonly int CATEGORY = WikipediaTokenizer.CATEGORY_ID;
public static readonly int BOLD = WikipediaTokenizer.BOLD_ID;
public static readonly int ITALICS = WikipediaTokenizer.ITALICS_ID;
public static readonly int BOLD_ITALICS = WikipediaTokenizer.BOLD_ITALICS_ID;
public static readonly int HEADING = WikipediaTokenizer.HEADING_ID;
public static readonly int SUB_HEADING = WikipediaTokenizer.SUB_HEADING_ID;
public static readonly int EXTERNAL_LINK_URL = WikipediaTokenizer.EXTERNAL_LINK_URL_ID;
private int currentTokType;
private int numBalanced = 0;
private int positionInc = 1;
private int numLinkToks = 0;
//Anytime we start a new on a Wiki reserved token (category, link, etc.) this value will be 0, otherwise it will be the number of tokens seen
//this can be useful for detecting when a new reserved token is encountered
//see https://issues.apache.org/jira/browse/LUCENE-1133
private int numWikiTokensSeen = 0;
public static readonly string[] TOKEN_TYPES = WikipediaTokenizer.TOKEN_TYPES;
/// <summary>
/// Returns the number of tokens seen inside a category or link, etc.
/// </summary>
/// <returns>the number of tokens seen inside the context of wiki syntax.</returns>
public int NumWikiTokensSeen
{
get { return numWikiTokensSeen; }
}
public int YyChar
{
get { return yychar; }
}
public int PositionIncrement
{
get { return positionInc; }
}
/// <summary>
/// Fills Lucene token with the current token text.
/// </summary>
internal void GetText(ICharTermAttribute t)
{
t.CopyBuffer(zzBuffer, zzStartRead, zzMarkedPos - zzStartRead);
}
internal int SetText(StringBuilder buffer)
{
int length = zzMarkedPos - zzStartRead;
buffer.Append(zzBuffer, zzStartRead, length);
return length;
}
internal void Reset()
{
currentTokType = 0;
numBalanced = 0;
positionInc = 1;
numLinkToks = 0;
numWikiTokensSeen = 0;
}
/// <summary>
/// Creates a new scanner
/// </summary>
/// <param name="in">the TextReader to read input from.</param>
internal WikipediaTokenizerImpl(TextReader @in)
{
this.zzReader = @in;
}
/// <summary>
/// Unpacks the compressed character translation table.
/// </summary>
/// <param name="packed">the packed character translation table</param>
/// <returns>the unpacked character translation table</returns>
private static char[] ZzUnpackCMap(string packed)
{
char[] map = new char[0x10000];
int i = 0; /* index in packed string */
int j = 0; /* index in unpacked array */
while (i < 230)
{
int count = packed[i++];
char value = packed[i++];
do map[j++] = value; while (--count > 0);
}
return map;
}
/// <summary>
/// Refills the input buffer.
/// </summary>
/// <returns><c>false</c>, iff there was new input.</returns>
/// <exception cref="IOException">if any I/O-Error occurs</exception>
private bool ZzRefill()
{
/* first: make room (if you can) */
if (zzStartRead > 0)
{
System.Array.Copy(zzBuffer, zzStartRead,
zzBuffer, 0,
zzEndRead - zzStartRead);
/* translate stored positions */
zzEndRead -= zzStartRead;
zzCurrentPos -= zzStartRead;
zzMarkedPos -= zzStartRead;
zzStartRead = 0;
}
/* is the buffer big enough? */
if (zzCurrentPos >= zzBuffer.Length)
{
/* if not: blow it up */
char[] newBuffer = new char[zzCurrentPos * 2];
System.Array.Copy(zzBuffer, 0, newBuffer, 0, zzBuffer.Length);
zzBuffer = newBuffer;
}
/* readonlyly: fill the buffer with new input */
int numRead = zzReader.Read(zzBuffer, zzEndRead,
zzBuffer.Length - zzEndRead);
if (numRead > 0)
{
zzEndRead += numRead;
return false;
}
// unlikely but not impossible: read 0 characters, but not at end of stream
if (numRead == 0)
{
int c = zzReader.Read();
if (c == -1)
{
return true;
}
else
{
zzBuffer[zzEndRead++] = (char)c;
return false;
}
}
// numRead < 0
return true;
}
/// <summary>
/// Disposes the input stream.
/// </summary>
public void YyClose()
{
zzAtEOF = true; /* indicate end of file */
zzEndRead = zzStartRead; /* invalidate buffer */
if (zzReader != null)
{
zzReader.Dispose();
}
}
/// <summary>
/// Resets the scanner to read from a new input stream.
/// Does not close the old reader.
/// <para/>
/// All internal variables are reset, the old input stream
/// <b>cannot</b> be reused (internal buffer is discarded and lost).
/// Lexical state is set to <see cref="YYINITIAL"/>.
/// <para/>
/// Internal scan buffer is resized down to its initial length, if it has grown.
/// </summary>
/// <param name="reader">the new input stream </param>
public void YyReset(TextReader reader)
{
zzReader = reader;
zzAtBOL = true;
zzAtEOF = false;
zzEOFDone = false;
zzEndRead = zzStartRead = 0;
zzCurrentPos = zzMarkedPos = 0;
yyline = yychar = yycolumn = 0;
zzLexicalState = YYINITIAL;
if (zzBuffer.Length > ZZ_BUFFERSIZE)
zzBuffer = new char[ZZ_BUFFERSIZE];
}
/// <summary>
/// Returns the current lexical state.
/// </summary>
public int YyState
{
get { return zzLexicalState; }
}
/// <summary>
/// Enters a new lexical state
/// </summary>
/// <param name="newState">the new lexical state</param>
public void YyBegin(int newState)
{
zzLexicalState = newState;
}
/// <summary>
/// Returns the text matched by the current regular expression.
/// </summary>
public string YyText
{
get { return new string(zzBuffer, zzStartRead, zzMarkedPos - zzStartRead); }
}
/// <summary>
/// Returns the character at position <paramref name="pos"/> from the
/// matched text.
/// <para/>
/// It is equivalent to YyText[pos], but faster
/// </summary>
/// <param name="pos">
/// the position of the character to fetch.
/// A value from 0 to YyLength-1.
/// </param>
/// <returns>the character at position pos</returns>
public char YyCharAt(int pos)
{
return zzBuffer[zzStartRead + pos];
}
/// <summary>
/// Returns the length of the matched text region.
/// </summary>
public int YyLength
{
get { return zzMarkedPos - zzStartRead; }
}
/// <summary>
/// Reports an error that occured while scanning.
/// <para/>
/// In a wellformed scanner (no or only correct usage of
/// YyPushBack(int) and a match-all fallback rule) this method
/// will only be called with things that "Can't Possibly Happen".
/// If this method is called, something is seriously wrong
/// (e.g. a JFlex bug producing a faulty scanner etc.).
/// <para/>
/// Usual syntax/scanner level error handling should be done
/// in error fallback rules.
/// </summary>
/// <param name="errorCode">the code of the errormessage to display</param>
private void ZzScanError(int errorCode)
{
string message;
try
{
message = ZZ_ERROR_MSG[errorCode];
}
catch (IndexOutOfRangeException /*e*/)
{
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
throw new Exception(message);
}
/// <summary>
/// Pushes the specified amount of characters back into the input stream.
/// <para/>
/// They will be read again by then next call of the scanning method
/// </summary>
/// <param name="number">
/// the number of characters to be read again.
/// This number must not be greater than YyLength!
/// </param>
public void YyPushBack(int number)
{
if (number > YyLength)
ZzScanError(ZZ_PUSHBACK_2BIG);
zzMarkedPos -= number;
}
/// <summary>
/// Resumes scanning until the next regular expression is matched,
/// the end of input is encountered or an I/O-Error occurs.
/// </summary>
/// <returns>the next token</returns>
/// <exception cref="IOException">if any I/O-Error occurs</exception>
public int GetNextToken()
{
int zzInput;
int zzAction;
// cached fields:
int zzCurrentPosL;
int zzMarkedPosL;
int zzEndReadL = zzEndRead;
char[] zzBufferL = zzBuffer;
char[] zzCMapL = ZZ_CMAP;
int[] zzTransL = ZZ_TRANS;
int[] zzRowMapL = ZZ_ROWMAP;
int[] zzAttrL = ZZ_ATTRIBUTE;
while (true)
{
zzMarkedPosL = zzMarkedPos;
yychar += zzMarkedPosL - zzStartRead;
zzAction = -1;
zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL;
zzState = ZZ_LEXSTATE[zzLexicalState];
// set up zzAction for empty match case:
int zzAttributes = zzAttrL[zzState];
if ((zzAttributes & 1) == 1)
{
zzAction = zzState;
}
while (true)
{
if (zzCurrentPosL < zzEndReadL)
zzInput = zzBufferL[zzCurrentPosL++];
else if (zzAtEOF)
{
zzInput = YYEOF;
goto zzForActionBreak;
}
else
{
// store back cached positions
zzCurrentPos = zzCurrentPosL;
zzMarkedPos = zzMarkedPosL;
bool eof = ZzRefill();
// get translated positions and possibly new buffer
zzCurrentPosL = zzCurrentPos;
zzMarkedPosL = zzMarkedPos;
zzBufferL = zzBuffer;
zzEndReadL = zzEndRead;
if (eof)
{
zzInput = YYEOF;
goto zzForActionBreak;
}
else
{
zzInput = zzBufferL[zzCurrentPosL++];
}
}
int zzNext = zzTransL[zzRowMapL[zzState] + zzCMapL[zzInput]];
if (zzNext == -1) goto zzForActionBreak;
zzState = zzNext;
zzAttributes = zzAttrL[zzState];
if ((zzAttributes & 1) == 1)
{
zzAction = zzState;
zzMarkedPosL = zzCurrentPosL;
if ((zzAttributes & 8) == 8) goto zzForActionBreak;
}
}
zzForActionBreak:
// store back cached position
zzMarkedPos = zzMarkedPosL;
switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction])
{
case 1:
{
numWikiTokensSeen = 0; positionInc = 1; /* Break so we don't hit fall-through warning: */ break;
}
case 47: break;
case 2:
{
positionInc = 1; return ALPHANUM;
}
case 48: break;
case 3:
{
positionInc = 1; return CJ;
}
case 49: break;
case 4:
{
numWikiTokensSeen = 0; positionInc = 1; currentTokType = EXTERNAL_LINK_URL; YyBegin(EXTERNAL_LINK_STATE);/* Break so we don't hit fall-through warning: */ break;
}
case 50: break;
case 5:
{
positionInc = 1; /* Break so we don't hit fall-through warning: */ break;
}
case 51: break;
case 6:
{
YyBegin(CATEGORY_STATE); numWikiTokensSeen++; return currentTokType;
}
case 52: break;
case 7:
{
YyBegin(INTERNAL_LINK_STATE); numWikiTokensSeen++; return currentTokType;
}
case 53: break;
case 8:
{ /* Break so we don't hit fall-through warning: */
break;/* ignore */
}
case 54: break;
case 9:
{
if (numLinkToks == 0) { positionInc = 0; } else { positionInc = 1; }
numWikiTokensSeen++; currentTokType = EXTERNAL_LINK; YyBegin(EXTERNAL_LINK_STATE); numLinkToks++; return currentTokType;
}
case 55: break;
case 10:
{
numLinkToks = 0; positionInc = 0; YyBegin(YYINITIAL); /* Break so we don't hit fall-through warning: */ break;
}
case 56: break;
case 11:
{
currentTokType = BOLD; YyBegin(THREE_SINGLE_QUOTES_STATE); /* Break so we don't hit fall-through warning: */ break;
}
case 57: break;
case 12:
{
currentTokType = ITALICS; numWikiTokensSeen++; YyBegin(STRING); return currentTokType;/*italics*/
}
case 58: break;
case 13:
{
currentTokType = EXTERNAL_LINK; numWikiTokensSeen = 0; YyBegin(EXTERNAL_LINK_STATE); /* Break so we don't hit fall-through warning: */ break;
}
case 59: break;
case 14:
{
YyBegin(STRING); numWikiTokensSeen++; return currentTokType;
}
case 60: break;
case 15:
{
currentTokType = SUB_HEADING; numWikiTokensSeen = 0; YyBegin(STRING); /* Break so we don't hit fall-through warning: */ break;
}
case 61: break;
case 16:
{
currentTokType = HEADING; YyBegin(DOUBLE_EQUALS_STATE); numWikiTokensSeen++; return currentTokType;
}
case 62: break;
case 17:
{
YyBegin(DOUBLE_BRACE_STATE); numWikiTokensSeen = 0; return currentTokType;
}
case 63: break;
case 18:
{ /* Break so we don't hit fall-through warning: */
break;/* ignore STRING */
}
case 64: break;
case 19:
{
YyBegin(STRING); numWikiTokensSeen++; return currentTokType;/* STRING ALPHANUM*/
}
case 65: break;
case 20:
{
numBalanced = 0; numWikiTokensSeen = 0; currentTokType = EXTERNAL_LINK; YyBegin(EXTERNAL_LINK_STATE); /* Break so we don't hit fall-through warning: */ break;
}
case 66: break;
case 21:
{
YyBegin(STRING); return currentTokType;/*pipe*/
}
case 67: break;
case 22:
{
numWikiTokensSeen = 0; positionInc = 1; if (numBalanced == 0) { numBalanced++; YyBegin(TWO_SINGLE_QUOTES_STATE); } else { numBalanced = 0; }/* Break so we don't hit fall-through warning: */
break;
}
case 68: break;
case 23:
{
numWikiTokensSeen = 0; positionInc = 1; YyBegin(DOUBLE_EQUALS_STATE);/* Break so we don't hit fall-through warning: */ break;
}
case 69: break;
case 24:
{
numWikiTokensSeen = 0; positionInc = 1; currentTokType = INTERNAL_LINK; YyBegin(INTERNAL_LINK_STATE);/* Break so we don't hit fall-through warning: */ break;
}
case 70: break;
case 25:
{
numWikiTokensSeen = 0; positionInc = 1; currentTokType = CITATION; YyBegin(DOUBLE_BRACE_STATE);/* Break so we don't hit fall-through warning: */ break;
}
case 71: break;
case 26:
{
YyBegin(YYINITIAL);/* Break so we don't hit fall-through warning: */ break;
}
case 72: break;
case 27:
{
numLinkToks = 0; YyBegin(YYINITIAL); /* Break so we don't hit fall-through warning: */ break;
}
case 73: break;
case 28:
{
currentTokType = INTERNAL_LINK; numWikiTokensSeen = 0; YyBegin(INTERNAL_LINK_STATE); /* Break so we don't hit fall-through warning: */ break;
}
case 74: break;
case 29:
{
currentTokType = INTERNAL_LINK; numWikiTokensSeen = 0; YyBegin(INTERNAL_LINK_STATE); /* Break so we don't hit fall-through warning: */ break;
}
case 75: break;
case 30:
{
YyBegin(YYINITIAL); /* Break so we don't hit fall-through warning: */ break;
}
case 76: break;
case 31:
{
numBalanced = 0; currentTokType = ALPHANUM; YyBegin(YYINITIAL); /* Break so we don't hit fall-through warning: */ break;/*end italics*/
}
case 77: break;
case 32:
{
numBalanced = 0; numWikiTokensSeen = 0; currentTokType = INTERNAL_LINK; YyBegin(INTERNAL_LINK_STATE); /* Break so we don't hit fall-through warning: */ break;
}
case 78: break;
case 33:
{
positionInc = 1; return APOSTROPHE;
}
case 79: break;
case 34:
{
positionInc = 1; return HOST;
}
case 80: break;
case 35:
{
positionInc = 1; return NUM;
}
case 81: break;
case 36:
{
positionInc = 1; return COMPANY;
}
case 82: break;
case 37:
{
currentTokType = BOLD_ITALICS; YyBegin(FIVE_SINGLE_QUOTES_STATE); /* Break so we don't hit fall-through warning: */ break;
}
case 83: break;
case 38:
{
numBalanced = 0; currentTokType = ALPHANUM; YyBegin(YYINITIAL); /* Break so we don't hit fall-through warning: */ break;/*end bold*/
}
case 84: break;
case 39:
{
numBalanced = 0; currentTokType = ALPHANUM; YyBegin(YYINITIAL); /* Break so we don't hit fall-through warning: */ break;/*end sub header*/
}
case 85: break;
case 40:
{
positionInc = 1; return ACRONYM;
}
case 86: break;
case 41:
{
positionInc = 1; return EMAIL;
}
case 87: break;
case 42:
{
numBalanced = 0; currentTokType = ALPHANUM; YyBegin(YYINITIAL); /* Break so we don't hit fall-through warning: */ break;/*end bold italics*/
}
case 88: break;
case 43:
{
positionInc = 1; numWikiTokensSeen++; YyBegin(EXTERNAL_LINK_STATE); return currentTokType;
}
case 89: break;
case 44:
{
numWikiTokensSeen = 0; positionInc = 1; currentTokType = CATEGORY; YyBegin(CATEGORY_STATE);/* Break so we don't hit fall-through warning: */ break;
}
case 90: break;
case 45:
{
currentTokType = CATEGORY; numWikiTokensSeen = 0; YyBegin(CATEGORY_STATE); /* Break so we don't hit fall-through warning: */ break;
}
case 91: break;
case 46:
{
numBalanced = 0; numWikiTokensSeen = 0; currentTokType = CATEGORY; YyBegin(CATEGORY_STATE); /* Break so we don't hit fall-through warning: */ break;
}
case 92: break;
default:
if (zzInput == YYEOF && zzStartRead == zzCurrentPos)
{
zzAtEOF = true;
return YYEOF;
}
else
{
ZzScanError(ZZ_NO_MATCH);
}
break;
}
}
}
}
}
| 52.54 | 218 | 0.557047 | [
"Apache-2.0"
] | NikolayXHD/Lucene.Net.Contrib | Lucene.Net.Analysis.Common/Analysis/Wikipedia/WikipediaTokenizerImpl.cs | 57,796 | C# |
#region License
// Copyright (c) 2011, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This software is licensed under the Open Software License v3.0.
// For the complete license, see http://www.clearcanvas.ca/OSLv3.0//
#endregion
// This file is auto-generated by the ClearCanvas.Model.SqlServer.CodeGenerator project.
namespace ClearCanvas.ImageServer.Model.EntityBrokers
{
using System;
using System.Xml;
using ClearCanvas.Enterprise.Core;
using ClearCanvas.ImageServer.Enterprise;
public partial class StudySelectCriteria : EntitySelectCriteria
{
public StudySelectCriteria()
: base("Study")
{}
public StudySelectCriteria(StudySelectCriteria other)
: base(other)
{}
public override object Clone()
{
return new StudySelectCriteria(this);
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="StudyInstanceUid")]
public ISearchCondition<String> StudyInstanceUid
{
get
{
if (!SubCriteria.ContainsKey("StudyInstanceUid"))
{
SubCriteria["StudyInstanceUid"] = new SearchCondition<String>("StudyInstanceUid");
}
return (ISearchCondition<String>)SubCriteria["StudyInstanceUid"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="ServerPartitionGUID")]
public ISearchCondition<ServerEntityKey> ServerPartitionKey
{
get
{
if (!SubCriteria.ContainsKey("ServerPartitionKey"))
{
SubCriteria["ServerPartitionKey"] = new SearchCondition<ServerEntityKey>("ServerPartitionKey");
}
return (ISearchCondition<ServerEntityKey>)SubCriteria["ServerPartitionKey"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="PatientGUID")]
public ISearchCondition<ServerEntityKey> PatientKey
{
get
{
if (!SubCriteria.ContainsKey("PatientKey"))
{
SubCriteria["PatientKey"] = new SearchCondition<ServerEntityKey>("PatientKey");
}
return (ISearchCondition<ServerEntityKey>)SubCriteria["PatientKey"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="NumberOfStudyRelatedSeries")]
public ISearchCondition<Int32> NumberOfStudyRelatedSeries
{
get
{
if (!SubCriteria.ContainsKey("NumberOfStudyRelatedSeries"))
{
SubCriteria["NumberOfStudyRelatedSeries"] = new SearchCondition<Int32>("NumberOfStudyRelatedSeries");
}
return (ISearchCondition<Int32>)SubCriteria["NumberOfStudyRelatedSeries"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="NumberOfStudyRelatedInstances")]
public ISearchCondition<Int32> NumberOfStudyRelatedInstances
{
get
{
if (!SubCriteria.ContainsKey("NumberOfStudyRelatedInstances"))
{
SubCriteria["NumberOfStudyRelatedInstances"] = new SearchCondition<Int32>("NumberOfStudyRelatedInstances");
}
return (ISearchCondition<Int32>)SubCriteria["NumberOfStudyRelatedInstances"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="StudySizeInKB")]
public ISearchCondition<Decimal> StudySizeInKB
{
get
{
if (!SubCriteria.ContainsKey("StudySizeInKB"))
{
SubCriteria["StudySizeInKB"] = new SearchCondition<Decimal>("StudySizeInKB");
}
return (ISearchCondition<Decimal>)SubCriteria["StudySizeInKB"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="ResponsiblePerson")]
public ISearchCondition<String> ResponsiblePerson
{
get
{
if (!SubCriteria.ContainsKey("ResponsiblePerson"))
{
SubCriteria["ResponsiblePerson"] = new SearchCondition<String>("ResponsiblePerson");
}
return (ISearchCondition<String>)SubCriteria["ResponsiblePerson"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="ResponsibleOrganization")]
public ISearchCondition<String> ResponsibleOrganization
{
get
{
if (!SubCriteria.ContainsKey("ResponsibleOrganization"))
{
SubCriteria["ResponsibleOrganization"] = new SearchCondition<String>("ResponsibleOrganization");
}
return (ISearchCondition<String>)SubCriteria["ResponsibleOrganization"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="QueryXml")]
public ISearchCondition<XmlDocument> QueryXml
{
get
{
if (!SubCriteria.ContainsKey("QueryXml"))
{
SubCriteria["QueryXml"] = new SearchCondition<XmlDocument>("QueryXml");
}
return (ISearchCondition<XmlDocument>)SubCriteria["QueryXml"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="SpecificCharacterSet")]
public ISearchCondition<String> SpecificCharacterSet
{
get
{
if (!SubCriteria.ContainsKey("SpecificCharacterSet"))
{
SubCriteria["SpecificCharacterSet"] = new SearchCondition<String>("SpecificCharacterSet");
}
return (ISearchCondition<String>)SubCriteria["SpecificCharacterSet"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="StudyStorageGUID")]
public ISearchCondition<ServerEntityKey> StudyStorageKey
{
get
{
if (!SubCriteria.ContainsKey("StudyStorageKey"))
{
SubCriteria["StudyStorageKey"] = new SearchCondition<ServerEntityKey>("StudyStorageKey");
}
return (ISearchCondition<ServerEntityKey>)SubCriteria["StudyStorageKey"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="PatientsName")]
public ISearchCondition<String> PatientsName
{
get
{
if (!SubCriteria.ContainsKey("PatientsName"))
{
SubCriteria["PatientsName"] = new SearchCondition<String>("PatientsName");
}
return (ISearchCondition<String>)SubCriteria["PatientsName"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="PatientId")]
public ISearchCondition<String> PatientId
{
get
{
if (!SubCriteria.ContainsKey("PatientId"))
{
SubCriteria["PatientId"] = new SearchCondition<String>("PatientId");
}
return (ISearchCondition<String>)SubCriteria["PatientId"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="IssuerOfPatientId")]
public ISearchCondition<String> IssuerOfPatientId
{
get
{
if (!SubCriteria.ContainsKey("IssuerOfPatientId"))
{
SubCriteria["IssuerOfPatientId"] = new SearchCondition<String>("IssuerOfPatientId");
}
return (ISearchCondition<String>)SubCriteria["IssuerOfPatientId"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="PatientsBirthDate")]
public ISearchCondition<String> PatientsBirthDate
{
get
{
if (!SubCriteria.ContainsKey("PatientsBirthDate"))
{
SubCriteria["PatientsBirthDate"] = new SearchCondition<String>("PatientsBirthDate");
}
return (ISearchCondition<String>)SubCriteria["PatientsBirthDate"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="PatientsAge")]
public ISearchCondition<String> PatientsAge
{
get
{
if (!SubCriteria.ContainsKey("PatientsAge"))
{
SubCriteria["PatientsAge"] = new SearchCondition<String>("PatientsAge");
}
return (ISearchCondition<String>)SubCriteria["PatientsAge"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="PatientsSex")]
public ISearchCondition<String> PatientsSex
{
get
{
if (!SubCriteria.ContainsKey("PatientsSex"))
{
SubCriteria["PatientsSex"] = new SearchCondition<String>("PatientsSex");
}
return (ISearchCondition<String>)SubCriteria["PatientsSex"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="StudyDate")]
public ISearchCondition<String> StudyDate
{
get
{
if (!SubCriteria.ContainsKey("StudyDate"))
{
SubCriteria["StudyDate"] = new SearchCondition<String>("StudyDate");
}
return (ISearchCondition<String>)SubCriteria["StudyDate"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="StudyTime")]
public ISearchCondition<String> StudyTime
{
get
{
if (!SubCriteria.ContainsKey("StudyTime"))
{
SubCriteria["StudyTime"] = new SearchCondition<String>("StudyTime");
}
return (ISearchCondition<String>)SubCriteria["StudyTime"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="AccessionNumber")]
public ISearchCondition<String> AccessionNumber
{
get
{
if (!SubCriteria.ContainsKey("AccessionNumber"))
{
SubCriteria["AccessionNumber"] = new SearchCondition<String>("AccessionNumber");
}
return (ISearchCondition<String>)SubCriteria["AccessionNumber"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="StudyId")]
public ISearchCondition<String> StudyId
{
get
{
if (!SubCriteria.ContainsKey("StudyId"))
{
SubCriteria["StudyId"] = new SearchCondition<String>("StudyId");
}
return (ISearchCondition<String>)SubCriteria["StudyId"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="StudyDescription")]
public ISearchCondition<String> StudyDescription
{
get
{
if (!SubCriteria.ContainsKey("StudyDescription"))
{
SubCriteria["StudyDescription"] = new SearchCondition<String>("StudyDescription");
}
return (ISearchCondition<String>)SubCriteria["StudyDescription"];
}
}
[EntityFieldDatabaseMappingAttribute(TableName="Study", ColumnName="ReferringPhysiciansName")]
public ISearchCondition<String> ReferringPhysiciansName
{
get
{
if (!SubCriteria.ContainsKey("ReferringPhysiciansName"))
{
SubCriteria["ReferringPhysiciansName"] = new SearchCondition<String>("ReferringPhysiciansName");
}
return (ISearchCondition<String>)SubCriteria["ReferringPhysiciansName"];
}
}
}
}
| 40.379421 | 125 | 0.568164 | [
"Apache-2.0"
] | SNBnani/Xian | ImageServer/Model/EntityBrokers/StudySelectCriteria.gen.cs | 12,558 | C# |
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
namespace GrpcNetProxyTest.Setup
{
/// <summary>
/// Test logger provider
/// </summary>
public class TestLoggerProvider : ILoggerProvider
{
/// <summary>
/// Test log sink
/// </summary>
public class TestLogSink
{
public List<string> Logs { get; private set; } = new List<string>();
public void AddEntry(string logEntry) => Logs.Add(logEntry);
}
/// <summary>
/// Test logger
/// </summary>
public class TestLogger : ILogger
{
private readonly string _categoryName;
private readonly Action<string> _addEntryAction;
public TestLogger(string categoryName, Action<string> addEntryAction)
{
_categoryName = categoryName;
_addEntryAction = addEntryAction;
}
public IDisposable BeginScope<TState>(TState state)
{
throw new NotImplementedException();
}
public bool IsEnabled(LogLevel logLevel)
{
return true;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
var logEntry = $"{_categoryName}:{state.ToString()}";
_addEntryAction.Invoke(logEntry);
}
}
private readonly TestLogSink _sink;
public TestLoggerProvider(TestLogSink sink)
{
_sink = sink;
}
public ILogger CreateLogger(string categoryName)
{
return new TestLogger(categoryName, (value) => _sink.AddEntry(value));
}
public void Dispose()
{
}
}
}
| 26.027397 | 149 | 0.552632 | [
"MIT"
] | jrozac/GrpcNetProxy | test/GrpcNetProxyTest/Setup/TestLoggerProvider.cs | 1,902 | C# |
using System;
using System.ComponentModel;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
namespace Rawr.RestoSham
{
public enum Faction
{
None,
Aldor,
Scryers
}
public partial class CalculationOptionsPanelRestoSham : CalculationOptionsPanelBase
{
private bool _bLoading = false;
public CalculationOptionsPanelRestoSham()
{
InitializeComponent();
txtFightLength.Tag = new NumericField("FightLength", 1f, 60f, false);
txtOutsideFSR.Tag = new NumericField("OutsideFSRPct", 0f, 75f, true);
txtSPriestMp5.Tag = new NumericField("SPriestMP5", 0f, 500f, true);
txtManaPotInterval.Tag = new NumericField("ManaPotTime", 2f, float.MaxValue, true);
txtHWRatio.Tag = new NumericField("HWRatio", 0f, 100f, true);
txtLHWRatio.Tag = new NumericField("LHWRatio", 0f, 100f, true);
txtCHRatio.Tag = new NumericField("CHRatio", 0f, 100f, true);
txtESInterval.Tag = new NumericField("ESInterval", 40f, 1000f, true);
cboManaPotAmount.Tag = new NumericField("ManaPotAmount", 0f, 3000f, true);
cboNumCHTargets.Items.Add(1);
cboNumCHTargets.Items.Add(2);
cboNumCHTargets.Items.Add(3);
cboESRank.Items.Add(1);
cboESRank.Items.Add(2);
cboESRank.Items.Add(3);
cboHWTotem.Items.Add(new TotemRelic());
cboLHWTotem.Items.Add(new TotemRelic());
cboCHTotem.Items.Add(new TotemRelic());
cboHWTotem.Tag = HealSpells.HealingWave;
cboLHWTotem.Tag = HealSpells.LesserHealingWave;
cboCHTotem.Tag = HealSpells.ChainHeal;
foreach (TotemRelic totem in TotemRelic.TotemList)
{
if (totem.AppliesTo == HealSpells.HealingWave)
cboHWTotem.Items.Add(totem);
else if (totem.AppliesTo == HealSpells.LesserHealingWave)
cboLHWTotem.Items.Add(totem);
else
cboCHTotem.Items.Add(totem);
}
}
protected override void LoadCalculationOptions()
{
if (Character.CalculationOptions == null)
Character.CalculationOptions = new CalculationOptionsRestoSham();
CalculationOptionsRestoSham options = Character.CalculationOptions as CalculationOptionsRestoSham;
_bLoading = true;
// Init General tab page:
txtFightLength.Text = options.FightLength.ToString();
txtOutsideFSR.Text = Math.Round(100 * options.OutsideFSRPct, 0).ToString();
txtSPriestMp5.Text = options.SPriestMP5.ToString();
cboManaPotAmount.Text = options.ManaPotAmount.ToString();
txtManaPotInterval.Text = options.ManaPotTime.ToString();
chkManaTide.Checked = options.ManaTideEveryCD;
chkWaterShield.Checked = options.WaterShield;
radioAldor.Checked = (options.ExaltedFaction == Faction.Aldor);
radioScryers.Checked = (options.ExaltedFaction == Faction.Scryers);
chkExalted.Checked = (options.ExaltedFaction != Faction.None);
// Init Spells tab page:
txtHWRatio.Text = options.HWRatio.ToString();
txtLHWRatio.Text = options.LHWRatio.ToString();
txtCHRatio.Text = options.CHRatio.ToString();
txtESInterval.Text = options.ESInterval.ToString();
cboESRank.SelectedIndex = options.ESRank - 1;
cboNumCHTargets.SelectedIndex = options.NumCHTargets - 1;
trkHW.Value = 100 - options.HWDownrank.Ratio;
trkCH.Value = 100 - options.CHDownrank.Ratio;
lblHWMaxPct.Text = String.Format("{0}%", 100 - trkHW.Value);
lblHWMinPct.Text = String.Format("{0}%", trkHW.Value);
lblCHMaxPct.Text = String.Format("{0}%", 100 - trkCH.Value);
lblCHMinPct.Text = String.Format("{0}%", trkCH.Value);
SetRankBoxes(cboHWMaxRank, cboHWMinRank, options.HWDownrank.MaxRank, options.HWDownrank.MinRank, 12);
SetRankBoxes(cboCHMaxRank, cboCHMinRank, options.CHDownrank.MaxRank, options.CHDownrank.MinRank, 5);
// Init Totems tab page:
cboHWTotem.SelectedIndex = FindIndex(cboHWTotem, options.Totems[HealSpells.HealingWave]);
cboLHWTotem.SelectedIndex = FindIndex(cboLHWTotem, options.Totems[HealSpells.LesserHealingWave]);
cboCHTotem.SelectedIndex = FindIndex(cboCHTotem, options.Totems[HealSpells.ChainHeal]);
chkEquipTotems.Checked = options.EquipTotemsDuringFight;
_bLoading = false;
}
private int FindIndex(ComboBox cbox, TotemRelic totem)
{
foreach (TotemRelic t in cbox.Items)
if (t.Equals(totem))
return cbox.Items.IndexOf(t);
return -1;
}
private bool _bInSetRankBoxes = false;
private void SetRankBoxes(ComboBox cboMax, ComboBox cboMin, int? maxRank, int? minRank, int maxSpellRank)
{
if (_bInSetRankBoxes)
return;
_bInSetRankBoxes = true;
// Bounds checking:
int iMax = maxRank ?? maxSpellRank;
int iMin = minRank ?? 1;
if (iMax > maxSpellRank)
iMax = maxSpellRank;
if (iMax < 2)
iMax = 2;
if (iMin >= iMax)
iMin = iMax - 1;
// Set textbox values and adjust choices:
if (maxRank.HasValue)
{
cboMax.Items.Clear();
for (int i = maxSpellRank; i > iMin; i--)
cboMax.Items.Add(i);
cboMax.SelectedItem = iMax;
}
if (minRank.HasValue)
{
cboMin.Items.Clear();
for (int i = iMax - 1; i >= 1; i--)
cboMin.Items.Add(i);
cboMin.SelectedItem = iMin;
}
_bInSetRankBoxes = false;
}
private void cboLHWTotem_SelectedIndexChanged(object sender, EventArgs e)
{
TotemRelic totem = cboLHWTotem.SelectedItem as TotemRelic;
lblLHWTotemDesc.Text = totem.Description;
if (!_bLoading)
{
if (totem.ID != 0 && !chkEquipTotems.Checked)
{
cboHWTotem.SelectedIndex = 0;
cboCHTotem.SelectedIndex = 0;
}
((CalculationOptionsRestoSham)(Character.CalculationOptions)).Totems[HealSpells.LesserHealingWave] = totem;
Character.OnItemsChanged();
}
}
private void cboHWTotem_SelectedIndexChanged(object sender, EventArgs e)
{
TotemRelic totem = cboHWTotem.SelectedItem as TotemRelic;
lblHWTotemDesc.Text = totem.Description;
if (!_bLoading)
{
if (totem.ID != 0 && !chkEquipTotems.Checked)
{
cboLHWTotem.SelectedIndex = 0;
cboCHTotem.SelectedIndex = 0;
}
((CalculationOptionsRestoSham)(Character.CalculationOptions)).Totems[HealSpells.HealingWave] = totem;
Character.OnItemsChanged();
}
}
private void cboCHTotem_SelectedIndexChanged(object sender, EventArgs e)
{
TotemRelic totem = cboCHTotem.SelectedItem as TotemRelic;
lblCHTotemDesc.Text = totem.Description;
if (!_bLoading)
{
if (totem.ID != 0 && !chkEquipTotems.Checked)
{
cboLHWTotem.SelectedIndex = 0;
cboHWTotem.SelectedIndex = 0;
}
((CalculationOptionsRestoSham)(Character.CalculationOptions)).Totems[HealSpells.ChainHeal] = totem;
Character.OnItemsChanged();
}
}
private void chkEquipTotems_CheckedChanged(object sender, EventArgs e)
{
if (!_bLoading)
{
((CalculationOptionsRestoSham)(Character.CalculationOptions)).EquipTotemsDuringFight = chkEquipTotems.Checked;
if (!chkEquipTotems.Checked)
{
if (cboHWTotem.SelectedIndex != 0)
{
cboLHWTotem.SelectedIndex = 0;
cboCHTotem.SelectedIndex = 0;
}
else if (cboLHWTotem.SelectedIndex != 0)
cboCHTotem.SelectedIndex = 0;
}
Character.OnItemsChanged();
}
}
private void SetHWComboBoxes()
{
SetRankBoxes(cboHWMaxRank, cboHWMinRank, (int?)cboHWMaxRank.SelectedItem, (int?)cboHWMinRank.SelectedItem, 12);
}
private void cboHWMaxRank_SelectedIndexChanged(object sender, EventArgs e)
{
if (Character != null && !_bLoading)
{
((CalculationOptionsRestoSham)(Character.CalculationOptions)).HWDownrank.MaxRank = (int)cboHWMaxRank.SelectedItem;
Character.OnItemsChanged();
}
SetHWComboBoxes();
}
private void cboHWMinRank_SelectedIndexChanged(object sender, EventArgs e)
{
if (Character != null && !_bLoading)
{
((CalculationOptionsRestoSham)(Character.CalculationOptions)).HWDownrank.MinRank = (int)cboHWMinRank.SelectedItem;
Character.OnItemsChanged();
}
SetHWComboBoxes();
}
private void SetCHComboBoxes()
{
SetRankBoxes(cboCHMaxRank, cboCHMinRank, (int?)cboCHMaxRank.SelectedItem, (int?)cboCHMinRank.SelectedItem, 5);
}
private void cboCHMaxRank_SelectedIndexChanged(object sender, EventArgs e)
{
if (Character != null && !_bLoading)
{
((CalculationOptionsRestoSham)(Character.CalculationOptions)).CHDownrank.MaxRank = (int)cboCHMaxRank.SelectedItem;
Character.OnItemsChanged();
}
SetCHComboBoxes();
}
private void cboCHMinRank_SelectedIndexChanged(object sender, EventArgs e)
{
if (Character != null && !_bLoading)
{
((CalculationOptionsRestoSham)(Character.CalculationOptions)).CHDownrank.MinRank = (int)cboCHMinRank.SelectedItem;
Character.OnItemsChanged();
}
SetCHComboBoxes();
}
private void trkHW_ValueChanged(object sender, EventArgs e)
{
if (!_bLoading)
{
((CalculationOptionsRestoSham)(Character.CalculationOptions)).HWDownrank.Ratio = 100 - trkHW.Value;
Character.OnItemsChanged();
}
lblHWMaxPct.Text = String.Format("{0}%", 100 - trkHW.Value);
lblHWMinPct.Text = String.Format("{0}%", trkHW.Value);
}
private void trkCH_ValueChanged(object sender, EventArgs e)
{
if (!_bLoading)
{
((CalculationOptionsRestoSham)(Character.CalculationOptions)).CHDownrank.Ratio = 100 - trkCH.Value;
Character.OnItemsChanged();
}
lblCHMaxPct.Text = String.Format("{0}%", 100 - trkCH.Value);
lblCHMinPct.Text = String.Format("{0}%", trkCH.Value);
}
private void numericTextBox_Validated(object sender, EventArgs e)
{
if (_bLoading || Character == null)
return;
Control txtBox = sender as Control;
if (txtBox.Tag == null)
return;
NumericField info = txtBox.Tag as NumericField;
this[info.PropertyName] = float.Parse(txtBox.Text);
Character.OnItemsChanged();
}
private void numericTextBox_Validating(object sender, CancelEventArgs e)
{
Control txtBox = sender as Control;
if (txtBox.Tag == null)
return;
NumericField info = txtBox.Tag as NumericField;
float f;
string szError = string.Empty;
if (!float.TryParse(txtBox.Text, out f))
szError = "Please enter a numeric value";
else
{
if (f < info.MinValue || f > info.MaxValue)
if (f == 0f && !info.CanBeZero)
{
if (info.MinValue == float.MinValue)
{
if (info.MaxValue == float.MaxValue)
szError = "Please enter a numeric value";
else
szError = "Please enter a number less than " + info.MaxValue.ToString();
}
else
{
if (info.MaxValue == float.MaxValue)
szError = "Please enter a number larger than " + info.MinValue.ToString();
else
szError = "Please enter a number between " + info.MinValue.ToString() + " and " +
info.MaxValue.ToString();
}
}
}
if (!string.IsNullOrEmpty(szError))
{
e.Cancel = true;
errorRestoSham.SetError(sender as Control, szError);
}
}
public object this[string szFieldName]
{
get
{
CalculationOptionsRestoSham options = Character.CalculationOptions as CalculationOptionsRestoSham;
Type t = options.GetType();
FieldInfo field = t.GetField(szFieldName);
if (field != null)
return field.GetValue(options);
return null;
}
set
{
CalculationOptionsRestoSham options = Character.CalculationOptions as CalculationOptionsRestoSham;
Type t = options.GetType();
FieldInfo field = t.GetField(szFieldName);
if (field != null)
field.SetValue(options, value);
}
}
private void cboNumCHTargets_SelectedIndexChanged(object sender, EventArgs e)
{
if (!_bLoading)
{
this["NumCHTargets"] = cboNumCHTargets.SelectedIndex + 1;
Character.OnItemsChanged();
}
}
private void chkManaTide_CheckedChanged(object sender, EventArgs e)
{
if (!_bLoading)
{
this["ManaTideEveryCD"] = chkManaTide.Checked;
Character.OnItemsChanged();
}
}
private void chkWaterShield_CheckedChanged(object sender, EventArgs e)
{
if (!_bLoading)
{
this["WaterShield"] = chkWaterShield.Checked;
Character.OnItemsChanged();
}
}
private void cboESRank_SelectedIndexChanged(object sender, EventArgs e)
{
if (!_bLoading)
{
this["ESRank"] = cboESRank.SelectedIndex + 1;
Character.OnItemsChanged();
}
}
private void radioAldor_CheckedChanged(object sender, EventArgs e)
{
RadioButton btn = sender as RadioButton;
if (!btn.Checked)
return;
Faction faction = (btn.Name == "radioAldor" ? Faction.Aldor : Faction.Scryers);
RadioButton otherBtn = (faction == Faction.Aldor ? radioScryers : radioAldor);
otherBtn.Checked = false;
if (!_bLoading)
{
this["ExaltedFaction"] = faction;
Character.OnItemsChanged();
}
}
private void chkExalted_CheckedChanged(object sender, EventArgs e)
{
radioAldor.Enabled = chkExalted.Checked;
radioScryers.Enabled = chkExalted.Checked;
if (!chkExalted.Checked)
{
this["ExaltedFaction"] = Faction.None;
Character.OnItemsChanged();
return;
}
if (!radioAldor.Checked && !radioScryers.Checked)
radioAldor.Checked = true;
else if (!_bLoading)
{
this["ExaltedFaction"] = (radioAldor.Checked ? Faction.Aldor : Faction.Scryers);
Character.OnItemsChanged();
}
}
}
class NumericField
{
public NumericField(string szName, float min, float max, bool bzero)
{
PropertyName = szName;
MinValue = min;
MaxValue = max;
CanBeZero = bzero;
}
public string PropertyName = string.Empty;
public float MinValue = float.MinValue;
public float MaxValue = float.MaxValue;
public bool CanBeZero = false;
}
[Serializable]
public class CalculationOptionsRestoSham : ICalculationOptionBase
{
public string GetXml()
{
System.Xml.Serialization.XmlSerializer serializer =
new System.Xml.Serialization.XmlSerializer(typeof(CalculationOptionsRestoSham));
StringBuilder xml = new StringBuilder();
System.IO.StringWriter writer = new System.IO.StringWriter(xml);
serializer.Serialize(writer, this);
return xml.ToString();
}
/// <summary>
/// Fight length, in minutes.
/// </summary>
public float FightLength = 5.0f;
/// <summary>
/// Percentage of time during the fight spent outside the FSR.
/// </summary>
public float OutsideFSRPct = 0.0f;
/// <summary>
/// Average amount restored by a mana potion.
/// </summary>
public float ManaPotAmount = 2400f;
/// <summary>
/// Interval of time between mana potion uses, in minutes.
/// </summary>
public float ManaPotTime = 2.25f;
/// <summary>
/// Mp5 received from Shadow Priest(s).
/// </summary>
public float SPriestMP5 = 0f;
/// <summary>
/// Whether a Mana Tide totem is placed every time the cooldown is up.
/// </summary>
public bool ManaTideEveryCD = true;
/// <summary>
/// Whether we keep Water Shield up or not (could use Earth Shield during some fights).
/// </summary>
public bool WaterShield = true;
/// <summary>
/// Used (with LHWRatio and CHRatio) to determine the ratio of HW : LHW : CH cast during the fight.
/// </summary>
public float HWRatio = 5.0f;
/// <summary>
/// Used (with HWRatio and CHRatio) to determine the ratio of HW : LHW : CH cast during the fight.
/// </summary>
public float LHWRatio = 5.0f;
/// <summary>
/// Used (with HWRatio and LHWRatio) to determine the ratio of HW : LHW : CH cast during the fight.
/// </summary>
public float CHRatio = 85.0f;
/// <summary>
/// Interval of time between Earth Shield casts, in seconds.
/// </summary>
public float ESInterval = 60f;
/// <summary>
/// Rank of Earth Shield that is used.
/// </summary>
public int ESRank = 3;
/// <summary>
/// Average number of targets healed by Chain Heal.
/// </summary>
public int NumCHTargets = 2;
/// <summary>
/// Information about downranking of Healing Wave during the fight.
/// </summary>
public DownrankInfo HWDownrank = new DownrankInfo(12, 8, 100);
/// <summary>
/// Information about downranking of Chain Heal during the fight.
/// </summary>
public DownrankInfo CHDownrank = new DownrankInfo(5, 3, 100);
/// <summary>
/// A dictionary that contains the totem used during the fight for each spell.
/// </summary>
public SerializableDictionary<HealSpells, TotemRelic> Totems;
/// <summary>
/// Whether or not to equip different totems during the fight.
/// </summary>
public bool EquipTotemsDuringFight = true;
/// <summary>
/// Which faction (Aldor, Scryers) we are exalted with (if any).
/// </summary>
public Faction ExaltedFaction = Faction.None;
[XmlIgnore]
public float HWWeight
{
get { return (HWRatio / (HWRatio + LHWRatio + CHRatio)); }
}
[XmlIgnore]
public float LHWWeight
{
get { return (LHWRatio / (HWRatio + LHWRatio + CHRatio)); }
}
[XmlIgnore]
public float CHWeight
{
get { return (CHRatio / (HWRatio + LHWRatio + CHRatio)); }
}
public CalculationOptionsRestoSham()
{
Totems = new SerializableDictionary<HealSpells, TotemRelic>();
Totems.Add(HealSpells.HealingWave, new TotemRelic());
Totems.Add(HealSpells.LesserHealingWave, new TotemRelic());
Totems.Add(HealSpells.ChainHeal, new TotemRelic());
}
}
[Serializable]
public class DownrankInfo
{
public DownrankInfo()
{
}
public DownrankInfo(int max, int min, int ratio)
{
MaxRank = max;
MinRank = min;
Ratio = ratio;
}
/// <summary>
/// Higher rank cast.
/// </summary>
public int MaxRank;
/// <summary>
/// Lower rank cast.
/// </summary>
public int MinRank;
/// <summary>
/// Ratio of MaxRank to MinRank spells cast.
/// </summary>
public int Ratio;
}
}
| 35.74415 | 131 | 0.53077 | [
"Apache-2.0"
] | satelliteprogrammer/rawr | Rawr.RestoSham/CalculationOptionsPanelRestoSham.cs | 22,914 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Coderr.Client.Config;
using Coderr.Client.ContextCollections;
using Coderr.Client.Contracts;
using Coderr.Client.Reporters;
namespace Coderr.Client.Processor
{
/// <summary>
/// Will process the exception to generate context info and then upload it to the server.
/// </summary>
public class ExceptionProcessor : IExceptionProcessor
{
internal const string AlreadyReportedSetting = "ErrSetting.Reported";
internal const string AppAssemblyVersion = "AppAssemblyVersion";
private readonly CoderrConfiguration _configuration;
/// <summary>
/// Creates a new instance of <see cref="ExceptionProcessor" />.
/// </summary>
/// <param name="configuration">Current configuration.</param>
/// <exception cref="ArgumentNullException">configuration</exception>
public ExceptionProcessor(CoderrConfiguration configuration)
{
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
}
/// <summary>
/// Build an report, but do not upload it
/// </summary>
/// <param name="exception">caught exception</param>
/// <remarks>
/// <para>
/// Will collect context info and generate a report.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">exception</exception>
public ErrorReportDTO Build(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
if (IsReported(exception))
return null;
var context = new ErrorReporterContext(null, exception);
return Build(context);
}
/// <summary>
/// Build an report, but do not upload it
/// </summary>
/// <param name="exception">caught exception</param>
/// <param name="contextData">context data</param>
/// <remarks>
/// <para>
/// Will collect context info and generate a report.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">exception;contextData</exception>
public ErrorReportDTO Build(Exception exception, object contextData)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
if (contextData == null) throw new ArgumentNullException(nameof(contextData));
if (IsReported(exception))
return null;
var context = new ErrorReporterContext(null, exception);
AppendCustomContextData(contextData, context.ContextCollections);
return Build(context);
}
/// <summary>
/// Build an report, but do not upload it
/// </summary>
/// <param name="context">
/// context passed to all context providers when collecting information. This context is typically
/// implemented by one of the integration libraries to provide more context that can be used to process the
/// environment.
/// </param>
/// <remarks>
/// <para>
/// Will collect context info and generate a report.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">exception;contextData</exception>
public ErrorReportDTO Build(IErrorReporterContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (context.Exception is CoderrClientException)
return null;
if (IsReported(context.Exception))
return null;
ErrorReporterContext.MoveCollectionsInException(context.Exception, context.ContextCollections);
InvokePreProcessor(context);
_configuration.ContextProviders.Collect(context);
// Invoke partition collection AFTER other context info providers
// since those other collections might provide the property that
// we want to create partions on.
InvokePartitionCollection(context);
var reportId = ReportIdGenerator.Generate(context.Exception);
AddAddemblyVersion(context.ContextCollections);
var report = new ErrorReportDTO(reportId, new ExceptionDTO(context.Exception),
context.ContextCollections.ToArray())
{
EnvironmentName = _configuration.EnvironmentName,
LogEntries = (context as IContextWithLogEntries)?.LogEntries
};
return report;
}
/// <summary>
/// Process exception.
/// </summary>
/// <param name="exception">caught exception</param>
/// <remarks>
/// <para>
/// Will collect context info, generate a report, go through filters and finally upload it.
/// </para>
/// </remarks>
public void Process(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
if (IsReported(exception))
return;
var report = Build(exception);
if (UploadReportIfAllowed(report))
MarkAsReported(exception);
}
/// <summary>
/// Process exception.
/// </summary>
/// <param name="context">
/// Used to reports (like for ASP.NET) can attach information which can be used during the context
/// collection pipeline.
/// </param>
/// <remarks>
/// <para>
/// Will collect context info, generate a report, go through filters and finally upload it.
/// </para>
/// </remarks>
/// <seealso cref="IReportFilter" />
public void Process(IErrorReporterContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (IsReported(context.Exception))
return;
ErrorReporterContext.MoveCollectionsInException(context.Exception, context.ContextCollections);
var report = Build(context);
if (UploadReportIfAllowed(report))
MarkAsReported(context.Exception);
}
/// <summary>
/// Process exception and upload the generated error report (along with context data)
/// </summary>
/// <param name="exception">caught exception</param>
/// <param name="contextData">Context data</param>
/// <remarks>
/// <para>
/// Will collect context info, generate a report, go through filters and finally upload it.
/// </para>
/// <para>
/// Do note that reports can be discarded if a filter in <c>Err.Configuration.FilterCollection</c> says so.
/// </para>
/// </remarks>
public void Process(Exception exception, object contextData)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
if (IsReported(exception))
return;
var report = Build(exception, contextData);
if (UploadReportIfAllowed(report))
MarkAsReported(exception);
}
internal void AddAddemblyVersion(IList<ContextCollectionDTO> contextInfo)
{
if (_configuration.ApplicationVersion == null)
return;
var col = contextInfo.GetCoderrCollection();
col.Properties.Add(AppAssemblyVersion, _configuration.ApplicationVersion);
contextInfo.Add(col);
}
private static void AppendCustomContextData(object contextData, IList<ContextCollectionDTO> contextInfo)
{
if (contextData is IEnumerable<ContextCollectionDTO> dtos)
{
var arr = dtos;
foreach (var dto in arr)
contextInfo.Add(dto);
}
else
{
var col = contextData.ToContextCollection();
if (col.Properties.ContainsKey("ErrTags"))
{
var coderrCollection = contextInfo.GetCoderrCollection();
if (coderrCollection.Properties.TryGetValue("ErrTags", out var value))
{
coderrCollection.Properties["ErrTags"] = value + "," + col.Properties["ErrTags"];
}
else
{
coderrCollection.Properties["ErrTags"] = col.Properties["ErrTags"];
}
col.Properties.Remove("ErrTags");
}
if (col.Properties.Count > 0)
contextInfo.Add(col);
}
}
private void InvokePartitionCollection(IErrorReporterContext context)
{
var col = context.GetCoderrCollection();
var partitionContext = new PartitionContext(col, context);
foreach (var callback in _configuration.PartitionCallbacks)
{
try
{
callback(partitionContext);
}
catch (Exception ex)
{
col.Properties.Add("PartitionCollection.Err", $"Callback {callback} failed: {ex}");
}
}
}
private void InvokePreProcessor(IErrorReporterContext context)
{
_configuration.ExceptionPreProcessor?.Invoke(context);
}
private bool IsReported(Exception exception)
{
return exception.Data.Contains(AlreadyReportedSetting);
}
private void MarkAsReported(Exception exception)
{
exception.Data[AlreadyReportedSetting] = true;
}
private bool UploadReportIfAllowed(ErrorReportDTO report)
{
if (report == null) throw new ArgumentNullException(nameof(report));
var canUpload = _configuration.FilterCollection.CanUploadReport(report);
if (!canUpload)
return false;
_configuration.Uploaders.Upload(report);
return true;
}
}
} | 39.395604 | 124 | 0.558345 | [
"Apache-2.0"
] | aTiKhan/Coderr.Client | src/Coderr.Client/Processor/ExceptionProcessor.cs | 10,757 | C# |
using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using System;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections.ObjectModel;
using NAudio.Midi;
namespace NAudioTests
{
public partial class Form1 : Form
{
private AudioFileReader stream = null;
private WaveOutEvent output = null;
private MonoToStereoSampleProvider stereo = null;
private SmbPitchShiftingSampleProvider pitch = null;
private WaveInEvent waveIn = new WaveInEvent();
private WaveFileWriter writer = null;
private WasapiLoopbackCapture capture = null;
private WaveOutEvent wo = null;
bool closing = false;
delegate void RecordingStoppedEventHandler(object source, EventArgs e);
public Form1()
{
InitializeComponent();
NAudio.CoreAudioApi.MMDeviceEnumerator enumerator = new NAudio.CoreAudioApi.MMDeviceEnumerator();
var devices = enumerator.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.All, NAudio.CoreAudioApi.DeviceState.Active);
comboBox1.Items.AddRange(devices.ToArray());
comboBox1.SelectedIndex = 1;
List<string> waves = new List<string>();
waves.Add("Sin");
waves.Add("Triangle");
waves.Add("Square");
waves.Add("SawTooth");
waves.Add("PinkNoise");
waves.Add("WhiteNoise");
waves.Add("Sweep");
cb_waves.DataSource = waves;
vsb_volumeL.Value = 50;
lb_volumeL.Text = "50";
lb_volumeR.Text = "50";
lb_volumeM.Text = "50";
btn_stop.Enabled = false;
btn_pause.Enabled = false;
trb_progress.Enabled = false;
vsb_volumeL.Enabled = false;
vsb_volumeR.Enabled = false;
vsb_volumeM.Enabled = false;
cb_controle.Enabled = false;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void timer1_Tick_1(object sender, EventArgs e)
{
if (output != null)
{
if (comboBox1.SelectedItem != null)
{
var device = (NAudio.CoreAudioApi.MMDevice)comboBox1.SelectedItem;
if ((int)(Math.Round(device.AudioMeterInformation.MasterPeakValue * 100)) < progressBar1.Maximum)
{
progressBar1.Value = (int)(Math.Round(device.AudioMeterInformation.MasterPeakValue * 100));
}
else
{
progressBar1.Value = progressBar1.Maximum;
}
if ((int)(Math.Round(device.AudioMeterInformation.PeakValues[0] * 100)) < progressBar2.Maximum)
{
progressBar2.Value = (int)(Convert.ToSingle(device.AudioMeterInformation.PeakValues[0].ToString()) * 100);
}
else
{
progressBar2.Value = progressBar2.Maximum;
}
if ((int)(Math.Round(device.AudioMeterInformation.PeakValues[1] * 100)) < progressBar3.Maximum)
{
progressBar3.Value = (int)(Convert.ToSingle(device.AudioMeterInformation.PeakValues[1].ToString()) * 100);
}
else
{
progressBar3.Value = progressBar3.Maximum;
}
if (((progressBar2.Value / 3) + progressBar3.Value) < progressBar4.Maximum)
{
progressBar4.Value = (progressBar2.Value / 3) + progressBar3.Value;
}
else
{
progressBar4.Value = progressBar4.Maximum;
}
progressBar6.Value = progressBar3.Value;
progressBar7.Value = progressBar1.Value;
progressBar8.Value = progressBar2.Value;
}
trb_progress.Value = (int)stream.CurrentTime.TotalSeconds;
if (stream.CurrentTime.ToString().Length > 8)
{
lb_decTime.Text = stream.CurrentTime.ToString().Remove(8);
}
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (output != null)
{
if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
{
output.Stop();
}
output.Dispose();
output = null;
}
if (stream != null)
{
stream.Dispose();
stream = null;
}
if (pitch != null)
{
pitch = null;
}
if (stereo != null)
{
stereo = null;
}
closing = true;
if (capture != null && capture.CaptureState == NAudio.CoreAudioApi.CaptureState.Capturing)
{
capture.StopRecording();
}
if (wo != null)
{
if (wo.PlaybackState == PlaybackState.Playing)
{
wo.Stop();
}
wo.Dispose();
}
waveIn.StopRecording();
writer?.Dispose();
wo = null;
waveIn = null;
capture = null;
writer = null;
}
private void btn_open_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "MP3 File (*.mp3)|*.mp3|WAV File (*.wav)|*.wav";
if (open.ShowDialog() != DialogResult.OK) return;
output = new WaveOutEvent();
stream = new AudioFileReader(open.FileName);
pitch = new SmbPitchShiftingSampleProvider(stream.ToSampleProvider());
pitch.PitchFactor = 1;
stereo = new MonoToStereoSampleProvider(pitch.ToMono());
output.Init(stereo);
stereo.RightVolume = 0.5f;
stereo.LeftVolume = 0.5f;
stream.Volume = 0.5f;
lb_name.Text = open.SafeFileName;
lb_length.Text = stream.TotalTime.ToString().Remove(8);
lb_length.Text += " sec.";
lb_decTime.Text = stream.CurrentTime.ToString();
btn_pause.Enabled = true;
btn_stop.Enabled = true;
vsb_volumeL.Enabled = true;
vsb_volumeM.Enabled = true;
vsb_volumeR.Enabled = true;
trb_progress.Enabled = true;
cb_controle.Enabled = true;
trb_progress.Maximum = (int)stream.TotalTime.TotalSeconds;
}
private void btn_pause_Click(object sender, EventArgs e)
{
if (output != null)
{
if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
{
output.Pause();
btn_pause.Text = "Play";
}
else
{
output.Play();
btn_pause.Text = "Pause";
}
}
}
private void btn_stop_Click(object sender, EventArgs e)
{
if (output != null)
{
btn_stop.Enabled = false;
btn_pause.Enabled = false;
vsb_volumeL.Enabled = false;
vsb_volumeR.Enabled = false;
vsb_volumeM.Enabled = false;
trb_progress.Enabled = false;
cb_controle.Enabled = false;
progressBar1.Value = 0;
progressBar2.Value = 0;
progressBar3.Value = 0;
progressBar4.Value = 0;
progressBar6.Value = 0;
progressBar7.Value = 0;
progressBar8.Value = 0;
btn_pause.Text = "Play";
lb_name.Text = "";
lb_length.Text = "";
trb_progress.Value = 0;
lb_decTime.Text = "";
if (output != null)
{
if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
{
output.Stop();
}
output.Dispose();
output = null;
}
if (stream != null)
{
stream.Dispose();
stream = null;
}
if (pitch != null)
{
pitch = null;
}
if (stereo != null)
{
stereo = null;
}
}
}
private void trb_progress_Scroll(object sender, EventArgs e)
{
TimeSpan T = new TimeSpan(trb_progress.Value * 10000000);
stream.CurrentTime = T;
}
private void vsb_volumeR_Scroll(object sender, ScrollEventArgs e)
{
if (output != null)
{
stereo.RightVolume = Convert.ToSingle(vsb_volumeR.Value) / 100;
}
lb_volumeR.Text = vsb_volumeR.Value.ToString();
}
private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
if (output != null)
{
stereo.LeftVolume = Convert.ToSingle(vsb_volumeL.Value) / 100;
}
lb_volumeL.Text = vsb_volumeL.Value.ToString();
}
private void vsb_volumeM_Scroll(object sender, ScrollEventArgs e)
{
if (output != null)
{
stream.Volume = Convert.ToSingle(vsb_volumeM.Value) / 100;
}
lb_volumeM.Text = vsb_volumeM.Value.ToString();
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (cb_controle.Checked == true)
{
vsb_volumeL.Value = 100 - ((e.X * 10) / 15);
vsb_volumeR.Value = (e.X * 10) / 15;
vsb_volumeM.Value = 100 - e.Y;
lb_volumeL.Text = vsb_volumeL.Value.ToString();
lb_volumeR.Text = vsb_volumeR.Value.ToString();
lb_volumeM.Text = vsb_volumeM.Value.ToString();
stereo.LeftVolume = Convert.ToSingle(vsb_volumeL.Value) / 100;
stereo.RightVolume = Convert.ToSingle(vsb_volumeR.Value) / 100;
stream.Volume = Convert.ToSingle(vsb_volumeM.Value) / 100;
}
}
private void trb_pitch_Scroll(object sender, EventArgs e)
{
switch (trb_pitch.Value)
{
case -2:
pitch.PitchFactor = (float)Globals.downTwoTone;
break;
case - 1:
pitch.PitchFactor = (float)Globals.downOneTone;
break;
case 0:
pitch.PitchFactor = 1;
break;
case 1:
pitch.PitchFactor = (float)Globals.upOneTone;
break;
case 2:
pitch.PitchFactor = (float)Globals.upTwoTone;
break;
default:
pitch.PitchFactor = 1;
break;
}
}
private void cb_controle_CheckedChanged(object sender, EventArgs e)
{
if (cb_controle.Checked == true)
{
pictureBox1.Cursor = Cursors.NoMove2D;
}
else
{
pictureBox1.Cursor = Cursors.Default;
}
}
private void btn_playWave_Click(object sender, EventArgs e)
{
btn_playWave.Enabled = false;
btn_stopWave.Enabled = true;
SignalGenerator wave = null;
switch (cb_waves.SelectedIndex)
{
case 0:
wave = new SignalGenerator()
{
Gain = 0.2,
Frequency = 500,
Type = SignalGeneratorType.Sin,
};
break;
case 1:
wave = new SignalGenerator()
{
Gain = 0.2,
Frequency = 500,
Type = SignalGeneratorType.Triangle,
};
break;
case 2:
wave = new SignalGenerator()
{
Gain = 0.2,
Frequency = 500,
Type = SignalGeneratorType.Square,
};
break;
case 3:
wave = new SignalGenerator()
{
Gain = 0.2,
Frequency = 500,
Type = SignalGeneratorType.SawTooth,
};
break;
case 4:
wave = new SignalGenerator()
{
Gain = 0.2,
Frequency = 500,
Type = SignalGeneratorType.Pink,
};
break;
case 5:
wave = new SignalGenerator()
{
Gain = 0.2,
Frequency = 500,
Type = SignalGeneratorType.White,
};
break;
case 6:
wave = new SignalGenerator()
{
Gain = 0.2,
Frequency = 500,
FrequencyEnd = 2000,
SweepLengthSecs = 2,
Type = SignalGeneratorType.Sweep,
};
break;
default:
wave = new SignalGenerator()
{
Gain = 0.2,
Frequency = 500,
Type = SignalGeneratorType.Sin,
};
break;
}
MidiEvent midi = new MidiEvent(100000, 1, MidiCommandCode.NoteOn);
wo = new WaveOutEvent();
wo.Init(wave);
wo.Play();
}
private void btn_stopWave_Click(object sender, EventArgs e)
{
btn_playWave.Enabled = true;
btn_stopWave.Enabled = false;
wo.Stop();
wo.Dispose();
wo = null;
}
}
}
| 34.737443 | 135 | 0.4558 | [
"MIT"
] | JoaoLuizSevero/Basic-Music-Player | NAudioTests/Form1.cs | 15,217 | C# |
using System;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Reactive;
using System.Reactive.Linq;
using System.Security.Cryptography;
using System.Text;
using GitHub.Authentication;
using GitHub.Primitives;
using NLog;
using NullGuard;
using Octokit;
using Octokit.Reactive;
using ReactiveUI;
namespace GitHub.Api
{
public partial class ApiClient : IApiClient
{
static readonly Logger log = LogManager.GetCurrentClassLogger();
const string ProductName = Info.ApplicationInfo.ApplicationDescription;
readonly IObservableGitHubClient gitHubClient;
// There are two sets of authorization scopes, old and new:
// The old scopes must be used by older versions of Enterprise that don't support the new scopes:
readonly string[] oldAuthorizationScopes = { "user", "repo" };
// These new scopes include write:public_key, which allows us to add public SSH keys to an account:
readonly string[] newAuthorizationScopes = { "user", "repo", "write:public_key" };
readonly static Lazy<string> lazyNote = new Lazy<string>(() => ProductName + " on " + GetMachineNameSafe());
readonly static Lazy<string> lazyFingerprint = new Lazy<string>(GetFingerprint);
string ClientId { get; set; }
string ClientSecret { get; set; }
public ApiClient(HostAddress hostAddress, IObservableGitHubClient gitHubClient)
{
Configure();
HostAddress = hostAddress;
this.gitHubClient = gitHubClient;
}
partial void Configure();
public IObservable<Repository> CreateRepository(NewRepository repository, string login, bool isUser)
{
Guard.ArgumentNotEmptyString(login, nameof(login));
var client = gitHubClient.Repository;
return (isUser ? client.Create(repository) : client.Create(login, repository));
}
public IObservable<User> GetUser()
{
return gitHubClient.User.Current();
}
public IObservable<ApplicationAuthorization> GetOrCreateApplicationAuthenticationCode(
Func<TwoFactorAuthorizationException, IObservable<TwoFactorChallengeResult>> twoFactorChallengeHander,
string authenticationCode = null,
bool useOldScopes = false,
bool useFingerPrint = true)
{
var newAuthorization = new NewAuthorization
{
Scopes = useOldScopes
? oldAuthorizationScopes
: newAuthorizationScopes,
Note = lazyNote.Value,
Fingerprint = useFingerPrint ? lazyFingerprint.Value : null
};
Func<TwoFactorAuthorizationException, IObservable<TwoFactorChallengeResult>> dispatchedHandler =
ex => Observable.Start(() => twoFactorChallengeHander(ex), RxApp.MainThreadScheduler).Merge();
var authorizationsClient = gitHubClient.Authorization;
return string.IsNullOrEmpty(authenticationCode)
? authorizationsClient.CreateAndDeleteExistingApplicationAuthorization(
ClientId,
ClientSecret,
newAuthorization,
dispatchedHandler,
true)
: authorizationsClient.CreateAndDeleteExistingApplicationAuthorization(
ClientId,
ClientSecret,
newAuthorization,
dispatchedHandler,
authenticationCode,
true);
}
public IObservable<Organization> GetOrganizations()
{
return gitHubClient.Organization.GetAllForCurrent();
}
public IObservable<Repository> GetUserRepositories(RepositoryType repositoryType)
{
var request = new RepositoryRequest
{
Type = repositoryType,
Direction = SortDirection.Ascending,
Sort = RepositorySort.FullName
};
return gitHubClient.Repository.GetAllForCurrent(request);
}
public IObservable<string> GetGitIgnoreTemplates()
{
return gitHubClient.Miscellaneous.GetAllGitIgnoreTemplates();
}
public IObservable<LicenseMetadata> GetLicenses()
{
return gitHubClient.Miscellaneous.GetAllLicenses();
}
public HostAddress HostAddress { get; }
public ITwoFactorChallengeHandler TwoFactorChallengeHandler { get; private set; }
static string GetSha256Hash(string input)
{
try
{
using (var sha256 = SHA256.Create())
{
var bytes = Encoding.UTF8.GetBytes(input);
var hash = sha256.ComputeHash(bytes);
return string.Join("", hash.Select(b => b.ToString("x2", CultureInfo.InvariantCulture)));
}
}
catch (Exception e)
{
log.Error("IMPOSSIBLE! Generating Sha256 hash caused an exception.", e);
return null;
}
}
static string GetFingerprint()
{
return GetSha256Hash(ProductName + ":" + GetMachineIdentifier());
}
static string GetMachineNameSafe()
{
try
{
return Dns.GetHostName();
}
catch (Exception e)
{
log.Info("Failed to retrieve host name using `DNS.GetHostName`.", e);
try
{
return Environment.MachineName;
}
catch (Exception ex)
{
log.Info("Failed to retrieve host name using `Environment.MachineName`.", ex);
return "(unknown)";
}
}
}
static string GetMachineIdentifier()
{
try
{
// adapted from http://stackoverflow.com/a/1561067
var fastedValidNetworkInterface = NetworkInterface.GetAllNetworkInterfaces()
.OrderBy(nic => nic.Speed)
.Where(nic => nic.OperationalStatus == OperationalStatus.Up)
.Select(nic => nic.GetPhysicalAddress().ToString())
.FirstOrDefault(address => address.Length > 12);
return fastedValidNetworkInterface ?? GetMachineNameSafe();
}
catch (Exception e)
{
log.Info("Could not retrieve MAC address. Fallback to using machine name.", e);
return GetMachineNameSafe();
}
}
public IObservable<Repository> GetRepositoriesForOrganization(string organization)
{
return gitHubClient.Repository.GetAllForOrg(organization);
}
public IObservable<Unit> DeleteApplicationAuthorization(int id, [AllowNull]string twoFactorAuthorizationCode)
{
return gitHubClient.Authorization.Delete(id, twoFactorAuthorizationCode);
}
}
}
| 35.950739 | 117 | 0.586325 | [
"MIT"
] | Acidburn0zzz/Github-io-VisualStudio | src/GitHub.App/Api/ApiClient.cs | 7,298 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.