content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace ONIT.VismaNetApi.Models.CustomDto { public class Subaccount : IProvideCustomDto { private List<Segment> _segments; [JsonProperty] public string description { get; private set; } [JsonProperty] public int id { get; private set; } [JsonProperty] public int subaccountId { get; private set; } [JsonProperty] public string lastModifiedDateTime { get; private set; } [JsonProperty] public List<Segment> segments { get => _segments ?? (_segments = new List<Segment>()); private set => _segments = value; } [JsonProperty] public string errorInfo { get; private set; } [JsonProperty] public JObject extras { get; private set; } /// <summary> /// Sets a segment (department, project) for an invoice line. Remember that you have to set ALL segments for a line. /// </summary> /// <param name="segmentId"></param> /// <returns></returns> public string this[int segmentId] { get { if (segments == null || segments.Count == 0 || segments.All(x => x.segmentId != segmentId)) return string.Empty; var firstOrDefault = segments.FirstOrDefault(x => x.segmentId == segmentId); if (firstOrDefault != null) return firstOrDefault.segmentValue; return string.Empty; } set { var firstOrDefault = segments.FirstOrDefault(x => x.segmentId == segmentId); if (firstOrDefault != null) { firstOrDefault.segmentValue = value; } else { segments.Add(new Segment {segmentId = segmentId, segmentValue = value}); } } } public object ToDto() { return segments.Select(x => new {x.segmentId, x.segmentValue}); } } }
32.072464
124
0.535472
[ "MIT" ]
LasseRafn/Visma.Net
Visma.net/Models/CustomDto/Subaccount.cs
2,215
C#
using System.Threading.Tasks; namespace TelerikUIExample.Data; public interface ITelerikUIExampleDbSchemaMigrator { Task MigrateAsync(); }
16.222222
50
0.808219
[ "MIT" ]
271943794/abp-samples
TelerikUIExample/src/TelerikUIExample.Domain/Data/ITelerikUIExampleDbSchemaMigrator.cs
148
C#
using System; using System.Collections; using System.Globalization; using System.Text; using NetUtils = Org.BouncyCastle.Utilities.Net; namespace Org.BouncyCastle.Asn1.X509 { /** * The GeneralName object. * <pre> * GeneralName ::= CHOICE { * otherName [0] OtherName, * rfc822Name [1] IA5String, * dNSName [2] IA5String, * x400Address [3] ORAddress, * directoryName [4] Name, * ediPartyName [5] EDIPartyName, * uniformResourceIdentifier [6] IA5String, * iPAddress [7] OCTET STRING, * registeredID [8] OBJECT IDENTIFIER} * * OtherName ::= Sequence { * type-id OBJECT IDENTIFIER, * value [0] EXPLICIT ANY DEFINED BY type-id } * * EDIPartyName ::= Sequence { * nameAssigner [0] DirectoryString OPTIONAL, * partyName [1] DirectoryString } * </pre> */ public class GeneralName : Asn1Encodable, IAsn1Choice { public const int OtherName = 0; public const int Rfc822Name = 1; public const int DnsName = 2; public const int X400Address = 3; public const int DirectoryName = 4; public const int EdiPartyName = 5; public const int UniformResourceIdentifier = 6; public const int IPAddress = 7; public const int RegisteredID = 8; internal readonly Asn1Encodable obj; internal readonly int tag; public GeneralName( X509Name directoryName) { this.obj = directoryName; this.tag = 4; } /** * When the subjectAltName extension contains an Internet mail address, * the address MUST be included as an rfc822Name. The format of an * rfc822Name is an "addr-spec" as defined in RFC 822 [RFC 822]. * * When the subjectAltName extension contains a domain name service * label, the domain name MUST be stored in the dNSName (an IA5String). * The name MUST be in the "preferred name syntax," as specified by RFC * 1034 [RFC 1034]. * * When the subjectAltName extension contains a URI, the name MUST be * stored in the uniformResourceIdentifier (an IA5String). The name MUST * be a non-relative URL, and MUST follow the URL syntax and encoding * rules specified in [RFC 1738]. The name must include both a scheme * (e.g., "http" or "ftp") and a scheme-specific-part. The scheme- * specific-part must include a fully qualified domain name or IP * address as the host. * * When the subjectAltName extension contains a iPAddress, the address * MUST be stored in the octet string in "network byte order," as * specified in RFC 791 [RFC 791]. The least significant bit (LSB) of * each octet is the LSB of the corresponding byte in the network * address. For IP Version 4, as specified in RFC 791, the octet string * MUST contain exactly four octets. For IP Version 6, as specified in * RFC 1883, the octet string MUST contain exactly sixteen octets [RFC * 1883]. */ public GeneralName( Asn1Object name, int tag) { this.obj = name; this.tag = tag; } public GeneralName( int tag, Asn1Encodable name) { this.obj = name; this.tag = tag; } /** * Create a GeneralName for the given tag from the passed in string. * <p> * This constructor can handle: * <ul> * <li>rfc822Name</li> * <li>iPAddress</li> * <li>directoryName</li> * <li>dNSName</li> * <li>uniformResourceIdentifier</li> * <li>registeredID</li> * </ul> * For x400Address, otherName and ediPartyName there is no common string * format defined. * </p><p> * Note: A directory name can be encoded in different ways into a byte * representation. Be aware of this if the byte representation is used for * comparing results. * </p> * * @param tag tag number * @param name string representation of name * @throws ArgumentException if the string encoding is not correct or * not supported. */ public GeneralName( int tag, string name) { this.tag = tag; if (tag == Rfc822Name || tag == DnsName || tag == UniformResourceIdentifier) { this.obj = new DerIA5String(name); } else if (tag == RegisteredID) { this.obj = new DerObjectIdentifier(name); } else if (tag == DirectoryName) { this.obj = new X509Name(name); } else if (tag == IPAddress) { byte[] enc = toGeneralNameEncoding(name); if (enc == null) throw new ArgumentException("IP Address is invalid", "name"); this.obj = new DerOctetString(enc); } else { throw new ArgumentException("can't process string for tag: " + tag, "tag"); } } public static GeneralName GetInstance( object obj) { if (obj == null || obj is GeneralName) { return (GeneralName) obj; } if (obj is Asn1TaggedObject) { Asn1TaggedObject tagObj = (Asn1TaggedObject) obj; int tag = tagObj.TagNo; switch (tag) { case OtherName: return new GeneralName(tag, Asn1Sequence.GetInstance(tagObj, false)); case Rfc822Name: return new GeneralName(tag, DerIA5String.GetInstance(tagObj, false)); case DnsName: return new GeneralName(tag, DerIA5String.GetInstance(tagObj, false)); case X400Address: throw new ArgumentException("unknown tag: " + tag); case DirectoryName: return new GeneralName(tag, X509Name.GetInstance(tagObj, true)); case EdiPartyName: return new GeneralName(tag, Asn1Sequence.GetInstance(tagObj, false)); case UniformResourceIdentifier: return new GeneralName(tag, DerIA5String.GetInstance(tagObj, false)); case IPAddress: return new GeneralName(tag, Asn1OctetString.GetInstance(tagObj, false)); case RegisteredID: return new GeneralName(tag, DerObjectIdentifier.GetInstance(tagObj, false)); } } throw new ArgumentException("unknown object in GetInstance: " + obj.GetType().FullName, "obj"); } public static GeneralName GetInstance( Asn1TaggedObject tagObj, bool explicitly) { return GetInstance(Asn1TaggedObject.GetInstance(tagObj, true)); } public int TagNo { get { return tag; } } public Asn1Encodable Name { get { return obj; } } public override string ToString() { StringBuilder buf = new StringBuilder(); buf.Append(tag); buf.Append(": "); switch (tag) { case Rfc822Name: case DnsName: case UniformResourceIdentifier: buf.Append(DerIA5String.GetInstance(obj).GetString()); break; case DirectoryName: buf.Append(X509Name.GetInstance(obj).ToString()); break; default: buf.Append(obj.ToString()); break; } return buf.ToString(); } private byte[] toGeneralNameEncoding( string ip) { if (NetUtils.IPAddress.IsValidIPv6WithNetmask(ip) || NetUtils.IPAddress.IsValidIPv6(ip)) { int slashIndex = ip.IndexOf('/'); if (slashIndex < 0) { byte[] addr = new byte[16]; int[] parsedIp = parseIPv6(ip); copyInts(parsedIp, addr, 0); return addr; } else { byte[] addr = new byte[32]; int[] parsedIp = parseIPv6(ip.Substring(0, slashIndex)); copyInts(parsedIp, addr, 0); string mask = ip.Substring(slashIndex + 1); if (mask.IndexOf(':') > 0) { parsedIp = parseIPv6(mask); } else { parsedIp = parseMask(mask); } copyInts(parsedIp, addr, 16); return addr; } } else if (NetUtils.IPAddress.IsValidIPv4WithNetmask(ip) || NetUtils.IPAddress.IsValidIPv4(ip)) { int slashIndex = ip.IndexOf('/'); if (slashIndex < 0) { byte[] addr = new byte[4]; parseIPv4(ip, addr, 0); return addr; } else { byte[] addr = new byte[8]; parseIPv4(ip.Substring(0, slashIndex), addr, 0); string mask = ip.Substring(slashIndex + 1); if (mask.IndexOf('.') > 0) { parseIPv4(mask, addr, 4); } else { parseIPv4Mask(mask, addr, 4); } return addr; } } return null; } private void parseIPv4Mask(string mask, byte[] addr, int offset) { int maskVal = Int32.Parse(mask); for (int i = 0; i != maskVal; i++) { addr[(i / 8) + offset] |= (byte)(1 << (i % 8)); } } private void parseIPv4(string ip, byte[] addr, int offset) { foreach (string token in ip.Split('.', '/')) { addr[offset++] = (byte)Int32.Parse(token); } } private int[] parseMask(string mask) { int[] res = new int[8]; int maskVal = Int32.Parse(mask); for (int i = 0; i != maskVal; i++) { res[i / 16] |= 1 << (i % 16); } return res; } private void copyInts(int[] parsedIp, byte[] addr, int offSet) { for (int i = 0; i != parsedIp.Length; i++) { addr[(i * 2) + offSet] = (byte)(parsedIp[i] >> 8); addr[(i * 2 + 1) + offSet] = (byte)parsedIp[i]; } } private int[] parseIPv6(string ip) { if (ip.StartsWith("::")) { ip = ip.Substring(1); } else if (ip.EndsWith("::")) { ip = ip.Substring(0, ip.Length - 1); } IEnumerator sEnum = ip.Split(':').GetEnumerator(); int index = 0; int[] val = new int[8]; int doubleColon = -1; while (sEnum.MoveNext()) { string e = (string) sEnum.Current; if (e.Length == 0) { doubleColon = index; val[index++] = 0; } else { if (e.IndexOf('.') < 0) { val[index++] = Int32.Parse(e, NumberStyles.AllowHexSpecifier); } else { string[] tokens = e.Split('.'); val[index++] = (Int32.Parse(tokens[0]) << 8) | Int32.Parse(tokens[1]); val[index++] = (Int32.Parse(tokens[2]) << 8) | Int32.Parse(tokens[3]); } } } if (index != val.Length) { Array.Copy(val, doubleColon, val, val.Length - (index - doubleColon), index - doubleColon); for (int i = doubleColon; i != val.Length - (index - doubleColon); i++) { val[i] = 0; } } return val; } public override Asn1Object ToAsn1Object() { // Explicitly tagged if DirectoryName return new DerTaggedObject(tag == DirectoryName, tag, obj); } } }
26.884521
98
0.571468
[ "Unlicense" ]
WolfeReiter/BouncyCastleCrypto
crypto/src/asn1/x509/GeneralName.cs
10,942
C#
using Microsoft.Win32; using System; using System.ComponentModel; using System.IO; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media.Animation; using System.Xml.Linq; namespace MAF.Entropy.WPF { /// <summary> /// Interaction logic for Base.xaml /// </summary> public partial class Base : Page { BackgroundWorker worker = new BackgroundWorker(); EntropyCalculator ec; string extension; public Base() { InitializeComponent(); tbFile.Text = Properties.Settings.Default.DataFile; } private void LoadFileButton_Click(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Feldolgozandó fájlok (*.txt)|*.txt|Eredmény fájlok (*.xml)|*.xml"; if (tbFile.Text != string.Empty) { try { if (File.Exists(tbFile.Text)) openFileDialog.InitialDirectory = Path.GetDirectoryName(tbFile.Text); else if (Directory.Exists(tbFile.Text)) openFileDialog.InitialDirectory = tbFile.Text; } catch { } } if (openFileDialog.ShowDialog() == true) { tbFile.Text = openFileDialog.FileName; extension = Path.GetExtension(openFileDialog.FileName).ToLower(); SetButtonRunAnalytics(); } } void SetButtonRunAnalytics() { try { if (File.Exists(tbFile.Text)) { bRunAnalytics.IsEnabled = true; if (extension == ".xml") { RunButtonText.Text = "Fájl betöltése"; LoadTextTabItem.Visibility = Visibility.Hidden; } else { RunButtonText.Text = "Fájl feldolgozása"; LoadTextTabItem.Visibility = Visibility.Visible; } } else bRunAnalytics.IsEnabled = false; } catch { } } private void AboutButton_Click(object sender, RoutedEventArgs e) { try { About login = new About(); login.Owner = Application.Current.MainWindow; login.ShowDialog(); bLoginTB1.Text = "Köszönöm, hogy megtekintetted a névjegyet!"; AboutButton.Click -= AboutButton_Click; } catch (Exception ex) { MessageBox.Show($"A névjegy ablak betöltése nem sikerült! {Environment.NewLine}Hiba: {ex.Message}", "Hiba"); } } private void RunAnalyticsButton_Click(object sender, RoutedEventArgs e) { try { if (!File.Exists(tbFile.Text)) { MessageBox.Show("Nem létezik a megadott fájl!"); return; } if (extension == ".xml") { XElement result = XElement.Load(tbFile.Text); StatisticsGrid.DataContext = result; DataPanel.Visibility = Visibility.Visible; return; } IsEnabled = false; LoadingAnimation.Visibility = Visibility.Visible; DataPanel.Visibility = Visibility.Hidden; DataText.Text = File.ReadAllText(tbFile.Text); ec = new EntropyCalculator(); ec.RunCalculation(tbFile.Text); Run r = (Run)LoadingAnimation.FindName("info"); r.Text = $"{ec.RunningThreadCount} száll dolgozik"; worker.DoWork += Worker_DoWork; worker.RunWorkerCompleted += Worker_RunWorkerCompleted; worker.RunWorkerAsync(); } catch (Exception ex) { IsEnabled = true; LoadingAnimation.Visibility = Visibility.Hidden; MessageBox.Show($"A feldolgozás nem sikerült! {Environment.NewLine}Hiba: {ex.Message}", "Hiba"); } } private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { XElement result = XElement.Load(ec.ResultFile); StatisticsGrid.DataContext = result; DataFile.Content = $"Feldolgozott fájl: {tbFile.Text}"; LoadingAnimation.Visibility = Visibility.Hidden; DataPanel.Visibility = Visibility.Visible; IsEnabled = true; } private void Worker_DoWork(object sender, DoWorkEventArgs e) { try { ec.WaitForAll(); } catch (Exception ex) { MessageBox.Show($"A feldolgozás nem sikerült! {Environment.NewLine}Hiba: {ex.Message}", "Hiba"); } } delegate void WriteInfoBackground(); private void StatisticsGrid_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) { if (StatisticsGrid.SelectedIndex == -1) return; ((MainWindow)Application.Current.MainWindow).Content = new Items((XElement)StatisticsGrid.SelectedItem); } private void File_TextChanged(object sender, TextChangedEventArgs e) { try { extension = Path.GetExtension(tbFile.Text).ToLower(); } catch { extension = "txt"; } SetButtonRunAnalytics(); } } }
32.241935
124
0.510922
[ "MIT" ]
malbertHE/1-TextAnalytics
SRC/Product/MAF.Entropy.WPF/Base.xaml.cs
6,024
C#
using MagicTheGatheringArena.Core; using MagicTheGatheringArena.Core.MVVM; using MagicTheGatheringArena.Core.Scryfall.Data; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; using System.Windows.Input; using System.Windows.Threading; using WPF.InternalDialogs; namespace MagicTheGatheringArenaDeckMaster.ViewModels { internal class MainWindowViewModel : ViewModelBase { #region Fields private CollectionView? cardCollectionView; private ObservableCollection<UniqueArtTypeViewModel> cardData; private CollectionView? cardImageCollectionView; private ObservableCollection<UniqueArtTypeViewModel> cardImageData; private string? cardImageSearch; private DispatcherTimer? cardImageSearchTimer; private DispatcherOperation? cardImageSearchOperation; private string? cardNameSearch; private DispatcherTimer? cardNameSearchTimer; private DispatcherOperation? cardNameSearchOperation; private Dispatcher? dispatcher; private ICommand? downloadCardImagesCommand; private ICommand? downloadDataCommand; private InternalDialogUserControlViewModel? internalDialogViewModel; private bool? isAllSmallChecked = false; private bool? isAllNormalChecked = false; private bool? isAllLargeChecked = false; private bool? isAllPngChecked = false; private bool? isAllArtCropChecked = false; private bool? isAllBorderCropChecked = false; private int selectedImageCount; private CollectionView? setCollectionView; private ObservableCollection<SetNameViewModel> setNames; private string? setNameSearch; private DispatcherTimer? setNameSearchTimer; private DispatcherOperation? setNameSearchOperation; private bool showOnlySetAllowedInStandard; private bool showOnlySetAllowedInMtgaStandard; private List<string>? standardOnlySets; private string? statusMessage; private string? version; #endregion #region Properties public CollectionView? CardCollectionView { get => cardCollectionView; set { cardCollectionView = value; OnPropertyChanged(); } } public ObservableCollection<UniqueArtTypeViewModel> CardData { get => cardData; set { cardData = value; OnPropertyChanged(); } } public CollectionView? CardImageCollectionView { get => cardImageCollectionView; set { cardImageCollectionView = value; OnPropertyChanged(); } } public ObservableCollection<UniqueArtTypeViewModel> CardImageData { get => cardImageData; set { cardImageData = value; OnPropertyChanged(); } } public string? CardImageSearch { get => cardImageSearch; set { cardImageSearch = value; //CardImageCollectionView?.Refresh(); if (cardImageSearchTimer != null && cardImageSearchTimer.IsEnabled) cardImageSearchTimer.Stop(); if (cardImageSearchOperation != null) cardImageSearchOperation.Abort(); if (cardImageSearchTimer != null) cardImageSearchTimer.Start(); OnPropertyChanged(); } } public string? CardNameSearch { get => cardNameSearch; set { cardNameSearch = value; //CardCollectionView?.Refresh(); //VerifyStateOfSmallCheckBoxAndSet(); //VerifyStateOfNormalCheckBoxAndSet(); //VerifyStateOfLargeCheckBoxAndSet(); //VerifyStateOfPngCheckBoxAndSet(); //VerifyStateOfArtCropCheckBoxAndSet(); //VerifyStateOfBorderCropCheckBoxAndSet(); if (cardNameSearchTimer != null && cardNameSearchTimer.IsEnabled) cardNameSearchTimer.Stop(); if (cardNameSearchOperation != null) cardNameSearchOperation.Abort(); if (cardNameSearchTimer != null) cardNameSearchTimer.Start(); OnPropertyChanged(); } } public Dispatcher? Dispatcher { get => dispatcher; set { dispatcher = value; cardImageSearchTimer = new DispatcherTimer(new TimeSpan(0, 0, 2), DispatcherPriority.Normal, CardImageSearchTick, value); cardNameSearchTimer = new DispatcherTimer(new TimeSpan(0, 0, 2), DispatcherPriority.Normal, CardNameSearchTick, value); setNameSearchTimer = new DispatcherTimer(new TimeSpan(0, 0, 2), DispatcherPriority.Normal, SetNameSearchTick, value); } } public ICommand? DownloadCardImagesCommand => downloadCardImagesCommand ??= new RelayCommand(DownloadCardData, CanDownloadCardImages); public ICommand? DownloadDataCommand => downloadDataCommand ??= new RelayCommand(DownloadData); public InternalDialogUserControlViewModel? InternalDialogViewModel { get => internalDialogViewModel; set { internalDialogViewModel = value; OnPropertyChanged(); } } public bool? IsAllSmallChecked { get => isAllSmallChecked; set { isAllSmallChecked = value; if (value.HasValue) { // if this nullable bool is null don't alter check box state CheckAllSmallOptionsForFilteredCards(value.Value); } OnPropertyChanged(); } } public bool? IsAllNormalChecked { get => isAllNormalChecked; set { isAllNormalChecked = value; if (value.HasValue) { // if this nullable bool is null don't alter check box state CheckAllNormalOptionsForFilteredCards(value.Value); } OnPropertyChanged(); } } public bool? IsAllLargeChecked { get => isAllLargeChecked; set { isAllLargeChecked = value; if (value.HasValue) { // if this nullable bool is null don't alter check box state CheckAllLargeOptionsForFilteredCards(value.Value); } OnPropertyChanged(); } } public bool? IsAllPngChecked { get => isAllPngChecked; set { isAllPngChecked = value; if (value.HasValue) { // if this nullable bool is null don't alter check box state CheckAllPngOptionsForFilteredCards(value.Value); } OnPropertyChanged(); } } public bool? IsAllArtCropChecked { get => isAllArtCropChecked; set { isAllArtCropChecked = value; if (value.HasValue) { // if this nullable bool is null don't alter check box state CheckAllArtCropOptionsForFilteredCards(value.Value); } OnPropertyChanged(); } } public bool? IsAllBorderCropChecked { get => isAllBorderCropChecked; set { isAllBorderCropChecked = value; if (value.HasValue) { // if this nullable bool is null don't alter check box state CheckAllBorderCropOptionsForFilteredCards(value.Value); } OnPropertyChanged(); } } public int SelectedImageCount { get => selectedImageCount; set { if (value < 0) // it its zero at a minimum selectedImageCount = 0; else selectedImageCount = value; OnPropertyChanged(); } } public CollectionView? SetCollectionView { get => setCollectionView; set { setCollectionView = value; OnPropertyChanged(); } } public ObservableCollection<SetNameViewModel> SetNames { get => setNames; set { setNames = value; OnPropertyChanged(); } } public string? SetNameSearch { get => setNameSearch; set { setNameSearch = value; //SetCollectionView?.Refresh(); if (setNameSearchTimer != null && setNameSearchTimer.IsEnabled) setNameSearchTimer.Stop(); if (setNameSearchOperation != null) setNameSearchOperation.Abort(); if (setNameSearchTimer != null) setNameSearchTimer.Start(); OnPropertyChanged(); } } public bool ShowOnlySetAllowedInStandard { get => showOnlySetAllowedInStandard; set { showOnlySetAllowedInStandard = value; SetCollectionView?.Refresh(); OnPropertyChanged(); } } public bool ShowOnlySetAllowedInMtgaStandard { get => showOnlySetAllowedInMtgaStandard; set { showOnlySetAllowedInMtgaStandard = value; SetCollectionView?.Refresh(); OnPropertyChanged(); } } public string? StatusMessage { get => statusMessage; set { statusMessage = value; OnPropertyChanged(); } } public string? Version { get => version; set { version = value; OnPropertyChanged(); } } #endregion #region Constructors public MainWindowViewModel() { cardData = new ObservableCollection<UniqueArtTypeViewModel>(); cardImageData = new ObservableCollection<UniqueArtTypeViewModel>(); setNames = new ObservableCollection<SetNameViewModel>(); } #endregion #region Methods private void BackupReferencedFile() { if (InternalDialogViewModel == null) return; // copy on another thread so we don't block the UI...wait 5 seconds though so we can read the data first Task.Delay(5000).ContinueWith((task) => { StatusMessage = "Backing up referenced file..."; string[] files = Directory.GetFiles(ServiceLocator.Instance.PathingService.BaseDataPath, "*.json"); if (files.Length > 0) { // there will only ever be one backup file string existingFilename = Path.GetFileName(files[0]); string newFilename = Path.GetFileName(InternalDialogViewModel.FileLocation); if ((existingFilename != newFilename) || existingFilename == newFilename && !InternalDialogViewModel.HasDataPreviously) { // either file names are not the same or they are but the user picked a new file with the same name, ok to delete old one string filename = Path.Combine(ServiceLocator.Instance.PathingService.BaseDataPath, Path.GetFileName(InternalDialogViewModel.FileLocation)); File.Copy(InternalDialogViewModel.FileLocation, filename, true); File.Delete(existingFilename); } else if (existingFilename == newFilename && InternalDialogViewModel.HasDataPreviously) { // leave the file alone because the user referenced this backed up file } } else { string filename = Path.Combine(ServiceLocator.Instance.PathingService.BaseDataPath, Path.GetFileName(InternalDialogViewModel.FileLocation)); File.Copy(InternalDialogViewModel.FileLocation, filename); } StatusMessage = "Referenced file successfully backed up."; // just wait 5 seconds to reset the status message Task.Delay(5000).ContinueWith(task => { StatusMessage = "Ready"; }); }).ContinueWith(task => { if (task.Exception != null) { ServiceLocator.Instance.LoggerService.Error($"An error occurred attempting to back up the referenced file.{Environment.NewLine}{task.Exception}"); StatusMessage = "Referenced file failed to back up. See log for more details."; } }); } public void BeginInvokeOnDispatcher(Action action) { Dispatcher?.BeginInvoke(action, DispatcherPriority.Normal); } private bool CardFilterPredicate(object obj) { if (obj is not UniqueArtTypeViewModel uavm) return false; foreach (SetNameViewModel vm in SetNames) { if (vm.IsChecked) { if (!string.IsNullOrWhiteSpace(CardNameSearch)) { if (uavm.Set == vm.Name && uavm.Name.IndexOf(CardNameSearch, StringComparison.OrdinalIgnoreCase) > -1) return true; } else { if (uavm.Set == vm.Name) return true; } } } return false; } private bool CardImageFilterPredicate(object obj) { if (obj is not UniqueArtTypeViewModel uavm) return false; foreach (SetNameViewModel vm in SetNames) { if (vm.IsChecked) { if (!string.IsNullOrWhiteSpace(CardImageSearch)) { if (uavm.Set == vm.Name && (!string.IsNullOrWhiteSpace(uavm.ImagePathSmall) || !string.IsNullOrWhiteSpace(uavm.ImagePathNormal)) || !string.IsNullOrWhiteSpace(uavm.ImagePathLarge) || !string.IsNullOrWhiteSpace(uavm.ImagePathPng) && (uavm.Name.IndexOf(CardImageSearch, StringComparison.OrdinalIgnoreCase) > -1 || (!string.IsNullOrWhiteSpace(uavm.Model.oracle_text) && uavm.Model.oracle_text.IndexOf(CardImageSearch, StringComparison.OrdinalIgnoreCase) > -1))) return true; } else { if (uavm.Set == vm.Name && (!string.IsNullOrWhiteSpace(uavm.ImagePathSmall) || !string.IsNullOrWhiteSpace(uavm.ImagePathNormal)) || !string.IsNullOrWhiteSpace(uavm.ImagePathLarge) || !string.IsNullOrWhiteSpace(uavm.ImagePathPng)) return true; } } } return false; } private void CardImageSearchTick(object? sender, EventArgs e) { cardImageSearchOperation = Dispatcher?.BeginInvoke(() => { CardImageCollectionView?.Refresh(); }, DispatcherPriority.Normal); } private void CardNameSearchTick(object? sender, EventArgs e) { cardNameSearchOperation = Dispatcher?.BeginInvoke(() => { CardCollectionView?.Refresh(); VerifyStateOfSmallCheckBoxAndSet(); VerifyStateOfNormalCheckBoxAndSet(); VerifyStateOfLargeCheckBoxAndSet(); VerifyStateOfPngCheckBoxAndSet(); VerifyStateOfArtCropCheckBoxAndSet(); VerifyStateOfBorderCropCheckBoxAndSet(); }, DispatcherPriority.Normal); } private void CheckAllSmallOptionsForFilteredCards(bool isChecked) { CheckAllForImageTypeForFilteredCards(isChecked, ImageType.Small); } private void CheckAllNormalOptionsForFilteredCards(bool isChecked) { CheckAllForImageTypeForFilteredCards(isChecked, ImageType.Normal); } private void CheckAllLargeOptionsForFilteredCards(bool isChecked) { CheckAllForImageTypeForFilteredCards(isChecked, ImageType.Large); } private void CheckAllPngOptionsForFilteredCards(bool isChecked) { CheckAllForImageTypeForFilteredCards(isChecked, ImageType.Png); } private void CheckAllArtCropOptionsForFilteredCards(bool isChecked) { CheckAllForImageTypeForFilteredCards(isChecked, ImageType.ArtCrop); } private void CheckAllBorderCropOptionsForFilteredCards(bool isChecked) { CheckAllForImageTypeForFilteredCards(isChecked, ImageType.BorderCrop); } private void CheckAllForImageTypeForFilteredCards(bool isChecked, ImageType imageType) { if (CardCollectionView == null) return; for (int i = 0; i < CardCollectionView.Count; i++) { if (CardCollectionView.GetItemAt(i) is not UniqueArtTypeViewModel uavm) continue; uavm.IsInternallySettingValue = true; switch (imageType) { case ImageType.Small: uavm.DownloadSmallPicture = isChecked; break; case ImageType.Normal: uavm.DownloadNormalPicture = isChecked; break; case ImageType.Large: uavm.DownloadLargePicture = isChecked; break; case ImageType.Png: uavm.DownloadPngPicture = isChecked; break; case ImageType.ArtCrop: uavm.DownloadArtCropPicture = isChecked; break; case ImageType.BorderCrop: uavm.DownloadBorderCropPicture = isChecked; break; } uavm.IsInternallySettingValue = false; } } private bool CanDownloadCardImages() { return SelectedImageCount > 0; } private void DownloadCardData() { if (InternalDialogViewModel == null) return; InternalDialogViewModel.MessageBoxTitle = "Confirm Download"; InternalDialogViewModel.MessageBoxMessage = $"Are you sure you wish download {SelectedImageCount} images? Images already downloaded will not be downloaded again."; InternalDialogViewModel.MessageBoxImage = MessageBoxInternalDialogImage.Help; InternalDialogViewModel.MessageBoxIsModal = true; InternalDialogViewModel.MessageBoxButton = MessageBoxButton.YesNo; InternalDialogViewModel.MessageBoxVisibility = Visibility.Visible; // because it is shown modally this code will not execute until it is closed InternalDialogViewModel.MessageBoxTitle = string.Empty; InternalDialogViewModel.MessageBoxMessage = string.Empty; InternalDialogViewModel.MessageBoxImage = MessageBoxInternalDialogImage.Information; InternalDialogViewModel.MessageBoxIsModal = false; InternalDialogViewModel.MessageBoxButton = MessageBoxButton.OK; if (InternalDialogViewModel.MessageBoxResult != MessageBoxResult.Yes) { return; } InternalDialogViewModel.CardProgressVisibility = Visibility.Visible; Task.Run(() => { if (CardCollectionView != null) { List<UniqueArtTypeViewModel> selectedCards = new List<UniqueArtTypeViewModel>(); for (int i = 0; i < CardData.Count; i++) { UniqueArtTypeViewModel? vm = CardData[i]; if (vm == null) continue; if (vm.DownloadArtCropPicture || vm.DownloadBorderCropPicture || vm.DownloadLargePicture || vm.DownloadNormalPicture || vm.DownloadPngPicture || vm.DownloadSmallPicture) { selectedCards.Add(vm); } } //ServiceLocator.Instance.ScryfallService.ImageProcessed += ScryfallService_ImageProcessed; StatusMessage = "Downloading image files..."; // now that we have all our cards that have at least one download check box checked...lets download them // we'll parallel process all the images the best we can Parallel.ForEach(selectedCards, new ParallelOptions { MaxDegreeOfParallelism = 6 }, card => { string setPath = Path.Combine(ServiceLocator.Instance.PathingService.CardImagePath, card.Model.set_name.ReplaceBadWindowsCharacters()); if (!Directory.Exists(setPath)) Directory.CreateDirectory(setPath); //ServiceLocator.Instance.ScryfallService.DownloadArtworkFiles(card.Model, card.DownloadSmallPicture, card.DownloadNormalPicture, // card.DownloadLargePicture, card.DownloadPngPicture, card.DownloadArtCropPicture, card.DownloadBorderCropPicture, setPath); }); // check to see if we have already downloaded cards List<string> setPaths = Directory.GetDirectories(ServiceLocator.Instance.PathingService.CardImagePath).ToList(); foreach (string setPath in setPaths) { // let's first get all the cards in that set List<UniqueArtTypeViewModel> setCards = selectedCards.Where(card => card.Model.set_name.ReplaceBadWindowsCharacters() == setPath.Substring(setPath.LastIndexOf("\\", StringComparison.OrdinalIgnoreCase) + 1)) .ToList(); // loop through all our matching cards foreach (UniqueArtTypeViewModel card in setCards) { // get all the paths in our set directory List<string> cardPaths = Directory.GetDirectories(setPath).ToList(); foreach (string cardPath in cardPaths) { // if the card directory name matches the last part of our path (the card name part) if (card.Model.name_field.ReplaceBadWindowsCharacters() == cardPath.Substring(cardPath.LastIndexOf("\\", StringComparison.OrdinalIgnoreCase) + 1)) { // check which images it has List<string> cardImagesFiles = Directory.GetFiles(cardPath).ToList(); foreach (string cardImagePath in cardImagesFiles) { string name = Path.GetFileNameWithoutExtension(cardImagePath); if (string.IsNullOrWhiteSpace(name)) continue; if (name.Contains("small", StringComparison.OrdinalIgnoreCase)) { card.ImagePathSmall = cardImagePath; } if (name.Contains("normal", StringComparison.OrdinalIgnoreCase)) { card.ImagePathNormal = cardImagePath; } if (name.Contains("large", StringComparison.OrdinalIgnoreCase)) { card.ImagePathLarge = cardImagePath; } if (name.Contains("png", StringComparison.OrdinalIgnoreCase)) { card.ImagePathPng = cardImagePath; } if (name.Contains("artCrop", StringComparison.OrdinalIgnoreCase)) { card.ImagePathArtCrop = cardImagePath; } if (name.Contains("borderCrop", StringComparison.OrdinalIgnoreCase)) { card.ImagePathBorderCrop = cardImagePath; } } } } // if our images doesn't contain our card then add because we added an image InvokeOnDispatcher(() => { if (!CardImageData.Contains(card)) CardImageData.Add(card); }); } } //ServiceLocator.Instance.ScryfallService.ImageProcessed -= ScryfallService_ImageProcessed; InternalDialogViewModel.CardProgressVisibility = Visibility.Collapsed; InternalDialogViewModel.CardProgressValue = 0; StatusMessage = "Card images downloaded"; InternalDialogViewModel.MessageBoxTitle = "Card Images Downloaded"; InternalDialogViewModel.MessageBoxMessage = "The card images that could be downloaded have been downloaded. See please log for failures (if any)."; InternalDialogViewModel.MessageBoxVisibility = Visibility.Visible; InvokeOnDispatcher(() => { CardImageCollectionView?.Refresh(); }); Task.Delay(5000).ContinueWith(task => { StatusMessage = "Ready"; }); } }); } private void ScryfallService_ImageProcessed(object? sender, int e) { if (InternalDialogViewModel == null) return; InternalDialogViewModel.CardProgressValue += e; } private void DownloadData() { if (InternalDialogViewModel == null) return; InternalDialogViewModel.ProgressDialogVisbility = Visibility.Visible; InternalDialogViewModel.ProgressMessage = "Contacting Scryfall for information..."; InternalDialogViewModel.ProgressTitle = "Downloading Data"; Task.Run(() => { return ServiceLocator.Instance.ScryfallService.GetUniqueArtworkUri(); }).ContinueWith(task => { if (task.Exception == null) { BulkDataType result = task.Result; if (result == null) { InternalDialogViewModel.ProgressDialogVisbility = Visibility.Collapsed; InternalDialogViewModel.ProgressMessage = string.Empty; InternalDialogViewModel.ProgressTitle = string.Empty; InternalDialogViewModel.MessageBoxVisibility = Visibility.Visible; InternalDialogViewModel.MessageBoxMessage = "Could not download information about unique artwork file from Scryfall."; InternalDialogViewModel.MessageBoxTitle = "Download Failure"; } else { InternalDialogViewModel.ProgressMessage = "Information downloaded from Scryfall. Downloading unique artwork file..."; string filename = result.download_uri.Substring(result.download_uri.LastIndexOf("/", StringComparison.OrdinalIgnoreCase) + 1); string fullPath = Path.Combine(ServiceLocator.Instance.PathingService.BaseDataPath, filename); // clear all existing JSON files (the one) string[] files = Directory.GetFiles(ServiceLocator.Instance.PathingService.BaseDataPath, "*.json"); foreach (string file in files) { File.Delete(file); } ServiceLocator.Instance.ScryfallService.DownloadUniqueArtworkFile(result, fullPath); if (File.Exists(fullPath)) { InternalDialogViewModel.FileLocation = fullPath; InternalDialogViewModel.ProgressMessage = "Information downloaded from Scryfall."; // after 5 seconds hide the message Task.Delay(5000).ContinueWith((delayTask) => { ProcessFileData(); }); } else { InternalDialogViewModel.ProgressDialogVisbility = Visibility.Collapsed; InternalDialogViewModel.ProgressMessage = string.Empty; InternalDialogViewModel.ProgressTitle = string.Empty; InternalDialogViewModel.MessageBoxVisibility = Visibility.Visible; InternalDialogViewModel.MessageBoxMessage = "Unable to download file information from Scryfall. Please check internet connect, that Scryfall is currently online or look in the log to see if an error occurred."; InternalDialogViewModel.MessageBoxTitle = "Download Failure"; } } } }).ContinueWith(task => { if (task.Exception != null) { ServiceLocator.Instance.LoggerService.Error($"An error occurred attempting to load in file form browser.{Environment.NewLine}{task.Exception}"); InternalDialogViewModel.ProgressDialogVisbility = Visibility.Collapsed; InternalDialogViewModel.ProgressMessage = string.Empty; InternalDialogViewModel.ProgressTitle = string.Empty; InternalDialogViewModel.MessageBoxVisibility = Visibility.Visible; InternalDialogViewModel.MessageBoxMessage = $"An error occurred attempting to download the file. {task.Exception.Message}{Environment.NewLine}See the log for more details."; InternalDialogViewModel.MessageBoxTitle = "Error Processing"; } }); } public void InvokeOnDispatcher(Action action) { Dispatcher?.Invoke(action, DispatcherPriority.Normal); } public void ProcessFileData() { if (InternalDialogViewModel == null) return; InternalDialogViewModel.ProgressDialogVisbility = Visibility.Visible; InternalDialogViewModel.ProgressMessage = "Processing selected file..."; InternalDialogViewModel.ProgressTitle = "Processing Data"; Task.Run(() => { BackupReferencedFile(); string text = File.ReadAllText(InternalDialogViewModel.FileLocation); List<UniqueArtType>? cards = JsonConvert.DeserializeObject<List<UniqueArtType>>(text); // get distinct card names within each set List<UniqueArtType> uniqueCards = new(); var groupedBySet = cards?.GroupBy(c => c.set_name); if (groupedBySet != null) { foreach (var group in groupedBySet) { var nameGrouped = group.GroupBy(c => c.name_field).ToList(); foreach (var nameGroup in nameGrouped) { uniqueCards.Add(nameGroup.First()); } } } uniqueCards = uniqueCards.Where(card => card.image_uris != null).ToList(); uniqueCards = uniqueCards.OrderBy(uat => uat.set_name).ThenBy(uat => uat.name_field).ToList(); // build our vm representations List<UniqueArtTypeViewModel> vms = uniqueCards.Select(c => new UniqueArtTypeViewModel(c, this)).ToList(); List<string> uniqueSetNames = uniqueCards.Select(c => c.set_name).Distinct().ToList(); // we know what cards are allowed in standard mode, then we get the list of distinct set names just like above standardOnlySets = uniqueCards.Where(c => c.legalities.standard == "legal").Select(c => c.set_name).Distinct().ToList(); // check to see if we have already downloaded cards List<string> setPaths = Directory.GetDirectories(ServiceLocator.Instance.PathingService.CardImagePath).ToList(); foreach (string setPath in setPaths) { // let's first get all the cards in that set List<UniqueArtTypeViewModel> setCards = vms.Where(card => card.Model.set_name.ReplaceBadWindowsCharacters() == setPath.Substring(setPath.LastIndexOf("\\", StringComparison.OrdinalIgnoreCase) + 1)) .ToList(); // loop through all our matching cards foreach (UniqueArtTypeViewModel card in setCards) { // get all the paths in our set directory List<string> cardPaths = Directory.GetDirectories(setPath).ToList(); foreach (string cardPath in cardPaths) { // if the card directory name matches the last part of our path (the card name part) if (card.Model.name_field.ReplaceBadWindowsCharacters() == cardPath.Substring(cardPath.LastIndexOf("\\", StringComparison.OrdinalIgnoreCase) + 1)) { // check which images it has List<string> cardImagesFiles = Directory.GetFiles(cardPath).ToList(); foreach (string cardImagePath in cardImagesFiles) { string name = Path.GetFileNameWithoutExtension(cardImagePath); if (string.IsNullOrWhiteSpace(name)) continue; if (name.Contains("small", StringComparison.OrdinalIgnoreCase)) { card.DownloadSmallPicture = true; card.ImagePathSmall = cardImagePath; } if (name.Contains("normal", StringComparison.OrdinalIgnoreCase)) { card.DownloadNormalPicture = true; card.ImagePathNormal = cardImagePath; } if (name.Contains("large", StringComparison.OrdinalIgnoreCase)) { card.DownloadLargePicture = true; card.ImagePathLarge = cardImagePath; } if (name.Contains("png", StringComparison.OrdinalIgnoreCase)) { card.DownloadPngPicture = true; card.ImagePathPng = cardImagePath; } if (name.Contains("artCrop", StringComparison.OrdinalIgnoreCase)) { card.DownloadArtCropPicture = true; card.ImagePathArtCrop = cardImagePath; } if (name.Contains("borderCrop", StringComparison.OrdinalIgnoreCase)) { card.DownloadBorderCropPicture = true; card.ImagePathBorderCrop = cardImagePath; } } } } } } InvokeOnDispatcher(() => { CardData.Clear(); CardData.AddRange(vms); CardImageData.Clear(); CardImageData.AddRange(vms.Where(vm => !string.IsNullOrWhiteSpace(vm.ImagePathPng) || !string.IsNullOrWhiteSpace(vm.ImagePathSmall) || !string.IsNullOrWhiteSpace(vm.ImagePathNormal) || !string.IsNullOrWhiteSpace(vm.ImagePathLarge))); SetNames.Clear(); SetNames.AddRange(uniqueSetNames.Select(s => new SetNameViewModel(this) { Name = s })); SetCollectionView = (CollectionView)CollectionViewSource.GetDefaultView(SetNames); SetCollectionView.Filter = SetNameFilterPredicate; CardCollectionView = (CollectionView)CollectionViewSource.GetDefaultView(CardData); CardCollectionView.Filter = CardFilterPredicate; CardImageCollectionView = (CollectionView)CollectionViewSource.GetDefaultView(CardImageData); CardImageCollectionView.Filter = CardImageFilterPredicate; }); }).ContinueWith((task) => { InternalDialogViewModel.ProgressMessage = string.Empty; InternalDialogViewModel.ProgressTitle = string.Empty; InternalDialogViewModel.ProgressDialogVisbility = Visibility.Collapsed; InternalDialogViewModel.MessageBoxVisibility = Visibility.Visible; InternalDialogViewModel.NeedDataVisibility = Visibility.Collapsed; StatusMessage = "Ready"; if (task.Exception != null) { ServiceLocator.Instance.LoggerService.Error($"An error occurred attempting to load in file form browser.{Environment.NewLine}{task.Exception}"); InternalDialogViewModel.MessageBoxMessage = $"An error occurred attempting to process the file. {task.Exception.Message}{Environment.NewLine}See the log for more details."; InternalDialogViewModel.MessageBoxTitle = "Error Processing"; } else { InternalDialogViewModel.MessageBoxMessage = "The file has been processed."; InternalDialogViewModel.MessageBoxTitle = "File Processed"; } }); } private bool SetNameFilterPredicate(object obj) { if (obj is not SetNameViewModel snvm) return false; if (ShowOnlySetAllowedInMtgaStandard) { if (snvm.Name.Equals("Adventures in the Forgotten Realms", StringComparison.OrdinalIgnoreCase) || snvm.Name.Equals("Innistrad: Crimson Vow", StringComparison.OrdinalIgnoreCase) || snvm.Name.Equals("Innistrad: Midnight Hunt", StringComparison.OrdinalIgnoreCase) || snvm.Name.Equals("Kaldheim", StringComparison.OrdinalIgnoreCase) || snvm.Name.Equals("Strixhaven: School of Mages", StringComparison.OrdinalIgnoreCase) || snvm.Name.Equals("Zendikar Rising", StringComparison.OrdinalIgnoreCase) || snvm.Name.Equals("Kamigawa: Neon Dynasty", StringComparison.OrdinalIgnoreCase)) { if (string.IsNullOrWhiteSpace(SetNameSearch)) return true; if (snvm.Name.IndexOf(SetNameSearch, StringComparison.OrdinalIgnoreCase) > -1) return true; else return false; } return false; } if (ShowOnlySetAllowedInStandard) { if (standardOnlySets == null) return false; if (standardOnlySets.Contains(snvm.Name)) { if (string.IsNullOrWhiteSpace(SetNameSearch)) return true; if (snvm.Name.IndexOf(SetNameSearch, StringComparison.OrdinalIgnoreCase) > -1) return true; else return false; } else return false; } else { if (string.IsNullOrWhiteSpace(SetNameSearch)) return true; if (snvm.Name.IndexOf(SetNameSearch, StringComparison.OrdinalIgnoreCase) > -1) return true; else return false; } } private void SetNameSearchTick(object? sender, EventArgs e) { setNameSearchOperation = Dispatcher?.BeginInvoke(() => { SetCollectionView?.Refresh(); }, DispatcherPriority.Normal); } public void VerifyStateOfSmallCheckBoxAndSet() { VerifyStateOfImageTypeCheckBoxAndSet(ImageType.Small); } public void VerifyStateOfNormalCheckBoxAndSet() { VerifyStateOfImageTypeCheckBoxAndSet(ImageType.Normal); } public void VerifyStateOfLargeCheckBoxAndSet() { VerifyStateOfImageTypeCheckBoxAndSet(ImageType.Large); } public void VerifyStateOfPngCheckBoxAndSet() { VerifyStateOfImageTypeCheckBoxAndSet(ImageType.Png); } public void VerifyStateOfArtCropCheckBoxAndSet() { VerifyStateOfImageTypeCheckBoxAndSet(ImageType.ArtCrop); } public void VerifyStateOfBorderCropCheckBoxAndSet() { VerifyStateOfImageTypeCheckBoxAndSet(ImageType.BorderCrop); } private void VerifyStateOfImageTypeCheckBoxAndSet(ImageType imageType) { if (CardCollectionView == null) return; int allCount = CardCollectionView.Count; int ourCount = 0; for (int i = 0; i < allCount; i++) { if (CardCollectionView.GetItemAt(i) is not UniqueArtTypeViewModel uavm) continue; switch (imageType) { case ImageType.Small: if (uavm.DownloadSmallPicture) ourCount++; break; case ImageType.Normal: if (uavm.DownloadNormalPicture) ourCount++; break; case ImageType.Large: if (uavm.DownloadLargePicture) ourCount++; break; case ImageType.Png: if (uavm.DownloadPngPicture) ourCount++; break; case ImageType.ArtCrop: if (uavm.DownloadArtCropPicture) ourCount++; break; case ImageType.BorderCrop: if (uavm.DownloadBorderCropPicture) ourCount++; break; } } switch (imageType) { case ImageType.Small: if (ourCount == 0) IsAllSmallChecked = false; // none = no check else if (ourCount == allCount) IsAllSmallChecked = true; // all = check else IsAllSmallChecked = null; // between 1 and count - 1 set to partial state break; case ImageType.Normal: if (ourCount == 0) IsAllNormalChecked = false; // none = no check else if (ourCount == allCount) IsAllNormalChecked = true; // all = check else IsAllNormalChecked = null; // between 1 and count - 1 set to partial state break; case ImageType.Large: if (ourCount == 0) IsAllLargeChecked = false; // none = no check else if (ourCount == allCount) IsAllLargeChecked = true; // all = check else IsAllLargeChecked = null; // between 1 and count - 1 set to partial state break; case ImageType.Png: if (ourCount == 0) IsAllPngChecked = false; // none = no check else if (ourCount == allCount) IsAllPngChecked = true; // all = check else IsAllPngChecked = null; // between 1 and count - 1 set to partial state break; case ImageType.ArtCrop: if (ourCount == 0) IsAllArtCropChecked = false; // none = no check else if (ourCount == allCount) IsAllArtCropChecked = true; // all = check else IsAllArtCropChecked = null; // between 1 and count - 1 set to partial state break; case ImageType.BorderCrop: if (ourCount == 0) IsAllBorderCropChecked = false; // none = no check else if (ourCount == allCount) IsAllBorderCropChecked = true; // all = check else IsAllBorderCropChecked = null; // between 1 and count - 1 set to partial state break; } } #endregion } }
40.863559
238
0.524275
[ "MIT" ]
AaronAmberman/MagicTheGatheringArenaDeckMaster
MagicTheGatheringArenaDeckMaster/MagicTheGatheringArenaDeckMaster/ViewModels/MainWindowViewModel.cs
48,221
C#
using GenericModConfigMenu.ModOption; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using StardewModdingAPI; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GenericModConfigMenu { internal class ModConfig { public IManifest ModManifest { get; } public Action RevertToDefault { get; } public Action SaveToFile { get; } public List<Action<string, object>> ChangeHandler { get; } public List<BaseModOption> Options { get; } = new List<BaseModOption>(); public ModConfig(IManifest manifest, Action revertToDefault, Action saveToFile ) { ModManifest = manifest; RevertToDefault = revertToDefault; SaveToFile = saveToFile; ChangeHandler = new List<Action<string, object>>(); } } }
30.166667
88
0.683978
[ "MIT" ]
Platonymous/GenericModConfigMenu
ModConfig.cs
907
C#
using System; using System.Collections.Generic; using System.Linq; using CaptureTheFlat.Models; using CaptureTheFlat.Repositories; using Microsoft.AspNetCore.Mvc; namespace CaptureTheFlat.Controllers { [Produces("application/json")] [Route("api/[controller]")] public class PostsController : Controller { private readonly IPostRepository _postRepository; public PostsController(IPostRepository postRepository) { _postRepository = postRepository; } private IEnumerable<Post> Posts => _postRepository.GetAllPosts(); [HttpGet] public OkObjectResult GetAllPosts() { IEnumerable<Post> posts = Posts; return Ok(posts); } [HttpGet("days={days}")] public IActionResult GetByDaysBack(int days) { DateTime minDate = DateTime.Now.AddDays(-days); IEnumerable<Post> postsWithDateBefore = Posts.Where(x => x.PublishDate >= minDate); return Ok(postsWithDateBefore); } } }
26.5
95
0.645283
[ "MIT" ]
wasnlosdu/capture-the-flat
CaptureTheFlat/Controllers/PostsController.cs
1,062
C#
using Algebra; using Algebra.PatternMatching; using Libs; using NUnit.Framework; using System; using System.Collections.Generic; using System.Text; namespace EvaluatorsTests.PatternMatching { class PatternMatchingMonadTests { private static readonly Expression[] arguments = new Expression[] { Expression.VarA, Expression.VarB * 5, 3 * Expression.VarX - 10 }; [Test] public void Matches([Values] MonadBuilder.Monad monad, [ValueSource(nameof(arguments))] Expression argument) { // Arrange Expression expression = MonadBuilder.Build(argument, monad); Expression pattern = MonadBuilder.Build(Expression.VarA, monad); PatternMatchingResultSet expected = new PatternMatchingResultSet(new PatternMatchingResult("a", argument)); // Act PatternMatchingResultSet resultSet = expression.Match(pattern); // Assert Assert.AreEqual(resultSet, expected); } [Test] public void DoesNotMatch([Values] MonadBuilder.Monad monad1, [Values] MonadBuilder.Monad monad2, [ValueSource(nameof(arguments))] Expression argument) { if (monad1 == monad2) { return; } // Arrange Expression expression = MonadBuilder.Build(argument, monad1); Expression pattern = MonadBuilder.Build(Expression.VarA, monad2); PatternMatchingResultSet expected = PatternMatchingResultSet.None; // Act PatternMatchingResultSet resultSet = expression.Match(pattern); // Assert Assert.AreEqual(resultSet, expected); Assert.IsTrue(resultSet.IsNone); } } }
31.631579
158
0.622296
[ "MIT" ]
Joeoc2001/AlgebraSystem
AlgebraSystem.Test/EvaluatorsTests/PatternMatching/PatternMatchingMonadTests.cs
1,805
C#
using System; /* * Now let's see how clearly the material on the methods of the * String object working with regular expressions was described. */ namespace step_5 { class Program { static void Main(string[] args) { Console.WriteLine("The result of the split() method is an array"); Console.WriteLine("The Replace(regex, str) method supports global search"); Console.WriteLine("If you pass a string to the Replace and Search methods instead of a regular expression, it will be converted to a regular expression"); } } }
30.85
167
0.643436
[ "Unlicense" ]
tshemake/Software-Development
stepik/3432/53073/step_5/Program.cs
619
C#
using UnityEditor; using UnityEngine; namespace SuperSystems.UnityBuild { public class UnityBuildGUIUtility { private const string HELP_URL = @"https://github.com/Chaser324/unity-build/wiki/{0}"; #region Singleton private static UnityBuildGUIUtility _instance = null; public static UnityBuildGUIUtility instance { get { if (_instance == null) { _instance = new UnityBuildGUIUtility(); } return _instance; } } #endregion private GUIStyle _dropdownHeaderStyle; private GUIStyle _dropdownContentStyle; private GUIStyle _helpButtonStyle; private GUIStyle _midHeaderStyle; private GUIStyle _popupStyle; private GUIStyle _mainTitleStyle; private GUIStyle _subTitleStyle; private GUIStyle _dragDropArea; private Color32 _defaultBackgroundColor = GUI.backgroundColor; private Color32 _mainHeaderColor = new Color32(180, 180, 255, 255); private GUIContent helpButtonContent; private UnityBuildGUIUtility() { _dropdownHeaderStyle = new GUIStyle(GUI.skin.button); _dropdownHeaderStyle.alignment = TextAnchor.MiddleLeft; _dropdownHeaderStyle.fontStyle = FontStyle.Bold; _dropdownHeaderStyle.margin = new RectOffset(5, 5, 0, 0); _popupStyle = new GUIStyle(EditorStyles.popup); _popupStyle.fontSize = 11; _popupStyle.alignment = TextAnchor.MiddleLeft; _popupStyle.margin = new RectOffset(0, 0, 4, 0); _popupStyle.fixedHeight = 18; _helpButtonStyle = new GUIStyle(_dropdownHeaderStyle); _helpButtonStyle.alignment = TextAnchor.MiddleCenter; _helpButtonStyle.fontStyle = FontStyle.Normal; _helpButtonStyle.margin = new RectOffset(0, 5, 0, 0); _helpButtonStyle.fixedWidth = 30; _midHeaderStyle = new GUIStyle(EditorStyles.helpBox); _midHeaderStyle.fontStyle = FontStyle.Bold; _dropdownContentStyle = new GUIStyle(GUI.skin.textField); _dropdownContentStyle.padding = new RectOffset(5, 5, 5, 5); _dropdownContentStyle.margin = new RectOffset(5, 5, 0, 0); _mainTitleStyle = new GUIStyle(EditorStyles.miniBoldLabel); _mainTitleStyle.fontSize = 18; _mainTitleStyle.fontStyle = FontStyle.Bold; _mainTitleStyle.alignment = TextAnchor.MiddleCenter; _mainTitleStyle.fixedHeight = 35; _mainTitleStyle.normal.textColor = new Color32(255, 55, 85, 255); _subTitleStyle = new GUIStyle(_mainTitleStyle); _subTitleStyle.fontSize = 9; _subTitleStyle.fontStyle = FontStyle.Normal; _subTitleStyle.normal.textColor = new Color32(83, 229, 255, 255); _dragDropArea = new GUIStyle(GUI.skin.box); _dragDropArea.stretchWidth = true; _dragDropArea.alignment = TextAnchor.MiddleCenter; _dragDropArea.normal.textColor = GUI.skin.textField.normal.textColor; helpButtonContent = new GUIContent("?", "Help"); } public static void OpenHelp(string anchor = "") { Application.OpenURL(string.Format(HELP_URL, anchor)); } public static void DropdownHeader(string content, ref bool showDropdown, bool noColor, params GUILayoutOption[] options) { if (!noColor) GUI.backgroundColor = instance._mainHeaderColor; if (GUILayout.Button(content, UnityBuildGUIUtility.dropdownHeaderStyle, options)) { showDropdown = !showDropdown; GUIUtility.keyboardControl = 0; } if (!noColor) GUI.backgroundColor = instance._defaultBackgroundColor; } public static void HelpButton(string anchor = "") { if (GUILayout.Button(_instance.helpButtonContent, UnityBuildGUIUtility.helpButtonStyle)) OpenHelp(anchor); } public static GUIStyle helpButtonStyle { get { return instance._helpButtonStyle; } } public static GUIStyle midHeaderStyle { get { return instance._midHeaderStyle; } } public static GUIStyle dropdownHeaderStyle { get { return instance._dropdownHeaderStyle; } } public static GUIStyle dropdownContentStyle { get { return instance._dropdownContentStyle; } } public static GUIStyle popupStyle { get { return instance._popupStyle; } } public static GUIStyle mainTitleStyle { get { return instance._mainTitleStyle; } } public static GUIStyle subTitleStyle { get { return instance._subTitleStyle; } } public static Color defaultBackgroundColor { get { return instance._defaultBackgroundColor; } } public static Color mainHeaderColor { get { return instance._mainHeaderColor; } } public static GUIStyle dragDropStyle { get { return instance._dragDropArea; } } } }
27.411168
125
0.613519
[ "MIT" ]
TrutzX/9Nations
Assets/Plugins/UnityBuild/Editor/Build/UI/UnityBuildGUIUtility.cs
5,402
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace ss_3d { public class DeathAnimationManager : Singleton<DeathAnimationManager> { DeathAnimationLoader deathAnimationLoader; List<RuntimeAnimatorController> Candidates = new List<RuntimeAnimatorController>(); void SetupDeathAnimationLoader() { if (deathAnimationLoader == null) { GameObject obj = Instantiate(Resources.Load("DeathAnimationLoader", typeof(GameObject)) as GameObject); DeathAnimationLoader loader = obj.GetComponent<DeathAnimationLoader>(); deathAnimationLoader = loader; } } public RuntimeAnimatorController GetAnimator(GeneralBodyPart generalBodyPart, AttackInfo info) { SetupDeathAnimationLoader(); Candidates.Clear(); foreach (DeathAnimationData data in deathAnimationLoader.DeathAnimationDataList) { if (info.deathType == data.deathType) { if(info.deathType != DeathType.NONE) { Candidates.Add(data.Animator); } else if (!info.MustCollide) { Candidates.Add(data.Animator); } else { foreach (GeneralBodyPart part in data.GeneralBodyParts) { if (part == generalBodyPart) { Candidates.Add(data.Animator); break; } } } } } return Candidates[Random.Range(0, Candidates.Count)]; } } }
32.79661
119
0.492506
[ "MIT" ]
Stand1k/3D_Platformer
SS_Platformer_URP/Assets/SS_3D/Managers/DeathAnimationManager.cs
1,937
C#
using System; using UnityEngine; namespace Harmony { /// <summary> /// Contient nombre de méthodes d'extensions pour l'aléatoire. /// </summary> public static class RandomExtensions { /// <summary> /// Retourne une position aléatoire entre les bornes données. Les positions négatives sont supportées. /// </summary> /// <param name="minX">Valeur minimale pour X.</param> /// <param name="maxX">Valeur maximale pour X.</param> /// <param name="minY">Valeur minimale pour Y.</param> /// <param name="maxY">Valeur maximale pour Y.</param> /// <returns>Vecteur aléatoire.</returns> public static Vector2 GetRandomPosition(float minX, float maxX, float minY, float maxY) { return new Vector2(GetRandomFloat(minX, maxX), GetRandomFloat(minY, maxY)); } /// <summary> /// Retourne une position aléatoire sur les bords d'un rectangle donné. /// </summary> /// <param name="center">Centre du rectangle.</param> /// <param name="height">Hauteur du rectangle.</param> /// <param name="width">Largeur du rectangle.</param> /// <returns>Position aléatoire sur l'un des bords du rectangle donné.</returns> /// <exception cref="System.ArgumentException">Si Height ou Width sont négatifs.</exception> public static Vector2 GetRandomPositionOnRectangleEdge(Vector2 center, float height, float width) { if (height < 0) { throw new ArgumentException("Rectangle Height cannot be negative."); } if (width < 0) { throw new ArgumentException("Rectangle Width cannot be negative."); } /* * Imagine a rectangle, like this : * * |---------------1---------------| * | | * | | * | | * 4 3 * | | * | | * | | * |---------------2---------------| * * We can "unfold" it in a line, like this : * * |--------1--------|--------2--------|--------3--------|--------4--------| * * By picking a random position on that line, we pick a random position on the rectangle edges. */ int linePart = Mathf.RoundToInt(GetRandomFloat(0, 1) * 4); float randomPosition = GetRandomFloat(-1, 1); float x = linePart <= 2 ? randomPosition : (linePart == 3 ? 1 : -1); float y = linePart >= 3 ? randomPosition : (linePart == 1 ? 1 : -1); return new Vector2(x * (width / 2), y * (height / 2)) + center; } /// <summary> /// Retourne une direction aléatoire. Le vecteur retournée est normalisé et a donc une longueur de 1. /// </summary> /// <returns>Vecteur représentant une direction aléatoire.</returns> public static Vector2 GetRandomDirection() { return GetRandomPosition(-1, 1, -1, 1).normalized; } /// <summary> /// Retourne 1 ou -1 de manière aléatoire. Il y a 50 % de chance pour chaque option. /// </summary> /// <returns>1 ou -1</returns> public static int GetOneOrMinusOneAtRandom() { return UnityEngine.Random.value > 0.5f ? 1 : -1; } /// <summary> /// Retourne un nombre entier aléatoire entre deux valeurs. /// </summary> /// <param name="min">Valeur minimal. Inclusif.</param> /// <param name="max">Valeur maximale. Inclusif.</param> /// <returns>Nombre aléatoire entre deux valeurs.</returns> /// <exception cref="System.ArgumentException">Si Min est plus grand que Max.</exception> public static uint GetRandomUInt(uint min, uint max) { return (uint) GetRandomFloat(min, max); } /// <summary> /// Retourne un nombre entier aléatoire entre deux valeurs. Les valeurs négatives sont supportées. /// </summary> /// <param name="min">Valeur minimal. Inclusif.</param> /// <param name="max">Valeur maximale. Inclusif.</param> /// <returns>Nombre aléatoire entre deux valeurs.</returns> /// <exception cref="System.ArgumentException">Si Min est plus grand que Max.</exception> public static int GetRandomInt(int min, int max) { return (int) GetRandomFloat(min, max); } /// <summary> /// Retourne un nombre à virgule flotante aléatoire entre deux valeurs. Les valeurs négatives sont supportées. /// </summary> /// <param name="min">Valeur minimal. Inclusif.</param> /// <param name="max">Valeur maximale. Inclusif.</param> /// <returns>Nombre aléatoire entre deux valeurs.</returns> /// <exception cref="System.ArgumentException">Si Min est plus grand que Max.</exception> public static float GetRandomFloat(float min, float max) { if (min > max) { throw new ArgumentException("Minimum value must be smaller or equal to maximum value."); } return UnityEngine.Random.value * (max - min) + min; } } }
43
118
0.523077
[ "MIT" ]
Allcatraz/Nullptr_ProjetSynthese
Assets/Libraries/Harmony/Scripts/Playmode/Util/Extension/RandomExtensions.cs
5,622
C#
namespace JetBrains.ReSharper.Koans.Refactoring { // 从参数中提取类 // // 基于一个方法的参数创建一个类, 并且在所有调用处创建该类 // // 没有快捷键, 执行Refactor This后在弹出菜单中选择 public class ExtractClassFromParameters { // 1. 从参数中提取类 // 将光标放在方法的定义上, 执行Extract Class From Parameters (???) // ReSharper prompts for options - name, class/struct, nested/top level // and which parameters should be extracted public ExtractClassFromParameters(string forename, string surname, int age) { } public static ExtractClassFromParameters Create(string forename, string surname, int age) { // 2. Confirm call site has been updated to create parameter class return new ExtractClassFromParameters(forename, surname, age); } } }
31.461538
97
0.641809
[ "Apache-2.0" ]
yusjoel/resharper-rider-samples-cn
04-Refactoring/Refactoring/16-Extract_class_from_parameters.cs
958
C#
using Semmle.Extraction.Entities; using Semmle.Util; namespace Semmle.Extraction { /// <summary> /// Methods for creating DB tuples. /// </summary> public static class Tuples { public static void containerparent(this System.IO.TextWriter trapFile, Folder parent, IEntity child) { trapFile.WriteTuple("containerparent", parent, child); } internal static void extractor_messages(this System.IO.TextWriter trapFile, ExtractionMessage error, Semmle.Util.Logging.Severity severity, string origin, string errorMessage, string entityText, Location location, string stackTrace) { trapFile.WriteTuple("extractor_messages", error, (int)severity, origin, errorMessage, entityText, location, stackTrace); } public static void files(this System.IO.TextWriter trapFile, File file, string fullName, string name, string extension) { trapFile.WriteTuple("files", file, fullName, name, extension, 0); } internal static void folders(this System.IO.TextWriter trapFile, Folder folder, string path, string name) { trapFile.WriteTuple("folders", folder, path, name); } public static void locations_default(this System.IO.TextWriter trapFile, SourceLocation label, Entities.File file, int startLine, int startCol, int endLine, int endCol) { trapFile.WriteTuple("locations_default", label, file, startLine, startCol, endLine, endCol); } } }
41.243243
240
0.684797
[ "MIT" ]
00mjk/codeql
csharp/extractor/Semmle.Extraction/Tuples.cs
1,526
C#
namespace ThreeDPayment { public class PaymentRequest { public string CardHolderName { get; set; } public string CardNumber { get; set; } public int ExpireMonth { get; set; } public int ExpireYear { get; set; } public string CvvCode { get; set; } public int Installment { get; set; } public decimal TotalAmount { get; set; } public string OrderNumber { get; set; } public string CurrencyIsoCode { get; set; } public string LanguageIsoCode { get; set; } public string CustomerIpAddress { get; set; } } }
35.411765
53
0.612957
[ "Apache-2.0" ]
suatsuphi/3DPaymentAspNetCore
src/ThreeDPayment/PaymentRequest.cs
602
C#
using System; using System.Threading.Tasks; using OmniSharp.Models; namespace NetPad.OmniSharpWrapper { public interface IOmniSharpServer : IDisposable { Task StartAsync(); Task StopAsync(); Task<TResponse> Send<TResponse>(object request) where TResponse : class; } }
21.133333
55
0.675079
[ "MIT" ]
tareqimbasher/NetPad
src/External/NetPad.OmniSharpWrapper/IOmniSharpServer.cs
317
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Internal; namespace System.ComponentModel.Composition { internal class ImportCardinalityMismatchExceptionDebuggerProxy { private readonly ImportCardinalityMismatchException _exception; public ImportCardinalityMismatchExceptionDebuggerProxy(ImportCardinalityMismatchException exception) { Requires.NotNull(exception, nameof(exception)); _exception = exception; } public Exception InnerException { get { return _exception.InnerException; } } public string Message { get { return _exception.Message; } } } }
28.064516
108
0.687356
[ "MIT" ]
939481896/dotnet-corefx
src/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ImportCardinalityMismatchExceptionDebuggerProxy.cs
870
C#
using System.Web; namespace MS.Lib.Utils.Core.Result { /// <summary> /// 文件下载 /// </summary> public class FileDownloadModel { /// <summary> /// 文件完整路径 /// </summary> public string FilePath { get; set; } private string _name; /// <summary> /// 文件名称 /// </summary> public string Name { get => HttpUtility.UrlEncode(_name); set => _name = value; } /// <summary> /// 多媒体类型 /// </summary> public string MediaType { get; set; } public FileDownloadModel(string filePath, string name, string mediaType) { FilePath = filePath; Name = name; MediaType = mediaType ?? ""; } } }
21.026316
80
0.473091
[ "MIT" ]
billowliu2/MS
src/Framework/Utils/Utils.Core/Result/FileDownloadModel.cs
839
C#
/* * Copyright 2020 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 iot-2015-05-28.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.IoT.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.IoT.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for VersionsLimitExceededException Object /// </summary> public class VersionsLimitExceededExceptionUnmarshaller : IErrorResponseUnmarshaller<VersionsLimitExceededException, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public VersionsLimitExceededException Unmarshall(JsonUnmarshallerContext context) { return this.Unmarshall(context, new ErrorResponse()); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <param name="errorResponse"></param> /// <returns></returns> public VersionsLimitExceededException Unmarshall(JsonUnmarshallerContext context, ErrorResponse errorResponse) { context.Read(); VersionsLimitExceededException unmarshalledObject = new VersionsLimitExceededException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { } return unmarshalledObject; } private static VersionsLimitExceededExceptionUnmarshaller _instance = new VersionsLimitExceededExceptionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static VersionsLimitExceededExceptionUnmarshaller Instance { get { return _instance; } } } }
35.4
151
0.67564
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/IoT/Generated/Model/Internal/MarshallTransformations/VersionsLimitExceededExceptionUnmarshaller.cs
3,009
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.OutboundBot.Transform; using Aliyun.Acs.OutboundBot.Transform.V20191226; namespace Aliyun.Acs.OutboundBot.Model.V20191226 { public class DescribeJobGroupRequest : RpcAcsRequest<DescribeJobGroupResponse> { public DescribeJobGroupRequest() : base("OutboundBot", "2019-12-26", "DescribeJobGroup", "outboundbot", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.OutboundBot.Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.OutboundBot.Endpoint.endpointRegionalType, null); } Method = MethodType.POST; } private List<string> briefTypess = new List<string>(){ }; private string instanceId; private string jobGroupId; public List<string> BriefTypess { get { return briefTypess; } set { briefTypess = value; for (int i = 0; i < briefTypess.Count; i++) { DictionaryUtil.Add(QueryParameters,"BriefTypes." + (i + 1) , briefTypess[i]); } } } public string InstanceId { get { return instanceId; } set { instanceId = value; DictionaryUtil.Add(QueryParameters, "InstanceId", value); } } public string JobGroupId { get { return jobGroupId; } set { jobGroupId = value; DictionaryUtil.Add(QueryParameters, "JobGroupId", value); } } public override bool CheckShowJsonItemName() { return false; } public override DescribeJobGroupResponse GetResponse(UnmarshallerContext unmarshallerContext) { return DescribeJobGroupResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
28.242718
141
0.676865
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-outboundbot/OutboundBot/Model/V20191226/DescribeJobGroupRequest.cs
2,909
C#
using AutoMapper; using MediatR; using System; using VotingIrregularities.Domain.Models; namespace VotingIrregularities.Domain.SectieAggregate { public class RegisterPollingStationCommand : IRequest<int> { public int IdObserver { get; set; } public int IdPollingStation { get; set; } public string CountyCode { get; set; } public bool? UrbanArea { get; set; } public DateTime? ObserverLeaveTime { get; set; } public DateTime? ObserverArrivalTime { get; set; } public bool? IsPollingStationPresidentFemale { get; set; } } public class PollingStationProfile : Profile { public PollingStationProfile() { CreateMap<RegisterPollingStationCommand, PollingStationInfo>() .ForMember(dest => dest.LastModified, c => c.MapFrom(src => DateTime.UtcNow)); CreateMap<UpdatePollingSectionCommand, PollingStationInfo>() .ForMember(dest => dest.LastModified, c => c.MapFrom(src => DateTime.UtcNow)); } } }
37.178571
94
0.666667
[ "MPL-2.0" ]
boneacsu/monitorizare-vot
src/api/VotingIrregularities.Domain/SectieAggregate/RegisterPollingSectionCommand.cs
1,043
C#
using Q42.WinRT.Portable; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace Q42.WinRT.Portable.Data { /// <summary> /// Possible loading states for the DataLoader /// </summary> public enum LoadingState { /// <summary>None</summary> None, /// <summary>Loading</summary> Loading, /// <summary>Finished</summary> Finished, /// <summary>Error</summary> Error } /// <summary> /// DataLoader that enables easy binding to Loading / Finished / Error properties /// </summary> public class DataLoader : INotifyPropertyChanged { private LoadingState _loadingState; private bool _swallowExceptions; /// <summary> /// Current loading state /// </summary> public LoadingState LoadingState { get { return _loadingState; } set { _loadingState = value; RaisePropertyChanged(); RaisePropertyChanged(() => IsBusy); RaisePropertyChanged(() => IsError); RaisePropertyChanged(() => IsFinished); } } /// <summary> /// Indicates LoadingState == LoadingState.Error /// </summary> public bool IsError { get { if (LoadingState == LoadingState.Error) return true; return false; } } /// <summary> /// Indicates LoadingState == LoadingState.Loading /// </summary> public bool IsBusy { get { if (LoadingState == LoadingState.Loading) return true; return false; } } /// <summary> /// Indicates LoadingState == LoadingState.Finished /// </summary> public bool IsFinished { get { if (LoadingState == LoadingState.Finished) return true; return false; } } /// <summary> /// DataLoader constructors /// </summary> /// <param name="swallowExceptions">Swallows exceptions. Defaults to true. It's a more common scenario to swallow exceptions and just bind to the IsError property. You don't want to surround each DataLoader with a try/catch block. You can listen to the error callback at all times to get the error.</param> public DataLoader(bool swallowExceptions = true) { _swallowExceptions = swallowExceptions; } /// <summary> /// Load data. Errors will be in errorcallback /// </summary> /// <typeparam name="T"></typeparam> /// <param name="loadingMethod"></param> /// <param name="resultCallback"></param> /// <param name="errorCallback">optional error callback. Fires when exceptino is thrown in loadingMethod</param> /// <returns></returns> public async Task<T> LoadAsync<T>(Func<Task<T>> loadingMethod, Action<T> resultCallback = null, Action<Exception> errorCallback = null) { //Set loading state LoadingState = Data.LoadingState.Loading; T result = default(T); try { result = await loadingMethod(); //Set finished state LoadingState = Data.LoadingState.Finished; if (resultCallback != null) resultCallback(result); } catch (Exception e) { //Set error state LoadingState = Data.LoadingState.Error; if (errorCallback != null) errorCallback(e); else if (!_swallowExceptions) //swallow exception if _swallowExceptions is true throw; //throw error if no callback is defined } return result; } /// <summary> /// First returns result callback with result from cache, then from refresh method /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cacheLoadingMethod"></param> /// <param name="refreshLoadingMethod"></param> /// <param name="resultCallback"></param> /// <param name="errorCallback"></param> /// <returns></returns> public async Task LoadCacheThenRefreshAsync<T>(Func<Task<T>> cacheLoadingMethod, Func<Task<T>> refreshLoadingMethod, Action<T> resultCallback = null, Action<Exception> errorCallback = null) { //Set loading state LoadingState = Data.LoadingState.Loading; T cacheResult = default(T); T refreshResult = default(T); try { cacheResult = await cacheLoadingMethod(); if (resultCallback != null) resultCallback(cacheResult); refreshResult = await refreshLoadingMethod(); if (resultCallback != null) resultCallback(refreshResult); //Set finished state LoadingState = Data.LoadingState.Finished; } catch (Exception e) { //Set error state LoadingState = Data.LoadingState.Error; if (errorCallback != null) errorCallback(e); else if (!_swallowExceptions) //swallow exception if catchexception is true throw; //throw error if no callback is defined } } /// <summary> /// Loads data from source A, if this fails, load it from source B (cache) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="refreshLoadingMethod"></param> /// <param name="cacheLoadingMethod"></param> /// <param name="resultCallback"></param> /// <param name="errorCallback"></param> /// <returns></returns> public async Task LoadFallbackToCacheAsync<T>(Func<Task<T>> refreshLoadingMethod, Func<Task<T>> cacheLoadingMethod, Action<T> resultCallback = null, Action<Exception> errorCallback = null) { //Set loading state LoadingState = Data.LoadingState.Loading; T refreshResult = default(T); T cacheResult = default(T); bool refreshSourceFail = false; try { refreshResult = await refreshLoadingMethod(); if (resultCallback != null) resultCallback(refreshResult); //Set finished state LoadingState = Data.LoadingState.Finished; } catch (Exception e) { refreshSourceFail = true; if (errorCallback != null) errorCallback(e); } //Did the loading fail? Load data from source B (cache) if (refreshSourceFail) { try { cacheResult = await cacheLoadingMethod(); if (resultCallback != null) resultCallback(cacheResult); //Set finished state LoadingState = Data.LoadingState.Finished; } catch (Exception e) { //Set error state LoadingState = Data.LoadingState.Error; if (errorCallback != null) errorCallback(e); } } } /// <summary> /// PropertyChanged for INotifyPropertyChanged implementation /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// RaisePropertyChanged for INotifyPropertyChanged implementation /// </summary> /// <param name="propertyName"></param> protected void RaisePropertyChanged([CallerMemberName] string propertyName = null) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } /// <summary> /// RaisePropertyChanged for INotifyPropertyChanged implementation /// </summary> /// <param name="expression"></param> protected void RaisePropertyChanged(Expression<Func<object>> expression) { RaisePropertyChanged(Util.GetPropertyName(expression)); } } }
31.327465
314
0.531527
[ "MIT" ]
Q42/Q42.WinRT
Q42.WinRT.Portable/Data/DataLoader.cs
8,899
C#
using System; using System.Text; #pragma warning disable 0649 namespace UnhollowerMini { internal class Il2CppException : Exception { [ThreadStatic] private static byte[] ourMessageBytes; public static Func<IntPtr, string> ParseMessageHook; public Il2CppException(IntPtr exception) : base(BuildMessage(exception)) { } private static unsafe string BuildMessage(IntPtr exception) { if (ParseMessageHook != null) return ParseMessageHook(exception); if (ourMessageBytes == null) ourMessageBytes = new byte[65536]; fixed (byte* message = ourMessageBytes) UnityInternals.format_exception(exception, message, ourMessageBytes.Length); string builtMessage = Encoding.UTF8.GetString(ourMessageBytes, 0, Array.IndexOf(ourMessageBytes, (byte)0)); fixed (byte* message = ourMessageBytes) UnityInternals.format_stack_trace(exception, message, ourMessageBytes.Length); builtMessage += "\n" + Encoding.UTF8.GetString(ourMessageBytes, 0, Array.IndexOf(ourMessageBytes, (byte)0)); return builtMessage; } public static void RaiseExceptionIfNecessary(IntPtr returnedException) { if (returnedException == IntPtr.Zero) return; throw new Il2CppException(returnedException); } } }
38.972222
119
0.667142
[ "Apache-2.0" ]
BigscreenModded/MelonLoader
MelonStartScreen/UnhollowerMini/Il2CppException.cs
1,405
C#
namespace Funccy { public static class CatchExtensions { public static CatchBuilder<TObj> AsCatch<TObj>(this TObj obj) => new CatchBuilder<TObj>(obj); } }
20.888889
72
0.632979
[ "MIT" ]
chriswxyz/funccy
src/Funccy/Catch/CatchExtensions.cs
190
C#
/* * Copyright (c) 2015 Jeff Lindberg * * 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; namespace Clouseau { public class StationFailedException : Exception { public StationFailedException(string s) : base(s) { } } }
37.485714
81
0.733232
[ "MIT" ]
jblindberg/Clouseau
Clouseau/StationFailedException.cs
1,312
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace ConDep.Samples.WebApi.Results { public class ChallengeResult : IHttpActionResult { public ChallengeResult(string loginProvider, ApiController controller) { LoginProvider = loginProvider; Request = controller.Request; } public string LoginProvider { get; set; } public HttpRequestMessage Request { get; set; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { Request.GetOwinContext().Authentication.Challenge(LoginProvider); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized); response.RequestMessage = Request; return Task.FromResult(response); } } }
29.333333
96
0.695248
[ "BSD-2-Clause" ]
condep/condep-samples
src/ConDep.Samples.WebApi/Results/ChallengeResult.cs
970
C#
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2016 Hotcakes Commerce, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #endregion namespace Hotcakes.Commerce.BusinessRules { public class NullTask : Task { public override string TaskName() { return "Null Task"; } public override bool Execute(TaskContext context) { return false; } public override bool Rollback(TaskContext context) { return true; } public override string TaskId() { return string.Empty; } public override Task Clone() { var result = new NullTask(); return result; } } }
33.5
101
0.649787
[ "MIT" ]
ketangarala/core
Libraries/Hotcakes.Commerce/BusinessRules/NullTask.cs
1,876
C#
using System; using System.Collections.Generic; using System.Text; using SingularityLathe.Forge.StellarForge.Services; namespace SingularityLathe.Forge.StellarForge { public class StellarForgeService { private readonly StarSystemBuilderService starSystemBuilderService = null; public StellarForgeService(StarSystemBuilderService starSystemBuilderService) { this.starSystemBuilderService = starSystemBuilderService; } } }
26.666667
85
0.760417
[ "MIT" ]
herrozerro/singularity-lathe
src/SingularityLathe.Forge/StellarForge/StellarForge.cs
482
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; namespace Lesson6 { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseMvc(); //app.UseMvc(routes => //{ // routes.MapRoute(name: "FirstRoute", // template: "Home", defaults: new // { // controller = "Home", // action = "Index2" // }); // routes.MapRoute(name: "default", // template: "{controller=Employee}/{action=Index}/{id?}"); //}); } } }
32.170732
122
0.593632
[ "MIT" ]
TrainingByPackt/Beginning-ASP.Net
Lesson6/Activity C-1/Lesson6/Startup.cs
1,321
C#
using System; using NUnit.Framework; using Python.Runtime; namespace Python.EmbeddingTest { public class PyScopeTest { private PyScope ps; [SetUp] public void SetUp() { using (Py.GIL()) { ps = Py.CreateScope("test"); } } [TearDown] public void Dispose() { using (Py.GIL()) { ps.Dispose(); ps = null; } } /// <summary> /// Eval a Python expression and obtain its return value. /// </summary> [Test] public void TestEval() { using (Py.GIL()) { ps.Set("a", 1); var result = ps.Eval<int>("a + 2"); Assert.AreEqual(3, result); } } /// <summary> /// Exec Python statements and obtain the variables created. /// </summary> [Test] public void TestExec() { using (Py.GIL()) { ps.Set("bb", 100); //declare a global variable ps.Set("cc", 10); //declare a local variable ps.Exec("aa = bb + cc + 3"); var result = ps.Get<int>("aa"); Assert.AreEqual(113, result); } } /// <summary> /// Compile an expression into an ast object; /// Execute the ast and obtain its return value. /// </summary> [Test] public void TestCompileExpression() { using (Py.GIL()) { ps.Set("bb", 100); //declare a global variable ps.Set("cc", 10); //declare a local variable PyObject script = PythonEngine.Compile("bb + cc + 3", "", RunFlagType.Eval); var result = ps.Execute<int>(script); Assert.AreEqual(113, result); } } /// <summary> /// Compile Python statements into an ast object; /// Execute the ast; /// Obtain the local variables created. /// </summary> [Test] public void TestCompileStatements() { using (Py.GIL()) { ps.Set("bb", 100); //declare a global variable ps.Set("cc", 10); //declare a local variable PyObject script = PythonEngine.Compile("aa = bb + cc + 3", "", RunFlagType.File); ps.Execute(script); var result = ps.Get<int>("aa"); Assert.AreEqual(113, result); } } /// <summary> /// Create a function in the scope, then the function can read variables in the scope. /// It cannot write the variables unless it uses the 'global' keyword. /// </summary> [Test] public void TestScopeFunction() { using (Py.GIL()) { ps.Set("bb", 100); ps.Set("cc", 10); ps.Exec( "def func1():\n" + " bb = cc + 10\n"); dynamic func1 = ps.Get("func1"); func1(); //call the function, it can be called any times var result = ps.Get<int>("bb"); Assert.AreEqual(100, result); ps.Set("bb", 100); ps.Set("cc", 10); ps.Exec( "def func2():\n" + " global bb\n" + " bb = cc + 10\n"); dynamic func2 = ps.Get("func2"); func2(); result = ps.Get<int>("bb"); Assert.AreEqual(20, result); } } /// <summary> /// Create a class in the scope, the class can read variables in the scope. /// Its methods can write the variables with the help of 'global' keyword. /// </summary> [Test] public void TestScopeClass() { using (Py.GIL()) { dynamic _ps = ps; _ps.bb = 100; ps.Exec( "class Class1():\n" + " def __init__(self, value):\n" + " self.value = value\n" + " def call(self, arg):\n" + " return self.value + bb + arg\n" + //use scope variables " def update(self, arg):\n" + " global bb\n" + " bb = self.value + arg\n" //update scope variable ); dynamic obj1 = _ps.Class1(20); var result = obj1.call(10).As<int>(); Assert.AreEqual(130, result); obj1.update(10); result = ps.Get<int>("bb"); Assert.AreEqual(30, result); } } /// <summary> /// Import a python module into the session. /// Equivalent to the Python "import" statement. /// </summary> [Test] public void TestImportModule() { using (Py.GIL()) { dynamic sys = ps.Import("sys"); Assert.IsTrue(ps.Contains("sys")); ps.Exec("sys.attr1 = 2"); var value1 = ps.Eval<int>("sys.attr1"); var value2 = sys.attr1.As<int>(); Assert.AreEqual(2, value1); Assert.AreEqual(2, value2); //import as ps.Import("sys", "sys1"); Assert.IsTrue(ps.Contains("sys1")); } } /// <summary> /// Create a scope and import variables from a scope, /// exec Python statements in the scope then discard it. /// </summary> [Test] public void TestImportScope() { using (Py.GIL()) { ps.Set("bb", 100); ps.Set("cc", 10); using (var scope = Py.CreateScope()) { scope.Import(ps, "ps"); scope.Exec("aa = ps.bb + ps.cc + 3"); var result = scope.Get<int>("aa"); Assert.AreEqual(113, result); } Assert.IsFalse(ps.Contains("aa")); } } /// <summary> /// Create a scope and import variables from a scope, /// exec Python statements in the scope then discard it. /// </summary> [Test] public void TestImportAllFromScope() { using (Py.GIL()) { ps.Set("bb", 100); ps.Set("cc", 10); using (var scope = ps.NewScope()) { scope.Exec("aa = bb + cc + 3"); var result = scope.Get<int>("aa"); Assert.AreEqual(113, result); } Assert.IsFalse(ps.Contains("aa")); } } /// <summary> /// Create a scope and import variables from a scope, /// call the function imported. /// </summary> [Test] public void TestImportScopeFunction() { using (Py.GIL()) { ps.Set("bb", 100); ps.Set("cc", 10); ps.Exec( "def func1():\n" + " return cc + bb\n"); using (PyScope scope = ps.NewScope()) { //'func1' is imported from the origion scope scope.Exec( "def func2():\n" + " return func1() - cc - bb\n"); dynamic func2 = scope.Get("func2"); var result1 = func2().As<int>(); Assert.AreEqual(0, result1); scope.Set("cc", 20);//it has no effect on the globals of 'func1' var result2 = func2().As<int>(); Assert.AreEqual(-10, result2); scope.Set("cc", 10); //rollback ps.Set("cc", 20); var result3 = func2().As<int>(); Assert.AreEqual(10, result3); ps.Set("cc", 10); //rollback } } } /// <summary> /// Import a python module into the session with a new name. /// Equivalent to the Python "import .. as .." statement. /// </summary> [Test] public void TestImportScopeByName() { using (Py.GIL()) { ps.Set("bb", 100); using (var scope = Py.CreateScope()) { scope.ImportAll("test"); //scope.ImportModule("test"); Assert.IsTrue(scope.Contains("bb")); } } } /// <summary> /// Use the locals() and globals() method just like in python module /// </summary> [Test] public void TestVariables() { (ps.Variables() as dynamic)["ee"] = new PyInt(200); var a0 = ps.Get<int>("ee"); Assert.AreEqual(200, a0); ps.Exec("locals()['ee'] = 210"); var a1 = ps.Get<int>("ee"); Assert.AreEqual(210, a1); ps.Exec("globals()['ee'] = 220"); var a2 = ps.Get<int>("ee"); Assert.AreEqual(220, a2); using (var item = ps.Variables()) { item["ee"] = new PyInt(230); } var a3 = ps.Get<int>("ee"); Assert.AreEqual(230, a3); } /// <summary> /// Share a pyscope by multiple threads. /// </summary> [Test] public void TestThread() { //After the proposal here https://github.com/pythonnet/pythonnet/pull/419 complished, //the BeginAllowThreads statement blow and the last EndAllowThreads statement //should be removed. dynamic _ps = ps; var ts = PythonEngine.BeginAllowThreads(); using (Py.GIL()) { _ps.res = 0; _ps.bb = 100; _ps.th_cnt = 0; //add function to the scope //can be call many times, more efficient than ast ps.Exec( "def update():\n" + " global res, th_cnt\n" + " res += bb + 1\n" + " th_cnt += 1\n" ); } int th_cnt = 3; for (int i =0; i< th_cnt; i++) { System.Threading.Thread th = new System.Threading.Thread(()=> { using (Py.GIL()) { //ps.GetVariable<dynamic>("update")(); //call the scope function dynamicly _ps.update(); } }); th.Start(); } //equivalent to Thread.Join, make the main thread join the GIL competition int cnt = 0; while(cnt != th_cnt) { using (Py.GIL()) { cnt = ps.Get<int>("th_cnt"); } System.Threading.Thread.Sleep(10); } using (Py.GIL()) { var result = ps.Get<int>("res"); Assert.AreEqual(101* th_cnt, result); } PythonEngine.EndAllowThreads(ts); } } }
31.747989
98
0.407448
[ "MIT" ]
GSPP/pythonnet
src/embed_tests/TestPyScope.cs
11,842
C#
// This code is distributed under MIT license. // Copyright (c) 2015 George Mamaladze // See license.txt or http://opensource.org/licenses/mit-license.php using System; namespace xClient.Core.MouseKeyHook.HotKeys { /// <summary> /// The event arguments passed when a HotKeySet's OnHotKeysDownHold event is triggered. /// </summary> public sealed class HotKeyArgs : EventArgs { private readonly DateTime m_TimeOfExecution; /// <summary> /// Creates an instance of the HotKeyArgs. /// <param name="triggeredAt">Time when the event was triggered</param> /// </summary> public HotKeyArgs(DateTime triggeredAt) { m_TimeOfExecution = triggeredAt; } /// <summary> /// Time when the event was triggered /// </summary> public DateTime Time { get { return m_TimeOfExecution; } } } }
28.909091
95
0.604822
[ "MIT" ]
AliBawazeEer/QuasarRAT
Client/Core/MouseKeyHook/HotKeys/HotKeyArgs.cs
956
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/d3d10effect.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using TerraFX.Interop.Windows; namespace TerraFX.Interop.DirectX; /// <include file='ID3D10EffectPool.xml' path='doc/member[@name="ID3D10EffectPool"]/*' /> [NativeTypeName("struct ID3D10EffectPool : IUnknown")] [NativeInheritance("IUnknown")] public unsafe partial struct ID3D10EffectPool : ID3D10EffectPool.Interface { public void** lpVtbl; /// <inheritdoc cref="IUnknown.QueryInterface" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(0)] public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) { return ((delegate* unmanaged<ID3D10EffectPool*, Guid*, void**, int>)(lpVtbl[0]))((ID3D10EffectPool*)Unsafe.AsPointer(ref this), riid, ppvObject); } /// <inheritdoc cref="IUnknown.AddRef" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(1)] [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* unmanaged<ID3D10EffectPool*, uint>)(lpVtbl[1]))((ID3D10EffectPool*)Unsafe.AsPointer(ref this)); } /// <inheritdoc cref="IUnknown.Release" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(2)] [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* unmanaged<ID3D10EffectPool*, uint>)(lpVtbl[2]))((ID3D10EffectPool*)Unsafe.AsPointer(ref this)); } /// <include file='ID3D10EffectPool.xml' path='doc/member[@name="ID3D10EffectPool.AsEffect"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(3)] public ID3D10Effect* AsEffect() { return ((delegate* unmanaged<ID3D10EffectPool*, ID3D10Effect*>)(lpVtbl[3]))((ID3D10EffectPool*)Unsafe.AsPointer(ref this)); } public interface Interface : IUnknown.Interface { [VtblIndex(3)] ID3D10Effect* AsEffect(); } public partial struct Vtbl<TSelf> where TSelf : unmanaged, Interface { [NativeTypeName("HRESULT (const IID &, void **) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, Guid*, void**, int> QueryInterface; [NativeTypeName("ULONG () __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, uint> AddRef; [NativeTypeName("ULONG () __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, uint> Release; [NativeTypeName("ID3D10Effect *() __attribute__((nothrow)) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, ID3D10Effect*> AsEffect; } }
38.213333
153
0.692254
[ "MIT" ]
reflectronic/terrafx.interop.windows
sources/Interop/Windows/DirectX/um/d3d10effect/ID3D10EffectPool.cs
2,868
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Sternzeit.Server.Models { public class FidoResponse { public string AttestationObject { get; set; } public string ClientDataJson { get; set; } public string AuthenticatorData { get; set; } public string Signature { get; set; } public string UserHandle { get; set; } } }
25.352941
53
0.672854
[ "MIT" ]
DerHulk/Sternzeit
src/Sternzeit.Server/Models/FidoResponse.cs
433
C#
/* * Apteco API * * An API to allow access to Apteco Marketing Suite resources * * OpenAPI spec version: v2 * Contact: support@apteco.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using SwaggerDateConverter = Apteco.ApiDataAggregator.ApiClient.Client.SwaggerDateConverter; namespace Apteco.ApiDataAggregator.ApiClient.Model { /// <summary> /// TimeRule /// </summary> [DataContract] public partial class TimeRule : IEquatable<TimeRule> { /// <summary> /// Initializes a new instance of the <see cref="TimeRule" /> class. /// </summary> /// <param name="RangeLow">RangeLow.</param> /// <param name="RangeHigh">RangeHigh.</param> public TimeRule(string RangeLow = default(string), string RangeHigh = default(string)) { this.RangeLow = RangeLow; this.RangeHigh = RangeHigh; } /// <summary> /// Gets or Sets RangeLow /// </summary> [DataMember(Name="rangeLow", EmitDefaultValue=false)] public string RangeLow { get; set; } /// <summary> /// Gets or Sets RangeHigh /// </summary> [DataMember(Name="rangeHigh", EmitDefaultValue=false)] public string RangeHigh { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class TimeRule {\n"); sb.Append(" RangeLow: ").Append(RangeLow).Append("\n"); sb.Append(" RangeHigh: ").Append(RangeHigh).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as TimeRule); } /// <summary> /// Returns true if TimeRule instances are equal /// </summary> /// <param name="input">Instance of TimeRule to be compared</param> /// <returns>Boolean</returns> public bool Equals(TimeRule input) { if (input == null) return false; return ( this.RangeLow == input.RangeLow || (this.RangeLow != null && this.RangeLow.Equals(input.RangeLow)) ) && ( this.RangeHigh == input.RangeHigh || (this.RangeHigh != null && this.RangeHigh.Equals(input.RangeHigh)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.RangeLow != null) hashCode = hashCode * 59 + this.RangeLow.GetHashCode(); if (this.RangeHigh != null) hashCode = hashCode * 59 + this.RangeHigh.GetHashCode(); return hashCode; } } } }
31.426357
94
0.545634
[ "Apache-2.0" ]
Apteco/ApiDataAggregator
Apteco.ApiDataAggregator.ApiClient/Model/TimeRule.cs
4,054
C#
using System; using AzureStorage.Tables.Templates.Index; namespace Lykke.AzureStorage.Tables { public static class AzureIndexExtensions { internal static Tuple<string, string> ToTuple(this IAzureIndex src) { return Tuple.Create(src.PrimaryPartitionKey, src.PrimaryRowKey); } } }
23.5
76
0.693009
[ "MIT" ]
LykkeBusinessPlatform/AzureStorage
src/Lykke.AzureStorage/Tables/AzureIndexExtensions.cs
331
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using VRGIN.Controls; using VRGIN.Core; using VRGIN.Helpers; using VRGIN.Modes; namespace WPVR { class GenericStandingMode : StandingMode { protected override IEnumerable<IShortcut> CreateShortcuts() { return base.CreateShortcuts().Concat(new IShortcut[] { new MultiKeyboardShortcut(new KeyStroke("Ctrl+C"), new KeyStroke("Ctrl+C"), () => { VR.Manager.SetMode<GenericSeatedMode>(); }) }); } } }
25.363636
143
0.66129
[ "MIT" ]
hakatashi/WPVR
WPVR/GenericStandingMode.cs
558
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Charlotte { /// <summary> /// Confused by ConfuserElsa /// </summary> public class DocumentInvalidKaleScreen { /// <summary> /// Confused by ConfuserElsa /// </summary> public int BuildAccessibleSycoraxUsername() { return EncodeUnusedCeresTemplate() == 1 ? 1 : DefaultVisibleDubniumTag; } /// <summary> /// Confused by ConfuserElsa /// </summary> public int IncludeStandaloneNeonColumn() { return AccessDuplicateSkathiPath; } /// <summary> /// Confused by ConfuserElsa /// </summary> public int RenameDeprecatedIapetusLabel() { return ReplaceEmptySpondeLayer() != 1 ? 0 : FailAlternativeDioneAccessibility; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static void LimitFreePapayaProblem() { foreach (MergeCompleteHelikeServer RetrieveMissingPlutoForm in CountCustomMabCommand) RetrieveMissingPlutoForm.CollapseUnauthorizedPanApplication(); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int GetInvalidWhipSize; /// <summary> /// Confused by ConfuserElsa /// </summary> public static int RegisterSpecificTarqeqHeader; /// <summary> /// Confused by ConfuserElsa /// </summary> public class EncodeExternalTitaniaProfile { public int BrowsePublicPassionPool; public int AddMinorVanadiumDocument; public int CloneAbstractNamakaMigration; } /// <summary> /// Confused by ConfuserElsa /// </summary> public int MonitorNativeSunsetTransition() { return LabelCompleteLawrenciumResource() == 0 ? 1 : DescribeFreeNileActivity; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static List<MergeCompleteHelikeServer> CountCustomMabCommand = new List<MergeCompleteHelikeServer>(); /// <summary> /// Confused by ConfuserElsa /// </summary> public void ClarifyNullRadonCore() { this.TypePrivateSparkleRemoval(this.ApplyVerboseCarpoDriver()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public void AdjustRawSpondeEvent(int RequireIncompatibleAluminiumWarning, int IncrementLocalPriestessLogic, int CompareEqualEuropiumNumber, int CalculateVirtualPeachPane, int ImportNestedSunshineStatement, int ShowMatchingEarlLevel) { var CreateVerboseProsperoHash = new[] { new { SplitDecimalSparkleMetadata = RequireIncompatibleAluminiumWarning, SearchPublicGadoliniumCoordinate = CalculateVirtualPeachPane }, new { SplitDecimalSparkleMetadata = IncrementLocalPriestessLogic, SearchPublicGadoliniumCoordinate = CalculateVirtualPeachPane }, new { SplitDecimalSparkleMetadata = CompareEqualEuropiumNumber, SearchPublicGadoliniumCoordinate = CalculateVirtualPeachPane }, }; this.CheckCorrectOxygenSetting(new EncodeExternalTitaniaProfile() { BrowsePublicPassionPool = RequireIncompatibleAluminiumWarning, AddMinorVanadiumDocument = IncrementLocalPriestessLogic, CloneAbstractNamakaMigration = CompareEqualEuropiumNumber, }); if (CreateVerboseProsperoHash[0].SplitDecimalSparkleMetadata == CalculateVirtualPeachPane) this.DestroyBinarySurturSetting(CreateVerboseProsperoHash[0].SearchPublicGadoliniumCoordinate); if (CreateVerboseProsperoHash[1].SplitDecimalSparkleMetadata == ImportNestedSunshineStatement) this.DestroyBinarySurturSetting(CreateVerboseProsperoHash[1].SearchPublicGadoliniumCoordinate); if (CreateVerboseProsperoHash[2].SplitDecimalSparkleMetadata == ShowMatchingEarlLevel) this.DestroyBinarySurturSetting(CreateVerboseProsperoHash[2].SearchPublicGadoliniumCoordinate); } /// <summary> /// Confused by ConfuserElsa /// </summary> public int ApplyVerboseCarpoDriver() { return DistributeUnnecessaryAquaStep++; } /// <summary> /// Confused by ConfuserElsa /// </summary> public int StoreManualAoedeAccessibility() { return StoreEmptyHelenePriority() == 1 ? 0 : ExportAvailableEtoileCloud; } /// <summary> /// Confused by ConfuserElsa /// </summary> public EncodeExternalTitaniaProfile FetchGenericIronCompatibility() { return DecodeExpectedMarsAvailability; } /// <summary> /// Confused by ConfuserElsa /// </summary> public int EncodeUnusedCeresTemplate() { return StoreManualAoedeAccessibility() == 0 ? 1 : RegisterSpecificTarqeqHeader; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int FailAlternativeDioneAccessibility; /// <summary> /// Confused by ConfuserElsa /// </summary> public void TypePrivateSparkleRemoval(int RequireIncompatibleAluminiumWarning) { this.CorrectUnavailableBeatCache(RequireIncompatibleAluminiumWarning, this.ApplyVerboseCarpoDriver()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int EncounterMultipleJarnsaxaFolder; /// <summary> /// Confused by ConfuserElsa /// </summary> public int ReplaceEmptySpondeLayer() { return IncludeStandaloneNeonColumn() != 0 ? 0 : MapInvalidMethoneCoordinate; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int DescribeFreeNileActivity; /// <summary> /// Confused by ConfuserElsa /// </summary> public static int MapInvalidMethoneCoordinate; /// <summary> /// Confused by ConfuserElsa /// </summary> public int ScanSecureMoscoviumTimestamp() { return PullGenericEtoileRoute() == 0 ? 1 : DescribeMockCopperImport; } /// <summary> /// Confused by ConfuserElsa /// </summary> public int ConvertUnavailableKryptonBlock() { return DistributeUnnecessaryAquaStep; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int DescribeMockCopperImport; /// <summary> /// Confused by ConfuserElsa /// </summary> public static int AccessDuplicateSkathiPath; /// <summary> /// Confused by ConfuserElsa /// </summary> public void DestroyBinarySurturSetting(int ActivateRedundantLogePersistence) { if (ActivateRedundantLogePersistence != this.ConvertUnavailableKryptonBlock()) this.ReturnDynamicTarvosInformation(ActivateRedundantLogePersistence); else this.TypePrivateSparkleRemoval(ActivateRedundantLogePersistence); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int DefaultVisibleDubniumTag; /// <summary> /// Confused by ConfuserElsa /// </summary> public int StoreEmptyHelenePriority() { return CastNestedEuropiumSchema() == 1 ? 1 : EncounterMultipleJarnsaxaFolder; } /// <summary> /// Confused by ConfuserElsa /// </summary> public void UpdateInvalidNitrogenDeclaration() { this.ReturnDynamicTarvosInformation(0); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int ExportAvailableEtoileCloud; /// <summary> /// Confused by ConfuserElsa /// </summary> public void CheckCorrectOxygenSetting(EncodeExternalTitaniaProfile FireUnavailableLutetiumConfiguration) { DecodeExpectedMarsAvailability = FireUnavailableLutetiumConfiguration; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int InstallNumericCopperQueue; /// <summary> /// Confused by ConfuserElsa /// </summary> public static int DistributeUnnecessaryAquaStep; /// <summary> /// Confused by ConfuserElsa /// </summary> public static int MergeMissingNaiadSize; /// <summary> /// Confused by ConfuserElsa /// </summary> public void PrintExpressMacherieWidth(int RequireIncompatibleAluminiumWarning, int IncrementLocalPriestessLogic, int CompareEqualEuropiumNumber) { this.AdjustRawSpondeEvent(RequireIncompatibleAluminiumWarning, IncrementLocalPriestessLogic, CompareEqualEuropiumNumber, this.FetchGenericIronCompatibility().BrowsePublicPassionPool, this.FetchGenericIronCompatibility().AddMinorVanadiumDocument, this.FetchGenericIronCompatibility().CloneAbstractNamakaMigration); } /// <summary> /// Confused by ConfuserElsa /// </summary> public void CorrectUnavailableBeatCache(int RequireIncompatibleAluminiumWarning, int IncrementLocalPriestessLogic) { this.PrintExpressMacherieWidth(RequireIncompatibleAluminiumWarning, IncrementLocalPriestessLogic, this.ApplyVerboseCarpoDriver()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int ExecuteMinimumCharonPassword; /// <summary> /// Confused by ConfuserElsa /// </summary> public void ReturnDynamicTarvosInformation(int CopyOpenThebeAsset) { DistributeUnnecessaryAquaStep = CopyOpenThebeAsset; } /// <summary> /// Confused by ConfuserElsa /// </summary> public int UninstallStandaloneHermippeInitialization() { return MonitorNativeSunsetTransition() + ExecuteMinimumCharonPassword; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int ReplaceUniqueMercuryDatabase; /// <summary> /// Confused by ConfuserElsa /// </summary> public static void Add(MergeCompleteHelikeServer RetrieveMissingPlutoForm) { CountCustomMabCommand.Add(RetrieveMissingPlutoForm); } /// <summary> /// Confused by ConfuserElsa /// </summary> public int PullGenericEtoileRoute() { return UninstallStandaloneHermippeInitialization() - InstallNumericCopperQueue; } /// <summary> /// Confused by ConfuserElsa /// </summary> public int CastNestedEuropiumSchema() { return RenameDeprecatedIapetusLabel() == 0 ? 1 : GetInvalidWhipSize; } /// <summary> /// Confused by ConfuserElsa /// </summary> public int TweakAbstractMilkyEnumeration() { return BuildAccessibleSycoraxUsername() != 0 ? 0 : ReplaceUniqueMercuryDatabase; } /// <summary> /// Confused by ConfuserElsa /// </summary> public int LabelCompleteLawrenciumResource() { return TweakAbstractMilkyEnumeration() == 0 ? 0 : MergeMissingNaiadSize; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static EncodeExternalTitaniaProfile DecodeExpectedMarsAvailability; } }
27.692308
316
0.739286
[ "MIT" ]
soleil-taruto/Hatena
a20201226/Confused_03/tmpsol/Elsa20200001/SerializeDecimalLithiumCallback.cs
10,082
C#
using System; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; namespace Knapcode.ExplorePackages.Entities { public class TestSqliteEntityContext : SqliteEntityContext { private readonly SqliteEntityContext _inner; private readonly Func<Task> _executeBeforeCommitAsync; public TestSqliteEntityContext( SqliteEntityContext inner, DbContextOptions<SqliteEntityContext> options, Func<Task> executeBeforeCommitAsync) : base( NullCommitCondition.Instance, options) { _inner = inner; _executeBeforeCommitAsync = executeBeforeCommitAsync; } public override DatabaseFacade Database => _inner.Database; public override void Dispose() { _inner.Dispose(); base.Dispose(); } public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken)) { await _executeBeforeCommitAsync(); return await base.SaveChangesAsync(cancellationToken); } } }
29.878049
122
0.668571
[ "MIT" ]
loic-sharma/ExplorePackages
test/ExplorePackages.Entities.Logic.Test/TestSupport/TestSqliteEntityContext.cs
1,227
C#
namespace GoLive.Generator.PropertyChangedNotifier { public static class EmbeddedResources { public static string Resources_AdditionalFiles_cs = "GoLive.Generator.PropertyChangedNotifier.Resources.AdditionalFiles.cs"; } }
34.428571
132
0.792531
[ "MIT" ]
surgicalcoder/PropertyChangeNotifierGenerator
GoLive.Generator.PropertyChangedNotifier/EmbeddedResource.g.cs
241
C#
using UnityEngine; namespace TSW.Noise { public class Source : ScriptableObject { public virtual float GetFloat(Vector3 xyz) { return 0f; } public virtual void SetSeed(int x) { } public virtual bool IsValid() { return false; } } }
11.863636
44
0.662835
[ "MIT" ]
vthem/PolyRace
Assets/Scripts/TSW.GameLib/Noise/Source.cs
261
C#
using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System.Diagnostics; using System.IO; using Xamarin.Android.Tools; namespace Xamarin.Android.Lite.Tasks { public class ResolveSdks : Task { [Output] public string AndroidSdkPath { get; set; } [Output] public string AndroidNdkPath { get; set; } [Output] public string JavaSdkPath { get; set; } [Output] public string AndroidSdkBuildToolsPath { get; set; } [Output] public string ZipAlignPath { get; set; } [Output] public string ApkSignerJar { get; set; } static readonly bool IsWindows = Path.DirectorySeparatorChar == '\\'; static readonly string ZipAlign = IsWindows ? "zipalign.exe" : "zipalign"; static readonly string ApkSigner = "apksigner.jar"; public override bool Execute () { var sdk = new AndroidSdkInfo (this.CreateTaskLogger (), AndroidSdkPath, AndroidNdkPath, JavaSdkPath); AndroidSdkPath = sdk.AndroidSdkPath; AndroidNdkPath = sdk.AndroidNdkPath; JavaSdkPath = sdk.JavaSdkPath; foreach (var dir in sdk.GetBuildToolsPaths ()) { var zipAlign = Path.Combine (dir, ZipAlign); if (File.Exists (zipAlign)) ZipAlignPath = dir; var apkSigner = Path.Combine (dir, "lib", ApkSigner); if (File.Exists (apkSigner)) ApkSignerJar = apkSigner; AndroidSdkBuildToolsPath = dir; break; } return !Log.HasLoggedErrors; } } }
23.779661
104
0.704205
[ "MIT" ]
ammogcoder/Xamarin.Android.Lite
Xamarin.Android.Lite.Tasks/Tasks/ResolveSdks.cs
1,405
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; namespace System.Windows.Forms { /// <summary> /// Specifies the return value for HITTEST on treeview. /// </summary> [Flags] [ComVisible(true)] public enum TreeViewHitTestLocations { /// <summary> /// No Information. /// </summary> None = NativeMethods.TVHT_NOWHERE, /// <summary> /// On Image. /// </summary> Image = NativeMethods.TVHT_ONITEMICON, /// <summary> /// On Label. /// </summary> Label = NativeMethods.TVHT_ONITEMLABEL, /// <summary> /// Indent. /// </summary> Indent = NativeMethods.TVHT_ONITEMINDENT, /// <summary> /// AboveClientArea. /// </summary> AboveClientArea = NativeMethods.TVHT_ABOVE, /// <summary> /// BelowClientArea. /// </summary> BelowClientArea = NativeMethods.TVHT_BELOW, /// <summary> /// LeftOfClientArea. /// </summary> LeftOfClientArea = NativeMethods.TVHT_TOLEFT, /// <summary> /// RightOfClientArea. /// </summary> RightOfClientArea = NativeMethods.TVHT_TORIGHT, /// <summary> /// RightOfNode. /// </summary> RightOfLabel = NativeMethods.TVHT_ONITEMRIGHT, /// <summary> /// StateImage. /// </summary> StateImage = NativeMethods.TVHT_ONITEMSTATEICON, /// <summary> /// PlusMinus. /// </summary> PlusMinus = NativeMethods.TVHT_ONITEMBUTTON, } }
25.430556
71
0.556526
[ "MIT" ]
15835229565/winforms-1
src/System.Windows.Forms/src/System/Windows/Forms/TreeViewHitTestLocation.cs
1,833
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. using System.Collections.Generic; using Microsoft.PowerFx.Core.App.ErrorContainers; using Microsoft.PowerFx.Core.Binding; using Microsoft.PowerFx.Core.Errors; using Microsoft.PowerFx.Core.Functions; using Microsoft.PowerFx.Core.Localization; using Microsoft.PowerFx.Core.Syntax.Nodes; using Microsoft.PowerFx.Core.Types; using Microsoft.PowerFx.Core.Utils; namespace Microsoft.PowerFx.Core.Texl.Builtins { // IsUTCToday(date: d): b internal sealed class IsUTCTodayFunction : BuiltinFunction { // Multiple invocations may result in different return values. public override bool IsStateless => false; public override bool IsSelfContained => true; public override bool SupportsParamCoercion => true; public IsUTCTodayFunction() : base("IsUTCToday", TexlStrings.AboutIsUTCToday, FunctionCategories.Information, DType.Boolean, 0, 1, 1, DType.DateTime) { } public override IEnumerable<TexlStrings.StringGetter[]> GetSignatures() { return EnumerableUtils.Yield(new[] { TexlStrings.IsUTCTodayFuncArg1 }); } public override bool CheckInvocation(TexlBinding binding, TexlNode[] args, DType[] argTypes, IErrorContainer errors, out DType returnType, out Dictionary<TexlNode, DType> nodeToCoercedTypeMap) { Contracts.AssertValue(args); Contracts.AssertAllValues(args); Contracts.AssertValue(argTypes); Contracts.Assert(args.Length == argTypes.Length); Contracts.AssertValue(errors); Contracts.Assert(MinArity <= args.Length && args.Length <= MaxArity); var fValid = CheckInvocation(args, argTypes, errors, out returnType, out nodeToCoercedTypeMap); var type0 = argTypes[0]; // Arg0 should not be a Time if (type0.Kind == DKind.Time) { fValid = false; errors.EnsureError(DocumentErrorSeverity.Severe, args[0], TexlStrings.ErrDateExpected); } returnType = ReturnType; return fValid; } } }
37.338983
200
0.672719
[ "MIT" ]
Grant-Archibald-MS/Power-Fx
src/libraries/Microsoft.PowerFx.Core/Texl/Builtins/IsUTCToday.cs
2,205
C#
namespace UblTr.Common { [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] [System.Xml.Serialization.XmlRootAttribute("CallBaseAmount", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", IsNullable = false)] public partial class CallBaseAmountType : AmountType1 { } }
52.25
169
0.77193
[ "MIT" ]
canyener/Ubl-Tr
Ubl-Tr/Common/CommonBasicComponents/CallBaseAmountType.cs
627
C#
using Lucene.Net.Index; using Lucene.Net.Queries; using Lucene.Net.Search; using Lucene.Net.Util; using NUnit.Framework; namespace Lucene.Net.Tests.Queries { public class BoostingQueryTest : LuceneTestCase { // TODO: this suite desperately needs more tests! // ... like ones that actually run the query [Test] public virtual void TestBoostingQueryEquals() { TermQuery q1 = new TermQuery(new Term("subject:", "java")); TermQuery q2 = new TermQuery(new Term("subject:", "java")); assertEquals("Two TermQueries with same attributes should be equal", q1, q2); BoostingQuery bq1 = new BoostingQuery(q1, q2, 0.1f); QueryUtils.Check(bq1); BoostingQuery bq2 = new BoostingQuery(q1, q2, 0.1f); assertEquals("BoostingQuery with same attributes is not equal", bq1, bq2); } } }
35.076923
89
0.635965
[ "Apache-2.0" ]
BlueCurve-Team/lucenenet
src/Lucene.Net.Tests.Queries/BoostingQueryTest.cs
914
C#
namespace NuGet.Versioning { /// <summary> /// Version comparison modes. /// </summary> public enum VersionComparison { /// <summary> /// Semantic version 2.0.1-rc comparison with additional compares for extra NuGetVersion fields. /// </summary> Default = 0, /// <summary> /// Compares only the version numbers. /// </summary> Version = 1, /// <summary> /// Include Version number and Release labels in the compare. /// </summary> VersionRelease = 2, /// <summary> /// Include all metadata during the compare. /// </summary> VersionReleaseMetadata = 3 } }
24.551724
104
0.542135
[ "Apache-2.0" ]
NuGet/NuGet.Versioning
src/NuGet.Versioning/VersionComparison.cs
714
C#
// CS0664: Literal of type double cannot be implicitly converted to type `decimal'. Add suffix `m' to create a literal of this type // Line: 7 class X { void A () { decimal d = -2.0; } }
19.3
131
0.658031
[ "Apache-2.0" ]
121468615/mono
mcs/errors/cs0664-4.cs
193
C#
using System.Text; using System.Windows.Forms; namespace Shotr.Core.Entities.Hotkeys { public class HotKeyData { public ushort ID { get; set; } public bool Active { get; set; } public HotKeyData(Keys hotkey) { _hk = hotkey; } private Keys _hk = Keys.None; private KeyTask _task = KeyTask.Empty; public KeyTask Task { get => _task; set => _task = value; } public Keys HotKey => _hk; public Keys KeyCode => HotKey & Keys.KeyCode; public Keys ModifiersKeys => HotKey & Keys.Modifiers; public bool Control => HotKey.HasFlag(Keys.Control); public bool Shift => HotKey.HasFlag(Keys.Shift); public bool Alt => HotKey.HasFlag(Keys.Alt); //return modifier keys only. public HotKeyModifiers ModifiersEnum { get { var mod = HotKeyModifiers.None; if (Alt) mod |= HotKeyModifiers.Alt; if (Control) mod |= HotKeyModifiers.Control; if (Shift) mod |= HotKeyModifiers.Shift; return mod; } } public bool IsOnlyModifiers => KeyCode == Keys.ControlKey || KeyCode == Keys.ShiftKey || KeyCode == Keys.Menu; public bool IsValidHotkey => KeyCode != Keys.None && !IsOnlyModifiers; public override string ToString() { var text = string.Empty; if (KeyCode != Keys.None) { if (Control) { text += "Ctrl + "; } if (Shift) { text += "Shift + "; } if (Alt) { text += "Alt + "; } } text += KeyCode switch { {} when IsOnlyModifiers => "...", Keys.Back => "Backspace", Keys.Return => "Enter", Keys.Capital => "Caps Lock", Keys.Next => "Page Down", Keys.Scroll => "Scroll Lock", Keys.Oemtilde => "~", {} when KeyCode >= Keys.D0 && KeyCode <= Keys.D9 => (KeyCode - Keys.D0).ToString(), {} when KeyCode >= Keys.NumPad0 && KeyCode <= Keys.NumPad9 => (KeyCode - Keys.NumPad0).ToString(), _ => ToStringWithSpaces(KeyCode) }; return text; } private string ToStringWithSpaces(Keys key) { var name = key.ToString(); var result = new StringBuilder(); for (var i = 0; i < name.Length; i++) { if (i > 0 && char.IsUpper(name[i])) { result.Append(" " + name[i]); } else { result.Append(name[i]); } } return result.ToString(); } } }
29.886957
118
0.394821
[ "Apache-2.0" ]
shotr-io/shotr-3
src/Shotr.Core/Entities/Hotkeys/HotkeyData.cs
3,439
C#
/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Copyright (C) 2009-2012 Michael Möller <mmoeller@openhardwaremonitor.org> Copyright (C) 2011 Christian Vallières */ using System; using System.Runtime.InteropServices; using System.Text; namespace OpenHardwareMonitor.Hardware.Nvidia { internal enum NvStatus { OK = 0, ERROR = -1, LIBRARY_NOT_FOUND = -2, NO_IMPLEMENTATION = -3, API_NOT_INTIALIZED = -4, INVALID_ARGUMENT = -5, NVIDIA_DEVICE_NOT_FOUND = -6, END_ENUMERATION = -7, INVALID_HANDLE = -8, INCOMPATIBLE_STRUCT_VERSION = -9, HANDLE_INVALIDATED = -10, OPENGL_CONTEXT_NOT_CURRENT = -11, NO_GL_EXPERT = -12, INSTRUMENTATION_DISABLED = -13, EXPECTED_LOGICAL_GPU_HANDLE = -100, EXPECTED_PHYSICAL_GPU_HANDLE = -101, EXPECTED_DISPLAY_HANDLE = -102, INVALID_COMBINATION = -103, NOT_SUPPORTED = -104, PORTID_NOT_FOUND = -105, EXPECTED_UNATTACHED_DISPLAY_HANDLE = -106, INVALID_PERF_LEVEL = -107, DEVICE_BUSY = -108, NV_PERSIST_FILE_NOT_FOUND = -109, PERSIST_DATA_NOT_FOUND = -110, EXPECTED_TV_DISPLAY = -111, EXPECTED_TV_DISPLAY_ON_DCONNECTOR = -112, NO_ACTIVE_SLI_TOPOLOGY = -113, SLI_RENDERING_MODE_NOTALLOWED = -114, EXPECTED_DIGITAL_FLAT_PANEL = -115, ARGUMENT_EXCEED_MAX_SIZE = -116, DEVICE_SWITCHING_NOT_ALLOWED = -117, TESTING_CLOCKS_NOT_SUPPORTED = -118, UNKNOWN_UNDERSCAN_CONFIG = -119, TIMEOUT_RECONFIGURING_GPU_TOPO = -120, DATA_NOT_FOUND = -121, EXPECTED_ANALOG_DISPLAY = -122, NO_VIDLINK = -123, REQUIRES_REBOOT = -124, INVALID_HYBRID_MODE = -125, MIXED_TARGET_TYPES = -126, SYSWOW64_NOT_SUPPORTED = -127, IMPLICIT_SET_GPU_TOPOLOGY_CHANGE_NOT_ALLOWED = -128, REQUEST_USER_TO_CLOSE_NON_MIGRATABLE_APPS = -129, OUT_OF_MEMORY = -130, WAS_STILL_DRAWING = -131, FILE_NOT_FOUND = -132, TOO_MANY_UNIQUE_STATE_OBJECTS = -133, INVALID_CALL = -134, D3D10_1_LIBRARY_NOT_FOUND = -135, FUNCTION_NOT_FOUND = -136 } internal enum NvThermalController { NONE = 0, GPU_INTERNAL, ADM1032, MAX6649, MAX1617, LM99, LM89, LM64, ADT7473, SBMAX6649, VBIOSEVT, OS, UNKNOWN = -1, } internal enum NvThermalTarget { NONE = 0, GPU = 1, MEMORY = 2, POWER_SUPPLY = 4, BOARD = 8, ALL = 15, UNKNOWN = -1 }; [StructLayout(LayoutKind.Sequential, Pack = 8)] internal struct NvSensor { public NvThermalController Controller; public uint DefaultMinTemp; public uint DefaultMaxTemp; public uint CurrentTemp; public NvThermalTarget Target; } [StructLayout(LayoutKind.Sequential, Pack = 8)] internal struct NvGPUThermalSettings { public uint Version; public uint Count; [MarshalAs(UnmanagedType.ByValArray, SizeConst = NVAPI.MAX_THERMAL_SENSORS_PER_GPU)] public NvSensor[] Sensor; } [StructLayout(LayoutKind.Sequential)] internal struct NvDisplayHandle { private readonly IntPtr ptr; } [StructLayout(LayoutKind.Sequential)] internal struct NvPhysicalGpuHandle { private readonly IntPtr ptr; } [StructLayout(LayoutKind.Sequential, Pack = 8)] internal struct NvClocks { public uint Version; [MarshalAs(UnmanagedType.ByValArray, SizeConst = NVAPI.MAX_CLOCKS_PER_GPU)] public uint[] Clock; } [StructLayout(LayoutKind.Sequential, Pack = 8)] internal struct NvPState { public bool Present; public int Percentage; } [StructLayout(LayoutKind.Sequential, Pack = 8)] internal struct NvPStates { public uint Version; public uint Flags; [MarshalAs(UnmanagedType.ByValArray, SizeConst = NVAPI.MAX_PSTATES_PER_GPU)] public NvPState[] PStates; } [StructLayout(LayoutKind.Sequential, Pack = 8)] internal struct NvUsages { public uint Version; [MarshalAs(UnmanagedType.ByValArray, SizeConst = NVAPI.MAX_USAGES_PER_GPU)] public uint[] Usage; } [StructLayout(LayoutKind.Sequential, Pack = 8)] internal struct NvCooler { public int Type; public int Controller; public int DefaultMin; public int DefaultMax; public int CurrentMin; public int CurrentMax; public int CurrentLevel; public int DefaultPolicy; public int CurrentPolicy; public int Target; public int ControlType; public int Active; } [StructLayout(LayoutKind.Sequential, Pack = 8)] internal struct NvGPUCoolerSettings { public uint Version; public uint Count; [MarshalAs(UnmanagedType.ByValArray, SizeConst = NVAPI.MAX_COOLER_PER_GPU)] public NvCooler[] Cooler; } [StructLayout(LayoutKind.Sequential, Pack = 8)] internal struct NvLevel { public int Level; public int Policy; } [StructLayout(LayoutKind.Sequential, Pack = 8)] internal struct NvGPUCoolerLevels { public uint Version; [MarshalAs(UnmanagedType.ByValArray, SizeConst = NVAPI.MAX_COOLER_PER_GPU)] public NvLevel[] Levels; } [StructLayout(LayoutKind.Sequential, Pack = 8)] internal struct NvMemoryInfo { public uint Version; [MarshalAs(UnmanagedType.ByValArray, SizeConst = NVAPI.MAX_MEMORY_VALUES_PER_GPU)] public uint[] Values; } [StructLayout(LayoutKind.Sequential, Pack = 8)] internal struct NvDisplayDriverVersion { public uint Version; public uint DriverVersion; public uint BldChangeListNum; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = NVAPI.SHORT_STRING_MAX)] public string BuildBranch; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = NVAPI.SHORT_STRING_MAX)] public string Adapter; } internal class NVAPI { public const int MAX_PHYSICAL_GPUS = 64; public const int SHORT_STRING_MAX = 64; public const int MAX_THERMAL_SENSORS_PER_GPU = 3; public const int MAX_CLOCKS_PER_GPU = 0x120; public const int MAX_PSTATES_PER_GPU = 8; public const int MAX_USAGES_PER_GPU = 33; public const int MAX_COOLER_PER_GPU = 20; public const int MAX_MEMORY_VALUES_PER_GPU = 5; public static readonly uint GPU_THERMAL_SETTINGS_VER = (uint) Marshal.SizeOf(typeof(NvGPUThermalSettings)) | 0x10000; public static readonly uint GPU_CLOCKS_VER = (uint) Marshal.SizeOf(typeof(NvClocks)) | 0x20000; public static readonly uint GPU_PSTATES_VER = (uint) Marshal.SizeOf(typeof(NvPStates)) | 0x10000; public static readonly uint GPU_USAGES_VER = (uint) Marshal.SizeOf(typeof(NvUsages)) | 0x10000; public static readonly uint GPU_COOLER_SETTINGS_VER = (uint) Marshal.SizeOf(typeof(NvGPUCoolerSettings)) | 0x20000; public static readonly uint GPU_MEMORY_INFO_VER = (uint) Marshal.SizeOf(typeof(NvMemoryInfo)) | 0x20000; public static readonly uint DISPLAY_DRIVER_VERSION_VER = (uint) Marshal.SizeOf(typeof(NvDisplayDriverVersion)) | 0x10000; public static readonly uint GPU_COOLER_LEVELS_VER = (uint) Marshal.SizeOf(typeof(NvGPUCoolerLevels)) | 0x10000; private delegate IntPtr nvapi_QueryInterfaceDelegate(uint id); private delegate NvStatus NvAPI_InitializeDelegate(); private delegate NvStatus NvAPI_GPU_GetFullNameDelegate( NvPhysicalGpuHandle gpuHandle, StringBuilder name); public delegate NvStatus NvAPI_GPU_GetThermalSettingsDelegate( NvPhysicalGpuHandle gpuHandle, int sensorIndex, ref NvGPUThermalSettings nvGPUThermalSettings); public delegate NvStatus NvAPI_EnumNvidiaDisplayHandleDelegate(int thisEnum, ref NvDisplayHandle displayHandle); public delegate NvStatus NvAPI_GetPhysicalGPUsFromDisplayDelegate( NvDisplayHandle displayHandle, [Out] NvPhysicalGpuHandle[] gpuHandles, out uint gpuCount); public delegate NvStatus NvAPI_EnumPhysicalGPUsDelegate( [Out] NvPhysicalGpuHandle[] gpuHandles, out int gpuCount); public delegate NvStatus NvAPI_GPU_GetTachReadingDelegate( NvPhysicalGpuHandle gpuHandle, out int value); public delegate NvStatus NvAPI_GPU_GetAllClocksDelegate( NvPhysicalGpuHandle gpuHandle, ref NvClocks nvClocks); public delegate NvStatus NvAPI_GPU_GetPStatesDelegate( NvPhysicalGpuHandle gpuHandle, ref NvPStates nvPStates); public delegate NvStatus NvAPI_GPU_GetUsagesDelegate( NvPhysicalGpuHandle gpuHandle, ref NvUsages nvUsages); public delegate NvStatus NvAPI_GPU_GetCoolerSettingsDelegate( NvPhysicalGpuHandle gpuHandle, int coolerIndex, ref NvGPUCoolerSettings nvGPUCoolerSettings); public delegate NvStatus NvAPI_GPU_SetCoolerLevelsDelegate( NvPhysicalGpuHandle gpuHandle, int coolerIndex, ref NvGPUCoolerLevels NvGPUCoolerLevels); public delegate NvStatus NvAPI_GPU_GetMemoryInfoDelegate( NvDisplayHandle displayHandle, ref NvMemoryInfo nvMemoryInfo); public delegate NvStatus NvAPI_GetDisplayDriverVersionDelegate( NvDisplayHandle displayHandle, [In, Out] ref NvDisplayDriverVersion nvDisplayDriverVersion); public delegate NvStatus NvAPI_GetInterfaceVersionStringDelegate( StringBuilder version); public delegate NvStatus NvAPI_GPU_GetPCIIdentifiersDelegate( NvPhysicalGpuHandle gpuHandle, out uint deviceId, out uint subSystemId, out uint revisionId, out uint extDeviceId); private static readonly bool available; private static readonly nvapi_QueryInterfaceDelegate nvapi_QueryInterface; private static readonly NvAPI_InitializeDelegate NvAPI_Initialize; private static readonly NvAPI_GPU_GetFullNameDelegate _NvAPI_GPU_GetFullName; private static readonly NvAPI_GetInterfaceVersionStringDelegate _NvAPI_GetInterfaceVersionString; public static readonly NvAPI_GPU_GetThermalSettingsDelegate NvAPI_GPU_GetThermalSettings; public static readonly NvAPI_EnumNvidiaDisplayHandleDelegate NvAPI_EnumNvidiaDisplayHandle; public static readonly NvAPI_GetPhysicalGPUsFromDisplayDelegate NvAPI_GetPhysicalGPUsFromDisplay; public static readonly NvAPI_EnumPhysicalGPUsDelegate NvAPI_EnumPhysicalGPUs; public static readonly NvAPI_GPU_GetTachReadingDelegate NvAPI_GPU_GetTachReading; public static readonly NvAPI_GPU_GetAllClocksDelegate NvAPI_GPU_GetAllClocks; public static readonly NvAPI_GPU_GetPStatesDelegate NvAPI_GPU_GetPStates; public static readonly NvAPI_GPU_GetUsagesDelegate NvAPI_GPU_GetUsages; public static readonly NvAPI_GPU_GetCoolerSettingsDelegate NvAPI_GPU_GetCoolerSettings; public static readonly NvAPI_GPU_SetCoolerLevelsDelegate NvAPI_GPU_SetCoolerLevels; public static readonly NvAPI_GPU_GetMemoryInfoDelegate NvAPI_GPU_GetMemoryInfo; public static readonly NvAPI_GetDisplayDriverVersionDelegate NvAPI_GetDisplayDriverVersion; public static readonly NvAPI_GPU_GetPCIIdentifiersDelegate NvAPI_GPU_GetPCIIdentifiers; private NVAPI() { } public static NvStatus NvAPI_GPU_GetFullName(NvPhysicalGpuHandle gpuHandle, out string name) { StringBuilder builder = new StringBuilder(SHORT_STRING_MAX); NvStatus status; if (_NvAPI_GPU_GetFullName != null) status = _NvAPI_GPU_GetFullName(gpuHandle, builder); else status = NvStatus.FUNCTION_NOT_FOUND; name = builder.ToString(); return status; } public static NvStatus NvAPI_GetInterfaceVersionString(out string version) { StringBuilder builder = new StringBuilder(SHORT_STRING_MAX); NvStatus status; if (_NvAPI_GetInterfaceVersionString != null) status = _NvAPI_GetInterfaceVersionString(builder); else status = NvStatus.FUNCTION_NOT_FOUND; version = builder.ToString(); return status; } private static string GetDllName() { if (IntPtr.Size == 4) { return "nvapi.dll"; } else { return "nvapi64.dll"; } } private static void GetDelegate<T>(uint id, out T newDelegate) where T : class { IntPtr ptr = nvapi_QueryInterface(id); if (ptr != IntPtr.Zero) { newDelegate = Marshal.GetDelegateForFunctionPointer(ptr, typeof(T)) as T; } else { newDelegate = null; } } static NVAPI() { DllImportAttribute attribute = new DllImportAttribute(GetDllName()); attribute.CallingConvention = CallingConvention.Cdecl; attribute.PreserveSig = true; attribute.EntryPoint = "nvapi_QueryInterface"; PInvokeDelegateFactory.CreateDelegate(attribute, out nvapi_QueryInterface); try { GetDelegate(0x0150E828, out NvAPI_Initialize); } catch (DllNotFoundException) { return; } catch (EntryPointNotFoundException) { return; } catch (ArgumentNullException) { return; } if (NvAPI_Initialize() == NvStatus.OK) { GetDelegate(0xE3640A56, out NvAPI_GPU_GetThermalSettings); GetDelegate(0xCEEE8E9F, out _NvAPI_GPU_GetFullName); GetDelegate(0x9ABDD40D, out NvAPI_EnumNvidiaDisplayHandle); GetDelegate(0x34EF9506, out NvAPI_GetPhysicalGPUsFromDisplay); GetDelegate(0xE5AC921F, out NvAPI_EnumPhysicalGPUs); GetDelegate(0x5F608315, out NvAPI_GPU_GetTachReading); GetDelegate(0x1BD69F49, out NvAPI_GPU_GetAllClocks); GetDelegate(0x60DED2ED, out NvAPI_GPU_GetPStates); GetDelegate(0x189A1FDF, out NvAPI_GPU_GetUsages); GetDelegate(0xDA141340, out NvAPI_GPU_GetCoolerSettings); GetDelegate(0x891FA0AE, out NvAPI_GPU_SetCoolerLevels); GetDelegate(0x774AA982, out NvAPI_GPU_GetMemoryInfo); GetDelegate(0xF951A4D1, out NvAPI_GetDisplayDriverVersion); GetDelegate(0x01053FA5, out _NvAPI_GetInterfaceVersionString); GetDelegate(0x2DDFB66E, out NvAPI_GPU_GetPCIIdentifiers); available = true; } } public static bool IsAvailable { get { return available; } } } }
35.115288
80
0.736636
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
AlannaMuir/open-hardware-monitor
Hardware/Nvidia/NVAPI.cs
14,015
C#
using System; using System.Threading; using Microsoft.Extensions.Hosting; using Unity; namespace Zero.Foundation.Web { public class FoundationHost { public FoundationHost() { this.CancellationSource = new CancellationTokenSource(); this.Container = new UnityContainer(); this.Container.RegisterInstance(this); } public CancellationTokenSource CancellationSource { get; set; } public UnityContainer Container { get; set; } public IHost Host { get; set; } public bool ShouldRestart { get; set; } public virtual void RequestRestart() { this.ShouldRestart = true; this.CancellationSource.Cancel(); this.CancellationSource = new CancellationTokenSource(); } public virtual void RequestStop() { this.ShouldRestart = false; this.CancellationSource.Cancel(); this.CancellationSource = new CancellationTokenSource(); } } }
28.916667
71
0.620557
[ "MIT" ]
wmansfield/zero.foundation
Zero.Foundation.Core/Web/FoundationHost.cs
1,041
C#
using NDO.UISupport; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace MySqlUISupport { public class MySqlUIProvider : DbUISupportBase { public override string Name => "MySql"; public override NdoDialogResult ShowCreateDbDialog( ref object necessaryData ) { NDOCreateDbParameter par; if (necessaryData == null) par = new NDOCreateDbParameter( string.Empty, "Data Source=localhost;User Id=root;" ); else par = necessaryData as NDOCreateDbParameter; if (par == null) throw new ArgumentException( "MySql provider: parameter type " + necessaryData.GetType().FullName + " is wrong.", "necessaryData" ); if (par.ConnectionString == null || par.ConnectionString == string.Empty) par.ConnectionString = "Data Source=localhost;User Id=root"; ConnectionDialog dlg = new ConnectionDialog( par.ConnectionString, true ); if (dlg.ShowDialog() == DialogResult.Cancel) return NdoDialogResult.Cancel; par.ConnectionString = dlg.ConnectionString; par.DatabaseName = dlg.Database; necessaryData = par; return NdoDialogResult.OK; } public override NdoDialogResult ShowConnectionDialog( ref string connectionString ) { ConnectionDialog dlg = new ConnectionDialog( connectionString, false ); if (dlg.ShowDialog() == DialogResult.Cancel) return NdoDialogResult.Cancel; connectionString = dlg.ConnectionString; return NdoDialogResult.OK; } public override string CreateDatabase( object necessaryData ) { // Don't need to check, if type is OK, since that happens in CreateDatabase NDOCreateDbParameter par = necessaryData as NDOCreateDbParameter; return EnsureProvider().CreateDatabase( par.DatabaseName, par.ConnectionString ); } } }
35.480769
137
0.728455
[ "MIT" ]
mirkomaty/NDO
Provider/MySqlNdoProvider/MySqlUISupport/MySqlUIProvider.cs
1,847
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.IO; using FluentAssertions; using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.InternalAbstractions; using Microsoft.DotNet.TestFramework; using Microsoft.DotNet.Tools.Test.Utilities; using NuGet.Frameworks; using Xunit; using Microsoft.DotNet.Tools.Tests.Utilities; namespace Microsoft.DotNet.Cli.Utils.Tests { public class GivenAProjectDependencyCommandResolver : TestBase { private TestAssetInstance MSBuildTestProjectInstance; public GivenAProjectDependencyCommandResolver() { Environment.SetEnvironmentVariable( Constants.MSBUILD_EXE_PATH, Path.Combine(new RepoDirectoriesProvider().Stage2Sdk, "MSBuild.dll")); } [Fact] public void ItReturnsACommandSpecWhenToolIsInAProjectRef() { MSBuildTestProjectInstance = TestAssets.Get("TestAppWithProjDepTool") .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); new BuildCommand() .WithProjectDirectory(MSBuildTestProjectInstance.Root) .WithConfiguration("Debug") .Execute() .Should().Pass(); var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", Configuration = "Debug", ProjectDirectory = MSBuildTestProjectInstance.Root.FullName, Framework = NuGetFrameworks.NetCoreApp30 }; var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); var commandFile = Path.GetFileNameWithoutExtension(result.Path); commandFile.Should().Be("dotnet"); result.Args.Should().Contain(commandResolverArguments.CommandName); } [Fact] public void ItPassesDepsfileArgToHostWhenReturningACommandSpecForMSBuildProject() { MSBuildTestProjectInstance = TestAssets.Get("TestAppWithProjDepTool") .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); new BuildCommand() .WithProjectDirectory(MSBuildTestProjectInstance.Root) .WithConfiguration("Debug") .Execute() .Should().Pass(); var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", Configuration = "Debug", ProjectDirectory = MSBuildTestProjectInstance.Root.FullName, Framework = NuGetFrameworks.NetCoreApp30 }; var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); result.Args.Should().Contain("--depsfile"); } [Fact] public void ItReturnsNullWhenCommandNameDoesNotExistInProjectDependenciesForMSBuildProject() { MSBuildTestProjectInstance = TestAssets.Get("TestAppWithProjDepTool") .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "nonexistent-command", CommandArguments = null, ProjectDirectory = MSBuildTestProjectInstance.Root.FullName, Framework = NuGetFrameworks.NetCoreApp30 }; var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void ItSetsDepsfileToOutputInCommandspecForMSBuild() { var testInstance = TestAssets .Get("TestAppWithProjDepTool") .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver(); var outputDir = testInstance.Root.GetDirectory("out"); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", Configuration = "Debug", ProjectDirectory = testInstance.Root.FullName, Framework = NuGetFrameworks.NetCoreApp30, OutputPath = outputDir.FullName }; new BuildCommand() .WithWorkingDirectory(testInstance.Root) .Execute($"-o {outputDir.FullName}") .Should() .Pass(); var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments); var depsFilePath = outputDir.GetFile("TestAppWithProjDepTool.deps.json"); result.Should().NotBeNull(); result.Args.Should().Contain($"--depsfile {depsFilePath.FullName}"); } private ProjectDependenciesCommandResolver SetupProjectDependenciesCommandResolver( IEnvironmentProvider environment = null, IPackagedCommandSpecFactory packagedCommandSpecFactory = null) { Environment.SetEnvironmentVariable( Constants.MSBUILD_EXE_PATH, Path.Combine(new RepoDirectoriesProvider().Stage2Sdk, "MSBuild.dll")); CommandContext.SetVerbose(true); environment = environment ?? new EnvironmentProvider(); packagedCommandSpecFactory = packagedCommandSpecFactory ?? new PackagedCommandSpecFactory(); var projectDependenciesCommandResolver = new ProjectDependenciesCommandResolver(environment, packagedCommandSpecFactory); return projectDependenciesCommandResolver; } } }
36.892655
133
0.623737
[ "MIT" ]
APiZFiBlockChain4/cli
test/Microsoft.DotNet.Cli.Utils.Tests/GivenAProjectDependencyCommandResolver.cs
6,530
C#
namespace VH.MiniService.Common { public static class CommonRequestHeaders { public const string Token = "vh-authorization"; public const string UserId = "vh-user-id"; public const string TenantId = "vh-tenant-id"; } }
25.6
55
0.65625
[ "Apache-2.0" ]
vit-h/mini-service-common
Common/CommonRequestHeaders.cs
258
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace PhilosopherPeasant.Services { public class AuthMessageSMSSenderOptions { public string SID { get; set; } public string AuthToken { get; set; } public string SendNumber { get; set; } } }
22.066667
46
0.691843
[ "MIT", "Unlicense" ]
dmdiehr/PhilosopherPeasant
src/PhilosopherPeasant/Services/AuthMessageSMSSenderOptions.cs
333
C#
/* * Copyright (c) 2016, Firely (info@fire.ly) and contributors * See the file CONTRIBUTORS for details. * * This file is licensed under the BSD 3-Clause license * available at https://raw.githubusercontent.com/FirelyTeam/fhir-net-api/master/LICENSE */ using System; using Hl7.Fhir.Model; using Hl7.Fhir.Specification.Snapshot; using Microsoft.VisualStudio.TestTools.UnitTesting; using Hl7.Fhir.Specification.Source; using Hl7.Fhir.Specification.Navigation; using System.Collections.Generic; using System.Diagnostics; using Hl7.Fhir.Introspection; using static Hl7.Fhir.Model.ElementDefinition.DiscriminatorComponent; using Hl7.Fhir.Utility; namespace Hl7.Fhir.Specification.Tests { // Unit tests for ElementMatcher [TestClass] public class SnapshotElementMatcherTests { IResourceResolver _testResolver; [TestInitialize] public void Setup() { var dirSource = new DirectorySource("TestData/snapshot-test", new DirectorySourceSettings { IncludeSubDirectories = true } ); _testResolver = new CachedResolver(dirSource); } [TestMethod] public void TestElementMatcher_Patient_Simple() { // Match element constraints on Patient and Patient.identifier to Patient core definition // Both element constraints should be merged var baseProfile = _testResolver.FindStructureDefinitionForCoreType(FHIRAllTypes.Patient); var userProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Patient"), new ElementDefinition("Patient.identifier") } } }; var snapNav = ElementDefinitionNavigator.ForSnapshot(baseProfile); var diffNav = ElementDefinitionNavigator.ForDifferential(userProfile); // Merge: Patient root var matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Merge: Patient.identifier matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToChild(diffNav.PathName)); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); } [TestMethod] public void TestElementMatcher_Patient_Identity() { // Match core patient profile to itself // All element constraints should be merged var baseProfile = _testResolver.FindStructureDefinitionForCoreType(FHIRAllTypes.Patient); var userProfile = (StructureDefinition)baseProfile.DeepCopy(); var snapNav = ElementDefinitionNavigator.ForSnapshot(baseProfile); var diffNav = ElementDefinitionNavigator.ForSnapshot(userProfile); // Recursively match all constraints and verify that all matches return action Merged var matches = matchAndVerify(snapNav, diffNav); } [TestMethod] public void TestElementMatcher_Patient_Extension_New() { // Slice core Patient.extension, introduce a new extension // Extension does not need a slicing introduction in differential var baseProfile = _testResolver.FindStructureDefinitionForCoreType(FHIRAllTypes.Patient); var userProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Patient"), new ElementDefinition("Patient.extension") { Type = new List<ElementDefinition.TypeRefComponent>() { new ElementDefinition.TypeRefComponent() { Code = FHIRAllTypes.Extension.GetLiteral(), Profile = "http://example.org/fhir/StructureDefinition/myExtension" } } } } } }; var snapNav = ElementDefinitionNavigator.ForSnapshot(baseProfile); var diffNav = ElementDefinitionNavigator.ForDifferential(userProfile); // Merge: Patient root var matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Slice: Patient.extension matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); Assert.AreEqual(2, matches.Count); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToChild(diffNav.PathName)); assertMatch(matches[0], ElementMatcher.MatchAction.Slice, snapNav); // Extension slice entry (no diff match) assertMatch(matches[1], ElementMatcher.MatchAction.Add, snapNav, diffNav); // Add new extension } [TestMethod] public void TestElementMatcher_Patient_Extension_Override() { // Constrain an existing Patient extension slice var baseProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Patient"), new ElementDefinition("Patient.extension") { Type = new List<ElementDefinition.TypeRefComponent>() { new ElementDefinition.TypeRefComponent() { Code = FHIRAllTypes.Extension.GetLiteral() } }, Slicing = new ElementDefinition.SlicingComponent() { Discriminator = ForValueSlice("url").ToList() } }, new ElementDefinition("Patient.extension") { Type = new List<ElementDefinition.TypeRefComponent>() { new ElementDefinition.TypeRefComponent() { Code = FHIRAllTypes.Extension.GetLiteral(), Profile = "http://example.org/fhir/StructureDefinition/myExtension" } } } } } }; var userProfile = (StructureDefinition)baseProfile.DeepCopy(); // Constrain existing extension definition userProfile.Differential.Element[2].Min = 1; var snapNav = ElementDefinitionNavigator.ForDifferential(baseProfile); var diffNav = ElementDefinitionNavigator.ForDifferential(userProfile); // Merge: Patient root var matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Slice: Patient.extension matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); Assert.AreEqual(2, matches.Count); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToChild(diffNav.PathName)); assertMatch(matches[0], ElementMatcher.MatchAction.Slice, snapNav, diffNav); // Extension slice entry Assert.IsTrue(diffNav.MoveToNext()); Assert.IsTrue(snapNav.MoveToNext()); assertMatch(matches[1], ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Override existing extension slice } [TestMethod] public void TestElementMatcher_Patient_Extension_Add() { // Add another extension to an existing extension slice var baseProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Patient"), new ElementDefinition("Patient.extension") { Type = new List<ElementDefinition.TypeRefComponent>() { new ElementDefinition.TypeRefComponent() { Code = FHIRAllTypes.Extension.GetLiteral() } }, Slicing = new ElementDefinition.SlicingComponent() { Discriminator = ForValueSlice("url").ToList(), Rules = ElementDefinition.SlicingRules.Closed } }, new ElementDefinition("Patient.extension") { Type = new List<ElementDefinition.TypeRefComponent>() { new ElementDefinition.TypeRefComponent() { Code = FHIRAllTypes.Extension.GetLiteral(), Profile = "http://example.org/fhir/StructureDefinition/myExtension" } } } } } }; var userProfile = (StructureDefinition)baseProfile.DeepCopy(); // Define another extension slice in diff userProfile.Differential.Element.RemoveAt(1); // Remove extension slicing entry (not required) userProfile.Differential.Element[1].Type[0].Profile = "http://example.org/fhir/StructureDefinition/myOtherExtension"; var snapNav = ElementDefinitionNavigator.ForDifferential(baseProfile); var diffNav = ElementDefinitionNavigator.ForDifferential(userProfile); // Merge: Patient root var matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Slice: Patient.extension matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); // [WMR 20170406] extension slice entry is inherited from base w/o diff constraints => no match // Expecting a single match for the additional complex extension element Assert.AreEqual(1, matches.Count); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToChild(diffNav.PathName)); assertMatch(matches[0], ElementMatcher.MatchAction.Add, snapNav, diffNav); // Add new extension slice } [TestMethod] public void TestElementMatcher_Patient_Extension_Insert() { // Insert another extension into an existing extension slice var baseProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Patient"), new ElementDefinition("Patient.extension") { Type = new List<ElementDefinition.TypeRefComponent>() { new ElementDefinition.TypeRefComponent() { Code = FHIRAllTypes.Extension.GetLiteral() } }, Slicing = new ElementDefinition.SlicingComponent() { Discriminator = ForValueSlice("url").ToList() } }, new ElementDefinition("Patient.extension") { Type = new List<ElementDefinition.TypeRefComponent>() { new ElementDefinition.TypeRefComponent() { Code = FHIRAllTypes.Extension.GetLiteral(), Profile = "http://example.org/fhir/StructureDefinition/myExtension" } } } } } }; var userProfile = (StructureDefinition)baseProfile.DeepCopy(); // Insert another extension slice before the existing extension var ext = (ElementDefinition)userProfile.Differential.Element[2].DeepCopy(); ext.Type[0].Profile = "http://example.org/fhir/StructureDefinition/myOtherExtension"; userProfile.Differential.Element.Insert(2, ext); var snapNav = ElementDefinitionNavigator.ForDifferential(baseProfile); var diffNav = ElementDefinitionNavigator.ForDifferential(userProfile); // Merge: Patient root var matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Slice: Patient.extension matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); Assert.AreEqual(3, matches.Count); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToChild(diffNav.PathName)); assertMatch(matches[0], ElementMatcher.MatchAction.Slice, snapNav, diffNav); // Extension slice entry Assert.IsTrue(diffNav.MoveToNext()); // Don't advance snapNav; new diff slice is merged with default base = snap slice entry assertMatch(matches[1], ElementMatcher.MatchAction.Add, snapNav, diffNav); // Insert new extension slice Assert.IsTrue(diffNav.MoveToNext()); Assert.IsTrue(snapNav.MoveToNext()); assertMatch(matches[2], ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Merge existing extension slice } [TestMethod] public void TestElementMatcher_ComplexExtension() { var baseProfile = _testResolver.FindStructureDefinitionForCoreType(FHIRAllTypes.Extension); var userProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Extension"), new ElementDefinition("Extension.extension") { SliceName = "name" }, new ElementDefinition("Extension.extension.value[x]") { Type = new List<ElementDefinition.TypeRefComponent>() { new ElementDefinition.TypeRefComponent() { Code = FHIRAllTypes.String.GetLiteral() } } }, new ElementDefinition("Extension.extension.url") { Fixed = new FhirUri("name") }, new ElementDefinition("Extension.extension") { SliceName = "age" }, new ElementDefinition("Extension.extension.value[x]") { Type = new List<ElementDefinition.TypeRefComponent>() { new ElementDefinition.TypeRefComponent() { Code = FHIRAllTypes.Integer.GetLiteral() } } }, new ElementDefinition("Extension.extension.url") { Fixed = new FhirUri("age") }, } } }; var snapNav = ElementDefinitionNavigator.ForSnapshot(baseProfile); var diffNav = ElementDefinitionNavigator.ForDifferential(userProfile); // Merge: Extension root var matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Slice: Extension.extension matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); // DSTU2 // [WMR 20170411] In DSTU2, The core Extension profile does NOT define a slicing component on "Extension.extension" // Current profile slices the extension element, so the matcher returns a virtual match (w/o diff element) // Assert.AreEqual(3, matches.Count); // extension slice entry + 2 complex extension elements // STU3 // [WMR 20170411] In STU3, The core Extension profile defines url slicing component on "Extension.extension" // Diff does not further constrain the inherited slice entry, so no match Assert.AreEqual(2, matches.Count); // 2 complex extension elements Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToChild(diffNav.PathName)); // assertMatch(matches[0], ElementMatcher.MatchAction.Slice, snapNav); // Extension slice entry (no diff match) assertMatch(matches[0], ElementMatcher.MatchAction.Add, snapNav, diffNav); // First extension child element "name" Assert.IsTrue(diffNav.MoveToNext()); assertMatch(matches[1], ElementMatcher.MatchAction.Add, snapNav, diffNav); // Second extension child element "age" Assert.IsFalse(diffNav.MoveToNext()); } [TestMethod] public void TestElementMatcher_ComplexExtension_Add() { // Add a child extension element to an existing complex extension definition var baseProfile = new StructureDefinition() { Snapshot = new StructureDefinition.SnapshotComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Extension"), new ElementDefinition("Extension.extension") { Slicing = new ElementDefinition.SlicingComponent() { Discriminator = ForValueSlice("url").ToList() } }, new ElementDefinition("Extension.extension") { SliceName = "name" }, new ElementDefinition("Extension.extension.value[x]") { Type = new List<ElementDefinition.TypeRefComponent>() { new ElementDefinition.TypeRefComponent() { Code = FHIRAllTypes.String.GetLiteral() } } }, new ElementDefinition("Extension.extension.url") { Fixed = new FhirUri("name") }, new ElementDefinition("Extension.extension") { SliceName = "age" }, new ElementDefinition("Extension.extension.value[x]") { Type = new List<ElementDefinition.TypeRefComponent>() { new ElementDefinition.TypeRefComponent() { Code = FHIRAllTypes.Integer.GetLiteral() } } }, new ElementDefinition("Extension.extension.url") { Fixed = new FhirUri("age") }, } } }; var userProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Extension"), new ElementDefinition("Extension.extension") { SliceName = "size" }, new ElementDefinition("Extension.extension.value[x]") { Type = new List<ElementDefinition.TypeRefComponent>() { new ElementDefinition.TypeRefComponent() { Code = FHIRAllTypes.Decimal.GetLiteral() } } }, new ElementDefinition("Extension.extension.url") { Fixed = new FhirUri("size") }, } } }; var snapNav = ElementDefinitionNavigator.ForSnapshot(baseProfile); var diffNav = ElementDefinitionNavigator.ForDifferential(userProfile); // Merge: Extension root var matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Slice: Extension.extension matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); // [WMR 20170406] extension slice entry is inherited from base w/o diff constraints => no match // Only expecting a single match for the additional complex extension element "size" Assert.AreEqual(1, matches.Count); // add one additional complex extension element Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToChild(diffNav.PathName)); assertMatch(matches[0], ElementMatcher.MatchAction.Add, snapNav, diffNav); // Add new extension child element "size" Assert.IsFalse(diffNav.MoveToNext()); } #if false // [WMR 20180604] Disabled; no longer possible due to fix for issue #611 // Does FHIR even allow this? Relevant discussion on Zulip: // https://chat.fhir.org/#narrow/stream/23-conformance/subject/Can.20a.20derived.20profile.20insert.20new.20named.20slices.3F // Grahame Grieve: // "have you seen build\tests\resources\snapshot-generation-tests.xml ? // it doesn't include that, so we can say with confidence that it's not tested behaviour // certainly if the slice is ordered, you cannot insert // if the slicing is not ordered, I don't see what the need for inseertion is" // => Derived profile is NOT allowed to *insert* named slices into an existing slice group [TestMethod] [Ignore] public void TestElementMatcher_ComplexExtension_Insert() { // Insert a child extension element into an existing complex extension definition var baseProfile = new StructureDefinition() { Snapshot = new StructureDefinition.SnapshotComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Extension"), new ElementDefinition("Extension.extension") { Slicing = new ElementDefinition.SlicingComponent() { Discriminator = ForValueSlice("url").ToList() } }, new ElementDefinition("Extension.extension") { SliceName = "name" }, new ElementDefinition("Extension.extension.value[x]") { Type = new List<ElementDefinition.TypeRefComponent>() { new ElementDefinition.TypeRefComponent() { Code = FHIRAllTypes.String.GetLiteral() } } }, new ElementDefinition("Extension.extension.url") { Fixed = new FhirUri("name") }, new ElementDefinition("Extension.extension") { SliceName = "age" }, new ElementDefinition("Extension.extension.value[x]") { Type = new List<ElementDefinition.TypeRefComponent>() { new ElementDefinition.TypeRefComponent() { Code = FHIRAllTypes.Integer.GetLiteral() } } }, new ElementDefinition("Extension.extension.url") { Fixed = new FhirUri("age") }, } } }; var userProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Extension"), new ElementDefinition("Extension.extension") { SliceName = "size" }, new ElementDefinition("Extension.extension.value[x]") { Type = new List<ElementDefinition.TypeRefComponent>() { new ElementDefinition.TypeRefComponent() { Code = FHIRAllTypes.Decimal.GetLiteral() } } }, new ElementDefinition("Extension.extension.url") { Fixed = new FhirUri("size") }, new ElementDefinition("Extension.extension") { SliceName = "name" }, new ElementDefinition("Extension.extension.value[x]") { Type = new List<ElementDefinition.TypeRefComponent>() { new ElementDefinition.TypeRefComponent() { Code = FHIRAllTypes.String.GetLiteral() } } }, new ElementDefinition("Extension.extension.url") { Fixed = new FhirUri("name") }, new ElementDefinition("Extension.extension") { SliceName = "age" }, new ElementDefinition("Extension.extension.value[x]") { Type = new List<ElementDefinition.TypeRefComponent>() { new ElementDefinition.TypeRefComponent() { Code = FHIRAllTypes.Integer.GetLiteral() } } }, new ElementDefinition("Extension.extension.url") { Fixed = new FhirUri("age") }, } } }; var snapNav = ElementDefinitionNavigator.ForSnapshot(baseProfile); var diffNav = ElementDefinitionNavigator.ForDifferential(userProfile); // Merge: Extension root var matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Slice: Extension.extension matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); // [WMR 20170406] extension slice entry is inherited from base w/o diff constraints => no match // Expecting three matches for three additional complex extension elements Assert.AreEqual(3, matches.Count); // three additional complex extension elements Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToChild(diffNav.PathName)); assertMatch(matches[0], ElementMatcher.MatchAction.Add, snapNav, diffNav); // Insert new extension child element "size" Assert.IsTrue(diffNav.MoveToNext()); Assert.IsTrue(snapNav.MoveToNext()); assertMatch(matches[1], ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Merge extension child element "name" Assert.IsTrue(diffNav.MoveToNext()); Assert.IsTrue(snapNav.MoveToNext()); assertMatch(matches[2], ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Merge extension child element "age" Assert.IsFalse(diffNav.MoveToNext()); } #endif [TestMethod] public void TestElementMatcher_ComplexExtension_ConstrainChild() { // Profile with constraint on a child element of a referenced complex extension var baseProfile = new StructureDefinition() { Snapshot = new StructureDefinition.SnapshotComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Extension"), new ElementDefinition("Extension.extension") { Slicing = new ElementDefinition.SlicingComponent() { Discriminator = ForValueSlice("url").ToList() } }, new ElementDefinition("Extension.extension") { SliceName = "parent" }, new ElementDefinition("Extension.extension.extension") { Slicing = new ElementDefinition.SlicingComponent() { Discriminator = ForValueSlice("url").ToList() } }, new ElementDefinition("Extension.extension.extension") { SliceName = "child" }, new ElementDefinition("Extension.extension.extension.value[x]") { Type = new List<ElementDefinition.TypeRefComponent>() { new ElementDefinition.TypeRefComponent() { Code = FHIRAllTypes.Coding.GetLiteral() } } }, new ElementDefinition("Extension.extension.extension.url") { Fixed = new FhirUri("child") }, new ElementDefinition("Extension.extension.value[x]") { Type = new List<ElementDefinition.TypeRefComponent>() { new ElementDefinition.TypeRefComponent() { Code = FHIRAllTypes.String.GetLiteral() } } }, new ElementDefinition("Extension.extension.url") { Fixed = new FhirUri("parent") }, } } }; var userProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Extension"), new ElementDefinition("Extension.extension") { SliceName = "parent" }, new ElementDefinition("Extension.extension.extension") { SliceName = "child" }, new ElementDefinition("Extension.extension.extension.valueCoding") { Min = 1, Type = new List<ElementDefinition.TypeRefComponent>() { new ElementDefinition.TypeRefComponent() { Code = FHIRAllTypes.Coding.GetLiteral() } } } } } }; var snapNav = ElementDefinitionNavigator.ForSnapshot(baseProfile); var diffNav = ElementDefinitionNavigator.ForDifferential(userProfile); // Merge: Extension root var matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Slice: Extension.extension matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); // [WMR 20170406] extension slice entry is inherited from base w/o diff constraints => no match // Expecting a single match for "parent" Assert.AreEqual(1, matches.Count); // three additional complex extension elements Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToChild(diffNav.PathName)); Assert.IsTrue(snapNav.MoveToNext()); Assert.AreEqual("parent", snapNav.Current.SliceName); Assert.AreEqual("parent", diffNav.Current.SliceName); assertMatch(matches[0], ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Merge extension child element "parent" matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToNext()); Assert.AreEqual("child", snapNav.Current.SliceName); Assert.AreEqual("child", diffNav.Current.SliceName); assertMatch(matches[0], ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Merge extension child element "child" matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(snapNav.MoveToFirstChild()); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.AreEqual("value[x]", snapNav.PathName); Assert.AreEqual("valueCoding", diffNav.PathName); assertMatch(matches[0], ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Merge extension child element valueCoding } [TestMethod] public void TestElementMatcher_Patient_Animal_Slice() { // Slice Patient.animal (named) var baseProfile = _testResolver.FindStructureDefinitionForCoreType(FHIRAllTypes.Patient); var userProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Patient"), new ElementDefinition("Patient.animal") { Slicing = new ElementDefinition.SlicingComponent() { Discriminator = ForValueSlice("species.coding.code").ToList() } }, new ElementDefinition("Patient.animal") { SliceName = "dog" } } } }; var snapNav = ElementDefinitionNavigator.ForSnapshot(baseProfile); var diffNav = ElementDefinitionNavigator.ForDifferential(userProfile); // Merge: Patient root var matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Slice: Patient.animal matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); Assert.AreEqual(2, matches.Count); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToChild(diffNav.PathName)); assertMatch(matches[0], ElementMatcher.MatchAction.Slice, snapNav, diffNav); // Extension slice entry Assert.IsTrue(diffNav.MoveToNext()); // Don't advance snapNav; new diff slice is merged with default base = snap slice entry assertMatch(matches[1], ElementMatcher.MatchAction.Add, snapNav, diffNav); // Define new slice } [TestMethod] public void TestElementMatcher_Patient_Animal_Slice_Override() { // Constrain existing slice on Patient.animal (named) var baseProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Patient"), new ElementDefinition("Patient.animal") { Slicing = new ElementDefinition.SlicingComponent() { Discriminator = ForValueSlice("species.coding.code").ToList() } }, new ElementDefinition("Patient.animal") { SliceName = "dog" } } } }; var userProfile = (StructureDefinition)baseProfile.DeepCopy(); userProfile.Differential.Element[2].Min = 1; var snapNav = ElementDefinitionNavigator.ForDifferential(baseProfile); var diffNav = ElementDefinitionNavigator.ForDifferential(userProfile); // Merge: Patient root var matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Slice: Patient.animal matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); Assert.AreEqual(2, matches.Count); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToChild(diffNav.PathName)); assertMatch(matches[0], ElementMatcher.MatchAction.Slice, snapNav, diffNav); // Extension slice entry Assert.IsTrue(diffNav.MoveToNext()); Assert.IsTrue(snapNav.MoveToNext()); assertMatch(matches[1], ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Merge existing new slice } [TestMethod] public void TestElementMatcher_Patient_Animal_Slice_Override_NoEntry() { // Constrain existing slice on Patient.animal (named) // Similar to previous, but differential does NOT provide a slice entry // Not strictly necessary, as it is implied by the base var baseProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Patient"), new ElementDefinition("Patient.animal") { Slicing = new ElementDefinition.SlicingComponent() { Discriminator = ForValueSlice("species.coding.code").ToList() } }, new ElementDefinition("Patient.animal") { SliceName = "dog" } } } }; var userProfile = (StructureDefinition)baseProfile.DeepCopy(); // Remove slice entry from diff userProfile.Differential.Element.RemoveAt(1); userProfile.Differential.Element[1].Min = 1; var snapNav = ElementDefinitionNavigator.ForDifferential(baseProfile); var diffNav = ElementDefinitionNavigator.ForDifferential(userProfile); // Merge: Patient root var matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Slice: Patient.animal matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); Assert.AreEqual(1, matches.Count); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToChild(diffNav.PathName)); // diff has no slice entry; no match Assert.IsTrue(snapNav.MoveToNext()); // Skip base slice entry assertMatch(matches[0], ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Merge existing new slice } [TestMethod] public void TestElementMatcher_Patient_Animal_Slice_Add() { // Add a new (named) slice to an existing slice on Patient.animal var baseProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Patient"), new ElementDefinition("Patient.animal") { Slicing = new ElementDefinition.SlicingComponent() { Discriminator = ForValueSlice("species.coding.code").ToList() } }, new ElementDefinition("Patient.animal") { SliceName = "dog" } } } }; var userProfile = (StructureDefinition)baseProfile.DeepCopy(); userProfile.Differential.Element[2].SliceName = "cat"; var snapNav = ElementDefinitionNavigator.ForDifferential(baseProfile); var diffNav = ElementDefinitionNavigator.ForDifferential(userProfile); // Merge: Patient root var matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Slice: Patient.animal matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); Assert.AreEqual(2, matches.Count); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToChild(diffNav.PathName)); assertMatch(matches[0], ElementMatcher.MatchAction.Slice, snapNav, diffNav); // Extension slice entry Assert.IsTrue(diffNav.MoveToNext()); // Don't advance snapNav; new diff slice is merged with default base = snap slice entry assertMatch(matches[1], ElementMatcher.MatchAction.Add, snapNav, diffNav); // Add new slice } [TestMethod] public void TestElementMatcher_Patient_Animal_Slice_Insert() { // Insert a new (named) slice into an existing slice on Patient.animal var baseProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Patient"), new ElementDefinition("Patient.animal") { Slicing = new ElementDefinition.SlicingComponent() { Discriminator = ForValueSlice("species.coding.code").ToList() } }, new ElementDefinition("Patient.animal") { SliceName = "dog" } } } }; var userProfile = (StructureDefinition)baseProfile.DeepCopy(); var slice = (ElementDefinition)userProfile.Differential.Element[2].DeepCopy(); slice.SliceName = "cat"; userProfile.Differential.Element.Insert(2, slice); var snapNav = ElementDefinitionNavigator.ForDifferential(baseProfile); var diffNav = ElementDefinitionNavigator.ForDifferential(userProfile); // Merge: Patient root var matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Slice: Patient.animal matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); Assert.AreEqual(3, matches.Count); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToChild(diffNav.PathName)); assertMatch(matches[0], ElementMatcher.MatchAction.Slice, snapNav, diffNav); // Extension slice entry Assert.IsTrue(diffNav.MoveToNext()); // Don't advance snapNav; new diff slice is merged with default base = snap slice entry assertMatch(matches[1], ElementMatcher.MatchAction.Add, snapNav, diffNav); // Insert new slice Assert.IsTrue(diffNav.MoveToNext()); Assert.IsTrue(snapNav.MoveToNext()); assertMatch(matches[2], ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Merge existing slice } [TestMethod] public void TestElementMatcher_Patient_Animal_Reslice() { // Reslice an existing (named) slice on Patient.animal var baseProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Patient"), new ElementDefinition("Patient.animal") { Slicing = new ElementDefinition.SlicingComponent() { Discriminator = ForValueSlice("species.coding.code").ToList() } }, new ElementDefinition("Patient.animal") { SliceName = "dog" }, new ElementDefinition("Patient.animal") { SliceName = "cat" } } } }; var userProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Patient"), new ElementDefinition("Patient.animal") { Slicing = new ElementDefinition.SlicingComponent() { Discriminator = ForValueSlice("species.coding.code").ToList() } }, new ElementDefinition("Patient.animal") { SliceName = "dog", Slicing = new ElementDefinition.SlicingComponent() { Discriminator = ForValueSlice("breed").ToList() } }, new ElementDefinition("Patient.animal") { SliceName = "dog/schnautzer" }, new ElementDefinition("Patient.animal") { SliceName = "dog/dachshund" } } } }; var snapNav = ElementDefinitionNavigator.ForDifferential(baseProfile); var diffNav = ElementDefinitionNavigator.ForDifferential(userProfile); // Merge: Patient root var matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Reslice: Patient.animal matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); Assert.AreEqual(4, matches.Count); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToChild(diffNav.PathName)); assertMatch(matches[0], ElementMatcher.MatchAction.Slice, snapNav, diffNav); // Slice entry Assert.IsTrue(diffNav.MoveToNext()); Assert.IsTrue(snapNav.MoveToNext()); assertMatch(matches[1], ElementMatcher.MatchAction.Slice, snapNav, diffNav); // Re-slice entry Assert.IsTrue(diffNav.MoveToNext()); // Don't advance snapNav; new diff slice is merged with default base = snap slice entry assertMatch(matches[2], ElementMatcher.MatchAction.Add, snapNav, diffNav); // Add new slice to reslice Assert.IsTrue(diffNav.MoveToNext()); // Don't advance snapNav; new diff slice is merged with default base = snap slice entry assertMatch(matches[3], ElementMatcher.MatchAction.Add, snapNav, diffNav); // Add new slice to reslice } [TestMethod] public void TestElementMatcher_Patient_Animal_Nested_Slice() { // Introduce a nested (named) slice within an existing (named) slice on Patient.animal var baseProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Patient"), new ElementDefinition("Patient.animal") { Slicing = new ElementDefinition.SlicingComponent() { Discriminator = ForValueSlice("species.coding.code").ToList() } }, new ElementDefinition("Patient.animal") { SliceName = "dog" }, new ElementDefinition("Patient.animal.breed"), new ElementDefinition("Patient.animal") { SliceName = "cat" }, new ElementDefinition("Patient.animal.breed") } } }; var userProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Patient"), // Is slice entry required? We're not reslicing animal... new ElementDefinition("Patient.animal") { Slicing = new ElementDefinition.SlicingComponent() { Discriminator = ForValueSlice("species.coding.code").ToList() } }, new ElementDefinition("Patient.animal") { SliceName = "dog" }, new ElementDefinition("Patient.animal.breed") { Slicing = new ElementDefinition.SlicingComponent() { Discriminator = ForValueSlice("coding.code").ToList() } }, new ElementDefinition("Patient.animal.breed") { SliceName="schnautzer" }, new ElementDefinition("Patient.animal.breed") { SliceName="dachshund" }, } } }; var snapNav = ElementDefinitionNavigator.ForDifferential(baseProfile); var diffNav = ElementDefinitionNavigator.ForDifferential(userProfile); // Merge: Patient root var matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Slice: Patient.animal matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); Assert.AreEqual(2, matches.Count); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToChild(diffNav.PathName)); assertMatch(matches[0], ElementMatcher.MatchAction.Slice, snapNav, diffNav); // Slice entry Assert.IsTrue(diffNav.MoveToNext()); Assert.IsTrue(snapNav.MoveToNext()); assertMatch(matches[1], ElementMatcher.MatchAction.Merge, snapNav, diffNav); // First slice Assert.AreEqual("dog", diffNav.Current.SliceName); // Nested slice: Patient.animal.breed matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); Assert.AreEqual(3, matches.Count); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches[0], ElementMatcher.MatchAction.Slice, snapNav, diffNav); // New nested slice entry Assert.IsTrue(diffNav.MoveToNext()); // Don't advance snapNav (not sliced) Assert.IsFalse(snapNav.MoveToNext()); assertMatch(matches[1], ElementMatcher.MatchAction.Add, snapNav, diffNav); // First new nested slice Assert.AreEqual("schnautzer", diffNav.Current.SliceName); Assert.IsTrue(diffNav.MoveToNext()); // Don't advance snapNav (not sliced) assertMatch(matches[2], ElementMatcher.MatchAction.Add, snapNav, diffNav); // Second new nested slice Assert.AreEqual("dachshund", diffNav.Current.SliceName); Assert.IsFalse(diffNav.MoveToNext()); // Don't advance snapNav (not sliced) } // [WMR 20170718] New: Match constraint on existing slice entry [TestMethod] public void TestElementMatcher_ConstraintOnExistingSliceEntry() { var baseProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Patient"), new ElementDefinition("Patient.identifier") { Slicing = new ElementDefinition.SlicingComponent() { Description = "TEST" }, }, new ElementDefinition("Patient.identifier") { SliceName = "bsn" } } } }; var userProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Patient"), // Constraint on inherited slice entry new ElementDefinition("Patient.identifier") { Min = 1 }, // Constraint on inherited slice new ElementDefinition("Patient.identifier") { SliceName = "bsn" }, // Introduce new slice new ElementDefinition("Patient.identifier") { SliceName = "ehrid" } } } }; var snapNav = ElementDefinitionNavigator.ForDifferential(baseProfile); var diffNav = ElementDefinitionNavigator.ForDifferential(userProfile); // Merge: Patient root var matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Slice entry: Patient.identifier matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); Assert.AreEqual(3, matches.Count); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToChild(diffNav.PathName)); assertMatch(matches[0], ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Constraint on slice entry var snapSliceEntryBookmark = snapNav.Bookmark(); Assert.IsTrue(diffNav.MoveToNext()); Assert.IsTrue(snapNav.MoveToNext()); assertMatch(matches[1], ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Constraint on first slice Assert.AreEqual("bsn", diffNav.Current.SliceName); // New slice: Patient.identifier:ehrid Assert.IsTrue(diffNav.MoveToNext()); Assert.IsFalse(snapNav.MoveToNext()); Assert.IsTrue(snapNav.ReturnToBookmark(snapSliceEntryBookmark)); assertMatch(matches[2], ElementMatcher.MatchAction.Add, snapNav, diffNav); // New slice Assert.AreEqual("ehrid", diffNav.Current.SliceName); Assert.IsFalse(diffNav.MoveToNext()); } // [WMR 20170927] New: match layered constraints on choice types [TestMethod] public void TestElementMatcher_ChoiceType1() { var baseProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Observation"), new ElementDefinition("Observation.value[x]") } } }; var userProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Observation"), new ElementDefinition("Observation.value[x]") } } }; var snapNav = ElementDefinitionNavigator.ForDifferential(baseProfile); var diffNav = ElementDefinitionNavigator.ForDifferential(userProfile); // Merge: Observation root var matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Merge: Observation.value[x] matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); // Verify: B:value[x] <-- merge --> D:value[x] Assert.AreEqual(1, matches.Count); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches[0], ElementMatcher.MatchAction.Merge, snapNav, diffNav); } [TestMethod] public void TestElementMatcher_ChoiceType2() { var baseProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Observation"), new ElementDefinition("Observation.valueString") } } }; var userProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Observation"), new ElementDefinition("Observation.valueString") } } }; var snapNav = ElementDefinitionNavigator.ForDifferential(baseProfile); var diffNav = ElementDefinitionNavigator.ForDifferential(userProfile); // Merge: Observation root var matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Merge: Observation.valueString matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); // Verify: B:valueString <-- merge --> D:valueString Assert.AreEqual(1, matches.Count); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches[0], ElementMatcher.MatchAction.Merge, snapNav, diffNav); } [TestMethod] public void TestElementMatcher_ChoiceType3() { var baseProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Observation"), new ElementDefinition("Observation.value[x]") } } }; var userProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Observation"), new ElementDefinition("Observation.valueString") } } }; // 2. Verify: match value[x] in derived profile to valueString in base profile var snapNav = ElementDefinitionNavigator.ForDifferential(baseProfile); var diffNav = ElementDefinitionNavigator.ForDifferential(userProfile); // Merge: Observation root var matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Merge: Observation.value[x] matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); // Verify: B:value[x] <-- merge --> D:valueString Assert.AreEqual(1, matches.Count); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches[0], ElementMatcher.MatchAction.Merge, snapNav, diffNav); } [TestMethod] public void TestElementMatcher_ChoiceType4() { var baseProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Observation"), new ElementDefinition("Observation.valueString") } } }; var userProfile = new StructureDefinition() { Differential = new StructureDefinition.DifferentialComponent() { Element = new List<ElementDefinition>() { new ElementDefinition("Observation"), // STU3: INVALID! // If the inherited element is already renamed, then derived profile MUST use new name new ElementDefinition("Observation.value[x]") } } }; var snapNav = ElementDefinitionNavigator.ForDifferential(baseProfile); var diffNav = ElementDefinitionNavigator.ForDifferential(userProfile); // Merge: Observation root var matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); assertMatch(matches, ElementMatcher.MatchAction.Merge, snapNav, diffNav); // Base profile renames value[x] to valueString // Derived profile refers to value[x] - WRONG! SHALL refer to valueString // Expected behavior: add new constraint for value[x] next to existing valueString constraint // This actually creates a profile that is invalid in STU3, but the validator will handle that // STU3: only rename choice type elements if constrained to a single type // R4: allow combinations of constraints on both value[x] and on renamed type slices // Add: Observation.value[x] matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); // Verify: B:Observation <-- new --> D:value[x] Assert.AreEqual(1, matches.Count); Assert.IsTrue(diffNav.MoveToFirstChild()); var match = matches[0]; assertMatch(match, ElementMatcher.MatchAction.New, snapNav, diffNav); // Verify: matcher should emit a warning Assert.IsNotNull(match.Issue); Debug.Print(match.Issue.Details?.Text); Assert.IsTrue(int.TryParse(match.Issue.Details?.Coding?[0]?.Code, out int code)); Assert.AreEqual(SnapshotGenerator.PROFILE_ELEMENTDEF_INVALID_CHOICETYPE_NAME.Code, code); } // ========== Helper functions ========== // Recursively match diffNav to snapNav and verify that all matches return the specified action (def. Merged) static List<ElementMatcher.MatchInfo> matchAndVerify(ElementDefinitionNavigator snapNav, ElementDefinitionNavigator diffNav, ElementMatcher.MatchAction action = ElementMatcher.MatchAction.Merge) { List<ElementMatcher.MatchInfo> matches = ElementMatcher.Match(snapNav, diffNav); Assert.IsTrue(diffNav.MoveToFirstChild()); Assert.IsTrue(snapNav.MoveToFirstChild()); for (int i = 0; i < matches.Count; i++) { matches[i].DumpMatch(snapNav, diffNav); assertMatch(matches[i], action, snapNav, diffNav); snapNav.ReturnToBookmark(matches[i].BaseBookmark); diffNav.ReturnToBookmark(matches[i].DiffBookmark); Assert.AreEqual(snapNav.HasChildren, diffNav.HasChildren); if (snapNav.HasChildren) { matchAndVerify(snapNav, diffNav); snapNav.ReturnToBookmark(matches[i].BaseBookmark); diffNav.ReturnToBookmark(matches[i].DiffBookmark); } bool notLastMatch = i < matches.Count - 1; Assert.AreEqual(notLastMatch, snapNav.MoveToNext()); Assert.AreEqual(notLastMatch, diffNav.MoveToNext()); } return matches; } static void assertMatch(List<ElementMatcher.MatchInfo> matches, ElementMatcher.MatchAction action, ElementDefinitionNavigator snapNav, ElementDefinitionNavigator diffNav) { Assert.IsNotNull(matches); matches.DumpMatches(snapNav, diffNav); Assert.AreEqual(1, matches.Count); assertMatch(matches[0], action, snapNav, diffNav); } static void assertMatch(ElementMatcher.MatchInfo match, ElementMatcher.MatchAction action, ElementDefinitionNavigator snapNav, ElementDefinitionNavigator diffNav = null) { assertMatch(match, action, snapNav.Bookmark(), diffNav != null ? diffNav.Bookmark() : Bookmark.Empty); } static void assertMatch(ElementMatcher.MatchInfo match, ElementMatcher.MatchAction action, Bookmark snap, Bookmark diff) { Assert.IsNotNull(match); Assert.AreEqual(action, match.Action); Assert.AreEqual(snap, match.BaseBookmark); Assert.AreEqual(diff, match.DiffBookmark); } } }
50.389928
202
0.566817
[ "BSD-3-Clause" ]
CASPA-Care/caspa-fhir-net-api
src/Hl7.Fhir.Specification.Tests/Snapshot/SnapshotElementMatcherTests.cs
70,044
C#
using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Flurl; using Semver; namespace NexusUploader.Nexus.Services { public class ApiClient { private readonly HttpClient _httpClient; public ApiClient(HttpClient httpClient) { _httpClient = httpClient; } public async Task<int> GetGameId(string gameName, string apiKey) { using (var req = new HttpRequestMessage(HttpMethod.Get, $"games/{gameName}.json")) { req.Headers.Add("apikey", apiKey); var resp = await _httpClient.SendAsync(req); var dict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(await resp.Content.ReadAsStringAsync()); var latest = dict["id"].ToString(); return int.Parse(latest); } } public async Task<bool> CheckValidKey(string apiKey) { using (var req = new HttpRequestMessage(HttpMethod.Get, "users/validate.json")) { req.Headers.Add("apikey", apiKey); var resp = await _httpClient.SendAsync(req); if (resp.IsSuccessStatusCode) { var dict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(await resp.Content.ReadAsStringAsync()); return !string.IsNullOrWhiteSpace(dict["name"].ToString()) && dict["key"].ToString() == apiKey; } else { return false; } } } public async Task<int?> GetLatestFileId(string gameName, int modId, string apiKey) { try { using (var req = new HttpRequestMessage(HttpMethod.Get, $"games/{gameName}/mods/{modId}/files.json")) { req.Headers.Add("apikey", apiKey); var resp = await _httpClient.SendAsync(req); var dict = System.Text.Json.JsonSerializer.Deserialize<Nexus.NexusFilesResponse>(await resp.Content.ReadAsStringAsync()); var mainFiles = dict.Files.Where(f => f.CategoryName != null && f.CategoryName == "MAIN").ToList(); if (mainFiles.Count == 1) { //well that was easy return mainFiles.First().FileId; } else { var semvers = mainFiles.Select(mf => (mf.FileVersion, SemVersion.Parse(mf.FileVersion))).ToList(); semvers.Sort((r1, r2) => { if (r1.Item2 == null && r2.Item2 == null) return 0; if (r1.Item2 == null) return -1; if (r2.Item2 == null) return 1; return r1.Item2.CompareByPrecedence(r2.Item2); }); // semvers.Reverse(); var highestV = mainFiles.FirstOrDefault(f => f.FileVersion == semvers.Last().FileVersion); return highestV.FileId; } } } catch (System.Exception) { return null; } } } }
41.256098
143
0.507538
[ "MIT" ]
focustense/nexus-uploader
src/NexusUploader/Services/ApiClient.cs
3,383
C#
using System.Net; using Content.Server.IP; using NUnit.Framework; namespace Content.Tests.Server.Utility { public class IPAddressExtTest { [Test] [TestCase("192.168.5.85/24", "192.168.5.1")] [TestCase("192.168.5.85/24", "192.168.5.254")] [TestCase("10.128.240.50/30", "10.128.240.48")] [TestCase("10.128.240.50/30", "10.128.240.49")] [TestCase("10.128.240.50/30", "10.128.240.50")] [TestCase("10.128.240.50/30", "10.128.240.51")] public void IpV4SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress) { var ipAddressObj = IPAddress.Parse(ipAddress); Assert.That(ipAddressObj.IsInSubnet(netMask), Is.True); } [Test] [TestCase("192.168.5.85/24", "192.168.4.254")] [TestCase("192.168.5.85/24", "191.168.5.254")] [TestCase("10.128.240.50/30", "10.128.240.47")] [TestCase("10.128.240.50/30", "10.128.240.52")] [TestCase("10.128.240.50/30", "10.128.239.50")] [TestCase("10.128.240.50/30", "10.127.240.51")] public void IpV4SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress) { var ipAddressObj = IPAddress.Parse(ipAddress); Assert.That(ipAddressObj.IsInSubnet(netMask), Is.False); } // ReSharper disable StringLiteralTypo [Test] [TestCase("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:0000:0000:0000:0000")] [TestCase("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:FFFF:FFFF:FFFF:FFFF")] [TestCase("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:0001:0000:0000:0000")] [TestCase("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:FFFF:FFFF:FFFF:FFF0")] [TestCase("2001:db8:abcd:0012::0/128", "2001:0DB8:ABCD:0012:0000:0000:0000:0000")] public void IpV6SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress) { var ipAddressObj = IPAddress.Parse(ipAddress); Assert.That(ipAddressObj.IsInSubnet(netMask), Is.True); } [Test] [TestCase("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0011:FFFF:FFFF:FFFF:FFFF")] [TestCase("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0013:0000:0000:0000:0000")] [TestCase("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0013:0001:0000:0000:0000")] [TestCase("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0011:FFFF:FFFF:FFFF:FFF0")] [TestCase("2001:db8:abcd:0012::0/128", "2001:0DB8:ABCD:0012:0000:0000:0000:0001")] // ReSharper restore StringLiteralTypo public void IpV6SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress) { var ipAddressObj = IPAddress.Parse(ipAddress); Assert.That(ipAddressObj.IsInSubnet(netMask), Is.False); } } }
45.903226
96
0.622628
[ "MIT" ]
A-Box-12/space-station-14
Content.Tests/Server/Utility/IPAddressExtTest.cs
2,848
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("EXER_SumBigNumbers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EXER_SumBigNumbers")] [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("fc2840f0-36e3-4f52-9b37-34444d6b66b2")] // 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.945946
84
0.75
[ "MIT" ]
mayapeneva/C-Sharp-Advanced
05.ManualStringProcessing/EXER_SumBigNumbers/Properties/AssemblyInfo.cs
1,407
C#
using System.Collections.Generic; namespace JackSParrot.Services.Network.Commands { public interface ICommandQueue : System.IDisposable { void AddCommand(Command command); void Send(); bool IsPaused(); void Pause(); void Resume(); } public class CommandQueue : ICommandQueue { bool _paused = false; string _baseUrl = ""; readonly Queue<Command> _commands = new Queue<Command>(); IHttpClient _client = null; System.Text.StringBuilder _stringBuilder = new System.Text.StringBuilder(); public bool Pending { get { return _commands.Count > 0; } } public CommandQueue(IHttpClient client, string baseUrl) { _baseUrl = baseUrl; _client = client; } public bool IsPaused() { return _paused; } public void Pause() { _paused = true; } public void Resume() { _paused = false; } public void AddCommand(Command command) { _commands.Enqueue(command); if(command.IsUrgent) { Send(); } } public void Send() { DoSend(); } void DoSend() { if(_commands.Count < 1 || _paused) { return; } CommandPacket packet = new CommandPacket(); while(Pending) { packet.AddCommand(_commands.Dequeue()); } Petition p = new Petition(_baseUrl, Petition.SendMethod.Post); _stringBuilder.Length = 0; packet.Serialize(_stringBuilder); p.SetData(_stringBuilder.ToString()); _client.Send(p, (petition) => OnPacketFinished(petition, packet)); } void OnPacketFinished(Petition pet, CommandPacket packet) { packet.ParseResponse(pet.GetResponse(), pet.Error); Utils.SharedServices.GetService<EventTracker>()?.PersistPending(); } public void Dispose() { } } }
23.926316
83
0.50198
[ "MIT" ]
JackSParrot/commands-pkg
Runtime/CommandQueue.cs
2,273
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Integration.AspNet.Core; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace Microsoft.BotBuilderSamples { public class AdapterWithErrorHandler : BotFrameworkHttpAdapter { public AdapterWithErrorHandler(IConfiguration configuration, ILogger<BotFrameworkHttpAdapter> logger) : base(configuration, logger) { OnTurnError = async (turnContext, exception) => { // Log any leaked exception from the application. logger.LogError($"Exception caught : {exception.Message}"); // Send a catch-all apology to the user. await turnContext.SendActivityAsync(exception.Message); }; } } }
33.107143
109
0.675297
[ "MIT" ]
EricDahlvang/teamsProactiveMessaging
AdapterWithErrorHandler.cs
929
C#
namespace Mods { namespace ModsList { public class FirstEditionPilotsMod : Mod { public FirstEditionPilotsMod() { Name = "First Edition Pilots"; Description = "Tycho Celchu as Second Edition pilot"; } } } }
20.8
69
0.5
[ "MIT" ]
97saundersj/FlyCasual
Assets/Scripts/Model/Mods/ModsList/FirstEditionPilots.cs
314
C#
using System.Collections; using System.Collections.Generic; using ScriptEngine.Machine.Contexts; namespace osf { public class FormsCollection : AutoContext<FormsCollection>, ICollectionContext, IEnumerable<ClForm> { private List<ClForm> _list; internal FormsCollection() { _list = new List<ClForm>(); } public void Add(ClForm form) { _list.Add(form); } public bool Remove(ClForm form) { return _list.Remove(form); } [ContextMethod("Получить", "Get")] public ClForm Get(int index) { return this._list[index]; } [ContextProperty("Количество", "Count")] public int CountForm { get { return _list.Count; } } public int Count() { return CountForm; } public CollectionEnumerator GetManagedIterator() { return new CollectionEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<ClForm>)_list).GetEnumerator(); } IEnumerator<ClForm> IEnumerable<ClForm>.GetEnumerator() { foreach (var item in _list) { yield return (item as ClForm); } } } }
22.129032
104
0.534985
[ "MPL-2.0" ]
Nivanchenko/OneScriptForms
OneScriptForms/OneScriptForms/FormsCollection.cs
1,392
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.Serialization.Json; using System.Text; using System.Threading.Tasks; using System.Web; using System.Collections.Specialized; using Fiddler; using Grabacr07.KanColleWrapper.Models.Raw; using Grabacr07.KanColleWrapper.Internal; namespace Grabacr07.KanColleWrapper.Models { public class SvData<T> : RawDataWrapper<svdata<T>> { public NameValueCollection Request { get; private set; } public bool IsSuccess { get { return this.RawData.api_result == 1; } } public T Data { get { return this.RawData.api_data; } } public kcsapi_deck[] Fleets { get { return this.RawData.api_data_deck; } } public SvData(svdata<T> rawData, string reqBody) : base(rawData) { this.Request = HttpUtility.ParseQueryString(reqBody); } } public class SvData : RawDataWrapper<svdata> { public NameValueCollection Request { get; private set; } public bool IsSuccess { get { return this.RawData.api_result == 1; } } public SvData(svdata rawData, string reqBody) : base(rawData) { this.Request = HttpUtility.ParseQueryString(reqBody); } #region Parse methods (generic) public static SvData<T> Parse<T>(Session session) { var bytes = Encoding.UTF8.GetBytes(session.GetResponseAsJson()); var serializer = new DataContractJsonSerializer(typeof(svdata<T>)); using (var stream = new MemoryStream(bytes)) { var rawResult = serializer.ReadObject(stream) as svdata<T>; var result = new SvData<T>(rawResult, session.GetRequestBodyAsString()); return result; } } public static bool TryParse<T>(Session session, out SvData<T> result) { try { result = Parse<T>(session); } catch (Exception ex) { Debug.WriteLine(ex); result = null; return false; } return true; } #endregion #region Parse methods (non generic) public static SvData Parse(Session session) { var bytes = Encoding.UTF8.GetBytes(session.GetResponseAsJson()); var serializer = new DataContractJsonSerializer(typeof(svdata)); using (var stream = new MemoryStream(bytes)) { var rawResult = serializer.ReadObject(stream) as svdata; var result = new SvData(rawResult, session.GetRequestBodyAsString()); return result; } } public static bool TryParse(Session session, out SvData result) { try { result = Parse(session); } catch (Exception ex) { Debug.WriteLine(ex); result = null; return false; } return true; } #endregion } }
22.443548
77
0.655049
[ "MIT" ]
KCV-Localisation/KanColleViewer
Grabacr07.KanColleWrapper/Models/SvData.cs
2,785
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Microsoft.Azure.IIoT.OpcUa.History.Models { using System; /// <summary> /// Read modified data /// </summary> public class ReadModifiedValuesDetailsModel { /// <summary> /// The start time to read from /// </summary> public DateTime? StartTime { get; set; } /// <summary> /// The end time to read to /// </summary> public DateTime? EndTime { get; set; } /// <summary> /// The number of values to read /// </summary> public uint? NumValues { get; set; } } }
29.433333
99
0.493771
[ "MIT" ]
Azure/Industrial-IoT
components/opc-ua/src/Microsoft.Azure.IIoT.OpcUa/src/History/Models/ReadModifiedValuesDetailsModel.cs
883
C#
using System; namespace HotChocolate; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Property | AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Enum | AttributeTargets.Field)] public sealed class GraphQLNameAttribute : Attribute { public GraphQLNameAttribute(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } Name = name; } public string Name { get; } }
21.62963
58
0.683219
[ "MIT" ]
AccountTechnologies/hotchocolate
src/HotChocolate/Core/src/Abstractions/GraphQLNameAttribute.cs
584
C#
using System; using System.Collections.Generic; using System.Text; namespace PyxisInt.GeographicLib { /// <summary> /// The GeodesicData class is used to return the results for a geodesic between /// points 1 and 2. Any fields that have not been set will be denoted by the value /// Double.NaN. The returned GeodesicData always includes the input paramters, the /// latitude &amp; longitude of the points 1 and 2 along with the ArcLength. /// </summary> public class GeodesicData { //Latitude of point 1 in degrees public double Latitude1 { get; set; } //Longitude of point 1 in degrees public double Longitude1 { get; set; } //Azimuth at point 1 in degrees public double InitialAzimuth { get; set; } //Latitude of point 2 in degrees public double Latitude2 { get; set; } //Longitude of point 2 in degrees public double Longitude2 { get; set; } /// <summary> /// Azimuth at point 2 in degrees /// </summary> public double FinalAzimuth { get; set; } /// <summary> /// Distance in meters between points 1 and 2 (s12) /// </summary> public double Distance { get; set; } /// <summary> /// Arc Length in degrees on the auxiliary sphere between points 1 and 2 (a12) /// </summary> public double ArcLength { get; set; } //Reduced length of geodesic in meters public double ReducedLength { get; set; } //Geodesic scale of point 2 relative to point 1 (dimensionless) public double GeodesicScale12 { get; set; } //Geodesic scale of point 1 relative to point 2 (dimensionless) public double GeodesicScale21 { get; set; } //Area in square meters under the geodesic public double AreaUnderGeodesic { get; set; } public GeodesicData() => Latitude1 = Longitude2 = InitialAzimuth = Latitude2 = Longitude2 = FinalAzimuth = Distance = ArcLength = ReducedLength = GeodesicScale12 = GeodesicScale21 = AreaUnderGeodesic = Double.NaN; } }
35.830508
221
0.637181
[ "MIT" ]
Flitesys/GeographicLib
PyxisInt.GeographicLib/GeodesicData.cs
2,116
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using AryuwatSystem.Baselibary; using Entity.Validation; namespace AryuwatSystem.Business { public class Prefix { public DataSet SelectPrefixAll() { var conn = new SqlConnection(DataObject.ConnectionString); conn.Open(); var trn = conn.BeginTransaction(); try { DataSet ds = Data.Prefix.SelectPrefixAll(trn); trn.Commit(); conn.Close(); return ds; } catch (AppException) { return null; } catch (Exception ex) { throw new AppException( "An error occurred while executing the Bussiness.SelectPrefixAll", ex); } } } }
23.717949
90
0.543784
[ "Unlicense" ]
Krailit/Aryuwat_Nurse
AryuwatSystem/Business/Prefix.cs
927
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/dxcore_interface.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="IDXCoreAdapterList" /> struct.</summary> public static unsafe class IDXCoreAdapterListTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="IDXCoreAdapterList" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(IDXCoreAdapterList).GUID, Is.EqualTo(IID_IDXCoreAdapterList)); } /// <summary>Validates that the <see cref="IDXCoreAdapterList" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<IDXCoreAdapterList>(), Is.EqualTo(sizeof(IDXCoreAdapterList))); } /// <summary>Validates that the <see cref="IDXCoreAdapterList" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(IDXCoreAdapterList).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="IDXCoreAdapterList" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(IDXCoreAdapterList), Is.EqualTo(8)); } else { Assert.That(sizeof(IDXCoreAdapterList), Is.EqualTo(4)); } } } }
37.519231
145
0.641722
[ "MIT" ]
phizch/terrafx.interop.windows
tests/Interop/Windows/um/dxcore_interface/IDXCoreAdapterListTests.cs
1,953
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Management.Automation.Configuration; using System.Management.Automation.Internal; using System.Management.Automation.Tracing; using System.Runtime.CompilerServices; namespace System.Management.Automation { /// <summary> /// Support experimental features in PowerShell. /// </summary> public class ExperimentalFeature { #region Const Members internal const string EngineSource = "PSEngine"; #endregion #region Instance Members /// <summary> /// Name of an experimental feature. /// </summary> public string Name { get; } /// <summary> /// Description of an experimental feature. /// </summary> public string Description { get; } /// <summary> /// Source of an experimental feature. /// </summary> public string Source { get; } /// <summary> /// Indicate whether the feature is enabled. /// </summary> public bool Enabled { get; private set; } /// <summary> /// Constructor for ExperimentalFeature. /// </summary> internal ExperimentalFeature(string name, string description, string source, bool isEnabled) { Name = name; Description = description; Source = source; Enabled = isEnabled; } #endregion #region Static Members /// <summary> /// All available engine experimental features. /// </summary> internal static readonly ReadOnlyCollection<ExperimentalFeature> EngineExperimentalFeatures; /// <summary> /// A dictionary of all available engine experimental features. Feature name is the key. /// </summary> internal static readonly ReadOnlyDictionary<string, ExperimentalFeature> EngineExperimentalFeatureMap; /// <summary> /// Experimental feature names that are enabled in the config file. /// </summary> internal static readonly ReadOnlyBag<string> EnabledExperimentalFeatureNames; /// <summary> /// Type initializer. Initialize the engine experimental feature list. /// </summary> static ExperimentalFeature() { // Initialize the readonly collection 'EngineExperimentalFeatures'. var engineFeatures = new ExperimentalFeature[] { /* Register engine experimental features here. Follow the same pattern as the example: new ExperimentalFeature( name: "PSFileSystemProviderV2", description: "Replace the old FileSystemProvider with cleaner design and faster code", source: EngineSource, isEnabled: false), */ new ExperimentalFeature( name: "PSImplicitRemotingBatching", description: "Batch implicit remoting proxy commands to improve performance", source: EngineSource, isEnabled: false), new ExperimentalFeature( name: "PSUseAbbreviationExpansion", description: "Allow tab completion of cmdlets and functions by abbreviation", source: EngineSource, isEnabled: false), new ExperimentalFeature( name: "PSTempDrive", description: "Create TEMP: PS Drive mapped to user's temporary directory path", source: EngineSource, isEnabled: false), }; EngineExperimentalFeatures = new ReadOnlyCollection<ExperimentalFeature>(engineFeatures); // Initialize the readonly dictionary 'EngineExperimentalFeatureMap'. var engineExpFeatureMap = engineFeatures.ToDictionary(f => f.Name, StringComparer.OrdinalIgnoreCase); EngineExperimentalFeatureMap = new ReadOnlyDictionary<string, ExperimentalFeature>(engineExpFeatureMap); // Initialize the readonly hashset 'EnabledExperimentalFeatureNames'. // The initialization of 'EnabledExperimentalFeatureNames' is deliberately made in the type initializer so that: // 1. 'EnabledExperimentalFeatureNames' can be declared as readonly; // 2. No need to deal with initialization from multiple threads; // 3. We don't need to decide where/when to read the config file for the enabled experimental features, // instead, it will be done when the type is used for the first time, which is always earlier than // any experimental features take effect. string[] enabledFeatures = Utils.EmptyArray<string>(); try { enabledFeatures = PowerShellConfig.Instance.GetExperimentalFeatures(); } catch (Exception e) when (LogException(e)) { } EnabledExperimentalFeatureNames = ProcessEnabledFeatures(enabledFeatures); } /// <summary> /// Process the array of enabled feature names retrieved from configuration. /// Ignore invalid feature names and unavailable engine feature names, and /// return an ReadOnlyBag of the valid enabled feature names. /// </summary> private static ReadOnlyBag<string> ProcessEnabledFeatures(string[] enabledFeatures) { if (enabledFeatures.Length == 0) { return ReadOnlyBag<string>.Empty; } var list = new List<string>(enabledFeatures.Length); foreach (string name in enabledFeatures) { if (IsModuleFeatureName(name)) { list.Add(name); } else if (IsEngineFeatureName(name)) { if (EngineExperimentalFeatureMap.TryGetValue(name, out ExperimentalFeature feature)) { feature.Enabled = true; list.Add(name); } else { string message = StringUtil.Format(Logging.EngineExperimentalFeatureNotFound, name); LogError(PSEventId.ExperimentalFeature_InvalidName, name, message); } } else { string message = StringUtil.Format(Logging.InvalidExperimentalFeatureName, name); LogError(PSEventId.ExperimentalFeature_InvalidName, name, message); } } return new ReadOnlyBag<string>(new HashSet<string>(list, StringComparer.OrdinalIgnoreCase)); } /// <summary> /// Log the exception without rewinding the stack. /// </summary> private static bool LogException(Exception e) { LogError(PSEventId.ExperimentalFeature_ReadConfig_Error, e.GetType().FullName, e.Message, e.StackTrace); return false; } /// <summary> /// Log an error message. /// </summary> private static void LogError(PSEventId eventId, params object[] args) { PSEtwLog.LogOperationalError(eventId, PSOpcode.Constructor, PSTask.ExperimentalFeature, PSKeyword.UseAlwaysOperational, args); } /// <summary> /// Check if the name follows the engine experimental feature name convention. /// Convention: prefix 'PS' to the feature name -- 'PSFeatureName'. /// </summary> internal static bool IsEngineFeatureName(string featureName) { return featureName.Length > 2 && featureName.IndexOf('.') == -1 && featureName.StartsWith("PS", StringComparison.Ordinal); } /// <summary> /// Check if the name follows the module experimental feature name convention. /// Convention: prefix the module name to the feature name -- 'ModuleName.FeatureName'. /// </summary> /// <param name="featureName">The feature name to check.</param> /// <param name="moduleName">When specified, we check if the feature name matches the module name.</param> internal static bool IsModuleFeatureName(string featureName, string moduleName = null) { // Feature names cannot start with a dot if (featureName.StartsWith('.')) { return false; } // Feature names must contain a dot, but not at the end int lastDotIndex = featureName.LastIndexOf('.'); if (lastDotIndex == -1 || lastDotIndex == featureName.Length - 1) { return false; } if (moduleName == null) { return true; } // If the module name is given, it must match the prefix of the feature name (up to the last dot). var moduleNamePart = featureName.AsSpan(0, lastDotIndex); return moduleNamePart.Equals(moduleName.AsSpan(), StringComparison.OrdinalIgnoreCase); } /// <summary> /// Determine the action to take for the specified experiment name and action. /// </summary> internal static ExperimentAction GetActionToTake(string experimentName, ExperimentAction experimentAction) { if (experimentName == null || experimentAction == ExperimentAction.None) { // If either the experiment name or action is not defined, then return 'Show' by default. // This could happen to 'ParameterAttribute' when no experimental related field is declared. return ExperimentAction.Show; } ExperimentAction action = experimentAction; if (!IsEnabled(experimentName)) { action = (action == ExperimentAction.Hide) ? ExperimentAction.Show : ExperimentAction.Hide; } return action; } /// <summary> /// Check if the specified experimental feature has been enabled. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsEnabled(string featureName) { return EnabledExperimentalFeatureNames.Contains(featureName); } #endregion } /// <summary> /// Indicates the action to take on the cmdlet/parameter that has the attribute declared. /// </summary> public enum ExperimentAction { /// <summary> /// Represent an undefined action, used as the default value. /// </summary> None = 0, /// <summary> /// Hide the cmdlet/parameter when the corresponding experimental feature is enabled. /// </summary> Hide = 1, /// <summary> /// Show the cmdlet/parameter when the corresponding experimental feature is enabled. /// </summary> Show = 2 } /// <summary> /// The attribute that applies to cmdlet/function/parameter to define what the engine should do with it. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property)] public sealed class ExperimentalAttribute : ParsingBaseAttribute { /// <summary> /// Get name of the experimental feature this attribute is associated with. /// </summary> public string ExperimentName { get; } /// <summary> /// Get action for engine to take when the experimental feature is enabled. /// </summary> public ExperimentAction ExperimentAction { get; } /// <summary> /// Initializes a new instance of the ExperimentalAttribute class. /// </summary> public ExperimentalAttribute(string experimentName, ExperimentAction experimentAction) { ValidateArguments(experimentName, experimentAction); ExperimentName = experimentName; ExperimentAction = experimentAction; } /// <summary> /// Initialize an instance that represents the none-value. /// </summary> private ExperimentalAttribute() {} /// <summary> /// An instance that represents the none-value. /// </summary> internal static readonly ExperimentalAttribute None = new ExperimentalAttribute(); /// <summary> /// Validate arguments for the constructor. /// </summary> internal static void ValidateArguments(string experimentName, ExperimentAction experimentAction) { if (string.IsNullOrEmpty(experimentName)) { string paramName = nameof(experimentName); throw PSTraceSource.NewArgumentNullException(paramName, Metadata.ArgumentNullOrEmpty, paramName); } if (experimentAction == ExperimentAction.None) { string paramName = nameof(experimentAction); string invalidMember = ExperimentAction.None.ToString(); string validMembers = StringUtil.Format("{0}, {1}", ExperimentAction.Hide, ExperimentAction.Show); throw PSTraceSource.NewArgumentException(paramName, Metadata.InvalidEnumArgument, invalidMember, paramName, validMembers); } } internal bool ToHide => EffectiveAction == ExperimentAction.Hide; internal bool ToShow => EffectiveAction == ExperimentAction.Show; /// <summary> /// Get effective action to take at run time. /// </summary> private ExperimentAction EffectiveAction { get { if (_effectiveAction == ExperimentAction.None) { _effectiveAction = ExperimentalFeature.GetActionToTake(ExperimentName, ExperimentAction); } return _effectiveAction; } } private ExperimentAction _effectiveAction = ExperimentAction.None; } }
39.988858
138
0.600794
[ "MIT" ]
mdibrahim2195/PowerShell
src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs
14,356
C#
using System; using System.Collections.Generic; using System.Text; namespace ChuangLan.Account { public class ChuangLanSubAccountManager : IChuangLanSubAccountManager { } }
15.666667
73
0.765957
[ "Apache-2.0" ]
liangshiw/ChuanLan253.Net
src/ChuangLan/Account/ChuangLanSubAccountManager.cs
190
C#
// ----------------------------------------------------------------------------------------- // <copyright file="CloudTableClientTest.cs" company="Microsoft"> // Copyright 2013 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // ----------------------------------------------------------------------------------------- using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using Microsoft.WindowsAzure.Storage.Core.Util; using Microsoft.WindowsAzure.Storage.RetryPolicies; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Microsoft.WindowsAzure.Storage.Table { [TestClass] public class CloudTableClientTest : TableTestBase #if XUNIT , IDisposable #endif { #if XUNIT // Todo: The simple/nonefficient workaround is to minimize change and support Xunit, // removed when we support mstest on projectK public CloudTableClientTest() { MyClassInitialize(null); MyTestInitialize(); } public void Dispose() { MyClassCleanup(); MyTestCleanup(); } #endif #region Locals + Ctors private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } static List<CloudTable> createdTables = new List<CloudTable>(); #endregion #region Additional test attributes // // You can use the following additional attributes as you write your tests: // // Use ClassInitialize to run code before running the first test in the class [ClassInitialize()] public static void MyClassInitialize(TestContext testContext) { CloudTableClient tableClient = GenerateCloudTableClient(); // 20 random tables for (int m = 0; m < 20; m++) { CloudTable tableRef = tableClient.GetTableReference(GenerateRandomTableName()); tableRef.CreateIfNotExistsAsync().Wait(); createdTables.Add(tableRef); } prefixTablesPrefix = "prefixtable" + GenerateRandomTableName(); // 20 tables with known prefix for (int m = 0; m < 20; m++) { CloudTable tableRef = tableClient.GetTableReference(prefixTablesPrefix + m.ToString()); tableRef.CreateIfNotExistsAsync().Wait(); createdTables.Add(tableRef); } } private static string prefixTablesPrefix = null; // Use ClassCleanup to run code after all tests in a class have run [ClassCleanup()] public static void MyClassCleanup() { foreach (CloudTable t in createdTables) { try { t.DeleteIfExistsAsync().Wait(); } catch (Exception) { } } } // // Use TestInitialize to run code before running each test [TestInitialize()] public void MyTestInitialize() { if (TestBase.TableBufferManager != null) { TestBase.TableBufferManager.OutstandingBufferCount = 0; } } // // Use TestCleanup to run code after each test has run [TestCleanup()] public void MyTestCleanup() { if (TestBase.TableBufferManager != null) { Assert.AreEqual(0, TestBase.TableBufferManager.OutstandingBufferCount); } } #endregion #region Ctor Tests [TestMethod] [Description("A test checks constructor of CloudTableClient.")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudTableClientConstructor() { Uri baseAddressUri = new Uri(TestBase.TargetTenantConfig.TableServiceEndpoint); CloudTableClient tableClient = new CloudTableClient(baseAddressUri, TestBase.StorageCredentials); Assert.IsTrue(tableClient.BaseUri.ToString().StartsWith(TestBase.TargetTenantConfig.TableServiceEndpoint)); Assert.AreEqual(TestBase.StorageCredentials, tableClient.Credentials); Assert.AreEqual(AuthenticationScheme.SharedKey, tableClient.AuthenticationScheme); } #endregion #region List Tables Segmented [TestMethod] [Description("Test List Tables Segmented Basic Sync")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public async Task ListTablesSegmentedBasicAsync() { foreach (TablePayloadFormat payloadFormat in Enum.GetValues(typeof(TablePayloadFormat))) { await DoCloudTableDeleteIfExistsAsync(payloadFormat); } } private async Task DoCloudTableDeleteIfExistsAsync(TablePayloadFormat payloadFormat) { CloudTableClient tableClient = GenerateCloudTableClient(); tableClient.DefaultRequestOptions.PayloadFormat = payloadFormat; TableResultSegment segment = null; List<CloudTable> totalResults = new List<CloudTable>(); do { segment = await tableClient.ListTablesSegmentedAsync(segment != null ? segment.ContinuationToken : null); totalResults.AddRange(segment); } while (segment.ContinuationToken != null); // Assert.AreEqual(totalResults.Count, tableClient.ListTables().Count()); } [TestMethod] [Description("Test List Tables Segmented MaxResults Sync")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public async Task ListTablesSegmentedMaxResultsAsync() { foreach (TablePayloadFormat payloadFormat in Enum.GetValues(typeof(TablePayloadFormat))) { await DoListTablesSegmentedMaxResultsAsync(payloadFormat); } } private async Task DoListTablesSegmentedMaxResultsAsync(TablePayloadFormat payloadFormat) { CloudTableClient tableClient = GenerateCloudTableClient(); tableClient.DefaultRequestOptions.PayloadFormat = payloadFormat; TableResultSegment segment = null; List<CloudTable> totalResults = new List<CloudTable>(); int segCount = 0; do { segment = await tableClient.ListTablesSegmentedAsync(string.Empty, 10, segment != null ? segment.ContinuationToken : null, null, null); totalResults.AddRange(segment); segCount++; } while (segment.ContinuationToken != null); // Assert.AreEqual(totalResults.Count, tableClient.ListTables().Count()); Assert.IsTrue(segCount >= totalResults.Count / 10); } [TestMethod] [Description("Test List Tables Segmented With Prefix Sync")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public async Task ListTablesSegmentedWithPrefixAsync() { foreach (TablePayloadFormat payloadFormat in Enum.GetValues(typeof(TablePayloadFormat))) { await DoListTablesSegmentedWithPrefixAsync(payloadFormat); } } private async Task DoListTablesSegmentedWithPrefixAsync(TablePayloadFormat payloadFormat) { CloudTableClient tableClient = GenerateCloudTableClient(); tableClient.DefaultRequestOptions.PayloadFormat = payloadFormat; TableResultSegment segment = null; List<CloudTable> totalResults = new List<CloudTable>(); int segCount = 0; do { segment = await tableClient.ListTablesSegmentedAsync(prefixTablesPrefix, null, segment != null ? segment.ContinuationToken : null, null, null); totalResults.AddRange(segment); segCount++; } while (segment.ContinuationToken != null); Assert.AreEqual(totalResults.Count, 20); foreach (CloudTable tbl in totalResults) { Assert.IsTrue(tbl.Name.StartsWith(prefixTablesPrefix)); } } [TestMethod] [Description("Test List Tables Segmented with Shared Key Lite")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public async Task CloudTableClientListTablesSegmentedSharedKeyLiteAsync() { foreach (TablePayloadFormat payloadFormat in Enum.GetValues(typeof(TablePayloadFormat))) { await DoCloudTableClientListTablesSegmentedSharedKeyLiteAsync(payloadFormat); } } private async Task DoCloudTableClientListTablesSegmentedSharedKeyLiteAsync(TablePayloadFormat payloadFormat) { CloudTableClient tableClient = GenerateCloudTableClient(); tableClient.DefaultRequestOptions.PayloadFormat = payloadFormat; tableClient.AuthenticationScheme = AuthenticationScheme.SharedKeyLite; TableResultSegment segment = null; List<CloudTable> totalResults = new List<CloudTable>(); do { segment = await tableClient.ListTablesSegmentedAsync(segment != null ? segment.ContinuationToken : null); totalResults.AddRange(segment); } while (segment.ContinuationToken != null); Assert.IsTrue(totalResults.Count > 0); } #endregion [TestMethod] [Description("Get service stats")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public async Task CloudTableClientGetServiceStatsAsync() { foreach (TablePayloadFormat payloadFormat in Enum.GetValues(typeof(TablePayloadFormat))) { await DoCloudTableClientGetServiceStatsAsync(payloadFormat); } } private async Task DoCloudTableClientGetServiceStatsAsync(TablePayloadFormat payloadFormat) { AssertSecondaryEndpoint(); CloudTableClient client = GenerateCloudTableClient(); client.DefaultRequestOptions.LocationMode = LocationMode.SecondaryOnly; client.DefaultRequestOptions.PayloadFormat = payloadFormat; TestHelper.VerifyServiceStats(await client.GetServiceStatsAsync()); } [TestMethod] [Description("Testing GetServiceStats with invalid Location Mode - ASYNC")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public async Task CloudTableClientGetServiceStatsInvalidLocAsync() { CloudTableClient client = GenerateCloudTableClient(); client.DefaultRequestOptions.LocationMode = LocationMode.PrimaryOnly; try { TestHelper.VerifyServiceStats(await client.GetServiceStatsAsync()); Assert.Fail("GetServiceStats should fail and throw an InvalidOperationException."); } catch (Exception e) { Assert.IsInstanceOfType(e, typeof(InvalidOperationException)); } } #if !FACADE_NETCORE [TestMethod] [Description("Server timeout query parameter")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public async Task CloudTableClientServerTimeoutAsync() { foreach (TablePayloadFormat payloadFormat in Enum.GetValues(typeof(TablePayloadFormat))) { await DoCloudTableClientServerTimeoutAsync(payloadFormat); } } private async Task DoCloudTableClientServerTimeoutAsync(TablePayloadFormat payloadFormat) { CloudTableClient client = GenerateCloudTableClient(); client.DefaultRequestOptions.PayloadFormat = payloadFormat; string timeout = null; OperationContext context = new OperationContext(); context.SendingRequest += (sender, e) => { IDictionary<string, string> query = HttpWebUtility.ParseQueryString(e.RequestUri.Query); if (!query.TryGetValue("timeout", out timeout)) { timeout = null; } }; TableRequestOptions options = new TableRequestOptions(); await client.GetServicePropertiesAsync(null, context); Assert.IsNull(timeout); await client.GetServicePropertiesAsync(options, context); Assert.IsNull(timeout); options.ServerTimeout = TimeSpan.FromSeconds(100); await client.GetServicePropertiesAsync(options, context); Assert.AreEqual("100", timeout); client.DefaultRequestOptions.ServerTimeout = TimeSpan.FromSeconds(90); await client.GetServicePropertiesAsync(null, context); Assert.AreEqual("90", timeout); await client.GetServicePropertiesAsync(options, context); Assert.AreEqual("100", timeout); options.ServerTimeout = null; await client.GetServicePropertiesAsync(options, context); Assert.AreEqual("90", timeout); options.ServerTimeout = TimeSpan.Zero; await client.GetServicePropertiesAsync(options, context); Assert.IsNull(timeout); } #endif } }
40.421446
159
0.633784
[ "Apache-2.0" ]
Meertman/azure-storage-net
Test/WindowsRuntime/Table/CloudTableClientTest.cs
16,211
C#
// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. // // To add a suppression to this file, right-click the message in the // Error List, point to "Suppress Message(s)", and click // "In Project Suppression File". // You do not need to add suppressions to this file manually. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields", Scope = "member", Target = "ImageTools.IO.Gif.GifLogicalScreenDescriptor.#Background")]
57
206
0.766082
[ "MIT" ]
kevingosse/Imageboard-Browser
ImageTools/Source/src/ImageTools/ImageTools.IO.Gif/GlobalSuppressions.cs
686
C#
using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using OrchardCore.DisplayManagement.Handlers; using OrchardCore.Modules; using OrchardCore.Users.Models; using OrchardCore.Users.TimeZone.Drivers; using OrchardCore.Users.TimeZone.Services; namespace OrchardCore.Users.TimeZone { [Feature("OrchardCore.Users.TimeZone")] public class Startup : StartupBase { public override void Configure(IApplicationBuilder builder, IRouteBuilder routes, IServiceProvider serviceProvider) { } public override void ConfigureServices(IServiceCollection services) { services.AddScoped<ITimeZoneSelector, UserTimeZoneSelector>(); services.AddScoped<UserTimeZoneService>(); services.AddScoped<IDisplayDriver<User>, UserTimeZoneDisplayDriver>(); } } }
34.576923
127
0.764182
[ "BSD-3-Clause" ]
1426463237/OrchardCore
src/OrchardCore.Modules/OrchardCore.Users/TimeZone/Startup.cs
899
C#
// // Swiss QR Bill Generator for .NET // Copyright (c) 2018 Manuel Bleichenbacher // Licensed under MIT License // https://opensource.org/licenses/MIT // using Codecrete.SwissQRBill.Generator; using System; using Xunit; namespace Codecrete.SwissQRBill.GeneratorTest { public class RemoveWhitespaceTest { [Fact] private void EmptyString() { Assert.Equal("", "".WhiteSpaceRemoved()); } [Fact] private void OneSpace() { Assert.Equal("", " ".WhiteSpaceRemoved()); } [Fact] private void SeveralSpaces() { Assert.Equal("", " ".WhiteSpaceRemoved()); } [Fact] private void NoWhitespace() { Assert.Equal("abcd", "abcd".WhiteSpaceRemoved()); } [Fact] private void LeadingSpace() { Assert.Equal("fggh", " fggh".WhiteSpaceRemoved()); } [Fact] private void MultipleLeadingSpaces() { Assert.Equal("jklm", " jklm".WhiteSpaceRemoved()); } [Fact] private void TrailingSpace() { Assert.Equal("nppo", "nppo ".WhiteSpaceRemoved()); } [Fact] private void MultipleTrailingSpaces() { Assert.Equal("qrs", "qrs ".WhiteSpaceRemoved()); } [Fact] private void LeadingAndTrailingSpaces() { Assert.Equal("guj", " guj ".WhiteSpaceRemoved()); } [Fact] private void SingleSpace() { Assert.Equal("abde", "ab de".WhiteSpaceRemoved()); } [Fact] private void MultipleSpaces() { Assert.Equal("cdef", "cd ef".WhiteSpaceRemoved()); } [Fact] private void MultipleGroupsOfSpaces() { Assert.Equal("ghijkl", "gh ij kl".WhiteSpaceRemoved()); } [Fact] private void LeadingAndMultipleGroupsOfSpaces() { Assert.Equal("opqrst", " op qr s t".WhiteSpaceRemoved()); } [Fact] private void LeadingAndTrailingAndMultipleGroupsOfSpaces() { Assert.Equal("uvxyz", " uv x y z ".WhiteSpaceRemoved()); } [Fact] private void CopyAvoidance() { string value = "qwerty"; Assert.Same(value, value.WhiteSpaceRemoved()); } [Fact] private void NullString() { Assert.Throws<NullReferenceException>(() => ((string)null).WhiteSpaceRemoved()); } } }
23.184211
92
0.515323
[ "MIT" ]
ChrisBerna/SwissQRBill.NET
GeneratorTest/RemoveWhitespaceTest.cs
2,645
C#
// ------------------------------------------------------------------------------------------------- // Simple Version Control - © Copyright 2020 - Jam-Es.com // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using System; using System.Windows; using System.Windows.Controls; using HL.Interfaces; using HL.Manager; using Newtonsoft.Json.Linq; namespace SimpleVersionControl.App.UserControls.ContentAreaControls { /// <summary> /// Interaction logic for ChangePage.xaml /// </summary> public partial class ChangePage : UserControl { private bool eventBlock = false; private ChangeRef openChangeRef; private VersionRef versionRef; public ChangePage() { InitializeComponent(); IThemedHighlightingManager hm = ThemedHighlightingManager.Instance; hm.SetCurrentTheme("VS2019_Dark"); AdditionalDataField.SyntaxHighlighting = hm.GetDefinitionByExtension(".js"); } public static ChangePage GetInstance() { return ContentArea.GetInstance().ChangePage; } public void Refresh(ChangeRef changeRef) { AdditionalDataExpander.IsExpanded = false; openChangeRef = changeRef; Change change = changeRef.GetChange().Result; versionRef = change.ReleaseVersion; VersionText.Text = $"Version: {change.ReleaseVersion.VersionName}"; eventBlock = true; ChangeTitleField.Text = change.Title; eventBlock = true; DescriptionField.Text = change.Description; if (change.AdditionalData == null) { change.AdditionalData = JObject.Parse("{}"); } eventBlock = true; AdditionalDataField.Text = change.AdditionalData.ToString(Newtonsoft.Json.Formatting.Indented); } public async void BackButtonPressed(object sender, RoutedEventArgs args) { Change change = await openChangeRef.GetChange(); VersionRef versionRef = change.ReleaseVersion; openChangeRef = null; ContentArea.GetInstance().OpenPage(ContentArea.PageType.Version, versionRef); } private async void ChangeTitleField_TextChanged(object sender, TextChangedEventArgs e) { if (eventBlock || MainWindow.GetInstance().VersionController == null) { eventBlock = false; return; } Change change = await openChangeRef.GetChange(); change.Title = ChangeTitleField.Text; } private async void DescriptionField_TextChanged(object sender, TextChangedEventArgs e) { if (eventBlock || MainWindow.GetInstance().VersionController == null) { eventBlock = false; return; } Change change = await openChangeRef.GetChange(); change.Description = DescriptionField.Text; } private async void AdditionalDataField_TextChanged(object sender, System.EventArgs e) { if (eventBlock || MainWindow.GetInstance().VersionController == null) { eventBlock = false; return; } Change change = await openChangeRef.GetChange(); try { JObject newObject = JObject.Parse(AdditionalDataField.Text); change.AdditionalData = newObject; JsonErrorText.Visibility = System.Windows.Visibility.Collapsed; } catch (Exception) { JsonErrorText.Visibility = System.Windows.Visibility.Visible; } } internal ChangeRef GetChangeRef() { return openChangeRef; } internal VersionRef GetVersionRef() { return versionRef; } } }
32.28125
107
0.566796
[ "MIT" ]
James231/Simple-Version-Control
src/SimpleVersionControl.App/UserControls/ContentAreaControls/ChangePage.xaml.cs
4,135
C#
using NUnit.Framework; namespace Mirror.Weaver.Tests { public class WeaverGeneralTests : WeaverTestsBuildFromTestName { [Test] public void RecursionCount() { Assert.That(weaverErrors, Contains.Item("Potato1 can't be serialized because it references itself (at MirrorTest.RecursionCount/Potato1)")); } [Test] public void TestingScriptableObjectArraySerialization() { Assert.That(weaverErrors, Is.Empty); } } }
25.55
152
0.643836
[ "MIT" ]
JavierCondeIAR/MirrorNG
Assets/Mirror/Tests/Editor/Weaver/WeaverGeneralTests.cs
511
C#
namespace Validot { using Validot.Specification; using Validot.Specification.Commands; public static class WithExtraMessageExtension { public static IWithExtraMessageOut<T> WithExtraMessage<T>(this IWithExtraMessageIn<T> @this, string message) { ThrowHelper.NullArgument(@this, nameof(@this)); return ((SpecificationApi<T>)@this).AddCommand(new WithExtraMessageCommand(message)); } public static IWithExtraMessageForbiddenOut<T> WithExtraMessage<T>(this IWithExtraMessageForbiddenIn<T> @this, string message) { ThrowHelper.NullArgument(@this, nameof(@this)); return ((SpecificationApi<T>)@this).AddCommand(new WithExtraMessageCommand(message)); } } namespace Specification { public interface IWithExtraMessageOut<T> : ISpecificationOut<T>, IRuleIn<T>, IWithExtraMessageIn<T>, IWithExtraCodeIn<T> { } public interface IWithExtraMessageIn<T> { } public interface IWithExtraMessageForbiddenOut<T> : ISpecificationOut<T>, IWithExtraMessageForbiddenIn<T>, IWithExtraCodeForbiddenIn<T> { } public interface IWithExtraMessageForbiddenIn<T> { } internal partial class SpecificationApi<T> : IWithExtraMessageIn<T>, IWithExtraMessageOut<T>, IWithExtraMessageForbiddenIn<T>, IWithExtraMessageForbiddenOut<T> { } } }
30.150943
168
0.616395
[ "MIT" ]
JeremySkinner/Validot
src/Validot/Specification/WithExtraMessageExtension.cs
1,598
C#
/* * author:symbolspace * e-mail:symbolspace@outlook.com */ namespace Symbol.Collections.Generic { /// <summary> /// 翻页适配器 /// </summary> /// <typeparam name="T">任意类型</typeparam> /// <remarks>遍历这个对象,就是当前页的所有行集。</remarks> public interface IPagingCollection<T> : System.Collections.Generic.IEnumerable<T> { /// <summary> /// 当前页码(0开始) /// </summary> int CurrentPageIndex { get; set; } /// <summary> /// 每页行数 /// </summary> int ItemPerPage { get; set; } /// <summary> /// 是否允许页码超出最大值(默认允许) /// </summary> bool AllowPageOutOfMax { get; set; } /// <summary> /// 总行数 /// </summary> int TotalCount { get; } /// <summary> /// 总页数 /// </summary> int PageCount { get; } } }
24.6
87
0.494774
[ "MIT" ]
symbolspace/Symbol
src/Symbol/Symbol/Collections/Generic/IPagingCollection.cs
989
C#
using System.Text.Json.Serialization; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// ItemDeliveryDetail Data Structure. /// </summary> public class ItemDeliveryDetail : AlipayObject { /// <summary> /// 已生产数量, 分批反馈时候必传. /// </summary> [JsonPropertyName("amount")] public string Amount { get; set; } /// <summary> /// 订单明细ID /// </summary> [JsonPropertyName("assign_item_id")] public string AssignItemId { get; set; } /// <summary> /// 由供应商自定义的分批反馈批次号,用于保持幂等,此值不传则需要按整批反馈.(由字母,数字,下划线组成) /// </summary> [JsonPropertyName("batch_no")] public string BatchNo { get; set; } /// <summary> /// 物流公司code, 比如: SF-顺丰, POST-中国邮政, CAINIAO-菜鸟. /// </summary> [JsonPropertyName("logistic_code")] public string LogisticCode { get; set; } /// <summary> /// 物流公司名称 /// </summary> [JsonPropertyName("logistics_name")] public string LogisticsName { get; set; } /// <summary> /// 物流订单号 /// </summary> [JsonPropertyName("logistics_no")] public string LogisticsNo { get; set; } } }
26.702128
62
0.545817
[ "MIT" ]
LuohuaRain/payment
src/Essensoft.AspNetCore.Payment.Alipay/Domain/ItemDeliveryDetail.cs
1,431
C#
using System; using TelefoniaWooza.Domain.Entities; using TelefoniaWooza.Domain.Interfaces.Repositories; using TelefoniaWooza.Infra.Data.Contexts; namespace TelefoniaWooza.Infra.Data.Repositories { public class DDDRepository : RepositoryBase<DDD>, IDDDRepository { public DDDRepository(TelefoniaContext db) : base(db) { } } }
24.266667
68
0.739011
[ "MIT" ]
DanielCanedo12/Telefonia
TelefoniaWooza/TelefoniaWooza.Infra.Data/Repositories/DDDRepository.cs
366
C#
using System; using MikhailKhalizev.Processor.x86.BinToCSharp; namespace MikhailKhalizev.Max.Program { public partial class RawProgram { [MethodInfo("0x1008_4a18-34fd0f8e")] public void Method_1008_4a18() { ii(0x1008_4a18, 5); push(0x38); /* push 0x38 */ ii(0x1008_4a1d, 5); call(Definitions.sys_check_available_stack_size, 0xe_1330);/* call 0x10165d52 */ ii(0x1008_4a22, 1); push(ebx); /* push ebx */ ii(0x1008_4a23, 1); push(ecx); /* push ecx */ ii(0x1008_4a24, 1); push(edx); /* push edx */ ii(0x1008_4a25, 1); push(esi); /* push esi */ ii(0x1008_4a26, 1); push(edi); /* push edi */ ii(0x1008_4a27, 1); push(ebp); /* push ebp */ ii(0x1008_4a28, 2); mov(ebp, esp); /* mov ebp, esp */ ii(0x1008_4a2a, 6); sub(esp, 0x1c); /* sub esp, 0x1c */ ii(0x1008_4a30, 3); mov(memd[ss, ebp - 4], eax); /* mov [ebp-0x4], eax */ ii(0x1008_4a33, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4a36, 3); add(eax, 0x32); /* add eax, 0x32 */ ii(0x1008_4a39, 5); call(0x1007_6574, -0xe4ca); /* call 0x10076574 */ ii(0x1008_4a3e, 3); mov(al, memb[ds, eax + 78]); /* mov al, [eax+0x4e] */ ii(0x1008_4a41, 5); and(eax, 0xff); /* and eax, 0xff */ ii(0x1008_4a46, 2); test(eax, eax); /* test eax, eax */ ii(0x1008_4a48, 2); if(jnz(0x1008_4a53, 9)) goto l_0x1008_4a53;/* jnz 0x10084a53 */ ii(0x1008_4a4a, 4); mov(memb[ss, ebp - 8], 0); /* mov byte [ebp-0x8], 0x0 */ ii(0x1008_4a4e, 5); jmp(0x1008_4c72, 0x21f); goto l_0x1008_4c72;/* jmp 0x10084c72 */ l_0x1008_4a53: ii(0x1008_4a53, 3); mov(edx, memd[ss, ebp - 4]); /* mov edx, [ebp-0x4] */ ii(0x1008_4a56, 3); add(edx, 0x36); /* add edx, 0x36 */ ii(0x1008_4a59, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4a5c, 3); add(eax, 0x32); /* add eax, 0x32 */ ii(0x1008_4a5f, 5); call(0x1007_6574, -0xe4f0); /* call 0x10076574 */ ii(0x1008_4a64, 5); call(0x1015_26ac, 0xc_dc43); /* call 0x101526ac */ ii(0x1008_4a69, 5); call(0x1008_b4b4, 0x6a46); /* call 0x1008b4b4 */ ii(0x1008_4a6e, 2); test(al, al); /* test al, al */ ii(0x1008_4a70, 2); if(jz(0x1008_4a7b, 9)) goto l_0x1008_4a7b;/* jz 0x10084a7b */ ii(0x1008_4a72, 4); mov(memb[ss, ebp - 8], 0); /* mov byte [ebp-0x8], 0x0 */ ii(0x1008_4a76, 5); jmp(0x1008_4c72, 0x1f7); goto l_0x1008_4c72;/* jmp 0x10084c72 */ l_0x1008_4a7b: ii(0x1008_4a7b, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4a7e, 3); add(eax, 0x36); /* add eax, 0x36 */ ii(0x1008_4a81, 5); call(0x1008_af84, 0x64fe); /* call 0x1008af84 */ ii(0x1008_4a86, 2); mov(edx, eax); /* mov edx, eax */ ii(0x1008_4a88, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4a8b, 3); add(eax, 0x32); /* add eax, 0x32 */ ii(0x1008_4a8e, 5); call(0x1007_6574, -0xe51f); /* call 0x10076574 */ ii(0x1008_4a93, 5); call(0x1015_2a52, 0xc_dfba); /* call 0x10152a52 */ ii(0x1008_4a98, 2); test(al, al); /* test al, al */ ii(0x1008_4a9a, 2); if(jnz(0x1008_4aa5, 9)) goto l_0x1008_4aa5;/* jnz 0x10084aa5 */ ii(0x1008_4a9c, 4); mov(memb[ss, ebp - 8], 0); /* mov byte [ebp-0x8], 0x0 */ ii(0x1008_4aa0, 5); jmp(0x1008_4c72, 0x1cd); goto l_0x1008_4c72;/* jmp 0x10084c72 */ l_0x1008_4aa5: ii(0x1008_4aa5, 4); mov(memb[ss, ebp - 16], 3); /* mov byte [ebp-0x10], 0x3 */ ii(0x1008_4aa9, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4aac, 4); cmp(memb[ds, eax + 21], 3); /* cmp byte [eax+0x15], 0x3 */ ii(0x1008_4ab0, 2); if(jl(0x1008_4ab6, 4)) goto l_0x1008_4ab6;/* jl 0x10084ab6 */ ii(0x1008_4ab2, 4); mov(memb[ss, ebp - 16], 2); /* mov byte [ebp-0x10], 0x2 */ l_0x1008_4ab6: ii(0x1008_4ab6, 4); movsx(ebx, memb[ss, ebp - 16]); /* movsx ebx, byte [ebp-0x10] */ ii(0x1008_4aba, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4abd, 3); add(eax, 0x32); /* add eax, 0x32 */ ii(0x1008_4ac0, 5); call(0x1007_65d0, -0xe4f5); /* call 0x100765d0 */ ii(0x1008_4ac5, 3); mov(ecx, memd[ss, ebp - 4]); /* mov ecx, [ebp-0x4] */ ii(0x1008_4ac8, 2); mov(edx, eax); /* mov edx, eax */ ii(0x1008_4aca, 2); mov(eax, ecx); /* mov eax, ecx */ ii(0x1008_4acc, 5); call(0x100a_3671, 0x1_eba0); /* call 0x100a3671 */ ii(0x1008_4ad1, 2); test(al, al); /* test al, al */ ii(0x1008_4ad3, 2); if(jz(0x1008_4ade, 9)) goto l_0x1008_4ade;/* jz 0x10084ade */ ii(0x1008_4ad5, 4); mov(memb[ss, ebp - 8], 1); /* mov byte [ebp-0x8], 0x1 */ ii(0x1008_4ad9, 5); jmp(0x1008_4c72, 0x194); goto l_0x1008_4c72;/* jmp 0x10084c72 */ l_0x1008_4ade: ii(0x1008_4ade, 2); xor(edx, edx); /* xor edx, edx */ ii(0x1008_4ae0, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4ae3, 3); add(eax, 0x2a); /* add eax, 0x2a */ ii(0x1008_4ae6, 5); call(0x1013_ad11, 0xb_6226); /* call 0x1013ad11 */ ii(0x1008_4aeb, 2); test(al, al); /* test al, al */ ii(0x1008_4aed, 2); if(jnz(0x1008_4b03, 0x14)) goto l_0x1008_4b03;/* jnz 0x10084b03 */ ii(0x1008_4aef, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4af2, 3); add(eax, 0x2a); /* add eax, 0x2a */ ii(0x1008_4af5, 5); call(0x1008_9d7c, 0x5282); /* call 0x10089d7c */ ii(0x1008_4afa, 5); call(0x1008_9f70, 0x5471); /* call 0x10089f70 */ ii(0x1008_4aff, 2); test(eax, eax); /* test eax, eax */ ii(0x1008_4b01, 2); if(jnz(0x1008_4b0c, 9)) goto l_0x1008_4b0c;/* jnz 0x10084b0c */ l_0x1008_4b03: ii(0x1008_4b03, 4); mov(memb[ss, ebp - 8], 0); /* mov byte [ebp-0x8], 0x0 */ ii(0x1008_4b07, 5); jmp(0x1008_4c72, 0x166); goto l_0x1008_4c72;/* jmp 0x10084c72 */ l_0x1008_4b0c: ii(0x1008_4b0c, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4b0f, 4); cmp(memb[ds, eax + 21], 2); /* cmp byte [eax+0x15], 0x2 */ ii(0x1008_4b13, 2); if(jg(0x1008_4b29, 0x14)) goto l_0x1008_4b29;/* jg 0x10084b29 */ ii(0x1008_4b15, 4); movsx(edx, memb[ss, ebp - 16]); /* movsx edx, byte [ebp-0x10] */ ii(0x1008_4b19, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4b1c, 5); call(0x1008_43e0, -0x741); /* call 0x100843e0 */ ii(0x1008_4b21, 3); mov(memb[ss, ebp - 8], al); /* mov [ebp-0x8], al */ ii(0x1008_4b24, 5); jmp(0x1008_4c72, 0x149); goto l_0x1008_4c72;/* jmp 0x10084c72 */ l_0x1008_4b29: ii(0x1008_4b29, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4b2c, 4); cmp(memb[ds, eax + 21], 5); /* cmp byte [eax+0x15], 0x5 */ ii(0x1008_4b30, 2); if(jl(0x1008_4b46, 0x14)) goto l_0x1008_4b46;/* jl 0x10084b46 */ ii(0x1008_4b32, 4); movsx(edx, memb[ss, ebp - 16]); /* movsx edx, byte [ebp-0x10] */ ii(0x1008_4b36, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4b39, 5); call(0x1008_43e0, -0x75e); /* call 0x100843e0 */ ii(0x1008_4b3e, 3); mov(memb[ss, ebp - 8], al); /* mov [ebp-0x8], al */ ii(0x1008_4b41, 5); jmp(0x1008_4c72, 0x12c); goto l_0x1008_4c72;/* jmp 0x10084c72 */ l_0x1008_4b46: ii(0x1008_4b46, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4b49, 3); add(eax, 0x32); /* add eax, 0x32 */ ii(0x1008_4b4c, 5); call(0x1007_6574, -0xe5dd); /* call 0x10076574 */ ii(0x1008_4b51, 4); test(memb[ds, eax + 19], 1); /* test byte [eax+0x13], 0x1 */ ii(0x1008_4b55, 2); if(jz(0x1008_4b88, 0x31)) goto l_0x1008_4b88;/* jz 0x10084b88 */ ii(0x1008_4b57, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4b5a, 3); add(eax, 0x32); /* add eax, 0x32 */ ii(0x1008_4b5d, 5); call(0x1007_6574, -0xe5ee); /* call 0x10076574 */ ii(0x1008_4b62, 3); mov(edx, memd[ds, eax + 26]); /* mov edx, [eax+0x1a] */ ii(0x1008_4b65, 3); sar(edx, 0x10); /* sar edx, 0x10 */ ii(0x1008_4b68, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4b6b, 3); add(eax, 0x32); /* add eax, 0x32 */ ii(0x1008_4b6e, 5); call(0x1007_6574, -0xe5ff); /* call 0x10076574 */ ii(0x1008_4b73, 3); mov(eax, memd[ds, eax + 24]); /* mov eax, [eax+0x18] */ ii(0x1008_4b76, 3); sar(eax, 0x10); /* sar eax, 0x10 */ ii(0x1008_4b79, 5); call(0x1007_3d48, -0x1_0e36); /* call 0x10073d48 */ ii(0x1008_4b7e, 5); and(eax, 0xffff); /* and eax, 0xffff */ ii(0x1008_4b83, 3); cmp(eax, 1); /* cmp eax, 0x1 */ ii(0x1008_4b86, 2); if(jnz(0x1008_4b8a, 2)) goto l_0x1008_4b8a;/* jnz 0x10084b8a */ l_0x1008_4b88: ii(0x1008_4b88, 2); jmp(0x1008_4ba9, 0x1f); goto l_0x1008_4ba9;/* jmp 0x10084ba9 */ l_0x1008_4b8a: ii(0x1008_4b8a, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4b8d, 3); mov(eax, memd[ds, eax + 7]); /* mov eax, [eax+0x7] */ ii(0x1008_4b90, 3); sar(eax, 0x10); /* sar eax, 0x10 */ ii(0x1008_4b93, 6); imul(edx, eax, 0xc5); /* imul edx, eax, 0xc5 */ ii(0x1008_4b99, 5); mov(eax, 0x101c_31c4); /* mov eax, 0x101c31c4 */ ii(0x1008_4b9e, 2); add(eax, edx); /* add eax, edx */ ii(0x1008_4ba0, 5); call(0x1008_a064, 0x54bf); /* call 0x1008a064 */ ii(0x1008_4ba5, 2); cmp(al, 5); /* cmp al, 0x5 */ ii(0x1008_4ba7, 2); if(jnz(0x1008_4bab, 2)) goto l_0x1008_4bab;/* jnz 0x10084bab */ l_0x1008_4ba9: ii(0x1008_4ba9, 2); jmp(0x1008_4bbf, 0x14); goto l_0x1008_4bbf;/* jmp 0x10084bbf */ l_0x1008_4bab: ii(0x1008_4bab, 4); movsx(edx, memb[ss, ebp - 16]); /* movsx edx, byte [ebp-0x10] */ ii(0x1008_4baf, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4bb2, 5); call(0x1008_43e0, -0x7d7); /* call 0x100843e0 */ ii(0x1008_4bb7, 3); mov(memb[ss, ebp - 8], al); /* mov [ebp-0x8], al */ ii(0x1008_4bba, 5); jmp(0x1008_4c72, 0xb3); goto l_0x1008_4c72;/* jmp 0x10084c72 */ l_0x1008_4bbf: ii(0x1008_4bbf, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4bc2, 3); add(eax, 0x32); /* add eax, 0x32 */ ii(0x1008_4bc5, 5); call(0x1007_6574, -0xe656); /* call 0x10076574 */ ii(0x1008_4bca, 2); mov(edx, eax); /* mov edx, eax */ ii(0x1008_4bcc, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4bcf, 3); add(eax, 0x32); /* add eax, 0x32 */ ii(0x1008_4bd2, 5); call(0x1007_6574, -0xe663); /* call 0x10076574 */ ii(0x1008_4bd7, 4); mov(dx, memw[ds, edx + 26]); /* mov dx, [edx+0x1a] */ ii(0x1008_4bdb, 4); mov(memw[ds, eax + 30], dx); /* mov [eax+0x1e], dx */ ii(0x1008_4bdf, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4be2, 3); add(eax, 0x32); /* add eax, 0x32 */ ii(0x1008_4be5, 5); call(0x1007_6574, -0xe676); /* call 0x10076574 */ ii(0x1008_4bea, 2); mov(edx, eax); /* mov edx, eax */ ii(0x1008_4bec, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4bef, 3); add(eax, 0x32); /* add eax, 0x32 */ ii(0x1008_4bf2, 5); call(0x1007_6574, -0xe683); /* call 0x10076574 */ ii(0x1008_4bf7, 4); mov(dx, memw[ds, edx + 28]); /* mov dx, [edx+0x1c] */ ii(0x1008_4bfb, 4); mov(memw[ds, eax + 32], dx); /* mov [eax+0x20], dx */ ii(0x1008_4bff, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4c02, 5); call(0x1008_46e6, -0x521); /* call 0x100846e6 */ ii(0x1008_4c07, 2); test(al, al); /* test al, al */ ii(0x1008_4c09, 2); if(jnz(0x1008_4c11, 6)) goto l_0x1008_4c11;/* jnz 0x10084c11 */ ii(0x1008_4c0b, 4); mov(memb[ss, ebp - 8], 0); /* mov byte [ebp-0x8], 0x0 */ ii(0x1008_4c0f, 2); jmp(0x1008_4c72, 0x61); goto l_0x1008_4c72;/* jmp 0x10084c72 */ l_0x1008_4c11: ii(0x1008_4c11, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4c14, 3); add(eax, 0x20); /* add eax, 0x20 */ ii(0x1008_4c17, 5); call(0x1008_9d08, 0x50ec); /* call 0x10089d08 */ ii(0x1008_4c1c, 2); mov(edx, eax); /* mov edx, eax */ ii(0x1008_4c1e, 3); lea(eax, memd[ss, ebp - 24]); /* lea eax, [ebp-0x18] */ ii(0x1008_4c21, 5); call(0x1008_9be4, 0x4fbe); /* call 0x10089be4 */ ii(0x1008_4c26, 4); or(memb[ss, ebp - 12], 1); /* or byte [ebp-0xc], 0x1 */ ii(0x1008_4c2a, 3); lea(eax, memd[ss, ebp - 20]); /* lea eax, [ebp-0x14] */ ii(0x1008_4c2d, 5); call(0x1007_64fc, -0xe736); /* call 0x100764fc */ ii(0x1008_4c32, 3); mov(memd[ss, ebp - 28], eax); /* mov [ebp-0x1c], eax */ ii(0x1008_4c35, 4); and(memb[ss, ebp - 12], -2 /* 0xfe */);/* and byte [ebp-0xc], 0xfe */ ii(0x1008_4c39, 4); movsx(edx, memb[ss, ebp - 16]); /* movsx edx, byte [ebp-0x10] */ ii(0x1008_4c3d, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1008_4c40, 5); call(0x1008_43e0, -0x865); /* call 0x100843e0 */ ii(0x1008_4c45, 3); mov(memb[ss, ebp - 8], al); /* mov [ebp-0x8], al */ ii(0x1008_4c48, 2); xor(edx, edx); /* xor edx, edx */ ii(0x1008_4c4a, 3); lea(eax, memd[ss, ebp - 20]); /* lea eax, [ebp-0x14] */ ii(0x1008_4c4d, 5); call(0x1007_5f6c, -0xece6); /* call 0x10075f6c */ ii(0x1008_4c52, 2); xor(edx, edx); /* xor edx, edx */ ii(0x1008_4c54, 3); lea(eax, memd[ss, ebp - 24]); /* lea eax, [ebp-0x18] */ ii(0x1008_4c57, 5); call(0x1008_9044, 0x43e8); /* call 0x10089044 */ ii(0x1008_4c5c, 2); jmp(0x1008_4c72, 0x14); goto l_0x1008_4c72;/* jmp 0x10084c72 */ // ii(0x1008_4c5e, 20); Недостижимый код. l_0x1008_4c72: ii(0x1008_4c72, 3); mov(al, memb[ss, ebp - 8]); /* mov al, [ebp-0x8] */ ii(0x1008_4c75, 2); mov(esp, ebp); /* mov esp, ebp */ ii(0x1008_4c77, 1); pop(ebp); /* pop ebp */ ii(0x1008_4c78, 1); pop(edi); /* pop edi */ ii(0x1008_4c79, 1); pop(esi); /* pop esi */ ii(0x1008_4c7a, 1); pop(edx); /* pop edx */ ii(0x1008_4c7b, 1); pop(ecx); /* pop ecx */ ii(0x1008_4c7c, 1); pop(ebx); /* pop ebx */ ii(0x1008_4c7d, 1); ret(); /* ret */ } } }
84.63981
114
0.460384
[ "Apache-2.0" ]
mikhail-khalizev/max
source/MikhailKhalizev.Max/source/Program/Auto/z-1008-4a18.cs
17,874
C#
using System; class Arrow { static void Main() { int n = int.Parse(Console.ReadLine()); Console.WriteLine("{0}{1}{0}", new string('.', n / 2), new string('#', n)); for (int i = 0; i < n - 2; i++) { Console.Write(new string('.', n / 2)); Console.Write("#"); Console.Write(new string('.', n - 2)); Console.Write("#"); Console.WriteLine(new string('.', n / 2)); } Console.WriteLine("{1}{0}{1}", new string('.', n - 2), new string('#', (n / 2) + 1)); for (int i = 0; i < n - 1; i++) { for (int j = 0; j < (2 * n) - 1; j++) { if (i + j == (n * 2) - 3 || i - j == -1) { Console.Write("#"); } else { Console.Write("."); } } Console.WriteLine(); } } }
27.083333
93
0.340513
[ "MIT" ]
vanncho/SoftUni-Entrance-Exam-Prepare
018.Arrow/Arrow.cs
977
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Composition; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces { [ExportWorkspaceServiceFactory(typeof(IHostDependentFormattingRuleFactoryService), ServiceLayer.Test), Shared, PartNotDiscoverable] internal sealed class TestFormattingRuleFactoryServiceFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestFormattingRuleFactoryServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { // return new factory per workspace return new Factory(); } public sealed class Factory : IHostDependentFormattingRuleFactoryService { public int BaseIndentation = 0; public TextSpan TextSpan = default; public bool UseBaseIndentation = false; public bool ShouldUseBaseIndentation(Document document) => UseBaseIndentation; public AbstractFormattingRule CreateRule(Document document, int position) { if (BaseIndentation == 0) { return NoOpFormattingRule.Instance; } var root = document.GetSyntaxRootAsync().Result; return new BaseIndentationFormattingRule(root, TextSpan, BaseIndentation + 4); } public IEnumerable<TextChange> FilterFormattedChanges(Document document, TextSpan span, IList<TextChange> changes) => changes; public bool ShouldNotFormatOrCommitOnPaste(Document document) => UseBaseIndentation; } } }
37.103448
135
0.683086
[ "MIT" ]
06needhamt/roslyn
src/EditorFeatures/TestUtilities/Workspaces/TestFormattingRuleFactoryServiceFactory.cs
2,154
C#
namespace CottonWinForms { partial class Form { /// <summary> /// Erforderliche Designervariable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Verwendete Ressourcen bereinigen. /// </summary> /// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Vom Windows Form-Designer generierter Code /// <summary> /// Erforderliche Methode für die Designerunterstützung. /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden. /// </summary> private void InitializeComponent() { this.target = new System.Windows.Forms.PictureBox(); this.renderButton = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.target)).BeginInit(); this.SuspendLayout(); // // target // this.target.Location = new System.Drawing.Point(0, 0); this.target.Name = "target"; this.target.Size = new System.Drawing.Size(800, 600); this.target.TabIndex = 0; this.target.TabStop = false; // // renderButton // this.renderButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.renderButton.Location = new System.Drawing.Point(0, 597); this.renderButton.Name = "renderButton"; this.renderButton.Size = new System.Drawing.Size(800, 61); this.renderButton.TabIndex = 1; this.renderButton.Text = "Render!"; this.renderButton.UseVisualStyleBackColor = true; this.renderButton.Click += new System.EventHandler(this.RenderButton_Click); // // Form // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(801, 657); this.Controls.Add(this.renderButton); this.Controls.Add(this.target); this.Name = "Form"; this.Text = "Cotton"; this.Load += new System.EventHandler(this.Form_Load); ((System.ComponentModel.ISupportInitialize)(this.target)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.PictureBox target; private System.Windows.Forms.Button renderButton; } }
38.428571
172
0.582629
[ "MIT" ]
SpacialCircumstances/CottonRenderer
CottonWinForms/Form1.Designer.cs
2,965
C#
namespace AppliedAlgebra.GfAlgorithms.Tests { using System; using Extensions; using GfPolynoms; using GfPolynoms.Extensions; using GfPolynoms.GaloisFields; using JetBrains.Annotations; using TestCases; using Xunit; public class FieldElementsVectorExtensionsTests { private static readonly GaloisField Gf3; [UsedImplicitly] public static readonly TheoryData<FieldElement[]> GetSpectrumParametersValidationTestCases; [UsedImplicitly] public static readonly TheoryData<CircularShiftParametersValidationTestCase> CircularShiftParametersValidationTestCases; static FieldElementsVectorExtensionsTests() { var gf2 = GaloisField.Create(2); Gf3 = GaloisField.Create(3); GetSpectrumParametersValidationTestCases = new TheoryData<FieldElement[]> { null, new FieldElement[0], new[] {gf2.One(), null}, new[] {gf2.One(), Gf3.One()} }; CircularShiftParametersValidationTestCases = new TheoryData<CircularShiftParametersValidationTestCase> { new CircularShiftParametersValidationTestCase(), new CircularShiftParametersValidationTestCase { Vector = gf2.CreateElementsVector(0, 1), PositionsCount = -1 }, new CircularShiftParametersValidationTestCase { Vector = gf2.CreateElementsVector(0, 1), PositionsCount = 2 } }; } [Theory] [MemberData(nameof(GetSpectrumParametersValidationTestCases))] public void GetSpectrumMustValidateParameters(FieldElement[] vector) { Assert.ThrowsAny<ArgumentException>(vector.GetSpectrum); } [Theory] [MemberData(nameof(CircularShiftParametersValidationTestCases))] public void RightCircularShiftMustValidateParameters(CircularShiftParametersValidationTestCase testCase) { Assert.ThrowsAny<ArgumentException>(() => testCase.Vector.RightCircularShift(testCase.PositionsCount)); } [Fact] public void ShouldPerformRightCircularShift() { // Given var sourceVector = Gf3.CreateElementsVector(0, 1, 2); // When var actual = sourceVector.RightCircularShift(2); // Then var expected = Gf3.CreateElementsVector(1, 2, 0); Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(CircularShiftParametersValidationTestCases))] public void LeftCircularShiftMustValidateParameters(CircularShiftParametersValidationTestCase testCase) { Assert.ThrowsAny<ArgumentException>(() => testCase.Vector.LeftCircularShift(testCase.PositionsCount)); } [Fact] public void ShouldPerformLeftCircularShift() { // Given var sourceVector = Gf3.CreateElementsVector(0, 1, 2); // When var actual = sourceVector.LeftCircularShift(2); // Then var expected = Gf3.CreateElementsVector(2, 0, 1); Assert.Equal(expected, actual); } } }
35.784946
133
0.622296
[ "MIT" ]
litichevskiydv/GfPolynoms
test/GfAlgorithms.Tests/FieldElementsVectorExtensionsTests.cs
3,330
C#
//----------------------------------------------------------------------------- // Copyright : (c) Chris Moore, 2020 // License : MIT //----------------------------------------------------------------------------- namespace Z0.Asm { using System; [Flags, SymSource] public enum OpszKind : byte { [Symbol("w16")] W16 = (byte)DataWidth.W16, [Symbol("w32")] W32 = (byte)DataWidth.W32, [Symbol("w64")] W64 = (byte)DataWidth.W64 } }
24.095238
79
0.353755
[ "BSD-3-Clause" ]
0xCM/z0
src/asm.core/src/models/encoding/OpszKind.cs
506
C#
// Copyright (c) Six Labors and contributors. // Licensed under the GNU Affero General Public License, Version 3. using System; using System.Collections.Generic; namespace SixLabors.ImageSharp { /// <content> /// Contains static named color values. /// <see href="https://www.w3.org/TR/css-color-3/"/> /// </content> public readonly partial struct Color { private static readonly Lazy<Dictionary<string, Color>> NamedColorsLookupLazy = new Lazy<Dictionary<string, Color>>(CreateNamedColorsLookup, true); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #F0F8FF. /// </summary> public static readonly Color AliceBlue = FromRgba(240, 248, 255, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FAEBD7. /// </summary> public static readonly Color AntiqueWhite = FromRgba(250, 235, 215, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #00FFFF. /// </summary> public static readonly Color Aqua = FromRgba(0, 255, 255, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #7FFFD4. /// </summary> public static readonly Color Aquamarine = FromRgba(127, 255, 212, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #F0FFFF. /// </summary> public static readonly Color Azure = FromRgba(240, 255, 255, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #F5F5DC. /// </summary> public static readonly Color Beige = FromRgba(245, 245, 220, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFE4C4. /// </summary> public static readonly Color Bisque = FromRgba(255, 228, 196, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #000000. /// </summary> public static readonly Color Black = FromRgba(0, 0, 0, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFEBCD. /// </summary> public static readonly Color BlanchedAlmond = FromRgba(255, 235, 205, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #0000FF. /// </summary> public static readonly Color Blue = FromRgba(0, 0, 255, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #8A2BE2. /// </summary> public static readonly Color BlueViolet = FromRgba(138, 43, 226, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #A52A2A. /// </summary> public static readonly Color Brown = FromRgba(165, 42, 42, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #DEB887. /// </summary> public static readonly Color BurlyWood = FromRgba(222, 184, 135, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #5F9EA0. /// </summary> public static readonly Color CadetBlue = FromRgba(95, 158, 160, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #7FFF00. /// </summary> public static readonly Color Chartreuse = FromRgba(127, 255, 0, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #D2691E. /// </summary> public static readonly Color Chocolate = FromRgba(210, 105, 30, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FF7F50. /// </summary> public static readonly Color Coral = FromRgba(255, 127, 80, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #6495ED. /// </summary> public static readonly Color CornflowerBlue = FromRgba(100, 149, 237, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFF8DC. /// </summary> public static readonly Color Cornsilk = FromRgba(255, 248, 220, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #DC143C. /// </summary> public static readonly Color Crimson = FromRgba(220, 20, 60, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #00FFFF. /// </summary> public static readonly Color Cyan = Aqua; /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #00008B. /// </summary> public static readonly Color DarkBlue = FromRgba(0, 0, 139, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #008B8B. /// </summary> public static readonly Color DarkCyan = FromRgba(0, 139, 139, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #B8860B. /// </summary> public static readonly Color DarkGoldenrod = FromRgba(184, 134, 11, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #A9A9A9. /// </summary> public static readonly Color DarkGray = FromRgba(169, 169, 169, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #006400. /// </summary> public static readonly Color DarkGreen = FromRgba(0, 100, 0, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #A9A9A9. /// </summary> public static readonly Color DarkGrey = DarkGray; /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #BDB76B. /// </summary> public static readonly Color DarkKhaki = FromRgba(189, 183, 107, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #8B008B. /// </summary> public static readonly Color DarkMagenta = FromRgba(139, 0, 139, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #556B2F. /// </summary> public static readonly Color DarkOliveGreen = FromRgba(85, 107, 47, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FF8C00. /// </summary> public static readonly Color DarkOrange = FromRgba(255, 140, 0, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #9932CC. /// </summary> public static readonly Color DarkOrchid = FromRgba(153, 50, 204, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #8B0000. /// </summary> public static readonly Color DarkRed = FromRgba(139, 0, 0, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #E9967A. /// </summary> public static readonly Color DarkSalmon = FromRgba(233, 150, 122, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #8FBC8F. /// </summary> public static readonly Color DarkSeaGreen = FromRgba(143, 188, 143, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #483D8B. /// </summary> public static readonly Color DarkSlateBlue = FromRgba(72, 61, 139, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #2F4F4F. /// </summary> public static readonly Color DarkSlateGray = FromRgba(47, 79, 79, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #2F4F4F. /// </summary> public static readonly Color DarkSlateGrey = DarkSlateGray; /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #00CED1. /// </summary> public static readonly Color DarkTurquoise = FromRgba(0, 206, 209, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #9400D3. /// </summary> public static readonly Color DarkViolet = FromRgba(148, 0, 211, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FF1493. /// </summary> public static readonly Color DeepPink = FromRgba(255, 20, 147, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #00BFFF. /// </summary> public static readonly Color DeepSkyBlue = FromRgba(0, 191, 255, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #696969. /// </summary> public static readonly Color DimGray = FromRgba(105, 105, 105, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #696969. /// </summary> public static readonly Color DimGrey = DimGray; /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #1E90FF. /// </summary> public static readonly Color DodgerBlue = FromRgba(30, 144, 255, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #B22222. /// </summary> public static readonly Color Firebrick = FromRgba(178, 34, 34, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFFAF0. /// </summary> public static readonly Color FloralWhite = FromRgba(255, 250, 240, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #228B22. /// </summary> public static readonly Color ForestGreen = FromRgba(34, 139, 34, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FF00FF. /// </summary> public static readonly Color Fuchsia = FromRgba(255, 0, 255, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #DCDCDC. /// </summary> public static readonly Color Gainsboro = FromRgba(220, 220, 220, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #F8F8FF. /// </summary> public static readonly Color GhostWhite = FromRgba(248, 248, 255, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFD700. /// </summary> public static readonly Color Gold = FromRgba(255, 215, 0, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #DAA520. /// </summary> public static readonly Color Goldenrod = FromRgba(218, 165, 32, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #808080. /// </summary> public static readonly Color Gray = FromRgba(128, 128, 128, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #008000. /// </summary> public static readonly Color Green = FromRgba(0, 128, 0, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #ADFF2F. /// </summary> public static readonly Color GreenYellow = FromRgba(173, 255, 47, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #808080. /// </summary> public static readonly Color Grey = Gray; /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #F0FFF0. /// </summary> public static readonly Color Honeydew = FromRgba(240, 255, 240, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FF69B4. /// </summary> public static readonly Color HotPink = FromRgba(255, 105, 180, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #CD5C5C. /// </summary> public static readonly Color IndianRed = FromRgba(205, 92, 92, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #4B0082. /// </summary> public static readonly Color Indigo = FromRgba(75, 0, 130, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFFFF0. /// </summary> public static readonly Color Ivory = FromRgba(255, 255, 240, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #F0E68C. /// </summary> public static readonly Color Khaki = FromRgba(240, 230, 140, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #E6E6FA. /// </summary> public static readonly Color Lavender = FromRgba(230, 230, 250, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFF0F5. /// </summary> public static readonly Color LavenderBlush = FromRgba(255, 240, 245, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #7CFC00. /// </summary> public static readonly Color LawnGreen = FromRgba(124, 252, 0, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFFACD. /// </summary> public static readonly Color LemonChiffon = FromRgba(255, 250, 205, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #ADD8E6. /// </summary> public static readonly Color LightBlue = FromRgba(173, 216, 230, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #F08080. /// </summary> public static readonly Color LightCoral = FromRgba(240, 128, 128, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #E0FFFF. /// </summary> public static readonly Color LightCyan = FromRgba(224, 255, 255, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FAFAD2. /// </summary> public static readonly Color LightGoldenrodYellow = FromRgba(250, 250, 210, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #D3D3D3. /// </summary> public static readonly Color LightGray = FromRgba(211, 211, 211, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #90EE90. /// </summary> public static readonly Color LightGreen = FromRgba(144, 238, 144, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #D3D3D3. /// </summary> public static readonly Color LightGrey = LightGray; /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFB6C1. /// </summary> public static readonly Color LightPink = FromRgba(255, 182, 193, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFA07A. /// </summary> public static readonly Color LightSalmon = FromRgba(255, 160, 122, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #20B2AA. /// </summary> public static readonly Color LightSeaGreen = FromRgba(32, 178, 170, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #87CEFA. /// </summary> public static readonly Color LightSkyBlue = FromRgba(135, 206, 250, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #778899. /// </summary> public static readonly Color LightSlateGray = FromRgba(119, 136, 153, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #778899. /// </summary> public static readonly Color LightSlateGrey = LightSlateGray; /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #B0C4DE. /// </summary> public static readonly Color LightSteelBlue = FromRgba(176, 196, 222, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFFFE0. /// </summary> public static readonly Color LightYellow = FromRgba(255, 255, 224, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #00FF00. /// </summary> public static readonly Color Lime = FromRgba(0, 255, 0, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #32CD32. /// </summary> public static readonly Color LimeGreen = FromRgba(50, 205, 50, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FAF0E6. /// </summary> public static readonly Color Linen = FromRgba(250, 240, 230, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FF00FF. /// </summary> public static readonly Color Magenta = Fuchsia; /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #800000. /// </summary> public static readonly Color Maroon = FromRgba(128, 0, 0, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #66CDAA. /// </summary> public static readonly Color MediumAquamarine = FromRgba(102, 205, 170, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #0000CD. /// </summary> public static readonly Color MediumBlue = FromRgba(0, 0, 205, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #BA55D3. /// </summary> public static readonly Color MediumOrchid = FromRgba(186, 85, 211, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #9370DB. /// </summary> public static readonly Color MediumPurple = FromRgba(147, 112, 219, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #3CB371. /// </summary> public static readonly Color MediumSeaGreen = FromRgba(60, 179, 113, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #7B68EE. /// </summary> public static readonly Color MediumSlateBlue = FromRgba(123, 104, 238, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #00FA9A. /// </summary> public static readonly Color MediumSpringGreen = FromRgba(0, 250, 154, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #48D1CC. /// </summary> public static readonly Color MediumTurquoise = FromRgba(72, 209, 204, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #C71585. /// </summary> public static readonly Color MediumVioletRed = FromRgba(199, 21, 133, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #191970. /// </summary> public static readonly Color MidnightBlue = FromRgba(25, 25, 112, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #F5FFFA. /// </summary> public static readonly Color MintCream = FromRgba(245, 255, 250, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFE4E1. /// </summary> public static readonly Color MistyRose = FromRgba(255, 228, 225, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFE4B5. /// </summary> public static readonly Color Moccasin = FromRgba(255, 228, 181, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFDEAD. /// </summary> public static readonly Color NavajoWhite = FromRgba(255, 222, 173, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #000080. /// </summary> public static readonly Color Navy = FromRgba(0, 0, 128, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FDF5E6. /// </summary> public static readonly Color OldLace = FromRgba(253, 245, 230, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #808000. /// </summary> public static readonly Color Olive = FromRgba(128, 128, 0, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #6B8E23. /// </summary> public static readonly Color OliveDrab = FromRgba(107, 142, 35, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFA500. /// </summary> public static readonly Color Orange = FromRgba(255, 165, 0, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FF4500. /// </summary> public static readonly Color OrangeRed = FromRgba(255, 69, 0, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #DA70D6. /// </summary> public static readonly Color Orchid = FromRgba(218, 112, 214, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #EEE8AA. /// </summary> public static readonly Color PaleGoldenrod = FromRgba(238, 232, 170, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #98FB98. /// </summary> public static readonly Color PaleGreen = FromRgba(152, 251, 152, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #AFEEEE. /// </summary> public static readonly Color PaleTurquoise = FromRgba(175, 238, 238, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #DB7093. /// </summary> public static readonly Color PaleVioletRed = FromRgba(219, 112, 147, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFEFD5. /// </summary> public static readonly Color PapayaWhip = FromRgba(255, 239, 213, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFDAB9. /// </summary> public static readonly Color PeachPuff = FromRgba(255, 218, 185, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #CD853F. /// </summary> public static readonly Color Peru = FromRgba(205, 133, 63, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFC0CB. /// </summary> public static readonly Color Pink = FromRgba(255, 192, 203, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #DDA0DD. /// </summary> public static readonly Color Plum = FromRgba(221, 160, 221, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #B0E0E6. /// </summary> public static readonly Color PowderBlue = FromRgba(176, 224, 230, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #800080. /// </summary> public static readonly Color Purple = FromRgba(128, 0, 128, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #663399. /// </summary> public static readonly Color RebeccaPurple = FromRgba(102, 51, 153, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FF0000. /// </summary> public static readonly Color Red = FromRgba(255, 0, 0, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #BC8F8F. /// </summary> public static readonly Color RosyBrown = FromRgba(188, 143, 143, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #4169E1. /// </summary> public static readonly Color RoyalBlue = FromRgba(65, 105, 225, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #8B4513. /// </summary> public static readonly Color SaddleBrown = FromRgba(139, 69, 19, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FA8072. /// </summary> public static readonly Color Salmon = FromRgba(250, 128, 114, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #F4A460. /// </summary> public static readonly Color SandyBrown = FromRgba(244, 164, 96, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #2E8B57. /// </summary> public static readonly Color SeaGreen = FromRgba(46, 139, 87, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFF5EE. /// </summary> public static readonly Color SeaShell = FromRgba(255, 245, 238, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #A0522D. /// </summary> public static readonly Color Sienna = FromRgba(160, 82, 45, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #C0C0C0. /// </summary> public static readonly Color Silver = FromRgba(192, 192, 192, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #87CEEB. /// </summary> public static readonly Color SkyBlue = FromRgba(135, 206, 235, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #6A5ACD. /// </summary> public static readonly Color SlateBlue = FromRgba(106, 90, 205, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #708090. /// </summary> public static readonly Color SlateGray = FromRgba(112, 128, 144, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #708090. /// </summary> public static readonly Color SlateGrey = SlateGray; /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFFAFA. /// </summary> public static readonly Color Snow = FromRgba(255, 250, 250, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #00FF7F. /// </summary> public static readonly Color SpringGreen = FromRgba(0, 255, 127, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #4682B4. /// </summary> public static readonly Color SteelBlue = FromRgba(70, 130, 180, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #D2B48C. /// </summary> public static readonly Color Tan = FromRgba(210, 180, 140, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #008080. /// </summary> public static readonly Color Teal = FromRgba(0, 128, 128, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #D8BFD8. /// </summary> public static readonly Color Thistle = FromRgba(216, 191, 216, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FF6347. /// </summary> public static readonly Color Tomato = FromRgba(255, 99, 71, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #00000000. /// </summary> public static readonly Color Transparent = FromRgba(0, 0, 0, 0); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #40E0D0. /// </summary> public static readonly Color Turquoise = FromRgba(64, 224, 208, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #EE82EE. /// </summary> public static readonly Color Violet = FromRgba(238, 130, 238, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #F5DEB3. /// </summary> public static readonly Color Wheat = FromRgba(245, 222, 179, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFFFFF. /// </summary> public static readonly Color White = FromRgba(255, 255, 255, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #F5F5F5. /// </summary> public static readonly Color WhiteSmoke = FromRgba(245, 245, 245, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #FFFF00. /// </summary> public static readonly Color Yellow = FromRgba(255, 255, 0, 255); /// <summary> /// Represents a <see paramref="Color"/> matching the W3C definition that has an hex value of #9ACD32. /// </summary> public static readonly Color YellowGreen = FromRgba(154, 205, 50, 255); private static Dictionary<string, Color> CreateNamedColorsLookup() { return new Dictionary<string, Color>(StringComparer.OrdinalIgnoreCase) { { nameof(AliceBlue), AliceBlue }, { nameof(AntiqueWhite), AntiqueWhite }, { nameof(Aqua), Aqua }, { nameof(Aquamarine), Aquamarine }, { nameof(Azure), Azure }, { nameof(Beige), Beige }, { nameof(Bisque), Bisque }, { nameof(Black), Black }, { nameof(BlanchedAlmond), BlanchedAlmond }, { nameof(Blue), Blue }, { nameof(BlueViolet), BlueViolet }, { nameof(Brown), Brown }, { nameof(BurlyWood), BurlyWood }, { nameof(CadetBlue), CadetBlue }, { nameof(Chartreuse), Chartreuse }, { nameof(Chocolate), Chocolate }, { nameof(Coral), Coral }, { nameof(CornflowerBlue), CornflowerBlue }, { nameof(Cornsilk), Cornsilk }, { nameof(Crimson), Crimson }, { nameof(Cyan), Cyan }, { nameof(DarkBlue), DarkBlue }, { nameof(DarkCyan), DarkCyan }, { nameof(DarkGoldenrod), DarkGoldenrod }, { nameof(DarkGray), DarkGray }, { nameof(DarkGreen), DarkGreen }, { nameof(DarkGrey), DarkGrey }, { nameof(DarkKhaki), DarkKhaki }, { nameof(DarkMagenta), DarkMagenta }, { nameof(DarkOliveGreen), DarkOliveGreen }, { nameof(DarkOrange), DarkOrange }, { nameof(DarkOrchid), DarkOrchid }, { nameof(DarkRed), DarkRed }, { nameof(DarkSalmon), DarkSalmon }, { nameof(DarkSeaGreen), DarkSeaGreen }, { nameof(DarkSlateBlue), DarkSlateBlue }, { nameof(DarkSlateGray), DarkSlateGray }, { nameof(DarkSlateGrey), DarkSlateGrey }, { nameof(DarkTurquoise), DarkTurquoise }, { nameof(DarkViolet), DarkViolet }, { nameof(DeepPink), DeepPink }, { nameof(DeepSkyBlue), DeepSkyBlue }, { nameof(DimGray), DimGray }, { nameof(DimGrey), DimGrey }, { nameof(DodgerBlue), DodgerBlue }, { nameof(Firebrick), Firebrick }, { nameof(FloralWhite), FloralWhite }, { nameof(ForestGreen), ForestGreen }, { nameof(Fuchsia), Fuchsia }, { nameof(Gainsboro), Gainsboro }, { nameof(GhostWhite), GhostWhite }, { nameof(Gold), Gold }, { nameof(Goldenrod), Goldenrod }, { nameof(Gray), Gray }, { nameof(Green), Green }, { nameof(GreenYellow), GreenYellow }, { nameof(Grey), Grey }, { nameof(Honeydew), Honeydew }, { nameof(HotPink), HotPink }, { nameof(IndianRed), IndianRed }, { nameof(Indigo), Indigo }, { nameof(Ivory), Ivory }, { nameof(Khaki), Khaki }, { nameof(Lavender), Lavender }, { nameof(LavenderBlush), LavenderBlush }, { nameof(LawnGreen), LawnGreen }, { nameof(LemonChiffon), LemonChiffon }, { nameof(LightBlue), LightBlue }, { nameof(LightCoral), LightCoral }, { nameof(LightCyan), LightCyan }, { nameof(LightGoldenrodYellow), LightGoldenrodYellow }, { nameof(LightGray), LightGray }, { nameof(LightGreen), LightGreen }, { nameof(LightGrey), LightGrey }, { nameof(LightPink), LightPink }, { nameof(LightSalmon), LightSalmon }, { nameof(LightSeaGreen), LightSeaGreen }, { nameof(LightSkyBlue), LightSkyBlue }, { nameof(LightSlateGray), LightSlateGray }, { nameof(LightSlateGrey), LightSlateGrey }, { nameof(LightSteelBlue), LightSteelBlue }, { nameof(LightYellow), LightYellow }, { nameof(Lime), Lime }, { nameof(LimeGreen), LimeGreen }, { nameof(Linen), Linen }, { nameof(Magenta), Magenta }, { nameof(Maroon), Maroon }, { nameof(MediumAquamarine), MediumAquamarine }, { nameof(MediumBlue), MediumBlue }, { nameof(MediumOrchid), MediumOrchid }, { nameof(MediumPurple), MediumPurple }, { nameof(MediumSeaGreen), MediumSeaGreen }, { nameof(MediumSlateBlue), MediumSlateBlue }, { nameof(MediumSpringGreen), MediumSpringGreen }, { nameof(MediumTurquoise), MediumTurquoise }, { nameof(MediumVioletRed), MediumVioletRed }, { nameof(MidnightBlue), MidnightBlue }, { nameof(MintCream), MintCream }, { nameof(MistyRose), MistyRose }, { nameof(Moccasin), Moccasin }, { nameof(NavajoWhite), NavajoWhite }, { nameof(Navy), Navy }, { nameof(OldLace), OldLace }, { nameof(Olive), Olive }, { nameof(OliveDrab), OliveDrab }, { nameof(Orange), Orange }, { nameof(OrangeRed), OrangeRed }, { nameof(Orchid), Orchid }, { nameof(PaleGoldenrod), PaleGoldenrod }, { nameof(PaleGreen), PaleGreen }, { nameof(PaleTurquoise), PaleTurquoise }, { nameof(PaleVioletRed), PaleVioletRed }, { nameof(PapayaWhip), PapayaWhip }, { nameof(PeachPuff), PeachPuff }, { nameof(Peru), Peru }, { nameof(Pink), Pink }, { nameof(Plum), Plum }, { nameof(PowderBlue), PowderBlue }, { nameof(Purple), Purple }, { nameof(RebeccaPurple), RebeccaPurple }, { nameof(Red), Red }, { nameof(RosyBrown), RosyBrown }, { nameof(RoyalBlue), RoyalBlue }, { nameof(SaddleBrown), SaddleBrown }, { nameof(Salmon), Salmon }, { nameof(SandyBrown), SandyBrown }, { nameof(SeaGreen), SeaGreen }, { nameof(SeaShell), SeaShell }, { nameof(Sienna), Sienna }, { nameof(Silver), Silver }, { nameof(SkyBlue), SkyBlue }, { nameof(SlateBlue), SlateBlue }, { nameof(SlateGray), SlateGray }, { nameof(SlateGrey), SlateGrey }, { nameof(Snow), Snow }, { nameof(SpringGreen), SpringGreen }, { nameof(SteelBlue), SteelBlue }, { nameof(Tan), Tan }, { nameof(Teal), Teal }, { nameof(Thistle), Thistle }, { nameof(Tomato), Tomato }, { nameof(Transparent), Transparent }, { nameof(Turquoise), Turquoise }, { nameof(Violet), Violet }, { nameof(Wheat), Wheat }, { nameof(White), White }, { nameof(WhiteSmoke), WhiteSmoke }, { nameof(Yellow), Yellow }, { nameof(YellowGreen), YellowGreen } }; } } }
46.810664
155
0.587136
[ "Apache-2.0" ]
fahadabdulaziz/ImageSharp
src/ImageSharp/Color/Color.NamedColors.cs
43,019
C#
// * ************************************************************************** // * Copyright (c) McCreary, Veselka, Bragg & Allen, P.C. // * This source code is subject to terms and conditions of the MIT License. // * A copy of the license can be found in the License.txt file // * at the root of this distribution. // * By using this source code in any fashion, you are agreeing to be bound by // * the terms of the MIT License. // * You must not remove this notice from this software. // * ************************************************************************** using System.Web.UI.WebControls; namespace FluentWebControls { public class AlignAttribute { public static AlignAttribute Center = new AlignAttribute("center", HorizontalAlign.Center); public static AlignAttribute Left = new AlignAttribute("left", HorizontalAlign.Left); public static AlignAttribute Right = new AlignAttribute("right", HorizontalAlign.Right); private readonly HorizontalAlign _horizontalAlign; private AlignAttribute(string text, HorizontalAlign horizontalAlign) { _horizontalAlign = horizontalAlign; Text = text; } public string Text { get; } public HorizontalAlign ToHorizontalAlign() { return _horizontalAlign; } public override string ToString() { return $" align='{Text}'"; } } }
33.25
93
0.643609
[ "MIT" ]
mvbalaw/FluentWebControls
src/FluentWebControls/AlignAttribute.cs
1,330
C#
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System; using System.Globalization; using System.Runtime.Serialization; using System.Text.RegularExpressions; using Elasticsearch.Net; using Elasticsearch.Net.Utf8Json; namespace Nest { [StringEnum] public enum IntervalUnit { [EnumMember(Value = "s")] Second, [EnumMember(Value = "m")] Minute, [EnumMember(Value = "h")] Hour, [EnumMember(Value = "d")] Day, [EnumMember(Value = "w")] Week, } [JsonFormatter(typeof(IntervalFormatter))] public class Interval : ScheduleBase, IComparable<Interval>, IEquatable<Interval> { private const long DaySeconds = 86400; private const long HourSeconds = 3600; private const long MinuteSeconds = 60; private const long Second = 1; private const long WeekSeconds = 604800; private static readonly Regex IntervalExpressionRegex = new Regex(@"^(?<factor>\d+)(?<unit>(?:w|d|h|m|s))?$", RegexOptions.Compiled | RegexOptions.ExplicitCapture); private long _seconds; public Interval(TimeSpan timeSpan) { if (timeSpan.TotalSeconds < 1) throw new ArgumentException("must be greater than or equal to 1 second", nameof(timeSpan)); var totalSeconds = (long)timeSpan.TotalSeconds; if (totalSeconds >= WeekSeconds && totalSeconds % WeekSeconds == 0) { Factor = totalSeconds / WeekSeconds; Unit = IntervalUnit.Week; } else if (totalSeconds >= DaySeconds && totalSeconds % DaySeconds == 0) { Factor = totalSeconds / DaySeconds; Unit = IntervalUnit.Day; } else if (totalSeconds >= HourSeconds && totalSeconds % HourSeconds == 0) { Factor = totalSeconds / HourSeconds; Unit = IntervalUnit.Hour; } else if (totalSeconds >= MinuteSeconds && totalSeconds % MinuteSeconds == 0) { Factor = totalSeconds / MinuteSeconds; Unit = IntervalUnit.Minute; } else { Factor = totalSeconds; Unit = IntervalUnit.Second; } _seconds = totalSeconds; } public Interval(long seconds) { Factor = seconds; _seconds = seconds; } public Interval(long factor, IntervalUnit unit) { Factor = factor; Unit = unit; SetSeconds(Factor, unit); } public Interval(string intervalUnit) { if (intervalUnit.IsNullOrEmpty()) throw new ArgumentException("Interval expression string cannot be null or empty", nameof(intervalUnit)); var match = IntervalExpressionRegex.Match(intervalUnit); if (!match.Success) throw new ArgumentException($"Interval expression '{intervalUnit}' string is invalid", nameof(intervalUnit)); Factor = long.Parse(match.Groups["factor"].Value, CultureInfo.InvariantCulture); var unit = match.Groups["unit"].Success ? match.Groups["unit"].Value.ToEnum<IntervalUnit>().GetValueOrDefault(IntervalUnit.Second) : IntervalUnit.Second; Unit = unit; SetSeconds(Factor, unit); } public long Factor { get; } public IntervalUnit? Unit { get; } public int CompareTo(Interval other) { if (other == null) return 1; if (_seconds == other._seconds) return 0; if (_seconds < other._seconds) return -1; return 1; } public bool Equals(Interval other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return _seconds == other._seconds; } public static implicit operator Interval(TimeSpan timeSpan) => new Interval(timeSpan); public static implicit operator Interval(long seconds) => new Interval(seconds); public static implicit operator Interval(string expression) => new Interval(expression); public static bool operator <(Interval left, Interval right) => left.CompareTo(right) < 0; public static bool operator <=(Interval left, Interval right) => left.CompareTo(right) < 0 || left.Equals(right); public static bool operator >(Interval left, Interval right) => left.CompareTo(right) > 0; public static bool operator >=(Interval left, Interval right) => left.CompareTo(right) > 0 || left.Equals(right); public static bool operator ==(Interval left, Interval right) => ReferenceEquals(left, null) ? ReferenceEquals(right, null) : left.Equals(right); public static bool operator !=(Interval left, Interval right) => !(left == right); public override string ToString() { var factor = Factor.ToString(CultureInfo.InvariantCulture); return Unit.HasValue ? factor + Unit.Value.GetStringValue() : factor; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((Interval)obj); } // ReSharper disable once NonReadonlyMemberInGetHashCode public override int GetHashCode() => _seconds.GetHashCode(); internal override void WrapInContainer(IScheduleContainer container) => container.Interval = this; private void SetSeconds(long factor, IntervalUnit interval) { switch (interval) { case IntervalUnit.Week: _seconds = factor * WeekSeconds; break; case IntervalUnit.Day: _seconds = factor * DaySeconds; break; case IntervalUnit.Hour: _seconds = factor * HourSeconds; break; case IntervalUnit.Minute: _seconds = factor * MinuteSeconds; break; case IntervalUnit.Second: _seconds = factor * Second; break; } } } internal class IntervalFormatter : IJsonFormatter<Interval> { public Interval Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver) { var token = reader.GetCurrentJsonToken(); switch (token) { case JsonToken.String: return new Interval(reader.ReadString()); case JsonToken.Number: var seconds = Convert.ToInt64(reader.ReadDouble()); return new Interval(seconds); default: reader.ReadNextBlock(); return null; } } public void Serialize(ref JsonWriter writer, Interval value, IJsonFormatterResolver formatterResolver) { if (value.Unit.HasValue) writer.WriteString(value.ToString()); else writer.WriteInt64(value.Factor); } } }
27.839286
115
0.704458
[ "Apache-2.0" ]
Atharvpatel21/elasticsearch-net
src/Nest/XPack/Watcher/Schedule/Interval.cs
6,236
C#
using Extensions; using System.Collections.Generic; public class MathFloatExpression { public MathFloatTerm[] terms = new MathFloatTerm[2]; public MathOperation[] operations = new MathOperation[1]; public MathFloatExpression (MathFloatTerm[] terms, MathOperation[] operations) { this.terms = terms; this.operations = operations; } public float? GetValue () { MathFloatExpression expression = new MathFloatExpression(terms, operations); float? output = null; int[] indicesOfOperation = new List<MathOperation>(operations).GetIndicesOf<MathOperation>(MathOperation.Factorial); int removedOperationCount = 0; for (int i = 0; i < indicesOfOperation.Length; i ++) { MathFloatTerm term = terms[i]; float value = term.number; for (int i2 = (int) term.number - 1; i2 > 1; i2 --) value *= i; output = value; expression.operations = expression.operations.RemoveAt(i - removedOperationCount); } return output; } public bool OperationsAreInOrder () { List<MathOperation> operations = new List<MathOperation>(this.operations); bool? isSubtractAfterAdd = operations.AreAllInstancesFoundAfterAllOthers<MathOperation>(new MathOperation[1] { MathOperation.Subtract }, new MathOperation[1] { MathOperation.Add }); bool? isAddAfterDivide = operations.AreAllInstancesFoundAfterAllOthers<MathOperation>(new MathOperation[1] { MathOperation.Add }, new MathOperation[1] { MathOperation.Divide }); bool? isDivideAfterMultiply = operations.AreAllInstancesFoundAfterAllOthers<MathOperation>(new MathOperation[1] { MathOperation.Divide }, new MathOperation[1] { MathOperation.Multiply }); bool? isMultiplyAfterExponent = operations.AreAllInstancesFoundAfterAllOthers<MathOperation>(new MathOperation[1] { MathOperation.Multiply }, new MathOperation[1] { MathOperation.Exponent }); return (isSubtractAfterAdd == null || (bool) isSubtractAfterAdd) && (isAddAfterDivide == null || (bool) isAddAfterDivide) && (isDivideAfterMultiply == null || (bool) isDivideAfterMultiply) && (isMultiplyAfterExponent == null || (bool) isMultiplyAfterExponent); } }
49.619048
262
0.761996
[ "Apache-2.0" ]
Master109/open-brush
Assets/New Assets/New Standard Assets/Scripts/Concepts/MathFloatExpression.cs
2,084
C#
// Copyright 2017 the original author or authors. // // 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 // // https://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 Steeltoe.CircuitBreaker.Hystrix.Util; using Steeltoe.Common.Util; namespace Steeltoe.CircuitBreaker.Hystrix.Collapser { public class RealCollapserTimer : ICollapserTimer { private static readonly HystrixTimer Timer = HystrixTimer.GetInstance(); public TimerReference AddListener(ITimerListener collapseTask) { return Timer.AddTimerListener(collapseTask); } } }
34.4
80
0.741279
[ "Apache-2.0" ]
FrancisChung/steeltoe
src/CircuitBreaker/src/HystrixBase/Collapser/RealCollapserTimer.cs
1,034
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace EpiInfo.Plugin { public interface IScope { string Name { get; set; } Dictionary<string, EpiInfo.Plugin.IVariable> SymbolList { get; } IScope GetEnclosingScope(); void Define(EpiInfo.Plugin.IVariable Symbol); void Undefine(string Name, string variableNamespace = null); void RemoveVariablesInScope(EpiInfo.Plugin.VariableScope scopeCombination, string variableNamespace = null); EpiInfo.Plugin.IVariable Resolve(string name, string variableNamespace = null); List<EpiInfo.Plugin.IVariable> FindVariables(EpiInfo.Plugin.VariableScope scopeCombination, string variableNamespace = null); } }
36.714286
133
0.725032
[ "Apache-2.0" ]
82ndAirborneDiv/Epi-Info-Cloud-Contact-Tracing
Cloud Enter/Epi.Compatibility/EpiInfoPlugin/IScope.cs
773
C#
using Newtonsoft.Json; using System.Linq; namespace LINGYUN.Abp.WebhooksManagement.Extensions { public static class WebhookSubscriptionExtensions { public static WebhookSubscriptionDto ToWebhookSubscriptionDto(this WebhookSubscription webhookSubscription) { return new WebhookSubscriptionDto { Id = webhookSubscription.Id, TenantId = webhookSubscription.TenantId, IsActive = webhookSubscription.IsActive, Secret = webhookSubscription.Secret, WebhookUri = webhookSubscription.WebhookUri, Webhooks = webhookSubscription.GetSubscribedWebhooks(), Headers = webhookSubscription.GetWebhookHeaders(), CreationTime = webhookSubscription.CreationTime, CreatorId = webhookSubscription.CreatorId }; } public static string ToSubscribedWebhooksString(this WebhookSubscriptionUpdateInput webhookSubscription) { if (webhookSubscription.Webhooks.Any()) { return JsonConvert.SerializeObject(webhookSubscription.Webhooks); } return null; } public static string ToWebhookHeadersString(this WebhookSubscriptionUpdateInput webhookSubscription) { if (webhookSubscription.Headers.Any()) { return JsonConvert.SerializeObject(webhookSubscription.Headers); } return null; } } }
35.422222
116
0.61606
[ "MIT" ]
colinin/abp-next-admin
aspnet-core/modules/webhooks/LINGYUN.Abp.WebhooksManagement.Application/LINGYUN/Abp/WebhooksManagement/Extensions/WebhookSubscriptionExtensions.cs
1,596
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the redshift-2012-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Redshift.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.Redshift.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DeleteEndpointAccess operation /// </summary> public class DeleteEndpointAccessResponseUnmarshaller : XmlResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { DeleteEndpointAccessResponse response = new DeleteEndpointAccessResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.IsStartElement) { if(context.TestExpression("DeleteEndpointAccessResult", 2)) { UnmarshallResult(context, response); continue; } if (context.TestExpression("ResponseMetadata", 2)) { response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context); } } } return response; } private static void UnmarshallResult(XmlUnmarshallerContext context, DeleteEndpointAccessResponse response) { int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("Address", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.Address = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ClusterIdentifier", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.ClusterIdentifier = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("EndpointCreateTime", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; response.EndpointCreateTime = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("EndpointName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.EndpointName = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("EndpointStatus", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.EndpointStatus = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Port", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; response.Port = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ResourceOwner", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.ResourceOwner = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("SubnetGroupName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.SubnetGroupName = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("VpcEndpoint", targetDepth)) { var unmarshaller = VpcEndpointUnmarshaller.Instance; response.VpcEndpoint = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("VpcSecurityGroups/VpcSecurityGroup", targetDepth)) { var unmarshaller = VpcSecurityGroupMembershipUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); response.VpcSecurityGroups.Add(item); continue; } } } return; } /// <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(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new XmlUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("ClusterNotFound")) { return ClusterNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("EndpointNotFound")) { return EndpointNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidClusterSecurityGroupState")) { return InvalidClusterSecurityGroupStateExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidClusterState")) { return InvalidClusterStateExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidEndpointState")) { return InvalidEndpointStateExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonRedshiftException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static DeleteEndpointAccessResponseUnmarshaller _instance = new DeleteEndpointAccessResponseUnmarshaller(); internal static DeleteEndpointAccessResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DeleteEndpointAccessResponseUnmarshaller Instance { get { return _instance; } } } }
42.90566
163
0.562335
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Redshift/Generated/Model/Internal/MarshallTransformations/DeleteEndpointAccessResponseUnmarshaller.cs
9,096
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Cake.Core; namespace Cake.Common.Build.BitbucketPipelines.Data; /// <summary> /// Provides Bitbucket Pipelines repository information for the current build. /// </summary> public class BitbucketPipelinesRepositoryInfo : BitbucketPipelinesInfo { /// <summary> /// Gets the branch on which the build was kicked off. This value is only available on branches. /// </summary> /// <remarks>Note: <see cref="Branch"/> and <see cref="Tag"/> are mutually exclusive. If you use both, only one will have a value.</remarks> /// <value> /// The SCM branch. /// </value> public string Branch => GetEnvironmentString("BITBUCKET_BRANCH"); /// <summary> /// Gets the tag on which the build was kicked off. This value is only available when tagged. /// </summary> /// <remarks>Note: <see cref="Branch"/> and <see cref="Tag"/> are mutually exclusive. If you use both, only one will have a value.</remarks> /// <value> /// The SCM tag. /// </value> public string Tag => GetEnvironmentString("BITBUCKET_TAG"); /// <summary> /// Gets the commit hash of a commit that kicked off the build. /// </summary> /// <value> /// The SCM commit. /// </value> public string Commit => GetEnvironmentString("BITBUCKET_COMMIT"); /// <summary> /// Gets the name of the account in which the repository lives. /// </summary> /// <value> /// The repository owner account. /// </value> public string RepoOwner => GetEnvironmentString("BITBUCKET_REPO_OWNER"); /// <summary> /// Gets the URL-friendly version of a repository name. /// </summary> /// <value> /// The URL-friendly repository name. /// </value> public string RepoSlug => GetEnvironmentString("BITBUCKET_REPO_SLUG"); /// <summary> /// Initializes a new instance of the <see cref="BitbucketPipelinesRepositoryInfo"/> class. /// </summary> /// <param name="environment">The environment.</param> public BitbucketPipelinesRepositoryInfo(ICakeEnvironment environment) : base(environment) { } }
36.539683
144
0.661164
[ "MIT" ]
ecampidoglio/cake
src/Cake.Common/Build/BitbucketPipelines/Data/BitbucketPipelinesRepositoryInfo.cs
2,304
C#
using ExtendedXmlSerializer.Configuration; using ExtendedXmlSerializer.Tests.ReportedIssues.Support; using FluentAssertions; using System; using Xunit; namespace ExtendedXmlSerializer.Tests.ReportedIssues { public sealed class Issue397Tests { [Fact] public void Verify() { var serializer = new ConfigurationContainer().UseAutoFormatting() .UseOptimizedNamespaces() .EnableImplicitTyping(typeof(MainDTO), typeof(SubDTO), typeof(SubSubDTO)) .Type<SubSubDTO>() .EnableReferences(definition => definition.Id) .Create() .ForTesting(); var instance = new MainDTO(); var cycled = serializer.Cycle(instance); cycled.Sub1.SubSub1.Should().BeSameAs(cycled.Sub2.SubSub1); cycled.Sub1.SubSub1.Should().BeSameAs(cycled.Sub3.SubSub1); } public class MainDTO { public SubDTO Sub1 { get; set; } = new SubDTO(); public SubDTO Sub2 { get; set; } = new SubDTO(); public SubDTO Sub3 { get; set; } = new SubDTO(); } public class SubDTO { public SubSubDTO SubSub1 { get; set; } = SubSubDTO.NullObject; } public class SubSubDTO { public static SubSubDTO NullObject { get; } = new SubSubDTO(); public string Id { get; set; } = Guid.NewGuid().ToString(); } } }
32.583333
104
0.553069
[ "MIT" ]
ExtendedXmlSerializer/ExtendedXmlSerializer
test/ExtendedXmlSerializer.Tests.ReportedIssues/Issue397Tests.cs
1,566
C#
using AngelNode.Model.Resource; using AngelNode.ViewModel; using GongSolutions.Wpf.DragDrop; using System.Windows; using System.Windows.Controls; using System.Linq; namespace AngelNode.Util { class OutfitDropHandler : IDropTarget { public void DragOver(IDropInfo dropInfo) { if (dropInfo.Data is Directory) { dropInfo.Effects = DragDropEffects.All; dropInfo.DropTargetAdorner = DropTargetAdorners.Highlight; } } public void Drop(IDropInfo dropInfo) { var dataContext = (CharacterViewModel)((ListView)dropInfo.VisualTarget).DataContext; var outfits = dataContext.Character?.Outfits; var directory = dropInfo.Data as Directory; if (outfits.Any(outfit => outfit.Directory?.Path == directory.Path)) return; outfits.Add(new Model.Outfit { Directory = directory, Name = directory.Name }); // First added outfit, populate outfit poses if (outfits.Count == 1) dataContext.Character.RebuildOutfitPoses(); } } }
29
96
0.601346
[ "MIT" ]
virusek20/AngelNodeCore
Util/OutfitDropHandler.cs
1,191
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20201101.Outputs { [OutputType] public sealed class AzureFirewallPublicIPAddressResponse { /// <summary> /// Public IP Address value. /// </summary> public readonly string? Address; [OutputConstructor] private AzureFirewallPublicIPAddressResponse(string? address) { Address = address; } } }
25.785714
81
0.671745
[ "Apache-2.0" ]
sebtelko/pulumi-azure-native
sdk/dotnet/Network/V20201101/Outputs/AzureFirewallPublicIPAddressResponse.cs
722
C#
using ActionWorkflow.Tracing; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace ActionWorkflow { public class ActionSequence<T> { private readonly IList<ActionInfo> _actionInfos; private readonly int _actionInfosInitialCount; private readonly IServiceProvider _serviceProvider; private readonly IExportProvider _exportProvider; public ActionSequence(IList<ActionInfo> actionInfos, IExportProvider exportProvider = null) : this(actionInfos, null, exportProvider) { } public ActionSequence(IList<ActionInfo> actionInfos, IServiceProvider serviceProvider, IExportProvider exportProvider = null) { _actionInfos = actionInfos ?? throw new ArgumentNullException(nameof(actionInfos)); _actionInfosInitialCount = actionInfos.Count; _serviceProvider = serviceProvider; _exportProvider = exportProvider ?? new ActionExportProvider(); } private ActionBundle<T> GetNextActionBundle() { List<ActionItem<T>> entries = null; for (int i = 0; i < _actionInfos.Count; i++) { var curActionInfo = _actionInfos[i]; if (curActionInfo.TypesToImport.Count > 0) { bool continueLoop = false; foreach (var curImportType in curActionInfo.TypesToImport) { if (!_exportProvider.ContainsExport(curImportType)) { continueLoop = true; break; } } if (continueLoop) { continue; } } if (entries == null) { entries = new List<ActionItem<T>>(); } entries.Add( this.CreateActionItem(curActionInfo)); _actionInfos.RemoveAt(i--); } return entries == null ? null : new ActionBundle<T>(entries); } private ActionItem<T> CreateActionItem(ActionInfo actionInfo) { var context = new DefaultActionContext(_exportProvider, actionInfo); var serviceProvider = new DefaultActionServiceProvider(context, _exportProvider, _serviceProvider); return new ActionItem<T>( (IAction<T>)ActivatorUtilities.CreateInstance(serviceProvider, actionInfo.ActionType), context, _exportProvider, serviceProvider); } public async Task<ActionSequenceExecutionResult> ExecuteAsync(T context) { // Check whether the target wants to be able to trace which actions were executed on it var trace = context is IActionTracingContainer atc ? atc.ActionTrace : null; try { trace?.AddEvent(ActionTraceEvent.Begin, this.ToString()); while (_actionInfos.Count > 0) { var actionBundle = this.GetNextActionBundle(); if (actionBundle == null) { // Stop the execution because no further actions are possible break; } // Execute all actions in the bundle await actionBundle.ExecuteAsync(context); } trace?.AddEvent(ActionTraceEvent.End, this.ToString()); } catch (Exception ex) { trace?.AddEvent(ActionTraceEvent.UnexpectedEnd, this.ToString(), ex); } return _actionInfos.Count == _actionInfosInitialCount ? ActionSequenceExecutionResult.None : _actionInfos.Count > 0 ? ActionSequenceExecutionResult.Partial : ActionSequenceExecutionResult.Full; } public override string ToString() { return $"{nameof(ActionSequence<T>)} ({_actionInfosInitialCount})"; } } }
34.539683
133
0.543888
[ "MIT" ]
jmptrader/action-workflow
src/ActionWorkflow/ActionSequence.cs
4,354
C#
using O10.Transactions.Core.Enums; namespace O10.Transactions.Core.Ledgers { public interface ILedgerPacket { LedgerType LedgerType { get; } } }
16.7
39
0.688623
[ "Apache-2.0" ]
muaddibco/O10city
Common/O10.Transactions.Core/Ledgers/ILedgerPacket.cs
169
C#