content
stringlengths
23
1.05M
 using Content.Shared.GameObjects.Components; using JetBrains.Annotations; using Robust.Client.GameObjects; using System; namespace Content.Client.GameObjects.Components { [UsedImplicitly] public class ExpendableLightVisualizer : AppearanceVisualizer { public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); if (component.Deleted) { return; } if (component.TryGetData(ExpendableLightVisuals.State, out string lightBehaviourID)) { if (component.Owner.TryGetComponent<LightBehaviourComponent>(out var lightBehaviour)) { lightBehaviour.StopLightBehaviour(); if (lightBehaviourID != string.Empty) { lightBehaviour.StartLightBehaviour(lightBehaviourID); } else if (component.Owner.TryGetComponent<PointLightComponent>(out var light)) { light.Enabled = false; } } } } } }
using System; namespace CoffeeShop { class Program { static void Main(string[] args) { var orders = int.Parse(Console.ReadLine()); var totalPrice = 0.0; for (var i = 0; i < orders; i++) { var pricePerCapsule = double.Parse(Console.ReadLine()); var days = int.Parse(Console.ReadLine()); var capsulesCount = int.Parse(Console.ReadLine()); var orderPrice = (days * capsulesCount) * pricePerCapsule; totalPrice += orderPrice; Console.WriteLine($"The price for the coffee is: ${orderPrice:F2}"); orderPrice = 0; } Console.WriteLine($"Total: ${totalPrice:F2}"); } } }
using UnityEngine; [RequireComponent(typeof(Camera))] [ExecuteInEditMode] public class PixelationPost : MonoBehaviour { public Shader _shader; [Range(0.0001f, 100.0f)] public float _cellSize = 0.025f; [Range(0, 8)] public int _colorBits = 8; private static Material mat = null; protected Material material { get { if (mat == null) { mat = new Material(_shader); mat.hideFlags = HideFlags.HideAndDontSave; } return mat; } } void OnRenderImage(RenderTexture src, RenderTexture dest) { if (_shader == null) { return; } material.SetFloat("_CellSize", _cellSize * 0.01f); material.SetFloat("_ColorBits", _colorBits); Graphics.Blit(src, dest, material); } }
using Lucene.Net.Analysis.Standard; using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.QueryParsers; using Lucene.Net.Search; using Lucene.Net.Store; using SourceBrowser.Search.DocumentFields; using SourceBrowser.Search.ViewModels; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SourceBrowser.Search { public class SearchIndex { private static string basePath = System.Web.Hosting.HostingEnvironment.MapPath("~") ?? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); private static string _luceneDir = Path.Combine(basePath, "luceneIndex"); private const int HITS_LIMIT = 100; private static FSDirectory _directory; /// <summary> /// Before doing anything with the search index, first make sure there's no existing /// write lock on the directory. (This can happen if the application crashes and restarts) /// </summary> static SearchIndex() { _directory = FSDirectory.Open(new DirectoryInfo(_luceneDir)); if (IndexWriter.IsLocked(_directory)) IndexWriter.Unlock(_directory); var lockFilePath = Path.Combine(_luceneDir, "write.lock"); if (File.Exists(lockFilePath)) File.Delete(lockFilePath); } static object _luceneWriteLock = new object(); public static void AddDeclarationsToIndex(IEnumerable<TokenViewModel> tokenModels) { lock(_luceneWriteLock) { using (var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30)) using (var writer = new IndexWriter(_directory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED)) { foreach(var tokenModel in tokenModels) { addDeclarationToIndex(writer, tokenModel); } } } } private static void addDeclarationToIndex(IndexWriter writer, TokenViewModel token) { //remove previous entry var searchQuery = new TermQuery(new Term(TokenFields.Id, token.Id)); writer.DeleteDocuments(searchQuery); //add new index entry var doc = new Document(); doc.Add(new Field(TokenFields.Id, token.Id, Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.Add(new Field(TokenFields.Path, token.Path, Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.Add(new Field(TokenFields.Username, token.Username, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field(TokenFields.Repository, token.Repository, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field(TokenFields.Name, token.DisplayName ,Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field(TokenFields.FullName, token.FullyQualifiedName, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field(TokenFields.LineNumber, token.LineNumber.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED)); writer.AddDocument(doc); } private static TokenViewModel mapDocumentToToken(Document document) { return new TokenViewModel( document.Get(TokenFields.Username), document.Get(TokenFields.Repository), document.Get(TokenFields.Path), document.Get(TokenFields.FullName), Convert.ToInt32(document.Get(TokenFields.LineNumber)) ); } private static IEnumerable<TokenViewModel> MapLuceneToDataList(IEnumerable<ScoreDoc> hits, IndexSearcher searcher) { return hits.Select(hit => mapDocumentToToken(searcher.Doc(hit.Doc))).ToList(); } private static Query parsePrefixQuery(string searchQuery, QueryParser parser) { Query query; try { query = parser.Parse(searchQuery.Trim() + "*"); } catch (ParseException) { query = parser.Parse(QueryParser.Escape(searchQuery.Trim())); } return query; } private static Query parseQuery(string searchQuery, QueryParser parser) { Query query; try { query = parser.Parse(searchQuery.Trim()); } catch (ParseException) { query = parser.Parse(QueryParser.Escape(searchQuery.Trim())); } return query; } public static IEnumerable<TokenViewModel> SearchRepository(string username, string repository, string searchQuery) { if (string.IsNullOrWhiteSpace(username)) throw new ArgumentException(nameof(username) + " must be provided."); if (string.IsNullOrWhiteSpace(repository)) throw new ArgumentException(nameof(repository) + " must be provided."); //If they send an empty query, just return nothing. if (string.IsNullOrWhiteSpace(searchQuery)) return new List<TokenViewModel>(); //Replace wild-card characters. For now we're not going to let the user //construct advanced queries unless it becomes a 'must-have' if (string.IsNullOrEmpty(searchQuery.Replace("*", "").Replace("?", ""))) return new List<TokenViewModel>(); using (var searcher = new IndexSearcher(_directory, false)) using (var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30)) { var userNameParser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, TokenFields.Username, analyzer); var usernameQuery = parseQuery(username, userNameParser); var repositoryParser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, TokenFields.Repository, analyzer); var repositoryQuery = parseQuery(repository, repositoryParser); var nameParser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, TokenFields.Name, analyzer); var nameQuery = parsePrefixQuery(searchQuery, nameParser); //Ensure that it's the user AND the repository AND the query var boolQuery = new BooleanQuery(); boolQuery.Add(usernameQuery, Occur.MUST); boolQuery.Add(repositoryQuery, Occur.MUST); boolQuery.Add(nameQuery, Occur.MUST); var hits = searcher.Search(boolQuery, HITS_LIMIT).ScoreDocs; var results = MapLuceneToDataList(hits, searcher); return results; } } } }
// Copyright © Nikola Milinkovic // Licensed under the MIT License (MIT). // See License.md in the repository root for more information. using Nuclear.ExportLocator.Decorators; using Nuclear.ExportLocator.Enumerations; using System.Collections.Generic; using System.Linq; using System.Text; namespace Nuclear.Channels.Server.Manager.Commands { [Export(typeof(ICommandExecutionResults), ExportLifetime.Singleton)] public class CommandExecutionResults : ICommandExecutionResults { private Dictionary<CommandId, object> _commandResults; public CommandExecutionResults() { _commandResults = new Dictionary<CommandId, object>(); } public void AddResult(CommandId cmdId, object result) { _commandResults.Add(cmdId, result); } public object GetResult(CommandId cmdId) { return _commandResults.FirstOrDefault(x => x.Key.Equals(cmdId)).Value; } public CommandId GetLastCommandId() { return _commandResults.Keys.Last(); } } }
namespace SunnyFarm.Services.Products { using System.Collections.Generic; using SunnyFarm.Models.Products; using SunnyFarm.Services.Products.Models; public interface IProductService { ProductQueryServiceModel All( string category, string searchTerm, ProductSorting sorting, int currentPage, int productsPerPage); ProductDetailsServiceModel Details(int id); int Create( string name, string description, string imageUrl, int categoryId, int size, decimal price, bool isAvailable); bool Edit( int id, string name, string description, string imageUrl, int categoryId, int size, decimal price, bool isAvailable); IEnumerable<string> AllProductCategories(); IEnumerable<ProductCategoryServiceModel> GetProductCategories(); bool CategoryExists(int categoryId); } }
using System; using UnityEngine; namespace CapsuleCharacterCollisionDetection { //This is a way for you to not worry about whether or not the rigidbody is Physx or our PlayerRigidbody. [RequireComponent(typeof(Rigidbody))] public class PhysXRigidbody : MonoBehaviour, IRigidbody { Rigidbody myRigidbody; void Awake() { myRigidbody = GetComponent<Rigidbody>(); } public Vector3 velocity {get {return myRigidbody.velocity;} set {myRigidbody.velocity = value;}} public void AddForce(Vector3 velocity, ForceMode forceMode = ForceMode.Force) { myRigidbody.AddForce(velocity, forceMode); } public void AddExplosionForce(float force, Vector3 position, float explosionRadius, ForceMode forceMode = ForceMode.Force) { myRigidbody.AddExplosionForce(force, position, explosionRadius, 0f, forceMode); } } }
using System; using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; using Akavache; using DynamicData; using DynamicData.Binding; using MovieList.ViewModels.Forms; using ReactiveUI; namespace MovieList.Views.Forms { public abstract class MovieSeriesFormControlBase : ReactiveUserControl<MovieSeriesFormViewModel> { } public partial class MovieSeriesFormControl : MovieSeriesFormControlBase { public MovieSeriesFormControl() { this.InitializeComponent(); this.WhenActivated(disposables => { this.WhenAnyValue(v => v.ViewModel) .BindTo(this, v => v.DataContext) .DisposeWith(disposables); this.WhenAnyObservable(v => v.ViewModel.FormTitle) .BindTo(this, v => v.FormTitleTextBlock.Text) .DisposeWith(disposables); this.LoadPoster(); this.BindCommands(disposables); this.BindCheckboxes(disposables); this.BindFields(disposables); this.OneWayBind(this.ViewModel, vm => vm.Entries, v => v.Entries.ItemsSource) .DisposeWith(disposables); this.AddValidation(disposables); }); } private void BindCommands(CompositeDisposable disposables) { var boolToVisibility = new BooleanToVisibilityTypeConverter(); const BooleanToVisibilityHint useHidden = BooleanToVisibilityHint.UseHidden; this.BindCommand(this.ViewModel, vm => vm.Save, v => v.SaveButton) .DisposeWith(disposables); this.BindCommand(this.ViewModel, vm => vm.Cancel, v => v.CancelButton) .DisposeWith(disposables); this.BindCommand(this.ViewModel, vm => vm.Close, v => v.CloseButton) .DisposeWith(disposables); this.BindCommand(this.ViewModel, vm => vm.GoToMovieSeries, v => v.GoToMovieSeriesButton) .DisposeWith(disposables); this.WhenAnyObservable(v => v.ViewModel.GoToMovieSeries.CanExecute) .BindTo(this, v => v.GoToMovieSeriesButton.Visibility, useHidden, boolToVisibility) .DisposeWith(disposables); this.BindCommand(this.ViewModel, vm => vm.GoToMovieSeries, v => v.GoToMovieSeriesArrowButton) .DisposeWith(disposables); this.WhenAnyObservable(v => v.ViewModel.GoToMovieSeries.CanExecute) .BindTo(this, v => v.GoToMovieSeriesArrowButton.Visibility, useHidden, boolToVisibility) .DisposeWith(disposables); this.BindCommand(this.ViewModel, vm => vm.GoToNext, v => v.GoToNextButton) .DisposeWith(disposables); this.WhenAnyObservable(v => v.ViewModel.GoToNext.CanExecute) .BindTo(this, v => v.GoToNextButton.Visibility, useHidden, boolToVisibility) .DisposeWith(disposables); this.BindCommand(this.ViewModel, vm => vm.GoToPrevious, v => v.GoToPreviousButton) .DisposeWith(disposables); this.WhenAnyObservable(v => v.ViewModel.GoToPrevious.CanExecute) .BindTo(this, v => v.GoToPreviousButton.Visibility, useHidden, boolToVisibility) .DisposeWith(disposables); this.BindCommand(this.ViewModel, vm => vm.AddMovie, v => v.AddMovieButton) .DisposeWith(disposables); this.WhenAnyObservable(v => v.ViewModel.AddMovie.CanExecute) .BindTo(this, v => v.AddMovieButton.Visibility, null, boolToVisibility) .DisposeWith(disposables); this.BindCommand(this.ViewModel, vm => vm.AddSeries, v => v.AddSeriesButton) .DisposeWith(disposables); this.WhenAnyObservable(v => v.ViewModel.AddSeries.CanExecute) .BindTo(this, v => v.AddSeriesButton.Visibility, null, boolToVisibility) .DisposeWith(disposables); this.BindCommand(this.ViewModel, vm => vm.AddMovieSeries, v => v.AddMovieSeriesButton) .DisposeWith(disposables); this.WhenAnyObservable(v => v.ViewModel.AddMovieSeries.CanExecute) .BindTo(this, v => v.AddMovieSeriesButton.Visibility, null, boolToVisibility) .DisposeWith(disposables); this.BindCommand(this.ViewModel, vm => vm.CreateMovieSeries, v => v.CreateMovieSeriesButton) .DisposeWith(disposables); this.WhenAnyObservable(v => v.ViewModel.CreateMovieSeries.CanExecute) .BindTo(this, v => v.CreateMovieSeriesButton.Visibility, null, boolToVisibility) .DisposeWith(disposables); this.BindCommand(this.ViewModel, vm => vm.Delete, v => v.DeleteButton) .DisposeWith(disposables); this.WhenAnyObservable(v => v.ViewModel.Delete.CanExecute) .BindTo(this, v => v.DeleteButton.Visibility, null, boolToVisibility) .DisposeWith(disposables); this.BindCommand(this.ViewModel, vm => vm.AddTitle, v => v.AddTitleButton) .DisposeWith(disposables); this.WhenAnyObservable(v => v.ViewModel.AddTitle.CanExecute) .BindTo(this, v => v.AddTitleButton.Visibility, null, boolToVisibility) .DisposeWith(disposables); this.BindCommand(this.ViewModel, vm => vm.AddOriginalTitle, v => v.AddOriginalTitleButton) .DisposeWith(disposables); this.WhenAnyObservable(v => v.ViewModel.AddOriginalTitle.CanExecute) .BindTo(this, v => v.AddOriginalTitleButton.Visibility, null, boolToVisibility) .DisposeWith(disposables); Observable.CombineLatest( this.WhenAnyObservable(v => v.ViewModel.Save.CanExecute), this.WhenAnyObservable(v => v.ViewModel.Cancel.CanExecute)) .AnyTrue() .BindTo(this, v => v.ActionPanel.Visibility, null, boolToVisibility) .DisposeWith(disposables); this.WhenAnyObservable(v => v.ViewModel.Save) .Subscribe(_ => this.LoadPoster()) .DisposeWith(disposables); } private void BindCheckboxes(CompositeDisposable disposables) { this.Bind(this.ViewModel, vm => vm.HasTitles, v => v.HasTitlesCheckBox.IsChecked) .DisposeWith(disposables); this.Bind(this.ViewModel, vm => vm.ShowTitles, v => v.ShowInListCheckBox.IsChecked) .DisposeWith(disposables); this.Bind(this.ViewModel, vm => vm.IsLooselyConnected, v => v.IsLooselyConnectedCheckBox.IsChecked) .DisposeWith(disposables); this.Bind(this.ViewModel, vm => vm.MergeDisplayNumbers, v => v.MergeDisplayNumbersCheckBox.IsChecked) .DisposeWith(disposables); this.WhenAnyValue( v => v.ViewModel.HasTitles, v => v.ViewModel.CanShowTitles, (hasTitles, canShowTitles) => hasTitles && canShowTitles) .BindTo(this, v => v.ShowInListCheckBox.IsEnabled) .DisposeWith(disposables); this.ViewModel.Entries.ToObservableChangeSet() .AutoRefresh(vm => vm.DisplayNumber) .ToCollection() .Select(vms => vms.All(vm => vm.DisplayNumber.HasValue)) .BindTo(this, v => v.IsLooselyConnectedCheckBox.IsEnabled) .DisposeWith(disposables); } private void BindFields(CompositeDisposable disposables) { this.OneWayBind(this.ViewModel, vm => vm.Titles, v => v.Titles.ItemsSource) .DisposeWith(disposables); this.OneWayBind(this.ViewModel, vm => vm.OriginalTitles, v => v.OriginalTitles.ItemsSource) .DisposeWith(disposables); var boolToVisibility = new BooleanToVisibilityTypeConverter(); this.WhenAnyValue(v => v.ViewModel.HasTitles) .BindTo(this, v => v.Titles.Visibility, null, boolToVisibility) .DisposeWith(disposables); this.WhenAnyValue(v => v.ViewModel.HasTitles) .BindTo(this, v => v.OriginalTitles.Visibility, null, boolToVisibility) .DisposeWith(disposables); this.WhenAnyValue(v => v.ViewModel.HasTitles) .BindTo(this, v => v.AddTitleButton.Visibility, null, boolToVisibility) .DisposeWith(disposables); this.WhenAnyValue(v => v.ViewModel.HasTitles) .BindTo(this, v => v.AddOriginalTitleButton.Visibility, null, boolToVisibility) .DisposeWith(disposables); this.Bind(this.ViewModel, vm => vm.PosterUrl, v => v.PosterUrlTextBox.Text) .DisposeWith(disposables); } private void AddValidation(CompositeDisposable disposables) => this.PosterUrlTextBox.ValidateWith(this.ViewModel.PosterUrlRule) .DisposeWith(disposables); private void LoadPoster() { if (!String.IsNullOrEmpty(this.ViewModel.PosterUrl)) { BlobCache.UserAccount.DownloadUrl(this.ViewModel.PosterUrl, TimeSpan.FromMinutes(5)) .Select(data => data.AsImage()) .WhereNotNull() .ObserveOnDispatcher() .BindTo(this, v => v.Poster.Source); } else { this.Poster.Source = null; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using TMS.Common; using TMS.DAL; namespace TMS.BLL { public class UserBLL { public DataTable GetAllUsersInTable() { return new DAL.UserDAL().GetAllInUsers(); } public bool updateUser(User user,string n) { return new UserDAL().updateUser(user,n); } public bool insertUser(User user) { return new UserDAL().insertUser(user); } public string checkLogin(User user) { return new DAL.UserDAL().checkLogin(user); } public bool delUser(User user) { return new UserDAL().delUser(user); } } }
using System; using System.Text.Json; using System.Text.Json.Serialization; using NBitcoin; namespace NRustLightning.Infrastructure.JsonConverters.NBitcoinTypes { public class HexPubKeyConverter : JsonConverter<PubKey> { public override PubKey Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var s = reader.GetString(); return new PubKey(s); } public override void Write(Utf8JsonWriter writer, PubKey value, JsonSerializerOptions options) { var s = value.ToHex(); writer.WriteStringValue(s); } } }
using System; using System.IO; using System.Text; using LibGit2Sharp.Tests.TestHelpers; using Xunit; namespace LibGit2Sharp.Tests { public class SetErrorFixture : BaseFixture { private const string simpleExceptionMessage = "This is a simple exception message."; private const string aggregateExceptionMessage = "This is aggregate exception."; private const string outerExceptionMessage = "This is an outer exception."; private const string innerExceptionMessage = "This is an inner exception."; private const string innerExceptionMessage2 = "This is inner exception #2."; private const string expectedInnerExceptionHeaderText = "Inner Exception:"; private const string expectedAggregateExceptionHeaderText = "Contained Exception:"; private const string expectedAggregateExceptionsHeaderText = "Contained Exceptions:"; [Fact] public void FormatSimpleException() { Exception exceptionToThrow = new Exception(simpleExceptionMessage); string expectedMessage = simpleExceptionMessage; AssertExpectedExceptionMessage(expectedMessage, exceptionToThrow); } [Fact] public void FormatExceptionWithInnerException() { Exception exceptionToThrow = new Exception(outerExceptionMessage, new Exception(innerExceptionMessage)); StringBuilder sb = new StringBuilder(); sb.AppendLine(outerExceptionMessage); sb.AppendLine(); AppendIndentedLine(sb, expectedInnerExceptionHeaderText, 0); AppendIndentedText(sb, innerExceptionMessage, 1); string expectedMessage = sb.ToString(); AssertExpectedExceptionMessage(expectedMessage, exceptionToThrow); } [Fact] public void FormatAggregateException() { Exception exceptionToThrow = new AggregateException(aggregateExceptionMessage, new Exception(innerExceptionMessage), new Exception(innerExceptionMessage2)); StringBuilder sb = new StringBuilder(); #if NETFRAMEWORK sb.AppendLine(aggregateExceptionMessage); #else sb.AppendLine($"{aggregateExceptionMessage} ({innerExceptionMessage}) ({innerExceptionMessage2})"); #endif sb.AppendLine(); AppendIndentedLine(sb, expectedAggregateExceptionsHeaderText, 0); AppendIndentedLine(sb, innerExceptionMessage, 1); sb.AppendLine(); AppendIndentedText(sb, innerExceptionMessage2, 1); string expectedMessage = sb.ToString(); AssertExpectedExceptionMessage(expectedMessage, exceptionToThrow); } private void AssertExpectedExceptionMessage(string expectedMessage, Exception exceptionToThrow) { Exception thrownException = null; ObjectId id = new ObjectId("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"); string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { repo.ObjectDatabase.AddBackend(new ThrowingOdbBackend(exceptionToThrow), priority: 1); try { repo.Lookup<Blob>(id); } catch (Exception ex) { thrownException = ex; } } Assert.NotNull(thrownException); Assert.Equal(expectedMessage, thrownException.Message); } private void AppendIndentedText(StringBuilder sb, string text, int indentLevel) { sb.AppendFormat("{0}{1}", IndentString(indentLevel), text); } private void AppendIndentedLine(StringBuilder sb, string text, int indentLevel) { sb.AppendFormat("{0}{1}{2}", IndentString(indentLevel), text, Environment.NewLine); } private string IndentString(int level) { return new string(' ', level * 4); } #region ThrowingOdbBackend private class ThrowingOdbBackend : OdbBackend { private Exception exceptionToThrow; public ThrowingOdbBackend(Exception exceptionToThrow) { this.exceptionToThrow = exceptionToThrow; } protected override OdbBackendOperations SupportedOperations { get { return OdbBackendOperations.Read | OdbBackendOperations.ReadPrefix | OdbBackendOperations.Write | OdbBackendOperations.WriteStream | OdbBackendOperations.Exists | OdbBackendOperations.ExistsPrefix | OdbBackendOperations.ForEach | OdbBackendOperations.ReadHeader; } } public override int Read(ObjectId oid, out UnmanagedMemoryStream data, out ObjectType objectType) { throw this.exceptionToThrow; } public override int ReadPrefix(string shortSha, out ObjectId id, out UnmanagedMemoryStream data, out ObjectType objectType) { throw this.exceptionToThrow; } public override int Write(ObjectId oid, Stream dataStream, long length, ObjectType objectType) { throw this.exceptionToThrow; } public override int WriteStream(long length, ObjectType objectType, out OdbBackendStream stream) { throw this.exceptionToThrow; } public override bool Exists(ObjectId oid) { throw this.exceptionToThrow; } public override int ExistsPrefix(string shortSha, out ObjectId found) { throw this.exceptionToThrow; } public override int ReadHeader(ObjectId oid, out int length, out ObjectType objectType) { throw this.exceptionToThrow; } public override int ReadStream(ObjectId oid, out OdbBackendStream stream) { throw this.exceptionToThrow; } public override int ForEach(ForEachCallback callback) { throw this.exceptionToThrow; } } #endregion } }
using System.IO; using System.Web.Mvc; using Newtonsoft.Json; namespace ERP.Web { public class JObjectModelBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var stream = controllerContext.RequestContext.HttpContext.Request.InputStream; stream.Seek(0, SeekOrigin.Begin); string json = new StreamReader(stream).ReadToEnd(); return JsonConvert.DeserializeObject<dynamic>(json); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Xamarin_Samples_Lifecycle.Views { public partial class OneView : ContentPage { public OneView() { InitializeComponent(); } protected override void OnAppearing() { base.OnAppearing(); ApplicationContext.Add($"{nameof(OneView)}.OnAppearing"); editorTxt.Text = ApplicationContext.GetMessageString(); } protected override void OnDisappearing() { base.OnDisappearing(); ApplicationContext.Add($"{nameof(OneView)}.OnDisappearing"); } private async void Button_Clicked(object sender, EventArgs e) { await Navigation.PushAsync(new MainPage()); } } }
using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using HostOptions = NetModular.Lib.Host.Web.Options.HostOptions; namespace NetModular.Lib.Host.Web { public abstract class StartupAbstract { protected readonly IHostEnvironment Env; private readonly IConfiguration _cfg; private readonly HostOptions _hostOptions; protected StartupAbstract(IHostEnvironment env, IConfiguration cfg) { Env = env; _cfg = cfg; //主机配置 _hostOptions = new HostOptions(); cfg.GetSection("Host").Bind(_hostOptions); if (_hostOptions.Urls.IsNull()) _hostOptions.Urls = "http://*:5000"; } public virtual void ConfigureServices(IServiceCollection services) { services.AddWebHost(_hostOptions, Env, _cfg); } public virtual void Configure(IApplicationBuilder app) { app.UseWebHost(_hostOptions, Env); app.UseShutdownHandler(); } } }
using System; using System.Threading; using System.Threading.Tasks; using AniDroid.AniList.Dto; using AniDroid.AniList.Enums.MediaEnums; using AniDroid.AniList.Interfaces; using AniDroid.AniListObject.Media; using AniDroid.Base; using AniDroid.Utils.Interfaces; using AniDroid.Utils.Logging; using Google.Android.Material.Snackbar; namespace AniDroid.SearchResults { public class SearchResultsPresenter : BaseAniDroidPresenter<ISearchResultsView>, IAniListMediaListEditPresenter { private const int PageSize = 20; public SearchResultsPresenter(IAniListService service, IAniDroidSettings settings, IAniDroidLogger logger) : base(service, settings, logger) { } public void SearchAniList(string searchType, string searchTerm) { switch (searchType) { case SearchResultsActivity.AniListSearchTypes.Anime: View.ShowMediaSearchResults(AniListService.SearchMedia(searchTerm, MediaType.Anime, PageSize)); break; case SearchResultsActivity.AniListSearchTypes.Manga: View.ShowMediaSearchResults(AniListService.SearchMedia(searchTerm, MediaType.Manga, PageSize)); break; case SearchResultsActivity.AniListSearchTypes.Characters: View.ShowCharacterSearchResults(AniListService.SearchCharacters(searchTerm, PageSize)); break; case SearchResultsActivity.AniListSearchTypes.Staff: View.ShowStaffSearchResults(AniListService.SearchStaff(searchTerm, PageSize)); break; case SearchResultsActivity.AniListSearchTypes.Studios: View.ShowStudioSearchResults(AniListService.SearchStudios(searchTerm, PageSize)); break; case SearchResultsActivity.AniListSearchTypes.Users: View.ShowUserSearchResults(AniListService.SearchUsers(searchTerm, PageSize)); break; case SearchResultsActivity.AniListSearchTypes.Forum: View.ShowForumThreadSearchResults(AniListService.SearchForumThreads(searchTerm, PageSize)); break; } } public override Task Init() { // TODO: determine if these are needed for this presenter return Task.CompletedTask; } public async Task SaveMediaListEntry(MediaListEditDto editDto, Action onSuccess, Action onError) { var mediaUpdateResp = await AniListService.UpdateMediaListEntry(editDto, default(CancellationToken)); mediaUpdateResp.Switch(mediaList => { onSuccess(); View.DisplaySnackbarMessage("Saved", Snackbar.LengthShort); View.UpdateMediaListItem(mediaList); }).Switch(error => onError()); } public async Task DeleteMediaListEntry(int mediaListId, Action onSuccess, Action onError) { var mediaDeleteResp = await AniListService.DeleteMediaListEntry(mediaListId, default(CancellationToken)); mediaDeleteResp.Switch((bool success) => { onSuccess(); View.DisplaySnackbarMessage("Deleted", Snackbar.LengthShort); View.RemoveMediaListItem(mediaListId); }).Switch(error => onError()); } } }
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using TotalError.OrderSales.Data; namespace TotalError.OrderSales.Data.Migrations { [DbContext(typeof(TotalErrorDbContext))] [Migration("20211011060109_FixDBTypes")] partial class FixDBTypes { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.10") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("TotalError.OrderSales.Data.Entities.CountryEntity", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<Guid>("RegionId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("RegionId"); b.ToTable("Countries"); }); modelBuilder.Entity("TotalError.OrderSales.Data.Entities.ItemEntity", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ItemType") .IsRequired() .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.Property<decimal>("UnitCost") .HasColumnType("smallmoney"); b.HasKey("Id"); b.ToTable("Items"); }); modelBuilder.Entity("TotalError.OrderSales.Data.Entities.OrderEntity", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("CountryId") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("OrderDate") .HasColumnType("datetime2"); b.Property<int>("OrderPriority") .HasColumnType("int"); b.Property<Guid>("RegionId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("SaleId") .HasColumnType("uniqueidentifier"); b.Property<int>("SalesChannel") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("CountryId"); b.HasIndex("RegionId"); b.HasIndex("SaleId"); b.ToTable("Orders"); }); modelBuilder.Entity("TotalError.OrderSales.Data.Entities.RegionEntity", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.HasKey("Id"); b.ToTable("Regions"); }); modelBuilder.Entity("TotalError.OrderSales.Data.Entities.SaleEntity", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("ItemId") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("ShipDate") .HasColumnType("datetime2"); b.Property<decimal>("TotalCost") .HasColumnType("money"); b.Property<decimal>("TotalProfit") .HasColumnType("money"); b.Property<decimal>("TotalRevenue") .HasColumnType("money"); b.Property<decimal>("UnitPrice") .HasColumnType("money"); b.Property<int>("UnitsSold") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("ItemId"); b.ToTable("Sales"); }); modelBuilder.Entity("TotalError.OrderSales.Data.Entities.UserEntity", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Email") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .IsRequired() .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.Property<string>("Password") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Salt") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Users"); }); modelBuilder.Entity("TotalError.OrderSales.Data.Entities.CountryEntity", b => { b.HasOne("TotalError.OrderSales.Data.Entities.RegionEntity", "Region") .WithMany("Countries") .HasForeignKey("RegionId") .OnDelete(DeleteBehavior.NoAction) .IsRequired(); b.Navigation("Region"); }); modelBuilder.Entity("TotalError.OrderSales.Data.Entities.OrderEntity", b => { b.HasOne("TotalError.OrderSales.Data.Entities.CountryEntity", "Country") .WithMany() .HasForeignKey("CountryId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("TotalError.OrderSales.Data.Entities.RegionEntity", "Region") .WithMany("Orders") .HasForeignKey("RegionId") .OnDelete(DeleteBehavior.NoAction) .IsRequired(); b.HasOne("TotalError.OrderSales.Data.Entities.SaleEntity", "Sale") .WithMany() .HasForeignKey("SaleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Country"); b.Navigation("Region"); b.Navigation("Sale"); }); modelBuilder.Entity("TotalError.OrderSales.Data.Entities.SaleEntity", b => { b.HasOne("TotalError.OrderSales.Data.Entities.ItemEntity", "Item") .WithMany("Sales") .HasForeignKey("ItemId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Item"); }); modelBuilder.Entity("TotalError.OrderSales.Data.Entities.ItemEntity", b => { b.Navigation("Sales"); }); modelBuilder.Entity("TotalError.OrderSales.Data.Entities.RegionEntity", b => { b.Navigation("Countries"); b.Navigation("Orders"); }); #pragma warning restore 612, 618 } } }
using System.Reflection; using LightJson; using Unisave.Serialization; using Unisave.Serialization.Context; using Unisave.Utils; namespace Unisave.Facets { /// <summary> /// Represents the response from a facet call /// /// IMPORTANT: This does not cover exceptions, /// those are left to propagate and serialized /// at the top-most level of the framework /// </summary> public class FacetResponse { public object Returned { get; private set; } public JsonValue ReturnedJson { get; private set; } private FacetResponse() { } public static FacetResponse CreateFrom( object returned, MethodInfo methodInfo ) { return new FacetResponse { Returned = returned, ReturnedJson = Facet.SerializeReturnedValue( methodInfo, returned ) }; } } }
namespace ShaderTools.CodeAnalysis.ShaderLab.Syntax { public sealed class CommandSetTextureCombineBinaryValueSyntax : BaseCommandSetTextureCombineValueSyntax { public readonly CommandSetTextureCombineSourceSyntax Source1; public readonly SyntaxToken OperatorToken; public readonly CommandSetTextureCombineSourceSyntax Source2; public CommandSetTextureCombineBinaryValueSyntax(CommandSetTextureCombineSourceSyntax source1, SyntaxToken operatorToken, CommandSetTextureCombineSourceSyntax source2) : base(SyntaxKind.CommandSetTextureCombineBinaryValue) { RegisterChildNode(out Source1, source1); RegisterChildNode(out OperatorToken, operatorToken); RegisterChildNode(out Source2, source2); } public override void Accept(SyntaxVisitor visitor) { visitor.VisitCommandSetTextureCombineBinaryValue(this); } public override T Accept<T>(SyntaxVisitor<T> visitor) { return visitor.VisitCommandSetTextureCombineBinaryValue(this); } } }
using System; using DuoCode.Runtime; namespace Knockout { [Js(Name = "ko.observableArray", Extern = true)] public class ObservableArray<T> : Observable<JsArray<T>> { [Js(Name = "push", OmitGenericArgs = true)] public extern void Push(T value); [Js(Name = "remove", OmitGenericArgs = true)] public extern T[] Remove(T item); [Js(Name = "remove", OmitGenericArgs = true)] public extern T[] Remove(Predicate<T> predicate); [Js(Name = "removeAll")] public extern T[] RemoveAll(); [Js(Name = "sort", OmitGenericArgs = true)] public extern void Sort(Func<T, T, int> sort); [Js(Name = "sort")] public extern void Sort(); [Js(Name = "splice")] public extern T[] Splice(int start, int length); } }
//#define PUBLICWORK using System.Linq; using System.Numerics; namespace Perpetuum { public static class Rsa { private static readonly byte[] _modulusKey = new byte[] #if !PUBLICWORK { 0xd5,0x36,0xee,0x26,0x9b,0x07,0x91,0x03, 0xfc,0xd3,0x37,0x36,0x6c,0x2b,0xe6,0x98, 0x19,0xe0,0xcf,0x44,0xee,0x3c,0x51,0xe2, 0x7c,0x00,0x05,0x3f,0x9c,0xd6,0x0a,0xc1, 0x26,0xea,0xbd,0x40,0x96,0x9a,0xb4,0xe7, 0xb4,0xdf,0xc4,0x20,0x2d,0x0a,0x6e,0x30, 0x7d,0xcb,0x91,0x03,0x6b,0x4e,0x06,0x9f, 0x5d,0x53,0x42,0x58,0xe0,0x98,0xc2,0xf3, 0xdb,0x6b,0x5f,0xf3,0x89,0x90,0xb6,0x00, 0x56,0xa8,0xab,0x85,0x7f,0xdd,0x2e,0x2d, 0xe9,0x56,0x6d,0xe2,0xa6,0x70,0x0a,0xee, 0xff,0xb9,0xe7,0x09,0x25,0x0d,0x54,0xf7, 0xd6,0x31,0x77,0x19,0x51,0x77,0xf1,0x5b, 0x0e,0x14,0x53,0x92,0xab,0x7a,0xd9,0x79, 0xfc,0xd9,0xc2,0x64,0x61,0xe3,0x4b,0xc9, 0x68,0xa7,0x27,0xe6,0xd6,0xd2,0x59,0xb2, 0x00, }; #else { 0xd5,0x36,0xee,0x26,0x9b,0x07,0x91,0x03, 0xfc,0xd3,0x37,0x36,0x6c,0x2b,0xe6,0xc4, 0x20,0x2d,0x0a,0x6e,0x30,0x7d,0xcb,0x91, 0x53,0xb2,0x00, }; #endif private static readonly byte[] _privateExponentKey = new byte[] #if !PUBLICWORK { 0x19,0xe6,0x48,0x86,0x7a,0x07,0xe5,0xe2, 0x3a,0x5f,0x16,0x0e,0x8d,0x2a,0x01,0x7b, 0xfd,0x76,0x1e,0xf7,0x8a,0xb5,0xeb,0x08, 0x24,0x97,0x24,0xd9,0xd6,0x8b,0xde,0x87, 0x74,0x0f,0x1c,0xac,0xea,0x13,0x7a,0x6d, 0x13,0x9f,0x5c,0xf4,0xe6,0x05,0x26,0xd2, 0xeb,0xa0,0x90,0x1b,0xa2,0x7d,0xe1,0xc6, 0xb4,0x24,0x41,0xf5,0x5c,0x24,0x7f,0xdd, 0xd1,0x58,0x12,0x6e,0x44,0xb3,0xf0,0x5a, 0xce,0xb7,0xe7,0x40,0xa5,0xf2,0x80,0x70, 0x29,0xde,0x2c,0x6f,0x89,0x20,0x90,0x4b, 0x5a,0xc6,0xaf,0x8f,0x2d,0x65,0x72,0x8f, 0x38,0x56,0x8f,0xab,0x24,0x44,0x30,0xc4, 0xfc,0x88,0x62,0x5a,0x9c,0xfb,0x94,0xa0, 0x84,0xb3,0xdc,0x34,0x50,0xca,0x89,0x69, 0x74,0x20,0x99,0xcc,0x83,0x8f,0xe0,0x92, 0x00, }; #else { 0x19,0xe6,0x48,0x86,0x7a,0x07,0xe5,0xe2, 0x3a,0x5f,0x16,0x0e,0x8d,0x2a,0x01,0x7b, 0xfd,0x76,0x1e,0xf7,0xe1,0x46,0x34,0x0b, 0xaf,0x92,0x00, }; #endif private static readonly BigInteger _modulus = new BigInteger(_modulusKey); private static readonly BigInteger _privateExponent = new BigInteger(_privateExponentKey); [CanBeNull] public static byte[] Decrypt(byte[] input) { if (input.Length > _modulusKey.Length) return null; var encryptedData = input.Reverse().ConcatSingle((byte)0).ToArray(); var output = BigInteger.ModPow(new BigInteger(encryptedData), _privateExponent, _modulus).ToByteArray().Reverse().ToArray(); return output[0] == 0 ? output.Skip(1).ToArray() : output; } [CanBeNull] public static byte[] Encrypt(byte[] input) { if (input.Length > _modulusKey.Length) return null; var encryptedData = input.Reverse().ConcatSingle((byte)0).ToArray(); var output = BigInteger.ModPow(new BigInteger(encryptedData),0x11, _modulus).ToByteArray().Reverse().ToArray(); return output[0] == 0 ? output.Skip(1).ToArray() : output; } } }
using System; using System.Diagnostics; using System.IO; using System.Management; using System.Net; using System.Text; namespace _51Racer { static class EnvInfo { static WebClient webClient = new WebClient(); static EnvInfo() { webClient.Encoding = Encoding.UTF8; } public static int GetSystemBits() { try { string addressWidth = String.Empty; ConnectionOptions mConnOption = new ConnectionOptions(); ManagementScope mMs = new ManagementScope(@"\\localhost", mConnOption); ObjectQuery mQuery = new ObjectQuery("select AddressWidth from Win32_Processor"); ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(mMs, mQuery); ManagementObjectCollection mObjectCollection = mSearcher.Get(); foreach (ManagementObject mObject in mObjectCollection) { addressWidth = mObject["AddressWidth"].ToString(); } return Int32.Parse(addressWidth); } catch { return 86; } } public static string GetTempPath() { return Environment.GetEnvironmentVariable("TEMP") + "\\"; } public static string GetStartPath() { return new FileInfo(Process.GetCurrentProcess().MainModule.FileName).DirectoryName; } public static string StartProcess(string exePath, string command,bool waitForExit = true) { Process p = new Process(); p.StartInfo.FileName = exePath; p.StartInfo.Arguments = command; p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.Start(); if (waitForExit) { p.WaitForExit(1000 * 60 * 5); } string ret = ""; if (p.HasExited) { ret = p.StandardOutput.ReadToEnd(); } else { p.Kill(); } p.Close(); return ret; } public static string HttpGet(string url) { return webClient.DownloadString(url); } } }
using System; using ExceptionsHomework.Contracts; namespace ExceptionsHomework.Models { public class SimpleMathExam : IExam { private const string ExelentResultComment = "Excellent result: everything's done correctly."; private const string AvarageResultComment = "Average result: almost nothing done."; private const string BadResultComment = "Bad result: nothing done."; private const string InvalidNumberOfProblemsSolved = "Invalid number of problems solved!"; private const int MinProblemsSolved = 0; private const int MaxProblemsSolved = 10; private const int BadGradeMaxProblems = 2; private const int AvarageGradeMaxProblems = 7; private const int BadGrade = 2; private const int AvarageGrade = 4; private const int ExelentGrade = 6; private int problemsSolved; public SimpleMathExam(int problemsSolved) { this.ProblemsSolved = problemsSolved; } public int ProblemsSolved { get { return this.problemsSolved; } private set { if (value < MinProblemsSolved) { value = MinProblemsSolved; } if (value > MaxProblemsSolved) { value = MaxProblemsSolved; } this.problemsSolved = value; } } public ExamResult Check() { var comment = string.Empty; var grade = 0; if (this.ProblemsSolved <= BadGradeMaxProblems) { grade = BadGrade; comment = BadResultComment; } else if (this.ProblemsSolved <= AvarageGradeMaxProblems) { grade = AvarageGrade; comment = AvarageResultComment; } else { grade = ExelentGrade; comment = ExelentResultComment; } return new ExamResult(grade, BadGrade, ExelentGrade, comment); } } }
using System.Text; /** * Author: Pantelis Andrianakis * Date: November 29th 2019 */ public class LocCommand { public static void Handle(Player player) { LocationHolder location = player.GetLocation(); // Send player success message. StringBuilder sb = new StringBuilder(); sb.Append("Your location is "); sb.Append(location.GetX()); sb.Append(" "); sb.Append(location.GetZ()); sb.Append(" "); sb.Append(location.GetY()); ChatManager.SendSystemMessage(player, sb.ToString()); } }
namespace BugNET.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("BugNet_IssueRevisions")] public partial class IssueRevision { [Key] public int IssueRevisionId { get; set; } public int Revision { get; set; } public int IssueId { get; set; } [Required] [StringLength(400)] public string Repository { get; set; } [Required] [StringLength(100)] public string RevisionAuthor { get; set; } [Required] [StringLength(100)] public string RevisionDate { get; set; } [Required] public string RevisionMessage { get; set; } public DateTime DateCreated { get; set; } [StringLength(255)] public string Branch { get; set; } [StringLength(100)] public string Changeset { get; set; } public virtual Issue Issue { get; set; } } }
// <copyright file="TimelapseMode.cs" company="Techyian"> // Copyright (c) Ian Auty and contributors. All rights reserved. // Licensed under the MIT License. Please see LICENSE.txt for License info. // </copyright> namespace MMALSharp.Config { /// <summary> /// The unit of time to use. /// </summary> public enum TimelapseMode { /// <summary> /// Uses milliseconds as unit of time. One hour equals 3'600'000 milliseconds. /// </summary> Millisecond, /// <summary> /// Uses seconds as unit of time. One hour equals 3'600 seconds. /// </summary> Second, /// <summary> /// Uses minutes as unit of time. One hour equals 60 minutes. /// </summary> Minute } }
using System.Runtime.CompilerServices; #if NETCOREAPP3_0_OR_GREATER using System.Numerics; using System.Runtime.Intrinsics.X86; #endif namespace AtCoder.Internal { using static MethodImplOptions; public static class InternalBit { /// <summary> /// _blsi_u32 OR <paramref name="n"/> &amp; -<paramref name="n"/> /// <para><paramref name="n"/>で立っているうちの最下位の 1 ビットのみを立てた整数を返す</para> /// </summary> /// <param name="n"></param> /// <returns><paramref name="n"/> &amp; -<paramref name="n"/></returns> [MethodImpl(AggressiveInlining)] public static uint ExtractLowestSetBit(int n) { #if NETCOREAPP3_0_OR_GREATER if (Bmi1.IsSupported) { return Bmi1.ExtractLowestSetBit((uint)n); } #endif return (uint)(n & -n); } /// <summary> /// (<paramref name="n"/> &amp; (1 &lt;&lt; x)) != 0 なる最小の非負整数 x を求めます。 /// </summary> /// <remarks> /// <para>BSF: Bit Scan Forward</para> /// <para>制約: 1 ≤ <paramref name="n"/></para> /// </remarks> [MethodImpl(AggressiveInlining)] public static int BSF(uint n) { Contract.Assert(n > 0, reason: $"{nameof(n)} must positive"); return BitOperations.TrailingZeroCount(n); } /// <summary> /// <paramref name="n"/> ≤ 2**x を満たす最小のx /// </summary> /// <remarks> /// <para>制約: 0≤<paramref name="n"/></para> /// </remarks> [MethodImpl(AggressiveInlining)] public static int CeilPow2(int n) { var un = (uint)n; if (un <= 1) return 0; return BitOperations.Log2(un - 1) + 1; } } }
using System; using System.Collections.Generic; using System.Text; using Newtonsoft.Json; namespace Cumulocity.SDK.Client.Rest.Representation.Alarm { public class AvailabilityStatRepresentation : BaseResourceRepresentation { private string source; private long? downtimeDuration; public AvailabilityStatRepresentation() { } public AvailabilityStatRepresentation(string source, long? downtimeDuration) { this.source = source; this.downtimeDuration = downtimeDuration; } [JsonProperty(propertyName: "source", NullValueHandling = NullValueHandling.Ignore)] public virtual string Source { get { return source; } set { this.source = value; } } [JsonProperty(propertyName: "downtimeDuration", NullValueHandling = NullValueHandling.Ignore)] public virtual long? DowntimeDuration { get { return downtimeDuration; } set { this.downtimeDuration = value; } } } }
using System.Windows; using Nova.Bindings.Base; namespace Nova.Bindings.Listeners { abstract class ResolvableDataContextListener<T> : DataContextListener<T> where T : FrameworkElement { private readonly ResolveMode _resolveMode; protected ResolvableDataContextListener(PropertyPath path, ResolveMode resolveMode) : base(path) { _resolveMode = resolveMode; } protected override void OnDataContextChanged(T element, object dataContext) { if (OnResolvableDataContextChanged(element, dataContext)) { if (_resolveMode == ResolveMode.Once) DetachFrom(element); } } protected abstract bool OnResolvableDataContextChanged(T element, object dataContext); } }
namespace DbCompare.Objects { internal enum RoutineChangeType { Added, DefinitionChanged, Deleted } }
using System; using System.ComponentModel.DataAnnotations; namespace LiteFx { public abstract class EntityBase { } /// <summary> /// Base class for entities. /// </summary> /// <typeparam name="TId">Type of id.</typeparam> public abstract class EntityBase<TId> : EntityBase, IEquatable<EntityBase<TId>> where TId : IEquatable<TId> { private int? hashcodeCache; /// <summary> /// Entity id. /// </summary> [ScaffoldColumn(false)] public virtual TId Id { get; set; } /// <summary> /// /// </summary> [ScaffoldColumn(false)] public virtual bool Transient { get { return Id.Equals(default(TId)); } } public virtual bool Equals(EntityBase<TId> other) { if (ReferenceEquals(other, null)) return false; if (ReferenceEquals(this, other)) return true; if (this.Transient || other.Transient) return false; if (!isSameTypeOf(other)) return false; return Id.Equals(other.Id); } private bool isSameTypeOf(EntityBase<TId> other) { return GetType().Equals(other.GetType()); } public override bool Equals(object obj) { if (obj == null) return base.Equals(obj); if (!(obj is EntityBase<TId>)) return false; else return Equals(obj as EntityBase<TId>); } public override int GetHashCode() { if (hashcodeCache.HasValue) return hashcodeCache.Value; if (Transient) hashcodeCache = base.GetHashCode(); else hashcodeCache = GetType().GetHashCode() + Id.GetHashCode(); return hashcodeCache.Value; } public static bool operator ==(EntityBase<TId> left, EntityBase<TId> right) { if (ReferenceEquals(left, null) && ReferenceEquals(right, null)) return true; if (ReferenceEquals(left, null) && !ReferenceEquals(right, null)) return false; return left.Equals(right); } public static bool operator !=(EntityBase<TId> left, EntityBase<TId> right) { if (ReferenceEquals(left, null) && ReferenceEquals(right, null)) return false; if (ReferenceEquals(left, null) && !ReferenceEquals(right, null)) return true; return !left.Equals(right); } } }
using System; using System.Collections.Generic; using System.Text; namespace PowerBot.Core.Models { public class PowerbotUser { public long Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string UserName { get; set; } public DateTime ActiveAt { get; set; } public UserAccess UserAccess { get; set; } public string FullName => FirstName + " " + LastName; public bool IsBanned => UserAccess == UserAccess.Ban; } }
using System; using Xamarin.Forms; using System.Collections.Generic; namespace PicMatcher { public class SettingsPage : ContentPage { GameSettings _settings; Dictionary<string, Category> _catsHash = new Dictionary<string, Category> (); Dictionary<int, Language> _langHash = new Dictionary<int, Language> (); public SettingsPage () {} public SettingsPage (ref GameSettings Settings) { _settings = Settings; // Categories table section var catSection = new TableSection ("Categories"); // Populate section with switches foreach (Category cat in Settings.Categories) { _catsHash.Add (cat.Name, cat); var cell = new SwitchCell { Text = cat.Name }; // If category is selected, turn the switch on // TODO: optimize if (_settings.SelectedCategories.IndexOf (cat) > -1) { cell.On = true; } cell.OnChanged += SwitchCellChanged; catSection.Add (cell); } var tableView = new TableView { Intent = TableIntent.Settings, Root = new TableRoot ("Settings") { catSection } }; // Languages picker var languagePicker = new Picker { Title = "Language", VerticalOptions = LayoutOptions.CenterAndExpand }; // Populate picker var i = 0; var selectedIndex = 0; foreach (Language lang in Settings.Languages) { _langHash.Add (i, lang); languagePicker.Items.Add (lang.Name); languagePicker.SelectedIndexChanged += LanguageSelected; if (lang.Equals (_settings.SelectedLanguage)) selectedIndex = i; i++; } languagePicker.SelectedIndex = selectedIndex; var languageGroup = new StackLayout { Padding = 20, Children = { languagePicker } }; var DoneBtn = new Button { Text = "Done" }; DoneBtn.Clicked += (object sender, EventArgs e) => { if(CanLeave()) Navigation.PopModalAsync(); }; Content = new StackLayout { VerticalOptions = LayoutOptions.FillAndExpand, Children = { languageGroup, tableView, DoneBtn } }; } void SwitchCellChanged(object sender, EventArgs e) { var cell = (SwitchCell)sender; // Get Category var cat = _catsHash [cell.Text]; // Count number of selected categories if (cell.On) { _settings.SelectCategory (cat); } else { _settings.DeselectCategory (cat); } } void LanguageSelected(object sender, EventArgs e) { var picker = (Picker)sender; _settings.SelectedLanguage = _langHash [picker.SelectedIndex]; } bool CanLeave() { if(_settings.SelectedCategories.Count == 0) { DisplayAlert("No category selected", "Select at least one category", "OK"); return false; } return true; } protected override bool OnBackButtonPressed () { // Return true if you don't want to leave page (wierd) if (!CanLeave()) return true; return base.OnBackButtonPressed (); } } }
using net.r_eg.SobaScript; using net.r_eg.SobaScript.Z.Core; using net.r_eg.Varhead; namespace SobaScript.Z.CoreTest.Stubs { internal class UserVariableComponentEvalStub: UserVariableComponent { private class Evaluator1: IEvaluator { public string Evaluate(string data) { return $"[E1:{data}]"; } } public UserVariableComponentEvalStub(IUVars uvariable) : base(new Soba(uvariable)) { } protected override void Evaluate(string name, string project = null) { uvars.Evaluate(name, project, new Evaluator1(), true); } } }
namespace Aliencube.Azure.Insights.WebTests.Models { /// <summary> /// This represents the configuration entity for web test. This MUST be inherited. /// </summary> public abstract class WebTestConfiguration { /// <summary> /// Gets the web test XML serialised value. /// </summary> public abstract string WebTest { get; } } }
// PhysicalSizeBitmapFontScaler using ClubPenguin; using UnityEngine; [RequireComponent(typeof(RectTransform))] public class PhysicalSizeBitmapFontScaler : PhysicalSizeScaler { public float TargetScale_Iphone5 = 0f; public float TargetScale_Ipad = 0f; private RectTransform rectTransform; private void Start() { rectTransform = GetComponent<RectTransform>(); ApplyScale(); } private void ApplyScale() { Vector3 targetDimensions = GetTargetDimensions(); rectTransform.localScale = targetDimensions; } private Vector3 GetTargetDimensions() { Vector3 result = default(Vector3); float deviceSize = GetDeviceSize(); float num = NormalizeScaleProperty(TargetScale_Ipad, TargetScale_Iphone5); result.x = TargetScale_Iphone5 + (deviceSize - 4f) * num; result.y = result.x; result.z = result.x; return result; } }
namespace VisualViajes.View { using System.Drawing; using System.Windows.Forms; /// <summary> /// Dlg para insertar los datos de un viaje. /// </summary> public class DlgInserta: Form { /// <summary> /// Inicializa una nueva instancia de este dlg. /// </summary> public DlgInserta() { this.Build(); } private Panel BuildPnlKms() { var toret = new Panel(); this.edKms = new NumericUpDown { Value = 0, TextAlign = HorizontalAlignment.Right, Dock = DockStyle.Fill, Minimum = 1 }; var lbKms = new Label { Text = "Kms:", Dock = DockStyle.Left }; toret.Controls.Add( this.edKms ); toret.Controls.Add( lbKms ); toret.Dock = DockStyle.Top; toret.MaximumSize = new Size( int.MaxValue, edKms.Height * 2 ); return toret; } private Panel BuildPnlCiudadOrigen() { var toret = new Panel { Dock = DockStyle.Top }; this.edCiudadOrigen = new TextBox { Dock = DockStyle.Fill }; var lbCiudadOrigen = new Label { Text = "Ciudad origen:", Dock = DockStyle.Left }; toret.Controls.Add( this.edCiudadOrigen ); toret.Controls.Add( lbCiudadOrigen ); toret.MaximumSize = new Size( int.MaxValue, edCiudadOrigen.Height * 2 ); this.edCiudadOrigen.Validating += (sender, cancelArgs) => { var btAccept = (Button) this.AcceptButton; bool invalid = string.IsNullOrWhiteSpace( this.CiudadOrigen ); invalid = invalid || !char.IsLetter( this.CiudadOrigen[ 0 ] ); if ( invalid ) { this.edCiudadOrigen.Text = "¿Ciudad de origen?"; } btAccept.Enabled = !invalid; cancelArgs.Cancel = invalid; }; return toret; } private Panel BuildPnlCiudadDestino() { var toret = new Panel(); this.edCiudadDestino = new TextBox { Dock = DockStyle.Fill }; var lbCiudadDestino = new Label() { Text = "Ciudad destino:", Dock = DockStyle.Left }; toret.Controls.Add( this.edCiudadDestino ); toret.Controls.Add( lbCiudadDestino ); toret.Dock = DockStyle.Top; toret.MaximumSize = new Size( int.MaxValue, edCiudadDestino.Height * 2 ); this.edCiudadDestino.Validating += (sender, cancelArgs) => { var btAccept = (Button) this.AcceptButton; bool invalid = string.IsNullOrWhiteSpace( this.CiudadDestino ); invalid = invalid || !char.IsLetter( this.CiudadDestino[ 0 ] ); if ( invalid ) { this.edCiudadDestino.Text = "¿Ciudad de destino?"; } btAccept.Enabled = !invalid; cancelArgs.Cancel = invalid; }; return toret; } private Panel BuildPnlBotones() { var toret = new TableLayoutPanel() { ColumnCount = 2, RowCount = 1 }; var btCierra = new Button() { DialogResult = DialogResult.Cancel, Text = "&Cancelar" }; var btGuarda = new Button() { DialogResult = DialogResult.OK, Text = "&Guardar" }; this.AcceptButton = btGuarda; this.CancelButton = btCierra; toret.Controls.Add( btGuarda ); toret.Controls.Add( btCierra ); toret.Dock = DockStyle.Top; return toret; } private void Build() { this.SuspendLayout(); var pnlInserta = new TableLayoutPanel { Dock = DockStyle.Fill }; pnlInserta.SuspendLayout(); this.Controls.Add( pnlInserta ); var pnlCiudadOrigen = this.BuildPnlCiudadOrigen(); pnlInserta.Controls.Add( pnlCiudadOrigen ); var pnlCiudadDestino = this.BuildPnlCiudadDestino(); pnlInserta.Controls.Add(pnlCiudadDestino); var pnlKms = this.BuildPnlKms(); pnlInserta.Controls.Add( pnlKms ); var pnlBotones = this.BuildPnlBotones(); pnlInserta.Controls.Add( pnlBotones ); pnlInserta.ResumeLayout( true ); this.Text = "Nuevo viaje"; this.Size = new Size( 400, pnlCiudadOrigen.Height + pnlCiudadDestino.Height + pnlKms.Height + pnlBotones.Height ); this.FormBorderStyle = FormBorderStyle.FixedDialog; this.MinimizeBox = false; this.MaximizeBox = false; this.StartPosition = FormStartPosition.CenterParent; this.ResumeLayout( false ); } /// <summary> /// Valida los datos en el dlg. /// </summary> /// <param name="e">Los params. del evento.</param> private void OnValidate(System.ComponentModel.CancelEventArgs e) { bool toret = string.IsNullOrWhiteSpace( this.CiudadOrigen ); toret = toret || string.IsNullOrWhiteSpace( this.CiudadDestino ); toret = toret || double.TryParse( this.edKms.Text, out double res ); e.Cancel = toret; } /// <summary> /// Obtiene la ciudad origen introducida por el usuario. /// </summary> /// <value>Una cadena de caracteres con la ciudad de origen.</value> public string CiudadOrigen => this.edCiudadOrigen.Text; /// <summary> /// Obtiene la ciudad destino introducida por el usuario. /// </summary> /// <value>Una cadena de caracteres con la ciudad de destino.</value> public string CiudadDestino => this.edCiudadDestino.Text; /// <summary> /// Obtiene los kms. introducidos por el usuario. /// </summary> /// <value>Los kms., como entero.</value> public double Kms => System.Convert.ToDouble( this.edKms.Value ); private TextBox edCiudadOrigen; private TextBox edCiudadDestino; private NumericUpDown edKms; } }
@using Resources; @model Eshop.Web.Models.Items.ItemBindingModel <fieldset> <legend>@ItemsResources.AddItemTitle</legend> <div class="form-group"> @Html.LabelFor(x => x.Title, new { @class = "col-lg-2 control-label" }) <div class="col-lg-10"> @Html.EditorFor(x => x.Title, new { @class = "form-control", placeholder = "Title" }) </div> </div> <div class="form-group"> @Html.LabelFor(x => x.Description, new { @class = "col-lg-2 control-label" }) <div class="col-lg-10"> @Html.TextAreaFor(x => x.Description, new { @class="form-control", rows = "6" }) </div> </div> <div class="form-group"> @Html.LabelFor(x => x.Quantity, new { @class = "col-lg-2 control-label" }) <div class="col-lg-10"> @Html.EditorFor(x => x.Quantity) </div> </div> @Html.LabelFor(x => x.DiscountPercentage) @Html.EditorFor(x => x.DiscountPercentage) @Html.LabelFor(x => x.Price, new { @class = "col-lg-2 control-label" }) @Html.EditorFor(x => x.Price) <div class="form-group"> <div class="col-lg-10 col-lg-offset-2"> <button type="reset" class="btn btn-default">Cancel</button> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </fieldset>
using Luban.Job.Common.Types; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Luban.Job.Common.TypeVisitors { public class IsFlatBuffersScalarTypeVisitor : AllTrueVisitor { public static IsFlatBuffersScalarTypeVisitor Ins { get; } = new(); public override bool Accept(TBytes type) { return false; } public override bool Accept(TBean type) { return false; } public override bool Accept(TArray type) { return false; } public override bool Accept(TList type) { return false; } public override bool Accept(TSet type) { return false; } public override bool Accept(TMap type) { return false; } public override bool Accept(TVector2 type) { return false; } public override bool Accept(TVector3 type) { return false; } public override bool Accept(TVector4 type) { return false; } } }
// *********************************************************************** // Copyright (c) 2009 Charlie Poole, Rob Prouse // // 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; namespace NUnit.Framework.Syntax { public class EqualToTest : SyntaxTest { [SetUp] public void SetUp() { ParseTree = "<equal 999>"; StaticSyntax = Is.EqualTo(999); BuilderSyntax = Builder().EqualTo(999); } } public class EqualToTest_IgnoreCase : SyntaxTest { [SetUp] public void SetUp() { ParseTree = @"<equal ""X"">"; StaticSyntax = Is.EqualTo("X").IgnoreCase; BuilderSyntax = Builder().EqualTo("X").IgnoreCase; } } public class EqualToTest_WithinTolerance : SyntaxTest { [SetUp] public void SetUp() { ParseTree = "<equal 0.7>"; StaticSyntax = Is.EqualTo(0.7).Within(.005); BuilderSyntax = Builder().EqualTo(0.7).Within(.005); } } public class EqualityTests { [Test] public void SimpleEqualityTests() { int[] i3 = new int[] { 1, 2, 3 }; double[] d3 = new double[] { 1.0, 2.0, 3.0 }; int[] iunequal = new int[] { 1, 3, 2 }; Assert.That(2 + 2, Is.EqualTo(4)); Assert.That(2 + 2 == 4); Assert.That(i3, Is.EqualTo(d3)); Assert.That(2 + 2, Is.Not.EqualTo(5)); Assert.That(i3, Is.Not.EqualTo(iunequal)); List<string> list = new List<string>(); list.Add("foo"); list.Add("bar"); Assert.That(list, Is.EqualTo(new string[] { "foo", "bar" })); } [Test] public void EqualityTestsWithTolerance() { Assert.That(4.99d, Is.EqualTo(5.0d).Within(0.05d)); Assert.That(4.0d, Is.Not.EqualTo(5.0d).Within(0.5d)); Assert.That(4.99f, Is.EqualTo(5.0f).Within(0.05f)); Assert.That(4.99m, Is.EqualTo(5.0m).Within(0.05m)); Assert.That(3999999999u, Is.EqualTo(4000000000u).Within(5u)); Assert.That(499, Is.EqualTo(500).Within(5)); Assert.That(4999999999L, Is.EqualTo(5000000000L).Within(5L)); Assert.That(5999999999ul, Is.EqualTo(6000000000ul).Within(5ul)); } [Test] public void EqualityTestsWithTolerance_MixedFloatAndDouble() { // Bug Fix 1743844 Assert.That(2.20492d, Is.EqualTo(2.2d).Within(0.01f), "Double actual, Double expected, Single tolerance"); Assert.That(2.20492d, Is.EqualTo(2.2f).Within(0.01d), "Double actual, Single expected, Double tolerance"); Assert.That(2.20492d, Is.EqualTo(2.2f).Within(0.01f), "Double actual, Single expected, Single tolerance"); Assert.That(2.20492f, Is.EqualTo(2.2f).Within(0.01d), "Single actual, Single expected, Double tolerance"); Assert.That(2.20492f, Is.EqualTo(2.2d).Within(0.01d), "Single actual, Double expected, Double tolerance"); Assert.That(2.20492f, Is.EqualTo(2.2d).Within(0.01f), "Single actual, Double expected, Single tolerance"); } [Test] public void EqualityTestsWithTolerance_MixingTypesGenerally() { // Extending tolerance to all numeric types Assert.That(202d, Is.EqualTo(200d).Within(2), "Double actual, Double expected, int tolerance"); Assert.That(4.87m, Is.EqualTo(5).Within(.25), "Decimal actual, int expected, Double tolerance"); Assert.That(4.87m, Is.EqualTo(5ul).Within(1), "Decimal actual, ulong expected, int tolerance"); Assert.That(487, Is.EqualTo(500).Within(25), "int actual, int expected, int tolerance"); Assert.That(487u, Is.EqualTo(500).Within(25), "uint actual, int expected, int tolerance"); Assert.That(487L, Is.EqualTo(500).Within(25), "long actual, int expected, int tolerance"); Assert.That(487ul, Is.EqualTo(500).Within(25), "ulong actual, int expected, int tolerance"); } [Test, DefaultFloatingPointTolerance(0.05)] public void EqualityTestsUsingDefaultFloatingPointTolerance() { Assert.That(4.99d, Is.EqualTo(5.0d)); Assert.That(4.0d, Is.Not.EqualTo(5.0d)); Assert.That(4.99f, Is.EqualTo(5.0f)); } } }
namespace Shkolo.Models.ScheduleHours { public class AllScheduleHourModel { public int ScheduleHourId { get; set; } public int Term_Number { get; set; } public string Date { get; set; } public int DayOfWeek { get; set; } public int SchoolHour { get; set; } public string ScheduleSubjectName { get; set; } public string ScheduleTeacherName { get; set; } public string Topics { get; set; } public int AbsenceStudentNimberInClass{ get; set; } } }
// 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.Linq; using Microsoft.AspNetCore.Razor.Language.Components; using Microsoft.AspNetCore.Razor.Language.Extensions; using Moq; using Xunit; namespace Microsoft.AspNetCore.Razor.Language.Test { public class RazorProjectEngineTest { [Fact] public void CreateDesignTime_Lambda_AddsFeaturesAndPhases() { // Arrange // Act var engine = RazorProjectEngine.Create(RazorConfiguration.Default, Mock.Of<RazorProjectFileSystem>()); // Assert AssertDefaultPhases(engine); AssertDefaultFeatures(engine); AssertDefaultDirectives(engine); AssertDefaultTargetExtensions(engine); } private static void AssertDefaultPhases(RazorProjectEngine engine) { Assert.Collection( engine.Phases, phase => Assert.IsType<DefaultRazorParsingPhase>(phase), phase => Assert.IsType<DefaultRazorSyntaxTreePhase>(phase), phase => Assert.IsType<DefaultRazorTagHelperBinderPhase>(phase), phase => Assert.IsType<DefaultRazorIntermediateNodeLoweringPhase>(phase), phase => Assert.IsType<DefaultRazorDocumentClassifierPhase>(phase), phase => Assert.IsType<DefaultRazorDirectiveClassifierPhase>(phase), phase => Assert.IsType<DefaultRazorOptimizationPhase>(phase), phase => Assert.IsType<DefaultRazorCSharpLoweringPhase>(phase)); } private static void AssertDefaultFeatures(RazorProjectEngine engine) { var features = engine.EngineFeatures.OrderBy(f => f.GetType().Name).ToArray(); Assert.Collection( features, feature => Assert.IsType<ComponentBindLoweringPass>(feature), feature => Assert.IsType<ComponentChildContentDiagnosticPass>(feature), feature => Assert.IsType<ComponentComplexAttributeContentPass>(feature), feature => Assert.IsType<ComponentDocumentClassifierPass>(feature), feature => Assert.IsType<ComponentEventHandlerLoweringPass>(feature), feature => Assert.IsType<ComponentGenericTypePass>(feature), feature => Assert.IsType<ComponentInjectDirectivePass>(feature), feature => Assert.IsType<ComponentLayoutDirectivePass>(feature), feature => Assert.IsType<ComponentLoweringPass>(feature), feature => Assert.IsType<ComponentMarkupBlockPass>(feature), feature => Assert.IsType<ComponentMarkupEncodingPass>(feature), feature => Assert.IsType<ComponentPageDirectivePass>(feature), feature => Assert.IsType<ComponentReferenceCaptureLoweringPass>(feature), feature => Assert.IsType<ComponentScriptTagPass>(feature), feature => Assert.IsType<ComponentTemplateDiagnosticPass>(feature), feature => Assert.IsType<ComponentWhitespacePass>(feature), feature => Assert.IsType<DefaultDirectiveSyntaxTreePass>(feature), feature => Assert.IsType<DefaultDocumentClassifierPass>(feature), feature => Assert.IsType<DefaultDocumentClassifierPassFeature>(feature), feature => Assert.IsType<DefaultMetadataIdentifierFeature>(feature), feature => Assert.IsType<DefaultRazorCodeGenerationOptionsFeature>(feature), feature => Assert.IsType<DefaultRazorDirectiveFeature>(feature), feature => Assert.IsType<DefaultRazorParserOptionsFeature>(feature), feature => Assert.IsType<DefaultRazorTargetExtensionFeature>(feature), feature => Assert.IsType<DefaultTagHelperOptimizationPass>(feature), feature => Assert.IsType<DesignTimeDirectivePass>(feature), feature => Assert.IsType<DirectiveRemovalOptimizationPass>(feature), feature => Assert.IsType<EliminateMethodBodyPass>(feature), feature => Assert.IsType<FunctionsDirectivePass>(feature), feature => Assert.IsType<HtmlNodeOptimizationPass>(feature), feature => Assert.IsType<ImplementsDirectivePass>(feature), feature => Assert.IsType<InheritsDirectivePass>(feature), feature => Assert.IsType<MetadataAttributePass>(feature), feature => Assert.IsType<PreallocatedTagHelperAttributeOptimizationPass>(feature)); } private static void AssertDefaultDirectives(RazorProjectEngine engine) { var feature = engine.EngineFeatures.OfType<IRazorDirectiveFeature>().FirstOrDefault(); Assert.NotNull(feature); Assert.Collection( feature.Directives, directive => Assert.Same(FunctionsDirective.Directive, directive), directive => Assert.Same(ImplementsDirective.Directive, directive), directive => Assert.Same(InheritsDirective.Directive, directive)); } private static void AssertDefaultTargetExtensions(RazorProjectEngine engine) { var feature = engine.EngineFeatures.OfType<IRazorTargetExtensionFeature>().FirstOrDefault(); Assert.NotNull(feature); var extensions = feature.TargetExtensions.OrderBy(f => f.GetType().Name).ToArray(); Assert.Collection( extensions, extension => Assert.IsType<DefaultTagHelperTargetExtension>(extension), extension => Assert.IsType<DesignTimeDirectiveTargetExtension>(extension), extension => Assert.IsType<MetadataAttributeTargetExtension>(extension), extension => Assert.IsType<PreallocatedAttributeTargetExtension>(extension)); } } }
using System.Collections.Generic; using Newtonsoft.Json; namespace Nordigen.Net.Requests; public class Agreement { [JsonConstructor] public Agreement( string institutionId, int maxHistoricalDays, int accessValidForDays, List<string> accessScope ) { MaxHistoricalDays = maxHistoricalDays; AccessValidForDays = accessValidForDays; AccessScope = accessScope; InstitutionId = institutionId; } [JsonProperty("max_historical_days")] public int MaxHistoricalDays { get; } [JsonProperty("access_valid_for_days")] public int AccessValidForDays { get; } [JsonProperty("access_scope")] public IReadOnlyList<string> AccessScope { get; } [JsonProperty("institution_id")] public string InstitutionId { get; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Reflection; using System.IO; using System.Globalization; using System.Collections; using Libraries.Imaging; using Libraries.Filter; using Frameworks.Plugin; using Libraries.LexicalAnalysis; using Libraries.Extensions; using Libraries.Parsing; using Libraries.Starlight; using Libraries.Tycho; using msg = Libraries.Messaging; namespace ImageProcessingApplication { public partial class MainForm { private void LoadFile(string path) { try { srcImage = new Bitmap(Image.FromFile(path)); source.Visible = true; } catch(Exception) { MessageBox.Show("Error: Given file isn't valid"); } } private void SaveFile(string path) { try { if(result.TargetImage != null) { result.TargetImage.Save(path); } else { MessageBox.Show("Error: Can't Save Resultant Image. None Exists!"); } } catch (Exception) { MessageBox.Show("Error: There was a problem saving the file. Check your permissions"); } } } }
using System; using System.Collections.Generic; using UnityEngine; using Random = UnityEngine.Random; namespace Assets.Scripts.Model { public static class SectorNameManager { private static List<string> _names; static SectorNameManager() { var textAsset = Resources.Load("Settings/system_names") as TextAsset; if (textAsset == null) return; _names = new List<string>(); foreach (string name in textAsset.text.Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries)) { _names.Add(name.Trim()); } } public static string GetName() { return _names[Random.Range(0, _names.Count - 1)]; } } }
using System; using System.IO; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Logging; namespace Netcool.Api.Domain.Files { public static class FileUploadExtensions { public static void UseUploadedStaticFiles(this IApplicationBuilder app, FileUploadOptions fileUploadOptions, ILogger logger) { if (fileUploadOptions == null) return; var path = fileUploadOptions.SubWebPath; if (string.IsNullOrWhiteSpace(fileUploadOptions.PhysicalPath)) { logger.LogWarning("文件物理目录未配置"); } else { if (!Directory.Exists(fileUploadOptions.PhysicalPath)) { try { Directory.CreateDirectory(fileUploadOptions.PhysicalPath); logger.LogWarning($"文件保存物理路径不存在,已自动创建目录:{fileUploadOptions.PhysicalPath}"); } catch (Exception e) { logger.LogWarning(e, $"文件保存物理路径不存在,试图创建失败: {fileUploadOptions.PhysicalPath}"); return; } } app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(fileUploadOptions.PhysicalPath), RequestPath = new PathString($"/{path.Trim('/')}") }); } } } }
using System; using System.Collections.Generic; using UnityEngine; using CommandBuffer = UnityEngine.Rendering.CommandBuffer; namespace OpenTibiaUnity.Core.WorldMap.Rendering { public struct ClassicStatusDescriptor { public bool showNames; public bool showHealth; public bool showMana; public bool showMarks; public bool showIcons; } public struct ClassicStatusRectData { public Matrix4x4 matrix; public Color color; } public struct ClassicStatusFlagData { public Vector4 uv; public Matrix4x4 matrix; } public class WorldMapRenderer { private static readonly Vector3 s_creatureStatSize = new Vector3(27, 4, 1); private int _drawnCreaturesCount = 0; private int _drawnEffectsCount = 0; private int _drawnTextualEffectsCount = 0; private int _maxZPlane = 0; private int _playerZPlane = 0; private float _highlightOpacity = Constants.HighlightMinOpacity; private Vector2Int _hangPixel = Vector2Int.zero; private Vector3Int _hangPattern = Vector3Int.zero; private Creatures.Creature _highlightCreature; private Dictionary<int, CreatureStatus> _creatureStatusCache = new Dictionary<int, CreatureStatus>(); private readonly int[] _minZPlane; private readonly float[] _highlightOpacities; private readonly int[] _creatureCount; private readonly RenderAtom[][] _creatureField; private readonly RenderAtom[] _drawnCreatures; private readonly EffectRenderAtom[] _drawnEffets; private readonly RenderAtom[] _drawnTextualEffets; private TileCursor _tileCursor = new TileCursor(); private Appearances.ObjectInstance _previousHang = null; private LightmapRenderer _lightmapRenderer = new MeshBasedLightmapRenderer(); private Appearances.Rendering.MarksView _creaturesMarksView = new Appearances.Rendering.MarksView(0); protected WorldMapStorage WorldMapStorage { get => OpenTibiaUnity.WorldMapStorage; } protected Creatures.CreatureStorage CreatureStorage { get => OpenTibiaUnity.CreatureStorage; } protected Creatures.Player Player { get => OpenTibiaUnity.Player; } protected Options.OptionStorage OptionStorage { get => OpenTibiaUnity.OptionStorage; } private Rect _lastWorldMapLayerRect = Rect.zero; private Rect _clipRect = Rect.zero; private Vector2 _realScreenTranslation = Vector2.zero; private uint _renderCounter = 0; // initially the first render private uint _lastRenderCounter = 0; private uint _clipRectRenderCounter = 0; private float _lastRenderTime = 0f; public int Framerate { get; private set; } = 0; public Vector3Int? HighlightTile { get; set; } public object HighlightObject { get; set; } public Vector2 ScreenZoom { get; private set; } = new Vector2(); public Vector2 LayerZoom { get; private set; } = new Vector2(); public WorldMapRenderer() { int mapCapacity = Constants.MapSizeX * Constants.MapSizeY; _minZPlane = new int[mapCapacity]; _creatureField = new RenderAtom[mapCapacity][]; _creatureCount = new int[mapCapacity]; _drawnCreatures = new RenderAtom[mapCapacity * Constants.MapSizeW]; for (int i = 0; i < mapCapacity; i++) { _creatureField[i] = new RenderAtom[Constants.MapSizeW]; for (int j = 0; j < Constants.MapSizeW; j++) _creatureField[i][j] = new RenderAtom(); _creatureCount[i] = 0; } for (int i = 0; i < _drawnCreatures.Length; i++) _drawnCreatures[i] = new RenderAtom(); _drawnEffets = new EffectRenderAtom[Constants.NumEffects]; _drawnTextualEffets = new RenderAtom[Constants.NumEffects]; for (int i = 0; i < _drawnTextualEffets.Length; i++) { _drawnEffets[i] = new EffectRenderAtom(); _drawnTextualEffets[i] = new RenderAtom(); } _creaturesMarksView.AddMarkToView(MarkType.ClientMapWindow, Constants.MarkThicknessBold); _creaturesMarksView.AddMarkToView(MarkType.Permenant, Constants.MarkThicknessBold); _creaturesMarksView.AddMarkToView(MarkType.OneSecondTemp, Constants.MarkThicknessBold); _tileCursor.FrameDuration = 100; _highlightOpacities = new float[8 * 2 - 2]; for (int i = 0; i < 8; i++) _highlightOpacities[i] = Constants.HighlightMinOpacity + (i / 7f) * (Constants.HighlightMaxOpacity - Constants.HighlightMinOpacity); for (int i = 1; i < 7; i++) _highlightOpacities[7 + i] = Constants.HighlightMaxOpacity - (i / 7f) * (Constants.HighlightMaxOpacity - Constants.HighlightMinOpacity); } public Rect CalculateClipRect() { if (_clipRectRenderCounter == _renderCounter) return _clipRect; float width = Constants.WorldMapRealWidth; float height = Constants.WorldMapRealHeight; // (0, 0) respects to the bottomleft float x = 2 * Constants.FieldSize + Player.AnimationDelta.x; float y = Constants.FieldSize - Player.AnimationDelta.y; width /= Constants.WorldMapScreenWidth; x /= Constants.WorldMapScreenWidth; height /= Constants.WorldMapScreenHeight; y /= Constants.WorldMapScreenHeight; _clipRect = new Rect(x, y, width, height); _clipRectRenderCounter = _renderCounter; return _clipRect; } public RenderError RenderWorldMap(Rect worldMapLayerRect, RenderTexture renderTarget) { if (WorldMapStorage == null || CreatureStorage == null || Player == null || !WorldMapStorage.Valid) return RenderError.WorldMapNotValid; _lastWorldMapLayerRect = worldMapLayerRect; if (_lastWorldMapLayerRect.width < Constants.WorldMapMinimumWidth || _lastWorldMapLayerRect.height < Constants.WorldMapMinimumHeight) return RenderError.SizeNotEffecient; var screenSize = new Vector2(Screen.width, Screen.height); ScreenZoom = new Vector2(screenSize.x / Constants.WorldMapScreenWidth, screenSize.y / Constants.WorldMapScreenHeight); LayerZoom = new Vector2(_lastWorldMapLayerRect.width / Constants.WorldMapRealWidth, _lastWorldMapLayerRect.height / Constants.WorldMapRealHeight); WorldMapStorage.Animate(); CreatureStorage.Animate(); _highlightOpacity = _highlightOpacities[(OpenTibiaUnity.TicksMillis / Constants.HighlightObjectOpacityInterval) % _highlightOpacities.Length]; _drawnCreaturesCount = 0; _drawnTextualEffectsCount = 0; _renderCounter++; if (Time.time - _lastRenderTime > 0.5f) { var currentTime = Time.time; Framerate = (int)((_renderCounter - _lastRenderCounter) / (currentTime - _lastRenderTime)); _lastRenderTime = currentTime; _lastRenderCounter = _renderCounter; } _playerZPlane = WorldMapStorage.ToMap(Player.Position).z; UpdateMinMaxZPlane(); if (HighlightObject is Creatures.Creature tmpCreature) _highlightCreature = tmpCreature; else if (HighlightObject is Appearances.ObjectInstance tmpObject && tmpObject.IsCreature) _highlightCreature = CreatureStorage.GetCreature(tmpObject.Data); else _highlightCreature = null; var commandBuffer = new CommandBuffer(); if (renderTarget) { commandBuffer.SetRenderTarget(renderTarget); commandBuffer.ClearRenderTarget(false, true, Color.black); } commandBuffer.SetViewMatrix( Matrix4x4.TRS(Vector3.zero, Quaternion.identity, ScreenZoom) * OpenTibiaUnity.GameManager.MainCamera.worldToCameraMatrix); for (int z = 0; z <= _maxZPlane; z++) { for (int i = 0; i < _creatureCount.Length; i++) _creatureCount[i] = 0; _drawnEffectsCount = 0; InternalUpdateFloor(z); InternalDrawFields(commandBuffer, z); if (OpenTibiaUnity.GameManager.ClientVersion >= 1200) InternalDrawEffects(commandBuffer); } if (OptionStorage.ShowLightEffects) { var lightmapMesh = _lightmapRenderer.CreateLightmap(); var position = new Vector3(Constants.FieldSize / 2, Constants.FieldSize / 2, 0); var scale = new Vector2(Constants.FieldSize, -Constants.FieldSize); var transformation = Matrix4x4.TRS(position, Quaternion.Euler(180, 0, 0), scale); commandBuffer.DrawMesh(lightmapMesh, transformation, OpenTibiaUnity.GameManager.LightmapMaterial); } Graphics.ExecuteCommandBuffer(commandBuffer); commandBuffer.Dispose(); return RenderError.None; } public void RenderOnscreenText(Rect viewport, RenderTexture renderTarget) { _realScreenTranslation = viewport.position; var commandBuffer = new CommandBuffer(); commandBuffer.name = "OnscreenText"; if (renderTarget) { commandBuffer.SetRenderTarget(renderTarget); commandBuffer.ClearRenderTarget(false, true, Utils.GraphicsUtility.TransparentColor); } InternelDrawCreatureStatus(commandBuffer); InternalDrawTextualEffects(commandBuffer); InternalDrawOnscreenMessages(commandBuffer); Graphics.ExecuteCommandBuffer(commandBuffer); commandBuffer.Dispose(); } private void UpdateMinMaxZPlane() { _maxZPlane = Constants.MapSizeZ - 1; while (_maxZPlane > _playerZPlane && WorldMapStorage.GetObjectPerLayer(_maxZPlane) <= 0) _maxZPlane--; for (int x = Constants.PlayerOffsetX - 1; x <= Constants.PlayerOffsetX + 1; x++) { for (int y = Constants.PlayerOffsetY - 1; y <= Constants.PlayerOffsetY + 1; y++) { if (!(x != Constants.PlayerOffsetX && y != Constants.PlayerOffsetY || !WorldMapStorage.IsLookPossible(x, y, _playerZPlane))) { int z = _playerZPlane + 1; while (z - 1 < _maxZPlane && x + _playerZPlane - z >= 0 && y + _playerZPlane - z >= 0) { var @object = WorldMapStorage.GetObject(x + _playerZPlane - z, y + _playerZPlane - z, z, 0); if (!!@object && !!@object.Type && @object.Type.IsGround && !@object.Type.IsDontHide) { _maxZPlane = z - 1; continue; } @object = WorldMapStorage.GetObject(x, y, z, 0); if (!!@object && !!@object.Type && (@object.Type.IsGround || @object.Type.IsBottom) && !@object.Type.IsDontHide) { _maxZPlane = z - 1; continue; } z++; } } } } if (!WorldMapStorage.CacheFullbank) { for (int y = 0; y < Constants.MapSizeY; y++) { for (int x = 0; x < Constants.MapSizeX; x++) { int index = y * Constants.MapSizeX + x; _minZPlane[index] = 0; for (int z = _maxZPlane; z > 0; z--) { bool covered = true, done = false; for (int ix = 0; ix < 2 && !done; ix++) { for (int iy = 0; iy < 2 && !done; iy++) { int mx = x + ix; int my = y + iy; if (mx < Constants.MapSizeX && my < Constants.MapSizeY) { Appearances.ObjectInstance @object = WorldMapStorage.GetObject(mx, my, z, 0); if (!@object || (!!@object.Type && !@object.Type.IsFullGround)) { covered = false; done = true; } } } } if (covered) _minZPlane[index] = z; } } } WorldMapStorage.CacheFullbank = true; } } private void InternalUpdateFloor(int z) { RenderAtom renderAtom; bool aboveGround = Player.Position.z <= 7; int brightness = aboveGround ? WorldMapStorage.AmbientCurrentBrightness : 0; float levelSeparator = OptionStorage.FixedLightLevelSeparator / 100f; for (int x = 0; x < Constants.MapSizeX; x++) { for (int y = 0; y < Constants.MapSizeY; y++) { Field field = WorldMapStorage.GetField(x, y, z); // update field light // todo; this shouldn't be called every frame unless light probes has changed if (OptionStorage.ShowLightEffects) { #if DEBUG UnityEngine.Profiling.Profiler.BeginSample("Lightmesh Level-Separator"); #endif var colorIndex = _lightmapRenderer.ToColorIndex(x, y); if (z == _playerZPlane && z > 0) { var color32 = _lightmapRenderer[colorIndex]; _lightmapRenderer[colorIndex] = Utils.Utility.MulColor32(color32, levelSeparator); } Appearances.ObjectInstance @object; if (z == 0 || (@object = field.ObjectsRenderer[0]) != null && @object.Type.IsGround) { var color = _lightmapRenderer[colorIndex]; _lightmapRenderer.SetFieldBrightness(x, y, brightness, aboveGround); if (z > 0 && field.CacheTranslucent) { color = Utils.Utility.MulColor32(color, levelSeparator); var alterColor = _lightmapRenderer[colorIndex]; if (color.r < alterColor.r) color.r = alterColor.r; if (color.g < alterColor.g) color.g = alterColor.g; if (color.b < alterColor.b) color.b = alterColor.b; _lightmapRenderer[colorIndex] = color; } } if (x > 0 && y > 0 && z < 7 && z == _playerZPlane + WorldMapStorage.Position.z - 8 && WorldMapStorage.IsTranslucent(x - 1, y - 1, z + 1)) _lightmapRenderer.SetFieldBrightness(x, y, WorldMapStorage.AmbientCurrentBrightness, aboveGround); #if DEBUG UnityEngine.Profiling.Profiler.EndSample(); #endif } for (int i = field.ObjectsCount - 1; i >= 0; i--) { var @object = field.ObjectsRenderer[i]; if (!@object.IsCreature) continue; var creature = CreatureStorage.GetCreature(@object.Data); if (!creature) continue; Vector2Int displacement = Vector2Int.zero; if (!!creature.MountOutfit && !!creature.MountOutfit.Type) displacement = creature.MountOutfit.Type.Offset; else if (!!creature.Outfit && !!creature.Outfit.Type) displacement = creature.Outfit.Type.Offset; int positionX = (x + 1) * Constants.FieldSize + creature.AnimationDelta.x - displacement.x; int positionY = (y + 1) * Constants.FieldSize + creature.AnimationDelta.y - displacement.y; int fieldX = (positionX - 1) / Constants.FieldSize; int fieldY = (positionY - 1) / Constants.FieldSize; int fieldIndex = fieldY * Constants.MapSizeX + fieldX; if (!(fieldIndex < 0 || fieldIndex >= Constants.MapSizeX * Constants.MapSizeY)) { RenderAtom[] fieldAtoms = _creatureField[fieldIndex]; int j = 0; while (j < _creatureCount[fieldIndex] && !!(renderAtom = fieldAtoms[j]) && (renderAtom.y < positionY || renderAtom.y == positionY && renderAtom.x <= positionX)) j++; if (j < Constants.MapSizeZ) { if (_creatureCount[fieldIndex] < Constants.MapSizeW) _creatureCount[fieldIndex]++; renderAtom = fieldAtoms[_creatureCount[fieldIndex] - 1]; for (int k = _creatureCount[fieldIndex] - 1; k > j; k--) fieldAtoms[k] = fieldAtoms[k - 1]; fieldAtoms[j] = renderAtom; renderAtom.Update(creature, positionX, positionY, z, fieldX, fieldY); } } } } } } private void InternalDrawFields(CommandBuffer commandBuffer, int z) { var absolutePosition = WorldMapStorage.ToAbsolute(new Vector3Int(0, 0, z)); int size = Constants.MapSizeX + Constants.MapSizeY; for (int i = 0; i < size; i++) { int y = Math.Max(i - Constants.MapSizeX + 1, 0); int x = Math.Min(i, Constants.MapSizeX - 1); while (x >= 0 && y < Constants.MapSizeY) { InternalDrawField(commandBuffer, (x + 1) * Constants.FieldSize, (y + 1) * Constants.FieldSize, absolutePosition.x + x, absolutePosition.y + y, absolutePosition.z, x, y, z, true); x--; y++; } if (OptionStorage.HighlightMouseTarget && HighlightTile.HasValue && HighlightTile.Value.z == z) _tileCursor.Draw(commandBuffer, (HighlightTile.Value.x + 1) * Constants.FieldSize, (HighlightTile.Value.y + 1) * Constants.FieldSize, OpenTibiaUnity.TicksMillis); } } private void InternalDrawField(CommandBuffer commandBuffer, int rectX, int rectY, int absoluteX, int absoluteY, int absoluteZ, int positionX, int positionY, int positionZ, bool drawLyingObjects) { Field field = WorldMapStorage.GetField(positionX, positionY, positionZ); int objectsCount = field.ObjectsCount; int fieldIndex = positionY * Constants.MapSizeX + positionX; bool isCovered = positionZ > _minZPlane[fieldIndex] || (positionX == 0 || positionZ >= _minZPlane[fieldIndex - 1]) || (positionY == 0 || positionZ >= _minZPlane[fieldIndex - Constants.MapSizeX]) || (positionX == 0 && positionY == 0 || positionZ >= _minZPlane[fieldIndex - Constants.MapSizeX - 1]); int objectsHeight = 0; // draw ground/bottom objects if (drawLyingObjects && objectsCount > 0 && isCovered) InternalDrawFieldObjects(commandBuffer, rectX, rectY, absoluteX, absoluteY, absoluteZ, positionX, positionY, positionZ, field, ref objectsHeight); // draw creatures InternalDrawFieldCreatures(commandBuffer, positionX, positionY, positionZ, drawLyingObjects, isCovered, objectsHeight); // draw effects InternalDrawFieldEffects(commandBuffer, rectX, rectY, absoluteX, absoluteY, absoluteZ, positionZ, drawLyingObjects, field, objectsHeight); // draw top objects if (drawLyingObjects) InternalDrawFieldTopObjects(commandBuffer, rectX, rectY, absoluteX, absoluteY, absoluteZ, field); } private void InternalDrawFieldObjects(CommandBuffer commandBuffer, int rectX, int rectY, int absoluteX, int absoluteY, int absoluteZ, int positionX, int positionY, int positionZ, Field field, ref int objectsHeight) { Appearances.ObjectInstance hangObject = null; bool isLying = false; // draw Items in reverse order for (int i = 0; i < field.ObjectsCount; i++) { var @object = field.ObjectsRenderer[i]; var type = @object.Type; if (@object.IsCreature || type.IsTop) break; if (OptionStorage.ShowLightEffects && type.IsLight) { // check how correct those are int lightX = (rectX - objectsHeight - (int)type.OffsetX) / Constants.FieldSize; int lightY = (rectY - objectsHeight - (int)type.OffsetY) / Constants.FieldSize; Color32 color32 = Colors.ColorFrom8Bit((byte)type.LightColor); _lightmapRenderer.SetLightSource(lightX, lightY, positionZ, type.Brightness, color32); } var screenPosition = new Vector2Int(rectX - objectsHeight, rectY - objectsHeight); bool highlighted = HighlightObject is Appearances.ObjectInstance && HighlightObject == @object; @object.Draw(commandBuffer, screenPosition, absoluteX, absoluteY, absoluteZ, highlighted, _highlightOpacity); isLying = isLying || type.IsLyingCorpse; if (type.IsHangable && @object.Hang == Appearances.AppearanceInstance.HookSouth) hangObject = @object; if (type.HasElevation) objectsHeight = Mathf.Min(objectsHeight + (int)type.Elevation, Constants.FieldHeight); } // lying tile, draw lying tile if (isLying) { if (positionX > 0 && positionY > 0) InternalDrawField(commandBuffer, rectX - Constants.FieldSize, rectY - Constants.FieldSize, absoluteX - 1, absoluteY - 1, absoluteZ, positionX - 1, positionY - 1, positionZ, false); else if (positionX > 0) InternalDrawField(commandBuffer, rectX - Constants.FieldSize, rectY, absoluteX - 1, absoluteY, absoluteZ, positionX - 1, positionY, positionZ, false); else if (positionY > 0) InternalDrawField(commandBuffer, rectX, rectY - Constants.FieldSize, absoluteX, absoluteY - 1, absoluteZ, positionX, positionY - 1, positionZ, false); } // draw hang object if (!!_previousHang) { bool highlighted = HighlightObject is Appearances.ObjectInstance && HighlightObject == _previousHang; _previousHang.Draw(commandBuffer, _hangPixel, _hangPattern.x, _hangPattern.y, _hangPattern.z, highlighted, _highlightOpacity); _previousHang = null; } if (!!hangObject) { _previousHang = hangObject; _hangPixel.Set(rectX, rectY); _hangPattern.Set(absoluteX, absoluteY, absoluteZ); } } private void InternalDrawFieldCreatures(CommandBuffer commandBuffer, int positionX, int positionY, int positionZ, bool drawLyingObjects, bool isCovered, int objectsHeight) { RenderAtom[] renderAtomArray = _creatureField[positionY * Constants.MapSizeX + positionX]; int creatureCount = _creatureCount[positionY * Constants.MapSizeX + positionX]; for (int i = creatureCount - 1; i >= 0; i--) { RenderAtom renderAtom; Creatures.Creature creature; if (!(renderAtom = renderAtomArray[i]) || !(creature = renderAtom.Object as Creatures.Creature) || !creature.Outfit) continue; if (drawLyingObjects) { renderAtom.x -= objectsHeight; renderAtom.y -= objectsHeight; } bool highlighted = !!_highlightCreature && _highlightCreature.Id == creature.Id; // marks if (creature.Marks.AnyMarkSet()) _creaturesMarksView.DrawMarks(commandBuffer, creature.Marks, renderAtom.x, renderAtom.y, ScreenZoom); var offset = Vector2Int.zero; if (isCovered && !!creature.MountOutfit) { offset += creature.MountOutfit.Type.Offset; var screenPosition = new Vector2Int(renderAtom.x + offset.x, renderAtom.y + offset.y); creature.MountOutfit.Draw(commandBuffer, screenPosition, (int)creature.Direction, 0, 0, highlighted, _highlightOpacity); } if (isCovered) { offset += creature.Outfit.Type.Offset; var screenPosition = new Vector2Int(renderAtom.x + offset.x, renderAtom.y + offset.y); creature.Outfit.Draw(commandBuffer, screenPosition, (int)creature.Direction, 0, !!creature.MountOutfit ? 1 : 0, highlighted, _highlightOpacity); } if (positionZ == _playerZPlane && (CreatureStorage.IsOpponent(creature) || creature.Id == Player.Id)) { _drawnCreatures[_drawnCreaturesCount].Assign(renderAtom); _drawnCreaturesCount++; } if (isCovered && drawLyingObjects && OptionStorage.ShowLightEffects) { int lightX = renderAtom.x / Constants.FieldSize; int lightY = renderAtom.y / Constants.FieldSize; _lightmapRenderer.SetLightSource(lightX, lightY, positionZ, (uint)creature.Brightness, creature.LightColor); if (!!creature.MountOutfit && creature.MountOutfit.Type.IsLight) { var color = Colors.ColorFrom8Bit((byte)creature.MountOutfit.Type.LightColor); _lightmapRenderer.SetLightSource(lightX, lightY, positionZ, creature.MountOutfit.Type.Brightness, color); } if (!!creature.Outfit && creature.Outfit.Type.IsLight) { var color = Colors.ColorFrom8Bit((byte)creature.Outfit.Type.LightColor); _lightmapRenderer.SetLightSource(lightX, lightY, positionZ, creature.Outfit.Type.Brightness, color); } if (creature.Id == Player.Id && creature.Brightness < 2) { var color = new Color32(255, 255, 255, 255); _lightmapRenderer.SetLightSource(lightX, lightY, positionZ, 2, color); } } } } private void InternalDrawFieldEffects(CommandBuffer commandBuffer, float rectX, float rectY, int absoluteX, int absoluteY, int absoluteZ, int positionZ, bool drawLyingObjects, Field field, int objectsHeight) { int effectRectX = (int)rectX - objectsHeight; int effectRectY = (int)rectY - objectsHeight; int effectLightX = effectRectX / Constants.FieldSize; int effectLightY = effectRectY / Constants.FieldSize; int totalTextualEffectsWidth = 0; int lastTextualEffectY = 0; int i = field.EffectsCount - 1; while (i >= 0 && (_drawnEffectsCount + _drawnTextualEffectsCount) <= Constants.NumEffects) { var effect = field.Effects[i]; i--; if (!effect) continue; if (effect is Appearances.TextualEffectInstance textualEffect) { if (drawLyingObjects) { var renderAtom = _drawnTextualEffets[_drawnTextualEffectsCount]; int x = effectRectX + Constants.FieldSize / 2 + totalTextualEffectsWidth; int y = effectRectY + Constants.FieldSize / 8 - 2 * textualEffect.Phase; renderAtom.Update(textualEffect, x, y, 0); if (renderAtom.y + textualEffect.Height > lastTextualEffectY) totalTextualEffectsWidth += (int)textualEffect.Width; if (totalTextualEffectsWidth < 2 * Constants.FieldSize) { _drawnTextualEffectsCount++; lastTextualEffectY = renderAtom.y; } } } else { var screenPosition = new Vector2Int(effectRectX, effectRectY); uint brightness = effect.Type.Brightness; if (effect is Appearances.MissileInstance missile) { screenPosition.x += missile.AnimationDelta.x; screenPosition.y += missile.AnimationDelta.y; uint activeBrightness = (uint)((Math.Min(effect.Phase, effect.Type.FrameGroups[0].SpriteInfo.Phases + 1 - effect.Phase) * effect.Type.Brightness + 2) / 3); brightness = Math.Min(brightness, activeBrightness); } if (OpenTibiaUnity.GameManager.ClientVersion >= 1200) { var renderAtom = _drawnEffets[_drawnEffectsCount]; int x = screenPosition.x; int y = screenPosition.y; renderAtom.Update(effect, x, y, (int)brightness, absoluteX, absoluteY, absoluteZ, positionZ, effectLightX, effectLightY); _drawnEffectsCount++; } else { effect.Draw(commandBuffer, screenPosition, absoluteX, absoluteY, absoluteZ); if (drawLyingObjects && OptionStorage.ShowLightEffects && effect.Type.IsLight) { var color = Colors.ColorFrom8Bit((byte)effect.Type.LightColor); _lightmapRenderer.SetLightSource(effectLightX, effectLightY, positionZ, brightness, color); } } } } } private void InternalDrawFieldTopObjects(CommandBuffer commandBuffer, int rectX, int rectY, int absoluteX, int absoluteY, int absoluteZ, Field field) { var screenPosition = new Vector2Int(rectX, rectY); for (int i = 0; i < field.ObjectsCount; i++) { var @object = field.ObjectsRenderer[i]; if (@object.Type.IsTop) { bool highlighted = HighlightObject is Appearances.ObjectInstance && HighlightObject == @object; @object.Draw(commandBuffer, screenPosition, absoluteX, absoluteY, absoluteZ, highlighted, _highlightOpacity); } } } private void InternelDrawCreatureStatus(CommandBuffer commandBuffer) { int playerIndex = -1; var gameManager = OpenTibiaUnity.GameManager; var optionStorage = OpenTibiaUnity.OptionStorage; var rectDrawData = new List<ClassicStatusRectData>(Constants.MaxCreatureCount * 4); var flagDrawData = new List<ClassicStatusFlagData>(Constants.MaxCreatureCount * 4); var speechDrawData = new List<ClassicStatusFlagData>(Constants.MaxCreatureCount * 4); var descriptor = new ClassicStatusDescriptor() { showNames = optionStorage.ShowNameForOtherCreatures, showMana = false, showMarks = optionStorage.ShowMarksForOtherCreatures, showIcons = optionStorage.ShowNPCIcons, }; for (int i = 0; i < _drawnCreaturesCount; i++) { var renderAtom = _drawnCreatures[i]; var creature = renderAtom.Object as Creatures.Creature; if (!creature) continue; if (creature.Id == Player.Id) { playerIndex = i; } else if (optionStorage.ShowHUDForOtherCreatures) { int positionX = (renderAtom.x - Constants.FieldSize) / Constants.FieldSize; int positionY = (renderAtom.y - Constants.FieldSize) / Constants.FieldSize; descriptor.showHealth = optionStorage.ShowHealthForOtherCreatures && (!creature.IsNPC || !gameManager.GetFeature(GameFeature.GameHideNpcNames)); InternelDrawCreatureStatusClassic(commandBuffer, creature, rectDrawData, flagDrawData, speechDrawData, renderAtom.x - Constants.FieldSize, renderAtom.y - Constants.FieldSize, renderAtom.z >= _minZPlane[positionY * Constants.MapSizeX + positionX], descriptor); } } if (playerIndex != -1) { var renderAtom = _drawnCreatures[playerIndex]; descriptor.showNames = optionStorage.ShowNameForOwnCharacter; descriptor.showHealth = optionStorage.ShowHealthForOwnCharacter; descriptor.showMana = optionStorage.ShowManaForOwnCharacter; descriptor.showMarks = optionStorage.ShowMarksForOwnCharacter; descriptor.showIcons = false; InternelDrawCreatureStatusClassic(commandBuffer, Player, rectDrawData, flagDrawData, speechDrawData, renderAtom.x - Constants.FieldSize, renderAtom.y - Constants.FieldSize, true, descriptor); } var appearanceMaterial = OpenTibiaUnity.GameManager.AppearanceTypeMaterial; var coloredMaterial = OpenTibiaUnity.GameManager.ColoredMaterial; if (SystemInfo.supportsInstancing) { var matrixArray = new Matrix4x4[rectDrawData.Count]; var exArray = new Vector4[rectDrawData.Count]; for (int i = 0; i < rectDrawData.Count; i++) { var data = rectDrawData[i]; matrixArray[i] = data.matrix; exArray[i] = data.color; } var matriciesToPass = new Matrix4x4[1023]; var exToPass = new Vector4[1023]; for (int i = 0; i < matrixArray.Length; i += 1023) { int sliceSize = Mathf.Min(1023, matrixArray.Length - i); Array.Copy(matrixArray, i, matriciesToPass, 0, sliceSize); Array.Copy(exArray, i, exToPass, 0, sliceSize); MaterialPropertyBlock props = new MaterialPropertyBlock(); props.SetVectorArray("_Color", exToPass); Utils.GraphicsUtility.DrawTextureInstanced(commandBuffer, matriciesToPass, sliceSize, coloredMaterial, props); } var drawDataArray = new List<ClassicStatusFlagData>[] { flagDrawData, speechDrawData }; var textureArray = new Texture2D[] { OpenTibiaUnity.GameManager.StateFlagsTexture, OpenTibiaUnity.GameManager.SpeechFlagsTexture }; for (int i = 0; i < drawDataArray.Length; i++) { var drawData = drawDataArray[i]; var texture = textureArray[i]; matrixArray = new Matrix4x4[drawData.Count]; exArray = new Vector4[drawData.Count]; for (int j = 0; j < drawData.Count; j++) { var data = drawData[j]; matrixArray[j] = data.matrix; exArray[j] = data.uv; } for (int j = 0; j < matrixArray.Length; j += 1023) { int sliceSize = Mathf.Min(1023, matrixArray.Length - j); Array.Copy(matrixArray, j, matriciesToPass, 0, sliceSize); Array.Copy(exArray, j, exToPass, 0, sliceSize); MaterialPropertyBlock props = new MaterialPropertyBlock(); props.SetTexture("_MainTex", texture); props.SetVectorArray("_MainTex_UV", exToPass); Utils.GraphicsUtility.DrawTextureInstanced(commandBuffer, matriciesToPass, sliceSize, appearanceMaterial, props); } } } else { foreach (var data in rectDrawData) { MaterialPropertyBlock props = new MaterialPropertyBlock(); props.SetColor("_Color", data.color); Utils.GraphicsUtility.DrawTexture(commandBuffer, data.matrix, coloredMaterial, props); } var statesTexture = OpenTibiaUnity.GameManager.StateFlagsTexture; foreach (var data in flagDrawData) { MaterialPropertyBlock props = new MaterialPropertyBlock(); props.SetTexture("_MainTex", statesTexture); props.SetVector("_MainTex_UV", data.uv); Utils.GraphicsUtility.DrawTexture(commandBuffer, data.matrix, appearanceMaterial, props); } var speechTexture = OpenTibiaUnity.GameManager.SpeechFlagsTexture; foreach (var data in speechDrawData) { MaterialPropertyBlock props = new MaterialPropertyBlock(); props.SetTexture("_MainTex", speechTexture); props.SetVector("_MainTex_UV", data.uv); Utils.GraphicsUtility.DrawTexture(commandBuffer, data.matrix, appearanceMaterial, props); } } } private void InternalDrawEffects(CommandBuffer commandBuffer) { for (int i = 0; i < _drawnEffectsCount; i++) { var renderAtom = _drawnEffets[i]; if (renderAtom.Object is Appearances.AppearanceInstance effect) { var screenPosition = new Vector2Int(renderAtom.x, renderAtom.y); effect.Draw(commandBuffer, screenPosition, renderAtom.fieldX, renderAtom.fieldY, renderAtom.fieldZ); if (OptionStorage.ShowLightEffects && effect.Type.IsLight) { var color = Colors.ColorFrom8Bit((byte)effect.Type.LightColor); _lightmapRenderer.SetLightSource(renderAtom.lightX, renderAtom.lightY, renderAtom.positionZ, (uint)renderAtom.z, color); } } } } private void InternalDrawTextualEffects(CommandBuffer commandBuffer) { for (int i = 0; i < _drawnTextualEffectsCount; i++) { var renderAtom = _drawnTextualEffets[i]; if (renderAtom.Object is Appearances.TextualEffectInstance textualEffect) { var pos = new Vector2(renderAtom.x, renderAtom.y); pos.x = (pos.x - 2 * Constants.FieldSize) * LayerZoom.x + _realScreenTranslation.x; pos.y = (pos.y - 2 * Constants.FieldSize) * LayerZoom.y + _realScreenTranslation.y; pos.x -= Player.AnimationDelta.x * LayerZoom.x; pos.y -= Player.AnimationDelta.y * LayerZoom.y; textualEffect.Draw(commandBuffer, new Vector2Int((int)pos.x, (int)pos.y), 0, 0, 0); } } } private void InternalDrawOnscreenMessages(CommandBuffer commandBuffer) { if (WorldMapStorage.LayoutOnscreenMessages) { InternalLayoutOnscreenMessages(); WorldMapStorage.LayoutOnscreenMessages = false; } var messageBoxes = WorldMapStorage.MessageBoxes; float animationDeltaX = 0; float animationDeltaY = 0; if (Player != null) { animationDeltaX = Player.AnimationDelta.x * LayerZoom.x; animationDeltaY = Player.AnimationDelta.y * LayerZoom.y; } float bottomBoxHeight = 0; var bottomBox = messageBoxes[(int)MessageScreenTargets.BoxBottom]; if (bottomBox != null && bottomBox.Visible && !bottomBox.Empty) bottomBoxHeight = bottomBox.Height; for (int i = messageBoxes.Count - 1; i >= (int)MessageScreenTargets.BoxLow; i--) { var messageBox = messageBoxes[i]; if (messageBox != null && messageBox.Visible && !messageBox.Empty) { var messagePosition = new Vector2(messageBox.X, messageBox.Y); // if this text should be fixed to player's screen, then move it with his animation if ((messageBox.Fixing & OnscreenMessageFixing.X) == 0) messagePosition.x -= animationDeltaX; if ((messageBox.Fixing & OnscreenMessageFixing.Y) == 0) messagePosition.y -= animationDeltaY; //messagePosition.x = Mathf.Clamp(messagePosition.x, messageBox.Width / 2, Constants.WorldMapRealWidth - messageBox.Width / 2); //messagePosition.y = Mathf.Clamp(messagePosition.y, messageBox.Height / 2, Constants.WorldMapRealHeight - bottomBoxHeight - messageBox.Height / 2); for (int j = 0; j < messageBox.VisibleMessages; j++) { var message = messageBox.GetMessage(j); var screenPosition = Vector2.zero; screenPosition.x = messagePosition.x; // if we have passed half the message, start aligning to the bottom screenPosition.y = messagePosition.y - (messageBox.Height - message.Height) / 2; message.Draw(commandBuffer, screenPosition + _realScreenTranslation); messagePosition.y += message.Height; } } } if (bottomBox != null && bottomBox.Visible && !bottomBox.Empty) { var message = bottomBox.GetMessage(0); var messagePosition = new Vector2() { x = Constants.WorldMapRealWidth * LayerZoom.x / 2, y = Constants.WorldMapRealHeight * LayerZoom.y - (message.Height + Constants.OnscreenMessageGap) / 2 }; message.Draw(commandBuffer, messagePosition + _realScreenTranslation); } } private void InternelDrawCreatureStatusClassic(CommandBuffer commandBuffer, Creatures.Creature creature, List<ClassicStatusRectData> rectData, List<ClassicStatusFlagData> flagData, List<ClassicStatusFlagData> speechData, int rectX, int rectY, bool visible, ClassicStatusDescriptor descriptor) { bool isLocalPlayer = creature.Id == Player.Id; Color32 healthColor, manaColor; int healthIdentifier; if (visible) { healthIdentifier = creature.HealthPercent; healthColor = Creatures.Creature.GetHealthColor(creature.HealthPercent); manaColor = Colors.ColorFromRGB(0, 0, 255); } else { healthIdentifier = 192; healthColor = Colors.ColorFromRGB(192, 192, 192); manaColor = Colors.ColorFromRGB(192, 192, 192); } if (OptionStorage.ShowLightEffects) { float mod = _lightmapRenderer.CalculateCreatureBrightnessFactor(creature, isLocalPlayer); healthIdentifier += (byte)(255 * mod); healthColor = Utils.Utility.MulColor32(healthColor, mod); manaColor = Utils.Utility.MulColor32(manaColor, mod); } float minimumY = 0; float neededHeight = 0; CreatureStatus status = null; if (descriptor.showNames) { status = GetCreatureStatusCache(creature.Name, healthIdentifier, healthColor); neededHeight += status.Height / 2 + 1; minimumY = status.Height; } if (descriptor.showHealth) neededHeight += 4 + 1; if (descriptor.showMana) neededHeight += 4 + 1; var initialScreenPosition = new Vector2 { x = (rectX - Constants.FieldSize / 2 - Player.AnimationDelta.x) * LayerZoom.x + _realScreenTranslation.x, y = (rectY - Constants.FieldSize - Player.AnimationDelta.y) * LayerZoom.y + _realScreenTranslation.y }; initialScreenPosition.y = Mathf.Clamp(initialScreenPosition.y, minimumY, Constants.WorldMapRealHeight * LayerZoom.y - neededHeight); var screenPosition = initialScreenPosition; screenPosition.y -= neededHeight; if (screenPosition.y < minimumY) screenPosition.y = minimumY; if (descriptor.showNames) { status.Draw(commandBuffer, screenPosition); screenPosition.y += (status.Height / 2) + 1; } if (descriptor.showHealth || descriptor.showMana) { var basePosition = new Vector2(screenPosition.x - 27 / 2f, screenPosition.y); var actualPosition = new Vector2(basePosition.x + 1, basePosition.y + 1); if (descriptor.showHealth) { rectData.Add(new ClassicStatusRectData() { matrix = Matrix4x4.TRS(basePosition, Quaternion.Euler(180, 0, 0), s_creatureStatSize), color = Color.black }); rectData.Add(new ClassicStatusRectData() { matrix = Matrix4x4.TRS(actualPosition, Quaternion.Euler(180, 0, 0), new Vector3(creature.HealthPercent / 4f, 2, 1)), color = healthColor }); screenPosition.y += 4 + 1; basePosition.y += 4 + 1; actualPosition.y += 4 + 1; } if (descriptor.showMana) { rectData.Add(new ClassicStatusRectData() { matrix = Matrix4x4.TRS(basePosition, Quaternion.Euler(180, 0, 0), s_creatureStatSize), color = Color.black }); rectData.Add(new ClassicStatusRectData() { matrix = Matrix4x4.TRS(actualPosition, Quaternion.Euler(180, 0, 0), new Vector3(creature.ManaPercent / 4f, 2, 1)), color = manaColor }); screenPosition.y += 4 + 1; } } if (descriptor.showMarks && !creature.IsNPC || descriptor.showIcons && creature.IsNPC) InternalDrawCreatureFlags(creature, flagData, speechData, (int)initialScreenPosition.x, (int)initialScreenPosition.y, visible); } private void InternalDrawCreatureFlags(Creatures.Creature creature, List<ClassicStatusFlagData> flagData, List<ClassicStatusFlagData> speechData, float rectX, float rectY, bool visible) { if (!creature.HasFlag) return; var screenPosition = new Vector2(rectX + 16 - Constants.StateFlagSize + 4, rectY + 1); var flagSize = new Vector2(Constants.StateFlagSize, Constants.StateFlagSize); int dX = 0; var flagsTexture = OpenTibiaUnity.GameManager.StateFlagsTexture; if (creature.PartyFlag > PartyFlag.None) { var r = NormalizeFlagRect(GetPartyFlagTextureRect(creature.PartyFlag), flagsTexture); flagData.Add(new ClassicStatusFlagData { matrix = Matrix4x4.TRS(screenPosition, Quaternion.Euler(180, 0, 0), flagSize), uv = new Vector4(r.width, r.height, r.x, r.y) }); dX += Constants.StateFlagGap + Constants.StateFlagSize; screenPosition.x += Constants.StateFlagGap + Constants.StateFlagSize; } if (creature.PKFlag > PKFlag.None) { var r = NormalizeFlagRect(GetPKFlagTextureRect(creature.PKFlag), flagsTexture); flagData.Add(new ClassicStatusFlagData { matrix = Matrix4x4.TRS(screenPosition, Quaternion.Euler(180, 0, 0), flagSize), uv = new Vector4(r.width, r.height, r.x, r.y) }); screenPosition.x += Constants.StateFlagGap + Constants.StateFlagSize; } if (creature.SummonType > SummonType.None) { var r = NormalizeFlagRect(GetSummonFlagTextureRect(creature.SummonType), flagsTexture); flagData.Add(new ClassicStatusFlagData { matrix = Matrix4x4.TRS(screenPosition, Quaternion.Euler(180, 0, 0), flagSize), uv = new Vector4(r.width, r.height, r.x, r.y) }); dX += Constants.StateFlagGap + Constants.StateFlagSize; screenPosition.x += Constants.StateFlagGap + Constants.StateFlagSize; } var speechCategory = creature.SpeechCategory; if (speechCategory == SpeechCategory.QuestTrader) speechCategory = OpenTibiaUnity.TicksMillis % 2048 <= 1024 ? SpeechCategory.Quest : SpeechCategory.Trader; if (speechCategory > SpeechCategory.None) { var speechTexture = OpenTibiaUnity.GameManager.SpeechFlagsTexture; var r = NormalizeFlagRect(GetSpeechFlagTextureRect(speechCategory), speechTexture); speechData.Add(new ClassicStatusFlagData { matrix = Matrix4x4.TRS(screenPosition, Quaternion.Euler(180, 0, 0), new Vector2(Constants.SpeechFlagSize, Constants.SpeechFlagSize)), uv = new Vector4(r.width, r.height, r.x, r.y) }); dX += Constants.StateFlagGap + Constants.SpeechFlagSize; screenPosition.x += Constants.StateFlagGap + Constants.SpeechFlagSize; } if (dX > 0) screenPosition.x -= dX; var gameManager = OpenTibiaUnity.GameManager; if ((gameManager.GetFeature(GameFeature.GameCreatureMarks) && gameManager.ClientVersion < 1185) || dX > 0) screenPosition.y += Constants.StateFlagGap + Constants.StateFlagSize; if (creature.GuildFlag > GuildFlag.None) { var r = NormalizeFlagRect(GetGuildFlagTextureRect(creature.GuildFlag), flagsTexture); flagData.Add(new ClassicStatusFlagData { matrix = Matrix4x4.TRS(screenPosition, Quaternion.Euler(180, 0, 0), flagSize), uv = new Vector4(r.width, r.height, r.x, r.y) }); screenPosition.y += Constants.StateFlagGap + Constants.StateFlagSize; } if (creature.RisknessFlag > RisknessFlag.None) { var r = NormalizeFlagRect(GetRisknessFlagTextureRect(creature.RisknessFlag), flagsTexture); flagData.Add(new ClassicStatusFlagData { matrix = Matrix4x4.TRS(screenPosition, Quaternion.Euler(180, 0, 0), flagSize), uv = new Vector4(r.width, r.height, r.x, r.y) }); } } private void InternalLayoutOnscreenMessages() { var messageBoxes = WorldMapStorage.MessageBoxes; for (int i = messageBoxes.Count - 1; i >= 0; i--) { var messageBox = WorldMapStorage.MessageBoxes[i]; if (messageBox != null && messageBox.Visible && !messageBox.Empty) messageBox.ArrangeMessages(); } var helperPoint = new Vector2(); var points = new List<Vector2>(); var workerRects = new List<Rect>(); var actualRects = new List<Rect>(); // the screen zoom is mapped to the size of the field, so // in order to match the preferred zoom of the text, we must // multiply the field/screen size by the precaculated zoom // of the text var fieldSize = new Vector2(Constants.FieldSize, Constants.FieldSize) * LayerZoom; var unscaledSize = _lastWorldMapLayerRect.size; for (int i = messageBoxes.Count - 1; i >= (int)MessageScreenTargets.BoxLow; i--) { var messageBox = WorldMapStorage.MessageBoxes[i]; if (messageBox != null && messageBox.Visible && !messageBox.Empty) { if (i == (int)MessageScreenTargets.BoxLow) { messageBox.Fixing = OnscreenMessageFixing.Both; helperPoint.x = unscaledSize.x / 2; helperPoint.y = (unscaledSize.y + fieldSize.y + messageBox.Height + Constants.OnscreenMessageGap) / 2; } else if (i == (int)MessageScreenTargets.BoxHigh) { messageBox.Fixing = OnscreenMessageFixing.Both; helperPoint.x = unscaledSize.x / 2; helperPoint.y = unscaledSize.y / 2; } else if (i == (int)MessageScreenTargets.BoxTop) { messageBox.Fixing = OnscreenMessageFixing.Both; helperPoint.x = unscaledSize.x / 2; helperPoint.y = unscaledSize.y / 4; } else { messageBox.Fixing = OnscreenMessageFixing.None; var closestMapPosition = WorldMapStorage.ToMapClosest(messageBox.Position.Value); helperPoint.x = (closestMapPosition.x - 0.5f) * fieldSize.x + Mathf.Max(0, Constants.FieldSize * Constants.MapWidth * LayerZoom.x - unscaledSize.x) / 2; helperPoint.y = (closestMapPosition.y - 1) * fieldSize.y + Mathf.Max(0, Constants.FieldSize * Constants.MapHeight * LayerZoom.y - unscaledSize.y) / 2; } float w1 = messageBox.Width + Constants.OnscreenMessageGap; float h1 = messageBox.Height + Constants.OnscreenMessageGap; float x1 = helperPoint.x - w1 / 2; float y1 = helperPoint.y - h1 / 2; points.Add(new Vector2(0, 0)); workerRects.Add(new Rect(x1, y1, w1, h1)); actualRects.Add(new Rect(x1 + w1 / 2, y1 - h1 / 2, w1, h1)); } } float sumMagnitude = float.MaxValue; float lastMagnitude; do { lastMagnitude = sumMagnitude; sumMagnitude = 0; for (int i = workerRects.Count - 1; i >= 0; i--) { Vector2 point = Vector2.zero; var rect = workerRects[i]; var tmpLength = rect.size.magnitude; // Explanation: // for every other rectangle, calculate the intersection area // the intersections' sizes are summed together, and then used to move the // the resepctive rectangle either left/right for (int j = workerRects.Count - 1; j >= 0; j--) { if (i == j) continue; var otherRect = workerRects[j]; var intersection = Utils.Utility.Intersect(rect, otherRect); if (intersection != Rect.zero) { var center = new Vector2() { x = Mathf.Floor(rect.x + rect.width / 2) - Mathf.Floor(otherRect.x + otherRect.width / 2), y = Mathf.Floor(rect.y + rect.height / 2) - Mathf.Floor(otherRect.y + otherRect.height / 2) }; sumMagnitude += intersection.width * intersection.height * Mathf.Pow(0.5f, center.magnitude / tmpLength - 1); if (center.x < 0) point.x -= intersection.width; else if (center.x > 0) point.x += intersection.width; if (center.y < 0) point.y -= intersection.height; else if (center.y > 0) point.y += intersection.height; if (center.x == 0 && center.y == 0 && j == workerRects.Count - 1) point.x += i - j; } } points[i] = point; } for (int i = workerRects.Count - 1; i >= 0; i--) { var point = points[i]; var rect = workerRects[i]; var centerRect = actualRects[i]; rect.x = Mathf.Clamp(rect.x + (point.x > 0 ? 1 : -1), centerRect.xMin, centerRect.xMax); rect.y = Mathf.Clamp(rect.y + (point.y > 0 ? 1 : -1), centerRect.yMin, centerRect.yMax); workerRects[i] = rect; } } while (sumMagnitude < lastMagnitude); int pointIndex = 0; for (int i = messageBoxes.Count - 1; i >= (int)MessageScreenTargets.BoxLow; i--) { var messageBox = WorldMapStorage.MessageBoxes[i]; if (messageBox != null && messageBox.Visible && !messageBox.Empty) { var rect = workerRects[pointIndex]; var otherRect = actualRects[pointIndex]; messageBox.X = Mathf.Max(otherRect.xMin, Mathf.Min(rect.x, otherRect.xMax)) + Constants.OnscreenMessageGap / 2; messageBox.Y = Mathf.Max(otherRect.yMin, Mathf.Min(rect.y, otherRect.yMax)) + Constants.OnscreenMessageGap / 2; pointIndex++; } } } private CreatureStatus GetCreatureStatusCache(string name, int identifier, Color color) { int hashCode = string.Format("{0}#{1}", name, identifier).GetHashCode(); if (_creatureStatusCache.TryGetValue(hashCode, out CreatureStatus creatureStatus)) return creatureStatus; creatureStatus = new CreatureStatus(name, color); _creatureStatusCache.Add(hashCode, creatureStatus); return creatureStatus; } private Rect NormalizeFlagRect(Rect rect, Texture2D tex2D) { rect.x /= tex2D.width; rect.y = (tex2D.height - rect.y) / tex2D.height; rect.width /= tex2D.width; rect.height /= tex2D.height; return rect; } private Rect GetPartyFlagTextureRect(PartyFlag partyFlag) { if (partyFlag == PartyFlag.Leader_SharedXP_Inactive_Innocent) partyFlag = PartyFlag.Leader_SharedXP_Inactive_Guilty; else if (partyFlag == PartyFlag.Member_SharedXP_Inactive_Innocent) partyFlag = PartyFlag.Leader_SharedXP_Inactive_Guilty; else if (partyFlag == PartyFlag.Other) partyFlag = PartyFlag.Member_SharedXP_Inactive_Innocent; return new Rect { x = (int)partyFlag * Constants.StateFlagSize, y = Constants.StateFlagSize, width = Constants.StateFlagSize, height = Constants.StateFlagSize }; } private Rect GetPKFlagTextureRect(PKFlag pkFlag) { return new Rect { x = (int)pkFlag * Constants.StateFlagSize, y = 2 * Constants.StateFlagSize, width = Constants.StateFlagSize, height = Constants.StateFlagSize }; } private Rect GetGuildFlagTextureRect(GuildFlag guildFlag) { return new Rect { x = (int)guildFlag * Constants.StateFlagSize, y = 3 * Constants.StateFlagSize, width = Constants.StateFlagSize, height = Constants.StateFlagSize }; } private Rect GetSummonFlagTextureRect(SummonType summonType) { return new Rect { x = (int)summonType * Constants.StateFlagSize, y = 4 * Constants.StateFlagSize, width = Constants.StateFlagSize, height = Constants.StateFlagSize }; } private Rect GetRisknessFlagTextureRect(RisknessFlag riskness) { return new Rect { x = (int)riskness * Constants.StateFlagSize, y = 5 * Constants.StateFlagSize, width = Constants.StateFlagSize, height = Constants.StateFlagSize }; } private Rect GetSpeechFlagTextureRect(SpeechCategory speechCategory) { int x = 0; switch (speechCategory) { case SpeechCategory.Normal: x = 1; break; case SpeechCategory.Trader: x = 2; break; case SpeechCategory.Quest: x = 3; break; case SpeechCategory.QuestTrader: x = 4; break; } return new Rect { x = x * Constants.SpeechFlagSize, y = 0, width = Constants.SpeechFlagSize, height = Constants.SpeechFlagSize }; } public Vector3Int? PointToMap(Vector2 point, bool restrictedToPlayerZPlane) { if (WorldMapStorage == null || (restrictedToPlayerZPlane && !Player)) return null; int x = (int)(point.x / (Constants.FieldSize * LayerZoom.x)) + 1; int y = (int)(point.y / (Constants.FieldSize * LayerZoom.y)) + 1; if (x < 0 || x > Constants.MapWidth || y < 0 || y > Constants.MapHeight) return null; int z; if (restrictedToPlayerZPlane) { z = WorldMapStorage.ToMap(Player.Position).z; } else { int minZ = _minZPlane[y * Constants.MapSizeX + x]; for (z = _maxZPlane; z > minZ; z--) { var field = WorldMapStorage.GetField(x, y, z); for (int i = 0; i < field.ObjectsCount; i++) { var type = field.ObjectsRenderer[i].Type; if ((type.IsGround || type.IsBottom) && !type.IsIgnoreLook) { minZ = -1; break; } } if (minZ < 0) break; } } if (z < 0 || z >= Constants.MapSizeZ) return null; return new Vector3Int(x, y, z); } public Vector3Int? PointToAbsolute(Vector2 point, bool restrictedToPlayerZPlane) { var mapPosition = PointToMap(point, restrictedToPlayerZPlane); if (mapPosition.HasValue) return WorldMapStorage.ToAbsolute(mapPosition.Value); return null; } public Creatures.Creature PointToCreature(Vector2 point, bool restrictedToPlayerZPlane) { if (WorldMapStorage == null || (restrictedToPlayerZPlane && !Player)) return null; int rectX = (int)(point.x / LayerZoom.x) + Constants.FieldSize; int rectY = (int)(point.y / LayerZoom.y) + Constants.FieldSize; int mapX = rectX / Constants.FieldSize; int mapY = rectY / Constants.FieldSize; if (mapX < 0 || mapX > Constants.MapWidth || mapY < 0 || mapY > Constants.MapHeight) return null; int minZ = _minZPlane[mapY * Constants.MapSizeX + mapX]; if (restrictedToPlayerZPlane) minZ = WorldMapStorage.ToMap(Player.Position).z; for (int i = 0; i < _drawnCreaturesCount; i++) { var renderAtom = _drawnCreatures[i]; int renderX = renderAtom.x - Constants.FieldSize / 2; int renderY = renderAtom.y - Constants.FieldSize / 2; if (!(Math.Abs(renderX - rectX) > Constants.FieldSize / 2 || Math.Abs(renderY - rectY) > Constants.FieldSize / 2)) { var creature = renderAtom.Object as Creatures.Creature; if (!!creature && WorldMapStorage.IsVisible(creature.Position, true) && WorldMapStorage.ToMap(creature.Position).z >= minZ) return creature; } } return null; } } }
using Newtonsoft.Json; namespace Miro.Models.Github.RequestPayloads { public class CreateCommentPayload { [JsonProperty(PropertyName = "body")] public string Body; } }
// Copyright (c) Microsoft. All rights reserved. using Microsoft.Azure.IoTSolutions.Auth.Services.Models; using Newtonsoft.Json; namespace Microsoft.Azure.IoTSolutions.Auth.WebService.v1.Models { public class UserApiModel { [JsonProperty(PropertyName = "Id", Order = 10)] public string Id { get; set; } [JsonProperty(PropertyName = "Email", Order = 20)] public string Email { get; set; } [JsonProperty(PropertyName = "Name", Order = 30)] public string Name { get; set; } public UserApiModel(User user) { this.Id = user.Id; this.Email = user.Email; this.Name = user.Name; } } }
using System; using System.Diagnostics; using Flunity.Common; using Flunity.Easing; namespace Flunity { /// <summary> /// Extension methods for creating tween animations on objects. /// </summary> public static class TweenExt { public static Tweener Tween(this Object target) { Debug.Assert(target != null, "target is null"); return TweenManager.instance.Tween(target); } public static Tweener Tween(this Object target, int duration) { Debug.Assert(target != null, "target is null"); return TweenManager.instance.Tween(target).Duration(duration); } public static Tweener Tween<TTarget, TValue>( this TTarget target, int duration, ITweenProperty<TValue> property, TValue to, EasyFunction easing = null) where TTarget : class { Debug.Assert(target != null, "target is null"); return TweenManager.instance.Tween(target, duration, property, to, easing); } public static bool HasAnyTweens(this Object target) { Debug.Assert(target != null, "target is null"); return TweenManager.HasAnyTweensOf(target); } public static object RemoveAllTweens(this Object target) { Debug.Assert(target != null, "target is null"); TweenManager.RemoveAllTweensOf(target); return target; } } }
using AutoMapper; using Microsoft.AspNetCore.Authentication.Twitter; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using RestSharp; using TwitterBackup.Data; using TwitterBackup.Data.Repository; using TwitterBackup.Infrastructure.Providers; using TwitterBackup.Infrastructure.Providers.Contracts; using TwitterBackup.Models; using TwitterBackup.Services.ApiClient; using TwitterBackup.Services.ApiClient.Contracts; using TwitterBackup.Services.Data; using TwitterBackup.Services.Data.Contracts; using TwitterBackup.Services.Email; using TwitterBackup.Services.TwitterAPI; using TwitterBackup.Services.TwitterAPI.Contracts; namespace TwitterBackup.Web { public class Startup { //TODO: review and refactor if needed public Startup(IConfiguration configuration) { this.Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<TwitterDbContext>(options => options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<TwitterDbContext>() .AddDefaultTokenProviders(); services.AddAuthentication().AddTwitter(twitterOptions => { twitterOptions.ConsumerKey = this.Configuration["Authentication:Twitter:ConsumerKey"]; twitterOptions.ConsumerSecret = this.Configuration["Authentication:Twitter:ConsumerSecret"]; }); // Add application services. services.AddTransient<IEmailSender, EmailSender>(); services.AddMvc(options => { options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); //options.Filters.Add(new RequireHttpsAttribute()); }); services.AddMemoryCache(); services.AddResponseCaching(); services.AddAutoMapper(); services.AddScoped(typeof(IRepository<>), typeof(EntityFrameworkRepository<>)); services.AddScoped<IUnitOfWork, EntityFrameworkUnitOfWork>(); services.AddTransient<IEmailSender, EmailSender>(); services.AddScoped<IMappingProvider, MappingProvider>(); services.AddTransient<ITweeterService, TweeterService>(); services.AddTransient<ITweetService, TweetService>(); services.AddTransient<IUserService, UserService>(); services.AddTransient<ITweetApiService, TweetApiService>(); services.AddTransient<ITweeterApiService, TweeterApiService>(); services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddScoped<IApiClient, ApiClient>(); var tokens = new RequestToken(); services.AddScoped<ITwitterAuthenticator>(provider => new TwitterAuthenticator( this.Configuration["Authentication:Twitter:ConsumerKey"], this.Configuration["Authentication:Twitter:ConsumerSecret"], this.Configuration["Authentication:Twitter:AccessToken"], this.Configuration["Authentication:Twitter:AccessTokenSecret"] )); services.AddScoped<IJsonProvider, JsonProvider>(); services.AddScoped<IRestClient, RestClient>(); services.AddScoped<IRestRequest, RestRequest>(); services.AddScoped<IUriFactory, UriFactory>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); } //var options = new RewriteOptions() // //.AddRedirectToHttpsPermanent() // .AddRedirectToHttps(301, 44342); //app.UseRewriter(options); app.UseStaticFiles(); app.UseAuthentication(); app.UseResponseCaching(); app.UseMvc(routes => { routes.MapRoute( name: "areaRoute", template: "{area:exists}/{controller=Statistics}/{action=Index}/{id?}" ); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
namespace WatchMyDrugs.Application.Services.Models { public class DrugListResponse { } }
namespace UglyToad.PdfPig.DocumentLayoutAnalysis.Export.PAGE { using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Xml.Serialization; public partial class PageXmlDocument { /// <remarks/> [EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [GeneratedCode("xsd", "4.6.1055.0")] [Serializable()] [DebuggerStepThrough()] [DesignerCategory("code")] [XmlType(Namespace = "http://schema.primaresearch.org/PAGE/gts/pagecontent/2019-07-15")] public class PageXmlGlyph { #region private private PageXmlAlternativeImage[] alternativeImageField; private PageXmlCoords coordsField; private PageXmlGraphemeBase[] graphemesField; private PageXmlTextEquiv[] textEquivField; private PageXmlTextStyle textStyleField; private PageXmlUserAttribute[] userDefinedField; private PageXmlLabels[] labelsField; private string idField; private bool ligatureField; private bool ligatureFieldSpecified; private bool symbolField; private bool symbolFieldSpecified; private PageXmlScriptSimpleType scriptField; private bool scriptFieldSpecified; private PageXmlProductionSimpleType productionField; private bool productionFieldSpecified; private string customField; private string commentsField; #endregion /// <summary> /// Alternative glyph images (e.g. black-and-white) /// </summary> [XmlElement("AlternativeImage")] public PageXmlAlternativeImage[] AlternativeImages { get { return this.alternativeImageField; } set { this.alternativeImageField = value; } } /// <remarks/> public PageXmlCoords Coords { get { return this.coordsField; } set { this.coordsField = value; } } /// <summary> /// Container for graphemes, grapheme groups and non-printing characters /// </summary> [XmlArrayItem("Grapheme", typeof(PageXmlGrapheme), IsNullable = false)] [XmlArrayItem("GraphemeGroup", typeof(PageXmlGraphemeGroup), IsNullable = false)] [XmlArrayItem("NonPrintingChar", typeof(PageXmlNonPrintingChar), IsNullable = false)] public PageXmlGraphemeBase[] Graphemes { get { return this.graphemesField; } set { this.graphemesField = value; } } /// <remarks/> [XmlElement("TextEquiv")] public PageXmlTextEquiv[] TextEquivs { get { return this.textEquivField; } set { this.textEquivField = value; } } /// <remarks/> public PageXmlTextStyle TextStyle { get { return this.textStyleField; } set { this.textStyleField = value; } } /// <remarks/> [XmlArrayItem("UserAttribute", IsNullable = false)] public PageXmlUserAttribute[] UserDefined { get { return this.userDefinedField; } set { this.userDefinedField = value; } } /// <summary> /// Semantic labels / tags /// </summary> [XmlElement("Labels")] public PageXmlLabels[] Labels { get { return this.labelsField; } set { this.labelsField = value; } } /// <remarks/> [XmlAttribute("id", DataType = "ID")] public string Id { get { return this.idField; } set { this.idField = value; } } /// <remarks/> [XmlAttribute("ligature")] public bool Ligature { get { return this.ligatureField; } set { this.ligatureField = value; this.ligatureFieldSpecified = true; } } /// <remarks/> [XmlIgnore()] public bool LigatureSpecified { get { return this.ligatureFieldSpecified; } set { this.ligatureFieldSpecified = value; } } /// <remarks/> [XmlAttribute("symbol")] public bool Symbol { get { return this.symbolField; } set { this.symbolField = value; this.symbolFieldSpecified = true; } } /// <remarks/> [XmlIgnore()] public bool SymbolSpecified { get { return this.symbolFieldSpecified; } set { this.symbolFieldSpecified = value; } } /// <summary> /// The script used for the glyph /// </summary> [XmlAttribute("script")] public PageXmlScriptSimpleType Script { get { return this.scriptField; } set { this.scriptField = value; this.scriptFieldSpecified = true; } } /// <remarks/> [XmlIgnore()] public bool ScriptSpecified { get { return this.scriptFieldSpecified; } set { this.scriptFieldSpecified = value; } } /// <summary> /// Overrides the production attribute of the parent word / text line / text region. /// </summary> [XmlAttribute("production")] public PageXmlProductionSimpleType Production { get { return this.productionField; } set { this.productionField = value; this.productionFieldSpecified = true; } } /// <remarks/> [XmlIgnore()] public bool ProductionSpecified { get { return this.productionFieldSpecified; } set { this.productionFieldSpecified = value; } } /// <summary> /// For generic use /// </summary> [XmlAttribute("custom")] public string Custom { get { return this.customField; } set { this.customField = value; } } /// <remarks/> [XmlAttribute("comments")] public string Comments { get { return this.commentsField; } set { this.commentsField = value; } } } } }
using System; namespace Oldmansoft.ClassicDomain.Util { class MapNullableEnumProperty : MapProperty { public override void Map(object source, object target) { var sourceValue = Getter.Get(source); if (sourceValue == null) { Setter.Set(target, null); return; } var targetValue = Enum.ToObject(TargetPropertyType.GenericTypeArguments[0], (int)sourceValue); Setter.Set(target, Activator.CreateInstance(TargetPropertyType, targetValue)); } } }
using RpgBot.Command.Abstraction; using RpgBot.Entity; using RpgBot.Level; using RpgBot.Service.Abstraction; using SQLitePCL; namespace RpgBot.Command { public class MeCommand : AbstractCommand, ICommand { private const int ArgsCount = 0; private const string Name = "/me"; private const string Description = "Show details about you"; private readonly IUserService _userService; public MeCommand(IUserService userService) { _userService = userService; } public string Run(string text, User user) { return _userService.Stringify(user); } public string GetName() { return Name; } public string GetDescription() { return Description; } public int GetArgsCount() { return ArgsCount; } } }
namespace VaultLib.Support.Undercover.VLT.RenderReflect { public enum State_GPUFunc { kStateGPUFunc_Never = 0x0, kStateGPUFunc_Less = 0x1, kStateGPUFunc_Equal = 0x2, kStateGPUFunc_Less_Equal = 0x3, kStateGPUFunc_Greater = 0x4, kStateGPUFunc_Not_Equal = 0x5, kStateGPUFunc_Greater_Equal = 0x6, kStateGPUFunc_Always = 0x7, } }
using StixNet.Schemas; namespace StixNet.Sdos; public class Malware: STIXObject { //name, description, malware_types, is_family, aliases, kill_chain_phases, first_seen, //last_seen, operating_system_refs, architecture_execution_envs, //implementation_languages, capabilities, sample_refs public string? Name { get; set; } public string? Description { get; set; } public IEnumerable<string> MalwareTypes { get; set; } public bool IsFamily { get; set; } public IEnumerable<string> Aliases { get; set; } public IEnumerable<string> KillChainPhases { get; set; } public DateTime FirstSeen { get; set; } public DateTime LastSeen { get; set; } public IEnumerable<string> OperatingSystemRefs { get; set; } public IEnumerable<string> ArchitectureExecutionEnvs { get; set; } // list of type openvocab public IEnumerable<string> ImplementationLanguages { get; set; } // list of type openvocab public IEnumerable<string> Capabilities { get; set; } // list of type open-vocab public IEnumerable<string> SampleRefs { get; set; } // list of type identifiers public Malware() { Aliases = new List<string>(); MalwareTypes = new List<string>(); KillChainPhases = new List<string>(); OperatingSystemRefs = new List<string>(); ArchitectureExecutionEnvs = new List<string>(); ImplementationLanguages = new List<string>(); Capabilities = new List<string>(); SampleRefs = new List<string>(); } }
using System; using System.Globalization; using System.Text; namespace PdfReader { public class ParseString : ParseObjectBase { public ParseString(TokenString token) { Token = token; } public string Value { get { return Token.Resolved; } } public byte[] ValueAsBytes { get { return Token.ResolvedAsBytes; } } public string BytesToString(byte[] bytes) { return Token.BytesToString(bytes); } private TokenString Token { get; set; } } }
using System.Xml.Serialization; using Inventor.Semantics.Metadata; namespace Inventor.Semantics.Xml { [XmlType] public abstract class Attribute { public abstract IAttribute Load(); public static Attribute Save(IAttribute attribute) { var definition = Repositories.Attributes.Definitions.GetSuitable(attribute); return definition.Xml; } } }
using FSharpUtils.Newtonsoft; using LanguageExt; using static LanguageExt.Prelude; namespace Tweek.Engine.Drivers { public static class JsonValueExtensions { public static Option<JsonValue> GetPropertyOption(this JsonValue json, string propName) { var prop = json.TryGetProperty(propName); return Optional(prop?.Value); } } }
namespace ESFA.DAS.ProvideFeedback.Apprentice.Data { public class CosmosDbRepository : CosmosDbRepositoryBase<CosmosDbRepository> { } }
using System; using System.Collections; using System.Collections.Generic; using JetBrains.Annotations; namespace InCube.Core.Functional { /// <summary> /// Represents the union of two distinct types, namely, <typeparamref name="TL" /> and <typeparamref name="TR" />. /// This union type is right-biased if used as an <see cref="IEnumerable" />. /// </summary> /// <typeparam name="TL">The <see cref="Left" /> type.</typeparam> /// <typeparam name="TR">The <see cref="Right" /> type.</typeparam> [PublicAPI] public interface IEither<out TL, out TR> : IEnumerable<TR> { /// <summary> /// Gets a value indicating whether or not the instance is of kind left. /// </summary> bool IsLeft { get; } /// <summary> /// Gets a value indicating whether or not the instance is of kind right. /// </summary> bool IsRight { get; } /// <summary> /// Gets the 'left' value. /// </summary> TL Left { get; } /// <summary> /// Gets the 'right' value. /// </summary> TR Right { get; } /// <summary> /// Gets 'left' value as an option. /// </summary> IOption<TL> LeftOption { get; } /// <summary> /// Gets 'right' value as an option. /// </summary> IOption<TR> RightOption { get; } /// <summary> /// Gets the right or left type depending if the either is right or left respectively. /// </summary> Type Type { get; } /// <summary> /// Maps either left or right value to output type. /// </summary> /// <typeparam name="TOut">The output type.</typeparam> /// <param name="left">The left mapping.</param> /// <param name="right">The right mapping.</param> /// <returns>An output type object.</returns> TOut Match<TOut>(Func<TL, TOut> left, Func<TR, TOut> right); /// <summary> /// Maps right to output type and preserves left. /// </summary> /// <typeparam name="TOut">Output type.</typeparam> /// <param name="f">Mapping from right type to output type.</param> /// <returns>An <see cref="Either{TL,TR}" /> of left and output types.</returns> IEither<TL, TOut> Select<TOut>(Func<TR, TOut> f); /// <summary> /// Performs an action on right. /// </summary> /// <param name="right">Action to perform on right.</param> void ForEach(Action<TR> right); /// <summary> /// Performs an action on right or left. /// </summary> /// <param name="left">The left action.</param> /// <param name="right">The right action.</param> void ForEach(Action<TL> left, Action<TR> right); } }
using Volo.Abp.Modularity; using Volo.Abp.Localization; using EasyAbp.EzGet.Localization; using Volo.Abp.Localization.ExceptionHandling; using Volo.Abp.Validation; using Volo.Abp.Validation.Localization; using Volo.Abp.VirtualFileSystem; using Volo.Abp.Users; namespace EasyAbp.EzGet { [DependsOn( typeof(AbpValidationModule), typeof(AbpUsersDomainSharedModule) )] public class EzGetDomainSharedModule : AbpModule { public override void ConfigureServices(ServiceConfigurationContext context) { Configure<AbpVirtualFileSystemOptions>(options => { options.FileSets.AddEmbedded<EzGetDomainSharedModule>(); }); Configure<AbpLocalizationOptions>(options => { options.Resources .Add<EzGetResource>("en") .AddBaseTypes(typeof(AbpValidationResource)) .AddVirtualJson("/EasyAbp/EzGet/Localization/EzGet"); }); Configure<AbpExceptionLocalizationOptions>(options => { options.MapCodeNamespace("EzGet", typeof(EzGetResource)); }); } } }
using Couchbase.Data.DAL; using Couchbase.Data.RepositoryExample.Models.Repositories; using Couchbase.Data.Tests.Documents; using NUnit.Framework; namespace Couchbase.Data.Tests { [TestFixture] public class RepositoryTests { [Test] public void Test_Get() { using (var cluster = new Cluster()) { using (var bucket = cluster.OpenBucket("beer-sample")) { var breweryRepository = new Repository<Couchbase.Data.RepositoryExample.Models.Brewery>(bucket); var brewery = breweryRepository.Find("21st_amendment_brewery_cafe"); var document = brewery.Content; breweryRepository.Save(brewery); } } } [Test] public void Test_Create() { using (var cluster = new Cluster()) { using (var bucket = cluster.OpenBucket("beer-sample")) { var repository = new BeerRepository(bucket); var beer = new Couchbase.Data.RepositoryExample.Models.Beer { Id = "bud_light", Name = "Bud Light", Type = "beer" }; repository.Save(beer); } } } } }
using System.Collections.Generic; namespace OASP4Net.Domain.Entities.Models { public partial class Table { public Table() { Booking = new HashSet<Booking>(); } public long Id { get; set; } public int SeatsNumber { get; set; } public ICollection<Booking> Booking { get; set; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections; using System.Collections.Generic; using UnityEngine; #if PLAY_GAMES_SERVICES using GooglePlayGames; using GooglePlayGames.BasicApi; using UnityEngine.SocialPlatforms; #endif public class PGSAchievementManager : MonoBehaviour { public enum TrivialKartAchievements { // Achievement for driving more than a certain distance Tk_Achievement_Distance = 0, // Achievement for purchasing the truck Tk_Achievement_Truck = 1 } // Internal state object for achievement status and description private class AchievementInfo { public string achievementId; public string achievementName; public bool achievementUnlocked; public AchievementInfo(string achId) { achievementId = achId; achievementName = ""; achievementUnlocked = false; } } private AchievementInfo[] _achievementInfo; void Awake() { #if PLAY_GAMES_SERVICES _achievementInfo = new AchievementInfo[] { new AchievementInfo(GPGSIds.achievement_tk_achievement_drive), new AchievementInfo(GPGSIds.achievement_tk_achievement_truck) }; #endif } // Loads the achievements from Play Games Services, and updates // internal description and unlock status using the achievement data. public void LoadAchievements() { #if PLAY_GAMES_SERVICES PlayGamesPlatform.Instance.LoadAchievements((achievements) => { foreach (var achievement in achievements) { foreach (var achievementInfo in _achievementInfo) { if (achievement.id.Equals(achievementInfo.achievementId)) { achievementInfo.achievementUnlocked = achievement.completed; } } } }); PlayGamesPlatform.Instance.LoadAchievementDescriptions(achievementDescriptions => { foreach (var description in achievementDescriptions) { foreach (var achievementInfo in _achievementInfo) { if (description.id.Equals(achievementInfo.achievementId)) { achievementInfo.achievementName = description.unachievedDescription; } } } }); #endif } public bool GetAchievementUnlocked(TrivialKartAchievements achievementId) { return _achievementInfo[(int)achievementId].achievementUnlocked; } public string GetAchievementName(TrivialKartAchievements achievementId) { return _achievementInfo[(int) achievementId].achievementName; } public void UnlockAchievement(TrivialKartAchievements achievementId) { #if PLAY_GAMES_SERVICES Social.ReportProgress(_achievementInfo[(int) achievementId].achievementId, 100.0f, (bool success) => { if (success) { _achievementInfo[(int) achievementId].achievementUnlocked = true; } else { Debug.Log("Unlock achievement failed for " + _achievementInfo[(int) achievementId].achievementId); } }); #endif } }
using BankScrapper.Models; namespace BankScrapper { public class BankScrapeResult { public Bank Bank { get; set; } public Account Account { get; set; } public Customer Customer { get; set; } public Transaction[] Transactions { get; set; } public Card[] Cards { get; set; } public Bill[] Bills { get; set; } } }
using System; using System.Collections.Generic; using Engine; using Katarai.Wpf.Monitor; using NSubstitute; using NUnit.Framework; namespace Katarai.Wpf.Tests.Monitor { [TestFixture] public class TestKataLogNotifier { readonly Stack<IDisposable> _itemsToDispose = new Stack<IDisposable>(); [TearDown] public void TesrDown() { while (_itemsToDispose.Count > 0) { var disposable = _itemsToDispose.Pop(); disposable.Dispose(); } } [Test] public void Constructor_GivenNullLogTarget_ShouldThrow() { //---------------Set up test pack------------------- var underlyingNotifier = Substitute.For<IPlayerNotifier>(); //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- var exception = Assert.Throws<ArgumentNullException>(() => new KataLogPlayerNotifier(null)); //---------------Test Result ----------------------- Assert.AreEqual("logTarget", exception.ParamName); } [Test] public void CheckForAndDisplayErrorMessage_ShouldCallUnderlyingLogTarget() { //---------------Set up test pack------------------- var underlyingLogTarget = Substitute.For<ILogTarget>(); var notifier = CreateNotifier(logTarget: underlyingLogTarget); //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- notifier.DisplayErrorMessage("Some Message"); //---------------Test Result ----------------------- underlyingLogTarget.Received().LogError("Some Message"); } [Test] public void DisplayMessage_ShouldCallUnderlyingLogTarget() { //---------------Set up test pack------------------- var underlyingLogTarget = Substitute.For<ILogTarget>(); var notifier = CreateNotifier(logTarget: underlyingLogTarget); //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- notifier.DisplayMessage("My Title", "Some Message", NotifyIcon.Red,NotifyIcon.TwoThumbs); //---------------Test Result ----------------------- underlyingLogTarget.Received().LogInfo("(Red) My Title - Some Message"); } [Test] public void Dispose_ShouldCallUnderlyingLogTarget() { //---------------Set up test pack------------------- var underlyingLogTarget = Substitute.For<ILogTarget>(); var notifier = CreateNotifier(logTarget: underlyingLogTarget); //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- notifier.Dispose(); //---------------Test Result ----------------------- underlyingLogTarget.Received().Dispose(); } private KataLogPlayerNotifier CreateNotifier(ILogTarget logTarget = null) { logTarget = logTarget ?? Substitute.For<ILogTarget>(); var loggingNotifier = new KataLogPlayerNotifier(logTarget); _itemsToDispose.Push(loggingNotifier); return loggingNotifier; } } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace ProjectCeilidh.PortAudio.Platform { internal abstract class NativeLibraryHandle : IDisposable { private readonly Dictionary<string, IntPtr> _symbolTable = new Dictionary<string, IntPtr>(); public T GetSymbolDelegate<T>(string name, bool throwOnError = true) where T : Delegate { if (!_symbolTable.TryGetValue(name, out var addr)) _symbolTable[name] = addr = GetSymbolAddress(name); if (addr == IntPtr.Zero) { if (throwOnError) throw new KeyNotFoundException($"Could not find symbol \"{name}\""); return default; } try { return (T) Marshal.GetDelegateForFunctionPointer(addr, typeof(T)); } catch (MarshalDirectiveException) { if (throwOnError) throw; return default; } } // This here would work in cases where there are exported variables, but PortAudio doesn't use any. /*public unsafe ref T GetSymbolReference<T>(string name) where T : struct { if (!_symbolTable.TryGetValue(name, out var addr)) _symbolTable[name] = addr = GetSymbolAddress(name); if (addr == IntPtr.Zero) throw new KeyNotFoundException($"Could not find symbol \"{name}\""); return ref Unsafe.AsRef<T>(addr.ToPointer()); }*/ protected abstract IntPtr GetSymbolAddress(string name); public abstract void Dispose(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using RxAs.Rx4.ProofTests.Mock; namespace RxAs.Rx4.ProofTests.Operators { [TestFixture] public class ScanFixture { [Test] public void outputs_one_value_for_each_input() { StatsObserver<int> stats = new StatsObserver<int>(); Observable.Range(0, 5) .Scan((x, y) => x + y) .Subscribe(stats); Assert.AreEqual(5, stats.NextCount); Assert.AreEqual(0, stats.NextValues[0]); Assert.AreEqual(1, stats.NextValues[1]); Assert.AreEqual(3, stats.NextValues[2]); Assert.AreEqual(6, stats.NextValues[3]); Assert.AreEqual(10, stats.NextValues[4]); } [Test] public void outputs_accumulator_type_if_different() { StatsObserver<DateTimeOffset> stats = new StatsObserver<DateTimeOffset>(); DateTimeOffset start = DateTimeOffset.UtcNow; Observable.Range(0, 5) .Scan(start, (x, y) => x.AddDays(y)) .Subscribe(stats); Assert.AreEqual(5, stats.NextCount); Assert.AreEqual(start.AddDays(0), stats.NextValues[0]); Assert.AreEqual(start.AddDays(1), stats.NextValues[1]); Assert.AreEqual(start.AddDays(3), stats.NextValues[2]); Assert.AreEqual(start.AddDays(6), stats.NextValues[3]); Assert.AreEqual(start.AddDays(10), stats.NextValues[4]); } [Test] public void calls_accumulator_for_first_value_when_initial_value_supplied() { StatsObserver<DateTimeOffset> stats = new StatsObserver<DateTimeOffset>(); List<int> accumulatorValues = new List<int>(); DateTimeOffset start = DateTimeOffset.UtcNow; Observable.Range(0, 5) .Scan(start, (x, y) => { accumulatorValues.Add(y); return x.AddDays(y); }) .Subscribe(stats); Assert.AreEqual(0, accumulatorValues[0]); } [Test] public void does_not_call_accumulator_for_first_value_initial_value_not_supplied() { StatsObserver<int> stats = new StatsObserver<int>(); List<int> accumulatorValues = new List<int>(); Observable.Range(0, 5) .Scan((x, y) => { accumulatorValues.Add(y); return x + y; }) .Subscribe(stats); Assert.AreEqual(1, accumulatorValues[0]); } [Test] public void does_not_error_on_empty_source() { StatsObserver<int> stats = new StatsObserver<int>(); Observable.Empty<int>() .Scan((x, y) => x + y) .Subscribe(stats); Assert.IsFalse(stats.ErrorCalled); Assert.IsTrue(stats.CompletedCalled); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { [SerializeField] private Ball ballPrefab; void Update() { // If the user presses space add a new ball to the scene if (Input.GetKeyDown(KeyCode.Space)) { Instantiate(ballPrefab); } } }
using System; using System.Collections.Generic; using System.Text; namespace Rainbow.DomainDriven.Event { public interface IEvent { Guid Id { get; } Guid AggregateRootId { get; set; } string AggregateRootTypeName { get; set; } long UTCTimestamp { get; } int Version { get; set; } EventOperation Operation { get; set; } } }
using Raylib_CsLo; using JustWind.Entities; using JustWind.Systems; using JustWind.Components; namespace JustWind { public class Engine { public List<Entity> Entities = new List<Entity>(); public List<JustWind.Systems.System> Systems = new List<JustWind.Systems.System>(); public List<JustWind.Systems.System> NoCameraSystems = new List<JustWind.Systems.System>(); public Entity Singleton; public Camera2D Camera; public Engine() { Systems.Add(new GenerationSystem(this)); Systems.Add(new AiMovementSystem(this)); Systems.Add(new HouseSafetySystem(this)); Systems.Add(new SoundSystem(this)); Systems.Add(new StateManagerSystem(this)); Systems.Add(new AnimationSystem(this)); Systems.Add(new CameraSystem(this)); Systems.Add(new RenderingSystem(this)); Systems.Add(new ControllableSystem(this)); Systems.Add(new ActionSystem(this)); Systems.Add(new RoundSystem(this)); NoCameraSystems.Add(new UiSystem(this)); var singleton = new Entity(); singleton.Components.Add(new Singleton { State = GameState.Menu }); Singleton = singleton; this.LoadConfiguration(); } public void Run() { Raylib.SetWindowState(ConfigFlags.FLAG_WINDOW_RESIZABLE); //Raylib.SetConfigFlags(ConfigFlags.FLAG_VSYNC_HINT); Raylib.InitWindow(1280, 720, "It's just the wind..."); Raylib.SetWindowIcon(Raylib.LoadImage("src/Assets/menu/icon.png")); Raylib.SetTargetFPS(240); //Raylib.SetWindowState(ConfigFlags.FLAG_WINDOW_UNDECORATED); Camera = new Camera2D(); Camera.zoom = 1; foreach (var system in Systems) { system.Load(); } foreach (var system in NoCameraSystems) { system.Load(); } while (!Raylib.WindowShouldClose()) { GameLoop(); } Raylib.CloseWindow(); } public void GameLoop() { Raylib.BeginDrawing(); Raylib.BeginMode2D(Camera); Raylib.ClearBackground(Raylib.WHITE); foreach (var system in Systems) { system.Update(Entities); } Raylib.EndMode2D(); foreach (var system in NoCameraSystems) { system.Update(Entities); } Raylib.EndDrawing(); } } }
using System; using System.Collections.Generic; using System.Linq; using OrbitVR.Components.Essential; using OrbitVR.Components.Items; using OrbitVR.Physics; using SharpDX; namespace OrbitVR.Framework { public class PlayerData { public PlayerData() {} } public class Player { public static Player[] players = new Player[5]; //0th for keyboard, 1st-4th for controllers (for now) public static bool EnablePlayers = true; public ItemSlots _currentItem = ItemSlots.Y_Yellow; public Node _node; public string ColorName; //public Controller controller; public Input input; public Dictionary<ItemSlots, Component> itemSlots = new Dictionary<ItemSlots, Component>() { {ItemSlots.Y_Yellow, null}, {ItemSlots.A_Green, null}, {ItemSlots.B_Red, null}, {ItemSlots.X_Blue, null}, }; public ItemSlots occupiedSlots = ItemSlots.None; public Color pColor; public Dictionary<Type, PlayerData> playerDatas = new Dictionary<Type, PlayerData>(); public int playerIndex; public Room room; public Node node { get { return _node; } set { if (_node != null) _node.player = null; _node = value; if (value != null) value.player = this; } } public Body body { get { return node != null ? node.body : null; } } public ItemSlots currentItem { get { return _currentItem; } set { foreach (var item in itemSlots.Keys) { if (itemSlots[item] != null) { if (item != value) itemSlots[item].active = false; else itemSlots[item].active = true; } } _currentItem = value; } } /* public static Player GetNew(int playerIndex) { bool success = false; Player p = new Player(playerIndex, ref success); return success ? p : null; } private Player(int playerIndex, ref bool sucess) { controller = FullController.GetNew(playerIndex); if (controller == null) { sucess = false; return; } sucess = true; room = OrbIt.game.room; this.playerIndex = playerIndex; SetPlayerColor(); } */ public Player(int playerIndex) { this.room = OrbIt.Game.Room; this.playerIndex = playerIndex; if (playerIndex == 0) { this.input = new PcFullInput(this); } else { this.input = new ControllerFullInput(this, (PlayerIndex) (playerIndex - 1)); } SetPlayerColor(); } public void AddItem(Component comp) { int count = 0; foreach (var slot in itemSlots.Keys.ToList()) { if (itemSlots[slot] != null) { count++; if (itemSlots[slot].GetType() == comp.GetType()) { itemSlots[slot] = comp; if (slot != currentItem) comp.active = false; if (count == 0) currentItem = slot; return; } } } if (count == 4) return; foreach (var slot in itemSlots.Keys.ToList()) { if (itemSlots[slot] == null) { itemSlots[slot] = comp; occupiedSlots |= slot; if (slot != currentItem) comp.active = false; return; } } } public void RemoveItem(Component comp) { foreach (var slot in itemSlots.Keys.ToList()) { if (comp == itemSlots[slot]) { occupiedSlots = occupiedSlots ^ slot; itemSlots[slot] = null; return; } } } public T Data<T>() where T : PlayerData { Type t = typeof (T); if (playerDatas.ContainsKey(t)) return (T) playerDatas[t]; return null; } public bool HasData<T>() where T : PlayerData { return playerDatas.ContainsKey(typeof (T)); } public void SetPlayerColor() { switch (playerIndex) { case 1: pColor = Color.Blue; ColorName = "Blue"; break; case 2: pColor = Color.Green; ColorName = "Green"; break; case 3: pColor = Color.Red; ColorName = "Red"; break; case 4: pColor = Color.Yellow; ColorName = "Yellow"; break; } byte min = 40; if (pColor.R == 0) pColor.R = min; if (pColor.G == 0) pColor.G = min; if (pColor.B == 0) pColor.B = min; } // public static void ResetPlayers(Room room) //todo:fix { room.Groups.Player.EmptyGroup(); Controller.ResetControllers(); CreatePlayers(room); //OrbIt.ui.sidebar.playerView.InitializePlayers(); } public static void CreatePlayers(Room room) { room.Groups.Player.defaultNode = room.MasterGroup.defaultNode.CreateClone(room); Shooter.MakeBullet(room); if (!EnablePlayers) return; //def.addComponent(comp.shooter, true); for (int i = 1; i < 5; i++) { TryCreatePlayer(room, room.Groups.Player.defaultNode, i, false); } //OrbIt.ui.sidebar.playerView.InitializePlayers(); } public static void CheckForPlayers(Room room) { for (int i = 1; i < 5; i++) { if (players[i] == null) // && GamePad.GetState((PlayerIndex)(i-1)).IsConnected) { TryCreatePlayer(room, room.Groups.Player.defaultNode, i, true); } } } public static void TryCreatePcPlayer() { if (players[0] == null) { TryCreatePlayer(OrbIt.Game.Room, OrbIt.Game.Room.Groups.Player.defaultNode, 0, true); } } private static void TryCreatePlayer(Room room, Node defaultNode, int playerIndex, bool updateUI) { if (playerIndex != 0) { GamePadState gamePadState = GamePad.GetState((PlayerIndex) (playerIndex - 1)); if (!gamePadState.IsConnected || gamePadState.Buttons.Back == ButtonState.Released) return; } //Player p = Player.GetNew(playerIndex); Player p = new Player(playerIndex); players[playerIndex] = p; if (p == null) return; double angle = Utils.random.NextDouble()*Math.PI*2; angle -= Math.PI; float dist = 200; float x = dist*(float) Math.Cos(angle); float y = dist*(float) Math.Sin(angle); Vector2R spawnPos = new Vector2R((room.WorldWidth/4)*playerIndex - (room.WorldWidth/8), room.WorldHeight - 600); // -new Vector2(x, y); Node node = defaultNode.CreateClone(room); p.node = node; node.body.pos = spawnPos; node.name = "player" + p.ColorName; node.SetColor(p.pColor); //node.addComponent(comp.shooter, true); //node.addComponent(comp.sword, true); //node.Comp<Sword>().sword.collision.DrawRing = false; //room.groups.player.IncludeEntity(node); node.meta.healthBar = Meta.HealthBarMode.Bar; //node.OnSpawn(); node.body.velocity = Vector2R.Zero; //node.body.mass = 0.1f; node.movement.maxVelocity.value = 6f; //node.addComponent<LinkGun>(true); room.SpawnNode(node, g: room.Groups.Player); //node.OnSpawn(); node.texture = Textures.Robot1; //if (updateUI) //{ // OrbIt.ui.sidebar.playerView.InitializePlayers(); //} } } }
// Copyright (c) Philipp Wagner. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Threading; using System.Threading.Tasks; using FcmSharp.Scheduler.Quartz.Services; using FcmSharp.Scheduler.Quartz.Web.Contracts; using FcmSharp.Scheduler.Quartz.Web.Converters; using Microsoft.AspNetCore.Mvc; namespace FcmSharp.Scheduler.Quartz.Web.Controllers { [Controller] [Route("scheduler")] public class SchedulerController : ControllerBase { private readonly ISchedulerService schedulerService; public SchedulerController(ISchedulerService schedulerService) { this.schedulerService = schedulerService; } [HttpPost] public async Task<IActionResult> Post([FromBody] Message message, CancellationToken cancellationToken) { // Convert into the Database Representation: var target = MessageConverter.Convert(message); // Save and Schedule: var result = await schedulerService.ScheduleMessageAsync(target, cancellationToken); return Ok(result); } } }
using SocialPlatform.Groups.Shared.Models; using System.Collections.Generic; namespace SocialPlatform.Groups.Actors { public class GroupState { public string Name { get; set; } public List<GroupMember> Members { get; set; } = new List<GroupMember>(); public List<GroupMessage> Messages { get; set; } = new List<GroupMessage>(); } }
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Luminous.Common.EntityModel { /// <summary> /// The abstract base entity class all domain models should inherit from /// </summary> /// <typeparam name="T">The type of object identifier</typeparam> public abstract class Entity<T> : IEntity<T> { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public T Id { get; private set; } [Timestamp] public byte[] Version { get; private set; } } }
// Spam Protection Bot GUI // Copyright (C) 2019 - 2021 ALiwoto // This file is subject to the terms and conditions defined in // file 'LICENSE', which is part of the source code. using System; using System.Threading.Tasks; using SPB.SandBox; using SPB.Security; using SPB.GameObjects.WMath; using SPB.GameObjects.Players; using SPB.GameObjects.ServerObjects; using SPB.SandBox.ErrorSandBoxes; namespace SPB.GameObjects.Troops { /// <summary> /// There is 4 types of Troops: /// Saber, Archer, Lancer, Assassin. /// NOTICE: Please do the Parsing in order... /// <see cref="Saber"/>, <see cref="Archer"/>, <see cref="Lancer"/>, <see cref="Assassin"/> /// </summary> public abstract partial class Troop { //------------------------------------------------- #region Constant's Region /// <summary> /// Use this to separate the heroes type from each other. /// </summary> public const string OutCharSeparator = "よ"; /// <summary> /// But use this in each type, for separate their parameters. /// </summary> public const string InCharSeparator = "つ"; public const string EndFileName = "_菟ループす"; public const string TROOP_MESSAGE = "P_T -- SPB"; public const uint BasicLevel = 1; #endregion //------------------------------------------------- #region static Properties Region /// <summary> /// The Basic Power in the level1. /// </summary> public static Unit BasicPower { get { return new Unit(0, 0, 0, 20); } } #endregion //------------------------------------------------- #region Properties Region /// <summary> /// The count of Troops in each types, /// for example: mrwoto has 10K Saber, 100K Archer, etc... /// </summary> public Unit Count { get; set; } /// <summary> /// The level of Troops in each types, /// for example: mrwoto has Saber lvl12 (all of his Sabers should be the same level). /// </summary> public uint Level { get; set; } /// <summary> /// The Power of Troops in each types, /// for example: mrwoto's Sabers Power is 120K (all of the Sabers should have the same power). /// </summary> public Unit Power { get; set; } #endregion //------------------------------------------------- #region protected Method's Region protected virtual StrongString GetForServer() { StrongString myString = Count.GetForServer() + InCharSeparator + Level.ToString() + InCharSeparator + Power.GetForServer() + InCharSeparator; return myString; } #endregion //------------------------------------------------- #region static Method's Region /// <summary> /// Parse the string value to Troops in the following order: /// <see cref="Saber"/>, <see cref="Archer"/>, <see cref="Lancer"/>, <see cref="Assassin"/> /// </summary> /// <param name="theString"></param> /// <returns></returns> public static Troop[] ParseToTroops(StrongString theString) { Troop[] troops = new Troop[4]; //There is 4 types of Troop. StrongString[] myStrings = theString.Split(OutCharSeparator); troops[0] = Saber.ParseToSaber(myStrings[0]); troops[1] = Archer.ParseToArcher(myStrings[1]); troops[2] = Lancer.ParseToLancer(myStrings[2]); troops[3] = Assassin.ParseToAssassin(myStrings[3]); return troops; } public static Troop[] GetBasicTroops() { Troop[] troops = new Troop[4]; troops[0] = Saber.GetBasicSaber(); troops[1] = Archer.GetBasicArcher(); troops[2] = Lancer.GetBasicLancer(); troops[3] = Assassin.GetBasicAssassin(); return troops; } /// <summary> /// Get the string value of these Troops for the Server DataBase. /// </summary> /// <param name="myTroops"></param> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="NullReferenceException"></exception> /// <returns></returns> public static StrongString GetForServer(Troop[] myTroops) { if(myTroops == null) { throw new ArgumentNullException(); } StrongString myString = myTroops[0].GetForServer() + OutCharSeparator + // Saber myTroops[1].GetForServer() + OutCharSeparator + // Archer myTroops[2].GetForServer() + OutCharSeparator + // Lancer myTroops[3].GetForServer() + OutCharSeparator; //Assassin return myString; } /// <summary> /// Create player's troops for the first time. /// </summary> /// <param name="troops"></param> public async static Task<DataBaseDataChangedInfo> CreatePlayerTroops(Troop[] troops) { //--------------------------------------------- StrongString myString = GetForServer(troops); var _p = ThereIsServer.GameObjects.MyProfile; var _s = ThereIsServer.ServersInfo.ServerManager.Get_Troops_Server(_p.Socket); var _target = _p.UID.GetValue() + EndFileName; var _creation = new DataBaseCreation(TROOP_MESSAGE, QString.Parse(myString)); return await ThereIsServer.Actions.CreateData(_s, _target, _creation); //--------------------------------------------- } /// <summary> /// Save Player's troops(Update them to the server.) /// </summary> /// <param name="troops"></param> public static async Task<DataBaseDataChangedInfo> SavePlayerTroops(Troop[] troops) { var _p = ThereIsServer.GameObjects.MyProfile; return await SavePlayerTroops(troops, _p); } public static async Task<DataBaseDataChangedInfo> SavePlayerTroops(Troop[] troops, Player _p) { StrongString myString = GetForServer(troops); //--------------------------------------------- var _s = ThereIsServer.ServersInfo.ServerManager.Get_Troops_Server(_p.Socket); var _target = _p.UID.GetValue() + EndFileName; var existing = await ThereIsServer.Actions.GetAllContentsByRef(_s, _target); //--------------------------------------------- if (existing.IsDeadCallBack || ThereIsServer.ServerSettings.HasConnectionClosed) { NoInternetConnectionSandBox.PrepareConnectionClosedSandBox(); return null; } //--------------------------------------------- var _req = new DataBaseUpdateRequest(TROOP_MESSAGE, QString.Parse(myString), existing.Sha); return await ThereIsServer.Actions.UpdateData(_s, _target, _req); //--------------------------------------------- } public static async Task<Troop[]> LoadPlayerTroops() { var _p = ThereIsServer.GameObjects.MyProfile; return await LoadPlayerTroops(_p); } public static async Task<Troop[]> LoadPlayerTroops(Player _p) { //--------------------------------------------- var _target = _p.UID.GetValue() + EndFileName; var _s = ThereIsServer.ServersInfo.ServerManager.Get_Troops_Server(_p.Socket); var existing = await ThereIsServer.Actions.GetAllContentsByRef(_s, _target); //--------------------------------------------- if (existing.IsDeadCallBack || ThereIsServer.ServerSettings.HasConnectionClosed) { NoInternetConnectionSandBox.PrepareConnectionClosedSandBox(); return null; } return ParseToTroops(existing.Decode()); } public static async Task<bool> DeleteTroops(UID _uid_) { //--------------------------------------------- var _target = _uid_.GetValue() + EndFileName; var _s = ThereIsServer.ServersInfo.ServerManager.Get_Troops_Server(_uid_.TheSocket); var existing = await ThereIsServer.Actions.GetAllContentsByRef(_s, _target); //--------------------------------------------- if (existing.DoesNotExist) { return true; } if (existing.IsDeadCallBack || ThereIsServer.ServerSettings.HasConnectionClosed) { NoInternetConnectionSandBox.PrepareConnectionClosedSandBox(); return false; } //--------------------------------------------- var _req = new DataBaseDeleteRequest(TROOP_MESSAGE, existing.Sha.GetStrong()); return await ThereIsServer.Actions.DeleteData(_s, _target, _req); //--------------------------------------------- } #endregion //------------------------------------------------- } }
namespace CyberCAT.Core.DumpedEnums { public enum gameEntityReferenceType { EntityRef = 0, Tag = 1, SlotID = 2, SceneActorContextName = 3 } }
using System.Collections.Generic; using System.Text; namespace BizHawk.Client.Common { public class BkmHeader : Dictionary<string, string> { public BkmHeader() { Comments = new List<string>(); Subtitles = new SubtitleList(); this[HeaderKeys.EMULATIONVERSION] = VersionInfo.GetEmuVersion(); this[HeaderKeys.PLATFORM] = Global.Emulator != null ? Global.Emulator.SystemId : ""; this[HeaderKeys.GAMENAME] = ""; this[HeaderKeys.AUTHOR] = ""; this[HeaderKeys.RERECORDS] = "0"; } public List<string> Comments { get; } public SubtitleList Subtitles { get; } public string SavestateBinaryBase64Blob { get { if (ContainsKey(HeaderKeys.SAVESTATEBINARYBASE64BLOB)) { return this[HeaderKeys.SAVESTATEBINARYBASE64BLOB]; } return null; } set { if (value == null) { Remove(HeaderKeys.SAVESTATEBINARYBASE64BLOB); } else { Add(HeaderKeys.SAVESTATEBINARYBASE64BLOB, value); } } } public ulong Rerecords { get { if (!ContainsKey(HeaderKeys.RERECORDS)) { this[HeaderKeys.RERECORDS] = "0"; } return ulong.Parse(this[HeaderKeys.RERECORDS]); } set { this[HeaderKeys.RERECORDS] = value.ToString(); } } public bool StartsFromSavestate { get { if (ContainsKey(HeaderKeys.STARTSFROMSAVESTATE)) { return bool.Parse(this[HeaderKeys.STARTSFROMSAVESTATE]); } return false; } set { if (value) { Add(HeaderKeys.STARTSFROMSAVESTATE, "True"); } else { Remove(HeaderKeys.STARTSFROMSAVESTATE); } } } public string GameName { get { if (ContainsKey(HeaderKeys.GAMENAME)) { return this[HeaderKeys.GAMENAME]; } return ""; } set { this[HeaderKeys.GAMENAME] = value; } } public string SystemId { get { if (ContainsKey(HeaderKeys.PLATFORM)) { return this[HeaderKeys.PLATFORM]; } return ""; } set { this[HeaderKeys.PLATFORM] = value; } } public new string this[string key] { get { return ContainsKey(key) ? base[key] : ""; } set { if (ContainsKey(key)) { base[key] = value; } else { Add(key, value); } } } public new void Clear() { Comments.Clear(); Subtitles.Clear(); base.Clear(); } public override string ToString() { var sb = new StringBuilder(); foreach (var kvp in this) { sb .Append(kvp.Key) .Append(' ') .Append(kvp.Value) .AppendLine(); } sb.Append(Subtitles); Comments.ForEach(comment => sb.AppendLine(comment)); return sb.ToString(); } public bool ParseLineFromFile(string line) { if (!string.IsNullOrWhiteSpace(line)) { var splitLine = line.Split(new[] { ' ' }, 2); if (HeaderKeys.Contains(splitLine[0]) && !ContainsKey(splitLine[0])) { Add(splitLine[0], splitLine[1]); } else if (line.StartsWith("subtitle") || line.StartsWith("sub")) { Subtitles.AddFromString(line); } else if (line.StartsWith("comment")) { Comments.Add(line.Substring(8, line.Length - 8)); } else if (line.StartsWith("|")) { return false; } } return true; } } }
using FluentAssertions; using Kros.KORM.Metadata.Attribute; using Kros.KORM.UnitTests.Base; using System.Collections.Generic; using System.Linq; using Xunit; namespace Kros.KORM.UnitTests.Integration { public class QueryNullableFieldsTests : DatabaseTestBase { #region Helpers private const string Table_TestTable = "People"; private static readonly string CreateTable_TestTable = $@"CREATE TABLE [dbo].[{Table_TestTable}] ( [Id] [int] NOT NULL, [Data] [nvarchar](50) NOT NULL, [NullableString] [nvarchar](50) NULL, [NullableInt] [int] NULL ) ON [PRIMARY];"; private static readonly string InsertTestData = $@"INSERT INTO {Table_TestTable} ([Id], [Data], [NullableString], [NullableInt]) VALUES (1, 'Not null', 'Lorem', 100), (2, 'String null', NULL, 100), (3, 'Int null', 'Lorem', NULL), (4, 'All null', NULL, NULL)"; public int Fact { get; private set; } [Alias(Table_TestTable)] public class PersonClass { [Key] public int Id { get; set; } public string Data { get; set; } public string NullableString { get; set; } public int? NullableInt { get; set; } } [Alias(Table_TestTable)] public record PersonRecord { [Key] public int Id { get; set; } public string Data { get; set; } public string NullableString { get; set; } public int? NullableInt { get; set; } } private TestDatabase CreateTestDatabase() => CreateDatabase(new[] { CreateTable_TestTable, InsertTestData }); #endregion [Fact] public void MapNullDataToClass() { var expectedData = new List<PersonClass>{ new PersonClass { Id = 1, Data = "Not null", NullableString = "Lorem", NullableInt = 100 }, new PersonClass { Id = 2, Data = "String null", NullableString = null, NullableInt = 100 }, new PersonClass { Id = 3, Data = "Int null", NullableString = "Lorem", NullableInt = null }, new PersonClass { Id = 4, Data = "All null", NullableString = null, NullableInt = null }, }; using TestDatabase korm = CreateTestDatabase(); var data = korm.Query<PersonClass>().OrderBy(item => item.Id).ToList(); data.Should().BeEquivalentTo(expectedData, config => { config.WithStrictOrdering(); return config; }); } [Fact] public void MapNullDataToRecord() { var expectedData = new List<PersonRecord>{ new PersonRecord { Id = 1, Data = "Not null", NullableString = "Lorem", NullableInt = 100 }, new PersonRecord { Id = 2, Data = "String null", NullableString = null, NullableInt = 100 }, new PersonRecord { Id = 3, Data = "Int null", NullableString = "Lorem", NullableInt = null }, new PersonRecord { Id = 4, Data = "All null", NullableString = null, NullableInt = null }, }; using TestDatabase korm = CreateTestDatabase(); var data = korm.Query<PersonRecord>().OrderBy(item => item.Id).ToList(); data.Should().BeEquivalentTo(expectedData, config => { config.WithStrictOrdering(); return config; }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Ep229News 的摘要说明 /// </summary> /// 实体类:和ep229News中的字段做映射 public class Ep229News { public int NewsId { get; set; } public string NewsTitle { get; set; } public string NewsContent { get; set; } public DateTime NewsDatetime { get; set; } }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ACTransit.Entities.Training { using System; using System.Collections.Generic; public partial class CourseSchedule { public CourseSchedule() { this.CourseEnrollments = new HashSet<CourseEnrollment>(); this.CourseScheduleInstructors = new HashSet<CourseScheduleInstructor>(); } public long CourseScheduleId { get; set; } public long CourseId { get; set; } public string Note { get; set; } public System.DateTime BeginEffDate { get; set; } public System.DateTime EndEffDate { get; set; } public Nullable<System.TimeSpan> StartTime { get; set; } public Nullable<System.TimeSpan> EndTime { get; set; } public Nullable<int> TotalSeat { get; set; } public Nullable<long> DivisionId { get; set; } public Nullable<long> Frequency { get; set; } public string Description { get; set; } public string AddUserId { get; set; } public System.DateTime AddDateTime { get; set; } public string UpdUserId { get; set; } public Nullable<System.DateTime> UpdDateTime { get; set; } public virtual Course Course { get; set; } public virtual ICollection<CourseEnrollment> CourseEnrollments { get; set; } public virtual Division Division { get; set; } public virtual ICollection<CourseScheduleInstructor> CourseScheduleInstructors { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; namespace Tools.Navigation { [CreateAssetMenu(menuName = "Tools/Navigation/Navigation Manager")] public class NavigationManager : SingletonScriptableObject<NavigationManager> { [SerializeField] private SceneReference _master = null; [SerializeField] private SceneReference _loadingScreen = null; private Stack<SceneReference> _history = null; public Stack<SceneReference> History { get { _history = _history ?? new Stack<SceneReference>(); return _history; } } public IEnumerator FastLoad(SceneReference scene) { yield return LoadAdditive(scene); yield return UnloadAll(new List<Scene> { SceneManager.GetSceneByPath(scene.path) }); } public IEnumerator DeepLoad(SceneReference scene, System.Action loadingScreenCallback) { if (_loadingScreen == null || string.IsNullOrEmpty(_loadingScreen.path)) { Debug.LogWarning("Couldn't deep load : loading scene path is set to null", this); yield return FastLoad(scene); } else { List<Scene> exceptions = new List<Scene> { SceneManager.GetSceneByPath(_master.path), SceneManager.GetSceneByPath(_loadingScreen.path) }; yield return LoadAdditive(_loadingScreen); loadingScreenCallback?.Invoke(); } } public IEnumerator LoadAdditive(SceneReference scene, bool setActive = true) { if (!SceneManager.GetSceneByPath(scene.path).isLoaded) { yield return SceneManager.LoadSceneAsync(scene.path, LoadSceneMode.Additive); if (setActive) { SceneManager.SetActiveScene(SceneManager.GetSceneByPath(scene.path)); } TrackScene(scene); } } private Scene[] GetLoadedScenes() { int sceneCount = SceneManager.sceneCount; Scene[] loadedScenes = new Scene[sceneCount]; for (int i = 0, length = SceneManager.sceneCount; i < length; i++) { loadedScenes[i] = SceneManager.GetSceneAt(i); } return loadedScenes; } public IEnumerator UnloadAll(List<Scene> exceptions = null) { foreach (Scene loadedScene in GetLoadedScenes()) { /// Active scene if (loadedScene == SceneManager.GetActiveScene()) { continue; } /// Master scene if (loadedScene.path == _master.path) { continue; } /// Exceptions if (exceptions != null && exceptions.Contains(loadedScene)) { continue; } yield return SceneManager.UnloadSceneAsync(loadedScene); } } public IEnumerator UnloadSingle(SceneReference scene) { yield return SceneManager.UnloadSceneAsync(scene.name); /// Pop scene from history stack. UntrackScene(scene); /// Set previous scene active. SceneManager.SetActiveScene(SceneManager.GetSceneByPath(_history.Peek().path)); } public static void QuitGame() { #if UNITY_EDITOR Debug.Log("Application.Quit()"); UnityEditor.EditorApplication.isPlaying = false; #else Application.Quit(); #endif } public void TrackScene(SceneReference scene) { if (History.Count == 0 || (History.Count > 0 && History.Peek() != scene)) { History.Push(scene); } } public void UntrackScene(SceneReference scene) { if (History.Count > 0 && History.Peek() == scene) { History.Pop(); } } } }
using System.Web.Security; using VsixMvcAppResult.Models.ProxyProviders; namespace VsixMvcAppResult.Models.Authentication { public class AuthenticationProxy : ProviderBaseChannel<IAuthenticationProxy>, IAuthenticationProxy { public bool LogIn(string userName, string password, string customCredential, bool isPersistent) { return this.proxy.LogIn(userName, password, customCredential, isPersistent); } public void LogOut() { this.proxy.LogOut(); } public bool IsLoggedIn() { return this.proxy.IsLoggedIn(); } public bool ValidateUser(string userName, string password, string customCredential) { return this.proxy.ValidateUser(userName, password, customCredential); } public FormsIdentity GetFormsIdentity() { return this.proxy.GetFormsIdentity(); } public override void Dispose() { base.Dispose(); } } }
using System.Collections.Generic; using System.Linq; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Configs; using BenchmarkDotNet.Order; namespace Konsarpoo.Collections.Tests.Benchmarks { [Orderer(SummaryOrderPolicy.FastestToSlowest)] [GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)] public class MapLookup { private static Map<int, int>[] m_map; private static Dictionary<int, int>[] m_dict; [GlobalSetup] public void Setup() { var data1 = new Dictionary<int, int>(); foreach (var i in Enumerable.Range(0, 2)) { data1.Add(i, i); } var data2 = new Dictionary<int, int>(); foreach (var i in Enumerable.Range(0, 1000)) { data2.Add(i, i); } var data3 = new Dictionary<int, int>(); foreach (var i in Enumerable.Range(0, 1000_000)) { data3.Add(i, i); } m_map = new [] { data1.ToMap(), data2.ToMap(), data3.ToMap() }; m_dict = new[] { data1, data2, data3 }; } (float, float) GetLinearTransformParams(float x1, float x2, float y1, float y2) { float dx = x1 - x2; if (dx != 0.0) { float a = (y1 - y2) / dx; float b = y1 - (a * x1); return (a, b); } return (0.0f, 0.0f); } private int GetIndex(int value, IReadOnlyDictionary<int, int> ints) { var (a, b) = GetLinearTransformParams(0, ints.Values.Max(), 0, ints.Count); int index = (int)((a * value) + b); return index; } public IEnumerable<int> Range() { return Enumerable.Range(0, 10); } [ArgumentsSource(nameof(Range))] [BenchmarkCategory("ContainsKey_1000"), Benchmark(Baseline = false)] public bool Map_1000_ContainsKey(int value) { var ints = m_map[1]; value = GetIndex(value, ints); return m_map[1].ContainsKey(value); } [ArgumentsSource(nameof(Range))] [BenchmarkCategory("ContainsKey_1000_000"), Benchmark(Baseline = false)] public bool Map_1000_000_ContainsKey(int value) { var ints = m_map[2]; value = GetIndex(value, ints); return m_map[2].ContainsKey(value); } [BenchmarkCategory("ContainsKey_2"), Benchmark(Baseline = false)] [ArgumentsSource(nameof(Range))] public bool Map_2_ContainsKey(int value) { var ints = m_map[0]; value = GetIndex(value, ints); return m_map[0].ContainsKey(value); } [ArgumentsSource(nameof(Range))] [BenchmarkCategory("ContainsKey_1000"), Benchmark(Baseline = true)] public bool Dict_1000_ContainsKey(int value) { var ints = m_map[1]; value = GetIndex(value, ints); return m_dict[1].ContainsKey(value); } [ArgumentsSource(nameof(Range))] [BenchmarkCategory("ContainsKey_1000_000"), Benchmark(Baseline = true)] public bool Dict_1000_000_ContainsKey(int value) { var ints = m_map[2]; value = GetIndex(value, ints); return m_dict[2].ContainsKey(value); } [BenchmarkCategory("ContainsKey_2"), Benchmark(Baseline = true)] [ArgumentsSource(nameof(Range))] public bool Dict_2_ContainsKey(int value) { var ints = m_map[0]; value = GetIndex(value, ints); return m_dict[0].ContainsKey(value); } } }
using COI.UI_MVC.Scheduler.Tasks; using COI.UI_MVC.Util; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using MQTTnet; using MQTTnet.Client; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using UI_MVC.Scheduler.Scheduling; using static COI.UI_MVC.Util.Util; namespace COI.UI_MVC.Services.MQTT { public sealed class MqttBroker { private const string TOPIC_PREFIX = "City of Ideas - "; private readonly IServiceProvider _serviceProvider; private readonly IConfiguration _configuration; private IMqttClient _client; public MqttBroker(IConfiguration configuration, IServiceProvider serviceProvider) { _configuration = configuration; _serviceProvider = serviceProvider; Initialize(); } private async void Initialize() { var factory = new MqttFactory(); _client = factory.CreateMqttClient(); string connectionString = _configuration["MQTT:ConnectionString"]; int port = int.Parse(_configuration["MQTT:Port"]); string username = _configuration["MQTT:Username"]; string password = _configuration["MQTT:Password"]; // See: https://github.com/chkr1011/MQTTnet/wiki/Client var options = new MqttClientOptionsBuilder() .WithClientId(Guid.NewGuid().ToString()) .WithTcpServer(connectionString, port) .WithCredentials(username, password) //.WithTls() .WithCleanSession() .Build(); _client.Connected += Client_Connected; _client.ApplicationMessageReceived += Client_ApplicationMessageReceived; await _client.ConnectAsync(options); } public async void Terminate() { if (_client.IsConnected) { await _client.DisconnectAsync(); _client = null; } } #region Events private void Client_Connected(object sender, EventArgs e) { SubscribeToTopic("Vote"); } private void Client_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e) { string encryptedBinary = Encoding.ASCII.GetString(e.ApplicationMessage.Payload); string encryptedPayload = BinaryToString(encryptedBinary); string payload = Rot47.Rotate(encryptedPayload); payload = payload.Replace("\0", ""); // remove padding 0's Debug.WriteLine("### RECEIVED APPLICATION MESSAGE ###"); Debug.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}"); Debug.WriteLine($"+ Binary Payload = {encryptedBinary}"); Debug.WriteLine($"+ Encrypted Payload = {encryptedPayload}"); Debug.WriteLine($"+ Decrypted Payload = {payload}"); Debug.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}"); Debug.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}"); if (e.ApplicationMessage.Topic.Contains("Vote")) { Tuple<int, char[]> parsedPayload = ParseVote(payload); var iotLinkId = parsedPayload.Item1; var votes = parsedPayload.Item2; using (var scope = _serviceProvider.CreateScope()) { var voteSpreadTask = (VoteSpreadTask)scope.ServiceProvider.GetService<IScheduledTask>(); Queue<char> votesQueue; if (voteSpreadTask.VoteQueues.ContainsKey(iotLinkId)) { votesQueue = voteSpreadTask.VoteQueues[iotLinkId]; } else { votesQueue = new Queue<char>(); } foreach (var vote in votes) { votesQueue.Enqueue(vote); } voteSpreadTask.VoteQueues[iotLinkId] = votesQueue; } } } #endregion #region Helper Methods private async void SubscribeToTopic(string topic) { await _client.SubscribeAsync( new TopicFilterBuilder() .WithTopic(TOPIC_PREFIX + topic) .Build() ); Debug.WriteLine("Subscribed to topic" + TOPIC_PREFIX + topic); } /// <summary> /// Parses the payload received from MQTT and returns a tuple with the usable values /// </summary> /// <param name="payload">Decrypted payload received from MQTT</param> /// <returns> /// Item 1: replyIdeationId /// Item 2: char array of votes with the delimiters removed (e.g. ++++-+-+) /// </returns> private static Tuple<int, char[]> ParseVote(string payload) { var replyId = int.Parse(payload.Substring(0, 4)); var votes = new List<char>(); for (var i = 4; i < payload.Length; i++) { votes.Add(payload[i]); } return Tuple.Create(replyId, votes.ToArray()); } #endregion } }
namespace HitBTC.Net.Requests { /// <summary> /// Get currency /// </summary> internal class GetCurrencyRequest : HitBTCSocketRequest { public GetCurrencyRequest(int id, string currency) : base(id, "getCurrency") { this.AddParameter("currency", currency); } } }
using System; using System.Windows.Input; using Xamarin.Forms; namespace ZXing.Net.Xamarin.Forms { public class ZXingOverlay : Grid { Label topText; Label botText; public ZXingOverlay() { BindingContext = this; VerticalOptions = LayoutOptions.FillAndExpand; HorizontalOptions = LayoutOptions.FillAndExpand; RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }); RowDefinitions.Add(new RowDefinition { Height = new GridLength(2, GridUnitType.Star) }); RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }); ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); Children.Add(new BoxView { VerticalOptions = LayoutOptions.Fill, HorizontalOptions = LayoutOptions.FillAndExpand, BackgroundColor = Color.Black, Opacity = 0.7, }, 0, 0); Children.Add(new BoxView { VerticalOptions = LayoutOptions.Fill, HorizontalOptions = LayoutOptions.FillAndExpand, BackgroundColor = Color.Black, Opacity = 0.7, }, 0, 2); Children.Add(new BoxView { VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.FillAndExpand, HeightRequest = 3, BackgroundColor = Color.Red, Opacity = 0.6, }, 0, 1); topText = new Label { VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center, TextColor = Color.White, }; topText.SetBinding(Label.TextProperty, new Binding(nameof(TopText))); Children.Add(topText, 0, 0); botText = new Label { VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center, TextColor = Color.White, }; botText.SetBinding(Label.TextProperty, new Binding(nameof(BottomText))); Children.Add(botText, 0, 2); } public static readonly BindableProperty TopTextProperty = BindableProperty.Create(nameof(TopText), typeof(string), typeof(ZXingOverlay), string.Empty); public string TopText { get { return (string)GetValue(TopTextProperty); } set { SetValue(TopTextProperty, value); } } public static readonly BindableProperty BottomTextProperty = BindableProperty.Create(nameof(BottomText), typeof(string), typeof(ZXingOverlay), string.Empty); public string BottomText { get { return (string)GetValue(BottomTextProperty); } set { SetValue(BottomTextProperty, value); } } } }
using ConsoleApp; using Microsoft.EntityFrameworkCore; using Microsoft.VisualStudio.TestTools.UnitTesting; using SamuraiApp.Data; using SamuraiApp.Domain; using System.Collections.Generic; using System.Linq; namespace TestsForConsoleApp { [TestClass] public class BizDataLogicTests { [TestMethod] public void AddMultipleSamuraisReturnsCorrectNumberOfInsertedRows() { var builder = new DbContextOptionsBuilder(); builder.UseInMemoryDatabase("AddMultipleSamurais"); using (var context = new SamuraiContext(builder.Options)) { var bizlogic = new BusinessDataLogic(context); var nameList = new string[] { "Kikuchiyo", "Kyuzo", "Rikchi" }; var result = bizlogic.AddMultipleSamurais(nameList); Assert.AreEqual(nameList.Count(), result); } } [TestMethod] public void CanInsertSingleSamurai() { var builder = new DbContextOptionsBuilder(); builder.UseInMemoryDatabase("InsertNewSamurai"); using (var context = new SamuraiContext(builder.Options)) { var bizlogic = new BusinessDataLogic(context); bizlogic.InsertNewSamurai(new Samurai()); }; using (var context2 = new SamuraiContext(builder.Options)) { Assert.AreEqual(1, context2.Samurais.Count()); } } [TestMethod] public void CanInsertSamuraiwithQuotes() { var samuraiGraph = new Samurai { Name = "Kyūzō", Quotes = new List<Quote> { new Quote { Text = "Watch out for my sharp sword!" }, new Quote { Text = "I told you to watch out for the sharp sword! Oh well!" } } }; var builder = new DbContextOptionsBuilder(); builder.UseInMemoryDatabase("SamuraiWithQuotes"); using (var context = new SamuraiContext(builder.Options)) { var bizlogic = new BusinessDataLogic(context); var result = bizlogic.InsertNewSamurai(samuraiGraph); }; using (var context2 = new SamuraiContext(builder.Options)) { var samuraiWithQuotes = context2.Samurais.Include(s => s.Quotes).FirstOrDefaultAsync().Result; Assert.AreEqual(2, samuraiWithQuotes.Quotes.Count); } } [TestMethod, TestCategory("SamuraiWithQuotes")] public void CanGetSamuraiwithQuotes() { int samuraiId; var builder = new DbContextOptionsBuilder(); builder.UseInMemoryDatabase("SamuraiWithQuotes"); using (var seedcontext = new SamuraiContext(builder.Options)) { var samuraiGraph = new Samurai { Name = "Kyūzō", Quotes = new List<Quote> { new Quote { Text = "Watch out for my sharp sword!" }, new Quote { Text = "I told you to watch out for the sharp sword! Oh well!" } } }; seedcontext.Samurais.Add(samuraiGraph); seedcontext.SaveChanges(); samuraiId = samuraiGraph.Id; } using (var context = new SamuraiContext(builder.Options)) { var bizlogic = new BusinessDataLogic(context); var result = bizlogic.GetSamuraiWithQuotes(samuraiId); Assert.AreEqual(2, result.Quotes.Count); }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NetPrintsEditor.Compilation { [Serializable] public class CodeCompileResults { public bool Success { get; } public IEnumerable<string> Errors { get; } public string PathToAssembly { get; } public CodeCompileResults(bool success, IEnumerable<string> errors, string pathToAssembly) { Success = success; Errors = errors; PathToAssembly = pathToAssembly; } } public interface ICodeCompiler { CodeCompileResults CompileSources(string outputPath, IEnumerable<string> assemblyPaths, IEnumerable<string> sources, bool generateExecutable); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PointInRectangle { class Program { static void Main(string[] args) { decimal x1 = decimal.Parse(Console.ReadLine()); decimal y1 = decimal.Parse(Console.ReadLine()); decimal x2 = decimal.Parse(Console.ReadLine()); decimal y2 = decimal.Parse(Console.ReadLine()); decimal x = decimal.Parse(Console.ReadLine()); decimal y = decimal.Parse(Console.ReadLine()); bool istInRectangle = (x1<= x && x <= x2) && (y1 <= y && y <= y2) ; Console.WriteLine("{0}",istInRectangle ? "Inside" : "Outside"); } } }
using Newtonsoft.Json; namespace Printful.API.Model.Entities { public class PackingSlip { [JsonProperty("email")] public string email { get; set; } [JsonProperty("phone")] public string phone { get; set; } [JsonProperty("message")] public string message { get; set; } } }
namespace SpreadsheetSerializer.AsposeCells { public class WorkbookCreator { public static AsposeWorkbook CreateWorkbookWithName(string workbookName) { return new AsposeWorkbook().WithWorkbookName(workbookName); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using BrightstarDB.Client; using System.Xml.Linq; using System.Threading.Tasks; namespace BrightstarDB.PerformanceBenchmarks { public class TaxonomyDocumentBenchmark : BenchmarkBase { private int _numDocs; public override void Setup() { var start = DateTime.UtcNow; int tripleCount = CreateTaxonomy(); var end = DateTime.UtcNow; Report.LogOperationCompleted("Create Taxonomy", string.Format("Created {0} triples", tripleCount), tripleCount, end.Subtract(start).TotalMilliseconds); _numDocs = TestScale*20000; // 20k to 100k depending on scale start = DateTime.UtcNow; tripleCount = CreateDocumentsInBatches(10, _numDocs/10); end = DateTime.UtcNow; Report.LogOperationCompleted("Create Documents", string.Format("created {0} triples", tripleCount), tripleCount, end.Subtract(start).TotalMilliseconds); CheckConsistency(); } /// <summary> /// Used to check that the data structures are in the expected form before doing any queries or updates /// </summary> private void CheckConsistency() { var docUri = "http://example.org/taxonomybenchmark/documents/400"; var result = XDocument.Load(Service.ExecuteQuery(StoreName, "select * where { <" + docUri + "> ?p ?o }")); if (!result.SparqlResultRows().Any()) { throw new BenchmarkAssertionException("Bad data - document resource not found."); } var taxterm = "http://example.org/taxonomybenchmark/classification/l1-0-l2-87-l3-69"; result = XDocument.Load(Service.ExecuteQuery(StoreName, "select * where { <" + taxterm + "> ?p ?o }")); var hasParent = false; foreach (XElement row in result.SparqlResultRows()) { if (row.GetColumnValue("p").Equals("http://example.org/taxonomybenchmark/schema/parent")) { hasParent = true; } } if (!hasParent) { throw new BenchmarkAssertionException("Bad data - resource not connected to a taxonomy term."); } } private int CreateTaxonomy() { var sb = new StringBuilder(); int tripleCount = 0; // root node MakeTriple("classification", "root", "schema", "a", "schema", "TaxonomyTerm", sb); tripleCount++; // level 1 int countLevelOne = 10; // level 2 int countLevelTwo = 100; // level 3 int countLevelThree = 100; for (var i = 0; i < countLevelOne; i++) { tripleCount += MakeTaxonomyNode("l1-" + i, "root", sb); for (var j = 0; j < countLevelTwo; j++) { tripleCount += MakeTaxonomyNode("l1-" + i + "-l2-" + j, "l1" + i, sb); for (var k = 0; k < countLevelThree; k++) { tripleCount += MakeTaxonomyNode("l1-" + i + "-l2-" + j + "-l3-" + k, "l1-" + i + "-l2-" + j, sb); } } } InsertData(sb.ToString()); return tripleCount; } private int MakeTaxonomyNode(string id, string parentId, StringBuilder sb) { MakeTriple("classification", id, "schema", "a", "schema", "TaxonomyTerm", sb); MakeTriple("classification", id, "schema", "parent", "classification", parentId, sb); return 2; } private const string TriplePattern = "<{0}> <{1}> <{2}> ."; private void MakeTriple(string subjContainer, string subjId, string predContainer, string predId, string objContainer, string objId, StringBuilder sb) { sb.AppendLine(string.Format(TriplePattern, MakeResourceUri(subjContainer, subjId), MakeResourceUri(predContainer, predId), MakeResourceUri(objContainer, objId))); } private void InsertData(String data) { var updateData = new UpdateTransactionData(); updateData.InsertData = data; Service.ExecuteTransaction(StoreName, updateData); } // try and create a uri length and namespace that is typical in the real world. private const string ResourcePrefix = "http://example.org/taxonomybenchmark/{0}/{1}"; private string MakeResourceUri(string container, string id) { return String.Format(ResourcePrefix, container, id); } private int CreateDocumentsInBatches(int batchSize, int batchItemCount) { var tripleCount = 0; var docId = 0; var rnd = new Random(1000000); string template = "l1-{0}-l2-{1}-l3-{2}"; for (int i = 0; i < batchSize; i++) { var sb = new StringBuilder(); for (int j = 0; j < batchItemCount; j++) { var classification = new List<String>() { string.Format(template, rnd.Next(10), rnd.Next(100), rnd.Next(100)), string.Format(template, rnd.Next(10), rnd.Next(100), rnd.Next(100)), string.Format(template, rnd.Next(10), rnd.Next(100), rnd.Next(100)) }; tripleCount += MakeDocumentNode(docId.ToString(), classification, sb); docId++; } InsertData(sb.ToString()); } return tripleCount; } private int MakeDocumentNode(string id, IEnumerable<string> classification, StringBuilder sb) { int count = 1; MakeTriple("documents", id, "schema", "a", "schema", "Document", sb); foreach (var c in classification) { MakeTriple("documents", id, "schema", "classified-by", "classification", c, sb); count++; } return count; } public override void RunMix() { // get document metadata Random rnd = new Random(565979575); int cycleCount = 1000; int docId; var start = DateTime.UtcNow; for (int i = 0; i < cycleCount; i++) { docId = rnd.Next(_numDocs); var result = XDocument.Load(Service.ExecuteQuery(StoreName, "select * where { <http://example.org/taxonomybenchmark/documents/" + docId + "> ?p ?o }")); } var end = DateTime.UtcNow; Report.LogOperationCompleted("random-lookup-by-docid", string.Format( "Fetched all properties for {0} randomly selected documents documents", cycleCount), cycleCount, end.Subtract(start).TotalMilliseconds); docId = rnd.Next(_numDocs); start = DateTime.UtcNow; for (int i = 0; i < cycleCount; i++) { var result = XDocument.Load(Service.ExecuteQuery(StoreName, "select * where { <http://example.org/taxonomybenchmark/documents/" + docId + "> ?p ?o }")); } end = DateTime.UtcNow; Report.LogOperationCompleted("repeated-lookup-by-docid", string.Format("Fetched all properties of the same document repeatedly"), cycleCount, end.Subtract(start).TotalMilliseconds); // Single-threaded retrieval cycleCount = 40000; start = DateTime.UtcNow; for (int i = 0; i < cycleCount; i++) { docId = rnd.Next(_numDocs); var result = XDocument.Load(Service.ExecuteQuery(StoreName, "select * where { <http://example.org/taxonomybenchmark/documents/" + docId + "> ?p ?o }")); } end = DateTime.UtcNow; Report.LogOperationCompleted("single-thread-metadata-lookup", string.Format("Single thread retrieving all properties of a randomly selected document", cycleCount), cycleCount, end.Subtract(start).TotalMilliseconds); // run threaded document lookup start = DateTime.UtcNow; Parallel.Invoke(() => GetDocumentMetadata(new Random(1), cycleCount/4), () => GetDocumentMetadata(new Random(2), cycleCount/4), () => GetDocumentMetadata(new Random(3), cycleCount/4), () => GetDocumentMetadata(new Random(4), cycleCount/4)); end = DateTime.UtcNow; Report.LogOperationCompleted("parallel-document-metadata-lookup", "4 parallel tasks retrieving all properties of randomly selected documents", cycleCount, end.Subtract(start).TotalMilliseconds); } public override void CleanUp() { // Nothing to do } private void GetDocumentMetadata(Random rnd, int cycleCount) { for (int i = 0; i < cycleCount; i++) { var docId = rnd.Next(_numDocs); var result = XDocument.Load(Service.ExecuteQuery(StoreName, "select * where { <http://example.org/taxonomybenchmark/documents/" + docId + "> ?p ?o }")); } } } }
namespace Trakt.Api.DataContracts.BaseModel; /// <summary> /// The trakt.tv movie id class. /// </summary> public class TraktMovieId : TraktIMDBandTMDBId { }
namespace AmazonPrimeVideoSearch.Model { public interface ITVRepository { TVMetadata GetTVMetadata(); TVSearchResults TVSearch(TVSearchCriteria criteria); } }
using System; using System.IO; namespace CustomerTestsExcel { public class ExcelTabularLibrary : ITabularLibrary { public string DefaultExtension => "xlsx"; public ITabularBook NewBook() => new ExcelTabularBook(); public ITabularBook NewBook(string filename) => new ExcelTabularBook(filename); public ITabularBook OpenBook(Stream stream) => new ExcelTabularBook(stream); } }
using Core.Entities; using System; namespace Entities.DTOs { public class RentalDetailDto: IDto { public int RentalId { get; set; } public int CarId { get; set; } public string BrandName { get; set; } public string CustomerName { get; set; } public string UserName { get; set; } public DateTime RentDate { get; set; } public DateTime? ReturnDate { get; set; } } }
namespace $RootNamespace$ { public class ProxyTypesAssembly { } }
namespace API.Routes; /// <summary> /// Represents container routes /// </summary> public static class ContainerRoutes { /// <summary> /// Route for get container list. /// </summary> public const string List = "api/Container/List"; /// <summary> /// Route for delete container /// </summary> public const string Delete = "api/Container/Delete"; }