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
#region CompositeStateTransitionTests.cs file // // Tests for StaMa state machine controller library // // Copyright (c) 2005-2014, Roland Schneider. All rights reserved. // #endregion using System; using StaMa; using System.Collections; #if !MF_FRAMEWORK using NUnit.Framework; #else using MFUnitTest.Framework; using Microsoft.SPOT; #endif namespace StaMaTest { [TestFixture] public class CompositeStateTransitionTests { #if !MF_FRAMEWORK [TestCase("Ev1", new string[] { "EnS1", "ExS1", "EnS2", "EnS2A2" }, TestName = "CompositeStateTransition_ToCompositeState_ExecutesActionsOrdered")] [TestCase("Ev2", new string[] { "EnS1", "ExS1", "EnS2", "EnS2A1" }, TestName = "CompositeStateTransition_ToSubState_ExecutesActionsOrdered")] public void CompositeStateTransition_ToCompositeState_ExecutesActionsOrdered(string signalEvent, string[] expectedActions) #else public void CompositeStateTransition_ToCompositeState_ExecutesActionsOrdered() { CompositeStateTransition_ToCompositeState_ExecutesActionsOrdered("Ev1", new string[] { "EnS1", "ExS1", "EnS2", "EnS2A2" }); } public void CompositeStateTransition_ToSubState_ExecutesActionsOrdered() { CompositeStateTransition_ToCompositeState_ExecutesActionsOrdered("Ev2", new string[] { "EnS1", "ExS1", "EnS2", "EnS2A1" }); } private void CompositeStateTransition_ToCompositeState_ExecutesActionsOrdered(string signalEvent, string[] expectedActions) #endif { // Arrange ActionRecorder recorder = new ActionRecorder(); StateMachineTemplate t = new StateMachineTemplate(); t.Region("S1", false); t.State("S1", recorder.CreateAction("EnS1"), recorder.CreateAction("ExS1")); t.Transition("T1", "S1", "S2", "Ev1", null, null); t.Transition("T2", "S1", "S2A1", "Ev2", null, null); t.EndState(); t.State("S2", recorder.CreateAction("EnS2"), recorder.CreateAction("ExS2")); t.Region("S2A2", false); t.State("S2A1", recorder.CreateAction("EnS2A1"), recorder.CreateAction("ExS2A1")); t.EndState(); t.State("S2A2", recorder.CreateAction("EnS2A2"), recorder.CreateAction("ExS2A2")); t.EndState(); t.EndRegion(); t.EndState(); t.EndRegion(); StateMachine stateMachine = t.CreateStateMachine(); stateMachine.Startup(); // Act stateMachine.SendTriggerEvent(signalEvent); // Assert Assert.That(recorder.RecordedActions, Is.EqualTo(expectedActions), "Unexpected action invocations"); } #if !MF_FRAMEWORK [TestCase("Ev1", new string[] { "EnS2", "EnS2A1", "ExS2A1", "ExS2", "EnS1" }, TestName = "CompositeStateTransition_FromSubStateToSimpleState_ExecutesActionsOrdered")] [TestCase("Ev2", new string[] { "EnS2", "EnS2A1", "ExS2A1", "ExS2", "EnS1" }, TestName = "CompositeStateTransition_FromCompositeStateToSimpleState_ExecutesActionsOrdered")] [TestCase("Ev3", new string[] { "EnS2", "EnS2A1", "ExS2A1", "EnS2A2" }, TestName = "CompositeStateTransition_FromSubStateToSubState_ExecutesActionsOrdered")] [TestCase("Ev4", new string[] { "EnS2", "EnS2A1", "ExS2A1", "ExS2", "EnS2", "EnS2A2" }, TestName = "CompositeStateTransition_FromSubStateToSubStateExternal_ExecutesActionsOrdered")] public void CompositeStateTransition_FromCompositeState_ExecutesActionsOrdered(string signalEvent, string[] expectedActions) #else public void CompositeStateTransition_FromSubStateToSimpleState_ExecutesActionsOrdered() { CompositeStateTransition_FromCompositeState_ExecutesActionsOrdered("Ev1", new string[] { "EnS2", "EnS2A1", "ExS2A1", "ExS2", "EnS1" }); } public void CompositeStateTransition_FromCompositeStateToSimpleState_ExecutesActionsOrdered() { CompositeStateTransition_FromCompositeState_ExecutesActionsOrdered("Ev2", new string[] { "EnS2", "EnS2A1", "ExS2A1", "ExS2", "EnS1" }); } public void CompositeStateTransition_FromSubStateToSubState_ExecutesActionsOrdered() { CompositeStateTransition_FromCompositeState_ExecutesActionsOrdered("Ev3", new string[] { "EnS2", "EnS2A1", "ExS2A1", "EnS2A2" }); } public void CompositeStateTransition_FromSubStateToSubStateExternal_ExecutesActionsOrdered() { CompositeStateTransition_FromCompositeState_ExecutesActionsOrdered("Ev4", new string[] { "EnS2", "EnS2A1", "ExS2A1", "ExS2", "EnS2", "EnS2A2" }); } private void CompositeStateTransition_FromCompositeState_ExecutesActionsOrdered(string signalEvent, string[] expectedActions) #endif { // Arrange ActionRecorder recorder = new ActionRecorder(); StateMachineTemplate t = new StateMachineTemplate(); t.Region("S2", false); t.State("S1", recorder.CreateAction("EnS1"), recorder.CreateAction("ExS1")); t.EndState(); t.State("S2", recorder.CreateAction("EnS2"), recorder.CreateAction("ExS2")); t.Transition("T2", "S2", "S1", "Ev2", null, null); t.Transition("T4", "S2A1", "S2A2", "Ev4", null, null); t.Region("S2A1", false); t.State("S2A1", recorder.CreateAction("EnS2A1"), recorder.CreateAction("ExS2A1")); t.Transition("T1", "S2A1", "S1", "Ev1", null, null); t.Transition("T3", "S2A1", "S2A2", "Ev3", null, null); t.EndState(); t.State("S2A2", recorder.CreateAction("EnS2A2"), recorder.CreateAction("ExS2A2")); t.EndState(); t.EndRegion(); t.EndState(); t.EndRegion(); StateMachine stateMachine = t.CreateStateMachine(); stateMachine.Startup(); // Act stateMachine.SendTriggerEvent(signalEvent); // Assert Assert.That(recorder.RecordedActions, Is.EqualTo(expectedActions), "Unexpected action invocations"); } } }
57
251
0.638217
[ "BSD-3-Clause" ]
StaMa-StateMachine/StaMa
Tests/StaMaTest/CompositeStateTransitionTests.cs
6,329
C#
 #region Using Directives using System; using System.ComponentModel; using System.Collections; using System.Xml.Serialization; using System.Data; using Nettiers.AdventureWorks.Entities; using Nettiers.AdventureWorks.Entities.Validation; using Nettiers.AdventureWorks.Data; using Microsoft.Practices.EnterpriseLibrary.Logging; #endregion namespace Nettiers.AdventureWorks.Services { /// <summary> /// An component type implementation of the 'ProductCostHistory' table. /// </summary> /// <remarks> /// All custom implementations should be done here. /// </remarks> [CLSCompliant(true)] public partial class ProductCostHistoryService : Nettiers.AdventureWorks.Services.ProductCostHistoryServiceBase { #region Constructors /// <summary> /// Initializes a new instance of the ProductCostHistoryService class. /// </summary> public ProductCostHistoryService() : base() { } #endregion Constructors }//End Class } // end namespace
24.463415
113
0.733799
[ "MIT" ]
aqua88hn/netTiers
Samples/AdventureWorks/Generated/Nettiers.AdventureWorks.Services/ProductCostHistoryService.cs
1,005
C#
using System; using CommunityPatch; using TaleWorlds.Library; using TaleWorlds.TwoDimension; namespace Aragas.TextureImportingHack { // Character icon on Map: // ButtonWidget with child ImageIdentifierWidget // ImageId = CharacterId data // ImageTypeCode = 5 // AdditionalArgs = "" // Texture - character_tableaue0 // TextureProvider TaleWorlds.MountAndBlade.GauntletUI.ImageIdentifierTextureProvider public static class SpriteDataFactory { public static SpriteData CreateNewFromModule(string name, ResourceDepot resourceDepot) { var spriteData = new SpriteData(name); try { spriteData.Load(resourceDepot); foreach (var spriteCategory in spriteData.SpriteCategories) spriteCategory.Value.LoadFromModules(resourceDepot); } catch(Exception ex) { CommunityPatchSubModule.Error(ex, "[Aragas.MercenaryContract]: Error while trying to initialize custom textures!"); } return spriteData; } } }
29.027027
131
0.675047
[ "MIT" ]
Aragas/Aragas.MercenaryContract
Aragas.MercenaryContract/TextureImportingHack/SpriteDataFactory.cs
1,076
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using NAudio.Wave; using ASong.Playback; namespace ASong { public partial class WaveformEditorForm : Form { private string romFile; private uint waveformOffset; private byte[] waveformData; private WaveOut waveOut = null; private bool tye = false; public WaveformEditorForm(string rom) { InitializeComponent(); romFile = rom; waveformOffset = 0; waveformData = new byte[32]; for (int i = 0; i < 32; i++) waveformData[i] = 0; // Fill with 0 JIC } public WaveformEditorForm(string rom, uint waveform) { InitializeComponent(); romFile = rom; waveformOffset = waveform; waveformData = new byte[32]; for (int i = 0; i < 32; i++) waveformData[i] = 0; // Fill with 0 JIC // Specified offset edition txtOffset.Visible = false; bLoad.Visible = false; } private void WaveformEditorForm_Load(object sender, EventArgs e) { LoadWaveform(); Text = "Edit Waveform @ 0x" + waveformOffset.ToString("X"); UpdateWaveText(); } private void WaveformEditorForm_FormClosing(object sender, FormClosingEventArgs e) { // Stop audio playback if still going. if (waveOut != null) { waveOut.Stop(); waveOut.Dispose(); waveOut = null; } } private void bLoad_Click(object sender, EventArgs e) { // Get offset if (txtOffset.TextLength <= 0 || txtOffset.Text == "0x") return; uint u = TryGetOffset(); // Some minor error checking if (u > 0x6000000 - 16) return; // Just a size limiter (max size of ROM - 16) waveformOffset = u; // Load the wave at said offset LoadWaveform(); Text = "Edit Waveform @ 0x" + waveformOffset.ToString("X"); // Show it UpdateWaveText(); pWave.Invalidate(); } private void bSave_Click(object sender, EventArgs e) { // This is all it takes. SaveWaveform(); } private void bExport_Click(object sender, EventArgs e) { saveFileDialog1.FileName = "waveform_" + waveformOffset.ToString("X") + ".raw"; saveFileDialog1.Filter = "Raw Waveform Files|*.raw"; saveFileDialog1.Title = "Export Waveform"; saveFileDialog1.InitialDirectory = Path.GetDirectoryName(romFile); if (saveFileDialog1.ShowDialog() != DialogResult.OK) return; File.WriteAllBytes(saveFileDialog1.FileName, waveformData); } private void bImport_Click(object sender, EventArgs e) { openFileDialog1.FileName = ""; openFileDialog1.Filter = "Raw Waveform Files|*.raw"; openFileDialog1.Title = "Import Waveform"; openFileDialog1.InitialDirectory = Path.GetDirectoryName(romFile); if (openFileDialog1.ShowDialog() != DialogResult.OK) return; byte[] temp = File.ReadAllBytes(openFileDialog1.FileName); if (temp.Length == 32) { waveformData = temp; pWave.Invalidate(); UpdateWaveText(); } else { MessageBox.Show("It seems the file you tried to load isn't the correct size!\n" + "It probably wasn't some waveform data... :(", "Uh-oh!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void bPlay_Click(object sender, EventArgs e) { if (waveOut == null) { var waveProvider = new WaveformWaveProvider(waveformData); waveOut = new WaveOut(); waveOut.Init(waveProvider); waveOut.Play(); bPlay.Text = "Stop"; bPlay.Image = Properties.Resources.stop; } else { waveOut.Stop(); waveOut.Dispose(); waveOut = null; bPlay.Text = "Play"; bPlay.Image = Properties.Resources.play; } } private void bAbout_Click(object sender, EventArgs e) { MessageBox.Show("This allows you to edit the 16-byte programmable waveform data found in an M4A instrument sample."+ "\n\nYes. I know that it's small.", "Help", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void UpdateWaveText() { tye = true; txtWave.Text = ""; for (int i = 0; i < 32; i++) { txtWave.Text += waveformData[i].ToString("X"); } tye = false; } private void ConvertWaveText() { if (txtWave.TextLength != 32) return; for (int i = 0; i < 32; i++) { byte b; if (byte.TryParse(txtWave.Text[i].ToString(), NumberStyles.HexNumber, null, out b)) { if (b <= 15) waveformData[i] = b; } } pWave.Invalidate(); } private void LoadWaveform() { BinaryReader br = new BinaryReader(File.OpenRead(romFile)); br.BaseStream.Seek(waveformOffset, SeekOrigin.Begin); for (int i = 0; i < 16; i++) { byte b = br.ReadByte(); // It is big endian, so is this the right order? Yes... waveformData[i * 2] = (byte)((b >> 4) & 0xF); waveformData[i * 2 + 1] = (byte)(b & 0xF); } br.Dispose(); bSave.Text = "Save @ 0x" + waveformOffset.ToString("X"); } private void SaveWaveform() { BinaryWriter bw = new BinaryWriter(File.OpenWrite(romFile)); bw.BaseStream.Seek(waveformOffset, SeekOrigin.Begin); for (int i = 0; i < 16; i++) { // We can flip it if the loading was wrong too. byte b = (byte)((waveformData[i * 2] << 4) | waveformData[i * 2 + 1]); bw.Write(b); // Simple enough. } bw.Dispose(); } private void pWave_Paint(object sender, PaintEventArgs e) { // Draw grid and BG e.Graphics.FillRectangle(Brushes.Black, 0, 0, pWave.Width, pWave.Height); e.Graphics.DrawLine(Pens.Red, 0, 64, pWave.Width, 64); for (int i = 8; i < 32; i += 8) { e.Graphics.DrawLine(Pens.MidnightBlue, i * 8 + 4, 0, i * 8 + 4, pWave.Height); } e.Graphics.DrawLine(Pens.LightSteelBlue, 0, 8, pWave.Width, 8); e.Graphics.DrawLine(Pens.LightSteelBlue, 0, 128, pWave.Width, 128); // Draw the wave Pen p = new Pen(new SolidBrush(Color.FromArgb(0, 248, 0)), 3); for (int i = 0; i < 32; i++) { // Draw a bar e.Graphics.DrawLine(p, i * 8, 128 - waveformData[i] * 8, (i + 1) * 8, 128 - waveformData[i] * 8); // Connect to previous if (i > 0) e.Graphics.DrawLine(p, i * 8, 128 - waveformData[i - 1] * 8, i * 8, 128 - waveformData[i] * 8); } } private void pWave_MouseMove(object sender, MouseEventArgs e) { pWave_MouseThing(e); } private void pWave_MouseDown(object sender, MouseEventArgs e) { pWave_MouseThing(e); } private void pWave_MouseThing(MouseEventArgs e) { // Keep it in bounds if (e.Y < 8 || e.Y >= pWave.Height) return; if (e.X < 0 || e.X >= pWave.Width) return; int x = e.X / 8; int y = 16 - e.Y / 8; lblXY.Text = "(X, Y) = (" + x + ", " + y + ")"; if (x < 32 && y < 16 && y > -1 && waveformData[x] == y) { pWave.Cursor = Cursors.SizeNS; } else if (e.Button == MouseButtons.None) { pWave.Cursor = Cursors.Hand; } // Do this if (e.Button == MouseButtons.Left) { if (x < 32 && y < 16) { // Set the data waveformData[x] = (byte)y; // Now redraw pWave.Invalidate(); // And update the code UpdateWaveText(); } } } private uint TryGetOffset() { uint u; if (uint.TryParse(txtOffset.Text.Replace("0x", ""), NumberStyles.HexNumber, null, out u)) return u; else return 0; } private void txtOffset_TextChanged(object sender, EventArgs e) { bLoad.Text = "Load @ 0x" + TryGetOffset().ToString("X"); } private void txtWave_TextChanged(object sender, EventArgs e) { if (tye) return; ConvertWaveText(); } private bool IsHexDigit(char c) { if (char.IsDigit(c)) return true; else if (c >= 'a' && c <= 'f') return true; else if (c >= 'A' && c <= 'F') return true; else return false; } private void txtWave_KeyPress(object sender, KeyPressEventArgs e) { if (txtWave.SelectionStart <= 32 && txtWave.SelectionStart > -1) { if (IsHexDigit(e.KeyChar) && txtWave.SelectionStart < 32) { txtWave.SelectionLength = 1; txtWave.SelectedText = e.KeyChar.ToString().ToUpper(); } else if (e.KeyChar == '\b' && txtWave.SelectionStart > 0) { txtWave.SelectionStart = txtWave.SelectionStart - 1; txtWave.SelectionLength = 1; txtWave.SelectedText = "0"; txtWave.SelectionStart = txtWave.SelectionStart - 1; } } e.Handled = true; } } }
31.642229
129
0.492864
[ "MIT" ]
Lostelle/AdvancedSong
old/ASong/WaveformEditorForm.cs
10,792
C#
/* MIT License Copyright (c) 2016 Marco Silipo (X39) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using System.Collections.ObjectModel; using DLNA_TestResultReader.ResultFileUtil; namespace DLNA_TestResultReader.FileFormats.UCTT { [Serializable] public class TestCase : ITestCase { [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("level")] public string Level { get; set; } [XmlAttribute("scriptVersion")] public string ScriptVersion { get; set; } [XmlAttribute("stamp")] public DateTime Timestamp { get; set; } [XmlElement("profileAllowedResults")] public List<string> AllowedResults { get; set; } [XmlArray("Logs")] [XmlArrayItem("Log")] public ObservableCollection<LogObject> LogCollection { get; set; } [XmlElement("Result")] public string ResultString { get; set; } [XmlIgnore] public EResult Result { get { switch(this.ResultString.ToLower()[0]) { case 'p': return EResult.Passed; case 'f': return EResult.Failed; case 'n': return EResult.NotApplicable; case 'w': return EResult.Warning; default: return EResult.NotRun; } } } [XmlIgnore] public string Log { get { StringBuilder builder = new StringBuilder(); foreach(var log in this.LogCollection) { builder.Append(log.Level); builder.Append(": "); builder.AppendLine(log.Content); } return builder.ToString(); } } [XmlIgnore] public string ResultNote { get { return this.LogCollection.Last().Content; } } [XmlIgnore] public string ID { get { return this.Name.Substring(0, this.Name.IndexOf(' ')); } } public ESeverityLevel Severity { get { if (this.AllowedResults.Contains("Failed")) return ESeverityLevel.Optional; else if (this.AllowedResults.Contains("NA")) return ESeverityLevel.Recommended; else if (this.AllowedResults.Contains("WARNING")) return ESeverityLevel.Mandatory; else if (this.AllowedResults.Contains("PASSED")) return ESeverityLevel.Mandatory; else return ESeverityLevel.NotAvailable; } } } }
34.473684
91
0.591094
[ "MIT" ]
X39/CTTResultReader
DLNA_TestResultReader/FileFormats/UCTT/TestCase.cs
3,932
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace ModernWpf.Toolkit { /// <summary> /// Set of helpers to convert between data types and notations. /// </summary> public static class Converters { /// <summary> /// Translate numeric file size in bytes to a human-readable shorter string format. /// </summary> /// <param name="size">File size in bytes.</param> /// <returns>Returns file size short string.</returns> public static string ToFileSizeString(long size) { if (size < 1024) { return size.ToString("F0") + " bytes"; } else if ((size >> 10) < 1024) { return (size / 1024F).ToString("F1") + " KB"; } else if ((size >> 20) < 1024) { return ((size >> 10) / 1024F).ToString("F1") + " MB"; } else if ((size >> 30) < 1024) { return ((size >> 20) / 1024F).ToString("F1") + " GB"; } else if ((size >> 40) < 1024) { return ((size >> 30) / 1024F).ToString("F1") + " TB"; } else if ((size >> 50) < 1024) { return ((size >> 40) / 1024F).ToString("F1") + " PB"; } else { return ((size >> 50) / 1024F).ToString("F0") + " EB"; } } } }
32.86
91
0.460743
[ "MIT" ]
ModernWpf-Community/ModernWpfCommunityToolkit
ModernWpf.Toolkit/Converters.cs
1,643
C#
using Microsoft.Build.Framework; using NUnit.Framework; using System.CodeDom; using System.IO; using System.Linq; using System.Maui.Build.Tasks; using System.Maui.Core.UnitTests; namespace System.Maui.MSBuild.UnitTests { [TestFixture] public class XamlgTests : BaseTestFixture { [Test] public void LoadXaml2006 () { var xaml = @"<View xmlns=""http://xamarin.com/schemas/2014/forms"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"" x:Class=""System.Maui.Xaml.UnitTests.CustomView"" > <Label x:Name=""label0""/> </View>"; var reader = new StringReader (xaml); var generator = new XamlGenerator(); generator.ParseXaml(reader); Assert.NotNull(generator.RootType); Assert.NotNull(generator.RootClrNamespace); Assert.NotNull (generator.BaseType); Assert.NotNull (generator.NamedFields); Assert.AreEqual ("CustomView", generator.RootType); Assert.AreEqual ("System.Maui.Xaml.UnitTests", generator.RootClrNamespace); Assert.AreEqual ("System.Maui.View", generator.BaseType.BaseType); Assert.AreEqual (1, generator.NamedFields.Count()); Assert.AreEqual ("label0", generator.NamedFields.First().Name); Assert.AreEqual ("System.Maui.Label", generator.NamedFields.First().Type.BaseType); } [Test] public void LoadXaml2009 () { var xaml = @"<View xmlns=""http://xamarin.com/schemas/2014/forms"" xmlns:x=""http://schemas.microsoft.com/winfx/2009/xaml"" x:Class=""System.Maui.Xaml.UnitTests.CustomView"" > <Label x:Name=""label0""/> </View>"; var reader = new StringReader (xaml); var generator = new XamlGenerator(); generator.ParseXaml(reader); Assert.NotNull(generator.RootType); Assert.NotNull(generator.RootClrNamespace); Assert.NotNull(generator.BaseType); Assert.NotNull(generator.NamedFields); Assert.AreEqual("CustomView", generator.RootType); Assert.AreEqual("System.Maui.Xaml.UnitTests", generator.RootClrNamespace); Assert.AreEqual("System.Maui.View", generator.BaseType.BaseType); Assert.AreEqual(1, generator.NamedFields.Count()); Assert.AreEqual("label0", generator.NamedFields.First().Name); Assert.AreEqual("System.Maui.Label", generator.NamedFields.First().Type.BaseType); } [Test] //https://github.com/xamarin/Duplo/issues/1207#issuecomment-47159917 public void xNameInCustomTypes () { var xaml = @"<ContentPage xmlns=""http://xamarin.com/schemas/2014/forms"" xmlns:x=""http://schemas.microsoft.com/winfx/2009/xaml"" xmlns:local=""clr-namespace:CustomListViewSample;assembly=CustomListViewSample"" xmlns:localusing=""using:CustomListViewSample"" x:Class=""CustomListViewSample.TestPage""> <StackLayout VerticalOptions=""CenterAndExpand"" HorizontalOptions=""CenterAndExpand""> <Label Text=""Hello, Custom Renderer!"" /> <local:CustomListView x:Name=""listView"" WidthRequest=""960"" CornerRadius=""50"" OutlineColor=""Blue"" /> <localusing:CustomListView x:Name=""listViewusing"" /> </StackLayout> </ContentPage>"; var reader = new StringReader (xaml); var generator = new XamlGenerator(); generator.ParseXaml(reader); Assert.AreEqual (2, generator.NamedFields.Count()); Assert.AreEqual("listView", generator.NamedFields.ToArray()[0].Name); Assert.AreEqual ("CustomListViewSample.CustomListView", generator.NamedFields.ToArray()[0].Type.BaseType); Assert.AreEqual("listViewusing", generator.NamedFields.ToArray()[1].Name); Assert.AreEqual ("CustomListViewSample.CustomListView", generator.NamedFields.ToArray()[1].Type.BaseType); } [Test] public void xNameInDataTemplates () { var xaml = @"<StackLayout xmlns=""http://xamarin.com/schemas/2014/forms"" xmlns:x=""http://schemas.microsoft.com/winfx/2009/xaml"" x:Class=""FooBar"" > <ListView> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <Label x:Name=""notincluded""/> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView> <Label x:Name=""included""/> </StackLayout>"; var reader = new StringReader (xaml); var generator = new XamlGenerator(); generator.ParseXaml(reader); Assert.Contains ("included", generator.NamedFields.Select(cmf => cmf.Name).ToList()); Assert.False (generator.NamedFields.Select(cmf => cmf.Name).Contains ("notincluded")); Assert.AreEqual (1, generator.NamedFields.Count()); } [Test] public void xNameInStyles () { var xaml = @"<StackLayout xmlns=""http://xamarin.com/schemas/2014/forms"" xmlns:x=""http://schemas.microsoft.com/winfx/2009/xaml"" x:Class=""FooBar"" > <StackLayout.Resources> <ResourceDictionary> <Style TargetType=""Label"" > <Setter Property=""Text""> <Setter.Value> <Label x:Name=""notincluded"" /> </Setter.Value> </Setter> </Style> </ResourceDictionary> </StackLayout.Resources> </StackLayout>"; var reader = new StringReader (xaml); var generator = new XamlGenerator(); generator.ParseXaml(reader); Assert.False (generator.NamedFields.Select(cmf => cmf.Name).Contains ("notincluded")); Assert.AreEqual (0, generator.NamedFields.Count()); } [Test] public void xTypeArgumentsOnRootElement () { var xaml = @"<Foo xmlns=""http://xamarin.com/schemas/2014/forms"" xmlns:x=""http://schemas.microsoft.com/winfx/2009/xaml"" x:Class=""FooBar"" x:TypeArguments=""x:String"" />"; var reader = new StringReader (xaml); var generator = new XamlGenerator(); generator.ParseXaml(reader); Assert.AreEqual("FooBar", generator.RootType); Assert.AreEqual ("System.Maui.Foo`1", generator.BaseType.BaseType); Assert.AreEqual (1, generator.BaseType.TypeArguments.Count); Assert.AreEqual ("System.String", generator.BaseType.TypeArguments [0].BaseType); } [Test] public void MulipleXTypeArgumentsOnRootElement () { var xaml = @"<Foo xmlns=""http://xamarin.com/schemas/2014/forms"" xmlns:x=""http://schemas.microsoft.com/winfx/2009/xaml"" x:Class=""FooBar"" x:TypeArguments=""x:String,x:Int32"" />"; var reader = new StringReader (xaml); var generator = new XamlGenerator(); generator.ParseXaml(reader); Assert.AreEqual ("FooBar", generator.RootType); Assert.AreEqual ("System.Maui.Foo`2", generator.BaseType.BaseType); Assert.AreEqual (2, generator.BaseType.TypeArguments.Count); Assert.AreEqual ("System.String", generator.BaseType.TypeArguments [0].BaseType); Assert.AreEqual ("System.Int32", generator.BaseType.TypeArguments [1].BaseType); } [Test] public void MulipleXTypeArgumentsOnRootElementWithWhitespace () { var xaml = @"<Foo xmlns=""http://xamarin.com/schemas/2014/forms"" xmlns:x=""http://schemas.microsoft.com/winfx/2009/xaml"" x:Class=""FooBar"" x:TypeArguments=""x:String, x:Int32"" />"; var reader = new StringReader (xaml); var generator = new XamlGenerator(); generator.ParseXaml(reader); Assert.AreEqual ("FooBar", generator.RootType); Assert.AreEqual ("System.Maui.Foo`2", generator.BaseType.BaseType); Assert.AreEqual (2, generator.BaseType.TypeArguments.Count); Assert.AreEqual ("System.String", generator.BaseType.TypeArguments [0].BaseType); Assert.AreEqual ("System.Int32", generator.BaseType.TypeArguments [1].BaseType); } [Test] public void MulipleXTypeArgumentsMulitpleNamespacesOnRootElement () { var xaml = @"<Foo xmlns=""http://xamarin.com/schemas/2014/forms"" xmlns:x=""http://schemas.microsoft.com/winfx/2009/xaml"" x:Class=""FooBar"" x:TypeArguments=""nsone:IDummyInterface,nstwo:IDummyInterfaceTwo"" xmlns:nsone=""clr-namespace:System.Maui.Xaml.UnitTests.Bugzilla24258.Interfaces"" xmlns:nstwo=""clr-namespace:System.Maui.Xaml.UnitTests.Bugzilla24258.InterfacesTwo"" />"; var reader = new StringReader (xaml); var generator = new XamlGenerator(); generator.ParseXaml(reader); Assert.AreEqual ("FooBar", generator.RootType); Assert.AreEqual ("System.Maui.Foo`2", generator.BaseType.BaseType); Assert.AreEqual (2, generator.BaseType.TypeArguments.Count); Assert.AreEqual ("System.Maui.Xaml.UnitTests.Bugzilla24258.Interfaces.IDummyInterface", generator.BaseType.TypeArguments [0].BaseType); Assert.AreEqual ("System.Maui.Xaml.UnitTests.Bugzilla24258.InterfacesTwo.IDummyInterfaceTwo", generator.BaseType.TypeArguments [1].BaseType); } [Test] public void MulipleXTypeArgumentsMulitpleNamespacesOnRootElementWithWhitespace () { var xaml = @"<Foo xmlns=""http://xamarin.com/schemas/2014/forms"" xmlns:x=""http://schemas.microsoft.com/winfx/2009/xaml"" x:Class=""FooBar"" x:TypeArguments=""nsone:IDummyInterface, nstwo:IDummyInterfaceTwo"" xmlns:nsone=""clr-namespace:System.Maui.Xaml.UnitTests.Bugzilla24258.Interfaces"" xmlns:nstwo=""clr-namespace:System.Maui.Xaml.UnitTests.Bugzilla24258.InterfacesTwo"" />"; var reader = new StringReader (xaml); var generator = new XamlGenerator(); generator.ParseXaml(reader); Assert.AreEqual ("FooBar", generator.RootType); Assert.AreEqual ("System.Maui.Foo`2", generator.BaseType.BaseType); Assert.AreEqual (2, generator.BaseType.TypeArguments.Count); Assert.AreEqual ("System.Maui.Xaml.UnitTests.Bugzilla24258.Interfaces.IDummyInterface", generator.BaseType.TypeArguments [0].BaseType); Assert.AreEqual ("System.Maui.Xaml.UnitTests.Bugzilla24258.InterfacesTwo.IDummyInterfaceTwo", generator.BaseType.TypeArguments [1].BaseType); } [Test] //https://bugzilla.xamarin.com/show_bug.cgi?id=33256 public void AlwaysUseGlobalReference () { var xaml = @" <ContentPage xmlns=""http://xamarin.com/schemas/2014/forms"" xmlns:x=""http://schemas.microsoft.com/winfx/2009/xaml"" x:Class=""FooBar"" > <Label x:Name=""label0""/> </ContentPage>"; using (var reader = new StringReader (xaml)) { var generator = new XamlGenerator(); generator.ParseXaml(reader); Assert.IsTrue (generator.BaseType.Options.HasFlag (CodeTypeReferenceOptions.GlobalReference)); Assert.IsTrue (generator.NamedFields.Select(cmf => cmf.Type).First ().Options.HasFlag (CodeTypeReferenceOptions.GlobalReference)); } } [Test] public void FieldModifier() { var xaml = @" <ContentPage xmlns=""http://xamarin.com/schemas/2014/forms"" xmlns:x=""http://schemas.microsoft.com/winfx/2009/xaml"" xmlns:local=""clr-namespace:System.Maui.Xaml.UnitTests"" x:Class=""System.Maui.Xaml.UnitTests.FieldModifier""> <StackLayout> <Label x:Name=""privateLabel"" /> <Label x:Name=""internalLabel"" x:FieldModifier=""NotPublic"" /> <Label x:Name=""publicLabel"" x:FieldModifier=""Public"" /> </StackLayout> </ContentPage>"; using (var reader = new StringReader(xaml)) { var generator = new XamlGenerator(); generator.ParseXaml(reader); Assert.That(generator.NamedFields.First(cmf => cmf.Name == "privateLabel").Attributes, Is.EqualTo(MemberAttributes.Private)); Assert.That(generator.NamedFields.First(cmf => cmf.Name == "internalLabel").Attributes, Is.EqualTo(MemberAttributes.Assembly)); Assert.That(generator.NamedFields.First(cmf => cmf.Name == "publicLabel").Attributes, Is.EqualTo(MemberAttributes.Public)); } } [Test] //https://github.com/xamarin/System.Maui/issues/2574 public void xNameOnRoot() { var xaml = @"<ContentPage xmlns=""http://xamarin.com/schemas/2014/forms"" xmlns:x=""http://schemas.microsoft.com/winfx/2009/xaml"" x:Class=""Foo"" x:Name=""bar""> </ContentPage>"; var generator = new XamlGenerator(); generator.ParseXaml(new StringReader(xaml)); Assert.AreEqual(1, generator.NamedFields.Count()); Assert.AreEqual("bar", generator.NamedFields.First().Name); Assert.AreEqual("System.Maui.ContentPage", generator.NamedFields.First().Type.BaseType); } [Test] public void XamlGDifferentInputOutputLengths () { var engine = new MSBuild.UnitTests.DummyBuildEngine(); var generator = new XamlGTask () { BuildEngine = engine, AssemblyName = "test", Language = "C#", XamlFiles = new ITaskItem [1], OutputFiles = new ITaskItem [2], }; Assert.IsFalse (generator.Execute (), "XamlGTask.Execute() should fail."); Assert.AreEqual (1, engine.Errors.Count, "XamlGTask should have 1 error."); var error = engine.Errors.First (); Assert.AreEqual ("\"XamlFiles\" refers to 1 item(s), and \"OutputFiles\" refers to 2 item(s). They must have the same number of items.", error.Message); } } }
36.532578
155
0.687112
[ "MIT" ]
AswinPG/maui
System.Maui.Xaml.UnitTests/XamlgTests.cs
12,896
C#
using System; namespace ReservationSystem.Base.Services.Identity { public interface IIdentityContext { Guid UserId { get; } UserRoles Roles { get; } bool IsAuthenticated { get; } bool IsAdmin { get; } } }
19.307692
50
0.613546
[ "MIT" ]
DawidMierzejewski/reservation-system
src/Base/ReservationSystem.Base.Services/Identity/IIdentityContext.cs
253
C#
using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Configuration; namespace SlackBufferedLogger.Extensions { public static class SlackBufferedLoggerExtensions { public static ILoggingBuilder AddSlackBufferedLogger( this ILoggingBuilder builder) { _ = builder ?? throw new ArgumentNullException(nameof(builder)); builder.AddConfiguration(); builder.Services.AddSingleton<ISlackWebhookService, SlackWebhookService>(); builder.Services.TryAddEnumerable( ServiceDescriptor.Singleton<ILoggerProvider, SlackBufferedLoggerProvider>()); LoggerProviderOptions.RegisterProviderOptions <SlackBufferedLoggerConfiguration, SlackBufferedLoggerProvider>(builder.Services); return builder; } public static ILoggingBuilder AddSlackBufferedLogger(this ILoggingBuilder builder, Action<SlackBufferedLoggerConfiguration> configure) { _ = builder ?? throw new ArgumentNullException(nameof(builder)); builder.AddSlackBufferedLogger(); builder.Services.Configure(configure); return builder; } } }
33.7
142
0.709941
[ "MIT" ]
kristofferjalen/SlackBufferedLogger
SlackBufferedLogger/Extensions/SlackBufferedLoggerExtensions.cs
1,350
C#
using Volo.Abp.Data; using Volo.Abp.MongoDB; namespace EasyAbp.UniappManagement.MongoDB { [ConnectionStringName(UniappManagementDbProperties.ConnectionStringName)] public class UniappManagementMongoDbContext : AbpMongoDbContext, IUniappManagementMongoDbContext { /* Add mongo collections here. Example: * public IMongoCollection<Question> Questions => Collection<Question>(); */ protected override void CreateModel(IMongoModelBuilder modelBuilder) { base.CreateModel(modelBuilder); modelBuilder.ConfigureUniappManagement(); } } }
31.15
100
0.712681
[ "MIT" ]
EasyAbp/UniApp
src/EasyAbp.UniappManagement.MongoDB/EasyAbp/UniappManagement/MongoDB/UniappManagementMongoDbContext.cs
625
C#
#region Licence /**************************************************************************** Copyright 1999-2015 Vincent J. Jacquet. All rights reserved. Permission is granted to anyone to use this software for any purpose on any computer system, and to alter it and redistribute it, subject to the following restrictions: 1. The author is not responsible for the consequences of use of this software, no matter how awful, even if they arise from flaws in it. 2. The origin of this software must not be misrepresented, either by explicit claim or by omission. Since few users ever read sources, credits must appear in the documentation. 3. Altered versions must be plainly marked as such, and must not be misrepresented as being the original software. Since few users ever read sources, credits must appear in the documentation. 4. This notice may not be removed or altered. ****************************************************************************/ #endregion using System; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Globalization; using System.Security; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace WmcSoft { [Serializable] [XmlSchemaProvider("GetSchema")] [TypeConverter(typeof(LatitudeConverter))] public partial struct Latitude : IXmlSerializable { class LatitudeConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof(InstanceDescriptor) || destinationType == typeof(string) || base.CanConvertTo(context, destinationType); } static Latitude ParseInvariant(string input) { var d = decimal.Parse(input, CultureInfo.InvariantCulture); return new Latitude(d); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value == null) throw GetConvertFromException(value); if (value is string text) return ParseInvariant(text); throw new ArgumentException(nameof(value)); } [SecurityCritical] public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (value is Latitude l) { if (destinationType == typeof(InstanceDescriptor)) { var method = GetType().GetConstructor(new Type[] { typeof(int), typeof(int), typeof(int), typeof(int) }); var (y, m, d, s) = l; return new InstanceDescriptor(method, new object[] { y, m, d, s }); } if (destinationType == typeof(string)) { decimal degrees = l; return degrees >= 0 ? string.Format(CultureInfo.InvariantCulture, "+{0:00.######}", degrees) : string.Format(CultureInfo.InvariantCulture, "-{0:00.######}", -degrees); } } return base.ConvertTo(context, culture, value, destinationType); } } public static XmlQualifiedName GetSchema(XmlSchemaSet _) { return new XmlQualifiedName("decimal", "http://www.w3.org/2001/XMLSchema"); } XmlSchema IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { var d = reader.NodeType == XmlNodeType.Element ? reader.ReadElementContentAsDecimal() : reader.ReadContentAsDecimal(); this = new Latitude(d); } void IXmlSerializable.WriteXml(XmlWriter writer) { writer.WriteValue(this); } } }
36.897436
153
0.577716
[ "MIT" ]
vjacquet/WmcSoft
WmcSoft.Business.Primitives/Latitude.Serialization.cs
4,319
C#
using Unity.Networking.Transport; using UnityEngine; public class NetMessage { public OpCode Code { get; set; } public virtual void Serialize(ref DataStreamWriter writer) { writer.WriteByte((byte)Code); } public virtual void Deserialize(DataStreamReader reader) { } public virtual void ReceivedOnClient() { } public virtual void ReceivedOnServer(NetworkConnection cnn) { } }
15.821429
63
0.672686
[ "MIT" ]
f-delacre/chaotic-chess
Assets/Scripts/Net/NetMessage/NetMessage.cs
443
C#
using Grasshopper.Kernel; using Grasshopper.Kernel.Types; using Rhino.Geometry; using System; using System.Collections.Generic; namespace GraphicPlus.Components.Drawings { public class GH_DrawingToText : GH_Component { /// <summary> /// Initializes a new instance of the GH_DrawingToScript class. /// </summary> public GH_DrawingToText() : base("SVG Text", "SVGtxt", "Converts a Drawing to SVG txt"+Environment.NewLine+"( WARNING: Complex drawings can crash Grasshopper's UI. Use the Save Svg component if this is the case.)", "Display", "Graphics") { } /// <summary> /// Set Exposure level for the component. /// </summary> public override GH_Exposure Exposure { get { return GH_Exposure.quinary | GH_Exposure.obscure; } } /// <summary> /// Registers all the input parameters for this component. /// </summary> protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager) { pManager.AddGenericParameter("Drawings / Shapes / Geometry", "D", "A list of Graphic Plus Drawing, Shapes, or Geometry (Curves, Breps, Meshes).", GH_ParamAccess.list); } /// <summary> /// Registers all the output parameters for this component. /// </summary> protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager) { pManager.AddTextParameter("SVG Text", "T", "The Svg text", GH_ParamAccess.item); } /// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { Drawing drawing = new Drawing(); List<IGH_Goo> goos = new List<IGH_Goo>(); if (!DA.GetDataList(0, goos)) return; foreach (IGH_Goo goo in goos) { goo.TryGetDrawings(ref drawing); } DA.SetData(0, drawing.ToScript()); } /// <summary> /// Provides an Icon for the component. /// </summary> protected override System.Drawing.Bitmap Icon { get { //You can add image files to your project resources and access them like this: // return Resources.IconForThisComponent; return Properties.Resources.GP_SVG_Text_01; } } /// <summary> /// Gets the unique ID for this component. Do not change this ID after release. /// </summary> public override Guid ComponentGuid { get { return new Guid("005ccb43-e524-4da8-ae64-8f5eea6402d6"); } } } }
34.928571
179
0.58589
[ "MIT" ]
interopxyz/GraphicPlus
GraphicPlus/Components/Drawings/GH_DrawingToText.cs
2,936
C#
// <copyright file="CalculationType.cs" company="Pyatygin S.Y."> // Copyright (c) Pyatygin S.Y.. All rights reserved. // </copyright> namespace SADT.Core.Enums { /// <summary> /// Calculation type. /// </summary> public enum CalculationType { /// <summary> /// Calculation transformer. /// </summary> CalculationTransformer, /// <summary> /// Calculation optimization. /// </summary> CalculationOptimization, } }
21.913043
65
0.569444
[ "MIT" ]
PyatyginSY/BindingRadioButtonsOrCheckBoxesToEnums
BindingRadioButtonsOrCheckBoxesToEnums.Core/Enums/CalculationType.cs
506
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:3.0.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ZigBeeNet.Hardware.Ember.Ezsp.Command { using ZigBeeNet.Hardware.Ember.Internal.Serializer; /// <summary> /// Class to implement the Ember EZSP command " callback ". /// Allows the NCP to respond with a pending callback. /// This class provides methods for processing EZSP commands. /// </summary> public class EzspCallbackRequest : EzspFrameRequest { public const int FRAME_ID = 6; private EzspSerializer _serializer; public EzspCallbackRequest() { _frameId = FRAME_ID; _serializer = new EzspSerializer(); } /// <summary> /// Method for serializing the command fields </summary> public override int[] Serialize() { SerializeHeader(_serializer); return _serializer.GetPayload(); } public override string ToString() { return base.ToString(); } } }
29.145833
80
0.518942
[ "EPL-1.0" ]
JanneMattila/ZigbeeNet
libraries/ZigbeeNet.Hardware.Ember/Ezsp/Command/EzspCallbackRequest.cs
1,399
C#
// ------------------------------------------------------------------------------------------------- // <copyright file="ElementGroupingMembershipContradictionErrorFactory.cs" company="RHEA System S.A."> // // Copyright 2022 RHEA System S.A. // // 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> // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ // --------THIS IS AN AUTOMATICALLY GENERATED FILE. ANY MANUAL CHANGES WILL BE OVERWRITTEN!-------- // ------------------------------------------------------------------------------------------------ namespace Kalliope.Dal { using System; using Kalliope.Core; using Kalliope.Diagrams; /// <summary> /// The purpose of the <see cref="ElementGroupingMembershipContradictionErrorFactory"/> is to create a new instance of a /// <see cref="Kalliope.Core.ElementGroupingMembershipContradictionError"/> based on a <see cref="Kalliope.DTO.ElementGroupingMembershipContradictionError"/> /// </summary> public class ElementGroupingMembershipContradictionErrorFactory { /// <summary> /// Creates an instance of the <see cref="ElementGroupingMembershipContradictionError"/> and sets the value properties /// based on the DTO /// </summary> /// <param name="dto"> /// The instance of the <see cref="Kalliope.DTO.ElementGroupingMembershipContradictionError"/> /// </param> /// <returns> /// an instance of <see cref="Kalliope.Core.ElementGroupingMembershipContradictionError"/> /// </returns> /// <exception cref="ArgumentNullException"> /// thrown when <paramref name="dto"/> is null /// </exception> public Kalliope.Core.ElementGroupingMembershipContradictionError Create(Kalliope.DTO.ElementGroupingMembershipContradictionError dto) { if (dto == null) { throw new ArgumentNullException(nameof(dto), $"the {nameof(dto)} may not be null"); } var elementGroupingMembershipContradictionError = new Kalliope.Core.ElementGroupingMembershipContradictionError() { ErrorState = dto.ErrorState, ErrorText = dto.ErrorText, Id = dto.Id, }; return elementGroupingMembershipContradictionError; } } } // ------------------------------------------------------------------------------------------------ // --------THIS IS AN AUTOMATICALLY GENERATED FILE. ANY MANUAL CHANGES WILL BE OVERWRITTEN!-------- // ------------------------------------------------------------------------------------------------
46.69863
162
0.533588
[ "Apache-2.0" ]
RHEAGROUP/Kalliope
Kalliope.Dal/AutoGenModelThingFactories/ElementGroupingMembershipContradictionErrorFactory.cs
3,409
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XsDupFinder.Lib.Finder { public class Duplicate { public class Location { public string Filename { get; set; } public string ClassName { get; set; } public string MethodName { get; set; } public int StartLine { get; set; } public int EndLine { get; set; } public int PercentOfMethod { get; set; } public bool IsFullMethod => PercentOfMethod == 100; } public int ID { get; set; } public List<int> OverlappingIDs { get; set; } public int LineCount => Locations.Count > 0 ? Locations[0].EndLine - Locations[0].StartLine + 1 : 0; public string Code { get; set; } public List<Location> Locations { get; set; } = new List<Location>(); } }
31.793103
108
0.597614
[ "Apache-2.0" ]
VolkmarR/XsDupFinder
src/XsDupFinder.Lib/Finder/Duplicate.cs
924
C#
using System; using System.Collections.Generic; using System.Linq; using VocaDb.Model.DataContracts; using VocaDb.Model.Helpers; using System.Collections; using VocaDb.Model.Utils; namespace VocaDb.Model.Domain.Globalization { public class NameManager<T> : INameManager<T>, IEnumerable<T> where T : LocalizedStringWithId { private string additionalNamesString; private IList<T> names = new List<T>(); private TranslatedString sortNames = new TranslatedString(); private T GetDefaultName() { if (!Names.Any()) return null; var name = FirstName(sortNames.DefaultLanguage); return name ?? Names.First(); } private T GetFirstName(ContentLanguageSelection languageSelection) { if (!Names.Any()) return null; var name = FirstName(languageSelection); // Substitute English with Romaji if (name == null && languageSelection == ContentLanguageSelection.English) name = FirstName(ContentLanguageSelection.Romaji); // Substitute Romaji with English if (name == null && languageSelection == ContentLanguageSelection.Romaji) name = FirstName(ContentLanguageSelection.English); return name ?? GetDefaultName(); } private void SetValueFor(ContentLanguageSelection language) { if (!Names.Any()) return; var name = GetFirstName(language); if (name != null) SortNames[language] = name.Value; if (string.IsNullOrEmpty(SortNames[language])) SortNames[language] = Names.First().Value; } /// <summary> /// Comma-separated string containing names that aren't part of any sort name. /// This can be used to construct the additional names string without loading the full list of names from the DB. /// </summary> public virtual string AdditionalNamesString { get { return additionalNamesString; } set { ParamIs.NotNull(() => value); additionalNamesString = value; } } public virtual IEnumerable<string> AllValues { get { return SortNames.All .Concat(Names.Select(n => n.Value)) .Distinct(); } } /// <summary> /// List of names. /// This is the list of assigned names for a entry. /// /// This list does not automatically include the sort names: /// the entry might have a translated sort name (<see cref="SortNames"/>) /// even though this list is empty. /// /// The sort names are generated from this list. /// This list is persisted to the database. /// /// Cannot be null. /// </summary> public virtual IList<T> Names { get { return names; } set { ParamIs.NotNull(() => value); names = value; } } public virtual IEnumerable<LocalizedStringWithId> NamesBase { get { return Names; } } public virtual TranslatedString SortNames { get { return sortNames; } set { ParamIs.NotNull(() => value); sortNames = value; } } public virtual void Add(T name, bool update = true) { Names.Add(name); if (update) UpdateSortNames(); } /// <summary> /// Gets the first name matching a language selection. /// Language substitutions are *not* applied. /// </summary> /// <param name="languageSelection">Language selection.</param> /// <returns>Name. Can be null if there is no name for the specfied language selection.</returns> public T FirstName(ContentLanguageSelection languageSelection) { return Names.FirstOrDefault(n => n.Language == languageSelection); } public LocalizedStringWithId FirstNameBase(ContentLanguageSelection languageSelection) { return FirstName(languageSelection); } public string FirstNameValue(ContentLanguageSelection languageSelection) { var name = FirstName(languageSelection); return name != null ? name.Value : null; } public string GetAdditionalNamesStringForLanguage(ContentLanguagePreference languagePreference) { var display = SortNames[languagePreference]; var different = SortNames.All.Where(s => s != display).Distinct(); if (!string.IsNullOrEmpty(AdditionalNamesString)) return string.Join(", ", different.Concat(Enumerable.Repeat(AdditionalNamesString, 1))); else return string.Join(", ", different); } IEnumerator IEnumerable.GetEnumerator() { return Names.GetEnumerator(); } public virtual IEnumerator<T> GetEnumerator() { return Names.GetEnumerator(); } public EntryNameContract GetEntryName(ContentLanguagePreference languagePreference) { var display = SortNames[languagePreference]; var additional = GetAdditionalNamesStringForLanguage(languagePreference); return new EntryNameContract(display, additional); } public virtual string GetUrlFriendlyName() { return UrlFriendlyNameFactory.GetUrlFriendlyName(this); } public virtual bool HasName(LocalizedString name) { return Names.Any(n => n.ContentEquals(name)); } public virtual bool HasNameForLanguage(ContentLanguageSelection language) { return FirstName(language) != null; } public virtual bool HasName(string val) { return Names.Any(n => n.Value.Equals(val, StringComparison.InvariantCultureIgnoreCase)); } public virtual void Init(IEnumerable<LocalizedStringContract> names, INameFactory<T> nameFactory) { ParamIs.NotNull(() => names); ParamIs.NotNull(() => nameFactory); foreach (var name in names) nameFactory.CreateName(name.Value, name.Language); if (names.Any(n => n.Language == ContentLanguageSelection.Japanese)) SortNames.DefaultLanguage = ContentLanguageSelection.Japanese; else if (names.Any(n => n.Language == ContentLanguageSelection.Romaji)) SortNames.DefaultLanguage = ContentLanguageSelection.Romaji; else if (names.Any(n => n.Language == ContentLanguageSelection.English)) SortNames.DefaultLanguage = ContentLanguageSelection.English; } public virtual void Remove(T name, bool update = true) { Names.Remove(name); if (update) UpdateSortNames(); } public virtual CollectionDiffWithValue<T,T> Sync(IEnumerable<LocalizedStringWithIdContract> newNames, INameFactory<T> nameFactory) { ParamIs.NotNull(() => newNames); ParamIs.NotNull(() => nameFactory); var diff = CollectionHelper.Diff(Names, newNames, (n1, n2) => n1.Id == n2.Id); var created = new List<T>(); var edited = new List<T>(); foreach (var n in diff.Removed) { Remove(n); } foreach (var nameEntry in newNames) { var entry = nameEntry; var old = (entry.Id != 0 ? Names.FirstOrDefault(n => n.Id == entry.Id) : null); if (old != null) { if (!old.ContentEquals(nameEntry)) { old.Language = nameEntry.Language; old.Value = nameEntry.Value; edited.Add(old); } } else { var n = nameFactory.CreateName(nameEntry.Value, nameEntry.Language); created.Add(n); } } UpdateSortNames(); return new CollectionDiffWithValue<T,T>(created, diff.Removed, diff.Unchanged, edited); } public virtual CollectionDiff<T, T> SyncByContent(IEnumerable<LocalizedStringContract> newNames, INameFactory<T> nameFactory) { ParamIs.NotNull(() => newNames); ParamIs.NotNull(() => nameFactory); var diff = CollectionHelper.Diff(Names, newNames, (n1, n2) => n1.ContentEquals(n2)); var created = new List<T>(); foreach (var n in diff.Removed) { Remove(n); } foreach (var nameEntry in diff.Added) { var n = nameFactory.CreateName(nameEntry.Value, nameEntry.Language); created.Add(n); } UpdateSortNames(); return new CollectionDiff<T, T>(created, diff.Removed, diff.Unchanged); } public virtual void UpdateSortNames() { if (!Names.Any()) return; var languages = new[] { ContentLanguageSelection.Japanese, ContentLanguageSelection.Romaji, ContentLanguageSelection.English }; foreach (var l in languages) SetValueFor(l); var additionalNames = Names.Select(n => n.Value).Where(n => !SortNames.All.Contains(n)).Distinct(); AdditionalNamesString = string.Join(", ", additionalNames); } } public class BasicNameManager : NameManager<LocalizedStringWithId> { public BasicNameManager() { } public BasicNameManager(INameManager nameManager) { ParamIs.NotNull(() => nameManager); Names = nameManager.NamesBase.Select(n => new LocalizedStringWithId(n.Value, n.Language)).ToArray(); SortNames = new TranslatedString(nameManager.SortNames); } } }
26.103448
134
0.701333
[ "MIT" ]
cazzar/VocaDbTagger
VocaDbModel/Domain/Globalization/NameManager.cs
8,329
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // try/catch, try/finally using System; using System.Runtime.CompilerServices; class Test4 { public static string teststr1 = null; public static string[] teststr2 = new string[3]; public static string teststr3 = null; public const string teststr4 = "const string\""; // special case for DiffObjRef public const string testgenstr4 = "GenC const string\""; // special case for DiffObjRef public static string teststr5 = null; // special case for DiffObjRef public static bool TestSameObjRef() { Console.WriteLine(); Console.WriteLine("When NGEN'ed, two strings in different modules have different object reference"); Console.WriteLine("When NGEN'ed, two strings in the same module have same object reference"); Console.WriteLine("When JIT'ed, two strings always have same object reference"); Console.WriteLine(); Console.WriteLine("Testing SameObjRef"); bool passed = true; string b = null; try { teststr1 = "static \uC09C\u7B8B field"; b = C.teststr1; throw new Exception(); } catch (System.Exception) { } if ((object)teststr1 != (object)b) { passed = false; Console.WriteLine("FAILED, (object) teststr1 == (object) b is expected"); } try { teststr2[0] = "\u3F2Aarray element 0"; b = C.teststr2[0]; throw new Exception(); } catch (System.Exception) { if ((object)teststr2[0] != (object)C.teststr2[0]) { passed = false; Console.WriteLine("FAILED, (object) teststr2[0] == (object)C.teststr2[0] is expected"); } } try { throw new Exception(); } catch (System.Exception) { teststr2[1] = "array element 1\uCB53"; b = C.teststr2[1]; } if ((object)teststr2[1] != (object)b) { passed = false; Console.WriteLine("FAILED, (object) teststr2[1] == (object) b is expected"); } try { throw new Exception(); } catch (System.Exception) { } finally { teststr2[2] = "array \u47BBelement 2"; } if ((object)teststr2[2] != (object)C.teststr2[2]) { passed = false; Console.WriteLine("FAILED, (object)teststr2[2] == (object)C.teststr2[2] is expected"); } try { teststr3 = @"method return\\"; throw new Exception(); } catch (System.Exception) { if ((object)teststr3 != (object)C.teststr3()) { passed = false; Console.WriteLine("FAILED, (object) teststr3 == (object)C.teststr3() is expected"); } try { } finally { if ((object)teststr4 != (object)C.teststr4) { passed = false; Console.WriteLine("FAILED, (object)teststr4 != (object)C.teststr4 is expected"); } try { throw new Exception(); } catch { } finally { teststr5 = String.Empty; if ((object)teststr5 != (object)C.teststr5) { passed = false; Console.WriteLine("FAILED, (object) teststr5 != (object)C.teststr5 is expected"); } } } } // Generic Class try { teststr1 = "GenC static \uC09C\u7B8B field"; b = GenC<string>.teststr1; throw new Exception(); } catch (System.Exception) { } if ((object)teststr1 != (object)b) { passed = false; Console.WriteLine("FAILED, (object)teststr1 == (object)GenC<string>.teststr1 is expected"); } try { teststr2[0] = "GenC \u3F2Aarray element 0"; throw new Exception(); } catch (System.Exception) { if ((object)teststr2[0] != (object)GenC<string>.teststr2[0]) { passed = false; Console.WriteLine("FAILED, (object) teststr2[0] == (object)GenC<string>.teststr2[0] is expected"); } } try { throw new Exception(); } catch (System.Exception) { teststr2[1] = "GenC array element 1\uCB53"; b = GenC<string>.teststr2[1]; } if ((object)teststr2[1] != (object)b) { passed = false; Console.WriteLine("FAILED, (object) teststr2[1] == (object)GenC<string>.teststr2[1] is expected"); } try { throw new Exception(); } catch (System.Exception) { } finally { teststr2[2] = "GenC array \u47BBelement 2"; } if ((object)teststr2[2] != (object)GenC<string>.teststr2[2]) { passed = false; Console.WriteLine("FAILED, (object)teststr2[2] == (object)GenC<string>.teststr2[2] is expected"); } try { teststr3 = @"GenC method return\\"; throw new Exception(); } catch (System.Exception) { if ((object)teststr3 != (object)GenC<string>.teststr3<int>()) { passed = false; Console.WriteLine("FAILED, (object) teststr3 == (object)GenC<string>.teststr3<int>() is expected"); } try { } finally { if ((object)testgenstr4 != (object)GenC<string>.teststr4) { passed = false; Console.WriteLine("FAILED, (object)testgenstr4 != (object)GenC<string>.teststr4 is expected"); } try { throw new Exception(); } catch { } finally { teststr5 = String.Empty; if ((object)teststr5 != (object)GenC<string>.teststr5) { passed = false; Console.WriteLine("FAILED, (object) teststr5 != (object)GenC<string>.teststr5 is expected"); } } } } return passed; } public static bool TestDiffObjRef() { Console.WriteLine(); Console.WriteLine("When NGEN'ed, two strings in different modules have different object reference"); Console.WriteLine("When NGEN'ed, two strings in the same module have same object reference"); Console.WriteLine("When JIT'ed, two strings always have same object reference"); Console.WriteLine(); Console.WriteLine("Testing DiffObjRef"); bool passed = true; string b = null; try { teststr1 = "static \uC09C\u7B8B field"; b = C.teststr1; throw new Exception(); } catch (System.Exception) { } if ((object)teststr1 == (object)b) { passed = false; Console.WriteLine("FAILED, (object) teststr1 == (object) b is NOT expected"); } try { teststr2[0] = "\u3F2Aarray element 0"; b = C.teststr2[0]; throw new Exception(); } catch (System.Exception) { if ((object)teststr2[0] == (object)C.teststr2[0]) { passed = false; Console.WriteLine("FAILED, (object) teststr2[0] == (object)C.teststr2[0] is NOT expected"); } } try { throw new Exception(); } catch (System.Exception) { teststr2[1] = "array element 1\uCB53"; b = C.teststr2[1]; } if ((object)teststr2[1] == (object)b) { passed = false; Console.WriteLine("FAILED, (object) teststr2[1] == (object) b is NOT expected"); } try { throw new Exception(); } catch (System.Exception) { } finally { teststr2[2] = "array \u47BBelement 2"; } if ((object)teststr2[2] == (object)C.teststr2[2]) { passed = false; Console.WriteLine("FAILED, (object)teststr2[2] == (object)C.teststr2[2] is NOT expected"); } try { teststr3 = @"method return\\"; throw new Exception(); } catch (System.Exception) { if ((object)teststr3 == (object)C.teststr3()) { passed = false; Console.WriteLine("FAILED, (object) teststr3 == (object)C.teststr3() is NOT expected"); } try { } finally { // Special case for const literal teststr4 // two consecutive LDSTR is emitted by C# compiler for the following statement // as a result, both are interned in the same module and object comparison returns true if ((object)teststr4 != (object)C.teststr4) { passed = false; Console.WriteLine("FAILED, (object)teststr4 == (object)C.teststr4 is expected"); } try { throw new Exception(); } catch { } finally { teststr5 = String.Empty; // Special case for String.Empty // String.Empty is loaded using LDSFLD, rather than LDSTR in any module // as a result, it is always the same reference to [mscorlib]System.String::Empty, // and object comparison return true if ((object)teststr5 != (object)C.teststr5) { passed = false; Console.WriteLine("FAILED, (object) teststr5 == (object)C.teststr5 is expected"); } } } } // Generic Class try { teststr1 = "GenC static \uC09C\u7B8B field"; b = GenC<string>.teststr1; throw new Exception(); } catch (System.Exception) { } if ((object)teststr1 == (object)b) { passed = false; Console.WriteLine("FAILED, (object)teststr1 == (object)GenC<string>.teststr1 is NOT expected"); } try { teststr2[0] = "GenC \u3F2Aarray element 0"; throw new Exception(); } catch (System.Exception) { if ((object)teststr2[0] == (object)GenC<string>.teststr2[0]) { passed = false; Console.WriteLine("FAILED, (object) teststr2[0] == (object)GenC<string>.teststr2[0] is NOT expected"); } } try { throw new Exception(); } catch (System.Exception) { teststr2[1] = "GenC array element 1\uCB53"; b = GenC<string>.teststr2[1]; } if ((object)teststr2[1] == (object)b) { passed = false; Console.WriteLine("FAILED, (object) teststr2[1] == (object)GenC<string>.teststr2[1] is NOT expected"); } try { throw new Exception(); } catch (System.Exception) { } finally { teststr2[2] = "GenC array \u47BBelement 2"; } if ((object)teststr2[2] == (object)GenC<string>.teststr2[2]) { passed = false; Console.WriteLine("FAILED, (object)teststr2[2] == (object)GenC<string>.teststr2[2] is NOT expected"); } try { teststr3 = @"GenC method return\\"; throw new Exception(); } catch (System.Exception) { if ((object)teststr3 == (object)GenC<string>.teststr3<int>()) { passed = false; Console.WriteLine("FAILED, (object) teststr3 == (object)GenC<string>.teststr3<int>() is NOT expected"); } try { } finally { // Special case for const literal teststr4 // two consecutive LDSTR is emitted by C# compiler for the following statement // as a result, both are interned in the same module and object comparison returns true if ((object)testgenstr4 != (object)GenC<string>.teststr4) { passed = false; Console.WriteLine("FAILED, (object)testgenstr4 == (object)GenC<string>.teststr4 is expected"); } try { throw new Exception(); } catch { } finally { teststr5 = String.Empty; // Special case for String.Empty // String.Empty is loaded using LDSFLD, rather than LDSTR in any module // as a result, it is always the same reference to [mscorlib]System.String::Empty, // and object comparison return true if ((object)teststr5 != (object)GenC<string>.teststr5) { passed = false; Console.WriteLine("FAILED, (object) teststr5 == (object)GenC<string>.teststr5 is expected"); } } } } return passed; } public static int Main(string[] args) { bool passed = false; if ((args.Length < 1) || (args[0].ToUpper() == "SAMEOBJREF")) passed = TestSameObjRef(); else if (args[0].ToUpper() == "DIFFOBJREF") passed = TestDiffObjRef(); else { Console.WriteLine("Usage: Test4.exe [SameObjRef|DiffObjRef]"); Console.WriteLine(); Console.WriteLine("When NGEN'ed, two strings in different modules have different object reference"); Console.WriteLine("When NGEN'ed, two strings in the same module have same object reference"); Console.WriteLine("When JIT'ed, two strings always have same object reference"); Console.WriteLine(); return 9; } Console.WriteLine(); if (passed) { Console.WriteLine("PASSED"); return 100; } else { Console.WriteLine("FAILED"); return 1; } } }
30.086207
119
0.466794
[ "MIT" ]
06needhamt/runtime
src/coreclr/tests/src/JIT/Methodical/stringintern/test4.cs
15,705
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Iot.Device.Media { /// <summary> /// The default and current values of a video device's control. /// </summary> public class VideoDeviceValue { /// <summary> /// Instantiate VideoDeviceValue. /// </summary> /// <param name="name">Control's name.</param> /// <param name="minimum">Minimum value.</param> /// <param name="maximum">Maximum value.</param> /// <param name="step">Value change step.</param> /// <param name="defaultValue">Control's default value.</param> /// <param name="currentValue">Control's current value.</param> public VideoDeviceValue(string name, int minimum, int maximum, int step, int defaultValue, int currentValue) { Name = name; Minimum = minimum; Maximum = maximum; Step = step; DefaultValue = defaultValue; CurrentValue = currentValue; } /// <summary> /// Control's name /// </summary> public string Name { get; set; } /// <summary> /// Minimum value /// </summary> public int Minimum { get; set; } /// <summary> /// Maximum value /// </summary> public int Maximum { get; set; } /// <summary> /// Value change step size /// </summary> public int Step { get; set; } /// <summary> /// Control's default value /// </summary> public int DefaultValue { get; set; } /// <summary> /// Control's current value /// </summary> public int CurrentValue { get; set; } } }
30.885246
117
0.519108
[ "MIT" ]
gukoff/nanoFramework.IoT.Device
src/devices_generated/Media/VideoDevice/VideoDeviceValue.cs
1,884
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MouseLook : MonoBehaviour { public float mouseSensitivity = 100f; public Transform playerBody; float xRoration = 0f; public int zoom = 20; public int normal = 60; public float smooth = 5; private bool isZoomed = false; // Start is called before the first frame update void Start() { Cursor.lockState = CursorLockMode.Locked; } // Update is called once per frame void Update() { if (Input.GetMouseButtonDown(1)) { isZoomed = !isZoomed; } if (isZoomed) { GetComponent<Camera>().fieldOfView = Mathf.Lerp(GetComponent<Camera>().fieldOfView, zoom, Time.deltaTime * smooth); } else { GetComponent<Camera>().fieldOfView = Mathf.Lerp(GetComponent<Camera>().fieldOfView, normal, Time.deltaTime * smooth); } float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime; float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime; xRoration -= mouseY; xRoration = Mathf.Clamp(xRoration, -90f, 90f); transform.localRotation = Quaternion.Euler(xRoration, 0f, 0f); playerBody.Rotate(Vector3.up * mouseX); } }
30.288889
129
0.622157
[ "MIT" ]
RyzAnugrah/the-maze
Assets/Scripts/Game/MouseLook.cs
1,365
C#
using System; using System.Buffers; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using Alex.Common; using Alex.Common.Blocks; using Alex.Common.Graphics; using Alex.Common.Graphics.GpuResources; using Alex.Common.Utils.Vectors; using Alex.Graphics.Models.Blocks; using Alex.Utils.Threading; using Alex.Worlds.Abstraction; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics.PackedVector; using NLog; namespace Alex.Worlds.Chunks { /*public class ChunkRenderStage : IDisposable { private readonly RenderStage _stage; private Dictionary<BlockCoordinates, BlockRecord> BlockIndices { get; set; } public bool HasChanges { get; set; } public bool IsEmpty => BlockIndices == null || BlockIndices.Count == 0; public int Size { get; set; } = 0; public int Position { get; set; } = 0; public ChunkRenderStage(RenderStage stage) { _stage = stage; BlockIndices = new Dictionary<BlockCoordinates, BlockRecord>(); } public void Remove(BlockCoordinates coordinates) { var bi = BlockIndices; if (bi == null) return; if (bi.TryGetValue(coordinates, out var indices)) { indices.Data.Clear(); HasChanges = true; } } public bool Contains(BlockCoordinates coordinates) { var bi = BlockIndices; if (bi == null) return false; return bi.ContainsKey(coordinates); } public static int BufferUploads = 0; public static int BufferCreations = 0; private bool _disposed = false; public void Dispose() { if (_disposed) return; try { var keys = BlockIndices.Keys.ToArray(); foreach (var key in keys) { Remove(key); } BlockIndices.Clear(); BlockIndices = null; } finally { _disposed = true; } } }*/ }
21.551724
82
0.696
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
kennyvv/Alex
src/Alex/Worlds/Chunks/ChunkRenderStage.cs
1,875
C#
//! \file ImagePRG.cs //! \date 2019 May 05 //! \brief Regrips obfuscated image. // // Copyright (C) 2019 by morkt // // 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.Composition; using System.IO; using System.Windows.Media; namespace GameRes.Formats.Regrips { [Export(typeof(ImageFormat))] public class PrgFormat : ImageFormat { public override string Tag { get { return "PRG"; } } public override string Description { get { return "Regrips encrypted image format"; } } public override uint Signature { get { return 0xB8B1AF76; } } public override bool CanWrite { get { return false; } } public override ImageMetaData ReadMetaData (IBinaryStream file) { using (var input = DecryptStream (file)) return Png.ReadMetaData (input); } public override ImageData Read (IBinaryStream file, ImageMetaData info) { using (var input = DecryptStream (file)) return Png.Read (input, info); } internal IBinaryStream DecryptStream (IBinaryStream input) { var stream = new XoredStream (input.AsStream, 0xFF, true); return new BinaryStream (stream, input.Name); } public override void Write (Stream file, ImageData image) { throw new System.NotImplementedException ("PrgFormat.Write not implemented"); } } [Export(typeof(ImageFormat))] public class BrgFormat : PrgFormat { public override string Tag { get { return "BRG"; } } public override string Description { get { return "Regrips encrypted bitmap"; } } public override uint Signature { get { return 0; } } public override bool CanWrite { get { return false; } } public override ImageMetaData ReadMetaData (IBinaryStream file) { var header = file.ReadHeader (2); if (header[0] != 0xBD || header[1] != 0xB2) return null; file.Position = 0; using (var input = DecryptStream (file)) return Bmp.ReadMetaData (input); } public override ImageData Read (IBinaryStream file, ImageMetaData info) { using (var input = DecryptStream (file)) return Bmp.Read (input, info); } public override void Write (Stream file, ImageData image) { throw new System.NotImplementedException ("BrgFormat.Write not implemented"); } } }
38.670213
95
0.645942
[ "MIT" ]
AyamiKaze/GARbro
Legacy/Regrips/ImagePRG.cs
3,635
C#
using System; namespace Lidgren.Network { /// <summary> /// Result of a SendMessage call /// </summary> public enum NetSendResult { /// <summary> /// Message failed to enqueue because there is no connection /// </summary> FailedNotConnected = 0, /// <summary> /// Message was immediately sent /// </summary> Sent = 1, /// <summary> /// Message was queued for delivery /// </summary> Queued = 2, /// <summary> /// Message was dropped immediately since too many message were queued /// </summary> Dropped = 3 } }
18.870968
73
0.593162
[ "MIT" ]
BeastLe9enD/lidgren-network-gen3
Lidgren.Network/NetSendResult.cs
589
C#
namespace Nullable.Extensions.Async { using System; using System.Threading.Tasks; /// <summary>Defines the `TapAsync()` extension for `T?` and `Task`s of type `T?`.</summary> public static class TapAsyncExt { /// <summary>Executes an asychronous side effect when the nullable value is not `null`.</summary> /// <param name="x">The nullable value.</param> /// <param name="effect">The asychronous side effect to execute. Its argument is guaranteed to be not `null`.</param> /// <returns>A `Task` returning the nullable input value unchanged.</returns> public static async Task<T?> TapAsync<T>(this T? x, Func<T, Task> effect) where T : class { if (x != null) await effect(x); return x; } /// <summary>`await`s the given `Task` of type `T?` and calls `TapAsync(effect)` on the returned nullable value.</summary> /// <param name="x">The nullable value `Task`.</param> /// <param name="effect">The asychronous side effect to execute. Its argument is guaranteed to be not `null`.</param> /// <returns>A `Task` wrapping the result of `TapAsync(effect)`.</returns> public static async Task<T?> TapAsync<T>(this Task<T?> x, Func<T, Task> effect) where T : class => await (await x).TapAsync(effect); /// <summary>Executes an asychronous side effect when the nullable value is not `null`.</summary> /// <param name="x">The nullable value.</param> /// <param name="effect">The asychronous side effect to execute. Its argument is guaranteed to be not `null`.</param> /// <returns>A `Task` returning the nullable input value unchanged.</returns> public static async Task<T?> TapAsync<T>(this T? x, Func<T, Task> effect) where T : struct { if (x.HasValue) await effect(x.Value); return x; } /// <summary>`await`s the given `Task` of type `T?` and calls `TapAsync(effect)` on the returned nullable value.</summary> /// <param name="x">The nullable value `Task`.</param> /// <param name="effect">The asychronous side effect to execute. Its argument is guaranteed to be not `null`.</param> /// <returns>A `Task` wrapping the result of `TapAsync(effect)`.</returns> public static async Task<T?> TapAsync<T>(this Task<T?> x, Func<T, Task> effect) where T : struct => await (await x).TapAsync(effect); } }
60.095238
131
0.614501
[ "MIT" ]
bert2/Nullable.Extensions
src/Nullable.Extensions/Async/TapAsyncExt.cs
2,526
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; class Program { static void Main(string[] args) { Type type = typeof(MyReflectionClass); MethodInfo method = type.GetMethod("MyMethod"); MyReflectionClass c = new MyReflectionClass(); string result = (string) method.Invoke(c, null); Console.WriteLine(result); Console.ReadLine(); } } public class MyReflectionClass { public string MyMethod() { Console.WriteLine("Call MyMethod 1"); return "Call MyMethod 2"; } }
22.206897
56
0.661491
[ "MIT" ]
AbdelBelkhiri/eiin839
TD2/ReflectionSample/Program.cs
646
C#
using System; using System.Threading; using Dasync.Accessors; using Dasync.Serialization; using Dasync.ValueContainer; namespace Dasync.Serializers.EETypes.Cancellation { public class CancellationTokenSerializer : IObjectDecomposer, IObjectComposer { public IValueContainer Decompose(object value) { var cancellationToken = (CancellationToken)value; return new CancellationTokenContainer { IsCanceled = cancellationToken.IsCancellationRequested, Source = cancellationToken.IsCancellationRequested ? null : cancellationToken.GetSource() }; } public object Compose(IValueContainer container, Type valueType) { var values = (CancellationTokenContainer)container; if (values.IsCanceled) return new CancellationToken(canceled: true); if (values.Source == null) return CancellationToken.None; return values.Source.Token; } public IValueContainer CreatePropertySet(Type valueType) { return new CancellationTokenContainer(); } } public class CancellationTokenContainer : ValueContainerBase { public bool IsCanceled; public CancellationTokenSource Source; } }
29.195652
105
0.654505
[ "Apache-2.0" ]
Dasync/Dasync
src/Data/Serializers.EETypes/Cancellation/CancellationToken.cs
1,345
C#
using Acr.UserDialogs; using Android.App; using Android.Content.PM; using Android.OS; using Xamarin.Forms; namespace OrderKingCoreDemo.Droid { [Activity(Label = "OrderKingCoreDemo", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); UserDialogs.Init(() => (Activity)Forms.Context); Forms.Init(this, bundle); LoadApplication(new App()); } } }
29.62963
194
0.6875
[ "MIT" ]
Binwell/Order-King-Mobile-Core
OrderKingCoreDemo/OrderKingCoreDemo.Android/MainActivity.cs
800
C#
namespace ArgentPonyWarcraftClassicClient; /// <summary> /// Item media. /// </summary> public record ItemMedia { /// <summary> /// Gets links for the achievement media. /// </summary> [JsonPropertyName("_links")] public Links Links { get; init; } /// <summary> /// Gets a collection of media assets. /// </summary> [JsonPropertyName("assets")] public Asset[] Assets { get; init; } /// <summary> /// Gets the ID of the item. /// </summary> [JsonPropertyName("id")] public int Id { get; init; } }
21.538462
45
0.589286
[ "MIT" ]
blizzard-net/warcraft-classic
src/ArgentPonyWarcraftClassicClient/Models/GameDataApi/Item/ItemMedia.cs
562
C#
namespace dotless.Core.Parser.Functions { using Infrastructure.Nodes; using Tree; class BlueFunction : ColorFunctionBase { protected override Node Eval(Color color) { return new Number(color.B); } protected override Node EditColor(Color color, Number number) { var value = number.Value; if (number.Unit == "%") value = (value*255)/100d; return new Color(color.R, color.G, color.B + value); } } }
23.130435
69
0.554511
[ "MIT" ]
Zocdoc/cassette
src/Cassette.Less/dotless/Core/Parser/Functions/BlueFunction.cs
534
C#
using System; namespace TextFilter { class TextFilter { public static void Main() { var bannedWords = Console.ReadLine() .Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries); var text = Console.ReadLine(); foreach (var word in bannedWords) { text = text.Replace(word, new string('*', word.Length)); } Console.WriteLine(text); } } }
24.6
87
0.506098
[ "MIT" ]
hristokrastev/MasteringC
StringProc_Exercises/TextFilter/TextFilter/TextFilter.cs
494
C#
using System; namespace Neuz.DevKit.Extensions { public static partial class DateTimeExt { /// <summary> /// 获取月的开始 DateTime (year-month-day 00:00:00.000) /// </summary> /// <param name="this"></param> /// <returns></returns> /// <exception cref="ArgumentOutOfRangeException"></exception> /// <example> /// <code> /// <![CDATA[ /// var dt = new DateTime(2019, 4, 12, 1, 2, 3); /// var rs = dt.StartOfMonth(); // 2019-04-01 00:00:00.000 /// ]]> /// </code> /// </example> public static DateTime StartOfMonth(this DateTime @this) { return new DateTime(@this.Year, @this.Month, 1); } } }
29.769231
70
0.48708
[ "MIT" ]
Neuz/DevKit
src/Extensions/Neuz.DevKit.Extensions/DateTimeExt/StartOfMonth.cs
788
C#
// Copyright © 2016-2017 NoID Developers. All rights reserved. // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. using System; using System.Configuration; using System.Collections.Generic; using Hl7.Fhir.Model; using NoID.Security; using NoID.Utilities; using NoID.Network.Transport; using NoID.FHIR.Profile; using NoID.Database.Wrappers; namespace NoID.Network.Client.Test { class Program { private static readonly string PatentCheckinUri = ConfigurationManager.AppSettings["PatentCheckinUri"].ToString(); private static readonly string PendingPatientsUri = ConfigurationManager.AppSettings["PendingPatientsUri"].ToString(); private static readonly string SearchBiometricsUri = ConfigurationManager.AppSettings["SearchBiometricsUri"].ToString(); private static readonly string NoIDServiceName = ConfigurationManager.AppSettings["NoIDServiceName"].ToString(); private static readonly string NoIDMongoDBAddress = ConfigurationManager.AppSettings["NoIDMongoDBAddress"].ToString(); private static readonly string SparkMongoDBAddress = ConfigurationManager.AppSettings["SparkMongoDBAddress"].ToString(); static void Main(string[] args) { string commandLine = ""; Console.WriteLine("Enter C for checkin patient, P for pending patient queue, M for Mongo tests, F for fingerprint identity and Q to quit"); while (commandLine != "q") { if (commandLine == "c") { // call PatentCheckinUri Console.WriteLine("Sending test patient FHIR message."); Patient testPt = TestPatient(); SendJSON(testPt); Console.WriteLine("Sending FHIR message from file."); Patient readPt = ReadPatient(@"C:\JSONTest\sample-new-patient.json"); SendJSON(readPt); } else if (commandLine == "p") //send profiles { // call PendingPatientsUri IList<PatientProfile> patientProfiles = GetCheckinList(); Console.WriteLine("Patient profiles received."); } else if (commandLine == "m") // MongoDB tests { MongoDBWrapper dbwrapper = new MongoDBWrapper(NoIDMongoDBAddress, SparkMongoDBAddress); SessionQueue seq = new SessionQueue(); seq._id = Guid.NewGuid().ToString(); seq.ClinicArea = "Test Clinic"; seq.LocalReference = "123456"; seq.SparkReference = "spark5"; seq.ApprovalStatus = "pending"; seq.PatientStatus = "new"; seq.RemoteHubReference = "rem440403"; seq.SessionComputerName = "Prototype Computer 1"; seq.SubmitDate = DateTime.UtcNow.AddMinutes(-15); seq.PatientBeginDate = DateTime.UtcNow.AddMinutes(-19); Console.WriteLine(seq.Serialize()); dbwrapper.AddPendingPatient(seq); List<SessionQueue> PendingPatients = dbwrapper.GetPendingPatients(); dbwrapper.UpdateSessionQueueRecord(seq._id, "approved", "TestUser", "TestComputer"); } else if (commandLine == "f") // test fingerprint identity web service { Media readMedia = ReadMedia(@"C:\JSONTest\sample-media-fhir-message.json"); SendJSON(readMedia); } string previousCommand = commandLine; commandLine = Console.ReadLine(); if (commandLine.Length > 0) { commandLine = commandLine.ToLower().Substring(0, 1); } else { commandLine = previousCommand; } } } private static Resource ReadJSONFile(string filePath) { return FHIRUtilities.FileToResource(filePath); } private static Patient ReadPatient(string filePath) { return (Patient)ReadJSONFile(filePath); } private static Media ReadMedia(string filePath) { return (Media)ReadJSONFile(filePath); } private static Patient TestPatient() { Patient testPatient = FHIRUtilities.CreateTestFHIRPatientProfile ( "Test NoID Org", Guid.NewGuid().ToString(), "", "English", "1961-04-22", "F", "No", "Donna", "Marie", "Kasick", "4712 W 3rd St.", "Apt 35", "New York", "NY", "10000-2221", "212-555-3000", "212-555-7400", "212-555-9555", "donnakasick@yandex.com" ); return testPatient; } private static void SendJSON(Patient payload) { Authentication auth = SecurityUtilities.GetAuthentication(NoIDServiceName); Uri endpoint = new Uri(PatentCheckinUri); HttpsClient client = new HttpsClient(); client.SendFHIRPatientProfile(endpoint, auth, payload); Console.WriteLine(client.ResponseText); } private static void SendJSON(Media payload) { Authentication auth = SecurityUtilities.GetAuthentication(NoIDServiceName); Uri endpoint = new Uri(SearchBiometricsUri); HttpsClient client = new HttpsClient(); client.SendFHIRMediaProfile(endpoint, auth, payload); Console.WriteLine(client.ResponseText); } private static IList<PatientProfile> GetCheckinList() { IList<PatientProfile> PatientProfiles = null; Authentication auth = SecurityUtilities.GetAuthentication(NoIDServiceName); Uri endpoint = new Uri(PendingPatientsUri); HttpsClient client = new HttpsClient(); PatientProfiles = client.RequestPendingQueue(endpoint, auth); Console.WriteLine(client.ResponseText); return PatientProfiles; } /* // Example using Google protobuf private static void SendProtoBuffer() { PatientFHIRProfile payload = CreatePatientFHIRProfile(); Authentication auth = SecurityUtilities.GetAuthentication(NoIDServiceName); Uri endpoint = new Uri(FHIREndPoint); WebSend ws = new WebSend(endpoint, auth, payload); Console.WriteLine(ws.PostHttpWebRequest()); } private static PatientFHIRProfile CreatePatientFHIRProfile() { PatientFHIRProfile pt = new PatientFHIRProfile("Test Org", new Uri(FHIREndPoint)); pt.LastName = "Williams"; pt.FirstName = "Brianna"; pt.MiddleName = "E."; pt.BirthDate = "20030514"; pt.Gender = AdministrativeGender.Female.ToString().Substring(0,1).ToUpper(); pt.EmailAddress = "Test@gtest.com"; pt.StreetAddress = "321 Easy St"; pt.StreetAddress2 = "Unit 4A"; pt.City = "New Orleans"; pt.State = "LA"; pt.PostalCode = "70112-2110"; pt.PhoneCell = "15045551212"; pt.PhoneHome = "12125551212"; return pt; } */ } }
43.97093
151
0.584424
[ "MIT" ]
HarmonIQ/noid
source/noid.network.client.test/Program.cs
7,566
C#
#nullable enable using System.Threading.Tasks; using Content.Shared.Construction; using JetBrains.Annotations; using Robust.Server.GameObjects; using Robust.Shared.Interfaces.GameObjects; using Robust.Shared.Serialization; using Robust.Shared.Utility; namespace Content.Server.Construction.Completions { [UsedImplicitly] public class SpriteChange : IGraphAction { public void ExposeData(ObjectSerializer serializer) { serializer.DataField(this, x => x.SpriteSpecifier, "specifier", SpriteSpecifier.Invalid); serializer.DataField(this, x => x.Layer, "layer", 0); } public int Layer { get; private set; } = 0; public SpriteSpecifier? SpriteSpecifier { get; private set; } = SpriteSpecifier.Invalid; public async Task PerformAction(IEntity entity, IEntity? user) { if (entity.Deleted || SpriteSpecifier == null || SpriteSpecifier == SpriteSpecifier.Invalid) return; if (!entity.TryGetComponent(out SpriteComponent? sprite)) return; sprite.LayerSetSprite(Layer, SpriteSpecifier); } } }
33.176471
112
0.693262
[ "MIT" ]
BlindfoldedHuman/space-station-14
Content.Server/Construction/Completions/SpriteChange.cs
1,130
C#
//------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // 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. // //------------------------------------------------------------------------------ [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Microsoft.IdentityModel.KeyVaultExtensions, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
62.137931
440
0.739734
[ "MIT" ]
amccool/azure-activedirectory-identitymodel-extensions-for-dotnet
src/Microsoft.IdentityModel.Tokens/InternalsVisibleTo.cs
1,804
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PatrolActionManager : SSActionManager { private GoPatrolAction go_patrol; //巡逻兵巡逻 public void GoPatrol(GameObject patrol) { go_patrol = GoPatrolAction.GetSSAction(patrol.transform.position); this.RunAction(patrol, go_patrol, this); } //停止所有动作 public void DestroyAllAction() { DestroyAll(); } public override void SSActionEvent(SSAction source, int intParam = 0, GameObject objectParam = null) { if(intParam == 0) { //侦查兵跟随玩家 PatrolFollowAction follow = PatrolFollowAction.GetSSAction(objectParam.gameObject.GetComponent<PatrolData>().player); this.RunAction(objectParam, follow, this); } else if (intParam == 1) { //侦察兵按照初始位置开始继续巡逻 GoPatrolAction move = GoPatrolAction.GetSSAction(objectParam.gameObject.GetComponent<PatrolData>().start_position); this.RunAction(objectParam, move, this); //玩家逃脱 Singleton<GameEventManager>.Instance.PlayerEscape(); } else { } } }
29.97561
129
0.62083
[ "Apache-2.0" ]
jiushiwola/unity-3D
hw7/Assets/Scripts/PatrolActionManager.cs
1,305
C#
/* Written by Peter O. in 2013. Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ If you like this, you should donate to Peter O. at: http://peteroupc.github.io/ */ using System; namespace PeterO.Numbers { // <summary>Implements the simplified arithmetic in Appendix A of the // General Decimal Arithmetic Specification. Unfortunately, it doesn't // pass all the test cases, since some aspects of the spec are left // open. For example: in which cases is the Clamped flag set? The test // cases set the Clamped flag in only a handful of test cases, all // within the <c>exp</c> operation.</summary> // <typeparam name='T'>Data type for a numeric value in a particular // radix.</typeparam> internal sealed class SimpleRadixMath<T> : IRadixMath<T> { private readonly IRadixMath<T> wrapper; public SimpleRadixMath(IRadixMath<T> wrapper) { this.wrapper = wrapper; } private static EContext GetContextWithFlags(EContext ctx) { return (ctx == null) ? ctx : ctx.WithBlankFlags(); } private T SignalInvalid(EContext ctx) { if (this.GetHelper().GetArithmeticSupport() == BigNumberFlags.FiniteOnly) { throw new ArithmeticException("Invalid operation"); } if (ctx != null && ctx.HasFlags) { ctx.Flags |= EContext.FlagInvalid; } return this.GetHelper().CreateNewWithFlags( EInteger.Zero, EInteger.Zero, BigNumberFlags.FlagQuietNaN); } private T PostProcess( T thisValue, EContext ctxDest, EContext ctxSrc) { return this.PostProcessEx(thisValue, ctxDest, ctxSrc, false, false); } private T PostProcessAfterDivision( T thisValue, EContext ctxDest, EContext ctxSrc) { return this.PostProcessEx(thisValue, ctxDest, ctxSrc, true, false); } private T PostProcessAfterQuantize( T thisValue, EContext ctxDest, EContext ctxSrc) { return this.PostProcessEx(thisValue, ctxDest, ctxSrc, false, true); } private T PostProcessEx( T thisValue, EContext ctxDest, EContext ctxSrc, bool afterDivision, bool afterQuantize) { int thisFlags = this.GetHelper().GetFlags(thisValue); if (ctxDest != null && ctxSrc != null) { if (ctxDest.HasFlags) { if (!ctxSrc.ClampNormalExponents) { ctxSrc.Flags &= ~EContext.FlagClamped; } ctxDest.Flags |= ctxSrc.Flags; if ((ctxSrc.Flags & EContext.FlagSubnormal) != 0) { // Treat subnormal numbers as underflows ctxDest.Flags |= BigNumberFlags.UnderflowFlags; } } } if ((thisFlags & BigNumberFlags.FlagSpecial) != 0) { return (ctxDest.Flags == 0) ? this.SignalInvalid(ctxDest) : thisValue; } EInteger mant = this.GetHelper().GetMantissa(thisValue).Abs(); if (mant.IsZero) { return afterQuantize ? this.GetHelper().CreateNewWithFlags( mant, this.GetHelper().GetExponent(thisValue), 0) : this.wrapper.RoundToPrecision( this.GetHelper().ValueOf(0), ctxDest); } if (afterQuantize) { return thisValue; } EInteger exp = this.GetHelper().GetExponent(thisValue); if (exp.Sign > 0) { FastInteger fastExp = FastInteger.FromBig(exp); if (ctxDest == null || !ctxDest.HasMaxPrecision) { mant = this.GetHelper().MultiplyByRadixPower(mant, fastExp); return this.GetHelper().CreateNewWithFlags( mant, EInteger.Zero, thisFlags); } if (!ctxDest.ExponentWithinRange(exp)) { return thisValue; } FastInteger prec = FastInteger.FromBig(ctxDest.Precision); FastInteger digits = this.GetHelper().CreateShiftAccumulator(mant).GetDigitLength(); prec.Subtract(digits); if (prec.Sign > 0 && prec.CompareTo(fastExp) >= 0) { mant = this.GetHelper().MultiplyByRadixPower(mant, fastExp); return this.GetHelper().CreateNewWithFlags( mant, EInteger.Zero, thisFlags); } if (afterDivision) { int radix = this.GetHelper().GetRadix(); mant = NumberUtility.ReduceTrailingZeros( mant, fastExp, radix, null, null, null); thisValue = this.GetHelper().CreateNewWithFlags( mant, fastExp.AsEInteger(), thisFlags); } } else if (afterDivision && exp.Sign < 0) { FastInteger fastExp = FastInteger.FromBig(exp); int radix = this.GetHelper().GetRadix(); mant = NumberUtility.ReduceTrailingZeros( mant, fastExp, radix, null, null, new FastInteger(0)); thisValue = this.GetHelper().CreateNewWithFlags( mant, fastExp.AsEInteger(), thisFlags); } return thisValue; } private T ReturnQuietNaN(T thisValue, EContext ctx) { EInteger mant = this.GetHelper().GetMantissa(thisValue).Abs(); var mantChanged = false; if (!mant.IsZero && ctx != null && ctx.HasMaxPrecision) { EInteger limit = this.GetHelper().MultiplyByRadixPower( EInteger.One, FastInteger.FromBig(ctx.Precision)); if (mant.CompareTo(limit) >= 0) { mant %= (EInteger)limit; mantChanged = true; } } int flags = this.GetHelper().GetFlags(thisValue); if (!mantChanged && (flags & BigNumberFlags.FlagQuietNaN) != 0) { return thisValue; } flags &= BigNumberFlags.FlagNegative; flags |= BigNumberFlags.FlagQuietNaN; return this.GetHelper().CreateNewWithFlags(mant, EInteger.Zero, flags); } private T HandleNotANumber(T thisValue, T other, EContext ctx) { int thisFlags = this.GetHelper().GetFlags(thisValue); int otherFlags = this.GetHelper().GetFlags(other); // Check this value then the other value for signaling NaN if ((thisFlags & BigNumberFlags.FlagSignalingNaN) != 0) { return this.SignalingNaNInvalid(thisValue, ctx); } if ((otherFlags & BigNumberFlags.FlagSignalingNaN) != 0) { return this.SignalingNaNInvalid(other, ctx); } // Check this value then the other value for quiet NaN return ((thisFlags & BigNumberFlags.FlagQuietNaN) != 0) ? this.ReturnQuietNaN(thisValue, ctx) : (((otherFlags & BigNumberFlags.FlagQuietNaN) != 0) ? this.ReturnQuietNaN( other, ctx) : default(T)); } private T CheckNotANumber3( T thisValue, T other, T other2, EContext ctx) { int thisFlags = this.GetHelper().GetFlags(thisValue); int otherFlags = this.GetHelper().GetFlags(other); int other2Flags = this.GetHelper().GetFlags(other2); // Check this value then the other value for signaling NaN if ((thisFlags & BigNumberFlags.FlagSignalingNaN) != 0) { return this.SignalingNaNInvalid(thisValue, ctx); } if ((otherFlags & BigNumberFlags.FlagSignalingNaN) != 0) { return this.SignalingNaNInvalid(other, ctx); } if ((other2Flags & BigNumberFlags.FlagSignalingNaN) != 0) { return this.SignalingNaNInvalid(other, ctx); } // Check this value then the other value for quiet NaN return ((thisFlags & BigNumberFlags.FlagQuietNaN) != 0) ? this.ReturnQuietNaN(thisValue, ctx) : (((otherFlags & BigNumberFlags.FlagQuietNaN) != 0) ? this.ReturnQuietNaN( other, ctx) : (((other2Flags & BigNumberFlags.FlagQuietNaN) != 0) ? this.ReturnQuietNaN(other, ctx) : default(T))); } private T SignalingNaNInvalid(T value, EContext ctx) { if (ctx != null && ctx.HasFlags) { ctx.Flags |= EContext.FlagInvalid; } return this.ReturnQuietNaN(value, ctx); } private T CheckNotANumber1(T val, EContext ctx) { return this.HandleNotANumber(val, val, ctx); } private T CheckNotANumber2(T val, T val2, EContext ctx) { return this.HandleNotANumber(val, val2, ctx); } private T RoundBeforeOp(T val, EContext ctx) { if (ctx == null || !ctx.HasMaxPrecision) { return val; } int thisFlags = this.GetHelper().GetFlags(val); if ((thisFlags & BigNumberFlags.FlagSpecial) != 0) { return val; } FastInteger fastPrecision = FastInteger.FromBig(ctx.Precision); EInteger mant = this.GetHelper().GetMantissa(val).Abs(); FastInteger digits = this.GetHelper().CreateShiftAccumulator(mant).GetDigitLength(); EContext ctx2 = ctx.WithBlankFlags().WithTraps(0); if (digits.CompareTo(fastPrecision) <= 0) { // Rounding is only to be done if the digit count is // too big (distinguishing this case is material // if the value also has an exponent that's out of range) return val; } val = this.wrapper.RoundToPrecision(val, ctx2); // the only time rounding can signal an invalid // operation is if an operand is signaling NaN, but // this was already checked beforehand #if DEBUG if ((ctx2.Flags & EContext.FlagInvalid) != 0) { throw new ArgumentException("doesn't satisfy (ctx2.Flags&FlagInvalid)==0"); } #endif if ((ctx2.Flags & EContext.FlagInexact) != 0) { if (ctx.HasFlags) { ctx.Flags |= BigNumberFlags.LostDigitsFlags; } } if ((ctx2.Flags & EContext.FlagRounded) != 0) { if (ctx.HasFlags) { ctx.Flags |= EContext.FlagRounded; } } if ((ctx2.Flags & EContext.FlagSubnormal) != 0) { // Console.WriteLine("Subnormal input: " + val); } if ((ctx2.Flags & EContext.FlagUnderflow) != 0) { // Console.WriteLine("Underflow"); } if ((ctx2.Flags & EContext.FlagOverflow) != 0) { bool neg = (thisFlags & BigNumberFlags.FlagNegative) != 0; ctx.Flags |= EContext.FlagLostDigits; return this.SignalOverflow2(ctx, neg); } return val; } public T DivideToIntegerNaturalScale( T thisValue, T divisor, EContext ctx) { T ret = this.CheckNotANumber2(thisValue, divisor, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); thisValue = this.RoundBeforeOp(thisValue, ctx2); divisor = this.RoundBeforeOp(divisor, ctx2); thisValue = this.wrapper.DivideToIntegerNaturalScale( thisValue, divisor, ctx2); return this.PostProcessAfterDivision(thisValue, ctx, ctx2); } public T DivideToIntegerZeroScale( T thisValue, T divisor, EContext ctx) { T ret = this.CheckNotANumber2(thisValue, divisor, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); thisValue = this.RoundBeforeOp(thisValue, ctx2); divisor = this.RoundBeforeOp(divisor, ctx2); thisValue = this.wrapper.DivideToIntegerZeroScale( thisValue, divisor, ctx2); return this.PostProcessAfterDivision(thisValue, ctx, ctx2); } public T Abs(T value, EContext ctx) { T ret = this.CheckNotANumber1(value, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); value = this.RoundBeforeOp(value, ctx2); value = this.wrapper.Abs(value, ctx2); return this.PostProcess(value, ctx, ctx2); } public T Negate(T value, EContext ctx) { T ret = this.CheckNotANumber1(value, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); value = this.RoundBeforeOp(value, ctx2); value = this.wrapper.Negate(value, ctx2); return this.PostProcess(value, ctx, ctx2); } // <summary>Finds the remainder that results when dividing two T // objects.</summary> // <param name='thisValue'></param> // <summary>Finds the remainder that results when dividing two T // objects.</summary> // <param name='thisValue'></param> // <param name='divisor'></param> // <param name='ctx'> (3).</param> // <returns>The remainder of the two objects.</returns> public T Remainder( T thisValue, T divisor, EContext ctx, bool roundAfterDivide) { T ret = this.CheckNotANumber2(thisValue, divisor, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); thisValue = this.RoundBeforeOp(thisValue, ctx2); divisor = this.RoundBeforeOp(divisor, ctx2); thisValue = this.wrapper.Remainder( thisValue, divisor, ctx2, roundAfterDivide); return this.PostProcess(thisValue, ctx, ctx2); } public T RemainderNear(T thisValue, T divisor, EContext ctx) { T ret = this.CheckNotANumber2(thisValue, divisor, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); thisValue = this.RoundBeforeOp(thisValue, ctx2); divisor = this.RoundBeforeOp(divisor, ctx2); thisValue = this.wrapper.RemainderNear(thisValue, divisor, ctx2); return this.PostProcess(thisValue, ctx, ctx2); } public T Pi(EContext ctx) { return this.wrapper.Pi(ctx); } private T SignalOverflow2(EContext pc, bool neg) { if (pc != null) { ERounding roundingOnOverflow = pc.Rounding; if (pc.HasFlags) { pc.Flags |= EContext.FlagOverflow | EContext.FlagInexact | EContext.FlagRounded; } if (pc.HasMaxPrecision && pc.HasExponentRange && (roundingOnOverflow == ERounding.Down || roundingOnOverflow == ERounding.ZeroFiveUp || (roundingOnOverflow == ERounding.OddOrZeroFiveUp) || (roundingOnOverflow == ERounding.Odd) || (roundingOnOverflow == ERounding.Ceiling && neg) || (roundingOnOverflow == ERounding.Floor && !neg))) { // Set to the highest possible value for // the given precision EInteger overflowMant = EInteger.Zero; FastInteger fastPrecision = FastInteger.FromBig(pc.Precision); overflowMant = this.GetHelper().MultiplyByRadixPower( EInteger.One, fastPrecision); overflowMant -= EInteger.One; FastInteger clamp = FastInteger.FromBig(pc.EMax).Increment().Subtract(fastPrecision); return this.GetHelper().CreateNewWithFlags( overflowMant, clamp.AsEInteger(), neg ? BigNumberFlags.FlagNegative : 0); } } return this.GetHelper().GetArithmeticSupport() == BigNumberFlags.FiniteOnly ? default(T) : this.GetHelper().CreateNewWithFlags( EInteger.Zero, EInteger.Zero, (neg ? BigNumberFlags.FlagNegative : 0) | BigNumberFlags.FlagInfinity); } public T Power(T thisValue, T pow, EContext ctx) { T ret = this.CheckNotANumber2(thisValue, pow, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); // Console.WriteLine("op was " + thisValue + ", "+pow); thisValue = this.RoundBeforeOp(thisValue, ctx2); pow = this.RoundBeforeOp(pow, ctx2); // Console.WriteLine("op now " + thisValue + ", "+pow); int powSign = this.GetHelper().GetSign(pow); thisValue = (powSign == 0 && this.GetHelper().GetSign(thisValue) == 0) ? this.wrapper.RoundToPrecision(this.GetHelper().ValueOf(1), ctx2) : this.wrapper.Power(thisValue, pow, ctx2); // Console.WriteLine("was " + thisValue); thisValue = this.PostProcessAfterDivision(thisValue, ctx, ctx2); // Console.WriteLine("result was " + thisValue); // Console.WriteLine("now " + thisValue); return thisValue; } public T Log10(T thisValue, EContext ctx) { T ret = this.CheckNotANumber1(thisValue, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); thisValue = this.RoundBeforeOp(thisValue, ctx2); thisValue = this.wrapper.Log10(thisValue, ctx2); return this.PostProcess(thisValue, ctx, ctx2); } public T Ln(T thisValue, EContext ctx) { T ret = this.CheckNotANumber1(thisValue, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); // Console.WriteLine("was: " + thisValue); thisValue = this.RoundBeforeOp(thisValue, ctx2); // Console.WriteLine("now: " + thisValue); thisValue = this.wrapper.Ln(thisValue, ctx2); // Console.WriteLine("result: " + thisValue); return this.PostProcess(thisValue, ctx, ctx2); } public IRadixMathHelper<T> GetHelper() { return this.wrapper.GetHelper(); } public T Exp(T thisValue, EContext ctx) { T ret = this.CheckNotANumber1(thisValue, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); thisValue = this.RoundBeforeOp(thisValue, ctx2); thisValue = this.wrapper.Exp(thisValue, ctx2); return this.PostProcess(thisValue, ctx, ctx2); } public T SquareRoot(T thisValue, EContext ctx) { T ret = this.CheckNotANumber1(thisValue, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); // Console.WriteLine("op was " + thisValue); thisValue = this.RoundBeforeOp(thisValue, ctx2); // Console.WriteLine("op now " + thisValue); thisValue = this.wrapper.SquareRoot(thisValue, ctx2); // Console.WriteLine("result was " + thisValue); return this.PostProcess(thisValue, ctx, ctx2); } public T NextMinus(T thisValue, EContext ctx) { T ret = this.CheckNotANumber1(thisValue, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); thisValue = this.RoundBeforeOp(thisValue, ctx2); thisValue = this.wrapper.NextMinus(thisValue, ctx2); return this.PostProcess(thisValue, ctx, ctx2); } public T NextToward(T thisValue, T otherValue, EContext ctx) { T ret = this.CheckNotANumber2(thisValue, otherValue, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); thisValue = this.RoundBeforeOp(thisValue, ctx2); otherValue = this.RoundBeforeOp(otherValue, ctx2); thisValue = this.wrapper.NextToward(thisValue, otherValue, ctx2); return this.PostProcess(thisValue, ctx, ctx2); } public T NextPlus(T thisValue, EContext ctx) { T ret = this.CheckNotANumber1(thisValue, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); thisValue = this.RoundBeforeOp(thisValue, ctx2); thisValue = this.wrapper.NextPlus(thisValue, ctx2); return this.PostProcess(thisValue, ctx, ctx2); } public T DivideToExponent( T thisValue, T divisor, EInteger desiredExponent, EContext ctx) { T ret = this.CheckNotANumber2(thisValue, divisor, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); thisValue = this.RoundBeforeOp(thisValue, ctx2); divisor = this.RoundBeforeOp(divisor, ctx2); thisValue = this.wrapper.DivideToExponent( thisValue, divisor, desiredExponent, ctx2); return this.PostProcessAfterDivision(thisValue, ctx, ctx2); } // <summary>Divides two T objects.</summary> // <param name='thisValue'></param> // <summary>Divides two T objects.</summary> // <param name='thisValue'></param> // <param name='divisor'></param> // <param name='ctx'> (3).</param> // <returns>The quotient of the two objects.</returns> public T Divide(T thisValue, T divisor, EContext ctx) { T ret = this.CheckNotANumber2(thisValue, divisor, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); thisValue = this.RoundBeforeOp(thisValue, ctx2); divisor = this.RoundBeforeOp(divisor, ctx2); thisValue = this.wrapper.Divide(thisValue, divisor, ctx2); return this.PostProcessAfterDivision(thisValue, ctx, ctx2); } public T MinMagnitude(T a, T b, EContext ctx) { T ret = this.CheckNotANumber2(a, b, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); a = this.RoundBeforeOp(a, ctx2); b = this.RoundBeforeOp(b, ctx2); a = this.wrapper.MinMagnitude(a, b, ctx2); return this.PostProcess(a, ctx, ctx2); } public T MaxMagnitude(T a, T b, EContext ctx) { T ret = this.CheckNotANumber2(a, b, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); a = this.RoundBeforeOp(a, ctx2); b = this.RoundBeforeOp(b, ctx2); a = this.wrapper.MaxMagnitude(a, b, ctx2); return this.PostProcess(a, ctx, ctx2); } public T Max(T a, T b, EContext ctx) { T ret = this.CheckNotANumber2(a, b, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); a = this.RoundBeforeOp(a, ctx2); b = this.RoundBeforeOp(b, ctx2); // choose the left operand if both are equal a = (this.CompareTo(a, b) >= 0) ? a : b; return this.PostProcess(a, ctx, ctx2); } public T Min(T a, T b, EContext ctx) { T ret = this.CheckNotANumber2(a, b, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); a = this.RoundBeforeOp(a, ctx2); b = this.RoundBeforeOp(b, ctx2); // choose the left operand if both are equal a = (this.CompareTo(a, b) <= 0) ? a : b; return this.PostProcess(a, ctx, ctx2); } // <summary>Multiplies two T objects.</summary> // <param name='thisValue'></param> // <summary>Multiplies two T objects.</summary> // <param name='thisValue'></param> // <param name='other'></param> // <param name='ctx'> (3).</param> // <returns>The product of the two objects.</returns> public T Multiply(T thisValue, T other, EContext ctx) { T ret = this.CheckNotANumber2(thisValue, other, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); thisValue = this.RoundBeforeOp(thisValue, ctx2); other = this.RoundBeforeOp(other, ctx2); thisValue = this.wrapper.Multiply(thisValue, other, ctx2); return this.PostProcess(thisValue, ctx, ctx2); } public T MultiplyAndAdd( T thisValue, T multiplicand, T augend, EContext ctx) { T ret = this.CheckNotANumber3(thisValue, multiplicand, augend, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); thisValue = this.RoundBeforeOp(thisValue, ctx2); multiplicand = this.RoundBeforeOp(multiplicand, ctx2); augend = this.RoundBeforeOp(augend, ctx2); // the only time the first operand to the addition can be // 0 is if either thisValue rounded or multiplicand // rounded is 0 bool zeroA = this.GetHelper().GetSign(thisValue) == 0 || this.GetHelper().GetSign(multiplicand) == 0; bool zeroB = this.GetHelper().GetSign(augend) == 0; if (zeroA) { thisValue = zeroB ? this.wrapper.RoundToPrecision(this.GetHelper().ValueOf(0), ctx2) : augend; thisValue = this.RoundToPrecision(thisValue, ctx2); } else { thisValue = !zeroB ? this.wrapper.MultiplyAndAdd( thisValue, multiplicand, augend, ctx2) : this.wrapper.Multiply(thisValue, multiplicand, ctx2); } return this.PostProcess(thisValue, ctx, ctx2); } public T Plus(T thisValue, EContext ctx) { T ret = this.CheckNotANumber1(thisValue, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); thisValue = this.RoundBeforeOp(thisValue, ctx2); thisValue = this.wrapper.Plus(thisValue, ctx2); return this.PostProcess(thisValue, ctx, ctx2); } public T RoundToPrecision(T thisValue, EContext ctx) { T ret = this.CheckNotANumber1(thisValue, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); thisValue = this.RoundBeforeOp(thisValue, ctx2); thisValue = this.wrapper.RoundToPrecision(thisValue, ctx2); return this.PostProcess(thisValue, ctx, ctx2); } public T Quantize(T thisValue, T otherValue, EContext ctx) { T ret = this.CheckNotANumber1(thisValue, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); // Console.WriteLine("was: "+thisValue+", "+otherValue); thisValue = this.RoundBeforeOp(thisValue, ctx2); // Console.WriteLine("now: "+thisValue+", "+otherValue); otherValue = this.RoundBeforeOp(otherValue, ctx2); // Apparently, subnormal values of "otherValue" raise // an invalid operation flag, according to the test cases EContext ctx3 = ctx2 == null ? null : ctx2.WithBlankFlags(); this.wrapper.RoundToPrecision(otherValue, ctx3); if (ctx3 != null && (ctx3.Flags & EContext.FlagSubnormal) != 0) { return this.SignalInvalid(ctx); } thisValue = this.wrapper.Quantize(thisValue, otherValue, ctx2); // Console.WriteLine("result: "+thisValue); return this.PostProcessAfterQuantize(thisValue, ctx, ctx2); } public T RoundToExponentExact( T thisValue, EInteger expOther, EContext ctx) { T ret = this.CheckNotANumber1(thisValue, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); thisValue = this.RoundBeforeOp(thisValue, ctx2); thisValue = this.wrapper.RoundToExponentExact(thisValue, expOther, ctx); return this.PostProcessAfterQuantize(thisValue, ctx, ctx2); } public T RoundToExponentSimple( T thisValue, EInteger expOther, EContext ctx) { T ret = this.CheckNotANumber1(thisValue, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); thisValue = this.RoundBeforeOp(thisValue, ctx2); thisValue = this.wrapper.RoundToExponentSimple(thisValue, expOther, ctx2); return this.PostProcessAfterQuantize(thisValue, ctx, ctx2); } public T RoundToExponentNoRoundedFlag( T thisValue, EInteger exponent, EContext ctx) { T ret = this.CheckNotANumber1(thisValue, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); thisValue = this.RoundBeforeOp(thisValue, ctx2); thisValue = this.wrapper.RoundToExponentNoRoundedFlag( thisValue, exponent, ctx); return this.PostProcessAfterQuantize(thisValue, ctx, ctx2); } public T Reduce(T thisValue, EContext ctx) { T ret = this.CheckNotANumber1(thisValue, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); thisValue = this.RoundBeforeOp(thisValue, ctx2); thisValue = this.wrapper.Reduce(thisValue, ctx); return this.PostProcessAfterQuantize(thisValue, ctx, ctx2); } public T Add(T thisValue, T other, EContext ctx) { T ret = this.CheckNotANumber2(thisValue, other, ctx); if ((object)ret != (object)default(T)) { return ret; } EContext ctx2 = GetContextWithFlags(ctx); thisValue = this.RoundBeforeOp(thisValue, ctx2); other = this.RoundBeforeOp(other, ctx2); bool zeroA = this.GetHelper().GetSign(thisValue) == 0; bool zeroB = this.GetHelper().GetSign(other) == 0; if (zeroA) { thisValue = zeroB ? this.wrapper.RoundToPrecision(this.GetHelper().ValueOf(0), ctx2) : other; thisValue = this.RoundToPrecision(thisValue, ctx2); } else { thisValue = (!zeroB) ? this.wrapper.AddEx( thisValue, other, ctx2, true) : this.RoundToPrecision(thisValue, ctx2); } return this.PostProcess(thisValue, ctx, ctx2); } public T AddEx( T thisValue, T other, EContext ctx, bool roundToOperandPrecision) { // NOTE: Ignores roundToOperandPrecision return this.Add(thisValue, other, ctx); } // <summary>Compares a T object with this instance.</summary> // <param name='thisValue'></param> // <param name='otherValue'>A T object.</param> // <param name='treatQuietNansAsSignaling'>A Boolean object.</param> // <param name='ctx'>A PrecisionContext object.</param> // <returns>Zero if the values are equal; a negative number if this // instance is less, or a positive number if this instance is // greater.</returns> public T CompareToWithContext( T thisValue, T otherValue, bool treatQuietNansAsSignaling, EContext ctx) { T ret = this.CheckNotANumber2(thisValue, otherValue, ctx); if ((object)ret != (object)default(T)) { return ret; } thisValue = this.RoundBeforeOp(thisValue, ctx); otherValue = this.RoundBeforeOp(otherValue, ctx); return this.wrapper.CompareToWithContext( thisValue, otherValue, treatQuietNansAsSignaling, ctx); } // <summary>Compares a T object with this instance.</summary> // <param name='thisValue'></param> // <returns>Zero if the values are equal; a negative number if this // instance is less, or a positive number if this instance is // greater.</returns> public int CompareTo(T thisValue, T otherValue) { return this.wrapper.CompareTo(thisValue, otherValue); } public T RoundAfterConversion(T thisValue, EContext ctx) { T ret = this.CheckNotANumber1(thisValue, ctx); if ((object)ret != (object)default(T)) { return ret; } if (this.GetHelper().GetSign(thisValue) == 0) { return this.wrapper.RoundToPrecision(this.GetHelper().ValueOf(0), ctx); } EContext ctx2 = GetContextWithFlags(ctx); thisValue = this.wrapper.RoundToPrecision(thisValue, ctx2); return this.PostProcessAfterQuantize(thisValue, ctx, ctx2); } } }
36.576074
81
0.622253
[ "MIT" ]
gebogebogebo/WebAuthnModokiDesktop
Source/WebAuthnModokiDesktop/WebAuthnModokiDesktop/OSS/Numbers/SimpleRadixMath.cs
31,492
C#
// *** WARNING: this file was generated by crd2pulumi. *** // *** 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.Kubernetes.Types.Outputs.Argoproj.V1Alpha1 { [OutputType] public sealed class ApplicationStatusHistorySourceKsonnetParameters { public readonly string Component; public readonly string Name; public readonly string Value; [OutputConstructor] private ApplicationStatusHistorySourceKsonnetParameters( string component, string name, string value) { Component = component; Name = name; Value = value; } } }
25.058824
81
0.659624
[ "Apache-2.0" ]
pulumi/pulumi-kubernetes-crds
operators/argocd-operator/dotnet/Kubernetes/Crds/Operators/ArgocdOperator/Argoproj/V1Alpha1/Outputs/ApplicationStatusHistorySourceKsonnetParameters.cs
852
C#
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Jobs; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; namespace Benchmark { [SimpleJob(RuntimeMoniker.Net472), SimpleJob(RuntimeMoniker.NetCoreApp31), SimpleJob(RuntimeMoniker.Net60), MemoryDiagnoser] public class PoolBenchmarks // investigating #668/#669 { [Params(1, 5, 20)] public int Threads { get; set; } private const int TotalCount = 10000; [Benchmark(OperationsPerInvoke = TotalCount)] public Task Concurrent() { var arr = new Task[Threads]; int perThreadCount = TotalCount / Threads; Action work = InnerLoop; for (int i = 0; i < Threads; i++) { arr[i] = Task.Run(work); } return Task.WhenAll(arr); void InnerLoop() { for(int i = 0; i < perThreadCount; i++) { var obj = ConcurrentQueuePool<object>.TryGet() ?? new object(); ConcurrentQueuePool<object>.Put(obj); } } } [Benchmark(OperationsPerInvoke = TotalCount)] public Task Locked() { var arr = new Task[Threads]; int perThreadCount = TotalCount / Threads; Action work = InnerLoop; for (int i = 0; i < Threads; i++) { arr[i] = Task.Run(work); } return Task.WhenAll(arr); void InnerLoop() { for (int i = 0; i < perThreadCount; i++) { var obj = LockedQueuePool<object>.TryGet() ?? new object(); LockedQueuePool<object>.Put(obj); } } } internal static class ConcurrentQueuePool<T> where T : class { internal static T TryGet() => GetShared(); internal static void Put(T obj) { if (obj != null) PutShared(obj); } const int POOL_SIZE = 20; private static readonly ConcurrentQueue<T> s_pool = new ConcurrentQueue<T>(); private static T GetShared() { var pool = s_pool; return pool.TryDequeue(out var next) ? next : null; } private static void PutShared(T obj) { var pool = s_pool; // there is an inherent race here - we may occasionally go slightly over, // but that isn't itself a problem - limit is just to prevent explosion if (pool.Count < POOL_SIZE) pool.Enqueue(obj); } } internal static class LockedQueuePool<T> where T : class { internal static T TryGet() => GetShared(); internal static void Put(T obj) { if (obj != null) PutShared(obj); } const int POOL_SIZE = 20; private static readonly Queue<T> s_pool = new Queue<T>(POOL_SIZE); private static T GetShared() { var pool = s_pool; lock (pool) { return pool.Count == 0 ? null : pool.Dequeue(); } } private static void PutShared(T obj) { var pool = s_pool; lock (pool) { if (pool.Count < POOL_SIZE) pool.Enqueue(obj); } } } } }
31.444444
128
0.484914
[ "Apache-2.0" ]
mgravell/protobuf-net
src/Benchmark/PoolBenchmarks.cs
3,681
C#
using System; using System.Collections.Generic; using System.Text; namespace Animals { class Cat : Animal { public Cat(string name, int age, string gender) : base(name, age, gender) { } public override void ProduceSound() { Console.WriteLine("Meow meow"); } } }
18.666667
81
0.574405
[ "MIT" ]
Alexxx2207/CSharpOOP
Inheritance-ex/Animals/Cat.cs
338
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // InlinedAggregationOperatorEnumerator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Threading; namespace System.Linq.Parallel { //--------------------------------------------------------------------------------------- // Inlined aggregate operators for finding the min/max values for primitives (int, long, float, // double, decimal). Versions are also offered for the nullable primitives (int?, long?, float?, // double?, decimal?), which differ slightly in behavior: they return a null value for empty // streams, whereas the ordinary primitive versions throw. // //--------------------------------------------------------------------------------------- // Inlined average operators for primitives (int, long, float, double, decimal), and the // nullable variants. The difference between the normal and nullable variety is that // nulls are skipped in tallying the count and sum for the average. // /// <summary> /// A class with some shared implementation between all aggregation enumerators. /// </summary> /// <typeparam name="TIntermediate"></typeparam> internal abstract class InlinedAggregationOperatorEnumerator<TIntermediate> : QueryOperatorEnumerator<TIntermediate, int> { private int _partitionIndex; // This partition's unique index. private bool _done = false; protected CancellationToken _cancellationToken; //--------------------------------------------------------------------------------------- // Instantiates a new aggregation operator. // internal InlinedAggregationOperatorEnumerator(int partitionIndex, CancellationToken cancellationToken) { _partitionIndex = partitionIndex; _cancellationToken = cancellationToken; } //--------------------------------------------------------------------------------------- // Tallies up the sum of the underlying data source, walking the entire thing the first // time MoveNext is called on this object. There is a boilerplate variant used by callers, // and then one that is used for extensibility by subclasses. // internal sealed override bool MoveNext(ref TIntermediate currentElement, ref int currentKey) { if (!_done && MoveNextCore(ref currentElement)) { // A reduction's "index" is the same as its partition number. currentKey = _partitionIndex; _done = true; return true; } return false; } protected abstract bool MoveNextCore(ref TIntermediate currentElement); } }
44.220588
125
0.549717
[ "MIT" ]
690486439/corefx
src/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Inlined/InlinedAggregationOperatorEnumerator.cs
3,007
C#
using MXGP.Core.Contracts; using MXGP.IO; using MXGP.IO.Contracts; using System; namespace MXGP.Core { public class Engine : IEngine { private IReader consoleReader; private IWriter consoleWriter; private IChampionshipController controller; public Engine() { this.consoleReader = new ConsoleReader(); this.consoleWriter = new ConsoleWriter(); this.controller = new ChampionshipController(); } public void Run() { while (true) { string command = consoleReader.ReadLine(); string output = string.Empty; if(command == "End") { break; } string[] info = command.Split(" ", StringSplitOptions.RemoveEmptyEntries); string method = info[0]; try { if (method == "CreateRider") { string riderName = info[1]; output = controller.CreateRider(riderName); } else if (method == "CreateMotorcycle") { string motorcycleType = info[1]; string model = info[2]; int horsepower = int.Parse(info[3]); output = controller.CreateMotorcycle(motorcycleType, model, horsepower); } else if (method == "AddMotorcycleToRider") { string name = info[1]; string motorcycleName = info[2]; output = controller.AddMotorcycleToRider(name, motorcycleName); } else if (method == "AddRiderToRace") { string raceName = info[1]; string riderName = info[2]; output = controller.AddRiderToRace(raceName, riderName); } else if (method == "CreateRace") { string name = info[1]; int laps = int.Parse(info[2]); output = controller.CreateRace(name, laps); } else if (method == "StartRace") { string raceName = info[1]; output = controller.StartRace(raceName); } consoleWriter.WriteLine(output); } catch(Exception ex) { this.consoleWriter.WriteLine(ex.Message); } } } } }
31.422222
96
0.425035
[ "MIT" ]
VinsantSavov/SoftUni-Software-Engineering
CSharp-OOP/Exams/(Demo) Exam - 07 Dec 2019/01. Structure_Skeleton/MXGP/Core/Engine.cs
2,830
C#
using System; using Android.Gms.Ads; using Plugin.MgAdmob.EventArgs; namespace Plugin.MgAdmob.Listeners; public class MgBannerAdViewListener : AdListener { public event EventHandler AdClicked; public event EventHandler AdClosed; public event EventHandler AdImpression; public event EventHandler AdOpened; public event EventHandler<MgErrorEventArgs> AdFailedToLoad; public event EventHandler AdLoaded; public override void OnAdClicked() { base.OnAdClicked(); AdClicked?.Invoke(this, null); } public override void OnAdClosed() { base.OnAdClosed(); AdClosed?.Invoke(this, null); } public override void OnAdImpression() { base.OnAdImpression(); AdImpression?.Invoke(this, null); } public override void OnAdOpened() { base.OnAdOpened(); AdOpened?.Invoke(this, null); } public override void OnAdFailedToLoad(LoadAdError adError) { base.OnAdFailedToLoad(adError); var errorMessage = "Unknown error"; switch (adError.Code) { case AdRequest.ErrorCodeInternalError: errorMessage = "Internal error, an invalid response was received from the ad server."; break; case AdRequest.ErrorCodeInvalidRequest: errorMessage = "Invalid ad request, possibly an incorrect ad unit ID was given."; break; case AdRequest.ErrorCodeNetworkError: errorMessage = "The ad request was unsuccessful due to network connectivity."; break; case AdRequest.ErrorCodeNoFill: errorMessage = "The ad request was successful, but no ad was returned due to lack of ad inventory."; break; } AdFailedToLoad?.Invoke(this, new MgErrorEventArgs { ErrorCode = adError.Code, ErrorMessage = errorMessage }); } public override void OnAdLoaded() { base.OnAdLoaded(); AdLoaded?.Invoke(this, null); } }
27.25
115
0.668705
[ "MIT" ]
mg-code-solutions/MgAdmob
MgAdmob/Listeners/MgBannerAdViewListener.android.cs
1,964
C#
using System; using System.Collections.Generic; using UnityEngine; public class SlimeMovement : MonoBehaviour { [Tooltip("Ground collision settings.")] public RaycastColliderConfig groundColliderConfig; [Tooltip("Speed of movement along a surface, in world units per second.")] public float walkingSpeed = -0.1f; public float gravity = -5.0f; public GameObject slimeSpitObject; private CharacterState characterState; private RaycastCollider groundCollider; private HitPoints hitPoints; private Animator animator; private Vector2 velocity; private DropIndicator dropIndicator; private AttackTrigger attackTrigger; private float previousSpitTime = 0.0f; private readonly float spitInterval = 2.0f; private readonly List<string> animationStates = new List<string>{ "Idle", "Move", "Spit"}; private void Start() { characterState = GetComponent<CharacterState>(); var boxCollider = GetComponent<BoxCollider2D>(); dropIndicator = GetComponentInChildren<DropIndicator>(); attackTrigger = GetComponentInChildren<AttackTrigger>(); groundCollider = new RaycastCollider( groundColliderConfig, boxCollider, characterState.collisions); hitPoints = GetComponent<HitPoints>(); animator = GetComponent<Animator>(); velocity = Vector2.zero; } void FixedUpdate() { if (attackTrigger.PlayerInAttackRange) { velocity.x = 0; if (Time.time - previousSpitTime > spitInterval) { previousSpitTime = Time.time; SetAnimationState("Spit"); } else { SetAnimationState("Idle"); } } else { SetAnimationState("Idle"); } //Slime can move only after it has finished spitting animation. var inSpittingState = animator.GetCurrentAnimatorStateInfo(0).IsName("Slime spit"); if (!attackTrigger.PlayerInAttackRange && !inSpittingState) { velocity.x = walkingSpeed; SetAnimationState("Move"); } velocity.y += gravity * Time.deltaTime; Move(velocity * Time.deltaTime); var collisions = characterState.collisions; if (collisions.HasVerticalCollisions) { velocity.y = 0; } if (collisions.HasHorizontalCollisions || !dropIndicator.IsGroundAhead) { walkingSpeed *= -1; transform.localScale = new Vector3( -transform.localScale.x, transform.localScale.y, transform.localScale.z); } } private void SetAnimationState(string state) { animationStates.ForEach(animationState => animator.SetBool(animationState, false)); animator.SetBool(state, true); } private void SpitAnimationEnded() { Spit(); } private void Spit() { var slimeSpit = Instantiate(slimeSpitObject, transform.position + new Vector3(0f, -0.01f, 0), Quaternion.identity); var slimeSpitMovement = slimeSpit.GetComponent<SlimeSpitMovement>(); var yStartVelocity = 2.0f; var timeInAir = (yStartVelocity + Mathf.Sqrt(yStartVelocity * yStartVelocity - 2 * gravity * 0.08f)) / -gravity; var xDistance = attackTrigger.PlayerPosition?.x - transform.position.x; var xVelocity = xDistance / timeInAir; if (xVelocity.HasValue) { slimeSpitMovement.InitialVelocity = new Vector2( GetLimitedInitialVelocity(attackTrigger.PlayerInLeft, 0.3f, xVelocity.Value), yStartVelocity); } } private float GetLimitedInitialVelocity(bool playerInLeft, float minVelocity, float velocity) { if (attackTrigger.PlayerInLeft) return Mathf.Min(-minVelocity, velocity); else return Mathf.Max(minVelocity, velocity); } private void Move(Vector2 moveAmount) { groundCollider.UpdateRaycastOrigins(); CollisionInfo collisions = characterState.collisions; collisions.Reset(); groundCollider.HorizontalCollisions(ref moveAmount); if (moveAmount.y != 0) groundCollider.VerticalCollisions(ref moveAmount); transform.Translate(moveAmount); } }
30.875862
123
0.625195
[ "MIT" ]
vvnurmi/trappedinside
TrappedInside/Assets/SlimeMovement.cs
4,479
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("WpfApp2")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WpfApp2")] [assembly: AssemblyCopyright("Copyright © 2020")] [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.160714
99
0.69218
[ "MIT" ]
mariuszf161/Projekt
WpfApp2/Properties/AssemblyInfo.cs
2,420
C#
// **************************************************************** // Copyright 2010, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; using NUnit.Core; namespace NUnit.Util { /// <summary> /// DefaultTestRunnerFactory handles creation of a suitable test /// runner for a given package to be loaded and run either in a /// separate process or within the same process. /// </summary> public class DefaultTestRunnerFactory : InProcessTestRunnerFactory, ITestRunnerFactory { #if CLR_2_0 || CLR_4_0 private RuntimeFrameworkSelector selector = new RuntimeFrameworkSelector(); /// <summary> /// Returns a test runner based on the settings in a TestPackage. /// Any setting that is "consumed" by the factory is removed, so /// that downstream runners using the factory will not repeatedly /// create the same type of runner. /// </summary> /// <param name="package">The TestPackage to be loaded and run</param> /// <returns>A TestRunner</returns> public override TestRunner MakeTestRunner(TestPackage package) { ProcessModel processModel = GetTargetProcessModel(package); switch (processModel) { case ProcessModel.Multiple: package.Settings.Remove("ProcessModel"); return new MultipleTestProcessRunner(); case ProcessModel.Separate: package.Settings.Remove("ProcessModel"); return new ProcessRunner(); default: return base.MakeTestRunner(package); } } public override bool CanReuse(TestRunner runner, TestPackage package) { RuntimeFramework currentFramework = RuntimeFramework.CurrentFramework; RuntimeFramework targetFramework = selector.SelectRuntimeFramework(package); ProcessModel processModel = (ProcessModel)package.GetSetting("ProcessModel", ProcessModel.Default); if (processModel == ProcessModel.Default) if (!currentFramework.Supports(targetFramework)) processModel = ProcessModel.Separate; switch (processModel) { case ProcessModel.Multiple: return runner is MultipleTestProcessRunner; case ProcessModel.Separate: ProcessRunner processRunner = runner as ProcessRunner; return processRunner != null && processRunner.RuntimeFramework == targetFramework; default: return base.CanReuse(runner, package); } } private ProcessModel GetTargetProcessModel(TestPackage package) { RuntimeFramework currentFramework = RuntimeFramework.CurrentFramework; RuntimeFramework targetFramework = selector.SelectRuntimeFramework(package); ProcessModel processModel = (ProcessModel)package.GetSetting("ProcessModel", ProcessModel.Default); if (processModel == ProcessModel.Default) if (!currentFramework.Supports(targetFramework)) processModel = ProcessModel.Separate; return processModel; } #endif } }
43.120482
112
0.58983
[ "MIT" ]
acken/AutoTest.Net
lib/NUnit/src/NUnit-2.6.0.12051/src/ClientUtilities/util/DefaultTestRunnerFactory.cs
3,581
C#
using org.ohdsi.cdm.framework.common.Builder; using org.ohdsi.cdm.framework.common.Omop; using System; using System.Collections.Generic; using System.Data; namespace org.ohdsi.cdm.framework.common.DataReaders.v6 { public class ProcedureOccurrenceDataReader : IDataReader { private readonly IEnumerator<ProcedureOccurrence> _enumerator; private readonly KeyMasterOffsetManager _offset; // A custom DataReader is implemented to prevent the need for the HashSet to be transformed to a DataTable for loading by SqlBulkCopy public ProcedureOccurrenceDataReader(List<ProcedureOccurrence> batch, KeyMasterOffsetManager o) { _enumerator = batch?.GetEnumerator(); _offset = o; } public bool Read() { return _enumerator.MoveNext(); } public int FieldCount { get { return 14; } } public object GetValue(int i) { if (_enumerator.Current == null) return null; switch (i) { case 0: return _offset.GetId(_enumerator.Current.PersonId, _enumerator.Current.Id); case 1: return _enumerator.Current.PersonId; case 2: return _enumerator.Current.ConceptId; case 3: return _enumerator.Current.StartDate; case 4: return _enumerator.Current.StartDate.TimeOfDay; case 5: return _enumerator.Current.TypeConceptId; case 6: return _enumerator.Current.ModifierConceptId; case 7: return _enumerator.Current.Quantity; case 8: return _enumerator.Current.ProviderId == 0 ? null : _enumerator.Current.ProviderId; case 9: if (_enumerator.Current.VisitOccurrenceId.HasValue) { if (_offset.GetKeyOffset(_enumerator.Current.PersonId).VisitOccurrenceIdChanged) return _offset.GetId(_enumerator.Current.PersonId, _enumerator.Current.VisitOccurrenceId.Value); return _enumerator.Current.VisitOccurrenceId.Value; } return null; case 10: if (_enumerator.Current.VisitDetailId.HasValue) { if (_offset.GetKeyOffset(_enumerator.Current.PersonId).VisitDetailIdChanged) return _offset.GetId(_enumerator.Current.PersonId, _enumerator.Current.VisitDetailId.Value); return _enumerator.Current.VisitDetailId; } return null; case 11: return _enumerator.Current.SourceValue; case 12: return _enumerator.Current.SourceConceptId; case 13: return _enumerator.Current.QualifierSourceValue; default: throw new NotImplementedException(); } } public string GetName(int i) { switch (i) { case 0: return "procedure_occurrence_id"; case 1: return "person_id"; case 2: return "procedure_concept_id"; case 3: return "procedure_date"; case 4: return "procedure_datetime"; case 5: return "procedure_type_concept_id"; case 6: return "modifier_concept_id"; case 7: return "quantity"; case 8: return "provider_id"; case 9: return "visit_occurrence_id"; case 10: return "visit_detail_id"; case 11: return "procedure_source_value"; case 12: return "procedure_source_concept_id"; case 13: return "modifier_source_value"; default: throw new NotImplementedException(); } } #region implementationn not required for SqlBulkCopy public bool NextResult() { throw new NotImplementedException(); } public void Close() { throw new NotImplementedException(); } public bool IsClosed { get { throw new NotImplementedException(); } } public int Depth { get { throw new NotImplementedException(); } } public DataTable GetSchemaTable() { throw new NotImplementedException(); } public int RecordsAffected { get { throw new NotImplementedException(); } } public void Dispose() { throw new NotImplementedException(); } public bool GetBoolean(int i) { return (bool)GetValue(i); } public byte GetByte(int i) { return (byte)GetValue(i); } public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) { throw new NotImplementedException(); } public char GetChar(int i) { return (char)GetValue(i); } public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length) { throw new NotImplementedException(); } public IDataReader GetData(int i) { throw new NotImplementedException(); } public string GetDataTypeName(int i) { throw new NotImplementedException(); } public DateTime GetDateTime(int i) { return (DateTime)GetValue(i); } public decimal GetDecimal(int i) { return (decimal)GetValue(i); } public double GetDouble(int i) { return Convert.ToDouble(GetValue(i)); } public Type GetFieldType(int i) { switch (i) { case 0: return typeof(long); case 1: return typeof(long); case 2: return typeof(int); case 3: return typeof(DateTime?); case 4: return typeof(TimeSpan); case 5: return typeof(int); case 6: return typeof(int); case 7: return typeof(int?); case 8: return typeof(long?); case 9: return typeof(long?); case 10: return typeof(long?); case 11: return typeof(string); case 12: return typeof(int); case 13: return typeof(string); default: throw new NotImplementedException(); } } public float GetFloat(int i) { return (float)GetValue(i); } public Guid GetGuid(int i) { return (Guid)GetValue(i); } public short GetInt16(int i) { return (short)GetValue(i); } public int GetInt32(int i) { return (int)GetValue(i); } public long GetInt64(int i) { return Convert.ToInt64(GetValue(i)); } public int GetOrdinal(string name) { throw new NotImplementedException(); } public string GetString(int i) { return (string)GetValue(i); } public int GetValues(object[] values) { var cnt = 0; for (var i = 0; i < FieldCount; i++) { values[i] = GetValue(i); cnt++; } return cnt; } public bool IsDBNull(int i) { return GetValue(i) == null; } public object this[string name] { get { throw new NotImplementedException(); } } public object this[int i] { get { throw new NotImplementedException(); } } #endregion } }
28.896194
141
0.506766
[ "Apache-2.0" ]
OHDSI/ETL-CDMBuilder
source/org.ohdsi.cdm.framework.common/DataReaders/v6/ProcedureOccurrenceDataReader.cs
8,353
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v9/errors/asset_group_error.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Ads.GoogleAds.V9.Errors { /// <summary>Holder for reflection information generated from google/ads/googleads/v9/errors/asset_group_error.proto</summary> public static partial class AssetGroupErrorReflection { #region Descriptor /// <summary>File descriptor for google/ads/googleads/v9/errors/asset_group_error.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static AssetGroupErrorReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjZnb29nbGUvYWRzL2dvb2dsZWFkcy92OS9lcnJvcnMvYXNzZXRfZ3JvdXBf", "ZXJyb3IucHJvdG8SHmdvb2dsZS5hZHMuZ29vZ2xlYWRzLnY5LmVycm9ycxoc", "Z29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5wcm90byK+AwoTQXNzZXRHcm91cEVy", "cm9yRW51bSKmAwoPQXNzZXRHcm91cEVycm9yEg8KC1VOU1BFQ0lGSUVEEAAS", "CwoHVU5LTk9XThABEhIKDkRVUExJQ0FURV9OQU1FEAISLAooQ0FOTk9UX0FE", "RF9BU1NFVF9HUk9VUF9GT1JfQ0FNUEFJR05fVFlQRRADEh0KGU5PVF9FTk9V", "R0hfSEVBRExJTkVfQVNTRVQQBBIiCh5OT1RfRU5PVUdIX0xPTkdfSEVBRExJ", "TkVfQVNTRVQQBRIgChxOT1RfRU5PVUdIX0RFU0NSSVBUSU9OX0FTU0VUEAYS", "IgoeTk9UX0VOT1VHSF9CVVNJTkVTU19OQU1FX0FTU0VUEAcSJAogTk9UX0VO", "T1VHSF9NQVJLRVRJTkdfSU1BR0VfQVNTRVQQCBIrCidOT1RfRU5PVUdIX1NR", "VUFSRV9NQVJLRVRJTkdfSU1BR0VfQVNTRVQQCRIZChVOT1RfRU5PVUdIX0xP", "R09fQVNTRVQQChI8CjhGSU5BTF9VUkxfU0hPUFBJTkdfTUVSQ0hBTlRfSE9N", "RV9QQUdFX1VSTF9ET01BSU5TX0RJRkZFUhALQu8BCiJjb20uZ29vZ2xlLmFk", "cy5nb29nbGVhZHMudjkuZXJyb3JzQhRBc3NldEdyb3VwRXJyb3JQcm90b1AB", "WkRnb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2Fkcy9n", "b29nbGVhZHMvdjkvZXJyb3JzO2Vycm9yc6ICA0dBQaoCHkdvb2dsZS5BZHMu", "R29vZ2xlQWRzLlY5LkVycm9yc8oCHkdvb2dsZVxBZHNcR29vZ2xlQWRzXFY5", "XEVycm9yc+oCIkdvb2dsZTo6QWRzOjpHb29nbGVBZHM6OlY5OjpFcnJvcnNi", "BnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V9.Errors.AssetGroupErrorEnum), global::Google.Ads.GoogleAds.V9.Errors.AssetGroupErrorEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V9.Errors.AssetGroupErrorEnum.Types.AssetGroupError) }, null, null) })); } #endregion } #region Messages /// <summary> /// Container for enum describing possible asset group errors. /// </summary> public sealed partial class AssetGroupErrorEnum : pb::IMessage<AssetGroupErrorEnum> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<AssetGroupErrorEnum> _parser = new pb::MessageParser<AssetGroupErrorEnum>(() => new AssetGroupErrorEnum()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<AssetGroupErrorEnum> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V9.Errors.AssetGroupErrorReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public AssetGroupErrorEnum() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public AssetGroupErrorEnum(AssetGroupErrorEnum other) : this() { _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public AssetGroupErrorEnum Clone() { return new AssetGroupErrorEnum(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as AssetGroupErrorEnum); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(AssetGroupErrorEnum other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(AssetGroupErrorEnum other) { if (other == null) { return; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; } } } #endif #region Nested types /// <summary>Container for nested types declared in the AssetGroupErrorEnum message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static partial class Types { /// <summary> /// Enum describing possible asset group errors. /// </summary> public enum AssetGroupError { /// <summary> /// Enum unspecified. /// </summary> [pbr::OriginalName("UNSPECIFIED")] Unspecified = 0, /// <summary> /// The received error code is not known in this version. /// </summary> [pbr::OriginalName("UNKNOWN")] Unknown = 1, /// <summary> /// Each asset group in a single campaign must have a unique name. /// </summary> [pbr::OriginalName("DUPLICATE_NAME")] DuplicateName = 2, /// <summary> /// Cannot add asset group for the campaign type. /// </summary> [pbr::OriginalName("CANNOT_ADD_ASSET_GROUP_FOR_CAMPAIGN_TYPE")] CannotAddAssetGroupForCampaignType = 3, /// <summary> /// Not enough headline asset for a valid asset group. /// </summary> [pbr::OriginalName("NOT_ENOUGH_HEADLINE_ASSET")] NotEnoughHeadlineAsset = 4, /// <summary> /// Not enough long headline asset for a valid asset group. /// </summary> [pbr::OriginalName("NOT_ENOUGH_LONG_HEADLINE_ASSET")] NotEnoughLongHeadlineAsset = 5, /// <summary> /// Not enough description headline asset for a valid asset group. /// </summary> [pbr::OriginalName("NOT_ENOUGH_DESCRIPTION_ASSET")] NotEnoughDescriptionAsset = 6, /// <summary> /// Not enough business name asset for a valid asset group. /// </summary> [pbr::OriginalName("NOT_ENOUGH_BUSINESS_NAME_ASSET")] NotEnoughBusinessNameAsset = 7, /// <summary> /// Not enough marketing image asset for a valid asset group. /// </summary> [pbr::OriginalName("NOT_ENOUGH_MARKETING_IMAGE_ASSET")] NotEnoughMarketingImageAsset = 8, /// <summary> /// Not enough square marketing image asset for a valid asset group. /// </summary> [pbr::OriginalName("NOT_ENOUGH_SQUARE_MARKETING_IMAGE_ASSET")] NotEnoughSquareMarketingImageAsset = 9, /// <summary> /// Not enough logo asset for a valid asset group. /// </summary> [pbr::OriginalName("NOT_ENOUGH_LOGO_ASSET")] NotEnoughLogoAsset = 10, /// <summary> /// Final url and shopping merchant url does not have the same domain. /// </summary> [pbr::OriginalName("FINAL_URL_SHOPPING_MERCHANT_HOME_PAGE_URL_DOMAINS_DIFFER")] FinalUrlShoppingMerchantHomePageUrlDomainsDiffer = 11, } } #endregion } #endregion } #endregion Designer generated code
41.589928
299
0.698063
[ "Apache-2.0" ]
friedenberg/google-ads-dotnet
src/V9/Types/AssetGroupError.g.cs
11,562
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Mercury.Client { [Serializable] public class Session { #region Private Properties private String token; private Int64 securityAuthorityId; private String securityAuthorityName; private Server.Enterprise.SecurityAuthorityType securityAuthorityType = Server.Enterprise.SecurityAuthorityType.WindowsIntegrated; private Int64 environmentId = 0; private String environmentName = String.Empty; private String confidentialityStatement; private String userAccountId; private String userAccountName; private String userDisplayName; private List<String> groupMembership = new List<String> (); private List<String> roleMembership = new List<String> (); private Dictionary<String, String> enterprisePermissionSet = new Dictionary<String, String> (); private Dictionary<String, String> environmentPermissionSet = new Dictionary<String, String> (); private Dictionary<Int64, Server.Application.WorkQueueTeamPermission> workQueuePermissions = new Dictionary<Int64, Server.Application.WorkQueueTeamPermission> (); #endregion #region Public Properties public String Token { get { return token; } } public Int64 SecurityAuthorityId { get { return securityAuthorityId; } set { securityAuthorityId = value; } } public String SecurityAuthorityName { get { return securityAuthorityName; } set { securityAuthorityName = value; } } // Property: AuthorityName public Server.Enterprise.SecurityAuthorityType SecurityAuthorityType { get { return securityAuthorityType; } set { securityAuthorityType = value; } } // Property: AuthorityType public Int64 EnvironmentId { get { return environmentId; } set { environmentId = value; } } public String EnvironmentName { get { return environmentName; } set { environmentName = value; } } // Property: EnvironmentName public String ConfidentialityStatement { get { return confidentialityStatement; } set { confidentialityStatement = value; } } // Property: ConfidentialityStatement public String UserAccountId { get { return userAccountId; } set { userAccountId = value; } } public String UserAccountName { get { return userAccountName; } set { userAccountName = value; } } public String UserDisplayName { get { return userDisplayName; } set { userDisplayName = value; } } public List<String> GroupMembership { get { return groupMembership; } set { groupMembership = value; } } public List<String> RoleMembership { get { return roleMembership; } set { roleMembership = value; } } public Dictionary<String, String> EnterprisePermissionSet { get { return enterprisePermissionSet; } } // Property: EnterprisePermissionSet public Dictionary<String, String> EnvironmentPermissionSet { get { return environmentPermissionSet; } } // Property: EnvironmentPermissionSet public Dictionary<Int64, Server.Application.WorkQueueTeamPermission> WorkQueuePermissions { get { return workQueuePermissions; } } #endregion #region Constructors public Session (Server.Enterprise.AuthenticationResponse authenticationResponse) { token = authenticationResponse.Token; securityAuthorityId = authenticationResponse.SecurityAuthorityId; securityAuthorityName = authenticationResponse.SecurityAuthorityName; securityAuthorityType = authenticationResponse.SecurityAuthorityType; environmentId = authenticationResponse.EnvironmentId; environmentName = authenticationResponse.EnvironmentName; confidentialityStatement = authenticationResponse.ConfidentialityStatement; userAccountId = authenticationResponse.UserAccountId; userAccountName = authenticationResponse.UserAccountName; userDisplayName = authenticationResponse.UserDisplayName; foreach (Int64 currentWorkQueueId in authenticationResponse.WorkQueuePermissions.Keys) { Int32 permission = (Int32) authenticationResponse.WorkQueuePermissions[currentWorkQueueId]; workQueuePermissions.Add (currentWorkQueueId, (Server.Application.WorkQueueTeamPermission) permission); } foreach (String currentGroupMembership in authenticationResponse.GroupMembership) { groupMembership.Add (currentGroupMembership); } foreach (String currentRoleMembership in authenticationResponse.RoleMembership) { roleMembership.Add (currentRoleMembership); } foreach (String currentPermission in authenticationResponse.EnterprisePermissionSet) { enterprisePermissionSet.Add (currentPermission, currentPermission); } foreach (String currentPermission in authenticationResponse.EnvironmentPermissionSet) { environmentPermissionSet.Add (currentPermission, currentPermission); } return; } public Session (String sessionToken) { token = sessionToken; return; } #endregion } }
33.805031
184
0.704372
[ "MIT" ]
Quebe/Mercury-Care-Management
Mercury.Clients/Mercury.Clients.Web/Mercury.Client/Client/Session.cs
5,377
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 workspaces-2015-04-08.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.WorkSpaces.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.WorkSpaces.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for AuthorizeIpRules operation /// </summary> public class AuthorizeIpRulesResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { AuthorizeIpRulesResponse response = new AuthorizeIpRulesResponse(); return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException")) { return AccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterValuesException")) { return InvalidParameterValuesExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidResourceStateException")) { return InvalidResourceStateExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceLimitExceededException")) { return ResourceLimitExceededExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonWorkSpacesException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static AuthorizeIpRulesResponseUnmarshaller _instance = new AuthorizeIpRulesResponseUnmarshaller(); internal static AuthorizeIpRulesResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static AuthorizeIpRulesResponseUnmarshaller Instance { get { return _instance; } } } }
41.4
194
0.643772
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/WorkSpaces/Generated/Model/Internal/MarshallTransformations/AuthorizeIpRulesResponseUnmarshaller.cs
4,761
C#
using Uno.UI.Samples.Controls; using Windows.UI.Xaml.Controls; namespace UITests.Windows_UI_Xaml_Controls.TimePicker { [SampleControlInfo("Pickers", nameof(TimePicker_TimePickerFlyoutStyle))] public sealed partial class TimePicker_TimePickerFlyoutStyle : UserControl { public TimePicker_TimePickerFlyoutStyle() { this.InitializeComponent(); } } }
24.133333
75
0.803867
[ "Apache-2.0" ]
iury-kc/uno
src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/TimePicker/TimePicker_TimePickerFlyoutStyle.xaml.cs
364
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 schemas-2019-12-02.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.Schemas.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Schemas.Model.Internal.MarshallTransformations { /// <summary> /// DescribeSchema Request Marshaller /// </summary> public class DescribeSchemaRequestMarshaller : IMarshaller<IRequest, DescribeSchemaRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DescribeSchemaRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DescribeSchemaRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Schemas"); request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2019-12-02"; request.HttpMethod = "GET"; if (!publicRequest.IsSetRegistryName()) throw new AmazonSchemasException("Request object does not have required field RegistryName set"); request.AddPathResource("{registryName}", StringUtils.FromString(publicRequest.RegistryName)); if (!publicRequest.IsSetSchemaName()) throw new AmazonSchemasException("Request object does not have required field SchemaName set"); request.AddPathResource("{schemaName}", StringUtils.FromString(publicRequest.SchemaName)); if (publicRequest.IsSetSchemaVersion()) request.Parameters.Add("schemaVersion", StringUtils.FromString(publicRequest.SchemaVersion)); request.ResourcePath = "/v1/registries/name/{registryName}/schemas/name/{schemaName}"; request.MarshallerVersion = 2; request.UseQueryString = true; return request; } private static DescribeSchemaRequestMarshaller _instance = new DescribeSchemaRequestMarshaller(); internal static DescribeSchemaRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DescribeSchemaRequestMarshaller Instance { get { return _instance; } } } }
38.6
144
0.643032
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/Schemas/Generated/Model/Internal/MarshallTransformations/DescribeSchemaRequestMarshaller.cs
3,667
C#
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames // // BRON-Y-ORC STOMP (lighting) // // Copyright (C) 2015 Faust Logic, Inc. // // 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. // //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~// // STOMP LIGHT datablock afxT3DPointLightData(BYOS_ExplosionLight_CE) { radius = "$$ 5.0 * %%._triggerScale[##]"; color = "1 1 1 1"; brightness = 3.0; castShadows = false; localRenderViz = false; }; datablock afxEffectWrapperData(BYOS_ExplosionLight_LF_EW) { effect = BYOS_ExplosionLight_CE; posConstraint = "target.Bip01 L Foot"; lifetime = 0.05; delay = 0; fadeInTime = 0.05; fadeOutTime = 0.05; xfmModifiers[0] = BYOS_StepOffset_LF_XM; }; datablock afxEffectWrapperData(BYOS_ExplosionLight_RT_EW : BYOS_ExplosionLight_LF_EW) { posConstraint = "target.Bip01 R Foot"; xfmModifiers[0] = BYOS_StepOffset_RT_XM; }; //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~// // JUMP LANDING LIGHTING datablock afxT3DPointLightData(BYOS_ExplosionLight_LAND_CE : BYOS_ExplosionLight_CE) { radius = "$$ 10.0 * %%._triggerScaleLAND"; }; datablock afxEffectWrapperData(BYOS_ExplosionLight_LAND_EW) { effect = BYOS_ExplosionLight_LAND_CE; posConstraint = target; lifetime = 0.05; delay = 0; fadeInTime = 0.05; fadeOutTime = 0.05; }; //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// function BYOS_add_footstep_Lighting_FX(%phrase_lf, %phrase_rt) { %phrase_rt.addEffect(BYOS_ExplosionLight_RT_EW); %phrase_lf.addEffect(BYOS_ExplosionLight_LF_EW); } function BYOS_add_landing_Lighting_FX(%phrase_landing) { %phrase_landing.addEffect(BYOS_ExplosionLight_LAND_EW); } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
34.811111
92
0.613789
[ "MIT" ]
7erj1/RPG_Starter
Templates/RPGDemo/game/scripts/server/afx/effects/SpellPack2/lighting/byos_lighting_t3d_sub.cs
3,044
C#
namespace MoreLinq { #if UNITY_5_6_OR_NEWER #pragma warning disable CS3015 [System.AttributeUsage(System.AttributeTargets.All)] public class MaybeNullAttribute : System.Attribute {} [System.AttributeUsage(System.AttributeTargets.All)] public class MaybeNullWhenAttribute : System.Attribute { public MaybeNullWhenAttribute(params object[] any) { } } #endif }
26.866667
62
0.727047
[ "Apache-2.0" ]
invocative/MoreLINQ
MoreLinq/MaybeNullAttribute.cs
403
C#
using PnP.Framework.Entities; using PnP.Framework.Graph; using PnP.PowerShell.Commands.Attributes; using PnP.PowerShell.Commands.Base; using PnP.PowerShell.Commands.Base.PipeBinds; using System.Management.Automation; namespace PnP.PowerShell.Commands.Graph { [Cmdlet(VerbsCommon.Clear, "PnPMicrosoft365GroupMember")] [RequiredMinimalApiPermissions("Group.ReadWrite.All")] public class ClearMicrosoft365GroupMember : PnPGraphCmdlet { [Parameter(Mandatory = true, ValueFromPipeline = true)] public Microsoft365GroupPipeBind Identity; protected override void ExecuteCmdlet() { UnifiedGroupEntity group = null; if (Identity != null) { group = Identity.GetGroup(AccessToken); } if (group != null) { UnifiedGroupsUtility.ClearUnifiedGroupMembers(group.GroupId, AccessToken); } } } }
29.90625
90
0.660397
[ "MIT" ]
sebastianmattar/powershell
src/Commands/Graph/ClearMicrosoft365GroupMember.cs
959
C#
/* * Copyright 2017-2018, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using Moq; using OptimizelySDK.Logger; using OptimizelySDK.Event.Builder; using OptimizelySDK.Event.Dispatcher; using OptimizelySDK.ErrorHandler; using OptimizelySDK.Exceptions; using OptimizelySDK.Event; using OptimizelySDK.Entity; using NUnit.Framework; using OptimizelySDK.Tests.UtilsTests; using OptimizelySDK.Bucketing; using OptimizelySDK.Notifications; using OptimizelySDK.Tests.NotificationTests; using OptimizelySDK.Utils; namespace OptimizelySDK.Tests { [TestFixture] public class OptimizelyTest { private Mock<ILogger> LoggerMock; private ProjectConfig Config; private Mock<EventBuilder> EventBuilderMock; private Mock<IErrorHandler> ErrorHandlerMock; private Mock<IEventDispatcher> EventDispatcherMock; private Optimizely Optimizely; private IEventDispatcher EventDispatcher; private const string TestUserId = "testUserId"; private OptimizelyHelper Helper; private Mock<Optimizely> OptimizelyMock; private Mock<DecisionService> DecisionServiceMock; private NotificationCenter NotificationCenter; private Mock<TestNotificationCallbacks> NotificationCallbackMock; private Variation VariationWithKeyControl; private Variation VariationWithKeyVariation; private Variation GroupVariation; #region Test Life Cycle [SetUp] public void Initialize() { LoggerMock = new Mock<ILogger>(); LoggerMock.Setup(i => i.Log(It.IsAny<LogLevel>(), It.IsAny<string>())); ErrorHandlerMock = new Mock<IErrorHandler>(); ErrorHandlerMock.Setup(e => e.HandleError(It.IsAny<Exception>())); EventBuilderMock = new Mock<EventBuilder>(new Bucketer(LoggerMock.Object), LoggerMock.Object); EventBuilderMock.Setup(b => b.CreateImpressionEvent(It.IsAny<ProjectConfig>(), It.IsAny<Experiment>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<UserAttributes>())); EventBuilderMock.Setup(b => b.CreateConversionEvent(It.IsAny<ProjectConfig>(), It.IsAny<string>(), It.IsAny<Dictionary<string, Variation>>(), It.IsAny<string>(), It.IsAny<UserAttributes>(), It.IsAny<EventTags>())); Config = ProjectConfig.Create( content: TestData.Datafile, logger: LoggerMock.Object, errorHandler: new NoOpErrorHandler()); EventDispatcherMock = new Mock<IEventDispatcher>(); Optimizely = new Optimizely(TestData.Datafile, EventDispatcherMock.Object, LoggerMock.Object, ErrorHandlerMock.Object); Helper = new OptimizelyHelper { Datafile = TestData.Datafile, EventDispatcher = EventDispatcherMock.Object, Logger = LoggerMock.Object, ErrorHandler = ErrorHandlerMock.Object, SkipJsonValidation = false, }; OptimizelyMock = new Mock<Optimizely>(TestData.Datafile, EventDispatcherMock.Object, LoggerMock.Object, ErrorHandlerMock.Object, null, false) { CallBase = true }; DecisionServiceMock = new Mock<DecisionService>(new Bucketer(LoggerMock.Object), ErrorHandlerMock.Object, Config, null, LoggerMock.Object); NotificationCenter = new NotificationCenter(LoggerMock.Object); NotificationCallbackMock = new Mock<TestNotificationCallbacks>(); VariationWithKeyControl = Config.GetVariationFromKey("test_experiment", "control"); VariationWithKeyVariation = Config.GetVariationFromKey("test_experiment", "variation"); GroupVariation = Config.GetVariationFromKey("group_experiment_1", "group_exp_1_var_2"); } [TestFixtureTearDown] public void Cleanup() { LoggerMock = null; Config = null; EventBuilderMock = null; } #endregion #region OptimizelyHelper private class OptimizelyHelper { static Type[] ParameterTypes = new[] { typeof(string), typeof(IEventDispatcher), typeof(ILogger), typeof(IErrorHandler), typeof(bool) }; public static Dictionary<string, object> SingleParameter = new Dictionary<string, object> { { "param1", "val1" } }; public static UserAttributes UserAttributes = new UserAttributes { { "device_type", "iPhone" }, { "company", "Optimizely" }, { "location", "San Francisco" } }; // NullUserAttributes extends copy of UserAttributes with key-value // pairs containing null values which should not be sent to OPTIMIZELY.COM . public static UserAttributes NullUserAttributes = new UserAttributes { { "device_type", "iPhone" }, { "company", "Optimizely" }, { "location", "San Francisco" }, { "null_value", null}, { "wont_be_sent", null}, { "bad_food", null} }; public string Datafile { get; set; } public IEventDispatcher EventDispatcher { get; set; } public ILogger Logger { get; set; } public IErrorHandler ErrorHandler { get; set; } public UserProfileService UserProfileService { get; set; } public bool SkipJsonValidation { get; set; } public PrivateObject CreatePrivateOptimizely() { return new PrivateObject(typeof(Optimizely), ParameterTypes, new object[] { Datafile, EventDispatcher, Logger, ErrorHandler, UserProfileService, SkipJsonValidation }); } } #endregion #region Test Validate [Test] public void TestValidateInputsInvalidFileJsonValidationNotSkipped() { string datafile = "{\"name\":\"optimizely\"}"; Optimizely optimizely = new Optimizely(datafile); Assert.IsFalse(optimizely.IsValid); } [Test] public void TestValidateInputsInvalidFileJsonValidationSkipped() { string datafile = "{\"name\":\"optimizely\"}"; Optimizely optimizely = new Optimizely(datafile, null, null, null, skipJsonValidation: true); Assert.IsTrue(optimizely.IsValid); } [Test] public void TestValidatePreconditionsExperimentNotRunning() { var optly = Helper.CreatePrivateOptimizely(); bool result = (bool)optly.Invoke("ValidatePreconditions", Config.GetExperimentFromKey("paused_experiment"), TestUserId, new UserAttributes { }); Assert.IsFalse(result); } [Test] public void TestValidatePreconditionsExperimentRunning() { var optly = Helper.CreatePrivateOptimizely(); bool result = (bool)optly.Invoke("ValidatePreconditions", Config.GetExperimentFromKey("test_experiment"), TestUserId, new UserAttributes { { "device_type", "iPhone" }, { "location", "San Francisco" } } ); Assert.IsTrue(result); } [Test] public void TestValidatePreconditionsUserInForcedVariationNotInExperiment() { var optly = Helper.CreatePrivateOptimizely(); bool result = (bool)optly.Invoke("ValidatePreconditions", Config.GetExperimentFromKey("test_experiment"), "user1", new UserAttributes { }); Assert.IsTrue(result); } [Test] public void TestValidatePreconditionsUserInForcedVariationInExperiment() { var optly = Helper.CreatePrivateOptimizely(); bool result = (bool)optly.Invoke("ValidatePreconditions", Config.GetExperimentFromKey("test_experiment"), "user1", new UserAttributes { }); Assert.IsTrue(result); } [Test] public void TestValidatePreconditionsUserNotInForcedVariationNotInExperiment() { var optly = Helper.CreatePrivateOptimizely(); bool result = (bool)optly.Invoke("ValidatePreconditions", Config.GetExperimentFromKey("test_experiment"), TestUserId, new UserAttributes { }); Assert.IsFalse(result); } [Test] public void TestValidatePreconditionsUserNotInForcedVariationInExperiment() { var attributes = new UserAttributes { { "device_type", "iPhone" }, { "location", "San Francisco" } }; var variation = Optimizely.GetVariation("test_experiment", "test_user", attributes); LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Exactly(4)); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "User \"test_user\" is not in the forced variation map."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Assigned bucket [3037] to user [test_user] with bucketing ID [test_user]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User [test_user] is in variation [control] of experiment [test_experiment]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "This decision will not be saved since the UserProfileService is null."), Times.Once); Assert.IsTrue(TestData.CompareObjects(VariationWithKeyControl, variation)); } [Test] public void TestActivateInvalidOptimizelyObject() { var optly = new Optimizely("Random datafile", null, LoggerMock.Object); LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Provided 'datafile' has invalid schema."), Times.Once); } //attributes can not be invalid beacuse now it is strongly typed. /* [TestMethod] public void TestActivateInvalidAttributes() { var attributes = new UserAttribute { {"abc", "43" } }; var result = Optimizely.Activate("test_experiment", TestUserId, attributes); LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Once); //LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Provided attributes are in an invalid format."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, string.Format("Not activating user {0}.", TestUserId)), Times.Once); ErrorHandlerMock.Verify(e => e.HandleError(It.IsAny<InvalidAttributeException>()), Times.Once); Assert.IsNull(result); } */ [Test] public void TestActivateUserInNoVariation() { var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("EventBuilder", EventBuilderMock.Object); var result = optly.Invoke("Activate", "test_experiment", "not_in_variation_user", OptimizelyHelper.UserAttributes); EventBuilderMock.Verify(b => b.CreateImpressionEvent(It.IsAny<ProjectConfig>(), It.IsAny<Experiment>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<UserAttributes>()), Times.Never); LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Exactly(4)); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Assigned bucket [8495] to user [not_in_variation_user] with bucketing ID [not_in_variation_user]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User [not_in_variation_user] is in no variation."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Not activating user not_in_variation_user."), Times.Once); Assert.IsNull(result); } [Test] public void TestActivateNoAudienceNoAttributes() { var parameters = new Dictionary<string, object> { { "param1", "val1" }, { "param2", "val2" } }; EventBuilderMock.Setup(b => b.CreateImpressionEvent(It.IsAny<ProjectConfig>(), It.IsAny<Experiment>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<UserAttributes>())) .Returns(new LogEvent("logx.optimizely.com/decision", parameters, "POST", new Dictionary<string, string> { })); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("EventBuilder", EventBuilderMock.Object); var variation = (Variation)optly.Invoke("Activate", "group_experiment_1", "user_1", null); EventBuilderMock.Verify(b => b.CreateImpressionEvent(It.IsAny<ProjectConfig>(), Config.GetExperimentFromKey("group_experiment_1"), "7722360022", "user_1", null), Times.Once); LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Exactly(8)); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Assigned bucket [1922] to user [user_1] with bucketing ID [user_1]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User [user_1] is in experiment [group_experiment_1] of group [7722400015]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Assigned bucket [9525] to user [user_1] with bucketing ID [user_1]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User [user_1] is in variation [group_exp_1_var_2] of experiment [group_experiment_1]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Activating user user_1 in experiment group_experiment_1."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, @"Dispatching impression event to URL logx.optimizely.com/decision with params {""param1"":""val1"",""param2"":""val2""}."), Times.Once); Assert.IsTrue(TestData.CompareObjects(GroupVariation, variation)); } #endregion #region Test Activate [Test] public void TestActivateAudienceNoAttributes() { var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("EventBuilder", EventBuilderMock.Object); var variationkey = optly.Invoke("Activate", "test_experiment", "test_user", null); EventBuilderMock.Verify(b => b.CreateImpressionEvent(It.IsAny<ProjectConfig>(), It.IsAny<Experiment>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<UserAttributes>()), Times.Never); LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Exactly(3)); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User \"test_user\" does not meet conditions to be in experiment \"test_experiment\"."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Not activating user test_user."), Times.Once); Assert.IsNull(variationkey); } [Test] public void TestActivateWithAttributes() { EventBuilderMock.Setup(b => b.CreateImpressionEvent(It.IsAny<ProjectConfig>(), It.IsAny<Experiment>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<UserAttributes>())) .Returns(new LogEvent("logx.optimizely.com/decision", OptimizelyHelper.SingleParameter, "POST", new Dictionary<string, string> { })); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("EventBuilder", EventBuilderMock.Object); var variation = (Variation)optly.Invoke("Activate", "test_experiment", "test_user", OptimizelyHelper.UserAttributes); EventBuilderMock.Verify(b => b.CreateImpressionEvent(It.IsAny<ProjectConfig>(), Config.GetExperimentFromKey("test_experiment"), "7722370027", "test_user", OptimizelyHelper.UserAttributes), Times.Once); LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Exactly(6)); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Assigned bucket [3037] to user [test_user] with bucketing ID [test_user]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User [test_user] is in variation [control] of experiment [test_experiment]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Activating user test_user in experiment test_experiment."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, @"Dispatching impression event to URL logx.optimizely.com/decision with params {""param1"":""val1""}."), Times.Once); Assert.IsTrue(TestData.CompareObjects(VariationWithKeyControl, variation)); } [Test] public void TestActivateWithNullAttributes() { EventBuilderMock.Setup(b => b.CreateImpressionEvent(It.IsAny<ProjectConfig>(), It.IsAny<Experiment>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<UserAttributes>())) .Returns(new LogEvent("logx.optimizely.com/decision", OptimizelyHelper.SingleParameter, "POST", new Dictionary<string, string> { })); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("EventBuilder", EventBuilderMock.Object); var variation = (Variation)optly.Invoke("Activate", "test_experiment", "test_user", OptimizelyHelper.NullUserAttributes); EventBuilderMock.Verify(b => b.CreateImpressionEvent(It.IsAny<ProjectConfig>(), Config.GetExperimentFromKey("test_experiment"), "7722370027", "test_user", OptimizelyHelper.UserAttributes), Times.Once); LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Exactly(9)); //"User "test_user" is not in the forced variation map." LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "User \"test_user\" is not in the forced variation map."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Assigned bucket [3037] to user [test_user] with bucketing ID [test_user]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User [test_user] is in variation [control] of experiment [test_experiment]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "[UserAttributes] Null value for key null_value removed and will not be sent to results."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "[UserAttributes] Null value for key wont_be_sent removed and will not be sent to results."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "[UserAttributes] Null value for key bad_food removed and will not be sent to results."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Activating user test_user in experiment test_experiment."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, @"Dispatching impression event to URL logx.optimizely.com/decision with params {""param1"":""val1""}."), Times.Once); Assert.IsTrue(TestData.CompareObjects(VariationWithKeyControl, variation)); } [Test] public void TestActivateExperimentNotRunning() { var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("EventBuilder", EventBuilderMock.Object); var variationkey = optly.Invoke("Activate", "paused_experiment", "test_user", null); EventBuilderMock.Verify(b => b.CreateImpressionEvent(It.IsAny<ProjectConfig>(), It.IsAny<Experiment>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<UserAttributes>()), Times.Never); LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Exactly(2)); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Experiment \"paused_experiment\" is not running."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Not activating user test_user."), Times.Once); Assert.IsNull(variationkey); } #endregion #region Test GetVariation [Test] public void TestGetVariationInvalidOptimizelyObject() { var optly = new Optimizely("Random datafile", null, LoggerMock.Object); var variationkey = optly.Activate("some_experiment", "some_user"); LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Exactly(2)); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Datafile has invalid format. Failing 'activate'."), Times.Once); //Assert.IsNull(variationkey); } //attributes can not be invalid beacuse now it is strongly typed. /* [TestMethod] public void TestGetVariationInvalidAttributes() { var attributes = new UserAttribute { {"abc", "43" } }; var result = Optimizely.getVariation("test_experiment", TestUserId, attributes); //LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Provided attributes are in an invalid format."), Times.Once); ErrorHandlerMock.Verify(e => e.HandleError(It.IsAny<InvalidAttributeException>()), Times.Once); Assert.IsNull(result); } */ [Test] public void TestGetVariationAudienceMatch() { var attributes = new UserAttributes { { "device_type", "iPhone" }, { "location", "San Francisco" } }; var variation = Optimizely.GetVariation("test_experiment", "test_user", attributes); LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Exactly(4)); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Assigned bucket [3037] to user [test_user] with bucketing ID [test_user]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User [test_user] is in variation [control] of experiment [test_experiment]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "This decision will not be saved since the UserProfileService is null."), Times.Once); Assert.IsTrue(TestData.CompareObjects(VariationWithKeyControl, variation)); } [Test] public void TestGetVariationAudienceNoMatch() { var variation = Optimizely.Activate("test_experiment", "test_user"); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User \"test_user\" does not meet conditions to be in experiment \"test_experiment\"."), Times.Once); Assert.IsNull(variation); } [Test] public void TestGetVariationExperimentNotRunning() { var variation = Optimizely.Activate("paused_experiment", "test_user"); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Experiment \"paused_experiment\" is not running."), Times.Once); Assert.IsNull(variation); } [Test] public void TestTrackInvalidOptimizelyObject() { var optly = new Optimizely("Random datafile", null, LoggerMock.Object); optly.Track("some_event", "some_user"); LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Exactly(2)); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Datafile has invalid format. Failing 'track'."), Times.Once); } #endregion #region Test Track [Test] public void TestTrackInvalidAttributes() { var attributes = new UserAttributes { { "abc", "43" } }; Optimizely.Track("purchase", TestUserId, attributes); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, @"Attribute key ""abc"" is not in datafile."), Times.Once); } [Test] public void TestTrackNoAttributesNoEventValue() { EventBuilderMock.Setup(b => b.CreateConversionEvent(It.IsAny<ProjectConfig>(), It.IsAny<string>(), It.IsAny<Dictionary<string,Variation>>(), It.IsAny<string>(), It.IsAny<UserAttributes>(), It.IsAny<EventTags>())) .Returns(new LogEvent("logx.optimizely.com/track", OptimizelyHelper.SingleParameter, "POST", new Dictionary<string, string> { })); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("EventBuilder", EventBuilderMock.Object); optly.Invoke("Track", "purchase", "test_user", null, null); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User \"test_user\" does not meet conditions to be in experiment \"test_experiment\"."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Not tracking user \"test_user\" for experiment \"test_experiment\""), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Experiment \"paused_experiment\" is not running."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Not tracking user \"test_user\" for experiment \"paused_experiment\""), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Tracking event purchase for user test_user."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Dispatching conversion event to URL logx.optimizely.com/track with params {\"param1\":\"val1\"}."), Times.Once); } [Test] public void TestTrackWithAttributesNoEventValue() { EventBuilderMock.Setup(b => b.CreateConversionEvent(It.IsAny<ProjectConfig>(), It.IsAny<string>(), It.IsAny<Dictionary<string, Variation>>(), It.IsAny<string>(), It.IsAny<UserAttributes>(), It.IsAny<EventTags>())) .Returns(new LogEvent("logx.optimizely.com/track", OptimizelyHelper.SingleParameter, "POST", new Dictionary<string, string> { })); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("EventBuilder", EventBuilderMock.Object); optly.Invoke("Track", "purchase", "test_user", OptimizelyHelper.UserAttributes, null); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Experiment \"paused_experiment\" is not running."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Not tracking user \"test_user\" for experiment \"paused_experiment\""), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Tracking event purchase for user test_user."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Dispatching conversion event to URL logx.optimizely.com/track with params {\"param1\":\"val1\"}."), Times.Once); } [Test] public void TestTrackNoAttributesWithEventValue() { EventBuilderMock.Setup(b => b.CreateConversionEvent(It.IsAny<ProjectConfig>(), It.IsAny<string>(), It.IsAny<Dictionary<string, Variation>>(), It.IsAny<string>(), It.IsAny<UserAttributes>(), It.IsAny<EventTags>())) .Returns(new LogEvent("logx.optimizely.com/track", OptimizelyHelper.SingleParameter, "POST", new Dictionary<string, string> { })); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("EventBuilder", EventBuilderMock.Object); optly.Invoke("Track", "purchase", "test_user", null, new EventTags { { "revenue", 42 } }); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User \"test_user\" does not meet conditions to be in experiment \"test_experiment\"."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Not tracking user \"test_user\" for experiment \"test_experiment\""), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Experiment \"paused_experiment\" is not running."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Not tracking user \"test_user\" for experiment \"paused_experiment\""), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Tracking event purchase for user test_user."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Dispatching conversion event to URL logx.optimizely.com/track with params {\"param1\":\"val1\"}."), Times.Once); } [Test] public void TestTrackWithAttributesWithEventValue() { var attributes = new UserAttributes { { "device_type", "iPhone" }, { "company", "Optimizely" }, }; EventBuilderMock.Setup(b => b.CreateConversionEvent(It.IsAny<ProjectConfig>(), It.IsAny<string>(), It.IsAny<Dictionary<string, Variation>>(), It.IsAny<string>(), It.IsAny<UserAttributes>(), It.IsAny<EventTags>())) .Returns(new LogEvent("logx.optimizely.com/track", OptimizelyHelper.SingleParameter, "POST", new Dictionary<string, string> { })); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("EventBuilder", EventBuilderMock.Object); optly.Invoke("Track", "purchase", "test_user", attributes, new EventTags { { "revenue", 42 } }); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User \"test_user\" does not meet conditions to be in experiment \"test_experiment\"."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Not tracking user \"test_user\" for experiment \"test_experiment\""), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Experiment \"paused_experiment\" is not running."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Not tracking user \"test_user\" for experiment \"paused_experiment\""), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Tracking event purchase for user test_user."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Dispatching conversion event to URL logx.optimizely.com/track with params {\"param1\":\"val1\"}."), Times.Once); } [Test] public void TestTrackWithNullAttributesWithNullEventValue() { EventBuilderMock.Setup(b => b.CreateConversionEvent(It.IsAny<ProjectConfig>(), It.IsAny<string>(), It.IsAny<Dictionary<string, Variation>>(), It.IsAny<string>(), It.IsAny<UserAttributes>(), It.IsAny<EventTags>())) .Returns(new LogEvent("logx.optimizely.com/track", OptimizelyHelper.SingleParameter, "POST", new Dictionary<string, string> { })); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("EventBuilder", EventBuilderMock.Object); optly.Invoke("Track", "purchase", "test_user", OptimizelyHelper.NullUserAttributes, new EventTags { { "revenue", 42 }, { "wont_send_null", null} }); LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Exactly(21)); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "User \"test_user\" is not in the forced variation map."), Times.Exactly(3)); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Assigned bucket [3037] to user [test_user] with bucketing ID [test_user].")); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User [test_user] is in variation [control] of experiment [test_experiment].")); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "This decision will not be saved since the UserProfileService is null.")); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Assigned bucket [4517] to user [test_user] with bucketing ID [test_user].")); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User [test_user] is not in experiment [group_experiment_1] of group [7722400015].")); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Assigned bucket [4517] to user [test_user] with bucketing ID [test_user].")); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User [test_user] is in experiment [group_experiment_2] of group [7722400015].")); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Assigned bucket [9871] to user [test_user] with bucketing ID [test_user].")); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User [test_user] is in variation [group_exp_2_var_2] of experiment [group_experiment_2].")); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "This decision will not be saved since the UserProfileService is null.")); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Experiment \"paused_experiment\" is not running.")); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Not tracking user \"test_user\" for experiment \"paused_experiment\"")); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "[UserAttributes] Null value for key null_value removed and will not be sent to results.")); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "[UserAttributes] Null value for key wont_be_sent removed and will not be sent to results.")); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "[UserAttributes] Null value for key bad_food removed and will not be sent to results.")); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "[EventTags] Null value for key wont_send_null removed and will not be sent to results.")); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Tracking event purchase for user test_user.")); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Dispatching conversion event to URL logx.optimizely.com/track with params {\"param1\":\"val1\"}.")); } #endregion #region Test Invalid Dispatch [Test] public void TestInvalidDispatchImpressionEvent() { EventBuilderMock.Setup(b => b.CreateImpressionEvent(It.IsAny<ProjectConfig>(), It.IsAny<Experiment>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Entity.UserAttributes>())) .Returns(new LogEvent("logx.optimizely.com/decision", OptimizelyHelper.SingleParameter, "POST", new Dictionary<string, string> { })); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("EventBuilder", EventBuilderMock.Object); optly.SetFieldOrProperty("EventDispatcher", new InvalidEventDispatcher()); var variation = (Variation)optly.Invoke("Activate", "test_experiment", "test_user", OptimizelyHelper.UserAttributes); LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Exactly(7)); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Assigned bucket [3037] to user [test_user] with bucketing ID [test_user]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User [test_user] is in variation [control] of experiment [test_experiment]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Activating user test_user in experiment test_experiment."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, @"Dispatching impression event to URL logx.optimizely.com/decision with params {""param1"":""val1""}."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Unable to dispatch impression event. Error Invalid dispatch event"), Times.Once); Assert.IsTrue(TestData.CompareObjects(VariationWithKeyControl, variation)); } [Test] public void TestInvalidDispatchConversionEvent() { EventBuilderMock.Setup(b => b.CreateConversionEvent(It.IsAny<ProjectConfig>(), It.IsAny<string>(), It.IsAny<Dictionary<string, Variation>>(), It.IsAny<string>(), It.IsAny<UserAttributes>(), It.IsAny<EventTags>())) .Returns(new LogEvent("logx.optimizely.com/track", OptimizelyHelper.SingleParameter, "POST", new Dictionary<string, string> { })); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("EventBuilder", EventBuilderMock.Object); optly.SetFieldOrProperty("EventDispatcher", new InvalidEventDispatcher()); optly.Invoke("Track", "purchase", "test_user", null, null); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User \"test_user\" does not meet conditions to be in experiment \"test_experiment\"."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Not tracking user \"test_user\" for experiment \"test_experiment\""), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Experiment \"paused_experiment\" is not running."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Not tracking user \"test_user\" for experiment \"paused_experiment\""), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Tracking event purchase for user test_user."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Dispatching conversion event to URL logx.optimizely.com/track with params {\"param1\":\"val1\"}."), Times.Once); } #endregion #region Test Misc /* Start 1 */ public void TestTrackNoAttributesWithInvalidEventValue() { EventBuilderMock.Setup(b => b.CreateConversionEvent(It.IsAny<ProjectConfig>(), It.IsAny<string>(), It.IsAny<Dictionary<string, Variation>>(), It.IsAny<string>(), It.IsAny<UserAttributes>(), It.IsAny<EventTags>())) .Returns(new LogEvent("logx.optimizely.com/track", OptimizelyHelper.SingleParameter, "POST", new Dictionary<string, string> { })); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("EventBuilder", EventBuilderMock.Object); optly.SetFieldOrProperty("EventDispatcher", new ValidEventDispatcher()); optly.Invoke("Track", "purchase", "test_user", null, new Dictionary<string, object> { {"revenue", 4200 } }); } public void TestTrackNoAttributesWithDeprecatedEventValue() { /* Note: This case is not applicable, C# only accepts what the datatype we provide. * In this case, int value can't be casted implicitly into Dictionary */ EventBuilderMock.Setup(b => b.CreateConversionEvent(It.IsAny<ProjectConfig>(), It.IsAny<string>(), It.IsAny<Dictionary<string, Variation>>(), It.IsAny<string>(), It.IsAny<UserAttributes>(), It.IsAny<EventTags>())) .Returns(new LogEvent("logx.optimizely.com/track", OptimizelyHelper.SingleParameter, "POST", new Dictionary<string, string> { })); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("EventBuilder", EventBuilderMock.Object); optly.SetFieldOrProperty("EventDispatcher", new ValidEventDispatcher()); optly.Invoke("Track", "purchase", "test_user", null, new Dictionary<string, object> { {"revenue", 42 } }); } [Test] public void TestForcedVariationPreceedsWhitelistedVariation() { var optimizely = new Optimizely(TestData.Datafile, EventDispatcher, LoggerMock.Object, ErrorHandlerMock.Object); var projectConfig = ProjectConfig.Create(TestData.Datafile, LoggerMock.Object, ErrorHandlerMock.Object); Variation expectedVariation1 = projectConfig.GetVariationFromKey("etag3", "vtag5"); Variation expectedVariation2 = projectConfig.GetVariationFromKey("etag3", "vtag6"); //Check whitelisted experiment var variation = optimizely.GetVariation("etag3", "testUser1"); Assert.IsTrue(TestData.CompareObjects(expectedVariation1, variation)); //Set forced variation Assert.IsTrue(optimizely.SetForcedVariation("etag3", "testUser1", "vtag6")); variation = optimizely.GetVariation("etag3", "testUser1"); // verify forced variation preceeds whitelisted variation Assert.IsTrue(TestData.CompareObjects(expectedVariation2, variation)); // remove forced variation and verify whitelisted should be returned. Assert.IsTrue(optimizely.SetForcedVariation("etag3", "testUser1", null)); variation = optimizely.GetVariation("etag3", "testUser1"); Assert.IsTrue(TestData.CompareObjects(expectedVariation1, variation)); LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Exactly(7)); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "User \"testUser1\" is not in the forced variation map."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User \"testUser1\" is forced in variation \"vtag5\"."), Times.Exactly(2)); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Set variation \"281\" for experiment \"224\" and user \"testUser1\" in the forced variation map."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Variation \"vtag6\" is mapped to experiment \"etag3\" and user \"testUser1\" in the forced variation map"), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Variation mapped to experiment \"etag3\" has been removed for user \"testUser1\"."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "No experiment \"etag3\" mapped to user \"testUser1\" in the forced variation map."), Times.Once); } [Test] public void TestForcedVariationPreceedsUserProfile() { var userProfileServiceMock = new Mock<UserProfileService>(); var experimentKey = "etag1"; var userId = "testUser3"; var variationKey = "vtag2"; var fbVariationKey = "vtag1"; UserProfile userProfile = new UserProfile(userId, new Dictionary<string, Decision> { { experimentKey, new Decision(variationKey)} }); userProfileServiceMock.Setup(_ => _.Lookup(userId)).Returns(userProfile.ToMap()); var optimizely = new Optimizely(TestData.Datafile, EventDispatcher, LoggerMock.Object, ErrorHandlerMock.Object, userProfileServiceMock.Object); var projectConfig = ProjectConfig.Create(TestData.Datafile, LoggerMock.Object, ErrorHandlerMock.Object); Variation expectedFbVariation = projectConfig.GetVariationFromKey(experimentKey, fbVariationKey); Variation expectedVariation = projectConfig.GetVariationFromKey(experimentKey, variationKey); var variationUserProfile = optimizely.GetVariation(experimentKey, userId); Assert.IsTrue(TestData.CompareObjects(expectedVariation, variationUserProfile)); //assign same user with different variation, forced variation have higher priority Assert.IsTrue(optimizely.SetForcedVariation(experimentKey, userId, fbVariationKey)); var variation2 = optimizely.GetVariation(experimentKey, userId); Assert.IsTrue(TestData.CompareObjects(expectedFbVariation, variation2)); //remove forced variation and re-check userprofile Assert.IsTrue(optimizely.SetForcedVariation(experimentKey, userId, null)); variationUserProfile = optimizely.GetVariation(experimentKey, userId); Assert.IsTrue(TestData.CompareObjects(expectedVariation, variationUserProfile)); LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Exactly(13)); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "User \"testUser3\" is not in the forced variation map."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "No previously activated variation of experiment \"etag1\" for user \"testUser3\" found in user profile."), Times.Exactly(2)); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Assigned bucket [4969] to user [testUser3] with bucketing ID [testUser3]."), Times.Exactly(2)); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User [testUser3] is in variation [vtag2] of experiment [etag1]."), Times.Exactly(2)); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Saved variation \"277\" of experiment \"223\" for user \"testUser3\"."), Times.Exactly(2)); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Set variation \"276\" for experiment \"223\" and user \"testUser3\" in the forced variation map."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Variation mapped to experiment \"etag1\" has been removed for user \"testUser3\"."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "No experiment \"etag1\" mapped to user \"testUser3\" in the forced variation map."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "User \"testUser3\" is not in the forced variation map."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "User \"testUser3\" is not in the forced variation map."), Times.Once); } // check that a null variation key clears the forced variation [Test] public void TestSetForcedVariationNullVariation() { var expectedForcedVariationKey = "variation"; var experimentKey = "test_experiment"; var userAttributes = new UserAttributes { {"device_type", "iPhone" }, {"location", "San Francisco" } }; Optimizely.Activate(experimentKey, TestUserId, userAttributes); // set variation Assert.IsTrue(Optimizely.SetForcedVariation(experimentKey, TestUserId, expectedForcedVariationKey), "Set forced variation to variation failed."); var actualForcedVariation = Optimizely.GetVariation(experimentKey, TestUserId, userAttributes); Assert.IsTrue(TestData.CompareObjects(VariationWithKeyVariation, actualForcedVariation), string.Format(@"Forced variation key should be variation, but got ""{0}"".", actualForcedVariation?.Key)); // clear variation and check that the user gets bucketed normally Assert.IsTrue(Optimizely.SetForcedVariation(experimentKey, TestUserId, null), "Clear forced variation failed."); var actualVariation = Optimizely.GetVariation("test_experiment", "test_user", userAttributes); Assert.IsTrue(TestData.CompareObjects(VariationWithKeyControl, actualVariation), string.Format(@"Variation key should be control, but got ""{0}"".", actualVariation?.Key)); } // check that the forced variation is set correctly [Test] public void TestSetForcedVariation() { var experimentKey = "test_experiment"; var expectedForcedVariationKey = "variation"; var userAttributes = new UserAttributes { {"device_type", "iPhone" }, {"location", "San Francisco" } }; Optimizely.Activate(experimentKey, TestUserId, userAttributes); // test invalid experiment -. normal bucketing should occur Assert.IsFalse(Optimizely.SetForcedVariation("bad_experiment", TestUserId, "bad_control"), "Set variation to 'variation' should have failed because of invalid experiment."); var variation = Optimizely.GetVariation(experimentKey, TestUserId, userAttributes); Assert.IsTrue(TestData.CompareObjects(VariationWithKeyControl, variation)); // test invalid variation -. normal bucketing should occur Assert.IsFalse(Optimizely.SetForcedVariation("test_experiment", TestUserId, "bad_variation"), "Set variation to 'bad_variation' should have failed."); variation = Optimizely.GetVariation("test_experiment", "test_user", userAttributes); Assert.IsTrue(TestData.CompareObjects(VariationWithKeyControl, variation)); // test valid variation -. the user should be bucketed to the specified forced variation Assert.IsTrue(Optimizely.SetForcedVariation(experimentKey, TestUserId, expectedForcedVariationKey), "Set variation to 'variation' failed."); var actualForcedVariation = Optimizely.GetVariation(experimentKey, TestUserId, userAttributes); Assert.IsTrue(TestData.CompareObjects(VariationWithKeyVariation, actualForcedVariation)); // make sure another setForcedVariation call sets a new forced variation correctly Assert.IsTrue(Optimizely.SetForcedVariation(experimentKey, "test_user2", expectedForcedVariationKey), "Set variation to 'variation' failed."); actualForcedVariation = Optimizely.GetVariation(experimentKey, "test_user2", userAttributes); Assert.IsTrue(TestData.CompareObjects(VariationWithKeyVariation, actualForcedVariation)); } // check that the get forced variation is correct. [Test] public void TestGetForcedVariation() { var experimentKey = "test_experiment"; var expectedForcedVariation = new Variation { Key = "variation", Id = "7721010009" }; var expectedForcedVariation2 = new Variation { Key = "variation", Id = "7721010509" }; var userAttributes = new UserAttributes { {"device_type", "iPhone" }, {"location", "San Francisco" } }; Optimizely.Activate(experimentKey, TestUserId, userAttributes); Assert.IsTrue(Optimizely.SetForcedVariation(experimentKey, TestUserId, expectedForcedVariation.Key), "Set variation to 'variation' failed."); // call getForcedVariation with valid experiment key and valid user ID var actualForcedVariation = Optimizely.GetForcedVariation("test_experiment", TestUserId); Assert.IsTrue(TestData.CompareObjects(expectedForcedVariation, actualForcedVariation)); // call getForcedVariation with invalid experiment and valid userID actualForcedVariation = Optimizely.GetForcedVariation("invalid_experiment", TestUserId); Assert.Null(actualForcedVariation); // call getForcedVariation with valid experiment and invalid userID actualForcedVariation = Optimizely.GetForcedVariation("test_experiment", "invalid_user"); Assert.Null(actualForcedVariation); // call getForcedVariation with an experiment that"s not running Assert.IsTrue(Optimizely.SetForcedVariation("paused_experiment", "test_user2", "variation"), "Set variation to 'variation' failed."); actualForcedVariation = Optimizely.GetForcedVariation("paused_experiment", "test_user2"); Assert.IsTrue(TestData.CompareObjects(expectedForcedVariation2, actualForcedVariation)); // confirm that the second setForcedVariation call did not invalidate the first call to that method actualForcedVariation = Optimizely.GetForcedVariation("test_experiment", TestUserId); Assert.IsTrue(TestData.CompareObjects(expectedForcedVariation, actualForcedVariation)); } [Test] public void TestGetVariationAudienceMatchAfterSetForcedVariation() { var userId = "test_user"; var experimentKey = "test_experiment"; var experimentId = "7716830082"; var variationKey = "control"; var variationId = "7722370027"; var attributes = new UserAttributes { { "device_type", "iPhone" }, { "location", "San Francisco" } }; Assert.True(Optimizely.SetForcedVariation(experimentKey, userId, variationKey), "Set variation for paused experiment should have failed."); var variation = Optimizely.GetVariation(experimentKey, userId, attributes); LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Exactly(2)); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, string.Format(@"Set variation ""{0}"" for experiment ""{1}"" and user ""{2}"" in the forced variation map.", variationId, experimentId, userId))); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, string.Format(@"Variation ""{0}"" is mapped to experiment ""{1}"" and user ""{2}"" in the forced variation map", variationKey, experimentKey, userId))); Assert.IsTrue(TestData.CompareObjects(VariationWithKeyControl, variation)); } [Test] public void TestGetVariationExperimentNotRunningAfterSetForceVariation() { var userId = "test_user"; var experimentKey = "paused_experiment"; var experimentId = "7716830585"; var variationKey = "control"; var variationId = "7722370427"; var attributes = new UserAttributes { { "device_type", "iPhone" }, { "location", "San Francisco" } }; Assert.True(Optimizely.SetForcedVariation(experimentKey, userId, variationKey), "Set variation for paused experiment should have failed."); var variation = Optimizely.GetVariation(experimentKey, userId, attributes); LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Exactly(2)); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, string.Format(@"Set variation ""{0}"" for experiment ""{1}"" and user ""{2}"" in the forced variation map.", variationId, experimentId, userId))); LoggerMock.Verify(l => l.Log(LogLevel.INFO, string.Format("Experiment \"{0}\" is not running.", experimentKey))); Assert.Null(variation); } [Test] public void TestGetVariationWhitelistedUserAfterSetForcedVariation() { var userId = "user1"; var experimentKey = "test_experiment"; var experimentId = "7716830082"; var variationKey = "variation"; var variationId = "7721010009"; Assert.True(Optimizely.SetForcedVariation(experimentKey, userId, variationKey), "Set variation for paused experiment should have passed."); var variation = Optimizely.GetVariation(experimentKey, userId); LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Exactly(2)); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, string.Format(@"Set variation ""{0}"" for experiment ""{1}"" and user ""{2}"" in the forced variation map.", variationId, experimentId, userId))); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, string.Format(@"Variation ""{0}"" is mapped to experiment ""{1}"" and user ""{2}"" in the forced variation map", variationKey, experimentKey, userId))); Assert.IsTrue(TestData.CompareObjects(VariationWithKeyVariation, variation)); } [Test] public void TestActivateNoAudienceNoAttributesAfterSetForcedVariation() { var userId = "test_user"; var experimentKey = "test_experiment"; var experimentId = "7716830082"; var variationKey = "control"; var variationId = "7722370027"; var parameters = new Dictionary<string, object> { { "param1", "val1" }, { "param2", "val2" } }; Experiment experiment = new Experiment(); experiment.Key = "group_experiment_1"; EventBuilderMock.Setup(b => b.CreateImpressionEvent(Config, It.IsAny<Experiment>(), It.IsAny <string>()/*"group_exp_1_var_2"*/, "user_1", null)) .Returns(new LogEvent("logx.optimizely.com/decision", parameters, "POST", new Dictionary<string, string> { })); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("EventBuilder", EventBuilderMock.Object); optly.SetFieldOrProperty("Config", Config); // Set forced variation Assert.True((bool)optly.Invoke("SetForcedVariation", experimentKey, userId, variationKey), "Set variation for paused experiment should have failed."); // Activate var variation = (Variation)optly.Invoke("Activate", "group_experiment_1", "user_1", null); EventBuilderMock.Verify(b => b.CreateImpressionEvent(It.IsAny<ProjectConfig>(), Config.GetExperimentFromKey("group_experiment_1"), "7722360022", "user_1", null), Times.Once); LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Exactly(9)); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, string.Format(@"Set variation ""{0}"" for experiment ""{1}"" and user ""{2}"" in the forced variation map.", variationId, experimentId, userId)), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "User \"user_1\" is not in the forced variation map."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Assigned bucket [1922] to user [user_1] with bucketing ID [user_1]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User [user_1] is in experiment [group_experiment_1] of group [7722400015]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Assigned bucket [9525] to user [user_1] with bucketing ID [user_1]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User [user_1] is in variation [group_exp_1_var_2] of experiment [group_experiment_1]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "This decision will not be saved since the UserProfileService is null."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Activating user user_1 in experiment group_experiment_1."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, @"Dispatching impression event to URL logx.optimizely.com/decision with params {""param1"":""val1"",""param2"":""val2""}."), Times.Once); Assert.IsTrue(TestData.CompareObjects(GroupVariation, variation)); } [Test] public void TestTrackNoAttributesNoEventValueAfterSetForcedVariation() { var userId = "test_user"; var experimentKey = "test_experiment"; var experimentId = "7716830082"; var variationKey = "control"; var variationId = "7722370027"; var parameters = new Dictionary<string, object> { { "param1", "val1" } }; EventBuilderMock.Setup(b => b.CreateConversionEvent(It.IsAny<ProjectConfig>(), It.IsAny<string>(), It.IsAny<Dictionary<string, Variation>>(), It.IsAny<string>(), It.IsAny<UserAttributes>(), It.IsAny<EventTags>())) .Returns(new LogEvent("logx.optimizely.com/track", parameters, "POST", new Dictionary<string, string> { })); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("EventBuilder", EventBuilderMock.Object); // Set forced variation Assert.True((bool)optly.Invoke("SetForcedVariation", experimentKey, userId, variationKey), "Set variation for paused experiment should have failed."); // Track optly.Invoke("Track", "purchase", "test_user", null, null); LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Exactly(15)); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, string.Format(@"Set variation ""{0}"" for experiment ""{1}"" and user ""{2}"" in the forced variation map.", variationId, experimentId, userId)), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Variation \"control\" is mapped to experiment \"test_experiment\" and user \"test_user\" in the forced variation map"), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "No experiment \"group_experiment_1\" mapped to user \"test_user\" in the forced variation map."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Assigned bucket [4517] to user [test_user] with bucketing ID [test_user]."), Times.Exactly(2)); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User [test_user] is not in experiment [group_experiment_1] of group [7722400015]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "No experiment \"group_experiment_2\" mapped to user \"test_user\" in the forced variation map."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Assigned bucket [4517] to user [test_user] with bucketing ID [test_user]."), Times.Exactly(2)); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User [test_user] is in experiment [group_experiment_2] of group [7722400015]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Assigned bucket [9871] to user [test_user] with bucketing ID [test_user]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User [test_user] is in variation [group_exp_2_var_2] of experiment [group_experiment_2]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "This decision will not be saved since the UserProfileService is null."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Experiment \"paused_experiment\" is not running."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Not tracking user \"test_user\" for experiment \"paused_experiment\""), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Tracking event purchase for user test_user."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Dispatching conversion event to URL logx.optimizely.com/track with params {\"param1\":\"val1\"}."), Times.Once); } [Test] public void TestGetVariationBucketingIdAttribute() { var testBucketingIdControl = "testBucketingIdControl!"; // generates bucketing number 3741 var testBucketingIdVariation = "123456789"; // generates bucketing number 4567 var userId = "test_user"; var experimentKey = "test_experiment"; var userAttributes = new UserAttributes { { "device_type", "iPhone" }, { "company", "Optimizely" }, { "location", "San Francisco" } }; var userAttributesWithBucketingId = new UserAttributes { { "device_type", "iPhone" }, { "company", "Optimizely" }, { "location", "San Francisco" }, { ControlAttributes.BUCKETING_ID_ATTRIBUTE, testBucketingIdVariation } }; // confirm that a valid variation is bucketed without the bucketing ID var actualVariation = Optimizely.GetVariation(experimentKey, userId, userAttributes); Assert.IsTrue(TestData.CompareObjects(VariationWithKeyControl, actualVariation), string.Format("Invalid variation key \"{0}\" for getVariation.", actualVariation?.Key)); // confirm that invalid audience returns null actualVariation = Optimizely.GetVariation(experimentKey, userId); Assert.Null(actualVariation, string.Format("Invalid variation key \"{0}\" for getVariation with bucketing ID \"{1}\".", actualVariation?.Key, testBucketingIdControl)); // confirm that a valid variation is bucketed with the bucketing ID actualVariation = Optimizely.GetVariation(experimentKey, userId, userAttributesWithBucketingId); Assert.IsTrue(TestData.CompareObjects(VariationWithKeyVariation, actualVariation), string.Format("Invalid variation key \"{0}\" for getVariation with bucketing ID \"{1}\".", actualVariation?.Key, testBucketingIdVariation)); // confirm that invalid experiment with the bucketing ID returns null actualVariation = Optimizely.GetVariation("invalidExperimentKey", userId, userAttributesWithBucketingId); Assert.Null(actualVariation, string.Format("Invalid variation key \"{0}\" for getVariation with bucketing ID \"{1}\".", actualVariation?.Key, testBucketingIdControl)); } #endregion #region Test GetFeatureVariable<Type> Typecasting [Test] public void TestGetFeatureVariableBooleanReturnTypecastedValue() { var featureKey = "featureKey"; var variableKeyTrue = "varTrue"; var variableKeyFalse = "varFalse"; var variableKeyNonBoolean = "varNonBoolean"; var variableKeyNull = "varNull"; var featureVariableType = FeatureVariable.VariableType.BOOLEAN; OptimizelyMock.Setup(om => om.GetFeatureVariableValueForType(It.IsAny<string>(), variableKeyTrue, It.IsAny<string>(), It.IsAny<UserAttributes>(), featureVariableType)).Returns("True"); Assert.AreEqual(true, OptimizelyMock.Object.GetFeatureVariableBoolean(featureKey, variableKeyTrue, TestUserId, null)); OptimizelyMock.Setup(om => om.GetFeatureVariableValueForType(It.IsAny<string>(), variableKeyFalse, It.IsAny<string>(), It.IsAny<UserAttributes>(), featureVariableType)).Returns("false"); Assert.AreEqual(false, OptimizelyMock.Object.GetFeatureVariableBoolean(featureKey, variableKeyFalse, TestUserId, null)); OptimizelyMock.Setup(om => om.GetFeatureVariableValueForType(It.IsAny<string>(), variableKeyNonBoolean, It.IsAny<string>(), It.IsAny<UserAttributes>(), featureVariableType)).Returns("non_boolean_value"); Assert.Null(OptimizelyMock.Object.GetFeatureVariableBoolean(featureKey, variableKeyNonBoolean, TestUserId, null)); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, $@"Unable to cast variable value ""non_boolean_value"" to type ""{featureVariableType}"".")); OptimizelyMock.Setup(om => om.GetFeatureVariableValueForType(It.IsAny<string>(), variableKeyNull, It.IsAny<string>(), It.IsAny<UserAttributes>(), featureVariableType)).Returns<string>(null); Assert.Null(OptimizelyMock.Object.GetFeatureVariableBoolean(featureKey, variableKeyNull, TestUserId, null)); } [Test] public void TestGetFeatureVariableDoubleReturnTypecastedValue() { var featureKey = "featureKey"; var variableKeyDouble = "varDouble"; var variableKeyInt = "varInt"; var variableKeyNonDouble = "varNonDouble"; var variableKeyNull = "varNull"; var featureVariableType = FeatureVariable.VariableType.DOUBLE; OptimizelyMock.Setup(om => om.GetFeatureVariableValueForType(It.IsAny<string>(), variableKeyDouble, It.IsAny<string>(), It.IsAny<UserAttributes>(), featureVariableType)).Returns("100.54"); Assert.AreEqual(100.54, OptimizelyMock.Object.GetFeatureVariableDouble(featureKey, variableKeyDouble, TestUserId, null)); OptimizelyMock.Setup(om => om.GetFeatureVariableValueForType(It.IsAny<string>(), variableKeyInt, It.IsAny<string>(), It.IsAny<UserAttributes>(), featureVariableType)).Returns("100"); Assert.AreEqual(100, OptimizelyMock.Object.GetFeatureVariableDouble(featureKey, variableKeyInt, TestUserId, null)); OptimizelyMock.Setup(om => om.GetFeatureVariableValueForType(It.IsAny<string>(), variableKeyNonDouble, It.IsAny<string>(), It.IsAny<UserAttributes>(), featureVariableType)).Returns("non_double_value"); Assert.Null(OptimizelyMock.Object.GetFeatureVariableDouble(featureKey, variableKeyNonDouble, TestUserId, null)); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, $@"Unable to cast variable value ""non_double_value"" to type ""{featureVariableType}"".")); OptimizelyMock.Setup(om => om.GetFeatureVariableValueForType(It.IsAny<string>(), variableKeyNull, It.IsAny<string>(), It.IsAny<UserAttributes>(), featureVariableType)).Returns<string>(null); Assert.Null(OptimizelyMock.Object.GetFeatureVariableDouble(featureKey, variableKeyNull, TestUserId, null)); } [Test] public void TestGetFeatureVariableIntegerReturnTypecastedValue() { var featureKey = "featureKey"; var variableKeyInt = "varInt"; var variableKeyDouble = "varDouble"; var variableNonInt = "varNonInt"; var variableKeyNull = "varNull"; var featureVariableType = FeatureVariable.VariableType.INTEGER; OptimizelyMock.Setup(om => om.GetFeatureVariableValueForType(It.IsAny<string>(), variableKeyInt, It.IsAny<string>(), It.IsAny<UserAttributes>(), featureVariableType)).Returns("100"); Assert.AreEqual(100, OptimizelyMock.Object.GetFeatureVariableInteger(featureKey, variableKeyInt, TestUserId, null)); OptimizelyMock.Setup(om => om.GetFeatureVariableValueForType(It.IsAny<string>(), variableKeyDouble, It.IsAny<string>(), It.IsAny<UserAttributes>(), featureVariableType)).Returns("100.45"); Assert.Null(OptimizelyMock.Object.GetFeatureVariableInteger(featureKey, variableKeyDouble, TestUserId, null)); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, $@"Unable to cast variable value ""100.45"" to type ""{featureVariableType}"".")); OptimizelyMock.Setup(om => om.GetFeatureVariableValueForType(It.IsAny<string>(), variableNonInt, It.IsAny<string>(), It.IsAny<UserAttributes>(), featureVariableType)).Returns("non_integer_value"); Assert.Null(OptimizelyMock.Object.GetFeatureVariableInteger(featureKey, variableNonInt, TestUserId, null)); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, $@"Unable to cast variable value ""non_integer_value"" to type ""{featureVariableType}"".")); OptimizelyMock.Setup(om => om.GetFeatureVariableValueForType(It.IsAny<string>(), variableKeyNull, It.IsAny<string>(), It.IsAny<UserAttributes>(), featureVariableType)).Returns<string>(null); Assert.Null(OptimizelyMock.Object.GetFeatureVariableInteger(featureKey, variableKeyNull, TestUserId, null)); } [Test] public void TestGetFeatureVariableStringReturnTypecastedValue() { var featureKey = "featureKey"; var variableKeyString = "varString1"; var variableKeyIntString = "varString2"; var variableKeyNull = "varNull"; var featureVariableType = FeatureVariable.VariableType.STRING; OptimizelyMock.Setup(om => om.GetFeatureVariableValueForType(It.IsAny<string>(), variableKeyString, It.IsAny<string>(), It.IsAny<UserAttributes>(), featureVariableType)).Returns("Test String"); Assert.AreEqual("Test String", OptimizelyMock.Object.GetFeatureVariableString(featureKey, variableKeyString, TestUserId, null)); OptimizelyMock.Setup(om => om.GetFeatureVariableValueForType(It.IsAny<string>(), variableKeyIntString, It.IsAny<string>(), It.IsAny<UserAttributes>(), featureVariableType)).Returns("123"); Assert.AreEqual("123", OptimizelyMock.Object.GetFeatureVariableString(featureKey, variableKeyIntString, TestUserId, null)); OptimizelyMock.Setup(om => om.GetFeatureVariableValueForType(It.IsAny<string>(), variableKeyNull, It.IsAny<string>(), It.IsAny<UserAttributes>(), featureVariableType)).Returns<string>(null); Assert.Null(OptimizelyMock.Object.GetFeatureVariableString(featureKey, variableKeyNull, TestUserId, null)); } #endregion // Test GetFeatureVariable<Type> TypeCasting #region Test GetFeatureVariableValueForType method // Should return null and log error message when arguments are null or empty. [Test] public void TestGetFeatureVariableValueForTypeGivenNullOrEmptyArguments() { var featureKey = "featureKey"; var variableKey = "variableKey"; var variableType = FeatureVariable.VariableType.BOOLEAN; // Passing null and empty feature key. Assert.IsNull(Optimizely.GetFeatureVariableValueForType(null, variableKey, TestUserId, null, variableType)); Assert.IsNull(Optimizely.GetFeatureVariableValueForType("", variableKey, TestUserId, null, variableType)); // Passing null and empty variable key. Assert.IsNull(Optimizely.GetFeatureVariableValueForType(featureKey, null, TestUserId, null, variableType)); Assert.IsNull(Optimizely.GetFeatureVariableValueForType(featureKey, "", TestUserId, null, variableType)); // Passing null and empty user Id. Assert.IsNull(Optimizely.GetFeatureVariableValueForType(featureKey, variableKey, null, null, variableType)); Assert.IsNull(Optimizely.GetFeatureVariableValueForType(featureKey, variableKey, "", null, variableType)); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Feature flag key must not be empty."), Times.Exactly(2)); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Variable key must not be empty."), Times.Exactly(2)); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "User ID must not be empty."), Times.Exactly(2)); } // Should return null and log error message when feature key or variable key does not get found. [Test] public void TestGetFeatureVariableValueForTypeGivenFeatureKeyOrVariableKeyNotFound() { var featureKey = "this_feature_should_never_be_found_in_the_datafile_unless_the_datafile_creator_got_insane"; var variableKey = "this_variable_should_never_be_found_in_the_datafile_unless_the_datafile_creator_got_insane"; var variableType = FeatureVariable.VariableType.BOOLEAN; Assert.IsNull(Optimizely.GetFeatureVariableValueForType(featureKey, variableKey, TestUserId, null, variableType)); Assert.IsNull(Optimizely.GetFeatureVariableValueForType("double_single_variable_feature", variableKey, TestUserId, null, variableType)); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, $@"Feature key ""{featureKey}"" is not in datafile.")); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, $@"No feature variable was found for key ""{variableKey}"" in feature flag ""double_single_variable_feature"".")); } // Should return null and log error message when variable type is invalid. [Test] public void TestGetFeatureVariableValueForTypeGivenInvalidVariableType() { var variableTypeBool = FeatureVariable.VariableType.BOOLEAN; var variableTypeInt = FeatureVariable.VariableType.INTEGER; var variableTypeDouble = FeatureVariable.VariableType.DOUBLE; var variableTypeString = FeatureVariable.VariableType.STRING; Assert.IsNull(Optimizely.GetFeatureVariableValueForType("double_single_variable_feature", "double_variable", TestUserId, null, variableTypeBool)); Assert.IsNull(Optimizely.GetFeatureVariableValueForType("boolean_single_variable_feature", "boolean_variable", TestUserId, null, variableTypeDouble)); Assert.IsNull(Optimizely.GetFeatureVariableValueForType("integer_single_variable_feature", "integer_variable", TestUserId, null, variableTypeString)); Assert.IsNull(Optimizely.GetFeatureVariableValueForType("string_single_variable_feature", "string_variable", TestUserId, null, variableTypeInt)); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, $@"Variable is of type ""DOUBLE"", but you requested it as type ""{variableTypeBool}"".")); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, $@"Variable is of type ""BOOLEAN"", but you requested it as type ""{variableTypeDouble}"".")); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, $@"Variable is of type ""INTEGER"", but you requested it as type ""{variableTypeString}"".")); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, $@"Variable is of type ""STRING"", but you requested it as type ""{variableTypeInt}"".")); } // Should return default value and log message when feature is not enabled for the user. [Test] public void TestGetFeatureVariableValueForTypeGivenFeatureFlagIsNotEnabledForUser() { var featureKey = "double_single_variable_feature"; var featureFlag = Config.GetFeatureFlagFromKey("double_single_variable_feature"); var variableKey = "double_variable"; var variableType = FeatureVariable.VariableType.DOUBLE; var expectedValue = "14.99"; DecisionServiceMock.Setup(ds => ds.GetVariationForFeature(featureFlag, TestUserId, null)).Returns<FeatureDecision>(null); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("DecisionService", DecisionServiceMock.Object); string variableValue = (string)optly.Invoke("GetFeatureVariableValueForType", featureKey, variableKey, TestUserId, null, variableType); Assert.AreEqual(expectedValue, variableValue); LoggerMock.Verify(l => l.Log(LogLevel.INFO, $@"User ""{TestUserId}"" is not in any variation for feature flag ""{featureKey}"", returning default value ""{variableValue}"".")); } // Should return default value and log message when feature is enabled for the user // but variable usage does not get found for the variation. [Test] public void TestGetFeatureVariableValueForTypeGivenFeatureFlagIsEnabledForUserAndVaribaleNotInVariation() { var featureKey = "double_single_variable_feature"; var featureFlag = Config.GetFeatureFlagFromKey("double_single_variable_feature"); var experiment = Config.GetExperimentFromKey("test_experiment_integer_feature"); var differentVariation = Config.GetVariationFromKey("test_experiment_integer_feature", "control"); var expectedDecision = new FeatureDecision(experiment, differentVariation, FeatureDecision.DECISION_SOURCE_EXPERIMENT); var variableKey = "double_variable"; var variableType = FeatureVariable.VariableType.DOUBLE; var expectedValue = "14.99"; // Mock GetVariationForFeature method to return variation of different feature. DecisionServiceMock.Setup(ds => ds.GetVariationForFeature(featureFlag, TestUserId, null)).Returns(expectedDecision); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("DecisionService", DecisionServiceMock.Object); string variableValue = (string)optly.Invoke("GetFeatureVariableValueForType", featureKey, variableKey, TestUserId, null, variableType); Assert.AreEqual(expectedValue, variableValue); LoggerMock.Verify(l => l.Log(LogLevel.INFO, $@"Variable ""{variableKey}"" is not used in variation ""control"", returning default value ""{expectedValue}"".")); } // Should return variable value from variation and log message when feature is enabled for the user // and variable usage has been found for the variation. [Test] public void TestGetFeatureVariableValueForTypeGivenFeatureFlagIsEnabledForUserAndVaribaleIsInVariation() { var featureKey = "double_single_variable_feature"; var featureFlag = Config.GetFeatureFlagFromKey("double_single_variable_feature"); var variableKey = "double_variable"; var variableType = FeatureVariable.VariableType.DOUBLE; var expectedValue = "42.42"; var experiment = Config.GetExperimentFromKey("test_experiment_double_feature"); var variation = Config.GetVariationFromKey("test_experiment_double_feature", "control"); var decision = new FeatureDecision(experiment, variation, FeatureDecision.DECISION_SOURCE_EXPERIMENT); DecisionServiceMock.Setup(ds => ds.GetVariationForFeature(featureFlag, TestUserId, null)).Returns(decision); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("DecisionService", DecisionServiceMock.Object); string variableValue = (string)optly.Invoke("GetFeatureVariableValueForType", featureKey, variableKey, TestUserId, null, variableType); Assert.AreEqual(expectedValue, variableValue); LoggerMock.Verify(l => l.Log(LogLevel.INFO, $@"Returning variable value ""{variableValue}"" for variation ""{variation.Key}"" of feature flag ""{featureKey}"".")); } // Verify that GetFeatureVariableValueForType returns correct variable value for rollout rule. [Test] public void TestGetFeatureVariableValueForTypeWithRolloutRule() { var featureKey = "boolean_single_variable_feature"; var featureFlag = Config.GetFeatureFlagFromKey(featureKey); var variableKey = "boolean_variable"; //experimentid - 177772 var experiment = Config.Rollouts[0].Experiments[1]; var variation = Config.GetVariationFromId(experiment.Key, "177773"); var decision = new FeatureDecision(experiment, variation, FeatureDecision.DECISION_SOURCE_ROLLOUT); var expectedVariableValue = false; DecisionServiceMock.Setup(ds => ds.GetVariationForFeature(featureFlag, TestUserId, null)).Returns(decision); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("DecisionService", DecisionServiceMock.Object); // Calling GetFeatureVariableBoolean to get GetFeatureVariableValueForType returned value casted in bool. var actualVariableValue = (bool?)optly.Invoke("GetFeatureVariableBoolean", featureKey, variableKey, TestUserId, null); // Verify that variable value 'false' has been returned from GetFeatureVariableValueForType as it is the value // stored in rollout rule '177772'. Assert.AreEqual(expectedVariableValue, actualVariableValue); } #endregion // Test GetFeatureVariableValueForType method #region Test IsFeatureEnabled method // Should return false and log error message when arguments are null or empty. [Test] public void TestIsFeatureEnabledGivenNullOrEmptyArguments() { var featureKey = "featureKey"; Assert.IsFalse(Optimizely.IsFeatureEnabled(featureKey, null, null)); Assert.IsFalse(Optimizely.IsFeatureEnabled(featureKey, "", null)); Assert.IsFalse(Optimizely.IsFeatureEnabled(null, TestUserId, null)); Assert.IsFalse(Optimizely.IsFeatureEnabled("", TestUserId, null)); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "User ID must not be empty."), Times.Exactly(2)); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Feature flag key must not be empty."), Times.Exactly(2)); } // Should return false and log error message when feature flag key is not found in the datafile. [Test] public void TestIsFeatureEnabledGivenFeatureFlagNotFound() { var featureKey = "feature_not_found"; Assert.IsFalse(Optimizely.IsFeatureEnabled(featureKey, TestUserId, null)); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, $@"Feature key ""{featureKey}"" is not in datafile.")); } // Should return false and log error message when arguments are null or empty. [Test] public void TestIsFeatureEnabledGivenFeatureFlagContainsInvalidExperiment() { var tempConfig = ProjectConfig.Create(TestData.Datafile, LoggerMock.Object, new NoOpErrorHandler()); var featureFlag = tempConfig.GetFeatureFlagFromKey("multi_variate_feature"); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("Config", tempConfig); // Set such an experiment to the list of experiment ids, that does not belong to the feature. featureFlag.ExperimentIds = new List<string> { "4209211" }; // Should return false when the experiment in feature flag does not get found in the datafile. Assert.False((bool)optly.Invoke("IsFeatureEnabled", "multi_variate_feature", TestUserId, null)); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, @"Experiment ID ""4209211"" is not in datafile.")); } // Should return false and log message when feature is not enabled for the user. [Test] public void TestIsFeatureEnabledGivenFeatureFlagIsNotEnabledForUser() { var featureKey = "double_single_variable_feature"; var featureFlag = Config.GetFeatureFlagFromKey("double_single_variable_feature"); DecisionServiceMock.Setup(ds => ds.GetVariationForFeature(featureFlag, TestUserId, null)).Returns<FeatureDecision>(null); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("DecisionService", DecisionServiceMock.Object); bool result = (bool)optly.Invoke("IsFeatureEnabled", featureKey, TestUserId, null); Assert.False(result); LoggerMock.Verify(l => l.Log(LogLevel.INFO, $@"Feature flag ""{featureKey}"" is not enabled for user ""{TestUserId}"".")); } // Should return true but does not send an impression event when feature is enabled for the user // but user does not get experimented. [Test] public void TestIsFeatureEnabledGivenFeatureFlagIsEnabledAndUserIsNotBeingExperimented() { var featureKey = "boolean_single_variable_feature"; var rollout = Config.GetRolloutFromId("166660"); var experiment = rollout.Experiments[0]; var variation = experiment.Variations[0]; var featureFlag = Config.GetFeatureFlagFromKey(featureKey); var decision = new FeatureDecision(experiment, variation, FeatureDecision.DECISION_SOURCE_ROLLOUT); DecisionServiceMock.Setup(ds => ds.GetVariationForFeature(featureFlag, TestUserId, null)).Returns(decision); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("DecisionService", DecisionServiceMock.Object); bool result = (bool)optly.Invoke("IsFeatureEnabled", featureKey, TestUserId, null); Assert.True(result); // SendImpressionEvent() does not get called. LoggerMock.Verify(l => l.Log(LogLevel.INFO, $@"The user ""{TestUserId}"" is not being experimented on feature ""{featureKey}""."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, $@"Feature flag ""{featureKey}"" is enabled for user ""{TestUserId}"".")); } // Should return true and send an impression event when feature is enabled for the user // and user is being experimented. [Test] public void TestIsFeatureEnabledGivenFeatureFlagIsEnabledAndUserIsBeingExperimented() { var featureKey = "double_single_variable_feature"; var experiment = Config.GetExperimentFromKey("test_experiment_double_feature"); var variation = Config.GetVariationFromKey("test_experiment_double_feature", "control"); var featureFlag = Config.GetFeatureFlagFromKey(featureKey); var decision = new FeatureDecision(experiment, variation, FeatureDecision.DECISION_SOURCE_EXPERIMENT); DecisionServiceMock.Setup(ds => ds.GetVariationForFeature(featureFlag, TestUserId, null)).Returns(decision); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("DecisionService", DecisionServiceMock.Object); bool result = (bool)optly.Invoke("IsFeatureEnabled", featureKey, TestUserId, null); Assert.True(result); // SendImpressionEvent() gets called. LoggerMock.Verify(l => l.Log(LogLevel.INFO, $@"The user ""{TestUserId}"" is not being experimented on feature ""{featureKey}""."), Times.Never); LoggerMock.Verify(l => l.Log(LogLevel.INFO, $@"Feature flag ""{featureKey}"" is enabled for user ""{TestUserId}"".")); } // Should return false and send an impression event when feature is enabled for the user // and user is being experimented. [Test] public void TestIsFeatureEnabledGivenFeatureFlagIsNotEnabledAndUserIsBeingExperimented() { var featureKey = "double_single_variable_feature"; var experiment = Config.GetExperimentFromKey("test_experiment_double_feature"); var variation = Config.GetVariationFromKey("test_experiment_double_feature", "variation"); var featureFlag = Config.GetFeatureFlagFromKey(featureKey); var decision = new FeatureDecision(experiment, variation, FeatureDecision.DECISION_SOURCE_EXPERIMENT); DecisionServiceMock.Setup(ds => ds.GetVariationForFeature(featureFlag, TestUserId, null)).Returns(decision); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("DecisionService", DecisionServiceMock.Object); bool result = (bool)optly.Invoke("IsFeatureEnabled", featureKey, TestUserId, null); Assert.False(result); // SendImpressionEvent() gets called. LoggerMock.Verify(l => l.Log(LogLevel.INFO, $@"The user ""{TestUserId}"" is not being experimented on feature ""{featureKey}""."), Times.Never); LoggerMock.Verify(l => l.Log(LogLevel.INFO, $@"Feature flag ""{featureKey}"" is not enabled for user ""{TestUserId}"".")); EventDispatcherMock.Verify(dispatcher => dispatcher.DispatchEvent(It.IsAny<LogEvent>())); } // Verify that IsFeatureEnabled returns true if a variation does not get found in the feature // flag experiment but found in the rollout rule. [Test] public void TestIsFeatureEnabledGivenVariationNotFoundInFeatureExperimentButInRolloutRule() { var featureKey = "boolean_single_variable_feature"; var userAttributes = new UserAttributes { { "device_type", "iPhone" }, { "company", "Optimizely" } }; Assert.True(Optimizely.IsFeatureEnabled(featureKey, TestUserId, userAttributes)); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "The feature flag \"boolean_single_variable_feature\" is not used in any experiments."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "User \"testUserId\" does not meet the conditions to be in rollout rule for audience \"Chrome users\"."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "User \"testUserId\" does not meet the conditions to be in rollout rule for audience \"iPhone users in San Francisco\"."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Assigned bucket [8408] to user [testUserId] with bucketing ID [testUserId]."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "The user \"testUserId\" is bucketed into a rollout for feature flag \"boolean_single_variable_feature\"."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "The user \"testUserId\" is not being experimented on feature \"boolean_single_variable_feature\"."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Feature flag \"boolean_single_variable_feature\" is enabled for user \"testUserId\"."), Times.Once); } public void TestIsFeatureEnabledWithFeatureEnabledPropertyGivenFeatureExperiment() { var userId = "testUserId2"; var featureKey = "double_single_variable_feature"; var experiment = Config.GetExperimentFromKey("test_experiment_double_feature"); var featureEnabledTrue = Config.GetVariationFromKey("test_experiment_double_feature", "control"); var featureEnabledFalse = Config.GetVariationFromKey("test_experiment_double_feature", "variation"); var featureFlag = Config.GetFeatureFlagFromKey(featureKey); var decisionTrue = new FeatureDecision(experiment, featureEnabledTrue, FeatureDecision.DECISION_SOURCE_EXPERIMENT); var decisionFalse = new FeatureDecision(experiment, featureEnabledFalse, FeatureDecision.DECISION_SOURCE_EXPERIMENT); DecisionServiceMock.Setup(ds => ds.GetVariationForFeature(featureFlag, TestUserId, null)).Returns(decisionTrue); DecisionServiceMock.Setup(ds => ds.GetVariationForFeature(featureFlag, userId, null)).Returns(decisionFalse); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("DecisionService", DecisionServiceMock.Object); // Verify that IsFeatureEnabled returns true when feature experiment variation's 'featureEnabled' property is true. bool result = (bool)optly.Invoke("IsFeatureEnabled", featureKey, TestUserId, null); Assert.True(result); // Verify that IsFeatureEnabled returns false when feature experiment variation's 'featureEnabled' property is false. result = (bool)optly.Invoke("IsFeatureEnabled", featureKey, userId, null); Assert.False(result); } public void TestIsFeatureEnabledWithFeatureEnabledPropertyGivenRolloutRule() { var featureKey = "boolean_single_variable_feature"; var featureFlag = Config.GetFeatureFlagFromKey(featureKey); // Verify that IsFeatureEnabled returns true when user is bucketed into the rollout rule's variation. Assert.True(Optimizely.IsFeatureEnabled("boolean_single_variable_feature", TestUserId)); DecisionServiceMock.Setup(ds => ds.GetVariationForFeature(featureFlag, TestUserId, null)).Returns<FeatureDecision>(null); var optly = Helper.CreatePrivateOptimizely(); optly.SetFieldOrProperty("DecisionService", DecisionServiceMock.Object); // Verify that IsFeatureEnabled returns false when user does not get bucketed into the rollout rule's variation. bool result = (bool)optly.Invoke("IsFeatureEnabled", featureKey, TestUserId, null); Assert.False(result); } #endregion // Test IsFeatureEnabled method #region Test NotificationCenter [Test] public void TestActivateListenerWithoutAttributes() { TestActivateListener(null); } [Test] public void TestActivateListenerWithAttributes() { var userAttributes = new UserAttributes { { "device_type", "iPhone" }, { "company", "Optimizely" }, { "location", "San Francisco" } }; TestActivateListener(userAttributes); } public void TestActivateListener(UserAttributes userAttributes) { var experimentKey = "group_experiment_1"; var variationKey = "group_exp_1_var_1"; var featureKey = "boolean_feature"; var experiment = Config.GetExperimentFromKey(experimentKey); var variation = Config.GetVariationFromKey(experimentKey, variationKey); var featureFlag = Config.GetFeatureFlagFromKey(featureKey); var decision = new FeatureDecision(experiment, variation, FeatureDecision.DECISION_SOURCE_EXPERIMENT); var logEvent = new LogEvent("https://logx.optimizely.com/v1/events", OptimizelyHelper.SingleParameter, "POST", new Dictionary<string, string> { }); // Mocking objects. NotificationCallbackMock.Setup(nc => nc.TestActivateCallback(It.IsAny<Experiment>(), It.IsAny<string>(), It.IsAny<UserAttributes>(), It.IsAny<Variation>(), It.IsAny<LogEvent>())); NotificationCallbackMock.Setup(nc => nc.TestAnotherActivateCallback(It.IsAny<Experiment>(), It.IsAny<string>(), It.IsAny<UserAttributes>(), It.IsAny<Variation>(), It.IsAny<LogEvent>())); NotificationCallbackMock.Setup(nc => nc.TestTrackCallback(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<UserAttributes>(), It.IsAny<EventTags>(), It.IsAny<LogEvent>())); EventBuilderMock.Setup(ebm => ebm.CreateImpressionEvent(It.IsAny<ProjectConfig>(), It.IsAny<Experiment>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<UserAttributes>())).Returns(logEvent); DecisionServiceMock.Setup(ds => ds.GetVariation(experiment, TestUserId, userAttributes)).Returns(variation); DecisionServiceMock.Setup(ds => ds.GetVariationForFeature(featureFlag, TestUserId, userAttributes)).Returns(decision); var optly = Helper.CreatePrivateOptimizely(); var optStronglyTyped = optly.GetObject() as Optimizely; // Adding notification listeners. var notificationType = NotificationCenter.NotificationType.Activate; optStronglyTyped. NotificationCenter.AddNotification(notificationType, NotificationCallbackMock.Object.TestActivateCallback); optStronglyTyped.NotificationCenter.AddNotification(notificationType, NotificationCallbackMock.Object.TestAnotherActivateCallback); optly.SetFieldOrProperty("DecisionService", DecisionServiceMock.Object); optly.SetFieldOrProperty("EventBuilder", EventBuilderMock.Object); // Calling Activate and IsFeatureEnabled. optly.Invoke("Activate", experimentKey, TestUserId, userAttributes); optly.Invoke("IsFeatureEnabled", featureKey, TestUserId, userAttributes); // Verify that all the registered callbacks are called once for both Activate and IsFeatureEnabled. NotificationCallbackMock.Verify(nc => nc.TestActivateCallback(experiment, TestUserId, userAttributes, variation, logEvent), Times.Exactly(2)); NotificationCallbackMock.Verify(nc => nc.TestAnotherActivateCallback(experiment, TestUserId, userAttributes, variation, logEvent), Times.Exactly(2)); } [Test] public void TestTrackListenerWithoutAttributesAndEventTags() { TestTrackListener(null, null); } [Test] public void TestTrackListenerWithAttributesWithoutEventTags() { var userAttributes = new UserAttributes { { "device_type", "iPhone" }, { "company", "Optimizely" }, { "location", "San Francisco" } }; TestTrackListener(userAttributes, null); } [Test] public void TestTrackListenerWithAttributesAndEventTags() { var userAttributes = new UserAttributes { { "device_type", "iPhone" }, { "company", "Optimizely" }, { "location", "San Francisco" } }; var eventTags = new EventTags { { "revenue", 42 } }; TestTrackListener(userAttributes, eventTags); } public void TestTrackListener(UserAttributes userAttributes, EventTags eventTags) { var experimentKey = "test_experiment"; var variationKey = "control"; var eventKey = "purchase"; var experiment = Config.GetExperimentFromKey(experimentKey); var variation = Config.GetVariationFromKey(experimentKey, variationKey); var logEvent = new LogEvent("https://logx.optimizely.com/v1/events", OptimizelyHelper.SingleParameter, "POST", new Dictionary<string, string> { }); var optly = Helper.CreatePrivateOptimizely(); var optStronglyTyped = optly.GetObject() as Optimizely; // Mocking objects. NotificationCallbackMock.Setup(nc => nc.TestTrackCallback(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<UserAttributes>(), It.IsAny<EventTags>(), It.IsAny<LogEvent>())); NotificationCallbackMock.Setup(nc => nc.TestAnotherTrackCallback(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<UserAttributes>(), It.IsAny<EventTags>(), It.IsAny<LogEvent>())); EventBuilderMock.Setup(ebm => ebm.CreateConversionEvent(It.IsAny<ProjectConfig>(), It.IsAny<string>(), It.IsAny<Dictionary<string, Variation>>(), It.IsAny<string>(), It.IsAny<UserAttributes>(), It.IsAny<EventTags>())).Returns(logEvent); DecisionServiceMock.Setup(ds => ds.GetVariation(experiment, TestUserId, userAttributes)).Returns(variation); // Adding notification listeners. var notificationType = NotificationCenter.NotificationType.Track; optStronglyTyped.NotificationCenter.AddNotification(notificationType, NotificationCallbackMock.Object.TestTrackCallback); optStronglyTyped.NotificationCenter.AddNotification(notificationType, NotificationCallbackMock.Object.TestAnotherTrackCallback); optly.SetFieldOrProperty("DecisionService", DecisionServiceMock.Object); optly.SetFieldOrProperty("EventBuilder", EventBuilderMock.Object); // Calling Track. optly.Invoke("Track", eventKey, TestUserId, userAttributes, eventTags); // Verify that all the registered callbacks for Track are called. NotificationCallbackMock.Verify(nc => nc.TestTrackCallback(eventKey, TestUserId, userAttributes, eventTags, logEvent), Times.Exactly(1)); NotificationCallbackMock.Verify(nc => nc.TestAnotherTrackCallback(eventKey, TestUserId, userAttributes, eventTags, logEvent), Times.Exactly(1)); } #endregion // Test NotificationCenter #region Test GetEnabledFeatures [Test] public void TestGetEnabledFeaturesWithInvalidDatafile() { var optly = new Optimizely("Random datafile", null, LoggerMock.Object); Assert.IsEmpty(optly.GetEnabledFeatures("some_user", null)); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Datafile has invalid format. Failing 'GetEnabledFeatures'."), Times.Once); } [Test] public void TestGetEnabledFeaturesWithNoFeatureEnabledForUser() { var userAttributes = new UserAttributes { { "device_type", "iPhone" }, { "location", "San Francisco" } }; OptimizelyMock.Setup(om => om.IsFeatureEnabled(It.IsAny<string>(), TestUserId, It.IsAny<UserAttributes>())).Returns(false); Assert.IsEmpty(OptimizelyMock.Object.GetEnabledFeatures(TestUserId, userAttributes)); } [Test] public void TestGetEnabledFeaturesWithSomeFeaturesEnabledForUser() { string[] enabledFeatures = { "boolean_feature", "double_single_variable_feature", "string_single_variable_feature", "multi_variate_feature", "empty_feature" }; string[] notEnabledFeatures = { "integer_single_variable_feature", "boolean_single_variable_feature", "mutex_group_feature", "no_rollout_experiment_feature" }; var userAttributes = new UserAttributes { { "device_type", "iPhone" }, { "location", "San Francisco" } }; OptimizelyMock.Setup(om => om.IsFeatureEnabled(It.IsIn<string>(enabledFeatures), TestUserId, It.IsAny<UserAttributes>())).Returns(true); OptimizelyMock.Setup(om => om.IsFeatureEnabled(It.IsIn<string>(notEnabledFeatures), TestUserId, It.IsAny<UserAttributes>())).Returns(false); var actualFeaturesList = OptimizelyMock.Object.GetEnabledFeatures(TestUserId, userAttributes); // Verify that the returned feature list contains only enabledFeatures. CollectionAssert.AreEquivalent(enabledFeatures, actualFeaturesList); Array.ForEach(notEnabledFeatures, nef => CollectionAssert.DoesNotContain(actualFeaturesList, nef)); } #endregion // Test GetEnabledFeatures #region Test ValidateStringInputs [Test] public void TestActivateValidateInputValues() { // Verify that ValidateStringInputs does not log error for valid values. var variation = Optimizely.Activate("test_experiment", "test_user"); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Provided User Id is in invalid format."), Times.Never); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Provided Experiment Key is in invalid format."), Times.Never); // Verify that ValidateStringInputs logs error for invalid values. variation = Optimizely.Activate("", null); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Provided User Id is in invalid format."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Provided Experiment Key is in invalid format."), Times.Once); } [Test] public void TestGetVariationValidateInputValues() { // Verify that ValidateStringInputs does not log error for valid values. var variation = Optimizely.GetVariation("test_experiment", "test_user"); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Provided User Id is in invalid format."), Times.Never); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Provided Experiment Key is in invalid format."), Times.Never); // Verify that ValidateStringInputs logs error for invalid values. variation = Optimizely.GetVariation("", null); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Provided User Id is in invalid format."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Provided Experiment Key is in invalid format."), Times.Once); } [Test] public void TestTrackValidateInputValues() { // Verify that ValidateStringInputs does not log error for valid values. Optimizely.Track("purchase", "test_user"); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Provided User Id is in invalid format."), Times.Never); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Provided Event Key is in invalid format."), Times.Never); // Verify that ValidateStringInputs logs error for invalid values. Optimizely.Track("", null); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Provided User Id is in invalid format."), Times.Once); LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Provided Event Key is in invalid format."), Times.Once); } #endregion // Test ValidateStringInputs } }
57.752114
235
0.652429
[ "Apache-2.0" ]
Nevett/csharp-sdk
OptimizelySDK.Tests/OptimizelyTest.cs
109,269
C#
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("Xms.QueryView")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Release")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("Xms.QueryView")] [assembly: System.Reflection.AssemblyTitleAttribute("Xms.QueryView")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // 由 MSBuild WriteCodeFragment 类生成。
36.875
80
0.630508
[ "MIT" ]
feilingdeng/xms
Libraries/QueryView/Xms.QueryView/obj/Release/netstandard2.0/Xms.QueryView.AssemblyInfo.cs
1,001
C#
using System; using System.Net; namespace Neutrino.Core { public class DeferredReceivable { public DeferredReceivable() { } public byte[] ReceivedBuffer { get; set; } public int TimeToReceiveTicks { get; set; } public IPEndPoint Endpoint { get; set; } } }
15.277778
45
0.698182
[ "MIT" ]
Claytonious/Neutrino
NeutrinoCore/DeferredReceivable.cs
277
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ScaleWithCameraDistance_Reverse : MonoBehaviour { public float objectScale = 1.0f; private Vector3 initialScale; // set the initial scale, and setup reference camera void Awake() { // record initial scale, use this as a basis initialScale = transform.localScale; } //[ExecuteInEditMode] void Update() { Plane plane = new Plane(Camera.main.transform.forward, Camera.main.transform.position); float dist = plane.GetDistanceToPoint(transform.position); if (dist < 1) { transform.localScale = initialScale * 1 / dist; } } }
25
95
0.657931
[ "MIT" ]
Chopium/ClowderBridge
Assets/Scripts/ScaleWithCameraDistance_Reverse.cs
727
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** Purpose: Base class which can be used to access any array ** ===========================================================*/ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Security; using Internal.Runtime.CompilerServices; #if BIT64 using nuint = System.UInt64; #else using nuint = System.UInt32; #endif namespace System { // Note that we make a T[] (single-dimensional w/ zero as the lower bound) implement both // IList<U> and IReadOnlyList<U>, where T : U dynamically. See the SZArrayHelper class for details. [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public abstract class Array : ICloneable, IList, IStructuralComparable, IStructuralEquatable { // This ctor exists solely to prevent C# from generating a protected .ctor that violates the surface area. I really want this to be a // "protected-and-internal" rather than "internal" but C# has no keyword for the former. internal Array() { } public static ReadOnlyCollection<T> AsReadOnly<T>(T[] array) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } // T[] implements IList<T>. return new ReadOnlyCollection<T>(array); } public static void Resize<T>(ref T[] array, int newSize) { if (newSize < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.newSize, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); T[] larray = array; if (larray == null) { array = new T[newSize]; return; } if (larray.Length != newSize) { T[] newArray = new T[newSize]; Array.Copy(larray, 0, newArray, 0, larray.Length > newSize ? newSize : larray.Length); array = newArray; } } // Create instance will create an array public static unsafe Array CreateInstance(Type elementType, int length) { if ((object)elementType == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.elementType); if (length < 0) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); RuntimeType t = elementType.UnderlyingSystemType as RuntimeType; if (t == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); return InternalCreate((void*)t.TypeHandle.Value, 1, &length, null); } public static unsafe Array CreateInstance(Type elementType, int length1, int length2) { if ((object)elementType == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.elementType); if (length1 < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length1, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); if (length2 < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length2, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); RuntimeType t = elementType.UnderlyingSystemType as RuntimeType; if (t == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); int* pLengths = stackalloc int[2]; pLengths[0] = length1; pLengths[1] = length2; return InternalCreate((void*)t.TypeHandle.Value, 2, pLengths, null); } public static unsafe Array CreateInstance(Type elementType, int length1, int length2, int length3) { if ((object)elementType == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.elementType); if (length1 < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length1, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); if (length2 < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length2, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); if (length3 < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length3, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); RuntimeType t = elementType.UnderlyingSystemType as RuntimeType; if (t == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); int* pLengths = stackalloc int[3]; pLengths[0] = length1; pLengths[1] = length2; pLengths[2] = length3; return InternalCreate((void*)t.TypeHandle.Value, 3, pLengths, null); } public static unsafe Array CreateInstance(Type elementType, params int[] lengths) { if ((object)elementType == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.elementType); if (lengths == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lengths); if (lengths.Length == 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NeedAtLeast1Rank); RuntimeType t = elementType.UnderlyingSystemType as RuntimeType; if (t == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); // Check to make sure the lenghts are all positive. Note that we check this here to give // a good exception message if they are not; however we check this again inside the execution // engine's low level allocation function after having made a copy of the array to prevent a // malicious caller from mutating the array after this check. for (int i = 0; i < lengths.Length; i++) if (lengths[i] < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.lengths, i, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); fixed (int* pLengths = &lengths[0]) return InternalCreate((void*)t.TypeHandle.Value, lengths.Length, pLengths, null); } public static Array CreateInstance(Type elementType, params long[] lengths) { if (lengths == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lengths); } if (lengths.Length == 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NeedAtLeast1Rank); int[] intLengths = new int[lengths.Length]; for (int i = 0; i < lengths.Length; ++i) { long len = lengths[i]; if (len > int.MaxValue || len < int.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.len, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); intLengths[i] = (int)len; } return Array.CreateInstance(elementType, intLengths); } public static unsafe Array CreateInstance(Type elementType, int[] lengths, int[] lowerBounds) { if (elementType == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.elementType); if (lengths == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lengths); if (lowerBounds == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lowerBounds); if (lengths.Length != lowerBounds.Length) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RanksAndBounds); if (lengths.Length == 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NeedAtLeast1Rank); RuntimeType t = elementType.UnderlyingSystemType as RuntimeType; if (t == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); // Check to make sure the lenghts are all positive. Note that we check this here to give // a good exception message if they are not; however we check this again inside the execution // engine's low level allocation function after having made a copy of the array to prevent a // malicious caller from mutating the array after this check. for (int i = 0; i < lengths.Length; i++) if (lengths[i] < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.lengths, i, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); fixed (int* pLengths = &lengths[0]) fixed (int* pLowerBounds = &lowerBounds[0]) return InternalCreate((void*)t.TypeHandle.Value, lengths.Length, pLengths, pLowerBounds); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern unsafe Array InternalCreate(void* elementType, int rank, int* pLengths, int* pLowerBounds); // Copies length elements from sourceArray, starting at index 0, to // destinationArray, starting at index 0. // public static void Copy(Array sourceArray, Array destinationArray, int length) { if (sourceArray == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.sourceArray); if (destinationArray == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destinationArray); Copy(sourceArray, sourceArray.GetLowerBound(0), destinationArray, destinationArray.GetLowerBound(0), length, false); } // Copies length elements from sourceArray, starting at sourceIndex, to // destinationArray, starting at destinationIndex. // public static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) { Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length, false); } // Reliability-wise, this method will either possibly corrupt your // instance & might fail when called from within a CER, or if the // reliable flag is true, it will either always succeed or always // throw an exception with no side effects. [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, bool reliable); // Provides a strong exception guarantee - either it succeeds, or // it throws an exception with no side effects. The arrays must be // compatible array types based on the array element type - this // method does not support casting, boxing, or primitive widening. // It will up-cast, assuming the array types are correct. public static void ConstrainedCopy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) { Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length, true); } public static void Copy(Array sourceArray, Array destinationArray, long length) { if (length > int.MaxValue || length < int.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); Array.Copy(sourceArray, destinationArray, (int)length); } public static void Copy(Array sourceArray, long sourceIndex, Array destinationArray, long destinationIndex, long length) { if (sourceIndex > int.MaxValue || sourceIndex < int.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sourceIndex, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); if (destinationIndex > int.MaxValue || destinationIndex < int.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.destinationIndex, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); if (length > int.MaxValue || length < int.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); Array.Copy(sourceArray, (int)sourceIndex, destinationArray, (int)destinationIndex, (int)length); } // Sets length elements in array to 0 (or null for Object arrays), starting // at index. // public static unsafe void Clear(Array array, int index, int length) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); ref byte p = ref GetRawArrayGeometry(array, out uint numComponents, out uint elementSize, out int lowerBound, out bool containsGCPointers); int offset = index - lowerBound; if (index < lowerBound || offset < 0 || length < 0 || (uint)(offset + length) > numComponents) ThrowHelper.ThrowIndexOutOfRangeException(); ref byte ptr = ref Unsafe.AddByteOffset(ref p, (uint)offset * (nuint)elementSize); nuint byteLength = (uint)length * (nuint)elementSize; if (containsGCPointers) SpanHelpers.ClearWithReferences(ref Unsafe.As<byte, IntPtr>(ref ptr), byteLength / (uint)sizeof(IntPtr)); else SpanHelpers.ClearWithoutReferences(ref ptr, byteLength); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern ref byte GetRawArrayGeometry(Array array, out uint numComponents, out uint elementSize, out int lowerBound, out bool containsGCPointers); // The various Get values... public unsafe object GetValue(params int[] indices) { if (indices == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices); if (Rank != indices.Length) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices); TypedReference elemref = new TypedReference(); fixed (int* pIndices = &indices[0]) InternalGetReference(&elemref, indices.Length, pIndices); return TypedReference.InternalToObject(&elemref); } public unsafe object GetValue(int index) { if (Rank != 1) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need1DArray); TypedReference elemref = new TypedReference(); InternalGetReference(&elemref, 1, &index); return TypedReference.InternalToObject(&elemref); } public unsafe object GetValue(int index1, int index2) { if (Rank != 2) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need2DArray); int* pIndices = stackalloc int[2]; pIndices[0] = index1; pIndices[1] = index2; TypedReference elemref = new TypedReference(); InternalGetReference(&elemref, 2, pIndices); return TypedReference.InternalToObject(&elemref); } public unsafe object GetValue(int index1, int index2, int index3) { if (Rank != 3) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need3DArray); int* pIndices = stackalloc int[3]; pIndices[0] = index1; pIndices[1] = index2; pIndices[2] = index3; TypedReference elemref = new TypedReference(); InternalGetReference(&elemref, 3, pIndices); return TypedReference.InternalToObject(&elemref); } public object GetValue(long index) { if (index > int.MaxValue || index < int.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); return this.GetValue((int)index); } public object GetValue(long index1, long index2) { if (index1 > int.MaxValue || index1 < int.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index1, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); if (index2 > int.MaxValue || index2 < int.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); return this.GetValue((int)index1, (int)index2); } public object GetValue(long index1, long index2, long index3) { if (index1 > int.MaxValue || index1 < int.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index1, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); if (index2 > int.MaxValue || index2 < int.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); if (index3 > int.MaxValue || index3 < int.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index3, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); return this.GetValue((int)index1, (int)index2, (int)index3); } public object GetValue(params long[] indices) { if (indices == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices); if (Rank != indices.Length) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices); int[] intIndices = new int[indices.Length]; for (int i = 0; i < indices.Length; ++i) { long index = indices[i]; if (index > int.MaxValue || index < int.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); intIndices[i] = (int)index; } return this.GetValue(intIndices); } public unsafe void SetValue(object value, int index) { if (Rank != 1) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need1DArray); TypedReference elemref = new TypedReference(); InternalGetReference(&elemref, 1, &index); InternalSetValue(&elemref, value); } public unsafe void SetValue(object value, int index1, int index2) { if (Rank != 2) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need2DArray); int* pIndices = stackalloc int[2]; pIndices[0] = index1; pIndices[1] = index2; TypedReference elemref = new TypedReference(); InternalGetReference(&elemref, 2, pIndices); InternalSetValue(&elemref, value); } public unsafe void SetValue(object value, int index1, int index2, int index3) { if (Rank != 3) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need3DArray); int* pIndices = stackalloc int[3]; pIndices[0] = index1; pIndices[1] = index2; pIndices[2] = index3; TypedReference elemref = new TypedReference(); InternalGetReference(&elemref, 3, pIndices); InternalSetValue(&elemref, value); } public unsafe void SetValue(object value, params int[] indices) { if (indices == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices); if (Rank != indices.Length) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices); TypedReference elemref = new TypedReference(); fixed (int* pIndices = &indices[0]) InternalGetReference(&elemref, indices.Length, pIndices); InternalSetValue(&elemref, value); } public void SetValue(object value, long index) { if (index > int.MaxValue || index < int.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); this.SetValue(value, (int)index); } public void SetValue(object value, long index1, long index2) { if (index1 > int.MaxValue || index1 < int.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index1, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); if (index2 > int.MaxValue || index2 < int.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); this.SetValue(value, (int)index1, (int)index2); } public void SetValue(object value, long index1, long index2, long index3) { if (index1 > int.MaxValue || index1 < int.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index1, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); if (index2 > int.MaxValue || index2 < int.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); if (index3 > int.MaxValue || index3 < int.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index3, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); this.SetValue(value, (int)index1, (int)index2, (int)index3); } public void SetValue(object value, params long[] indices) { if (indices == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices); if (Rank != indices.Length) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices); int[] intIndices = new int[indices.Length]; for (int i = 0; i < indices.Length; ++i) { long index = indices[i]; if (index > int.MaxValue || index < int.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); intIndices[i] = (int)index; } this.SetValue(value, intIndices); } [MethodImplAttribute(MethodImplOptions.InternalCall)] // reference to TypedReference is banned, so have to pass result as pointer private extern unsafe void InternalGetReference(void* elemRef, int rank, int* pIndices); // Ideally, we would like to use TypedReference.SetValue instead. Unfortunately, TypedReference.SetValue // always throws not-supported exception [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern unsafe void InternalSetValue(void* target, object value); public extern int Length { [MethodImpl(MethodImplOptions.InternalCall)] get; } private static int GetMedian(int low, int hi) { // Note both may be negative, if we are dealing with arrays w/ negative lower bounds. Debug.Assert(low <= hi); Debug.Assert(hi - low >= 0, "Length overflow!"); return low + ((hi - low) >> 1); } // We impose limits on maximum array lenght in each dimension to allow efficient // implementation of advanced range check elimination in future. // Keep in sync with vm\gcscan.cpp and HashHelpers.MaxPrimeArrayLength. // The constants are defined in this method: inline SIZE_T MaxArrayLength(SIZE_T componentSize) from gcscan // We have different max sizes for arrays with elements of size 1 for backwards compatibility internal const int MaxArrayLength = 0X7FEFFFFF; internal const int MaxByteArrayLength = 0x7FFFFFC7; public extern long LongLength { [MethodImpl(MethodImplOptions.InternalCall)] get; } [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int GetLength(int dimension); public long GetLongLength(int dimension) { //This method should throw an IndexOufOfRangeException for compat if dimension < 0 or >= Rank return GetLength(dimension); } public extern int Rank { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; } [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int GetUpperBound(int dimension); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int GetLowerBound(int dimension); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern int GetDataPtrOffsetInternal(); // Number of elements in the Array. int ICollection.Count { get { return Length; } } // Returns an object appropriate for synchronizing access to this // Array. public object SyncRoot { get { return this; } } // Is this Array read-only? public bool IsReadOnly { get { return false; } } public bool IsFixedSize { get { return true; } } // Is this Array synchronized (i.e., thread-safe)? If you want a synchronized // collection, you can use SyncRoot as an object to synchronize your // collection with. You could also call GetSynchronized() // to get a synchronized wrapper around the Array. public bool IsSynchronized { get { return false; } } object IList.this[int index] { get { return GetValue(index); } set { SetValue(value, index); } } int IList.Add(object value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); return default; } bool IList.Contains(object value) { return Array.IndexOf(this, value) >= this.GetLowerBound(0); } void IList.Clear() { Array.Clear(this, this.GetLowerBound(0), this.Length); } int IList.IndexOf(object value) { return Array.IndexOf(this, value); } void IList.Insert(int index, object value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); } void IList.Remove(object value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); } void IList.RemoveAt(int index) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); } // Make a new array which is a shallow copy of the original array. // public object Clone() { return MemberwiseClone(); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) { return 1; } Array o = other as Array; if (o == null || this.Length != o.Length) { ThrowHelper.ThrowArgumentException(ExceptionResource.ArgumentException_OtherNotArrayOfCorrectLength, ExceptionArgument.other); } int i = 0; int c = 0; while (i < o.Length && c == 0) { object left = GetValue(i); object right = o.GetValue(i); c = comparer.Compare(left, right); i++; } return c; } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) { return false; } if (object.ReferenceEquals(this, other)) { return true; } Array o = other as Array; if (o == null || o.Length != this.Length) { return false; } int i = 0; while (i < o.Length) { object left = GetValue(i); object right = o.GetValue(i); if (!comparer.Equals(left, right)) { return false; } i++; } return true; } // From System.Web.Util.HashCodeCombiner internal static int CombineHashCodes(int h1, int h2) { return (((h1 << 5) + h1) ^ h2); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { if (comparer == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparer); int ret = 0; for (int i = (this.Length >= 8 ? this.Length - 8 : 0); i < this.Length; i++) { ret = CombineHashCodes(ret, comparer.GetHashCode(GetValue(i))); } return ret; } // Searches an array for a given element using a binary search algorithm. // Elements of the array are compared to the search value using the // IComparable interface, which must be implemented by all elements // of the array and the given search value. This method assumes that the // array is already sorted according to the IComparable interface; // if this is not the case, the result will be incorrect. // // The method returns the index of the given value in the array. If the // array does not contain the given value, the method returns a negative // integer. The bitwise complement operator (~) can be applied to a // negative result to produce the index of the first element (if any) that // is larger than the given search value. // public static int BinarySearch(Array array, object value) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); int lb = array.GetLowerBound(0); return BinarySearch(array, lb, array.Length, value, null); } // Searches a section of an array for a given element using a binary search // algorithm. Elements of the array are compared to the search value using // the IComparable interface, which must be implemented by all // elements of the array and the given search value. This method assumes // that the array is already sorted according to the IComparable // interface; if this is not the case, the result will be incorrect. // // The method returns the index of the given value in the array. If the // array does not contain the given value, the method returns a negative // integer. The bitwise complement operator (~) can be applied to a // negative result to produce the index of the first element (if any) that // is larger than the given search value. // public static int BinarySearch(Array array, int index, int length, object value) { return BinarySearch(array, index, length, value, null); } // Searches an array for a given element using a binary search algorithm. // Elements of the array are compared to the search value using the given // IComparer interface. If comparer is null, elements of the // array are compared to the search value using the IComparable // interface, which in that case must be implemented by all elements of the // array and the given search value. This method assumes that the array is // already sorted; if this is not the case, the result will be incorrect. // // The method returns the index of the given value in the array. If the // array does not contain the given value, the method returns a negative // integer. The bitwise complement operator (~) can be applied to a // negative result to produce the index of the first element (if any) that // is larger than the given search value. // public static int BinarySearch(Array array, object value, IComparer comparer) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); int lb = array.GetLowerBound(0); return BinarySearch(array, lb, array.Length, value, comparer); } // Searches a section of an array for a given element using a binary search // algorithm. Elements of the array are compared to the search value using // the given IComparer interface. If comparer is null, // elements of the array are compared to the search value using the // IComparable interface, which in that case must be implemented by // all elements of the array and the given search value. This method // assumes that the array is already sorted; if this is not the case, the // result will be incorrect. // // The method returns the index of the given value in the array. If the // array does not contain the given value, the method returns a negative // integer. The bitwise complement operator (~) can be applied to a // negative result to produce the index of the first element (if any) that // is larger than the given search value. // public static int BinarySearch(Array array, int index, int length, object value, IComparer comparer) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); int lb = array.GetLowerBound(0); if (index < lb) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (length < 0) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); if (array.Length - (index - lb) < length) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); if (array.Rank != 1) ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported); if (comparer == null) comparer = Comparer.Default; if (comparer == Comparer.Default) { int retval; bool r = TrySZBinarySearch(array, index, length, value, out retval); if (r) return retval; } int lo = index; int hi = index + length - 1; object[] objArray = array as object[]; if (objArray != null) { while (lo <= hi) { // i might overflow if lo and hi are both large positive numbers. int i = GetMedian(lo, hi); int c = 0; try { c = comparer.Compare(objArray[i], value); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } if (c == 0) return i; if (c < 0) { lo = i + 1; } else { hi = i - 1; } } } else { while (lo <= hi) { int i = GetMedian(lo, hi); int c = 0; try { c = comparer.Compare(array.GetValue(i), value); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } if (c == 0) return i; if (c < 0) { lo = i + 1; } else { hi = i - 1; } } } return ~lo; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool TrySZBinarySearch(Array sourceArray, int sourceIndex, int count, object value, out int retVal); public static int BinarySearch<T>(T[] array, T value) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); return BinarySearch<T>(array, 0, array.Length, value, null); } public static int BinarySearch<T>(T[] array, T value, System.Collections.Generic.IComparer<T> comparer) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); return BinarySearch<T>(array, 0, array.Length, value, comparer); } public static int BinarySearch<T>(T[] array, int index, int length, T value) { return BinarySearch<T>(array, index, length, value, null); } public static int BinarySearch<T>(T[] array, int index, int length, T value, System.Collections.Generic.IComparer<T> comparer) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (index < 0) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (length < 0) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); if (array.Length - index < length) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); return ArraySortHelper<T>.Default.BinarySearch(array, index, length, value, comparer); } public static TOutput[] ConvertAll<TInput, TOutput>(TInput[] array, Converter<TInput, TOutput> converter) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (converter == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter); } TOutput[] newArray = new TOutput[array.Length]; for (int i = 0; i < array.Length; i++) { newArray[i] = converter(array[i]); } return newArray; } // CopyTo copies a collection into an Array, starting at a particular // index into the array. // // This method is to support the ICollection interface, and calls // Array.Copy internally. If you aren't using ICollection explicitly, // call Array.Copy to avoid an extra indirection. // public void CopyTo(Array array, int index) { if (array != null && array.Rank != 1) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); // Note: Array.Copy throws a RankException and we want a consistent ArgumentException for all the IList CopyTo methods. Array.Copy(this, GetLowerBound(0), array, index, Length); } public void CopyTo(Array array, long index) { if (index > int.MaxValue || index < int.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); this.CopyTo(array, (int)index); } private static class EmptyArray<T> { internal static readonly T[] Value = new T[0]; } public static T[] Empty<T>() { return EmptyArray<T>.Value; } public static bool Exists<T>(T[] array, Predicate<T> match) { return Array.FindIndex(array, match) != -1; } public static void Fill<T>(T[] array, T value) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } for (int i = 0; i < array.Length; i++) { array[i] = value; } } public static void Fill<T>(T[] array, T value, int startIndex, int count) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (startIndex < 0 || startIndex > array.Length) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } if (count < 0 || startIndex > array.Length - count) { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } for (int i = startIndex; i < startIndex + count; i++) { array[i] = value; } } public static T Find<T>(T[] array, Predicate<T> match) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } for (int i = 0; i < array.Length; i++) { if (match(array[i])) { return array[i]; } } return default; } public static T[] FindAll<T>(T[] array, Predicate<T> match) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } List<T> list = new List<T>(); for (int i = 0; i < array.Length; i++) { if (match(array[i])) { list.Add(array[i]); } } return list.ToArray(); } public static int FindIndex<T>(T[] array, Predicate<T> match) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return FindIndex(array, 0, array.Length, match); } public static int FindIndex<T>(T[] array, int startIndex, Predicate<T> match) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return FindIndex(array, startIndex, array.Length - startIndex, match); } public static int FindIndex<T>(T[] array, int startIndex, int count, Predicate<T> match) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (startIndex < 0 || startIndex > array.Length) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } if (count < 0 || startIndex > array.Length - count) { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } if (match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } int endIndex = startIndex + count; for (int i = startIndex; i < endIndex; i++) { if (match(array[i])) return i; } return -1; } public static T FindLast<T>(T[] array, Predicate<T> match) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } for (int i = array.Length - 1; i >= 0; i--) { if (match(array[i])) { return array[i]; } } return default; } public static int FindLastIndex<T>(T[] array, Predicate<T> match) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return FindLastIndex(array, array.Length - 1, array.Length, match); } public static int FindLastIndex<T>(T[] array, int startIndex, Predicate<T> match) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return FindLastIndex(array, startIndex, startIndex + 1, match); } public static int FindLastIndex<T>(T[] array, int startIndex, int count, Predicate<T> match) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } if (array.Length == 0) { // Special case for 0 length List if (startIndex != -1) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } } else { // Make sure we're not out of range if (startIndex < 0 || startIndex >= array.Length) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } } // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } int endIndex = startIndex - count; for (int i = startIndex; i > endIndex; i--) { if (match(array[i])) { return i; } } return -1; } public static void ForEach<T>(T[] array, Action<T> action) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (action == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action); } for (int i = 0; i < array.Length; i++) { action(array[i]); } } // GetEnumerator returns an IEnumerator over this Array. // // Currently, only one dimensional arrays are supported. // public IEnumerator GetEnumerator() { int lowerBound = GetLowerBound(0); if (Rank == 1 && lowerBound == 0) return new SZArrayEnumerator(this); else return new ArrayEnumerator(this, lowerBound, Length); } // Returns the index of the first occurrence of a given value in an array. // The array is searched forwards, and the elements of the array are // compared to the given value using the Object.Equals method. // public static int IndexOf(Array array, object value) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); int lb = array.GetLowerBound(0); return IndexOf(array, value, lb, array.Length); } // Returns the index of the first occurrence of a given value in a range of // an array. The array is searched forwards, starting at index // startIndex and ending at the last element of the array. The // elements of the array are compared to the given value using the // Object.Equals method. // public static int IndexOf(Array array, object value, int startIndex) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); int lb = array.GetLowerBound(0); return IndexOf(array, value, startIndex, array.Length - startIndex + lb); } // Returns the index of the first occurrence of a given value in a range of // an array. The array is searched forwards, starting at index // startIndex and upto count elements. The // elements of the array are compared to the given value using the // Object.Equals method. // public static int IndexOf(Array array, object value, int startIndex, int count) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (array.Rank != 1) ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported); int lb = array.GetLowerBound(0); if (startIndex < lb || startIndex > array.Length + lb) ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); if (count < 0 || count > array.Length - startIndex + lb) ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); // Try calling a quick native method to handle primitive types. int retVal; bool r = TrySZIndexOf(array, startIndex, count, value, out retVal); if (r) return retVal; object[] objArray = array as object[]; int endIndex = startIndex + count; if (objArray != null) { if (value == null) { for (int i = startIndex; i < endIndex; i++) { if (objArray[i] == null) return i; } } else { for (int i = startIndex; i < endIndex; i++) { object obj = objArray[i]; if (obj != null && obj.Equals(value)) return i; } } } else { for (int i = startIndex; i < endIndex; i++) { object obj = array.GetValue(i); if (obj == null) { if (value == null) return i; } else { if (obj.Equals(value)) return i; } } } // Return one less than the lower bound of the array. This way, // for arrays with a lower bound of -1 we will not return -1 when the // item was not found. And for SZArrays (the vast majority), -1 still // works for them. return lb - 1; } public static int IndexOf<T>(T[] array, T value) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return IndexOf(array, value, 0, array.Length); } public static int IndexOf<T>(T[] array, T value, int startIndex) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return IndexOf(array, value, startIndex, array.Length - startIndex); } public static int IndexOf<T>(T[] array, T value, int startIndex, int count) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if ((uint)startIndex > (uint)array.Length) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } if ((uint)count > (uint)(array.Length - startIndex)) { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } if (typeof(T) == typeof(byte)) { int result = SpanHelpers.IndexOf( ref Unsafe.Add(ref array.GetRawSzArrayData(), startIndex), Unsafe.As<T, byte>(ref value), count); return (result >= 0 ? startIndex : 0) + result; } if (typeof(T) == typeof(char)) { int result = SpanHelpers.IndexOf( ref Unsafe.Add(ref Unsafe.As<byte, char>(ref array.GetRawSzArrayData()), startIndex), Unsafe.As<T, char>(ref value), count); return (result >= 0 ? startIndex : 0) + result; } return EqualityComparer<T>.Default.IndexOf(array, value, startIndex, count); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool TrySZIndexOf(Array sourceArray, int sourceIndex, int count, object value, out int retVal); // Returns the index of the last occurrence of a given value in an array. // The array is searched backwards, and the elements of the array are // compared to the given value using the Object.Equals method. // public static int LastIndexOf(Array array, object value) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); int lb = array.GetLowerBound(0); return LastIndexOf(array, value, array.Length - 1 + lb, array.Length); } // Returns the index of the last occurrence of a given value in a range of // an array. The array is searched backwards, starting at index // startIndex and ending at index 0. The elements of the array are // compared to the given value using the Object.Equals method. // public static int LastIndexOf(Array array, object value, int startIndex) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); int lb = array.GetLowerBound(0); return LastIndexOf(array, value, startIndex, startIndex + 1 - lb); } // Returns the index of the last occurrence of a given value in a range of // an array. The array is searched backwards, starting at index // startIndex and counting uptocount elements. The elements of // the array are compared to the given value using the Object.Equals // method. // public static int LastIndexOf(Array array, object value, int startIndex, int count) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); int lb = array.GetLowerBound(0); if (array.Length == 0) { return lb - 1; } if (startIndex < lb || startIndex >= array.Length + lb) ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); if (count < 0) ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); if (count > startIndex - lb + 1) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.endIndex, ExceptionResource.ArgumentOutOfRange_EndIndexStartIndex); if (array.Rank != 1) ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported); // Try calling a quick native method to handle primitive types. int retVal; bool r = TrySZLastIndexOf(array, startIndex, count, value, out retVal); if (r) return retVal; object[] objArray = array as object[]; int endIndex = startIndex - count + 1; if (objArray != null) { if (value == null) { for (int i = startIndex; i >= endIndex; i--) { if (objArray[i] == null) return i; } } else { for (int i = startIndex; i >= endIndex; i--) { object obj = objArray[i]; if (obj != null && obj.Equals(value)) return i; } } } else { for (int i = startIndex; i >= endIndex; i--) { object obj = array.GetValue(i); if (obj == null) { if (value == null) return i; } else { if (obj.Equals(value)) return i; } } } return lb - 1; // Return lb-1 for arrays with negative lower bounds. } public static int LastIndexOf<T>(T[] array, T value) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return LastIndexOf(array, value, array.Length - 1, array.Length); } public static int LastIndexOf<T>(T[] array, T value, int startIndex) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } // if array is empty and startIndex is 0, we need to pass 0 as count return LastIndexOf(array, value, startIndex, (array.Length == 0) ? 0 : (startIndex + 1)); } public static int LastIndexOf<T>(T[] array, T value, int startIndex, int count) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Length == 0) { // // Special case for 0 length List // accept -1 and 0 as valid startIndex for compablility reason. // if (startIndex != -1 && startIndex != 0) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } // only 0 is a valid value for count if array is empty if (count != 0) { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } return -1; } // Make sure we're not out of range if ((uint)startIndex >= (uint)array.Length) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } if (typeof(T) == typeof(byte)) { int endIndex = startIndex - count + 1; int result = SpanHelpers.LastIndexOf( ref Unsafe.Add(ref array.GetRawSzArrayData(), endIndex), Unsafe.As<T, byte>(ref value), count); return (result >= 0 ? endIndex : 0) + result; } if (typeof(T) == typeof(char)) { int endIndex = startIndex - count + 1; int result = SpanHelpers.LastIndexOf( ref Unsafe.Add(ref Unsafe.As<byte, char>(ref array.GetRawSzArrayData()), endIndex), Unsafe.As<T, char>(ref value), count); return (result >= 0 ? endIndex : 0) + result; } return EqualityComparer<T>.Default.LastIndexOf(array, value, startIndex, count); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool TrySZLastIndexOf(Array sourceArray, int sourceIndex, int count, object value, out int retVal); // Reverses all elements of the given array. Following a call to this // method, an element previously located at index i will now be // located at index length - i - 1, where length is the // length of the array. // public static void Reverse(Array array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Reverse(array, array.GetLowerBound(0), array.Length); } // Reverses the elements in a range of an array. Following a call to this // method, an element in the range given by index and count // which was previously located at index i will now be located at // index index + (index + count - i - 1). // Reliability note: This may fail because it may have to box objects. // public static void Reverse(Array array, int index, int length) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); int lowerBound = array.GetLowerBound(0); if (index < lowerBound) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (length < 0) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); if (array.Length - (index - lowerBound) < length) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); if (array.Rank != 1) ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported); if (length <= 1) return; bool r = TrySZReverse(array, index, length); if (r) return; object[] objArray = array as object[]; if (objArray != null) { Array.Reverse<object>(objArray, index, length); } else { int i = index; int j = index + length - 1; while (i < j) { object temp = array.GetValue(i); array.SetValue(array.GetValue(j), i); array.SetValue(temp, j); i++; j--; } } } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool TrySZReverse(Array array, int index, int count); public static void Reverse<T>(T[] array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Reverse(array, 0, array.Length); } public static void Reverse<T>(T[] array, int index, int length) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (index < 0) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (length < 0) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); if (array.Length - index < length) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); if (length <= 1) return; ref T first = ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), index); ref T last = ref Unsafe.Add(ref Unsafe.Add(ref first, length), -1); do { T temp = first; first = last; last = temp; first = ref Unsafe.Add(ref first, 1); last = ref Unsafe.Add(ref last, -1); } while (Unsafe.IsAddressLessThan(ref first, ref last)); } // Sorts the elements of an array. The sort compares the elements to each // other using the IComparable interface, which must be implemented // by all elements of the array. // public static void Sort(Array array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Sort(array, null, array.GetLowerBound(0), array.Length, null); } // Sorts the elements of two arrays based on the keys in the first array. // Elements in the keys array specify the sort keys for // corresponding elements in the items array. The sort compares the // keys to each other using the IComparable interface, which must be // implemented by all elements of the keys array. // public static void Sort(Array keys, Array items) { if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); Sort(keys, items, keys.GetLowerBound(0), keys.Length, null); } // Sorts the elements in a section of an array. The sort compares the // elements to each other using the IComparable interface, which // must be implemented by all elements in the given section of the array. // public static void Sort(Array array, int index, int length) { Sort(array, null, index, length, null); } // Sorts the elements in a section of two arrays based on the keys in the // first array. Elements in the keys array specify the sort keys for // corresponding elements in the items array. The sort compares the // keys to each other using the IComparable interface, which must be // implemented by all elements of the keys array. // public static void Sort(Array keys, Array items, int index, int length) { Sort(keys, items, index, length, null); } // Sorts the elements of an array. The sort compares the elements to each // other using the given IComparer interface. If comparer is // null, the elements are compared to each other using the // IComparable interface, which in that case must be implemented by // all elements of the array. // public static void Sort(Array array, IComparer comparer) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Sort(array, null, array.GetLowerBound(0), array.Length, comparer); } // Sorts the elements of two arrays based on the keys in the first array. // Elements in the keys array specify the sort keys for // corresponding elements in the items array. The sort compares the // keys to each other using the given IComparer interface. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented // by all elements of the keys array. // public static void Sort(Array keys, Array items, IComparer comparer) { if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); Sort(keys, items, keys.GetLowerBound(0), keys.Length, comparer); } // Sorts the elements in a section of an array. The sort compares the // elements to each other using the given IComparer interface. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented // by all elements in the given section of the array. // public static void Sort(Array array, int index, int length, IComparer comparer) { Sort(array, null, index, length, comparer); } // Sorts the elements in a section of two arrays based on the keys in the // first array. Elements in the keys array specify the sort keys for // corresponding elements in the items array. The sort compares the // keys to each other using the given IComparer interface. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented // by all elements of the given section of the keys array. // public static void Sort(Array keys, Array items, int index, int length, IComparer comparer) { if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); if (keys.Rank != 1 || (items != null && items.Rank != 1)) ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported); int keysLowerBound = keys.GetLowerBound(0); if (items != null && keysLowerBound != items.GetLowerBound(0)) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_LowerBoundsMustMatch); if (index < keysLowerBound) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (length < 0) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); if (keys.Length - (index - keysLowerBound) < length || (items != null && (index - keysLowerBound) > items.Length - length)) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); if (length > 1) { if (comparer == Comparer.Default || comparer == null) { bool r = TrySZSort(keys, items, index, index + length - 1); if (r) return; } object[] objKeys = keys as object[]; object[] objItems = null; if (objKeys != null) objItems = items as object[]; if (objKeys != null && (items == null || objItems != null)) { SorterObjectArray sorter = new SorterObjectArray(objKeys, objItems, comparer); sorter.Sort(index, length); } else { SorterGenericArray sorter = new SorterGenericArray(keys, items, comparer); sorter.Sort(index, length); } } } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool TrySZSort(Array keys, Array items, int left, int right); public static void Sort<T>(T[] array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Sort<T>(array, 0, array.Length, null); } public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items) { if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); Sort<TKey, TValue>(keys, items, 0, keys.Length, null); } public static void Sort<T>(T[] array, int index, int length) { Sort<T>(array, index, length, null); } public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length) { Sort<TKey, TValue>(keys, items, index, length, null); } public static void Sort<T>(T[] array, System.Collections.Generic.IComparer<T> comparer) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Sort<T>(array, 0, array.Length, comparer); } public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, System.Collections.Generic.IComparer<TKey> comparer) { if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); Sort<TKey, TValue>(keys, items, 0, keys.Length, comparer); } public static void Sort<T>(T[] array, int index, int length, System.Collections.Generic.IComparer<T> comparer) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (index < 0) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (length < 0) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); if (array.Length - index < length) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); if (length > 1) { if (comparer == null || comparer == Comparer<T>.Default) { if (TrySZSort(array, null, index, index + length - 1)) { return; } } ArraySortHelper<T>.Default.Sort(array, index, length, comparer); } } public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length, System.Collections.Generic.IComparer<TKey> comparer) { if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); if (index < 0) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (length < 0) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); if (keys.Length - index < length || (items != null && index > items.Length - length)) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); if (length > 1) { if (comparer == null || comparer == Comparer<TKey>.Default) { if (TrySZSort(keys, items, index, index + length - 1)) { return; } } if (items == null) { Sort<TKey>(keys, index, length, comparer); return; } ArraySortHelper<TKey, TValue>.Default.Sort(keys, items, index, length, comparer); } } public static void Sort<T>(T[] array, Comparison<T> comparison) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (comparison == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); } ArraySortHelper<T>.Sort(array, 0, array.Length, comparison); } public static bool TrueForAll<T>(T[] array, Predicate<T> match) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } for (int i = 0; i < array.Length; i++) { if (!match(array[i])) { return false; } } return true; } // Private value type used by the Sort methods. private readonly struct SorterObjectArray { private readonly object[] keys; private readonly object[] items; private readonly IComparer comparer; internal SorterObjectArray(object[] keys, object[] items, IComparer comparer) { if (comparer == null) comparer = Comparer.Default; this.keys = keys; this.items = items; this.comparer = comparer; } internal void SwapIfGreaterWithItems(int a, int b) { if (a != b) { if (comparer.Compare(keys[a], keys[b]) > 0) { object temp = keys[a]; keys[a] = keys[b]; keys[b] = temp; if (items != null) { object item = items[a]; items[a] = items[b]; items[b] = item; } } } } private void Swap(int i, int j) { object t = keys[i]; keys[i] = keys[j]; keys[j] = t; if (items != null) { object item = items[i]; items[i] = items[j]; items[j] = item; } } internal void Sort(int left, int length) { IntrospectiveSort(left, length); } private void IntrospectiveSort(int left, int length) { if (length < 2) return; try { IntroSort(left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length)); } catch (IndexOutOfRangeException) { IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } private void IntroSort(int lo, int hi, int depthLimit) { while (hi > lo) { int partitionSize = hi - lo + 1; if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold) { if (partitionSize == 1) { return; } if (partitionSize == 2) { SwapIfGreaterWithItems(lo, hi); return; } if (partitionSize == 3) { SwapIfGreaterWithItems(lo, hi - 1); SwapIfGreaterWithItems(lo, hi); SwapIfGreaterWithItems(hi - 1, hi); return; } InsertionSort(lo, hi); return; } if (depthLimit == 0) { Heapsort(lo, hi); return; } depthLimit--; int p = PickPivotAndPartition(lo, hi); IntroSort(p + 1, hi, depthLimit); hi = p - 1; } } private int PickPivotAndPartition(int lo, int hi) { // Compute median-of-three. But also partition them, since we've done the comparison. int mid = lo + (hi - lo) / 2; // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreaterWithItems(lo, mid); SwapIfGreaterWithItems(lo, hi); SwapIfGreaterWithItems(mid, hi); object pivot = keys[mid]; Swap(mid, hi - 1); int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { while (comparer.Compare(keys[++left], pivot) < 0) ; while (comparer.Compare(pivot, keys[--right]) < 0) ; if (left >= right) break; Swap(left, right); } // Put pivot in the right location. Swap(left, (hi - 1)); return left; } private void Heapsort(int lo, int hi) { int n = hi - lo + 1; for (int i = n / 2; i >= 1; i = i - 1) { DownHeap(i, n, lo); } for (int i = n; i > 1; i = i - 1) { Swap(lo, lo + i - 1); DownHeap(1, i - 1, lo); } } private void DownHeap(int i, int n, int lo) { object d = keys[lo + i - 1]; object dt = (items != null) ? items[lo + i - 1] : null; int child; while (i <= n / 2) { child = 2 * i; if (child < n && comparer.Compare(keys[lo + child - 1], keys[lo + child]) < 0) { child++; } if (!(comparer.Compare(d, keys[lo + child - 1]) < 0)) break; keys[lo + i - 1] = keys[lo + child - 1]; if (items != null) items[lo + i - 1] = items[lo + child - 1]; i = child; } keys[lo + i - 1] = d; if (items != null) items[lo + i - 1] = dt; } private void InsertionSort(int lo, int hi) { int i, j; object t, ti; for (i = lo; i < hi; i++) { j = i; t = keys[i + 1]; ti = (items != null) ? items[i + 1] : null; while (j >= lo && comparer.Compare(t, keys[j]) < 0) { keys[j + 1] = keys[j]; if (items != null) items[j + 1] = items[j]; j--; } keys[j + 1] = t; if (items != null) items[j + 1] = ti; } } } // Private value used by the Sort methods for instances of Array. // This is slower than the one for Object[], since we can't use the JIT helpers // to access the elements. We must use GetValue & SetValue. private readonly struct SorterGenericArray { private readonly Array keys; private readonly Array items; private readonly IComparer comparer; internal SorterGenericArray(Array keys, Array items, IComparer comparer) { if (comparer == null) comparer = Comparer.Default; this.keys = keys; this.items = items; this.comparer = comparer; } internal void SwapIfGreaterWithItems(int a, int b) { if (a != b) { if (comparer.Compare(keys.GetValue(a), keys.GetValue(b)) > 0) { object key = keys.GetValue(a); keys.SetValue(keys.GetValue(b), a); keys.SetValue(key, b); if (items != null) { object item = items.GetValue(a); items.SetValue(items.GetValue(b), a); items.SetValue(item, b); } } } } private void Swap(int i, int j) { object t1 = keys.GetValue(i); keys.SetValue(keys.GetValue(j), i); keys.SetValue(t1, j); if (items != null) { object t2 = items.GetValue(i); items.SetValue(items.GetValue(j), i); items.SetValue(t2, j); } } internal void Sort(int left, int length) { IntrospectiveSort(left, length); } private void IntrospectiveSort(int left, int length) { if (length < 2) return; try { IntroSort(left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length)); } catch (IndexOutOfRangeException) { IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } private void IntroSort(int lo, int hi, int depthLimit) { while (hi > lo) { int partitionSize = hi - lo + 1; if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold) { if (partitionSize == 1) { return; } if (partitionSize == 2) { SwapIfGreaterWithItems(lo, hi); return; } if (partitionSize == 3) { SwapIfGreaterWithItems(lo, hi - 1); SwapIfGreaterWithItems(lo, hi); SwapIfGreaterWithItems(hi - 1, hi); return; } InsertionSort(lo, hi); return; } if (depthLimit == 0) { Heapsort(lo, hi); return; } depthLimit--; int p = PickPivotAndPartition(lo, hi); IntroSort(p + 1, hi, depthLimit); hi = p - 1; } } private int PickPivotAndPartition(int lo, int hi) { // Compute median-of-three. But also partition them, since we've done the comparison. int mid = lo + (hi - lo) / 2; SwapIfGreaterWithItems(lo, mid); SwapIfGreaterWithItems(lo, hi); SwapIfGreaterWithItems(mid, hi); object pivot = keys.GetValue(mid); Swap(mid, hi - 1); int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { while (comparer.Compare(keys.GetValue(++left), pivot) < 0) ; while (comparer.Compare(pivot, keys.GetValue(--right)) < 0) ; if (left >= right) break; Swap(left, right); } // Put pivot in the right location. Swap(left, (hi - 1)); return left; } private void Heapsort(int lo, int hi) { int n = hi - lo + 1; for (int i = n / 2; i >= 1; i = i - 1) { DownHeap(i, n, lo); } for (int i = n; i > 1; i = i - 1) { Swap(lo, lo + i - 1); DownHeap(1, i - 1, lo); } } private void DownHeap(int i, int n, int lo) { object d = keys.GetValue(lo + i - 1); object dt = (items != null) ? items.GetValue(lo + i - 1) : null; int child; while (i <= n / 2) { child = 2 * i; if (child < n && comparer.Compare(keys.GetValue(lo + child - 1), keys.GetValue(lo + child)) < 0) { child++; } if (!(comparer.Compare(d, keys.GetValue(lo + child - 1)) < 0)) break; keys.SetValue(keys.GetValue(lo + child - 1), lo + i - 1); if (items != null) items.SetValue(items.GetValue(lo + child - 1), lo + i - 1); i = child; } keys.SetValue(d, lo + i - 1); if (items != null) items.SetValue(dt, lo + i - 1); } private void InsertionSort(int lo, int hi) { int i, j; object t, dt; for (i = lo; i < hi; i++) { j = i; t = keys.GetValue(i + 1); dt = (items != null) ? items.GetValue(i + 1) : null; while (j >= lo && comparer.Compare(t, keys.GetValue(j)) < 0) { keys.SetValue(keys.GetValue(j), j + 1); if (items != null) items.SetValue(items.GetValue(j), j + 1); j--; } keys.SetValue(t, j + 1); if (items != null) items.SetValue(dt, j + 1); } } } private sealed class SZArrayEnumerator : IEnumerator, ICloneable { private readonly Array _array; private int _index; private int _endIndex; // Cache Array.Length, since it's a little slow. internal SZArrayEnumerator(Array array) { Debug.Assert(array.Rank == 1 && array.GetLowerBound(0) == 0, "SZArrayEnumerator only works on single dimension arrays w/ a lower bound of zero."); _array = array; _index = -1; _endIndex = array.Length; } public object Clone() { return MemberwiseClone(); } public bool MoveNext() { if (_index < _endIndex) { _index++; return (_index < _endIndex); } return false; } public object Current { get { if (_index < 0) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted(); if (_index >= _endIndex) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded(); return _array.GetValue(_index); } } public void Reset() { _index = -1; } } private sealed class ArrayEnumerator : IEnumerator, ICloneable { private Array array; private int index; private int endIndex; private int startIndex; // Save for Reset. private int[] _indices; // The current position in a multidim array private bool _complete; internal ArrayEnumerator(Array array, int index, int count) { this.array = array; this.index = index - 1; startIndex = index; endIndex = index + count; _indices = new int[array.Rank]; int checkForZero = 1; // Check for dimensions of size 0. for (int i = 0; i < array.Rank; i++) { _indices[i] = array.GetLowerBound(i); checkForZero *= array.GetLength(i); } // To make MoveNext simpler, decrement least significant index. _indices[_indices.Length - 1]--; _complete = (checkForZero == 0); } private void IncArray() { // This method advances us to the next valid array index, // handling all the multiple dimension & bounds correctly. // Think of it like an odometer in your car - we start with // the last digit, increment it, and check for rollover. If // it rolls over, we set all digits to the right and including // the current to the appropriate lower bound. Do these overflow // checks for each dimension, and if the most significant digit // has rolled over it's upper bound, we're done. // int rank = array.Rank; _indices[rank - 1]++; for (int dim = rank - 1; dim >= 0; dim--) { if (_indices[dim] > array.GetUpperBound(dim)) { if (dim == 0) { _complete = true; break; } for (int j = dim; j < rank; j++) _indices[j] = array.GetLowerBound(j); _indices[dim - 1]++; } } } public object Clone() { return MemberwiseClone(); } public bool MoveNext() { if (_complete) { index = endIndex; return false; } index++; IncArray(); return !_complete; } public object Current { get { if (index < startIndex) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted(); if (_complete) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded(); return array.GetValue(_indices); } } public void Reset() { index = startIndex - 1; int checkForZero = 1; for (int i = 0; i < array.Rank; i++) { _indices[i] = array.GetLowerBound(i); checkForZero *= array.GetLength(i); } _complete = (checkForZero == 0); // To make MoveNext simpler, decrement least significant index. _indices[_indices.Length - 1]--; } } // if this is an array of value classes and that value class has a default constructor // then this calls this default constructor on every element in the value class array. // otherwise this is a no-op. Generally this method is called automatically by the compiler [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern void Initialize(); } //---------------------------------------------------------------------------------------- // ! READ THIS BEFORE YOU WORK ON THIS CLASS. // // The methods on this class must be written VERY carefully to avoid introducing security holes. // That's because they are invoked with special "this"! The "this" object // for all of these methods are not SZArrayHelper objects. Rather, they are of type U[] // where U[] is castable to T[]. No actual SZArrayHelper object is ever instantiated. Thus, you will // see a lot of expressions that cast "this" "T[]". // // This class is needed to allow an SZ array of type T[] to expose IList<T>, // IList<T.BaseType>, etc., etc. all the way up to IList<Object>. When the following call is // made: // // ((IList<T>) (new U[n])).SomeIListMethod() // // the interface stub dispatcher treats this as a special case, loads up SZArrayHelper, // finds the corresponding generic method (matched simply by method name), instantiates // it for type <T> and executes it. // // The "T" will reflect the interface used to invoke the method. The actual runtime "this" will be // array that is castable to "T[]" (i.e. for primitivs and valuetypes, it will be exactly // "T[]" - for orefs, it may be a "U[]" where U derives from T.) //---------------------------------------------------------------------------------------- internal sealed class SZArrayHelper { // It is never legal to instantiate this class. private SZArrayHelper() { Debug.Fail("Hey! How'd I get here?"); } // ----------------------------------------------------------- // ------- Implement IEnumerable<T> interface methods -------- // ----------------------------------------------------------- internal IEnumerator<T> GetEnumerator<T>() { //! Warning: "this" is an array, not an SZArrayHelper. See comments above //! or you may introduce a security hole! T[] _this = Unsafe.As<T[]>(this); return _this.Length == 0 ? SZGenericArrayEnumerator<T>.Empty : new SZGenericArrayEnumerator<T>(_this); } // ----------------------------------------------------------- // ------- Implement ICollection<T> interface methods -------- // ----------------------------------------------------------- private void CopyTo<T>(T[] array, int index) { //! Warning: "this" is an array, not an SZArrayHelper. See comments above //! or you may introduce a security hole! T[] _this = Unsafe.As<T[]>(this); Array.Copy(_this, 0, array, index, _this.Length); } internal int get_Count<T>() { //! Warning: "this" is an array, not an SZArrayHelper. See comments above //! or you may introduce a security hole! T[] _this = Unsafe.As<T[]>(this); return _this.Length; } // ----------------------------------------------------------- // ---------- Implement IList<T> interface methods ----------- // ----------------------------------------------------------- internal T get_Item<T>(int index) { //! Warning: "this" is an array, not an SZArrayHelper. See comments above //! or you may introduce a security hole! T[] _this = Unsafe.As<T[]>(this); if ((uint)index >= (uint)_this.Length) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } return _this[index]; } internal void set_Item<T>(int index, T value) { //! Warning: "this" is an array, not an SZArrayHelper. See comments above //! or you may introduce a security hole! T[] _this = Unsafe.As<T[]>(this); if ((uint)index >= (uint)_this.Length) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } _this[index] = value; } private void Add<T>(T value) { // Not meaningful for arrays. ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); } private bool Contains<T>(T value) { //! Warning: "this" is an array, not an SZArrayHelper. See comments above //! or you may introduce a security hole! T[] _this = Unsafe.As<T[]>(this); return Array.IndexOf(_this, value, 0, _this.Length) >= 0; } private bool get_IsReadOnly<T>() { return true; } private void Clear<T>() { //! Warning: "this" is an array, not an SZArrayHelper. See comments above //! or you may introduce a security hole! ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } private int IndexOf<T>(T value) { //! Warning: "this" is an array, not an SZArrayHelper. See comments above //! or you may introduce a security hole! T[] _this = Unsafe.As<T[]>(this); return Array.IndexOf(_this, value, 0, _this.Length); } private void Insert<T>(int index, T value) { // Not meaningful for arrays ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); } private bool Remove<T>(T value) { // Not meaningful for arrays ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); return default; } private void RemoveAt<T>(int index) { // Not meaningful for arrays ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); } // This is a normal generic Enumerator for SZ arrays. It doesn't have any of the "this" stuff // that SZArrayHelper does. // private sealed class SZGenericArrayEnumerator<T> : IEnumerator<T> { private readonly T[] _array; private int _index; // Array.Empty is intentionally omitted here, since we don't want to pay for generic instantiations that // wouldn't have otherwise been used. internal static readonly SZGenericArrayEnumerator<T> Empty = new SZGenericArrayEnumerator<T>(new T[0]); internal SZGenericArrayEnumerator(T[] array) { Debug.Assert(array != null); _array = array; _index = -1; } public bool MoveNext() { int index = _index + 1; if ((uint)index >= (uint)_array.Length) { _index = _array.Length; return false; } _index = index; return true; } public T Current { get { int index = _index; T[] array = _array; if ((uint)index >= (uint)array.Length) { ThrowHelper.ThrowInvalidOperationException_EnumCurrent(index); } return array[index]; } } object IEnumerator.Current => Current; void IEnumerator.Reset() => _index = -1; public void Dispose() { } } } }
39.209689
167
0.53545
[ "MIT" ]
AzureMentor/coreclr
src/System.Private.CoreLib/src/System/Array.cs
106,023
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Jc.ApiHelper { internal class TsCreator { public TsCreator() { } /// <summary> /// 生成TsCode /// </summary> public TsResultModel GetTsResultModel(string itemId, string itemType = "") { TsResultModel result = null; if (itemType.ToLower() == TsCreateType.Controller.ToString().ToLower()) { ControllerModel controller = JcApiHelper.GetController(itemId); if (controller == null) { throw new Exception("无效的ItemId."); } result = GetTsResultModel(controller); } else if (itemType.ToLower() == TsCreateType.Action.ToString().ToLower()) { ActionModel action = JcApiHelper.GetAction(itemId); if (action == null) { throw new Exception("无效的ItemId."); } result = GetTsResultModel(action); } else { PTypeModel ptype = JcApiHelper.GetPTypeModel(itemId); if (ptype == null) { throw new Exception("无效的ItemId."); } result = GetTsResultModel(ptype); } return result; } /// <summary> /// 生成TsCode /// </summary> public TsResultModel GetTsResultModel(ControllerModel controller) { TsResultModel result = new TsResultModel() { Id = controller.Id, Summary = controller.Summary }; result.Name = (string.IsNullOrEmpty(controller.AreaName) ? "" : $"{controller.AreaName}/") + controller.ControllerName; result.TsModelList = new List<TsModel>(); for (int i = 0; i < controller.ActionList.Count; i++) { ActionModel action = controller.ActionList[i]; #region 处理输入输出参数 if (action.InputParameters != null && action.InputParameters.Count > 0) { for (int j = 0; j < action.InputParameters.Count; j++) { if (action.InputParameters[j].PType.PiList != null && action.InputParameters[j].PType.PiList.Count > 0) { FillTsModelList(result.TsModelList, action.InputParameters[j].PType); } } } if (action.ReturnParameter.PType.PiList != null && action.ReturnParameter.PType.PiList.Count > 0) { FillTsModelList(result.TsModelList, action.ReturnParameter.PType); } #endregion } result.TsService = GetTsServiceModel(controller); return result; } /// <summary> /// 生成TsCode /// </summary> public TsResultModel GetTsResultModel(ActionModel action) { TsResultModel result = new TsResultModel() { Id = action.Id, Summary = action.Summary }; result.Name = (string.IsNullOrEmpty(action.AreaName) ? "" : $"{action.AreaName}/") + $"{action.ControllerName}/{action.ActionName}"; result.TsModelList = new List<TsModel>(); #region 处理输入输出参数 if (action.InputParameters != null && action.InputParameters.Count > 0) { for (int i = 0; i < action.InputParameters.Count; i++) { if (action.InputParameters[i].PType.PiList != null && action.InputParameters[i].PType.PiList.Count > 0) { FillTsModelList(result.TsModelList, action.InputParameters[i].PType); } } } if (action.ReturnParameter.PType.PiList != null && action.ReturnParameter.PType.PiList.Count > 0) { FillTsModelList(result.TsModelList, action.ReturnParameter.PType); } #endregion result.TsService = GetTsServiceModel(action); return result; } /// <summary> /// 生成TsCode /// </summary> public TsResultModel GetTsResultModel(PTypeModel ptype) { TsResultModel result = new TsResultModel() { Id = ptype.Id, Name = ptype.TypeName, Summary = ptype.Summary }; result.TsModelList = new List<TsModel>(); FillTsModelList(result.TsModelList, ptype); return result; } /// <summary> /// 获取TsModelList /// </summary> /// <param name="list"></param> /// <param name="ptype"></param> private void FillTsModelList(List<TsModel> list, PTypeModel ptype) { ptype = JcApiHelper.GetPTypeModel(ptype.Id); //读取Ptype注释内容 if (list.Any(tsPtype => tsPtype.Id == ptype.Id)) { //已添加过,不再添加 return; } if (ptype.IsIEnumerable) { //枚举类型 添加其泛型类型 PTypeModel enumItemPtype = JcApiHelper.GetPTypeModel(ptype.EnumItemId); //读取Ptype注释内容 if (enumItemPtype?.PiList?.Count > 0) { FillTsModelList(list, enumItemPtype); } return; } TsModel tsPType = new TsModel() { Id = ptype.Id, Name = GetTsType(ptype), Summary = ptype.Summary, TsModelCode = GetTsModelCode(ptype), PgQueryModelCode = GetTsQueryModelCode(ptype), PiList = new List<TsPi>() }; list.Add(tsPType); for (int i = 0; i < ptype.PiList?.Count; i++) { TsPi tsPi = new TsPi() { Name = ptype.PiList[i].Name, Summary = ptype.PiList[i].Summary, TsType = GetTsType(ptype.PiList[i].PType) }; tsPType.PiList.Add(tsPi); if (ptype.PiList[i].PType.PiList?.Count > 0) { FillTsModelList(list, ptype.PiList[i].PType); } } } /// <summary> /// 生成TsCode /// </summary> private string GetTsModelCode(PTypeModel ptype) { StringBuilder strBuilder = new StringBuilder(); string tsType = GetTsType(ptype); strBuilder.AppendLine($"/*{(string.IsNullOrEmpty(ptype.Summary) ? tsType : ptype.Summary)}*/"); strBuilder.AppendLine("export class " + tsType + " {"); for (int i = 0; i < ptype.PiList.Count; i++) { strBuilder.AppendLine($" { FirstToLower(ptype.PiList[i].Name)}: {GetTsType(ptype.PiList[i].PType)}; // " + ptype.PiList[i].Summary); } strBuilder.AppendLine("}"); strBuilder.AppendLine(); return strBuilder.ToString(); } /// <summary> /// 获取TsQueryModel /// </summary> private string GetTsQueryModelCode(PTypeModel ptype) { if(ptype.IsEnum || ptype.IsGeneric) { //排除枚举和泛型类型 return ""; } string tsType = GetTsType(ptype); StringBuilder strBuilder = new StringBuilder(); strBuilder.AppendLine($"/*{(string.IsNullOrEmpty(ptype.Summary) ? tsType : ptype.Summary)} QueryObj 分页查询对象*/"); strBuilder.AppendLine($"export class { tsType }QueryObj extends { tsType } implements IPage {{"); strBuilder.AppendLine(" pageIndex: number;"); strBuilder.AppendLine(" pageSize: number;"); strBuilder.AppendLine(" sort: string;"); strBuilder.AppendLine(" order: string;"); strBuilder.AppendLine(" constructor() {"); strBuilder.AppendLine(" super();"); strBuilder.AppendLine(" }"); strBuilder.AppendLine("}"); strBuilder.AppendLine(); return strBuilder.ToString(); } /// <summary> /// 生成TsService /// </summary> private TsServiceModel GetTsServiceModel(ControllerModel controller) { TsServiceModel tsService = new TsServiceModel(); StringBuilder jcCodeBuilder = new StringBuilder(); StringBuilder commonCodeBuilder = new StringBuilder(); StringBuilder headerCodeBuilder = new StringBuilder(); headerCodeBuilder.AppendLine("import {Injectable} from '@angular/core';"); headerCodeBuilder.AppendLine("import {Observable} from 'rxjs/Observable';"); headerCodeBuilder.AppendLine(); jcCodeBuilder.AppendLine("import {Util} from '@core/util'"); jcCodeBuilder.AppendLine(); jcCodeBuilder.AppendLine("@Injectable()"); jcCodeBuilder.AppendLine($"export class {controller.ControllerName}Service {{"); jcCodeBuilder.AppendLine(); commonCodeBuilder.AppendLine("import {HttpClient} from '@angular/common/http';"); commonCodeBuilder.AppendLine(); commonCodeBuilder.AppendLine("@Injectable()"); commonCodeBuilder.AppendLine($"export class {controller.ControllerName} {{"); commonCodeBuilder.AppendLine(); commonCodeBuilder.AppendLine(" constructor(private http: HttpClient) {"); commonCodeBuilder.AppendLine(" }"); commonCodeBuilder.AppendLine(); for (int i = 0; i < controller.ActionList.Count; i++) { ActionModel action = controller.ActionList[i]; jcCodeBuilder.AppendLine(GetTsServiceJcCode(action)); commonCodeBuilder.AppendLine(GetTsServiceCommonCode(action)); } jcCodeBuilder.AppendLine("}"); commonCodeBuilder.AppendLine("}"); tsService.JcCode = headerCodeBuilder.ToString() + jcCodeBuilder.ToString(); tsService.CommonCode = headerCodeBuilder.ToString() + commonCodeBuilder.ToString(); return tsService; } #region 获取Ts Service CodeModel /// <summary> /// 生成TsService /// </summary> private TsServiceModel GetTsServiceModel(ActionModel action) { TsServiceModel tsService = new TsServiceModel() { JcCode = GetTsServiceJcCode(action), CommonCode = GetTsServiceCommonCode(action) }; return tsService; } /// <summary> /// 生成TsService /// </summary> private string GetTsServiceJcCode(ActionModel action) { StringBuilder strBuilder = new StringBuilder(); string actionRouteName = (string.IsNullOrEmpty(action.AreaName) ? "" : $"{action.AreaName}/") + $"{action.ControllerName}/{action.ActionName}"; string inputParamStr = ""; string ajaxParamStr = ""; string returnParamTypeStr = ""; if (action.InputParameters != null && action.InputParameters.Count > 0) { if (action.InputParameters.Count == 1 && action.InputParameters[0].HasPiList == true) { inputParamStr = $"{action.InputParameters[0].Name}:{GetTsType(action.InputParameters[0].PType)}"; ajaxParamStr = $",{action.InputParameters[0].Name}"; } else if (action.InputParameters.Any(param=>param.Name.ToLower().Contains("index")) && action.InputParameters.Any(param => param.Name.ToLower().Contains("size"))) { //处理分页查询方法 string queryObjTypeName = "PgQueryObj"; if (action.ReturnParameter.PType.PiList?.Count > 0) { for (int i = 0; i < action.ReturnParameter.PType.PiList.Count; i++) { if (action.ReturnParameter.PType.PiList[i].IsIEnumerable) { PTypeModel enumPType = JcApiHelper.GetPTypeModel(action.ReturnParameter.PType.PiList[i].EnumItemId); queryObjTypeName = GetTsType(enumPType) + "QueryObj"; break; } } } inputParamStr = $"{FirstToLower(queryObjTypeName)}: {queryObjTypeName}"; ajaxParamStr = $",{FirstToLower(queryObjTypeName)}"; } else { ajaxParamStr = ",{"; for (int i = 0; i < action.InputParameters.Count; i++) { if (i > 0) { inputParamStr += ","; ajaxParamStr += ","; } inputParamStr += $"{action.InputParameters[i].Name}: {GetTsType(action.InputParameters[i].PType)}"; ajaxParamStr += $"{action.InputParameters[i].Name}: {action.InputParameters[i].Name}"; } ajaxParamStr += "}"; } } returnParamTypeStr = GetTsType(action.ReturnParameter.PType); strBuilder.AppendLine($" /*{(string.IsNullOrEmpty(action.Summary) ? action.ActionName : action.Summary)}*/"); strBuilder.AppendLine($" public { FirstToLower(action.ActionName)}({inputParamStr}): Observable<{returnParamTypeStr}>{{"); strBuilder.AppendLine($" return Util.ajax('{actionRouteName}'{ajaxParamStr});"); strBuilder.AppendLine(" }"); return strBuilder.ToString(); } /// <summary> /// 生成TsService /// </summary> private string GetTsServiceCommonCode(ActionModel action) { StringBuilder strBuilder = new StringBuilder(); string actionRouteName = (string.IsNullOrEmpty(action.AreaName) ? "" : $"{action.AreaName}/") + $"{action.ControllerName}/{action.ActionName}"; string inputParamStr = ""; string ajaxParamStr = ""; string returnParamTypeStr = ""; if (action.InputParameters != null && action.InputParameters.Count > 0) { if (action.InputParameters.Count == 1 && action.InputParameters[0].HasPiList == true) { inputParamStr = $"{action.InputParameters[0].Name}:{GetTsType(action.InputParameters[0].PType)}"; ajaxParamStr = $",{action.InputParameters[0].Name}"; } else if (action.InputParameters.Any(param => param.Name.ToLower().Contains("index")) && action.InputParameters.Any(param => param.Name.ToLower().Contains("size"))) { //处理分页查询方法 string queryObjTypeName = "PgQueryObj"; if (action.ReturnParameter.PType.PiList?.Count > 0) { for (int i = 0; i < action.ReturnParameter.PType.PiList.Count; i++) { if (action.ReturnParameter.PType.PiList[i].IsIEnumerable) { PTypeModel enumPType = JcApiHelper.GetPTypeModel(action.ReturnParameter.PType.PiList[i].EnumItemId); queryObjTypeName = GetTsType(enumPType) + "QueryObj"; break; } } } inputParamStr = $"{FirstToLower(queryObjTypeName)}: {queryObjTypeName}"; ajaxParamStr = $",{FirstToLower(queryObjTypeName)}"; } else { ajaxParamStr = ",{"; for (int i = 0; i < action.InputParameters.Count; i++) { if (i > 0) { inputParamStr += ","; ajaxParamStr += ","; } inputParamStr += $"{action.InputParameters[i].Name}: {GetTsType(action.InputParameters[i].PType)}"; ajaxParamStr += $"{action.InputParameters[i].Name}: {action.InputParameters[i].Name}"; } ajaxParamStr += "}"; } } returnParamTypeStr = GetTsType(action.ReturnParameter.PType); strBuilder.AppendLine($" /*{(string.IsNullOrEmpty(action.Summary) ? action.ActionName : action.Summary)}*/"); strBuilder.AppendLine($" public { FirstToLower(action.ActionName)}({inputParamStr}): Observable<{returnParamTypeStr}>{{"); strBuilder.AppendLine($" return this.http.post('{actionRouteName}'{ajaxParamStr});"); strBuilder.AppendLine(" }"); return strBuilder.ToString(); } #endregion #region Other Methods /// <summary> /// 首字母小写 /// </summary> /// <param name="str"></param> /// <returns></returns> private string FirstToLower(string str) { if (!string.IsNullOrEmpty(str)) { str = str.Substring(0, 1).ToLower() + str.Substring(1); } return str; } /// <summary> /// c#中的数据类型与TsType对照 /// </summary> /// <param name="ptype"></param> /// <returns></returns> private string GetTsType(PTypeModel ptype) { if (ptype == null) { return ""; } string tsTypeStr = ""; Type type = ptype.SourceType; if (type == typeof(Microsoft.AspNetCore.Mvc.IActionResult)) { tsTypeStr = "any"; } else if (ptype.IsIEnumerable) { //枚举类型特殊处理 PTypeModel enumPType = JcApiHelper.GetPTypeModel(ptype.EnumItemId); tsTypeStr = $"{GetTsType(enumPType)}[]"; } else { tsTypeStr = GetTsType(ptype.TypeName); } return tsTypeStr; } /// <summary> /// c#中的数据类型与TsType对照 /// </summary> /// <param name="typeName">类型名称</param> /// <returns></returns> private string GetTsType(string typeName) { string tsTypeStr = ""; List<string> numberTypeList = ("int,int?,int16,int16?,int32,int32?,int64,int64?,decimal,decimal?," + "double,double?,byte,byte?,long,long?,single,single?").Split(',').ToList(); List<string> boolTypeList = ("bool,bool?,boolean,boolean?").Split(',').ToList(); List<string> stringTypeList = ("string,guid,guid?").Split(',').ToList(); List<string> dateTimeTypeList = ("datetime,datetime?").Split(',').ToList(); if (boolTypeList.Contains(typeName.ToLower())) { tsTypeStr = "boolean"; } else if (stringTypeList.Contains(typeName.ToLower())) { tsTypeStr = "string"; } else if (dateTimeTypeList.Contains(typeName.ToLower())) { tsTypeStr = "Date"; } else if (numberTypeList.Contains(typeName.ToLower())) { tsTypeStr = "number"; } else { tsTypeStr = typeName; #region 去掉Dto,Model命名 if (tsTypeStr.EndsWith("Dto")) { //参数类型名称 去掉末尾Dto,Model命名 tsTypeStr = tsTypeStr.Substring(0, tsTypeStr.LastIndexOf("Dto")); } else if (tsTypeStr.EndsWith("Dto>")) { tsTypeStr = tsTypeStr.Substring(0, tsTypeStr.LastIndexOf("Dto")) + ">"; } else if (tsTypeStr.EndsWith("Model")) { tsTypeStr = tsTypeStr.Substring(0, tsTypeStr.LastIndexOf("Model")); } else if (tsTypeStr.EndsWith("Model>")) { tsTypeStr = tsTypeStr.Substring(0, tsTypeStr.LastIndexOf("Model")) + ">"; } #endregion } return tsTypeStr; } #endregion } }
40.426667
151
0.496325
[ "MIT" ]
279328316/JcApiHelper
Jc.ApiHelper/Helper/TsCreator.cs
21,550
C#
using System; using UnityEngine; using UnityEditor.ShaderGraph; using UnityEditor.ShaderGraph.Internal; using UnityEditor.Graphing; using UnityEngine.Rendering.HighDefinition; namespace UnityEditor.Rendering.HighDefinition.ShaderGraph { static class PassDescriptorExtension { public static bool IsDepthOrMV(this PassDescriptor pass) { return pass.lightMode == HDShaderPassNames.s_DepthForwardOnlyStr || pass.lightMode == HDShaderPassNames.s_DepthOnlyStr || pass.lightMode == HDShaderPassNames.s_MotionVectorsStr; } public static bool IsLightingOrMaterial(this PassDescriptor pass) { return pass.IsForward() || pass.lightMode == HDShaderPassNames.s_GBufferStr // DXR passes without visibility, prepass or path tracing || (pass.lightMode.Contains("DXR") && pass.lightMode != HDShaderPassNames.s_RayTracingVisibilityStr && pass.lightMode != HDShaderPassNames.s_PathTracingDXRStr); } public static bool IsDXR(this PassDescriptor pass) { return pass.lightMode.Contains("DXR") || pass.lightMode == HDShaderPassNames.s_RayTracingVisibilityStr || pass.lightMode == HDShaderPassNames.s_RayTracingPrepassStr; } public static bool IsForward(this PassDescriptor pass) { return pass.lightMode == HDShaderPassNames.s_ForwardOnlyStr || pass.lightMode == HDShaderPassNames.s_ForwardStr || pass.lightMode == HDShaderPassNames.s_TransparentBackfaceStr; } } }
39.166667
176
0.67234
[ "MIT" ]
ACBGZM/JasonMaToonRenderPipeline
Packages/com.unity.render-pipelines.high-definition@10.5.0/Editor/Material/ShaderGraph/PassDescriptorExtension.cs
1,645
C#
// <copyright file="FiniteString.cs" company="Microsoft"> // Copyright (c) Microsoft. All rights reserved. // </copyright> namespace ZenLib { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using static ZenLib.Language; /// <summary> /// A class representing a finite unicode string. /// </summary> public struct FiniteString : IEquatable<FiniteString> { /// <summary> /// Convert a string to a FiniteString. /// </summary> /// <param name="s">The string.</param> public static implicit operator FiniteString(string s) { return new FiniteString(s); } /// <summary> /// Create a new finite string from a string. /// </summary> /// <param name="s">The string.</param> public FiniteString(string s) { var chars = new List<ushort>(); foreach (var c in s) { chars.Add(c); } this.Characters = chars; } /// <summary> /// Creates a constant string value. /// </summary> /// <returns>The string value.</returns> public static Zen<FiniteString> Constant(string s) { var l = EmptyList<ushort>(); foreach (var c in s.Reverse()) { l = l.AddFront(c); } return Create(l); } /// <summary> /// Creates an FiniteString. /// </summary> /// <returns>The empty string.</returns> public static Zen<FiniteString> Create(Zen<IList<ushort>> values) { return Create<FiniteString>(("Characters", values)); } /// <summary> /// Creates an empty string. /// </summary> /// <returns>The empty string.</returns> public static Zen<FiniteString> Empty() { return Create(EmptyList<ushort>()); } /// <summary> /// Creates an empty string. /// </summary> /// <returns>The empty string.</returns> public static Zen<FiniteString> Singleton(Zen<ushort> b) { return Create(Language.Singleton(b)); } /// <summary> /// Gets the underlying characters. /// </summary> public IList<ushort> Characters { get; set; } /// <summary> /// Convert the finite string to a string. /// </summary> /// <returns></returns> [ExcludeFromCodeCoverage] public override string ToString() { var sb = new StringBuilder(); foreach (var c in this.Characters) { sb.Append((char)c); } return sb.ToString(); } /// <summary> /// Equality between finite strings. /// </summary> /// <param name="obj">The other object.</param> /// <returns>Whether they are equal.</returns> public override bool Equals(object obj) { return obj is FiniteString @string && Equals(@string); } /// <summary> /// Equality between finite strings. /// </summary> /// <param name="other">The other string.</param> /// <returns>Whether they are equal.</returns> public bool Equals(FiniteString other) { if (this.Characters.Count != other.Characters.Count) { return false; } return Enumerable.SequenceEqual(this.Characters, other.Characters); } /// <summary> /// Equality between finite strings. /// </summary> /// <param name="left">The left string.</param> /// <param name="right">The right string.</param> /// <returns>Whether they are equal.</returns> public static bool operator ==(FiniteString left, FiniteString right) { return left.Equals(right); } /// <summary> /// Inequality between finite strings. /// </summary> /// <param name="left">The left string.</param> /// <param name="right">The right string.</param> /// <returns></returns> public static bool operator !=(FiniteString left, FiniteString right) { return !(left == right); } /// <summary> /// Gets a hash code for the finite string. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int hash = 7; foreach (var c in this.Characters) { hash = 31 * hash + c; } return hash; } } /// <summary> /// Extension Zen methods for FiniteString types. /// </summary> public static class FiniteStringExtensions { /// <summary> /// Get whether a string is empty. /// </summary> /// <param name="s">The string.</param> /// <returns>A boolean.</returns> public static Zen<bool> IsEmpty(this Zen<FiniteString> s) { return s.GetCharacters().IsEmpty(); } /// <summary> /// Gets the list of bytes for a finite string. /// </summary> /// <param name="s">The string.</param> /// <returns>The bytes.</returns> public static Zen<IList<ushort>> GetCharacters(this Zen<FiniteString> s) { return s.GetField<FiniteString, IList<ushort>>("Characters"); } /// <summary> /// Concatenation of two strings. /// </summary> /// <param name="s1">The first string.</param> /// <param name="s2">The second string.</param> /// <returns>The concatenated string.</returns> public static Zen<FiniteString> Concat(this Zen<FiniteString> s1, Zen<FiniteString> s2) { return FiniteString.Create(s1.GetCharacters().Append(s2.GetCharacters())); } /// <summary> /// Gets the length of the string. /// </summary> /// <param name="s">The string.</param> /// <returns>The length.</returns> public static Zen<ushort> Length(this Zen<FiniteString> s) { return s.GetCharacters().Length(); } /// <summary> /// Whether a string is a prefix of another. /// </summary> /// <param name="s">The string.</param> /// <param name="pre">The prefix.</param> /// <returns>A boolean.</returns> public static Zen<bool> StartsWith(this Zen<FiniteString> s, Zen<FiniteString> pre) { return StartsWith(s.GetCharacters(), pre.GetCharacters()); } private static Zen<bool> StartsWith(Zen<IList<ushort>> s, Zen<IList<ushort>> pre) { return pre.Case( empty: true, cons: (hd1, tl1) => s.Case( empty: false, cons: (hd2, tl2) => AndIf(hd1 == hd2, StartsWith(tl2, tl1)))); } /// <summary> /// Whether a string is a suffix of another. /// </summary> /// <param name="s">The string.</param> /// <param name="suf">The suffix.</param> /// <returns>A boolean.</returns> public static Zen<bool> EndsWith(this Zen<FiniteString> s, Zen<FiniteString> suf) { return StartsWith(s.GetCharacters().Reverse(), suf.GetCharacters().Reverse()); } /// <summary> /// Substring of length 1 at the offset. /// Empty if the offset is invalid. /// </summary> /// <param name="s">The string.</param> /// <param name="i">The index.</param> /// <returns>The substring.</returns> public static Zen<FiniteString> At(this Zen<FiniteString> s, Zen<ushort> i) { return At(s.GetCharacters(), i, 0); } private static Zen<FiniteString> At(Zen<IList<ushort>> s, Zen<ushort> i, int current) { return s.Case( empty: FiniteString.Empty(), cons: (hd, tl) => If(i == (ushort)current, FiniteString.Singleton(hd), At(tl, i, current + 1))); } /// <summary> /// Whether a string contains a substring. /// </summary> /// <param name="s">The string.</param> /// <param name="sub">The substring.</param> /// <returns>A boolean.</returns> public static Zen<bool> Contains(this Zen<FiniteString> s, Zen<FiniteString> sub) { return Contains(s.GetCharacters(), sub.GetCharacters()); } private static Zen<bool> Contains(Zen<IList<ushort>> s, Zen<IList<ushort>> sub) { return s.Case( empty: sub.IsEmpty(), cons: (hd, tl) => OrIf(StartsWith(s, sub), Contains(tl, sub))); } /// <summary> /// Gets the first index of a substring in a string. /// </summary> /// <param name="s">The string.</param> /// <param name="sub">The substring.</param> /// <returns>An index.</returns> public static Zen<Option<ushort>> IndexOf(this Zen<FiniteString> s, Zen<FiniteString> sub) { return IndexOf(s.GetCharacters(), sub.GetCharacters(), 0); } private static Zen<Option<ushort>> IndexOf(Zen<IList<ushort>> s, Zen<IList<ushort>> sub, int current) { return s.Case( empty: If(sub.IsEmpty(), Some<ushort>((ushort)current), Null<ushort>()), cons: (hd, tl) => If(StartsWith(s, sub), Some<ushort>((ushort)current), IndexOf(tl, sub, current + 1))); } /// <summary> /// Gets the first index of a substring in a /// string starting at an offset. /// </summary> /// <param name="s">The string.</param> /// <param name="sub">The substring.</param> /// <param name="offset">The offset.</param> /// <returns>An index.</returns> public static Zen<Option<ushort>> IndexOf(this Zen<FiniteString> s, Zen<FiniteString> sub, Zen<ushort> offset) { var trimmed = s.GetCharacters().Drop(offset); var idx = IndexOf(trimmed, sub.GetCharacters(), 0); return If(idx.HasValue(), Some(idx.Value() + offset), idx); } /// <summary> /// Gets the substring at an offset and for a given length.. /// </summary> /// <param name="s">The string.</param> /// <param name="offset">The offset.</param> /// <param name="len">The length.</param> /// <returns>An index.</returns> public static Zen<FiniteString> SubString(this Zen<FiniteString> s, Zen<ushort> offset, Zen<ushort> len) { return FiniteString.Create(s.GetCharacters().Drop(offset).Take(len)); } /// <summary> /// Replaces all occurrences of a given character with another. /// </summary> /// <param name="s">The string.</param> /// <param name="src">The source value.</param> /// <param name="dst">The destination value.</param> /// <returns>A new string.</returns> public static Zen<FiniteString> ReplaceAll(this Zen<FiniteString> s, Zen<ushort> src, Zen<ushort> dst) { return FiniteString.Create(s.GetCharacters().Select(c => If(c == src, dst, c))); } /// <summary> /// Removes all occurrences of a given character. /// </summary> /// <param name="s">The string.</param> /// <param name="value">The value to remove.</param> /// <returns>A new string.</returns> public static Zen<FiniteString> RemoveAll(this Zen<FiniteString> s, Zen<ushort> value) { return Transform(s, l => l.Where(c => c != value)); } /// <summary> /// Transform a string by modifying its characters. /// </summary> /// <param name="s">The string.</param> /// <param name="f">The transformation function.</param> /// <returns>A new string.</returns> public static Zen<FiniteString> Transform(this Zen<FiniteString> s, Func<Zen<IList<ushort>>, Zen<IList<ushort>>> f) { return FiniteString.Create(f(s.GetCharacters())); } } }
34.395604
123
0.530112
[ "MIT" ]
filippoquaranta/Zen
ZenLib/DataTypes/FiniteString.cs
12,522
C#
using GNB.Api.App.Clients; using NUnit.Framework; using System; using System.Net.Http; using System.Threading.Tasks; namespace GNB.Api.Tests.Clients { [TestFixture] internal class HerokuAppClientTest { private HerokuAppClient herokuAppClient; [SetUp] public void SetUp() { herokuAppClient = new HerokuAppClient(new HttpClient { BaseAddress = new Uri("http://quiet-stone-2094.herokuapp.com") }); } [TestCase(Category = "UnitTest")] public async Task GetStringRatesIsNotNull() { string rates = await herokuAppClient.GetStringRates(); Assert.IsNotNull(rates); } [TestCase(Category = "UnitTest")] public async Task GetStringTransactionsIsNotNull() { string transactions = await herokuAppClient.GetStringTransactions(); Assert.IsNotNull(transactions); } } }
25.736842
80
0.609407
[ "MIT" ]
henksandoval/GNB
NUnitGNB.Api/Clients/HerokuAppClientTest.cs
980
C#
using System; using System.ComponentModel; using System.Globalization; using Devcat.Core.Design; namespace Devcat.Core.Math.GeometricAlgebra { [TypeConverter(typeof(Vector2Converter))] [Serializable] public struct Vector2 : IEquatable<Vector2> { public static Vector2 Zero { get { return Vector2._zero; } } public static Vector2 One { get { return Vector2._one; } } public static Vector2 UnitX { get { return Vector2._unitX; } } public static Vector2 UnitY { get { return Vector2._unitY; } } public Vector2(float x, float y) { this.X = x; this.Y = y; } public Vector2(float value) { this.Y = value; this.X = value; } public override string ToString() { CultureInfo currentCulture = CultureInfo.CurrentCulture; return string.Format(currentCulture, "{{X:{0} Y:{1}}}", new object[] { this.X.ToString(currentCulture), this.Y.ToString(currentCulture) }); } public bool Equals(Vector2 other) { return this.X == other.X && this.Y == other.Y; } public override bool Equals(object obj) { bool result = false; if (obj is Vector2) { result = this.Equals((Vector2)obj); } return result; } public override int GetHashCode() { return this.X.GetHashCode() + this.Y.GetHashCode(); } public float Length() { float num = this.X * this.X + this.Y * this.Y; return (float)System.Math.Sqrt((double)num); } public float LengthSquared() { return this.X * this.X + this.Y * this.Y; } public static float Distance(Vector2 value1, Vector2 value2) { float num = value1.X - value2.X; float num2 = value1.Y - value2.Y; float num3 = num * num + num2 * num2; return (float)System.Math.Sqrt((double)num3); } public static void Distance(ref Vector2 value1, ref Vector2 value2, out float result) { float num = value1.X - value2.X; float num2 = value1.Y - value2.Y; float num3 = num * num + num2 * num2; result = (float)System.Math.Sqrt((double)num3); } public static float DistanceSquared(Vector2 value1, Vector2 value2) { float num = value1.X - value2.X; float num2 = value1.Y - value2.Y; return num * num + num2 * num2; } public static void DistanceSquared(ref Vector2 value1, ref Vector2 value2, out float result) { float num = value1.X - value2.X; float num2 = value1.Y - value2.Y; result = num * num + num2 * num2; } public static float Dot(Vector2 value1, Vector2 value2) { return value1.X * value2.X + value1.Y * value2.Y; } public static void Dot(ref Vector2 value1, ref Vector2 value2, out float result) { result = value1.X * value2.X + value1.Y * value2.Y; } public void Normalize() { float num = this.X * this.X + this.Y * this.Y; float num2 = 1f / (float)System.Math.Sqrt((double)num); this.X *= num2; this.Y *= num2; } public static Vector2 Normalize(Vector2 value) { float num = value.X * value.X + value.Y * value.Y; float num2 = 1f / (float)System.Math.Sqrt((double)num); Vector2 result; result.X = value.X * num2; result.Y = value.Y * num2; return result; } public static void Normalize(ref Vector2 value, out Vector2 result) { float num = value.X * value.X + value.Y * value.Y; float num2 = 1f / (float)System.Math.Sqrt((double)num); result.X = value.X * num2; result.Y = value.Y * num2; } public static Vector2 Reflect(Vector2 vector, Vector2 normal) { float num = vector.X * normal.X + vector.Y * normal.Y; Vector2 result; result.X = vector.X - 2f * num * normal.X; result.Y = vector.Y - 2f * num * normal.Y; return result; } public static void Reflect(ref Vector2 vector, ref Vector2 normal, out Vector2 result) { float num = vector.X * normal.X + vector.Y * normal.Y; result.X = vector.X - 2f * num * normal.X; result.Y = vector.Y - 2f * num * normal.Y; } public static Vector2 Min(Vector2 value1, Vector2 value2) { Vector2 result; result.X = ((value1.X < value2.X) ? value1.X : value2.X); result.Y = ((value1.Y < value2.Y) ? value1.Y : value2.Y); return result; } public static void Min(ref Vector2 value1, ref Vector2 value2, out Vector2 result) { result.X = ((value1.X < value2.X) ? value1.X : value2.X); result.Y = ((value1.Y < value2.Y) ? value1.Y : value2.Y); } public static Vector2 Max(Vector2 value1, Vector2 value2) { Vector2 result; result.X = ((value1.X > value2.X) ? value1.X : value2.X); result.Y = ((value1.Y > value2.Y) ? value1.Y : value2.Y); return result; } public static void Max(ref Vector2 value1, ref Vector2 value2, out Vector2 result) { result.X = ((value1.X > value2.X) ? value1.X : value2.X); result.Y = ((value1.Y > value2.Y) ? value1.Y : value2.Y); } public static Vector2 Clamp(Vector2 value1, Vector2 min, Vector2 max) { float num = value1.X; num = ((num > max.X) ? max.X : num); num = ((num < min.X) ? min.X : num); float num2 = value1.Y; num2 = ((num2 > max.Y) ? max.Y : num2); num2 = ((num2 < min.Y) ? min.Y : num2); Vector2 result; result.X = num; result.Y = num2; return result; } public static void Clamp(ref Vector2 value1, ref Vector2 min, ref Vector2 max, out Vector2 result) { float num = value1.X; num = ((num > max.X) ? max.X : num); num = ((num < min.X) ? min.X : num); float num2 = value1.Y; num2 = ((num2 > max.Y) ? max.Y : num2); num2 = ((num2 < min.Y) ? min.Y : num2); result.X = num; result.Y = num2; } public static Vector2 Lerp(Vector2 value1, Vector2 value2, float amount) { Vector2 result; result.X = value1.X + (value2.X - value1.X) * amount; result.Y = value1.Y + (value2.Y - value1.Y) * amount; return result; } public static void Lerp(ref Vector2 value1, ref Vector2 value2, float amount, out Vector2 result) { result.X = value1.X + (value2.X - value1.X) * amount; result.Y = value1.Y + (value2.Y - value1.Y) * amount; } public static Vector2 Barycentric(Vector2 value1, Vector2 value2, Vector2 value3, float amount1, float amount2) { Vector2 result; result.X = value1.X + amount1 * (value2.X - value1.X) + amount2 * (value3.X - value1.X); result.Y = value1.Y + amount1 * (value2.Y - value1.Y) + amount2 * (value3.Y - value1.Y); return result; } public static void Barycentric(ref Vector2 value1, ref Vector2 value2, ref Vector2 value3, float amount1, float amount2, out Vector2 result) { result.X = value1.X + amount1 * (value2.X - value1.X) + amount2 * (value3.X - value1.X); result.Y = value1.Y + amount1 * (value2.Y - value1.Y) + amount2 * (value3.Y - value1.Y); } public static Vector2 SmoothStep(Vector2 value1, Vector2 value2, float amount) { amount = ((amount > 1f) ? 1f : ((amount < 0f) ? 0f : amount)); amount = amount * amount * (3f - 2f * amount); Vector2 result; result.X = value1.X + (value2.X - value1.X) * amount; result.Y = value1.Y + (value2.Y - value1.Y) * amount; return result; } public static void SmoothStep(ref Vector2 value1, ref Vector2 value2, float amount, out Vector2 result) { amount = ((amount > 1f) ? 1f : ((amount < 0f) ? 0f : amount)); amount = amount * amount * (3f - 2f * amount); result.X = value1.X + (value2.X - value1.X) * amount; result.Y = value1.Y + (value2.Y - value1.Y) * amount; } public static Vector2 CatmullRom(Vector2 value1, Vector2 value2, Vector2 value3, Vector2 value4, float amount) { float num = amount * amount; float num2 = amount * num; Vector2 result; result.X = 0.5f * (2f * value2.X + (-value1.X + value3.X) * amount + (2f * value1.X - 5f * value2.X + 4f * value3.X - value4.X) * num + (-value1.X + 3f * value2.X - 3f * value3.X + value4.X) * num2); result.Y = 0.5f * (2f * value2.Y + (-value1.Y + value3.Y) * amount + (2f * value1.Y - 5f * value2.Y + 4f * value3.Y - value4.Y) * num + (-value1.Y + 3f * value2.Y - 3f * value3.Y + value4.Y) * num2); return result; } public static void CatmullRom(ref Vector2 value1, ref Vector2 value2, ref Vector2 value3, ref Vector2 value4, float amount, out Vector2 result) { float num = amount * amount; float num2 = amount * num; result.X = 0.5f * (2f * value2.X + (-value1.X + value3.X) * amount + (2f * value1.X - 5f * value2.X + 4f * value3.X - value4.X) * num + (-value1.X + 3f * value2.X - 3f * value3.X + value4.X) * num2); result.Y = 0.5f * (2f * value2.Y + (-value1.Y + value3.Y) * amount + (2f * value1.Y - 5f * value2.Y + 4f * value3.Y - value4.Y) * num + (-value1.Y + 3f * value2.Y - 3f * value3.Y + value4.Y) * num2); } public static Vector2 Hermite(Vector2 value1, Vector2 tangent1, Vector2 value2, Vector2 tangent2, float amount) { float num = amount * amount; float num2 = amount * num; float num3 = 2f * num2 - 3f * num + 1f; float num4 = -2f * num2 + 3f * num; float num5 = num2 - 2f * num + amount; float num6 = num2 - num; Vector2 result; result.X = value1.X * num3 + value2.X * num4 + tangent1.X * num5 + tangent2.X * num6; result.Y = value1.Y * num3 + value2.Y * num4 + tangent1.Y * num5 + tangent2.Y * num6; return result; } public static void Hermite(ref Vector2 value1, ref Vector2 tangent1, ref Vector2 value2, ref Vector2 tangent2, float amount, out Vector2 result) { float num = amount * amount; float num2 = amount * num; float num3 = 2f * num2 - 3f * num + 1f; float num4 = -2f * num2 + 3f * num; float num5 = num2 - 2f * num + amount; float num6 = num2 - num; result.X = value1.X * num3 + value2.X * num4 + tangent1.X * num5 + tangent2.X * num6; result.Y = value1.Y * num3 + value2.Y * num4 + tangent1.Y * num5 + tangent2.Y * num6; } public static Vector2 Transform(Vector2 position, Matrix matrix) { float x = position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M41; float y = position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M42; Vector2 result; result.X = x; result.Y = y; return result; } public static void Transform(ref Vector2 position, ref Matrix matrix, out Vector2 result) { float x = position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M41; float y = position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M42; result.X = x; result.Y = y; } public static Vector2 TransformNormal(Vector2 normal, Matrix matrix) { float x = normal.X * matrix.M11 + normal.Y * matrix.M21; float y = normal.X * matrix.M12 + normal.Y * matrix.M22; Vector2 result; result.X = x; result.Y = y; return result; } public static void TransformNormal(ref Vector2 normal, ref Matrix matrix, out Vector2 result) { float x = normal.X * matrix.M11 + normal.Y * matrix.M21; float y = normal.X * matrix.M12 + normal.Y * matrix.M22; result.X = x; result.Y = y; } public static Vector2 Transform(Vector2 value, Quaternion rotation) { float num = rotation.X + rotation.X; float num2 = rotation.Y + rotation.Y; float num3 = rotation.Z + rotation.Z; float num4 = rotation.W * num3; float num5 = rotation.X * num; float num6 = rotation.X * num2; float num7 = rotation.Y * num2; float num8 = rotation.Z * num3; float x = value.X * (1f - num7 - num8) + value.Y * (num6 - num4); float y = value.X * (num6 + num4) + value.Y * (1f - num5 - num8); Vector2 result; result.X = x; result.Y = y; return result; } public static void Transform(ref Vector2 value, ref Quaternion rotation, out Vector2 result) { float num = rotation.X + rotation.X; float num2 = rotation.Y + rotation.Y; float num3 = rotation.Z + rotation.Z; float num4 = rotation.W * num3; float num5 = rotation.X * num; float num6 = rotation.X * num2; float num7 = rotation.Y * num2; float num8 = rotation.Z * num3; float x = value.X * (1f - num7 - num8) + value.Y * (num6 - num4); float y = value.X * (num6 + num4) + value.Y * (1f - num5 - num8); result.X = x; result.Y = y; } public static void Transform(Vector2[] sourceArray, ref Matrix matrix, Vector2[] destinationArray) { if (sourceArray == null) { throw new ArgumentNullException("sourceArray"); } if (destinationArray == null) { throw new ArgumentNullException("destinationArray"); } if (destinationArray.Length < sourceArray.Length) { throw new ArgumentException("NotEnoughTargetSize"); } for (int i = 0; i < sourceArray.Length; i++) { float x = sourceArray[i].X; float y = sourceArray[i].Y; destinationArray[i].X = x * matrix.M11 + y * matrix.M21 + matrix.M41; destinationArray[i].Y = x * matrix.M12 + y * matrix.M22 + matrix.M42; } } public static void Transform(Vector2[] sourceArray, int sourceIndex, ref Matrix matrix, Vector2[] destinationArray, int destinationIndex, int length) { if (sourceArray == null) { throw new ArgumentNullException("sourceArray"); } if (destinationArray == null) { throw new ArgumentNullException("destinationArray"); } if (sourceArray.Length < sourceIndex + length) { throw new ArgumentException("NotEnoughSourceSize"); } if (destinationArray.Length < destinationIndex + length) { throw new ArgumentException("NotEnoughTargetSize"); } while (length > 0) { float x = sourceArray[sourceIndex].X; float y = sourceArray[sourceIndex].Y; destinationArray[destinationIndex].X = x * matrix.M11 + y * matrix.M21 + matrix.M41; destinationArray[destinationIndex].Y = x * matrix.M12 + y * matrix.M22 + matrix.M42; sourceIndex++; destinationIndex++; length--; } } public static void TransformNormal(Vector2[] sourceArray, ref Matrix matrix, Vector2[] destinationArray) { if (sourceArray == null) { throw new ArgumentNullException("sourceArray"); } if (destinationArray == null) { throw new ArgumentNullException("destinationArray"); } if (destinationArray.Length < sourceArray.Length) { throw new ArgumentException("NotEnoughTargetSize"); } for (int i = 0; i < sourceArray.Length; i++) { float x = sourceArray[i].X; float y = sourceArray[i].Y; destinationArray[i].X = x * matrix.M11 + y * matrix.M21; destinationArray[i].Y = x * matrix.M12 + y * matrix.M22; } } public static void TransformNormal(Vector2[] sourceArray, int sourceIndex, ref Matrix matrix, Vector2[] destinationArray, int destinationIndex, int length) { if (sourceArray == null) { throw new ArgumentNullException("sourceArray"); } if (destinationArray == null) { throw new ArgumentNullException("destinationArray"); } if (sourceArray.Length < sourceIndex + length) { throw new ArgumentException("NotEnoughSourceSize"); } if (destinationArray.Length < destinationIndex + length) { throw new ArgumentException("NotEnoughTargetSize"); } while (length > 0) { float x = sourceArray[sourceIndex].X; float y = sourceArray[sourceIndex].Y; destinationArray[destinationIndex].X = x * matrix.M11 + y * matrix.M21; destinationArray[destinationIndex].Y = x * matrix.M12 + y * matrix.M22; sourceIndex++; destinationIndex++; length--; } } public static void Transform(Vector2[] sourceArray, ref Quaternion rotation, Vector2[] destinationArray) { if (sourceArray == null) { throw new ArgumentNullException("sourceArray"); } if (destinationArray == null) { throw new ArgumentNullException("destinationArray"); } if (destinationArray.Length < sourceArray.Length) { throw new ArgumentException("NotEnoughTargetSize"); } float num = rotation.X + rotation.X; float num2 = rotation.Y + rotation.Y; float num3 = rotation.Z + rotation.Z; float num4 = rotation.W * num3; float num5 = rotation.X * num; float num6 = rotation.X * num2; float num7 = rotation.Y * num2; float num8 = rotation.Z * num3; float num9 = 1f - num7 - num8; float num10 = num6 - num4; float num11 = num6 + num4; float num12 = 1f - num5 - num8; for (int i = 0; i < sourceArray.Length; i++) { float x = sourceArray[i].X; float y = sourceArray[i].Y; destinationArray[i].X = x * num9 + y * num10; destinationArray[i].Y = x * num11 + y * num12; } } public static void Transform(Vector2[] sourceArray, int sourceIndex, ref Quaternion rotation, Vector2[] destinationArray, int destinationIndex, int length) { if (sourceArray == null) { throw new ArgumentNullException("sourceArray"); } if (destinationArray == null) { throw new ArgumentNullException("destinationArray"); } if (sourceArray.Length < sourceIndex + length) { throw new ArgumentException("NotEnoughSourceSize"); } if (destinationArray.Length < destinationIndex + length) { throw new ArgumentException("NotEnoughTargetSize"); } float num = rotation.X + rotation.X; float num2 = rotation.Y + rotation.Y; float num3 = rotation.Z + rotation.Z; float num4 = rotation.W * num3; float num5 = rotation.X * num; float num6 = rotation.X * num2; float num7 = rotation.Y * num2; float num8 = rotation.Z * num3; float num9 = 1f - num7 - num8; float num10 = num6 - num4; float num11 = num6 + num4; float num12 = 1f - num5 - num8; while (length > 0) { float x = sourceArray[sourceIndex].X; float y = sourceArray[sourceIndex].Y; destinationArray[destinationIndex].X = x * num9 + y * num10; destinationArray[destinationIndex].Y = x * num11 + y * num12; sourceIndex++; destinationIndex++; length--; } } public static Vector2 Negate(Vector2 value) { Vector2 result; result.X = -value.X; result.Y = -value.Y; return result; } public static void Negate(ref Vector2 value, out Vector2 result) { result.X = -value.X; result.Y = -value.Y; } public static Vector2 Add(Vector2 value1, Vector2 value2) { Vector2 result; result.X = value1.X + value2.X; result.Y = value1.Y + value2.Y; return result; } public static void Add(ref Vector2 value1, ref Vector2 value2, out Vector2 result) { result.X = value1.X + value2.X; result.Y = value1.Y + value2.Y; } public static Vector2 Subtract(Vector2 value1, Vector2 value2) { Vector2 result; result.X = value1.X - value2.X; result.Y = value1.Y - value2.Y; return result; } public static void Subtract(ref Vector2 value1, ref Vector2 value2, out Vector2 result) { result.X = value1.X - value2.X; result.Y = value1.Y - value2.Y; } public static Vector2 Multiply(Vector2 value1, Vector2 value2) { Vector2 result; result.X = value1.X * value2.X; result.Y = value1.Y * value2.Y; return result; } public static void Multiply(ref Vector2 value1, ref Vector2 value2, out Vector2 result) { result.X = value1.X * value2.X; result.Y = value1.Y * value2.Y; } public static Vector2 Multiply(Vector2 value1, float scaleFactor) { Vector2 result; result.X = value1.X * scaleFactor; result.Y = value1.Y * scaleFactor; return result; } public static void Multiply(ref Vector2 value1, float scaleFactor, out Vector2 result) { result.X = value1.X * scaleFactor; result.Y = value1.Y * scaleFactor; } public static Vector2 Divide(Vector2 value1, Vector2 value2) { Vector2 result; result.X = value1.X / value2.X; result.Y = value1.Y / value2.Y; return result; } public static void Divide(ref Vector2 value1, ref Vector2 value2, out Vector2 result) { result.X = value1.X / value2.X; result.Y = value1.Y / value2.Y; } public static Vector2 Divide(Vector2 value1, float divider) { float num = 1f / divider; Vector2 result; result.X = value1.X * num; result.Y = value1.Y * num; return result; } public static void Divide(ref Vector2 value1, float divider, out Vector2 result) { float num = 1f / divider; result.X = value1.X * num; result.Y = value1.Y * num; } public static Vector2 operator -(Vector2 value) { Vector2 result; result.X = -value.X; result.Y = -value.Y; return result; } public static bool operator ==(Vector2 value1, Vector2 value2) { return value1.X == value2.X && value1.Y == value2.Y; } public static bool operator !=(Vector2 value1, Vector2 value2) { return value1.X != value2.X || value1.Y != value2.Y; } public static Vector2 operator +(Vector2 value1, Vector2 value2) { Vector2 result; result.X = value1.X + value2.X; result.Y = value1.Y + value2.Y; return result; } public static Vector2 operator -(Vector2 value1, Vector2 value2) { Vector2 result; result.X = value1.X - value2.X; result.Y = value1.Y - value2.Y; return result; } public static Vector2 operator *(Vector2 value1, Vector2 value2) { Vector2 result; result.X = value1.X * value2.X; result.Y = value1.Y * value2.Y; return result; } public static Vector2 operator *(Vector2 value, float scaleFactor) { Vector2 result; result.X = value.X * scaleFactor; result.Y = value.Y * scaleFactor; return result; } public static Vector2 operator *(float scaleFactor, Vector2 value) { Vector2 result; result.X = value.X * scaleFactor; result.Y = value.Y * scaleFactor; return result; } public static Vector2 operator /(Vector2 value1, Vector2 value2) { Vector2 result; result.X = value1.X / value2.X; result.Y = value1.Y / value2.Y; return result; } public static Vector2 operator /(Vector2 value1, float divider) { float num = 1f / divider; Vector2 result; result.X = value1.X * num; result.Y = value1.Y * num; return result; } public float X; public float Y; private static Vector2 _zero = default(Vector2); private static Vector2 _one = new Vector2(1f, 1f); private static Vector2 _unitX = new Vector2(1f, 0f); private static Vector2 _unitY = new Vector2(0f, 1f); } }
28.836387
202
0.644456
[ "MIT" ]
ulkyome/laucher_server
Core/Math/GeometricAlgebra/Vector2.cs
22,033
C#
/***************************************************************************************************************************************** Author: Michael Shoots Email: michael.shoots@live.com Project: Open Space 4x License: MIT License Notes: ******************************************************************************************************************************************/ using UnityEngine; using System.Collections.Generic; public class HardPoints : MonoBehaviour { public List<HardPointSet> foreWeaponHardPoints; public List<HardPointSet> aftWeaponHardPoints; public List<HardPointSet> portWeaponHardPoints; public List<HardPointSet> starboardWeaponHardPoints; public List<GameObject> damageHardPoints = new List<GameObject>(); public void DestroyAllObjects() { foreach(HardPointSet set in foreWeaponHardPoints) { set.DestroyChildren(); Destroy(set.gameObject); } foreach (HardPointSet set in aftWeaponHardPoints) { set.DestroyChildren(); Destroy(set.gameObject); } foreach (HardPointSet set in portWeaponHardPoints) { set.DestroyChildren(); Destroy(set.gameObject); } foreach (HardPointSet set in starboardWeaponHardPoints) { set.DestroyChildren(); Destroy(set.gameObject); } foreach (GameObject point in damageHardPoints) { Destroy(point); } } }
29.423077
139
0.522222
[ "MIT" ]
McShooterz/OpenSpace4x
Assets/Scripts/Data/HardPoints.cs
1,532
C#
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; using System.Linq; using NUnit.Framework; namespace ICSharpCode.AvalonEdit.Document { [TestFixture] public class ChangeTrackingTest { [Test] public void NoChanges() { TextDocument document = new TextDocument("initial text"); ChangeTrackingCheckpoint checkpoint1, checkpoint2; ITextSource snapshot1 = document.CreateSnapshot(out checkpoint1); ITextSource snapshot2 = document.CreateSnapshot(out checkpoint2); Assert.AreEqual(0, checkpoint1.CompareAge(checkpoint2)); Assert.AreEqual(0, checkpoint1.GetChangesTo(checkpoint2).Count()); Assert.AreEqual(document.Text, snapshot1.Text); Assert.AreEqual(document.Text, snapshot2.Text); } [Test] public void ForwardChanges() { TextDocument document = new TextDocument("initial text"); ChangeTrackingCheckpoint checkpoint1, checkpoint2; ITextSource snapshot1 = document.CreateSnapshot(out checkpoint1); document.Replace(0, 7, "nw"); document.Insert(1, "e"); ITextSource snapshot2 = document.CreateSnapshot(out checkpoint2); Assert.AreEqual(-1, checkpoint1.CompareAge(checkpoint2)); DocumentChangeEventArgs[] arr = checkpoint1.GetChangesTo(checkpoint2).ToArray(); Assert.AreEqual(2, arr.Length); Assert.AreEqual("nw", arr[0].InsertedText); Assert.AreEqual("e", arr[1].InsertedText); Assert.AreEqual("initial text", snapshot1.Text); Assert.AreEqual("new text", snapshot2.Text); } [Test] public void BackwardChanges() { TextDocument document = new TextDocument("initial text"); ChangeTrackingCheckpoint checkpoint1, checkpoint2; ITextSource snapshot1 = document.CreateSnapshot(out checkpoint1); document.Replace(0, 7, "nw"); document.Insert(1, "e"); ITextSource snapshot2 = document.CreateSnapshot(out checkpoint2); Assert.AreEqual(1, checkpoint2.CompareAge(checkpoint1)); DocumentChangeEventArgs[] arr = checkpoint2.GetChangesTo(checkpoint1).ToArray(); Assert.AreEqual(2, arr.Length); Assert.AreEqual("", arr[0].InsertedText); Assert.AreEqual("initial", arr[1].InsertedText); Assert.AreEqual("initial text", snapshot1.Text); Assert.AreEqual("new text", snapshot2.Text); } } }
36.415385
103
0.744825
[ "MIT" ]
4lab/ILSpy
AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/ChangeTrackingTest.cs
2,369
C#
namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Parameter)] public class MaybeNullWhenAttribute : Attribute { public MaybeNullWhenAttribute( bool returnValue) { this.ReturnValue = returnValue; } public bool ReturnValue { get; } } }
21.4375
48
0.618076
[ "Apache-2.0" ]
aetos382/PowerShell.StorageDevice
PSAsync.CodeGenerator/MaybeNullWhenAttribute.cs
345
C#
using System; using System.Collections.Concurrent; using System.Data; namespace NHulk.DynamicCache { public static class SqlDelegate<T> { public delegate void GetCommandByInstance(ref IDbCommand source, object instance); public delegate void GetGenericCommand(ref IDbCommand source, T instance); public delegate void GetCommandByObject(ref IDbCommand source, object[] instances); public delegate T GetReaderInstance(IDataReader reader); public readonly static ConcurrentDictionary<int, ConcurrentDictionary<string, GetCommandByInstance>> CommandInstancesCache; public readonly static ConcurrentDictionary<string, GetCommandByObject> CommandObjectsCache; public readonly static ConcurrentDictionary<string, GetReaderInstance> SingleReaderCache; public readonly static ConcurrentDictionary<string, GetGenericCommand> CommandGenericCache; public readonly static ConcurrentDictionary<Tuple<string,int,int>, GetReaderInstance> ComplexReaderCache; static SqlDelegate() { CommandInstancesCache = new ConcurrentDictionary<int, ConcurrentDictionary<string, GetCommandByInstance>>(); CommandObjectsCache = new ConcurrentDictionary<string, GetCommandByObject>(); CommandGenericCache = new ConcurrentDictionary<string, GetGenericCommand>(); SingleReaderCache = new ConcurrentDictionary<string, GetReaderInstance>(); ComplexReaderCache = new ConcurrentDictionary<Tuple<string, int, int>, GetReaderInstance>(); } } }
54.275862
131
0.757306
[ "MIT" ]
huangweiboy/NHulk
NHulk/OrmCache/SqlDelegate.cs
1,576
C#
//------------------------------------------------------------------------------ // <自动生成> // 此代码由工具生成。 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </自动生成> //------------------------------------------------------------------------------ namespace EIS.Web.Mail { public partial class MailWrite { /// <summary> /// Head1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlHead Head1; /// <summary> /// form1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; /// <summary> /// LinkButton1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.LinkButton LinkButton1; /// <summary> /// LinkButton2 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.LinkButton LinkButton2; /// <summary> /// TO_NAME 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox TO_NAME; /// <summary> /// TO_ID 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox TO_ID; /// <summary> /// CC_Name 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox CC_Name; /// <summary> /// CC_ID 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox CC_ID; /// <summary> /// BCC_Name 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox BCC_Name; /// <summary> /// BCC_ID 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox BCC_ID; /// <summary> /// Out_ID 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox Out_ID; /// <summary> /// Out_Name 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox Out_Name; /// <summary> /// Subject 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox Subject; /// <summary> /// MailBody 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox MailBody; } }
27.528169
81
0.461499
[ "MIT" ]
chen1993nian/CPMPlatform
Dev/Mail/MailWrite.aspx.designer.cs
5,115
C#
namespace EA.Weee.Core.AatfReturn { using System; using System.ComponentModel.DataAnnotations; [Serializable] public enum FacilityType { [Display(Name = "AATF")] Aatf = 1, [Display(Name = "AE")] Ae = 2 } }
17.6
48
0.568182
[ "Unlicense" ]
DEFRA/prsd-weee
src/EA.Weee.Core/AatfReturn/FacilityType.cs
266
C#
using System; namespace bc.Framework { /// <summary> /// /// </summary> public struct ProbabilisticItem<T> : IEquatable<ProbabilisticItem<T>> where T : IEquatable<T> { public T Item { get; init; } public double Probability { get; init; } public bool Equals(ProbabilisticItem<T> other) => Item.Equals(other.Item) && Probability.Equals(other.Probability); public override bool Equals(object obj) => obj is ProbabilisticItem<T> other && this.Equals(other); public override int GetHashCode() => (Item, Probability).GetHashCode(); public static bool operator ==(ProbabilisticItem<T> lhs, ProbabilisticItem<T> rhs) => lhs.Probability.Equals(rhs.Probability) && lhs.Item.Equals(rhs.Item); public static bool operator !=(ProbabilisticItem<T> lhs, ProbabilisticItem<T> rhs) => !lhs.Probability.Equals(rhs.Probability) || !lhs.Item.Equals(rhs.Item); public static implicit operator ProbabilisticItem<T>(T item) => new ProbabilisticItem<T> { Item = item, Probability = 1.0 }; public static implicit operator ProbabilisticItem<T>((T item, double probability) pair) => new ProbabilisticItem<T> { Item = pair.item, Probability = pair.probability}; } }
43.655172
176
0.673776
[ "MIT" ]
bcbodily/lsystem
src/bc/Framework/ProbabilisticItem.cs
1,266
C#
using System; namespace Vertical.HubSpot.Api.Data { /// <summary> /// attribute indicating id property /// </summary> public class HubspotIdAttribute : Attribute { } }
17.363636
49
0.643979
[ "MIT" ]
loker0/hubspot-api
Vertical.HubSpot.Api/Data/HubspotIdAttribute.cs
193
C#
using System; using NetRuntimeSystem = System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.ComponentModel; using System.Reflection; using System.Collections.Generic; using NetOffice; namespace NetOffice.VisioApi { ///<summary> /// DispatchInterface IVStatusBarItem /// SupportByVersion Visio, 11,12,14,15,16 ///</summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] [EntityTypeAttribute(EntityType.IsDispatchInterface)] public class IVStatusBarItem : COMObject { #pragma warning disable #region Type Information private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(IVStatusBarItem); return _type; } } #endregion #region Construction ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public IVStatusBarItem(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IVStatusBarItem(COMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IVStatusBarItem(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IVStatusBarItem(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IVStatusBarItem(COMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IVStatusBarItem() : base() { } /// <param name="progId">registered ProgID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IVStatusBarItem(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public string Default { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Default", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int32 Index { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Index", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public NetOffice.VisioApi.IVStatusBarItems Parent { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Parent", paramsArray); NetOffice.VisioApi.IVStatusBarItems newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.VisioApi.IVStatusBarItems; return newObject; } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int16 CmdNum { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "CmdNum", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "CmdNum", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Int16 HelpContextID { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "HelpContextID", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "HelpContextID", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public string ActionText { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ActionText", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ActionText", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public string AddOnName { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "AddOnName", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "AddOnName", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public string AddOnArgs { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "AddOnArgs", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "AddOnArgs", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public string HelpFile { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "HelpFile", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "HelpFile", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int16 CntrlType { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "CntrlType", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "CntrlType", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Int16 CntrlID { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "CntrlID", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "CntrlID", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int16 TypeSpecific1 { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "TypeSpecific1", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "TypeSpecific1", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Int16 Priority { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Priority", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Priority", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Int16 Spacing { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Spacing", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Spacing", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int16 TypeSpecific2 { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "TypeSpecific2", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "TypeSpecific2", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public string Caption { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Caption", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Caption", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public string MiniHelp { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "MiniHelp", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "MiniHelp", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public bool BuiltIn { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "BuiltIn", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public bool Enabled { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Enabled", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Enabled", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int16 FaceID { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "FaceID", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "FaceID", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int16 State { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "State", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "State", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int16 Style { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Style", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Style", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public bool Visible { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Visible", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Visible", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int16 Width { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Width", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Width", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int16 PaletteWidth { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "PaletteWidth", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "PaletteWidth", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public NetOffice.VisioApi.IVStatusBarItems StatusBarItems { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "StatusBarItems", paramsArray); NetOffice.VisioApi.IVStatusBarItems newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.VisioApi.IVStatusBarItems; return newObject; } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Int16 IsSeparator { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "IsSeparator", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int16 IsHierarchical { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "IsHierarchical", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } } #endregion #region Methods /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public void Delete() { object[] paramsArray = null; Invoker.Method(this, "Delete", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// /// </summary> /// <param name="iconFileName">string IconFileName</param> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public void IconFileName(string iconFileName) { object[] paramsArray = Invoker.ValidateParamsArray(iconFileName); Invoker.Method(this, "IconFileName", paramsArray); } #endregion #pragma warning restore } }
27.133536
169
0.672054
[ "MIT" ]
Engineerumair/NetOffice
Source/Visio/DispatchInterfaces/IVStatusBarItem.cs
17,883
C#
namespace BookStore.Web.Controllers { using System.Security.Claims; using BookStore.Services.Data.Book; using BookStore.Web.ViewModels.Author; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; public class AuthorController : Controller { private readonly IAuthorService authorService; private readonly IHttpContextAccessor httpContextAccessor; public AuthorController(IAuthorService authorService, IHttpContextAccessor httpContextAccessor) { this.authorService = authorService; this.httpContextAccessor = httpContextAccessor; } [Authorize] [HttpGet] public IActionResult RegistarAuthor() => this.View(); [HttpPost] [Authorize] public IActionResult RegistarAuthor(RegistarAuthorModel model) { var userId = this.httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; if (!this.ModelState.IsValid) { return this.View(); } this.authorService.AddAuthorInSystem(model, userId); return this.Redirect("/Book/Create"); } } }
28.659091
110
0.659001
[ "MIT" ]
Anzzhhela98/C-Web
ASP.NET Core/Web/BookStore.Web/Controllers/Author/AuthorController.cs
1,263
C#
using System.Collections.Generic; using System.Runtime.CompilerServices; using Jint.Native.Object; using Jint.Native.Symbol; using Jint.Runtime; using Jint.Runtime.Descriptors; namespace Jint.Native.Array { public class ArrayInstance : ObjectInstance { internal PropertyDescriptor _length; private const int MaxDenseArrayLength = 1024 * 10; private const ulong MaxArrayLength = 4294967295; // we have dense and sparse, we usually can start with dense and fall back to sparse when necessary internal PropertyDescriptor[] _dense; private Dictionary<uint, PropertyDescriptor> _sparse; public ArrayInstance(Engine engine, uint capacity = 0) : base(engine, ObjectClass.Array) { if (capacity < MaxDenseArrayLength) { _dense = capacity > 0 ? new PropertyDescriptor[capacity] : System.Array.Empty<PropertyDescriptor>(); } else { _sparse = new Dictionary<uint, PropertyDescriptor>((int) (capacity <= 1024 ? capacity : 1024)); } } /// <summary> /// Possibility to construct valid array fast, requires that supplied array does not have holes. /// </summary> public ArrayInstance(Engine engine, PropertyDescriptor[] items) : base(engine, ObjectClass.Array) { int length = 0; if (items == null || items.Length == 0) { _dense = System.Array.Empty<PropertyDescriptor>(); length = 0; } else { _dense = items; length = items.Length; } _length = new PropertyDescriptor(length, PropertyFlag.OnlyWritable); } public ArrayInstance(Engine engine, Dictionary<uint, PropertyDescriptor> items) : base(engine, ObjectClass.Array) { _sparse = items; var length = items?.Count ?? 0; _length = new PropertyDescriptor(length, PropertyFlag.OnlyWritable); } public override bool IsArrayLike => true; internal override bool HasOriginalIterator => ReferenceEquals(Get(GlobalSymbolRegistry.Iterator), _engine.Array.PrototypeObject._originalIteratorFunction); public override bool DefineOwnProperty(JsValue property, PropertyDescriptor desc) { var oldLenDesc = _length; var oldLen = (uint) TypeConverter.ToNumber(oldLenDesc.Value); if (property == CommonProperties.Length) { var value = desc.Value; if (ReferenceEquals(value, null)) { return base.DefineOwnProperty(CommonProperties.Length, desc); } var newLenDesc = new PropertyDescriptor(desc); uint newLen = TypeConverter.ToUint32(value); if (newLen != TypeConverter.ToNumber(value)) { ExceptionHelper.ThrowRangeError(_engine); } newLenDesc.Value = newLen; if (newLen >= oldLen) { return base.DefineOwnProperty(CommonProperties.Length, newLenDesc); } if (!oldLenDesc.Writable) { return false; } bool newWritable; if (!newLenDesc.WritableSet || newLenDesc.Writable) { newWritable = true; } else { newWritable = false; newLenDesc.Writable = true; } var succeeded = base.DefineOwnProperty(CommonProperties.Length, newLenDesc); if (!succeeded) { return false; } var count = _dense?.Length ?? _sparse.Count; if (count < oldLen - newLen) { if (_dense != null) { for (uint keyIndex = 0; keyIndex < _dense.Length; ++keyIndex) { if (_dense[keyIndex] == null) { continue; } // is it the index of the array if (keyIndex >= newLen && keyIndex < oldLen) { var deleteSucceeded = Delete(keyIndex); if (!deleteSucceeded) { newLenDesc.Value = keyIndex + 1; if (!newWritable) { newLenDesc.Writable = false; } base.DefineOwnProperty(CommonProperties.Length, newLenDesc); return false; } } } } else { // in the case of sparse arrays, treat each concrete element instead of // iterating over all indexes var keys = new List<uint>(_sparse.Keys); var keysCount = keys.Count; for (var i = 0; i < keysCount; i++) { var keyIndex = keys[i]; // is it the index of the array if (keyIndex >= newLen && keyIndex < oldLen) { var deleteSucceeded = Delete(TypeConverter.ToString(keyIndex)); if (!deleteSucceeded) { newLenDesc.Value = JsNumber.Create(keyIndex + 1); if (!newWritable) { newLenDesc.Writable = false; } base.DefineOwnProperty(CommonProperties.Length, newLenDesc); return false; } } } } } else { while (newLen < oldLen) { // algorithm as per the spec oldLen--; var deleteSucceeded = Delete(oldLen); if (!deleteSucceeded) { newLenDesc.Value = oldLen + 1; if (!newWritable) { newLenDesc.Writable = false; } base.DefineOwnProperty(CommonProperties.Length, newLenDesc); return false; } } } if (!newWritable) { base.DefineOwnProperty(CommonProperties.Length, new PropertyDescriptor(value: null, PropertyFlag.WritableSet)); } return true; } else if (IsArrayIndex(property, out var index)) { if (index >= oldLen && !oldLenDesc.Writable) { return false; } var succeeded = base.DefineOwnProperty(property, desc); if (!succeeded) { return false; } if (index >= oldLen) { oldLenDesc.Value = index + 1; base.DefineOwnProperty(CommonProperties.Length, oldLenDesc); } return true; } return base.DefineOwnProperty(property, desc); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal uint GetLength() { if (_length is null) { return 0; } return (uint) ((JsNumber) _length._value)._value; } protected override void AddProperty(JsValue property, PropertyDescriptor descriptor) { if (property == CommonProperties.Length) { _length = descriptor; return; } base.AddProperty(property, descriptor); } protected override bool TryGetProperty(JsValue property, out PropertyDescriptor descriptor) { if (property == CommonProperties.Length) { descriptor = _length; return _length != null; } return base.TryGetProperty(property, out descriptor); } public override List<JsValue> GetOwnPropertyKeys(Types types) { var properties = new List<JsValue>(_dense?.Length ?? 0 + 1); if (_dense != null) { var length = System.Math.Min(_dense.Length, GetLength()); for (var i = 0; i < length; i++) { if (_dense[i] != null) { properties.Add(JsString.Create(i)); } } } else { foreach (var entry in _sparse) { properties.Add(JsString.Create(entry.Key)); } } if (_length != null) { properties.Add(CommonProperties.Length); } properties.AddRange(base.GetOwnPropertyKeys(types)); return properties; } public override IEnumerable<KeyValuePair<JsValue, PropertyDescriptor>> GetOwnProperties() { if (_dense != null) { var length = System.Math.Min(_dense.Length, GetLength()); for (var i = 0; i < length; i++) { if (_dense[i] != null) { yield return new KeyValuePair<JsValue, PropertyDescriptor>(TypeConverter.ToString(i), _dense[i]); } } } else { foreach (var entry in _sparse) { yield return new KeyValuePair<JsValue, PropertyDescriptor>(TypeConverter.ToString(entry.Key), entry.Value); } } if (_length != null) { yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Length, _length); } foreach (var entry in base.GetOwnProperties()) { yield return entry; } } public override PropertyDescriptor GetOwnProperty(JsValue property) { if (property == CommonProperties.Length) { return _length ?? PropertyDescriptor.Undefined; } if (IsArrayIndex(property, out var index)) { if (TryGetDescriptor(index, out var result)) { return result; } return PropertyDescriptor.Undefined; } return base.GetOwnProperty(property); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private PropertyDescriptor GetOwnProperty(uint index) { return TryGetDescriptor(index, out var result) ? result : PropertyDescriptor.Undefined; } internal JsValue Get(uint index) { var prop = GetOwnProperty(index); if (prop == PropertyDescriptor.Undefined) { prop = Prototype?.GetProperty(index) ?? PropertyDescriptor.Undefined; } return UnwrapJsValue(prop); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private PropertyDescriptor GetProperty(uint index) { var prop = GetOwnProperty(index); if (prop != PropertyDescriptor.Undefined) { return prop; } return Prototype?.GetProperty(index) ?? PropertyDescriptor.Undefined; } protected internal override void SetOwnProperty(JsValue property, PropertyDescriptor desc) { if (IsArrayIndex(property, out var index)) { WriteArrayValue(index, desc); } else if (property == CommonProperties.Length) { _length = desc; } else { base.SetOwnProperty(property, desc); } } public override bool HasOwnProperty(JsValue p) { if (IsArrayIndex(p, out var index)) { return index < GetLength() && (_sparse == null || _sparse.ContainsKey(index)) && (_dense == null || (index < (uint) _dense.Length && _dense[index] != null)); } if (p == CommonProperties.Length) { return _length != null; } return base.HasOwnProperty(p); } public override void RemoveOwnProperty(JsValue p) { if (IsArrayIndex(p, out var index)) { Delete(index); } if (p == CommonProperties.Length) { _length = null; } base.RemoveOwnProperty(p); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsArrayIndex(JsValue p, out uint index) { if (p is JsNumber number) { var value = number._value; var intValue = (uint) value; index = intValue; return value == intValue && intValue != uint.MaxValue; } index = ParseArrayIndex(p.ToString()); return index != uint.MaxValue; // 15.4 - Use an optimized version of the specification // return TypeConverter.ToString(index) == TypeConverter.ToString(p) && index != uint.MaxValue; } private static uint ParseArrayIndex(string p) { if (p.Length == 0) { return uint.MaxValue; } int d = p[0] - '0'; if (d < 0 || d > 9) { return uint.MaxValue; } if (d == 0 && p.Length > 1) { // If p is a number that start with '0' and is not '0' then // its ToString representation can't be the same a p. This is // not a valid array index. '01' !== ToString(ToUInt32('01')) // http://www.ecma-international.org/ecma-262/5.1/#sec-15.4 return uint.MaxValue; } if (p.Length > 1) { return StringAsIndex(d, p); } return (uint) d; } private static uint StringAsIndex(int d, string p) { ulong result = (uint) d; for (int i = 1; i < p.Length; i++) { d = p[i] - '0'; if (d < 0 || d > 9) { return uint.MaxValue; } result = result * 10 + (uint) d; if (result >= uint.MaxValue) { return uint.MaxValue; } } return (uint) result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void SetIndexValue(uint index, JsValue value, bool updateLength) { if (updateLength) { var length = GetLength(); if (index >= length) { SetLength(index + 1); } } WriteArrayValue(index, new PropertyDescriptor(value, PropertyFlag.ConfigurableEnumerableWritable)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void SetLength(uint length) { _length.Value = length; } internal uint GetSmallestIndex() { if (_dense != null) { return 0; } uint smallest = 0; // only try to help if collection reasonable small if (_sparse.Count > 0 && _sparse.Count < 100 && !_sparse.ContainsKey(0)) { smallest = uint.MaxValue; foreach (var key in _sparse.Keys) { smallest = System.Math.Min(key, smallest); } } return smallest; } public bool TryGetValue(uint index, out JsValue value) { value = Undefined; if (!TryGetDescriptor(index, out var desc)) { desc = GetProperty(index); } return desc.TryGetValue(this, out value); } internal bool DeletePropertyOrThrow(uint index) { if (!Delete(index)) { ExceptionHelper.ThrowTypeError(Engine); } return true; } internal bool Delete(uint index) { var desc = GetOwnProperty(index); if (desc == PropertyDescriptor.Undefined) { return true; } if (desc.Configurable) { DeleteAt(index); return true; } return false; } internal bool DeleteAt(uint index) { var temp = _dense; if (temp != null) { if (index < (uint) temp.Length) { temp[index] = null; return true; } } else { return _sparse.Remove(index); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool TryGetDescriptor(uint index, out PropertyDescriptor descriptor) { var temp = _dense; if (temp != null) { descriptor = null; if (index < (uint) temp.Length) { descriptor = temp[index]; } return descriptor != null; } return _sparse.TryGetValue(index, out descriptor); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void WriteArrayValue(uint index, PropertyDescriptor desc) { // calculate eagerly so we know if we outgrow var newSize = _dense != null && index >= (uint) _dense.Length ? System.Math.Max(index, System.Math.Max(_dense.Length, 2)) * 2 : 0; bool canUseDense = _dense != null && index < MaxDenseArrayLength && newSize < MaxDenseArrayLength && index < _dense.Length + 50; // looks sparse if (canUseDense) { if (index >= (uint) _dense.Length) { EnsureCapacity((uint) newSize); } _dense[index] = desc; } else { if (_dense != null) { ConvertToSparse(); } _sparse[index] = desc; } } private void ConvertToSparse() { _sparse = new Dictionary<uint, PropertyDescriptor>(_dense.Length <= 1024 ? _dense.Length : 0); // need to move data for (uint i = 0; i < (uint) _dense.Length; ++i) { if (_dense[i] != null) { _sparse[i] = _dense[i]; } } _dense = null; } internal void EnsureCapacity(uint capacity) { if (capacity > MaxDenseArrayLength || _dense is null || capacity <= (uint) _dense.Length) { return; } // need to grow var newArray = new PropertyDescriptor[capacity]; System.Array.Copy(_dense, newArray, _dense.Length); _dense = newArray; } public IEnumerator<JsValue> GetEnumerator() { var length = GetLength(); for (uint i = 0; i < length; i++) { if (TryGetValue(i, out JsValue outValue)) { yield return outValue; } }; } internal uint Push(JsValue[] arguments) { var initialLength = GetLength(); var newLength = initialLength + arguments.Length; // if we see that we are bringing more than normal growth algorithm handles, ensure capacity eagerly if (_dense != null && initialLength != 0 && arguments.Length > initialLength * 2 && newLength <= MaxDenseArrayLength) { EnsureCapacity((uint) newLength); } var canUseDirectIndexSet = _dense != null && newLength <= _dense.Length; double n = initialLength; foreach (var argument in arguments) { var desc = new PropertyDescriptor(argument, PropertyFlag.ConfigurableEnumerableWritable); if (canUseDirectIndexSet) { _dense[(uint) n] = desc; } else { WriteValueSlow(n, desc); } n++; } // check if we can set length fast without breaking ECMA specification if (n < uint.MaxValue && CanSetLength()) { _length.Value = (uint) n; } else { if (!Set(CommonProperties.Length, newLength, this)) { ExceptionHelper.ThrowTypeError(_engine); } } return (uint) n; } private bool CanSetLength() { if (!_length.IsAccessorDescriptor()) { return _length.Writable; } var set = _length.Set; return !(set is null) && !set.IsUndefined(); } [MethodImpl(MethodImplOptions.NoInlining)] private void WriteValueSlow(double n, PropertyDescriptor desc) { if (n < uint.MaxValue) { WriteArrayValue((uint) n, desc); } else { DefinePropertyOrThrow((uint) n, desc); } } internal ArrayInstance Map(JsValue[] arguments) { var callbackfn = arguments.At(0); var thisArg = arguments.At(1); var len = GetLength(); var callable = GetCallable(callbackfn); var a = Engine.Array.ConstructFast(len); var args = _engine._jsValueArrayPool.RentArray(3); args[2] = this; for (uint k = 0; k < len; k++) { if (TryGetValue(k, out var kvalue)) { args[0] = kvalue; args[1] = k; var mappedValue = callable.Call(thisArg, args); var desc = new PropertyDescriptor(mappedValue, PropertyFlag.ConfigurableEnumerableWritable); if (a._dense != null && k < (uint) a._dense.Length) { a._dense[k] = desc; } else { a.WriteArrayValue(k, desc); } } } _engine._jsValueArrayPool.ReturnArray(args); return a; } /// <inheritdoc /> internal override bool FindWithCallback( JsValue[] arguments, out uint index, out JsValue value, bool visitUnassigned) { var thisArg = arguments.At(1); var callbackfn = arguments.At(0); var callable = GetCallable(callbackfn); var len = GetLength(); if (len == 0) { index = 0; value = Undefined; return false; } var args = _engine._jsValueArrayPool.RentArray(3); args[2] = this; for (uint k = 0; k < len; k++) { if (TryGetValue(k, out var kvalue) || visitUnassigned) { args[0] = kvalue; args[1] = k; var testResult = callable.Call(thisArg, args); if (TypeConverter.ToBoolean(testResult)) { index = k; value = kvalue; return true; } } } _engine._jsValueArrayPool.ReturnArray(args); index = 0; value = Undefined; return false; } public override uint Length => GetLength(); internal override bool IsIntegerIndexedArray => true; public JsValue this[uint index] { get { TryGetValue(index, out var kValue); return kValue; } } internal ArrayInstance ToArray(Engine engine) { var length = GetLength(); var array = _engine.Array.ConstructFast(length); for (uint i = 0; i < length; i++) { if (TryGetValue(i, out var kValue)) { array.SetIndexValue(i, kValue, updateLength: false); } } return array; } /// <summary> /// Fast path for concatenating sane-sized arrays, we assume size has been calculated. /// </summary> internal void CopyValues(ArrayInstance source, uint sourceStartIndex, uint targetStartIndex, uint length) { if (length == 0) { return; } var dense = _dense; var sourceDense = source._dense; if (dense != null && sourceDense != null && (uint) dense.Length >= targetStartIndex + length && dense[targetStartIndex] is null) { uint j = 0; for (uint i = sourceStartIndex; i < sourceStartIndex + length; ++i, j++) { var sourcePropertyDescriptor = i < (uint) sourceDense.Length && sourceDense[i] != null ? sourceDense[i] : source.GetProperty(i); dense[targetStartIndex + j] = sourcePropertyDescriptor?._value is not null ? new PropertyDescriptor(sourcePropertyDescriptor._value, PropertyFlag.ConfigurableEnumerableWritable) : null; } } else { // slower version for (uint k = sourceStartIndex; k < length; k++) { if (source.TryGetValue(k, out var subElement)) { SetIndexValue(targetStartIndex, subElement, updateLength: false); } } } } public override string ToString() { // debugger can make things hard when evaluates computed values return "(" + (_length?._value.AsNumber() ?? 0) + ")[]"; } } }
31.718062
131
0.444965
[ "BSD-2-Clause" ]
KurtGokhan/jint
Jint/Native/Array/ArrayInstance.cs
28,802
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HackerNewsDownloader { public static class JsonNetUtils { public static void SerializeSequenceToJson<T>(this IEnumerable<T> sequence, string fileName) { using (var fileStream = File.CreateText(fileName)) SerializeSequenceToJson(sequence, fileStream); } public static IEnumerable<T> DeserializeSequenceFromJson<T>(string fileName) { using (var fileStream = File.OpenText(fileName)) foreach (var responseJson in DeserializeSequenceFromJson<T>(fileStream)) yield return responseJson; } public static void SerializeSequenceToJson<T>(this IEnumerable<T> sequence, TextWriter writeStream, Action<T, long> progress = null) { using (var writer = new JsonTextWriter(writeStream)) { var serializer = new JsonSerializer(); writer.WriteStartArray(); long index = 0; foreach (var item in sequence) { if (progress != null) progress(item, index++); serializer.Serialize(writer, item); } writer.WriteEnd(); } } public static IEnumerable<T> DeserializeSequenceFromJson<T>(TextReader readerStream) { using (var reader = new JsonTextReader(readerStream)) { var serializer = new JsonSerializer(); if (!reader.Read() || reader.TokenType != JsonToken.StartArray) throw new Exception("Expected start of array in the deserialized json string"); while (reader.Read()) { if (reader.TokenType == JsonToken.EndArray) break; var item = serializer.Deserialize<T>(reader); yield return item; } } } } }
36.55
141
0.548564
[ "MIT" ]
chinna1986/HackerNewsDownloader
JsonNetUtils.cs
2,195
C#
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET. // Licensed under the Apache License, Version 2.0. using System; using System.Collections.Generic; using System.Globalization; namespace ImageMagick.Defines { /// <summary> /// Base class that can create defines. /// </summary> public abstract class DefinesCreator : IDefines { /// <summary> /// Initializes a new instance of the <see cref="DefinesCreator"/> class. /// </summary> /// <param name="format">The format where the defines are for.</param> protected DefinesCreator(MagickFormat format) => Format = format; /// <summary> /// Gets the defines that should be set as a define on an image. /// </summary> public abstract IEnumerable<IDefine> Defines { get; } /// <summary> /// Gets the format where the defines are for. /// </summary> protected MagickFormat Format { get; } /// <summary> /// Create a define with the specified name and value. /// </summary> /// <param name="name">The name of the define.</param> /// <param name="value">The value of the define.</param> /// <returns>A <see cref="MagickDefine"/> instance.</returns> protected MagickDefine CreateDefine(string name, bool value) => new MagickDefine(Format, name, value ? "true" : "false"); /// <summary> /// Create a define with the specified name and value. /// </summary> /// <param name="name">The name of the define.</param> /// <param name="value">The value of the define.</param> /// <returns>A <see cref="MagickDefine"/> instance.</returns> protected MagickDefine CreateDefine(string name, double value) => new MagickDefine(Format, name, value.ToString(CultureInfo.InvariantCulture)); /// <summary> /// Create a define with the specified name and value. /// </summary> /// <param name="name">The name of the define.</param> /// <param name="value">The value of the define.</param> /// <returns>A <see cref="MagickDefine"/> instance.</returns> protected MagickDefine CreateDefine(string name, int value) => new MagickDefine(Format, name, value.ToString(CultureInfo.InvariantCulture)); /// <summary> /// Create a define with the specified name and value. /// </summary> /// <param name="name">The name of the define.</param> /// <param name="value">The value of the define.</param> /// <returns>A <see cref="MagickDefine"/> instance.</returns> protected MagickDefine CreateDefine(string name, long value) => new MagickDefine(Format, name, value.ToString(CultureInfo.InvariantCulture)); /// <summary> /// Create a define with the specified name and value. /// </summary> /// <param name="name">The name of the define.</param> /// <param name="value">The value of the define.</param> /// <returns>A <see cref="MagickDefine"/> instance.</returns> protected MagickDefine CreateDefine(string name, IMagickGeometry value) { Throw.IfNull(nameof(value), value); return new MagickDefine(Format, name, value.ToString()); } /// <summary> /// Create a define with the specified name and value. /// </summary> /// <param name="name">The name of the define.</param> /// <param name="value">The value of the define.</param> /// <returns>A <see cref="MagickDefine"/> instance.</returns> protected MagickDefine CreateDefine(string name, string value) => new MagickDefine(Format, name, value); /// <summary> /// Create a define with the specified name and value. /// </summary> /// <param name="name">The name of the define.</param> /// <param name="value">The value of the define.</param> /// <typeparam name="TEnum">The type of the enumeration.</typeparam> /// <returns>A <see cref="MagickDefine"/> instance.</returns> protected MagickDefine CreateDefine<TEnum>(string name, TEnum value) where TEnum : Enum => new MagickDefine(Format, name, Enum.GetName(typeof(TEnum), value)); /// <summary> /// Create a define with the specified name and value. /// </summary> /// <param name="name">The name of the define.</param> /// <param name="value">The value of the define.</param> /// <typeparam name="T">The type of the enumerable.</typeparam> /// <returns>A <see cref="MagickDefine"/> instance.</returns> protected MagickDefine? CreateDefine<T>(string name, IEnumerable<T>? value) { if (value == null) return null; var values = new List<string>(); foreach (var val in value) { if (val != null) values.Add(val.ToString()); } if (values.Count == 0) return null; return new MagickDefine(Format, name, string.Join(",", values.ToArray())); } } }
41.519685
92
0.586952
[ "Apache-2.0" ]
ScriptBox99/Magick.NET
src/Magick.NET/Defines/DefinesCreator.cs
5,275
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using GoPay.Common; using GoPay.Model.Payments; using GoPay.Model.Payment; using GoPay.EETProp; using System.Collections.Generic; namespace GoPay.Tests { [TestClass()] public class EetTests { private BasePayment createEETBasePayment() { List<AdditionalParam> addParams = new List<AdditionalParam>(); addParams.Add(new AdditionalParam() { Name = "AdditionalKey", Value = "AdditionalValue" }); List<OrderItem> addItems = new List<OrderItem>(); addItems.Add(new OrderItem() { Name = "Pocitac Item1", Amount = 119990, Count = 1, VatRate = VatRate.RATE_4, ItemType = ItemType.ITEM, Ean = "1234567890123", ProductURL = @"https://www.eshop123.cz/pocitac" }); addItems.Add(new OrderItem() { Name = "Oprava Item2", Amount = 19960, Count = 1, VatRate = VatRate.RATE_3, ItemType = ItemType.ITEM, Ean = "1234567890189", ProductURL = @"https://www.eshop123.cz/pocitac/oprava" }); List<PaymentInstrument> allowedInstruments = new List<PaymentInstrument>(); allowedInstruments.Add(PaymentInstrument.BANK_ACCOUNT); allowedInstruments.Add(PaymentInstrument.PAYMENT_CARD); List<string> swifts = new List<string>(); swifts.Add("GIBACZPX"); swifts.Add("RZBCCZPP"); BasePayment baseEETPayment = new BasePayment() { Callback = new Callback() { ReturnUrl = @"https://eshop123.cz/return", NotificationUrl = @"https://eshop123.cz/notify" }, OrderNumber = "EET4321", Amount = 139950, Currency = Currency.CZK, OrderDescription = "EET4321Description", Lang = "CS", AdditionalParams = addParams, Items = addItems, Target = new Target() { GoId = TestUtils.GOID_EET, Type = Target.TargetType.ACCOUNT }, Payer = new Payer() { AllowedPaymentInstruments = allowedInstruments, AllowedSwifts = swifts, //DefaultPaymentInstrument = PaymentInstrument.BANK_ACCOUNT, //PaymentInstrument = PaymentInstrument.BANK_ACCOUNT, Contact = new PayerContact() { Email = "test@test.gopay.cz" } } }; return baseEETPayment; } private Payment createEETPaymentObject(GPConnector connector, BasePayment baseEETPayment) { Payment result = null; try { result = connector.GetAppToken().CreatePayment(baseEETPayment); Assert.IsNotNull(result); Assert.IsNotNull(result.Id); Console.WriteLine("EET Payment id: {0}", result.Id); Console.WriteLine("EET Payment gw_url: {0}", result.GwUrl); Console.WriteLine("EET Payment instrument: {0}", result.PaymentInstrument); Console.WriteLine(baseEETPayment.Eet); } catch (GPClientException exception) { Console.WriteLine("Create EET payment ERROR"); var err = exception.Error; DateTime date = err.DateIssued; foreach (var element in err.ErrorMessages) { // } } return result; } //[TestMethod()] public void GPConnectorTestCreateEETPayment() { var connector = new GPConnector(TestUtils.API_URL, TestUtils.CLIENT_ID_EET, TestUtils.CLIENT_SECRET_EET); BasePayment baseEETPayment = createEETBasePayment(); EET eet = new EET() { CelkTrzba = 139950, ZaklDan1 = 99165, Dan1 = 20825, ZaklDan2 = 17357, Dan2 = 2603, Mena = Currency.CZK }; baseEETPayment.Eet = eet; Payment result = createEETPaymentObject(connector, baseEETPayment); } //[TestMethod()] public void GPConnectorTestCreateRecurrentEETPayment() { var connector = new GPConnector(TestUtils.API_URL, TestUtils.CLIENT_ID_EET, TestUtils.CLIENT_SECRET_EET); BasePayment baseEETPayment = createEETBasePayment(); /* Recurrence recurrence = new Recurrence() { Cycle = RecurrenceCycle.WEEK, Period = 1, DateTo = new DateTime(2018, 4, 1) }; baseEETPayment.Recurrence = recurrence; */ Recurrence onDemandRecurrence = new Recurrence() { Cycle = RecurrenceCycle.ON_DEMAND, DateTo = new DateTime(2018, 4, 1) }; baseEETPayment.Recurrence = onDemandRecurrence; EET eet = new EET() { CelkTrzba = 139950, ZaklDan1 = 99165, Dan1 = 20825, ZaklDan2 = 17357, Dan2 = 2603, Mena = Currency.CZK }; baseEETPayment.Eet = eet; Payment result = createEETPaymentObject(connector, baseEETPayment); Console.WriteLine(result.Recurrence); } //[TestMethod()] public void GPConnectorTestNextOnDemandEET() { var connector = new GPConnector(TestUtils.API_URL, TestUtils.CLIENT_ID_EET, TestUtils.CLIENT_SECRET_EET); try { NextPayment nextPayment = new NextPayment() { OrderNumber = "EETOnDemand4321", Amount = 2000, Currency = Currency.CZK, OrderDescription = "EETOnDemand4321Description", }; nextPayment.Items.Add(new OrderItem() { Name = "OnDemand Prodlouzena zaruka", Amount = 2000, Count = 1, VatRate = VatRate.RATE_4, ItemType = ItemType.ITEM, Ean = "12345678901234", ProductURL = @"https://www.eshop123.cz/pocitac/prodlouzena_zaruka" }); EET eet = new EET() { CelkTrzba = 2000, ZaklDan1 = 1580, Dan1 = 420, Mena = Currency.CZK }; nextPayment.Eet = eet; Payment onDemandEETPayment = connector.GetAppToken().CreateRecurrentPayment(3049250282, nextPayment); Console.WriteLine("OnDemand payment id: {0}", onDemandEETPayment.Id); Console.WriteLine("OnDemand payment gw_url: {0}", onDemandEETPayment.GwUrl); Console.WriteLine("OnDemand EET Payment instrument: {0}", onDemandEETPayment.PaymentInstrument); Console.WriteLine("OnDemand recurrence: {0}", onDemandEETPayment.Recurrence); Console.WriteLine("OnDemand amount: {0}", onDemandEETPayment.Amount); Console.Write(onDemandEETPayment.EetCode); Console.WriteLine(nextPayment.Eet); } catch (GPClientException exception) { Console.WriteLine("Creating next on demand EET payment ERROR"); var err = exception.Error; DateTime date = err.DateIssued; foreach (var element in err.ErrorMessages) { // } } } [TestMethod()] public void GPConnectorTestEETStatus() { long id = 3049250282; var connector = new GPConnector(TestUtils.API_URL, TestUtils.CLIENT_ID_EET, TestUtils.CLIENT_SECRET_EET); try { var payment = connector.GetAppToken().PaymentStatus(id); Assert.IsNotNull(payment.Id); Console.WriteLine("EET Payment id: {0}", payment.Id); Console.WriteLine("EET Payment gw_url: {0}", payment.GwUrl); Console.WriteLine("EET Payment state: {0}", payment.State); Console.WriteLine("EET Payment instrument: {0}", payment.PaymentInstrument); Console.WriteLine("EET PreAuthorization: {0}", payment.PreAuthorization); Console.WriteLine("EET Recurrence: {0}", payment.Recurrence); Console.WriteLine(payment.EetCode); } catch (GPClientException ex) { Console.WriteLine("EET Payment status ERROR"); var err = ex.Error; DateTime date = err.DateIssued; foreach (var element in err.ErrorMessages) { // } } } //[TestMethod()] public void GPConnectorTestEETPaymentRefund() { var connector = new GPConnector(TestUtils.API_URL, TestUtils.CLIENT_ID_EET, TestUtils.CLIENT_SECRET_EET); List<OrderItem> refundedItems = new List<OrderItem>(); refundedItems.Add(new OrderItem() { Name = "Pocitac Item1", Amount = 119990, Count = 1, VatRate = VatRate.RATE_4, ItemType = ItemType.ITEM, Ean = "1234567890123", ProductURL = @"https://www.eshop123.cz/pocitac" }); refundedItems.Add(new OrderItem() { Name = "Oprava Item2", Amount = 19960, Count = 1, VatRate = VatRate.RATE_3, ItemType = ItemType.ITEM, Ean = "1234567890189", ProductURL = @"https://www.eshop123.cz/pocitac/oprava" }); EET eet = new EET() { CelkTrzba = 139950, ZaklDan1 = 99165, Dan1 = 20825, ZaklDan2 = 17357, Dan2 = 2603, Mena = Currency.CZK }; RefundPayment refundObject = new RefundPayment() { Amount = 139950, Items = refundedItems, Eet = eet }; try { var refundEETPayment = connector.GetAppToken().RefundPayment(3049250113, refundObject); Console.WriteLine("EET refund result: {0}", refundEETPayment); } catch (GPClientException ex) { Console.WriteLine("EET Payment refund ERROR"); var err = ex.Error; DateTime date = err.DateIssued; foreach (var element in err.ErrorMessages) { // } } } //[TestMethod()] public void GPConnectorTestEETPReceiptFindByFilter() { var connector = new GPConnector(TestUtils.API_URL, TestUtils.CLIENT_ID_EET, TestUtils.CLIENT_SECRET_EET); EETReceiptFilter filter = new EETReceiptFilter() { DateFrom = new DateTime(2017, 3, 2), DateTo = new DateTime(2017, 4, 2), IdProvoz = 11 }; try { List<EETReceipt> receipts = connector.GetAppToken().FindEETReceiptsByFilter(filter); foreach(EETReceipt currReceipt in receipts) { Console.WriteLine(currReceipt); } Console.WriteLine(receipts.Count); } catch (GPClientException ex) { Console.WriteLine("EET Receipt by filter ERROR"); var err = ex.Error; DateTime date = err.DateIssued; foreach (var element in err.ErrorMessages) { // } } } //[TestMethod()] public void GPConnectorTestEETPReceiptFindByPaymentId() { var connector = new GPConnector(TestUtils.API_URL, TestUtils.CLIENT_ID_EET, TestUtils.CLIENT_SECRET_EET); try { List<EETReceipt> receipts = connector.GetAppToken().GetEETReceiptByPaymentId(3049205133); foreach (EETReceipt currReceipt in receipts) { Console.WriteLine(currReceipt); } Console.WriteLine(receipts.Count); } catch (GPClientException ex) { Console.WriteLine("EET Receipt by payment ID ERROR"); var err = ex.Error; DateTime date = err.DateIssued; foreach (var element in err.ErrorMessages) { // } } } } }
35.259947
119
0.510193
[ "MIT" ]
gopaycommunity/gopay-dotnet-api
GoPay.net-sdkTests/src/Tests/EetTests.cs
13,295
C#
// <copyright file="OpenGLContextObservable.cs" company="KinsonDigital"> // Copyright (c) KinsonDigital. All rights reserved. // </copyright> namespace Velaptor.Observables { using Velaptor.Observables.Core; /// <summary> /// Creates an observable to send push notifications of OpenGL events. /// </summary> internal class OpenGLContextObservable : Observable<object> { /// <summary> /// Sends a push notification that the OpenGL context has been created. /// </summary> /// <param name="data">The data to send with the notification.</param> public virtual void OnGLContextCreated(object data) { foreach (var observer in Observers) { observer.OnNext(data); } } } }
29.777778
79
0.618159
[ "MIT" ]
teezzan/Velaptor
Velaptor/Observables/OpenGLContextObservable.cs
806
C#
using NUnit.Framework; namespace ConfigInjector.UnitTests { public abstract class TestFor<T> { protected abstract T Given(); protected abstract void When(); protected T Subject { get; private set; } [SetUp] public void SetUp() { Subject = Given(); When(); } } }
18.789474
49
0.537815
[ "MIT" ]
ConfigInjector/ConfigInjector
src/ConfigInjector.UnitTests/TestFor.cs
359
C#
using Serilog; using Serilog.Events; namespace FilterLists.SharedKernel.Logging; internal static class ConfigurationBuilder { public static readonly LoggerConfiguration BaseLoggerConfiguration = new LoggerConfiguration() .MinimumLevel.Information() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Console(); }
31.875
91
0.717647
[ "MIT" ]
collinbarrett/filterlists
services/SharedKernel/FilterLists.SharedKernel.Logging/ConfigurationBuilder.cs
512
C#
using LinCms.Common; using System.ComponentModel.DataAnnotations; namespace LinCms.Cms.Account { public class LoginInputDto { /// <summary> /// 登录名:admin /// </summary> [Required(ErrorMessage = "登录名为必填项")] public string Username { get; set; } /// <summary> /// 密码:123qwe /// </summary> [Required(ErrorMessage = "密码为必填项")] public string Password { get; set; } } }
22.85
44
0.557987
[ "MIT" ]
KribKing/lin-cms-dotnetcore
src/LinCms.Application.Contracts/Cms/Account/LoginInputDto.cs
497
C#
namespace UI { partial class NonProfitOrganizationForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NonProfitOrganizationForm)); this.label1 = new System.Windows.Forms.Label(); this.button_CreateCampaign = new System.Windows.Forms.Button(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.richTextBox_CampaignName = new System.Windows.Forms.RichTextBox(); this.richTextBox_CampaignURL = new System.Windows.Forms.RichTextBox(); this.richTextBox_CampaignHashtag = new System.Windows.Forms.RichTextBox(); this.label5 = new System.Windows.Forms.Label(); this.dataGridView_MyCampaigns = new System.Windows.Forms.DataGridView(); this.UserName = new System.Windows.Forms.Label(); this.label_ID = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView_MyCampaigns)).BeginInit(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.Font = new System.Drawing.Font("Impact", 36F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); this.label1.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label1.Location = new System.Drawing.Point(0, 9); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(702, 75); this.label1.TabIndex = 3; this.label1.Text = "NonProfit Organization Aera"; // // button_CreateCampaign // this.button_CreateCampaign.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(44)))), ((int)(((byte)(44)))), ((int)(((byte)(44))))); this.button_CreateCampaign.Cursor = System.Windows.Forms.Cursors.Hand; this.button_CreateCampaign.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(49)))), ((int)(((byte)(46)))), ((int)(((byte)(46))))); this.button_CreateCampaign.FlatAppearance.BorderSize = 0; this.button_CreateCampaign.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_CreateCampaign.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); this.button_CreateCampaign.ForeColor = System.Drawing.Color.White; this.button_CreateCampaign.Location = new System.Drawing.Point(29, 359); this.button_CreateCampaign.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.button_CreateCampaign.Name = "button_CreateCampaign"; this.button_CreateCampaign.Size = new System.Drawing.Size(649, 66); this.button_CreateCampaign.TabIndex = 13; this.button_CreateCampaign.Text = "Create Campaign"; this.button_CreateCampaign.UseVisualStyleBackColor = false; this.button_CreateCampaign.Click += new System.EventHandler(this.button_CreateCampaign_Click); // // label4 // this.label4.AutoSize = true; this.label4.BackColor = System.Drawing.Color.Transparent; this.label4.Font = new System.Drawing.Font("Cambria", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); this.label4.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label4.Location = new System.Drawing.Point(28, 121); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(236, 36); this.label4.TabIndex = 12; this.label4.Text = "Campaign name"; // // label3 // this.label3.AutoSize = true; this.label3.BackColor = System.Drawing.Color.Transparent; this.label3.Font = new System.Drawing.Font("Cambria", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); this.label3.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label3.Location = new System.Drawing.Point(28, 241); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(268, 36); this.label3.TabIndex = 11; this.label3.Text = "Campaign hashtag"; // // label2 // this.label2.AutoSize = true; this.label2.BackColor = System.Drawing.Color.Transparent; this.label2.Font = new System.Drawing.Font("Cambria", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); this.label2.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label2.Location = new System.Drawing.Point(28, 185); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(216, 36); this.label2.TabIndex = 10; this.label2.Text = "Campaign URL"; // // richTextBox_CampaignName // this.richTextBox_CampaignName.Location = new System.Drawing.Point(301, 132); this.richTextBox_CampaignName.Name = "richTextBox_CampaignName"; this.richTextBox_CampaignName.Size = new System.Drawing.Size(376, 30); this.richTextBox_CampaignName.TabIndex = 14; this.richTextBox_CampaignName.Text = ""; // // richTextBox_CampaignURL // this.richTextBox_CampaignURL.Location = new System.Drawing.Point(301, 192); this.richTextBox_CampaignURL.Name = "richTextBox_CampaignURL"; this.richTextBox_CampaignURL.Size = new System.Drawing.Size(376, 30); this.richTextBox_CampaignURL.TabIndex = 15; this.richTextBox_CampaignURL.Text = ""; // // richTextBox_CampaignHashtag // this.richTextBox_CampaignHashtag.Location = new System.Drawing.Point(301, 247); this.richTextBox_CampaignHashtag.Name = "richTextBox_CampaignHashtag"; this.richTextBox_CampaignHashtag.Size = new System.Drawing.Size(376, 30); this.richTextBox_CampaignHashtag.TabIndex = 16; this.richTextBox_CampaignHashtag.Text = ""; // // label5 // this.label5.AutoSize = true; this.label5.BackColor = System.Drawing.Color.Transparent; this.label5.Font = new System.Drawing.Font("Cambria", 25.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); this.label5.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label5.Location = new System.Drawing.Point(880, 45); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(289, 51); this.label5.TabIndex = 17; this.label5.Text = "My Campaigns"; // // dataGridView_MyCampaigns // this.dataGridView_MyCampaigns.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; this.dataGridView_MyCampaigns.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView_MyCampaigns.Location = new System.Drawing.Point(770, 118); this.dataGridView_MyCampaigns.Name = "dataGridView_MyCampaigns"; this.dataGridView_MyCampaigns.RowHeadersWidth = 51; this.dataGridView_MyCampaigns.RowTemplate.Height = 29; this.dataGridView_MyCampaigns.Size = new System.Drawing.Size(541, 395); this.dataGridView_MyCampaigns.TabIndex = 18; // // UserName // this.UserName.AutoSize = true; this.UserName.BackColor = System.Drawing.Color.Transparent; this.UserName.Font = new System.Drawing.Font("Impact", 19.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); this.UserName.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.UserName.Location = new System.Drawing.Point(12, 502); this.UserName.Name = "UserName"; this.UserName.Size = new System.Drawing.Size(158, 41); this.UserName.TabIndex = 31; this.UserName.Text = "UserName"; // // label_ID // this.label_ID.AutoSize = true; this.label_ID.BackColor = System.Drawing.Color.Transparent; this.label_ID.Font = new System.Drawing.Font("Impact", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); this.label_ID.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label_ID.Location = new System.Drawing.Point(1284, 519); this.label_ID.Name = "label_ID"; this.label_ID.Size = new System.Drawing.Size(27, 25); this.label_ID.TabIndex = 32; this.label_ID.Text = "id"; // // NonProfitOrganizationForm // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = global::UI.Properties.Resources.twbackgound; this.ClientSize = new System.Drawing.Size(1332, 553); this.Controls.Add(this.label_ID); this.Controls.Add(this.UserName); this.Controls.Add(this.dataGridView_MyCampaigns); this.Controls.Add(this.label5); this.Controls.Add(this.richTextBox_CampaignHashtag); this.Controls.Add(this.richTextBox_CampaignURL); this.Controls.Add(this.richTextBox_CampaignName); this.Controls.Add(this.button_CreateCampaign); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "NonProfitOrganizationForm"; this.Text = "NonProfitOrganizationForm"; ((System.ComponentModel.ISupportInitialize)(this.dataGridView_MyCampaigns)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private Label label1; private Button button_CreateCampaign; private Label label4; private Label label3; private Label label2; private RichTextBox richTextBox_CampaignName; private RichTextBox richTextBox_CampaignURL; private RichTextBox richTextBox_CampaignHashtag; private Label label5; private DataGridView dataGridView_MyCampaigns; private Label UserName; private Label label_ID; } }
53.610619
171
0.629498
[ "MIT" ]
Yanivv77/PromoIt
Client/UI/NonProfitOrganizationForm.Designer.cs
12,118
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("10. Sum of Chars")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("10. Sum of Chars")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3c7027c2-f838-478d-92f9-4a2574750968")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.837838
84
0.743571
[ "MIT" ]
jstavrev/SoftwareUniversity
2. Tech Module/1. Programming Fundamentals/05. Types n Variables - More Exrc/10. Sum of Chars/Properties/AssemblyInfo.cs
1,403
C#
// This file has been generated using the Simplic.Flow.NodeGenerator using System; using Simplic.Flow; namespace Simplic.Flow.Node { [ActionNodeDefinition(Name = nameof(SystemConvertToString_Boolean_IFormatProvider), DisplayName = "ToString(Boolean,IFormatProvider)", Category = "System/Convert")] public class SystemConvertToString_Boolean_IFormatProvider : ActionNode { public override bool Execute(IFlowRuntimeService runtime, DataPinScope scope) { try { var returnValue = System.Convert.ToString( scope.GetValue<System.Boolean>(InPinValue), scope.GetValue<System.IFormatProvider>(InPinProvider)); scope.SetValue(OutPinReturn, returnValue); if (OutNodeSuccess != null) { runtime.EnqueueNode(OutNodeSuccess, scope); } } catch (Exception ex) { Simplic.Log.LogManagerInstance.Instance.Error("Error in SystemConvertToString_Boolean_IFormatProvider: ", ex); if (OutNodeFailed != null) runtime.EnqueueNode(OutNodeFailed, scope); } return true; } public override string Name => nameof(SystemConvertToString_Boolean_IFormatProvider); public override string FriendlyName => nameof(SystemConvertToString_Boolean_IFormatProvider); [FlowPinDefinition( PinDirection = PinDirection.Out, DisplayName = "Success", Name = nameof(OutNodeSuccess), AllowMultiple = false)] public ActionNode OutNodeSuccess { get; set; } [FlowPinDefinition( PinDirection = PinDirection.Out, DisplayName = "Failed", Name = nameof(OutNodeFailed), AllowMultiple = false)] public ActionNode OutNodeFailed { get; set; } [DataPinDefinition( Id = "ad7b3560-3337-4602-a590-d5dfc24645a3", ContainerType = DataPinContainerType.Single, DataType = typeof(System.Boolean), Direction = PinDirection.In, Name = nameof(InPinValue), DisplayName = "Value", IsGeneric = false, AllowedTypes = null)] public DataPin InPinValue { get; set; } [DataPinDefinition( Id = "e0e0a976-8149-4a49-ab0b-33d1f1ad0989", ContainerType = DataPinContainerType.Single, DataType = typeof(System.IFormatProvider), Direction = PinDirection.In, Name = nameof(InPinProvider), DisplayName = "Provider", IsGeneric = false, AllowedTypes = null)] public DataPin InPinProvider { get; set; } [DataPinDefinition( Id = "ff61084a-ae5e-4a51-b400-99c30ba36b86", ContainerType = DataPinContainerType.Single, DataType = typeof(System.String), Direction = PinDirection.Out, Name = nameof(OutPinReturn), DisplayName = "Return", IsGeneric = false, AllowedTypes = null)] public DataPin OutPinReturn { get; set; } } }
37.107143
168
0.619185
[ "MIT" ]
simplic/flow
src/Simplic.Flow.Node/ActionNode/Generic/System.Convert/SystemConvertToString_Boolean_IFormatProviderNode.cs
3,117
C#
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("NServiceBus.Transport.Kafka.Tests")]
36
67
0.833333
[ "Apache-2.0" ]
pablocastilla/NServiceBus.Kafka
src/NServiceBus.Kafka/InternalsVisibleTo.cs
110
C#
// Copyright (c) .NET Foundation 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.Text; using Microsoft.NET.TestFramework; using Microsoft.NET.TestFramework.Assertions; using Microsoft.NET.TestFramework.Commands; using Xunit; using Xunit.Abstractions; namespace Microsoft.NET.Publish.Tests { public class GivenThatWeWantToPublishAComServerLibrary : SdkTest { public GivenThatWeWantToPublishAComServerLibrary(ITestOutputHelper log) : base(log) { } [WindowsOnlyFact] public void It_publishes_comhost_to_the_publish_folder() { var testAsset = _testAssetsManager .CopyTestAsset("ComServer") .WithSource(); var publishCommand = new PublishCommand(Log, testAsset.TestRoot); publishCommand.Execute() .Should() .Pass(); var publishDirectory = publishCommand.GetOutputDirectory("netcoreapp3.0"); var outputDirectory = publishDirectory.Parent; var filesPublished = new[] { "ComServer.dll", "ComServer.pdb", "ComServer.deps.json", "ComServer.comhost.dll" }; outputDirectory.Should().HaveFiles(filesPublished); publishDirectory.Should().HaveFiles(filesPublished); } } }
31.729167
101
0.645437
[ "MIT" ]
5l1v3r1/sdk-1
src/Tests/Microsoft.NET.Publish.Tests/GivenThatWeWantToPublishAComServerLibrary.cs
1,525
C#
namespace SpaceEngineers.Core.DataAccess.Orm.InMemoryDatabase.Model { using System; using System.Collections.Generic; using System.Linq; using Api.Model; using AutoRegistration.Api.Attributes; using AutoRegistration.Api.Enumerations; using Basics; using CompositionRoot.Api.Abstractions; [Component(EnLifestyle.Singleton)] internal class DatabaseTypeProvider : IDatabaseTypeProvider { private readonly ITypeProvider _typeProvider; private IReadOnlyCollection<Type>? _databaseEntities; public DatabaseTypeProvider(ITypeProvider typeProvider) { _typeProvider = typeProvider; } public IEnumerable<Type> DatabaseEntities() { _databaseEntities ??= InitDatabaseEntities(); return _databaseEntities; IReadOnlyCollection<Type> InitDatabaseEntities() { return _typeProvider .OurTypes .Where(type => type.IsSubclassOfOpenGeneric(typeof(IUniqueIdentified<>)) && IsNotAbstraction(type)) .ToList(); } static bool IsNotAbstraction(Type type) { return type != typeof(IUniqueIdentified<>) && type != typeof(IDatabaseEntity<>) && type != typeof(BaseDatabaseEntity<>); } } } }
31.673913
92
0.592999
[ "MIT" ]
warning-explosive/Core
Modules/DataAccess.Orm.InMemoryDatabase/Model/DatabaseTypeProvider.cs
1,457
C#
using System; namespace SetStartupProjects { /// <summary> /// What versions of Visual Studio to target for .suo creation. /// </summary> [Flags] public enum VisualStudioVersions { /// <summary> /// Target suo creation for Visual Studio 2012. /// </summary> Vs2012 = 1, /// <summary> /// Target suo creation for Visual Studio 2013. /// </summary> Vs2013 = 2, /// <summary> /// Target suo creation for Visual Studio 2015. /// </summary> Vs2015 = 4, /// <summary> /// Target suo creation for Visual Studio 2017. /// </summary> Vs2017 = 8, /// <summary> /// Target suo creation for Visual Studio versions 2012, 2013, 2015 and 2017. /// </summary> All = Vs2012 | Vs2013 | Vs2015 | Vs2017, } }
28.40625
86
0.509351
[ "MIT" ]
igorushi/SetStartupProjects
src/SetStartupProjects/VisualStudioVersions.cs
880
C#
/* * Hydrogen Integration API * * The Hydrogen Integration API * * OpenAPI spec version: 1.3.1 * Contact: info@hydrogenplatform.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using NUnit.Framework; using System; using System.Linq; using System.IO; using System.Collections.Generic; using Integration.Api; using Integration.ModelEntity; using Integration.Client; using System.Reflection; using Newtonsoft.Json; namespace Integration.Test { /// <summary> /// Class for testing SmtpResponseVO /// </summary> /// <remarks> /// This file is automatically generated by Swagger Codegen. /// Please update the test case below to test the model. /// </remarks> [TestFixture] public class SmtpResponseVOTests { // TODO uncomment below to declare an instance variable for SmtpResponseVO //private SmtpResponseVO instance; /// <summary> /// Setup before each test /// </summary> [SetUp] public void Init() { // TODO uncomment below to create an instance of SmtpResponseVO //instance = new SmtpResponseVO(); } /// <summary> /// Clean up after each test /// </summary> [TearDown] public void Cleanup() { } /// <summary> /// Test an instance of SmtpResponseVO /// </summary> [Test] public void SmtpResponseVOInstanceTest() { // TODO uncomment below to test "IsInstanceOfType" SmtpResponseVO //Assert.IsInstanceOfType<SmtpResponseVO> (instance, "variable 'instance' is a SmtpResponseVO"); } /// <summary> /// Test the property 'EmailId' /// </summary> [Test] public void EmailIdTest() { // TODO unit test for the property 'EmailId' } /// <summary> /// Test the property 'Message' /// </summary> [Test] public void MessageTest() { // TODO unit test for the property 'Message' } /// <summary> /// Test the property 'NucleusBusinessId' /// </summary> [Test] public void NucleusBusinessIdTest() { // TODO unit test for the property 'NucleusBusinessId' } /// <summary> /// Test the property 'NucleusClientId' /// </summary> [Test] public void NucleusClientIdTest() { // TODO unit test for the property 'NucleusClientId' } /// <summary> /// Test the property 'VendorName' /// </summary> [Test] public void VendorNameTest() { // TODO unit test for the property 'VendorName' } /// <summary> /// Test the property 'VendorResponse' /// </summary> [Test] public void VendorResponseTest() { // TODO unit test for the property 'VendorResponse' } } }
25.239669
108
0.55632
[ "Apache-2.0" ]
ShekharPaatni/SDK
integration/csharp/src/Integration.Test/Model/SmtpResponseVOTests.cs
3,054
C#
using System; using System.Collections.Generic; using System.Collections.Specialized; using SharpGen.Doc; namespace SharpGen.Platform.Documentation { /// <inheritdoc /> internal sealed class DocSubItem : IDocSubItem { private readonly ObservableSet<string> attributes = new(StringComparer.InvariantCultureIgnoreCase); private string description; private string term; public DocSubItem() { attributes.CollectionChanged += OnCollectionChanged; } public string Term { get => term; set { if (term == value) return; term = value; IsDirty = true; } } public string Description { get => description; set { if (description == value) return; description = value; IsDirty = true; } } public IList<string> Attributes => attributes; public bool IsDirty { get; set; } private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { IsDirty = true; } } }
22.763636
91
0.532748
[ "MIT" ]
JetBrains/SharpGenTools
SharpGen.Platform/Documentation/DocSubItem.cs
1,252
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DocumentFormat.OpenXml.Validation.Semantic { internal class AttributeCannotOmitConstraint : SemanticConstraint { private readonly byte _attribute; public AttributeCannotOmitConstraint(byte attribute) : base(SemanticValidationLevel.Element) { _attribute = attribute; } public override ValidationErrorInfo ValidateCore(ValidationContext context) { var element = context.Stack.Current.Element; if (element.ParsedState.Attributes[_attribute].HasValue) { return null; } return new ValidationErrorInfo() { Id = "Sem_MissRequiredAttribute", ErrorType = ValidationErrorType.Schema, Node = element, Description = SR.Format(ValidationResources.Sch_MissRequiredAttribute, GetAttributeQualifiedName(element, _attribute)), }; } } }
32.628571
135
0.6331
[ "MIT" ]
06needhamt/Open-XML-SDK
src/DocumentFormat.OpenXml/Validation/Semantic/AttributeCannotOmitConstraint.cs
1,144
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: IMethodRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The interface IWindowsQualityUpdateProfileAssignRequestBuilder. /// </summary> public partial interface IWindowsQualityUpdateProfileAssignRequestBuilder : IBaseRequestBuilder { /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> IWindowsQualityUpdateProfileAssignRequest Request(IEnumerable<Option> options = null); } }
38.344828
153
0.598022
[ "MIT" ]
ScriptBox99/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IWindowsQualityUpdateProfileAssignRequestBuilder.cs
1,112
C#
using OrmTest.Demo; using OrmTest.Models; using SqlSugar; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace OrmTest.Demo { /// <summary> /// Secure string operations /// </summary> public class JoinSql : DemoBase { public static void Init() { Where(); OrderBy(); SelectMerge(); ConditionalModel(); JoinExp(); Clone(); WhereClassTest(); } private static void Clone() { var db = GetInstance(); var qy = db.Queryable<Student>().Where(it => 1 == 1); var list1 = qy.Clone().Where(it => it.Id == 1).ToList(); var list2 = qy.Clone().Where(it => it.Id == 2).ToList(); var qy2 = db.Queryable<Student,School>((st,sc)=>new object[]{ JoinType.Left,st.SchoolId==sc.Id }).Where((st,sc)=>st.Id == 1); var join0 = qy2.Clone().Where((st, sc) => sc.Id == 222).Select(st=>st.Id).ToList(); var join1 = qy2.Clone().Where((st,sc) => st.Id== 1111).ToList(); var join2 = qy2.Clone().Where((st,sc)=>sc.Id==222).ToList(); } private static void JoinExp() { var db = GetInstance(); var exp= Expressionable.Create<Student>() .OrIF(1==1,it => it.Id == 11) .And(it=>it.Id==1) .AndIF(2==2,it => it.Id == 1) .Or(it =>it.Name == "a1").ToExpression(); var list=db.Queryable<Student>().Where(exp).ToList(); } private static void ConditionalModel() { var db = GetInstance(); List<IConditionalModel> conModels = new List<IConditionalModel>(); conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "1" });//id=1 conModels.Add(new ConditionalModel() { FieldName = "Student.id", ConditionalType = ConditionalType.Equal, FieldValue = "1" });//id=1 conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Like, FieldValue = "1" });// id like '%1%' conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.IsNullOrEmpty }); conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.In,FieldValue="1,2,3" }); conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.NotIn, FieldValue = "1,2,3" }); conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.NoEqual, FieldValue = "1,2,3" }); conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.IsNot,FieldValue=null});// id is not null conModels.Add(new ConditionalCollections() { ConditionalList=new List<KeyValuePair<WhereType, SqlSugar.ConditionalModel>>()// (id=1 or id=2 and id=1) { new KeyValuePair<WhereType, ConditionalModel>( WhereType.And ,new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "1" }), new KeyValuePair<WhereType, ConditionalModel> (WhereType.Or,new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "2" }), new KeyValuePair<WhereType, ConditionalModel> ( WhereType.And,new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "2" }) } }); var student = db.Queryable<Student>().Where(conModels).ToList(); } private static void SelectMerge() { var db = GetInstance(); //page join var pageJoin = db.Queryable<Student, School>((st, sc) => new object[] { JoinType.Left,st.SchoolId==sc.Id }) .Where(st => st.Id==1) .Where(st => st.Id==2) .Select((st, sc) => new { id = st.Id, name = sc.Name }) .MergeTable().Where(XXX => XXX.id == 1).OrderBy("name asc").ToList();// Prefix, is, not, necessary, and take the columns in select } private static void Where() { var db = GetInstance(); //Parameterized processing string value = "'jack';drop table Student"; var list = db.Queryable<Student>().Where("name=@name", new { name = value }).ToList(); //Nothing happened } private static void OrderBy() { var db = GetInstance(); //propertyName is valid string propertyName = "Id"; string dbColumnName = db.EntityMaintenance.GetDbColumnName<Student>(propertyName); var list = db.Queryable<Student>().OrderBy(dbColumnName).ToList(); //propertyName is invalid try { propertyName = "Id'"; dbColumnName = db.EntityMaintenance.GetDbColumnName<Student>(propertyName); var list2 = db.Queryable<Student>().OrderBy(dbColumnName).ToList(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } private static void WhereClassTest() { var db = GetInstance(); var list=db.Queryable<Student>().WhereClass(new WhereClass() { Id=1 }).ToList(); //where id=1 var list2 = db.Queryable<Student>().WhereClass(new WhereClass() { Name="a"},ignoreDefaultValue:true).ToList(); //where name="a" var list3 = db.Queryable<Student>().WhereClass(new WhereClass() { Name = "a" }).ToList(); //where id=0 and name="a" var list4 = db.Queryable<Student>().WhereClass(new WhereClass() { SchoolId="1", Name = "a" },ignoreDefaultValue:true).ToList(); //school=1,name=a var list5= db.Queryable<Student>().WhereClass(new WhereClass() { SchoolId = "1", Name = "a" }).ToList(); //school=1,name=a,id=0 var list6 = db.Queryable<Student>().WhereClass(new List<WhereClass>() { new WhereClass(){ Name="a",SchoolId="1" }, new WhereClass(){ Id=1 } },ignoreDefaultValue:true).ToList(); //(name=a and schoolid=1) or id=1 var list7 = db.Queryable<Student>().WhereClass(new List<WhereClass>() { new WhereClass(){ Name="a",SchoolId="1" }, new WhereClass(){ Id=1 } }).ToList(); //(name=a and schoolid=1 and id=0) or id=1 } public class WhereClass{ public string Name { get; set; } public int Id { get; set; } public string SchoolId { get; set; } } } }
43.776398
183
0.546254
[ "Apache-2.0" ]
690275538/SqlSugar
Src/Asp.NetCore2/SqlSeverTest/SqlSeverTest/Demos/8_JoinSql.cs
7,050
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Audiochan.API; using Audiochan.Core.Extensions; using Audiochan.Core.Persistence; using Audiochan.Core.Services; using Audiochan.Domain.Entities; using Audiochan.Domain.Enums; using Audiochan.Infrastructure.Persistence; using Audiochan.Tests.Common.Mocks; using MediatR; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Moq; using Npgsql; using NUnit.Framework; using Respawn; #pragma warning disable 8618 namespace Audiochan.Core.IntegrationTests { [SetUpFixture] public class TestFixture { private static IConfigurationRoot _configuration; private static IWebHostEnvironment _env; private static IServiceScopeFactory _scopeFactory; private static Checkpoint _checkpoint; private static ClaimsPrincipal? _user; [OneTimeSetUp] public async Task RunBeforeAnyTests() { // Create database container for integration tests var dockerSqlPort = await DockerDatabaseUtilities.EnsureDockerStartedAsync(); var dockerConnectionString = DockerDatabaseUtilities.GetSqlConnectionString(dockerSqlPort); // Build configuration, including the connection string from the database container var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", false, true) .AddInMemoryCollection(new Dictionary<string, string> { { "ConnectionStrings:Database", dockerConnectionString } }) .AddEnvironmentVariables(); _configuration = builder.Build(); _env = Mock.Of<IWebHostEnvironment>(); var startup = new Startup(_configuration, _env); var services = new ServiceCollection(); services.AddLogging(); startup.ConfigureServices(services); #region Register mocks var descriptorCurrentUserService = services.FirstOrDefault(d => d.ServiceType == typeof(ICurrentUserService)); services.Remove(descriptorCurrentUserService!); services.AddTransient(_ => CurrentUserServiceMock.Create(_user).Object); var descriptorDateTimeProvider = services.FirstOrDefault(d => d.ServiceType == typeof(IDateTimeProvider)); services.Remove(descriptorDateTimeProvider!); services.AddTransient(_ => DateTimeProviderMock.Create(DateTime.UtcNow).Object); var descriptorStorageService = services.FirstOrDefault(d => d.ServiceType == typeof(IStorageService)); services.Remove(descriptorStorageService!); services.AddTransient(_ => StorageServiceMock.Create().Object); #endregion _scopeFactory = services.BuildServiceProvider().GetService<IServiceScopeFactory>() ?? throw new InvalidOperationException(); _checkpoint = new Checkpoint { TablesToIgnore = new[] { "__EFMigrationsHistory" }, DbAdapter = DbAdapter.Postgres }; EnsureDatabase(); } public static void ExecuteDbContext(Action<ApplicationDbContext> action) { using var scope = _scopeFactory.CreateScope(); using var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); action(db); } public static T ExecuteDbContext<T>(Func<ApplicationDbContext, T> action) { using var scope = _scopeFactory.CreateScope(); using var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); return action(db); } public static async Task ExecuteDbContextAsync(Func<ApplicationDbContext, Task> action) { using var scope = _scopeFactory.CreateScope(); await using var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); await action(db); } public static async Task<T> ExecuteDbContextAsync<T>(Func<ApplicationDbContext, Task<T>> action) { using var scope = _scopeFactory.CreateScope(); await using var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); return await action(db); } public static async ValueTask ExecuteDbContextAsync(Func<ApplicationDbContext, ValueTask> action) { using var scope = _scopeFactory.CreateScope(); await using var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); await action(db); } public static async ValueTask<T> ExecuteDbContextAsync<T>(Func<ApplicationDbContext, ValueTask<T>> action) { using var scope = _scopeFactory.CreateScope(); await using var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); return await action(db); } public static void ExecuteScope(Action<IServiceProvider> action) { using var scope = _scopeFactory.CreateScope(); action(scope.ServiceProvider); } public static T ExecuteScope<T>(Func<IServiceProvider, T> action) { using var scope = _scopeFactory.CreateScope(); return action(scope.ServiceProvider); } public static async Task ExecuteScopeAsync(Func<IServiceProvider, Task> action) { using var scope = _scopeFactory.CreateScope(); await action(scope.ServiceProvider); } public static async Task<T> ExecuteScopeAsync<T>(Func<IServiceProvider, Task<T>> action) { using var scope = _scopeFactory.CreateScope(); var result = await action(scope.ServiceProvider); return result; } public static async ValueTask ExecuteScopeAsync(Func<IServiceProvider, ValueTask> action) { using var scope = _scopeFactory.CreateScope(); await action(scope.ServiceProvider); } public static async ValueTask<T> ExecuteScopeAsync<T>(Func<IServiceProvider, ValueTask<T>> action) { using var scope = _scopeFactory.CreateScope(); var result = await action(scope.ServiceProvider); return result; } public static void InsertIntoDatabase<T>(params T[] entities) where T : class { ExecuteDbContext(db => { foreach (var entity in entities) { db.Set<T>().Add(entity); } db.SaveChanges(); }); } public static void InsertRangeIntoDatabase<T>(IEnumerable<T> entities) where T : class { ExecuteDbContext(db => { db.Set<T>().AddRange(entities); db.SaveChanges(); }); } public static Task<TResponse?> GetCache<TResponse>(string key) { return ExecuteScopeAsync(sp => { var cache = sp.GetRequiredService<IDistributedCache>(); return cache.GetAsync<TResponse>(key); }); } public static Task<TResponse> SendAsync<TResponse>(IRequest<TResponse> request) { return ExecuteScopeAsync(sp => { var mediator = sp.GetRequiredService<IMediator>(); return mediator.Send(request); }); } public static Task SendAsync(IRequest request) { return ExecuteScopeAsync(sp => { var mediator = sp.GetRequiredService<IMediator>(); return mediator.Send(request); }); } public static void ClearCurrentUser() { _user = null; } public static async Task<ClaimsPrincipal> RunAsDefaultUserAsync() { return await RunAsUserAsync("defaultuser", "Testing1234!"); } public static async Task<ClaimsPrincipal> RunAsUserAsync(string userName = "", string password = "", UserRole role = UserRole.Regular) { using var scope = _scopeFactory.CreateScope(); var dbContext = scope.ServiceProvider.GetService<ApplicationDbContext>() ?? throw new Exception("No user manager"); if (!string.IsNullOrEmpty(userName)) { var user = await dbContext.Users.SingleOrDefaultAsync(u => u.UserName == userName); if (user != null) { return CurrentUserServiceMock.CreateMockPrincipal(user.Id, user.UserName); } } else { userName = $"user{DateTime.Now.Ticks}"; } if (string.IsNullOrEmpty(password)) { password = Guid.NewGuid().ToString("N"); } var pwHasher = scope.ServiceProvider.GetRequiredService<IPasswordHasher>(); password = pwHasher.Hash(password); var newUser = new User(userName, userName + "@localhost", password, role); await dbContext.Users.AddAsync(newUser); await dbContext.SaveChangesAsync(); _user = CurrentUserServiceMock.CreateMockPrincipal(newUser.Id, newUser.UserName); return _user; } public static async Task ResetState() { await using var conn = new NpgsqlConnection(_configuration.GetConnectionString("Database")); await conn.OpenAsync(); await _checkpoint.Reset(conn); } private static void EnsureDatabase() { using var scope = _scopeFactory.CreateScope(); var context = scope.ServiceProvider.GetService<ApplicationDbContext>(); context?.Database.Migrate(); } [OneTimeTearDown] public void RunAfterAnyTests() { } } }
36.167808
142
0.604488
[ "MIT" ]
nollidnosnhoj/Audiochan_old
src/api/tests/Audiochan.Core.IntegrationTests/TestFixture.cs
10,563
C#
using RuneForge.Data.Components; using RuneForge.Game.Components.Attributes; using RuneForge.Game.Components.Implementations; namespace RuneForge.Game.Components.Factories { [ComponentDto(typeof(LocationComponentDto))] public class LocationComponentFactory : ComponentFactory<LocationComponent, LocationComponentPrototype, LocationComponentDto> { public override LocationComponent CreateComponentFromPrototype(LocationComponentPrototype componentPrototype, LocationComponentPrototype componentPrototypeOverride) { int xCells = componentPrototype.XCells ?? 0; int yCells = componentPrototype.YCells ?? 0; int widthCells = (int)componentPrototype.WidthCells; int heightCells = (int)componentPrototype.HeightCells; if (componentPrototypeOverride != null) { if (componentPrototypeOverride.XCells.HasValue) xCells = (int)componentPrototypeOverride.XCells; if (componentPrototypeOverride.YCells.HasValue) yCells = (int)componentPrototypeOverride.YCells; } return LocationComponent.CreateFromCellLocation(xCells, yCells, widthCells, heightCells); } public override LocationComponent CreateComponentFromDto(LocationComponentDto componentDto) { return new LocationComponent(componentDto.X, componentDto.Y, componentDto.Width, componentDto.Height); } } }
43.941176
172
0.711513
[ "MIT" ]
RuneForge/RuneForge
Source/RuneForge.Game/Components/Factories/LocationComponentFactory.cs
1,496
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using NUnit.Framework; using QuantConnect.Data.Market; using QuantConnect.Indicators; namespace QuantConnect.Tests.Indicators { [TestFixture] public class TrueRangeTests : CommonIndicatorTests<TradeBar> { protected override IndicatorBase<TradeBar> CreateIndicator() { return new TrueRange("TR"); } protected override string TestFileName { get { return "spy_tr.txt"; } } protected override string TestColumnName { get { return "TR"; } } } }
31.146341
85
0.693814
[ "Apache-2.0" ]
CircleOnCircles/Lean
Tests/Indicators/TrueRangeTests.cs
1,279
C#
/* * Original author: Brendan MacLean <brendanx .at. u.washington.edu>, * MacCoss Lab, Department of Genome Sciences, UW * * Copyright 2009 University of Washington - Seattle, WA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Globalization; using pwiz.Skyline.Util; namespace pwiz.Skyline.Model { public sealed class IsotopeLabelType : IComparable { // ReSharper disable InconsistentNaming public const string LIGHT_NAME = "light"; // Not L10N public const string HEAVY_NAME = "heavy"; // Not L10N public const string NONE_NAME = "none"; // Not L10N public static readonly IsotopeLabelType light = new IsotopeLabelType(LIGHT_NAME, 0); // Default heavy label for testing public static readonly IsotopeLabelType heavy = new IsotopeLabelType(HEAVY_NAME, 1); // ReSharper restore InconsistentNaming public static int FirstHeavy { get { return light.SortOrder + 1; } } public IsotopeLabelType(string name, int sortOrder) { Name = name; SortOrder = sortOrder; } // NHibernate constructor // ReSharper disable UnusedMember.Local private IsotopeLabelType() { } // ReSharper restore UnusedMember.Local public string Name { get; private set; } public int SortOrder { get; private set; } public bool IsLight { get { return ReferenceEquals(this, light); } } public string Title { get { if (char.IsUpper(Name[0])) return Name; return Name[0].ToString(CultureInfo.InvariantCulture).ToUpperInvariant() + (Name.Length > 1 ? Name.Substring(1) : string.Empty); } } public string Id { get { return Helpers.MakeId(Name); } } public int CompareTo(object obj) { return SortOrder - ((IsotopeLabelType) obj).SortOrder; } #region object overrides public bool Equals(IsotopeLabelType other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Equals(other.Name, Name) && other.SortOrder == SortOrder; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof (IsotopeLabelType)) return false; return Equals((IsotopeLabelType) obj); } public override int GetHashCode() { unchecked { return (Name.GetHashCode()*397) ^ SortOrder; } } /// <summary> /// Label type combo box in peptide settings Modifications tab depends on this /// </summary> public override string ToString() { return Name; } #endregion } }
32.614035
93
0.584185
[ "Apache-2.0" ]
shze/pwizard-deb
pwiz_tools/Skyline/Model/IsotopeLabelType.cs
3,718
C#
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace PInvoke { using System; /// <content> /// Contains the <see cref="WindowStylesEx"/> nested type. /// </content> public partial class User32 { [Flags] public enum WindowStylesEx : uint { /// <summary> /// Specifies a window that accepts drag-drop files. /// </summary> WS_EX_ACCEPTFILES = 0x00000010, /// <summary> /// Forces a top-level window onto the taskbar when the window is visible. /// </summary> WS_EX_APPWINDOW = 0x00040000, /// <summary> /// Specifies a window that has a border with a sunken edge. /// </summary> WS_EX_CLIENTEDGE = 0x00000200, /// <summary> /// Specifies a window that paints all descendants in bottom-to-top painting order using /// double-buffering. This cannot be used if the window has a class style of either CS_OWNDC /// or CS_CLASSDC. This style is not supported in Windows 2000. /// </summary> /// <remarks> /// With WS_EX_COMPOSITED set, all descendants of a window get bottom-to-top painting order /// using double-buffering. Bottom-to-top painting order allows a descendant window to have /// translucency (alpha) and transparency (color-key) effects, but only if the descendant /// window also has the WS_EX_TRANSPARENT bit set. Double-buffering allows the window and its /// descendents to be painted without flicker. /// </remarks> WS_EX_COMPOSITED = 0x02000000, /// <summary> /// Specifies a window that includes a question mark in the title bar. When the user clicks /// the question mark, the cursor changes to a question mark with a pointer. If the user then /// clicks a child window, the child receives a WM_HELP message. The child window should pass /// the message to the parent window procedure, which should call the WinHelp function using /// the HELP_WM_HELP command. The Help application displays a pop-up window that typically /// contains help for the child window. WS_EX_CONTEXTHELP cannot be used with the /// WS_MAXIMIZEBOX or WS_MINIMIZEBOX styles. /// </summary> WS_EX_CONTEXTHELP = 0x00000400, /// <summary> /// Specifies a window which contains child windows that should take part in dialog box /// navigation. If this style is specified, the dialog manager recurses into children of this /// window when performing navigation operations such as handling the TAB key, an arrow key, /// or a keyboard mnemonic. /// </summary> WS_EX_CONTROLPARENT = 0x00010000, /// <summary> /// Specifies a window that has a double border. /// </summary> WS_EX_DLGMODALFRAME = 0x00000001, /// <summary> /// Specifies a window that is a layered window. This cannot be used for child windows or if /// the window has a class style of either CS_OWNDC or CS_CLASSDC. /// </summary> WS_EX_LAYERED = 0x00080000, /// <summary> /// Specifies a window with the horizontal origin on the right edge. Increasing horizontal /// values advance to the left. The shell language must support reading-order alignment for /// this to take effect. /// </summary> WS_EX_LAYOUTRTL = 0x00400000, /// <summary> /// Specifies a window that has generic left-aligned properties. This is the default. /// </summary> WS_EX_LEFT = 0x00000000, /// <summary> /// Specifies a window with the vertical scroll bar (if present) to the left of the client /// area. The shell language must support reading-order alignment for this to take effect. /// </summary> WS_EX_LEFTSCROLLBAR = 0x00004000, /// <summary> /// Specifies a window that displays text using left-to-right reading-order properties. This /// is the default. /// </summary> WS_EX_LTRREADING = 0x00000000, /// <summary> /// Specifies a multiple-document interface (MDI) child window. /// </summary> WS_EX_MDICHILD = 0x00000040, /// <summary> /// Specifies a top-level window created with this style does not become the foreground /// window when the user clicks it. The system does not bring this window to the foreground /// when the user minimizes or closes the foreground window. The window does not appear on /// the taskbar by default. To force the window to appear on the taskbar, use the /// WS_EX_APPWINDOW style. To activate the window, use the SetActiveWindow or /// SetForegroundWindow function. /// </summary> WS_EX_NOACTIVATE = 0x08000000, /// <summary> /// Specifies a window which does not pass its window layout to its child windows. /// </summary> WS_EX_NOINHERITLAYOUT = 0x00100000, /// <summary> /// Specifies that a child window created with this style does not send the WM_PARENTNOTIFY /// message to its parent window when it is created or destroyed. /// </summary> WS_EX_NOPARENTNOTIFY = 0x00000004, /// <summary> /// Specifies an overlapped window. /// </summary> WS_EX_OVERLAPPEDWINDOW = WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE, /// <summary> /// Specifies a palette window, which is a modeless dialog box that presents an array of commands. /// </summary> WS_EX_PALETTEWINDOW = WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST, /// <summary> /// Specifies a window that has generic "right-aligned" properties. This depends on the /// window class. The shell language must support reading-order alignment for this to take /// effect. Using the WS_EX_RIGHT style has the same effect as using the SS_RIGHT (static), /// ES_RIGHT (edit), and BS_RIGHT/BS_RIGHTBUTTON (button) control styles. /// </summary> WS_EX_RIGHT = 0x00001000, /// <summary> /// Specifies a window with the vertical scroll bar (if present) to the right of the client /// area. This is the default. /// </summary> WS_EX_RIGHTSCROLLBAR = 0x00000000, /// <summary> /// Specifies a window that displays text using right-to-left reading-order properties. The /// shell language must support reading-order alignment for this to take effect. /// </summary> WS_EX_RTLREADING = 0x00002000, /// <summary> /// Specifies a window with a three-dimensional border style intended to be used for items /// that do not accept user input. /// </summary> WS_EX_STATICEDGE = 0x00020000, /// <summary> /// Specifies a window that is intended to be used as a floating toolbar. A tool window has a /// title bar that is shorter than a normal title bar, and the window title is drawn using a /// smaller font. A tool window does not appear in the taskbar or in the dialog that appears /// when the user presses ALT+TAB. If a tool window has a system menu, its icon is not /// displayed on the title bar. However, you can display the system menu by right-clicking or /// by typing ALT+SPACE. /// </summary> WS_EX_TOOLWINDOW = 0x00000080, /// <summary> /// Specifies a window that should be placed above all non-topmost windows and should stay /// above them, even when the window is deactivated. To add or remove this style, use the /// SetWindowPos function. /// </summary> WS_EX_TOPMOST = 0x00000008, /// <summary> /// Specifies a window that should not be painted until siblings beneath the window (that /// were created by the same thread) have been painted. The window appears transparent /// because the bits of underlying sibling windows have already been painted. To achieve /// transparency without these restrictions, use the SetWindowRgn function. /// </summary> WS_EX_TRANSPARENT = 0x00000020, /// <summary> /// Specifies a window that has a border with a raised edge. /// </summary> WS_EX_WINDOWEDGE = 0x00000100 } } }
48.082902
118
0.597091
[ "MIT" ]
jmelosegui/pinvoke
src/User32.Desktop/User32+WindowStylesEx.cs
9,282
C#