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
 namespace NetFramework { using Cloud.Governance.Client.Api; using Cloud.Governance.Client.Client; using Cloud.Governance.Client.Model; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; public class CreateSite_Basic : TestBase { public CreateSite_Basic(ApiConfig config) : base(config) { } public Guid Run(CreateSiteTestData data) { try { var serviceName = this.ServicesApi.GetServiceId(data.ServiceName); var service = this.ServicesApi.GetCreateSiteService(serviceName); var request = service.RequestTemplate; request.SiteUrl.Name = $"Api{DateTime.Now.Ticks}"; request.Summary = $"Summary_{DateTime.Now}"; request.SiteTitle = $"Title_{DateTime.Now}"; //request.Department = data.Department; request.PrimaryContact = new ApiUser { LoginName = data.PrimaryContactLoginName }; request.SecondaryContact = new ApiUser { LoginName = data.SecondaryContactLoginName }; return this.RequestsApi.SubmitCreateSiteRequest(request); } catch (ApiException e) { Console.WriteLine("Exception when calling RequestsApi.SubmitCreateSiteRequest: " + e.Message); Console.WriteLine("Status Code: " + e.ErrorCode); Console.WriteLine(e.StackTrace); } return Guid.Empty; } } }
34.413043
110
0.600758
[ "Apache-2.0" ]
AvePoint/cloud-governance-client
example/csharp/netframework/Requests/CreateSite/CreateSite_Basic.cs
1,585
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("MvcDemo.Web")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MvcDemo.Web")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b34fbaca-5677-4994-ba24-3461123c8c8b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.5
84
0.74963
[ "MIT" ]
LambertW/Fogy
samples/MvcDemo.Web/Properties/AssemblyInfo.cs
1,353
C#
// ********************************************************************************************************************** // // Copyright © 2005-2019 Trading Technologies International, Inc. // All Rights Reserved Worldwide // // * * * S T R I C T L Y P R O P R I E T A R Y * * * // // WARNING: This file and all related programs (including any computer programs, example programs, and all source code) // are the exclusive property of Trading Technologies International, Inc. (“TT”), are protected by copyright law and // international treaties, and are for use only by those with the express written permission from TT. Unauthorized // possession, reproduction, distribution, use or disclosure of this file and any related program (or document) derived // from it is prohibited by State and Federal law, and by local law outside of the U.S. and may result in severe civil // and criminal penalties. // // ************************************************************************************************************************ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Windows; using System.Windows.Data; using System.Runtime.CompilerServices; using tt_net_sdk; using System.Text.RegularExpressions; namespace TTNETAPI_Sample_WPF_VolumeRatio { #region TreeRow Implementation public interface ITreeRow : INotifyPropertyChanged { string MarketName { get; } string ProductName { get; } string ContractAlias { get; } decimal Volume { get; } long NumNewOrders { get; } long NumModifications { get; } long NumCancellations { get; } int Score { get; } decimal Ratio { get; } bool IsExpanded { get; set; } } public class MarketTreeRow : ITreeRow { public MarketTreeRow(Instrument instr) { m_market = instr.Product.Market; IsExpanded = false; CreateOrGetExistingChild(instr); } #region Tree Column Properties public string MarketName => m_market.Name; public string ProductName => string.Empty; public string ContractAlias => string.Empty; public long NumNewOrders => this.Children.Sum(x => x.NumNewOrders); public long NumModifications => this.Children.Sum(x => x.NumModifications); public long NumCancellations => this.Children.Sum(x => x.NumCancellations); public decimal Volume => this.Children.Sum(x => x.Volume); public int Score => this.Children.Sum(x => x.Score); public decimal Ratio => (this.Volume == 0) ? 0 : this.Score / this.Volume; #endregion #region TreeViewItem Methods/Properties public MarketId MarketId => m_market.MarketId; public ObservableCollection<ITreeRow> Children { get; } = new ObservableCollection<ITreeRow>(); public bool IsExpanded { get { return m_isExpanded; } set { m_isExpanded = value; NotifyPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion #region Public Methods public ProductTreeRow CreateOrGetExistingChild(Instrument instr) { var child = this.Children.FirstOrDefault(x => x.ProductName == instr.Product.Key.Name); if (child == null) { this.Children.Add(new ProductTreeRow(this, instr)); child = this.Children.Last(); child.PropertyChanged += (o, args) => { NotifyPropertyChanged(args.PropertyName); NotifyPropertyChanged("Score"); NotifyPropertyChanged("Ratio"); }; } return child as ProductTreeRow; } public void ResetWeights(int nos_weight, int chg_weight, int cxl_weight) { foreach (var child in Children) { var contractRow = child as ProductTreeRow; contractRow.ResetWeights(nos_weight, chg_weight, cxl_weight); } } #endregion #region Private Members private readonly Market m_market; private bool m_isExpanded = false; #endregion } public class ProductTreeRow : ITreeRow { public ProductTreeRow(MarketTreeRow parent, Instrument instr) { m_parent = parent; m_productKey = instr.Product.Key; CreateOrGetExistingChild(instr); } #region Tree Column Properties public string MarketName => string.Empty; public string ProductName => m_productKey.Name; public string ContractAlias => string.Empty; public decimal Volume => this.Children.Sum(x => x.Volume); public long NumNewOrders => this.Children.Sum(x => x.NumNewOrders); public long NumModifications => this.Children.Sum(x => x.NumModifications); public long NumCancellations => this.Children.Sum(x => x.NumCancellations); public int Score => this.Children.Sum(x => x.Score); public decimal Ratio => (this.Volume == 0) ? 0 : this.Score / this.Volume; #endregion #region TreeViewItem Methods/Properties public ulong ProductId => m_productKey.ProductId; public ObservableCollection<ITreeRow> Children { get; } = new ObservableCollection<ITreeRow>(); public bool IsExpanded { get { return m_isExpanded; } set { m_isExpanded = value; this.NotifyPropertyChanged("IsExpanded"); } } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion #region Public Methods public ContractTreeRow CreateOrGetExistingChild(Instrument instr) { var child = this.Children.FirstOrDefault(x => (x as ContractTreeRow).ContractId == instr.InstrumentDetails.Id); if (child == null) { this.Children.Add(new ContractTreeRow(this, instr)); child = this.Children.Last(); child.PropertyChanged += (o, args) => { NotifyPropertyChanged(args.PropertyName); NotifyPropertyChanged("Score"); NotifyPropertyChanged("Ratio"); }; } return child as ContractTreeRow; } public void ResetWeights(int nos_weight, int chg_weight, int cxl_weight) { foreach(var child in Children) { var contractRow = child as ContractTreeRow; contractRow.ResetWeights(nos_weight, chg_weight, cxl_weight); } } #endregion #region Private Members private readonly MarketTreeRow m_parent = null; private readonly ProductKey m_productKey = ProductKey.Empty; private bool m_isExpanded = false; #endregion } public class ContractTreeRow : ITreeRow { public ContractTreeRow(ProductTreeRow parent, Instrument instr) { m_parent = parent; m_instrKey = instr.Key; IsExpanded = false; } #region Tree Column Properties public string MarketName => string.Empty; public string ProductName => string.Empty; public string ContractAlias => m_instrKey.Alias; public decimal Volume { get { return m_volume; } set { m_volume = value; NotifyRatioChanged(); } } public long NumNewOrders { get { return m_numNewOrders; } set { m_numNewOrders = value; NotifyRatioChanged(); } } public long NumModifications { get { return m_numModifications; } set { m_numModifications = value; NotifyRatioChanged(); } } public long NumCancellations { get { return m_numCancellations; } set { m_numCancellations = value; NotifyRatioChanged(); } } public int Score => (int)(m_numNewOrders * m_nosWeight) + (int)(m_numModifications * m_chgWeight) + (int)(m_numCancellations * m_cxlWeight); public decimal Ratio => (this.Volume == 0) ? 0 : this.Score / this.Volume; #endregion #region TreeViewItem Methods/Properties public ProductTreeRow Parent => m_parent; public ulong ContractId => m_instrKey.InstrumentId; public bool IsExpanded { get { return m_isExpanded; } set { m_isExpanded = value; NotifyPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } private void NotifyRatioChanged([CallerMemberName] String baseProperty = "") { if (baseProperty != "") { NotifyPropertyChanged(baseProperty); } NotifyPropertyChanged("Score"); NotifyPropertyChanged("Ratio"); } #endregion #region Public Methods public void ProcessMessage(OrderAddedEventArgs e) { NumNewOrders++; } public void ProcessMessage(OrderUpdatedEventArgs e) { NumModifications++; } public void ProcessMessage(OrderDeletedEventArgs e) { NumCancellations++; } public void ProcessMessage(OrderFilledEventArgs e) { Volume += e.Fill.Quantity.Value; } public void ResetWeights(int nos_weight, int chg_weight, int cxl_weight) { m_nosWeight = nos_weight; m_chgWeight = chg_weight; m_cxlWeight = cxl_weight; NotifyRatioChanged(); } #endregion #region Private Members private int m_nosWeight = 0; private int m_chgWeight = 1; private int m_cxlWeight = 3; private decimal m_volume = 0; private long m_numNewOrders = 0; private long m_numModifications = 0; private long m_numCancellations = 0; private readonly InstrumentKey m_instrKey = InstrumentKey.Empty; private readonly ProductTreeRow m_parent = null; private bool m_isExpanded = false; #endregion } public class MarketList : ObservableCollection<MarketTreeRow> { public MarketList() : base() { } } #endregion /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private TTAPI m_api = null; private tt_net_sdk.Dispatcher m_dispatcher = null; private TradeSubscription m_ts = null; private bool m_shutdownComplete = false; private MarketList MarketListData = new MarketList(); public int NOS_Weight { get; set; } = 0; public int CHG_Weight { get; set; } = 1; public int CXL_Weight { get; set; } = 3; public MainWindow() { InitializeComponent(); this.DataContext = this; treeviewList.ItemsSource = MarketListData; var app = App.Current as TTNETAPI_Sample_WPF_VolumeRatio.App; m_dispatcher = app.SDKDispatcher; var app_key = "app_key"; var env = ServiceEnvironment.ProdSim; var mode = TTAPIOptions.SDKMode.Client; var options = new TTAPIOptions(mode, env, app_key, 5000); TTAPI.CreateTTAPI(m_dispatcher, options, new ApiInitializeHandler(OnSDKInitialized)); lblStatus.Text = "Initializing..."; } #region SDK Events private void OnSDKInitialized(TTAPI api, ApiCreationException ex) { if (ex == null) { lblStatus.Text = "Initialized. Authenticating..."; m_api = api; m_api.TTAPIStatusUpdate += OnSDKStatusUpdate; TTAPI.ShutdownCompleted += OnSDKShutdownComplete; m_api.Start(); } else if (!ex.IsRecoverable) { MessageBox.Show($"API Initialization Failed: {ex.Message}"); } } private void OnSDKStatusUpdate(object sender, TTAPIStatusUpdateEventArgs e) { if (e.IsReady && m_ts == null) { lblStatus.Text = "Authenticated. Launching subscriptions..."; m_ts = new TradeSubscription(m_dispatcher, false); m_ts.OrderBookDownload += OnOrderBookDownload; m_ts.OrderAdded += OnOrderAdded; m_ts.OrderDeleted += OnOrderDeleted; m_ts.OrderFilled += OnOrderFilled; m_ts.OrderUpdated += OnOrderUpdated; m_ts.OrderPendingAction += OnOrderPendingAction; m_ts.OrderRejected += OnOrderRejected; m_ts.Start(); } else if (e.IsDown) { lblStatus.Text = $"SDK is down: {e.StatusMessage}"; } } private void OnSDKShutdownComplete(object sender, EventArgs e) { m_shutdownComplete = true; this.Close(); } #endregion #region TradeSubscription Events private void OnOrderBookDownload(object sender, OrderBookDownloadEventArgs e) { lblStatus.Text = "Running"; } private void OnOrderAdded(object sender, OrderAddedEventArgs e) { var row = GetContractRow(e.Order.Instrument); if (row != null) { row.ProcessMessage(e); } } private void OnOrderUpdated(object sender, OrderUpdatedEventArgs e) { var row = GetContractRow(e.NewOrder.Instrument); if (row != null) { row.ProcessMessage(e); } } private void OnOrderDeleted(object sender, OrderDeletedEventArgs e) { var row = GetContractRow(e.DeletedUpdate.Instrument); if (row != null) { row.ProcessMessage(e); } } private void OnOrderFilled(object sender, OrderFilledEventArgs e) { var row = GetContractRow(e.Fill.Instrument); if (row != null) { row.ProcessMessage(e); } } private void OnOrderRejected(object sender, OrderRejectedEventArgs e) { // Not Implemented } private void OnOrderPendingAction(object sender, OrderPendingActionEventArgs e) { // Not Implemented } #endregion #region Form Events private void OnWindowClosing(object sender, System.ComponentModel.CancelEventArgs e) { if (!m_shutdownComplete) { e.Cancel = true; Shutdown(); } } private static readonly Regex s_numericOnly = new Regex("[^0-9.-]+"); private void TextBox_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e) { e.Handled = s_numericOnly.IsMatch(e.Text); } private void TextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e) { try { if (string.IsNullOrWhiteSpace(txtNOSWeight.Text)) return; if (string.IsNullOrWhiteSpace(txtCHGWeight.Text)) return; if (string.IsNullOrWhiteSpace(txtCXLWeight.Text)) return; var nos_weight = Int32.Parse(txtNOSWeight.Text); var chg_weight = Int32.Parse(txtCHGWeight.Text); var cxl_weight = Int32.Parse(txtCXLWeight.Text); foreach(var parent in MarketListData) { var parentRow = parent as MarketTreeRow; parentRow.ResetWeights(nos_weight, chg_weight, cxl_weight); } } catch { } } #endregion #region Private Methods private ContractTreeRow GetContractRow(Instrument instr) { var parent = this.MarketListData.FirstOrDefault(x => x.MarketId == instr.Product.Market.MarketId); if (parent == null) { this.MarketListData.Add(new MarketTreeRow(instr)); parent = this.MarketListData.Last(); } var productRow = parent.CreateOrGetExistingChild(instr); var contractRow = productRow.CreateOrGetExistingChild(instr); return contractRow; } private void Shutdown() { if (m_ts != null) { m_ts.OrderBookDownload -= OnOrderBookDownload; m_ts.OrderAdded -= OnOrderAdded; m_ts.OrderDeleted -= OnOrderDeleted; m_ts.OrderFilled -= OnOrderFilled; m_ts.OrderUpdated -= OnOrderUpdated; m_ts.OrderPendingAction -= OnOrderPendingAction; m_ts.OrderRejected -= OnOrderRejected; m_ts.Dispose(); m_ts = null; } TTAPI.Shutdown(); } #endregion } }
33.499096
123
0.562483
[ "BSD-3-Clause" ]
shatteringlass/TT_Samples
TT_NET_CLIENT_SIDE/TTNETAPI_Sample_WPF_VolumeRatio/MainWindow.xaml.cs
18,532
C#
using System; using System.IO; using System.Linq; using System.Reflection; using PowerArgs; namespace ArkProjects.Wireguard.Cli; [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)] public class VersionHook : ArgHook { public static class CustomAttributesName { public const string RepoUrl = "REPO_URL"; public const string ProjectUrl = "PROJECT_URL"; /// <summary> /// branch or tag /// </summary> public const string GitRef = "GIT_REF"; /// <summary> /// branch or tag /// </summary> public const string GitRefType = "GIT_REF_TYPE"; public const string GitCommitSha = "GIT_COMMIT_SHA"; public const string BuildDate = "BUILD_DATE"; } private CommandLineArgument _target; private bool _iDidTheCancel; /// <summary> /// If true (which it is by default) the hook will write the help after the target property is populated. If false, processing will still stop, but /// the help will not be written (yoy will have to do it yourself). /// </summary> public bool WriteVersion { get; set; } public Type TypeInTargetAssembly { get; set; } public VersionHook() { WriteVersion = true; AfterCancelPriority = 0; } /// <summary>Makes sure the target is a boolean</summary> /// <param name="context">Context passed by the parser</param> public override void BeforePopulateProperty(HookContext context) { base.BeforePopulateProperty(context); _target = context.CurrentArgument; if (context.CurrentArgument.ArgumentType != typeof(bool)) throw new InvalidArgDefinitionException(nameof(ArgHook) + " attributes can only be used with boolean properties or parameters"); } /// <summary> /// This gets called after the target property is populated. It cancels processing. /// </summary> /// <param name="context">Context passed by the parser</param> public override void AfterPopulateProperty(HookContext context) { _iDidTheCancel = false; base.AfterPopulateProperty(context); if (context.CurrentArgument.RevivedValue is not true) return; _iDidTheCancel = true; context.CancelAllProcessing(); } /// <summary>Writes the help as long as WriteHelp is true</summary> /// <param name="context">Context passed by the parser</param> public override void AfterCancel(HookContext context) { base.AfterCancel(context); if (!_iDidTheCancel || !WriteVersion) return; var assembly = TypeInTargetAssembly?.Assembly ?? Assembly.GetEntryAssembly(); var attrs = assembly?.GetCustomAttributes<AssemblyMetadataAttribute>().ToArray(); var versionAttr = assembly?.GetCustomAttribute<AssemblyFileVersionAttribute>(); var template = "{{ExeName Cyan !}} version {{Version Green!}}, commit {{GitCommitSha!}}\r\n" + "{{if HasGitTag}}Tag: {{GitTag Green!}}\r\n!{{if}}" + "{{if HasGitRef}}Branch: {{GitRef Red!}}\r\n!{{if}}" + "Build: {{BuildDate DarkGreen!}}\r\n" + "Project: {{ProjectUrl Green!}}\r\n" + "Repo: {{RepoUrl Green!}}\r\n"; var refType = attrs?.FirstOrDefault(x => x.Key == CustomAttributesName.GitRefType)?.Value ?? "branch"; var refName = attrs?.FirstOrDefault(x => x.Key == CustomAttributesName.GitRef)?.Value ?? ""; var gitRef = refType == "branch" ? refName : null; var gitTag = refType == "tag" ? refName : null; var data = new { ExeName = Path.GetFileName(Environment.ProcessPath), RepoUrl = attrs?.FirstOrDefault(x => x.Key == CustomAttributesName.RepoUrl)?.Value, ProjectUrl = attrs?.FirstOrDefault(x => x.Key == CustomAttributesName.ProjectUrl)?.Value, GitRef = gitRef, GitTag = gitTag, GitCommitSha = attrs?.FirstOrDefault(x => x.Key == CustomAttributesName.GitCommitSha)?.Value, BuildDate = attrs?.FirstOrDefault(x => x.Key == CustomAttributesName.BuildDate)?.Value, HasGitTag = gitTag != null, HasGitRef = gitRef != null, Version = versionAttr?.Version }; new DocumentRenderer().Render(template, data).Write(); } }
39.846847
152
0.628759
[ "MIT" ]
mixa3607/WgNet
Wireguard.Cli/Cli/VersionHook.cs
4,425
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace GitClientVS.Infrastructure.Extensions { public static class CommonExtensions { public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { HashSet<TKey> seenKeys = new HashSet<TKey>(); foreach (TSource element in source) { if (seenKeys.Add(keySelector(element))) { yield return element; } } } public static string GetPropertyName<T, TResult>(this Expression<Func<T, TResult>> expression) { var member = expression.Body as MemberExpression; return member?.Member?.Name; } public static void AddOrUpdate<K, V>(this ConcurrentDictionary<K, V> dictionary, K key, V value) { dictionary.AddOrUpdate(key, value, (oldkey, oldvalue) => value); } } }
30.945946
135
0.619214
[ "MIT" ]
DirtyApexAlpha/bitbucket-for-visual-studio
Source/GitClientVS.Infrastructure/Extensions/CommonExtensions.cs
1,147
C#
namespace Battleship.Warehouse { using System; using Battleship.Warehouse.Scheduler; public static class WareHousing { #region Methods public static void IntervalInDays(int hour, int min, double interval, Action task) { interval = interval * 24; TaskScheduler.Instance.ScheduleTask(hour, min, interval, task); } #endregion } }
21.842105
90
0.624096
[ "MIT" ]
ofthesea-io/Battleship.Microservices
src/Battleship.Warehouse/WareHousing.cs
417
C#
using System; using System.Collections; using System.Web.UI; namespace umbraco { /// <summary> /// Class that adapts an <see cref="AttributeCollection"/> to the <see cref="IDictionary"/> interface. /// </summary> public class AttributeCollectionAdapter : IDictionary { private readonly AttributeCollection _collection; /// <summary> /// Initializes a new instance of the <see cref="AttributeCollectionAdapter"/> class. /// </summary> /// <param name="collection">The collection.</param> public AttributeCollectionAdapter(AttributeCollection collection) { _collection = collection; } #region IDictionary Members /// <summary> /// Adds an element with the provided key and value to the <see cref="T:System.Collections.IDictionary"/> object. /// </summary> /// <param name="key">The <see cref="T:System.Object"/> to use as the key of the element to add.</param> /// <param name="value">The <see cref="T:System.Object"/> to use as the value of the element to add.</param> public void Add(object key, object value) { _collection.Add(key.ToString(), value.ToString()); } /// <summary> /// Removes all elements from the <see cref="T:System.Collections.IDictionary"/> object. /// </summary> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.IDictionary"/> object is read-only. /// </exception> public void Clear() { _collection.Clear(); } /// <summary> /// Determines whether the <see cref="T:System.Collections.IDictionary"/> object contains an element with the specified key. /// </summary> /// <param name="key">The key to locate in the <see cref="T:System.Collections.IDictionary"/> object.</param> /// <returns> /// true if the <see cref="T:System.Collections.IDictionary"/> contains an element with the key; otherwise, false. /// </returns> public bool Contains(object key) { return _collection[key.ToString()] != null; } /// <summary> /// Returns an <see cref="T:System.Collections.IDictionaryEnumerator"/> object for the <see cref="T:System.Collections.IDictionary"/> object. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IDictionaryEnumerator"/> object for the <see cref="T:System.Collections.IDictionary"/> object. /// </returns> public IDictionaryEnumerator GetEnumerator() { return new AttributeCollectionAdapterEnumerator(this); } /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.IDictionary"/> object has a fixed size. /// </summary> /// <value></value> /// <returns>true if the <see cref="T:System.Collections.IDictionary"/> object has a fixed size; otherwise, false. /// </returns> public bool IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.IDictionary"/> object is read-only. /// </summary> /// <value></value> /// <returns>true if the <see cref="T:System.Collections.IDictionary"/> object is read-only; otherwise, false. /// </returns> public bool IsReadOnly { get { return false; } } /// <summary> /// Gets an <see cref="T:System.Collections.ICollection"/> object containing the keys of the <see cref="T:System.Collections.IDictionary"/> object. /// </summary> /// <value></value> /// <returns> /// An <see cref="T:System.Collections.ICollection"/> object containing the keys of the <see cref="T:System.Collections.IDictionary"/> object. /// </returns> public ICollection Keys { get { return _collection.Keys; } } /// <summary> /// Removes the element with the specified key from the <see cref="T:System.Collections.IDictionary"/> object. /// </summary> /// <param name="key">The key of the element to remove.</param> public void Remove(object key) { _collection.Remove(key.ToString()); } /// <summary> /// Gets an <see cref="T:System.Collections.ICollection"/> object containing the values in the <see cref="T:System.Collections.IDictionary"/> object. /// </summary> /// <value></value> /// <returns> /// An <see cref="T:System.Collections.ICollection"/> object containing the values in the <see cref="T:System.Collections.IDictionary"/> object. /// </returns> public ICollection Values { get { throw new NotImplementedException(); } } /// <summary> /// Gets or sets the <see cref="System.Object"/> with the specified key. /// </summary> /// <value></value> public object this[object key] { get { return _collection[key.ToString()]; } set { _collection[key.ToString()] = value.ToString(); } } #endregion #region ICollection Members /// <summary>Not implemented.</summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param> public void CopyTo(Array array, int index) { throw new NotImplementedException(); } /// <summary> /// Gets the number of elements contained in the <see cref="T:System.Collections.ICollection"/>. /// </summary> /// <value></value> /// <returns> /// The number of elements contained in the <see cref="T:System.Collections.ICollection"/>. /// </returns> public int Count { get { return _collection.Count; } } /// <summary> /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is synchronized (thread safe). /// </summary> /// <value></value> /// <returns>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized (thread safe); otherwise, false. /// </returns> public bool IsSynchronized { get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>. /// </summary> /// <value></value> /// <returns> /// An object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>. /// </returns> public object SyncRoot { get { return _collection; } } #endregion #region IEnumerable Members /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { foreach (object key in _collection.Keys) yield return _collection[(string)key]; } #endregion /// <summary> /// <see cref="IDictionaryEnumerator"/> for the <see cref="AttributeCollectionAdapter"/> class. /// </summary> private class AttributeCollectionAdapterEnumerator : IDictionaryEnumerator { private readonly AttributeCollectionAdapter _adapter; private readonly IEnumerator _enumerator; /// <summary> /// Initializes a new instance of the <see cref="AttributeCollectionAdapterEnumerator"/> class. /// </summary> /// <param name="adapter">The adapter.</param> public AttributeCollectionAdapterEnumerator(AttributeCollectionAdapter adapter) { _adapter = adapter; _enumerator = ((IEnumerable)adapter).GetEnumerator(); } #region IDictionaryEnumerator Members /// <summary> /// Gets both the key and the value of the current dictionary entry. /// </summary> /// <value></value> /// <returns> /// A <see cref="T:System.Collections.DictionaryEntry"/> containing both the key and the value of the current dictionary entry. /// </returns> /// <exception cref="T:System.InvalidOperationException"> /// The <see cref="T:System.Collections.IDictionaryEnumerator"/> is positioned before the first entry of the dictionary or after the last entry. /// </exception> public DictionaryEntry Entry { get { return new DictionaryEntry(Key, Value); } } /// <summary> /// Gets the key of the current dictionary entry. /// </summary> /// <value></value> /// <returns> /// The key of the current element of the enumeration. /// </returns> /// <exception cref="T:System.InvalidOperationException"> /// The <see cref="T:System.Collections.IDictionaryEnumerator"/> is positioned before the first entry of the dictionary or after the last entry. /// </exception> public object Key { get { return _enumerator.Current; } } /// <summary> /// Gets the value of the current dictionary entry. /// </summary> /// <value></value> /// <returns> /// The value of the current element of the enumeration. /// </returns> /// <exception cref="T:System.InvalidOperationException"> /// The <see cref="T:System.Collections.IDictionaryEnumerator"/> is positioned before the first entry of the dictionary or after the last entry. /// </exception> public object Value { get { return _adapter[_enumerator.Current]; } } #endregion #region IEnumerator Members /// <summary> /// Gets the current element in the collection. /// </summary> /// <value></value> /// <returns> /// The current element in the collection. /// </returns> /// <exception cref="T:System.InvalidOperationException"> /// The enumerator is positioned before the first element of the collection or after the last element. /// </exception> public object Current { get { return _enumerator.Current; } } /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns> /// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection. /// </returns> /// <exception cref="T:System.InvalidOperationException"> /// The collection was modified after the enumerator was created. /// </exception> public bool MoveNext() { return _enumerator.MoveNext(); } /// <summary> /// Sets the enumerator to its initial position, which is before the first element in the collection. /// </summary> /// <exception cref="T:System.InvalidOperationException"> /// The collection was modified after the enumerator was created. /// </exception> public void Reset() { _enumerator.Reset(); } #endregion } } }
40.731629
253
0.553298
[ "MIT" ]
ismailmayat/Umbraco-CMS
src/Umbraco.Web/umbraco.presentation/AttributeCollectionAdapter.cs
12,751
C#
using System; using System.Collections; using System.Collections.Generic; namespace TP5 { class Program { static void Main(string[] args) { string oracion; Console.Write("Escriba su oración: "); oracion = Console.ReadLine(); oracion = reverse(oracion); Console.WriteLine($"\nOracion revertida: {oracion}"); LaColaLoca cola = new LaColaLoca(); for (int i = 1; i <= 10; i++) { cola.Encolar(i); } Console.WriteLine("\nPrimera cola: "); printColaLoca(cola); Console.Write("\n\nInserte el numero reversor: "); int num = Convert.ToInt16(Console.ReadLine()); try { cola = reorder(cola,num); Console.WriteLine("\nCola loca nueva: "); printColaLoca(cola); } catch (System.Exception e) { Console.WriteLine(e.Message); } } static string reverse(string s) { Stack stack = new Stack(); string[] words = s.Split(" "); foreach (string item in words) { stack.Push(item); } string oracion=""; foreach (string item in stack) { oracion += $"{item} "; } return oracion; } static LaColaLoca reorder(LaColaLoca colaVieja, int n) { if (n>colaVieja.Cantidad) { throw new Exception("El numero insertado esta fuera del rango"); } LaColaLoca colaNueva = new LaColaLoca(); Stack<int> pila = new Stack<int>(); for (int i = 0; i < n; i++) { pila.Push(colaVieja.Tope); colaVieja.Desencolar(); } foreach (int item in pila) { colaNueva.Encolar(item); } foreach (int item in colaVieja) { colaNueva.Encolar(item); } return colaNueva; } static void printColaLoca(LaColaLoca cola) { foreach (var item in cola) { Console.Write($"{item} ->"); } } } public class LaColaLoca : IEnumerable { /* Dado un valor entero N y una Cola de números enteros, se requiere reversar el orden de los primeros N elementos manteniendo el mismo orden para los demás elementos Debe realizar la implementación de la Cola utilizando una Lista Enlazada Simple y solo puede contener las siguientes operaciones: -encolar(i) : Añade un elemento i a la cola -desencolar() : Retira el elemento que se encuentra al inicio -cantidad() : Devuelve la cantidad de elementos que posee la cola -tope() : Indica cuál es el primer elemento de la cola */ LinkedList<int> cola = new LinkedList<int>(); public void Encolar(int i) { cola.AddLast(i); } public void Desencolar() { cola.RemoveFirst(); } public IEnumerator GetEnumerator() { return ((IEnumerable)cola).GetEnumerator(); } public int Cantidad { get { return cola.Count; } } public int Tope { get { return cola.First.Value; } } } }
26.181818
171
0.467949
[ "MIT" ]
LarryKapija/TP5
TP5/Program.cs
3,752
C#
using System.Collections.Generic; using System.Threading.Tasks; using UserService.views; using UserService.Models; namespace UserService.Services { public interface IUserService { Task Fill(); Task<List<User>> Get(); Task<User> Insert(string viewName, string viewEmail, string viewPassword); Task<User> Login(string viewEmail, string viewPassword); } }
19.238095
82
0.69802
[ "MIT" ]
KwetterS6/UserService
UserService/Services/IUserService.cs
406
C#
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using ICSharpCode.Core; using ICSharpCode.Core.Presentation; using ICSharpCode.SharpDevelop.Debugging; using ICSharpCode.SharpDevelop.Editor.Bookmarks; using ICSharpCode.SharpDevelop.Gui; using ICSharpCode.SharpDevelop.Workbench; namespace ICSharpCode.SharpDevelop.Editor.Bookmarks { public sealed class BookmarkPad : BookmarkPadBase { public BookmarkPad() { ToolBar toolbar = ToolBarService.CreateToolBar((UIElement)this.Control, this, "/SharpDevelop/Pads/BookmarkPad/Toolbar"); this.control.Children.Add(toolbar); } protected override bool ShowBookmarkInThisPad(SDBookmark bookmark) { return bookmark.ShowInPad(this); } } public abstract class BookmarkPadBase : AbstractPadContent { protected BookmarkPadContent control; public override object Control { get { return this.control; } } public ListView ListView { get { return this.control.listView; } } public ItemCollection Items { get { return this.control.listView.Items; } } public SDBookmark SelectedItem { get { return (SDBookmark)this.control.listView.SelectedItem; } } public IEnumerable<SDBookmark> SelectedItems { get { return this.control.listView.SelectedItems.OfType<SDBookmark>(); } } protected BookmarkPadBase() { this.control = new BookmarkPadContent(); this.control.InitializeComponent(); SD.BookmarkManager.BookmarkAdded += BookmarkManagerAdded; SD.BookmarkManager.BookmarkRemoved += BookmarkManagerRemoved; foreach (SDBookmark bookmark in SD.BookmarkManager.Bookmarks) { if (ShowBookmarkInThisPad(bookmark)) { this.Items.Add(bookmark); } } this.control.listView.MouseDoubleClick += delegate { SDBookmark bm = this.control.listView.SelectedItem as SDBookmark; if (bm != null) OnItemActivated(bm); }; this.control.listView.KeyDown += delegate(object sender, System.Windows.Input.KeyEventArgs e) { var selectedItems = this.SelectedItems.ToList(); if (!selectedItems.Any()) return; switch (e.Key) { case System.Windows.Input.Key.Delete: foreach (var selectedItem in selectedItems) { SD.BookmarkManager.RemoveMark(selectedItem); } break; } }; } public override void Dispose() { SD.BookmarkManager.BookmarkAdded -= BookmarkManagerAdded; SD.BookmarkManager.BookmarkRemoved -= BookmarkManagerRemoved; } protected abstract bool ShowBookmarkInThisPad(SDBookmark mark); protected virtual void OnItemActivated(SDBookmark bm) { FileService.JumpToFilePosition(bm.FileName, bm.LineNumber, 1); } void BookmarkManagerAdded(object sender, BookmarkEventArgs e) { if (ShowBookmarkInThisPad(e.Bookmark)) { this.Items.Add(e.Bookmark); } } void BookmarkManagerRemoved(object sender, BookmarkEventArgs e) { this.Items.Remove(e.Bookmark); } } }
31.310606
123
0.74135
[ "MIT" ]
TetradogOther/SharpDevelop
src/Main/Base/Project/Editor/Bookmarks/BookmarkPad.cs
4,135
C#
using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; namespace Basilisk.Inject.Configuration.Implementation { /// <summary> /// Default implementation of <see cref="IHostConfig"/>. /// </summary> public class HostConfig : IHostConfig { /// <summary> /// Configuration configurers /// </summary> protected List<Action<IConfigurationBuilder>> Configurers { get; } = new(); /// <inheritdoc/> public IDictionary<object, object> Properties { get; } = new Dictionary<object, object>(); /// <inheritdoc/> public void Add(Action<IConfigurationBuilder> configurer) { Configurers.Add(configurer); } /// <inheritdoc/> public void Apply(IConfigurationBuilder builder) { foreach (Action<IConfigurationBuilder> configurer in Configurers) { configurer(builder); } } } }
26.289474
98
0.597598
[ "MIT" ]
tldag/basilisk
Basilisk.Inject/Configuration/Implementation/HostConfig.cs
1,001
C#
// Copyright 2010 Chris Patterson // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Stact.Internal { using System.Collections.Generic; using System.Linq; class TokenImpl<T> : Token<T> { IEnumerable<Token<T>> _children; Element _element; IEnumerable<NegativeJoinResult> _joinResults; IEnumerable<NegativeJoinResult> _nccResults; ReteNode _node; Token _owner; Token<T> _parent; public TokenImpl(ReteNode node, Token<T> parent, Element<T> element) { _node = node; _parent = parent; _element = element; _children = Enumerable.Empty<Token<T>>(); parent.Add(this); if (element != null) element.AddToken(this); } public void Add(Token<T> token) { _children = Enumerable.Repeat(token, 1).Concat(_children); } } }
26.431373
84
0.686202
[ "Apache-2.0" ]
Nangal/Stact
src/Stact.Playground/Rules/Internal/TokenImpl.cs
1,350
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences { internal interface INamingStylesInfoDialogViewModel { string ItemName { get; set; } bool CanBeDeleted { get; set; } } }
37.272727
161
0.741463
[ "Apache-2.0" ]
20chan/roslyn
src/VisualStudio/Core/Impl/Options/Style/NamingPreferences/INamingStylesInfoDialogViewModel.cs
412
C#
using System; using System.Runtime.InteropServices; namespace Vlc.DotNet.Core.Interops.Signatures { /// <summary> /// Set video track. /// </summary> [LibVlcFunction("libvlc_video_set_track")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void SetVideoTrack(IntPtr mediaPlayerInstance, int trackId); }
27.076923
82
0.741477
[ "MIT" ]
CrookedFingerGuy/Vlc.DotNet
src/Vlc.DotNet.Core.Interops/Signatures/libvlc_media_player.h/libvlc_video_set_track.cs
354
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections; using Microsoft.TestCommon; using Moq; namespace System.Web.WebPages.Test { public class RequestResourceTrackerTest { [Fact] public void RegisteringForDisposeDisposesObjects() { // Arrange var context = new Mock<HttpContextBase>(); IDictionary items = new Hashtable(); context.Setup(m => m.Items).Returns(items); var disposable = new Mock<IDisposable>(); disposable.Setup(m => m.Dispose()).Verifiable(); // Act RequestResourceTracker.RegisterForDispose(context.Object, disposable.Object); RequestResourceTracker.DisposeResources(context.Object); // Assert disposable.VerifyAll(); } [Fact] public void RegisteringForDisposeExtensionMethodNullContextThrows() { // Arrange var disposable = new Mock<IDisposable>(); // Act Assert.ThrowsArgumentNull( () => HttpContextExtensions.RegisterForDispose(null, disposable.Object), "context" ); } } }
30.409091
111
0.603886
[ "Apache-2.0" ]
belav/AspNetWebStack
test/System.Web.WebPages.Test/WebPage/RequestResourceTrackerTest.cs
1,340
C#
using Microsoft.HockeyApp.Model; using Microsoft.Phone.Net.NetworkInformation; using Microsoft.Phone.Reactive; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO.IsolatedStorage; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using Microsoft.HockeyApp.Views; using Microsoft.HockeyApp.Tools; using Microsoft.Phone.Controls; namespace Microsoft.HockeyApp.ViewModels { public class FeedbackPageVM : VMBase { public Task Initialization { get; private set; } Action<FeedbackViewState> switchViewStateAction; #region ctor public FeedbackPageVM(Action<FeedbackViewState> switchViewStateAction) { this.ThreadInfo = FeedbackManager.Instance.FeedbackPageTopTitle; this.switchViewStateAction = switchViewStateAction; Initialization = InitializeAsync(); //await this.Initialization to make shure its inititalized } private async Task InitializeAsync() { if (FeedbackManager.Instance.IsThreadOpen) { if (NetworkInterface.GetIsNetworkAvailable()) { try { IFeedbackThread thread = await FeedbackManager.Instance.GetActiveThreadAsync(forceReload: true); if (thread != null) { foreach (var msg in (thread.Messages)) { this.Messages.Add(new FeedbackMessageReadOnlyVM(msg, this)); } if (FeedbackManager.Instance.FeedbackPageTopTitle.IsEmpty() && !thread.Messages.First().Subject.IsEmpty()) { Deployment.Current.Dispatcher.BeginInvoke(() => this.ThreadInfo = thread.Messages.First().Subject); } SwitchToMessageList(); } else //thread has been deleted { Deployment.Current.Dispatcher.BeginInvoke(() => IsThreadActive = false); SwitchToMessageForm(); } } catch (Exception) { Deployment.Current.Dispatcher.BeginInvoke(() => { MessageBox.Show(LocalizedStrings.LocalizedResources.FeedbackFetchError); }); LeaveFeedbackPageViaBackButton(); } } else //no internet connection { Deployment.Current.Dispatcher.BeginInvoke(() => { MessageBox.Show(LocalizedStrings.LocalizedResources.FeedbackNoInternet); }); LeaveFeedbackPageViaBackButton(); } } else { Deployment.Current.Dispatcher.BeginInvoke(() => IsThreadActive = false); SwitchToMessageForm(); } HideOverlay(); } #endregion #region Properties private string threadinfo; public string ThreadInfo { get { return threadinfo; } set { threadinfo = value; NotifyOfPropertyChange("ThreadInfo"); } } private bool isShowOverlay = true; public bool IsShowOverlay { get { return isShowOverlay; } set { isShowOverlay = value; NotifyOfPropertyChange("IsShowOverlay"); } } private bool isThreadActive = false; public bool IsThreadActive { get { return isThreadActive; } set { isThreadActive = value; NotifyOfPropertyChange("IsThreadActive"); } } ObservableCollection<FeedbackMessageReadOnlyVM> messages = new ObservableCollection<FeedbackMessageReadOnlyVM>(); public ObservableCollection<FeedbackMessageReadOnlyVM> Messages { get { return messages; } } #endregion #region cmd-methods public void SwitchToMessageList() { Deployment.Current.Dispatcher.BeginInvoke(() => { this.IsShowOverlay = false; }); switchViewStateAction(FeedbackViewState.MessageList); } public void SwitchToMessageForm() { Deployment.Current.Dispatcher.BeginInvoke(() => { this.IsShowOverlay = false; }); switchViewStateAction(FeedbackViewState.MessageForm); } public void ShowOverlay() { Deployment.Current.Dispatcher.BeginInvoke(() => { this.IsShowOverlay = true; }); } public void HideOverlay() { Deployment.Current.Dispatcher.BeginInvoke(() => { this.IsShowOverlay = false; }); } private FeedbackImageVM iVM; public FeedbackImageVM CurrentImageVM { get { return iVM; } set { iVM = value; } } private void LeaveFeedbackPageViaBackButton() { switchViewStateAction(FeedbackViewState.Unknown); } internal void SwitchToImageEditor(FeedbackImageVM imageVM) { CurrentImageVM = imageVM; if (imageVM.IsEditable) { switchViewStateAction(FeedbackViewState.ImageEdit); } else { switchViewStateAction(FeedbackViewState.ImageShow); } } #endregion } }
32.255319
134
0.527045
[ "MIT" ]
bitstadium/HockeySDK-Windows
Src/Kit.WP8/ViewModels/FeedbackPageVM.cs
6,066
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace lm.Comol.Core.BaseModules.Tickets.Domain.DTO { [Serializable, CLSCompliant(true)] public class DTO_UserModify { public DTO_UserModify() { TicketId = -1; Code = "TK00000000-0"; Status = Enums.TicketStatus.open; CategoryName = ""; Notifications = new MailNotification(); Messages = null; Errors = Enums.TicketEditUserErrors.none; IsReadOnly = true; IsBehalf = false; isOwner = false; } public Int64 TicketId { get; set; } public string Code { get; set; } public Domain.Enums.TicketStatus Status { get; set; } public String CategoryName { get; set; } public Domain.MailNotification Notifications { get; set; } public string Title { get; set; } public IList<DTO_UserModifyItem> Messages { get; set; } public Domain.Enums.TicketEditUserErrors Errors { get; set; } public Boolean IsClosed { get; set; } public String CurrentUserDisplayName { get; set; } public Domain.Enums.MessageUserType CurrentUserType { get; set; } /// <summary> /// Messaggio in DRAFT. /// Se non presente, ne viene creato uno vuoto. /// </summary> public Domain.Message DraftMessage { get; set; } public DateTime? LastUserAccess { get; set; } public Domain.Enums.TicketCondition Condition { get; set; } /// <summary> /// Indica SE il ticket è stato creato "per conto di..." /// </summary> public bool IsBehalf { get; set; } /// <summary> /// Indica se è visibile in sola lettura (Manager/Resolver che controllano ciò che l'utente vede) /// </summary> public bool IsReadOnly { get; set; } /// <summary> /// Utente non accesso + SysSettings + Behalf permission /// </summary> public bool ShowBehalf { get; set; } /// <summary> /// SE PUO' riassegnare a sè stesso /// </summary> public bool CanRemoveBehalf { get; set; } /// <summary> /// Ha permessi di behalf /// </summary> public bool BehalfRevoked { get; set; } /// <summary> /// Indica SE l'utente corrente è anche manager/resolver del Ticket, per lo switch tra vista utente e vista normale... /// </summary> public bool IsManagerOrResolver { get; set; } //Visibilità tasti navigazione public bool ShowToUserList { get; set; } public bool ShowToManagementList { get; set; } public bool ShowToBehalfList { get; set; } /// <summary> /// Indica SE il Ticket è visibile o meno all'utente /// </summary> public bool IsHideToOwner { get; set; } //NOTIFICATION public Domain.Enums.MailSettings CreatorMailSettings { get; set; } public bool IsDefaultNotCreator { get; set; } public Domain.Enums.MailSettings OwnerMailSettings { get; set; } public bool IsDefaultNotOwner { get; set; } public bool isOwner { get; set; } public bool IsOwnerNotificationEnable { get; set; } public bool IsCreatorNotificationEnable { get; set; } } }
32.509615
126
0.590949
[ "MIT" ]
EdutechSRL/Adevico
3-Business/3-Modules/lm.Comol.Core.BaseModules/Tickets/Domain/DTO/DTO_UserModify.cs
3,390
C#
using Ryujinx.Graphics.Shader.Instructions; using Ryujinx.Graphics.Shader.IntermediateRepresentation; using System.Collections.Generic; namespace Ryujinx.Graphics.Shader.Decoders { class OpCodeSsy : OpCodeBranch { public Dictionary<OpCodeSync, Operand> Syncs { get; } public OpCodeSsy(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode) { Syncs = new Dictionary<OpCodeSync, Operand>(); Predicate = new Register(RegisterConsts.PredicateTrueIndex, RegisterType.Predicate); InvertPredicate = false; } } }
30.75
106
0.700813
[ "MIT" ]
Danik2343/Ryujinx
Ryujinx.Graphics/Shader/Decoders/OpCodeSsy.cs
615
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using TokoBeDia.Controller; using TokoBeDia.Model; namespace TokoBeDia.View.profile { public partial class ViewProfile : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (ViewProfileController.isUserLoggedIn()) { User currentUser = ViewProfileController.getUserData(); nameLbl.Text = currentUser.UName; emailLbl.Text = currentUser.UEmail; genderLbl.Text = currentUser.UGender; } else { userWarnLbl.Text = "403. You're not logged in!"; logOutBtn.Visible = false; updateBtn.Visible = false; changePswdBtn.Visible = false; } } protected void homeBtn_Click(object sender, EventArgs e) { Response.Redirect("../Home.aspx"); } protected void logOutBtn_Click(object sender, EventArgs e) { HttpCookie currentUser = HttpContext.Current.Request.Cookies["user_email"]; HttpContext.Current.Response.Cookies.Remove("user_email"); currentUser.Expires = DateTime.Now.AddDays(-7.0); currentUser.Value = null; HttpContext.Current.Response.Cookies.Set(currentUser); Session.Abandon(); Response.Redirect("../Home.aspx"); } protected void updateBtn_Click(object sender, EventArgs e) { Response.Redirect("./UpdateProfile.aspx"); } protected void changePswdBtn_Click(object sender, EventArgs e) { Response.Redirect("./ChangePassword.aspx"); } } }
31.896552
87
0.592432
[ "MIT" ]
johaneka06/PSD-TokoBeDia
Code/TokoBeDia/View/profile/ViewProfile.aspx.cs
1,852
C#
using Blindspot.Core; using Blindspot.Core.Models; using ScreenReaderAPIWrapper; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Blindspot.ViewModels { public class SearchBufferList : BufferList, IDisposable { private Search _search; public SearchBufferList(Search searchIn) { _search = searchIn; Name = searchIn.Query; } public SearchBufferList(Search searchIn, bool isDismissableIn) : this(searchIn) { this.IsDismissable = isDismissableIn; } public override void NextItem() { if (this.Count > 0 && CurrentItemIndex == this.Count - 1) { GetNextSetOfResults(); } base.NextItem(); } private void GetNextSetOfResults() { _search = SpotifyClient.Instance.GetMoreResultsFromSearch(_search); switch (_search.Type) { case SearchType.Track: AddNewTracks(); break; case SearchType.Artist: AddNewAartists(); break; case SearchType.Album: AddNewAlbums(); break; default: break; } } private void AddNewTracks() { if (_search.Tracks == null || _search.Tracks.Count == 0) return; // no new search results _search.Tracks.ForEach(pointer => { this.Add(new TrackBufferItem(new Track(pointer))); }); } private void AddNewAartists() { if (_search.Artists == null || _search.Artists.Count == 0) return; _search.Artists.ForEach(pointer => { this.Add(new ArtistBufferItem(new Artist(pointer))); }); } private void AddNewAlbums() { if (_search.Albums == null || _search.Albums.Count == 0) return; _search.Albums.ForEach(pointer => { this.Add(new AlbumBufferItem(new Album(pointer))); }); } public override string ToString() { return String.Format("{0}: {1}: {2} {3} {4} {5}", StringStore.SearchFor, _search.Query, this.CurrentItemIndex + 1, StringStore.Of, this.Count, StringStore.Items); } public void Dispose() { _search.Dispose(); } } }
28.173913
174
0.51196
[ "BSD-2-Clause" ]
craigbrett17/Blindspot
Blindspot/ViewModels/SearchBufferList.cs
2,594
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("Nebula.Core.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Nebula.Core.Tests")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("1d0b0756-27ec-40cc-be7a-48afb1eb126b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.027027
84
0.744136
[ "Apache-2.0" ]
inkadnb/Nebula
Nebula.Core.Tests/Properties/AssemblyInfo.cs
1,410
C#
using System; using System.Linq; using DefaultNamespace; using UnityEngine; public class ClientLemingManager : MonoBehaviour { public RecordsStorage RecordsStorage; public LemingMovementController Leming; [SerializeField] private LemmingMovementDirection _input; public LemmingRunRecord Record; public Vector3 SpawnPosition; public bool RecordRun; public bool Simulate; public float killRadius = 0.3f; private int _minimumFrameDistanceToForceMutation = 100; private void Awake() { Record = RecordsStorage.GetNewRecord(); //[RecordID]; if (Leming == null) { Leming = FindObjectOfType<LemingMovementController>(); } Leming.OnDead += (controller, killer) => { BloodManager.instance.ShowKillEffect(controller.transform.position); Record.Mutate(SimualtionFrameId, _previousFrameId); _previousFrameId = SimualtionFrameId; if(killer == Killer.Player) BloodManager.instance.SpawnGrave(controller.transform.position); SimualtionFrameId = 0; controller.Respawn(SpawnPosition); }; Leming.OnExit += controller => { WinnersTable.WinnersData.Add(Record); }; SpawnPosition = Leming.transform.position; } public int RecordID = 0; private void Update() { KillLemmingsOnMouseClick(); if (Input.GetKeyDown(KeyCode.Space)) Leming.transform.position = SpawnPosition; _input = 0; var horizontal = Input.GetAxis("Horizontal"); _input |= ((horizontal > 0) ? LemmingMovementDirection.Right : horizontal < 0 ? LemmingMovementDirection.Left : LemmingMovementDirection.None); var vertical = Input.GetAxis("Vertical"); _input |= (vertical > 0 ? LemmingMovementDirection.Jump : LemmingMovementDirection.None); } private void KillLemmingsOnMouseClick() { if (Input.GetMouseButtonDown(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); var hitedCount = Physics2D.CircleCastNonAlloc(ray.origin, killRadius, ray.direction, _raycastResults, Mathf.Infinity); if (hitedCount > 0) { for (var i = 0; i < hitedCount; i++) { var colliderGameObject = _raycastResults[i].collider.gameObject; var lemingMovementController = colliderGameObject.GetComponent<LemingMovementController>(); if (lemingMovementController != null) { lemingMovementController.Die(Killer.Player); } } } } } public bool Save; public int SimualtionFrameId = 0; private int _previousFrameId = 0; private RaycastHit2D[] _raycastResults = new RaycastHit2D[100]; private void FixedUpdate() { if (Simulate) { _input = Record.GetOrGenerateNextMovement(SimualtionFrameId++); } else if (RecordRun) Record.AddMovement(_input); Leming.ManualFixedUpdate(_input); // if (Save) // { // Save = false; // RecordsStorage.Records.Add(Record); // } } }
29.181034
130
0.600886
[ "MIT" ]
uugspb/team5
Assets/Scripts/ClientLemingManager.cs
3,387
C#
using System.Collections.Generic; namespace EzAspDotNet.Notification.Data { public class WebHook { public string Text { get; set; } public string Title { get; set; } public string TitleLink { get; set; } public string Author { get; set; } public string AuthorLink { get; set; } public string AuthorIcon { get; set; } public long? TimeStamp { get; set; } public string Footer { get; set; } public string ImageUrl { get; set; } public string ThumbUrl { get; set; } public string FooterIcon { get; set; } = "https://platform.slack-edge.com/img/default_application_icon.png"; public string Color { get; set; } = "#2eb886"; public List<Field> Fields { get; set; } = new(); } }
23.588235
116
0.59601
[ "MIT" ]
elky84/EzAspDotNet
EzAspDotNet/Notification/Data/WebHook.cs
804
C#
using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Modules.Internal; using System.IO; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Options; using Microsoft.AspNetCore.Mvc.Razor.Compilation; using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Builder; namespace Microsoft.AspNetCore.Modules.Mvc { public static class MvcServiceCollectionExtensions { public static IServiceCollection AddViewOverrides(this IServiceCollection services) { services.AddTransient<IRazorPageFactoryProvider, ModulesRazorPageFactoryProvider>(); return services; } } }
31.464286
96
0.796822
[ "MIT" ]
danroth27/AspNetCoreModules
src/Microsoft.AspNetCore.Modules.Mvc/MvcServiceCollectionExtensions.cs
883
C#
// =================================================================== // 项目说明,功能实体类,用CodeSmith自动生成。 // =================================================================== // 文件名: RemindItem.cs // 修改时间:2017/12/26 17:33:33 // 修改人: lixiong // =================================================================== using System; namespace JX.Core.Entity { /// <summary> /// 数据库表:RemindItem 的实体类. /// </summary> public partial class RemindItem { #region Properties private System.Int32 _remindID = 0; /// <summary> /// 提醒ID (主键) /// </summary> public System.Int32 RemindID { get {return _remindID;} set {_remindID = value;} } private System.String _creater = string.Empty; /// <summary> /// 创建提醒的人 /// </summary> public System.String Creater { get {return _creater;} set {_creater = value;} } private DateTime? _createTime = DateTime.MaxValue; /// <summary> /// 创建提醒的时间 /// </summary> public DateTime? CreateTime { get {return _createTime;} set {_createTime = value;} } private DateTime? _remindTime = DateTime.MaxValue; /// <summary> /// 提醒时间 /// </summary> public DateTime? RemindTime { get {return _remindTime;} set {_remindTime = value;} } private System.String _relationType = string.Empty; /// <summary> /// 预约联系方式 /// </summary> public System.String RelationType { get {return _relationType;} set {_relationType = value;} } private System.String _remindContent = string.Empty; /// <summary> /// 提醒内容(备注型字段,不支持HTML) /// </summary> public System.String RemindContent { get {return _remindContent;} set {_remindContent = value;} } private System.Int32 _correlativeClient = 0; /// <summary> /// 关联客户(记录客户ID) /// </summary> public System.Int32 CorrelativeClient { get {return _correlativeClient;} set {_correlativeClient = value;} } private System.String _correlativeContacter = string.Empty; /// <summary> /// 关联客户的联系人 /// </summary> public System.String CorrelativeContacter { get {return _correlativeContacter;} set {_correlativeContacter = value;} } private System.Boolean _isRemindByTips = false; /// <summary> /// 是否冒泡提示主动提醒 /// </summary> public System.Boolean IsRemindByTips { get {return _isRemindByTips;} set {_isRemindByTips = value;} } private System.Boolean _isRemindByEmail = false; /// <summary> /// 是否发送邮件主动提醒 /// </summary> public System.Boolean IsRemindByEmail { get {return _isRemindByEmail;} set {_isRemindByEmail = value;} } private System.Boolean _isRemindBySms = false; /// <summary> /// 是否发送手机短信主动提醒 /// </summary> public System.Boolean IsRemindBySms { get {return _isRemindBySms;} set {_isRemindBySms = value;} } private System.Boolean _isFinish = false; /// <summary> /// 状态。0表示未处理,1表示已经处理 /// </summary> public System.Boolean IsFinish { get {return _isFinish;} set {_isFinish = value;} } #endregion } }
23.186047
72
0.608158
[ "Apache-2.0" ]
lixiong24/IPS2.1
JXIPS/JX.Core/Entity/RemindItemEntity.cs
3,277
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace BundleFileViewer.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.666667
151
0.583567
[ "MIT" ]
Jamiras/Core
BundleFileViewer/Properties/Settings.Designer.cs
1,073
C#
// Generated by SharpKit.QooxDoo.Generator using System; using System.Collections.Generic; using SharpKit.Html; using SharpKit.JavaScript; namespace qx.theme.manager { /// <summary> /// <para>Manager for meta themes</para> /// </summary> [JsType(JsMode.Prototype, Name = "qx.theme.manager.Meta", OmitOptionalParameters = true, Export = false)] public partial class Meta : qx.core.Object { #region Properties /// <summary> /// <para>Meta theme. Applies the defined color, decoration, ... themes to /// the corresponding managers.</para> /// </summary> /// <remarks> /// Allow nulls: true /// </remarks> [JsProperty(Name = "theme", NativeField = true)] public Theme Theme { get; set; } #endregion Properties #region Methods public Meta() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property theme.</para> /// </summary> [JsMethod(Name = "getTheme")] public Theme GetTheme() { throw new NotImplementedException(); } /// <summary> /// <para>Initialize the themes which were selected using the settings. Should only /// be called from qooxdoo based application.</para> /// </summary> [JsMethod(Name = "initialize")] public void Initialize() { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property theme /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property theme.</param> [JsMethod(Name = "initTheme")] public void InitTheme(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property theme.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetTheme")] public void ResetTheme() { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property theme.</para> /// </summary> /// <param name="value">New value for property theme.</param> [JsMethod(Name = "setTheme")] public void SetTheme(Theme value) { throw new NotImplementedException(); } /// <summary> /// <para>Returns a singleton instance of this class. On the first call the class /// is instantiated by calling the constructor with no arguments. All following /// calls will return this instance.</para> /// <para>This method has been added by setting the &#8220;type&#8221; key in the class definition /// (<see cref="qx.Class.Define"/>) to &#8220;singleton&#8221;.</para> /// </summary> /// <returns>The singleton instance of this class.</returns> [JsMethod(Name = "getInstance")] public static qx.theme.manager.Meta GetInstance() { throw new NotImplementedException(); } #endregion Methods } }
36.710843
106
0.688546
[ "MIT" ]
SharpKit/SharpKit-SDK
Defs/Qooxdoo/theme/manager/Meta.cs
3,047
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.Buffers; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Text { // A Decoder is used to decode a sequence of blocks of bytes into a // sequence of blocks of characters. Following instantiation of a decoder, // sequential blocks of bytes are converted into blocks of characters through // calls to the GetChars method. The decoder maintains state between the // conversions, allowing it to correctly decode byte sequences that span // adjacent blocks. // // Instances of specific implementations of the Decoder abstract base // class are typically obtained through calls to the GetDecoder method // of Encoding objects. internal class DecoderNLS : Decoder { // Remember our encoding private readonly Encoding _encoding; private bool _mustFlush; internal bool _throwOnOverflow; internal int _bytesUsed; private int _leftoverBytes; // leftover data from a previous invocation of GetChars (up to 4 bytes) private int _leftoverByteCount; // number of bytes of actual data in _leftoverBytes internal DecoderNLS(Encoding encoding) { _encoding = encoding; _fallback = this._encoding.DecoderFallback; this.Reset(); } public override void Reset() { ClearLeftoverData(); _fallbackBuffer?.Reset(); } public override int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(bytes, index, count, false); } public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush) { // Validate Parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // Just call pointer version fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) return GetCharCount(pBytes + index, count, flush); } public override unsafe int GetCharCount(byte* bytes, int count, bool flush) { // Validate parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); // Remember the flush _mustFlush = flush; _throwOnOverflow = true; // By default just call the encoding version, no flush by default Debug.Assert(_encoding != null); return _encoding.GetCharCount(bytes, count, this); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false); } public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_Index); int charCount = chars.Length - charIndex; // Just call pointer version fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars)) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush); } public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); // Remember our flush _mustFlush = flush; _throwOnOverflow = true; // By default just call the encodings version Debug.Assert(_encoding != null); return _encoding.GetChars(bytes, byteCount, chars, charCount, this); } // This method is used when the output buffer might not be big enough. // Just call the pointer version. (This gets chars) public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate parameters if (bytes == null || chars == null) throw new ArgumentNullException((bytes == null ? nameof(bytes) : nameof(chars)), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); // Just call the pointer version (public overrides can't do this) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) { fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars)) { Convert(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush, out bytesUsed, out charsUsed, out completed); } } } // This is the version that used pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting chars public override unsafe void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate input parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); // We don't want to throw _mustFlush = flush; _throwOnOverflow = false; _bytesUsed = 0; // Do conversion Debug.Assert(_encoding != null); charsUsed = _encoding.GetChars(bytes, byteCount, chars, charCount, this); bytesUsed = _bytesUsed; // Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed completed = (bytesUsed == byteCount) && (!flush || !this.HasState) && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0); // Our data thingy are now full, we can return } public bool MustFlush => _mustFlush; // Anything left in our decoder? internal virtual bool HasState => _leftoverByteCount != 0; // Allow encoding to clear our must flush instead of throwing (in ThrowCharsOverflow) internal void ClearMustFlush() { _mustFlush = false; } internal ReadOnlySpan<byte> GetLeftoverData() => MemoryMarshal.AsBytes(new ReadOnlySpan<int>(ref _leftoverBytes, 1)).Slice(0, _leftoverByteCount); internal void SetLeftoverData(ReadOnlySpan<byte> bytes) { bytes.CopyTo(MemoryMarshal.AsBytes(new Span<int>(ref _leftoverBytes, 1))); _leftoverByteCount = bytes.Length; } internal bool HasLeftoverData => _leftoverByteCount != 0; internal void ClearLeftoverData() { _leftoverByteCount = 0; } internal int DrainLeftoverDataForGetCharCount(ReadOnlySpan<byte> bytes, out int bytesConsumed) { // Quick check: we _should not_ have leftover fallback data from a previous invocation, // as we'd end up consuming any such data and would corrupt whatever Convert call happens // to be in progress. Unlike EncoderNLS, this is simply a Debug.Assert. No exception is thrown. Debug.Assert(_fallbackBuffer is null || _fallbackBuffer.Remaining == 0, "Should have no data remaining in the fallback buffer."); Debug.Assert(HasLeftoverData, "Caller shouldn't invoke this routine unless there's leftover data in the decoder."); // Copy the existing leftover data plus as many bytes as possible of the new incoming data // into a temporary concated buffer, then get its char count by decoding it. Span<byte> combinedBuffer = stackalloc byte[4]; combinedBuffer = combinedBuffer.Slice(0, ConcatInto(GetLeftoverData(), bytes, combinedBuffer)); int charCount = 0; Debug.Assert(_encoding != null); switch (_encoding.DecodeFirstRune(combinedBuffer, out Rune value, out int combinedBufferBytesConsumed)) { case OperationStatus.Done: charCount = value.Utf16SequenceLength; goto Finish; // successfully transcoded bytes -> chars case OperationStatus.NeedMoreData: if (MustFlush) { goto case OperationStatus.InvalidData; // treat as equivalent to bad data } else { goto Finish; // consumed some bytes, output 0 chars } case OperationStatus.InvalidData: break; default: Debug.Fail("Unexpected OperationStatus return value."); break; } // Couldn't decode the buffer. Fallback the buffer instead. See comment in DrainLeftoverDataForGetChars // for more information on why a negative index is provided. if (FallbackBuffer.Fallback(combinedBuffer.Slice(0, combinedBufferBytesConsumed).ToArray(), index: -_leftoverByteCount)) { charCount = _fallbackBuffer!.DrainRemainingDataForGetCharCount(); Debug.Assert(charCount >= 0, "Fallback buffer shouldn't have returned a negative char count."); } Finish: bytesConsumed = combinedBufferBytesConsumed - _leftoverByteCount; // amount of 'bytes' buffer consumed just now return charCount; } internal int DrainLeftoverDataForGetChars(ReadOnlySpan<byte> bytes, Span<char> chars, out int bytesConsumed) { // Quick check: we _should not_ have leftover fallback data from a previous invocation, // as we'd end up consuming any such data and would corrupt whatever Convert call happens // to be in progress. Unlike EncoderNLS, this is simply a Debug.Assert. No exception is thrown. Debug.Assert(_fallbackBuffer is null || _fallbackBuffer.Remaining == 0, "Should have no data remaining in the fallback buffer."); Debug.Assert(HasLeftoverData, "Caller shouldn't invoke this routine unless there's leftover data in the decoder."); // Copy the existing leftover data plus as many bytes as possible of the new incoming data // into a temporary concated buffer, then transcode it from bytes to chars. Span<byte> combinedBuffer = stackalloc byte[4]; combinedBuffer = combinedBuffer.Slice(0, ConcatInto(GetLeftoverData(), bytes, combinedBuffer)); int charsWritten = 0; bool persistNewCombinedBuffer = false; Debug.Assert(_encoding != null); switch (_encoding.DecodeFirstRune(combinedBuffer, out Rune value, out int combinedBufferBytesConsumed)) { case OperationStatus.Done: if (value.TryEncodeToUtf16(chars, out charsWritten)) { goto Finish; // successfully transcoded bytes -> chars } else { goto DestinationTooSmall; } case OperationStatus.NeedMoreData: if (MustFlush) { goto case OperationStatus.InvalidData; // treat as equivalent to bad data } else { persistNewCombinedBuffer = true; goto Finish; // successfully consumed some bytes, output no chars } case OperationStatus.InvalidData: break; default: Debug.Fail("Unexpected OperationStatus return value."); break; } // Couldn't decode the buffer. Fallback the buffer instead. The fallback mechanism relies // on a negative index to convey "the start of the invalid sequence was some number of // bytes back before the current buffer." Since we know the invalid sequence must have // started at the beginning of our leftover byte buffer, we can signal to our caller that // they must backtrack that many bytes to find the real start of the invalid sequence. if (FallbackBuffer.Fallback(combinedBuffer.Slice(0, combinedBufferBytesConsumed).ToArray(), index: -_leftoverByteCount) && !_fallbackBuffer!.TryDrainRemainingDataForGetChars(chars, out charsWritten)) { goto DestinationTooSmall; } Finish: // Report back the number of bytes (from the new incoming span) we consumed just now. // This calculation is simple: it's the difference between the original leftover byte // count and the number of bytes from the combined buffer we needed to decode the first // scalar value. We need to report this before the call to SetLeftoverData / // ClearLeftoverData because those methods will overwrite the _leftoverByteCount field. bytesConsumed = combinedBufferBytesConsumed - _leftoverByteCount; if (persistNewCombinedBuffer) { Debug.Assert(combinedBufferBytesConsumed == combinedBuffer.Length, "We should be asked to persist the entire combined buffer."); SetLeftoverData(combinedBuffer); // the buffer still only contains partial data; a future call to Convert will need it } else { ClearLeftoverData(); // the buffer contains no partial data; we'll go down the normal paths } return charsWritten; DestinationTooSmall: // If we got to this point, we're trying to write chars to the output buffer, but we're unable to do // so. Unlike EncoderNLS, this type does not allow partial writes to the output buffer. Since we know // draining leftover data is the first operation performed by any DecoderNLS API, there was no // opportunity for any code before us to make forward progress, so we must fail immediately. _encoding.ThrowCharsOverflow(this, nothingDecoded: true); throw null!; // will never reach this point } /// <summary> /// Given a byte buffer <paramref name="dest"/>, concatenates as much of <paramref name="srcLeft"/> followed /// by <paramref name="srcRight"/> into it as will fit, then returns the total number of bytes copied. /// </summary> private static int ConcatInto(ReadOnlySpan<byte> srcLeft, ReadOnlySpan<byte> srcRight, Span<byte> dest) { int total = 0; for (int i = 0; i < srcLeft.Length; i++) { if ((uint)total >= (uint)dest.Length) { goto Finish; } else { dest[total++] = srcLeft[i]; } } for (int i = 0; i < srcRight.Length; i++) { if ((uint)total >= (uint)dest.Length) { goto Finish; } else { dest[total++] = srcRight[i]; } } Finish: return total; } } }
44.471132
144
0.583714
[ "MIT" ]
Azure-2019/corefx
src/Common/src/CoreLib/System/Text/DecoderNLS.cs
19,256
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("Labs_game")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("Labs_game")] [assembly: System.Reflection.AssemblyTitleAttribute("Labs_game")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
40.708333
80
0.645855
[ "MIT" ]
SebastianTrifa/c-
Labs_game/obj/Debug/netcoreapp2.1/Labs_game.AssemblyInfo.cs
977
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace ComprarCafe { public partial class MainPage : ContentPage { public int Qtde { get; set; } public Double ValorUnd { get; set; } public Double Total { get; set; } public MainPage() { InitializeComponent(); this.Qtde = 0; this.ValorUnd = 5; this.Total = 0; } private void Button_Clicked(object sender, EventArgs e) { Button bt = (Button)sender; if (bt.Text == "-") { if (this.Qtde > 0) { this.Qtde--; } } else { this.Qtde++; } this.Total = this.Qtde * this.ValorUnd; lTotal.Text = "Total: R$ " +Total.ToString(); lQtde.Text = "Quantidade: " + Qtde.ToString(); } } }
23.25
63
0.485826
[ "MIT" ]
dfilitto/ProjetosXamarinForms
ComprarCafe/ComprarCafe/ComprarCafe/MainPage.xaml.cs
1,025
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // </auto-generated> namespace Microsoft.Azure.Management.Compute.Fluent.Models { using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Describes a Virtual Machine Scale Set. /// </summary> [Rest.Serialization.JsonTransformation] public partial class VirtualMachineScaleSetUpdate : UpdateResource { /// <summary> /// Initializes a new instance of the VirtualMachineScaleSetUpdate /// class. /// </summary> public VirtualMachineScaleSetUpdate() { CustomInit(); } /// <summary> /// Initializes a new instance of the VirtualMachineScaleSetUpdate /// class. /// </summary> /// <param name="tags">Resource tags</param> /// <param name="sku">The virtual machine scale set sku.</param> /// <param name="plan">The purchase plan when deploying a virtual /// machine scale set from VM Marketplace images.</param> /// <param name="upgradePolicy">The upgrade policy.</param> /// <param name="virtualMachineProfile">The virtual machine /// profile.</param> /// <param name="overprovision">Specifies whether the Virtual Machine /// Scale Set should be overprovisioned.</param> /// <param name="singlePlacementGroup">When true this limits the scale /// set to a single placement group, of max size 100 virtual /// machines.</param> /// <param name="additionalCapabilities">Specifies additional /// capabilities enabled or disabled on the Virtual Machines in the /// Virtual Machine Scale Set. For instance: whether the Virtual /// Machines have the capability to support attaching managed data /// disks with UltraSSD_LRS storage account type.</param> /// <param name="identity">The identity of the virtual machine scale /// set, if configured.</param> public VirtualMachineScaleSetUpdate(IDictionary<string, string> tags = default(IDictionary<string, string>), Sku sku = default(Sku), Plan plan = default(Plan), UpgradePolicy upgradePolicy = default(UpgradePolicy), VirtualMachineScaleSetUpdateVMProfile virtualMachineProfile = default(VirtualMachineScaleSetUpdateVMProfile), bool? overprovision = default(bool?), bool? singlePlacementGroup = default(bool?), AdditionalCapabilities additionalCapabilities = default(AdditionalCapabilities), VirtualMachineScaleSetIdentity identity = default(VirtualMachineScaleSetIdentity)) : base(tags) { Sku = sku; Plan = plan; UpgradePolicy = upgradePolicy; VirtualMachineProfile = virtualMachineProfile; Overprovision = overprovision; SinglePlacementGroup = singlePlacementGroup; AdditionalCapabilities = additionalCapabilities; Identity = identity; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the virtual machine scale set sku. /// </summary> [JsonProperty(PropertyName = "sku")] public Sku Sku { get; set; } /// <summary> /// Gets or sets the purchase plan when deploying a virtual machine /// scale set from VM Marketplace images. /// </summary> [JsonProperty(PropertyName = "plan")] public Plan Plan { get; set; } /// <summary> /// Gets or sets the upgrade policy. /// </summary> [JsonProperty(PropertyName = "properties.upgradePolicy")] public UpgradePolicy UpgradePolicy { get; set; } /// <summary> /// Gets or sets the virtual machine profile. /// </summary> [JsonProperty(PropertyName = "properties.virtualMachineProfile")] public VirtualMachineScaleSetUpdateVMProfile VirtualMachineProfile { get; set; } /// <summary> /// Gets or sets specifies whether the Virtual Machine Scale Set should /// be overprovisioned. /// </summary> [JsonProperty(PropertyName = "properties.overprovision")] public bool? Overprovision { get; set; } /// <summary> /// Gets or sets when true this limits the scale set to a single /// placement group, of max size 100 virtual machines. /// </summary> [JsonProperty(PropertyName = "properties.singlePlacementGroup")] public bool? SinglePlacementGroup { get; set; } /// <summary> /// Gets or sets specifies additional capabilities enabled or disabled /// on the Virtual Machines in the Virtual Machine Scale Set. For /// instance: whether the Virtual Machines have the capability to /// support attaching managed data disks with UltraSSD_LRS storage /// account type. /// </summary> [JsonProperty(PropertyName = "properties.additionalCapabilities")] public AdditionalCapabilities AdditionalCapabilities { get; set; } /// <summary> /// Gets or sets the identity of the virtual machine scale set, if /// configured. /// </summary> [JsonProperty(PropertyName = "identity")] public VirtualMachineScaleSetIdentity Identity { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (UpgradePolicy != null) { UpgradePolicy.Validate(); } } } }
42.041096
578
0.634409
[ "MIT" ]
acelina/azure-libraries-for-net
src/ResourceManagement/Compute/Generated/Models/VirtualMachineScaleSetUpdate.cs
6,138
C#
/*-------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *-------------------------------------------------------------------------------------------*/ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Xunit; [module: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "Tests", Scope = "namespaceanddescendants", Target = "~N:Microsoft.Unity.Analyzers.Tests")] namespace Microsoft.Unity.Analyzers.Tests { public abstract class BaseDiagnosticVerifierTest<TAnalyzer> : DiagnosticVerifier where TAnalyzer : DiagnosticAnalyzer, new() { internal const string InterfaceTest = @" using UnityEngine; interface IFailure { void FixedUpdate(); } class Failure : MonoBehaviour, IFailure { void IFailure.FixedUpdate() { } } "; [Fact] public async Task DoNotFailWithInterfaceMembers() { await VerifyCSharpDiagnosticAsync(InterfaceTest); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new TAnalyzer(); } } public abstract class BaseSuppressorVerifierTest<TAnalyzer> : SuppressorVerifier where TAnalyzer : DiagnosticSuppressor, new() { [Fact] public async Task DoNotFailWithInterfaceMembers() { await VerifyCSharpDiagnosticAsync(BaseDiagnosticVerifierTest<TAnalyzer>.InterfaceTest); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new TAnalyzer(); } } public abstract class BaseCodeFixVerifierTest<TAnalyzer, TCodeFix> : CodeFixVerifier where TAnalyzer : DiagnosticAnalyzer, new() where TCodeFix : CodeFixProvider, new() { [Fact] public async Task DoNotFailWithInterfaceMembers() { await VerifyCSharpDiagnosticAsync(BaseDiagnosticVerifierTest<TAnalyzer>.InterfaceTest); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new TAnalyzer(); } protected override CodeFixProvider GetCSharpCodeFixProvider() { return new TCodeFix(); } } }
26.27907
117
0.704425
[ "MIT" ]
Mindstyler/Microsoft.Unity.Analyzers
src/Microsoft.Unity.Analyzers.Tests/BaseTest.cs
2,262
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using NLog; using ZVRPub.Library.Model; using ZVRPub.Repository; using ZVRPub.Scaffold; namespace ZVRPub.API.Controllers { [Route("api/inventoryHasLocation")] [ApiController] public class InventoryHasLocationController : ControllerBase { private static readonly Logger log = LogManager.GetCurrentClassLogger(); private readonly IZVRPubRepository Repo; public InventoryHasLocationController(IZVRPubRepository repo) { log.Info("Creating instance of orders controller"); Repo = repo; } // GET: api/InventoryHasLocation [HttpGet] public ActionResult<List<InventoryHasLocation>> GetAll() { log.Info("Retreiving all inventory Location from database"); return Repo.GetAllLocationInventoryByLocation().ToList(); } // GET: api/InventoryHasLocation/5 [HttpGet("{city}", Name = "GetInventoryHasLocation")] public IEnumerable<IngredientInformationAndLocation> Get([FromQuery]string city) { Locations loc = Repo.GetLocationByCity(city); List<InventoryHasLocation> ingredientsIDs = new List<InventoryHasLocation> (); ingredientsIDs.AddRange(Repo.GetLocationInventoryByLocationId(loc.Id)); List<IngredientInformationAndLocation> returnIngredients = new List<IngredientInformationAndLocation>(); foreach (var item in ingredientsIDs) { returnIngredients.Add(new IngredientInformationAndLocation { Id = item.Id, LocationId = item.LocationId, InventoryId = item.InventoryId, Quantity = item.Quantity, IngredientName = Repo.GetIngredientNameById(item.InventoryId) }); } return returnIngredients; } // PUT: api/InventoryHasLocation/5 [HttpPut("{city}")] public async Task<ActionResult> Put([FromQuery]string city) { Locations loc = Repo.GetLocationByCity(city); List<InventoryHasLocation> ingredientsIDs = new List<InventoryHasLocation>(); ingredientsIDs.AddRange(Repo.GetLocationInventoryByLocationId(loc.Id)); foreach (var item in ingredientsIDs) { item.Quantity = 10; await Repo.EditInventoryAsync(item); } return NoContent(); } } }
33.506173
116
0.633751
[ "MIT" ]
1806-jun25-net/Project-Anthony-Randall-Cristian-BackEnd-
ZVRPub.API/ZVRPub.API/Controllers/InventoryHasLocationController.cs
2,716
C#
using Harmony; using ModComponentAPI; namespace ModComponentMapper { [HarmonyPatch(typeof(ItemDescriptionPage), "GetEquipButtonLocalizationId")] class ItemDescriptionPageGetEquipButtonLocalizationIdPatch { public static void Postfix(GearItem gi, ref string __result) { if (__result != string.Empty) { return; } ModComponent modComponent = ModUtils.GetModComponent(gi); if (modComponent != null) { __result = modComponent.InventoryActionLocalizationId; } } } [HarmonyPatch(typeof(ItemDescriptionPage), "CanExamine")] class ItemDescriptionPageCanExaminePatch { public static void Postfix(GearItem gi, ref bool __result) { // guns can always be examined __result |= ModUtils.GetComponent<GunItem>(gi) != null; } } }
26.8
79
0.609808
[ "MIT" ]
WulfMarius/ModComponent
ModComponentMapper/src/patches/ItemDescriptionPagePatch.cs
940
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using WorkflowCore.Persistence.EntityFramework.Models; using WorkflowCore.Persistence.EntityFramework.Services; namespace WorkflowCore.Persistence.SqlServer { public class SqlServerContext : WorkflowDbContext { private readonly string _connectionString; public SqlServerContext(string connectionString) : base() { _connectionString = connectionString; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); optionsBuilder.UseSqlServer(_connectionString); } protected override void ConfigureSubscriptionStorage(EntityTypeBuilder<PersistedSubscription> builder) { builder.ToTable("Subscription", "wfc"); builder.Property(x => x.PersistenceId).UseSqlServerIdentityColumn(); } protected override void ConfigureWorkflowStorage(EntityTypeBuilder<PersistedWorkflow> builder) { builder.ToTable("Workflow", "wfc"); builder.Property(x => x.PersistenceId).UseSqlServerIdentityColumn(); } protected override void ConfigureExecutionPointerStorage(EntityTypeBuilder<PersistedExecutionPointer> builder) { builder.ToTable("ExecutionPointer", "wfc"); builder.Property(x => x.PersistenceId).UseSqlServerIdentityColumn(); } protected override void ConfigureExecutionErrorStorage(EntityTypeBuilder<PersistedExecutionError> builder) { builder.ToTable("ExecutionError", "wfc"); builder.Property(x => x.PersistenceId).UseSqlServerIdentityColumn(); } protected override void ConfigureExetensionAttributeStorage(EntityTypeBuilder<PersistedExtensionAttribute> builder) { builder.ToTable("ExtensionAttribute", "wfc"); builder.Property(x => x.PersistenceId).UseSqlServerIdentityColumn(); } protected override void ConfigureEventStorage(EntityTypeBuilder<PersistedEvent> builder) { builder.ToTable("Event", "wfc"); builder.Property(x => x.PersistenceId).UseSqlServerIdentityColumn(); } } }
37.584615
123
0.691363
[ "MIT" ]
5118234/workflow-core
src/providers/WorkflowCore.Persistence.SqlServer/SqlServerContext.cs
2,445
C#
using Zinnia.Data.Type; namespace Test.Zinnia.Data.Type { using UnityEngine; using System; using NUnit.Framework; using Assert = UnityEngine.Assertions.Assert; public class SerializableTypeTest { [Test] public void ConvertFromType() { Component componentType = new Component(); SerializableType subject = componentType.GetType(); Assert.AreEqual(componentType.GetType(), subject.ActualType); } [Test] public void ConvertToType() { Component componentType = new Component(); SerializableType subject = componentType.GetType(); Type convertedType = subject; Assert.AreEqual(componentType.GetType(), convertedType); } } }
25.806452
73
0.61625
[ "MIT" ]
BestProjectMember/Ship
Library/PackageCache/io.extendreality.zinnia.unity@1.9.0/Tests/Editor/Data/Type/SerializableTypeTest.cs
802
C#
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; namespace Meadow.CoverageReport { [Flags] public enum BranchType { [EnumMember(Value = "none")] None, [EnumMember(Value = "if_statement")] IfStatement, [EnumMember(Value = "ternary")] Ternary, [EnumMember(Value = "assert")] Assert, [EnumMember(Value = "require")] Require } }
17.814815
44
0.594595
[ "MIT" ]
MeadowSuite/Meadow
src/Meadow.CoverageReport/BranchType.cs
483
C#
#region BSD License /* * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE.md file or at * https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.472/blob/master/LICENSE * */ #endregion using ComponentFactory.Krypton.Toolkit; using Core.Classes.Colours; using Core.Classes.Other; using System; using System.Drawing; namespace Core.UX { public partial class ContrastColourGenerator : KryptonForm { #region Variables private RandomNumberGenerator _rng = new RandomNumberGenerator(); #endregion #region Constructors public ContrastColourGenerator() { InitializeComponent(); } public ContrastColourGenerator(Color baseColour) { InitializeComponent(); cpbBaseColour.BackColor = baseColour; } #endregion private void ContrastColourGenerator_Load(object sender, EventArgs e) { } private void kbtnGenerateComplementaryColour_Click(object sender, EventArgs e) { cpbContrastColour.BackColor = ColourExtensions.GetContrast(cpbBaseColour.BackColor, kchkKeepOpacityValues.Checked); } private void tmrUpdateUI_Tick(object sender, EventArgs e) { cpbBaseColour.BackColor = Color.FromArgb(Convert.ToInt32(knumBaseAlphaChannelValue.Value), Convert.ToInt32(knumBaseRedChannelValue.Value), Convert.ToInt32(knumBaseGreenChannelValue.Value), Convert.ToInt32(knumBaseBlueChannelValue.Value)); if (kchkAutomateColourContrastValues.Checked) { cpbContrastColour.BackColor = ColourExtensions.GetContrast(cpbBaseColour.BackColor, kchkKeepOpacityValues.Checked); } } private void cpbContrastColour_BackColorChanged(object sender, EventArgs e) { knumContrastAlphaChannelValue.Value = cpbContrastColour.BackColor.A; knumContrastRedChannelValue.Value = cpbContrastColour.BackColor.R; knumContrastGreenChannelValue.Value = cpbContrastColour.BackColor.G; knumContrastBlueChannelValue.Value = cpbContrastColour.BackColor.B; } private void kbtnInvertColours_Click(object sender, EventArgs e) { cpbBaseColour.BackColor = cpbContrastColour.BackColor; } private void cpbBaseColour_BackColorChanged(object sender, EventArgs e) { knumBaseAlphaChannelValue.Value = cpbBaseColour.BackColor.A; knumBaseRedChannelValue.Value = cpbBaseColour.BackColor.R; knumBaseGreenChannelValue.Value = cpbBaseColour.BackColor.G; knumBaseBlueChannelValue.Value = cpbBaseColour.BackColor.B; } private void kbtnGenerateBaseAlphaValue_Click(object sender, EventArgs e) { knumBaseAlphaChannelValue.Value = _rng.RandomlyGenerateAlphaNumberBetween(0, 255); } private void kbtnGenerateRedValue_Click(object sender, EventArgs e) { knumBaseRedChannelValue.Value = _rng.RandomlyGenerateARedNumberBetween(0, 255); } private void kbtnGenerateGreenValue_Click(object sender, EventArgs e) { knumBaseGreenChannelValue.Value = _rng.RandomlyGenerateAGreenNumberBetween(0, 255); } private void kbtnGenerateBlueValue_Click(object sender, EventArgs e) { knumBaseBlueChannelValue.Value = _rng.RandomlyGenerateABlueNumberBetween(0, 255); } private void kbtnUtiliseBaseColour_Click(object sender, EventArgs e) { PaletteColourCreator paletteColourCreator = new PaletteColourCreator(cpbBaseColour.BackColor); paletteColourCreator.Show(); } } }
33.910714
250
0.690627
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-Toolkit-Suite-Extended-NET-5.472
Source/Krypton Toolkit Suite Extended/Shared/Tooling/UX/Colours/ContrastColourGenerator.cs
3,800
C#
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace ConsoleApp { /* * 抽象建造类,确定部件有几部分组成 * 并生命一个活的结果的办法 */ abstract class Builder { public abstract void BuildPartA(); public abstract void BuildPartB(); public abstract Product GetResult(); } class Product { IList<string> parts = new List<string>(); public void Add(string part) { parts.Add(part); } public void Show() { Console.WriteLine("产品的结果是:\n"); foreach (var part in parts) { Console.WriteLine(part); } } } class ConcreteBuilder1:Builder { private Product _product = new Product(); public override void BuildPartA() { _product.Add("MethodA"); } public override void BuildPartB() { _product.Add("MethodB"); } public override Product GetResult() { return _product; } } class ConcreteBuilder2:Builder { private Product _product = new Product(); public override void BuildPartA() { _product.Add("MethodC"); } public override void BuildPartB() { _product.Add("MethodD"); } public override Product GetResult() { return _product; } } class Director { public void Construe(Builder builder) { builder.BuildPartA(); builder.BuildPartB(); } } }
20.107143
49
0.516874
[ "Apache-2.0" ]
imkcrevit/-
ConsoleApp/Builder.cs
1,759
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using Neutron; namespace Test { class Program { static Random Rnd = new Random(); static string GetString(int Len) { string Ret = ""; for (int i = 0; i < Len; i++) Ret += (char)Rnd.Next((int)'A', (int)'Z'); return Ret; } static void Main(string[] args) { Console.Title = "NeutronVM Test"; Assembler Asm = new Assembler() .OpCode(Opcode.PUSHINT64).AddressOf("1") .OpCode(Opcode.PUSHINT32).Constant(1) .OpCode(Opcode.REGINT) .OpCode(Opcode.PUSHINT32).Constant(0) .OpCode(Opcode.PUSHINT64).AddressOf("Main") .OpCode(Opcode.CALL) .OpCode(Opcode.RELJMP).Constant((long)-1) .Label("Main") .OpCode(Opcode.PUSHSTRING).Constant("Hello World!") .OpCode(Opcode.PUSHINT32).Constant(1) .OpCode(Opcode.LOAD).Constant("print".GetHashCode()) .OpCode(Opcode.CALL) .OpCode(Opcode.RET) .Label("1") .OpCode(Opcode.PUSHSTRING).Constant("Interrupt #1") .OpCode(Opcode.PUSHINT32).Constant(1) .OpCode(Opcode.LOAD).Constant("print".GetHashCode()) .OpCode(Opcode.CALL) .OpCode(Opcode.TERMINATE) .OpCode(Opcode.RET); VM V = new VM(Asm.ToBytecode()); V.Store("getstring".GetHashCode(), new Func<int, string>(GetString)); V.Store("print".GetHashCode(), new Action<object>(Console.WriteLine)); new Thread(() => { Thread.Sleep(1000); V.Interrupt(1); }).Start(); while (V.Executing) V.Run(); Console.WriteLine("Done!"); Console.ReadLine(); } } }
25.967742
73
0.655901
[ "Unlicense" ]
cartman300/Neutron
Test/Program.cs
1,612
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Diagnostics; using Microsoft.Languages.Editor.Shell; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.Languages.Editor.Undo { /// <summary> /// Opens and closes a compound undo action in Visual Studio for a given text buffer /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "ICompoundUndoAction.Close is used instead")] public class CompoundUndoAction : ICompoundUndoAction, ICompoundUndoActionOptions { private ITextBufferUndoManager _undoManager; private ITextUndoTransaction _undoTransaction; private IEditorOperations _editorOperations; private bool _undoAfterClose; private bool _addRollbackOnCancel; public CompoundUndoAction(ITextView textView, ITextBuffer textBuffer, bool addRollbackOnCancel = true) { if (!EditorShell.Current.IsUnitTestEnvironment) { IEditorOperationsFactoryService operationsService = EditorShell.Current.ExportProvider.GetExport<IEditorOperationsFactoryService>().Value; ITextBufferUndoManagerProvider undoProvider = EditorShell.Current.ExportProvider.GetExport<ITextBufferUndoManagerProvider>().Value; _editorOperations = operationsService.GetEditorOperations(textView); _undoManager = undoProvider.GetTextBufferUndoManager(_editorOperations.TextView.TextBuffer); _addRollbackOnCancel = addRollbackOnCancel; } } public void Open(string name) { Debug.Assert(_undoTransaction == null); if (_undoTransaction == null && _undoManager != null && _editorOperations != null) { _undoTransaction = _undoManager.TextBufferUndoHistory.CreateTransaction(name); if (_addRollbackOnCancel) { // Some hosts (*cough* VS *cough*) don't properly implement ITextUndoTransaction such // that their Cancel operation doesn't rollback the already performed actions. // In those scenarios, we'll use our own rollback mechanism (unabashedly copied // from Roslyn) _undoTransaction = new TextUndoTransactionThatRollsBackProperly(_undoTransaction); } _editorOperations.AddBeforeTextBufferChangePrimitive(); } } public void Close(bool discardChanges) { if (_undoTransaction != null) { if (discardChanges) { _undoTransaction.Cancel(); } else { _editorOperations.AddAfterTextBufferChangePrimitive(); _undoTransaction.Complete(); if (_undoAfterClose) { _undoManager.TextBufferUndoHistory.Undo(1); } } } } public void SetMergeDirections(bool mergePrevious, bool mergeNext) { Debug.Assert(_undoTransaction != null); if (_undoTransaction != null) { if (mergePrevious || mergeNext) { _undoTransaction.MergePolicy = new MergeUndoActionPolicy( _undoTransaction.Description, mergePrevious, mergeNext, addedTextChangePrimitives: true); } else { _undoTransaction.MergePolicy = null; } } } public void SetUndoAfterClose(bool undoAfterClose) { _undoAfterClose = undoAfterClose; } } }
46.518072
191
0.649055
[ "MIT" ]
AlexanderSher/RTVS-Old
src/Languages/Editor/Impl/Undo/CompoundUndoAction.cs
3,863
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== namespace Squidex.Domain.Users { public interface IRoleFactory { IRole Create(string name); } }
32.266667
78
0.357438
[ "MIT" ]
BtrJay/squidex
src/Squidex.Domain.Users/IRoleFactory.cs
487
C#
using System; using System.Collections.Generic; using Gtk; using NLog; using System.ServiceModel.Syndication; using System.Xml; using System.Linq; using QSWidgetLib; using QSProjectsLib; using System.Threading; namespace QSSupportLib { public class NewsMenuItem : MenuItem { private static Logger logger = LogManager.GetCurrentClassLogger(); Label menuLabel; Image newsicon; int UnreadNewsCount; public NewsMenuItem () { HBox box = new HBox (false, 0); menuLabel = new Label (); box.Add (menuLabel); newsicon = new Image (Gdk.Pixbuf.LoadFromResource ("QSSupportLib.icons.internet-news-reader.png")); newsicon.TooltipText = "Нет непрочитанных новостей."; newsicon.Show (); box.Add (newsicon); this.Add (box); this.RightJustified = true; this.ShowAll (); menuLabel.Visible = false; } public void LoadFeed() { if (MainNewsFeed.NewsFeeds == null || MainNewsFeed.NewsFeeds.Count == 0) { logger.Warn ("Нет настроенных лент новостей, выходим..."); return; } Thread loadThread = new Thread (new ThreadStart (ThreadWorks)); loadThread.Start (); } private void ThreadWorks() { logger.Info ("Поток: Получаем ленты новостей."); SyndicationFeed mainFeed = new SyndicationFeed(); foreach (var feed in MainNewsFeed.NewsFeeds) { if (!feed.Active) continue; SyndicationFeed syndicationFeed; try { using (XmlReader reader = XmlReader.Create(feed.FeedUri.AbsoluteUri)) { syndicationFeed = SyndicationFeed.Load(reader); } syndicationFeed.Id = feed.Id; syndicationFeed.Items.ToList().ForEach(i => i.SourceFeed = syndicationFeed); } catch(Exception ex) { logger.Warn (ex, "Не удалось прочитать feed"); continue; } SyndicationFeed tempFeed = new SyndicationFeed( mainFeed.Items.Union(syndicationFeed.Items).OrderByDescending(u => u.PublishDate)); mainFeed = tempFeed; } logger.Info ("Создаем меню новостей.."); Application.Invoke (delegate { logger.Info ("Запуск операций в основном потоке.."); UnreadNewsCount = 0; var newsMenu = new Menu (); MenuItemId<SyndicationItem> newsItem; foreach (var news in mainFeed.Items) { Label itemLabel = new Label (); if (MainNewsFeed.ItemIsRead (news)) itemLabel.Text = news.Title.Text; else { itemLabel.Markup = String.Format ("<b>{0}</b>", news.Title.Text); UnreadNewsCount++; } newsItem = new MenuItemId<SyndicationItem> (); newsItem.Add (itemLabel); newsItem.ID = news; newsItem.TooltipMarkup = String.Format ("<b>{0:D}</b> {1}", news.PublishDate, news.Summary.Text); newsItem.Activated += OnNewsActivated; newsMenu.Append (newsItem); } this.Submenu = newsMenu; UpdateIcon (); newsMenu.ShowAll (); MainNewsFeed.SaveFirstRead (); logger.Info("Ок"); }); } void OnNewsActivated (object sender, EventArgs e) { if (sender is MenuItemId<SyndicationItem>) { var news = (sender as MenuItemId<SyndicationItem>).ID; foreach(var link in news.Links) { System.Diagnostics.Process.Start (link.Uri.AbsoluteUri); } var feed = MainNewsFeed.NewsFeeds.Find (f => f.Id == news.SourceFeed.Id); if (feed.AddReadItem (news.Id)) { UnreadNewsCount--; ((sender as MenuItemId<SyndicationItem>).Child as Label).Text = news.Title.Text; UpdateIcon (); } } else logger.Warn ("Некорректная привязка события."); } void UpdateIcon() { if (UnreadNewsCount > 0) { menuLabel.Markup = String.Format ("<span foreground=\"red\" weight=\"bold\">+{0}</span>", UnreadNewsCount); menuLabel.TooltipText = RusNumber.FormatCase (UnreadNewsCount, "{0} непрочитанная новость", "{0} непрочитанных новости", "{0} непрочитанных новостей"); } menuLabel.Visible = (UnreadNewsCount > 0); newsicon.Visible = (UnreadNewsCount == 0); } } }
28.271429
155
0.663719
[ "Apache-2.0" ]
opopve/QSProjects
QSSupportLib/widgets/NewsMenuItem.cs
4,199
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("Q03 All Caps")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Hewlett-Packard")] [assembly: AssemblyProduct("Q03 All Caps")] [assembly: AssemblyCopyright("Copyright © Hewlett-Packard 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6e45f6f3-5765-469c-9d97-daebe33b410e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.432432
84
0.748945
[ "MIT" ]
Uendy/Tech-Module
L08 Files, Exceptions, Directories/L08 Exception Qs/L08 Exception Qs/Q03 All Caps/Properties/AssemblyInfo.cs
1,425
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ZimmerBot.Core.Knowledge; namespace ZimmerBot.Core.WordRegex { public class NFANode { public enum TypeEnum { Literal, EntityLiteral, Split, Match } public TypeEnum Type { get; protected set; } public string Literal { get; protected set; } public List<string> MatchNames { get; protected set; } public List<NFAEdge> Out { get; protected set; } public static readonly NFANode MatchNode = new NFANode { Type = TypeEnum.Match }; internal NFANode() { Out = new List<NFAEdge>(); MatchNames = new List<string>(); } public static NFANode CreateLiteral(WRegexBase.EvaluationContext context, string literal) { NFANode n = new NFANode { Type = TypeEnum.Literal, Literal = literal }; n.Out.Add(new NFAEdge(null)); n.MatchNames.AddRange(context.MatchNames); return n; } public static NFANode CreateEntityLiteral(WRegexBase.EvaluationContext context) { NFANode n = new NFANode { Type = TypeEnum.EntityLiteral }; n.Out.Add(new NFAEdge(null)); n.MatchNames.AddRange(context.MatchNames); return n; } public static NFANode CreateSplit(WRegexBase.EvaluationContext context, IEnumerable<NFANode> choices) { NFANode n = new NFANode { Type = TypeEnum.Split }; n.Out.AddRange(choices.Select(c => new NFAEdge(c))); return n; } public static NFANode CreateSplit(WRegexBase.EvaluationContext context, params NFANode[] choices) { return CreateSplit(context, (IEnumerable<NFANode>)choices); } } }
26.876923
106
0.660561
[ "MIT" ]
JornWildt/ZimmerBot
ZimmerBot.Core/WordRegex/NFANode.cs
1,749
C#
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2017 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. 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. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2017 Senparc 文件名:Config.cs 文件功能描述:全局设置 创建标识:Senparc - 20150211 修改标识:Senparc - 20150303 修改描述:整理接口 修改标识:Senparc - 20160813 修改描述:v4.7.7 添加DefaultCacheNamespace ----------------------------------------------------------------*/ using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading; namespace Senparc.Weixin { /// <summary> /// 全局设置 /// </summary> public static class Config { /// <summary> /// 请求超时设置(以毫秒为单位),默认为10秒。 /// 说明:此处常量专为提供给方法的参数的默认值,不是方法内所有请求的默认超时时间。 /// </summary> public const int TIME_OUT = 10000; private static bool _isDebug = false;//TODO:需要考虑分布式的情况,后期需要储存在缓存中 /// <summary> /// 指定是否是Debug状态,如果是,系统会自动输出日志 /// </summary> public static bool IsDebug { get { return _isDebug; } set { _isDebug = value; //if (_isDebug) //{ // WeixinTrace.Open(); //} //else //{ // WeixinTrace.Close(); //} } } /// <summary> /// JavaScriptSerializer 类接受的 JSON 字符串的最大长度 /// </summary> public static int MaxJsonLength = int.MaxValue;//TODO:需要考虑分布式的情况,后期需要储存在缓存中 /// <summary> /// 默认缓存键的第一级命名空间,默认值:DefaultCache /// </summary> public static string DefaultCacheNamespace = "DefaultCache";//TODO:需要考虑分布式的情况,后期需要储存在缓存中,或进行全局配置 } }
28.271739
104
0.538639
[ "Apache-2.0" ]
AjuPrince/WeiXinMPSDK
src/Senparc.Weixin/Senparc.Weixin/Config.cs
3,063
C#
using STRINGS; using static SkyLib.OniUtils; using Harmony; using Klei.AI; using PeterHan.PLib; using UnityEngine; namespace DiseasesReimagined { using TempMonitorStateMachine = GameStateMachine<ExternalTemperatureMonitor, ExternalTemperatureMonitor.Instance, IStateMachineTarget, object>; // Patches for frostbite-related things public static class FrostbitePatch { // Add strings and status items for Frostbite public static class Mod_OnLoad { public static void OnLoad() { AddStatusItem("FROSTBITTEN", "NAME", "Frostbite", "CREATURES"); AddStatusItem("FROSTBITTEN", "TOOLTIP", "Current external " + UI.PRE_KEYWORD + "Temperature" + UI.PST_KEYWORD + " is perilously low [<b>{ExternalTemperature}</b> / <b>{TargetTemperature}</b>]", "CREATURES"); AddStatusItem("FROSTBITTEN", "NOTIFICATION_NAME", "Frostbite", "CREATURES"); AddStatusItem("FROSTBITTEN", "NOTIFICATION_TOOLTIP", "Freezing " + UI.PRE_KEYWORD + "Temperatures" + UI.PST_KEYWORD + " are hurting these Duplicants:", "CREATURES"); Strings.Add("STRINGS.DUPLICANTS.ATTRIBUTES.FROSTBITETHRESHOLD.NAME", "Frostbite Threshold"); Strings.Add("STRINGS.DUPLICANTS.ATTRIBUTES.FROSTBITETHRESHOLD.TOOLTIP", "Determines the " + UI.PRE_KEYWORD + "Temperature" + UI.PST_KEYWORD + " at which a Duplicant will be frostbitten."); } } // Gets the minimum external pressure of the cells occupied by the creature public static float GetCurrentExternalPressure(ExternalTemperatureMonitor.Instance instance) { int cell = Grid.PosToCell(instance.gameObject); var area = instance.occupyArea; float pressure = Grid.Pressure[cell]; if (area != null) { foreach (CellOffset offset in area.OccupiedCellsOffsets) { int newCell = Grid.OffsetCell(cell, offset); if (Grid.IsValidCell(newCell)) { float newPressure = Grid.Pressure[newCell]; if (newPressure < pressure) pressure = newPressure; } } } return pressure; } public static float GetFrostbiteThreshold(ExternalTemperatureMonitor.Instance data) { return data.attributes.GetValue("FrostbiteThreshold") + GermExposureTuning. BASE_FROSTBITE_THRESHOLD; } // Add Frostbite that is Scalding but for cold [HarmonyPatch(typeof(ExternalTemperatureMonitor), "InitializeStates")] public static class ExternalTemperatureMonitor_InitializeStates_Patch { public static TempMonitorStateMachine.State frostbite; public static TempMonitorStateMachine.State transitionToFrostbite; public static StatusItem Frostbitten = new StatusItem( "FROSTBITTEN", "CREATURES", string.Empty, StatusItem.IconType.Exclamation, NotificationType.DuplicantThreatening, true, OverlayModes.None.ID ) { resolveTooltipCallback = (str, data) => { float externalTemperature = ((ExternalTemperatureMonitor.Instance) data).AverageExternalTemperature; float frostbiteThreshold = GetFrostbiteThreshold((ExternalTemperatureMonitor.Instance)data); str = str.Replace("{ExternalTemperature}", GameUtil.GetFormattedTemperature(externalTemperature)); str = str.Replace("{TargetTemperature}", GameUtil.GetFormattedTemperature(frostbiteThreshold)); return str; }}; public static bool isFrostbite(ExternalTemperatureMonitor.Instance data) { // a bit of a kludge, because for some reason Average External Temperature // does not update for Frostbite even though it does for Scalding. var exttemp = data.GetCurrentExternalTemperature; return exttemp < GetFrostbiteThreshold(data) && exttemp > 0.01f && GetCurrentExternalPressure(data) >= GermExposureTuning.MIN_PRESSURE; } public static void Postfix(ExternalTemperatureMonitor __instance) { Frostbitten.AddNotification(); frostbite = __instance.CreateState(nameof(frostbite)); transitionToFrostbite = __instance.CreateState(nameof(transitionToFrostbite)); __instance.tooCool.Transition(transitionToFrostbite, smi => isFrostbite(smi) && smi.timeinstate > 3.0f); transitionToFrostbite .Transition(__instance.tooCool, smi => !isFrostbite(smi)) .Transition(frostbite, smi => { // If in a frostbite-valid state and stays there for 1s, we are now frostbitten return isFrostbite(smi) && smi.timeinstate > 1.0; }); frostbite .Transition(__instance.tooCool, smi => !isFrostbite(smi) && smi.timeinstate > 3.0f) // to leave frostbite state .ToggleExpression(Db.Get().Expressions.Cold) // brr .ToggleThought(Db.Get().Thoughts.Cold) // I'm thinking of brr .ToggleStatusItem(Frostbitten, smi => smi) .Update("ColdDamage", (smi, dt) => smi.ScaldDamage(dt), UpdateRate.SIM_1000ms); } } // Frostbite and scald damage depending on temperature [HarmonyPatch(typeof(ExternalTemperatureMonitor.Instance), "ScaldDamage")] public static class ExternalTemperatureMonitor_Instance_ScaldDamage_Patch { public static bool Prefix(ExternalTemperatureMonitor.Instance __instance, float dt, float ___lastScaldTime) { float now = Time.time; var hp = __instance.health; // Avoid damage for pressures < threshold bool pressure = GetCurrentExternalPressure(__instance) > GermExposureTuning. MIN_PRESSURE; if (hp != null && now - ___lastScaldTime > 5.0f && pressure) { float temp = __instance.AverageExternalTemperature, mult = GermExposureTuning.DAMAGE_PER_K; // For every 5 C outside the limits, damage 1HP more float damage = System.Math.Max(0.0f, mult * (temp - __instance. GetScaldingThreshold())) + System.Math.Max(0.0f, mult * ( GetFrostbiteThreshold(__instance) - temp)); if (damage > 0.0f) hp.Damage(damage * dt); } return pressure; } } // Frostbite attribute setup [HarmonyPatch(typeof(Database.Attributes), MethodType.Constructor, typeof(ResourceSet))] public static class Database_Attributes_Attributes_Patch { public static void Postfix(Database.Attributes __instance) { var frostbiteThreshold = new Attribute("FrostbiteThreshold", false, Attribute.Display.General, false); frostbiteThreshold.SetFormatter(new StandardAttributeFormatter( GameUtil.UnitClass.Temperature, GameUtil.TimeSlice.None)); __instance.Add(frostbiteThreshold); } } // Add Atmo Suit frostbite immunity [HarmonyPatch(typeof(AtmoSuitConfig), "CreateEquipmentDef")] public static class AtmosuitConfig_CreateEquipmentDef_Patch { public static void Postfix(EquipmentDef __result) { __result.AttributeModifiers.Add(new AttributeModifier("FrostbiteThreshold", -200.0f, EQUIPMENT.PREFABS.ATMO_SUIT.NAME)); } } } }
47.75
130
0.583651
[ "MIT" ]
BaalEvan/sky-oni-mods
DiseasesReimagined/FrostbitePatch.cs
8,404
C#
#if ! (UNITY_DASHBOARD_WIDGET || UNITY_WEBPLAYER || UNITY_WII || UNITY_WIIU || UNITY_NACL || UNITY_FLASH || UNITY_BLACKBERRY) // Disable under unsupported platforms. //------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 3.0.12 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ public enum AKRESULT { AK_NotImplemented = 0, AK_Success = 1, AK_Fail = 2, AK_PartialSuccess = 3, AK_NotCompatible = 4, AK_AlreadyConnected = 5, AK_InvalidFile = 7, AK_AudioFileHeaderTooLarge = 8, AK_MaxReached = 9, AK_InvalidID = 14, AK_IDNotFound = 15, AK_InvalidInstanceID = 16, AK_NoMoreData = 17, AK_InvalidStateGroup = 20, AK_ChildAlreadyHasAParent = 21, AK_InvalidLanguage = 22, AK_CannotAddItseflAsAChild = 23, AK_InvalidParameter = 31, AK_ElementAlreadyInList = 35, AK_PathNotFound = 36, AK_PathNoVertices = 37, AK_PathNotRunning = 38, AK_PathNotPaused = 39, AK_PathNodeAlreadyInList = 40, AK_PathNodeNotInList = 41, AK_DataNeeded = 43, AK_NoDataNeeded = 44, AK_DataReady = 45, AK_NoDataReady = 46, AK_InsufficientMemory = 52, AK_Cancelled = 53, AK_UnknownBankID = 54, AK_BankReadError = 56, AK_InvalidSwitchType = 57, AK_FormatNotReady = 63, AK_WrongBankVersion = 64, AK_FileNotFound = 66, AK_DeviceNotReady = 67, AK_BankAlreadyLoaded = 69, AK_RenderedFX = 71, AK_ProcessNeeded = 72, AK_ProcessDone = 73, AK_MemManagerNotInitialized = 74, AK_StreamMgrNotInitialized = 75, AK_SSEInstructionsNotSupported = 76, AK_Busy = 77, AK_UnsupportedChannelConfig = 78, AK_PluginMediaNotAvailable = 79, AK_MustBeVirtualized = 80, AK_CommandTooLarge = 81, AK_RejectedByFilter = 82, AK_InvalidCustomPlatformName = 83, AK_DLLCannotLoad = 84, AK_DLLPathNotFound = 85, AK_NoJavaVM = 86, AK_OpenSLError = 87, AK_PluginNotRegistered = 88, AK_DataAlignmentError = 89, AK_DeviceNotCompatible = 90, AK_DuplicateUniqueID = 91, AK_InitBankNotLoaded = 92, AK_DeviceNotFound = 93 } #endif // #if ! (UNITY_DASHBOARD_WIDGET || UNITY_WEBPLAYER || UNITY_WII || UNITY_WIIU || UNITY_NACL || UNITY_FLASH || UNITY_BLACKBERRY) // Disable under unsupported platforms.
31.519481
175
0.688916
[ "MIT" ]
AlbertCayuela/AudioDigital
WAG_No_Sound/Assets/Wwise/Deployment/API/Generated/Common/AKRESULT.cs
2,427
C#
using NiFpgaGen.DataTypes; using NiFpgaGen.FRC; using NiFpgaGen.Languages.C; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; namespace NiFpgaGen { //public enum DataType //{ // Array, // Boolean, // Cluster, // FXP, // EnumU16, // U8, // I8, // I16, // U16, // I32, // U32, // U64, // I64 //} //public class Register //{ // public string Name { get; set; } // public bool Hidden { get; } // public bool Indicator { get; } // public DataType DataType { get; } // public uint Offset { get; } // public XElement ExtraData { get; } // public List<(int, uint)> OffsetList = new List<(int, uint)>(); // public Register(XElement element) // { // Name = element.Element("Name").Value; // Hidden = bool.Parse(element.Element("Hidden").Value); // Indicator = bool.Parse(element.Element("Indicator").Value); // DataType = Enum.Parse<DataType>(((XElement)element.Element("Datatype").FirstNode).Name.LocalName); // Offset = uint.Parse(element.Element("Offset").Value); // ExtraData = element; // ; // } //} class Program { static async Task Main(string[] args) { string fileName = @"C:\Users\thadh\Documents\GitHub\thadhouse\NiFpgaGen\roboRIO_FPGA_2020_20.1.2.lvbitx"; using var file = new FileStream(fileName, FileMode.Open, FileAccess.Read); XElement bitfile = await XElement.LoadAsync(file, LoadOptions.None, CancellationToken.None); //var registerList = bitfile.Descendants("VI").Descendants("RegisterList").Descendants("Register").Select(x => new Register(x)); var registerList2 = bitfile.Element("VI").Element("RegisterList").Elements("Register"); DataTypeFactory factory = DataTypeFactory.Instance; List<Register> registers = new List<Register>(); foreach (var register in registerList2) { registers.Add(new Register(register)); } var frcRegisters = FRCClass.GetDefaultClassList(); foreach (var register in registers) { FRCClass.AddRegisterToClassList(frcRegisters, register); } FRCClass.ValidateClasses(frcRegisters); var tempalteMapper = new CLanguageTemplates(); foreach (var cls in frcRegisters) { } //var frcMapping = new FRCMapping(registerList); //frcMapping.GenerateC(@"C:\Users\thadh\Documents\GitHub\thadhouse\NiFpgaGen\Generated", "FRC"); ; } } }
29.456311
141
0.556361
[ "MIT" ]
ThadHouse/NiFpgaGen
src/NiFpgaGen/Program.cs
3,036
C#
using System; namespace AspIdApi.Areas.HelpPage.ModelDescriptions { /// <summary> /// Describes a type model. /// </summary> public abstract class ModelDescription { public string Documentation { get; set; } public Type ModelType { get; set; } public string Name { get; set; } } }
20.6875
51
0.616314
[ "MIT" ]
cloudstrifebro/sampleWork
TestSample/AspIdentityImplementation/AspIdApi/Areas/HelpPage/ModelDescriptions/ModelDescription.cs
331
C#
using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEngine; namespace MetaSprite { public class MetaLayerPivot : MetaLayerProcessor { public override string actionName { get { return "pivot"; } } public override int executionOrder => 2; // After @subTarget. struct PivotFrame { public int frame; public Vector2 pivot; } public override void Process(ImportContext ctx, Layer layer) { var pivots = new List<PivotFrame>(); var file = ctx.file; for (int i = 0; i < file.frames.Count; ++i) { Cel cel; file.frames[i].cels.TryGetValue(layer.index, out cel); if (cel != null) { Vector2 center = Vector2.zero; int pixelCount = 0; for (int y = 0; y < cel.height; ++y) for (int x = 0; x < cel.width; ++x) { // tex coords relative to full texture boundaries int texX = cel.x + x; int texY = -(cel.y + y) + file.height - 1; var col = cel.GetPixelRaw(x, y); if (col.a > 0.1f) { center += new Vector2(texX, texY); ++pixelCount; } } if (pixelCount > 0) { center /= pixelCount; pivots.Add(new PivotFrame { frame = i, pivot = center }); } } } if (pivots.Count == 0) return; // Modify pivot for each and every atlas sprites var spriteRetargetDict = new Dictionary<Sprite, Sprite>(); foreach (var atlas in ctx.output.generatedAtlasList) { var sprites = atlas.sprites; for (int i = 0; i < sprites.Count; ++i) { int j = 1; while (j < pivots.Count && pivots[j].frame <= i) ++j; // j = index after found item Vector2 pivot = pivots[j - 1].pivot; pivot -= atlas.spriteCropPositions[i]; pivot = Vector2.Scale(pivot, new Vector2(1.0f / sprites[i].rect.width, 1.0f / sprites[i].rect.height)); var oldSprite = sprites[i]; var newSprite = Sprite.Create(oldSprite.texture, oldSprite.rect, pivot, oldSprite.pixelsPerUnit); newSprite.name = oldSprite.name; // Object.DestroyImmediate(oldSprite); sprites[i] = newSprite; spriteRetargetDict.Add(oldSprite, newSprite); } } foreach (var clip in ctx.output.generatedClips.Values) { foreach (var curveBinding in AnimationUtility.GetObjectReferenceCurveBindings(clip)) { if (curveBinding.type == typeof(SpriteRenderer) && curveBinding.propertyName == "m_Sprite") { var keyFrames = AnimationUtility.GetObjectReferenceCurve(clip, curveBinding); for (int i = 0; i < keyFrames.Length; ++i) { if (spriteRetargetDict.TryGetValue((Sprite) keyFrames[i].value, out var replaceSprite)) { keyFrames[i].value = replaceSprite; } } AnimationUtility.SetObjectReferenceCurve(clip, curveBinding, keyFrames); } } } } } }
37.484536
121
0.485699
[ "MIT" ]
TraditoreZ/MetaSprite
Assets/Plugins/MetaSprite/Editor/MetaLayer/MetaLayerPivot.cs
3,636
C#
using ExtendedXmlSerializer.ContentModel.Identification; using ExtendedXmlSerializer.ContentModel.Properties; namespace ExtendedXmlSerializer.ContentModel.Content { sealed class NullElementIdentity : IIdentity { public static NullElementIdentity Default { get; } = new NullElementIdentity(); NullElementIdentity() : this(new FrameworkIdentity("Null")) {} readonly IIdentity _identity; public NullElementIdentity(IIdentity identity) => _identity = identity; public string Identifier => _identity.Identifier; public string Name => _identity.Name; } }
29.4
82
0.770408
[ "MIT" ]
ExtendedXmlSerializer/NextRelease
src/ExtendedXmlSerializer/ContentModel/Content/NullElementIdentity.cs
588
C#
using BepuUtilities; using DemoContentLoader; using SharpDX.Direct3D11; using System; using System.Numerics; using System.Runtime.InteropServices; using Quaternion = BepuUtilities.Quaternion; namespace DemoRenderer.ShapeDrawing { /// <summary> /// GPU-relevant information for the rendering of a single sphere instance. /// </summary> public struct SphereInstance { public Vector3 Position; public float Radius; public Vector3 PackedOrientation; public uint PackedColor; } /// <summary> /// GPU-relevant information for the rendering of a single capsule instance. /// </summary> public struct CapsuleInstance { public Vector3 Position; public float Radius; public ulong PackedOrientation; public float HalfLength; public uint PackedColor; } }
25.558824
80
0.684695
[ "Apache-2.0" ]
Jjagg/bepuphysics2
DemoRenderer/ShapeDrawing/RayTracedInstances.cs
871
C#
using System; using System.IO; using EventStore.Core.TransactionLog; using EventStore.Core.TransactionLog.Checkpoint; using EventStore.Core.TransactionLog.Chunks; using EventStore.Core.TransactionLog.FileNamingStrategy; using NUnit.Framework; namespace EventStore.Core.Tests.TransactionLog { [TestFixture] public class when_creating_chunked_transaction_chaser : SpecificationWithDirectory { [Test] public void a_null_file_config_throws_argument_null_exception() { Assert.Throws<ArgumentNullException>( () => new TFChunkChaser(null, new InMemoryCheckpoint(0), new InMemoryCheckpoint(0), false)); } [Test] public void a_null_writer_checksum_throws_argument_null_exception() { var db = new TFChunkDb(TFChunkHelper.CreateDbConfig(PathName, 0)); Assert.Throws<ArgumentNullException>(() => new TFChunkChaser(db, null, new InMemoryCheckpoint(), false)); } [Test] public void a_null_chaser_checksum_throws_argument_null_exception() { var db = new TFChunkDb(TFChunkHelper.CreateDbConfig(PathName, 0)); Assert.Throws<ArgumentNullException>(() => new TFChunkChaser(db, new InMemoryCheckpoint(), null, false)); } } }
37.032258
108
0.789199
[ "Apache-2.0", "CC0-1.0" ]
01100010011001010110010101110000/EventStore
src/EventStore.Core.Tests/TransactionLog/when_creating_chunked_transaction_chaser.cs
1,148
C#
using System; using MikhailKhalizev.Processor.x86.BinToCSharp; namespace MikhailKhalizev.Max.Program { public partial class RawProgram { [MethodInfo("0x100b_4d3b-dd4bb79c")] public void Method_100b_4d3b() { ii(0x100b_4d3b, 5); push(0x20); /* push 0x20 */ ii(0x100b_4d40, 5); call(Definitions.sys_check_available_stack_size, 0xb_100d);/* call 0x10165d52 */ ii(0x100b_4d45, 1); push(ebx); /* push ebx */ ii(0x100b_4d46, 1); push(ecx); /* push ecx */ ii(0x100b_4d47, 1); push(edx); /* push edx */ ii(0x100b_4d48, 1); push(esi); /* push esi */ ii(0x100b_4d49, 1); push(edi); /* push edi */ ii(0x100b_4d4a, 1); push(ebp); /* push ebp */ ii(0x100b_4d4b, 2); mov(ebp, esp); /* mov ebp, esp */ ii(0x100b_4d4d, 6); sub(esp, 4); /* sub esp, 0x4 */ ii(0x100b_4d53, 3); mov(memd[ss, ebp - 4], eax); /* mov [ebp-0x4], eax */ ii(0x100b_4d56, 2); xor(edx, edx); /* xor edx, edx */ ii(0x100b_4d58, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x100b_4d5b, 3); add(eax, 0x13); /* add eax, 0x13 */ ii(0x100b_4d5e, 5); call(0x1007_6630, -0x3_e733); /* call 0x10076630 */ ii(0x100b_4d63, 2); xor(edx, edx); /* xor edx, edx */ ii(0x100b_4d65, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x100b_4d68, 3); add(eax, 0x17); /* add eax, 0x17 */ ii(0x100b_4d6b, 5); call(0x1007_6630, -0x3_e740); /* call 0x10076630 */ ii(0x100b_4d70, 2); xor(edx, edx); /* xor edx, edx */ ii(0x100b_4d72, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x100b_4d75, 3); add(eax, 0xf); /* add eax, 0xf */ ii(0x100b_4d78, 5); call(0x1008_afe4, -0x2_9d99); /* call 0x1008afe4 */ ii(0x100b_4d7d, 3); mov(edx, memd[ss, ebp - 4]); /* mov edx, [ebp-0x4] */ ii(0x100b_4d80, 5); mov(eax, 0x101c_3180); /* mov eax, 0x101c3180 */ ii(0x100b_4d85, 5); call(0x100a_5e27, -0xef63); /* call 0x100a5e27 */ ii(0x100b_4d8a, 2); mov(esp, ebp); /* mov esp, ebp */ ii(0x100b_4d8c, 1); pop(ebp); /* pop ebp */ ii(0x100b_4d8d, 1); pop(edi); /* pop edi */ ii(0x100b_4d8e, 1); pop(esi); /* pop esi */ ii(0x100b_4d8f, 1); pop(edx); /* pop edx */ ii(0x100b_4d90, 1); pop(ecx); /* pop ecx */ ii(0x100b_4d91, 1); pop(ebx); /* pop ebx */ ii(0x100b_4d92, 1); ret(); /* ret */ } } }
70.291667
114
0.407528
[ "Apache-2.0" ]
mikhail-khalizev/max
source/MikhailKhalizev.Max/source/Program/Auto/z-100b-4d3b.cs
3,374
C#
// WARNING // // This file has been generated automatically by Visual Studio from the outlets and // actions declared in your storyboard file. // Manual changes to this file will not be maintained. // using Foundation; using System; using System.CodeDom.Compiler; using UIKit; namespace IndoorRouting.iOS { [Register ("MapViewController")] partial class MapViewController { [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UITableView AutosuggestionsTableView { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.NSLayoutConstraint ButtonBottomConstraint { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UIView ContactCardView { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UIButton CurrentLocationButton { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UIButton DirectionsButton { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.NSLayoutConstraint FloorPickerBottomConstraint { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UITableView FloorsTableView { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.NSLayoutConstraint HeightConstraint { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UIBarButtonItem HomeButton { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UISearchBar LocationSearchBar { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UILabel MainLabel { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] Esri.ArcGISRuntime.UI.Controls.MapView MapView { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UIView RouteCard { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UITableView RouteTableView { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UIToolbar SearchToolbar { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UILabel SecondaryLabel { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UIBarButtonItem SettingsButton { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UILabel WalkTimeLabel { get; set; } [Action ("CurrentLocationButton_TouchUpInside:")] [GeneratedCode ("iOS Designer", "1.0")] partial void CurrentLocationButton_TouchUpInside (UIKit.UIButton sender); [Action ("Home_TouchUpInside:")] [GeneratedCode ("iOS Designer", "1.0")] partial void Home_TouchUpInside (UIKit.UIBarButtonItem sender); void ReleaseDesignerOutlets () { if (AutosuggestionsTableView != null) { AutosuggestionsTableView.Dispose (); AutosuggestionsTableView = null; } if (ButtonBottomConstraint != null) { ButtonBottomConstraint.Dispose (); ButtonBottomConstraint = null; } if (ContactCardView != null) { ContactCardView.Dispose (); ContactCardView = null; } if (CurrentLocationButton != null) { CurrentLocationButton.Dispose (); CurrentLocationButton = null; } if (DirectionsButton != null) { DirectionsButton.Dispose (); DirectionsButton = null; } if (FloorPickerBottomConstraint != null) { FloorPickerBottomConstraint.Dispose (); FloorPickerBottomConstraint = null; } if (FloorsTableView != null) { FloorsTableView.Dispose (); FloorsTableView = null; } if (HeightConstraint != null) { HeightConstraint.Dispose (); HeightConstraint = null; } if (HomeButton != null) { HomeButton.Dispose (); HomeButton = null; } if (LocationSearchBar != null) { LocationSearchBar.Dispose (); LocationSearchBar = null; } if (MainLabel != null) { MainLabel.Dispose (); MainLabel = null; } if (MapView != null) { MapView.Dispose (); MapView = null; } if (RouteCard != null) { RouteCard.Dispose (); RouteCard = null; } if (RouteTableView != null) { RouteTableView.Dispose (); RouteTableView = null; } if (SearchToolbar != null) { SearchToolbar.Dispose (); SearchToolbar = null; } if (SecondaryLabel != null) { SecondaryLabel.Dispose (); SecondaryLabel = null; } if (SettingsButton != null) { SettingsButton.Dispose (); SettingsButton = null; } if (WalkTimeLabel != null) { WalkTimeLabel.Dispose (); WalkTimeLabel = null; } } } }
29.5
84
0.527208
[ "Apache-2.0" ]
YixinZhou/indoor-routing-xamarin
iOS/Controllers/MapViewController_.designer.cs
5,605
C#
namespace StudentSystem.Data.Contracts { using System.Data.Entity; using System.Data.Entity.Infrastructure; using Models; public interface IStudentSystemDbContext { IDbSet<Course> Courses { get; set; } IDbSet<Homework> Homeworks { get; set; } IDbSet<Student> Students { get; set; } IDbSet<T> Set<T>() where T : class; DbEntityEntry<T> Entry<T>(T entity) where T : class; int SaveChanges(); } }
22.47619
60
0.625
[ "MIT" ]
danisio/WebServicesAndCloud-Homeworks
01.ASP.NET Web API/1.StudentSystem/StudentSystem.Data/Contracts/IStudentSystemDbContext.cs
474
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using RuneOptim.swar; namespace RunePlugin { public class SWMessage { [JsonProperty("command")] public string CommandStr; [JsonIgnore] public SWCommand Command { get { SWCommand c = SWCommand.Unhandled; Enum.TryParse<SWCommand>(CommandStr, out c); return c; } } [JsonProperty("session_key")] protected string SessionKey; [JsonProperty("proto_ver")] public int ProtoVer; [JsonProperty("infocsv")] public string InfoCSV; [JsonProperty("channel_uid")] public int ChannelUID; [JsonProperty("ts_val")] public int TSVal; [JsonProperty("wizard_id")] public int WizardId; } [System.AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)] sealed class SWCommandAttribute : Attribute { public SWCommand Command { get; private set; } // This is a positional argument public SWCommandAttribute(SWCommand command) { this.Command = command; } } public class ClearRecord { [JsonProperty("is_new_record")] public bool NewRecord; [JsonProperty("current_time")] public long Current; [JsonProperty("best_time")] public long Best; } public class DungeonReward { [JsonProperty("mana")] public int Mana; [JsonProperty("crystal")] public int Crystal; [JsonProperty("energy")] public int Energy; [JsonProperty("crate")] public RewardCrate Crate; [JsonProperty("item_list")] public InventoryItem[] Items; } public class RewardCrate { [JsonProperty("rune")] public RuneOptim.swar.Rune Rune; [JsonProperty("craft_stuff")] public Craft Craft; [JsonProperty("material")] public InventoryItem Material; //[JsonProperty("material")] //public RuneOptim.InventoryItem[] Materials; [JsonProperty("summon_pieces")] public InventoryItem[] SummoningPieces; [JsonProperty("unit_info")] public Monster Monster; } [JsonConverter(typeof(StringEnumConverter))] public enum SWCommand { Unhandled, EquipRune, EquipRuneList, UnequipRune, HubUserLogin, LockUnit, UnlockUnit, SummonUnit, BattleScenarioResult, BattleDungeonResult, SellRune, SacrificeUnit, SellRuneCraftItem, UpgradeUnit, UpdateUnitExpGained, BattleRiftDungeonResult, GetBestClearRiftDungeon, UpgradeRune, RevalueRune, ConfirmRune, UpgradeDeco, // Guild War GetGuildWarMatchupInfo, GetGuildWarParticipationInfo, GetGuildInfo, GetGuildWarBattleLogByGuildId, GetGuildWarBattleLogByWizardId, // Siege Battle GetTargetUnitInfo, GetGuildSiegeDefenseDeckByWizardId, GetGuildSiegeRankingInfo, GetGuildSiegeBaseDefenseUnitList, GetGuildSiegeBattleLogByDeckId, GetGuildSiegeMatchupInfo, GetGuildSiegeBattleLogByWizardId, } }
24.538462
92
0.616985
[ "BSD-3-Clause" ]
RuneManager/RuneManager
RunePlugin/SWMessage.cs
3,511
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RayTracer.Models { public class Ray : INotifyPropertyChanged { private Vector start; public Ray() { } public Ray(Vector start, Vector dir) { Start = start; Dir = dir; } public Vector Start { get { return start; } set { if (start != value) { start = value; OnPropertyChanged("Start"); } } } private Vector dir; public Vector Dir { get { return dir; } set { if (dir != value) { dir = value; OnPropertyChanged("Dir"); } } } protected virtual void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) { handler.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public event PropertyChangedEventHandler PropertyChanged; } }
20.808824
81
0.435336
[ "Apache-2.0" ]
georghinkel/RayTracer
Models/Ray.cs
1,417
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Primitives; using Xunit; namespace Microsoft.Extensions.Configuration.KeyPerFile.Test { public class KeyPerFileTests { [Fact] public void DoesNotThrowWhenOptionalAndNoSecrets() { new ConfigurationBuilder().AddKeyPerFile(o => o.Optional = true).Build(); } [Fact] public void DoesNotThrowWhenOptionalAndDirectoryDoesntExist() { new ConfigurationBuilder().AddKeyPerFile("nonexistent", true).Build(); } [Fact] public void ThrowsWhenNotOptionalAndDirectoryDoesntExist() { var e = Assert.Throws<ArgumentException>(() => new ConfigurationBuilder().AddKeyPerFile("nonexistent", false).Build()); Assert.Contains("The path must be absolute.", e.Message); } [Fact] public void CanLoadMultipleSecrets() { var testFileProvider = new TestFileProvider( new TestFile("Secret1", "SecretValue1"), new TestFile("Secret2", "SecretValue2")); var config = new ConfigurationBuilder() .AddKeyPerFile(o => o.FileProvider = testFileProvider) .Build(); Assert.Equal("SecretValue1", config["Secret1"]); Assert.Equal("SecretValue2", config["Secret2"]); } [Fact] public void CanLoadMultipleSecretsWithDirectory() { var testFileProvider = new TestFileProvider( new TestFile("Secret1", "SecretValue1"), new TestFile("Secret2", "SecretValue2"), new TestFile("directory")); var config = new ConfigurationBuilder() .AddKeyPerFile(o => o.FileProvider = testFileProvider) .Build(); Assert.Equal("SecretValue1", config["Secret1"]); Assert.Equal("SecretValue2", config["Secret2"]); } [Fact] public void CanLoadNestedKeys() { var testFileProvider = new TestFileProvider( new TestFile("Secret0__Secret1__Secret2__Key", "SecretValue2"), new TestFile("Secret0__Secret1__Key", "SecretValue1"), new TestFile("Secret0__Key", "SecretValue0")); var config = new ConfigurationBuilder() .AddKeyPerFile(o => o.FileProvider = testFileProvider) .Build(); Assert.Equal("SecretValue0", config["Secret0:Key"]); Assert.Equal("SecretValue1", config["Secret0:Secret1:Key"]); Assert.Equal("SecretValue2", config["Secret0:Secret1:Secret2:Key"]); } [Fact] public void CanIgnoreFilesWithDefault() { var testFileProvider = new TestFileProvider( new TestFile("ignore.Secret0", "SecretValue0"), new TestFile("ignore.Secret1", "SecretValue1"), new TestFile("Secret2", "SecretValue2")); var config = new ConfigurationBuilder() .AddKeyPerFile(o => o.FileProvider = testFileProvider) .Build(); Assert.Null(config["ignore.Secret0"]); Assert.Null(config["ignore.Secret1"]); Assert.Equal("SecretValue2", config["Secret2"]); } [Fact] public void CanTurnOffDefaultIgnorePrefixWithCondition() { var testFileProvider = new TestFileProvider( new TestFile("ignore.Secret0", "SecretValue0"), new TestFile("ignore.Secret1", "SecretValue1"), new TestFile("Secret2", "SecretValue2")); var config = new ConfigurationBuilder() .AddKeyPerFile(o => { o.FileProvider = testFileProvider; o.IgnoreCondition = null; }) .Build(); Assert.Equal("SecretValue0", config["ignore.Secret0"]); Assert.Equal("SecretValue1", config["ignore.Secret1"]); Assert.Equal("SecretValue2", config["Secret2"]); } [Fact] public void CanIgnoreAllWithCondition() { var testFileProvider = new TestFileProvider( new TestFile("Secret0", "SecretValue0"), new TestFile("Secret1", "SecretValue1"), new TestFile("Secret2", "SecretValue2")); var config = new ConfigurationBuilder() .AddKeyPerFile(o => { o.FileProvider = testFileProvider; o.IgnoreCondition = s => true; }) .Build(); Assert.Empty(config.AsEnumerable()); } [Fact] public void CanIgnoreFilesWithCustomIgnore() { var testFileProvider = new TestFileProvider( new TestFile("meSecret0", "SecretValue0"), new TestFile("meSecret1", "SecretValue1"), new TestFile("Secret2", "SecretValue2")); var config = new ConfigurationBuilder() .AddKeyPerFile(o => { o.FileProvider = testFileProvider; o.IgnorePrefix = "me"; }) .Build(); Assert.Null(config["meSecret0"]); Assert.Null(config["meSecret1"]); Assert.Equal("SecretValue2", config["Secret2"]); } [Fact] public void CanUnIgnoreDefaultFiles() { var testFileProvider = new TestFileProvider( new TestFile("ignore.Secret0", "SecretValue0"), new TestFile("ignore.Secret1", "SecretValue1"), new TestFile("Secret2", "SecretValue2")); var config = new ConfigurationBuilder() .AddKeyPerFile(o => { o.FileProvider = testFileProvider; o.IgnorePrefix = null; }) .Build(); Assert.Equal("SecretValue0", config["ignore.Secret0"]); Assert.Equal("SecretValue1", config["ignore.Secret1"]); Assert.Equal("SecretValue2", config["Secret2"]); } [Fact] public void BindingDoesNotThrowIfReloadedDuringBinding() { var testFileProvider = new TestFileProvider( new TestFile("Number", "-2"), new TestFile("Text", "Foo")); var config = new ConfigurationBuilder() .AddKeyPerFile(o => o.FileProvider = testFileProvider) .Build(); MyOptions options = null; using (var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(250))) { _ = Task.Run(() => { while (!cts.IsCancellationRequested) config.Reload(); }); while (!cts.IsCancellationRequested) { options = config.Get<MyOptions>(); } } Assert.Equal(-2, options.Number); Assert.Equal("Foo", options.Text); } private sealed class MyOptions { public int Number { get; set; } public string Text { get; set; } } } class TestFileProvider : IFileProvider { IDirectoryContents _contents; public TestFileProvider(params IFileInfo[] files) { _contents = new TestDirectoryContents(files); } public IDirectoryContents GetDirectoryContents(string subpath) { return _contents; } public IFileInfo GetFileInfo(string subpath) { throw new NotImplementedException(); } public IChangeToken Watch(string filter) { throw new NotImplementedException(); } } class TestDirectoryContents : IDirectoryContents { List<IFileInfo> _list; public TestDirectoryContents(params IFileInfo[] files) { _list = new List<IFileInfo>(files); } public bool Exists { get { return true; } } public IEnumerator<IFileInfo> GetEnumerator() { return _list.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } //TODO: Probably need a directory and file type. class TestFile : IFileInfo { private string _name; private string _contents; public bool Exists { get { return true; } } public bool IsDirectory { get; } public DateTimeOffset LastModified { get { throw new NotImplementedException(); } } public long Length { get { throw new NotImplementedException(); } } public string Name { get { return _name; } } public string PhysicalPath { get { throw new NotImplementedException(); } } public TestFile(string name) { _name = name; IsDirectory = true; } public TestFile(string name, string contents) { _name = name; _contents = contents; } public Stream CreateReadStream() { if(IsDirectory) { throw new InvalidOperationException("Cannot create stream from directory"); } return new MemoryStream(Encoding.UTF8.GetBytes(_contents)); } } }
29.436047
131
0.527355
[ "Apache-2.0" ]
uhaciogullari/HttpClientFactoryLite
src/Configuration/Config.KeyPerFile/test/KeyPerFileTests.cs
10,126
C#
using System; using System.Diagnostics; using System.Threading.Tasks; using Abp.Runtime.Validation; using Abp.UI; using Acr.UserDialogs; using Flurl.Http; using Roc.CMS.Extensions; using Roc.CMS.Localization.Resources; using Plugin.Connectivity; using Roc.CMS.Localization; namespace Roc.CMS.Core.Threading { public static class WebRequestExecuter { public static async Task Execute<TResult>( Func<Task<TResult>> func, Func<TResult, Task> successCallback, Func<System.Exception, Task> failCallback = null, Action finallyCallback = null) { if (successCallback == null) { successCallback = _ => Task.CompletedTask; } if (failCallback == null) { failCallback = _ => Task.CompletedTask; } try { if (!CrossConnectivity.Current.IsConnected) { UserDialogs.Instance.HideLoading(); var accepted = await UserDialogs.Instance.ConfirmAsync(LocalTranslation.NoInternet, LocalTranslation.MessageTitle, LocalTranslation.Ok, LocalTranslation.Cancel); if (accepted) { await Execute(func, successCallback, failCallback); } else { await failCallback(new System.Exception(LocalTranslation.NoInternet)); } } else { await successCallback(await func()); } } catch (System.Exception exception) { await HandleException(exception, func, successCallback, failCallback); } finally { finallyCallback?.Invoke(); } } public static async Task Execute( Func<Task> func, Func<Task> successCallback = null, Func<System.Exception, Task> failCallback = null, Action finallyCallback = null) { if (successCallback == null) { successCallback = () => Task.CompletedTask; } if (failCallback == null) { failCallback = _ => Task.CompletedTask; } try { if (!CrossConnectivity.Current.IsConnected) { UserDialogs.Instance.HideLoading(); var accepted = await UserDialogs.Instance.ConfirmAsync(LocalTranslation.NoInternet, LocalTranslation.MessageTitle, LocalTranslation.Ok, LocalTranslation.Cancel); if (accepted) { await Execute(func, successCallback, failCallback); } else { await failCallback(new System.Exception(LocalTranslation.NoInternet)); } } else { await func(); await successCallback(); } } catch (System.Exception ex) { await HandleException(ex, func, successCallback, failCallback); } finally { finallyCallback?.Invoke(); } } private static async Task HandleException<TResult>(System.Exception exception, Func<Task<TResult>> func, Func<TResult, Task> successCallback, Func<System.Exception, Task> failCallback) { UserDialogs.Instance.HideLoading(); switch (exception) { case UserFriendlyException userFriendlyException: await HandleUserFriendlyException(userFriendlyException, failCallback); break; case FlurlHttpTimeoutException httpTimeoutException: await HandleFlurlHttpTimeoutException(httpTimeoutException, func, successCallback, failCallback); break; case FlurlHttpException httpException: await HandleFlurlHttpException(httpException, func, successCallback, failCallback); break; case AbpValidationException abpValidationException: await HandleAbpValidationException(abpValidationException, failCallback); break; default: await HandleDefaultException(exception, func, successCallback, failCallback); break; } } private static async Task HandleException(System.Exception exception, Func<Task> func, Func<Task> successCallback, Func<System.Exception, Task> failCallback) { UserDialogs.Instance.HideLoading(); switch (exception) { case UserFriendlyException userFriendlyException: await HandleUserFriendlyException(userFriendlyException, failCallback); break; case FlurlHttpTimeoutException httpTimeoutException: await HandleFlurlHttpTimeoutException(httpTimeoutException, func, successCallback, failCallback); break; case FlurlHttpException httpException: await HandleFlurlHttpException(httpException, func, successCallback, failCallback); break; case AbpValidationException abpValidationException: await HandleAbpValidationException(abpValidationException, failCallback); break; default: await HandleDefaultException(exception, func, successCallback, failCallback); break; } } private static async Task HandleUserFriendlyException(UserFriendlyException userFriendlyException, Func<System.Exception, Task> failCallback) { if (string.IsNullOrEmpty(userFriendlyException.Details)) { UserDialogs.Instance.Alert(userFriendlyException.Message, L.Localize("Error")); } else { UserDialogs.Instance.Alert(userFriendlyException.Details, userFriendlyException.Message); } await failCallback(userFriendlyException); } private static async Task HandleFlurlHttpTimeoutException<TResult>( FlurlHttpTimeoutException httpTimeoutException, Func<Task<TResult>> func, Func<TResult, Task> successCallback, Func<System.Exception, Task> failCallback) { var accepted = await UserDialogs.Instance.ConfirmAsync(LocalTranslation.RequestTimedOut, LocalTranslation.MessageTitle, LocalTranslation.Ok, LocalTranslation.Cancel); if (accepted) { await Execute(func, successCallback, failCallback); } else { await failCallback(httpTimeoutException); } } private static async Task HandleFlurlHttpTimeoutException(FlurlHttpTimeoutException httpTimeoutException, Func<Task> func, Func<Task> successCallback, Func<System.Exception, Task> failCallback) { var accepted = await UserDialogs.Instance.ConfirmAsync(LocalTranslation.RequestTimedOut, LocalTranslation.MessageTitle, LocalTranslation.Ok, LocalTranslation.Cancel); if (accepted) { await Execute(func, successCallback, failCallback); } else { await failCallback(httpTimeoutException); } } private static async Task HandleFlurlHttpException(FlurlHttpException httpException, Func<Task> func, Func<Task> successCallback, Func<System.Exception, Task> failCallback) { if (await new AbpExceptionHandler().HandleIfAbpResponseAsync(httpException)) { await failCallback(httpException); return; } var httpExceptionMessage = LocalTranslation.HttpException; if (Debugger.IsAttached) { httpExceptionMessage += Environment.NewLine + httpException.Message; } var accepted = await UserDialogs.Instance.ConfirmAsync(httpExceptionMessage, LocalTranslation.MessageTitle, LocalTranslation.Ok, LocalTranslation.Cancel); if (accepted) { await Execute(func, successCallback, failCallback); } else { await failCallback(httpException); } } private static async Task HandleFlurlHttpException<TResult>(FlurlHttpException httpException, Func<Task<TResult>> func, Func<TResult, Task> successCallback, Func<System.Exception, Task> failCallback) { if (await new AbpExceptionHandler().HandleIfAbpResponseAsync(httpException)) { await failCallback(httpException); return; } var httpExceptionMessage = LocalTranslation.HttpException; if (Debugger.IsAttached) { httpExceptionMessage += Environment.NewLine + httpException.Message; } var accepted = await UserDialogs.Instance.ConfirmAsync(httpExceptionMessage, LocalTranslation.MessageTitle, LocalTranslation.Ok, LocalTranslation.Cancel); if (accepted) { await Execute(func, successCallback, failCallback); } else { await failCallback(httpException); } } private static async Task HandleAbpValidationException(AbpValidationException abpValidationException, Func<System.Exception, Task> failCallback) { await UserDialogs.Instance.AlertAsync(abpValidationException.GetConsolidatedMessage(), LocalTranslation.MessageTitle, LocalTranslation.Ok); await failCallback(abpValidationException); } private static async Task HandleDefaultException(System.Exception exception, Func<Task> func, Func<Task> successCallback, Func<System.Exception, Task> failCallback) { var accepted = await UserDialogs.Instance.ConfirmAsync(LocalTranslation.UnhandledWebRequestException, LocalTranslation.MessageTitle, LocalTranslation.Ok, LocalTranslation.Cancel); if (accepted) { await Execute(func, successCallback, failCallback); } else { await failCallback(exception); } } private static async Task HandleDefaultException<TResult>(System.Exception exception, Func<Task<TResult>> func, Func<TResult, Task> successCallback, Func<System.Exception, Task> failCallback) { var accepted = await UserDialogs.Instance.ConfirmAsync(LocalTranslation.UnhandledWebRequestException, LocalTranslation.MessageTitle, LocalTranslation.Ok, LocalTranslation.Cancel); if (accepted) { await Execute(func, successCallback, failCallback); } else { await failCallback(exception); } } } }
36.702454
117
0.561722
[ "MIT" ]
RocChing/Roc.CMS
src/Roc.CMS.Mobile.Shared/Core/Threading/WebRequestExecuter.cs
11,967
C#
using System; namespace Twitter.Models { public class PostViewModel { public int Id { get; set; } public string Content { get; set; } public DateTime CreatedTime { get; set; } public virtual string AuthorId { get; set; } public virtual ApplicationUser Author { get; set; } } }
25.384615
59
0.615152
[ "MIT" ]
tayanovskii/Course-M-ND2-31-18
Tayanovskii/src/Lab4/Lab4/Twitter/Twitter/Models/PostViewModel.cs
332
C#
using System.Collections; using System.Text.RegularExpressions; using UnityEngine; using WizardsCode.Tools.DocGen; namespace WizardsCode.Animation { [DocGen("Using Buildup it is possible to automatically create an animation of a game object buing built. " + "This is useful in games such as Tower Defense or an RTS game.\n\n" + "To use BuildUp add this component to the game object to build or to another game object and identify the object to be built in the `objectToBuild` field.\n\n" + "When the object is instantiated this script will turn off all renderers, other than those belonging to an object whose name matches a pattern in the `ObjectsToIgnoreInBuild`, and then run through the build cycle.\n\n" + "The build cycle consists of a number of build phases in which parts of the game object will be 'built'. " + "Define as many build phases as you would like in the `objectBuildPhases`, each phase will be executed in order. " + "During each phase any children mathcing the regular expression defining the phase will be built up. " + "Once all the defined phases have been completed any remaining inactive children, that are not excluded from the build using `objectsToIgnoreInBuild`, will be built.")] public class BuildUp : MonoBehaviour { [Tooltip("The parent game object to build. If null then it is assumed that this script is attached to the desired game object.")] [SerializeField] // TODO: provide a custom editor that allows us to clearly indicate that the selected object is this or an explicitly supplied object GameObject objectToBuild; [Tooltip("An ordered list of regular expressions that will match the names of child objects that should be built in each step.")] [SerializeField] // TODO: make this a sortable list in the inspector string[] objectBuildPhases; [Tooltip("A list of regular expressions that will match the names of child objects that should not be a part of the build phases. These items will not be marked as inactive/invisible at the start of the build cycle.")] [SerializeField] string[] objectsToIgnoreInBuild; enum axis { X, Y, Z } [Tooltip("The axis along which the object is to be built.")] [SerializeField] axis buildAxis = axis.Y; [Tooltip("The time in seconds that each phase of a build lasts. Each phase is defined by a single pattern in the `Object Build Order`.")] float phaseTime = 2f; bool isBuilt = false; bool isBuilding = false; int currentPhase = 0; private void Start() { if (objectToBuild == null) { objectToBuild = gameObject; } // turn off all children that do not have children of their own DeactivateBuildComponents(objectToBuild.transform); } private void DeactivateBuildComponents(Transform parent) { if (parent.childCount == 0) { parent.gameObject.SetActive(IsExcluded(parent)); } else { for (int i = 0; i < parent.childCount; i++) { DeactivateBuildComponents(parent.GetChild(i)); } } } private bool IsExcluded(Transform parent) { bool excluded = false; for (int i = 0; i < objectsToIgnoreInBuild.Length; i++) { if (Regex.IsMatch(parent.name, objectsToIgnoreInBuild[i])) { excluded = true; break; } } return excluded; } void Update() { if (!isBuilt && !isBuilding) { StartCoroutine(ExecuteBuildPhases()); } else { this.enabled = false; } } private IEnumerator ExecuteBuildPhases() { isBuilding = true; while (currentPhase < objectBuildPhases.Length) { // Get the first regular expression string re = objectBuildPhases[currentPhase]; // find all objects that match the regular expression and activate them BuildMatching(objectToBuild.transform, re); yield return new WaitForSeconds(phaseTime); currentPhase++; } BuildRemaining(objectToBuild.transform); isBuilding = false; isBuilt = true; } /// <summary> /// Build all the leaves on or below an object that have names matching a regulare expression. /// </summary> /// <param name="obj">The object to consider building. If this object is a parent and matches the RE then all children will be built. If it is a leaf then it will be built if the RE matches or if it is the child of a parent whose RE matches.</param> /// <param name="re">A regular expression to use in matching the name of the parent</param> /// <param name="forceBuild">Build even if the RE does not match?</param> private void BuildMatching(Transform obj, string re, bool forceBuild = false) { if (!obj.gameObject.activeSelf && (forceBuild || (obj.childCount == 0 && Regex.IsMatch(obj.name, re)))) { StartCoroutine(Build(obj, phaseTime)); } else { for (int i = 0; i < obj.childCount; i++) { BuildMatching(obj.GetChild(i), re, Regex.IsMatch(obj.name, re)); } } } /// <summary> /// Build all leaves and parents that are still inactive and are not in the exclude list. /// </summary> private void BuildRemaining(Transform parent) { if (parent.transform.childCount == 0 && !parent.gameObject.activeSelf && !IsExcluded(parent)) { StartCoroutine(Build(parent, phaseTime)); } else { for (int i = 0; i < parent.childCount; i++) { BuildRemaining(parent.GetChild(i)); } } } private IEnumerator Build(Transform obj, float duration) { Vector3 currentScale = obj.localScale; float min = 0; float max = 0; switch (buildAxis) { case axis.X: max = obj.localScale.x; currentScale.x = min; break; case axis.Y: max = obj.localScale.y; currentScale.y = min; break; case axis.Z: max = obj.localScale.z; currentScale.z = min; break; } obj.transform.localScale = currentScale; obj.gameObject.SetActive(true); int steps = 50; float pause = duration / steps; float inc = (max - min) / steps; for (int i = 0; i < steps; i++) { yield return new WaitForSeconds(pause); switch (buildAxis) { case axis.X: currentScale.x += inc; break; case axis.Y: currentScale.y += inc; break; case axis.Z: currentScale.z += inc; break; } obj.transform.localScale = currentScale; } switch (buildAxis) { case axis.X: currentScale.x = max; break; case axis.Y: currentScale.y = max; break; case axis.Z: currentScale.z = max; break; } obj.transform.localScale = currentScale; } } }
39.108491
257
0.534917
[ "Apache-2.0" ]
3dtbd/Common
Assets/OpenSourceCommon/Scripts/BuildUp.cs
8,293
C#
using System; using System.ComponentModel; using EfsTools.Attributes; using EfsTools.Utils; using Newtonsoft.Json; using EfsTools.Items.Data; namespace EfsTools.Items.Efs { [Serializable] [EfsFile("/nv/item_files/rfnv/00020961", true, 0xE1FF)] [Attributes(9)] public class C1Wcdma1800LnaRangeFall5Car1 { [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Value { get; set; } } }
22.181818
60
0.633197
[ "MIT" ]
HomerSp/EfsTools
EfsTools/Items/Efs/C1Wcdma1800LnaRangeFall5Car1I.cs
488
C#
using System.Collections.Generic; using BCrypt.Net; using Microsoft.EntityFrameworkCore; using BookMark.Domain.Models; namespace BookMark.OrmData.Databases { public class BookMarkDbContext : DbContext { private DbSet<User> Users { get; set; } private DbSet<Appointment> Appointments { get; set; } public BookMarkDbContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { // Setup Primary Keys builder.Entity<User>().HasKey(u => u.UserID); builder.Entity<User>().Property(u => u.UserID).ValueGeneratedNever(); builder.Entity<Appointment>().HasKey(a => a.AppointmentID); builder.Entity<Appointment>().Property(a => a.AppointmentID).ValueGeneratedNever(); builder.Entity<User>().HasMany(u => u.UserAppointments).WithOne(ua => ua.User).HasForeignKey(ua => ua.UserID); builder.Entity<Appointment>().HasMany(a => a.UserAppointments).WithOne(ua => ua.Appointment).HasForeignKey(ua => ua.AppointmentID); builder.Entity<UserAppointment>().HasKey(ua => ua.UserAppointmentID); builder.Entity<UserAppointment>().Property(ua => ua.UserAppointmentID).ValueGeneratedNever(); builder.Entity<UserAppointment>().HasOne(ua => ua.User).WithMany(u => u.UserAppointments).HasForeignKey(u => u.UserID); builder.Entity<UserAppointment>().HasOne(ua => ua.Appointment).WithMany(a => a.UserAppointments).HasForeignKey(a => a.AppointmentID); // Seed Data User[] users = new User[] { new User() { UserID = 1, Name = "synaodev", Password = BCrypt.Net.BCrypt.HashPassword("tylercadena") } }; builder.Entity<User>().HasData(users); } } }
50.96875
136
0.729614
[ "MIT" ]
bookmark-dev/bookmark
BookMark.OrmData/Databases/BookMarkDbContext.cs
1,631
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Diagnostics; using System.ServiceProcess; using System.Text; using SuperSocket.Common; using SuperSocket.SocketBase; using SuperSocket.SocketEngine; using SuperSocket.SocketEngine.Configuration; namespace SuperSocket.SocketService { partial class MainService : ServiceBase { public MainService() { InitializeComponent(); } protected override void OnStart(string[] args) { var serverConfig = ConfigurationManager.GetSection("socketServer") as SocketServiceConfig; if (!SocketServerManager.Initialize(serverConfig)) return; if (!SocketServerManager.Start()) SocketServerManager.Stop(); } protected override void OnStop() { SocketServerManager.Stop(); base.OnStop(); } protected override void OnShutdown() { SocketServerManager.Stop(); base.OnShutdown(); } } }
25.673913
103
0.616427
[ "BSD-3-Clause" ]
3rdandUrban-dev/Nuxleus
src/external/SuperSocket/v1.4/SocketService/MainService.cs
1,181
C#
/* * freee API * * <h1 id=\"freee_api\">freee API</h1> <hr /> <h2 id=\"\">スタートガイド</h2> <p>1. セットアップ</p> <ol> <ul><li><a href=\"https://support.freee.co.jp/hc/ja/articles/202847230\" class=\"external-link\" rel=\"nofollow\">freeeアカウント(無料)</a>を<a href=\"https://secure.freee.co.jp/users/sign_up\" class=\"external-link\" rel=\"nofollow\">作成</a>します(すでにお持ちの場合は次へ)</li><li><a href=\"https://app.secure.freee.co.jp/developers/demo_companies/description\" class=\"external-link\" rel=\"nofollow\">開発者向け事業所・環境を作成</a>します</li><li><span><a href=\"https://app.secure.freee.co.jp/developers/applications\" class=\"external-link\" rel=\"nofollow\">前のステップで作成した事業所を選択してfreeeアプリを追加</a>します</span></li><li>Client IDをCopyしておきます</li> </ul> </ol> <p>2. 実際にAPIを叩いてみる(ブラウザからAPIのレスポンスを確認する)</p> <ol> <ul><li><span><span>以下のURLの●をclient_idに入れ替えて<a href=\"https://app.secure.freee.co.jp/developers/tutorials/3-%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%E3%83%88%E3%83%BC%E3%82%AF%E3%83%B3%E3%82%92%E5%8F%96%E5%BE%97%E3%81%99%E3%82%8B#%E8%AA%8D%E5%8F%AF%E3%82%B3%E3%83%BC%E3%83%89%E3%82%92%E5%8F%96%E5%BE%97%E3%81%99%E3%82%8B\" class=\"external-link\" rel=\"nofollow\">アクセストークンを取得</a>します</span></span><ul><li><span><span><pre><code>https://accounts.secure.freee.co.jp/public_api/authorize?client_id=●&amp;redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&amp;response_type=token</a></code></pre></span></span></li></ul></li><li><span><a href=\"https://developer.freee.co.jp/docs/accounting/reference#/%E9%80%A3%E7%B5%A1%E5%85%88\" class=\"external-link\" rel=\"nofollow\">APIリファレンス</a>で<code>Authorize</code>を押下します</span></li><li><span>アクセストークン<span><span>を入力して</span></span>&nbsp;もう一度<span><code>Authorize</code>を押下して<code>Close</code>を押下します</span></span></li><li>リファレンス内のCompanies(事業所)に移動し、<code>Try it out</code>を押下し、<code>Execute</code>を押下します</li><li>Response bodyを参照し、事業所ID(id属性)を活用して、Companies以外のエンドポイントでどのようなデータのやりとりできるのか確認します</li></ul> </ol> <p>3. 連携を実装する</p> <ol> <ul><li><a href=\"https://developer.freee.co.jp/tips\" class=\"external-link\" rel=\"nofollow\">API TIPS</a>を参考に、ユースケースごとの連携の概要を学びます。<span>例えば</span><span>&nbsp;</span><a href=\"https://developer.freee.co.jp/tips/how-to-cooperate-salesmanegement-system\" class=\"external-link\" rel=\"nofollow\">SFA、CRM、販売管理システムから会計freeeへの連携</a>や<a href=\"https://developer.freee.co.jp/tips/how-to-cooperate-excel-and-spreadsheet\" class=\"external-link\" rel=\"nofollow\">エクセルやgoogle spreadsheetからの連携</a>です</li><li>実利用向け事業所がすでにある場合は利用、ない場合は作成します(セットアップで作成したのは開発者向け環境のため活用不可)</li><li><a href=\"https://developer.freee.co.jp/docs/accounting/reference\" class=\"external-link\" rel=\"nofollow\">API documentation</a><span>&nbsp;を参照し、躓いた場合は</span><span>&nbsp;</span><a href=\"https://developer.freee.co.jp/community/forum/community\" class=\"external-link\" rel=\"nofollow\">Community</a><span>&nbsp;で質問してみましょう</span></li></ul> </ol> <p>アプリケーションの登録方法や認証方法、またはAPIの活用方法でご不明な点がある場合は<a href=\"https://support.freee.co.jp/hc/ja/sections/115000030743\">ヘルプセンター</a>もご確認ください</p> <hr /> <h2 id=\"_2\">仕様</h2> <h3 id=\"api\">APIエンドポイント</h3> <p>https://api.freee.co.jp/ (httpsのみ)</p> <h3 id=\"_3\">認証方式</h3> <p><a href=\"http://tools.ietf.org/html/rfc6749\">OAuth2</a>に対応</p> <ul> <li>Authorization Code Flow (Webアプリ向け)</li> <li>Implicit Flow (Mobileアプリ向け)</li> </ul> <h3 id=\"_4\">認証エンドポイント</h3> <p>https://accounts.secure.freee.co.jp/</p> <ul> <li>authorize : https://accounts.secure.freee.co.jp/public_api/authorize</li> <li>token : https://accounts.secure.freee.co.jp/public_api/token</li> </ul> <h3 id=\"_5\">アクセストークンのリフレッシュ</h3> <p>認証時に得たrefresh_token を使ってtoken の期限をリフレッシュして新規に発行することが出来ます。</p> <p>grant_type=refresh_token で https://accounts.secure.freee.co.jp/public_api/token にアクセスすればリフレッシュされます。</p> <p>e.g.)</p> <p>POST: https://accounts.secure.freee.co.jp/public_api/token</p> <p>params: grant_type=refresh_token&amp;client_id=UID&amp;client_secret=SECRET&amp;refresh_token=REFRESH_TOKEN</p> <p>詳細は<a href=\"https://github.com/applicake/doorkeeper/wiki/Enable-Refresh-Token-Credentials#flow\">refresh_token</a>を参照下さい。</p> <h3 id=\"_6\">アクセストークンの破棄</h3> <p>認証時に得たaccess_tokenまたはrefresh_tokenを使って、tokenを破棄することができます。 token=access_tokenまたはtoken=refresh_tokenでhttps://accounts.secure.freee.co.jp/public_api/revokeにアクセスすると破棄されます。token_type_hintでaccess_tokenまたはrefresh_tokenを陽に指定できます。</p> <p>e.g.)</p> <p>POST: https://accounts.secure.freee.co.jp/public_api/revoke</p> <p>params: token=ACCESS_TOKEN</p> <p>または</p> <p>params: token=REFRESH_TOKEN</p> <p>または</p> <p>params: token=ACCESS_TOKEN&amp;token_type_hint=access_token</p> <p>または</p> <p>params: token=REFRESH_TOKEN&amp;token_type_hint=refresh_token</p> <p>詳細は <a href=\"https://tools.ietf.org/html/rfc7009\">OAuth 2.0 Token revocation</a> をご参照ください。</p> <h3 id=\"_7\">データフォーマット</h3> <p>リクエスト、レスポンスともにJSON形式をサポート</p> <h3 id=\"_8\">共通レスポンスヘッダー</h3> <p>すべてのAPIのレスポンスには以下のHTTPヘッダーが含まれます。</p> <ul> <li> <p>X-Freee-Request-ID</p> <ul> <li>各リクエスト毎に発行されるID</li> </ul> </li> </ul> <h3 id=\"_9\">共通エラーレスポンス</h3> <ul> <li> <p>ステータスコードはレスポンス内のJSONに含まれる他、HTTPヘッダにも含まれる</p> </li> <li> <p>type</p> <ul> <li>status : HTTPステータスコードの説明</li> <li>validation : エラーの詳細の説明(開発者向け)</li> </ul> </li> </ul> <p>レスポンスの例</p> <pre><code> { &quot;status_code&quot; : 400, &quot;errors&quot; : [ { &quot;type&quot; : &quot;status&quot;, &quot;messages&quot; : [&quot;不正なリクエストです。&quot;] }, { &quot;type&quot; : &quot;validation&quot;, &quot;messages&quot; : [&quot;Date は不正な日付フォーマットです。入力例:2013-01-01&quot;] } ] }</code></pre> <hr /> <h2 id=\"_10\">連絡先</h2> <p>ご不明点、ご要望等は <a href=\"https://support.freee.co.jp/hc/ja/requests/new\">freee サポートデスクへのお問い合わせフォーム</a> からご連絡ください。</p> <hr />&copy; Since 2013 freee K.K. * * The version of the OpenAPI document: v1.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using OpenAPIDateConverter = Freee.Accounting.Client.OpenAPIDateConverter; namespace Freee.Accounting.Models { /// <summary> /// UpdateCompanyParamsFiscalYearsAttributes /// </summary> [DataContract] public partial class UpdateCompanyParamsFiscalYearsAttributes : IEquatable<UpdateCompanyParamsFiscalYearsAttributes> { /// <summary> /// Initializes a new instance of the <see cref="UpdateCompanyParamsFiscalYearsAttributes" /> class. /// </summary> /// <param name="useIndustryTemplate">製造業向け機能(0: 使用しない、1: 使用する).</param> /// <param name="indirectWriteOffMethod">固定資産の控除法(0: 直接控除法、1: 間接控除法).</param> /// <param name="indirectWriteOffMethodType">間接控除時の累計額(0: 共通、1: 資産分類別).</param> /// <param name="startDate">期首日.</param> /// <param name="endDate">期末日(決算日).</param> /// <param name="accountingPeriod">期.</param> /// <param name="depreciationFraction">減価償却端数処理法(法人のみ)(0: 切り捨て、1: 切り上げ).</param> /// <param name="returnCode">不動産所得使用区分(個人事業主のみ)(0: 使用しない、3: 使用する).</param> /// <param name="taxFraction">消費税端数処理方法(0: 切り上げ、1: 切り捨て, 2: 四捨五入).</param> public UpdateCompanyParamsFiscalYearsAttributes(int useIndustryTemplate = default(int), int indirectWriteOffMethod = default(int), int indirectWriteOffMethodType = default(int), string startDate = default(string), string endDate = default(string), int accountingPeriod = default(int), int depreciationFraction = default(int), int returnCode = default(int), int taxFraction = default(int)) { this.UseIndustryTemplate = useIndustryTemplate; this.IndirectWriteOffMethod = indirectWriteOffMethod; this.IndirectWriteOffMethodType = indirectWriteOffMethodType; this.StartDate = startDate; this.EndDate = endDate; this.AccountingPeriod = accountingPeriod; this.DepreciationFraction = depreciationFraction; this.ReturnCode = returnCode; this.TaxFraction = taxFraction; } /// <summary> /// 製造業向け機能(0: 使用しない、1: 使用する) /// </summary> /// <value>製造業向け機能(0: 使用しない、1: 使用する)</value> [DataMember(Name="use_industry_template", EmitDefaultValue=false)] public int UseIndustryTemplate { get; set; } /// <summary> /// 固定資産の控除法(0: 直接控除法、1: 間接控除法) /// </summary> /// <value>固定資産の控除法(0: 直接控除法、1: 間接控除法)</value> [DataMember(Name="indirect_write_off_method", EmitDefaultValue=false)] public int IndirectWriteOffMethod { get; set; } /// <summary> /// 間接控除時の累計額(0: 共通、1: 資産分類別) /// </summary> /// <value>間接控除時の累計額(0: 共通、1: 資産分類別)</value> [DataMember(Name="indirect_write_off_method_type", EmitDefaultValue=false)] public int IndirectWriteOffMethodType { get; set; } /// <summary> /// 期首日 /// </summary> /// <value>期首日</value> [DataMember(Name="start_date", EmitDefaultValue=false)] public string StartDate { get; set; } /// <summary> /// 期末日(決算日) /// </summary> /// <value>期末日(決算日)</value> [DataMember(Name="end_date", EmitDefaultValue=false)] public string EndDate { get; set; } /// <summary> /// 期 /// </summary> /// <value>期</value> [DataMember(Name="accounting_period", EmitDefaultValue=false)] public int AccountingPeriod { get; set; } /// <summary> /// 減価償却端数処理法(法人のみ)(0: 切り捨て、1: 切り上げ) /// </summary> /// <value>減価償却端数処理法(法人のみ)(0: 切り捨て、1: 切り上げ)</value> [DataMember(Name="depreciation_fraction", EmitDefaultValue=false)] public int DepreciationFraction { get; set; } /// <summary> /// 不動産所得使用区分(個人事業主のみ)(0: 使用しない、3: 使用する) /// </summary> /// <value>不動産所得使用区分(個人事業主のみ)(0: 使用しない、3: 使用する)</value> [DataMember(Name="return_code", EmitDefaultValue=false)] public int ReturnCode { get; set; } /// <summary> /// 消費税端数処理方法(0: 切り上げ、1: 切り捨て, 2: 四捨五入) /// </summary> /// <value>消費税端数処理方法(0: 切り上げ、1: 切り捨て, 2: 四捨五入)</value> [DataMember(Name="tax_fraction", EmitDefaultValue=false)] public int TaxFraction { 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 UpdateCompanyParamsFiscalYearsAttributes {\n"); sb.Append(" UseIndustryTemplate: ").Append(UseIndustryTemplate).Append("\n"); sb.Append(" IndirectWriteOffMethod: ").Append(IndirectWriteOffMethod).Append("\n"); sb.Append(" IndirectWriteOffMethodType: ").Append(IndirectWriteOffMethodType).Append("\n"); sb.Append(" StartDate: ").Append(StartDate).Append("\n"); sb.Append(" EndDate: ").Append(EndDate).Append("\n"); sb.Append(" AccountingPeriod: ").Append(AccountingPeriod).Append("\n"); sb.Append(" DepreciationFraction: ").Append(DepreciationFraction).Append("\n"); sb.Append(" ReturnCode: ").Append(ReturnCode).Append("\n"); sb.Append(" TaxFraction: ").Append(TaxFraction).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return 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 UpdateCompanyParamsFiscalYearsAttributes); } /// <summary> /// Returns true if UpdateCompanyParamsFiscalYearsAttributes instances are equal /// </summary> /// <param name="input">Instance of UpdateCompanyParamsFiscalYearsAttributes to be compared</param> /// <returns>Boolean</returns> public bool Equals(UpdateCompanyParamsFiscalYearsAttributes input) { if (input == null) return false; return ( this.UseIndustryTemplate == input.UseIndustryTemplate || this.UseIndustryTemplate.Equals(input.UseIndustryTemplate) ) && ( this.IndirectWriteOffMethod == input.IndirectWriteOffMethod || this.IndirectWriteOffMethod.Equals(input.IndirectWriteOffMethod) ) && ( this.IndirectWriteOffMethodType == input.IndirectWriteOffMethodType || this.IndirectWriteOffMethodType.Equals(input.IndirectWriteOffMethodType) ) && ( this.StartDate == input.StartDate || (this.StartDate != null && this.StartDate.Equals(input.StartDate)) ) && ( this.EndDate == input.EndDate || (this.EndDate != null && this.EndDate.Equals(input.EndDate)) ) && ( this.AccountingPeriod == input.AccountingPeriod || this.AccountingPeriod.Equals(input.AccountingPeriod) ) && ( this.DepreciationFraction == input.DepreciationFraction || this.DepreciationFraction.Equals(input.DepreciationFraction) ) && ( this.ReturnCode == input.ReturnCode || this.ReturnCode.Equals(input.ReturnCode) ) && ( this.TaxFraction == input.TaxFraction || this.TaxFraction.Equals(input.TaxFraction) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; hashCode = hashCode * 59 + this.UseIndustryTemplate.GetHashCode(); hashCode = hashCode * 59 + this.IndirectWriteOffMethod.GetHashCode(); hashCode = hashCode * 59 + this.IndirectWriteOffMethodType.GetHashCode(); if (this.StartDate != null) hashCode = hashCode * 59 + this.StartDate.GetHashCode(); if (this.EndDate != null) hashCode = hashCode * 59 + this.EndDate.GetHashCode(); hashCode = hashCode * 59 + this.AccountingPeriod.GetHashCode(); hashCode = hashCode * 59 + this.DepreciationFraction.GetHashCode(); hashCode = hashCode * 59 + this.ReturnCode.GetHashCode(); hashCode = hashCode * 59 + this.TaxFraction.GetHashCode(); return hashCode; } } } }
65.615063
5,736
0.624665
[ "MIT" ]
s-taira/freee-accounting-sdk-csharp
src/Freee.Accounting/Models/UpdateCompanyParamsFiscalYearsAttributes.cs
18,368
C#
using System; using System.Collections.Generic; using System.Linq; using WixSharp; namespace NineDigit.WixSharpExtensions { public static class CustomActionManagedProjectExtensions { /// <summary> /// Binds custom action to the <paramref name="project"/>. /// </summary> /// <typeparam name="TCustomAction"></typeparam> /// <param name="project"></param> /// <returns></returns> public static ManagedProject BindCustomAction<TCustomAction>(this ManagedProject project) where TCustomAction : CustomAction, new() => BindCustomAction(project, new TCustomAction()); /// <summary> /// Binds <paramref name="customAction"/> to the <paramref name="project"/>. /// </summary> /// <param name="project"></param> /// <param name="customAction"></param> /// <returns></returns> public static ManagedProject BindCustomAction(this ManagedProject project, CustomAction customAction) { if (project is null) throw new ArgumentNullException(nameof(project)); if (customAction is null) throw new ArgumentNullException(nameof(customAction)); customAction.BindTo(project); project.EmbedWixSharpExtensions(); return project; } /// <summary> /// Packages WixSharpExtensions assembly into MSI setup. This is required when using <see cref="CustomAction"/> classes. /// </summary> /// <param name="project"></param> /// <returns></returns> public static ManagedProject EmbedWixSharpExtensions(this ManagedProject project) { if (project is null) throw new ArgumentNullException(nameof(project)); var wixSharpLocation = typeof(CustomActionManagedProjectExtensions).Assembly.Location; return project.EmbedAssembly(wixSharpLocation); } /// <summary> /// Packages assembly specified by <paramref name="assemblyPath"/> into MSI setup. /// This is useful when external functionality is stored outside main setup project. /// </summary> /// <param name="project"></param> /// <param name="assemblyPath"></param> /// <returns></returns> public static ManagedProject EmbedAssembly(this ManagedProject project, string assemblyPath) { if (project is null) throw new ArgumentNullException(nameof(project)); if (string.IsNullOrWhiteSpace(assemblyPath)) throw new ArgumentException("Invalid assembly path.", nameof(assemblyPath)); if (project.DefaultRefAssemblies is null) project.DefaultRefAssemblies = new List<string>(); if (!project.DefaultRefAssemblies.Any(i => i.Equals(assemblyPath, StringComparison.InvariantCultureIgnoreCase))) project.DefaultRefAssemblies.Add(assemblyPath); return project; } } }
37.753086
128
0.623937
[ "MIT" ]
ninedigit/wixsharpextensions
NineDigit.WixSharpExtensions/CustomActions/CustomActionManagedProjectExtensions.cs
3,060
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.WebSockets; using System.Text; using BassUtils; using Lithogen.Engine; using Unosquare.Labs.EmbedIO.Modules; namespace Lithogen { public sealed class LiveReloadServer : WebSocketsServer, IDisposable { public string Directory { get; private set; } readonly DirectoryWatcher Watcher; readonly object WatcherPadlock; bool Disposed; public LiveReloadServer() : base(true, 0) { Directory = Program.TheSettings.LithogenWebsiteDirectory; Watcher = new DirectoryWatcher(Directory); WatcherPadlock = new object(); Watcher.ChangedFiles += Watcher_ChangedFiles; } //public LiveReloadServer(string directory, WebSocket webSocket) //{ // Directory = directory.ThrowIfDirectoryDoesNotExist("directory"); // WebSocket = webSocket.ThrowIfNull("webSocket"); // Watcher = new DirectoryWatcher(Directory); // WatcherPadlock = new object(); // Watcher.ChangedFiles += Watcher_ChangedFiles; //} /// <summary> /// Starts the server. It begins watching the <code>Directory</code> /// and will respond to websocket requests from the LiveReload client. /// </summary> //public void Start() //{ // Watcher.Start(); // EmitHelloMessage(); //} /// <summary> /// Returns the JSON that must be sent to the client during the handshake process. /// </summary> /// <returns></returns> public static string HelloJson { get { return @"{ ""command"": ""hello"", ""protocols"": [""http://livereload.com/protocols/official-7""], ""serverName"": ""LithogenLiveReloadServer"" }"; } } public IEnumerable<string> GetReloadJson(IEnumerable<string> files) { files.ThrowIfNull("files"); foreach (string file in files) yield return GetReloadJson(file); } public string GetReloadJson(string file) { file.ThrowIfNullOrWhiteSpace("file"); if (file.StartsWith(Directory)) file = file.Substring(Directory.Length + 1); file = file.Replace('\\', '/'); string template = @"{ ""command"": ""reload"", ""path"": ""THEPATH"", ""liveCSS"": ""true"" }"; return template.Replace("THEPATH", file); } public new void Dispose() { if (!Disposed) { Watcher.Dispose(); base.Dispose(); Disposed = true; } } void Watcher_ChangedFiles(object sender, DirectoryWatcherEventArgs e) { lock (WatcherPadlock) { // Alas, we get events for directories (which we don't care about). var filtered = (from n in e.FileSystemEvents where File.Exists(n.FullPath) select n.FullPath ).Distinct(); if (filtered.Any()) { foreach (var file in filtered) EmitReloadMessage(file); } } } void EmitHelloMessage() { //var buffer = System.Text.Encoding.UTF8.GetBytes(HelloJson); Send(this.WebSockets[0], HelloJson); //await WebSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None); } void EmitReloadMessage(string file) { Console.WriteLine("Sending reload message for {0}", file); string json = GetReloadJson(file); Send(this.WebSockets[0], json); //var buffer = System.Text.Encoding.UTF8.GetBytes(json); //await WebSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None); } #region EmbedIO support /// <summary> /// Called when this WebSockets Server receives a full message (EndOfMessage) form a WebSockets client. /// </summary> /// <param name="context">The context.</param> /// <param name="rxBuffer">The rx buffer.</param> /// <param name="rxResult">The rx result.</param> protected override void OnMessageReceived(WebSocketContext context, byte[] rxBuffer, WebSocketReceiveResult rxResult) { var msg = Encoding.UTF8.GetString(rxBuffer); Console.WriteLine("WS OnMessageReceived: " + msg); } public override string ServerName { get { return "Lithogen LiveReload Server"; } } /// <summary> /// Called when this WebSockets Server accepts a new WebSockets client. /// </summary> /// <param name="context">The context.</param> protected override void OnClientConnected(WebSocketContext context) { Console.WriteLine("WS: OnClientConnected"); EmitHelloMessage(); Console.WriteLine("WS: OnClientConnected - hello sent, starting watcher."); Watcher.Start(); } /// <summary> /// Called when this WebSockets Server receives a message frame regardless if the frame represents the EndOfMessage. /// </summary> /// <param name="context">The context.</param> /// <param name="rxBuffer">The rx buffer.</param> /// <param name="rxResult">The rx result.</param> protected override void OnFrameReceived(WebSocketContext context, byte[] rxBuffer, WebSocketReceiveResult rxResult) { return; } /// <summary> /// Called when the server has removed a WebSockets connected client for any reason. /// </summary> /// <param name="context">The context.</param> protected override void OnClientDisconnected(WebSocketContext context) { Console.WriteLine("WS: OnClientDisconnected"); } #endregion } }
34.152632
130
0.551703
[ "MIT" ]
PhilipDaniels/Lithogen
Lithogen/Lithogen/LiveReloadServer.cs
6,491
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Drawing; using System.Drawing.Design; using System.Reflection; using System.Windows.Forms.Design.Behavior; using Microsoft.Win32; namespace System.Windows.Forms.Design { internal sealed class ToolStripDesignerUtils { private static readonly Type s_toolStripItemType = typeof(ToolStripItem); [ThreadStatic] private static Dictionary<Type, ToolboxItem> s_cachedToolboxItems; [ThreadStatic] private static int s_customToolStripItemCount = 0; private const int TOOLSTRIPCHARCOUNT = 9; // used to cache in the selection. This is used when the selection is changing and we need to invalidate the original selection Especially, when the selection is changed through NON UI designer action like through propertyGrid or through Doc Outline. public static ArrayList originalSelComps; [ThreadStatic] private static Dictionary<Type, Bitmap> s_cachedWinformsImages; private static readonly string s_systemWindowsFormsNamespace = typeof(ToolStripItem).Namespace; private ToolStripDesignerUtils() { } #region NewItemTypeLists // This section controls the ordering of standard item types in all the various pieces of toolstrip designer UI. // ToolStrip - Default item is determined by being first in the list private static readonly Type[] s_newItemTypesForToolStrip = new Type[] { typeof(ToolStripButton), typeof(ToolStripLabel), typeof(ToolStripSplitButton), typeof(ToolStripDropDownButton), typeof(ToolStripSeparator), typeof(ToolStripComboBox), typeof(ToolStripTextBox), typeof(ToolStripProgressBar) }; // StatusStrip - Default item is determined by being first in the list private static readonly Type[] s_newItemTypesForStatusStrip = new Type[] { typeof(ToolStripStatusLabel), typeof(ToolStripProgressBar), typeof(ToolStripDropDownButton), typeof(ToolStripSplitButton) }; // MenuStrip - Default item is determined by being first in the list private static readonly Type[] s_newItemTypesForMenuStrip = new Type[] { typeof(ToolStripMenuItem), typeof(ToolStripComboBox), typeof(ToolStripTextBox) }; // ToolStripDropDown - roughly same as menu strip. private static readonly Type[] s_newItemTypesForToolStripDropDownMenu = new Type[] { typeof(ToolStripMenuItem), typeof(ToolStripComboBox), typeof(ToolStripSeparator), typeof(ToolStripTextBox) }; #endregion // Get the Correct bounds for painting... public static void GetAdjustedBounds(ToolStripItem item, ref Rectangle r) { // adjust bounds as per item if (!(item is ToolStripControlHost && item.IsOnDropDown)) { //Deflate the SelectionGlyph for the MenuItems... if (item is ToolStripMenuItem && item.IsOnDropDown) { r.Inflate(-3, -2); r.Width++; } else if (item is ToolStripControlHost && !item.IsOnDropDown) { r.Inflate(0, -2); } else if (item is ToolStripMenuItem && !item.IsOnDropDown) { r.Inflate(-3, -3); } else { r.Inflate(-1, -1); } } } /// <summary> /// If IComponent is ToolStrip return ToolStrip /// If IComponent is ToolStripItem return the Owner ToolStrip /// If IComponent is ToolStripDropDownItem return the child DropDown ToolStrip /// </summary> private static ToolStrip GetToolStripFromComponent(IComponent component) { ToolStrip parent; if (component is ToolStripItem stripItem) { if (!(stripItem is ToolStripDropDownItem)) { parent = stripItem.Owner; } else { parent = ((ToolStripDropDownItem)stripItem).DropDown; } } else { parent = component as ToolStrip; } return parent; } private static ToolboxItem GetCachedToolboxItem(Type itemType) { ToolboxItem tbxItem = null; if (s_cachedToolboxItems is null) { s_cachedToolboxItems = new Dictionary<Type, ToolboxItem>(); } else if (s_cachedToolboxItems.ContainsKey(itemType)) { tbxItem = s_cachedToolboxItems[itemType]; return tbxItem; } // no cache hit - load the item. if (tbxItem is null) { // create a toolbox item to match tbxItem = new ToolboxItem(itemType); } s_cachedToolboxItems[itemType] = tbxItem; if (s_customToolStripItemCount > 0 && (s_customToolStripItemCount * 2 < s_cachedToolboxItems.Count)) { // time to clear the toolbox item cache - we've got twice the number of toolbox items than actual custom item types. s_cachedToolboxItems.Clear(); } return tbxItem; } // only call this for well known items. private static Bitmap GetKnownToolboxBitmap(Type itemType) { if (s_cachedWinformsImages is null) { s_cachedWinformsImages = new Dictionary<Type, Bitmap>(); } if (!s_cachedWinformsImages.ContainsKey(itemType)) { Bitmap knownImage = ToolboxBitmapAttribute.GetImageFromResource(itemType, null, false) as Bitmap; s_cachedWinformsImages[itemType] = knownImage; return knownImage; } return s_cachedWinformsImages[itemType]; } public static Bitmap GetToolboxBitmap(Type itemType) { // if and only if the namespace of the type is System.Windows.Forms. try to pull the image out of the manifest. if (itemType.Namespace == s_systemWindowsFormsNamespace) { return GetKnownToolboxBitmap(itemType); } // check to see if we've got a toolbox item, and use it. ToolboxItem tbxItem = GetCachedToolboxItem(itemType); if (tbxItem != null) { return tbxItem.Bitmap; } // if all else fails, throw up a default image. return GetKnownToolboxBitmap(typeof(Component)); } /// <summary> /// Fishes out the display name attribute from the Toolbox item if not present, uses Type.Name /// </summary> public static string GetToolboxDescription(Type itemType) { string currentName = null; ToolboxItem tbxItem = GetCachedToolboxItem(itemType); if (tbxItem != null) { currentName = tbxItem.DisplayName; } if (currentName is null) { currentName = itemType.Name; } if (currentName.StartsWith("ToolStrip")) { return currentName.Substring(TOOLSTRIPCHARCOUNT); } return currentName; } /// <summary> /// The first item returned should be the DefaultItem to create on the ToolStrip /// </summary> public static Type[] GetStandardItemTypes(IComponent component) { ToolStrip toolStrip = GetToolStripFromComponent(component); if (toolStrip is MenuStrip) { return s_newItemTypesForMenuStrip; } else if (toolStrip is ToolStripDropDownMenu) { // ToolStripDropDown gets default items. return s_newItemTypesForToolStripDropDownMenu; } else if (toolStrip is StatusStrip) { return s_newItemTypesForStatusStrip; } Debug.Assert(toolStrip != null, "why werent we handed a toolstrip here? returning default list"); return s_newItemTypesForToolStrip; } private static ToolStripItemDesignerAvailability GetDesignerVisibility(ToolStrip toolStrip) { ToolStripItemDesignerAvailability visiblity; if (toolStrip is StatusStrip) { visiblity = ToolStripItemDesignerAvailability.StatusStrip; } else if (toolStrip is MenuStrip) { visiblity = ToolStripItemDesignerAvailability.MenuStrip; } else if (toolStrip is ToolStripDropDownMenu) { visiblity = ToolStripItemDesignerAvailability.ContextMenuStrip; } else { visiblity = ToolStripItemDesignerAvailability.ToolStrip; } return visiblity; } public static Type[] GetCustomItemTypes(IComponent component, IServiceProvider serviceProvider) { ITypeDiscoveryService discoveryService = null; if (serviceProvider != null) { discoveryService = serviceProvider.GetService(typeof(ITypeDiscoveryService)) as ITypeDiscoveryService; } return GetCustomItemTypes(component, discoveryService); } public static Type[] GetCustomItemTypes(IComponent component, ITypeDiscoveryService discoveryService) { if (discoveryService != null) { // fish out all types which derive from toolstrip item ICollection itemTypes = discoveryService.GetTypes(s_toolStripItemType, false /*excludeGlobalTypes*/); ToolStrip toolStrip = GetToolStripFromComponent(component); // determine the value of the visibility attribute which matches the current toolstrip type. ToolStripItemDesignerAvailability currentToolStripVisibility = GetDesignerVisibility(toolStrip); Debug.Assert(currentToolStripVisibility != ToolStripItemDesignerAvailability.None, "Why is GetDesignerVisibility returning None?"); // fish out the ones we've already listed. Type[] stockItemTypeList = GetStandardItemTypes(component); if (currentToolStripVisibility != ToolStripItemDesignerAvailability.None) { ArrayList createableTypes = new ArrayList(itemTypes.Count); foreach (Type t in itemTypes) { if (t.IsAbstract) { continue; } if (!t.IsPublic && !t.IsNestedPublic) { continue; } if (t.ContainsGenericParameters) { continue; } // Check if we have public constructor... ConstructorInfo ctor = t.GetConstructor(Array.Empty<Type>()); if (ctor is null) { continue; } // if the visibility matches the current toolstrip type, add it to the list of possible types to create. ToolStripItemDesignerAvailabilityAttribute visiblityAttribute = (ToolStripItemDesignerAvailabilityAttribute)TypeDescriptor.GetAttributes(t)[typeof(ToolStripItemDesignerAvailabilityAttribute)]; if (visiblityAttribute != null && ((visiblityAttribute.ItemAdditionVisibility & currentToolStripVisibility) == currentToolStripVisibility)) { bool isStockType = false; // PERF: consider a dictionary - but this list will usually be 3-7 items. foreach (Type stockType in stockItemTypeList) { if (stockType == t) { isStockType = true; break; } } if (!isStockType) { createableTypes.Add(t); } } } if (createableTypes.Count > 0) { Type[] createableTypesArray = new Type[createableTypes.Count]; createableTypes.CopyTo(createableTypesArray, 0); s_customToolStripItemCount = createableTypes.Count; return createableTypesArray; } } } s_customToolStripItemCount = 0; return Array.Empty<Type>(); } /// <summary> /// wraps the result of GetStandardItemTypes in ItemTypeToolStripMenuItems. /// </summary> public static ToolStripItem[] GetStandardItemMenuItems(IComponent component, EventHandler onClick, bool convertTo) { Type[] standardTypes = GetStandardItemTypes(component); ToolStripItem[] items = new ToolStripItem[standardTypes.Length]; for (int i = 0; i < standardTypes.Length; i++) { ItemTypeToolStripMenuItem item = new ItemTypeToolStripMenuItem(standardTypes[i]) { ConvertTo = convertTo }; if (onClick != null) { item.Click += onClick; } items[i] = item; } return items; } /// <summary> /// wraps the result of GetCustomItemTypes in ItemTypeToolStripMenuItems. /// </summary> public static ToolStripItem[] GetCustomItemMenuItems(IComponent component, EventHandler onClick, bool convertTo, IServiceProvider serviceProvider) { Type[] customTypes = GetCustomItemTypes(component, serviceProvider); ToolStripItem[] items = new ToolStripItem[customTypes.Length]; for (int i = 0; i < customTypes.Length; i++) { ItemTypeToolStripMenuItem item = new ItemTypeToolStripMenuItem(customTypes[i]) { ConvertTo = convertTo }; if (onClick != null) { item.Click += onClick; } items[i] = item; } return items; } /// <summary> /// build up a list of standard items separated by the custom items /// </summary> public static NewItemsContextMenuStrip GetNewItemDropDown(IComponent component, ToolStripItem currentItem, EventHandler onClick, bool convertTo, IServiceProvider serviceProvider, bool populateCustom) { NewItemsContextMenuStrip contextMenu = new NewItemsContextMenuStrip(component, currentItem, onClick, convertTo, serviceProvider); contextMenu.GroupOrdering.Add("StandardList"); contextMenu.GroupOrdering.Add("CustomList"); // plumb through the standard and custom items. foreach (ToolStripItem item in GetStandardItemMenuItems(component, onClick, convertTo)) { contextMenu.Groups["StandardList"].Items.Add(item); if (convertTo) { if (item is ItemTypeToolStripMenuItem toolItem && currentItem != null && toolItem.ItemType == currentItem.GetType()) { toolItem.Enabled = false; } } } if (populateCustom) { GetCustomNewItemDropDown(contextMenu, component, currentItem, onClick, convertTo, serviceProvider); } if (serviceProvider.GetService(typeof(IUIService)) is IUIService uis) { contextMenu.Renderer = (ToolStripProfessionalRenderer)uis.Styles["VsRenderer"]; contextMenu.Font = (Font)uis.Styles["DialogFont"]; if (uis.Styles["VsColorPanelText"] is Color) { contextMenu.ForeColor = (Color)uis.Styles["VsColorPanelText"]; } } contextMenu.Populate(); return contextMenu; } public static void GetCustomNewItemDropDown(NewItemsContextMenuStrip contextMenu, IComponent component, ToolStripItem currentItem, EventHandler onClick, bool convertTo, IServiceProvider serviceProvider) { foreach (ToolStripItem item in GetCustomItemMenuItems(component, onClick, convertTo, serviceProvider)) { contextMenu.Groups["CustomList"].Items.Add(item); if (convertTo) { if (item is ItemTypeToolStripMenuItem toolItem && currentItem != null && toolItem.ItemType == currentItem.GetType()) { toolItem.Enabled = false; } } } contextMenu.Populate(); } public static void InvalidateSelection(ArrayList originalSelComps, ToolStripItem nextSelection, IServiceProvider provider, bool shiftPressed) { // if we are not selecting a ToolStripItem then return (dont invalidate). if (nextSelection is null || provider is null) { return; } //InvalidateOriginal SelectedComponents. Region invalidateRegion = null; Region itemRegion = null; int GLYPHBORDER = 1; int GLYPHINSET = 2; ToolStripItemDesigner designer = null; bool templateNodeSelected = false; try { Rectangle invalidateBounds = Rectangle.Empty; IDesignerHost designerHost = (IDesignerHost)provider.GetService(typeof(IDesignerHost)); if (designerHost != null) { foreach (Component comp in originalSelComps) { if (comp is ToolStripItem selItem) { if ((originalSelComps.Count > 1) || (originalSelComps.Count == 1 && selItem.GetCurrentParent() != nextSelection.GetCurrentParent()) || selItem is ToolStripSeparator || selItem is ToolStripControlHost || !selItem.IsOnDropDown || selItem.IsOnOverflow) { // finally Invalidate the selection rect ... designer = designerHost.GetDesigner(selItem) as ToolStripItemDesigner; if (designer != null) { invalidateBounds = designer.GetGlyphBounds(); GetAdjustedBounds(selItem, ref invalidateBounds); invalidateBounds.Inflate(GLYPHBORDER, GLYPHBORDER); if (invalidateRegion is null) { invalidateRegion = new Region(invalidateBounds); invalidateBounds.Inflate(-GLYPHINSET, -GLYPHINSET); invalidateRegion.Exclude(invalidateBounds); } else { itemRegion = new Region(invalidateBounds); invalidateBounds.Inflate(-GLYPHINSET, -GLYPHINSET); itemRegion.Exclude(invalidateBounds); invalidateRegion.Union(itemRegion); } } } } } } if (invalidateRegion != null || templateNodeSelected || shiftPressed) { BehaviorService behaviorService = (BehaviorService)provider.GetService(typeof(BehaviorService)); if (behaviorService != null) { if (invalidateRegion != null) { behaviorService.Invalidate(invalidateRegion); } // When a ToolStripItem is PrimarySelection, the glyph bounds are not invalidated through the SelectionManager so we have to do this. designer = designerHost.GetDesigner(nextSelection) as ToolStripItemDesigner; if (designer != null) { invalidateBounds = designer.GetGlyphBounds(); GetAdjustedBounds(nextSelection, ref invalidateBounds); invalidateBounds.Inflate(GLYPHBORDER, GLYPHBORDER); invalidateRegion = new Region(invalidateBounds); invalidateBounds.Inflate(-GLYPHINSET, -GLYPHINSET); invalidateRegion.Exclude(invalidateBounds); behaviorService.Invalidate(invalidateRegion); } } } } finally { if (invalidateRegion != null) { invalidateRegion.Dispose(); } if (itemRegion != null) { itemRegion.Dispose(); } } } /// <summary> represents cached information about the display</summary> internal static class DisplayInformation { private static bool s_highContrast; //whether we are under hight contrast mode private static bool s_lowRes; //whether we are under low resolution mode private static bool s_isTerminalServerSession; //whether this application is run on a terminal server (remote desktop) private static bool s_highContrastSettingValid; //indicates whether the high contrast setting is correct private static bool s_lowResSettingValid; //indicates whether the low resolution setting is correct private static bool s_terminalSettingValid; //indicates whether the terminal server setting is correct private static short s_bitsPerPixel; private static bool s_dropShadowSettingValid; private static bool s_dropShadowEnabled; static DisplayInformation() { SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(UserPreferenceChanged); SystemEvents.DisplaySettingsChanged += new EventHandler(DisplaySettingChanged); } public static short BitsPerPixel { get { if (s_bitsPerPixel == 0) { foreach (Screen s in Screen.AllScreens) { if (s_bitsPerPixel == 0) { s_bitsPerPixel = (short)s.BitsPerPixel; } else { s_bitsPerPixel = (short)Math.Min(s.BitsPerPixel, s_bitsPerPixel); } } } return s_bitsPerPixel; } } /// <summary> /// Tests to see if the monitor is in low resolution mode (8-bit color depth or less). /// </summary> public static bool LowResolution { get { if (s_lowResSettingValid) { return s_lowRes; } s_lowRes = BitsPerPixel <= 8; s_lowResSettingValid = true; return s_lowRes; } } /// <summary> /// Tests to see if we are under high contrast mode /// </summary> public static bool HighContrast { get { if (s_highContrastSettingValid) { return s_highContrast; } s_highContrast = SystemInformation.HighContrast; s_highContrastSettingValid = true; return s_highContrast; } } public static bool IsDropShadowEnabled { get { if (s_dropShadowSettingValid) { return s_dropShadowEnabled; } s_dropShadowEnabled = SystemInformation.IsDropShadowEnabled; s_dropShadowSettingValid = true; return s_dropShadowEnabled; } } /// <summary> ///test to see if we are under terminal server mode /// </summary> public static bool TerminalServer { get { if (s_terminalSettingValid) { return s_isTerminalServerSession; } s_isTerminalServerSession = SystemInformation.TerminalServerSession; s_terminalSettingValid = true; return s_isTerminalServerSession; } } /// <summary> ///event handler for change in display setting /// </summary> private static void DisplaySettingChanged(object obj, EventArgs ea) { s_highContrastSettingValid = false; s_lowResSettingValid = false; s_terminalSettingValid = false; s_dropShadowSettingValid = false; } /// <summary> ///event handler for change in user preference /// </summary> private static void UserPreferenceChanged(object obj, UserPreferenceChangedEventArgs ea) { s_highContrastSettingValid = false; s_lowResSettingValid = false; s_terminalSettingValid = false; s_dropShadowSettingValid = false; s_bitsPerPixel = 0; } } } }
41.500745
258
0.529321
[ "MIT" ]
adamsitnik/winforms
src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesignerUtils.cs
27,849
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using NuGet.Packaging; using NuGetPackageVerifier.Logging; namespace NuGetPackageVerifier { public class PackageAnalysisContext : IDisposable { private PackageArchiveReader _reader; public FileInfo PackageFileInfo { get; set; } public IPackageMetadata Metadata { get; set; } public PackageVerifierOptions Options { get; set; } public IPackageVerifierLogger Logger { get; set; } public PackageArchiveReader PackageReader { get { if (_reader == null) { _reader = new PackageArchiveReader(PackageFileInfo.FullName); } return _reader; } } public void Dispose() { _reader?.Dispose(); } } }
27.567568
111
0.601961
[ "Apache-2.0" ]
natemcmaster/AspNetBuildTools
src/NuGetPackageVerifier/PackageAnalysisContext.cs
1,022
C#
using Microsoft.IdentityModel.Clients.ActiveDirectory; using System.IO; using System.Security.Cryptography; class FileCache : TokenCache { public string CacheFilePath; private static readonly object FileLock = new object(); // Initializes the cache against a local file. // If the file is already present, it loads its content in the ADAL cache public FileCache(string filePath = @".\TokenCache.dat") { CacheFilePath = filePath; this.AfterAccess = AfterAccessNotification; this.BeforeAccess = BeforeAccessNotification; lock (FileLock) { this.Deserialize(File.Exists(CacheFilePath) ? ProtectedData.Unprotect(File.ReadAllBytes(CacheFilePath), null, DataProtectionScope.CurrentUser) : null); } } // Empties the persistent store. public override void Clear() { base.Clear(); File.Delete(CacheFilePath); } // Triggered right before ADAL needs to access the cache. // Reload the cache from the persistent store in case it changed since the last access. void BeforeAccessNotification(TokenCacheNotificationArgs args) { lock (FileLock) { this.Deserialize(File.Exists(CacheFilePath) ? ProtectedData.Unprotect(File.ReadAllBytes(CacheFilePath), null, DataProtectionScope.CurrentUser) : null); } } // Triggered right after ADAL accessed the cache. void AfterAccessNotification(TokenCacheNotificationArgs args) { // if the access operation resulted in a cache update if (this.HasStateChanged) { lock (FileLock) { // reflect changes in the persistent store File.WriteAllBytes(CacheFilePath, ProtectedData.Protect(this.Serialize(), null, DataProtectionScope.CurrentUser)); // once the write operation took place, restore the HasStateChanged bit to false this.HasStateChanged = false; } } } }
35.895522
97
0.557173
[ "MIT" ]
plasne/multitenant
dotnet/WpfClient/FileCache.cs
2,407
C#
using ExtractRdlImages.Install; using Microsoft.Win32; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ExtractRdlImages.Forms { public partial class MainForm : Form { public MainForm() { InitializeComponent(); UpdateState(); } private InstallScope CurrentScope { get { return allUsersCheckBox.Checked ? InstallScope.LocalMachine : InstallScope.CurrentUser; } } private bool DropHighlighted { get { return lbExtract.BackColor != gbExtract.BackColor; } set { if (value) { lbExtract.BackColor = SystemColors.Highlight; lbExtract.ForeColor = SystemColors.HighlightText; } else { lbExtract.BackColor = gbExtract.BackColor; lbExtract.ForeColor = gbExtract.ForeColor; } } } private void installButton_Click(object sender, EventArgs e) { Installer.Install(CurrentScope); UpdateState(); } private void uninstallButton_Click(object sender, EventArgs e) { Installer.Uninstall(CurrentScope); UpdateState(); } private void allUsersCheckBox_CheckedChanged(object sender, EventArgs e) { UpdateState(); } private void UpdateState() { var installed = false; var installedCurrentUser = Installer.IsInstalled(InstallScope.CurrentUser); var installedLocalMachine = Installer.IsInstalled(InstallScope.LocalMachine); if (installedLocalMachine) { installed = true; allUsersCheckBox.Checked = true; } if (installedCurrentUser) { installed = true; allUsersCheckBox.Checked = false; } installButton.SetShield(allUsersCheckBox.Checked); uninstallButton.SetShield(allUsersCheckBox.Checked); installButton.Enabled = !installed; uninstallButton.Enabled = installed; allUsersCheckBox.Visible = !installed; } private void lbExtract_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent("FileDrop")) { e.Effect = DragDropEffects.Copy; DropHighlighted = true; } } private void lbExtract_DragDrop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent("FileDrop")) { var filePaths = e.Data.GetData("FileDrop") as string[]; if (filePaths != null) { var reports = filePaths .Where(x => x.EndsWith(".rdl", StringComparison.OrdinalIgnoreCase)); foreach (var report in reports) { Extractor.ExtractImages(report); } } } DropHighlighted = false; } private void lbExtract_DragLeave(object sender, EventArgs e) { DropHighlighted = false; } } }
28.472
107
0.534982
[ "Apache-2.0" ]
dmester/extract-rdl-images
ExtractRdlImages/Forms/MainForm.cs
3,561
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: IMethodRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The interface IWindowsAutopilotDeviceIdentityAssignResourceAccountToDeviceRequest. /// </summary> public partial interface IWindowsAutopilotDeviceIdentityAssignResourceAccountToDeviceRequest : IBaseRequest { /// <summary> /// Gets the request body. /// </summary> WindowsAutopilotDeviceIdentityAssignResourceAccountToDeviceRequestBody RequestBody { get; } /// <summary> /// Issues the POST request. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await for async call.</returns> System.Threading.Tasks.Task PostAsync( CancellationToken cancellationToken = default); /// <summary> /// Issues the POST request and returns a <see cref="GraphResponse"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse"/> object of the request</returns> System.Threading.Tasks.Task<GraphResponse> PostResponseAsync(CancellationToken cancellationToken = default); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IWindowsAutopilotDeviceIdentityAssignResourceAccountToDeviceRequest Expand(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IWindowsAutopilotDeviceIdentityAssignResourceAccountToDeviceRequest Select(string value); } }
41.065574
153
0.627944
[ "MIT" ]
ScriptBox99/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IWindowsAutopilotDeviceIdentityAssignResourceAccountToDeviceRequest.cs
2,505
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using System.Runtime.CompilerServices; using NUnit.Engine; using AutomationFrameWork.Driver; using OpenQA.Selenium.Chrome; using OpenQA.Selenium; using OpenQA.Selenium.Remote; using AutomationFrameWork.Utils; using AutomationFrameWork.ActionsKeys; using System.Web.UI; using System.IO; using AutomationFrameWork.Extensions; using System.Collections.ObjectModel; using Mono.Collections.Generic; using OpenQA.Selenium.Support.PageObjects; using AutomationFrameWork.Driver.Interface; using OpenQA.Selenium.Support; using OpenQA.Selenium.Support.UI; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.Support.Events; using OpenQA.Selenium.Appium.Android; using OpenQA.Selenium.Appium; namespace AutomationTesting { [TestFixture(Browser.ChromeDesktop)] [TestFixture(Browser.iPad)] [TestFixture(Browser.FirefoxDesktop)] [TestFixture(Browser.InternetExplorerDesktop)] [TestFixture(Browser.iPhone4)] [TestFixture(Browser.iPhone5)] [TestFixture(Browser.iPhone6)] [TestFixture(Browser.Nexus6)] [TestFixture(Browser.Nexus7)] [Parallelizable(ParallelScope.Self)] public class TestITestListener { public TestITestListener(Browser browserType) { _type = browserType; } Browser _type; object driverType; IWebDriver driver; [Category("Capture Element Image")] [Test] public void Event () { ChromeOptions op = new ChromeOptions(); op.EnableMobileEmulation("Apple iPhone 4"); //DriverFactory.Instance.DriverOption = op; DriverManager.StartDriver(Browser.ChromeDesktop); IWebDriver driver = DriverManager.GetDriver<IWebDriver>(); driver.Url = "https://www.whatismybrowser.com/"; IWebElement el = driver.FindElement(By.XPath("//*[@id='holder']//*[@class='detection-primary content-block']")); WebKeywords.Instance.GetScreenShot(); Utilities.Instance.GetWebElementBaseImage(el, formatType: System.Drawing.Imaging.ImageFormat.Jpeg); driver.Dispose(); DriverManager.CloseDriver(); } [Category("TestReportTemplate")] [Test] public void CreateHTML () { string FullPage = string.Empty; var strWr = new StringWriter(); using (var writer = new HtmlTextWriter(strWr)) { writer.Write("<!DOCTYPE html>"); writer.AddAttribute(HtmlTextWriterAttribute.Id,"Test"); writer.RenderBeginTag(HtmlTextWriterTag.Head); writer.AddAttribute("http-equiv", "X-UA-Compatible"); writer.AddAttribute("content", @"IE=edge"); writer.AddAttribute("charset", "utf-8"); writer.RenderBeginTag(HtmlTextWriterTag.Meta); writer.RenderEndTag(); writer.AddAttribute(HtmlTextWriterAttribute.Rel, "stylesheet"); writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/css"); writer.AddAttribute(HtmlTextWriterAttribute.Href, @"D:\WorkSpace\Git\AutomationFramework\AutomationFramework\Base\Reporter\EmbeddedResources\Primer\primer.css"); writer.RenderBeginTag(HtmlTextWriterTag.Link); writer.RenderEndTag(); writer.NewLine = "\r\n"; writer.AddAttribute(HtmlTextWriterAttribute.Id, "Div 1"); writer.AddStyleAttribute(HtmlTextWriterStyle.TextAlign, "center"); writer.RenderBeginTag(HtmlTextWriterTag.Div); writer.AddAttribute(HtmlTextWriterAttribute.Id, "testname"); writer.RenderBeginTag(HtmlTextWriterTag.A); writer.RenderBeginTag(HtmlTextWriterTag.H1); writer.Write("Test this show in html page"); writer.NewLine = "\r\n"; writer.RenderEndTag(); writer.RenderEndTag(); writer.RenderEndTag(); writer.RenderEndTag(); writer.Write("</html>"); } FullPage = strWr.ToString(); File.WriteAllText(@"C:\Users\Minh\Desktop\New folder\TestReport.html", FullPage); } #region //Test FindContext [Test] [Parallelizable(ParallelScope.Self)] [Category("Context")] public void TestContextFind() { //IDriver<IWebDriver> test = new ChromeDesktop { Driver= new ChromeDesktop().StartDriver()}; IWebDriver driver = new ChromeDriver(); driver.Url = "http://www.google.com"; driver.Navigate().GoToUrl("http://vtc.vn"); driver.Navigate().Back(); driver.FindElement(OpenQA.Selenium.By.Id("lst-ib")).SendKeys("test this show with long string "); driver.FindElement(OpenQA.Selenium.By.Id("lst-ib")).Clear(); driver.FindElement(OpenQA.Selenium.By.Id("lst-ib")).SendKeys("test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string test this show with long string "); driver.Quit(); } #endregion [Test] [Category("WebDriverListner")] public void TestFactory() { IWebDriver driver = new FirefoxDriver(); driver = new EventFiringWebDriver(driver); ((EventFiringWebDriver)driver).Navigated+= new EventHandler<WebDriverNavigationEventArgs>(EventFiringInstance_Navigated); ((EventFiringWebDriver)driver).FindingElement += new EventHandler<FindElementEventArgs>(ClickEvent); driver.Url = "http://www.google.com"; driver.FindElement(OpenQA.Selenium.By.Id("lst-ib")); driver.Quit(); } private void EventFiringInstance_Navigated(object sender, WebDriverNavigationEventArgs e) { Console.WriteLine(sender.ToString()); Console.WriteLine("Test: "+e.Url); } private void ClickEvent(object sender, FindElementEventArgs e) { Console.WriteLine(e.FindMethod.ToString()); } [Test] [Category("TestListner")] public void TestAddInFailed() { POM.TestFramework.TestFrameworkAction.Instance.DoSomething("Minh Hoang Test"); Assert.True(POM.TestFramework.TestFrameworkAction.Instance.CheckSingleton(),POM.TestFramework.TestFrameworkAction.Instance.Message); } [Test] [Category("TestListner")] public void TestAddInIgnore() { throw new IgnoreException("Ignore"); POM.TestFramework.TestFrameworkAction.Instance.DoSomething("Minh Hoang Test"); Assert.True(POM.TestFramework.TestFrameworkAction.Instance.CheckSingleton(), POM.TestFramework.TestFrameworkAction.Instance.Message); } [Test] [Category("TestListner")] public void TestAddInPass() { POM.TestFramework.TestFrameworkAction.Instance.DoSomething("Minh Hoang Test"); Assert.True(!POM.TestFramework.TestFrameworkAction.Instance.CheckSingleton(), POM.TestFramework.TestFrameworkAction.Instance.Message); } [Test] [Category("Test Nested Class")] public void TestAddInExplicit() { POM.TestFramework.TestFrameworkAction.Instance.DoSomeThing().PrintSomeThing().Verify().ValidateFalse(true).ValidateTrue(true).ValidateString("TEst mnasda"); POM.TestFramework.TestFrameworkAction.Instance.DoSomeThing().PrintSomeThing().Verify().ValidateFalse(true).ValidateTrue(true).ValidateString("TEsrsd"); } [Test] [Category("Test MARIONETTE Driver")] public void TestMaruonetteDriver() { //System.Environment.SetEnvironmentVariable("webdriver.gecko.driver", @"D:\WorkSpace\Git\AutomationFramework\Drivers\geckodriver.exe"); //FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(@"D:\WorkSpace\Git\AutomationFramework\Drivers\", "geckodriver.exe"); //service.Port = 64444; //service.FirefoxBinaryPath = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe"; IWebDriver driver = new FirefoxDriver(); driver.Url = "https://www.google.com"; //driver.Quit(); } [Test] [Category("HTMLUnit Driver")] public void TestHtmlUnit() { var remoteServer = new Uri("http://localhost:6969/wd/hub/"); DesiredCapabilities desiredCapabilities = DesiredCapabilities.HtmlUnit(); desiredCapabilities.IsJavaScriptEnabled = true; var WebDriver = new RemoteWebDriver(remoteServer,desiredCapabilities); WebDriver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30)); //go to url WebDriver.Navigate().GoToUrl("https://www.kbb.com"); Console.WriteLine(WebDriver.Title); WebDriver.Quit(); } [Test,Category("Appium Test")] public void OpenSampleApp() { DesiredCapabilities caps = new DesiredCapabilities(); caps.SetCapability("deviceName", "Note5"); caps.SetCapability("udid", "0415313132353234"); caps.SetCapability("appActivity",".activities.login.LoginActivity"); //caps.SetCapability("appWaitActivity", ".activities.main.MainActivity"); caps.SetCapability("appWaitPackage", "com.sample.directory"); var driver = new AndroidDriver<AppiumWebElement>(new Uri("http://127.0.0.1:4723/wd/hub"), caps); driver.FindElement(By.Id("com.sample_technology.sampledirectory:id/userNameEditText")).SendKeys("minhhoang"); driver.FindElement(By.Id("com.sample_technology.sampledirectory:id/passwordEditText")).SendKeys("sample@1234"); driver.FindElement(By.Id("com.sample_technology.sampledirectory:id/loginBtn")).Click(); System.Threading.Thread.Sleep(10000); driver.FindElement(By.Id("com.sample_technology.sampledirectory:id/editText")).SendKeys("minh hoang"); Console.WriteLine(driver.FindElement(By.Id("com.sample_technology.sampledirectory:id/editText")).Text); System.Threading.Thread.Sleep(10000); driver.Quit(); } } }
61.666667
3,726
0.676869
[ "Apache-2.0" ]
toilatester/sample-automation-frameworks-across-languages
dotnet/AutomationTesting/TestITestListener.cs
14,247
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the forecast-2018-06-26.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ForecastService.Model { /// <summary> /// This is the response object from the CreateDatasetImportJob operation. /// </summary> public partial class CreateDatasetImportJobResponse : AmazonWebServiceResponse { private string _datasetImportJobArn; /// <summary> /// Gets and sets the property DatasetImportJobArn. /// <para> /// The Amazon Resource Name (ARN) of the dataset import job. /// </para> /// </summary> [AWSProperty(Max=256)] public string DatasetImportJobArn { get { return this._datasetImportJobArn; } set { this._datasetImportJobArn = value; } } // Check to see if DatasetImportJobArn property is set internal bool IsSetDatasetImportJobArn() { return this._datasetImportJobArn != null; } } }
31.192982
106
0.675478
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/ForecastService/Generated/Model/CreateDatasetImportJobResponse.cs
1,778
C#
using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Kroeg.ActivityStreams; using Kroeg.EntityStore.Models; using Kroeg.EntityStore.Store; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Primitives; using Microsoft.EntityFrameworkCore.Storage; using Kroeg.ActivityPub; using Kroeg.EntityStore.Services; using System.IO; using System.Text; // For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace Kroeg.Server.Middleware { public class GetEntityMiddleware { private readonly RequestDelegate _next; private List<IConverterFactory> _converters; public GetEntityMiddleware(RequestDelegate next) { _next = next; _converters = new List<IConverterFactory> { new AS2ConverterFactory() }; } public async Task Invoke(HttpContext context, IServiceProvider serviceProvider, IServerConfig serverConfig, IEntityStore store) { var handler = ActivatorUtilities.CreateInstance<GetEntityHandler>(serviceProvider, context.User); if (serverConfig.RewriteRequestScheme) context.Request.Scheme = "https"; // var fullpath = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}"; var fullpath = $"{serverConfig.BaseUriWithoutTrailing}{context.Request.Path}"; foreach (var converterFactory in _converters) { if (converterFactory.FileExtension != null && fullpath.EndsWith("." + converterFactory.FileExtension)) { fullpath = fullpath.Substring(0, fullpath.Length - 1 - converterFactory.FileExtension.Length); context.Request.Headers.Remove("Accept"); context.Request.Headers.Add("Accept", converterFactory.RenderMimeType); break; } } if (!context.Request.Path.ToUriComponent().StartsWith("/auth")) { context.Response.Headers.Add("Access-Control-Allow-Credentials", "true"); context.Response.Headers.Add("Access-Control-Allow-Headers", "Authorization"); context.Response.Headers.Add("Access-Control-Expose-Headers", "Link"); context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST"); context.Response.Headers.Add("Access-Control-Allow-Origin", context.Request.Headers["Origin"]); context.Response.Headers.Add("Vary", "Origin"); } /* && ConverterHelpers.GetBestMatch(_converters[0].MimeTypes, context.Request.Headers["Accept"]) != null */ if (context.Request.Method == "OPTIONS") { context.Response.StatusCode = 200; return; } Console.WriteLine(fullpath); foreach (var line in context.Request.Headers["Accept"]) Console.WriteLine($"---- {line}"); if (context.Request.Headers["Accept"].Contains("text/event-stream")) { await handler.EventStream(context, fullpath); return; } if (context.WebSockets.IsWebSocketRequest) { await handler.WebSocket(context, fullpath); return; } if (context.Request.Method == "POST" && context.Request.ContentType.StartsWith("multipart/form-data")) { context.Items.Add("fullPath", fullpath); context.Request.Path = "/settings/uploadMedia"; await _next(context); return; } IConverter readConverter = null; IConverter writeConverter = null; bool needRead = context.Request.Method == "POST"; var target = fullpath.Replace("127.0.0.1", "localhost"); APEntity targetEntity = null; targetEntity = await store.GetEntity(target, false); if (needRead) { if (targetEntity?.Type == "_inbox") target = targetEntity.Data["attributedTo"].Single().Id; } if (targetEntity == null) { // using var ms = new MemoryStream(); // await context.Request.Body.CopyToAsync(ms); // var x = Encoding.UTF8.GetString(ms.ToArray()); // System.Console.WriteLine(x); await _next(context); return; } var acceptHeaders = context.Request.Headers["Accept"]; if (acceptHeaders.Count == 0 && context.Request.ContentType != null) { acceptHeaders.Append(context.Request.ContentType); } foreach (var converterFactory in _converters) { bool worksForWrite = converterFactory.CanRender && ConverterHelpers.GetBestMatch(converterFactory.MimeTypes, acceptHeaders) != null; bool worksForRead = needRead && converterFactory.CanParse && ConverterHelpers.GetBestMatch(converterFactory.MimeTypes, context.Request.ContentType) != null; if (worksForRead && worksForWrite && readConverter == null && writeConverter == null) { readConverter = writeConverter = converterFactory.Build(serviceProvider, target); break; } if (worksForRead && readConverter == null) readConverter = converterFactory.Build(serviceProvider, target); if (worksForWrite && writeConverter == null) writeConverter = converterFactory.Build(serviceProvider, target); } ASObject data = null; if (readConverter != null) data = await readConverter.Parse(context.Request.Body); if (needRead && readConverter != null && writeConverter == null) writeConverter = readConverter; if (data == null && needRead && targetEntity != null) { context.Response.StatusCode = 415; await context.Response.WriteAsync("Unknown mime type " + context.Request.ContentType); return; } var arguments = context.Request.Query; APEntity entOut = null; try { if (context.Request.Method == "GET" || context.Request.Method == "HEAD" || context.Request.Method == "OPTIONS") { entOut = await handler.Get(fullpath, arguments, context, targetEntity); if (entOut?.Id == "kroeg:unauthorized" && writeConverter != null) throw new UnauthorizedAccessException("no access"); } else if (context.Request.Method == "POST" && data != null) { await handler._connection.OpenAsync(); using (var transaction = handler._connection.BeginTransaction()) { entOut = await handler.Post(context, fullpath, targetEntity, data); transaction.Commit(); } } } catch (UnauthorizedAccessException e) { context.Response.StatusCode = 403; Console.WriteLine(e); await context.Response.WriteAsync(e.Message); } catch (InvalidOperationException e) { context.Response.StatusCode = 401; Console.WriteLine(e); await context.Response.WriteAsync(e.Message); } if (context.Response.HasStarted) return; if (entOut != null) { if (context.Request.Method == "HEAD") { context.Response.StatusCode = 200; return; } if (writeConverter != null) await writeConverter.Render(context.Request, context.Response, entOut); else if (context.Request.ContentType == "application/magic-envelope+xml") { context.Response.StatusCode = 202; await context.Response.WriteAsync("accepted"); } else { context.Request.Method = "GET"; context.Request.Path = "/render"; context.Items["object"] = entOut; await _next(context); } return; } if (!context.Response.HasStarted) { await _next(context); } } } }
39.950893
172
0.553693
[ "MIT" ]
Cosmic-Chimps/timon-activity-pub
Kroeg.Server/Middleware/GetEntityMiddleware.cs
8,949
C#
using System.Collections.Generic; using System.Linq; using BenchmarkDotNet.Running; namespace BenchmarkDotNet.Validators { public class CompilationValidator : IValidator { private const char Underscore = '_'; public static readonly IValidator Default = new CompilationValidator(); private CompilationValidator() { } public bool TreatsWarningsAsErrors => true; public IEnumerable<ValidationError> Validate(ValidationParameters validationParameters) => validationParameters .Benchmarks .Where(benchmark => !IsValidCSharpIdentifier(benchmark.Target.Method.Name)) .Distinct(BenchmarkMethodEqualityComparer.Instance) // we might have multiple jobs targeting same method. Single error should be enough ;) .Select(benchmark => new ValidationError( true, $"Benchmarked method `{benchmark.Target.Method.Name}` contains illegal character(s). Please use `[<Benchmark(Description = \"Custom name\")>]` to set custom display name.", benchmark )); private bool IsValidCSharpIdentifier(string identifier) // F# allows to use whitespaces as names #479 => !string.IsNullOrEmpty(identifier) && (char.IsLetter(identifier[0]) || identifier[0] == Underscore) // An identifier must start with a letter or an underscore && identifier .Skip(1) .All(character => char.IsLetterOrDigit(character) || character == Underscore); private class BenchmarkMethodEqualityComparer : IEqualityComparer<Benchmark> { internal static readonly IEqualityComparer<Benchmark> Instance = new BenchmarkMethodEqualityComparer(); public bool Equals(Benchmark x, Benchmark y) => x.Target.Method.Equals(y.Target.Method); public int GetHashCode(Benchmark obj) => obj.Target.Method.GetHashCode(); } } }
44.297872
196
0.632565
[ "MIT" ]
agocke/BenchmarkDotNet
src/BenchmarkDotNet.Core/Validators/CompilationValidator.cs
2,084
C#
using System; using System.Threading.Tasks; namespace YIF.Core.Data.Interfaces { public interface ISchoolGraduateRepository<T> : IDisposable where T : class { Task<T> GetSchoolByUserId(string userId); } }
20.636364
79
0.718062
[ "MIT" ]
ita-social-projects/YIF_Backend
YIF.Core.Data/Interfaces/ISchoolGraduateRepository.cs
229
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace FastGuess { public class ScoreBoard { [Key] public Guid Id { get; set; } public string Nickname { get; set; } public DateTime Date { get; set; } = DateTime.UtcNow; public int Score { get; set; } } public class ScoreRecord { [Required] public string Id { get; set; } [Required] public string Nickname { get; set; } public DateTime Date = DateTime.UtcNow; [Required] public UsedAnswers Answers { get; set; } } }
20.878788
61
0.606676
[ "MIT" ]
nvbach91/4IZ268-2020-2021-ZS
www/duzm00/sp2/FastGuess/ScoreBoard.cs
691
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Vod.V20180717.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class AiRecognitionTaskOcrWordsResultItem : AbstractModel { /// <summary> /// 文本关键词。 /// </summary> [JsonProperty("Word")] public string Word{ get; set; } /// <summary> /// 文本关键出现的片段列表。 /// </summary> [JsonProperty("SegmentSet")] public AiRecognitionTaskOcrWordsSegmentItem[] SegmentSet{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "Word", this.Word); this.SetParamArrayObj(map, prefix + "SegmentSet.", this.SegmentSet); } } }
30.470588
81
0.644788
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Vod/V20180717/Models/AiRecognitionTaskOcrWordsResultItem.cs
1,590
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace ScriptRepository { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
27.666667
70
0.713855
[ "MIT" ]
yimlu/script-repo
ScriptRepository/Global.asax.cs
666
C#
//----------------------------------------------------------------------- // <copyright file="CoordinatedShutdownSpec.cs" company="Akka.NET Project"> // Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using Akka.Actor; using Akka.TestKit; using Akka.Util.Internal; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Akka.Configuration; using FluentAssertions; using Xunit; using static Akka.Actor.CoordinatedShutdown; namespace Akka.Tests.Actor { public class CoordinatedShutdownSpec : AkkaSpec { public ExtendedActorSystem ExtSys => Sys.AsInstanceOf<ExtendedActorSystem>(); private Phase Phase(params string[] dependsOn) { return new Phase(dependsOn?.ToImmutableHashSet() ?? ImmutableHashSet<string>.Empty, TimeSpan.FromSeconds(10), true); } private static readonly Phase EmptyPhase = new Phase(ImmutableHashSet<string>.Empty, TimeSpan.FromSeconds(10), true); private List<string> CheckTopologicalSort(Dictionary<string, Phase> phases) { var result = CoordinatedShutdown.TopologicalSort(phases); result.ZipWithIndex().ForEach(pair => { if (!phases.ContainsKey(pair.Key)) return; var i = pair.Value; var p = phases[pair.Key]; p.DependsOn.ForEach(depPhase => { i.Should().BeGreaterThan(result.IndexOf(depPhase), $"phase [{p}] depends on [{depPhase}] but was ordered before it in topological sort result {string.Join("->", result)}"); }); }); return result; } [Fact] public void CoordinatedShutdown_must_sort_phases_in_topological_order() { CheckTopologicalSort(new Dictionary<string, Phase>()).Count.Should().Be(0); CheckTopologicalSort(new Dictionary<string, Phase>() { { "a", EmptyPhase } }) .Should() .Equal(new List<string>() { "a" }); CheckTopologicalSort(new Dictionary<string, Phase>() { { "b", Phase("a") } }) .Should() .Equal(new List<string>() { "a", "b" }); var result1 = CheckTopologicalSort(new Dictionary<string, Phase>() { { "c", Phase("a") }, { "b", Phase("a") } }); result1.First().Should().Be("a"); // b,c can be in any order result1.ToImmutableHashSet() .SetEquals(new HashSet<string>(new[] { "a", "b", "c" })) .ShouldBeTrue(); CheckTopologicalSort(new Dictionary<string, Phase>() { { "b", Phase("a") }, { "c", Phase("b") } }) .Should() .Equal(new List<string>() { "a", "b", "c" }); CheckTopologicalSort(new Dictionary<string, Phase>() { { "b", Phase("a") }, { "c", Phase("a", "b") } }) .Should() .Equal(new List<string>() { "a", "b", "c" }); var result2 = CheckTopologicalSort(new Dictionary<string, Phase>() { { "c", Phase("a", "b") } }); result2.Last().Should().Be("c"); // a, b can be in any order result2.ToImmutableHashSet().SetEquals(new[] { "a", "b", "c" }).Should().BeTrue(); CheckTopologicalSort(new Dictionary<string, Phase>() { {"b", Phase("a")}, {"c", Phase("b")}, {"d", Phase("b", "c")}, {"e", Phase("d")} }).Should().Equal(new List<string>() { "a", "b", "c", "d", "e" }); var result3 = CheckTopologicalSort(new Dictionary<string, Phase>() { {"a2", Phase("a1")}, {"a3", Phase("a2")}, {"b2", Phase("b1")}, {"b3", Phase("b2")}, }); var a = result3.TakeWhile(x => x.First() == 'a'); var b = result3.SkipWhile(x => x.First() == 'a'); a.Should().Equal(new List<string>() { "a1", "a2", "a3" }); b.Should().Equal(new List<string>() { "b1", "b2", "b3" }); } [Fact] public void CoordinatedShutdown_must_detect_cycles_in_phases_non_DAG() { Intercept<ArgumentException>(() => { CoordinatedShutdown.TopologicalSort(new Dictionary<string, Phase>() { { "a", Phase("a") } }); }); Intercept<ArgumentException>(() => { CoordinatedShutdown.TopologicalSort(new Dictionary<string, Phase>() { { "b", Phase("a") }, { "a", Phase("b") }, }); }); Intercept<ArgumentException>(() => { CoordinatedShutdown.TopologicalSort(new Dictionary<string, Phase>() { { "c", Phase("a") }, { "c", Phase("b") }, { "b", Phase("c") }, }); }); Intercept<ArgumentException>(() => { CoordinatedShutdown.TopologicalSort(new Dictionary<string, Phase>() { { "d", Phase("a") }, { "d", Phase("c") }, { "c", Phase("b") }, { "b", Phase("d") }, }); }); } [Fact] public void CoordinatedShutdown_must_predefined_phases_from_config() { CoordinatedShutdown.Get(Sys).OrderedPhases.Should().Equal(new[] { PhaseBeforeServiceUnbind, PhaseServiceUnbind, PhaseServiceRequestsDone, PhaseServiceStop, PhaseBeforeClusterShutdown, PhaseClusterShardingShutdownRegion, PhaseClusterLeave, PhaseClusterExiting, PhaseClusterExitingDone, PhaseClusterShutdown, PhaseBeforeActorSystemTerminate, PhaseActorSystemTerminate }); } [Fact] public void CoordinatedShutdown_must_run_ordered_phases() { var phases = new Dictionary<string, Phase>() { { "a", EmptyPhase }, { "b", Phase("a") }, { "c", Phase("b", "a") } }; var co = new CoordinatedShutdown(ExtSys, phases); co.AddTask("a", "a1", () => { TestActor.Tell("A"); return TaskEx.Completed; }); co.AddTask("b", "b1", () => { TestActor.Tell("B"); return TaskEx.Completed; }); co.AddTask("b", "b2", () => { // to verify that c is not performed before b Task.Delay(TimeSpan.FromMilliseconds(100)).Wait(); TestActor.Tell("B"); return TaskEx.Completed; }); co.AddTask("c", "c1", () => { TestActor.Tell("C"); return TaskEx.Completed; }); co.Run().Wait(RemainingOrDefault); ReceiveN(4).Should().Equal(new object[] { "A", "B", "B", "C" }); } [Fact] public void CoordinatedShutdown_must_run_from_given_phase() { var phases = new Dictionary<string, Phase>() { { "a", EmptyPhase }, { "b", Phase("a") }, { "c", Phase("b", "a") } }; var co = new CoordinatedShutdown(ExtSys, phases); co.AddTask("a", "a1", () => { TestActor.Tell("A"); return TaskEx.Completed; }); co.AddTask("b", "b1", () => { TestActor.Tell("B"); return TaskEx.Completed; }); co.AddTask("c", "c1", () => { TestActor.Tell("C"); return TaskEx.Completed; }); co.Run("b").Wait(RemainingOrDefault); ReceiveN(2).Should().Equal(new object[] { "B", "C" }); } [Fact] public void CoordinatedShutdown_must_only_run_once() { var phases = new Dictionary<string, Phase>() { { "a", EmptyPhase } }; var co = new CoordinatedShutdown(ExtSys, phases); co.AddTask("a", "a1", () => { TestActor.Tell("A"); return TaskEx.Completed; }); co.Run().Wait(RemainingOrDefault); ExpectMsg("A"); co.Run().Wait(RemainingOrDefault); TestActor.Tell("done"); ExpectMsg("done"); // no additional A } [Fact] public void CoordinatedShutdown_must_continue_after_timeout_or_failure() { var phases = new Dictionary<string, Phase>() { { "a", EmptyPhase }, { "b", new Phase(ImmutableHashSet<string>.Empty.Add("a"), TimeSpan.FromMilliseconds(100), true)}, { "c", Phase("b", "a") } }; var co = new CoordinatedShutdown(ExtSys, phases); co.AddTask("a", "a1", () => { TestActor.Tell("A"); return TaskEx.FromException<Done>(new ApplicationException("boom")); }); co.AddTask("a", "a2", () => { Task.Delay(TimeSpan.FromMilliseconds(100)).Wait(); TestActor.Tell("A"); return TaskEx.Completed; }); co.AddTask("b", "b1", () => { TestActor.Tell("B"); return new TaskCompletionSource<Done>().Task; // never completed }); co.AddTask("c", "c1", () => { TestActor.Tell("C"); return TaskEx.Completed; }); co.Run().Wait(RemainingOrDefault); ExpectMsg("A"); ExpectMsg("A"); ExpectMsg("B"); ExpectMsg("C"); } [Fact] public void CoordinatedShutdown_must_abort_if_recover_is_off() { var phases = new Dictionary<string, Phase>() { { "b", new Phase(ImmutableHashSet<string>.Empty.Add("a"), TimeSpan.FromMilliseconds(100), false)}, { "c", Phase("b", "a") } }; var co = new CoordinatedShutdown(ExtSys, phases); co.AddTask("b", "b1", () => { TestActor.Tell("B"); return new TaskCompletionSource<Done>().Task; // never completed }); co.AddTask("c", "c1", () => { TestActor.Tell("C"); return TaskEx.Completed; }); var result = co.Run(); ExpectMsg("B"); Intercept<AggregateException>(() => { if (result.Wait(RemainingOrDefault)) { result.Exception?.Flatten().InnerException.Should().BeOfType<TimeoutException>(); } else { throw new ApplicationException("CoordinatedShutdown task did not complete"); } }); ExpectNoMsg(TimeSpan.FromMilliseconds(200)); // C not run } [Fact] public void CoordinatedShutdown_must_be_possible_to_add_tasks_in_later_phase_from_earlier_phase() { var phases = new Dictionary<string, Phase>() { { "a", EmptyPhase }, {"b", Phase("a") } }; var co = new CoordinatedShutdown(ExtSys, phases); co.AddTask("a", "a1", () => { TestActor.Tell("A"); co.AddTask("b", "b1", () => { TestActor.Tell("B"); return TaskEx.Completed; }); return TaskEx.Completed; }); co.Run().Wait(RemainingOrDefault); ExpectMsg("A"); ExpectMsg("B"); } [Fact] public void CoordinatedShutdown_must_be_possible_to_parse_phases_from_config() { CoordinatedShutdown.PhasesFromConfig(ConfigurationFactory.ParseString(@" default-phase-timeout = 10s phases { a = {} b { depends-on = [a] timeout = 15s } c { depends-on = [a, b] recover = off } }")).Should() .Equal(new Dictionary<string, Phase>() { { "a", new Phase(ImmutableHashSet<string>.Empty, TimeSpan.FromSeconds(10), true)}, { "b", new Phase(ImmutableHashSet<string>.Empty.Add("a"), TimeSpan.FromSeconds(15), true)}, { "c", new Phase(ImmutableHashSet<string>.Empty.Add("a").Add("b"), TimeSpan.FromSeconds(10), false)}, }); } [Fact] public void CoordinatedShutdown_must_terminate_ActorSystem() { var shutdownSystem = CoordinatedShutdown.Get(Sys).Run(); shutdownSystem.Wait(TimeSpan.FromSeconds(10)).Should().BeTrue(); Sys.WhenTerminated.IsCompleted.Should().BeTrue(); } } }
34.346535
145
0.461805
[ "Apache-2.0" ]
corefan/akka.net
src/core/Akka.Tests/Actor/CoordinatedShutdownSpec.cs
13,878
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("RunAsUser")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RunAsUser")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9dff282c-93b9-4063-bf8a-b6798371d35a")] // 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.459459
84
0.746753
[ "MIT" ]
atthacks/RunAsUser
Properties/AssemblyInfo.cs
1,389
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Multiformats.Codec; using Multiformats.Hash; using Nethereum.Contracts.Standards.ENS; using Nethereum.Hex.HexConvertors.Extensions; using Nethereum.Util; using Nethereum.XUnitEthereumClients; using Xunit; namespace Nethereum.Contracts.IntegrationTests.SmartContracts.Standards { [Collection(EthereumClientIntegrationFixture.ETHEREUM_CLIENT_COLLECTION_DEFAULT)] public class ENSMainNetTest { private readonly EthereumClientIntegrationFixture _ethereumClientIntegrationFixture; public ENSMainNetTest(EthereumClientIntegrationFixture ethereumClientIntegrationFixture) { _ethereumClientIntegrationFixture = ethereumClientIntegrationFixture; } public async void ShouldBeAbleToRegisterExample() { var durationInDays = 365; var ourName = "lllalalalal"; //enter owner name var tls = "eth"; var owner = "0x111F530216fBB0377B4bDd4d303a465a1090d09d"; var secret = "Today is gonna be the day That theyre gonna throw it back to you"; //make your own var web3 = _ethereumClientIntegrationFixture.GetInfuraWeb3(InfuraNetwork.Mainnet); var ethTLSService = web3.Eth.GetEnsEthTlsService(); await ethTLSService.InitialiseAsync(); var price = await ethTLSService.CalculateRentPriceInEtherAsync(ourName, durationInDays); Assert.True(price > 0); var commitment = await ethTLSService.CalculateCommitmentAsync(ourName, owner, secret); var commitTransactionReceipt = await ethTLSService.CommitRequestAndWaitForReceiptAsync(commitment); var txnHash = await ethTLSService.RegisterRequestAsync(ourName, owner, durationInDays, secret, price); } public async void ShouldBeAbleToSetTextExample() { var web3 = _ethereumClientIntegrationFixture.GetInfuraWeb3(InfuraNetwork.Mainnet); var ensService = web3.Eth.GetEnsService(); var txn = await ensService.SetTextRequestAsync("nethereum.eth", TextDataKey.url, "https://nethereum.com"); } [Fact] public async void ShouldBeAbleToResolveText() { var web3 = _ethereumClientIntegrationFixture.GetInfuraWeb3(InfuraNetwork.Mainnet); var ensService = web3.Eth.GetEnsService(); var url = await ensService.ResolveTextAsync("nethereum.eth", TextDataKey.url); Assert.Equal("https://nethereum.com", url); } [Fact] public async void ShouldBeAbleToCalculateRentPriceAndCommitment() { var durationInDays = 365; var ourName = "supersillynameformonkeys"; var tls = "eth"; var owner = "0x12890D2cce102216644c59daE5baed380d84830c"; var secret = "animals in the forest"; var web3 = _ethereumClientIntegrationFixture.GetInfuraWeb3(InfuraNetwork.Mainnet); var ethTLSService = web3.Eth.GetEnsEthTlsService(); await ethTLSService.InitialiseAsync(); var price = await ethTLSService.CalculateRentPriceInEtherAsync(ourName, durationInDays); Assert.True(price > 0); var commitment = await ethTLSService.CalculateCommitmentAsync(ourName, owner, secret); Assert.Equal("0x546d078db03381f4a33a33600cf1b91e00815b572c944f4a19624c8d9aaa9c14", commitment.ToHex(true)); } [Fact] public async void ShouldFindEthControllerFromMainnet() { var web3 = _ethereumClientIntegrationFixture.GetInfuraWeb3(InfuraNetwork.Mainnet); var ethTLSService = web3.Eth.GetEnsEthTlsService(); await ethTLSService.InitialiseAsync(); var controllerAddress = ethTLSService.TLSControllerAddress; Assert.True("0x283Af0B28c62C092C9727F1Ee09c02CA627EB7F5".IsTheSameAddress(controllerAddress)); } [Fact] public async void ShouldResolveAddressFromMainnet() { var web3 = _ethereumClientIntegrationFixture.GetInfuraWeb3(InfuraNetwork.Mainnet); var ensService = web3.Eth.GetEnsService(); var theAddress = await ensService.ResolveAddressAsync("nick.eth"); var expectedAddress = "0xb8c2C29ee19D8307cb7255e1Cd9CbDE883A267d5"; Assert.True(expectedAddress.IsTheSameAddress(theAddress)); } //Food for thought, a simple CID just using IPFS Base58 Defaulting all other values / Swarm [Fact] public async void ShouldRetrieveTheContentHashAndDecodeIt() { var web3 = _ethereumClientIntegrationFixture.GetInfuraWeb3(InfuraNetwork.Mainnet); var ensService = web3.Eth.GetEnsService(); var content = await ensService.GetContentHashAsync("3-7-0-0.web3.nethereum.dotnet.netdapps.eth"); var storage = content[0]; //This depends on IPLD.ContentIdentifier, Multiformats Hash and Codec if (storage == 0xe3) // if storage is IPFS { //We skip 2 storage ++ var cid = IPLD.ContentIdentifier.Cid.Cast(content.Skip(2).ToArray()); var decoded = cid.Hash.B58String(); Assert.Equal("QmRZiL8WbAVQMF1715fhG3b4x9tfGS6hgBLPQ6KYfKzcYL", decoded); } } [Fact] public async void ShouldCreateContentIPFSHash() { var multihash = Multihash.FromB58String("QmRZiL8WbAVQMF1715fhG3b4x9tfGS6hgBLPQ6KYfKzcYL"); var cid = new IPLD.ContentIdentifier.Cid(MulticodecCode.MerkleDAGProtobuf, multihash); var ipfsStoragePrefix = new byte[] {0xe3, 0x01}; var fullContentHash = ipfsStoragePrefix.Concat(cid.ToBytes()).ToArray(); var web3 = _ethereumClientIntegrationFixture.GetInfuraWeb3(InfuraNetwork.Mainnet); var ensService = web3.Eth.GetEnsService(); var content = await ensService.GetContentHashAsync("3-7-0-0.web3.nethereum.dotnet.netdapps.eth"); //e301017012202febb4a7c84c8079f78844e50150d97ad33e2a3a0d680d54e7211e30ef13f08d Assert.Equal(content.ToHex(), fullContentHash.ToHex()); } //[Fact] public async void ShouldSetSubnodeExample() { var web3 = _ethereumClientIntegrationFixture.GetInfuraWeb3(InfuraNetwork.Mainnet); var ensService = web3.Eth.GetEnsService(); var txn = await ensService.SetSubnodeOwnerRequestAsync("yoursupername.eth", "subdomainName", "addressOwner"); } [Fact] public async void ShouldReverseResolveAddressFromMainnet() { var web3 = _ethereumClientIntegrationFixture.GetInfuraWeb3(InfuraNetwork.Mainnet); var ensService = web3.Eth.GetEnsService(); var name = await ensService.ReverseResolveAsync("0xd1220a0cf47c7b9be7a2e6ba89f429762e7b9adb"); var expectedName = "alex.vandesande.eth"; Assert.Equal(expectedName, name); } } }
44.46875
119
0.678285
[ "MIT" ]
GitHubPang/Nethereum
tests/Nethereum.Contracts.IntegrationTests/SmartContracts/Standards/ENSTests.cs
7,117
C#
// Project: Daggerfall Tools For Unity // Copyright: Copyright (C) 2009-2016 Daggerfall Workshop // Web Site: http://www.dfworkshop.net // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/Interkarma/daggerfall-unity // Original Author: Gavin Clayton (interkarma@dfworkshop.net) // Contributors: // // Notes: // #region Using Statements using System; using System.Collections.Generic; using System.Text; using System.IO; using DaggerfallConnect.Utility; #endregion namespace DaggerfallConnect.Arena2 { /// <summary> /// Connects to DAGGER.SND to enumerate and extract sound data. /// </summary> public class SndFile { #region Class Variables public const int SampleRate = 11025; /// <summary> /// Auto-discard behaviour enabled or disabled. /// </summary> private bool autoDiscardValue = true; /// <summary> /// The last record opened. Used by auto-discard logic. /// </summary> private int lastSound = -1; /// <summary> /// The BsaFile representing DAGGER.SND. /// </summary> private BsaFile bsaFile = new BsaFile(); /// <summary> /// Array of decomposed sound records. /// </summary> internal SoundRecord[] sounds; #endregion #region Class Structures /// <summary> /// Represents a single sound record. /// </summary> internal struct SoundRecord { public FileProxy MemoryFile; public DFSound DFSound; } #endregion #region Public Properties /// <summary> /// If true then decomposed sound records will be destroyed every time a different sound is fetched. /// If false then decomposed sound records will be maintained until DiscardRecord() or DiscardAllRecords() is called. /// Turning off auto-discard will speed up sound retrieval times at the expense of RAM. For best results, disable /// auto-discard and impose your own caching scheme based on your application needs. /// </summary> public bool AutoDiscard { get { return autoDiscardValue; } set { autoDiscardValue = value; } } /// <summary> /// Number of BSA records in DAGGER.SND. /// </summary> public int Count { get { return bsaFile.Count; } } /// <summary> /// BSA file for sound effects. /// </summary> public BsaFile BsaFile { get { return bsaFile; } } #endregion #region Static Properties /// <summary> /// Gets default DAGGER.SND filename. /// </summary> static public string Filename { get { return "DAGGER.SND"; } } #endregion #region Constructors /// <summary> /// Default constructor. /// </summary> public SndFile() { } /// <summary> /// Load constructor. /// </summary> /// <param name="filePath">Absolute path to DAGGER.SND.</param> /// <param name="usage">Determines if the BSA file will read from disk or memory.</param> /// <param name="readOnly">File will be read-only if true, read-write if false.</param> public SndFile(string filePath, FileUsage usage, bool readOnly) { Load(filePath, usage, readOnly); } #endregion #region Public Methods /// <summary> /// Gets index of sound record with specified id. /// </summary> /// <param name="id">ID of mesh.</param> /// <returns>Index of sound if located, or -1 if not found.</returns> public int GetRecordIndex(uint id) { // Otherwise find and store index by searching for id for (int i = 0; i < Count; i++) { if (bsaFile.GetRecordId(i) == id) return i; } return -1; } /// <summary> /// Load DAGGER.SND file. /// </summary> /// <param name="filePath">Absolute path to DAGGER.SND file.</param> /// <param name="usage">Specify if file will be accessed from disk, or loaded into RAM.</param> /// <param name="readOnly">File will be read-only if true, read-write if false.</param> /// <returns>True if successful, otherwise false.</returns> public bool Load(string filePath, FileUsage usage, bool readOnly) { // Validate filename if (!filePath.EndsWith("DAGGER.SND", StringComparison.InvariantCultureIgnoreCase)) return false; // Load file if (!bsaFile.Load(filePath, usage, readOnly)) return false; // Create records array sounds = new SoundRecord[bsaFile.Count]; return true; } /// <summary> /// Get a sound from index. /// </summary> /// <param name="sound">SoundEffect.</param> /// <param name="soundOut">Sound data out.</param> /// <returns>True if successful.</returns> public bool GetSound(int sound, out DFSound soundOut) { soundOut = new DFSound(); if (sound < 0 || sound >= bsaFile.Count) return false; // Just return sound if already loaded if (sounds[sound].DFSound.WaveHeader != null && sounds[sound].DFSound.WaveData != null) { soundOut = sounds[sound].DFSound; return true; } // Discard previous sound if (AutoDiscard == true && lastSound != -1) { DiscardSound(lastSound); } // Load sound data sounds[sound].MemoryFile = bsaFile.GetRecordProxy(sound); if (sounds[sound].MemoryFile == null) return false; // Attempt to read sound ReadSound(sound); soundOut = sounds[sound].DFSound; return true; } /// <summary> /// Helper method to get an entire WAV file in a memory stream. /// </summary> /// <param name="sound">Sound index.</param> /// <returns>Wave file in MemoryStream.</returns> public MemoryStream GetStream(int sound) { // Get sound DFSound dfSound; GetSound(sound, out dfSound); if (dfSound.WaveHeader == null || dfSound.WaveData == null) { return null; } // Create stream byte[] data = new byte[dfSound.WaveHeader.Length + dfSound.WaveData.Length]; MemoryStream ms = new MemoryStream(data); // Write header and data BinaryWriter writer = new BinaryWriter(ms); writer.Write(dfSound.WaveHeader); writer.Write(dfSound.WaveData); // Reset start position in stream ms.Position = 0; return ms; } /// <summary> /// Discard a sound from memory. /// </summary> /// <param name="sound">Index of sound to discard.</param> public void DiscardSound(int sound) { // Validate if (sound >= bsaFile.Count) return; // Discard memory files and other data if (sounds[sound].MemoryFile != null) sounds[sound].MemoryFile.Close(); sounds[sound].MemoryFile = null; sounds[sound].DFSound = new DFSound(); } #endregion #region Readers /// <summary> /// Read a sound. /// </summary> /// <param name="sound">Sound index.</param> private bool ReadSound(int sound) { try { CreatePcmHeader(sound); ReadWaveData(sound); } catch (Exception e) { DiscardSound(sound); Console.WriteLine(e.Message); return false; } return true; } /// <summary> /// Reads wave data for the sound. /// </summary> /// <param name="sound">Sound index.</param> private void ReadWaveData(int sound) { // The entire BSA record is just raw sound bytes sounds[sound].DFSound.Name = sounds[sound].MemoryFile.FileName; sounds[sound].DFSound.WaveData = sounds[sound].MemoryFile.Buffer; } /// <summary> /// Creates a PCM header for the sound, including the DATA prefix preceding raw sound bytes. /// </summary> /// <param name="sound">Sound index.</param> private void CreatePcmHeader(int sound) { Int32 headerLength = 44; Int32 dataLength = sounds[sound].MemoryFile.Length; Int32 fileLength = dataLength + 36; String sRIFF = "RIFF"; String sWAVE = "WAVE"; String sFmtID = "fmt "; String sDataID = "data"; Int32 nFmtLength = 16; Int16 nFmtFormat = 1; Int16 nFmtChannels = 1; Int32 nFmtSampleRate = 11025; Int32 nFmtAvgBytesPerSec = 11025; Int16 nFmtBlockAlign = 1; Int16 nFmtBitsPerSample = 8; // Create header bytes byte[] header = new byte[headerLength]; // Create memory stream and writer MemoryStream ms = new MemoryStream(header); BinaryWriter writer = new BinaryWriter(ms); // Write the RIFF tag and file length writer.Write(sRIFF.ToCharArray()); writer.Write((Int32)fileLength); // Write the WAVE tag and fmt header writer.Write(sWAVE.ToCharArray()); writer.Write(sFmtID.ToCharArray()); // Write fmt information writer.Write(nFmtLength); writer.Write(nFmtFormat); writer.Write(nFmtChannels); writer.Write(nFmtSampleRate); writer.Write(nFmtAvgBytesPerSec); writer.Write(nFmtBlockAlign); writer.Write(nFmtBitsPerSample); // Write PCM data prefix writer.Write(sDataID.ToCharArray()); writer.Write(dataLength); // Close writer writer.Close(); // Assign header to sound sounds[sound].DFSound.WaveHeader = header; } #endregion } }
30.097222
126
0.534656
[ "MIT" ]
InconsolableCellist/daggerfall-unity
Assets/Scripts/API/SndFile.cs
10,837
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Kujikatsu102.Algorithms; using Kujikatsu102.Collections; using Kujikatsu102.Numerics; using Kujikatsu102.Questions; using Kujikatsu102.Graphs; namespace Kujikatsu102.Questions { /// <summary> /// https://atcoder.jp/contests/apc001/tasks/apc001_e /// </summary> public class QuestionG : AtCoderQuestionBase { public override void Solve(IOManager io) { var n = io.ReadInt(); var graph = new BasicGraph(n); var degrees = new int[n]; for (int i = 0; i < n - 1; i++) { var a = io.ReadInt(); var b = io.ReadInt(); graph.AddEdge(new BasicEdge(a, b)); graph.AddEdge(new BasicEdge(b, a)); degrees[a]++; degrees[b]++; } for (int i = 0; i < degrees.Length; i++) { if (degrees[i] > 2) { var result = Dfs(i, -1); io.WriteLine(result); return; } } io.WriteLine(1); int Dfs(int current, int parent) { var children = 0; var antennas = 0; var antennaBranches = 0; foreach (var edge in graph[current]) { var next = edge.To.Index; if (next == parent) { continue; } children++; var an = Dfs(next, current); antennas += an; if (an > 0) { antennaBranches++; } } if (children > antennaBranches + 1) { antennas += children - (antennaBranches + 1); } return antennas; } } } }
26.011905
65
0.430664
[ "MIT" ]
terry-u16/AtCoder
Kujikatsu102/Kujikatsu102/Kujikatsu102/Questions/QuestionG.cs
2,187
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace ORM.Initiator.Helpers { public static class TypeResolver { public static Type FindType(string assembly, string fullTypeName) { string typeQualifiedName = Assembly.CreateQualifiedName( assembly, fullTypeName); return Type.GetType(typeQualifiedName); } } }
23.894737
73
0.678414
[ "Apache-2.0" ]
nickun/orm_initiator
ORM.Initiator/Helpers/TypeResolver.cs
456
C#
using SRQH.Domain.Entities.Base; namespace SRQH.Domain.Entities.BookingFlow { public class Booking : BaseEntity { public Customer Customer { get; set; } public Room Room { get; set; } public BookingPeriod BookingPeriod { get; set; } public DiscountRule DiscountRule { get; set; } public Booking(Customer customer, Room room, BookingPeriod bookingPeriod, DiscountRule discountRule) : base() { Customer = customer; Room = room; BookingPeriod = bookingPeriod; DiscountRule = discountRule; } } }
29.095238
117
0.621931
[ "MIT" ]
JaymeAlves/SRQH
SRQH/SRQH.Domain/Entities/BookingFlow/Booking.cs
613
C#
/* * PROJECT: Atomix Development * LICENSE: BSD 3-Clause (LICENSE.md) * PURPOSE: Ldind_U2 MSIL * PROGRAMMERS: Aman Priyadarshi (aman.eureka@gmail.com) */ using System; using System.Reflection; using Atomixilc.Machine; using Atomixilc.Attributes; namespace Atomixilc.IL { [ILImpl(ILCode.Ldind_U2)] internal class Ldind_U2_il : MSIL { public Ldind_U2_il() : base(ILCode.Ldind_U2) { } /* * URL : https://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.Ldind_U2(v=vs.110).aspx * Description : Loads a value of type unsigned int16 as an int32 onto the evaluation stack indirectly. */ internal override void Execute(Options Config, OpCodeType xOp, MethodBase method, Optimizer Optimizer) { if (Optimizer.vStack.Count < 1) throw new Exception("Internal Compiler Error: vStack.Count < 1"); /* The stack transitional behavior, in sequential order, is: * An address is pushed onto the stack. * The address is popped from the stack; the value located at the address is fetched. * The fetched value is pushed onto the stack. */ var item = Optimizer.vStack.Pop(); switch (Config.TargetPlatform) { case Architecture.x86: { if (!item.SystemStack) throw new Exception(string.Format("UnImplemented-RegisterType '{0}'", msIL)); Ldind_I_il.Executex86(2, false); } break; default: throw new Exception(string.Format("Unsupported target platform '{0}' for MSIL '{1}'", Config.TargetPlatform, msIL)); } Optimizer.vStack.Push(new StackItem(typeof(uint))); Optimizer.SaveStack(xOp.NextPosition); } } }
33.754098
137
0.55221
[ "BSD-3-Clause" ]
CatGirlsAreLife/AtomOS
src/Compiler/Atomixilc/IL/Load/Ldind/Ldind_U2.cs
2,061
C#
namespace DapperExtensionsReloaded.Predicates { /// <summary> /// Comparison operator for predicates. /// </summary> public enum Operator { /// <summary> /// Equal to /// </summary> Eq, /// <summary> /// Greater than /// </summary> Gt, /// <summary> /// Greater than or equal to /// </summary> Ge, /// <summary> /// Less than /// </summary> Lt, /// <summary> /// Less than or equal to /// </summary> Le, /// <summary> /// Like (You can use % in the value to do wilcard searching) /// </summary> Like } }
19.052632
69
0.428177
[ "MIT" ]
MisterGoodcat/Dapper-Extensions
DapperExtensionsReloaded/Predicates/Operator.cs
724
C#
using NLog; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace CommonUtil.Core; public class KeywordResult { /// <summary> /// 文件路径 /// </summary> public string File { get; set; } = string.Empty; } public class KeywordFinder { private static readonly int ThreadCount = 16; private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); public string SearchDirectory { get; private set; } public List<string> ExcludeDirectoryRegexes { get; private set; } public List<string> ExcludeFileRegexes { get; private set; } private readonly IDictionary<string, string> FileDataDict = new Dictionary<string, string>(); /// <summary> /// /// </summary> /// <param name="searchDirectory">搜索目录</param> /// <param name="excludeDirectoryRegexes">排除目录正则</param> /// <param name="excludeFileRegexes">排除文件正则</param> public KeywordFinder(string searchDirectory, List<string>? excludeDirectoryRegexes = null, List<string>? excludeFileRegexes = null) { SearchDirectory = searchDirectory; ExcludeDirectoryRegexes = excludeDirectoryRegexes ?? new List<string>(); ExcludeFileRegexes = excludeFileRegexes ?? new List<string>(); FileDataDict = GetFileData(FilterFiles(SearchDirectory, ExcludeDirectoryRegexes, ExcludeFileRegexes)); } /// <summary> /// 获取文件所有内容 /// </summary> /// <param name="files"></param> /// <returns></returns> private Dictionary<string, string> GetFileData(List<string> files) { var dataList = new Dictionary<string, string>(); int perThreadCount = (int)Math.Ceiling(files.Count / (double)ThreadCount); var tasks = new List<Task>(ThreadCount); // 文件总数小于等于线程数 if (files.Count <= ThreadCount) { foreach (var file in files) { tasks.Add(Task.Factory.StartNew(() => { try { lock (this) { dataList[file] = File.ReadAllText(file); } } catch (Exception e) { Logger.Error(e); } })); } } else { for (int i = 0; i < ThreadCount; i++) { int tempI = i; tasks.Add(Task.Factory.StartNew(() => { for (int j = tempI * perThreadCount; j < Math.Min(files.Count, (tempI + 1) * perThreadCount); j++) { try { lock (this) { dataList[files[j]] = File.ReadAllText(files[j]); } } catch (Exception e) { Logger.Error(e); } } })); } } Task.WaitAll(tasks.ToArray()); return dataList; } /// <summary> /// 查找关键字 /// </summary> /// <param name="keywordRegex">查找的正则</param> /// <param name="results"></param> /// <returns></returns> public void FindKeyword(string keywordRegex, List<string> excludeDirs, List<string> excludeFiles, ObservableCollection<KeywordResult> results) { // 加载必要文件 var dict = GetFileData(FilterFiles(SearchDirectory, excludeDirs, excludeFiles)); foreach (var item in dict) { FileDataDict[item.Key] = item.Value; } var re = new Regex(keywordRegex, RegexOptions.IgnoreCase | RegexOptions.ECMAScript); var tasks = new List<Task>(ThreadCount); // 线程集合 var keyList = new List<List<string>>(ThreadCount); // 线程进行处理的数据 var filterKeys = FilterDirectoryFiles(excludeDirs, excludeFiles).ToArray(); int perThreadCount = (int)Math.Ceiling(filterKeys.Length / (double)ThreadCount); // 每个线程进行处理的数据数目 App.Current.Dispatcher.Invoke(() => results.Clear()); // 初始化集合 for (int i = 0; i < ThreadCount; i++) { keyList.Add(new()); } // 拆分集合 if (filterKeys.Length <= ThreadCount) { for (int i = 0; i < filterKeys.Length; i++) { keyList[i].Add(filterKeys[i]); } } else { for (int i = 0; i < ThreadCount; i++) { keyList[i] = filterKeys[Math.Min(i * perThreadCount, filterKeys.Length)..Math.Min((i + 1) * perThreadCount, filterKeys.Length)].ToList(); } } // 查找 foreach (var list in keyList) { Task task = Task.Factory.StartNew(() => { foreach (var file in list) { if (re.IsMatch(FileDataDict[file])) { lock (this) { App.Current.Dispatcher.Invoke(() => results.Add(new() { File = file })); } } } }); tasks.Add(task); } Task.WaitAll(tasks.ToArray()); } /// <summary> /// 筛选目录和文件 /// </summary> /// <param name="excludeDirs"></param> /// <param name="excludeFiles"></param> /// <returns></returns> private List<string> FilterDirectoryFiles(List<string> excludeDirs, List<string> excludeFiles) { List<Regex> excludeFileRegexes = CompileRegex(excludeFiles); List<Regex> excludeDirRegexes = CompileRegex(excludeDirs); var tempFiles = new List<string>(); var tempFiles2 = new List<string>(); // 筛选目录 foreach (var file in FileDataDict.Keys) { bool found = false; foreach (var regex in excludeDirRegexes) { if (regex.IsMatch(GetRelativeDirectory(SearchDirectory, file))) { found = true; break; } } if (!found) { tempFiles.Add(file); } } // 筛选查找文件 foreach (var file in tempFiles) { bool found = false; foreach (var regex in excludeFileRegexes) { if (regex.IsMatch(file)) { found = true; break; } } if (!found) { tempFiles2.Add(file); } } return tempFiles2; } /// <summary> /// 筛选文件 /// </summary> /// <param name="directory"></param> /// <param name="excludeDirectoryRegex"></param> /// <param name="excludeFileRegex"></param> /// <returns></returns> private List<string> FilterFiles(string directory, List<string> excludeDirectoryRegex, List<string> excludeFileRegex) { var files = new List<string>(); var results = new List<string>(); // 编译正则 var excludeDirs = CompileRegex(excludeDirectoryRegex); var excludeFiles = CompileRegex(excludeFileRegex); GetAllFiles(directory, files, excludeDirs); // 获取所有文件 // 排除文件 foreach (var f in files) { bool found = false; foreach (var regex in excludeFiles) { if (regex.IsMatch(f)) { found = true; break; } } // 不匹配并且没有加载过 if (!found && !FileDataDict.ContainsKey(f)) { results.Add(f); } } return results; } /// <summary> /// 编译正则 /// </summary> /// <param name="regexes"></param> /// <returns></returns> private List<Regex> CompileRegex(List<string> regexes) { var results = new List<Regex>(); foreach (var item in regexes) { results.Add(new Regex(item, RegexOptions.IgnoreCase | RegexOptions.ECMAScript)); } return results; } /// <summary> /// 获取文件夹下所有的文件 /// </summary> /// <param name="directory"></param> /// <param name="files"></param> private void GetAllFiles(string directory, List<string> files, List<Regex> excludeDir = null) { files.AddRange(Directory.GetFiles(directory)); excludeDir ??= new List<Regex>(); foreach (var dir in Directory.GetDirectories(directory)) { bool found = false; foreach (var regex in excludeDir) { if (regex.IsMatch(dir)) { Logger.Debug($"excluded: {dir}"); found = true; break; } } if (!found) { GetAllFiles(dir, files, excludeDir); } } } /// <summary> /// 获取相对路径文件夹 /// </summary> /// <param name="directory"></param> /// <param name="file"></param> /// <returns></returns> private string GetRelativeDirectory(string directory, string file) { directory = directory.Replace("\\", "/").TrimEnd('/'); file = file.Replace("\\", "/"); return file[directory.Length..file.LastIndexOf('/')]; } }
36.184
153
0.531616
[ "MIT" ]
Luxiu123/CommonUtil
CommonUtil/Core/KeywordFinder.cs
9,370
C#
//----------------------------------------------------------------------- // <copyright file="Repository.cs" company="QJJS"> // Copyright QJJS. All rights reserved. // </copyright> // <author>liyuhang</author> // <date>2021/9/1 13:53:58</date> //----------------------------------------------------------------------- using FastHttpApi.Entity.Base; using FastHttpApi.Schema.Base; using Mapster; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Driver; using MongoDB.Driver.Core.Events; using MongoDB.Driver.Linq; using Serilog; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace FastHttpApi.Repository { public class Repository<TEntity> : IRepository<TEntity> where TEntity : BaseEntity { public IMongoQueryable<TEntity> QueryData() => GetCollection().AsQueryable(); public IMongoCollection<TEntity> GetCollection() { string tableName = BsonClassMap.LookupClassMap(typeof(TEntity)).Discriminator; var client = GetClient(AppSettings.MongoConnection, AppSettings.ShowMongoLog); var database = client.GetDatabase(AppSettings.MongoDatabase); return database.GetCollection<TEntity>(tableName); } public async Task<TModel> Get<TModel>(Expression<Func<TEntity, bool>> filter) { return (await GetCollection().Find(filter).SingleOrDefaultAsync()).Adapt<TModel>(); } public async Task<IList<TModel>> List<TModel>(Expression<Func<TEntity, bool>> filter) { return (await GetCollection().Find(filter).ToListAsync()).Adapt<IList<TModel>>(); } public async Task<IList<TModel>> List<TModel>() { return (await GetCollection().Find(Builders<TEntity>.Filter.Empty).ToListAsync()).Adapt<IList<TModel>>(); } public async Task<IList<TModel>> ListByIds<TModel>(IList<string> ids) { var builderFilter = Builders<TEntity>.Filter; var query = builderFilter.In(x => x.Id, ids); return ((await GetCollection().FindAsync(query)).ToList()).Adapt<IList<TModel>>(); } public PageResultModel<TModel> PageData<TModel>(Expression<Func<TEntity, bool>> filter, PageQueryModel pageQuery) { var pageResult = new PageResultModel<TModel> { TotalCount = QueryData().Count(), PageIndex = pageQuery.PageIndex, PageSize = pageQuery.PageSize, }; List<TEntity> list; if (filter != null) { list = QueryData().Where(filter).Skip(pageQuery.PageSize * (pageQuery.PageIndex - 1)).Take(pageQuery.PageSize).ToList(); } else { list = QueryData().Skip(pageQuery.PageSize * (pageQuery.PageIndex - 1)).Take(pageQuery.PageSize).ToList(); } pageResult.Data = list.Adapt<IList<TModel>>(); return pageResult; } public async Task<long> Count(Expression<Func<TEntity, bool>> filter) { return await GetCollection().CountDocumentsAsync(filter); } public async Task<TModel> Save<TModel>(TModel model) { var t = model.Adapt<TEntity>(); t.DataStatus = true; t.CreateAt = DateTime.Now; t.UpdateAt = DateTime.Now; await GetCollection().InsertOneAsync(t); return t.Adapt<TModel>(); } public async Task<TModel> Update<TModel>(TModel model) { var t = model.Adapt<TEntity>(); t.DataStatus = true; t.UpdateAt = DateTime.Now; var filter = Builders<TEntity>.Filter.Eq(x => x.Id, t.Id); await GetCollection().ReplaceOneAsync(filter, t, new ReplaceOptions() { IsUpsert = false }); return t.Adapt<TModel>(); } public async Task<long> Delete(Expression<Func<TEntity, bool>> filter) { var d = await GetCollection().DeleteManyAsync(filter); return d.DeletedCount; } private MongoClient GetClient(string dbPath, bool showlog) { var mongoConnectionUrl = new MongoUrl(dbPath); var mongoClientSettings = MongoClientSettings.FromUrl(mongoConnectionUrl); if (showlog) { mongoClientSettings.ClusterConfigurator = cb => { cb.Subscribe<CommandStartedEvent>(e => { Log.ForContext<Repository<TEntity>>().Debug($"[mongodb] {e.CommandName} - {e.Command.ToJson()}"); }); }; } return new MongoClient(mongoClientSettings); } } }
36.335821
136
0.577531
[ "MIT" ]
ydfk/dotnet5-starter
src/Repository/Repository.cs
4,871
C#
namespace OpenMinesweeper.NET { /// <summary> /// Interaction logic for AboutWindow.xaml /// </summary> public partial class AboutWindow { public AboutWindow() { InitializeComponent(); } } }
18
46
0.555556
[ "MIT" ]
Fe-Bell/OpenMinesweeper
OpenMinesweeper.NET/AboutWindow.xaml.cs
254
C#
using System; namespace Deltix.Luminary { /// <summary>Represents the builtin Luminary type <c>Type</c>.</summary> public sealed class TypeType : Type, IEquatable<TypeType> { private TypeType() : base(TypeKind.Type) {} /// <summary>Singleton describing the builtin Luminary type <c>Type</c>.</summary> public static readonly TypeType Instance = new TypeType(); /// <summary>Serves as the default hash function.</summary> /// <returns>A hash code for the current object.</returns> public override Int32 GetHashCode() => base.GetHashCode(); /// <summary>Determines whether the specified object is equal to the current object.</summary> /// <returns><c>true</c>if the specified object is equal to the current object; otherwise, <c>false</c>.</returns> /// <param name="obj">The object to compare with the current object. </param> public override Boolean Equals(Object obj) => Equals(obj as TypeType); /// <summary>Indicates whether the current object is equal to another object of the same type.</summary> /// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns> /// <param name="other">An object to compare with this object.</param> public Boolean Equals(TypeType other) => other != null; /// <summary>Returns a string that represents the current object.</summary> /// <returns>A string that represents the current object.</returns> public override String ToString() => "Type"; } }
43.941176
122
0.715529
[ "Apache-2.0" ]
DeltixInc/Luminary
csharp/main/TypeType.cs
1,496
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using NTracer.Communication; using NTracer.Server.Core.Repositories; using NTracer.Server.Core.Sink.Run; namespace NTracer.Server.Core { public class SinkSource : IRemoteService, ISinkSource { public event Action<ScopeEventWithConnectionData<OpenScopeEvent>> OpenScopeEventAdded; public event Action<ScopeEventWithConnectionData<CloseScopeEvent>> CloseScopeEventAdded; public event Action<ScopeEventWithConnectionData<SetPropertyEvent>> SetPropertyScopeEventAdded; public event Action<ScopeEventWithConnectionData<LogEvent>> LogScopeEventAdded; private readonly IConnectionRepository _connectionRepository; public SinkSource(IConnectionRepository connectionRepository) { _connectionRepository = connectionRepository; } public async Task SendBatch(ScopeEventsFromConnection eventsFromConnection) { var connectionData = _connectionRepository.GetConnectionDataById(eventsFromConnection.ConnectionId); DoEventProcessing(OpenScopeEventAdded, eventsFromConnection.OpenScopeEvents, connectionData); DoEventProcessing(CloseScopeEventAdded, eventsFromConnection.CloseScopeEvents, connectionData); DoEventProcessing(SetPropertyScopeEventAdded, eventsFromConnection.SetPropertyScopeEvents, connectionData); DoEventProcessing(LogScopeEventAdded, eventsFromConnection.LogScopeEvents, connectionData); } public Task<string> Connect(ConnectionData connection) { var connectionId = _connectionRepository.AddConnection(connection); return Task.FromResult(connectionId); } private static void DoEventProcessing<T>(Action<ScopeEventWithConnectionData<T>> @event, IEnumerable<T> collection, ConnectionData connectionData) where T : ScopeEvent { if(@event != null) foreach (var item in collection) { @event(new ScopeEventWithConnectionData<T>(item, connectionData)); } } } }
44.367347
119
0.727231
[ "Apache-2.0" ]
vikingkom/n-tracer
NTracer.Server.Core/SinkSource.cs
2,176
C#
namespace EnvironmentAssessment.Common.VimApi { public class ServiceLocatorNamePassword : ServiceLocatorCredential { protected string _username; protected string _password; public string Username { get { return this._username; } set { this._username = value; } } public string Password { get { return this._password; } set { this._password = value; } } } }
13.806452
67
0.647196
[ "MIT" ]
octansIt/environmentassessment
EnvironmentAssessment.Wizard/Common/VimApi/S/ServiceLocatorNamePassword.cs
428
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace HenloWorl.Controllers { public class HenloController : Controller { // GET: HenloController public ActionResult Index() { return View(); } // GET: HenloController/Details/5 public ActionResult Details(int id) { return View(); } // GET: HenloController/Create public ActionResult Create() { return View(); } // POST: HenloController/Create [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(IFormCollection collection) { try { return RedirectToAction(nameof(Index)); } catch { return View(); } } // GET: HenloController/Edit/5 public ActionResult Edit(int id) { return View(); } // POST: HenloController/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(int id, IFormCollection collection) { try { return RedirectToAction(nameof(Index)); } catch { return View(); } } // GET: HenloController/Delete/5 public ActionResult Delete(int id) { return View(); } // POST: HenloController/Delete/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Delete(int id, IFormCollection collection) { try { return RedirectToAction(nameof(Index)); } catch { return View(); } } } }
22.409091
70
0.495943
[ "MIT" ]
2006-jun15-net/william-code
HTML/HenloWorl/HenloWorl/Controllers/HenloController.cs
1,974
C#
using Application.DTOs.Account; using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.Text; namespace Infrastructure.Identity.Models { public class ApplicationRole : IdentityRole<int> { } }
19.076923
52
0.774194
[ "MIT" ]
mrbol/desafio_aspnetcore
Infrastructure.Identity/Models/ApplicationRole.cs
250
C#
using System; using System.Globalization; namespace Uri1060 { class Program { static void Main(string[] args) { double num1 = double.Parse(Console.ReadLine(),CultureInfo.InvariantCulture); double num2 = double.Parse(Console.ReadLine(),CultureInfo.InvariantCulture); double num3 = double.Parse(Console.ReadLine(),CultureInfo.InvariantCulture); double num4 = double.Parse(Console.ReadLine(),CultureInfo.InvariantCulture); double num5 = double.Parse(Console.ReadLine(),CultureInfo.InvariantCulture); double num6 = double.Parse(Console.ReadLine(),CultureInfo.InvariantCulture); double aux = 0; if(num1 > 0) { aux = aux += 1; } if(num2 > 0){ aux = aux += 1; } if(num3 > 0) { aux = aux += 1; } if(num4 > 0) { aux = aux += 1; } if(num5 > 0) { aux = aux += 1; } if(num6 > 0) { aux = aux += 1; } Console.WriteLine(aux + " valores positivos"); Console.ReadKey(); } } }
29.952381
88
0.483307
[ "MIT" ]
cledson-paranhos/Exercicios-Curso-CSharp
Lógica/Uri1060/Uri1060/Program.cs
1,260
C#