text
stringlengths
13
6.01M
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Monster : MonoBehaviour { //public int id; //public float spacing; ////// Use this for initialization ////void Start () { ////} ////// Update is called once per frame ////void Update () { //// float wave = Mathf.Sin(Time.fixedTime + id); //// transform.position = new Vector3(/*id * spacing*/0.0f, wave, 0.0f); //// } public GameObject playerObject; void Start() { Vector3 pos = new Vector3(); pos.x = Random.Range(-10f, 10f); pos.z = Random.Range(-10f, 10f); transform.position = pos; GameObject[] AllGameObjects = GameObject.FindObjectsOfType (typeof(GameObject)) as GameObject[]; foreach (GameObject aGameObject in AllGameObjects) { Component aComponent = aGameObject.GetComponent(typeof(Player1)); if (aComponent != null) playerObject = aGameObject; } } void OnDrawGizmos() { Gizmos.DrawLine(transform.position, transform.position + direction); } Vector3 direction;// variable con alcance de clase public float attackRange = 1.0f; public float speedMultiplier = 0.1f; void Update() { //if (mState == MonsterState.standing) //{ // print("El monstruo está quieto"); //} //if (mState == MonsterState.wandering) //{ // print("El monstruo está rondando"); //} //if (mState == MonsterState.chasing) //{ // print("El monstruo está persiguiendo"); //} //if (mState == MonsterState.attacking) //{ // print("El monstruo está atacando"); //} if ((playerObject.transform.position - transform.position).magnitude > attackRange) { direction = Vector3.Normalize(playerObject.transform.position - transform.position); transform.position += direction * speedMultiplier; } } }
using System.Collections.Generic; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { /// <summary> /// /// </summary> /// <remarks> /// Is not a record on purpose... /// get; set; for the moment, to allow for replacement of values. /// </remarks> public class ServerCapabilities : CapabilitiesBase, IServerCapabilities { /// <summary> /// Defines how text documents are synced. Is either a detailed structure defining each notification or /// for backwards compatibility the TextDocumentSyncKind number. /// </summary> [Optional] public TextDocumentSync? TextDocumentSync { get; set; } /// <summary> /// The server provides hover support. /// </summary> [Optional] public BooleanOr<HoverRegistrationOptions.StaticOptions>? HoverProvider { get; set; } /// <summary> /// The server provides completion support. /// </summary> [Optional] public CompletionRegistrationOptions.StaticOptions? CompletionProvider { get; set; } /// <summary> /// The server provides signature help support. /// </summary> [Optional] public SignatureHelpRegistrationOptions.StaticOptions? SignatureHelpProvider { get; set; } /// <summary> /// The server provides goto definition support. /// </summary> [Optional] public BooleanOr<DefinitionRegistrationOptions.StaticOptions>? DefinitionProvider { get; set; } /// <summary> /// The server provides find references support. /// </summary> [Optional] public BooleanOr<ReferenceRegistrationOptions.StaticOptions>? ReferencesProvider { get; set; } /// <summary> /// The server provides document highlight support. /// </summary> [Optional] public BooleanOr<DocumentHighlightRegistrationOptions.StaticOptions>? DocumentHighlightProvider { get; set; } /// <summary> /// The server provides document symbol support. /// </summary> [Optional] public BooleanOr<DocumentSymbolRegistrationOptions.StaticOptions>? DocumentSymbolProvider { get; set; } /// <summary> /// The server provides workspace symbol support. /// </summary> [Optional] public BooleanOr<WorkspaceSymbolRegistrationOptions.StaticOptions>? WorkspaceSymbolProvider { get; set; } /// <summary> /// The server provides code actions. /// </summary> [Optional] public BooleanOr<CodeActionRegistrationOptions.StaticOptions>? CodeActionProvider { get; set; } /// <summary> /// The server provides code lens. /// </summary> [Optional] public CodeLensRegistrationOptions.StaticOptions? CodeLensProvider { get; set; } /// <summary> /// The server provides document formatting. /// </summary> [Optional] public BooleanOr<DocumentFormattingRegistrationOptions.StaticOptions>? DocumentFormattingProvider { get; set; } /// <summary> /// The server provides document range formatting. /// </summary> [Optional] public BooleanOr<DocumentRangeFormattingRegistrationOptions.StaticOptions>? DocumentRangeFormattingProvider { get; set; } /// <summary> /// The server provides document formatting on typing. /// </summary> [Optional] public DocumentOnTypeFormattingRegistrationOptions.StaticOptions? DocumentOnTypeFormattingProvider { get; set; } /// <summary> /// The server provides rename support. /// </summary> [Optional] public BooleanOr<RenameRegistrationOptions.StaticOptions>? RenameProvider { get; set; } /// <summary> /// The server provides document link support. /// </summary> [Optional] public DocumentLinkRegistrationOptions.StaticOptions? DocumentLinkProvider { get; set; } /// <summary> /// The server provides execute command support. /// </summary> [Optional] public ExecuteCommandRegistrationOptions.StaticOptions? ExecuteCommandProvider { get; set; } /// <summary> /// Experimental server capabilities. /// </summary> [Optional] public IDictionary<string, JToken> Experimental { get; set; } = new Dictionary<string, JToken>(); /// <summary> /// The server provides Goto Type Definition support. /// /// Since 3.6.0 /// </summary> [Optional] public BooleanOr<TypeDefinitionRegistrationOptions.StaticOptions>? TypeDefinitionProvider { get; set; } /// <summary> /// The server provides Goto Implementation support. /// /// Since 3.6.0 /// </summary> [Optional] public BooleanOr<ImplementationRegistrationOptions.StaticOptions>? ImplementationProvider { get; set; } /// <summary> /// The server provides color provider support. /// /// Since 3.6.0 /// </summary> [Optional] public BooleanOr<DocumentColorRegistrationOptions.StaticOptions>? ColorProvider { get; set; } /// <summary> /// The server provides Call Hierarchy support. /// </summary> [Optional] public BooleanOr<CallHierarchyRegistrationOptions.StaticOptions>? CallHierarchyProvider { get; set; } /// <summary> /// The server provides Call Hierarchy support. /// </summary> [Optional] public SemanticTokensRegistrationOptions.StaticOptions? SemanticTokensProvider { get; set; } /// <summary> /// The server provides Call Hierarchy support. /// </summary> [Optional] public MonikerRegistrationOptions.StaticOptions? MonikerProvider { get; set; } /// <summary> /// The server provides folding provider support. /// /// Since 3.10.0 /// </summary> public BooleanOr<FoldingRangeRegistrationOptions.StaticOptions>? FoldingRangeProvider { get; set; } /// <summary> /// The server provides selection range support. /// /// Since 3.15.0 /// </summary> public BooleanOr<SelectionRangeRegistrationOptions.StaticOptions>? SelectionRangeProvider { get; set; } /// <summary> /// The server provides on type rename support. /// /// Since 3.16.0 /// </summary> [Optional] public BooleanOr<LinkedEditingRangeRegistrationOptions.StaticOptions>? LinkedEditingRangeProvider { get; set; } /// <summary> /// The server provides folding provider support. /// /// Since 3.14.0 /// </summary> public BooleanOr<DeclarationRegistrationOptions.StaticOptions>? DeclarationProvider { get; set; } /// <summary> /// Workspace specific server capabilities /// </summary> [Optional] public WorkspaceServerCapabilities? Workspace { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Library { public class Katalog : IZarzadzaniePozycjami { //private string dzialTematyczny; public List<Pozycja> listaPozycji = new List<Pozycja>(); public string dzialTematyczny { get; private set; } public Katalog() { } public Katalog(string dzialTematyczny) { this.dzialTematyczny = dzialTematyczny; } public void DodajPozycje(Pozycja pozycja) { if (listaPozycji == null) { listaPozycji[0] = pozycja; } else { listaPozycji.Add(pozycja); } } public void WypiszWszystkiePozycje() { Console.WriteLine($"~~~~~~~~~~~~~~~~~~~~~~~~Kategoria : {dzialTematyczny}"); foreach (Pozycja pozycja in listaPozycji) { pozycja.WypiszInfo(); } } public void ZnajdzPozycjePoId(int i) { var tmp = listaPozycji.Find(x => x.id == i); if (tmp != null) { Console.WriteLine($"\nZnaleziono pozycję o id {i} w katalogu {this.dzialTematyczny}:"); tmp.WypiszInfo(); } } public void ZnajdzPozycjePoTytule(string title) { var tmp = listaPozycji.Find(x => x.tytul == title); if (tmp != null) { Console.WriteLine($"\nZnaleziono pozycję o tytule \"{title}\" w katalogu {this.dzialTematyczny}:"); tmp.WypiszInfo(); } } } }
using UnityEngine; using System.Collections; public class EnemyMovement : MonoBehaviour { public float speed; // Control enemy movement speed private Animator myAnimator; // Control animations public bool facingLeft = true; // Check if facing left public bool onWall; // Check if enemy is colliding with wall public LayerMask whatIsWall; private Rigidbody2D myRigidBody; private Collider2D myCollider; float h; // Horizontal movement direction Vector3 playerPos; // Player position Vector3 enemyPos; // Enemy position float distance; // Distance from player and enemy PlayerController player; LevelController levelController; // Use this for initialization void Start() { myRigidBody = GetComponent<Rigidbody2D> (); myAnimator = GetComponent<Animator> (); myCollider = GetComponent<Collider2D>(); player = FindObjectOfType<PlayerController>(); levelController = FindObjectOfType<LevelController>(); } void FixedUpdate () { if (facingLeft) { h = -1; } else { h = 1; } Vector3 movement = new Vector3 (h*speed, transform.position.y, transform.position.z); myRigidBody.velocity = movement; } // Update is called once per frame void Update() { enemyPos = GetComponent<Transform>().position; playerPos = player.transform.position; distance = Vector3.Distance(enemyPos, playerPos); onWall = Physics2D.IsTouchingLayers(myCollider, whatIsWall); if (onWall) { Flip (); } } // Flip object when encountering a wall void Flip() { Vector3 theScale = transform.localScale; theScale.x *= -1; transform.localScale = theScale; if (facingLeft) facingLeft = false; else facingLeft = true; } }
using Prism.Commands; using Prism.Events; using Prism.Mvvm; using Prism.Navigation; using SafetyForAllApp.Messages; using SafetyForAllApp.Model; using SafetyForAllApp.Service.Interfaces; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Reflection; namespace SafetyForAllApp.ViewModels { public class MasterDetailViewModel : ViewModelBase { private IMenuService _menuService; private IEventAggregator _eventAggregator; private IDocumentViewer _documentViewer; private string _pdfPath; private ObservableCollection<DetailsItem> _detailsItems; public ObservableCollection<DetailsItem> DetailsItems { get { return _detailsItems; } set { SetProperty(ref _detailsItems, value); } } private DelegateCommand<DetailsItem> _navigateCommand; public DelegateCommand<DetailsItem> NavigateCommand => _navigateCommand ?? (_navigateCommand = new DelegateCommand<DetailsItem>(ExecuteNavigateCommand)); public async void ExecuteNavigateCommand(DetailsItem item) { { if (item.MenuType == SafetyForAllApp.MenuType.MenuItemEnum.LogOut) _menuService.LogOut(); else { if (!string.IsNullOrEmpty(item.NavigationPath)) await NavigationService.NavigateAsync(item.NavigationPath); else { switch (item.Id) { case 3: // Id of the menu CopyEmbeddedContent("SafetyForAllApp.PdfFile.PersonalSafety.pdf", "PersonalSafety.pdf"); _documentViewer.ViewDocument(_pdfPath, "PersonalSafety.pdf"); break; } } } } } public MasterDetailViewModel(INavigationService navigationService, IMenuService menuService, IEventAggregator eventAggregator, IDocumentViewer documentViewer) : base(navigationService) { _menuService = menuService; _eventAggregator = eventAggregator; _documentViewer = documentViewer; DetailsItems = new ObservableCollection<DetailsItem>(_menuService.GetAllowedAccessItems()); _eventAggregator.GetEvent<LogInMessage>().Subscribe(LoginEvent); _eventAggregator.GetEvent<LogOutMessage>().Subscribe(LogOutEvent); _pdfPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); } public void LoginEvent() { DetailsItems = new ObservableCollection<DetailsItem>(_menuService.GetAllowedAccessItems()); NavigationService.NavigateAsync("NavigationPage/MenuPage"); } public void LogOutEvent() { DetailsItems = new ObservableCollection<DetailsItem>(_menuService.GetAllowedAccessItems()); NavigationService.NavigateAsync("NavigationPage/MainPage"); } private void CopyEmbeddedContent(string resourceName, string outputFileName) { var assembly = typeof(App).GetTypeInfo().Assembly; using (Stream resFilestream = assembly.GetManifestResourceStream(resourceName)) { if (resFilestream == null) return; byte[] ba = new byte[resFilestream.Length]; resFilestream.Read(ba, 0, ba.Length); File.WriteAllBytes(Path.Combine(_pdfPath, outputFileName), ba); } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNet.OData; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore.TestModels.ComplexNavigationsModel; namespace Microsoft.EntityFrameworkCore.Query { public class LevelOneController : TestODataController, IDisposable { private readonly ComplexNavigationsODataContext _context; public LevelOneController(ComplexNavigationsODataContext context) { _context = context; } [HttpGet] [EnableQuery] public IEnumerable<Level1> Get() { return _context.LevelOne; } [HttpGet] [EnableQuery] public ITestActionResult Get([FromODataUri] int key) { var result = _context.LevelOne.FirstOrDefault(e => e.Id == key); return result == null ? NotFound() : (ITestActionResult)Ok(result); } public void Dispose() { } } public class LevelTwoController : TestODataController, IDisposable { private readonly ComplexNavigationsODataContext _context; public LevelTwoController(ComplexNavigationsODataContext context) { _context = context; } [HttpGet] [EnableQuery] public IEnumerable<Level2> Get() { return _context.LevelTwo; } [HttpGet] [EnableQuery] public ITestActionResult Get([FromODataUri] int key) { var result = _context.LevelTwo.FirstOrDefault(e => e.Id == key); return result == null ? NotFound() : (ITestActionResult)Ok(result); } public void Dispose() { } } public class LevelThreeController : TestODataController, IDisposable { private readonly ComplexNavigationsODataContext _context; public LevelThreeController(ComplexNavigationsODataContext context) { _context = context; } [HttpGet] [EnableQuery] public IEnumerable<Level3> Get() { return _context.LevelThree; } [HttpGet] [EnableQuery] public ITestActionResult Get([FromODataUri] int key) { var result = _context.LevelThree.FirstOrDefault(e => e.Id == key); return result == null ? NotFound() : (ITestActionResult)Ok(result); } public void Dispose() { } } public class LevelFourController : TestODataController, IDisposable { private readonly ComplexNavigationsODataContext _context; public LevelFourController(ComplexNavigationsODataContext context) { _context = context; } [HttpGet] [EnableQuery] public IEnumerable<Level4> Get() { return _context.LevelFour; } [HttpGet] [EnableQuery] public ITestActionResult Get([FromODataUri] int key) { var result = _context.LevelFour.FirstOrDefault(e => e.Id == key); return result == null ? NotFound() : (ITestActionResult)Ok(result); } public void Dispose() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebService.ViewModel { public class PhieuDatHangVM { public string MaPDH { get; set; } public string MaKH { get; set; } public string MaNV { get; set; } public string MaDV { get; set; } public DateTime? NgayLap { get; set; } } }
namespace Triton.Game.Mapping { using ns25; using ns26; using System; using System.Collections.Generic; [Attribute38("Tutorial_02")] public class Tutorial_02 : TutorialEntity { public Tutorial_02(IntPtr address) : this(address, "Tutorial_02") { } public Tutorial_02(IntPtr address, string className) : base(address, className) { } public void FadeInManaSpotlight() { base.method_8("FadeInManaSpotlight", Array.Empty<object>()); } public List<RewardData> GetCustomRewards() { Class267<RewardData> class2 = base.method_14<Class267<RewardData>>("GetCustomRewards", Array.Empty<object>()); if (class2 != null) { return class2.method_25(); } return null; } public string GetTurnStartReminderText() { return base.method_13("GetTurnStartReminderText", Array.Empty<object>()); } public void ManaLabelLoadedCallback(string actorName, GameObject actorObject, object callbackData) { object[] objArray1 = new object[] { actorName, actorObject, callbackData }; base.method_8("ManaLabelLoadedCallback", objArray1); } public void NotifyOfCardDropped(Triton.Game.Mapping.Entity entity) { object[] objArray1 = new object[] { entity }; base.method_8("NotifyOfCardDropped", objArray1); } public void NotifyOfCardGrabbed(Triton.Game.Mapping.Entity entity) { object[] objArray1 = new object[] { entity }; base.method_8("NotifyOfCardGrabbed", objArray1); } public void NotifyOfCardMousedOff(Triton.Game.Mapping.Entity mousedOffEntity) { object[] objArray1 = new object[] { mousedOffEntity }; base.method_8("NotifyOfCardMousedOff", objArray1); } public void NotifyOfCardMousedOver(Triton.Game.Mapping.Entity mousedOverEntity) { object[] objArray1 = new object[] { mousedOverEntity }; base.method_8("NotifyOfCardMousedOver", objArray1); } public void NotifyOfCoinFlipResult() { base.method_8("NotifyOfCoinFlipResult", Array.Empty<object>()); } public void NotifyOfDefeatCoinAnimation() { base.method_8("NotifyOfDefeatCoinAnimation", Array.Empty<object>()); } public bool NotifyOfEndTurnButtonPushed() { return base.method_11<bool>("NotifyOfEndTurnButtonPushed", Array.Empty<object>()); } public void NotifyOfEnemyManaCrystalSpawned() { base.method_8("NotifyOfEnemyManaCrystalSpawned", Array.Empty<object>()); } public void NotifyOfGameOver(TAG_PLAYSTATE gameResult) { object[] objArray1 = new object[] { gameResult }; base.method_8("NotifyOfGameOver", objArray1); } public List<string> NotifyOfKeywordHelpPanelDisplay(Triton.Game.Mapping.Entity entity) { object[] objArray1 = new object[] { entity }; Class245 class2 = base.method_14<Class245>("NotifyOfKeywordHelpPanelDisplay", objArray1); if (class2 != null) { return class2.method_25(); } return null; } public void NotifyOfManaCrystalSpawned() { base.method_8("NotifyOfManaCrystalSpawned", Array.Empty<object>()); } public void NotifyOfManaError() { base.method_8("NotifyOfManaError", Array.Empty<object>()); } public void NotifyOfTooltipZoneMouseOver(TooltipZone tooltip) { object[] objArray1 = new object[] { tooltip }; base.method_8("NotifyOfTooltipZoneMouseOver", objArray1); } public void Plus1ActorLoadedCallback(string actorName, GameObject actorObject, object callbackData) { object[] objArray1 = new object[] { actorName, actorObject, callbackData }; base.method_8("Plus1ActorLoadedCallback", objArray1); } public void Plus1ActorLoadedCallbackEnemy(string actorName, GameObject actorObject, object callbackData) { object[] objArray1 = new object[] { actorName, actorObject, callbackData }; base.method_8("Plus1ActorLoadedCallbackEnemy", objArray1); } public void PreloadAssets() { base.method_8("PreloadAssets", Array.Empty<object>()); } public void ShowEndTurnBouncingArrow() { base.method_8("ShowEndTurnBouncingArrow", Array.Empty<object>()); } public GameObject costLabel { get { return base.method_3<GameObject>("costLabel"); } } public Triton.Game.Mapping.Notification endTurnNotifier { get { return base.method_3<Triton.Game.Mapping.Notification>("endTurnNotifier"); } } public Triton.Game.Mapping.Notification handBounceArrow { get { return base.method_3<Triton.Game.Mapping.Notification>("handBounceArrow"); } } public Triton.Game.Mapping.Notification manaNotifier { get { return base.method_3<Triton.Game.Mapping.Notification>("manaNotifier"); } } public Triton.Game.Mapping.Notification manaNotifier2 { get { return base.method_3<Triton.Game.Mapping.Notification>("manaNotifier2"); } } public int numManaThisTurn { get { return base.method_2<int>("numManaThisTurn"); } } } }
using System; public static class Kata { public static string Likes(string[] name) { if(name.Length == 0){ return "no one likes this"; }else if(name.Length == 1){ return name[0] +" likes this"; }else if(name.Length == 2){ return name[0]+" and "+name[1]+" like this"; }else if(name.Length == 3){ return name[0]+", "+name[1]+" and "+name[2]+" like this"; }else{ if(name.Length > 3){ int len = name.Length - 2; return name[0]+", "+name[1]+" and "+ len+" others like this"; } } return ""; } } /* You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item. Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples: */ /* Kata.Likes(new string[0]) => "no one likes this" Kata.Likes(new string[] {"Peter"}) => "Peter likes this" Kata.Likes(new string[] {"Jacob", "Alex"}) => "Jacob and Alex like this" Kata.Likes(new string[] {"Max", "John", "Mark"}) => "Max, John and Mark like this" Kata.Likes(new string[] {"Alex", "Jacob", "Mark", "Max"}) => "Alex, Jacob and 2 others like this" */
using DEMO_DDD.DOMAIN.Entidades; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace DEMO_DDD.INFRA.DATA.Contexto { public class DemoDDDContext : DbContext { public DemoDDDContext(DbContextOptions options) : base(options) { } public DbSet<Cliente> Clientes { get; set; } public DbSet<Produto> Produtos { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfigurationsFromAssembly(typeof(DemoDDDContext).Assembly); //caso esqueca de mapear um campo da sua entidade e o mesmo na entre como valor maximo no banco. //setando como padrao varchar(100) para campos do tipo string foreach (var property in modelBuilder.Model.GetEntityTypes() .SelectMany(e => e.GetProperties().Where(p => p.ClrType == typeof(string)))) property.SetColumnType("varchar(100)"); //aplicando as configurações acima para campos varchar modelBuilder.ApplyConfigurationsFromAssembly(typeof(DemoDDDContext).Assembly); //desabilitando o cascade delete que por padrao do entity é do tipo cascade foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys())) relationship.DeleteBehavior = DeleteBehavior.ClientSetNull; base.OnModelCreating(modelBuilder); } /// <summary> /// Configrando a data cadastro pra sempre setar data atual ao adicionar um registro novo Added /// </summary> /// <returns></returns> public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default) { foreach (var entry in ChangeTracker.Entries().Where(entry => entry.GetType().GetProperty("DataCadastro") == null)) { if (entry.State == EntityState.Added) { entry.Property("DataCadastro").CurrentValue = DateTime.Now; } if (entry.State == EntityState.Modified) { entry.Property("DataCadastro").IsModified = false; } } return await base.SaveChangesAsync(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using CoordControl.Core.Domains; namespace CoordControl.Forms { public interface IFormPlans { List<Plan> PlanList { set; } Plan SelectedPlan { get; } String TitleForm { get; set; } event EventHandler ModelingButtonClick; event EventHandler EditClick; event EventHandler DeleteClick; event EventHandler ViewClick; event EventHandler CalcAnalytClick; event EventHandler CalcImitRightWayClick; event EventHandler CalcImitLeftWayClick; event EventHandler CalcImitSumClick; event EventHandler CalcMoveTimeCorrectClick; event EventHandler CalcMoveTimeClick; event EventHandler CalcWithoutShiftsClick; } public partial class FormPlans : Form, IFormPlans { public FormPlans() { InitializeComponent(); } #region экранирование данных public List<Plan> PlanList { set { planBindingSource.DataSource = value; planBindingSource.ResetBindings(false); } } public Plan SelectedPlan { get { if (planBindingSource.Count > 0) return (Plan)planBindingSource.Current; else return null; } } public string TitleForm { set { this.Text = value; } get { return this.Text; } } #endregion #region проброс событий public event EventHandler ModelingButtonClick; public event EventHandler EditClick; public event EventHandler DeleteClick; public event EventHandler ViewClick; public event EventHandler CalcAnalytClick; public event EventHandler CalcMoveTimeCorrectClick; public event EventHandler CalcMoveTimeClick; public event EventHandler CalcWithoutShiftsClick; private void buttonModeling_Click(object sender, EventArgs e) { if (ModelingButtonClick != null) ModelingButtonClick(this, EventArgs.Empty); } private void изменитьToolStripMenuItem_Click(object sender, EventArgs e) { if (EditClick != null) EditClick(this, EventArgs.Empty); } private void удалитьToolStripMenuItem_Click(object sender, EventArgs e) { DialogResult dr = MessageBox.Show("Вы действительно хотите удалить программу координации?", "Удалить программу координации", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if(DeleteClick != null && dr == System.Windows.Forms.DialogResult.Yes) DeleteClick(this, EventArgs.Empty); } private void toolStripButtonView_Click(object sender, EventArgs e) { if (ViewClick != null) ViewClick(this, EventArgs.Empty); } private void аналитическийToolStripMenuItem_Click(object sender, EventArgs e) { if (CalcAnalytClick != null) CalcAnalytClick(this, EventArgs.Empty); } private void безСдвиговToolStripMenuItem_Click(object sender, EventArgs e) { if (CalcWithoutShiftsClick != null) CalcWithoutShiftsClick(this, EventArgs.Empty); } #endregion #region логика формы private void dataGridViewCoordProgs_CurrentCellChanged(object sender, EventArgs e) { CheckElementsState(); } #endregion private void CheckElementsState() { bool isSelected = (SelectedPlan != null); buttonModeling.Enabled = isSelected; изменитьToolStripMenuItem.Enabled = isSelected; удалитьToolStripMenuItem.Enabled = isSelected; просмотрToolStripMenuItem.Enabled = isSelected; } private void FormPlans_Load(object sender, EventArgs e) { CheckElementsState(); } private void просмотрToolStripMenuItem_Click(object sender, EventArgs e) { if (ViewClick != null) ViewClick(this, EventArgs.Empty); } private void безКоррекцииToolStripMenuItem_Click(object sender, EventArgs e) { if (CalcMoveTimeClick != null) CalcMoveTimeClick(this, EventArgs.Empty); } private void сКоррекциейToolStripMenuItem_Click(object sender, EventArgs e) { if (CalcMoveTimeCorrectClick != null) CalcMoveTimeCorrectClick(this, EventArgs.Empty); } public event EventHandler CalcImitRightWayClick; public event EventHandler CalcImitLeftWayClick; public event EventHandler CalcImitSumClick; private void оптимизацияПрямогоНаправленияToolStripMenuItem_Click(object sender, EventArgs e) { if (CalcImitRightWayClick != null) CalcImitRightWayClick(this, EventArgs.Empty); } private void обратноеНаправлениеToolStripMenuItem_Click(object sender, EventArgs e) { if (CalcImitLeftWayClick != null) CalcImitLeftWayClick(this, EventArgs.Empty); } private void обаНаправленияToolStripMenuItem_Click(object sender, EventArgs e) { if (CalcImitSumClick != null) CalcImitSumClick(this, EventArgs.Empty); } private void dataGridViewCoordProgs_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) { dataGridViewCoordProgs.Rows[e.RowIndex].Height = 36; } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class PatientList : MonoBehaviour { public GameObject listItemPrefab; public InputField newPatientName; public InputField newPatientSurname; public GameObject newPatientPanel; public Button selectBtn; public Button updateBtn; public UpdatePatientPanel updatePanel; private int selectedPatientId = -1; // Use this for initialization void OnEnable() { updateBtn.interactable = false; selectBtn.interactable = false; RefreshPatientList(); } public void RefreshPatientList() { ClearPatientList(); var patients = DataService.Instance.GetPatients(); int i = 0; foreach (var patient in patients) { var patientListItem = (GameObject)Instantiate(listItemPrefab, transform, false); patientListItem.transform.Find("Text").GetComponent<Text>().text = patient.Name + " " + patient.Surname; Patient currentPatient = patient; patientListItem.GetComponent<Button>().onClick.AddListener(() => { selectedPatientId = currentPatient.Id; selectBtn.interactable = true; updateBtn.interactable = true; }); i++; } } void ClearPatientList() { foreach (Transform child in transform) { GameObject.Destroy(child.gameObject); } } public void SelectPatient() { GlobalVariables.SelectedPatientId = selectedPatientId; } public void AddPatient() { if(newPatientName.text != "" && newPatientSurname.text != "") { DataService.Instance.CreatePatient(newPatientName.text, newPatientSurname.text); RefreshPatientList(); newPatientName.text = ""; newPatientSurname.text = ""; newPatientPanel.SetActive(false); } } public void DeletePatient() { DataService.Instance.DeletePatient(selectedPatientId); selectedPatientId = -1; GlobalVariables.SelectedPatientId = -1; RefreshPatientList(); updateBtn.interactable = false; selectBtn.interactable = false; } public void ShowUpdatePanel() { if(selectedPatientId >= 0) { updatePanel.gameObject.SetActive(true); updatePanel.Init(selectedPatientId); } } }
namespace _5.CalculateSequenceWithQueue { using System; using System.Collections.Generic; public class Startup { public static void Main(string[] args) { long number = long.Parse(Console.ReadLine()); Queue<long> queue = new Queue<long>(); queue.Enqueue(number); for (int i = 0; i < 50; i++) { long currentElement = queue.Dequeue(); Console.Write(currentElement + " "); queue.Enqueue(currentElement + 1); queue.Enqueue(currentElement * 2 + 1); queue.Enqueue(currentElement + 2); } } } }
using FluentValidation; namespace Application.Discounts.Commands.UpdateDiscountCommands { public class UpdateDiscountCommandValidator : AbstractValidator<UpdateDiscountCommand> { public UpdateDiscountCommandValidator () { RuleFor (e => e.DiscountDto.IdDiscount) .NotEmpty ().WithMessage ("IdDiscount is required"); } } }
using System; using System.Collections.Generic; using System.Text; using Domain.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Persistence.Configuration { class OrderConfiguration : IEntityTypeConfiguration<Order> { public void Configure (EntityTypeBuilder<Order> builder) { builder.HasKey (e => e.IdOrder); builder.Property (e => e.EmailUser) .HasColumnType ("nvarchar(50)") .HasMaxLength (50); builder.Property (e => e.TanggalOrder) .HasColumnType ("datetime2"); builder.Property (e => e.StatusOrder) .HasColumnType ("SMALLINT") .HasMaxLength (1); builder.Property (e => e.IdOrder) .HasColumnType ("Uniqueidentifier") .ValueGeneratedOnAdd (); builder.Property (e => e.IdCourier) .HasColumnType ("Uniqueidentifier"); builder.HasIndex (e => e.EmailUser); builder.HasIndex (e => e.IdOrder); builder.HasIndex (e => e.StatusOrder); } } }
using System.Xml.Linq; using PlatformRacing3.Common.Block; using PlatformRacing3.Web.Controllers.DataAccess2.Procedures.Exceptions; using PlatformRacing3.Web.Responses; using PlatformRacing3.Web.Responses.Procedures; namespace PlatformRacing3.Web.Controllers.DataAccess2.Procedures; public class GetBlock2Procedure : IProcedure { public async Task<IDataAccessDataResponse> GetResponseAsync(HttpContext httpContext, XDocument xml) { XElement data = xml.Element("Params"); if (data != null) { uint blockId = (uint?)data.Element("p_block_id") ?? throw new DataAccessProcedureMissingData(); BlockData block = await BlockManager.GetBlockAsync(blockId); if (block != null) { return new DataAccessGetBlock2Response(block); } else { return new DataAccessGetBlock2Response(BlockData.GetDeletedBlock(blockId)); } } else { throw new DataAccessProcedureMissingData(); } } }
using Xamarin.Forms; using App1.Renderers; using App1.Droid.Renderers; using Xamarin.Forms.Platform.Android; [assembly: ExportRenderer(typeof(BoxBorderEntry), typeof(BoxBorderEntryRenderer))] namespace App1.Droid.Renderers { public class BoxBorderEntryRenderer : EntryRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) { base.OnElementChanged(e); if (Control != null) { Control.SetBackgroundResource(Resource.Drawable.editextborder); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace Tsu { /// <summary> /// The class with the factory methods for the result /// </summary> public static class Result { /// <summary> /// Creates a successful result /// </summary> /// <typeparam name="TOk"></typeparam> /// <typeparam name="TErr"></typeparam> /// <param name="ok"></param> /// <returns></returns> public static Result<TOk, TErr> Ok<TOk, TErr> ( TOk ok ) => new Result<TOk, TErr> ( true, ok, default! ); /// <summary> /// Creates an unsuccessful result /// </summary> /// <typeparam name="TOk"></typeparam> /// <typeparam name="TErr"></typeparam> /// <param name="error"></param> /// <returns></returns> public static Result<TOk, TErr> Err<TOk, TErr> ( TErr error ) => new Result<TOk, TErr> ( false, default!, error ); } /// <summary> /// A result type /// </summary> /// <typeparam name="TOk"></typeparam> /// <typeparam name="TErr"></typeparam> [DebuggerDisplay ( "{" + nameof ( GetDebuggerDisplay ) + "(),nq}" )] public readonly struct Result<TOk, TErr> : IEquatable<Result<TOk, TErr>> { private readonly TOk _ok; private readonly TErr _err; /// <summary> /// Whether this result is Ok. /// </summary> public Boolean IsOk { get; } /// <summary> /// Whether this result is an Error. /// </summary> // This is implemented as a calculated propery because, otherwise, by calling the default // constructor, or using the default operator, we'd get a Result that both isn't Ok nor Err. public Boolean IsErr => !this.IsOk; /// <summary> /// The result of the operation if it was successful. /// </summary> public Option<TOk> Ok => this.IsOk ? Option.Some ( this._ok ) : Option.None<TOk> ( ); /// <summary> /// The error of the operation if it errored. /// </summary> public Option<TErr> Err => this.IsErr ? Option.Some ( this._err ) : Option.None<TErr> ( ); internal Result ( Boolean isOk, TOk ok, TErr err ) { this.IsOk = isOk; this._ok = ok; this._err = err; } /// <summary> /// Returns <see langword="true" /> if this is an Ok result and the contained value is equal /// to the provided <paramref name="value" />. /// </summary> /// <typeparam name="TOther"></typeparam> /// <param name="value"> /// The value to be compared to the containing value if it's an Ok result. /// </param> /// <returns></returns> public Boolean Contains<TOther> ( TOther value ) where TOther : IEquatable<TOk> => this.IsOk && ( value?.Equals ( this._ok ) is true || ( default ( TOk ) is null && default ( TOther ) is null && value is null && this._ok is null ) ); /// <summary> /// Returns <see langword="true" /> if this is an Err result and the contained Err value is /// equal to the provided <paramref name="value" />. /// </summary> /// <typeparam name="TOther"></typeparam> /// <param name="value"> /// The value to be compared to the containing Err value if it's an Err result. /// </param> /// <returns></returns> public Boolean ContainsErr<TOther> ( TOther value ) where TOther : IEquatable<TErr> => this.IsErr && ( value?.Equals ( this._err ) is true || ( default ( TErr ) is null && default ( TOther ) is null && value is null && this._err is null ) ); /// <summary> /// Maps a <c>Result&lt; <typeparamref name="TOk" />, <typeparamref name="TErr" />&gt;</c> /// to <c>Result&lt; <typeparamref name="TMappedOk" />, <typeparamref name="TErr" />&gt;</c> /// by invoking the provided <paramref name="op" /> on the wrapped Ok value (if any), /// leaving Err untouched. /// </summary> /// <typeparam name="TMappedOk"> /// The type that the contained value (if any) will be mapped to. /// </typeparam> /// <param name="op">The function that maps the result if this Result contains one.</param> /// <returns>A Result with the mapped result if it contains one. Returns Err otherwise.</returns> public Result<TMappedOk, TErr> Map<TMappedOk> ( Func<TOk, TMappedOk> op ) { if ( op is null ) throw new ArgumentNullException ( nameof ( op ) ); return this.IsOk ? Result.Ok<TMappedOk, TErr> ( op ( this._ok ) ) : Result.Err<TMappedOk, TErr> ( this._err ); } /// <summary> /// Maps a <c>Result&lt; <typeparamref name="TOk" />, <typeparamref name="TErr" />&gt;</c> /// to <c><typeparamref name="TMappedOk" /></c> by invoking the provided <paramref name="op" /// /> on the wrapped Ok value or returns the provided <paramref name="fallback" /> value if /// the value contained is an Err. /// </summary> /// <typeparam name="TMappedOk"></typeparam> /// <param name="fallback"></param> /// <param name="op"></param> /// <returns></returns> public TMappedOk MapOr<TMappedOk> ( TMappedOk fallback, Func<TOk, TMappedOk> op ) { if ( op is null ) throw new ArgumentNullException ( nameof ( op ) ); return this.IsOk ? op ( this._ok ) : fallback; } /// <summary> /// Maps a <c>Result&lt; <typeparamref name="TOk" />, <typeparamref name="TErr" />&gt;</c> /// to <c><typeparamref name="TMappedOk" /></c> by invoking the provided <paramref name="op" /// /> on the wrapped Ok value or returns the result of invoking the <paramref /// name="fallbackFunc" /> function if the value contained is an Err. /// </summary> /// <typeparam name="TMappedOk"></typeparam> /// <param name="fallbackFunc"> /// The fallback function to be called if this Result doesn't contain a value. /// </param> /// <param name="op">The function to call with the value contained by this Result (if any).</param> /// <returns></returns> public TMappedOk MapOrElse<TMappedOk> ( Func<TMappedOk> fallbackFunc, Func<TOk, TMappedOk> op ) { if ( fallbackFunc is null ) throw new ArgumentNullException ( nameof ( fallbackFunc ) ); if ( op is null ) throw new ArgumentNullException ( nameof ( op ) ); return this.IsOk ? op ( this._ok ) : fallbackFunc ( ); } /// <summary> /// Maps a <c>Result&lt; <typeparamref name="TOk" />, <typeparamref name="TErr" />&gt;</c> /// into a <c>Result&lt; <typeparamref name="TOk" />, <typeparamref name="TMappedErr" /// />&gt;</c> by applying the provided <paramref name="op" /> on the error (if any). /// </summary> /// <typeparam name="TMappedErr"></typeparam> /// <param name="op"></param> /// <returns></returns> public Result<TOk, TMappedErr> MapErr<TMappedErr> ( Func<TErr, TMappedErr> op ) { if ( op is null ) throw new ArgumentNullException ( nameof ( op ) ); return this.IsErr ? Result.Err<TOk, TMappedErr> ( op ( this._err ) ) : Result.Ok<TOk, TMappedErr> ( this._ok ); } /// <summary> /// Returns <paramref name="res" /> if this result is Ok ( <see cref="IsOk" />). Otherwise /// returns an Err containing the error in this result. /// </summary> /// <typeparam name="TOtherOk"></typeparam> /// <param name="res">The result to be retured if this is an Ok result.</param> /// <returns></returns> public Result<TOtherOk, TErr> And<TOtherOk> ( Result<TOtherOk, TErr> res ) => this.IsOk ? res : Result.Err<TOtherOk, TErr> ( this._err ); /// <summary> /// Returns the result of invoking <paramref name="op" /> with this ok value if this result /// is Ok. Otherwise returns an Err containing th error in this result. /// </summary> /// <typeparam name="TMappedOk"></typeparam> /// <param name="op"> /// The delegate to be invoked with the Ok value of this result if it's an Ok result. /// </param> /// <returns></returns> public Result<TMappedOk, TErr> AndThen<TMappedOk> ( Func<TOk, Result<TMappedOk, TErr>> op ) { if ( op is null ) throw new ArgumentNullException ( nameof ( op ) ); return this.IsOk ? op ( this._ok ) : Result.Err<TMappedOk, TErr> ( this._err ); } /// <summary> /// Returns this result if it's an Ok result. Otherwies returns <paramref name="res" />. /// </summary> /// <typeparam name="TOtherErr"></typeparam> /// <param name="res">The result to be returned if this is an Err result.</param> /// <returns></returns> public Result<TOk, TOtherErr> Or<TOtherErr> ( Result<TOk, TOtherErr> res ) => this.IsErr ? res : Result.Ok<TOk, TOtherErr> ( this._ok ); /// <summary> /// Returns this result if it's an Ok result. Otherwise returns the result of invoking /// <paramref name="op" /> with the Err value of this result if this is an Err result. /// </summary> /// <typeparam name="TMappedErr"></typeparam> /// <param name="op"> /// The function to be invoked with the Err value of this result if it's an Err result. /// </param> /// <returns></returns> public Result<TOk, TMappedErr> OrThen<TMappedErr> ( Func<TErr, Result<TOk, TMappedErr>> op ) { if ( op is null ) throw new ArgumentNullException ( nameof ( op ) ); return this.IsErr ? op ( this._err ) : Result.Ok<TOk, TMappedErr> ( this._ok ); } /// <summary> /// Returns the Ok value of this result if it's an Ok result. Otherwise returns the /// <paramref name="fallback" /> result. /// </summary> /// <param name="fallback">The result to be retured if this is an Err result.</param> /// <returns></returns> public TOk UnwrapOr ( TOk fallback ) => this.IsOk ? this._ok : fallback; /// <summary> /// </summary> /// <param name="fallbackFunc"></param> /// <returns></returns> public TOk UnwrapOrElse ( Func<TOk> fallbackFunc ) { if ( fallbackFunc is null ) throw new ArgumentNullException ( nameof ( fallbackFunc ) ); return this.IsOk ? this._ok : fallbackFunc ( ); } #region IEquatable<T> /// <summary> /// Checks whether this result is equal to another. /// </summary> /// <param name="other"></param> /// <returns></returns> public Boolean Equals ( Result<TOk, TErr> other ) => ( this.IsOk && other.IsOk && EqualityComparer<TOk>.Default.Equals ( this._ok, other._ok ) ) || ( this.IsErr && other.IsErr && EqualityComparer<TErr>.Default.Equals ( this._err, other._err ) ); #endregion IEquatable<T> #region Object #pragma warning disable IDE0079 // Remove unnecessary suppression (Valid for some target frameworks) #pragma warning disable CS8604 // Possible null reference argument. (We ensure null passes only when it's safe) /// <inheritdoc /> public override Boolean Equals ( Object? obj ) => ( obj is Result<TOk, TErr> result && this.Equals ( result ) ) // `default(T) is null` is used here to check if T is a reference type. // `typeof(T).IsClass` cannot be turned into a constant by the JIT: https://sharplab.io/#v2:EYLgHgbALANALiAhgZwLYB8ACAGABJgRgDoAlAVwDs4BLVAUyIGEB7VAB2oBs6AnAZV4A3agGM6yANwBYAFCzMAZnwAmXI1wBvWbh24A2gFk6cABbMAJgEl2nABRHTF6204B5NjWYVkRAIIBzfx5xZGpBOksKTmoKGP8ASgBdbV1FXGBmZk5cAwIAHgAVAD5beM0U3VSAdlxzOgAzRDJOOFsCsupkXApmzmkZSoBfCtwRw2MzKxt7Cacbd09vP0Dg5FDwyOjYigTkgdSlDKyc5UKSsq19yp1MGrgATzY6Znq2+KJLZEZOFEkR4auo0BaSO2QAGgQCKURpdrtUcvkYnBzv0hiMRiDMuCCMpoYDYXD8DUDKckSj/ujgYcsbgwcoofEYSNKrcEXlCNhyYCAZUMdTjnTcYz8cz4ST2QROaVUboAYMgA= || ( this.IsOk && ( obj is TOk || ( default ( TOk ) is null && obj is null ) ) && EqualityComparer<TOk>.Default.Equals ( ( TOk ) obj, this._ok ) ) || ( this.IsErr && ( obj is TErr || ( default ( TErr ) is null && obj is null ) ) && EqualityComparer<TErr>.Default.Equals ( ( TErr ) obj, this._err ) ); #pragma warning restore CS8604 // Possible null reference argument. (We ensure null passes only when it's safe) #pragma warning restore IDE0079 // Remove unnecessary suppression (Valid for some target frameworks) /// <inheritdoc /> public override Int32 GetHashCode ( ) { var hashCode = -1322039524; hashCode = hashCode * -1521134295 + this.IsOk.GetHashCode ( ); if ( this.IsOk ) { #pragma warning disable IDE0079 // Remove unnecessary suppression (required for some target frameworks) #pragma warning disable CS8607 // A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] (GetHashCode supports nulls) hashCode = hashCode * -1521134295 + EqualityComparer<TOk?>.Default.GetHashCode ( this._ok ); #pragma warning restore CS8607 // A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] (GetHashCode supports nulls) #pragma warning restore IDE0079 // Remove unnecessary suppression (required for some target frameworks) } else { #pragma warning disable IDE0079 // Remove unnecessary suppression (required for some target frameworks) #pragma warning disable CS8607 // A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] (GetHashCode supports nulls) hashCode = hashCode * -1521134295 + EqualityComparer<TErr?>.Default.GetHashCode ( this._err ); #pragma warning restore CS8607 // A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] (GetHashCode supports nulls) #pragma warning restore IDE0079 // Remove unnecessary suppression (required for some target frameworks) } return hashCode; } #endregion Object #region Operators /// <summary> /// Checks structural equality between two <see cref="Result{TOk, TErr}" /> s. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static Boolean operator == ( Result<TOk, TErr> left, Result<TOk, TErr> right ) => left.Equals ( right ); /// <summary> /// Checks structural difference between two <see cref="Result{TOk, TErr}" /> s. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static Boolean operator != ( Result<TOk, TErr> left, Result<TOk, TErr> right ) => !( left == right ); /// <summary> /// Converts an <paramref name="ok" /> value to a result. /// </summary> /// <param name="ok"></param> [SuppressMessage ( "Usage", "CA2225:Operator overloads have named alternates", Justification = "Result.Ok<TOk, TErr>(TOk) exists." )] public static explicit operator Result<TOk, TErr> ( TOk ok ) => new Result<TOk, TErr> ( true, ok, default! ); /// <summary> /// Converts an <paramref name="err" /> value to a result. /// </summary> /// <param name="err"></param> [SuppressMessage ( "Usage", "CA2225:Operator overloads have named alternates", Justification = "Result.Err<TOk, TErr>(TErr) exists." )] public static explicit operator Result<TOk, TErr> ( TErr err ) => new Result<TOk, TErr> ( false, default!, err ); #endregion Operators private String GetDebuggerDisplay ( ) => this.IsOk ? $"Ok({this._ok})" : $"Err({this._err})"; } /// <summary> /// Extension methods for <see cref="Result{TOk, TErr}" />. /// </summary> public static class ResultExtensions { /// <summary> /// Transposes a Result of an Option into an Option of a Result. /// </summary> /// <remarks> /// The mapping rules are the same as rust: /// <list type="bullet"> /// <item>Ok(None) → None</item> /// <item>Ok(Some(x)) → Some(Ok(x))</item> /// <item>Err(x) → Some(Err(x))</item> /// </list> /// </remarks> /// <typeparam name="TOk"></typeparam> /// <typeparam name="TErr"></typeparam> /// <param name="self"></param> /// <returns></returns> public static Option<Result<TOk, TErr>> Transpose<TOk, TErr> ( this Result<Option<TOk>, TErr> self ) { return self switch { { IsOk: true, Ok: { Value: var nestedOption } } => nestedOption switch { // Ok(None) -> None { IsNone: true } => Option.None<Result<TOk, TErr>> ( ), // Ok(Some(_)) -> Some(Ok(_)) { IsSome: true, Value: var value } => Option.Some ( Result.Ok<TOk, TErr> ( value ) ), // Branch shouldn't be reached _ => throw new Exception ( "This branch shouldn't be reached." ), }, // Err(_) -> Some(Err(_)) { IsErr: true, Err: { Value: var value } } => Option.Some ( Result.Err<TOk, TErr> ( value ) ), // Branch shouldn't be reached _ => throw new Exception ( "This branch shouldn't be reached." ), }; } } }
using System; using System.Collections.Generic; namespace SheMediaConverterClean.Infra.Data.Models { public partial class VAusleihlagerort { public string Bezeichnung { get; set; } public int Id { get; set; } public string Gang { get; set; } public string Regal { get; set; } public string Ebene { get; set; } public string Fach { get; set; } public int? HausId { get; set; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Threading; using MediatR; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters; using OmniSharp.Extensions.LanguageServer.Protocol.Server; // ReSharper disable once CheckNamespace namespace OmniSharp.Extensions.LanguageServer.Protocol { namespace Models { [Serial] [Method(GeneralNames.Progress, Direction.Bidirectional)] [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol")] [GenerateHandlerMethods] [GenerateRequestMethods(typeof(IGeneralLanguageClient), typeof(ILanguageClient), typeof(IGeneralLanguageServer), typeof(ILanguageServer))] public record ProgressParams : IRequest { public static ProgressParams Create<T>(ProgressToken token, T value, JsonSerializer jsonSerializer) { return new ProgressParams { Token = token, Value = JToken.FromObject(value, jsonSerializer) }; } /// <summary> /// The progress token provided by the client or server. /// </summary> public ProgressToken Token { get; init; } = null!; /// <summary> /// The progress data. /// </summary> public JToken Value { get; init; } = null!; } [JsonConverter(typeof(ProgressTokenConverter))] [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] public record ProgressToken : IEquatable<long>, IEquatable<string> { private long? _long; private string? _string; public ProgressToken(long value) { _long = value; _string = null; } public ProgressToken(string value) { _long = null; _string = value; } public bool IsLong => _long.HasValue; public long Long { get => _long ?? 0; set { String = null; _long = value; } } public bool IsString => _string != null; public string? String { get => _string; set { _string = value; _long = null; } } public static implicit operator ProgressToken(long value) { return new ProgressToken(value); } public static implicit operator ProgressToken(string value) { return new ProgressToken(value); } public ProgressParams Create<T>(T value, JsonSerializer jsonSerializer) { return ProgressParams.Create(this, value, jsonSerializer); } public bool Equals(long other) { return IsLong && Long == other; } public bool Equals(string other) { return IsString && String == other; } private string DebuggerDisplay => IsString ? String! : IsLong ? Long.ToString() : ""; /// <inheritdoc /> public override string ToString() { return DebuggerDisplay; } } } public static partial class ProgressExtensions { public static IRequestProgressObservable<TItem, TResponse> RequestProgress<TResponse, TItem>( this ILanguageProtocolProxy requestRouter, IPartialItemRequest<TResponse, TItem> @params, Func<TItem, TResponse> factory, CancellationToken cancellationToken = default ) { @params.SetPartialResultToken(new ProgressToken(Guid.NewGuid().ToString())); return requestRouter.ProgressManager.MonitorUntil(@params, factory, cancellationToken); } public static IRequestProgressObservable<IEnumerable<TItem>, TResponse> RequestProgress<TResponse, TItem>( this ILanguageProtocolProxy requestRouter, IPartialItemsRequest<TResponse, TItem> @params, Func<IEnumerable<TItem>, TResponse> factory, CancellationToken cancellationToken = default ) where TResponse : IEnumerable<TItem> { @params.SetPartialResultToken(new ProgressToken(Guid.NewGuid().ToString())); return requestRouter.ProgressManager.MonitorUntil(@params, factory, cancellationToken); } private static readonly PropertyInfo PartialResultTokenProperty = typeof(IPartialResultParams).GetProperty(nameof(IPartialResultParams.PartialResultToken))!; internal static ProgressToken SetPartialResultToken(this IPartialResultParams @params, ProgressToken? progressToken = null) { if (@params.PartialResultToken is not null) return @params.PartialResultToken; PartialResultTokenProperty.SetValue(@params, progressToken ?? new ProgressToken(Guid.NewGuid().ToString())); return @params.PartialResultToken!; } } }
using System; using System.Collections.Generic; using System.Text; using Zhouli.DbEntity.Models; namespace Zhouli.BLL.Interface { public interface ISysRaRelatedBLL : IBaseBLL<SysRaRelated> {} }
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Jobs; using System; using System.Collections.Generic; using System.Collections.Specialized; namespace NetFabric.Hyperlinq.Benchmarks { //[SimpleJob(RuntimeMoniker.Net48, baseline: true)] //[SimpleJob(RuntimeMoniker.NetCoreApp21)] //[SimpleJob(RuntimeMoniker.NetCoreApp31)] [SimpleJob(RuntimeMoniker.NetCoreApp50)] [MemoryDiagnoser] public abstract class BenchmarksBase { protected const int seed = 42; protected int[] array; protected ReadOnlyMemory<int> memory; protected IEnumerable<int> linqRange; protected ValueEnumerable.RangeEnumerable hyperlinqRange; protected IEnumerable<int> enumerableReference; protected TestEnumerable.Enumerable enumerableValue; protected IReadOnlyCollection<int> collectionReference; protected TestCollection.Enumerable collectionValue; protected IReadOnlyList<int> listReference; protected TestList.Enumerable listValue; protected IAsyncEnumerable<int> asyncEnumerableReference; protected TestAsyncEnumerable.Enumerable asyncEnumerableValue; [GlobalSetup] public abstract void GlobalSetup(); protected void Initialize(int[] array) { this.array = array; memory = array.AsMemory(); enumerableReference = TestEnumerable.ReferenceType(array); enumerableValue = TestEnumerable.ValueType(array); collectionReference = TestCollection.ReferenceType(array); collectionValue = TestCollection.ValueType(array); listReference = TestList.ReferenceType(array); listValue = TestList.ValueType(array); asyncEnumerableReference = TestAsyncEnumerable.ReferenceType(array); asyncEnumerableValue = TestAsyncEnumerable.ValueType(array); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class GoalBehaviour : MonoBehaviour { private bool cleared; // Start is called before the first frame update void Start() { cleared = false; } // Update is called once per frame void Update() { } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.CompareTag("Player") && GameObject.Find("RicardoNormal_0") == null && !cleared) { StartCoroutine(Outro()); } } public IEnumerator Outro() { cleared = true; GameObject.Find("Main Camera").GetComponent<AudioSource>().Stop(); SoundManager.PlaySound("clear"); float counter = 0; float waitTime = 6.0f; //Now, Wait until the current state is done playing while (counter < (waitTime)) { counter += Time.deltaTime; yield return null; } SceneManager.LoadScene("Credits"); } }
using Everest.Entities; using System.Collections.Generic; using System.Threading.Tasks; namespace Everest.Repository.Interfaces { public interface IAnuncioRepository { Task<List<AnuncioEntity>> ConsultarAnunciosAsync(string idUsuario); Task<AnuncioEntity> ConsultarAsync(int id); Task<AnuncioEntity> ConsultarAnuncioMasAntiguoAsync(); Task<int> CrearAnuncioAsync(AnuncioEntity entity); Task<bool> EditarAnuncioAsync(AnuncioEntity entity); Task<bool> EliminarAnuncioAsync(int id); Task<bool> ActivarAnuncioAsync(int id, bool esActivo); } }
using System; using System.Collections.Generic; using System.IO; using System.Reflection; namespace Hik.Sps { /// <summary> /// This class contains general purpose methods to be used by PlugIn system. /// </summary> internal static class SpsHelper { /// <summary> /// Gets an attribute from a MemberInfo object. /// </summary> /// <typeparam name="T">Type of searched Attribute</typeparam> /// <param name="memberInfo">MemberInfo object</param> /// <returns>Specified Attribute, if found, else null</returns> public static T GetAttribute<T>(MemberInfo memberInfo) where T : class { var attributes = memberInfo.GetCustomAttributes(typeof(T), true); if (attributes.Length <= 0) { return null; } return attributes[0] as T; } /// <summary> /// Searches a directory and all subdirectories and returns a list of assembly files. /// </summary> /// <param name="plugInFolder">Directory to search assemblies</param> /// <returns>List of found assemblies</returns> public static List<string> FindAssemblyFiles(string plugInFolder) { var assemblyFilePaths = new List<string>(); assemblyFilePaths.AddRange(Directory.GetFiles(plugInFolder, "*.exe", SearchOption.AllDirectories)); assemblyFilePaths.AddRange(Directory.GetFiles(plugInFolder, "*.dll", SearchOption.AllDirectories)); return assemblyFilePaths; } /// <summary> /// Gets the current directory of executing assembly. /// </summary> /// <returns>Directory path</returns> public static string GetCurrentDirectory() { try { return (new FileInfo(Assembly.GetExecutingAssembly().Location)).Directory.FullName; } catch (Exception) { return Directory.GetCurrentDirectory(); } } } }
// Copyright 2021 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using NtApiDotNet.Win32.Security.Authentication.Schannel; using NtApiDotNet.Win32.Security.Native; using System; using System.Runtime.InteropServices; namespace NtApiDotNet.Win32.Security.Authentication.CredSSP { /// <summary> /// Credentials for the CredSSP package. /// </summary> /// <remarks>This is only needed if you must have both schannel and user credentials. Otherwise use UserCredentials or SchannelCredentials.</remarks> public sealed class CredSSPCredentials : AuthenticationCredentials { private readonly SchannelCredentials _schannel; private readonly UserCredentials _user; /// <summary> /// Constructor. /// </summary> /// <param name="schannel">The credentials for the Schannel connection.</param> /// <param name="user">The credentials for the user.</param> public CredSSPCredentials(SchannelCredentials schannel, UserCredentials user) { _schannel = schannel ?? throw new ArgumentNullException(nameof(schannel)); _user = user ?? throw new ArgumentNullException(nameof(user)); } /// <summary> /// Constructor. /// </summary> /// <param name="credentials">The credentials for the user.</param> public CredSSPCredentials(UserCredentials credentials) { _user = credentials ?? throw new ArgumentNullException(nameof(credentials)); } internal override SafeBuffer ToBuffer(DisposableList list, string package) { if (!AuthenticationPackage.CheckCredSSP(package)) { throw new ArgumentException("Can only use CredSSPCredentials for the CredSSP package.", nameof(package)); } CREDSSP_CRED ret = new CREDSSP_CRED { Type = CREDSSP_SUBMIT_TYPE.CredsspSubmitBufferBoth, pSchannelCred = list.AddResource(_schannel.ToBuffer(list, package)).DangerousGetHandle(), pSpnegoCred = list.AddResource(_user.ToBuffer(list, package)).DangerousGetHandle() }; return ret.ToBuffer(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace лаба_13 { class AESLog { public static void Writer(string MethodName, string path = "none", string nameFile = "none") { using (StreamWriter write = new StreamWriter("AESLog.txt", true)) { write.WriteLine($"Method: {MethodName} Path: {path.Replace(" ", "_")} File: {nameFile.Replace(" ", "_")} Called: {DateTime.Now}"); write.Close(); } } public static string SearchMethod(string method) { string line = "none", line2 = ""; using (StreamReader reader = new StreamReader("AESLog.txt")) { while ((line = reader.ReadLine()) != null) { string[] splitLine = line.Split(' '); if (splitLine[1] == method) { line2 += line + "\n"; } } reader.Close(); if (line2 == "") line2 = "none"; return line2; } } public static string SearchDate(string time) { string line = "none", line2 = ""; using (StreamReader reader = new StreamReader("AESLog.txt")) { while ((line = reader.ReadLine()) != null) { string[] splitLine = line.Split(' '); try { if (splitLine[7] + " " + splitLine[8] == time || splitLine[7] == time) { line2 += line + "\n"; } } catch(Exception e) { Console.WriteLine("Ошибка:" + e.Message); } } reader.Close(); if (line2 == "") line2 = "none\n"; return line2 + "\n"; } } public static string SearchTime(string timefirst, string timelast) { string line = "none"; string line2 = ""; using (StreamReader reader = new StreamReader("AESLog.txt")) { while ((line = reader.ReadLine()) != null) { string[] splitLine = line.Split(' '); try { splitLine[7].Remove(0, 3); if (((Convert.ToDateTime(splitLine[7] + " " + splitLine[8]) >= Convert.ToDateTime(timefirst)) && (Convert.ToDateTime(splitLine[7] + " " + splitLine[8]) <= Convert.ToDateTime(timelast))) || ((Convert.ToDateTime(splitLine[7]) <= Convert.ToDateTime(timefirst)) && (Convert.ToDateTime(splitLine[7]) >= Convert.ToDateTime(timelast)))) { line2 += line + "\n"; } } catch (Exception e) { Console.WriteLine("Ошибка:" + e.Message); } } reader.Close(); if (line2 == "") line2 = "none"; return line2; } } } }
using System; using System.Collections.Generic; using System.Text; namespace OCP { /** * Interface ICertificate * * @package OCP * @since 8.0.0 */ public interface ICertificate { /** * @return string * @since 8.0.0 */ string getName(); /** * @return string * @since 8.0.0 */ string getCommonName(); /** * @return string * @since 8.0.0 */ string getOrganization(); /** * @return \DateTime * @since 8.0.0 */ string getIssueDate(); /** * @return \DateTime * @since 8.0.0 */ string getExpireDate(); /** * @return bool * @since 8.0.0 */ string isExpired(); /** * @return string * @since 8.0.0 */ string getIssuerName(); /** * @return string * @since 8.0.0 */ string getIssuerOrganization(); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; namespace Voronov.Nsudotnet.BuildingCompanyIS.Entities { [Table("bcis.ResourceResults")] public partial class ResourceResult : IEntity { public int Id { get { return ResourcePlanId; } set { ResourcePlanId = value; } } [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int ResourcePlanId { get; set; } [Required] public int ResourceId { get; set; } [Required] public int BuildPlanId { get; set; } public int ResourceCount { get; set; } public virtual ResourcePlan ResourcePlan { get; set; } public virtual Resource Resource { get; set; } public virtual BuildPlan BuildPlan { get; set; } } }
using Dapper; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Dynamic; using System.Linq; using System.Text; using MobileWx.Dal.Model; using Sys.Utility; namespace MobileWx.Dal { public class DalWx : DalBase { public string GetAccessToken() { var p = new DynamicParameters(); p.Add("@config_name", "Access_Token", dbType: DbType.AnsiString, size: 100); using (var connection = new SqlConnection(SqlConnectString)) { dynamic d = connection.Query("sp_weixin_config_get", p, commandType: CommandType.StoredProcedure) .FirstOrDefault(); if (d != null) { return d.config_value; } } return null; } /// <summary> /// 获取用户等级及金币 /// </summary> /// <returns></returns> public DBCommoninfo platform_user_get_commoninfo_byweixin(string openId) { try { using (var connection = new SqlConnection(conn_platform218_db)) { var p = new DynamicParameters(); p.Add("@weixin", openId, dbType: DbType.String); p.Add("@rtnMsg", size: 50, dbType: DbType.String, direction: ParameterDirection.Output); p.Add("@returnVal", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue); var result = connection.Query<DBCommoninfo>("platform_user_get_commoninfo_byweixin", p, commandType: CommandType.StoredProcedure).ToList(); DBCommoninfo info = new DBCommoninfo(); if (result.Count > 0) { info.point = result[0].point; info.userexp = result[0].userexp; info.userlevel = result[0].userlevel; info.account = result[0].account; info.zxg_cur_pid = result[0].zxg_cur_pid; info.zxg_customsID = result[0].zxg_customsID; info.zxg_last_pid = result[0].zxg_last_pid; } return info; } } catch (Exception ex) { Loger.Error(ex); return new DBCommoninfo(); } } /// <summary> /// 获取用户兑换记录 /// </summary> /// <param name="openId"></param> /// <param name="searchtype"></param> /// <returns></returns> public List<DalUserExchangeLog> platform_user_get_exchange_byweixin(string openId) { using (var connection = new SqlConnection(conn_platform218_db)) { var p = new DynamicParameters(); p.Add("@weixin", openId, dbType: DbType.String); p.Add("@rtnMsg", size: 50, dbType: DbType.String, direction: ParameterDirection.Output); p.Add("@returnVal", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue); var result = connection.Query<DalUserExchangeLog>("platform_user_get_exchange_byweixin", p, commandType: CommandType.StoredProcedure).ToList(); return result; } } /// <summary> /// 绑定微信号 /// </summary> /// <param name="userName"></param> /// <param name="pwd"></param> /// <param name="weixin">微信号</param> /// <param name="isbind">0是解绑,1是绑定</param> /// <returns></returns> public int sp_platform_user_bind_weixin(string userName, string pwd, string weixin, bool isbind) { using (var connection = new SqlConnection(conn_platform218_db)) { var p = new DynamicParameters(); p.Add("@username", userName); p.Add("@cpPasswd", pwd); p.Add("@weixin", weixin); p.Add("@isbind", isbind); p.Add("@rtnMsg", size: 1024, dbType: DbType.String, direction: ParameterDirection.Output); p.Add("@rtnVal", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue); connection.Execute("sp_platform_user_bind_weixin", p, commandType: CommandType.StoredProcedure); var b = p.Get<string>("@rtnMsg"); int c = p.Get<int>("@rtnVal"); return c; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace ProjectMFS { public partial class ParticipantActivityView : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string WIN = Request.QueryString["WIN"]; //PLACEHOLDER WIN = "bla"; //PLACEHOLDER if (((SiteMaster)this.Master).IsLoggedIn) { this.LoginPanel.Visible = false; if (!String.IsNullOrEmpty(WIN)) //Load Existing Participant { this.MainDataPanel.Visible = true; } } } protected void AddActivity_Click(object sender, EventArgs e) { //AddActivity logic; } protected void ActivitiesGridViewButton_Click(object source, GridViewCommandEventArgs e) { //LogicHere } } }
using CommonFrameWork; using Dominio; using System.Collections.Generic; namespace BLL { public class BLLPrefeitura { public IEnumerable<Prefeitura> Listar() { using (var dao = new DAL.DbPrefeitura()) { return dao.Listar(); } } public Prefeitura Selecionar(decimal sqPrefeitura) { using (var dao = new DAL.DbPrefeitura()) { return dao.Selecionar(sqPrefeitura); } } public void Incluir(Prefeitura prefeitura) { using (var dao = new DAL.DbPrefeitura()) { Validador.Validar(prefeitura.CD_MUNICIPIO > 0, "Informe o município."); Validador.Validar(!string.IsNullOrWhiteSpace(prefeitura.NM_PREFEITURA), "Informe o nome da prefeitura"); Validador.Validar(!string.IsNullOrWhiteSpace(prefeitura.NM_PREFEITO), "Informe o nome do prefeito."); Validador.Validar(!string.IsNullOrWhiteSpace(prefeitura.NM_CONTADOR), "Informe o nome do contador."); Validador.Validar(!string.IsNullOrWhiteSpace(prefeitura.NM_LOGRADOURO), "Informe o logradouro."); Validador.Validar(!string.IsNullOrWhiteSpace(prefeitura.NU_NUMERO), "Informe o número."); Validador.Validar(!string.IsNullOrWhiteSpace(prefeitura.TX_COMPLEMENTO), "Informe o complemento."); Validador.Validar(!string.IsNullOrWhiteSpace(prefeitura.TX_CONTATO), "Informe o contato."); dao.Incluir(prefeitura); } } public void Atualizar(Prefeitura prefeitura) { using (var dao = new DAL.DbPrefeitura()) { Validador.Validar(prefeitura.SQ_PREFEITURA > 0, "Selecione a prefeitura"); Validador.Validar(prefeitura.CD_MUNICIPIO > 0, "Informe o município."); Validador.Validar(!string.IsNullOrWhiteSpace(prefeitura.NM_PREFEITURA), "Informe o nome da prefeitura"); Validador.Validar(!string.IsNullOrWhiteSpace(prefeitura.NM_PREFEITO), "Informe o nome do prefeito."); Validador.Validar(!string.IsNullOrWhiteSpace(prefeitura.NM_CONTADOR), "Informe o nome do contador."); Validador.Validar(!string.IsNullOrWhiteSpace(prefeitura.NM_LOGRADOURO), "Informe o logradouro."); Validador.Validar(!string.IsNullOrWhiteSpace(prefeitura.NU_NUMERO), "Informe o número."); Validador.Validar(!string.IsNullOrWhiteSpace(prefeitura.TX_COMPLEMENTO), "Informe o complemento."); Validador.Validar(!string.IsNullOrWhiteSpace(prefeitura.TX_CONTATO), "Informe o contato."); dao.Atualizar(prefeitura); } } public void Excluir(decimal SQ_PREFEITURA) { using (var dao = new DAL.DbPrefeitura()) { Validador.Validar(SQ_PREFEITURA > 0, "Informe a prefeitura."); dao.Excluir(SQ_PREFEITURA); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Door : MonoBehaviour { public int enemyNum; public Vector2 direction; public float distance; public float playerDistance; private GameObject player; private bool inDoor; public Sprite open; public Sprite closed; public int nextRoomNum; public GameObject enemies; // Use this for initialization void Start () { inDoor = false; player = GameObject.Find ("Player"); } // Update is called once per frame void Update () { if (inDoor == true) { Camera.main.transform.position = new Vector3 ( Camera.main.transform.position.x + direction.x * distance, Camera.main.transform.position.y + direction.y * distance, Camera.main.transform.position.z); player.transform.position = new Vector3 ( player.transform.position.x + direction.x * playerDistance, player.transform.position.y + direction.y * playerDistance, player.transform.position.z); player.GetComponent<Movement> ().changeRoomNum (nextRoomNum); enemies.SetActive (true); inDoor = false; } if (enemyNum <= 0) { this.gameObject.GetComponent<SpriteRenderer> ().sprite = open; } else { this.gameObject.GetComponent<SpriteRenderer> ().sprite = closed; } } public void doorDeath(){ enemyNum--; } void OnTriggerStay2D(Collider2D other){ if (enemyNum <= 0 && other.gameObject.tag.Equals("Player")) { inDoor = true; } } }
using System.Collections.Generic; namespace PaderbornUniversity.SILab.Hip.EventSourcing.Tests { public class Foo : IEntity<int> { public int Id { get; set; } public string Name { get; set; } public int Parent { get; set; } public List<int> Bars { get; set; } public TestEnum EnumValue { get; set; } public override bool Equals(object obj) { var foo = obj as Foo; return foo != null && Id == foo.Id && Name == foo.Name && Parent == foo.Parent && EqualityComparer<List<int>>.Default.Equals(Bars, foo.Bars); } public override int GetHashCode() { var hashCode = 1778032246; hashCode = hashCode * -1521134295 + Id.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Name); hashCode = hashCode * -1521134295 + Parent.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<List<int>>.Default.GetHashCode(Bars); return hashCode; } } public enum TestEnum { Enum1, Enum2 } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations.Schema; namespace ServiceHost.ModelsDTO { [NotMapped] public class GlobalFeeDTO { public Guid Id { get; set; } public decimal FeePercentace { get; set; } public DateTime ValidFrom { get; set; } public DateTime? ValidTo { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RopeController : MonoBehaviour { //objects that will interact with the rope public Transform whatTheRopeIsConnectedTo; public Transform whatIsHangingFromTheRope; //line render to display the rope private LineRenderer lineRenderer; //A list with all rope sections public List<Vector3> allRopeSections = new List<Vector3>(); //Rope data public float ropeLength; public float minRopeLength; public float maxRopeLength; //How fast we add more/less rope public float winchSpeed; public float scalar; //joint used to approximate the rope SpringJoint2D springJoint2D; // Start is called before the first frame update void Start() { springJoint2D = whatTheRopeIsConnectedTo.GetComponent<SpringJoint2D>(); //Init the line renderer we use to display the rope lineRenderer = GetComponent<LineRenderer>(); //Init the spring we use to approximate the rope from point a to b UpdateSpring(); } // Update is called once per frame void Update() { //Add more/less rope UpdateWinch(); //Display the rope with a line renderer DisplayRope(); } //Update the spring constant and the length of the spring private void UpdateSpring() { springJoint2D.distance = ropeLength; } //Display the rope with a line render private void DisplayRope() { //this is not actual width, but width use so we can see the ropw float ropeWidth = 0.2f; lineRenderer.startWidth = ropeWidth; lineRenderer.endWidth = ropeWidth; //update the list with rope secctions by approximating the rope with bezier curve //a bezier curve needs 4 control points Vector3 A = whatTheRopeIsConnectedTo.position; Vector3 D = whatIsHangingFromTheRope.position; //upper control point //to get a little curve at the top than at the bottom Vector3 B = A + whatTheRopeIsConnectedTo.up * (-(A - D).magnitude * 0.1f); //B=A //Lower control point Vector3 C = D + whatIsHangingFromTheRope.up * ((A - D).magnitude * 0.5f); //get the positions BezierCurve.GetBezierCurve(A, B, C, D, allRopeSections); //an array wit all rope section positions Vector3[] positions = new Vector3[allRopeSections.Count]; for (int i = 0; i < allRopeSections.Count; i++) { positions[i] = allRopeSections[i]; } //just add a line between the start ad end position for testing purposes //Vector3[] positions = new Vector3[2]; //position[0] = whatTheRopeIsConnectedTo.position; //postions[1] = whatIsHangingFromTheRope.position; //add the positions to the line renderer lineRenderer.positionCount = positions.Length; lineRenderer.SetPositions(positions); } //add more/less rope private void UpdateWinch() { bool hasChangedRope = false; //more rope if ((Input.GetKey(KeyCode.JoystickButton2) || Input.GetKey(KeyCode.H)) && ropeLength < maxRopeLength) { ropeLength += winchSpeed * Time.deltaTime; hasChangedRope = true; } else if ((Input.GetKey(KeyCode.JoystickButton1) || Input.GetKey(KeyCode.F)) && ropeLength > minRopeLength) { ropeLength -= scalar * winchSpeed * Time.deltaTime; hasChangedRope = true; } if (hasChangedRope) { ropeLength = Mathf.Clamp(ropeLength, minRopeLength, maxRopeLength); //need to recalculate the k-value because it depends on the length of the rope UpdateSpring(); } } public static class BezierCurve { public static void GetBezierCurve(Vector3 A, Vector3 B, Vector3 C, Vector3 D, List<Vector3> allRopeSections) { //resolution of the line //make sure resolution is adding up to 1, so 0.3 will give a gap at the end, but 0.2 will work float resolution = 0.1f; //clear the list allRopeSections.Clear(); float t = 0; while(t<= 1f) { //find the coordinates between the control points with a bezier curve Vector3 newPos = DeCasteljausAlgorithm(A, B, C, D, t); allRopeSections.Add(newPos); //which t position are we at? t += resolution; } allRopeSections.Add(D); } //the de casteljau's algorithm static Vector3 DeCasteljausAlgorithm(Vector3 A, Vector3 B, Vector3 C, Vector3 D, float t) { //linear interpolation = lerp = (1 - t) * A + t * B //could use Vector3.Lep(A, B, t) //to make it faster float oneMinusT = 1f - t; //layer 1 Vector3 Q = oneMinusT * A + t * B; Vector3 R = oneMinusT * B + t * C; Vector3 S = oneMinusT * C + t * D; //layer 2 Vector3 P = oneMinusT * Q + t * R; Vector3 T = oneMinusT * R + t * S; //final interpolated position Vector3 U = oneMinusT * P + t * T; return U; } } }
using UnityEngine; using System.Collections; public class GameMaster : MonoBehaviour { public GameObject PlayerCharacter; public Camera MainCamera; public GameObject GameSettings; public float zOffSet; public float yOffSet; public float xRotOffSet; private GameObject pc; private PlayerCharacter pcScript; // Use this for initialization void Start () { pc = Instantiate(PlayerCharacter, Vector3.zero, Quaternion.identity) as GameObject; pc.name = "pc"; pcScript = pc.GetComponent<PlayerCharacter>(); zOffSet = -2.5f; yOffSet = 2.5f; xRotOffSet = 22.5f; MainCamera.transform.position = new Vector3(pc.transform.position.x, pc.transform.position.y+yOffSet, pc.transform.position.z+zOffSet); MainCamera.transform.Rotate(xRotOffSet, 0, 0); LoadCharacter(); } public void LoadCharacter(){ GameObject gs = GameObject.Find("GameSettings"); if(gs == null){ Instantiate(GameSettings, Vector3.zero, Quaternion.identity); gs.name = "gameSettings"; } gameSettings gsScript = gs.GetComponent<gameSettings>(); gsScript.LoadCharacterData(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArraysandStrings { public class PalindromePermutation { public void CheckPermutationOfAPalindrome(string str) { Console.WriteLine("===========Check permutation of a palindrome============"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Switch : MonoBehaviour { // Start is called before the first frame update public GameObject off; public GameObject on; public GameObject chest; public GameObject door; public bool ison = false; void Start() { } // Update is called once per frame void Update() { if (ison) { door.transform.position = new Vector3(door.transform.position.x, Mathf.Lerp(door.transform.position.y, -2.45f, 0.5f), door.transform.position.z); } } private void OnTriggerEnter2D(Collider2D other) { if (other.tag == "summon1") { off.SetActive(false); on.SetActive(true); if (!ison) { ison = true; chest.SetActive(true); } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="LogEntryMap.cs" company="CGI"> // Copyright (c) CGI. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using CGI.Reflex.Core.Entities; namespace CGI.Reflex.Core.Mappings { public class LogEntryMap : BaseEntityMap<LogEntry> { public LogEntryMap() { Map(x => x.Date); Map(x => x.Thread); Map(x => x.Level); Map(x => x.Logger); Map(x => x.CorrelationId); Map(x => x.LoggedUser); Map(x => x.Context); Map(x => x.Message); Map(x => x.Exception); } } }
using System; using System.Collections.ObjectModel; using System.IO; using System.Windows; using System.Text.RegularExpressions; namespace EasyVideoEdition.Model { /// <summary> /// Every subtitles of a video in srt format /// </summary> class Subtitles : ObjectBase { #region Attributes private ObservableCollection<Subtitle> _subtitlesCollection; private String _srtPath; private static readonly Regex TIME_FORMAT = new Regex(@"^\d{2}:\d{2}:\d{2},\d{3}$"); //Format of a time (hh:mm:ss,msmsms) #endregion #region Get/Set /// <summary> /// Path of the srt file /// </summary> public String srtPath { get { return _srtPath; } set { _srtPath = value; RaisePropertyChanged("srtPath"); } } /// <summary> /// List of Subtitles of a video /// </summary> public ObservableCollection<Subtitle> subtitlesCollection { get { return _subtitlesCollection; } set { _subtitlesCollection = value; RaisePropertyChanged("subtitlesCollection"); } } #endregion /// <summary> /// Creates the subtitles of the video /// </summary> /// <param name="srtPath">Path of the video</param> public Subtitles(String srtPath) { this.srtPath = CreateSrtFileName(srtPath); subtitlesCollection = new ObservableCollection<Subtitle>(); } /// <summary> /// Create the file name with the path /// </summary> /// <param name="originalPath">Path of the video file</param> /// <returns>Path of the srt file</returns> public String CreateSrtFileName(String originalPath) { String filePath; int endIndex = originalPath.Length - 1; /* Remove the extension of the pah searching the '.' at the end */ while (originalPath[endIndex] != '.') { endIndex--; } filePath = originalPath.Remove(endIndex + 1); //Remove chars from the '.' to the end filePath = filePath + "srt"; //Write srt after the '.' in the file path return filePath; } /// <summary> /// Add a subtitle to the video /// </summary> /// <param name="startTime">Time when the subtitle will start</param> /// <param name="endTime">Time when the subtitle will end</param> /// <param name="text">Text that the subtitle will contain</param> public void AddSubtitle(String startTime, String endTime, String text) { /* Check if the format of the strings are good */ if (TIME_FORMAT.IsMatch(startTime) && TIME_FORMAT.IsMatch(endTime)) { Subtitle sub = new Subtitle(startTime, endTime, text); subtitlesCollection.Add(sub); } else { MessageBox.Show("Syntaxe des temps incorrecte"); } } /// <summary> /// Edit a subtitle of the video /// </summary> /// <param name="index">Index of the subtitle in the list</param> /// <param name="startTime">Time when the subtitle will start</param> /// <param name="endTime">Time when the subtitle will end</param> /// <param name="text">Text that the subtitle will contain</param> public void EditSubtitle(int index, String startTime, String endTime, String text) { if (subtitlesCollection.Count > index) { subtitlesCollection[index].EditSubtile(startTime, endTime, text); } } /// <summary> /// Delete a subtitle /// </summary> /// <param name="index">Index of the subtitle in the list</param> public void DeleteSubtitle(int index) { if (subtitlesCollection.Count > index) { subtitlesCollection.RemoveAt(index); } } /// <summary> /// Create the srt file corresponding to the video /// </summary> public void CreateSrtFile() { int i = 0; int indexSubtitle = 1; String[] subtitleFormat = new String[subtitlesCollection.Count * 3]; /* Write all subtitles in the format of srt file */ foreach (Subtitle sub in subtitlesCollection) { subtitleFormat[i + 0] = indexSubtitle.ToString(); //Write the index (number) of the subtitle subtitleFormat[i + 1] = sub.startTime + " --> " + sub.endTime; //Write the both start and end time with the good syntaxe subtitleFormat[i + 2] = sub.subtitleText + "\n"; //Write the content of the subtitle i += 3; indexSubtitle++; } File.WriteAllLines(srtPath, subtitleFormat); } /// <summary> /// Read a srt file and put all subtitles in the collection of subtitles /// </summary> public void ReadSrtFile() { String line; String textRead; String[] times = new String[2]; //Both start time and end time for each subtitles Subtitle sub; int index = 1; int ret = 0; subtitlesCollection.Clear(); //Clear the collection of subtitles if (!File.Exists(this.srtPath)) File.Create(this.srtPath).Close(); StreamReader file = new StreamReader(this.srtPath); while ((line = file.ReadLine()) != null) { if (int.TryParse(line, out ret)) { sub = new Subtitle(); times = new String[2]; /* Read both start and end times */ if ((line = file.ReadLine()) != null) { times = Regex.Split(line, " --> "); //Split the line containing the times } /* Read the text of the subtitle and add the subtitle to the collection of subtitles*/ if ((line = file.ReadLine()) != null) { textRead = line; sub.EditSubtile(times[0], times[1], textRead); subtitlesCollection.Add(sub); index++; } } } } /// <summary> /// Print all subtitles in MessageBox /// </summary> public void PrintAllSubtitles() { MessageBox.Show("---------------------------"); foreach (Subtitle sub in subtitlesCollection) { MessageBox.Show(sub.startTime + sub.endTime + sub.subtitleText); } } } }
using Lfs.Web.Api.App_Start; using AutoMapper; using Ninject.Modules; namespace Lfs.Web.Api.NinjectModules { public class AutoMapperModule : NinjectModule { public override void Load() { var mapperConfig = new AutoMapperConfig().Create(); Bind<MapperConfiguration>().ToConstant(mapperConfig).InSingletonScope(); Bind<IMapper>().ToMethod(x => new Mapper(mapperConfig)); } } }
using System; using MonoMac.AppKit; using MonoMac.Foundation; using Radish.Models; namespace Radish { [MonoMac.Foundation.Register("FileInformationController")] public partial class FileInformationController : NSViewController { private MediaMetadata MediaMetadata; public FileInformationController(IntPtr handle) : base(handle) { Initialize(); } [Export ("initWithCoder:")] public FileInformationController(NSCoder coder) : base(coder) { Initialize(); } void Initialize() { } public override void AwakeFromNib() { base.AwakeFromNib(); tableView.BackgroundColor = NSColor.Clear; } public void SetFile(MediaMetadata mediaMetadata) { MediaMetadata = mediaMetadata; tableView.ReloadData(); for (var column = 0; column < tableView.TableColumns().Length; ++column) { var biggestWidth = 0f; for (int row = 0; row < tableView.RowCount; ++row) { var cellWidth = tableView.GetCell(column, row).CellSize.Width; biggestWidth = Math.Max(biggestWidth, cellWidth); } var c = tableView.TableColumns()[column]; c.Width = c.MaxWidth = biggestWidth; } } [Export("numberOfRowsInTableView:")] public int NumberOfRowsInTableView(NSTableView tv) { if (MediaMetadata == null) { return 0; } return MediaMetadata.Metadata.Count; } [Export("tableView:objectValueForTableColumn:row:")] public string ObjectValueForTableColumn(NSTableView table, NSTableColumn column, int rowIndex) { var info = MediaMetadata.Metadata[rowIndex]; switch (column.DataCell.Tag) { case 1: return info.Category; case 2: return info.Name; case 3: return info.Value; } return "<Unknown>"; } [Export("tableView:isGroupRow:")] public bool IsGroupRow(NSTableView table, int row) { return MediaMetadata.Metadata[row].Category != null; } [Export("tableView:willDisplayCell:forTableColumn:row:")] public void WillDisplayCell(NSTableView table, NSObject cell, NSTableColumn column, int row) { var textCell = cell as NSTextFieldCell; if (textCell != null) { textCell.TextColor = NSColor.White; textCell.DrawsBackground = false; textCell.StringValue = textCell.StringValue; } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace Zelo.Management.Models { public class BaseLoginUserInfo { /// <summary> /// token /// </summary> public String token { get; set; } /// <summary> /// 用户ID /// </summary> public String user_id { get; set; } } public abstract class AbstractUserInfo:BaseLoginUserInfo { /// <summary> /// 姓名 /// </summary> public String name { get; set; } public String avatar { get; set; } } /// <summary> /// 用户手机注册模板 /// </summary> public class UserPhoneSignUp { public String phone { get; set; } public String password { get; set; } [Required(ErrorMessage="请填写验证码")] public String validcode { get; set; } } /// <summary> /// 用户手机登录模板 /// </summary> public class UserPhoneLogin { public String phone { get; set; } public String password { get; set; } } public class UserUpdatePassword:BaseParams{ [Required(AllowEmptyStrings = false, ErrorMessage = "password为空")] [StringLength(60,MinimumLength=6)] public String password { get; set; } } public class UpdateAvatarParams : BaseParams { [Required(ErrorMessage = "缺少image_data参数")] public String image_data { get; set; } } public class QueryDoctorInfoByMIDParams : BaseParams { [Required(AllowEmptyStrings = false, ErrorMessage = "doctor_id为空")] public String doctor_id { get; set; } } }
using UnityEngine; public enum TypeOwner { Character } public interface IOwner { TypeOwner GetTypeOwner { get; } bool CheckIgnoreObject(Transform obj); GameObject GameObj { get; } IAnchor Anchor { get; } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace FuelLevelSystem.View { /// <summary> /// Interaction logic for StationStatWindow.xaml /// </summary> public partial class StationStatWindow : Window { public StationStatWindow() { InitializeComponent(); } private DataRowView rowBeingEdited = null; private void statDataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) { DataRowView rowView = e.Row.Item as DataRowView; rowBeingEdited = rowView; } private void statDataGrid_CurrentCellChanged(object sender, EventArgs e) { if (rowBeingEdited != null) { rowBeingEdited.EndEdit(); } } } }
using GameLib; using JumpAndRun.API; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace JumpAndRun.Actors { public class MultiplayerPlayer : Actor { public override string Name => "JumpAndRun.MultiplayerRepresentation"; private IndexBuffer _indexBuffer; private VertexBuffer _vertexBuffer; private Texture2D _texture; private Matrix _world; private Vector3 _interpolatePosition; private Platform _platform; public override void Draw(Effect effect, Matrix view, Matrix proj) { if (!Alive) return; Game.GraphicsDevice.SetVertexBuffer(_vertexBuffer); Game.GraphicsDevice.Indices = _indexBuffer; Game.GraphicsDevice.RasterizerState = RasterizerState.CullNone; switch (_platform) { case Platform.WindowsForms: effect.Parameters["DiffuseTexture"].SetValue(_texture); effect.Parameters["World"].SetValue(_world); effect.Parameters["WorldViewProj"].SetValue(_world * view * proj); break; case Platform.Android: ((BasicEffect)effect).Texture = _texture; ((BasicEffect)effect).View = view; ((BasicEffect)effect).Projection = proj; ((BasicEffect)effect).World = _world; break; } foreach (var pass in effect.CurrentTechnique.Passes) { pass.Apply(); Game.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _indexBuffer.IndexCount / 3); } } private void GenerateVertexBuffer(GraphicsDevice graphicsDevice) { _texture = ContentManager.Instance.Textures["Player"]; var vertices = new VertexPositionNormalTexture[4]; vertices[0] = new VertexPositionNormalTexture(new Vector3(0, 0, -0.5f), Vector3.Forward, new Vector2(0, 1)); vertices[1] = new VertexPositionNormalTexture(new Vector3(0, Player.Size.Y, -0.5f), Vector3.Forward, new Vector2(0, 0)); vertices[2] = new VertexPositionNormalTexture(new Vector3(Player.Size.X, Player.Size.Y, -0.5f), Vector3.Forward, new Vector2(1, 0)); vertices[3] = new VertexPositionNormalTexture(new Vector3(Player.Size.X, 0, -0.5f), Vector3.Forward, new Vector2(1, 1)); var indices = new short[] { 0, 1, 3, 3, 1, 2 }; _indexBuffer = new IndexBuffer(graphicsDevice, IndexElementSize.SixteenBits, 6, BufferUsage.WriteOnly); _vertexBuffer = new VertexBuffer(graphicsDevice, VertexPositionNormalTexture.VertexDeclaration, 4, BufferUsage.WriteOnly); _vertexBuffer.SetData(vertices); _indexBuffer.SetData(indices); } public override void Init(Actor player, IGlobalCache cache, Game game, CameraBase camera) { Game = game; Camera = camera; GenerateVertexBuffer(game.GraphicsDevice); Initialized = true; _interpolatePosition = Position; _platform = GameContext.Instance.Platform; } public override void Update(JumpAndRunTime gameTime) { _interpolatePosition += (Position - _interpolatePosition) / 3; _world = Matrix.CreateWorld(_interpolatePosition, Vector3.Forward, Vector3.Up); BoundingBox = new BoundingBox(_interpolatePosition, _interpolatePosition + new Vector3(1, 1, 0)); } protected override void OnDead() { } public override void Dispose() { _vertexBuffer.Dispose(); _indexBuffer.Dispose(); } } }
using Zhouli.DbEntity.Models; using System; using System.Collections.Generic; using System.Text; using System.Linq.Expressions; namespace Zhouli.DAL.Interface { public interface ISysUserDAL : IBaseDAL<SysUser> { /// <summary> /// 获取需要登录的用户所有信息 /// </summary> /// <returns></returns> SysUser SetLoginSysUser(SysUser user); } }
namespace Diyseed.Core { public enum EncodingType { Number = 10, // 10 characters (0..9) Alphabet = 26, // 10 characters (a..z) } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Evpro.Domain.Entities; namespace Evpro.Gui.Models { public class CostumeModel { public List<EventModel> Ev { get; set; } public EventModel A { get; set; } public EventModel B { get; set; } public List<reward> Re { get; set; } public List<eventowner> Eo { get; set; } } }
using System.Threading; using System.Threading.Tasks; using Micro.Net.Core.Abstractions.Management; namespace Micro.Net.Abstractions { public interface IStartable : IMicroComponent { Task Start(CancellationToken cancellationToken); } }
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; public partial class EditProduct : System.Web.UI.Page { string obj_Authenticated; PlaceHolder maPlaceHolder; UserControl obj_Tabs; UserControl obj_LoginCtrl; UserControl obj_WelcomCtrl; UserControl obj_Navi; UserControl obj_Navihome; BizConnectClass bizconnect = new BizConnectClass(); string obj_productid; string cmp; ArrayList arr = new ArrayList(); string connStr = ConfigurationManager.ConnectionStrings["BizCon"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { if (IsPostBack == false) { string ID = Request.QueryString["value"]; fill_Product(); fillProductType(); fillProductCategory(); FillPackingtype(); fillUnitWeight(); fillUnitVolume(); fillUnitLH(); ChkAuthentication(); } } public void ChkAuthentication() { obj_LoginCtrl = null; obj_WelcomCtrl = null; obj_Navi = null; obj_Navihome = null; if (Session["Authenticated"] == null) { Session["Authenticated"] = "0"; } else { obj_Authenticated = Session["Authenticated"].ToString(); } maPlaceHolder = (PlaceHolder)Master.FindControl("P1"); if (maPlaceHolder != null) { obj_Tabs = (UserControl)maPlaceHolder.FindControl("loginheader1"); if (obj_Tabs != null) { obj_LoginCtrl = (UserControl)obj_Tabs.FindControl("login1"); obj_WelcomCtrl = (UserControl)obj_Tabs.FindControl("welcome1"); // obj_Navi = (UserControl)obj_Tabs.FindControl("Navii"); //obj_Navihome = (UserControl)obj_Tabs.FindControl("Navihome1"); if (obj_LoginCtrl != null & obj_WelcomCtrl != null) { if (obj_Authenticated == "1") { SetVisualON(); } else { SetVisualOFF(); } } } else { } } else { } } public void SetVisualON() { obj_LoginCtrl.Visible = false; obj_WelcomCtrl.Visible = true; //obj_Navi.Visible = true; // obj_Navihome.Visible = true; } public void SetVisualOFF() { obj_LoginCtrl.Visible = true; obj_WelcomCtrl.Visible = false; //obj_Navi.Visible = true; // obj_Navihome.Visible = false; } public void fillProductType() { DataSet ds =new DataSet(); ds = bizconnect.get_ProductType(); DDLproducttype.DataSource = ds; DDLproducttype.DataTextField = "ProductType"; DDLproducttype.DataValueField = "ProductTypeID"; DDLproducttype.DataBind(); } public void fillProductCategory() { DataSet ds=new DataSet(); ds = bizconnect.get_ProductCategory(Convert.ToInt32(DDLproducttype.SelectedValue)); DDLproductcategory.DataSource = ds; DDLproductcategory.DataTextField = "CategoryName"; DDLproductcategory.DataValueField = "ProductCategoryID"; DDLproductcategory.DataBind(); } public void FillPackingtype() { DataSet ds= new DataSet(); ds=bizconnect.get_PackingType(Convert.ToInt32(DDLproducttype.SelectedValue)); DDLpackingType.DataSource = ds; DDLpackingType.DataTextField = "PackingMethod"; DDLpackingType.DataValueField = "PackingMethodID"; DDLpackingType.DataBind(); } public void fillUnitWeight() { DataSet ds=new DataSet(); ds = bizconnect.get_unit(2); DDLWeightUnit.DataSource = ds; DDLWeightUnit.DataTextField = "unit"; DDLWeightUnit.DataValueField = "unitid"; DDLWeightUnit.DataBind(); } public void fillUnitVolume() { DataSet ds=new DataSet(); ds = bizconnect.get_unit(3); DDlvolumeunit.DataSource = ds; DDlvolumeunit.DataTextField = "unit"; DDlvolumeunit.DataValueField = "unitid"; DDlvolumeunit.DataBind(); } public void fillUnitLH() { DataSet ds = new DataSet(); ds = bizconnect.get_unit(1); //Length DDLLengthUnit.DataSource = ds; DDLLengthUnit.DataTextField = "unit"; DDLLengthUnit.DataValueField = "unitid"; DDLLengthUnit.DataBind(); //Width DDLwidthunit.DataSource = ds; DDLwidthunit.DataTextField = "unit"; DDLwidthunit.DataValueField = "unitid"; DDLwidthunit.DataBind(); //Height DDLHeightUnit.DataSource = ds; DDLHeightUnit.DataTextField = "unit"; DDLHeightUnit.DataValueField = "unitid"; DDLHeightUnit.DataBind(); } public void fill_Product() { obj_productid = Request.QueryString["value"]; arr.Clear(); arr = bizconnect.get_product(obj_productid); if (arr[0].ToString() != "0") { Txt_productname.Text = arr[3].ToString(); txt_productDescription.Text = arr[4].ToString(); Txt_sku.Text = arr[6].ToString(); txt_weight.Text = arr[7].ToString(); txt_length.Text = arr[9].ToString(); Txt_width.Text = arr[10].ToString(); txt_height.Text = arr[11].ToString(); txt_volume.Text = arr[12].ToString(); txt_transcostperunit.Text = arr[14].ToString(); } else { lblmsg.ForeColor = System.Drawing.Color.Red; lblmsg.Text = "Record not found or Table is Empty...!"; } } protected void Btn_submit_Click(object sender, EventArgs e) { int res; string ID = Request.QueryString["value"]; int id=Convert.ToInt32(ID); int sku=Convert.ToInt32(Txt_sku.Text); int pdttyp=Convert.ToInt32(DDLproducttype.SelectedValue); int pdtcat=Convert.ToInt32(DDLproductcategory.SelectedValue); int pcktyp=Convert.ToInt32(DDLpackingType.SelectedValue); double wgt=Convert.ToDouble(txt_weight.Text); int wgtunit=Convert.ToInt32(DDLWeightUnit.SelectedValue); double len=Convert.ToDouble(txt_length.Text); int lenunit= Convert.ToInt32(DDLLengthUnit.SelectedValue); double wid=Convert.ToDouble(Txt_width.Text); int widunit = Convert.ToInt32(DDLwidthunit.SelectedValue); double hght=Convert.ToDouble(txt_height.Text); int hghtunit = Convert.ToInt32(DDLHeightUnit.SelectedValue); double vol = Convert.ToDouble(txt_volume.Text); int volunit = Convert.ToInt32(DDlvolumeunit.SelectedValue); int pcksp = Convert.ToInt32(DDLpckngsp.SelectedValue); double cost = Convert.ToDouble(txt_transcostperunit.Text); res = bizconnect.Update_Product(id, sku, Txt_productname.Text, txt_productDescription.Text,pdttyp , pdtcat,pcktyp ,wgt , wgtunit,len ,lenunit,wid,widunit,hght,hghtunit, vol, volunit, pcksp, cost); if (res == 1) { lblmsg.ForeColor = System.Drawing.Color.Red; lblmsg.Text = "Updation of Customer details is Success..."; } else { lblmsg.ForeColor = System.Drawing.Color.Red; lblmsg.Text = "Error Occured in Updation of Posted Ad..."; } } public void EnableSolid() { DDLLengthUnit.Enabled =true; DDLwidthunit.Enabled =true; DDLHeightUnit.Enabled = true; DDlvolumeunit.Enabled = false; txt_length.Enabled = true; Txt_width.Enabled = true; txt_height.Enabled = true; txt_volume.Enabled = false; } public void EnableLiquid() { DDLLengthUnit.Enabled = false; DDLwidthunit.Enabled = false; DDLHeightUnit.Enabled = false; DDlvolumeunit.Enabled = true; txt_length.Enabled = true; Txt_width.Enabled = false; txt_height.Enabled = false; txt_volume.Enabled = true; } protected void DDLproducttype_SelectedIndexChanged(object sender, EventArgs e) { fillProductCategory(); FillPackingtype(); } protected void DDLpackingType_SelectedIndexChanged(object sender, EventArgs e) { if (Convert.ToInt32(DDLpackingType.SelectedValue) == 6) { EnableLiquid(); } else { EnableSolid(); } } }
using System; using Android.Views; using Android.Views.Animations; using Android.Animation; using Ts.Core.Containers; namespace Ts.Core { public static class AndroidAnimation { public static void Zoom(this View view, bool isIn, long duration = 500, Action animationStart = null, Action animationEnd = null){ float fromScale = isIn ? 1 : 0; ScaleAnimation animate = new ScaleAnimation (fromScale, 1-fromScale, fromScale, 1-fromScale, Dimension.RelativeToSelf, 0.5f, Dimension.RelativeToSelf, 0.5f); animate.Duration = duration; animate.AnimationStart += (s, e) => { if (animationStart != null) { animationStart.Invoke(); } }; animate.AnimationEnd += (sender, e) => { if (animationEnd != null) { animationEnd.Invoke(); } }; // view.Visibility = ViewStates.Visible; view.StartAnimation (animate); } public static void ZoomFromPosition(this View view, BaseViewWrapper fromScreen, IZoomScreen toScreen, bool isBack, long duration = 500, Action animationEnd = null) { var interpolator = new DecelerateInterpolator(1.5f); var argsScreen = fromScreen as IZoomScreen; var x = argsScreen.Center.X - (float)fromScreen.View.Width * argsScreen.WidthRatio / 2f; var y = argsScreen.Center.Y - (float)fromScreen.View.Height * argsScreen.HeightRatio / 2f - 50; view.SetX(x); view.SetY(y); if (x > 0 && y > 0) { view.PivotX = x / (float)fromScreen.View.Width; view.PivotY = y / (float)fromScreen.View.Height; } else { view.PivotX = view.PivotY = 0.5f; } view.ScaleX = argsScreen.WidthRatio; view.ScaleY = argsScreen.HeightRatio; if(view.Visibility != ViewStates.Visible) view.Visibility = ViewStates.Visible; ObjectAnimator scaleXAnimator; ObjectAnimator scaleYAnimator; ObjectAnimator xAnimator; ObjectAnimator yAnimator; ObjectAnimator alphaAnimator; if (!isBack) { alphaAnimator = ObjectAnimator.OfFloat(view, "alpha", 0, 1); xAnimator = ObjectAnimator.OfFloat(view, "x", x, 0); yAnimator = ObjectAnimator.OfFloat(view, "y", y, 0); scaleXAnimator = ObjectAnimator.OfFloat(view, "scaleX", argsScreen.WidthRatio, 1f); scaleYAnimator = ObjectAnimator.OfFloat(view, "scaleY", argsScreen.HeightRatio, 1f); } else { alphaAnimator = ObjectAnimator.OfFloat(view, "alpha", 1, 0); xAnimator = ObjectAnimator.OfFloat(view, "x", 0, x); yAnimator = ObjectAnimator.OfFloat(view, "y", 0, y); scaleXAnimator = ObjectAnimator.OfFloat(view, "scaleX", 1f, argsScreen.WidthRatio); scaleYAnimator = ObjectAnimator.OfFloat(view, "scaleY", 1f, argsScreen.HeightRatio); } var animatorSet = new AnimatorSet(); animatorSet.PlayTogether(alphaAnimator, xAnimator, yAnimator, scaleXAnimator, scaleYAnimator); animatorSet.SetDuration(duration); animatorSet.SetInterpolator(interpolator); animatorSet.AnimationEnd += (sender, e) => { if (animationEnd != null) animationEnd(); }; animatorSet.Start(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using NutritionalResearchToolApplication.Pages; namespace NutritionalResearchToolApplication { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void mainWindows_Loaded(object sender, RoutedEventArgs e) { App.Current.Properties["MyFrame"] = myFrame; } private void btn_GotoMainPage_Click(object sender, RoutedEventArgs e) { if(!myFrame.CurrentSource.OriginalString.Contains("MainPage")) { myFrame.Navigate(new Uri(@"Pages\MainPage.xaml",UriKind.Relative)); } //else //{ // MessageBox.Show("当前就是主页"); //} } } }
using System; using System.IO; using System.Reflection; using Harmony; using SharedCode.Config; using SharedCode.Logging; using SharedCode.Utils; using UnityEngine.SceneManagement; namespace FishOverflowDistributor { /// <summary> /// Contains mod entry point and basic bootstrapping /// </summary> public class FishOverflowDistributor { private const string ModId = "snowrabbit007_subnauticamod_FishOverflowDistributor"; //same as in mod.json private const string ModName = "FishOverflowDistributor"; //same as in mod.json private const string LogFileName = "log.txt"; private const string ConfigFileName = "config.yml"; /// <summary> /// Logger instance used for logging throughout the mod. Initialization done in Load() method. /// </summary> public static ILogger Logger { get; set; } /// <summary> /// Config representing config.yml in the mod directory. /// </summary> public static FishOverflowDistributorConfig Config { get; set; } /// <summary> /// Stores the directory path of the mod assembly (e.g. "QMods\SomeGenericMod\") /// </summary> public static string ModDirectoryPath { get { string p = Assembly.GetExecutingAssembly().CodeBase; var uri = new UriBuilder(p); string dir = Uri.UnescapeDataString(uri.Path); return Path.GetDirectoryName(dir); } } /// <summary> /// Stores the full file path of the mod's log file (e.g. "QMods\SomeGenericMod\log.txt") /// </summary> public static string LogFilePath { get { return Path.Combine(ModDirectoryPath, LogFileName); } } /// <summary> /// Stores the full file path of the mod's config file (e.g. "QMods\SomeGenericMod\config.yml") /// </summary> public static string ConfigFilePath { get { return Path.Combine(ModDirectoryPath, ConfigFileName); } } /// <summary> /// Stores the directory path to the Subnautica Data Directory (e.g. Steamapps\Common\Subnautica\Subnautica /// </summary> public static string SubnauticaDirectoryPath { get { return Path.Combine(ModDirectoryPath, @"\..\Subnautica_Data\"); } } /// <summary> /// Main entry point which is called by QMods. Specified in mod.json /// </summary> public static void Load() { Config = YamlConfigReader.Readconfig<FishOverflowDistributorConfig>( ConfigFilePath, x => { Console.WriteLine( $"[{ModName}] [Fatal] Error parsing config file '{ConfigFilePath}. {Environment.NewLine}"); Console.WriteLine(ExceptionUtils.GetExceptionErrorString(x)); }); if (Config == null) return; Logger = new QModLogger() .WithTarget(new QModFileLoggerTarget(LogFilePath, Config.LogLevel)) .WithTarget(new SubnauticaConsoleLoggerTarget(ModName, LogLevel.Error)) .Open(); SceneManager.sceneLoaded += OnSceneLoaded; SceneManager.sceneUnloaded += OnSceneUnloaded; OnGameStart(); } /// <summary> /// Called when the game starts (We will be in main menu after this) /// </summary> public static void OnGameStart() { Logger.LogInfo($"Game start. Applying patches."); HarmonyInstance.Create(ModId).PatchAll(Assembly.GetExecutingAssembly()); } /// <summary> /// Called when scene "main" is loaded (the user has started a new game/loaded a save) /// </summary> public static void OnSceneStart() { Logger.LogInfo("Scene 'main' loaded."); //TODO: Apply behaviors which need to be done when scene has started //e.g. GameObject go = new GameObject(); //e.g. go.AddComponent<SomeImportantComponent>(); } /// <summary> /// Called when scene "main" is unloaded (user exits subnautica) /// </summary> public static void OnSceneFinish() { Logger.LogInfo("scene 'main' unloaded."); //TODO: Do things here before the scene is destroyed //e.g. File.Write(SavePath, ImportantSaveInformation); } private static void OnSceneLoaded(Scene scene, LoadSceneMode mode) { Logger.LogTrace($"Scene '{scene.name}' loaded."); if (scene.name == "Main") OnSceneStart(); } private static void OnSceneUnloaded(Scene scene) { Logger.LogTrace($"Scene '{scene.name}' unloaded."); if (scene.name == "Main") OnSceneFinish(); } } }
using Plus.HabboHotel.Rooms; namespace Plus.Communication.Packets.Outgoing.Rooms.AI.Bots { internal class OpenBotActionComposer : MessageComposer { public int BotId { get; } public string BotName { get; } public int ActionId { get; } public string BotSpeech { get; } public OpenBotActionComposer(RoomUser botUser, int actionId, string botSpeech) : base(ServerPacketHeader.OpenBotActionMessageComposer) { BotId = botUser.BotData.Id; BotName = botUser.BotData.Name; ActionId = actionId; BotSpeech = botSpeech; } public override void Compose(ServerPacket packet) { packet.WriteInteger(BotId); packet.WriteInteger(ActionId); if (ActionId == 2) packet.WriteString(BotSpeech); else if (ActionId == 5) packet.WriteString(BotName); } } }
using UnityEngine; using System.Collections; public class CameraControll : MonoBehaviour { private GameObject m_buildTowerHUD; private GameObject m_totemHUD; private GameObject m_upgradeTower; public GameObject m_mainCamera; public GameObject m_villageCamera; public float m_cameraSpeed = 5.0f; public int m_cameraBorderFactor = 10; public float m_cameraVelocityFactor = 30.0f; public int m_offsetBottom = 300; public int m_offsetTop = 760; private Vector3 mousePos; //values for the position and rotation of the main camera private float m_translationX1 = -3.0f; private float m_translationY1 = 7.0f; private float m_translationZ1 = 3.5f; private float m_rotationX1 = 50.0f; private float m_rotationY1 = 80.0f; private float m_rotationZ1 = 0.0f; //values for the position and rotation of the village camera private float m_translationXVillage = 5.0f; private float m_translationYVillage = 5.0f; private float m_translationZVillage = -5.0f; private float m_rotationXVillage = 50.0f; private float m_rotationYVillage = 0.0f; private float m_rotationZVillage = 0.0f; public GameObject m_fieldSystem; private FieldScript m_fieldScript; // Use this for initialization void Start () { m_buildTowerHUD = GameObject.Find("HUDCanvas").transform.FindChild("BuildTowerHUD").gameObject; m_totemHUD = GameObject.Find("HUDCanvas").transform.FindChild("TotemHUD").gameObject; m_upgradeTower = GameObject.Find("HUDCanvas").transform.Find("UpgradeTowerHUD").gameObject; m_mainCamera.transform.Translate(m_translationX1, m_translationY1, m_translationZ1); m_mainCamera.transform.Rotate(m_rotationX1, m_rotationY1, m_rotationZ1); m_mainCamera.SetActive(true); setVillageCamera(); m_villageCamera.SetActive(false); m_fieldScript = m_fieldSystem.GetComponent<FieldScript>(); } // Update is called once per frame void Update () { //Steuerung mit der Maus if (m_mainCamera.activeSelf) { mousePos = Input.mousePosition; Vector3 worldCoordinates = Camera.main.ScreenToWorldPoint(mousePos); if (mousePos.x < (Screen.width / m_cameraBorderFactor) && checkYParamters()) //links { if (worldCoordinates.z > m_fieldScript.GetCameraMax()) return; float value = (Screen.width / m_cameraBorderFactor) - mousePos.x; float speed = m_cameraSpeed * (value / m_cameraVelocityFactor); if(m_buildTowerHUD.activeSelf || m_totemHUD.activeSelf || m_upgradeTower.activeSelf) { m_buildTowerHUD.SetActive(false); m_totemHUD.SetActive(false); m_upgradeTower.GetComponent<SelectUpgradeScript>().Unshow(); m_upgradeTower.SetActive(false); } m_mainCamera.transform.position += new Vector3(0.0f, 0.0f, speed * Time.deltaTime); } else if (mousePos.x > (Screen.width - (Screen.width / m_cameraBorderFactor)) && checkYParamters()) //rechts { if (worldCoordinates.z < 0) return; float value = mousePos.x - (Screen.width - (Screen.width / m_cameraBorderFactor)); float speed = m_cameraSpeed * (value / m_cameraVelocityFactor); if (m_buildTowerHUD.activeSelf || m_totemHUD.activeSelf || m_upgradeTower.activeSelf) { m_buildTowerHUD.SetActive(false); m_totemHUD.SetActive(false); m_upgradeTower.GetComponent<SelectUpgradeScript>().Unshow(); m_upgradeTower.SetActive(false); } m_mainCamera.transform.position += new Vector3(0.0f, 0.0f, -speed * Time.deltaTime); } } //Mausrad drücken if(Input.GetMouseButtonUp(2)) { if(m_mainCamera.activeSelf) { m_mainCamera.SetActive(false); setVillageCamera(); m_villageCamera.SetActive(true); GameObject.Find("CounterSystem").GetComponent<OverallInformation>().m_curretCam = m_villageCamera.GetComponent<Camera>(); } else { m_mainCamera.SetActive(true); m_villageCamera.SetActive(false); GameObject.Find("CounterSystem").GetComponent<OverallInformation>().m_curretCam = m_mainCamera.GetComponent<Camera>(); } if (m_buildTowerHUD.activeSelf || m_totemHUD.activeSelf || m_upgradeTower.activeSelf) { m_buildTowerHUD.SetActive(false); m_totemHUD.SetActive(false); m_upgradeTower.GetComponent<SelectUpgradeScript>().Unshow(); m_upgradeTower.SetActive(false); } } //ALT: Steuerung mit der Tastatur //if (Input.GetKeyUp(KeyCode.Space)) //{ // if (m_mainCamera.activeSelf) // { // m_mainCamera.SetActive(false); // setVillageCamera(); // m_villageCamera.SetActive(true); // } // else // { // m_mainCamera.SetActive(true); // m_villageCamera.SetActive(false); // } //} //if (m_mainCamera.activeSelf) //{ // if (Input.GetKey(KeyCode.A)) // { // //transform.Translate(new Vector3(-(m_cameraSpeed * Time.deltaTime), 0.0f, 0.0f)); // m_mainCamera.transform.position += new Vector3(0.0f, 0.0f, m_cameraSpeed * Time.deltaTime); // } // if (Input.GetKey(KeyCode.D)) // { // //Vector3 currPos = m_mainCamera.transform.position; // //Vector3 toAdd = new Vector3(0.0f, 0.0f, -(m_cameraSpeed * Time.deltaTime)); // //Vector3 toGoTo = currPos + toAdd; // //m_mainCamera.transform.position = Vector3.Lerp(currPos, toGoTo, Time.deltaTime * 50f); // m_mainCamera.transform.position += new Vector3(0.0f, 0.0f, -(m_cameraSpeed * Time.deltaTime)); // } //} //else //{ // if (Input.GetKey(KeyCode.W)) // { // m_villageCamera.transform.position += new Vector3(0.0f, 0.0f, m_cameraSpeed * Time.deltaTime); // } // if (Input.GetKey(KeyCode.S)) // { // m_villageCamera.transform.position += new Vector3(0.0f, 0.0f, -(m_cameraSpeed * Time.deltaTime)); // } //} } private void setVillageCamera() { m_villageCamera.transform.position = new Vector3(m_translationXVillage, m_translationYVillage, m_translationZVillage); m_villageCamera.transform.eulerAngles = new Vector3(m_rotationXVillage, m_rotationYVillage, m_rotationZVillage); } private bool checkYParamters() { if ((mousePos.y > m_offsetBottom) /*&& (mousePos.y < m_offsetTop)*/) return true; return false; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ToDo.Client.Core.Tasks { public enum ProjectTaskType { Bug, Feature, Task, } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.XR; public class ButtonInput : MonoBehaviour { [SerializeField] private Camera _Cam; [SerializeField] private AudioSource _AudioSource; [SerializeField] private RadioController _RadioController; private SphereCollider _ButtonCollider; private bool _IsPlaying = false; private void Awake() { _ButtonCollider = GetComponent<SphereCollider>(); } private void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { Application.Quit(); } var ray = _Cam.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out var hit) == false) return; if (hit.transform.GetComponent<SphereCollider>() != _ButtonCollider || Input.GetMouseButtonDown(0) == false) return; _AudioSource.Play(); if (_IsPlaying == true) { _IsPlaying = false; _RadioController.gameObject.SetActive(false); } else { _IsPlaying = true; _RadioController.gameObject.SetActive(true); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Program.cs" company="my company"> // Test // </copyright> // <summary> // The program. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace ConsoleApplication1 { /// <summary> /// The program. /// </summary> internal class Program { /// <summary> /// The main. /// </summary> /// <param name="args"> /// The args. /// </param> private static void Main(string[] args) { } private void test() { var i = 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Planning { class PdbPlaner { List<Agent> agents = null; Domain d; Problem p; int countOfLandmarks = 0; List<Action> publicActions = null; PatternDatabase pd = null; Dictionary<string, HashSet<CompoundFormula>> agentEffect = new Dictionary<string, HashSet<CompoundFormula>>(); // StreamWriter sw = new StreamWriter("sss.txt", false); public PdbPlaner(List<Agent> m_agents, List<Landmark> goals, PatternDatabase pd) { // d = m_d; // p = m_p; agents = m_agents; this.pd = pd; publicActions = new List<Action>(); foreach (Agent agent in agents) { agentEffect.Add(agent.name, new HashSet<CompoundFormula>()); foreach (Action act in agent.publicActions) { CompoundFormula eff = new CompoundFormula("and"); foreach (GroundedPredicate gp in act.HashEffects) { if (agent.PublicPredicates.Contains(gp)) { eff.AddOperand(gp); } } if (!agentEffect[agent.name].Contains(eff)) { agentEffect[agent.name].Add(eff); } } agent.initPdbPlaner(); countOfLandmarks += agent.GetNumberOfRestLandmarks(); } PdbVertex.initVertxClass(agents, d, p, goals, pd); } private bool CheckAgentEquality() { List<HashSet<Predicate>> lAgentsEffects = new List<HashSet<Predicate>>(); foreach (Agent a in agents) { HashSet<Predicate> lAllSingleAgentPublicEffects = new HashSet<Predicate>(); foreach (Action aAction in a.publicActions) { HashSet<Predicate> lEffects = aAction.GetMandatoryEffects(); foreach (GroundedPredicate p in lEffects) if (!p.Negation && a.PublicPredicates.Contains(p)) lAllSingleAgentPublicEffects.Add(p); } if (lAgentsEffects.Count > 0) { if (lAgentsEffects[0].Count != lAllSingleAgentPublicEffects.Count) return false; foreach (Predicate p in lAllSingleAgentPublicEffects) if (!lAgentsEffects[0].Contains(p)) return false; } lAgentsEffects.Add(lAllSingleAgentPublicEffects); } return true; } public List<string> Plan() { bool bAllAgentsEqual = CheckAgentEquality(); int i = 300;// countOfLandmarks; int[] statesNum = new int[agents.Count]; for (int k = 0; k < statesNum.Length; k++) { statesNum[k] = 0; } PdbVertex rootVertex = new PdbVertex(statesNum, new List<Action>(), 0, 0, 0, null, null); rootVertex.publicState = new State((Problem)null); foreach(Agent agent in agents) { foreach (GroundedPredicate pgp in agent.GetPublicInitial()) { if (!rootVertex.publicState.Contains(pgp)) { rootVertex.publicState.AddPredicate(pgp); } } } //DateTime begin = DateTime.Now; int count = 0; PdbVertex curentVertex = null; DateTime dtStart = DateTime.Now; //for (; i < 1000; i++) { HashSet<int[]> lVisited = new HashSet<int[]>(new ComparerArray()); HashSet<PdbVertex> lVisited2 = new HashSet<PdbVertex>(); DateTime begin = DateTime.Now; List<PdbVertex> queue = new List<PdbVertex>(); //PriorityQueue<PdbVertex, double> queue2 = new PriorityQueue<PdbVertex, double>(PdbVertex.ComparerDouble); //PriorityQueue<PdbVertex, double> queue2 = new PriorityQueue<PdbVertex, double>(); //Heap heap = new Heap(1000000); //queue2.Insert(rootVertex, rootVertex.h); //heap.Insert(rootVertex); queue.Add(rootVertex); lVisited.Add(rootVertex.statesNubmber); // double priority = -1 * (rootVertex.h + (double)(rootVertex.g) / 100000 ); //queue2.Enqueue(rootVertex, priority); int temp = 0; List<string> lplan = null;// new List<string>(); bool flag = true; int c = 0; double minh = 99999999; while (queue.Count > 0) { c++; if (c % 1000 == 0) { //Console.Write("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\bExpanded: " + c + ", open: " + queue.Count + ", h: " + curentVertex.h + ", T: " + (int)(DateTime.Now - dtStart).TotalSeconds); Console.Write("\rExpanded: " + c + ", open: " + queue.Count + ", h: " + curentVertex.h + ", T: " + (int)(DateTime.Now - dtStart).TotalSeconds); if (queue.Count > 200000) { return null; Console.WriteLine(); Console.WriteLine("Queue too large, breaking."); } } flag = true; //curentVertex = queue[0]; // List<PriorityQueueItem<PdbVertex,double>> v = queue2.ToList(); //curentVertex = queue2.Dequeue().Value; temp++; curentVertex = FindMin(queue);// queue[0];// heap.Remove(); // queue.Remove(curentVertex); // queue.RemoveAt(0); count++; bool bDeadend = curentVertex.IsDeadEnd(); if (bDeadend) continue; // if (curentVertex.Parent != null && curentVertex.Parent.Parent != null && curentVertex.h == curentVertex.Parent.h && curentVertex.h == curentVertex.Parent.Parent.h) // Console.WriteLine("stuck!"); // Program.messages += agents.Count; int f = 0; List<PdbVertex> needUpDate = new List<PdbVertex>(); HashSet<CompoundFormula> levelPotential = new HashSet<CompoundFormula>(); int index = 1; bool con = false; if (curentVertex.h == 0) { curentVertex.publicPredicateImplications = new List<HashSet<CompoundFormula>>(); PdbVertex tmp = curentVertex; while (tmp != null) { curentVertex.publicPredicateImplications.Insert(0, tmp.canGetInParallel); tmp = tmp.Parent; } string isGoal = curentVertex.IsGoal(out lplan); if (isGoal.Equals("true")) { double time = ((double)((DateTime.Now.Subtract(begin)).Minutes)) * 60.0; time += ((double)((DateTime.Now.Subtract(begin)).Seconds)); time += ((double)((DateTime.Now.Subtract(begin)).Milliseconds) / 1000); //Console.WriteLine(time); //Console.WriteLine(lplan.Count); // Console.WriteLine(((double)((DateTime.Now.Subtract(begin)).Milliseconds) / 1000)); Program.times.Add(time); Program.countActions.Add(lplan.Count); Program.timeSum += time; Program.actionSum += lplan.Count; /* foreach (Action act in curentVertex.lplan) { sw.WriteLine(act.Name); lplan.Add(act.Name); } sw.Close();*/ return lplan; } if (!isGoal.Equals("false")) { //return null; } } bool stop = false; foreach (Agent agent in agents) { foreach (Action act in agent.publicActions) { f++; Program.messages += agents.Count; PdbVertex newVertex = curentVertex.Apply(agent.name, act); bool bVisited = true; if (newVertex != null) { if (bAllAgentsEqual) bVisited = lVisited2.Contains(newVertex); else bVisited = lVisited.Contains(newVertex.statesNubmber); } if (!bVisited) { // newVertex.History = new List<string>(curentVertex.History); // newVertex.History.Add(act.Name); // newVertex.g += (double)index / 1000000; queue.Add(newVertex); if (minh > newVertex.h) { minh = newVertex.h; // if(minh==0) Console.WriteLine(minh); // break; } if (newVertex.h < curentVertex.h) { stop = true; break; } index++; //queue2.Enqueue(newVertex, priority); // needUpDate.Add(newVertex); CompoundFormula effect = new CompoundFormula("and"); foreach (GroundedPredicate gp in act.HashEffects) { if (agent.PublicPredicates.Contains(gp)) effect.AddOperand(gp); } levelPotential.Add(effect); } } if (stop) break; } curentVertex.canGetInParallel = levelPotential; } } return null; } public PdbVertex FindMin(List<PdbVertex> lvertxs) { int index = 0; int counter = 0; PdbVertex min = lvertxs.ElementAt(0); foreach (PdbVertex v in lvertxs) { if (PdbVertex.Comparer(min, v) == 1) { min = v; index = counter; } counter++; } var ans = lvertxs.ElementAt(index); lvertxs.RemoveAt(index); return ans; } } }
// Accord Statistics Library // The Accord.NET Framework // http://accord-framework.net // // Copyright © César Souza, 2009-2015 // cesarsouza at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // namespace Accord.Statistics.Distributions.Fitting { using Accord.Statistics.Distributions.Univariate; using Accord.Math; /// <summary> /// Options for Survival distributions. /// </summary> /// public class SurvivalOptions : IFittingOptions { /// <summary> /// Default survival estimation method. Returns <see cref="SurvivalEstimator.FlemingHarrington"/>. /// </summary> /// public const SurvivalEstimator DefaultSurvival = SurvivalEstimator.FlemingHarrington; /// <summary> /// Gets or sets the values for /// the right-censoring variable. /// </summary> /// public SurvivalOutcome[] Outcome { get; set; } /// <summary> /// Initializes a new instance of the <see cref="SurvivalOptions"/> class. /// </summary> /// public SurvivalOptions() { } } /// <summary> /// Options for Empirical Hazard distributions. /// </summary> /// public class EmpiricalHazardOptions : SurvivalOptions { /// <summary> /// Default hazard estimator. Returns <see cref="HazardEstimator.BreslowNelsonAalen"/>. /// </summary> /// public const HazardEstimator DefaultEstimator = HazardEstimator.BreslowNelsonAalen; /// <summary> /// Default tie handling method. Returns <see cref="HazardTiesMethod.Efron"/>. /// </summary> /// public const HazardTiesMethod DefaultTies = HazardTiesMethod.Efron; /// <summary> /// Gets or sets the estimator to be used. Default is <see cref="HazardEstimator.BreslowNelsonAalen"/>. /// </summary> /// public HazardEstimator Estimator { get; set; } /// <summary> /// Gets or sets the tie handling method to be used. Default is <see cref="HazardTiesMethod.Efron"/>. /// </summary> /// public HazardTiesMethod Ties { get; set; } /// <summary> /// Initializes a new instance of the <see cref="EmpiricalHazardOptions"/> class. /// </summary> /// public EmpiricalHazardOptions() { Estimator = DefaultEstimator; Ties = DefaultTies; } /// <summary> /// Initializes a new instance of the <see cref="EmpiricalHazardOptions"/> class. /// </summary> /// public EmpiricalHazardOptions(HazardEstimator estimator, SurvivalOutcome[] output) { Estimator = estimator; Outcome = output; Ties = DefaultTies; } /// <summary> /// Initializes a new instance of the <see cref="EmpiricalHazardOptions"/> class. /// </summary> /// public EmpiricalHazardOptions(HazardEstimator estimator, int[] output) { Estimator = estimator; Outcome = output.To<SurvivalOutcome[]>(); Ties = HazardTiesMethod.Breslow; } /// <summary> /// Initializes a new instance of the <see cref="EmpiricalHazardOptions"/> class. /// </summary> /// public EmpiricalHazardOptions(HazardEstimator estimator, HazardTiesMethod ties, SurvivalOutcome[] outcome) { Estimator = estimator; Outcome = outcome; Ties = ties; } /// <summary> /// Initializes a new instance of the <see cref="EmpiricalHazardOptions"/> class. /// </summary> /// public EmpiricalHazardOptions(HazardEstimator estimator, HazardTiesMethod ties, int[] output) { Estimator = estimator; Outcome = output.To<SurvivalOutcome[]>(); Ties = ties; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Metani.Models { public class TaniLokasi { public IEnumerable<JenisTani> jenisTani { get; set; } public IEnumerable<Lokasi> lokasi { get; set; } public HasilTani hasilTani { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace UberFrba.Abm_Automovil { public partial class ListadoAutomovil : Form { private Decimal telefonoChoferFiltro = 0; public ListadoAutomovil() { InitializeComponent(); this.telefonoChoferFiltro = 0; } private void ListadoAutomovil_Load(object sender, EventArgs e) { this.telefonoChoferFiltro = 0; DataTable marcasDt = Automovil.traerMarcas(); cmbMarca.DataSource = marcasDt; cmbMarca.DisplayMember = "Marca_Nombre"; cmbMarca.ValueMember = "Marca_Codigo"; cmbMarca.SelectedIndex = -1; } private void btnBuscarChofer_Click(object sender, EventArgs e) { GrillaChofer_Auto grillaSeleccionChofer = new GrillaChofer_Auto(this,"filtro"); grillaSeleccionChofer.Show(); } public void cambiarChofer(String chofer,Decimal telefonoChofer) { txtChofer.Text = chofer; this.telefonoChoferFiltro = telefonoChofer; } private void btnLimpiar_Click(object sender, EventArgs e) { txtChofer.Text = ""; txtModelo.Text = ""; txtPatente.Text = ""; telefonoChoferFiltro = 0; grillaAutomovil.DataSource = null; grillaAutomovil.Columns.Clear(); } private void btnRegresar_Click(object sender, EventArgs e) { this.Hide(); } private void btnAltaAutomovil_Click(object sender, EventArgs e) { AltaAutomovil altaAutomovil = new AltaAutomovil(); altaAutomovil.Show(); this.Hide(); } private void btnBuscar_Click(object sender, EventArgs e) { try { //Limpio la tabla de clientes grillaAutomovil.Columns.Clear(); //Busco los autos en la base de datos DataTable dtAutos = Automovil.buscarAutos(txtPatente.Text, txtModelo.Text, telefonoChoferFiltro,((cmbMarca.Text == "")? 0 :(Int32)cmbMarca.SelectedValue)); //Le asigno a la grilla los autos grillaAutomovil.DataSource = dtAutos; //Escondo datos que puedan confundir al usuario (Codigo de marca, Dni del chofer) grillaAutomovil.Columns["Auto_Marca"].Visible = false; grillaAutomovil.Columns["Auto_Chofer"].Visible = false; grillaAutomovil.Columns["Auto_Turno"].Visible = false; //Agrego botones para Modificar y Eliminar Automovil DataGridViewButtonColumn btnModificar = new DataGridViewButtonColumn(); btnModificar.HeaderText = "Modificar"; btnModificar.Text = "Modificar"; btnModificar.UseColumnTextForButtonValue = true; grillaAutomovil.Columns.Add(btnModificar); DataGridViewButtonColumn btnBorrar = new DataGridViewButtonColumn(); btnBorrar.HeaderText = "Dar de baja"; btnBorrar.Text = "Dar de baja"; btnBorrar.UseColumnTextForButtonValue = true; grillaAutomovil.Columns.Add(btnBorrar); } catch (Exception ex) { MessageBox.Show("Error inesperado: " + ex.Message, "Error", MessageBoxButtons.OK); } } private void grillaAutomovil_CellContentClick(object sender, DataGridViewCellEventArgs e) { var senderGrid = (DataGridView)sender; //En caso de que se presiono el boton "Modificar" de algun auto, se crea un objeto Automovil con los datos de la grilla y se lo manda a modificar //En caso de que se presiono el boton "Eliminar" de algun auto, se confirma si se quiere eliminar ese Auto y luego se ejecuta la acción. if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && senderGrid.CurrentCell.Value.ToString() == "Modificar" && e.RowIndex >= 0) { try { Automovil autoAModificar = new Automovil(); autoAModificar.Chofer = (Decimal)senderGrid.CurrentRow.Cells["Auto_Chofer"].Value; autoAModificar.Turno = (Int32)senderGrid.CurrentRow.Cells["Auto_Turno"].Value; autoAModificar.Marca = (Int32)senderGrid.CurrentRow.Cells["Auto_Marca"].Value; autoAModificar.Patente = senderGrid.CurrentRow.Cells["Auto_Patente"].Value.ToString(); autoAModificar.Modelo = senderGrid.CurrentRow.Cells["Auto_Modelo"].Value.ToString(); autoAModificar.Rodado = senderGrid.CurrentRow.Cells["Auto_Rodado"].Value.ToString(); autoAModificar.Licencia = senderGrid.CurrentRow.Cells["Auto_Licencia"].Value.ToString(); autoAModificar.Activo = (Byte)senderGrid.CurrentRow.Cells["Auto_Activo"].Value; ModificarAutomovil modificarAuto = new ModificarAutomovil(autoAModificar); modificarAuto.Show(); } catch (Exception ex) { MessageBox.Show("Ha ocurrido un error al realizar la seleccion del automovil: " + ex.Message, "Error", MessageBoxButtons.OK); } } else if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && senderGrid.CurrentCell.Value.ToString() == "Dar de baja" && e.RowIndex >= 0) { try { DialogResult dialogResult = MessageBox.Show("Esta seguro que desea dar de baja este automovil?", "Confirmación", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { String[] respuesta = Automovil.eliminarAuto(senderGrid.CurrentRow.Cells["Auto_Patente"].Value.ToString()); if (respuesta[0] == "Error") { MessageBox.Show("Error al dar de baja automovil: " + respuesta[1], "Error", MessageBoxButtons.OK); } else { MessageBox.Show(respuesta[1], "Operación exitosa", MessageBoxButtons.OK); } } } catch (Exception ex) { MessageBox.Show("Ha ocurrido un error al realizar la seleccion de rol " + ex.Message, "Error", MessageBoxButtons.OK); } } } } }
using log4net; using System; namespace ClouDeveloper.Log4net.CallerInfo { /// <summary> /// CallerInfoLogHelper /// </summary> public static class CallerInfoLogHelper { /// <summary> /// Obtains the logger. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instance">The instance.</param> /// <param name="enableSignature">if set to <c>true</c> [enable signature].</param> /// <returns></returns> public static CallerInfoLog ObtainLog<T>( this T instance, bool enableSignature = false) { return new CallerInfoLog( LogManager.GetLogger(typeof(T)), enableSignature); } /// <summary> /// Obtains the logger. /// </summary> /// <param name="typeInfo">The type information.</param> /// <param name="enableSignature">if set to <c>true</c> [enable signature].</param> /// <returns></returns> public static CallerInfoLog ObtainLog( this Type typeInfo, bool enableSignature = false) { return new CallerInfoLog( LogManager.GetLogger(typeInfo), enableSignature); } /// <summary> /// Obtains the log. /// </summary> /// <param name="log">The log.</param> /// <param name="enableSignature">if set to <c>true</c> [enable signature].</param> /// <returns></returns> public static CallerInfoLog ObtainLog( this ILog log, bool enableSignature = false) { return new CallerInfoLog(log, enableSignature); } } }
using System; using System.Collections.Generic; using System.Globalization; namespace cursoSeccao3Csharp { public class Program { private static void Main(string[] args) { Console.Write("Número da conta: "); int numero = int.Parse(Console.ReadLine()); Console.Write("Nome do titular: "); string titular = Console.ReadLine(); Console.Write("Limite de saque: "); double limite = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture); Conta novaConta = new Conta(numero, titular, limite); Console.Write("\nInforme um valor para depósito: "); double valorDeposito = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture); novaConta.depositar(valorDeposito); Console.WriteLine("Novo saldo = R$ " + novaConta.saldo.ToString("F2", CultureInfo.InvariantCulture)); Console.Write("\nInforme um valor para saque: "); double valorSaque = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture); // Tenta executar o bloco try { novaConta.sacar(valorSaque); Console.WriteLine("Novo saldo = R$ " + novaConta.saldo.ToString("F2", CultureInfo.InvariantCulture)); } // Se acontecer algum erro, ele captura e retorna a mensagem catch (OperacaoException e) { Console.WriteLine(e.Message); } Console.ReadLine(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace MyCore { public class CharacterEquipment : MonoBehaviour { [SerializeField] Transform m_backJoint; [SerializeField] Transform m_rightHandJoint; [SerializeField] Transform m_mainWeapon; public Transform rightHandJoint { get { return m_rightHandJoint; } } public Transform backJoint { get { return m_backJoint; } } public Transform mainWeapon { get { return m_mainWeapon; } } public bool IsEquipped(Transform joint) { return joint.childCount != 0; } public void Equipped(Transform joint, Transform equipment, bool worldPositionStays = false) { equipment.SetParent(joint,worldPositionStays); //equipment.parent = joint; equipment.localPosition = Vector3.zero; equipment.localRotation = Quaternion.identity; } public void SetMainWeapon(Transform mainWeapon) { m_mainWeapon = mainWeapon; } } }
namespace Plus.Communication.Packets.Outgoing.Catalog { internal class CatalogItemDiscountComposer : MessageComposer { public CatalogItemDiscountComposer() : base(ServerPacketHeader.CatalogItemDiscountMessageComposer) { } public override void Compose(ServerPacket packet) { packet.WriteInteger(100); //Most you can get. packet.WriteInteger(6); packet.WriteInteger(1); packet.WriteInteger(1); packet.WriteInteger(2); //Count { packet.WriteInteger(40); packet.WriteInteger(99); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; namespace Equinox.Domain.Models { [Table("AgentGlobalAdminRolesSystem")] public class AgentGlobalAdminRolesSystem : Core.Models.Entity { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid IdKey { get; set; } public AgentGlobalAdminRolesSystem(string RoleName, bool READ, bool WRITE, bool UPDATE) { this.RoleName = RoleName; this.READ = READ; this.WRITE = WRITE; this.UPDATE = UPDATE; } public List<ElinaPayInternalUsersRoles> ElinaPayUsersRoles { get; set; } public AgentGlobalAdminRolesSystem() { } [Column("RoleName")] public string RoleName { get; set; } [Column("READ")] public bool READ { get; set; } [Column("WRITE")] public bool WRITE { get; set; } [Column("UPDATE")] public bool UPDATE { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Zaliczenie.Models; namespace Zaliczenie.Controllers { public class ProductController : ApiController { private List<Product> products = new List<Product>() { new Product{Id=1,Name="koszulka",Price=60,Qty=6}, new Product{Id=2,Name="Buty",Price=90,Qty=6}, new Product{Id=3,Name="Rękawiczki",Price=90,Qty=6}, new Product{Id=4,Name="Czapki",Price=90,Qty=6}, new Product{Id=5,Name="KOrki",Price=90,Qty=6}, new Product{Id=6,Name="Kamizelka",Price=90,Qty=6} }; public IEnumerable<Product> Get() { return products.ToList(); } public IHttpActionResult Get(int id) { var product = products.Where(x => x.Id == id); if (product == null) return NotFound(); return Ok(product); } } }
using LinqToTwitter; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using personal_site.Models; using personal_site.Services.AuthHandlers; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Diagnostics; using System.Linq; using System.Net.Mail; using System.Security.Claims; using System.Threading.Tasks; using System.Web; namespace personal_site.Services { public class AccountService { public const string SESSION_CODE_NAME = "sys_authcode"; public const string SESSION_USER_NAME = "sys_authuser"; private static AccountService _instance; private AccountService() { } public async Task<bool> SendAuthCode() { MailService mailService = MailService.GetInstance(); string authCode = Guid.NewGuid().ToString(); HttpContext.Current.Session[SESSION_CODE_NAME] = authCode; MailMessage message = mailService.PrepareAuthCodeMessage(authCode); return await mailService.SendMessage(message); } public async Task<bool> VerifyAuthCode(string userAuthCode, ApplicationSignInManager signInManager) { var session = HttpContext.Current.Session; var systemAuthCode = session[SESSION_CODE_NAME]; var systemUser = session[SESSION_USER_NAME]; if (systemAuthCode == null || systemUser == null || userAuthCode == null) return false; else { bool authStatus = userAuthCode.Equals(systemAuthCode); if (authStatus) { ApplicationUser user = (ApplicationUser) systemUser; await signInManager.SignInAsync(user, false, false); session.Remove(SESSION_CODE_NAME); session.Remove(SESSION_USER_NAME); } return authStatus; } } public async Task<bool> VerifySystemUser(string username, string password, ApplicationUserManager userManager) { ApplicationUser user = await userManager.FindByNameAsync(username); if (user == null) return false; bool validStatus = await userManager.CheckPasswordAsync(user, password); bool roleStatus = await userManager.IsInRoleAsync(user.Id, "Admin"); if (validStatus && roleStatus) { HttpContext.Current.Session[SESSION_USER_NAME] = user; return true; } else return false; } public bool AuthCodePending() { var session = HttpContext.Current.Session; return session[SESSION_CODE_NAME] != null && session[SESSION_USER_NAME] != null; } public ExternalAuthHandler GetExternalAuthHandler(ExternalLoginInfo loginInfo) { string provider = loginInfo.Login.LoginProvider; switch(provider) { case "Google": return new GoogleAuthHandler(); case "Twitter": return new TwitterAuthHandler(); case "Facebook": return new FacebookAuthHandler(); case "Microsoft": return new MicrosoftAuthHandler(); default: return null; } } public static AccountService GetInstance() { _instance = _instance ?? new AccountService(); return _instance; } } }
using System; using System.IO; using LordG.Tools.Drive; namespace Tests { class Program { static void Main(string[] args) { Drive.GetDrives getDrives = new Drive.GetDrives(); Drive drive = new Drive(); DriveInfo[] drives = getDrives.AsDriveInfo(); foreach (DriveInfo d in drives) { if (drive.IsType(d, DriveType.Fixed)) { Console.WriteLine(d.Name); } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Spine.Unity; using UnityEngine.EventSystems; using UnityEngine.Networking.Types; using UnityEngine.Networking.Match; using Prototype.NetworkLobby; public class cofreLobby : MonoBehaviour { public GameObject Cartas; public int abiertas; public int deb1; public int deb2; public int deb3; bool listo1; bool listo2; bool listo3; public GameObject card1; public GameObject card2; public GameObject card3; public GameObject card1b; public GameObject card2b; public GameObject card3b; public GameObject baul; //CANTIDAD DE CARTAS public int carta1; public int carta2; public int carta3; //DE QUE A QUE CARTA PUEDE DESTAPAR public int minima; public int maxima;//1,2,7,8,9,11,15 public int cajas; bool esconder; public GameObject master; public bool open; // Use this for initialization void Start () { abiertas = 0; deb1 = Random.Range(minima,maxima); deb2 = Random.Range(minima,maxima); deb3 = Random.Range(minima,maxima); listo1 = true; cajas = PlayerPrefs.GetInt("caja1"); } // Update is called once per frame void Update () { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if(Input.GetMouseButtonDown(0)) { if(Physics.Raycast(ray, out hit)) { if(hit.collider == gameObject.GetComponent<Collider>()) { GetComponent<BoxCollider>().enabled = false; cajas -= 1; PlayerPrefs.SetInt("card"+deb1, carta1); PlayerPrefs.SetInt("card"+deb2, carta2); PlayerPrefs.SetInt("card"+deb3, carta3); GetComponent<Animator>().SetBool("abre", true); if(gameObject.name == "Baul") { //master.GetComponent<CommunityList>().pantalla = "esconder"; }else { master.GetComponent<regresaLobby>().actual = "esconder"; } open = false; } } } if(Input.GetButtonDown("Cancel")) { open = false; } PlayerPrefs.SetInt("caja", cajas); if(open && Input.GetButtonDown("Jump") || open && Input.GetButtonDown("Submit")) { open = false; GetComponent<BoxCollider>().enabled = false; cajas -= 1; print("RESTAR COFRE"); PlayerPrefs.SetInt("card"+deb1, carta1); PlayerPrefs.SetInt("card"+deb2, carta2); PlayerPrefs.SetInt("card"+deb3, carta3); GetComponent<Animator>().SetBool("abre", true); if(gameObject.name == "Baul") { //master.GetComponent<CommunityList>().pantalla = "esconder"; }else { master.GetComponent<regresaLobby>().actual = "esconder"; } } if(GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).IsName("entrac")) { GetComponent<Animator>().SetBool("cerrar", false); GetComponent<BoxCollider>().enabled = true; abiertas = 0; card1b.GetComponent<CajaCarta>().seleccionada = false; card2b.GetComponent<CajaCarta>().seleccionada = false; card3b.GetComponent<CajaCarta>().seleccionada = false; card1b.GetComponent<EventTrigger>().enabled = true; card2b.GetComponent<EventTrigger>().enabled = true; card3b.GetComponent<EventTrigger>().enabled = true; deb1 = Random.Range(minima,maxima); deb2 = Random.Range(minima,maxima); deb3 = Random.Range(minima,maxima); listo1 = true; cajas = PlayerPrefs.GetInt("caja1"); GetComponent<Animator>().SetBool("reiniciar", false); } if(GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).IsName("abrec")) { GetComponent<Animator>().SetBool("abre", false); } /*if(GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).IsName("cierrac")) { GetComponent<Animator>().SetBool("cerrar", false); }*/ ////CARTAS PlayerPrefs.SetInt("caja1", cajas); if(listo1) { print("TODOS DEBERIAN SER DIFERENTES"); card1.GetComponent<skinCarta>().skinsToCombine[0] = deb1.ToString(); card2.GetComponent<skinCarta>().skinsToCombine[0] = deb2.ToString(); card3.GetComponent<skinCarta>().skinsToCombine[0] = deb3.ToString(); /*PlayerPrefs.SetInt("card"+deb1, 1); PlayerPrefs.SetInt("card"+deb2, 1); PlayerPrefs.SetInt("card"+deb3, 1);*/ //CANTIDAD DE CARTAS carta1 = PlayerPrefs.GetInt("card"+deb1); carta1 = carta1+1; carta2 = PlayerPrefs.GetInt("card"+deb2); carta2 = carta2+1; carta3 = PlayerPrefs.GetInt("card"+deb3); carta3 = carta3+1; listo1 = false; } if(abiertas >= 3 && cajas <= 0 && !esconder) { open = false; //otra.SetActive(true); StartCoroutine(cerrar()); esconder = true; } if(abiertas >= 3 && cajas >= 1 && !esconder) { open = false; StartCoroutine(cerrarNuevo()); esconder = true; } } public EventSystem eventsystem; public GameObject m1; IEnumerator cerrar() { yield return new WaitForSeconds(2); card1.GetComponent<SkeletonGraphic>().AnimationState.SetAnimation(0, "salida", false); card2.GetComponent<SkeletonGraphic>().AnimationState.SetAnimation(0, "salida", false); card3.GetComponent<SkeletonGraphic>().AnimationState.SetAnimation(0, "salida", false); abiertas = 0; esconder = false; GetComponent<Animator>().SetBool("cerrar", true); eventsystem.GetComponent<EventSystem>().SetSelectedGameObject(m1); if(gameObject.name == "Baul") { /*master.GetComponent<CommunityList>().pantalla = ""; master.GetComponent<CommunityList>().menu.GetComponent<Animator>().SetBool("sale", false); master.GetComponent<CommunityList>().menu.GetComponent<Animator>().SetBool("entra", true);*/ }else { master.GetComponent<regresaLobby>().actual = master.GetComponent<regresaLobby>().actual2; master.GetComponent<regresaLobby>().menu.GetComponent<Animator>().SetBool("sale", false); master.GetComponent<regresaLobby>().menu.GetComponent<Animator>().SetBool("entra", true); } } IEnumerator cerrarNuevo() { yield return new WaitForSeconds(2); card1.GetComponent<SkeletonGraphic>().AnimationState.SetAnimation(0, "salida", false); card2.GetComponent<SkeletonGraphic>().AnimationState.SetAnimation(0, "salida", false); card3.GetComponent<SkeletonGraphic>().AnimationState.SetAnimation(0, "salida", false); GetComponent<Animator>().SetBool("cerrar", true); if(cajas >= 1) { if(gameObject.name == "Baul") { //master.GetComponent<CommunityList>().pantalla = "cofre"; }else { master.GetComponent<regresaLobby>().actual = "cofre"; } StartCoroutine(abreNuevo()); }else { if(gameObject.name == "Baul") { /*master.GetComponent<CommunityList>().pantalla = ""; master.GetComponent<CommunityList>().menu.GetComponent<Animator>().SetBool("sale", false); master.GetComponent<CommunityList>().menu.GetComponent<Animator>().SetBool("entra", true);*/ }else { print("NO MAS COFRES"); master.GetComponent<regresaLobby>().Regresar(); /*master.GetComponent<regresaLobby>().actual = master.GetComponent<regresaLobby>().actual2; master.GetComponent<regresaLobby>().menu.GetComponent<Animator>().SetBool("sale", false); master.GetComponent<regresaLobby>().menu.GetComponent<Animator>().SetBool("entra", true);*/ } } } IEnumerator abreNuevo() { yield return new WaitForSeconds(2); abiertas = 0; esconder = false; GetComponent<Animator>().SetBool("reiniciar", true); } public void aparecen() { Cartas.SetActive(true); card1.GetComponent<SkeletonGraphic>().AnimationState.SetAnimation(0, "entradacaja", false); card2.GetComponent<SkeletonGraphic>().AnimationState.SetAnimation(0, "entradacaja", false); card3.GetComponent<SkeletonGraphic>().AnimationState.SetAnimation(0, "entradacaja", false); } public void desaparecen() { Cartas.SetActive(false); } public void reset() { if(gameObject.name == "Baul") { //master.GetComponent<CommunityList>().pantalla = "cofre"; }else { master.GetComponent<regresaLobby>().actual = "cofre"; } } public void ahora() { open = true; } //SONIDOS public AudioSource audio1; public AudioClip nacer; public void nace() { audio1.clip = nacer; audio1.Play(); } public AudioClip[] cart; public void abre() { audio1.clip = cart[Random.Range(0,cart.Length)]; audio1.Play(); } public AudioClip sale1; public void exit() { audio1.clip = sale1; audio1.Play(); } public AudioClip sale2; public void exit2() { audio1.clip = sale2; audio1.Play(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Newtonsoft.Json; using ERPMVC.Models; using System.Net.Http; using System.Net.Http.Headers; namespace ERPMVC.Controllers { public class StaffController : Controller { public ActionResult Index() { int id = 3; string str = HttpClientHelper.Send("get","api/CheckApi/",null); List<CheckViewModel> list = JsonConvert.DeserializeObject<List<CheckViewModel>>(str); ViewBag.a = list; string str1 = HttpClientHelper.Send("get", "/api/StaffApi", null); List<StaffViewModel> list1 = JsonConvert.DeserializeObject<List<StaffViewModel>>(str1); StaffViewModel aa= (from a in list1.AsEnumerable() where a.StaffId == id select new StaffViewModel { HandImg = a.HandImg, StaffName=a.StaffName }).FirstOrDefault(); ViewBag.img = aa.HandImg; ViewBag.name = aa.StaffName; string str2 = HttpClientHelper.Send("get","/api/LeaveApi",null); List<LeaveViewModel> list2 = JsonConvert.DeserializeObject<List<LeaveViewModel>>(str2); ViewBag.qj = from a in list2.AsEnumerable() where a.StaffId == id select a; return View(); } [HttpGet] public ActionResult Add() { string str = HttpClientHelper.Send("get", "api/DepartmentApi", null); List<DepartmentViewModel> list = JsonConvert.DeserializeObject<List<DepartmentViewModel>>(str); ViewBag.dep = from d in list.AsEnumerable() select new SelectListItem { Text = d.DepartmentName, Value = d.DepartmentId.ToString() }; ViewBag.a = new List<SelectListItem>(); return View(); } [HttpPost] public ActionResult Add(StaffViewModel m,HttpPostedFileBase file) { string jue = Server.MapPath("/Image/"); string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + file.FileName; file.SaveAs(jue + filename); m.HandImg = "/Image/" + filename; m.StaffPassword = m.Identitycard.Substring(10, 8); m.StaffEntryDate = DateTime.Now.Date; string str = JsonConvert.SerializeObject(m); string result = HttpClientHelper.Send("post","api/StaffApi",str); return View(); } public ActionResult Wan(int pid) { string str= HttpClientHelper.Send("get", "api/RoleApi", null); List<RoleViewModel> list = JsonConvert.DeserializeObject<List<RoleViewModel>>(str); ViewBag.role = from r in list.AsEnumerable() where r.DepartmentId==pid select new SelectListItem { Text = r.RoleName, Value = r.RoleId.ToString() }; return PartialView("Role"); } [HttpGet] public ActionResult StaffUpd(int id) { Uri uri = new Uri("http://localhost:56425/"); HttpClient client = new HttpClient(); client.BaseAddress = uri;//赋值API地址 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//转换成json字符串格式 HttpResponseMessage response = client.GetAsync("/api/StaffApi/" + id).Result; if (response.IsSuccessStatusCode) { string jie = response.Content.ReadAsStringAsync().Result; var list = JsonConvert.DeserializeObject<StaffViewModel>(jie); return View(list); } else { return View(); } } public ActionResult StaffUpd(StaffViewModel Staff) { return View(); } } }
using System; using System.Collections.Generic; using System.Text; namespace Contoso.XPlatform.Constants { public struct Platforms { public const string iOS = "iOS"; public const string Android = "Android"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Benchmark.Benchmarks { using BenchmarkDotNet.Attributes; /* Unfair comparison, System is not doing Cast Method | ItemType | SizeOfInput | Mean | Error | StdDev | --------------- |--------- |------------ |----------:|----------:|----------:| Count | Array | 100 | 3.078 ns | 0.2947 ns | 0.0167 ns | FastLinq_Count | Array | 100 | 5.201 ns | 1.7888 ns | 0.1011 ns | Index | Array | 100 | 3.180 ns | 1.9171 ns | 0.1083 ns | FastLinq_Index | Array | 100 | 18.627 ns | 3.0802 ns | 0.1740 ns | Count | List | 100 | 1.363 ns | 1.2183 ns | 0.0688 ns | FastLinq_Count | List | 100 | 3.444 ns | 0.6790 ns | 0.0384 ns | Index | List | 100 | 1.976 ns | 0.3642 ns | 0.0206 ns | FastLinq_Index | List | 100 | 16.115 ns | 3.3330 ns | 0.1883 ns | */ public class CastListBenchmark { [Params( UnderlyingItemType.Array, UnderlyingItemType.List)] public UnderlyingItemType ItemType; [Params(100)] public int SizeOfInput; private IReadOnlyList<object> CastList; private IReadOnlyList<string> underlying; [GlobalSetup] public void Setup() { switch (this.ItemType) { case UnderlyingItemType.Array: this.underlying = Enumerable.Range(0, this.SizeOfInput).Select(i => i.ToString()).ToArray(); break; case UnderlyingItemType.List: this.underlying = Enumerable.Range(0, this.SizeOfInput).Select(i => i.ToString()).ToList(); break; default: throw new ArgumentOutOfRangeException(); } this.CastList = FastLinq.Cast<string, object>( this.underlying); } [Benchmark] [BenchmarkCategory("System", "Count")] public void Count() { var _ = this.underlying.Count; } [Benchmark] [BenchmarkCategory("System", "Index")] public void Index() { var _ = this.underlying[0]; } [Benchmark] [BenchmarkCategory("FastLinq", "Count")] public void FastLinq_Count() { var _ = this.CastList.Count; } [Benchmark] [BenchmarkCategory("FastLinq", "Index")] public void FastLinq_Index() { var _ = this.CastList[0]; } public enum UnderlyingItemType { List, Array } } }
using System; using System.ComponentModel; using System.Windows.Input; using Xamarin.Forms; namespace TipsAndTricksB.ViewModels { public class TipsAndTricksPageViewModel : INotifyPropertyChanged { public bool IsReadOnly { get; set; } = true; public ICommand ChangeColorCommand { get; set; } public DateTime Date { get; set; } = DateTime.Now; public TipsAndTricksPageViewModel() { ChangeColorCommand = new Command(() => { IsReadOnly = false; }); } public event PropertyChangedEventHandler PropertyChanged; } }
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Security.Cryptography; namespace LostAndFound { public class LoginUserModel : IModel { //private string appPath = @"C:\Users\Dovydas\Documents\GitHub\top-smartvision\top-smartvision\bin\Debug\Users\users.txt"; public string username { get; set; } public string password { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ConfigSettings : MonoBehaviour { public List<GameObject> subMenus; public List<GameObject> buttons; // Start is called before the first frame update void Start() { foreach (GameObject _menu in subMenus) { if (_menu == subMenus[0]) { _menu.SetActive(true); } else { _menu.SetActive(false); } } } // Update is called once per frame void Update() { } public void OnClickGame() { foreach (GameObject _menu in subMenus) { if(_menu == subMenus[0]) { _menu.SetActive(true); } else { _menu.SetActive(false); } } } public void OnClickControls() { foreach (GameObject _menu in subMenus) { if (_menu == subMenus[1]) { _menu.SetActive(true); } else { _menu.SetActive(false); } } } public void OnClickVideo() { foreach (GameObject _menu in subMenus) { if (_menu == subMenus[2]) { _menu.SetActive(true); } else { _menu.SetActive(false); } } } public void SelectedButtons() { for (int i = 0; i < subMenus.Count; i++) { if (subMenus[i].activeSelf) { buttons[i].GetComponent<Button>().Select(); } } } }
using backend.models; namespace backend.services { public class AtualizaQuebraRecordMinimoServico { public int AtualizaQuebraRecordMinimo(Jogo jogo, int quantidadeJogadas, int recordMinimo, int placarMinimo) { if (quantidadeJogadas == 0) { return recordMinimo; } else { if (jogo.Placar < placarMinimo) { return recordMinimo + 1; } } return recordMinimo; } } }
namespace VoxelEngine { public interface IGameTime { float ElapsedTime { get; } } }
using Microsoft.Extensions.DependencyInjection; using MongoDB.Driver; using Serilog.Ui.Core; using System; namespace Serilog.Ui.MongoDbProvider { /// <summary> /// SerilogUI option builder extensions. /// </summary> public static class SerilogUiOptionBuilderExtensions { /// <summary> /// Adds MongoDB log data provider. /// </summary> /// <param name="optionsBuilder">The options builder.</param> /// <param name="connectionString">The connection string.</param> /// <param name="collectionName">Name of the collection.</param> /// <exception cref="ArgumentNullException">connectionString</exception> /// <exception cref="ArgumentNullException">collectionName</exception> public static void UseMongoDb( this SerilogUiOptionsBuilder optionsBuilder, string connectionString, string collectionName ) { if (string.IsNullOrEmpty(connectionString)) throw new ArgumentNullException(nameof(connectionString)); if (string.IsNullOrEmpty(collectionName)) throw new ArgumentNullException(nameof(collectionName)); var mongoProvider = new MongoDbOptions { ConnectionString = connectionString, DatabaseName = MongoUrl.Create(connectionString).DatabaseName, CollectionName = collectionName }; ((ISerilogUiOptionsBuilder)optionsBuilder).Services.AddSingleton(mongoProvider); ((ISerilogUiOptionsBuilder)optionsBuilder).Services.AddSingleton<IMongoClient>(o => new MongoClient(connectionString)); ((ISerilogUiOptionsBuilder)optionsBuilder).Services.AddScoped<IDataProvider, MongoDbDataProvider>(); } /// <summary> /// Adds MongoDB log data provider. /// </summary> /// <param name="optionsBuilder">The options builder.</param> /// <param name="connectionString">The connection string without database name.</param> /// <param name="databaseName">Name of the database.</param> /// <param name="collectionName">Name of the collection.</param> /// <exception cref="ArgumentNullException">connectionString</exception> /// <exception cref="ArgumentNullException">databaseName</exception> /// <exception cref="ArgumentNullException">collectionName</exception> public static void UseMongoDb( this SerilogUiOptionsBuilder optionsBuilder, string connectionString, string databaseName, string collectionName ) { if (string.IsNullOrEmpty(connectionString)) throw new ArgumentNullException(nameof(connectionString)); if (string.IsNullOrEmpty(databaseName)) throw new ArgumentNullException(nameof(databaseName)); if (string.IsNullOrEmpty(collectionName)) throw new ArgumentNullException(nameof(collectionName)); var mongoProvider = new MongoDbOptions { ConnectionString = connectionString, DatabaseName = databaseName, CollectionName = collectionName }; ((ISerilogUiOptionsBuilder)optionsBuilder).Services.AddSingleton(mongoProvider); ((ISerilogUiOptionsBuilder)optionsBuilder).Services.AddSingleton<IMongoClient>(o => new MongoClient(connectionString)); ((ISerilogUiOptionsBuilder)optionsBuilder).Services.AddScoped<IDataProvider, MongoDbDataProvider>(); } } }
using BlogProject.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BlogProject.Repositories { public class PostTagRepository : IRepository<PostTag> { private BlogContext db; public PostTagRepository(BlogContext db) { this.db = db; } public void Delete(PostTag obj) { throw new NotImplementedException(); } public void Update(PostTag obj) { throw new NotImplementedException(); } public void Create(PostTag posttag) { db.PostTags.Add(posttag); db.SaveChanges(); } public IEnumerable<PostTag> GetAll() { return db.PostTags; } public PostTag GetById(int id) { return db.PostTags.Single(pt => pt.Id == id); } } }
namespace Newtonsoft.Json.Schema { using Newtonsoft.Json; using Newtonsoft.Json.Linq; using ns20; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; public static class Extensions { public static bool IsValid(this JToken source, JsonSchema schema) { Class118 class2 = new Class118 { bool_0 = true }; source.Validate(schema, new ValidationEventHandler(class2.method_0)); return class2.bool_0; } public static bool IsValid(this JToken source, JsonSchema schema, out IList<string> errorMessages) { Class119 class2 = new Class119 { ilist_0 = new List<string>() }; source.Validate(schema, new ValidationEventHandler(class2.method_0)); errorMessages = class2.ilist_0; return (errorMessages.Count == 0); } public static void Validate(this JToken source, JsonSchema schema) { source.Validate(schema, null); } public static void Validate(this JToken source, JsonSchema schema, ValidationEventHandler validationEventHandler) { Class203.smethod_2(source, "source"); Class203.smethod_2(schema, "schema"); using (JsonValidatingReader reader = new JsonValidatingReader(source.CreateReader())) { reader.Schema = schema; if (validationEventHandler != null) { reader.ValidationEventHandler += validationEventHandler; } while (reader.Read()) { } } } [CompilerGenerated] private sealed class Class118 { public bool bool_0; public void method_0(object sender, ValidationEventArgs e) { this.bool_0 = false; } } [CompilerGenerated] private sealed class Class119 { public IList<string> ilist_0; public void method_0(object sender, ValidationEventArgs e) { this.ilist_0.Add(e.Message); } } } }
using MKModel; using MKViewModel; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace MKView.Views { /// <summary> /// Interaction logic for ArmyBuilder.xaml /// </summary> public partial class ArmyBuilder : UserControl { private IArmyBuilder ab; public ArmyBuilder() { InitializeComponent(); this.Loaded += ArmyBuilder_Loaded; } private void ArmyBuilder_Loaded(object sender, RoutedEventArgs e) { ab = this.DataContext as IArmyBuilder; } private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { ab = this.DataContext as IArmyBuilder; //ab.SelectedArmy = lba.SelectedItem as IArmy; } private void ListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e) { ab = this.DataContext as IArmyBuilder; //ab.SelectedMageKnight = lbm.SelectedItem as IMageKnightModel; } private void lbm_MouseDoubleClick(object sender, MouseButtonEventArgs e) { ab = this.DataContext as IArmyBuilder; // this.lbm.ItemsSource = ab.User.MageKnights; } private void Button_Click(object sender, RoutedEventArgs e) { //this.Visibility = Visibility.Collapsed; } private void Games_SelectionChanged(object sender, SelectionChangedEventArgs e) { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public interface IGameMode { string GetLevelDescription(); void StartGameMode(); void GameModeOver(); void FinishGameMode(); void RestartGameMode(); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Workflow.Interface { /// <summary> /// this interface tells that the workflow uses a Database Context /// </summary> public interface IDbContextUtilizer { IDbContext Context { get; set; } } }
using Reserva.Infra.Context; using System; using System.Collections.Generic; using System.Text; namespace Reserva.Infra.Transactions { public class Uow : IUow { private readonly ReservaContext _context; public Uow(ReservaContext context) { _context = context; } public void commit() { _context.SaveChanges(); } public void RollBack() { throw new NotImplementedException(); } } }
namespace ConsoleWebServer.Framework { public interface IResponseFactory { HttpResponse CreateResponse(HttpRequest request); } }
using InstagramMVC.DataManagers; using System.Linq; namespace InstagramMVC.Models { /// <summary> /// Класс для экспорта в систему win32 InstagramAppUpdater /// </summary> public class TeleUser : AppUserMin { public bool CAN_USER_TRANSLATE_SHOW { get { return UserManager.CanUserTranslateShow(this.USER_ID); } set { } } public bool CAN_USER_MODERATE_SHOW { get { return UserManager.CanUserModerateShow(this.USER_ID); } set { } } public string TagCaption { get; set; } public int MediaTagCount { get { return UserManager.GetTeleUserMediatagCount(this.USER_LOGIN, this.TagCaption); } set { } } public long TicksFromLastUpdate { get { return UserManager.TicksFromLastUserEvent(this.USER_ID, (int)InstagramMVC.Globals.AppEnums.Event.Запуск_обновления_медиатегов, string.Format("'{0}'", this.TagCaption)); } set { } } public bool IsTelegramAllowedUser { get { string[] allowedRoles = InstagramMVC.DataManagers.UtilManager.GetVarValue("telegram.allowedroles").Split(','); return allowedRoles.Contains(UserManager.GetUserRole(this.USER_ID)); } set { } } } }
/* DotNetMQ - A Complete Message Broker For .NET Copyright (C) 2011 Halil ibrahim KALKAN This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using MDS.Serialization; namespace MDS.Communication.Messages { /// <summary> /// This class represents a message that is being transmitted between MDS server and a Controller (MDS Manager). /// </summary> public class MDSControllerMessage : MDSMessage { /// <summary> /// MessageTypeId for MDSControllerMessage. /// </summary> public override int MessageTypeId { get { return MDSMessageFactory.MessageTypeIdMDSControllerMessage; } } /// <summary> /// MessageTypeId of ControllerMessage. /// This field is used to deserialize MessageData. /// All types defined in ControlMessageFactory class. /// </summary> public int ControllerMessageTypeId { get; set; } /// <summary> /// Essential message data. /// This is a serialized object of a class in MDS.Communication.Messages.ControllerMessages namespace. /// </summary> public byte[] MessageData { get; set; } public override void Serialize(IMDSSerializer serializer) { base.Serialize(serializer); serializer.WriteInt32(ControllerMessageTypeId); serializer.WriteByteArray(MessageData); } public override void Deserialize(IMDSDeserializer deserializer) { base.Deserialize(deserializer); ControllerMessageTypeId = deserializer.ReadInt32(); MessageData = deserializer.ReadByteArray(); } } }
using Dapper; using EWF.Data; using EWF.Data.Repository; using EWF.IRepository.SysManage; using EWF.Util.Options; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Data; using System.Text; namespace EWF.Repository.SysManage { public partial class SYS_FACEQRepository:DefaultRepository, ISYS_FACEQRepository { public SYS_FACEQRepository(IOptionsSnapshot<DbOption> options) : base(options) { } /// <summary> /// 根据站码和表名获取数据 /// </summary> /// <param name="stcd"></param> /// <param name="tableName"></param> /// <returns></returns> public DataTable SearchFacEqData(string stcd, string tableName) { string sqlInnerText =string.Format("select * from {0} where STCD ={1}", File_Schema+tableName, stcd); return new RepositoryBase(database).FindTable(sqlInnerText); //using (var db = fileDataBase.Connection) //{ // return db.Query<dynamic>(sqlInnerText, sqlParams); //} } /// <summary> /// 根据测站和表名删除数据 /// </summary> /// <param name="stcd"></param> /// <param name="tableName"></param> /// <returns></returns> public IEnumerable<dynamic> DeleteFacEqData(string stcd, string tableName) { var sqlParams = new DynamicParameters(); sqlParams.Add("stcd", stcd); string sqlInnerText = "delete from " + File_Schema + tableName + " where STCD =@stcd"; using (var db = database.Connection) { return db.Query<dynamic>(sqlInnerText, sqlParams); } } /// <summary> /// 保存编辑后的设施设备数据 /// </summary> /// <param name="stcd"></param> /// <param name="tableName"></param> /// <param name="data"></param> /// <returns></returns> public string SaveFacEqData(string stcd, string tableName, string fieldName,string fieldType, string fieldContent) { var sqlParams = new DynamicParameters(); sqlParams.Add("stcd", stcd); var db = new RepositoryBase(database); var result = ""; //获取原数据 DataTable oldtable = SearchFacEqData(stcd, tableName); DeleteFacEqData(stcd, tableName);//删除数据 if (!string.IsNullOrWhiteSpace(fieldContent)) { int cnt = 0; string[] nameAry = fieldName.Split(new string[] { "," }, StringSplitOptions.None); string[] typeAry = fieldType.Split(new string[] { "," }, StringSplitOptions.None); string[] contentAry = fieldContent.Split(new string[] { "$" }, StringSplitOptions.None); StringBuilder strSql = new StringBuilder(); strSql.Append("INSERT INTO " + File_Schema + tableName + " ("); for (int i = 0; i < nameAry.Length; i++) { strSql.Append(nameAry[i].ToString() + ","); } strSql = strSql.Remove(strSql.Length - 1, 1); strSql.Append(")VALUES"); for (int j = 0; j < contentAry.Length; j++) { strSql.Append("("); string[] contentArychildren = contentAry[j].Split(new string[] { "," }, StringSplitOptions.None); for (int k = 0; k < contentArychildren.Length - 1; k++) { if (k == contentArychildren.Length - 2) { if (typeAry[k] == "number" || typeAry[k] == "numeric") { if (!string.IsNullOrWhiteSpace(contentArychildren[k].ToString().Replace("undefined", ""))) strSql.Append("" + contentArychildren[k].ToString().Replace("undefined", "") + ""); else strSql.Append("null"); } else strSql.Append("'" + contentArychildren[k].ToString().Replace("undefined", "") + "'"); } else { if (typeAry[k] == "number" || typeAry[k] == "numeric") { if (!string.IsNullOrWhiteSpace(contentArychildren[k].ToString().Replace("undefined", ""))) strSql.Append("" + contentArychildren[k].ToString().Replace("undefined", "") + ", "); else strSql.Append("null,"); } else { strSql.Append("'" + contentArychildren[k].ToString().Replace("undefined", "") + "', "); } } } strSql.Append("),"); } try { cnt = db.ExecuteBySql(strSql.ToString().Substring(0, strSql.ToString().Length - 1)); //删除成功 if (cnt > 0) { result = "true"; } } catch (Exception ex) { //删除失败时重加加入之前的数据 StringBuilder strSql2 = new StringBuilder(); strSql2.Append("INSERT INTO " + File_Schema + tableName + " ("); for (int i = 0; i < nameAry.Length; i++) { strSql2.Append(nameAry[i].ToString() + ","); } strSql2 = strSql2.Remove(strSql2.Length - 1, 1); strSql2.Append(")VALUES"); for (int j = 0; j < oldtable.Rows.Count; j++) { strSql2.Append("("); for (int k = 0; k < typeAry.Length; k++) { if (typeAry[k] == "number" || typeAry[k] == "numeric") { if (!string.IsNullOrWhiteSpace(oldtable.Rows[j][nameAry[k]].ToString().Replace("undefined", ""))) strSql2.Append("" + oldtable.Rows[j][nameAry[k]].ToString().Replace("undefined", "") + ", "); else strSql2.Append("null,"); } else { strSql2.Append("'" + oldtable.Rows[j][nameAry[k]].ToString().Replace("undefined", "") + "', "); } } strSql2.Remove(strSql2.Length - 2, 1); strSql2.Append("),"); } cnt = db.ExecuteBySql(strSql2.ToString().Substring(0, strSql2.ToString().Length - 1)); result = "false"; } return result; } else { return "true"; } } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // namespace DotNetNuke.UI.WebControls { /// ----------------------------------------------------------------------------- /// <summary> /// Enumeration that determines the mode of the editor. /// </summary> /// <remarks> /// PropertyEditorMode is used by <see cref="DotNetNuke.UI.WebControls.PropertyEditorControl">PropertyEditorControl</see> /// to determine the mode of the Editor. /// </remarks> /// ----------------------------------------------------------------------------- public enum PropertyEditorMode { Edit, View } }
/*using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; public class MoveScript : MonoBehaviour { public float paddleSpeed = 1f; private Vector3 playerPos = new Vector3(0, -9.5f, 0); float directionX; Rigidbody rb; // Use this for initialization void Start () { rb = GetComponent<Rigidbody>(); } // Update is called once per frame void Update () { directionX = transform.position.x + (CrossPlatformInputManager.GetAxis("Horizontal") * paddleSpeed); playerPos = new Vector3(Mathf.Clamp(directionX, -8f, 8f), -9.5f, 0f); rb.velocity = new Vector3(directionX * 10, 0); transform.position = playerPos; } }*/
using MyBlog.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MyBlog.Controllers { //Controller for a Form Model. public class HomeController : Controller { public ActionResult Form(Form form) { if (HttpContext.Request.HttpMethod == "POST") { return View("~/Views/Home/TestResult.cshtml", form); } else { return View(form); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Psub.DataService.DTO; using Psub.DataAccess.Abstract; using Psub.DataService.Abstract; using Psub.Domain.Entities; using NHibernate.Linq; namespace Psub.DataService.Concrete { public class RelayDataService : IRelayDataService { private readonly IRepository<RelayData> _relayDataRepository; private readonly IRepository<ControlObject> _controlObjectRepository; private readonly IActionLogService _actionLogService; public RelayDataService(IRepository<RelayData> relayDataRepository, IRepository<ControlObject> controlObjectRepository, IActionLogService actionLogService) { _relayDataRepository = relayDataRepository; _controlObjectRepository = controlObjectRepository; _actionLogService = actionLogService; } public int SaveOrUpdate(RelayDataDTO relayDataDTO) { var relayData = relayDataDTO.Id == 0 ? new RelayData() : _relayDataRepository.Get(relayDataDTO.Id); relayData.Id = relayDataDTO.Id; var isChangeVal = relayDataDTO.Id == 0 || relayDataDTO.Value != relayData.Value; if (isChangeVal) relayData.LastUpdate = DateTime.Now; if (!string.IsNullOrEmpty(relayDataDTO.Name)) relayData.Name = relayDataDTO.Name; if (relayDataDTO.PinName != 0) relayData.PinName = relayDataDTO.PinName; relayData.Value = relayDataDTO.Value; if (relayDataDTO.ControlObject != null) relayData.ControlObject = new ControlObject { Id = relayDataDTO.ControlObject.Id }; var id = _relayDataRepository.SaveOrUpdate(relayData); if (isChangeVal) _actionLogService.SetActionLog(string.Format("{0} {1} '{2}'",relayDataDTO.Id > 0 ? (relayData.Value ? "включил(а)" : "отключил(а)") : "", relayDataDTO.Id > 0 ? "исполнительную систему" : "создал(а) исполнительную систему", relayData.Name), id, typeof(RelayData).Name); return id; } public void SaveOrUpdateList(List<RelayDataDTO> relayDataDTO) { foreach (var relayData in relayDataDTO) { SaveOrUpdate(relayData); } } public int UpdateBySMS(string controlObjectGuid, string name,string val) { var raley = _relayDataRepository.Query().Fetch(x=>x.ControlObject).First(m => m.ControlObject.Guid == controlObjectGuid && m.PinName == Convert.ToInt32(name)); raley.Value = val == "1"; var id = _relayDataRepository.SaveOrUpdate(raley); _actionLogService.SetActionLog(string.Format("{0} {1} '{2}'", raley.Id > 0 ? (raley.Value ? "включил(а)" : "отключил(а)") : "", raley.Id > 0 ? "исполнительную систему" : "создал(а) исполнительную систему", raley.Name), id, typeof(RelayData).Name); return id; } public List<RelayDataDTO> GetRelayDataDTOByControlObjectId(int id) { return _relayDataRepository.Query().Where(m => m.ControlObject.Id == id).Select(m => new RelayDataDTO { Id = m.Id, Name = m.Name, PinName = m.PinName, Value = m.Value, LastUpdate = m.LastUpdate.ToString(CultureInfo.InvariantCulture) }).ToList(); } public List<RelayDataDTO> GetRelayDataDTOByControlObjectGuid(string guid) { return _relayDataRepository.Query().Where(m => m.ControlObject.Guid == guid).Select(m => new RelayDataDTO { Id = m.Id, Name = m.Name, PinName = m.PinName, Value = m.Value, LastUpdate = m.LastUpdate.ToString(CultureInfo.InvariantCulture) }).ToList(); } public RelayDataDTO GetRelayDataDTOById(int id) { var relayData = _relayDataRepository.Get(id); return new RelayDataDTO { Id = relayData.Id, Name = relayData.Name, PinName = relayData.PinName, Value = relayData.Value, LastUpdate = relayData.LastUpdate.ToString(CultureInfo.InvariantCulture), ControlObject = new ControlObjectDTO { Id = _controlObjectRepository.Query().First(m => m.RelayDatas.Select(x => x.Id).Contains(id)).Id } }; } public int GetControlObjectIdByRelayDataId(int id) { return _relayDataRepository.Get(id).ControlObject.Id; } public void Delete(int id) { _relayDataRepository.Delete(id); } } }
/* * Copyright 2016 Open University of the Netherlands * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * This project has received funding from the European Union’s Horizon * 2020 research and innovation programme under grant agreement No 644187. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace TrackerAssetUnitTests { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using AssetPackage; using System.Net; public class TesterBridge : IBridge, ILog, IDataStorage, IAppend, IWebServiceRequest { readonly String StorageDir = String.Format(@".{0}TestStorage", Path.DirectorySeparatorChar); /// <summary> /// Initializes a new instance of the asset_proof_of_concept_demo_CSharp.Bridge class. /// </summary> public TesterBridge() { /*if (!Directory.Exists(StorageDir)) { Directory.CreateDirectory(StorageDir); }*/ } #region IDataStorage Members Dictionary<string, string> files = new Dictionary<string, string>(); public bool Exists(string fileId) { return files.ContainsKey(fileId); } /// <summary> /// Gets the files. /// </summary> /// /// <returns> /// A List&lt;String&gt; /// </returns> public String[] Files() { /*return Directory.GetFiles(StorageDir).ToList().ConvertAll( new Converter<String, String>(p => p.Replace(StorageDir + Path.DirectorySeparatorChar, ""))).ToArray();*/ return null; //! EnumerateFiles not supported in Unity3D. // //return Directory.EnumerateFiles(StorageDir).ToList().ConvertAll( // new Converter<String, String>(p => p.Replace(StorageDir + Path.DirectorySeparatorChar, ""))).ToList(); } public void Save(string fileId, string fileData) { if (Exists(fileId)) files[fileId] = fileData; else files.Add(fileId, fileData); } public string Load(string fileId) { string content = ""; if (Exists(fileId)) content = files[fileId]; return content; } public bool Delete(string fileId) { if (Exists(fileId)) files.Remove(fileId); return true; } #endregion #region IAppend Members public void Append(string fileId, string fileData) { if (Exists(fileId)) files[fileId] = files[fileId] + fileData; else files.Add(fileId, fileData); } #endregion IAppend Members #region ILog Members /// <summary> /// Executes the log operation. /// /// Implement this in Game Engine Code. /// </summary> /// /// <param name="severity"> The severity. </param> /// <param name="msg"> The message. </param> public void Log(Severity severity, string msg) { // if (((int)LogLevel.Info & (int)severity) == (int)severity) { if (String.IsNullOrEmpty(msg)) { Console.WriteLine(""); } else { Console.WriteLine(String.Format("{0}: {1}", severity, msg)); } } } #endregion ILog Members #region IWebServiceRequest Members bool connected = true; public bool Connnected { get { return this.connected; } set { this.connected = value; } } public void WebServiceRequest(RequestSetttings requestSettings, out RequestResponse requestResponse) { requestResponse = this.WebServiceRequest(requestSettings); } private RequestResponse WebServiceRequest(RequestSetttings requestSettings) { RequestResponse result = new RequestResponse(requestSettings); if (connected) { result.responseCode = 200; result.body = SimpleJSON.JSON.Parse("{" + "\"authToken\": \"5a26cb5ac8b102008b41472b5a30078bc8b102008b4147589108928341\", " + "\"actor\": { \"account\": { \"homePage\": \"http://a2:3000/\", \"name\": \"Anonymous\"}, \"name\": \"test-animal-name\"}, " + "\"playerAnimalName\": \"test-animal-name\", " + "\"playerId\": \"5a30078bc8b102008b41475769103\", " + "\"objectId\": \"http://a2:3000/api/proxy/gleaner/games/5a26cb5ac8b102008b41472a/5a26cb5ac8b102008b41472b\", " + "\"session\": 1, " + "\"firstSessionStarted\": \"2017-12-12T16:44:59.273Z\", " + "\"currentSessionStarted\": \"2017-12-12T16:44:59.273Z\" " + "}").ToString(); this.Append("netstorage", requestSettings.body); } else { result.responseCode = 0; } return result; } #endregion IWebServiceRequest Members } }
#region license // Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Ayende Rahien nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; namespace Ayende.NHibernateQueryAnalyzer.UserInterface.Interfaces { public interface IView : IDisposable { /// <summary> /// Starts the wait message by the UI. The view need to check every <c>checkInterval</c> /// that the work was comleted (using <c>HasFinishedWork()</c> method). /// The work should finish in shouldWaitFor, but there is no gurantee about it. /// <c>EndWait</c> is called to end the wait. /// </summary> /// <param name="waitMessage">The Wait message.</param> /// <param name="checkInterval">Check interval.</param> /// <param name="shouldWaitFor">Should wait for.</param> void StartWait(string waitMessage, int checkInterval, int shouldWaitFor); void EndWait(string endMessage); void AddException(Exception ex); void ShowError(string error); /// <summary> /// Executes the delegate in the UI thread. /// </summary> /// <param name="d">Delegate to execute</param> /// <param name="parameters">Parameters.</param> void ExecuteInUIThread(Delegate d, params object[] parameters); bool AskYesNo(string question, string title); string Ask(string question, string answer); bool HasChanges { get; set; } bool Save(); string Title { get; set; } void Close(bool askToSave); bool SaveAs(); event EventHandler Closed; event EventHandler TitleChanged; } }
namespace Task01_TreeOfNNodes { using System; using System.Linq; internal class Startup { internal static void Main() { Console.WriteLine("N = "); var n = int.Parse(Console.ReadLine()); var nodes = new TreeNode<int>[n]; for (int i = 0; i < n; i++) { nodes[i] = new TreeNode<int>(i); } for (int i = 0; i < n - 1; i++) { Console.WriteLine("Enter parent and child node [separated by spaces] "); var input = Console.ReadLine().Split(' '); var parentValue = int.Parse(input[0]); var childValue = int.Parse(input[1]); nodes[parentValue].AddChild(nodes[childValue]); } Console.WriteLine("Root node: "); var rootNode = nodes.FirstOrDefault(x => x.HasParent == false); if (rootNode != null) { Console.WriteLine(rootNode.Value); } Console.WriteLine("Leaf nodes: "); var leafNodes = nodes.Where(x => x.Children.Count == 0).ToList(); leafNodes.ForEach(x => Console.WriteLine(x.Value)); Console.WriteLine("Middle nodes: "); var middleNodes = nodes.Where(x => x.Children.Count != 0 && x.HasParent).ToList(); middleNodes.ForEach(x => Console.WriteLine(x.Value)); Console.WriteLine("Max depth: " + TreeDepthCalculate(rootNode)); } public static int TreeDepthCalculate(TreeNode<int> root) { if (root == null) { return 0; } int maxPath = 0; foreach (var child in root.Children) { maxPath = Math.Max(maxPath, TreeDepthCalculate(child)); } return maxPath + 1; } } }
using KekManager.Domain; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace KekManager.Data.Models { public class LearningProgramModel { public int Id { get; set; } [Required] public string Name { get; set; } public string Specialization { get; set; } public int NumberOfSemesters { get; set; } public Level Level { get; set; } public Mode Mode { get; set; } public ICollection<ModuleModel> Modules { get; set; } public int CnpsHours { get; set; } public ICollection<KekModel> Keks { get; set; } } }