text
stringlengths
13
6.01M
using System; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.IE; using OpenQA.Selenium.Edge; using OpenQA.Selenium.PhantomJS; using System.Web.Configuration; using OpenQA.Selenium.Remote; using System.Threading; using BoDi; namespace FC_TestFramework.Core.Setup { public class SetupBrowser { public RemoteWebDriver Driver { get; set; } private RemoteWebDriver driver; /**Método de recuperação do Driver Selenium * e configuração do Browser de execução dos testes. * Deve ser implementado no início de cada classe Step Definitions */ public RemoteWebDriver Setup() { Console.WriteLine("Driver iniciado"); Driver = RecuperarDriver(); return Driver; } /**Método de recuperação do Driver Selenium * e configuração do Browser de execução dos testes. * Deve ser implementado no início de cada classe Step Definitions */ public RemoteWebDriver RecuperarInstancia() { return Driver; } /**Método interno da classe que deve Recuperar * o Driver Selenium conforme Browser informado */ private RemoteWebDriver RecuperarDriver() { string Browser = WebConfigurationManager.AppSettings["Browser"]; if (Browser.Equals("chrome")) { ChromeOptions Options = new ChromeOptions(); Options.AddArguments("--disable-extensions"); Options.AddArguments("--start-maximized"); ChromeDriverService Servico = ChromeDriverService.CreateDefaultService(); return Driver = new ChromeDriver(Servico, Options, TimeSpan.FromMinutes(3)); } else if (Browser.Equals("firefox")) { FirefoxOptions Options = new FirefoxOptions(); Options.AddArguments("--disable-extensions"); Options.AddArguments("--start-maximized"); FirefoxDriverService Servico = FirefoxDriverService.CreateDefaultService(); return Driver = new FirefoxDriver(Servico, Options, TimeSpan.FromMinutes(3)); } else if (Browser.Equals("ie")) { InternetExplorerOptions Options = new InternetExplorerOptions(); Options.AddAdditionalCapability("platform", "Windows"); Options.AddAdditionalCapability("version", "10"); Options.IgnoreZoomLevel = true; Options.EnableNativeEvents = false; Options.IntroduceInstabilityByIgnoringProtectedModeSettings = true; Options.EnsureCleanSession = true; Options.UnexpectedAlertBehavior = InternetExplorerUnexpectedAlertBehavior.Ignore; Options.EnableFullPageScreenshot = true; InternetExplorerDriverService Servico = InternetExplorerDriverService.CreateDefaultService(); return Driver = new InternetExplorerDriver(Servico, Options, TimeSpan.FromMinutes(3)); } else if (Browser.Equals("edge")) { EdgeOptions Options = new EdgeOptions(); Options.AddAdditionalCapability("platform", "Windows"); Options.AddAdditionalCapability("version", "10"); EdgeDriverService Servico = EdgeDriverService.CreateDefaultService(); return Driver = new EdgeDriver(Servico, Options, TimeSpan.FromMinutes(3)); } else { PhantomJSOptions Options = new PhantomJSOptions(); Options.AddAdditionalCapability("platform", "Windows"); Options.AddAdditionalCapability("version", "10"); PhantomJSDriverService Servico = PhantomJSDriverService.CreateDefaultService(); return Driver = new PhantomJSDriver(Servico, Options, TimeSpan.FromMinutes(3)); } } /**Método interno da classe que deve Navegar até * a URL específica do ambiente informado */ public void DirecionarAmbiente(string CaminhoMenu) { string Ambiente = WebConfigurationManager.AppSettings["Ambiente"]; Driver.Navigate().GoToUrl(Ambiente+"/"+CaminhoMenu); Driver.Manage().Window.Maximize(); } /**Método que encerra a sessão do Driver Selenium * e fecha o Browser. * Deve ser implementado no final de cada classe Step Definitions */ public void TearDown() { if(Driver != null) { Driver.Close(); Driver.Quit(); } Console.WriteLine("Driver finalizado."); } } }
using Project.Interface; using Project.Presenter; 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 Project.View { public partial class Signup : Form , ISignup { LoginSignupPresenter presenter; public Signup() { InitializeComponent(); presenter = new LoginSignupPresenter(this); } public string username { get { return textBox1.Text; } } public string password { get { return textBox2.Text; } } public Form currentForm { get { return this; } } public string name { get { return textBox3.Text; } } private void button2_Click(object sender, EventArgs e) { presenter.signup(); } private void minimize_btn_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; } private void close_btn_Click(object sender, EventArgs e) { this.Close(); } private void Cancel_btn_Click(object sender, EventArgs e) { this.Close(); Login Login = new Login(); Login.Show(); } } }
using System; using Alura.LeilaoOnline.Core; namespace Alura.LeilaoOnline.ConsoleApp { class Program { public static void UmLance() { //Arrange var modalidade = new MaiorValor(); var leilao = new Leilao("Van Gogh", modalidade); var fulano = new Interessada("fulano", leilao); leilao.RecebeLance(fulano, 800); var maiorLance = 800; //Act leilao.TerminaPregao(); //Assert Verifica(maiorLance, leilao.Ganhador.Valor); } public static void VariosLances() { //Arrange var modalidade = new MaiorValor(); var leilao = new Leilao("Van Gogh", modalidade); var fulano = new Interessada("fulano", leilao); var sicrano = new Interessada("sicrano", leilao); leilao.RecebeLance(fulano, 800); leilao.RecebeLance(sicrano, 900); leilao.RecebeLance(fulano, 1200); leilao.RecebeLance(sicrano, 1800); leilao.RecebeLance(fulano, 1500); var maiorLance = 1800; //Act leilao.TerminaPregao(); //Assert Verifica(maiorLance, leilao.Ganhador.Valor); } public static void Verifica (double esperado, double obtido) { var consoleColor = Console.ForegroundColor; if (obtido == esperado){ Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Success"); } else{ Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Fail"); } Console.ForegroundColor = consoleColor; } static void Main() { UmLance(); VariosLances(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using ApartmentApps.Api.Modules; using ApartmentApps.Portal.Controllers; namespace ApartmentApps.Api.ViewModels { [DisplayName("Messages")] public class MessageViewModel : BaseViewModel { public string Body { get; set; } public int SentToCount { get; set; } public DateTime? SentOn { get; set; } public int OpenCount { get; set; } public int DeliverCount { get; set; } public string TargetsXml { get; set; } public IEnumerable<MessageReceiptViewModel> Receipts { get; set; } public UserBindingModel From { get; set; } public int TargetsCount { get; set; } public string TargetsDescription { get; set; } public bool Sent { get; set; } public MessageStatus Status { get; set; } public string ErrorMessage { get; set; } } }
namespace Application.Views.Home { using System; using System.Text; using Common; using Common.Utilities; using Models.ViewModels; using SimpleMVC.Interfaces.Generic; public class Details : IRenderable<DetailsGameViewModel> { private readonly string header = Constants.HeaderHtml.GetContentByName(); private readonly string nav = Constants.NavHtml; private readonly string footer = Constants.FooterHtml.GetContentByName(); public DetailsGameViewModel Model { get; set; } public string Render() { var outputHtml = new StringBuilder(); outputHtml.AppendLine(this.header) .AppendLine(this.nav) .AppendLine( $"{this.Model}{Constants.GameDetailsForm}{Constants.GameDetailsEndHtml.GetContentByName()}") .AppendLine(this.footer); Console.WriteLine(outputHtml.ToString()); return outputHtml.ToString(); } } }
// 文 件 名:Project.cs // 功能描述:自动运行实体 // 修改描述: //----------------------------------------------------------------*/ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PlanMGMT.Model { public class Project { /// <summary> /// 项目ID /// </summary> public int ProjectID { get; set; } /// <summary> /// 项目名称 /// </summary> public string ProjectName { get; set; } /// <summary> /// 项目状态 /// </summary> public short Status { get; set; } /// <summary> /// 项目编码 /// </summary> public string ProjectCode { get; set; } /// <summary> /// 负责人 /// </summary> public string InCharge { get; set; } /// <summary> /// 计划开始时间 /// </summary> public DateTime? PlanStartTime { get; set; } /// <summary> /// 计划结束时间 /// </summary> public DateTime? PlanEndTime { get; set; } /// <summary> /// 实际开始时间 /// </summary> public DateTime? ActualStartTime { get; set; } /// <summary> /// 实际结束时间 /// </summary> public DateTime? ActualEndTime { get; set; } /// <summary> /// 项目分类 /// </summary> public string Category { get; set; } /// <summary> /// 项目大小 /// </summary> public decimal ProjectAmount { get; set; } /// <summary> /// 客户 /// </summary> public string Customer { get; set; } /// <summary> /// 客户联系人 /// </summary> public string CustomerPM { get; set; } public override string ToString() { return ProjectName; } } }
//============================================================================== // Copyright (c) 2012-2020 Fiats Inc. All rights reserved. // https://www.fiats.asia/ // using System; using System.Collections.Generic; using System.Reactive; using System.Reactive.Linq; using System.Reactive.Subjects; namespace Financial.Extensions { public static partial class RxExtensions { // ** If market data feed from source is infrequent than period, buffer feed will be delayed. // With getter method public static IObservable<IList<TSource>> BufferByPeriod<TSource>(this IObservable<TSource> source, Func<TSource, DateTime> timeGetter, TimeSpan period) { var duration = new Subject<Unit>(); return source .Scan((prev, current) => { if (timeGetter(prev).Round(period) != timeGetter(current).Round(period)) { duration.OnNext(Unit.Default); } return current; }) .Buffer(() => duration); } // Common trade class public static IObservable<IList<TSource>> BufferByPeriod<TSource>(this IObservable<TSource> source, TimeSpan period) where TSource : IExecutionStream { var duration = new Subject<Unit>(); return source .Scan((prev, current) => { if (prev.Time.Round(period) != current.Time.Round(period)) { duration.OnNext(Unit.Default); } return current; }) .Buffer(() => duration); } } }
using Core.Interface; using Core.Model; using System.Collections.Generic; using System.Linq; namespace Core.Controller { public class AchievementHandle : IAchievement { public bool AddInfo(Model.Info info) { Info origen = DataHelper<Entities, Info>.FindBy(t => t.UserId.Equals(info.UserId) && t.SubId.Equals(info.SubId)).FirstOrDefault(); if (origen != null) { origen.NumAnswer += info.NumAnswer; origen.NumAnswerTrue += info.NumAnswerTrue; origen.TimeUse += info.TimeUse; DataHelper<Entities, Info>.AddOrUpdate(info); return true; } return false; } public bool AddHistory(Model.History history) { DataHelper<Entities, History>.Add(history); return true; } public List<Model.Info> GetInfoOfUser(string userid) { return DataHelper<Entities, Info>.FindBy(t => t.UserId.Equals(userid)).ToList(); } public List<Model.History> GetHistoryOfUser(string userid) { return DataHelper<Entities, History>.FindBy(t => t.UserId.Equals(userid)).ToList(); } } }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Journey.WebApp.Data; using Microsoft.AspNetCore.Authorization; using System.Net.Http; using Journey.WebApp.Models; namespace Journey.WebApp.Views.Home { public class TravelerController : Controller { private readonly JourneyDBContext _context; private HttpClient _httpClient; private Options _options; public TravelerController(JourneyDBContext context, HttpClient httpClient, Options options) { _context = context; _httpClient = httpClient; _options = options; } // GET: Traveler/Edit/5 [Authorize] public async Task<IActionResult> Edit(long? id) { if (id == null || (int)TempData.Peek("TravelerID") != id) { return NotFound(); } var traveler = await _context.Traveler.Include(t => t.TravelerAlbum) .ThenInclude(ta => ta.AlbumPhoto) .ThenInclude(ap => ap.Photo) .FirstOrDefaultAsync(t => t.Id == id); if (traveler == null) { return NotFound(); } var profile = new ProfileViewModel { Traveler = traveler, }; var photo = await FindOrCreateProfileAlbum(traveler); ViewBag.profilePicThumb = photo?.Thumbnail; ViewBag.profilePic = photo?.FilePath; return View(profile); } // POST: Traveler/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(long id, ProfileViewModel profile) { if (id != profile.Traveler.Id) { return NotFound(); } if (ModelState.IsValid) { try { var travelerAlbum = await _context.TravelerAlbum.FirstOrDefaultAsync(ta => ta.TravelerId == profile.Traveler.Id && ta.AlbumName == "Profile Photos"); var travelerPhoto = await MyUtility.UploadPhoto(_context, _httpClient, _options, profile.Upload, travelerAlbum.Id); travelerAlbum.Thumbnail = travelerPhoto.Thumbnail; _context.Update(travelerAlbum); _context.Update(profile.Traveler); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TravelerExists(profile.Traveler.Id)) { return NotFound(); } else { throw; } } return RedirectToAction("Index", "Home"); } return View(profile); } private bool TravelerExists(long id) { return _context.Traveler.Any(e => e.Id == id); } private async Task<TravelerPhoto> FindOrCreateProfileAlbum(Traveler traveler) { var profileAlbum = traveler.TravelerAlbum.FirstOrDefault(ta => ta.AlbumName.Equals("Profile Photos")); if(profileAlbum == null) { profileAlbum = new TravelerAlbum { AlbumName = "Profile Photos", DateCreated = DateTime.Now, TravelerId = traveler.Id }; _context.TravelerAlbum.Add(profileAlbum); await _context.SaveChangesAsync(); } else { var profilePic = profileAlbum.AlbumPhoto.LastOrDefault()?.Photo; if (profilePic != null) return profilePic; } return null; } } }
using UnityEngine; using Npc; using System.Collections; using System.Collections.Generic; public class NpcCore : MonoBehaviour { // base components [HideInInspector] public Transform myTransform; [HideInInspector] public GameObject myGameObject; // spawner [HideInInspector] public NpcSpawner spawnedBy; [HideInInspector] public int spawnedByIndex; [HideInInspector] public bool isConnectedToOtherNpc; [HideInInspector] public NpcCore connectedBy; [HideInInspector] public List<NpcCore> myMinions; [HideInInspector] public NpcCore minionMaster; // boss [HideInInspector] public bool isBoss; // type [Header("type")] public Type myType; // hitbox [Header("hitbox")] public BoxCollider myHitBox; // movement [HideInInspector] public MovementTransformContainer movementTransformContainer; // minion spawn [HideInInspector] public MinionSpawnTransformContainer minionSpawnTransformContainer; // dungeon boss [HideInInspector] public NpcCore dungeonBossNpcCore; // magic skull [HideInInspector] public Transform[] eyeTransforms; [HideInInspector] public bool lostEyes; [HideInInspector] public int justLostEyesDur, justLostEyesCounter; // cannon scripts [HideInInspector] public CannonScriptContainer cannonScriptContainer; [HideInInspector] public List<CannonScript> cannonScripts; // graphics [Header("graphics")] public NpcGraphics myGraphics; // physics [HideInInspector] public Vector3 forceDirTarget, forceDirCur; [HideInInspector] public float forceDirLerpie; int hitDur, hitCounter; [HideInInspector] public bool hitButImmune; [HideInInspector] public int hitFlickerIndex, hitFlickerRate, hitFlickerCounter; // attacks [HideInInspector] public AttackData lastAttackData; [HideInInspector] public AttackData curAttackData; [HideInInspector] public int curAttackIndex; [HideInInspector] public int curAttackSprayCount, curAttackSprayCounter; [HideInInspector] public int attackFireTrailCounter; [HideInInspector] public float attackPrepareDurFac, attackDoDurFac; [HideInInspector] public float speedBoost; Coroutine curRangedAttackCoroutine; [HideInInspector] public bool overrideAttackPoint; [HideInInspector] public Vector3 attackPointOverride; [HideInInspector] public Vector3 attackDir; // unit [Header("unit")] public Unit myUnit; // physics [Header("physics")] public LayerMask bounceLayerMask; // health indicator [HideInInspector] public HealthIndicator myHealthIndicator; // particles [HideInInspector] public Vector3 particleSpawnPoint; // stats [HideInInspector] public Info myInfo; [HideInInspector] public int health; [HideInInspector] public WeightedRandomBag<AttackData> myAttackDatas; // state [HideInInspector] public int stageIndex; [HideInInspector] public bool enteredNextStage; // state public enum State { Roam, Chase, AttackPrepare, AttackDo, Alerted, Hit, Stunned, Block, LightCannon, MoveToPosition, Flee, Vulnerable, Sleeping, WakeUp, Laugh, Hide, WakeDungeonBoss, CollectFire, EnterNextStage }; public State curState; [HideInInspector] public bool inCombat; [HideInInspector] public int tearDropCount; [HideInInspector] public bool preventTearDrop; [HideInInspector] public Vector3 moveToPositionTargetPoint; [HideInInspector] public State moveToPositionEndState; [HideInInspector] public float moveToPositionStopDst; [HideInInspector] public bool autoAlerted; // alerted [HideInInspector] public int alertedDur, alertedCounter; // attack prepare [HideInInspector] public int attackPrepareCounter; [HideInInspector] public Vector3 attackPrepareDir; // block [HideInInspector] public int blockMinDur, blockMaxDur, blockDur, blockCounter; [HideInInspector] public int canBlockDur, canBlockCounter; // attack do [HideInInspector] public int attackDoCounter; [HideInInspector] public bool attackDealtDamage; // stunned [HideInInspector] public int stunnedDur, stunnedCounter; // vulnerable [HideInInspector] public int vulnerableDur, vulnerableCounter; // collect fire [HideInInspector] public int collectFireDur, collectFireCounter; public Transform fireCollectPointTransform; [HideInInspector] public int fireCollectedCount; // enter next stage [HideInInspector] public int enterNextStageDur, enterNextStageCounter; [HideInInspector] public bool clearingLava, clearedLava; [HideInInspector] public int lavaCollectCreateRate, lavaCollectCreateCounter; // wakeUp [HideInInspector] public int wakeUpDur, wakeUpCounter; [HideInInspector] public float wakeUpProgress; // laugh [HideInInspector] public int laughDur, laughCounter; [HideInInspector] public bool didLaugh; // hide [HideInInspector] public int hideDur, hideCounter; // chasing [HideInInspector] public Transform chaseTransform; // fleeing [HideInInspector] public Transform fleeTransform; // cannon [HideInInspector] public CannonScript cannonScriptTarget; // audio //[Header("audio")] //public AudioSource myAudioSource; //public Transform audioSourceTransform; //public GameObject audioSourceGameObject; AudioClip[] alertClipsUse; float alertPitchMin, alertPitchMax; float alertVolumeMin, alertVolumeMax; AudioClip[] attackPrepareClipsUse; float attackPreparePitchMin, attackPreparePitchMax; float attackPrepareVolumeMin, attackPrepareVolumeMax; AudioClip[] attackDoClipsUse; float attackDoPitchMin, attackDoPitchMax; float attackDoVolumeMin, attackDoVolumeMax; AudioClip[] hurtClipsUse; float hurtPitchMin, hurtPitchMax; float hurtVolumeMin, hurtVolumeMax; AudioClip[] deadClipsUse; float deadPitchMin, deadPitchMax; float deadVolumeMin, deadVolumeMax; // init [HideInInspector] public bool initialized; void Start () { Init(); } void Init () { // base components myTransform = transform; myGameObject = gameObject; // stage stageIndex = 0; // load stats myInfo = NpcDatabase.instance.LoadInfo(myType); health = myInfo.stats.health; // gru bestaat? if ( minionMaster != null ) { health = Mathf.FloorToInt(health * .5f); if ( health < 1 ) { health = 1; } } // become stronger? (endless mode) if (SetupManager.instance.curRunType == SetupManager.RunType.Endless) { health += (3 * SetupManager.instance.runDataRead.curLoopIndex + 1); attackPrepareDurFac = 1f - (.1f * SetupManager.instance.runDataRead.curLoopIndex); attackPrepareDurFac = Mathf.Clamp(attackPrepareDurFac, .25f, 1f); attackDoDurFac = 1f - (.1f * SetupManager.instance.runDataRead.curLoopIndex); attackDoDurFac = Mathf.Clamp(attackDoDurFac,.25f,1f); speedBoost = (.1f * SetupManager.instance.runDataRead.curLoopIndex); speedBoost = Mathf.Clamp(speedBoost,0f,2f); } else { attackPrepareDurFac = 1f; attackDoDurFac = 1f; speedBoost = 0f; } // load attackDatas myAttackDatas = new WeightedRandomBag<AttackData>(); if ( myInfo.attacks != null && myInfo.attacks.Length > 0 ) { for (int i = 0; i < myInfo.attacks.Length; i++) { myAttackDatas.AddEntry(myInfo.attacks[i],myInfo.attacks[i].weight); } } // graphics? if ( myGraphics != null ) { myGraphics.Init(); } // physics forceDirTarget = Vector3.zero; forceDirCur = forceDirTarget; forceDirLerpie = 2.5f; // hitBox if ( myHitBox != null ) { myHitBox.center += myInfo.stats.hitBoxCenterOff; myHitBox.size += myInfo.stats.hitBoxScaleFac; } // lava collect lavaCollectCreateRate = 6; lavaCollectCreateCounter = 0; // counters hitDur = 0; hitCounter = hitDur; hitFlickerIndex = 0; hitFlickerRate = 6; hitFlickerCounter = 0; // create UI prompts? GameObject newHealthIndicatorO = PrefabManager.instance.SpawnPrefabAsGameObject(PrefabManager.instance.healthIndicatorPrefab[0], Vector3.zero, Quaternion.identity, 1f); Transform newHealthIndicatorTr = newHealthIndicatorO.transform; newHealthIndicatorTr.parent = GameManager.instance.mainCanvasRectTransform; BasicFunctions.ResetTransform(newHealthIndicatorTr); RectTransform rTr = newHealthIndicatorO.GetComponent<RectTransform>(); rTr.localScale = Vector3.one; myHealthIndicator = newHealthIndicatorO.GetComponent<HealthIndicator>(); myHealthIndicator.myNpcCore = this; myHealthIndicator.HideAllContent(); // wakeUp wakeUpProgress = .25f; // state State startState; switch ( myType ) { default: startState = State.Roam; break; case Type.MagicSkull: startState = State.Sleeping; myGraphics.SetScale(wakeUpProgress); break; } if (myInfo.stats.hideOnStart) { InitSetHide(); } else { SetState(startState); } // store if (!LevelGeneratorManager.instance.activeLevelGenerator.activeNpcs.Contains(this)) { LevelGeneratorManager.instance.activeLevelGenerator.activeNpcs.Add(this); } // audio alertClipsUse = myInfo.audio.alertClips; alertPitchMin = myInfo.audio.alertPitchMin; alertPitchMax = myInfo.audio.alertPitchMax; alertVolumeMin = myInfo.audio.alertVolumeMin; alertVolumeMax = myInfo.audio.alertVolumeMax; attackPrepareClipsUse = myInfo.audio.attackPrepareClips; attackPreparePitchMin = myInfo.audio.attackPreparePitchMin; attackPreparePitchMax = myInfo.audio.attackPreparePitchMax; attackPrepareVolumeMin = myInfo.audio.attackPrepareVolumeMin; attackPrepareVolumeMax = myInfo.audio.attackPrepareVolumeMax; attackDoClipsUse = myInfo.audio.attackDoClips; attackDoPitchMin = myInfo.audio.attackDoPitchMin; attackDoPitchMax = myInfo.audio.attackDoPitchMax; attackDoVolumeMin = myInfo.audio.attackDoVolumeMin; attackDoVolumeMax = myInfo.audio.attackDoVolumeMax; hurtClipsUse = myInfo.audio.hurtClips; hurtPitchMin = myInfo.audio.hurtPitchMin; hurtPitchMax = myInfo.audio.hurtPitchMax; hurtVolumeMin = myInfo.audio.hurtVolumeMin; hurtVolumeMax = myInfo.audio.hurtVolumeMax; deadClipsUse = myInfo.audio.deadClips; deadPitchMin = myInfo.audio.deadPitchMin; deadPitchMax = myInfo.audio.deadPitchMax; deadVolumeMin = myInfo.audio.deadVolumeMin; deadVolumeMax = myInfo.audio.deadVolumeMax; // tear drop count tearDropCount = myInfo.stats.tearDropCount; // block blockMinDur = 60; blockMaxDur = 90; blockDur = Mathf.RoundToInt(TommieRandom.instance.RandomRange(blockMinDur,blockMaxDur)); blockCounter = 0; canBlockDur = 16; canBlockCounter = 0; // eyes lostEyes = false; justLostEyesDur = 24; justLostEyesCounter = justLostEyesDur; // mournful blessing if (SetupManager.instance != null && SetupManager.instance.CheckIfBlessingClaimed(BlessingDatabase.Blessing.Mournful)) { if (TommieRandom.instance.RandomValue(1f) <= .33f) { tearDropCount++; } } // no tear drop?? :( if ( preventTearDrop ) { tearDropCount = 0; } // alerted if (autoAlerted) { InitSetAlerted(); } // define starting attack PickRandomAttack(); // store boss? if ( myType == Type.HellLord ) { LevelGeneratorManager.instance.activeLevelGenerator.curBossCore = this; } // done initialized = true; } void Update () { //if ( myType == Type.MagicSkull ) //{ // Debug.Log("lost eyes: " + lostEyes.ToString() + " || " + Time.time.ToString()); //} if ( curState != State.EnterNextStage ) { SetupManager.instance.clearingLava = false; } if (initialized) { if (!SetupManager.instance.inFreeze && LevelGeneratorManager.instance.activeLevelGenerator.generatedLevel ) { // connectedBy is gone? if (myType == Type.Faerie) { isConnectedToOtherNpc = true; connectedBy = spawnedBy.dungeonBossNpcSpawner.myNpcCores[0]; if (isConnectedToOtherNpc && connectedBy == null ) { Clear(); } } // check if we're bouncing into player? CheckIfBouncingIntoPlayer(); // just lost eyes? if ( justLostEyesCounter < justLostEyesDur ) { justLostEyesCounter++; } // can block again? if ( canBlockCounter < canBlockDur ) { canBlockCounter++; } // state switch (curState) { case State.Roam: if (!inCombat) { Vector3 pp0 = myTransform.position; Vector3 pp1 = GameManager.instance.playerFirstPersonDrifter.myTransform.position; float dd0 = Vector3.Distance(pp0, pp1); float alertDst = 6f + myInfo.stats.alertDstExtra; alertDst += SetupManager.instance.playerEquipmentStatsTotal.alertDstAdd; if (dd0 <= alertDst) { InitSetAlerted(); } } break; case State.Alerted: if (alertedCounter < alertedDur) { alertedCounter++; } else { if (myInfo.stats.fleeFromPlayer) { InitSetFleeing(GameManager.instance.playerFirstPersonDrifter.myTransform); } else { InitSetChasing(GameManager.instance.playerFirstPersonDrifter.myTransform); } } break; case State.Hit: if (hitFlickerCounter < hitFlickerRate) { hitFlickerCounter++; } else { hitFlickerCounter = 0; hitFlickerIndex = (hitFlickerIndex == 0) ? 1 : 0; } if (hitCounter < hitDur) { hitCounter++; } else { StopGetHit(); } break; case State.AttackPrepare: if (attackPrepareCounter < (curAttackData.attackPrepareDur * attackPrepareDurFac)) { attackPrepareCounter++; Vector3 pp0 = myTransform.position; Vector3 pp1 = (myInfo.stats.fleeFromPlayer) ? fleeTransform.position : chaseTransform.position; Vector3 pp2 = (pp1 - pp0).normalized; pp2.y = 0f; attackPrepareDir = pp2; } else { InitSetAttackDo(); } break; case State.AttackDo: if (attackDoCounter < curAttackData.attackDoDur) { // continue attackDoCounter++; // laser is in play? if ( curAttackData.attackType == AttackData.AttackType.Ranged && curAttackData.rangedAttackType == AttackData.RangedAttackType.Laser ) { SetupManager.instance.SetLaserAttackInPlay(); } // leave fire trail? if ( curAttackData.leaveFireTrail && (attackDoCounter < ((curAttackData.attackDoDur * attackDoDurFac) * .75f)) ) { if ( attackFireTrailCounter < curAttackData.fireTrailRate ) { attackFireTrailCounter++; } else { Vector3 fireTrailP = myGraphics.bodyTransform.position; Quaternion fireTrailR = Quaternion.identity; float fireTrailScl = .125f; GameObject trailProjectileO = PrefabManager.instance.SpawnPrefabAsGameObject(curAttackData.fireTrailProjectilePrefab,fireTrailP,fireTrailR,fireTrailScl); ProjectileScript trailProjectileScript = trailProjectileO.GetComponent<ProjectileScript>(); if ( trailProjectileScript != null ) { trailProjectileScript.radius = .5f; trailProjectileScript.npcCoreBy = this; trailProjectileScript.SetOwnerType(ProjectileScript.OwnerType.Npc); trailProjectileScript.speed = 0f; trailProjectileScript.createFire = true; float offX = TommieRandom.instance.RandomRange(curAttackData.fireTrailDirOffMin.x, curAttackData.fireTrailDirOffMax.x); float offY = TommieRandom.instance.RandomRange(curAttackData.fireTrailDirOffMin.y, curAttackData.fireTrailDirOffMax.y); float offZ = TommieRandom.instance.RandomRange(curAttackData.fireTrailDirOffMin.z, curAttackData.fireTrailDirOffMax.z); Vector3 off = new Vector3(offX,offY,offZ); trailProjectileScript.dir = off; trailProjectileScript.clearDurAdd = 600; } attackFireTrailCounter = 0; } } // do attack? if (!attackDealtDamage && curAttackData.attackType == AttackData.AttackType.Melee && curAttackData.damage > 0) { float attackSpawnDamageDealFac = .175f; if (attackDoCounter >= ((curAttackData.attackDoDur * attackDoDurFac) * attackSpawnDamageDealFac)) { Vector3 d0 = myTransform.position; Vector3 d1 = chaseTransform.position; d1.y = d0.y; Vector3 d2 = (d1 - d0).normalized; Vector3 damageDealP = myTransform.position; damageDealP += (d2 * .5f); damageDealP.y += .5f; damageDealP += (myGraphics.graphicsTransform.forward * curAttackData.damageDealSpawnLocalAdd.z); damageDealP += (myGraphics.graphicsTransform.right * curAttackData.damageDealSpawnLocalAdd.x); damageDealP += (myGraphics.graphicsTransform.up * curAttackData.damageDealSpawnLocalAdd.y); PrefabManager.instance.SpawnDamageDeal(damageDealP, 1.5f + curAttackData.damageDealExtraRadius, curAttackData.damage, curAttackData.damageType, 10, myTransform, 1f, true, DamageDeal.Target.Player,this,false,false); attackDealtDamage = true; } } } else { StopAttackDo(); } break; case State.Block: if ( blockCounter < blockDur ) { blockCounter++; } else { StopBlock(); } break; case State.Stunned: if ( stunnedCounter < stunnedDur ) { stunnedCounter++; } else { StopGetStunned(); } break; case State.Vulnerable: if (vulnerableCounter < vulnerableDur) { vulnerableCounter++; } else { StopGetVulnerable(); } break; case State.CollectFire: { if (collectFireCounter < collectFireDur) { collectFireCounter++; // stop looking? if (collectFireCounter >= (collectFireDur / 3)) { bool stopLooking = false; if (!GameManager.instance.CheckIfFireInRadius(myTransform.position, 10f, 1)) { stopLooking = true; } // look for nearby fire? if (!stopLooking) { CollectFire(10f,false); } else { if (collectFireCounter < (collectFireDur - 60)) { collectFireCounter = (collectFireDur - 60); } } } } else { StopCollectFire(); } } break; case State.EnterNextStage: if (enterNextStageCounter < enterNextStageDur) { clearingLava = false; enterNextStageCounter++; if (enterNextStageCounter >= (enterNextStageDur / 4)) { SetupManager.instance.clearingLava = true; clearingLava = true; clearedLava = true; // collect all fire CollectFire(200f,true); // robes on fire if (!enteredNextStage) { // set robes on fire? if (myGraphics != null && myGraphics.robeMeshRenderers != null && myGraphics.robeMeshRenderers.Length > 0) { for (int i = 0; i < myGraphics.robeMeshRenderers.Length; i++) { MeshRenderer curRobeMeshRenderer = myGraphics.robeMeshRenderers[i]; Material[] robeMats = curRobeMeshRenderer.materials; for (int ii = 0; ii < robeMats.Length; ii++) { robeMats[ii].SetFloat("_OnFire", 1f); } curRobeMeshRenderer.materials = robeMats; } } } enteredNextStage = true; } } else { //SetupManager.instance.clearingLava = false; clearingLava = false; StopEnterNextStage(); } break; case State.WakeUp: if (wakeUpProgress < 1f) { float wakeUpScaleSpd = (.25f * Time.deltaTime); wakeUpProgress += wakeUpScaleSpd; } else { wakeUpProgress = 1f; } myGraphics.SetScale(wakeUpProgress); if (wakeUpCounter < wakeUpDur) { wakeUpCounter++; } else { StopSleeping(); } break; case State.Laugh: if (laughCounter < laughDur) { laughCounter ++; } else { didLaugh = true; SetState(State.Chase); NpcCore dungeonBossCore = spawnedBy.dungeonBossNpcSpawner.myNpcCores[0]; if (dungeonBossCore.curState == State.Sleeping) { Vector3 dungeonBossP = dungeonBossCore.myTransform.position; InitSetMoveToPosition(dungeonBossP,State.WakeDungeonBoss, 4f); myUnit.LookForPath(dungeonBossP, Grid.instance); } } break; case State.Hide: { if (hideCounter < hideDur) { Vector3 ppp0 = myTransform.position; Vector3 ppp1 = GameManager.instance.playerFirstPersonDrifter.myTransform.position; ppp1.y = ppp0.y; float ddd0 = Vector3.Distance(ppp0,ppp1); float hideContinueThreshold = 14f; if (ddd0 <= hideContinueThreshold) { hideCounter++; } } else { StopHide(); } } break; } // hit dir float forceDirTargetLerpie = 10f; if ( curState == State.Hit || curState == State.Stunned ) { forceDirTargetLerpie = 7.5f; } float forceDirCurLerpie = 5f; forceDirTarget = Vector3.Lerp(forceDirTarget, Vector3.zero, forceDirTargetLerpie * Time.deltaTime); forceDirCur = Vector3.Lerp(forceDirCur, forceDirTarget, forceDirCurLerpie * Time.deltaTime); float c0 = .25f; float y0 = .125f; Vector3 p0 = myTransform.position; Vector3 p1 = p0; p0.y += y0; p0 += forceDirCur.normalized * -c0; p1.y += y0; p1 += forceDirCur.normalized * c0; RaycastHit cHit; if (Physics.Linecast(p0, p1, out cHit, bounceLayerMask)) { float m0 = forceDirTarget.magnitude; Vector3 r0 = forceDirTarget.normalized; Vector3 r1 = -cHit.normal.normalized; r1.y = r0.y; Vector3 r2 = Vector3.Reflect(r0, r1).normalized; forceDirTarget = r2 * m0; forceDirTarget.y = 0f; forceDirCur = forceDirTarget; // particles Vector3 particlePoint = cHit.point; particlePoint.y = particleSpawnPoint.y; PrefabManager.instance.SpawnPrefab(PrefabManager.instance.whiteOrbPrefab, particlePoint, Quaternion.identity, 1.25f); // create impact particles PrefabManager.instance.SpawnPrefab(PrefabManager.instance.magicImpactParticlesPrefab[2], particlePoint, Quaternion.identity, 1f); // hit vernietigbaar? if ( cHit.transform.GetComponent<Vernietigbaar>() != null ) { Vernietigbaar hitVernietigbaar = cHit.transform.GetComponent<Vernietigbaar>(); if ( hitVernietigbaar != null ) { hitVernietigbaar.Destroy(); } } // log Debug.DrawLine(cHit.point, cHit.point + r0, Color.magenta, 5f); Debug.DrawLine(cHit.point, cHit.point + r1, Color.cyan, 5f); Debug.DrawLine(cHit.point, cHit.point + r2, Color.green, 5f); } Debug.DrawLine(p0,p1,Color.red); // particles particleSpawnPoint = myTransform.position + (Vector3.up * .25f); } } } void CollectFire ( float _radius, bool _fromLava ) { if (GameManager.instance != null && GameManager.instance.fireScripts != null && GameManager.instance.fireScripts.Count > 0) { for (int i = 0; i < GameManager.instance.fireScripts.Count; i++) { FireScript fireScriptCheck = GameManager.instance.fireScripts[i]; if (fireScriptCheck != null && fireScriptCheck.npcConnectedTo != this) { Vector3 pp0 = myTransform.position; Vector3 pp1 = fireScriptCheck.myTransform.position; pp1.y = pp0.y; float dd0 = Vector3.Distance(pp0, pp1); if (dd0 <= _radius) { bool doCollect = (TommieRandom.instance.RandomValue(1f) <= .025f); if (doCollect) { fireScriptCheck.Collect(false, this); } } } } } if ( _fromLava ) { SetupManager.instance.SetScreenShake(1); SetupManager.instance.lavaFactor = Mathf.Lerp(SetupManager.instance.lavaFactor,0f,.25f * Time.deltaTime); if (lavaCollectCreateCounter < lavaCollectCreateRate) { lavaCollectCreateCounter++; } else { Vector3 p0 = spawnedBy.enterNextStageMovePoint.myTransform.position; Vector3 p1 = TommieRandom.instance.RandomInsideSphere(); p1.y = 0f; p1.Normalize(); Vector3 p2 = p0 + (p1 * TommieRandom.instance.RandomRange(20f,40f)); GameObject fireCollectO = PrefabManager.instance.SpawnPrefabAsGameObject(PrefabManager.instance.fireCollectPrefab,p2,Quaternion.identity, 1f); FireCollectScript fireCollectScript = fireCollectO.GetComponent<FireCollectScript>(); if (fireCollectScript != null) { fireCollectScript.targetTransform = fireCollectPointTransform; fireCollectScript.npcCollectedBy = this; } lavaCollectCreateCounter = 0; } } } void CheckIfBouncingIntoPlayer () { if (curState == State.AttackDo) { if (forceDirCur.magnitude > .0125f) { float cHeight = GameManager.instance.playerFirstPersonDrifter.myTransform.position.y + .25f; float cDst = 1f + myInfo.stats.bounceIntoPlayerCheckDst; Vector3 c0 = myTransform.position; c0.y = cHeight; c0 += (forceDirCur.normalized * -cDst); Vector3 c1 = c0; c1 += (forceDirCur.normalized * cDst); if (Physics.Linecast(c0, c1, SetupManager.instance.playerLayerMask)) { //DampForce(.025f); float dampFac = .125f; forceDirTarget *= dampFac; forceDirCur *= dampFac; //Debug.Log("dampen die boel! || " + Time.time.ToString()); } Debug.DrawLine(c0, c1, Color.cyan); } } } public void IncreaseStageIndex () { stageIndex++; // robes of hell lord? } public void Heal ( int _amount ) { if (health > 0) { int maxHealth = myInfo.stats.health; if (health < maxHealth) { health += _amount; } if (health > maxHealth) { health = maxHealth; } // create UI text Vector3 indicatorHeightOff = (Vector3.up * myInfo.graphics.healthIndicatorOff); if (myInfo.graphics.flying) { Vector3 flyOffAdd = (Vector3.up * myGraphics.flyOff); indicatorHeightOff += flyOffAdd; } Vector3 damageIndicatorP = myGraphics.graphicsTransform.position + indicatorHeightOff; Transform damageIndicatorOffTr = GameManager.instance.mainCameraTransform; damageIndicatorP += (damageIndicatorOffTr.forward * myInfo.graphics.damageIndicatorLocalAdd.z); damageIndicatorP += (damageIndicatorOffTr.right * myInfo.graphics.damageIndicatorLocalAdd.x); damageIndicatorP += (damageIndicatorOffTr.up * myInfo.graphics.damageIndicatorLocalAdd.y); GameManager.instance.CreateDamageIndicatorString("heal", damageIndicatorP); // health indicator flicker if (myHealthIndicator != null) { myHealthIndicator.InitFlicker(8); } // heal audio } } public void DealDamage ( int _amount, AttackData.DamageType _type ) { int dmgAmount = _amount; if ( SetupManager.instance.playerStrong ) { dmgAmount = 100; } // check for damage boosting blessings switch ( _type ) { case AttackData.DamageType.Melee: if ( SetupManager.instance.CheckIfBlessingClaimed(BlessingDatabase.Blessing.Warrior) ) { dmgAmount+=BlessingDatabase.instance.warriorDamageBoost; }; break; case AttackData.DamageType.Magic: if ( SetupManager.instance.CheckIfBlessingClaimed(BlessingDatabase.Blessing.Sorcerer) ) { dmgAmount += BlessingDatabase.instance.sorcererDamageBoost; ; }; break; } // melee damage if (_type == AttackData.DamageType.Melee) { if ( SetupManager.instance.CheckIfBlessingClaimed(BlessingDatabase.Blessing.Sorcerer) ) { dmgAmount--; } dmgAmount += SetupManager.instance.playerEquipmentStatsTotal.meleeDamageAdd; } // magic damage if ( _type == AttackData.DamageType.Magic ) { if (SetupManager.instance.CheckIfBlessingClaimed(BlessingDatabase.Blessing.Warrior)) { dmgAmount--; } if (!SetupManager.instance.CheckIfBlessingClaimed(BlessingDatabase.Blessing.Spray)) { dmgAmount += 1; } if ( SetupManager.instance.CheckIfBlessingClaimed(BlessingDatabase.Blessing.HotFire) ) { dmgAmount += 1; } dmgAmount += SetupManager.instance.playerEquipmentStatsTotal.magicDamageAdd; } if ( SetupManager.instance.CheckIfBlessingClaimed(BlessingDatabase.Blessing.GlassCannon) ) { dmgAmount+=BlessingDatabase.instance.glassCannonDamageBoost; } if ( dmgAmount < 1 ) { dmgAmount = 1; } if (health > 0) { health -= dmgAmount; } // heal? // audio? if ( health > 0 ) { PlayHurtAudio(); } else { //audioSourceTransform.parent = null; PlayDeadAudio(); //Destroy(audioSourceGameObject,2f); } // set alerted (if not already) //if (!inCombat) //{ // InitSetAlerted(); //} // particles PrefabManager.instance.SpawnPrefab(PrefabManager.instance.whiteOrbPrefab, particleSpawnPoint, Quaternion.identity, 1.5f); // create magic impact effect PrefabManager.instance.SpawnPrefab(PrefabManager.instance.magicImpactParticlesPrefab[2], particleSpawnPoint, Quaternion.identity, 1f); // create indicator prefab Vector3 indicatorHeightOff = (Vector3.up * myInfo.graphics.healthIndicatorOff); if ( myInfo.graphics.flying ) { Vector3 flyOffAdd = (Vector3.up * myGraphics.flyOff); indicatorHeightOff += flyOffAdd; } Vector3 damageIndicatorP = myGraphics.graphicsTransform.position + indicatorHeightOff; Transform damageIndicatorOffTr = GameManager.instance.mainCameraTransform; damageIndicatorP += (damageIndicatorOffTr.forward * myInfo.graphics.damageIndicatorLocalAdd.z); damageIndicatorP += (damageIndicatorOffTr.right * myInfo.graphics.damageIndicatorLocalAdd.x); damageIndicatorP += (damageIndicatorOffTr.up * myInfo.graphics.damageIndicatorLocalAdd.y); GameManager.instance.CreateDamageIndicator(dmgAmount,damageIndicatorP); // impact type AudioManager.instance.PlayAttackImpactSound(_type); // regrow fire charges? if (_amount > 0) { Invoke("RequestFireChargeRegrows", .5f); } // health indicator flicker if (myHealthIndicator != null) { myHealthIndicator.InitFlicker(16); } // set in combat if ( !inCombat ) { chaseTransform = GameManager.instance.playerFirstPersonDrifter.myTransform; inCombat = true; } // log //Debug.Log("au ik krijg " + _amount.ToString() + " " + _type + " schade! || " + Time.time.ToString()); } void RequestFireChargeRegrows () { if (myInfo.graphics.eyeHasFireCharge) { for (int i = 0; i < myGraphics.eyeFireChargeScripts.Count; i++) { FireChargeScript fireChargeScriptCheck = myGraphics.eyeFireChargeScripts[i]; if (fireChargeScriptCheck != null && fireChargeScriptCheck.regrowWhenNpcGotHit) { fireChargeScriptCheck.Regrow(); } } } if (myInfo.graphics.mouthHasFireCharge) { for (int i = 0; i < myGraphics.mouthFireChargeScripts.Count; i++) { FireChargeScript fireChargeScriptCheck = myGraphics.mouthFireChargeScripts[i]; if (fireChargeScriptCheck != null && fireChargeScriptCheck.regrowWhenNpcGotHit) { fireChargeScriptCheck.Regrow(); } } } } public void SetDead () { SetupManager.instance.clearingLava = false; for ( int i = 0; i < tearDropCount; i ++ ) { GameObject tearO = PrefabManager.instance.SpawnPrefabAsGameObject(PrefabManager.instance.tearPrefab[0], myTransform.position, Quaternion.identity, 1f); Stuiterbaar stuiterbaarScript = tearO.GetComponent<Stuiterbaar>(); if (stuiterbaarScript != null) { float spawnSideForceOffMax = .05f; float spawnUpForceOffMax = .075f; float xDir = Mathf.Sign(TommieRandom.instance.RandomRange(-1f,1f)); float zDir = Mathf.Sign(TommieRandom.instance.RandomRange(-1f, 1f)); float xAdd = TommieRandom.instance.RandomRange(spawnSideForceOffMax * .25f, spawnSideForceOffMax); float zAdd = TommieRandom.instance.RandomRange(spawnSideForceOffMax * .25f, spawnSideForceOffMax); stuiterbaarScript.forceCur.x += (xAdd * xDir); stuiterbaarScript.forceCur.y += TommieRandom.instance.RandomRange(spawnUpForceOffMax * .5f,spawnUpForceOffMax); stuiterbaarScript.forceCur.z += (zAdd * zDir); } } if (myType == Type.Skeleton || myType == Type.RedSkeleton || myType == Type.BlackSkeleton) { GameObject bonePrefab = null; GameObject skullPrefab = null; switch (myType) { case Type.Skeleton: bonePrefab = PrefabManager.instance.whiteBonePrefab[0]; skullPrefab = PrefabManager.instance.whiteSkullPrefab[0]; break; case Type.RedSkeleton: bonePrefab = PrefabManager.instance.redBonePrefab[0]; skullPrefab = PrefabManager.instance.redSkullPrefab[0]; break; case Type.BlackSkeleton: bonePrefab = PrefabManager.instance.blackBonePrefab[0]; skullPrefab = PrefabManager.instance.blackSkullPrefab[0]; break; } // spawn bones int boneCount = 4; for (int ii = 0; ii < boneCount; ii++) { GameObject boneO = PrefabManager.instance.SpawnPrefabAsGameObject(bonePrefab, myTransform.position + (Vector3.up * .5f), Quaternion.identity, 1f); Stuiterbaar stuiterbaarScript = boneO.GetComponent<Stuiterbaar>(); if (stuiterbaarScript != null) { float spawnSideForceOffMax = .05f; float spawnUpForceOffMax = .075f; float xDir = Mathf.Sign(TommieRandom.instance.RandomRange(-1f, 1f)); float zDir = Mathf.Sign(TommieRandom.instance.RandomRange(-1f, 1f)); float xAdd = TommieRandom.instance.RandomRange(spawnSideForceOffMax * .25f, spawnSideForceOffMax); float zAdd = TommieRandom.instance.RandomRange(spawnSideForceOffMax * .25f, spawnSideForceOffMax); stuiterbaarScript.forceCur.x += (xAdd * xDir); stuiterbaarScript.forceCur.y += TommieRandom.instance.RandomRange(spawnUpForceOffMax * .5f, spawnUpForceOffMax); stuiterbaarScript.forceCur.z += (zAdd * zDir); stuiterbaarScript.autoClearDur = Mathf.RoundToInt(TommieRandom.instance.RandomRange(240f, 300f)); } } // spawn skull int skullCount = 1; for (int ii = 0; ii < skullCount; ii++) { GameObject skullO = PrefabManager.instance.SpawnPrefabAsGameObject(skullPrefab, myTransform.position + (Vector3.up * .5f), Quaternion.identity, 1f); Stuiterbaar stuiterbaarScript = skullO.GetComponent<Stuiterbaar>(); if (stuiterbaarScript != null) { float spawnSideForceOffMax = .05f; float spawnUpForceOffMax = .075f; float xDir = Mathf.Sign(TommieRandom.instance.RandomRange(-1f, 1f)); float zDir = Mathf.Sign(TommieRandom.instance.RandomRange(-1f, 1f)); float xAdd = TommieRandom.instance.RandomRange(spawnSideForceOffMax * .25f, spawnSideForceOffMax); float zAdd = TommieRandom.instance.RandomRange(spawnSideForceOffMax * .25f, spawnSideForceOffMax); stuiterbaarScript.forceCur.x += (xAdd * xDir); stuiterbaarScript.forceCur.y += TommieRandom.instance.RandomRange(spawnUpForceOffMax * .5f, spawnUpForceOffMax); stuiterbaarScript.forceCur.z += (zAdd * zDir); stuiterbaarScript.autoClearDur = Mathf.RoundToInt(TommieRandom.instance.RandomRange(240f,300f)); } } } if ( spawnedBy != null ) { spawnedBy.myNpcsDefeated[spawnedByIndex] = true; } // is a minion? if ( minionMaster != null ) { minionMaster.RemoveMinion(this); } // drop a key? bool dropKey = false; if ( myType == Type.RatKing || myType == Type.MagicSkull ) { dropKey = true; } if ( dropKey ) { Vector3 keySpawnPos = myTransform.position + (Vector3.up * .75f); for (int i = 0; i < 1; i++) { GameObject keyO = PrefabManager.instance.SpawnPrefabAsGameObject(PrefabManager.instance.keyPrefab[0], keySpawnPos, Quaternion.identity, 1f); Stuiterbaar stuiterbaarScript = keyO.GetComponent<Stuiterbaar>(); if (stuiterbaarScript != null) { float spawnSideForceOffMax = .05f; float spawnUpForceOffMax = .075f; float xDir = Mathf.Sign(TommieRandom.instance.RandomRange(-1f, 1f)); float zDir = Mathf.Sign(TommieRandom.instance.RandomRange(-1f, 1f)); float xAdd = TommieRandom.instance.RandomRange(spawnSideForceOffMax * .25f, spawnSideForceOffMax); float zAdd = TommieRandom.instance.RandomRange(spawnSideForceOffMax * .25f, spawnSideForceOffMax); stuiterbaarScript.forceCur.x += (xAdd * xDir); stuiterbaarScript.forceCur.y += TommieRandom.instance.RandomRange(spawnUpForceOffMax * .5f, spawnUpForceOffMax); stuiterbaarScript.forceCur.z += (zAdd * zDir); } } } // explode? if ( SetupManager.instance.CheckIfItemSpecialActive(EquipmentDatabase.Specials.EnemiesExplodeOnDefeat) ) { PrefabManager.instance.SpawnPrefab(PrefabManager.instance.whiteOrbPrefab,myTransform.position,Quaternion.identity,2f); PrefabManager.instance.SpawnDamageDeal(myTransform.position, 2f, 1, AttackData.DamageType.Magic, 10, HandManager.instance.myTransform, .325f, true, DamageDeal.Target.AI, null, false, false); AudioManager.instance.PlaySoundAtPosition(myTransform.position, BasicFunctions.PickRandomAudioClipFromArray(AudioManager.instance.cannonImpactClips), .9f, 1.1f, .3f, .325f); //// create UI text //Vector3 indicatorHeightOff = (Vector3.up * myInfo.graphics.healthIndicatorOff); //if (myInfo.graphics.flying) //{ // Vector3 flyOffAdd = (Vector3.up * myGraphics.flyOff); // indicatorHeightOff += flyOffAdd; //} //Vector3 damageIndicatorP = myGraphics.graphicsTransform.position + indicatorHeightOff; //Transform damageIndicatorOffTr = GameManager.instance.mainCameraTransform; //damageIndicatorP += (damageIndicatorOffTr.forward * myInfo.graphics.damageIndicatorLocalAdd.z); //damageIndicatorP += (damageIndicatorOffTr.right * myInfo.graphics.damageIndicatorLocalAdd.x); //damageIndicatorP += (damageIndicatorOffTr.up * myInfo.graphics.damageIndicatorLocalAdd.y); //GameManager.instance.CreateDamageIndicatorString("explode", damageIndicatorP); } // drop extra tear? if (SetupManager.instance.CheckIfItemSpecialActive(EquipmentDatabase.Specials.EnemiesDropExtraTear)) { GameObject tearO = PrefabManager.instance.SpawnPrefabAsGameObject(PrefabManager.instance.tearPrefab[0], myTransform.position, Quaternion.identity, 1f); Stuiterbaar stuiterbaarScript = tearO.GetComponent<Stuiterbaar>(); if (stuiterbaarScript != null) { float spawnSideForceOffMax = .05f; float spawnUpForceOffMax = .075f; float xDir = Mathf.Sign(TommieRandom.instance.RandomRange(-1f, 1f)); float zDir = Mathf.Sign(TommieRandom.instance.RandomRange(-1f, 1f)); float xAdd = TommieRandom.instance.RandomRange(spawnSideForceOffMax * .25f, spawnSideForceOffMax); float zAdd = TommieRandom.instance.RandomRange(spawnSideForceOffMax * .25f, spawnSideForceOffMax); stuiterbaarScript.forceCur.x += (xAdd * xDir); stuiterbaarScript.forceCur.y += TommieRandom.instance.RandomRange(spawnUpForceOffMax * .5f, spawnUpForceOffMax); stuiterbaarScript.forceCur.z += (zAdd * zDir); } } // drop extra coin? if (SetupManager.instance.CheckIfItemSpecialActive(EquipmentDatabase.Specials.EnemiesDropExtraCoin)) { GameObject tearO = PrefabManager.instance.SpawnPrefabAsGameObject(PrefabManager.instance.coinPrefab[0], myTransform.position, Quaternion.identity, 1f); Stuiterbaar stuiterbaarScript = tearO.GetComponent<Stuiterbaar>(); if (stuiterbaarScript != null) { float spawnSideForceOffMax = .05f; float spawnUpForceOffMax = .075f; float xDir = Mathf.Sign(TommieRandom.instance.RandomRange(-1f, 1f)); float zDir = Mathf.Sign(TommieRandom.instance.RandomRange(-1f, 1f)); float xAdd = TommieRandom.instance.RandomRange(spawnSideForceOffMax * .25f, spawnSideForceOffMax); float zAdd = TommieRandom.instance.RandomRange(spawnSideForceOffMax * .25f, spawnSideForceOffMax); stuiterbaarScript.forceCur.x += (xAdd * xDir); stuiterbaarScript.forceCur.y += TommieRandom.instance.RandomRange(spawnUpForceOffMax * .5f, spawnUpForceOffMax); stuiterbaarScript.forceCur.z += (zAdd * zDir); } } // draaaaaain gang if ( SetupManager.instance.CheckIfBlessingClaimed(BlessingDatabase.Blessing.Drainer) ) { if ( TommieRandom.instance.RandomValue(1f) <= .05f ) { GameManager.instance.AddPlayerHealth(1); // create UI text Vector3 indicatorHeightOff = (Vector3.up * myInfo.graphics.healthIndicatorOff); if (myInfo.graphics.flying) { Vector3 flyOffAdd = (Vector3.up * myGraphics.flyOff); indicatorHeightOff += flyOffAdd; } Vector3 damageIndicatorP = myGraphics.graphicsTransform.position + indicatorHeightOff; Transform damageIndicatorOffTr = GameManager.instance.mainCameraTransform; damageIndicatorP += (damageIndicatorOffTr.forward * myInfo.graphics.damageIndicatorLocalAdd.z); damageIndicatorP += (damageIndicatorOffTr.right * myInfo.graphics.damageIndicatorLocalAdd.x); damageIndicatorP += (damageIndicatorOffTr.up * myInfo.graphics.damageIndicatorLocalAdd.y); GameManager.instance.CreateDamageIndicatorString("drained", damageIndicatorP); } } // drain item effect? if (SetupManager.instance.CheckIfItemSpecialActive(EquipmentDatabase.Specials.DrainHealth)) { GameManager.instance.AddPlayerHealth(1); // create UI text Vector3 indicatorHeightOff = (Vector3.up * myInfo.graphics.healthIndicatorOff); if (myInfo.graphics.flying) { Vector3 flyOffAdd = (Vector3.up * myGraphics.flyOff); indicatorHeightOff += flyOffAdd; } Vector3 damageIndicatorP = myGraphics.graphicsTransform.position + indicatorHeightOff; Transform damageIndicatorOffTr = GameManager.instance.mainCameraTransform; damageIndicatorP += (damageIndicatorOffTr.forward * myInfo.graphics.damageIndicatorLocalAdd.z); damageIndicatorP += (damageIndicatorOffTr.right * myInfo.graphics.damageIndicatorLocalAdd.x); damageIndicatorP += (damageIndicatorOffTr.up * myInfo.graphics.damageIndicatorLocalAdd.y); GameManager.instance.CreateDamageIndicatorString("drained", damageIndicatorP); } // fire charge item effect? if (SetupManager.instance.CheckIfItemSpecialActive(EquipmentDatabase.Specials.FireCharge)) { GameManager.instance.AddPlayerFire(1); // create UI text Vector3 indicatorHeightOff = (Vector3.up * myInfo.graphics.healthIndicatorOff); if (myInfo.graphics.flying) { Vector3 flyOffAdd = (Vector3.up * myGraphics.flyOff); indicatorHeightOff += flyOffAdd; } Vector3 damageIndicatorP = myGraphics.graphicsTransform.position + indicatorHeightOff; Transform damageIndicatorOffTr = GameManager.instance.mainCameraTransform; damageIndicatorP += (damageIndicatorOffTr.forward * myInfo.graphics.damageIndicatorLocalAdd.z); damageIndicatorP += (damageIndicatorOffTr.right * myInfo.graphics.damageIndicatorLocalAdd.x); damageIndicatorP += (damageIndicatorOffTr.up * myInfo.graphics.damageIndicatorLocalAdd.y); GameManager.instance.CreateDamageIndicatorString("charged", damageIndicatorP); } // audio AudioManager.instance.PlaySoundAtPosition(myTransform.position,BasicFunctions.PickRandomAudioClipFromArray(AudioManager.instance.enemyClearClips),.9f,1.1f,.3f,.325f); // freeze because it was an important defeat?? if ( myType == Type.RatKing || myType == Type.MagicSkull || myType == Type.HellLord ) { SetupManager.instance.SetFreeze(SetupManager.instance.bossDefeatFreeze); } // was final boss? if (!SetupManager.instance.defeatedFinalBoss) { if (myType == Type.HellLord) { SetupManager.instance.defeatedFinalBoss = true; SetupManager.instance.RequestProceedToOutro(); } } // doeg Clear(); } public void SetState ( State _to ) { curState = _to; switch ( _to ) { case State.WakeDungeonBoss: InitWakeDungeonBoss(); break; } // log //if (myType == Type.HellLord) //{ // Debug.Log("set " + myInfo.stats.name + " state to: " + _to + " || " + Time.time.ToString()); //} } public void PickRandomAttack () { switch (myType) { default: PickRandomAttackData(); break; case Type.MagicSkull: MagicSkullPickAttackData(); break; case Type.HellLord: HellLordPickAttackData(); break; } } public void StopSleeping () { myGraphics.SetScale(1f); SetState(State.Roam); } public void InitGetStunned ( Vector3 _dir, float _speed, int _duration ) { PickRandomAttack(); forceDirLerpie = 2.5f; AddForce(_dir,_speed); stunnedDur = _duration; stunnedCounter = 0; myUnit.StopMoving(); SetState(State.Stunned); // audio PlayHurtAudio(); } public void StopGetStunned() { forceDirTarget = Vector3.zero; forceDirCur = forceDirTarget; if (inCombat) { SetState((!myInfo.stats.fleeFromPlayer) ? State.Chase : State.Flee); } else { SetState(State.Roam); } } public void InitGetVulnerable ( int _duration ) { PickRandomAttack(); vulnerableDur = _duration; vulnerableCounter = 0; myUnit.StopMoving(); SetState(State.Vulnerable); // audio PlayHurtAudio(); } public void StopGetVulnerable () { if (inCombat) { SetState((!myInfo.stats.fleeFromPlayer) ? State.Chase : State.Flee); } else { SetState(State.Roam); } } public void InitSetCollectFire () { // define starting attack PickRandomAttack(); fireCollectedCount = 0; collectFireDur = 300; collectFireCounter = 0; forceDirLerpie = 2.5f; myUnit.StopMoving(); SetState(State.CollectFire); } public void StopCollectFire () { PickRandomAttack(); if (inCombat) { SetState((!myInfo.stats.fleeFromPlayer) ? State.Chase : State.Flee); } else { SetState(State.Roam); } } public void InitSetEnterNextStage () { PickRandomAttack(); enterNextStageDur = 900; enterNextStageCounter = 0; enteredNextStage = false; forceDirLerpie = 2.5f; myUnit.StopMoving(); SetState(State.EnterNextStage); // log //Debug.Log("enter next stage! || " + Time.time.ToString()); } public void StopEnterNextStage () { PickRandomAttack(); enteredNextStage = false; if (inCombat) { SetState((!myInfo.stats.fleeFromPlayer) ? State.Chase : State.Flee); } else { SetState(State.Roam); } } public void InitGetHit ( Vector3 _dir, float _speed, int _duration, bool _immune ) { PickRandomAttack(); forceDirLerpie = 2.5f; hitButImmune = _immune; hitDur = _duration; hitCounter = 0; hitFlickerIndex = 0; hitFlickerCounter = 0; myUnit.StopMoving(); SetState(State.Hit); Vector3 d = _dir; float sideDir = Mathf.Sign(TommieRandom.instance.RandomRange(-1f,1f)); float sideOffMax = .25f; float sideAdd = TommieRandom.instance.RandomRange(0f,sideOffMax) * sideDir; d += (myGraphics.graphicsTransform.right * sideAdd); AddForce(d,_speed * .375f); // faerie? if (myType == Type.Faerie) { NpcCore dungeonBossCore = spawnedBy.dungeonBossNpcSpawner.myNpcCores[0]; if (dungeonBossCore.curState == State.Sleeping) { didLaugh = false; } } } public void StopGetHit () { forceDirTarget = Vector3.zero; forceDirCur = forceDirTarget; if (health <= 0) { SetDead(); } else { bool preventDefaultBehaviour = false; // next stage? switch (myType) { case Type.HellLord: if (stageIndex == 0) { bool enterNextStage = (health <= (myInfo.stats.health / 2)); if (enterNextStage) { stageIndex++; InitSetEnterNextStage(); preventDefaultBehaviour = true; } } break; } if (!preventDefaultBehaviour) { if (inCombat) { SetState((!myInfo.stats.fleeFromPlayer) ? State.Chase : State.Flee); } else { SetState(State.Roam); } } } } public void InitSetHide () { hideCounter = 0; hideDur = 180; SetState(State.Hide); myGraphics.SetGraphicsObject(false); } public void StopHide () { myGraphics.SetGraphicsObject(true); SetState(State.Roam); // 1 witte orb svp PrefabManager.instance.SpawnPrefab(PrefabManager.instance.whiteOrbPrefab,myGraphics.bodyTransform.position,Quaternion.identity,3f); } public void InitSetLaugh () { laughCounter = 0; laughDur = 120; SetState(State.Laugh); // audio AudioManager.instance.PlaySoundAtPosition(myTransform.position + myInfo.stats.hitBoxCenterOff,BasicFunctions.PickRandomAudioClipFromArray(AudioManager.instance.faerieLaughClips),.7f,.8f,.3f,.325f,2f + myInfo.audio.distanceAdd,8f + myInfo.audio.distanceAdd); } public void InitSetWakeUp () { wakeUpCounter = 0; wakeUpDur = 180; SetState(State.WakeUp); PrefabManager.instance.SpawnPrefab(PrefabManager.instance.whiteOrbPrefab,myTransform.position,Quaternion.identity,3f); SetupManager.instance.SetFreeze(24); // audio AudioManager.instance.PlaySoundAtPosition(myTransform.position + myInfo.stats.hitBoxCenterOff, BasicFunctions.PickRandomAudioClipFromArray(AudioManager.instance.magicSkullAwokenClips), .6f, .7f, .5f, .525f, 2f + myInfo.audio.distanceAdd, 8f + myInfo.audio.distanceAdd); } public void InitSetAlerted () { myUnit.StopMoving(); alertedDur = 24; alertedCounter = 0; SetState(State.Alerted); inCombat = true; // create indicator CreateAlertIndicator(); // audio PlayAlertedAudio(); } public void InitSetChasing ( Transform _targetTransform ) { chaseTransform = _targetTransform; SetState(State.Chase); // store AddPlayerInCombatWith(); } public void InitSetFleeing ( Transform _targetTransform ) { fleeTransform = _targetTransform; SetState(State.Flee); // store AddPlayerInCombatWith(); } public void SetCannonTarget ( CannonScript _cannonScriptTarget ) { cannonScriptTarget = _cannonScriptTarget; } public void InitSetCannonLight (CannonScript _cannonScriptTarget ) { PickSpecificAttackData(Npc.AttackData.AttackType.Ranged); Vector3 cannonP = cannonScriptTarget.ropeLinePointsCur[cannonScriptTarget.ropeLinePointsCur.Length - 1]; InitSetAttackPrepare(true, cannonP); SetState(State.LightCannon); } public void InitSetMoveToPosition ( Vector3 _pos, State _endState, float _stopDst ) { moveToPositionTargetPoint = _pos; moveToPositionEndState = _endState; moveToPositionStopDst = _stopDst; myUnit.moveToPositionWaitDur = 30; myUnit.moveToPositionWaitCounter = 0; SetState(State.MoveToPosition); } public void InitSetAttackPrepare ( bool _overrideAttackPoint, Vector3 _attackPointOverride ) { if (myInfo.attacks != null && myInfo.attacks.Length > 0) { if (_overrideAttackPoint) { attackPointOverride = _attackPointOverride; } overrideAttackPoint = _overrideAttackPoint; attackPrepareCounter = 0; myUnit.StopMoving(); SetState(State.AttackPrepare); // audio PlayAttackPrepareAudio(); } } public void InitSetAttackDo () { forceDirLerpie = 10f; attackDir = myGraphics.graphicsTransform.forward; //myTransform.forward; attackDir.y = 0f; attackFireTrailCounter = curAttackData.fireTrailRate; attackDoCounter = 0; attackDealtDamage = false; SetState(State.AttackDo); if ( curAttackData.attackType == AttackData.AttackType.MinionSpawn ) { if ( minionSpawnTransformContainer != null ) { for ( int i = 0; i < minionSpawnTransformContainer.minionSpawnTransforms.Count; i ++ ) { if (myMinions.Count < minionSpawnTransformContainer.minionSpawnTransforms.Count) { WeightedRandomBag<Npc.Type> npcMinionTypesPossible = new WeightedRandomBag<Type>(); for (int ii = 0; ii < curAttackData.minionSpawnDatas.Length; ii++) { npcMinionTypesPossible.AddEntry(curAttackData.minionSpawnDatas[ii].type, curAttackData.minionSpawnDatas[ii].weight); } Npc.Type spawnTypeChosen = npcMinionTypesPossible.Choose(); Transform spawnTr = minionSpawnTransformContainer.minionSpawnTransforms[i]; Vector3 spawnP = spawnTr.position; spawnP.y = myTransform.position.y; Quaternion spawnR = spawnTr.rotation; GameManager.instance.SpawnNpc(spawnTypeChosen, spawnP, spawnedBy, false, false, true, null, null, null, this); PrefabManager.instance.SpawnPrefab(PrefabManager.instance.whiteOrbPrefab, spawnP, spawnR, 2f); } } } attackDealtDamage = true; // audio AudioManager.instance.PlaySoundAtPosition(myTransform.position,BasicFunctions.PickRandomAudioClipFromArray(AudioManager.instance.spawnMinionClips),.7f,.9f,.5f,.525f, 2f + myInfo.audio.distanceAdd, 8f + myInfo.audio.distanceAdd); } Vector3 p0 = myTransform.position; Vector3 p1 = GameManager.instance.playerFirstPersonDrifter.myTransform.position; if ( overrideAttackPoint ) { p1 = attackPointOverride; } p1.y = p0.y; float dstToPlayer = Vector3.Distance(p0,p1); float dstToPlayerFac = Mathf.Clamp(dstToPlayer * .5f,.1f,1f); Vector3 r0 = myTransform.position; Vector3 r1 = ( myInfo.stats.fleeFromPlayer ) ? fleeTransform.position : chaseTransform.position; if (overrideAttackPoint) { r1 = attackPointOverride; } r1.y = r0.y; Vector3 r2 = (r1 - r0).normalized; AddForce(r2, (4f * curAttackData.fwdForceFac) * dstToPlayerFac); // laser? if (curAttackData.attackType == AttackData.AttackType.Ranged && curAttackData.rangedAttackType == AttackData.RangedAttackType.Laser ) { SetupManager.instance.SetLaserAttackInPlay(); } // spawn projectile if (curAttackData.attackType == AttackData.AttackType.Ranged || curAttackData.attackType == AttackData.AttackType.WakeBoss) { int shootCount; switch ( curAttackData.rangedShootFromType ) { default: shootCount = 1; break; case AttackData.RangedShootFromType.Eye: shootCount = myGraphics.eyeTransforms.Length; break; case AttackData.RangedShootFromType.Mouth: shootCount = 1; break; } int repeat = (curAttackData.rangedAttackType == AttackData.RangedAttackType.Single || curAttackData.rangedAttackType == AttackData.RangedAttackType.Laser ) ? 1 : curAttackData.sprayCount; StartCoroutine(ShootProjectile(shootCount,repeat)); } // heal self? if ( curAttackData.attackType == AttackData.AttackType.HealSelf ) { Heal(curAttackData.healAmount); } // heal others? if ( curAttackData.attackType == AttackData.AttackType.HealRadius ) { if ( LevelGeneratorManager.instance.activeLevelGenerator.activeNpcs != null && LevelGeneratorManager.instance.activeLevelGenerator.activeNpcs.Count > 0 ) { for ( int i = 0; i < LevelGeneratorManager.instance.activeLevelGenerator.activeNpcs.Count; i ++ ) { NpcCore npcHeal = LevelGeneratorManager.instance.activeLevelGenerator.activeNpcs[i]; if ( npcHeal != null && npcHeal != this ) { Vector3 healP0 = myTransform.position; Vector3 healP1 = npcHeal.myTransform.position; healP1.y = healP0.y; float d0 = Vector3.Distance(healP0,healP1); if ( d0 <= curAttackData.healRadius ) { npcHeal.Heal(curAttackData.healAmount); } } } } } // store this attack lastAttackData = curAttackData; // audio PlayAttackDoAudio(); } IEnumerator ShootProjectile ( int _shootCount, int _repeat ) { while ( curAttackSprayCounter < curAttackData.sprayInterval ) { while (SetupManager.instance.inFreeze) { yield return null; } curAttackSprayCounter++; yield return null; } while (curAttackSprayCount < _repeat) { if ( curAttackSprayCount > 0 ) { PlayAttackDoAudio(); } for (int i = 0; i < _shootCount; i++) { Vector3 projectileSpawnPos; switch (curAttackData.rangedShootFromType) { // shoot from default position default: projectileSpawnPos = myTransform.position + (Vector3.up * .5f); projectileSpawnPos += myTransform.forward * .5f; break; // shoot from eye(s) case AttackData.RangedShootFromType.Eye: projectileSpawnPos = eyeTransforms[i].position; projectileSpawnPos += myTransform.forward * .5f; break; // shoot from mouth case AttackData.RangedShootFromType.Mouth: projectileSpawnPos = myGraphics.mouthProjectileSpawnTransform.position; //myGraphics.mouthTransforms[0].position; projectileSpawnPos += myTransform.forward * .5f; break; } if (curAttackData.rangedAttackType == AttackData.RangedAttackType.Laser) { Quaternion laserSpawnRot = Quaternion.identity; GameObject laserO = PrefabManager.instance.SpawnPrefabAsGameObject(curAttackData.projectilePrefab, myGraphics.mouthProjectileSpawnTransform.position, laserSpawnRot, .125f); LaserScript laserScript = laserO.GetComponent<LaserScript>(); Vector3 shootPointTargetStart = (myTransform.position + (myGraphics.graphicsTransform.forward * 1.25f)); shootPointTargetStart.y = 0f; laserScript.shootPointTarget = shootPointTargetStart; laserScript.shootPointCur = shootPointTargetStart; laserScript.targetPlayer = true; laserScript.clearDur = Mathf.RoundToInt(curAttackData.attackDoDur * attackDoDurFac); laserScript.npcCoreBy = this; laserScript.shootFromTransform = myGraphics.mouthProjectileSpawnTransform; } else { Quaternion projectileSpawnRot = Quaternion.identity; GameObject projectileO = PrefabManager.instance.SpawnPrefabAsGameObject(curAttackData.projectilePrefab, projectileSpawnPos, projectileSpawnRot, .125f); if (projectileO != null) { Transform projectileTr = projectileO.transform; // magic projectile? if (projectileO.GetComponent<ProjectileScript>() != null) { ProjectileScript projectileScript = projectileO.GetComponent<ProjectileScript>(); Vector3 d2 = attackDir.normalized; d2 += (Vector3.up * .325f); if (curAttackData.facePlayer) { Vector3 pp0 = myTransform.position; Vector3 pp1 = GameManager.instance.playerFirstPersonDrifter.myTransform.position; pp1.y = pp0.y; Vector3 pp2 = (pp1 - pp0).normalized; d2 = pp2; } d2 += (myTransform.forward * TommieRandom.instance.RandomRange(curAttackData.rangedFwdOffMax.x, curAttackData.rangedFwdOffMax.y)); d2 += (myTransform.right * TommieRandom.instance.RandomRange(curAttackData.rangedSideOffMax.x, curAttackData.rangedSideOffMax.y)); d2 += (myTransform.up * TommieRandom.instance.RandomRange(curAttackData.rangedUpOffMax.x, curAttackData.rangedUpOffMax.y)); projectileScript.dir = d2; projectileScript.speed = (7f * curAttackData.rangedSpeedFactor); projectileScript.radius = .25f; projectileScript.gravityMultiplier *= curAttackData.rangedGravityFactor; projectileScript.npcCoreBy = this; projectileScript.SetOwnerType(ProjectileScript.OwnerType.Npc); if ( myType == Type.Faerie ) { projectileScript.isFromFaerie = true; } } else if (projectileO.GetComponent<Stuiterbaar>() != null) { projectileTr.localScale = Vector3.one; Stuiterbaar stuiterbaarScript = projectileO.GetComponent<Stuiterbaar>(); Vector3 d2 = attackDir.normalized; d2 += (Vector3.up * .325f); if (curAttackData.facePlayer) { Vector3 pp0 = myTransform.position; Vector3 pp1 = GameManager.instance.playerFirstPersonDrifter.myTransform.position; pp1.y = pp0.y; Vector3 pp2 = (pp1 - pp0).normalized; d2 = pp2; } d2 += (myTransform.forward * TommieRandom.instance.RandomRange(curAttackData.rangedFwdOffMax.x, curAttackData.rangedFwdOffMax.y)); d2 += (myTransform.right * TommieRandom.instance.RandomRange(curAttackData.rangedSideOffMax.x, curAttackData.rangedSideOffMax.y)); d2 += (myTransform.up * TommieRandom.instance.RandomRange(curAttackData.rangedUpOffMax.x, curAttackData.rangedUpOffMax.y)); d2 += (Vector3.up * 1f); stuiterbaarScript.forceCur = (d2 * curAttackData.rangedSpeedFactor) * .1f; stuiterbaarScript.gravityMultiplier = curAttackData.rangedGravityFactor; stuiterbaarScript.npcCoreBy = this; stuiterbaarScript.dealDamage = true; stuiterbaarScript.SetOwnerType(ProjectileScript.OwnerType.Npc); stuiterbaarScript.autoClear = true; stuiterbaarScript.autoClearDur = 600; // log //Debug.Log("botje || " + Time.time.ToString()); } } } } curAttackSprayCount++; curAttackSprayCounter = 0; yield return new WaitForSeconds((1f / 60f) * curAttackData.sprayInterval); } } public void LoseEyes () { if (!lostEyes) { PickRandomAttack(); Vector3 d0 = myTransform.position; Vector3 d1 = GameManager.instance.playerFirstPersonDrifter.myTransform.position; d1.y = d0.y; Vector3 d2 = (d1 - d0).normalized; AddForce(d2,-4f); InitGetStunned(-d2,6f,60); justLostEyesCounter = 0; lostEyes = true; } } public void StopAttackDo () { if (inCombat) { SetState((!myInfo.stats.fleeFromPlayer) ? State.Chase : State.Flee); } else { SetState(State.Roam); } myUnit.StopMoving(); PickRandomAttack(); } public void InitSetBlock () { blockDur = Mathf.RoundToInt(TommieRandom.instance.RandomRange(blockMinDur,blockMaxDur)); blockCounter = 0; myUnit.StopMoving(); SetState(State.Block); // audio AudioManager.instance.PlaySoundAtPosition(myTransform.position,BasicFunctions.PickRandomAudioClipFromArray(attackPrepareClipsUse), attackPreparePitchMin, attackPreparePitchMax, attackPrepareVolumeMin, attackPrepareVolumeMax, 2f + myInfo.audio.distanceAdd, 8f + myInfo.audio.distanceAdd); } public void InitBlockReact (float _blockDelay) { Invoke("BlockReact",_blockDelay); } void BlockReact () { StopBlock(); InitSetAttackPrepare(false,Vector3.zero); } public void StopBlock () { canBlockCounter = 0; blockCounter = blockDur; SetState((!myInfo.stats.fleeFromPlayer) ? State.Chase : State.Flee); } public void InitWakeDungeonBoss () { PickSpecificAttackData(Npc.AttackData.AttackType.WakeBoss); Transform dungeonBossTr = spawnedBy.dungeonBossNpcSpawner.myNpcCores[0].myTransform; Vector3 dungeonBossP = dungeonBossTr.position; InitSetAttackPrepare(true, dungeonBossP); // flee after this? fleeTransform = dungeonBossTr;//GameManager.instance.playerFirstPersonDrifter.myTransform; myInfo.stats.fleeFromPlayer = true; } public void AddForce ( Vector3 _dir, float _speed ) { Vector3 f = _dir; f.x *= _speed; f.y *= _speed; f.z *= _speed; f.y = 0f; forceDirTarget = f; forceDirCur = forceDirTarget; // log //Debug.DrawLine(myRigidbody.position,myRigidbody.position + f,Color.white,5f); } public void DampForce ( float _f ) { forceDirTarget *= _f; } public void CreateAlertIndicator () { GameObject newAlertIndicatorO = PrefabManager.instance.SpawnPrefabAsGameObject(PrefabManager.instance.alertIndicatorPrefab[0], myTransform.position, Quaternion.identity, 1f); Transform newAlertIndicatorTr = newAlertIndicatorO.transform; newAlertIndicatorTr.parent = GameManager.instance.mainCanvasRectTransform; BasicFunctions.ResetTransform(newAlertIndicatorTr); RectTransform rTr = newAlertIndicatorO.GetComponent<RectTransform>(); rTr.localScale = Vector3.one; AlertIndicator newAlertIndicatorScript = newAlertIndicatorO.GetComponent<AlertIndicator>(); newAlertIndicatorScript.myNpcCore = this; } public void Clear () { // create white orb if (myType == Type.RatKing || myType == Type.MagicSkull || myType == Type.HellLord) { GameObject bossExplosionO = PrefabManager.instance.SpawnPrefabAsGameObject(PrefabManager.instance.bossExplosionPrefab, particleSpawnPoint + myInfo.stats.defeatWhiteOrbOffset,Quaternion.identity,1f); if ( bossExplosionO != null ) { BossExplosion bossExplosionScript = bossExplosionO.GetComponent<BossExplosion>(); if ( bossExplosionScript != null ) { bossExplosionScript.orbRadius = (2f + myInfo.stats.defeatWhiteOrbScaleFactor); } } } else { PrefabManager.instance.SpawnPrefab(PrefabManager.instance.whiteOrbPrefab, particleSpawnPoint + myInfo.stats.defeatWhiteOrbOffset, Quaternion.identity, 2f + myInfo.stats.defeatWhiteOrbScaleFactor); } // remove health indicator if ( myHealthIndicator != null ) { myHealthIndicator.Clear(); } // remove from list of active npcs if (LevelGeneratorManager.instance.activeLevelGenerator.activeNpcs.Contains(this)) { LevelGeneratorManager.instance.activeLevelGenerator.activeNpcs.Remove(this); } // weg met die vieze voeten if ( myInfo.graphics.hasFeet ) { if ( myGraphics.feetObjects != null && myGraphics.feetObjects.Length > 0 ) { for ( int i = myGraphics.feetObjects.Length - 1; i >= 0; i -- ) { Destroy(myGraphics.feetObjects[i]); } } } // DOEI HANDEN DOEEEHOEEI if (myInfo.graphics.hasHand) { if (myGraphics.handObjects != null && myGraphics.handObjects.Length > 0) { for (int i = myGraphics.handObjects.Length - 1; i >= 0; i--) { Destroy(myGraphics.handObjects[i]); } } } // zeg maar dag tegen die vleugels if (myInfo.graphics.hasWings) { if (myGraphics.wingObjects != null && myGraphics.wingObjects.Length > 0) { for (int i = myGraphics.wingObjects.Length - 1; i >= 0; i--) { Destroy(myGraphics.wingObjects[i]); } } } // fire charge objecten? if ( myInfo.graphics.eyeHasFireCharge ) { if ( myGraphics.eyeFireChargeObjects.Count > 0 ) { for ( int i = myGraphics.eyeFireChargeObjects.Count - 1; i >= 0; i -- ) { Destroy(myGraphics.eyeFireChargeObjects[i]); } } } // mouth charge objecten? if (myInfo.graphics.mouthHasFireCharge) { if (myGraphics.mouthFireChargeObjects.Count > 0) { for (int i = myGraphics.mouthFireChargeObjects.Count - 1; i >= 0; i--) { Destroy(myGraphics.mouthFireChargeObjects[i]); } } } // equipments if (myInfo.graphics.hasEquipment) { if (myGraphics.equipmentObjects != null && myGraphics.equipmentObjects.Length > 0) { for (int i = myGraphics.equipmentObjects.Length - 1; i >= 0; i--) { if ( myGraphics.equipmentObjects[i].GetComponent<ObjectScript>() != null ) { ObjectScript objectScript = myGraphics.equipmentObjects[i].GetComponent<ObjectScript>(); if ( objectScript != null ) { if ( objectScript.myFlameableScript != null ) { objectScript.myFlameableScript.Clear(); } } } Destroy(myGraphics.equipmentObjects[i]); } } } // remove player in combat with reference RemovePlayerInCombatWith(); // destroy object Destroy(myGameObject); } public void AddPlayerInCombatWith () { if ( GameManager.instance != null && GameManager.instance.playerInCombatWith != null && !GameManager.instance.playerInCombatWith.Contains(this) ) { GameManager.instance.playerInCombatWith.Add(this); } } public void RemovePlayerInCombatWith () { if (GameManager.instance != null && GameManager.instance.playerInCombatWith != null && GameManager.instance.playerInCombatWith.Count > 0 && GameManager.instance.playerInCombatWith.Contains(this) ) { GameManager.instance.playerInCombatWith.Remove(this); } } public void AddMinion ( NpcCore _minion ) { if ( myMinions == null ) { myMinions = new List<NpcCore>(); } myMinions.Add(_minion); } public void RemoveMinion ( NpcCore _minion ) { if ( myMinions != null && myMinions.Contains(_minion) ) { myMinions.Remove(_minion); } } public void SetAttackData ( AttackData _to ) { curAttackData = _to; curAttackSprayCount = 0; curAttackSprayCounter = 0; } public void PickRandomAttackData () { if (myInfo.attacks != null && myInfo.attacks.Length > 0) { SetAttackData(myAttackDatas.Choose()); } } public void MagicSkullPickAttackData () { if (myInfo.attacks != null && myInfo.attacks.Length > 0) { bool eyesAreGone = true; for (int i = 0; i < myGraphics.eyeFireChargeScripts.Count; i++) { if (!myGraphics.eyeFireChargeScripts[i].collected) { eyesAreGone = false; break; } } WeightedRandomBag<AttackData> possibleAttackDatas = new WeightedRandomBag<AttackData>(); for (int i = 0; i < myInfo.attacks.Length; i++) { AttackData attackDataCheck = myInfo.attacks[i]; bool canAddAttack = false; // check for eye attack if (attackDataCheck.attackType == AttackData.AttackType.Ranged && attackDataCheck.rangedShootFromType == AttackData.RangedShootFromType.Eye && !eyesAreGone) { canAddAttack = true; } // check for laser attack if (attackDataCheck.attackType == AttackData.AttackType.Ranged && attackDataCheck.rangedShootFromType == AttackData.RangedShootFromType.Mouth && eyesAreGone) { canAddAttack = true; } // check for melee attack if (attackDataCheck.attackType == AttackData.AttackType.Melee && eyesAreGone) { canAddAttack = true; } if (canAddAttack) { possibleAttackDatas.AddEntry(attackDataCheck, attackDataCheck.weight); } } AttackData attackDataChosen = possibleAttackDatas.Choose(); SetAttackData(attackDataChosen); } } public void HellLordPickAttackData () { if (myInfo.attacks != null && myInfo.attacks.Length > 0) { WeightedRandomBag<AttackData> possibleAttackDatas = new WeightedRandomBag<AttackData>(); for (int i = 0; i < myInfo.attacks.Length; i++) { AttackData attackDataCheck = myInfo.attacks[i]; bool canAddAttack = true; // check for spray attack if (attackDataCheck.attackType == AttackData.AttackType.Ranged && attackDataCheck.rangedAttackType == AttackData.RangedAttackType.Spray && stageIndex < 1 ) { canAddAttack = false; } if (canAddAttack) { possibleAttackDatas.AddEntry(attackDataCheck, attackDataCheck.weight); } } AttackData attackDataChosen = possibleAttackDatas.Choose(); SetAttackData(attackDataChosen); } } public void PickSpecificAttackData ( AttackData.AttackType _type ) { bool foundAttackData = false; if (myInfo.attacks.Length > 0) { for (int i = 0; i < myInfo.attacks.Length; i++) { AttackData attackDataCheck = myInfo.attacks[i]; if (!foundAttackData) { if (attackDataCheck.attackType == _type) { SetAttackData(attackDataCheck); foundAttackData = true; } } } } } public void PlayAlertedAudio () { AudioManager.instance.PlaySoundAtPosition(myTransform.position, BasicFunctions.PickRandomAudioClipFromArray(alertClipsUse), alertPitchMin, alertPitchMax, alertVolumeMin, alertVolumeMax, 2f + myInfo.audio.distanceAdd, 8f + myInfo.audio.distanceAdd); } public void PlayHurtAudio () { AudioManager.instance.PlaySoundAtPosition(myTransform.position, BasicFunctions.PickRandomAudioClipFromArray(hurtClipsUse), hurtPitchMin, hurtPitchMax, hurtVolumeMin, hurtVolumeMax, 2f + myInfo.audio.distanceAdd, 8f + myInfo.audio.distanceAdd); } public void PlayDeadAudio () { AudioManager.instance.PlaySoundAtPosition(myTransform.position, BasicFunctions.PickRandomAudioClipFromArray(deadClipsUse), deadPitchMin, deadPitchMax, deadVolumeMin, deadVolumeMax, 2f + myInfo.audio.distanceAdd, 8f + myInfo.audio.distanceAdd); } public void PlayAttackPrepareAudio () { AudioManager.instance.PlaySoundAtPosition(myTransform.position, BasicFunctions.PickRandomAudioClipFromArray(attackPrepareClipsUse), attackPreparePitchMin, attackPreparePitchMax, attackPrepareVolumeMin, attackPrepareVolumeMax, 2f + myInfo.audio.distanceAdd, 8f + myInfo.audio.distanceAdd); } public void PlayAttackDoAudio () { AudioManager.instance.PlaySoundAtPosition(myTransform.position, BasicFunctions.PickRandomAudioClipFromArray(attackDoClipsUse), attackDoPitchMin, attackDoPitchMax, attackDoVolumeMin, attackDoVolumeMax, 2f + myInfo.audio.distanceAdd, 8f + myInfo.audio.distanceAdd); } }
using NSchedule.Entities; using NSchedule.ViewModels; using NSchedule.Views; using Plugin.Toast; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace NSchedule.Views { public partial class ScheduleListPage : ContentPage { ScheduleListViewModel _viewModel; public ScheduleListPage() { InitializeComponent(); BindingContext = _viewModel = new ScheduleListViewModel(); } protected override void OnAppearing() { base.OnAppearing(); _viewModel.OnAppearing(); } private void TapGestureRecognizer_Tapped(object sender, EventArgs e) { var s = (View)sender; s.BackgroundColor = Color.Red; } } }
using ServiceStack.DataAnnotations; using System; namespace LeadChina.CCDMonitor.Infrastrue.Entity { [Serializable] [Alias("bas_loc")] public class LocEntity { [Alias("loc_no")] public string LocNo { get; set; } [Alias("loc_name")] public string LocName { get; set; } [Alias("line_no")] public string LineNo { get; set; } [Alias("process_no")] public string ProcessNo { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TP.Entities { [Table("Reports")] public class Report { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int ReportID { get; set; } public int TestJobID { get; set; } [ForeignKey("TestJobID")] public virtual Test_Job Test_Job { get; set; } [DisplayName("Rapor Başlığı"),Required,StringLength(150)] public string report_title { get; set; } [DisplayName("Rapor İçeriği"),Required, StringLength(4000)] public string report { get; set; } // public virtual Test_Master ownerTestMaster { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Sqo; namespace siaqodatabase { class Program { static void Main(string[] args) { var dbPath = Path.Combine(Path.GetDirectoryName(Environment.GetCommandLineArgs().First()), "Data"); if (Directory.Exists(dbPath)) Directory.Delete(dbPath, true); Directory.CreateDirectory(dbPath); var db = new Siaqodb(dbPath); var client = new Doctor() { Name = "Piotr", Surname = "Kowal", BirthYear = 1990, Salary = 3000, City = "Kielce" }; var client2 = new Doctor() { Name = "Anna", Surname = "Pakosz", BirthYear = 1980, Salary = 6000, City = "Kielce" }; var client3 = new Doctor() { Name = "Marian", Surname = "Ludwik", BirthYear = 2000, Salary = 4000, City = "Warszawa" }; db.StoreObject(client); db.StoreObject(client2); db.StoreObject(client3); var menu = new Menu(db); menu.Run(); Console.ReadLine(); } } }
using System; using System.ComponentModel.DataAnnotations; using DashBoard.Data.Enums; namespace DashBoard.Data.Entities { public class User { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Username { get; set; } public byte[] PasswordHash { get; set; } public byte[] PasswordSalt { get; set; } public string Role { get; set; } public string UserEmail { get; set; } public Guid Team_Key { get; set; } public int Created_By { get; set; } public int Modified_By { get; set; } public DateTime Date_Created { get; set; } public DateTime Date_Modified { get; set; } = DateTime.Now; public string RefreshToken { get; set; } public DateTime RefreshTokenValidDate { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using DistCWebSite.Core.Entities; using System.Web.Http; using DistCWebSite.Infrastructure; namespace DistCWebSite.Controllers { public class DictionaryController : ApiController { /// <summary> /// 根据类型获取列表 /// </summary> /// <param name="m_MasterDictionary"></param> /// <returns></returns> [HttpPost] public List<M_MasterDictionary> GetDictionaryListByCategory(M_MasterDictionary m_MasterDictionary) { DictionaryRepository dictionaryRepository = new Infrastructure.DictionaryRepository(); List<M_MasterDictionary> list = dictionaryRepository.GetDictionaryList(); //返回指定类型的列表 return list.FindAll(x=>x.Cagetory==m_MasterDictionary.Cagetory); } /// <summary> /// 根据类型和key获取列表 /// </summary> /// <param name="m_MasterDictionary"></param> /// <returns></returns> [HttpPost] public List<M_MasterDictionary> GetDictionaryListByWhere(M_MasterDictionary m_MasterDictionary) { DictionaryRepository dictionaryRepository = new Infrastructure.DictionaryRepository(); List<M_MasterDictionary> list = dictionaryRepository.GetDictionaryList(); //返回指定类型的列表 return list.FindAll(x => x.Cagetory == m_MasterDictionary.Cagetory).FindAll(x=>x.DicKey==m_MasterDictionary.DicKey); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using VendingMachine.Domain.Business; using VendingMachine.Domain.Models; namespace VendingMachine.App { public partial class App : Form { private List<ProductUC> products; int i = 0; int j = 0; public App() { InitializeComponent(); //Comment out function to avoid database issue GetProducts(); //GeldService gs = new GeldService(); //Prijs product, inworp geld //gs.GetChange(1.75F, 2.0F); //ProductService ps = new ProductService(); //ProductUC productUC = new ProductUC(ps.GetProducts()[0]); //this.Controls.Add(productUC); } public void GetProducts() { // Producten service voor ophalen producten ProductService ps = new ProductService(); List<ProductUC> productList; productList = new List<ProductUC>(); // Door alle producten heen gaan foreach (Product p in ps.GetProducts()) { if (i <= 3) { ProductUC productUC = new ProductUC(p); productUC.Location = new Point(i * productUC.Width, j * productUC.Height); i++; productList.Add(productUC); } if(i == 4) { i = 0; j++; } } pnlProducts.Controls.Clear(); pnlProducts.Controls.AddRange(productList.ToArray()); products = productList; } // Functie voor het omzetten van byte array naar image class public Image byteArrayToImage(byte[] byteArrayIn) { try { MemoryStream ms = new MemoryStream(byteArrayIn); Image returnImage = Image.FromStream(ms); return returnImage; } catch (Exception ex) { MessageBox.Show(ex.Message); } return null; } public void length() { int labelLength = lblChoice.Text.Length; if (labelLength > 5) { lblChoice.Font = new Font("Microsoft Sans Serif", 30, FontStyle.Italic); } if (labelLength > 8) { lblChoice.Font = new Font("Microsoft Sans Serif", 20, FontStyle.Italic); } } private void btn_Click(object sender, EventArgs e) { Button button = (Button)sender; lblChoice.Text = lblChoice.Text + button.Text; length(); } private void btnClear_Click(object sender, EventArgs e) { lblChoice.Text = ""; lblChoice.Font = new Font("Microsoft Sans Serif", 40, FontStyle.Italic); } private void btnGo_Click(object sender, EventArgs e) { ProductUC pp = products.Find(x => x.tag == Int32.Parse(lblChoice.Text)); BuyProduct buyProduct = new BuyProduct(pp); buyProduct.Show(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using RWCustom; using Rainbow.Enum; namespace Rainbow.CreatureAddition { public class SmallCentiwingAI : ArtificialIntelligence, IUseARelationshipTracker { public SmallCentiwingAI(AbstractCreature creature, World world) : base(creature, world) { this.centiwing = (creature.realizedCreature as SmallCentiwing); this.centiwing.AI = this; base.AddModule(new CentipedePather(this, world, creature)); base.pathFinder.accessibilityStepsPerFrame = 40; base.AddModule(new Tracker(this, 10, 10, -1, 0.5f, 5, 5, 20)); base.AddModule(new PreyTracker(this, 5, 1f, 5f, 150f, 0.05f)); base.AddModule(new ThreatTracker(this, 3)); base.AddModule(new RainTracker(this)); base.AddModule(new DenFinder(this, creature)); base.AddModule(new RelationshipTracker(this, base.tracker)); base.AddModule(new UtilityComparer(this)); base.AddModule(new InjuryTracker(this, 0.6f)); base.utilityComparer.AddComparedModule(base.threatTracker, null, 1f, 1.1f); base.utilityComparer.AddComparedModule(base.preyTracker, null, 0.12f, 1.1f); base.utilityComparer.AddComparedModule(base.rainTracker, null, 1f, 1.1f); base.utilityComparer.AddComparedModule(base.injuryTracker, null, 0.7f, 1.1f); if (base.noiseTracker != null) { base.utilityComparer.AddComparedModule(base.noiseTracker, null, 0.2f, 1.2f); } this.behavior = SmallCentiwingAI.Behavior.Idle; } public SmallCentiwing centiwing; public SmallCentiwingAI.Behavior behavior; public enum Behavior { Idle, Flee, Attack, EscapeRain, Injured, InvestigateSound } public AIModule ModuleToTrackRelationship(CreatureTemplate.Relationship relationship) { CreatureTemplate.Relationship.Type type = relationship.type; if (type != CreatureTemplate.Relationship.Type.Eats) { if (type == CreatureTemplate.Relationship.Type.Afraid) { return base.threatTracker; } if (type != CreatureTemplate.Relationship.Type.Antagonizes) { return null; } } return base.preyTracker; } public CreatureTemplate.Relationship UpdateDynamicRelationship(RelationshipTracker.DynamicRelationship dRelation) { CreatureTemplate.Relationship result = base.StaticRelationship(dRelation.trackerRep.representedCreature); if (result.type == CreatureTemplate.Relationship.Type.Ignores) { return result; } if (dRelation.trackerRep.representedCreature.realizedCreature == null) { return result; } if (dRelation.trackerRep.representedCreature.realizedCreature.dead) { return new CreatureTemplate.Relationship(CreatureTemplate.Relationship.Type.Ignores, 0f); } if (result.type != CreatureTemplate.Relationship.Type.Eats || dRelation.trackerRep.representedCreature.realizedCreature.TotalMass >= this.centiwing.TotalMass) { return new CreatureTemplate.Relationship(CreatureTemplate.Relationship.Type.Afraid, 0.2f + 0.8f * Mathf.InverseLerp(this.centiwing.TotalMass, this.centiwing.TotalMass * 1.5f, dRelation.trackerRep.representedCreature.realizedCreature.TotalMass)); } float num = Mathf.Pow(Mathf.InverseLerp(0f, this.centiwing.TotalMass, dRelation.trackerRep.representedCreature.realizedCreature.TotalMass), 0.75f); if (dRelation.trackerRep.age < 300) { num *= 1f - this.OverChasm(dRelation.trackerRep.BestGuessForPosition().Tile); return new CreatureTemplate.Relationship(CreatureTemplate.Relationship.Type.Afraid, num * Mathf.InverseLerp(300f, 0f, (float)dRelation.trackerRep.age)); } num *= 1f - this.OverChasm(dRelation.trackerRep.BestGuessForPosition().Tile); return new CreatureTemplate.Relationship(CreatureTemplate.Relationship.Type.Eats, num * Mathf.InverseLerp(300f, 800f, (float)dRelation.trackerRep.age)); } public RelationshipTracker.TrackedCreatureState CreateTrackedCreatureState(RelationshipTracker.DynamicRelationship rel) { return new CentipedeAI.CentipedeTrackState(); } public float OverChasm(IntVector2 testPos) { float num = (this.centiwing.room.aimap.getAItile(testPos).fallRiskTile.y >= 0) ? 0f : 1f; for (int i = -1; i < 2; i += 2) { for (int j = 1; j < 7; j++) { if (this.centiwing.room.GetTile(testPos + new IntVector2(j * i, 0)).Solid) { break; } if (this.centiwing.room.aimap.getAItile(testPos + new IntVector2(j * i, 0)).fallRiskTile.y < 0) { num += 1f / (float)j; } } } return Mathf.InverseLerp(0f, 5.9f, num); } public bool DoIWantToShockCreature(AbstractCreature critter) { if (this.annoyingCollisions < 150 && (this.behavior == SmallCentiwingAI.Behavior.Flee || this.behavior == SmallCentiwingAI.Behavior.EscapeRain) && this.currentUtility > 0.1f) { return false; } if (critter.state.dead) { return false; } if (critter.realizedCreature != null) { Tracker.CreatureRepresentation creatureRepresentation = base.tracker.RepresentationForObject(critter.realizedCreature, false); if (this.annoyingCollisions > 150 && (creatureRepresentation == null || (creatureRepresentation.dynamicRelationship.state as CentipedeAI.CentipedeTrackState).annoyingCollisions > 150 * this.centiwing.CentiState.health)) { return true; } if (creatureRepresentation != null) { return creatureRepresentation.dynamicRelationship.currentRelationship.type == CreatureTemplate.Relationship.Type.Eats; } } return base.StaticRelationship(critter).type == CreatureTemplate.Relationship.Type.Eats; } public float run; public int annoyingCollisions; public float currentUtility; public WorldCoordinate forbiddenIdlePos; public WorldCoordinate tempIdlePos; private List<PlacedObject> centipedeAttractors; public int idleCounter; public float excitement; public int charge { get { return this.centiwing.charge; } set { this.centiwing.charge = value; } } public override void NewRoom(Room room) { base.NewRoom(room); this.forbiddenIdlePos = this.creature.pos; this.tempIdlePos = this.creature.pos; this.centipedeAttractors = new List<PlacedObject>(); for (int i = 0; i < room.roomSettings.placedObjects.Count; i++) { if (room.roomSettings.placedObjects[i].type == PlacedObject.Type.CentipedeAttractor) { this.centipedeAttractors.Add(room.roomSettings.placedObjects[i]); } } } public override void Update() { base.Update(); if (this.annoyingCollisions > 0) { this.annoyingCollisions--; } if (base.noiseTracker != null) { base.noiseTracker.hearingSkill = ((!this.centiwing.moving) ? 1.5f : 0f); } if (base.preyTracker.MostAttractivePrey != null) { base.utilityComparer.GetUtilityTracker(base.preyTracker).weight = Mathf.InverseLerp(50f, 10f, (float)base.preyTracker.MostAttractivePrey.TicksSinceSeen); } if (base.threatTracker.mostThreateningCreature != null) { base.utilityComparer.GetUtilityTracker(base.threatTracker).weight = Mathf.InverseLerp(500f, 100f, (float)base.threatTracker.mostThreateningCreature.TicksSinceSeen); } AIModule aimodule = base.utilityComparer.HighestUtilityModule(); this.currentUtility = base.utilityComparer.HighestUtility(); if (aimodule != null) { if (aimodule is ThreatTracker) { this.behavior = SmallCentiwingAI.Behavior.Flee; } else if (aimodule is RainTracker) { this.behavior = SmallCentiwingAI.Behavior.EscapeRain; } else if (aimodule is NoiseTracker) { this.behavior = SmallCentiwingAI.Behavior.InvestigateSound; } else if (aimodule is InjuryTracker) { this.behavior = SmallCentiwingAI.Behavior.Injured; } } if (this.currentUtility < 0.1f) { this.behavior = SmallCentiwingAI.Behavior.Idle; } float to = 0f; switch (this.behavior) { case SmallCentiwingAI.Behavior.Idle: { WorldCoordinate testPos = this.creature.pos + new IntVector2(UnityEngine.Random.Range(-10, 11), UnityEngine.Random.Range(-10, 11)); if (UnityEngine.Random.value < 1f / 30f) { testPos = new WorldCoordinate(this.creature.pos.room, UnityEngine.Random.Range(0, this.centiwing.room.TileWidth), UnityEngine.Random.Range(0, this.centiwing.room.TileHeight), -1); } else if (this.centipedeAttractors.Count > 0 && UnityEngine.Random.value < 0.025f) { PlacedObject placedObject = this.centipedeAttractors[UnityEngine.Random.Range(0, this.centipedeAttractors.Count)]; testPos = this.centiwing.room.GetWorldCoordinate(placedObject.pos + Custom.RNV() * (placedObject.data as PlacedObject.ResizableObjectData).Rad * UnityEngine.Random.value); } if (this.IdleScore(testPos) > this.IdleScore(this.tempIdlePos)) { this.tempIdlePos = testPos; this.idleCounter = 0; } else { this.idleCounter++; if (this.creature.pos.room == this.tempIdlePos.room && this.creature.pos.Tile.FloatDist(this.tempIdlePos.Tile) < 15f) { this.idleCounter += 2; } if (this.idleCounter > ((this.centiwing.room.aimap.getAItile(this.tempIdlePos.Tile).acc <= AItile.Accessibility.Climb) ? 1400 : 400) || (this.centiwing.flying && !this.centiwing.RatherClimbThanFly(this.tempIdlePos.Tile) && this.creature.pos.room == this.tempIdlePos.room && this.creature.pos.Tile.FloatDist(this.tempIdlePos.Tile) < 5f) || this.centiwing.outsideLevel) { this.idleCounter = 0; this.forbiddenIdlePos = this.tempIdlePos; } } if (this.tempIdlePos != base.pathFinder.GetDestination && this.IdleScore(this.tempIdlePos) > this.IdleScore(base.pathFinder.GetDestination) + 100f) { this.creature.abstractAI.SetDestination(this.tempIdlePos); } break; } case SmallCentiwingAI.Behavior.Flee: { to = 1f; WorldCoordinate destination = base.threatTracker.FleeTo(this.creature.pos, 1, 30, this.currentUtility > 0.3f); this.creature.abstractAI.SetDestination(destination); break; } case SmallCentiwingAI.Behavior.Attack: to = base.DynamicRelationship(base.preyTracker.MostAttractivePrey).intensity; this.creature.abstractAI.SetDestination(base.preyTracker.MostAttractivePrey.BestGuessForPosition()); break; case SmallCentiwingAI.Behavior.EscapeRain: to = 0.5f; if (base.denFinder.GetDenPosition() != null) { this.creature.abstractAI.SetDestination(base.denFinder.GetDenPosition().Value); } break; case SmallCentiwingAI.Behavior.Injured: to = 1f; if (base.denFinder.GetDenPosition() != null) { this.creature.abstractAI.SetDestination(base.denFinder.GetDenPosition().Value); } break; case SmallCentiwingAI.Behavior.InvestigateSound: to = 0.2f; this.creature.abstractAI.SetDestination(base.noiseTracker.ExaminePos); break; } this.excitement = Mathf.Lerp(this.excitement, to, 0.1f); this.run -= 1f; if (this.run < Mathf.Lerp(-50f, -5f, this.excitement)) { this.run = Mathf.Lerp(30f, 50f, this.excitement); } int num = 0; float num2 = 0f; for (int i = 0; i < base.tracker.CreaturesCount; i++) { if (base.tracker.GetRep(i).representedCreature.creatureTemplate.type == CreatureTemplate.Type.Centipede && base.tracker.GetRep(i).representedCreature.realizedCreature != null && base.tracker.GetRep(i).representedCreature.Room == this.creature.Room && (base.tracker.GetRep(i).representedCreature.realizedCreature as Centipede).AI.run > 0f == this.run > 0f) { num2 += (base.tracker.GetRep(i).representedCreature.realizedCreature as Centipede).AI.run; num++; } } if (num > 0) { this.run = Mathf.Lerp(this.run, num2 / (float)num, 0.1f); } } public override PathCost TravelPreference(MovementConnection coord, PathCost cost) { if (coord.destinationCoord.TileDefined) { if (!this.centiwing.flying && !this.centiwing.RatherClimbThanFly(coord.DestTile)) { return new PathCost(cost.resistance + 1000f, cost.legality); } if (this.centiwing.flying) { return new PathCost(cost.resistance + ((this.centiwing.room.aimap.getAItile(coord.destinationCoord).terrainProximity >= 2) ? Custom.LerpMap((float)this.centiwing.room.aimap.getAItile(coord.destinationCoord).terrainProximity, 1f, 6f, 500f, 0f) : 0f), cost.legality); } } return base.TravelPreference(coord, cost); } public override void CreatureSpotted(bool firstSpot, Tracker.CreatureRepresentation creatureRep) { } public override Tracker.CreatureRepresentation CreateTrackerRepresentationForCreature(AbstractCreature otherCreature) { Tracker.CreatureRepresentation result; if (otherCreature.creatureTemplate.smallCreature) { result = new Tracker.SimpleCreatureRepresentation(base.tracker, otherCreature, 0f, false); } else { result = new Tracker.ElaborateCreatureRepresentation(base.tracker, otherCreature, 1f, 3); } return result; } public override float VisualScore(Vector2 lookAtPoint, float bonus) { Vector2 pos; Vector2 pos2; if (this.centiwing.visionDirection) { pos = this.centiwing.bodyChunks[1].pos; pos2 = this.centiwing.bodyChunks[0].pos; } else { pos = this.centiwing.bodyChunks[this.centiwing.bodyChunks.Length - 2].pos; pos2 = this.centiwing.bodyChunks[this.centiwing.bodyChunks.Length - 1].pos; } return base.VisualScore(lookAtPoint, bonus) - Mathf.InverseLerp(1f, 0.5f, Vector2.Dot((pos - pos2).normalized, (pos2 - lookAtPoint).normalized)) - ((!this.centiwing.moving) ? 0f : 0.75f); } public override bool TrackerToDiscardDeadCreature(AbstractCreature crit) { return true; } public override bool WantToStayInDenUntilEndOfCycle() { return base.rainTracker.Utility() > 0.01f; } public void AnnoyingCollision(AbstractCreature critter) { if (critter.state.dead) { return; } this.annoyingCollisions += 10; if (this.annoyingCollisions < 150) { return; } if (base.tracker.RepresentationForCreature(critter, false) == null) { return; } (base.tracker.RepresentationForCreature(critter, false).dynamicRelationship.state as CentipedeAI.CentipedeTrackState).annoyingCollisions++; } public float IdleScore(WorldCoordinate testPos) { if (!testPos.TileDefined) { return float.MinValue; } if (testPos.room != this.creature.pos.room) { return float.MinValue; } if (!base.pathFinder.CoordinateReachableAndGetbackable(testPos)) { return float.MinValue; } float num = 1000f; num /= Mathf.Max(1f, (float)this.centiwing.room.aimap.getAItile(testPos).terrainProximity - 1f); num -= Custom.LerpMap(testPos.Tile.FloatDist(this.forbiddenIdlePos.Tile), 0f, 10f, 1000f, 0f); for (int i = 0; i < base.tracker.CreaturesCount; i++) { if (base.tracker.GetRep(i).representedCreature.creatureTemplate.type == this.creature.creatureTemplate.type && base.tracker.GetRep(i).representedCreature.realizedCreature != null && base.tracker.GetRep(i).BestGuessForPosition().room == this.creature.pos.room && (base.tracker.GetRep(i).representedCreature.realizedCreature as SmallCentiwing).AI.behavior == SmallCentiwingAI.Behavior.Idle) { SmallCentiwing otherWing = base.tracker.GetRep(i).representedCreature.realizedCreature as SmallCentiwing; num -= Custom.LerpMap(testPos.Tile.FloatDist(otherWing.AI.tempIdlePos.Tile), 0f, 20f, 1000f, 0f) * 0.2f; num -= Custom.LerpMap(testPos.Tile.FloatDist(otherWing.AI.pathFinder.GetDestination.Tile), 0f, 20f, 1000f, 0f) * 0.2f; } } if (this.centiwing.room.aimap.getAItile(testPos).fallRiskTile.y < 0) { num -= Custom.LerpMap((float)testPos.y, 10f, 30f, 1000f, 0f); } for (int j = 0; j < this.centipedeAttractors.Count; j++) { if (Custom.DistLess(this.centiwing.room.MiddleOfTile(testPos), this.centipedeAttractors[j].pos, (this.centipedeAttractors[j].data as PlacedObject.ResizableObjectData).Rad)) { num += 1000f; break; } } return num; } public void CheckRandomIdlePos() { WorldCoordinate testPos = new WorldCoordinate(this.creature.pos.room, UnityEngine.Random.Range(0, this.centiwing.room.TileWidth), UnityEngine.Random.Range(0, this.centiwing.room.TileHeight), -1); if (this.IdleScore(testPos) > this.IdleScore(this.tempIdlePos)) { this.tempIdlePos = testPos; this.idleCounter = 0; } } } }
/*/ using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using System; using MongoDB.Bson; using MongoDB.Driver; using MongoDB.Driver.Builders; using System.Collections.Generic; namespace desafio.connection { public class Connection{ MongoClient _client; MongoServer _server; MongoDatabase _db; public Connection(){ _client = new MongoClient("mongodb://localhost:27017"); _server = _client.GetServer(); _db = _server.GetDatabase("desafio"); return(_db); } } } */
using System; using FluentMigrator; namespace Profiling2.Migrations.Migrations { [Migration(201304041154)] public class RelaxCareerNotNulls : Migration { public override void Down() { // need to drop and recreate indexes //Alter.Column("OrganizationID").OnTable("PRF_Career").AsInt32().NotNullable(); //Alter.Column("LocationID").OnTable("PRF_Career").AsInt32().NotNullable(); //Alter.Column("RankID").OnTable("PRF_Career").AsInt32().NotNullable(); } public override void Up() { Alter.Column("OrganizationID").OnTable("PRF_Career").AsInt32().Nullable(); Alter.Column("LocationID").OnTable("PRF_Career").AsInt32().Nullable(); Alter.Column("RankID").OnTable("PRF_Career").AsInt32().Nullable(); Execute.Sql(@"UPDATE PRF_Career SET RankID = NULL FROM PRF_Career AS c INNER JOIN PRF_Rank AS r ON c.RankID = r.RankID WHERE r.RankName = '0' "); } } }
namespace TripDestination.Web.MVC.Areas.Admin.Controllers { using System.Web.Mvc; using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; using TripDestination.Services.Data.Contracts; using TripDestination.Common.Infrastructure.Mapping; using TripDestination.Web.MVC.Areas.Admin.ViewModels; using TripDestination.Web.MVC.Controllers; public class TownAdminController : BaseController { private readonly ITownsServices townServices; public TownAdminController(ITownsServices townServices) { this.townServices = townServices; } public ActionResult Index() { return this.View(); } public ActionResult Towns_Read([DataSourceRequest]DataSourceRequest request) { var result = this.townServices .GetAll() .To<TownAdminViewModel>() .ToDataSourceResult(request); return this.Json(result); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Towns_Create([DataSourceRequest]DataSourceRequest request, TownAdminViewModel town) { if (this.ModelState.IsValid) { var dbTown = this.townServices.Create(town.Name); town.Id = dbTown.Id; } return this.Json(new[] { town }.ToDataSourceResult(request, this.ModelState)); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Towns_Update([DataSourceRequest]DataSourceRequest request, TownAdminViewModel town) { if (this.ModelState.IsValid) { this.townServices.Edit(town.Id, town.Name); } return this.Json(new[] { town }.ToDataSourceResult(request, this.ModelState)); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Towns_Destroy([DataSourceRequest]DataSourceRequest request, TownAdminViewModel town) { if (this.ModelState.IsValid) { this.townServices.Delete(town.Id); } return this.Json(new[] { town }.ToDataSourceResult(request, this.ModelState)); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace capacited_facility_location_problem { class Program { static void Main(string[] args) { InputFacilityProblemDataReader dataReader = new InputFacilityProblemDataReader(); #if DEBUG // by the moment but only for debug var round = args[0]; var path = args[1]; var filePath = String.Format("{0}{1}", path, round); // read input from stdin and create the respective objetcs FacilityProblemData problemData = dataReader.CreateProblemDataFromFileInPath(filePath); #else FacilityProblemData problemData = dataReader.CreateProblemDataFromStandardInput(); #endif FacilityOptimizer facilityOptimizer = new FacilityOptimizer(); var result = facilityOptimizer.SolveProblemForInstance(problemData); Console.Write(result); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace vega3.Models { [Table("VechileFeatures")] public class VehicleFeature { [Required] public int VehicleId { get; set; } [Required] public int FeatureId { get; set; } public Vehicle Vehicle { get; set; } public Feature Feature { get; set; } } }
using Tomelt.Events; namespace Tomelt.Environment { public interface ITomeltShellEvents : IEventHandler { void Activated(); void Terminating(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerAttack : MonoBehaviour { Animator ani; [SerializeField] private ParticleSystem fire1; [SerializeField] private ParticleSystem fire2; private int type; //玩家攻击对象之所以放进列表是因为,有的招数技能攻打的是一个区域内的小兵,并不一定是一个 List<GameObject> enemyList=new List<GameObject>(); // Use this for initialization void Start () { ani = GetComponent<Animator>(); //设定敌方英雄,我方英雄类型 if (this.tag=="player") { type = 0; } else { type = 1; } } void OnTriggerExit(Collider col) { //print ("移除队列"); enemyList.Remove(col.gameObject); enemyList.RemoveAll(t=>t==null);//移除列表里所有为空的元素(括号里是泛型用法) } void OnTriggerEnter(Collider col) { if (!this.enemyList.Contains (col.gameObject)) { //print ("进入队列"); enemyList.Add (col.gameObject); } } public void Atk1() { ani.SetInteger("state", AnimState.ATTACK1); if (enemyList.Count <= 0) return; for (int i = 0; i < enemyList.Count; i++) { if (enemyList.Count > 0 && !enemyList[i].name.Contains("Tower")) { SmartSoldier soldier = enemyList[i].GetComponent<SmartSoldier>(); if (soldier&&soldier.type!=this.type)//是小兵就攻击小兵 { Health hp=soldier.GetComponent<Health>(); hp.TakeDamage(0.5f); if (hp.hp.Value<=0) { enemyList.Remove(soldier.gameObject); Destroy(soldier.gameObject); } } } } } public void Atk2() { ani.SetInteger("state",AnimState.ATTACK1); if (enemyList.Count <= 0) return; for (int i = 0; i < enemyList.Count; i++) { if (enemyList.Count > 0 && !enemyList[i].name.Contains("Tower")) { SmartSoldier soldier = enemyList[i].GetComponent<SmartSoldier>(); if (soldier&&soldier.type!=this.type)//是小兵就攻击小兵 { Health hp=soldier.GetComponent<Health>(); hp.TakeDamage(1f); if (hp.hp.Value<=0) { enemyList.Remove(soldier.gameObject); Destroy(soldier.gameObject); } } } } } public void Dance() { //用dance代替第三次攻击 ani.SetInteger("state", AnimState.DANCE); } //动画监听事件,攻击动画播放完播放攻击特效 public void EffectPlay1() { fire1.Play(); } public void EffectPlay2() { fire2.Play(); } //攻击动画播放完转换成Idle状态 public void ResetIdle() { ani.SetInteger("state", AnimState.IDLE); } }
using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; using System; using Fbtc.Application.Interfaces; using Fbtc.Domain.Entities; namespace Fbtc.Api.Controllers { [RoutePrefix("api/Perfil")] public class PerfilController : ApiController { private readonly IPerfilApplication _perfilApplication; public PerfilController(IPerfilApplication perfilApplication) { _perfilApplication = perfilApplication; } // [Authorize] [Route("GetAll/{isAtivo},{dominio}")] [HttpGet] public Task<HttpResponseMessage> GetAll(bool? isAtivo, string dominio) { HttpResponseMessage response = new HttpResponseMessage(); var tsc = new TaskCompletionSource<HttpResponseMessage>(); try { bool? _isAtivo = null; if (isAtivo != null) _isAtivo = isAtivo.Equals(true) ? true : false; var resultado = _perfilApplication.GetAll(_isAtivo, dominio); response = Request.CreateResponse(HttpStatusCode.OK, resultado); tsc.SetResult(response); return tsc.Task; } catch (Exception ex) { if (ex.GetType().Name == "InvalidOperationException" || ex.Source == "prmToolkit.Validation") { response = Request.CreateResponse(HttpStatusCode.NotFound); response.ReasonPhrase = ex.Message; } else { response = Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message); } tsc.SetResult(response); return tsc.Task; } } // [Authorize] [Route("{id:int}")] [HttpGet] public Task<HttpResponseMessage> GetById(int id) { HttpResponseMessage response = new HttpResponseMessage(); var tsc = new TaskCompletionSource<HttpResponseMessage>(); try { if (id == 0) throw new InvalidOperationException("Id não informado!"); var resultado = _perfilApplication.GetPerfilById(id); response = Request.CreateResponse(HttpStatusCode.OK, resultado); tsc.SetResult(response); return tsc.Task; } catch (Exception ex) { if (ex.GetType().Name == "InvalidOperationException" || ex.Source == "prmToolkit.Validation") { response = Request.CreateResponse(HttpStatusCode.NotFound); response.ReasonPhrase = ex.Message; } else { response = Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message); } tsc.SetResult(response); return tsc.Task; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace DChild.Gameplay.Objects { public class MaterialTime : IsolatedTime,IVisualBody, IVisualTime { [SerializeField] [HideInInspector] private MaterialTimeHandler m_handler; private float m_deltaTime; public float deltaTime => m_deltaTime; public void UpdateDeltaTime(float deltaTime) => m_deltaTime = deltaTime * totalTimeScale; protected override void UpdateComponents() { m_handler.ChangeSimulationSpeed(totalTimeScale); } private void OnValidate() { m_handler = new MaterialTimeHandler(GetComponentsInChildren<Renderer>()); UpdateTimeScale(); UpdateComponents(); } } }
namespace Funding.Common.Constants { public class Account { public const string AdminName = "admin@admin.com"; public const string AdminPassword = "admin11"; public const string ProjectName = "Funding"; } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace HW2 { public class GamesManager { public static List<Profile> profiles = new List<Profile>(); public static int countProfile; public static int numAllGames; public static int minDuration; public static int maxDuration; public static int totleDuration; public static int highScore; public static int lowScore; public static Bitmap[] allImage = new Bitmap[4]; static GamesManager() { allImage[0] = new Bitmap(Properties.Resources._5c8954160c96b047950052); allImage[1] = new Bitmap(Properties.Resources._5c895373ba5e5773675130); allImage[2] = new Bitmap(Properties.Resources.donald_1); allImage[3] = new Bitmap(Properties.Resources._200w_d); } public static void calcStatiistcs() { var gameCalc = from p in profiles select p.Games; minDuration = gameCalc.Min(x => x.Min(y => y.Duration)); maxDuration = gameCalc.Max(x => x.Max(y => y.Duration)); totleDuration = gameCalc.Sum(x => x.Sum(y => y.Duration)); lowScore = gameCalc.Min(x=>x.Min(y=>y.Score)); highScore = gameCalc.Max(x=>x.Max(y=>y.Score)); countProfile = profiles.Count; } } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace _2018_07_02 { class Program { static List<int> primes = new List<int>(); static void Main(string[] args) { Stopwatch sw = new Stopwatch(); Console.WriteLine("We are finding primes. How high should we go?"); int.TryParse(Console.ReadLine(), out int maxNumber); sw.Start(); primes.Add(2); for (int potentialPrime = 3; potentialPrime < maxNumber; potentialPrime += 2) { bool itIsPrime = IsPrime(potentialPrime); if (itIsPrime) { primes.Add(potentialPrime); } } string output = string.Join(", ", primes); Console.WriteLine(output); sw.Stop(); Console.WriteLine(sw.Elapsed); } private static bool IsPrime(int potentialPrime) { int maxDivisor = (int)Math.Sqrt(potentialPrime); foreach (int prime in primes) { if (potentialPrime % prime == 0) { return false; } if (prime >= maxDivisor) { break; } } return true; } } }
using UnityEngine; namespace Project.Game { public class BaseControls : MonoBehaviour { internal protected struct TouchV2 { public Touch touch; public bool availability; public Vector2 origin; public Vector2 Position { get { return touch.position; } } public int TapCount { get { return touch.tapCount; } } public int FingerId { get { return touch.fingerId; } } public TouchPhase Phase { get { return touch.phase; } } } private bool isEnable = true; protected Ray touchRay0; protected Ray touchRay1; protected static TouchV2 touch0; protected static TouchV2 touch1; public bool IsEnable { get { return isEnable; } set { isEnable = value; } } private void Start() { touch0.availability = true; touch1.availability = true; } void Update() { if (!isEnable) return; switch (Input.touchCount) { case 0: break; case 1: touch0.touch = Input.GetTouch(0); TouchUpdate(ref touch0, ref touchRay0); TouchUpdate(ref touch0); break; case 2: touch0.touch = Input.GetTouch(0); touch1.touch = Input.GetTouch(1); TouchUpdate(ref touch0, ref touchRay0); TouchUpdate(ref touch1, ref touchRay1); TouchUpdate(ref touch0); TouchUpdate(ref touch1); break; default: touch0.touch = Input.GetTouch(0); touch1.touch = Input.GetTouch(1); TouchUpdate(ref touch0, ref touchRay0); TouchUpdate(ref touch1, ref touchRay1); TouchUpdate(ref touch0); TouchUpdate(ref touch1); break; } } protected virtual void TouchUpdate(ref TouchV2 touch) { if (touch.Phase == TouchPhase.Began) { touch.origin = touch.Position; } } protected virtual void TouchUpdate(ref TouchV2 touch, ref Ray touchRay) { Vector3 v1 = new Vector3(touch.Position.x, touch.Position.y, Camera.main.nearClipPlane); Vector3 v2 = new Vector3(touch.Position.x, touch.Position.y, Camera.main.farClipPlane); Vector3 p1 = Camera.main.ScreenToWorldPoint(v1); Vector3 p2 = Camera.main.ScreenToWorldPoint(v2); touchRay = new Ray(p1, p2 - p1); } } }
using NUnit.Framework; using Xamarin.UITest; using Xamarin.UITests.POP.PageObjects; namespace Xamarin.UITests.POP.Tests { [TestFixture(Platform.Android)] [TestFixture(Platform.iOS)] public class BaseTestFixture<T> where T : BasePageObject { protected IApp App => AppManager.App; protected bool OnAndroid => AppManager.Platform == Platform.Android; protected bool OniOS => AppManager.Platform == Platform.iOS; protected T PageObject { get; set; } protected BaseTestFixture(Platform platform) { AppManager.Platform = platform; } [SetUp] public virtual void SetUp() { AppManager.StartApp(); } [TearDown] public virtual void TearDown() { AppManager.App = null; PageObject = null; } } }
using Sirenix.OdinInspector.Editor; using Sirenix.Utilities; using UnityEngine; namespace XNodeEditor.Odin { [DrawerPriority( 91, 0, 0 )] public class DynamicNoDataNodePropertyPortDrawer<T> : OdinValueDrawer<T> { protected override bool CanDrawValueProperty( InspectorProperty property ) { return property.ChildResolver != null && property.ChildResolver.GetType().ImplementsOpenGenericClass( typeof( DynamicNoDataNodePropertyPortResolver<> ) ); } protected override void DrawPropertyLayout( GUIContent label ) { var portListProp = Property.Children[NodePropertyPort.NodePortListPropertyName]; if ( portListProp != null ) portListProp.Draw( label ); else CallNextDrawer( label ); } } }
using RecipesFinal.Data.Context; using RecipesFinal.Data.Model; using RecipesFinal.Data.Repository.Interface; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace RecipesFinal.Data.Repository.Implementation { public class WeredaRepository:Repository<Woreda>, IWeredaReposistory { public WeredaRepository(RecipeDatacontext context):base(context) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; using System.IO; namespace Les8Exercise5 { public class Student { //public string lastName; //public string firstName; //public string university; //public string faculty; //public int course; //public string department; //public int group; //public string city; //public int age; string lastName; string firstName; string university; string faculty; int course; string department; int group; string city; int age; // Конструктор для сериализации public Student() { } // Конструктор public Student(string firstName, string lastName, string university, string faculty, string department, int age, int course, int group, string city) { this.lastName = lastName; this.firstName = firstName; this.university = university; this.faculty = faculty; this.department = department; this.course = course; this.age = age; this.group = group; this.city = city; } public string LastName { get { return lastName; } set { lastName = value; } } public string FirstName { get { return firstName; } set { firstName = value; } } public string University { get { return university; } set { university = value; } } public string Faculty { get { return faculty; } set { faculty = value; } } public string Department { get { return department; } set { department = value; } } public int Course { get { return course; } set { course = value; } } public int Age { get { return age; } set { age = value; } } public int Group { get { return group; } set { group = value; } } public string City { get { return city; } set { city = value; } } public static List<Student> ReadCSV(string fileName) { List<Student> students = new List<Student>(); // Создаем список студентов StreamReader sr = new StreamReader(fileName); while (!sr.EndOfStream) { try { string[] s = sr.ReadLine().Split(';'); // Добавляем в список новый экземпляр класса Student students.Add(new Student(s[0], s[1], s[2], s[3], s[4], int.Parse(s[5]), int.Parse(s[6]), int.Parse(s[7]), s[8])); } catch (Exception t) { Console.WriteLine(t.Message); Console.WriteLine("Ошибка!ESC - прекратить выполнение программы"); } } sr.Close(); return students; } public static void ConvertXML(string fileName, List<Student> students) { XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Student>)); Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.Write); xmlFormat.Serialize(fStream, students); fStream.Close(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ismetles { class Program { static Random rnd = new Random(); static int[] SzamTomb = new int[60]; static void Main(string[] args) { Feladat1(); Console.WriteLine("\n----------------------------\n"); Feladat2(); Console.WriteLine("\n----------------------------\n"); Feladat3(); Console.WriteLine("\n----------------------------\n"); Feladat4(); Console.WriteLine("\n----------------------------\n"); Feladat5(); Console.WriteLine("\n----------------------------\n"); Feladat6(); Console.WriteLine("\n----------------------------\n"); Feladat7(); Console.WriteLine("\n----------------------------\n"); Feladat8(); Console.WriteLine("\n----------------------------\n"); Console.ReadKey(); } private static void Feladat8() { Console.WriteLine("Feladat 8: minimum, maximum kiválasztási tétel"); int Min = int.MaxValue; int MinHely = 0; int Max = int.MinValue; int MaxHely = 0; for (int i = 0; i < SzamTomb.Length; i++) { if(SzamTomb[i]<Min) { Min = SzamTomb[i]; MinHely = i + 1; } if (SzamTomb[i] > Max) { Max = SzamTomb[i]; MaxHely = i + 1; } } Console.WriteLine("A tömb legnagyobb értéke: {0}",Max); Console.WriteLine("A tömb beni helye:{0}", MaxHely); Console.WriteLine("A tömb legkisebb értéke: {0}", Min); Console.WriteLine("A tömb beni helye:{0}", MinHely); } private static void Feladat7() { Console.WriteLine("Feladat 7: logiai változó használata, eldöntési tétel"); bool VanNincs = false; for (int i = 0; i < SzamTomb.Length; i++) { if(SzamTomb[i]==42) { VanNincs = true; } } if(VanNincs==true) { Console.WriteLine("\tA 42 eleme a tömbnek"); } else { Console.WriteLine("\tNem eleme a 42 a tömbnek"); } } private static void Feladat6() { Console.WriteLine("Feladat 6: File-ba való kiíratás"); var sw = new StreamWriter(@"Tombelemei.txt", false, Encoding.UTF8); for (int j = 0; j < SzamTomb.Length; j++) { if (j % 10 == 0) { Console.Write("\n"); sw.Write("\n"); } Console.Write("\t{0,-3} , ", SzamTomb[j]); sw.Write("\t{0,-3} , ", SzamTomb[j]); } sw.Close(); } private static void Feladat5() { Console.WriteLine("Feladat 5: leszámlálási tétel, páros-páratlan aránya"); int ParosDB = 0; int ParatlanDB = 0; for (int i = 0; i < SzamTomb.Length; i++) { if(SzamTomb[i]%2==0) { ParosDB++; } /*else { ParatlanDB++; }*/ } ParatlanDB = SzamTomb.Length - ParosDB; Console.WriteLine("A páros elemek száma: {0}",ParosDB); Console.WriteLine("A páratlan elemek száma: {0}", ParatlanDB); } private static void Feladat4() { Console.WriteLine("Feladat 4: rendezési tétel növekvő sorrendbe"); int CsereElem = 0; for (int i = 0; i < SzamTomb.Length-1; i++) { for (int k = 0; k < SzamTomb.Length-1; k++) { if(SzamTomb[k]>SzamTomb[k+1]) { CsereElem = SzamTomb[k]; SzamTomb[k] = SzamTomb[k + 1]; SzamTomb[k + 1] = CsereElem; } } } for (int j = 0; j < SzamTomb.Length; j++) { if (j % 10 == 0) { Console.Write("\n"); } Console.Write("\t{0,-3} , ", SzamTomb[j]); } } private static void Feladat3() { Console.WriteLine("Feladat 3.é bekérés és keresés"); Console.Write("Kérem adjn meg egy számot: "); int Keresendo = int.Parse(Console.ReadLine()); int Szamlalo = 0; while(Szamlalo<SzamTomb.Length && Keresendo!=SzamTomb[Szamlalo]) { Szamlalo++; } if(Szamlalo==SzamTomb.Length) { Console.WriteLine("\tA keresett szám nincs benne a tömbben"); } else { Console.WriteLine("\tKeresett szám benne van a tömbben, mégpedig eze a helyen: {0}", Szamlalo+1); } } private static void Feladat2() { Console.WriteLine("Feladat 2: Össszegzés átlagolás tétele"); double Osszeg = 0; double Atlag = 0; for (int i = 0; i < SzamTomb.Length; i++) { Osszeg += (double)SzamTomb[i]; //Osszeg = Osszeg + SzamTomb[i]; } Atlag = Osszeg / SzamTomb.Length; Console.WriteLine("\tTömb eleminek átlaga: {0:0.00}",Atlag); Console.WriteLine("\tTömb eleminek összege: {0}", Osszeg); } private static void Feladat1() { Console.WriteLine("Feladat 1: tömb feltöltése"); for (int i = 0; i < SzamTomb.Length; i++) { SzamTomb[i] = rnd.Next(-30, 61); if(i%10==0) { Console.Write("\n"); } Console.Write("\t{0,-3} , ",SzamTomb[i]); } } } }
using System; namespace Crystal.Plot2D.Charts { public interface IDateTimeTicksStrategy { DifferenceIn GetDifference(TimeSpan span); bool TryGetLowerDiff(DifferenceIn diff, out DifferenceIn lowerDiff); bool TryGetBiggerDiff(DifferenceIn diff, out DifferenceIn biggerDiff); } }
using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class View_WSDashBoard : System.Web.UI.Page { static string Condition = ""; DashBoard d = new DashBoard(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //Condition = "gamt"; InitPage(); BindGridView(grdDash1); BindGridView(grdData, ddlDailyMonth, ddlDailyYear); BindGridView(grdData2, ddlDailyMonth2, ddlDailyYear2); divHDaily1.Visible = false; divHDaily2.Visible = false; //ALLC //BDT //EX1 //EX2 //MT //WS } } private void InitPage() { Dictionary<string, string> listValueType = new Dictionary<string, string>(); listValueType.Add("gamt", "Gross Amount"); listValueType.Add("namt", "Net Amount"); listValueType.Add("qty", "Quantity"); BindDropdownList(ddlValueType, listValueType); var _date = DateTime.Now; Dictionary<string, string> monthList = new Dictionary<string, string>(); for (int i = 1; i <= 12; i++) { var _month = new DateTime(_date.Year, i, 1); monthList.Add(i.ToString(), _month.ToString("MMMM")); } BindDropdownList(ddlMonth, monthList); ddlMonth.SelectedValue = _date.Month.ToString(); Dictionary<string, string> yearList = new Dictionary<string, string>(); for (int i = 2010; i <= _date.Year; i++) { yearList.Add(i.ToString(), i.ToString()); } BindDropdownList(ddlYear, yearList); ddlYear.SelectedValue = _date.Year.ToString(); var _date_b = DateTime.Now.AddMonths(-1); BindDropdownList(ddlDailyMonth, monthList); ddlDailyMonth.SelectedValue = _date_b.Month.ToString(); BindDropdownList(ddlDailyYear, yearList); ddlDailyYear.SelectedValue = _date_b.Year.ToString(); BindDropdownList(ddlDailyMonth2, monthList); ddlDailyMonth2.SelectedValue = _date.Month.ToString(); BindDropdownList(ddlDailyYear2, yearList); ddlDailyYear2.SelectedValue = _date.Year.ToString(); Dictionary<string, string> periodList = new Dictionary<string, string>(); periodList.Add("1-10", "1-10"); periodList.Add("11-20", "11-20"); periodList.Add("21-31", "21-31"); BindDropdownList(ddlPeriod, periodList); if (_date.Day <= 10) ddlPeriod.SelectedValue = "1-10"; if (_date.Day > 10 && _date.Day <= 20) ddlPeriod.SelectedValue = "11-20"; if (_date.Day > 20 && _date.Day <= 31) ddlPeriod.SelectedValue = "21-31"; } private void BindDropdownList(DropDownList ddl, Dictionary<string, string> data) { ddl.DataSource = data; ddl.DataTextField = "value"; ddl.DataValueField = "key"; ddl.DataBind(); } private void BindGridView(GridView grd) { DataTable dt = d.LoadData(ddlMonth, ddlYear, ddlValueType, ddlPeriod, "WS", true); d.GetHeader(lblTitle, ddlMonth, ddlYear, ddlValueType, ddlPeriod, "WS"); if (dt.Rows.Count > 0) { DataRow totalRow = dt.NewRow(); //totalRow["#"] = dt.Rows.Count + 1; totalRow["Sales Area"] = "TOTAL"; foreach (DataColumn column in dt.Columns) { if (column.ColumnName != "#" && column.ColumnName != "Sales Area") { var _col_total = 0; foreach (var x in dt.AsEnumerable()) { var _temp_data = x.Field<string>(column.ColumnName); var _data = !string.IsNullOrEmpty(_temp_data) ? Convert.ToInt32(_temp_data.ToString().Replace(",", "")) : 0; _col_total += _data; } totalRow[column.ColumnName] = _col_total.ToString("#,##0"); } } dt.Rows.InsertAt(totalRow, dt.Rows.Count); } if (dt.Rows.Count > 0) grd.DataSource = dt; else grd.DataSource = null; grd.DataBind(); } private void BindGridView(GridView grd, DropDownList _ddlMonth, DropDownList _ddlYear) { DataTable dt = d.GetDailyData(_ddlMonth, _ddlYear, null); if (dt.Rows.Count > 0) grd.DataSource = dt; else grd.DataSource = null; grd.DataBind(); if (grd.ID == "grdData") { lblDaily1.Text = _ddlMonth.SelectedItem.Text + " / " + _ddlYear.SelectedValue.ToString(); } else { lblDaily2.Text = _ddlMonth.SelectedItem.Text + " / " + _ddlYear.SelectedValue.ToString(); } } protected void grdDash1_RowDataBound(object sender, GridViewRowEventArgs e) { DataTable dt = ((DataTable)((BaseDataBoundControl)sender).DataSource); for (int j = 0; j < e.Row.Cells.Count; j++) { var cell = e.Row.Cells[j]; if (j == 0) { cell.HorizontalAlign = HorizontalAlign.Left; cell.Text = cell.Text + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; } else cell.HorizontalAlign = HorizontalAlign.Right; if (j >= 1 && j <= 3) { cell.BackColor = ColorTranslator.FromHtml("#A9D08E"); if (j == 3) cell.Font.Bold = true; } if (string.IsNullOrEmpty(cell.Text) || cell.Text == "0" || cell.Text == "&nbsp;") { cell.Text = "-"; cell.BackColor = ColorTranslator.FromHtml("#D9D9D9"); } if (j == 0) { cell.Width = 120; } else if (j > 0 && j <= 3) { cell.Width = 60; } else { cell.Width = 55; } } if (e.Row.RowIndex == dt.Rows.Count - 1) { e.Row.Font.Bold = true; } } protected void btnUpdate_Click(object sender, EventArgs e) { BindGridView(grdDash1); BindGridView(grdData, ddlDailyMonth, ddlDailyYear); BindGridView(grdData2, ddlDailyMonth2, ddlDailyYear2); } protected void btnSearch_Click(object sender, EventArgs e) { BindGridView(grdData, ddlDailyMonth, ddlDailyYear); } protected void btnSearch2_Click(object sender, EventArgs e) { BindGridView(grdData2, ddlDailyMonth2, ddlDailyYear2); } protected void grdData_RowDataBound(object sender, GridViewRowEventArgs e) { SetRowDataBound(sender, e); } protected void grdData2_RowDataBound(object sender, GridViewRowEventArgs e) { SetRowDataBound(sender, e); } private void SetRowDataBound(object sender, GridViewRowEventArgs e) { DataTable dt = ((DataTable)((BaseDataBoundControl)sender).DataSource); for (int j = 0; j < e.Row.Cells.Count; j++) { var cell = e.Row.Cells[j]; if (j <= 3) cell.HorizontalAlign = HorizontalAlign.Left; else cell.HorizontalAlign = HorizontalAlign.Right; if (string.IsNullOrEmpty(cell.Text) || cell.Text == "0.00" || cell.Text == "&nbsp;") { cell.Text = "-"; cell.BackColor = ColorTranslator.FromHtml("#D9D9D9"); } if (j == 0) { cell.Width = 20; } else if (j == 1) { cell.Width = 80; } else if (j == 2) { cell.Width = 80; } else if (j == 3) { cell.Width = 120; } else { cell.Width = 55; } } } }
namespace Memento { // This editor exposes API for any app to apply filter, change brightness etc for a photo // The editor also supports undo public class PhotoEditor { private Photo _photo; public PhotoEditor(Photo photo) { _photo = photo; } // Editor exposes method to apply filter on photo // Sets Brightness, Color etc based on Filter applied public void ApplyFilter(Filter filter) { switch (filter) { case Filter.Vivid: _photo.Brightness = 90; _photo.Sharpness = 90; _photo.Contrast = 90; _photo.Filter = Filter.Vivid; break; case Filter.BlackandWhite: _photo.Color = 0; _photo.Filter = Filter.BlackandWhite; break; case Filter.Cool: _photo.Brightness = 10; _photo.Sharpness = 10; _photo.Contrast = 10; _photo.Filter = Filter.Cool; break; default: case Filter.Original: break; } } // Editor exposes method to get the current state of photo in editor public Photo GetCurrentPhoto() { return _photo; } // Editor exposes method to create/get current state of editor public PhotoEditorState CreateState() { return new PhotoEditorState(new Photo { Filter = _photo.Filter, Brightness = _photo.Brightness, Sharpness = _photo.Sharpness, Contrast = _photo.Contrast, Color = _photo.Color }); } // Editor exposes method to restore state to any required state public void Restore(PhotoEditorState state) { _photo = state.GetPhoto(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace ClaimDi.Intergration.K4KObject { #region K4KReauest [XmlRoot(ElementName = "data")] [DataContract] public class K4KRequestData { [XmlElement("policy_owner")] [DataMember(Name = "policy_owner")] public PolicyOwner policyOwner { get; set; } [XmlElement("third_party")] [DataMember(Name = "third_party")] public ThirdParty thirdParty { get; set; } [XmlElement("location")] [DataMember(Name = "location")] public Location Location { get; set; } } [DataContract] public class NARequestData { [DataMember(Name = "policy_owner")] public PolicyOwner policyOwner { get; set; } [DataMember(Name = "location")] public Location Location { get; set; } } [DataContract] public class PolicyOwner { [XmlElement("policy_no")] [DataMember(Name = "policy_no")] public string policyNo { get; set; } [XmlElement("insurer_code")] [DataMember(Name = "insurer_code")] public string insurerCode { get; set; } [XmlElement("policy_effective")] [DataMember(Name = "policy_effective")] public string policyEffective { get; set; } [XmlElement("policy_risk_no")] [DataMember(Name = "policy_risk_no")] public string policyRiskNo { get; set; } [XmlElement("car_license_no")] [DataMember(Name = "car_license_no")] public string carLicenseNo { get; set; } [XmlElement("car_license_province")] [DataMember(Name = "car_license_province")] public string carLicenseProvince { get; set; } [XmlElement("car_license_province_short")] [DataMember(Name = "car_license_province_short")] public string carLicenseProvinceShort { get; set; } [XmlElement("owner_first_name")] [DataMember(Name = "owner_first_name")] public string ownerFirstName { get; set; } [XmlElement("owner_last_name")] [DataMember(Name = "owner_last_name")] public string ownerLastName { get; set; } [XmlElement("owner_mobile_no")] [DataMember(Name = "owner_mobile_no")] public string ownerMobileNo { get; set; } [XmlElement("driver_first_name")] [DataMember(Name = "driver_first_name")] public string driverFirstName { get; set; } [XmlElement("driver_last_name")] [DataMember(Name = "driver_last_name")] public string driverLastName { get; set; } [XmlElement("driver_mobile_no")] [DataMember(Name = "driver_mobile_no")] public string driverMobileNo { get; set; } [XmlElement("case_number")] [DataMember(Name = "case_number")] public string caseNumber { get; set; } [XmlElement("case_result")] [DataMember(Name = "case_result")] public string caseResult { get; set; } [XmlElement("case_datetime")] [DataMember(Name = "case_datetime")] public string caseDatetime { get; set; } } [DataContract] public class ThirdParty { [XmlElement("case_number")] [DataMember(Name = "case_number")] public string caseNumber { get; set; } [XmlElement("policy_no")] [DataMember(Name = "policy_no")] public string policyNo { get; set; } [XmlElement("insurer_code")] [DataMember(Name = "insurer_code")] public string insurerCode { get; set; } [XmlElement("insurer_name")] [DataMember(Name = "insurer_name")] public string insurerName { get; set; } [XmlElement("car_license_no")] [DataMember(Name = "car_license_no")] public string carLicenseNo { get; set; } [XmlElement("car_license_province")] [DataMember(Name = "car_license_province")] public string carLicenseProvince { get; set; } [XmlElement("car_license_province_short")] [DataMember(Name = "car_license_province_short")] public string carLicenseProvinceShort { get; set; } [XmlElement("owner_first_name")] [DataMember(Name = "owner_first_name")] public string ownerFirstName { get; set; } [XmlElement("owner_last_name")] [DataMember(Name = "owner_last_name")] public string ownerLastName { get; set; } [XmlElement("owner_mobile_no")] [DataMember(Name = "owner_mobile_no")] public string ownerMobileNo { get; set; } [XmlElement("driver_first_name")] [DataMember(Name = "driver_first_name")] public string driverFirstName { get; set; } [XmlElement("driver_last_name")] [DataMember(Name = "driver_last_name")] public string driverLastName { get; set; } [XmlElement("driver_mobile_no")] [DataMember(Name = "driver_mobile_no")] public string driverMobileNo { get; set; } [XmlElement("third_party_case_number")] [DataMember(Name = "third_party_case_number")] public string thirdPartyCaseNumber { get; set; } } [DataContract] public class Location { [XmlElement("case_number")] [DataMember(Name = "case_number")] public string caseNumber { get; set; } [XmlElement("place")] [DataMember(Name = "place")] public string place { get; set; } [XmlElement("latitude")] [DataMember(Name = "latitude")] public double latitude { get; set; } [XmlElement("longitude")] [DataMember(Name = "longitude")] public double longitude { get; set; } } #endregion K4KReauest #region K4KResult [DataContract] public class K4KResult { [DataMember(Name = "result")] public Result result { get; set; } [DataMember(Name = "policy")] public PolicyResult policy { get; set; } } public class PolicyResult { [DataMember(Name = "policy_no")] public string policy_no { get; set; } [DataMember(Name = "policy_effective")] public string policy_effective { get; set; } [DataMember(Name = "policy_expire")] public string policy_expire { get; set; } [DataMember(Name = "policy_risk_no")] public string policy_risk_no { get; set; } [DataMember(Name = "car_license_no")] public string car_license_no { get; set; } [DataMember(Name = "car_license_province")] public string car_license_province { get; set; } [DataMember(Name = "car_license_province_short")] public string car_license_province_short { get; set; } [DataMember(Name = "owner_first_name")] public string owner_first_name { get; set; } [DataMember(Name = "owner_last_name")] public string owner_last_name { get; set; } [DataMember(Name = "owner_mobile_no")] public string owner_mobile_no { get; set; } } public class Result { [DataMember(Name = "success")] public string success { get; set; } [DataMember(Name = "message")] public string message { get; set; } } #endregion K4KResult }
namespace GraphicalEditorServer.DTO { public class DoctorDTO { public string Name { get; set; } public string Surname { get; set; } public string Jmbg { get; set; } public DoctorDTO() { } public DoctorDTO(string name, string surname, string jmbg) { Name = name; Surname = surname; Jmbg = jmbg; } } }
using BinaryTree.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace BinaryTree { public class Tree<T> : ICollection<Node<T>> where T : IComparable { private int _count; private Node<T> _rootNode; public int Count => _count; public bool IsReadOnly => false; public void Add(Node<T> item) { if (_count == 0) _rootNode = item; else if (_count == 1) { var result = _rootNode.CompareTo(item); SetPosition(_rootNode, item, result); } else { var node = MoveTree(_rootNode, item); var result = node.CompareTo(item); if (result < 0) node.SetRIghtNode(item); else node.SetLeftNode(item); } _count++; } private Node<T> MoveTree(Node<T> nodeFather, Node<T> nodeChild) { var result = nodeFather.CompareTo(nodeChild); if (result == 0) throw new Exception("Error!"); if (result > 0 && nodeFather.LeftNode != null) return MoveTree(nodeFather.LeftNode, nodeChild); if (result < 1 && nodeFather.RightNode != null) return MoveTree(nodeFather.RightNode, nodeChild); return nodeFather; } private void SetPosition(Node<T> nodeFather, Node<T> nodeChild, int comparablePosition) { if (comparablePosition == 0) throw new Exception("Error!"); if (comparablePosition > 0) nodeFather.SetLeftNode(nodeChild); if (comparablePosition < 1) nodeFather.SetRIghtNode(nodeChild); } public void Clear() { _count = 0; _rootNode = null; } public bool Contains(Node<T> item) { return Find(item) != null; } public void CopyTo(Node<T>[] array, int arrayIndex) { throw new NotImplementedException(); } public IEnumerator<Node<T>> GetEnumerator() { return PrintTree(_rootNode).GetEnumerator(); } public IEnumerable<Node<T>> PrintTree(Node<T> node) { if (node == null) yield break; if (node.LeftNode != null) foreach (var subNode in PrintTree(node.LeftNode)) yield return subNode; yield return node; if (node.RightNode != null) foreach (var subNode in PrintTree(node.RightNode)) yield return subNode; } public bool Remove(Node<T> item) { if (!Contains(item)) return false; var nodeToRemove = Find(item); var nodeFather = FindNodeFather(nodeToRemove); if (nodeFather == _rootNode) { _rootNode = _rootNode.RightNode; Add(nodeToRemove.LeftNode); return true; } if (nodeToRemove.LeftNode == null && nodeToRemove.RightNode == null) { if (nodeToRemove.Value.CompareTo(nodeFather.Value) < 0) nodeFather.SetLeftNode(null); else nodeFather.SetRIghtNode(null); return true; } if (nodeToRemove.LeftNode != null && nodeToRemove.RightNode == null) { nodeFather.SetLeftNode(nodeToRemove.LeftNode); return true; } if (nodeToRemove.RightNode != null && nodeToRemove.LeftNode == null) { nodeFather.SetRIghtNode(nodeToRemove.RightNode); return true; } if (nodeToRemove.RightNode != null && nodeToRemove.LeftNode != null) { nodeFather.SetRIghtNode(nodeToRemove.RightNode); Add(nodeToRemove.LeftNode); return true; } return false; } private Node<T> FindNodeFather(Node<T> child) { var root = _rootNode; if (root == child) return root; while (root != null) { if (root.LeftNode == child || root.RightNode == child) return root; else if (child.Value.CompareTo(root.Value) > 0) root = root.RightNode; else root = root.LeftNode; } return null; ; } public Node<T> Find(Node<T> item) { var root = _rootNode; while (root != null) { if (root.Value.Equals(item.Value)) return root; else if (item.Value.CompareTo(root.Value) > 0) root = root.RightNode; else root = root.LeftNode; } return null; } IEnumerator IEnumerable.GetEnumerator() { return PrintTree(_rootNode).GetEnumerator(); } public int Height() { var lista = new List<Node<T>>(); var height = 0; var enumerator = GetEnumerator(); enumerator.MoveNext(); do { var current = enumerator.Current; if (current.LeftNode == null && current.RightNode == null) lista.Add(current); } while (enumerator.MoveNext()); foreach (var item in lista) { var h = HeightOfNode(item); if (h > height) height = h; } return height; } private int HeightOfNode(Node<T> node) { var root = _rootNode; int count = 0; while (root != null) { if (root.Value.Equals(node.Value)) return count; else if (node.Value.CompareTo(root.Value) > 0) root = root.RightNode; else root = root.LeftNode; count++; } return -1; ; } public void ReBalanceTree() { var itens = new List<Node<T>>(); var enumerator = GetEnumerator(); Clear(); var index = 0; enumerator.MoveNext(); do { itens.Add(enumerator.Current); } while (enumerator.MoveNext()); itens.Sort(); var middle = itens.Count / 2; //Add(itens[middle]); AddBalanced(itens.GetRange(0, middle)); AddBalanced(itens.GetRange(middle, itens.Count - (middle ))); } void AddBalanced(List<Node<T>> list) { if (list.Count == 0) return; var middle = Convert.ToInt32(Math.Ceiling((list.Count - 1) / 2.0)); Add(list[middle]); if (middle == 0) return; AddBalanced(list.GetRange(0, middle)); if (list.Count >= (middle + 1)) AddBalanced(list.GetRange(middle + 1, list.Count - 1)); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using tellick_admin.Repository; namespace tellick_admin.Controllers { [Authorize] [Route("api/[controller]")] public class LogController : Controller { private GenericRepository<Project> _projectRepository; private GenericRepository<Log> _logRepository; public LogController(TellickAdminContext context) { _projectRepository = new GenericRepository<Project>(context); _logRepository = new GenericRepository<Log>(context); } [HttpGet(Name = "GetAllLogs")] public IActionResult GetAllLogs() { return NotFound(); } [HttpGet("{projectName}", Name = "GetLog")] public IActionResult GetLog(string projectName) { int year = DateTime.Now.Year; int month = DateTime.Now.Month; Log[] logs = _logRepository.SearchFor(i => i.Project.Name == projectName && i.ForDate.Month == month && i.ForDate.Year == year, includeProperties: "Project").ToArray(); return Ok(logs); } [HttpGet("{projectName}/{dateSpecification}", Name = "GetLogByProjectName")] public IActionResult GetLogSpecific(string projectName, string dateSpecification) { Project p = _projectRepository.SearchFor(i => i.Name == projectName).SingleOrDefault(); if (p == null) BadRequest("Project does not exist"); // DateSpecification is either yyyy or yyyy-M and nothing else string[] parts = dateSpecification.Split('-'); if (parts.Length == 1) { int year; if (Int32.TryParse(parts[0], out year)) { Log[] logs = _logRepository.SearchFor(i => i.Project.Name == projectName && i.ForDate.Year == year, includeProperties: "Project").ToArray(); return Ok(logs); } else { return BadRequest(); } } if (parts.Length == 2) { int year; int month; if (Int32.TryParse(parts[0], out year) && Int32.TryParse(parts[1], out month) && month >= 1 && month <= 12) { Log[] logs = _logRepository.SearchFor(i => i.Project.Name == projectName && i.ForDate.Month == month && i.ForDate.Year == year, includeProperties: "Project").ToArray(); return Ok(logs); } else { return BadRequest(); } } return BadRequest(); } [HttpPost] public IActionResult Create([FromBody] Log item) { if (item == null) return BadRequest(); Project p = _projectRepository.GetByID(item.ProjectId); if (p == null) BadRequest("Project does not exist"); _logRepository.Insert(item); _logRepository.Save(); return CreatedAtRoute("GetLogByProjectName", new { projectName = p.Name }, item); } } }
using System; using Net01_1.Inerface; namespace Net01_1.Model { class VideoMaterial:BaseTrainingMaterial, IVersionable, ICloneable { public Uri VideoUri { get; set; } public Uri HeadBandUri { get; set; } public VideoFormat VideoFormat { get; set; } public Byte[] Version { get; set; } public VideoMaterial() { Version = new byte[8]; } public override string ToString() { return Description; } public object Clone() { var video = new VideoMaterial { HeadBandUri = HeadBandUri, Version = Version, VideoFormat = VideoFormat, VideoUri = VideoUri, Id = Id, Description = Description }; return video; } } }
/// <summary> /// 2015 /// Ben Redahan, redahanb@gmail.com /// Project: Spectral - The Silicon Domain (Unity) /// GameState component: handles the GameState for transitions between scenes, Saving and Loading savefiles /// </summary> using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; public class GameState : MonoBehaviour { public static GameState gameState; private HealthManager pHealth; private HUD_Healthbar healthHUD; private PlayerInventory pInventory; private InventoryItem invItem; private HUD_Inventory invHUD; private TimeScaler pTime; private Color tempColor; // Singleton design pattern - there can only be one GameState Object: the one from the first scene loaded void Awake () { if (gameState == null) { // If this is the first scene loaded, set this as the GameState object DontDestroyOnLoad (gameObject); gameState = this; } else { // If a GameState object already exists, destroy this object, leaving the pre-existing GameState in the scene if(gameState != gameObject){ Destroy(gameObject); } } } void Start() { // Cache references to scripts that utilise GameState variables pHealth = GameObject.Find ("Health Manager").GetComponent<HealthManager> (); healthHUD = GameObject.Find ("HUD_Healthbar").GetComponent<HUD_Healthbar> (); pInventory = GameObject.Find ("Inventory Manager").GetComponent<PlayerInventory> (); invHUD = GameObject.Find ("HUD_Inventory").GetComponent<HUD_Inventory> (); pTime = GameObject.Find("Time Manager").GetComponent<TimeScaler>(); // Load game at the start of every scene LoadGame (); } void Update () { } public void SaveGame() { // Create a biary formatter, save file and empty savedata object BinaryFormatter bf = new BinaryFormatter (); FileStream file = File.Create (Application.persistentDataPath + "/playerInfo.dat"); SaveData data = new SaveData (); // Store player stats into savedata data.currentHealth = pHealth.playerHealth; data.maxHealth = pHealth.maxHealth; data.inventorySize = pInventory.inventorySize; // Inventory contents have to be stored as primitive values: can't use binary formatter on GameObjects or prefabs data.itemNames = new string[pInventory.inventorySize]; data.itemValues = new string[pInventory.inventorySize]; data.itemColours = new float[pInventory.inventorySize][]; for(int x = 0; x < pInventory.playerInventory.Length; x++) { // Store the key parameters for each item in the inventory if(pInventory.playerInventory[x] != null){ InventoryItem tempInfo = pInventory.playerInventory[x].GetComponent<InventoryItem>(); data.itemNames[x] = tempInfo.name; tempColor = tempInfo.itemColor; //data.itemColors[x] = new Vector3(tempColor.r, tempColor.b, tempColor.g); float[] tempArray = new float[3]{tempColor.r, tempColor.b, tempColor.g}; data.itemColours[x] = tempArray; data.itemValues[x] = tempInfo.itemValue; } } // Save time upgrade parameters data.maxStoredTime = pTime.GetMaxStoredTime (); data.noiseDampening = pTime.GetNoiseDampening (); // Serialize and commit the savedata into the savefile bf.Serialize (file, data); file.Close (); print ("Saving Game..."); } // end SaveGame public void LoadGame() { BinaryFormatter bf = new BinaryFormatter(); SaveData data; if (File.Exists (Application.persistentDataPath + "/playerInfo.dat")) { print ("Save file found!"); FileStream file = File.Open (Application.persistentDataPath + "/playerInfo.dat", FileMode.Open); data = (SaveData)bf.Deserialize (file); file.Close (); // Update player stats from save file pHealth.maxHealth = data.maxHealth; pHealth.playerHealth = data.maxHealth; // give player full health at start of a new scene pInventory.inventorySize = data.inventorySize; pInventory.playerInventory = new GameObject[pInventory.inventorySize]; // Compile inventory contents for(int x = 0; x < data.inventorySize; x++){ if(data.itemNames[x] != null) { GameObject tempItem = Instantiate( Resources.Load("Pickups/" + data.itemNames[x]), new Vector3(-50,-50,-50), Quaternion.identity ) as GameObject; invItem = tempItem.GetComponent<InventoryItem>(); // Update item stats invItem.name = data.itemNames[x]; invItem.itemName = data.itemNames[x]; invItem.itemValue = data.itemValues[x]; tempColor = new Color(); tempColor.r = data.itemColours[x][0]; tempColor.b = data.itemColours[x][1]; tempColor.g = data.itemColours[x][2]; tempColor.a = 1.0f; invItem.itemColor = tempColor; // Hide and disable the item, and add to player inventory pInventory.playerInventory[x] = tempItem; } } // Build inventory HUD and update the icons invHUD.buildInventoryUI (pInventory.inventorySize); invHUD.UpdateAllIcons(); // Build the health HUD, set health to full healthHUD.buildHealthbarUI(pHealth.maxHealth); healthHUD.healthBarSize = pHealth.maxHealth; // Set time upgrade data pTime.SetMaxStoredTime(data.maxStoredTime); pTime.SetNoiseDampening(data.noiseDampening); } else { // If no save file, use the default settings print ("No save file found... Initialising default player stats."); // Default health pHealth.maxHealth = 3; pHealth.playerHealth = 3; // Default inventory pInventory.inventorySize = 4; pInventory.playerInventory = new GameObject[4]; // Build default HUD invHUD.buildInventoryUI (4); healthHUD.buildHealthbarUI(3); healthHUD.healthBarSize = 3; // Default time upgrades pTime.SetMaxStoredTime(5.0f); pTime.SetNoiseDampening(false); } } // end LoadGame public void ResetGame() { // Function for use in the Restore Point, clear all data in the save file, restart the game print ("Clearing saved data..."); // Default health pHealth.maxHealth = 3; pHealth.playerHealth = 3; // Default inventory pInventory.inventorySize = 4; pInventory.playerInventory = new GameObject[4]; // Default time upgrades pTime.SetMaxStoredTime(5.0f); pTime.SetNoiseDampening(false); // Save data to the save file SaveGame (); // Restart the game from scene 0 (splash screen) Application.LoadLevel (0); } /// SAVE FILE DATA MODEL /// [Serializable] private class SaveData // Private class to serve as a container for all relevant data to be saved { // Health Data public int currentHealth; public int maxHealth; // Inventory Data public int inventorySize; public string[] itemNames; public string[] itemValues; public float[][] itemColours; // Time Upgrade Data public float maxStoredTime; public bool noiseDampening; } // end SaveData class }
namespace gView.Framework.Symbology { public interface IFontColor { GraphicsEngine.ArgbColor FontColor { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HASRental.Models { public class Proizvodjac { public int Id { get; set; } public string Naziv { get; set; } } }
using AkCore.E2ETests.Enums; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AkCore.E2ETests { [TestClass] public class LoginTests : E2ETestsBase { private static TestContext _context; [ClassInitialize] public static void TestClassInitialize(TestContext context) { _context = context; } [DataTestMethod] [DataRow(Browser.DesktopChrome)] public void Login_in_with_correct_username( Browser browser) { BaseTestClassInitialize(_context); SetDrivers(browser); Driver.Navigate().GoToUrl(appUrl); var page = new LoginPage(Driver); page.Login(login.UserName, login.Password); var profileLink = Driver.WaitFindSelector(".profile-link"); Assert.IsNotNull(profileLink); Assert.AreEqual(profileLink.Text, login.UserName); } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using RabbitMQ.Client.Core.DependencyInjection; using VetClinicPublic.Web.Interfaces; using VetClinicPublic.Web.Services; namespace VetClinicPublic { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddSingleton<ISendConfirmationEmails, SmtpConfirmationEmailSender>(); // https://github.com/AntonyVorontsov/RabbitMQ.Client.Core.DependencyInjection/tree/master/examples/Examples.AdvancedConfiguration var rabbitMqConsumerSection = Configuration.GetSection("RabbitMqConsumer"); var rabbitMqProducerSection = Configuration.GetSection("RabbitMqProducer"); var producingExchangeSection = Configuration.GetSection("ProducingExchange"); var consumingExchangeSection = Configuration.GetSection("ConsumingExchange"); services .AddRabbitMqConsumingClientSingleton(rabbitMqConsumerSection) .AddRabbitMqProducingClientSingleton(rabbitMqProducerSection) .AddProductionExchange("exchange.to.send.messages.only", producingExchangeSection) .AddConsumptionExchange("consumption.exchange", consumingExchangeSection) .AddMessageHandlerSingleton<CustomMessageHandler>("routing.key"); services.AddHostedService<ConsumingHostedService>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } // configure docker compose // http://codereform.com/blog/post/net-core-and-rabbitmq/ }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SMG.Common.Effects { /// <summary> /// Effect of the CALL action. Invokes a method in the target code class. /// </summary> public class CallEffect : Effect { #region Private string _name; #endregion /// <summary> /// The name of the method. /// </summary> public string MethodName { get { return _name; } } public override string UniqueID { get { return "CALL " + _name; } } public CallEffect(StateMachine sm, string name) { sm.AddMethod(name); _name = name; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LightingBook.Tests.Api.Dto.Dto.GetFinalItinerary.Response.Search.Passenger { public class PersonalMembership { public string MembershipNumber { get; set; } public string MembershipProgram { get; set; } public string MembershipTypeCode { get; set; } public string CompanyCode { get; set; } public string CompanyName { get; set; } } }
using System; using System.Collections.Generic; using System.Collections; using System.Text; namespace CursoCsharp.Colecoes { class ColecoesQueue { public static void Executar() { var fila = new Queue<string>(); // esse usa o using System.Collections.Generic; fila.Enqueue("Leonardo"); fila.Enqueue("Sicano"); fila.Enqueue("Beutrano"); Console.WriteLine("Primeiro da fila: " + fila.Peek());// mostra o primeiro da lista, sem remover ele da lista Console.WriteLine("Quantidade de pessoas na fila: " + fila.Count);// provar que nao saiu da fila, mostra em numeração Console.WriteLine("=============================="); Console.WriteLine("Excluir da fila: " + fila.Dequeue());// remover o primeiro da fila Console.WriteLine("Quantidade de pessoas na fila: " + fila.Count); Console.WriteLine("=============================="); foreach(var pessoa in fila) { Console.WriteLine("Proximos da fila: " + pessoa); } Console.WriteLine("=============================="); var salada = new Queue(); // esse usa o using System.Collections; salada.Enqueue(3); salada.Enqueue("Item"); salada.Enqueue(true); salada.Enqueue(3.14); foreach(var t in salada) { Console.WriteLine("Lista de Queue: " + t); } } } }
using System; using System.Collections.Generic; using System.Text; namespace Mars.Helpers { class ScenarioContextData { public Int64 intNum { get; set; } } }
using UnityEngine; using System.Collections; public class ItemController : MonoBehaviour { void OnTriggerEnter2D(Collider2D c2d_) { Collider2D c2d = this.gameObject.GetComponent<Collider2D>(); if (c2d && c2d.isTrigger) { //GlobalRef.s_gr.PlaySound(ESound.SOUND_ITEM_COLLISION); Destroy(this.gameObject); } } }
using System; using System.Collections.Generic; using Android.Runtime; namespace RU.Tinkoff.Acquiring.Sdk { // Metadata.xml XPath class reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='ThreeDsData']" [global::Android.Runtime.Register ("ru/tinkoff/acquiring/sdk/ThreeDsData", DoNotGenerateAcw=true)] public partial class ThreeDsData : global::Java.Lang.Object { static IntPtr EMPTY_THREE_DS_DATA_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='ThreeDsData']/field[@name='EMPTY_THREE_DS_DATA']" [Register ("EMPTY_THREE_DS_DATA")] public static global::RU.Tinkoff.Acquiring.Sdk.ThreeDsData EmptyThreeDsData { get { if (EMPTY_THREE_DS_DATA_jfieldId == IntPtr.Zero) EMPTY_THREE_DS_DATA_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "EMPTY_THREE_DS_DATA", "Lru/tinkoff/acquiring/sdk/ThreeDsData;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, EMPTY_THREE_DS_DATA_jfieldId); return global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.ThreeDsData> (__ret, JniHandleOwnership.TransferLocalRef); } } internal static new IntPtr java_class_handle; internal static new IntPtr class_ref { get { return JNIEnv.FindClass ("ru/tinkoff/acquiring/sdk/ThreeDsData", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (ThreeDsData); } } protected ThreeDsData (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Ljava_lang_Long_Ljava_lang_String_Ljava_lang_Long_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_; // Metadata.xml XPath constructor reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='ThreeDsData']/constructor[@name='ThreeDsData' and count(parameter)=6 and parameter[1][@type='java.lang.Long'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.Long'] and parameter[4][@type='java.lang.String'] and parameter[5][@type='java.lang.String'] and parameter[6][@type='java.lang.String']]" [Register (".ctor", "(Ljava/lang/Long;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", "")] public unsafe ThreeDsData (global::Java.Lang.Long p0, string p1, global::Java.Lang.Long p2, string p3, string p4, string p5) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; IntPtr native_p1 = JNIEnv.NewString (p1); IntPtr native_p3 = JNIEnv.NewString (p3); IntPtr native_p4 = JNIEnv.NewString (p4); IntPtr native_p5 = JNIEnv.NewString (p5); try { JValue* __args = stackalloc JValue [6]; __args [0] = new JValue (p0); __args [1] = new JValue (native_p1); __args [2] = new JValue (p2); __args [3] = new JValue (native_p3); __args [4] = new JValue (native_p4); __args [5] = new JValue (native_p5); if (((object) this).GetType () != typeof (ThreeDsData)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "(Ljava/lang/Long;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "(Ljava/lang/Long;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", __args); return; } if (id_ctor_Ljava_lang_Long_Ljava_lang_String_Ljava_lang_Long_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero) id_ctor_Ljava_lang_Long_Ljava_lang_String_Ljava_lang_Long_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/lang/Long;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_lang_Long_Ljava_lang_String_Ljava_lang_Long_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor_Ljava_lang_Long_Ljava_lang_String_Ljava_lang_Long_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_, __args); } finally { JNIEnv.DeleteLocalRef (native_p1); JNIEnv.DeleteLocalRef (native_p3); JNIEnv.DeleteLocalRef (native_p4); JNIEnv.DeleteLocalRef (native_p5); } } static Delegate cb_getAcsUrl; #pragma warning disable 0169 static Delegate GetGetAcsUrlHandler () { if (cb_getAcsUrl == null) cb_getAcsUrl = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetAcsUrl); return cb_getAcsUrl; } static IntPtr n_GetAcsUrl (IntPtr jnienv, IntPtr native__this) { global::RU.Tinkoff.Acquiring.Sdk.ThreeDsData __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.ThreeDsData> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.AcsUrl); } #pragma warning restore 0169 static IntPtr id_getAcsUrl; public virtual unsafe string AcsUrl { // Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='ThreeDsData']/method[@name='getAcsUrl' and count(parameter)=0]" [Register ("getAcsUrl", "()Ljava/lang/String;", "GetGetAcsUrlHandler")] get { if (id_getAcsUrl == IntPtr.Zero) id_getAcsUrl = JNIEnv.GetMethodID (class_ref, "getAcsUrl", "()Ljava/lang/String;"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getAcsUrl), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getAcsUrl", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } } static Delegate cb_getAmount; #pragma warning disable 0169 static Delegate GetGetAmountHandler () { if (cb_getAmount == null) cb_getAmount = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetAmount); return cb_getAmount; } static IntPtr n_GetAmount (IntPtr jnienv, IntPtr native__this) { global::RU.Tinkoff.Acquiring.Sdk.ThreeDsData __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.ThreeDsData> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.Amount); } #pragma warning restore 0169 static IntPtr id_getAmount; public virtual unsafe global::Java.Lang.Long Amount { // Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='ThreeDsData']/method[@name='getAmount' and count(parameter)=0]" [Register ("getAmount", "()Ljava/lang/Long;", "GetGetAmountHandler")] get { if (id_getAmount == IntPtr.Zero) id_getAmount = JNIEnv.GetMethodID (class_ref, "getAmount", "()Ljava/lang/Long;"); try { if (((object) this).GetType () == ThresholdType) return global::Java.Lang.Object.GetObject<global::Java.Lang.Long> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getAmount), JniHandleOwnership.TransferLocalRef); else return global::Java.Lang.Object.GetObject<global::Java.Lang.Long> (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getAmount", "()Ljava/lang/Long;")), JniHandleOwnership.TransferLocalRef); } finally { } } } static Delegate cb_isThreeDsNeed; #pragma warning disable 0169 static Delegate GetIsThreeDsNeedHandler () { if (cb_isThreeDsNeed == null) cb_isThreeDsNeed = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_IsThreeDsNeed); return cb_isThreeDsNeed; } static bool n_IsThreeDsNeed (IntPtr jnienv, IntPtr native__this) { global::RU.Tinkoff.Acquiring.Sdk.ThreeDsData __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.ThreeDsData> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.IsThreeDsNeed; } #pragma warning restore 0169 static IntPtr id_isThreeDsNeed; public virtual unsafe bool IsThreeDsNeed { // Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='ThreeDsData']/method[@name='isThreeDsNeed' and count(parameter)=0]" [Register ("isThreeDsNeed", "()Z", "GetIsThreeDsNeedHandler")] get { if (id_isThreeDsNeed == IntPtr.Zero) id_isThreeDsNeed = JNIEnv.GetMethodID (class_ref, "isThreeDsNeed", "()Z"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.CallBooleanMethod (((global::Java.Lang.Object) this).Handle, id_isThreeDsNeed); else return JNIEnv.CallNonvirtualBooleanMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "isThreeDsNeed", "()Z")); } finally { } } } static Delegate cb_getMd; #pragma warning disable 0169 static Delegate GetGetMdHandler () { if (cb_getMd == null) cb_getMd = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetMd); return cb_getMd; } static IntPtr n_GetMd (IntPtr jnienv, IntPtr native__this) { global::RU.Tinkoff.Acquiring.Sdk.ThreeDsData __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.ThreeDsData> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.Md); } #pragma warning restore 0169 static IntPtr id_getMd; public virtual unsafe string Md { // Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='ThreeDsData']/method[@name='getMd' and count(parameter)=0]" [Register ("getMd", "()Ljava/lang/String;", "GetGetMdHandler")] get { if (id_getMd == IntPtr.Zero) id_getMd = JNIEnv.GetMethodID (class_ref, "getMd", "()Ljava/lang/String;"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getMd), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getMd", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } } static Delegate cb_getOrderId; #pragma warning disable 0169 static Delegate GetGetOrderIdHandler () { if (cb_getOrderId == null) cb_getOrderId = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetOrderId); return cb_getOrderId; } static IntPtr n_GetOrderId (IntPtr jnienv, IntPtr native__this) { global::RU.Tinkoff.Acquiring.Sdk.ThreeDsData __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.ThreeDsData> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.OrderId); } #pragma warning restore 0169 static IntPtr id_getOrderId; public virtual unsafe string OrderId { // Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='ThreeDsData']/method[@name='getOrderId' and count(parameter)=0]" [Register ("getOrderId", "()Ljava/lang/String;", "GetGetOrderIdHandler")] get { if (id_getOrderId == IntPtr.Zero) id_getOrderId = JNIEnv.GetMethodID (class_ref, "getOrderId", "()Ljava/lang/String;"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getOrderId), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getOrderId", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } } static Delegate cb_getPaReq; #pragma warning disable 0169 static Delegate GetGetPaReqHandler () { if (cb_getPaReq == null) cb_getPaReq = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetPaReq); return cb_getPaReq; } static IntPtr n_GetPaReq (IntPtr jnienv, IntPtr native__this) { global::RU.Tinkoff.Acquiring.Sdk.ThreeDsData __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.ThreeDsData> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.PaReq); } #pragma warning restore 0169 static IntPtr id_getPaReq; public virtual unsafe string PaReq { // Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='ThreeDsData']/method[@name='getPaReq' and count(parameter)=0]" [Register ("getPaReq", "()Ljava/lang/String;", "GetGetPaReqHandler")] get { if (id_getPaReq == IntPtr.Zero) id_getPaReq = JNIEnv.GetMethodID (class_ref, "getPaReq", "()Ljava/lang/String;"); try { if (((object) this).GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getPaReq), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getPaReq", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } } static Delegate cb_getPaymentId; #pragma warning disable 0169 static Delegate GetGetPaymentIdHandler () { if (cb_getPaymentId == null) cb_getPaymentId = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetPaymentId); return cb_getPaymentId; } static IntPtr n_GetPaymentId (IntPtr jnienv, IntPtr native__this) { global::RU.Tinkoff.Acquiring.Sdk.ThreeDsData __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.ThreeDsData> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.PaymentId); } #pragma warning restore 0169 static IntPtr id_getPaymentId; public virtual unsafe global::Java.Lang.Long PaymentId { // Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='ThreeDsData']/method[@name='getPaymentId' and count(parameter)=0]" [Register ("getPaymentId", "()Ljava/lang/Long;", "GetGetPaymentIdHandler")] get { if (id_getPaymentId == IntPtr.Zero) id_getPaymentId = JNIEnv.GetMethodID (class_ref, "getPaymentId", "()Ljava/lang/Long;"); try { if (((object) this).GetType () == ThresholdType) return global::Java.Lang.Object.GetObject<global::Java.Lang.Long> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getPaymentId), JniHandleOwnership.TransferLocalRef); else return global::Java.Lang.Object.GetObject<global::Java.Lang.Long> (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getPaymentId", "()Ljava/lang/Long;")), JniHandleOwnership.TransferLocalRef); } finally { } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BE; using System.Xml.Linq; namespace DAL { internal class Dal_XML : IDal { public int addMother(Mother m) { DS.DatasourceXML.Mothers.Add(m.toXML()); DS.DatasourceXML.SaveMothers(); return m.ID; } private int MaxContractID() { int result; var kayam = DS.DatasourceXML.Contracts.Elements("Contract").Any(); if (!kayam) { result = 100000; } else { result = (from c in DS.DatasourceXML.Contracts.Elements("Contract") select Int32.Parse(c.Element("ContractID").Value)).Max(); } return result; } public int addContract(Contract c) { //ContractNannyChild contract = c.clone(); //contract.ContractID = MaxContractID() + 1; //DS.DatasourceXML.Contracts.Add(contract.toXML()); XElement contract = c.toXML(); contract.Element("ContractID").Value = (MaxContractID() + 1).ToString(); DS.DatasourceXML.Contracts.Add(contract); DS.DatasourceXML.SaveContracts(); return Int32.Parse(contract.Element("ContractID").Value); } public IEnumerable<Mother> getAllMothers() { XElement root = DS.DatasourceXML.Mothers; List<Mother> result = new List<Mother>(); foreach (var m in root.Elements("Mother")) { result.Add(m.toMother()); } return result.AsEnumerable(); } public IEnumerable<Contract> getAllContracts() { XElement root = DS.DatasourceXML.Contracts; List<Contract> result = new List<Contract>(); foreach (var c in root.Elements("Contract")) { result.Add(c.toContract()); } return result.AsEnumerable(); } public bool removeMother(Mother m) { throw new NotImplementedException(); } public bool removeContract(Contract c) { throw new NotImplementedException(); } } }
using NGeoNames.Entities; namespace NGeoNames.Entities { /// <summary> /// Provides geolocation related extension methods. /// </summary> public static class GeoExtensionMethods { /// <summary> /// Calculates the distance from this instance to destination location (in meters). /// </summary> /// <param name="loc">The <see cref="IGeoLocation"/> to apply the method to.</param> /// <param name="lat">The latitude of the destination point.</param> /// <param name="lng">The longitude of the destination point.</param> /// <returns>Returns the distance, in meters, from this instance to destination.</returns> /// <remarks> /// Note that we use the <a href="http://en.wikipedia.org/wiki/International_System_of_Units">International /// System of Units (SI)</a>; units of distance are specified in meters. If you want to use imperial system (e.g. /// miles, nautical miles, yards, foot and other units) you need to convert from/to meters. You can use the /// helper methods <see cref="GeoUtil.MilesToMeters"/> / <see cref="GeoUtil.MetersToMiles"/> and /// <see cref="GeoUtil.YardsToMeters"/> / <see cref="GeoUtil.MetersToYards"/> for quick conversion. /// </remarks> /// <seealso cref="GeoUtil.MilesToMeters"/> /// <seealso cref="GeoUtil.MetersToMiles"/> /// <seealso cref="GeoUtil.YardsToMeters"/> /// <seealso cref="GeoUtil.MetersToYards"/> public static double DistanceTo(this IGeoLocation loc, double lat, double lng) { return GeoUtil.DistanceTo(loc, new GeoName { Latitude = lat, Longitude = lng }); } /// <summary> /// Calculates the distance from this instance to destination location (in meters). /// </summary> /// <param name="loc">The <see cref="IGeoLocation"/> to apply the method to.</param> /// <param name="lat">The latitude of the destination point.</param> /// <param name="lng">The longitude of the destination point.</param> /// <param name="radiusofearthinmeters">The radius of the earth in meters (default: 6371000).</param> /// <returns>Returns the distance, in meters, from this instance to destination.</returns> /// <remarks> /// Note that we use the <a href="http://en.wikipedia.org/wiki/International_System_of_Units">International /// System of Units (SI)</a>; units of distance are specified in meters. If you want to use imperial system (e.g. /// miles, nautical miles, yards, foot and other units) you need to convert from/to meters. You can use the /// helper methods <see cref="GeoUtil.MilesToMeters"/> / <see cref="GeoUtil.MetersToMiles"/> and /// <see cref="GeoUtil.YardsToMeters"/> / <see cref="GeoUtil.MetersToYards"/> for quick conversion. /// </remarks> /// <seealso cref="GeoUtil.MilesToMeters"/> /// <seealso cref="GeoUtil.MetersToMiles"/> /// <seealso cref="GeoUtil.YardsToMeters"/> /// <seealso cref="GeoUtil.MetersToYards"/> public static double DistanceTo(this IGeoLocation loc, double lat, double lng, double radiusofearthinmeters) { return GeoUtil.DistanceTo(loc, new GeoName { Latitude = lat, Longitude = lng }, radiusofearthinmeters); } /// <summary> /// Calculates the distance from the this instance to destination location (in meters). /// </summary> /// <param name="src">The <see cref="IGeoLocation"/> to apply the method to.</param> /// <param name="dst">The destination location.</param> /// <returns>Returns the distance, in meters, from this instance to destination.</returns> /// <remarks> /// Note that we use the <a href="http://en.wikipedia.org/wiki/International_System_of_Units">International /// System of Units (SI)</a>; units of distance are specified in meters. If you want to use imperial system (e.g. /// miles, nautical miles, yards, foot and other units) you need to convert from/to meters. You can use the /// helper methods <see cref="GeoUtil.MilesToMeters"/> / <see cref="GeoUtil.MetersToMiles"/> and /// <see cref="GeoUtil.YardsToMeters"/> / <see cref="GeoUtil.MetersToYards"/> for quick conversion. /// </remarks> /// <seealso cref="GeoUtil.MilesToMeters"/> /// <seealso cref="GeoUtil.MetersToMiles"/> /// <seealso cref="GeoUtil.YardsToMeters"/> /// <seealso cref="GeoUtil.MetersToYards"/> public static double DistanceTo(this IGeoLocation src, IGeoLocation dst) { return GeoUtil.DistanceTo(src, dst); } /// <summary> /// Calculates the distance from this instance to destination location (in meters). /// </summary> /// <param name="src">The <see cref="IGeoLocation"/> to apply the method to.</param> /// <param name="dst">The destination location.</param> /// <param name="radiusofearthinmeters">The radius of the earth in meters (default: 6371000).</param> /// <returns>Returns the distance, in meters, from this instance to destination.</returns> /// <remarks> /// Note that we use the <a href="http://en.wikipedia.org/wiki/International_System_of_Units">International /// System of Units (SI)</a>; units of distance are specified in meters. If you want to use imperial system (e.g. /// miles, nautical miles, yards, foot and other units) you need to convert from/to meters. You can use the /// helper methods <see cref="GeoUtil.MilesToMeters"/> / <see cref="GeoUtil.MetersToMiles"/> and /// <see cref="GeoUtil.YardsToMeters"/> / <see cref="GeoUtil.MetersToYards"/> for quick conversion. /// </remarks> /// <seealso cref="GeoUtil.MilesToMeters"/> /// <seealso cref="GeoUtil.MetersToMiles"/> /// <seealso cref="GeoUtil.YardsToMeters"/> /// <seealso cref="GeoUtil.MetersToYards"/> public static double DistanceTo(this IGeoLocation src, IGeoLocation dst, double radiusofearthinmeters) { return GeoUtil.DistanceTo(src, dst, radiusofearthinmeters); } } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace SP_Bewegungserkennung { /** * Class point, which describes an 2-dimentional vector, and it's operations */ [DataContract] public class point : IComparable<point>, IEquatable<point> { [DataMember] /** * \param x is a x-coordinate of a 2-dimensional vector * \param y is a y-coordinate of a 2-dimensional vector * \param time is a time stamp of a point */ public double x { get; private set; } [DataMember] public double y { get; private set; } [DataMember] public long time { get; private set; } /** * Constructor, which defines a point with x and y coordinates and a default time variable */ public point(double px, double py) { x = px; y = py; time = 0; } /** * Constructor, which defines new point from an exsiting point */ public point(point p) { x = p.x; y = p.y; time = p.time; } /** * Constructor, which defines a point with x and y coordinates and a time variable */ public point(double px, double py, long t) { x = px; y = py; time = t; } /** * Addition of a point on to existing one */ public void addition(point ipt) { this.x += ipt.x; this.y += ipt.y; } /** * Subsraction of one point from another */ public static point substract(point p1, point p2) { return new point(p1.x - p2.x, p1.y - p2.y); } /** * Division of a point with a variable */ public void divide(int c) { this.x /= c; this.y /= c; } /** * Mutiplicatoin of a point with a variable */ public point mult(double m) { return new point(this.x * m, this.y * m); } /** * Mutiplicatoin of an existing point with a given point */ public void multiply(point p) { this.x *= p.x; this.y *= p.y; } /** * Exponentianlion function of a point as a base and a variable n as an exponent */ public point power(double n) { return new point(Math.Pow(this.x, n), Math.Pow(this.y, n)); } /** * Square root function of a point */ public point sqroot() { return new point(Math.Sqrt(this.x), Math.Sqrt(this.y)); } /** * An absolte value function of a given point */ public static point abs(point p) { return new point(Math.Abs(p.x), Math.Abs(p.y)); } /** * Comparison of two points, according to x and y */ public bool compareXY(point p) { return this.x <= p.x && this.y <= p.y; } /** * Comparison of two points, according to x */ public int CompareTo(point comparepoint) { if (comparepoint == null) return 1; if (this.x == comparepoint.x) return this.y.CompareTo(comparepoint.y); return this.x.CompareTo(comparepoint.x); } /** *Euclidean distance function between an existing point and a given one */ public double distance(point p) { return Math.Sqrt(Math.Pow(this.x - p.x, 2) + Math.Pow(this.y - p.y, 2)); } /** * Equality function between an existing point and a given one */ public bool Equals(point eqpoint) { if (this.x == eqpoint.x && this.y == eqpoint.y) return true; return false; } /** * ToString function, which returns a string of x and y coordinates of a point in format (x,y) */ public override String ToString() { return "(" + this.x.ToString() + "," + this.y.ToString() + ")"; } } /** *Comparer class, which compares points with one another */ public class pointComparer : IComparer<point> { public int Compare(point p1, point p2) { if (p1.time > p2.time) return 1; else if (p1.time < p2.time) return -1; else return 0; } } }
// <copyright file="ScriptLoad.cs" company="Morten Larsen"> // Copyright (c) Morten Larsen. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. // </copyright> namespace AspNetWebpack.AssetHelpers { /// <summary> /// Defines how to load the script. /// </summary> public enum ScriptLoad { /// <summary> /// The normal way. /// </summary> Normal, /// <summary> /// With async on the script tag. /// </summary> Async, /// <summary> /// With defer on the script tag. /// </summary> Defer, /// <summary> /// With both async and defer on the script tag. /// </summary> AsyncDefer, } }
namespace FeriaVirtual.Infrastructure.Persistence.OracleContext.Configuration { sealed class EventStoreConfig : DBConfig, IDBConfig { public string GetConnectionString { get; } public string GetDatabaseName { get; } private EventStoreConfig() : base() { GetConnectionString = GetEventStoreConnectionString; GetDatabaseName = this.GetType().Name; } public static IDBConfig Build() => new EventStoreConfig(); } }
public class Solution { public bool IsPalindrome(string s) { int left = 0, right = s.Length - 1; while (left < right) { if (!IsAlphaNumeric(s[left])) { left ++; continue; } if (!IsAlphaNumeric(s[right])) { right --; continue; } if (Char.ToLower(s[left]) != Char.ToLower(s[right])) return false; left ++; right --; } return true; } private bool IsAlphaNumeric(char c) { if ((c >= '0') && (c <= '9') || ((c >= 'a') && (c <='z')) || ((c >= 'A') && (c <= 'Z'))) return true; return false; } }
namespace TextFilter { using System; public class Startup { public static void Main(string[] args) { Console.WriteLine(Execute()); } private static string Execute() { var args = Console.ReadLine() .Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries); var input = Console.ReadLine(); for (int i = 0; i < args.Length; i++) { input = input.Replace(args[i], new string('*', args[i].Length)); } return input; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CRL.RoleAuthorize { public class AccessControlBusiness : BaseProvider<AccessControl> { public static AccessControlBusiness Instance { get { return new AccessControlBusiness(); } } protected override DBExtend dbHelper { get { return GetDbHelper<AccessControlBusiness>(); } } public new string CreateTable() { DBExtend helper = dbHelper; AccessControl obj1 = new AccessControl(); string msg = obj1.CreateTable(helper); Employee obj2 = new Employee(); msg += obj2.CreateTable(helper); var obj3 = new Menu(); msg += obj3.CreateTable(helper); var obj4 = new Role(); msg += obj4.CreateTable(helper); var obj5 = new SystemType(); msg += obj5.CreateTable(helper); var obj6 = new CRL.Person.LoginLog(); msg += obj6.CreateTable(helper); SystemTypeBusiness.Instance.Add(new SystemType() { Name = "默认项目" }); return msg; } //static List<AccessControl> accessControls; //public static List<AccessControl> AccessControls //{ // get // { // if (accessControls == null) // { // var helper = dbHelper; // accessControls = helper.QueryList<AccessControl>(); // } // return accessControls; // } //} /// <summary> /// 查询用户的访问权限 /// </summary> /// <param name="systemTypeId"></param> /// <param name="userId"></param> /// <returns></returns> public bool CheckAccess(int systemTypeId,int userId) { var menu = MenuBusiness.Instance.GetMenuByUrl(systemTypeId); if (menu == null)//默认没有的菜单都有权限 { return true; } if (menu.ShowInNav) { #region 常用菜单 Dictionary<string, int> dic = MenuBusiness.Instance.GetFavMenuDic(systemTypeId, userId); if (!dic.ContainsKey(menu.SequenceCode)) { dic.Add(menu.SequenceCode, 0); } dic[menu.SequenceCode] += 1; MenuBusiness.Instance.SaveFavMenus(dic, systemTypeId, userId); #endregion } var item = GetAccess(systemTypeId, menu.SequenceCode, userId); if (item == null) return false; var method = System.Web.HttpContext.Current.Request.HttpMethod; return item.Que; } /// <summary> /// 查询菜单操作权限 /// </summary> /// <param name="systemTypeId"></param> /// <param name="userId"></param> /// <param name="op"></param> /// <returns></returns> public bool CheckAccess(int systemTypeId,int userId, MenuOperation op) { return CheckAccess(systemTypeId, userId);//暂不验证操作 } AccessControl GetAccess(int systemTypeId, string menuCode, int userId) { var user = EmployeeBusiness.Instance.QueryItem(b => b.Id == userId); var item = QueryItem(b => ((b.Role == userId && b.RoleType == RoleType.用户) || (b.Role == user.Role && b.RoleType == RoleType.角色)) && b.SystemTypeId == systemTypeId && b.MenuCode == menuCode); return item; } } }
using CsvHelper; using Data.ViewModel; using Repository.ImportData.Extensions; using System; using System.IO; using System.Text; namespace Repository.ImportData.SeedingData { public class ScoreDetailImportStrategy : IScoreImportStrategy { public void SeedToContext(Stream stream, SeedingContext context, int year) { using (stream) { using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { CsvReader csvReader = new CsvReader(reader); try { csvReader.SkipHeaders(6); while (csvReader.Read()) { var locationCode = csvReader.GetInt(0); var locationName = csvReader.GetString(1); if (!string.IsNullOrWhiteSpace(locationName)) { Location location = new Location() { PlaceName = locationName, Code = locationCode, State = null }; location = context.Locations.AddOrUpdate(location); var disadvantage = csvReader.GetInt(2); var advantage = csvReader.GetInt(4); Score score = new Score() { DisadvantageScore = disadvantage, AdvantageDisadvantageScore = advantage, Year = year, Location = location }; score = context.Scores.AddOrUpdate(score); var disadvantageDecile = csvReader.GetInt(3); var advantageDecile = csvReader.GetInt(5); var indexOfEconomicResourcesScore = csvReader.GetInt(6); var indexOfEconomicResourcesDecile = csvReader.GetInt(7); var indexOfEducationAndOccupationScore = csvReader.GetInt(8); var indexOfEducationAndOccupationDecile = csvReader.GetInt(9); var usualResedantPopulation = csvReader.GetDecimal(10); ScoreDetail scoreDetail = new ScoreDetail() { Score = score, DisadvantageDecile = disadvantageDecile, AdvantageDisadvantageDecile = advantageDecile, IndexOfEconomicResourcesScore = indexOfEconomicResourcesScore, IndexOfEconomicResourcesDecile = indexOfEconomicResourcesDecile, IndexOfEducationAndOccupationScore = indexOfEducationAndOccupationScore, IndexOfEducationAndOccupationDecile = indexOfEducationAndOccupationDecile, UsualResedantPopulation = usualResedantPopulation }; scoreDetail.Score = score; context.ScoreDetails.Add(scoreDetail); } } } // Todo: Create exception class to be caught and logged the right logging catch (Exception e) { throw new DataImportException() { Year = year, Context = csvReader.Context, ThrownException = e }; } } } } } }
using System; using System.Collections.Generic; using System.Linq; using TheMapToScrum.Back.DAL.Entities; using TheMapToScrum.Back.DTO; namespace TheMapToScrum.Back.BLL { internal static class MapUserStoryContentDTO { internal static UserStoryDTO ToDto(UserStory objet) { UserStoryDTO retour = new UserStoryDTO(); if (objet != null) { retour.Id = objet.Id; retour.ProjectId = objet.ProjectId; retour.Label = objet.Label; retour.Version = objet.Version; retour.Role = objet.Role; retour.Function1 = objet.Function1; retour.Function2 = objet.Function2; retour.Notes = objet.Notes; retour.Priority = objet.Priority; retour.StoryPoints = objet.StoryPoints; retour.EpicStory = objet.EpicStory; retour.IsDeleted = objet.IsDeleted; retour.DateCreation = (System.DateTime)objet.DateCreation; retour.DateModification = DateTime.UtcNow; } return retour; } internal static List<UserStoryDTO> ToDto(List<UserStory> liste) { //récupération de la liste d'entités USContentDTO transformés en entités List<UserStoryDTO> retour = new List<UserStoryDTO>(); retour = liste.Select(x => new UserStoryDTO() { Id = x.Id, Version = x.Version, Label = x.Label, Role = x.Role, Project = MapProjectDTO.ToDto(x.Project), Priority = x.Priority, DateCreation = (System.DateTime)x.DateCreation, DateModification = (System.DateTime)x.DateModification, EpicStory = x.EpicStory, StoryPoints = x.StoryPoints, Function1 = x.Function1, Function2 = x.Function2, Notes = x.Notes, IsDeleted = x.IsDeleted, ProjectId = x.ProjectId //proprietes dto }).ToList(); return retour; } } }
namespace Alabo.Framework.Core.WebUis.Services { public interface IAutoImageService { } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BitirmeParsing.GenreParser { public class GenreParserAlperen : ParserBase<Movie> { // Action Adventure Adult Animation // Comedy Crime Documentary Drama // Fantasy Family Film-Noir Horror // Musical Mystery Romance Sci-Fi //Short Thriller War Western Dictionary<string, int> genreIDDict; public GenreParserAlperen() { genreIDDict = new Dictionary<string, int>(); genreIDDict["Action"] = 1; genreIDDict["Adventure"] = 2; genreIDDict["Adult"] = 3; genreIDDict["Animation"] = 4; genreIDDict["Comedy"] = 5; genreIDDict["Crime"] = 6; genreIDDict["Documentary"] = 7; genreIDDict["Drama"] = 8; genreIDDict["Fantasy"] = 9; genreIDDict["Family"] = 10; genreIDDict["Film-Noir"] = 11; genreIDDict["Horror"] = 12; genreIDDict["Musical"] = 13; genreIDDict["Mystery"] = 14; genreIDDict["Romance"] = 15; genreIDDict["Sci-Fi"] = 16; genreIDDict["Short"] = 17; genreIDDict["Thriller"] = 18; genreIDDict["War"] = 19; genreIDDict["Western"] = 20; } public override void parseLogic(BlockingCollection<List<Movie>> dataItems) { throw new NotImplementedException(); } public override void writeLogic(List<Movie> writeList) { throw new NotImplementedException(); } } }
using UnityEngine; public class Player : MonoBehaviour { public Transform planetTransform; //惑星objectをInspectorから代入 float playerPosFix; float playerPosJ; void Start() { //惑星の大きさに合わせて位置を補正する変数 playerPosFix = planetTransform.localScale.x / 2 + 0.5f; } void Update() { //AS←→入力で角度を変更 transform.Rotate (0,0,-Input.GetAxis ("Horizontal")); //三角関数を使用して角度方向で現在位置を求める this.transform.position = new Vector3(-Mathf.Sin (this.transform.eulerAngles.z * Mathf.Deg2Rad) * playerPosFix ,Mathf.Cos (this.transform.eulerAngles.z * Mathf.Deg2Rad) * playerPosFix + playerPosJ , 0); if (Input.GetKey(KeyCode.Space)) { playerPosJ = 0.5f; } else { } } }
using Crypteron; using System; using System.Collections.Generic; using System.Text; namespace eMAM.Data.Models { public class Email { public int Id { get; set; } public string GmailIdNumber { get; set; } public int StatusId { get; set; } public Status Status { get; set; } [Secure] public string Body { get; set; } public int SenderId { get; set; } public Sender Sender { get; set; } public DateTime DateReceived { get; set; } [Secure] public string Subject { get; set; } public ICollection<Attachment> Attachments { get; set; } public int? CustomerId { get; set; } public Customer Customer { get; set; } public bool MissingApplication { get; set; } public DateTime InitialRegistrationInSystemOn { get; set; } public DateTime SetInCurrentStatusOn { get; set; } public DateTime SetInTerminalStatusOn { get; set; } public string OpenedById { get; set; } public User OpenedBy { get; set; } public string ClosedById { get; set; } public User ClosedBy { get; set; } public bool WorkInProcess { get; set; } public string WorkingById { get; set; } public User WorkingBy { get; set; } public string PreviewedById { get; set; } public User PreviewedBy { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EBS.Query.SyncObject; using EBS.Query.DTO; namespace EBS.Query { /// <summary> /// Pos 数据同步查询 /// </summary> public interface IPosSyncQuery { IEnumerable<AccountSync> QueryAccountSync(); IEnumerable<StoreSync> QueryStoreSync(); IEnumerable<VipCardSync> QueryVipCardSync(); IEnumerable<VipProductSync> QueryVipProductSync(); IEnumerable<ProductStorePriceSync> QueryProductStorePriceSync(int storeId); IEnumerable<ProductAreaPriceSync> QueryProductAreaPriceSync(int storeId); /// <summary> /// 库存商品数据 /// </summary> /// <param name="page"></param> /// <param name="storeId">门店</param> /// <returns></returns> IEnumerable<ProductSync> QueryProductSync(int storeId,string productCodeOrBarCode); } }
using System; using System.Collections.Generic; using System.Text; namespace DAL.Entities { public class UserBankAccount { public int Id { get; set; } public string AppUserId { get; set; } public string Bank { get; set; } public string MerchantId { get; set; } public string Card { get; set; } public string Password { get; set; } public string Token { get; set; } public virtual AppUser AppUser { get; set; } public virtual ICollection<Expense> Expenses { get; set; } } }
/* This source file is under MIT License (MIT) Copyright (c) 2019 Ian Schlarman https://opensource.org/licenses/MIT */ namespace REvE.Configuration { /// <summary> /// Contract for a type that can provide a generic Configuration Model. /// </summary> /// <typeparam name="TResult">The Configuration Model.</typeparam> public interface IConfigProvider<TResult> { /// <summary> /// The generic Configuration Model. /// </summary> TResult Configuration { get; } } }
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; using System.Collections.Generic; using System.Linq; using ICSharpCode.Core; using ICSharpCode.SharpDevelop.Project; namespace MyLoadTest.LoadRunnerSvnAddin { public sealed class SubversionWorkingCopyModifiedCondition : IConditionEvaluator { private static readonly HashSet<StatusKind> Modified = new HashSet<StatusKind>(new[] { StatusKind.Added, StatusKind.Modified, StatusKind.Replaced }); public bool IsValid(object caller, Condition condition) { if (condition == null) { return false; } var selectedNode = ProjectBrowserPad.Instance?.SelectedNode; var fileSystemInfo = selectedNode?.GetNodeFileSystemInfo(); var workingCopyRoot = fileSystemInfo?.GetWorkingCopyRoot(); if (workingCopyRoot == null) { return false; } using (var client = new SvnClientWrapper()) { var multiStatus = client.MultiStatus(workingCopyRoot); var result = multiStatus.Any(pair => Modified.Contains(pair.Value.TextStatus)); return result; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Clutter : MonoBehaviour { [SerializeField] private Transform[] clutter; protected void Awake() { int idx = Random.Range(0, clutter.Length); Instantiate(clutter[idx], transform.position, transform.rotation, transform); } }
using System; namespace Algorithms.Lib.Interfaces { //public struct PairNode //{ // public PairNode(INode node, bool isX) // { // Node = node ?? throw new ArgumentNullException(nameof(node)); // IsX = isX; // } // public INode Node { get; } // public bool IsX { get; } //} }
using System; using System.Threading; using System.Windows.Threading; namespace BearSubPlayer { public static class XAMLExtensions { public static void InvokeIfNeeded(this DispatcherObject dispatcher, Action action) { if (Thread.CurrentThread != dispatcher.Dispatcher.Thread) dispatcher.Dispatcher.Invoke(action); else action(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace shipment { class Program { static void Main(string[] args) { Shipment ship = new Shipment(); ship.addPkg(new Package("auto",15,2000,"1A")); ship.addPkg(new Package("bus", 30, 3000,"1B")); ship.addPkg(new Package("elekricka", 10, 5000, "1C")); // Notification notif = new Notification(); //ship.PackageArrived += new Shipment.PackageHandler(notif.sendInfo); //ship.PackageArrived += new Shipment.PackageHandler(notif.sendMail); Package pkgClient = ship.GetPackageForClient("1B"); //if (pkgClient != null) //{ pkgClient.trackId = "AA22BB"; //ship.packageArrived(pkgClient, "Tovar prisiel prosim zaplate sumu"); //} //ship.packageArrived(pkg,"Prisiel Tovar pre Vas"); Console.WriteLine("Cakam na balik...."); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Text; namespace CarritoCompras.Modelo { public class Departamento { public string nombredepartamento { get; set; } } }
using System; using System.Runtime.Serialization; namespace CODE.Framework.Core.Exceptions { /// <summary> /// This exception is thrown whenever part of Milos requires a configuration setting that is not present. /// </summary> [Serializable] public class MissingConfigurationSettingException : Exception { /// <summary> /// Default Constructor. /// </summary> public MissingConfigurationSettingException() : base(Properties.Resources.IndexOutOfBounds) { } /// <summary> /// Constructor. /// </summary> /// <param name="setting">Name of the missing setting</param> public MissingConfigurationSettingException(string setting) : base(setting) { } /// <summary> /// Constructor. /// </summary> /// <param name="message">Exception message.</param> /// <param name="innerException">Inner exception.</param> public MissingConfigurationSettingException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Constructor. /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> protected MissingConfigurationSettingException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
using Senparc.CO2NET.Extensions; using Senparc.Core.Enums; using Senparc.Core.Utility; using System; using System.Collections.Generic; using System.Runtime.Serialization; //using WURFL; namespace Senparc.Core.Models { #region 全局 /// <summary> /// 分页 /// </summary> /// <typeparam name="T"></typeparam> public class PagedList<T> : List<T> where T : class /*,new()*/ { public PagedList(List<T> list, int pageIndex, int pageCount, int totalCount) : this(list, pageIndex, pageCount, totalCount, null) { } public PagedList(List<T> list, int pageIndex, int pageCount, int totalCount, int? skipCount = null) { AddRange(list); PageIndex = pageIndex; PageCount = pageCount; TotalCount = totalCount < 0 ? list.Count : totalCount; SkipCount = skipCount ?? Senparc.Core.Utility.Extensions.GetSkipRecord(pageIndex, pageCount); } public int PageIndex { get; set; } public int PageCount { get; set; } public int TotalCount { get; set; } public int SkipCount { get; set; } public int TotalPageNumber => Convert.ToInt32((TotalCount - 1) / PageCount) + 1; } /// <summary> /// 网页Meta标签集合 /// </summary> public class MetaCollection : Dictionary<MetaType, string> { //new public string this[MetaType metaType] //{ // get // { // if (!this.ContainsKey(metaType)) // { // this.Add(metaType, null); // } // return this[metaType]; // } // set { this[metaType] = value; } //} } /// <summary> /// 首页图片切换 /// </summary> public class HomeSlider { public int Id { get; set; } public string Title { get; set; } public string Url { get; set; } public string Pic { get; set; } public int DisplayOrder { get; set; } } /// <summary> /// 系统配置文件 /// </summary> [Serializable] public class SenparcConfig { public int Id { get; set; } public string Name { get; set; } public string Host { get; set; } public string DataBase { get; set; } public string UserName { get; set; } public string Password { get; set; } public string Provider { get; set; } public string ConnectionString { get; set; } public string ConnectionStringFull { get; set; } public string ApplicationPath { get; set; } } /// <summary> /// 全局提示消息 /// </summary> [Serializable] public class Messager { public MessageType MessageType { get; set; } public string MessageText { get; set; } public bool ShowClose { get; set; } public Messager(MessageType messageType, string messageText, bool showClose = true) { MessageType = messageType; MessageText = messageText; ShowClose = showClose; } } /// <summary> /// 日志 /// </summary> public class WebLog { public DateTime DateTime { get; set; } public string Level { get; set; } public string LoggerName { get; set; } public string Message { get; set; } public string Details { get; set; } public string ThreadName { get; set; } public int PageIndex { get; set; } public int Line { get; set; } } #endregion #region 数据库实体扩展 #region FullEntity相关 public interface IBaseFullEntity<in TEntity> { void CreateEntity(TEntity entity); } [Serializable] public abstract class BaseFullEntity<TEntity> : IBaseFullEntity<TEntity> { public virtual string Key { get; } public virtual void CreateEntity(TEntity entity) { FullEntityCache.SetFullEntityCache(this, entity); } /// <summary> /// 创建对象 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <typeparam name="TEntity">实体类型</typeparam> /// <param name="entity">实体实例</param> /// <returns></returns> public static T CreateEntity<T>(TEntity entity) where T : BaseFullEntity<TEntity>, new() { T obj = new T(); obj.CreateEntity(entity); return obj; } /// <summary> /// 创建对象列表 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <typeparam name="TEntity">试题类型</typeparam> /// <param name="entityList">实体列表</param> /// <returns></returns> public static List<T> CreateList<T>(IEnumerable<TEntity> entityList) where T : BaseFullEntity<TEntity>, new() { var result = new List<T>(); foreach (var item in entityList) { T obj = BaseFullEntity<TEntity>.CreateEntity<T>(item); result.Add(obj); } return result; } } #endregion [Serializable] public partial class FullSystemConfigBase : BaseFullEntity<SystemConfig> { [AutoSetCache] public string SystemName { get; set; } public override void CreateEntity(SystemConfig entity) { base.CreateEntity(entity); } } /// <summary> /// 用户信息 /// </summary> [Serializable] public partial class FullAccountBase : BaseFullEntity<Account> { public override string Key => UserName; [AutoSetCache] public int Id { get; set; } [AutoSetCache] public string UserName { get; set; } public DateTime LastActiveTime { get; set; } public DateTime LastOpenPageTime { get; set; } public string LastOpenPageUrl { get; set; } public string LastActiveUserAgent { get; set; } ///// <summary> ///// 最近一次活动的客户端设备信息 ///// </summary> //public IDevice LastActiveDevice //{ // get // { // if (!LastActiveUserAgent.IsNullOrEmpty()) // { // var wurflManager = WurflUtility.WurflManager; // var device = wurflManager.GetDeviceForRequest(LastActiveUserAgent); // return device; // } // return null; // } //} public bool IsLogined => Id > 0 && !UserName.IsNullOrEmpty() && (DateTime.Now - LastActiveTime).TotalMinutes < 2; /// <summary> /// 强制退出登录 /// </summary> public bool ForceLogout { get; set; } /// <summary> /// 未读消息数量 /// </summary> public int UnReadMessageCount { get; set; } /// <summary> /// 已经输入过验证码(如果需要加强验证,可以加上次输入验证码的时间以及token) /// </summary> public bool CheckCodePassed { get; set; } /// <summary> /// 在线图标 /// </summary> public string OnlineImg => $"/Content/Images/{(IsLogined ? "online" : "offline")}.png"; public FullAccountBase() { LastActiveTime = DateTime.MinValue; LastOpenPageTime = DateTime.MinValue; } } [Serializable] public class FullAccount : FullAccountBase { [AutoSetCache] public string Password { get; set; } [AutoSetCache] public string PasswordSalt { get; set; } [AutoSetCache] public string NickName { get; set; } [AutoSetCache] public string RealName { get; set; } [AutoSetCache] public string Email { get; set; } [AutoSetCache] public bool? EmailChecked { get; set; } [AutoSetCache] public string Phone { get; set; } [AutoSetCache] public bool? PhoneChecked { get; set; } [AutoSetCache] public string WeixinOpenId { get; set; } [AutoSetCache] public string PicUrl { get; set; } [AutoSetCache] public string HeadImgUrl { get; set; } [AutoSetCache] public decimal Package { get; set; } [AutoSetCache] public decimal Balance { get; set; } [AutoSetCache] public decimal LockMoney { get; set; } [AutoSetCache] public byte Sex { get; set; } [AutoSetCache] public string QQ { get; set; } [AutoSetCache] public string Country { get; set; } [AutoSetCache] public string Province { get; set; } [AutoSetCache] public string City { get; set; } [AutoSetCache] public string District { get; set; } [AutoSetCache] public string Address { get; set; } [AutoSetCache] public string Note { get; set; } [AutoSetCache] public System.DateTime ThisLoginTime { get; set; } [AutoSetCache] public string ThisLoginIp { get; set; } [AutoSetCache] public System.DateTime LastLoginTime { get; set; } [AutoSetCache] public string LastLoginIP { get; set; } [AutoSetCache] public System.DateTime AddTime { get; set; } [AutoSetCache] public decimal Points { get; set; } [AutoSetCache] public DateTime? LastWeixinSignInTime { get; set; } [AutoSetCache] public int WeixinSignTimes { get; set; } [AutoSetCache] public string WeixinUnionId { get; set; } /// <summary> /// 账户显示名称 /// </summary> public string DisplayName => NickName ?? UserName; public override void CreateEntity(Account entity) { base.CreateEntity(entity); } } /// <summary> /// 应用版本信息 /// </summary> [Serializable] public class AppVersion { public int Main { get; set; } public int Sub { get; set; } public int Fix { get; set; } public AppVersion(int main, int sub, int fix) { Main = main; Sub = sub; Fix = fix; } /// <summary> /// 返回指定格式的版本号 /// </summary> /// <returns></returns> public override string ToString() { return $"{Main}.{Sub}.{Fix}"; } /// <summary> /// 比较当前版本是否大于或等于appVersion /// </summary> /// <param name="appVersion"></param> /// <returns></returns> public bool IsGreatEqualThan(AppVersion appVersion) { if (appVersion == null) { return false; //无法比较 } if (Main < appVersion.Main) { return false; } if (Main == appVersion.Main && Sub < appVersion.Sub) { return false; } if (Main == appVersion.Main && Sub == appVersion.Sub && Fix < appVersion.Fix) { return false; } return true; } } #endregion #region Email /// <summary> /// 自动发送 /// </summary> public class AutoSendEmail { public int Id { get; set; } public string Address { get; set; } public string Subject { get; set; } public string Body { get; set; } public string UserName { get; set; } public DateTime LastSendTime { get; set; } public int SendCount { get; set; } } /// <summary> /// 自动发送完成 /// </summary> public class AutoSendEmailBak { public int Id { get; set; } public string Address { get; set; } public string Subject { get; set; } public string Body { get; set; } public string UserName { get; set; } public DateTime SendTime { get; set; } } public class EmailUser { public int Id { get; set; } public string Name { get; set; } public string DisplayName { get; set; } public string EmailAddress { get; set; } public string Password { get; set; } public string SmtpHost { get; set; } public int SmtpPort { get; set; } public bool NeedCredentials { get; set; } public string Note { get; set; } } #endregion #region XML Config格式 /// <summary> /// Email /// </summary> public class XmlConfig_Email { public string ToUse { get; set; } public string Subject { get; set; } public string Body { get; set; } public string Holders { get; set; } public DateTime UpdateTime { get; set; } } #endregion #region 省、市、区XML数据格式 [DataContract] [Serializable] public class AreaXML_Provinces { [DataMember] public int ID { get; set; } [DataMember] public string ProvinceName { get; set; } /// <summary> /// 地区代码 /// </summary> [DataMember] public string DivisionsCode { get; set; } /// <summary> /// 缩写(去掉“省”“市”“自治区”等) /// </summary> [DataMember] public string ShortName { get; set; } public AreaXML_Provinces(int id, string provinceName, string divisionsCode, string shortName) { this.ID = id; this.ProvinceName = provinceName; this.DivisionsCode = divisionsCode; this.ShortName = shortName; } } [DataContract] [Serializable] public class AreaXML_Cities { [DataMember] public int ID { get; set; } [DataMember] public int PID { get; set; } [DataMember] public string CityName { get; set; } [DataMember] public string ZipCode { get; set; } [DataMember] public string CityCode { get; set; } [DataMember] public int MaxShopId { get; set; } public AreaXML_Cities(int id, int pID, string cityName, string zipCode, string cityCode, int maxShopId) { this.ID = id; this.PID = pID; this.CityName = cityName; this.ZipCode = zipCode; this.CityCode = cityCode; this.MaxShopId = maxShopId; } } [DataContract] [Serializable] public class AreaXML_Districts { [DataMember] public int ID { get; set; } [DataMember] public int CID { get; set; } [DataMember] public string DistrictName { get; set; } public AreaXML_Districts(int id, int cID, string districtName) { this.ID = id; this.CID = cID; this.DistrictName = districtName; } } #endregion }
// Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the root of the repo. /* This file configures auth for the add-in. */ using Owin; using System.IdentityModel.Tokens; using System.Configuration; using Microsoft.Owin.Security.OAuth; using Microsoft.Owin.Security.Jwt; using Office_Add_in_ASPNET_SSO_WebAPI.App_Start; namespace Office_Add_in_ASPNET_SSO_WebAPI { public partial class Startup { public void ConfigureAuth(IAppBuilder app) { var tvps = new TokenValidationParameters { // Set the strings to validate against. (Scopes, which should be // simply "access_as_user" in this sample, is validated inside the controller.) ValidAudience = ConfigurationManager.AppSettings["ida:Audience"], ValidIssuer = ConfigurationManager.AppSettings["ida:Issuer"], // Save the raw token recieved from the Office host, so it can be // used in the "on behalf of" flow. SaveSigninToken = true }; // The more familiar UseWindowsAzureActiveDirectoryBearerAuthentication does not work // with the Azure AD V2 endpoint, so use UseOAuthBearerAuthentication instead. app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions { AccessTokenFormat = new JwtFormat(tvps, // Specify the discovery endpoint, also called the "metadata address". new OpenIdConnectCachingSecurityTokenProvider("https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration")) }); } } }
using System; using System.Collections.Generic; using System.Text; namespace AppointmentManagement.Entities.Concrete.Procedure { public class uspGetOrderAsnLineToOrderHeaderId { public Guid OrderAsnLineID { get; set; } public Guid OrderLineID { get; set; } public string OrderNumber { get; set; } public string ItemCode { get; set; } public string ItemDescription { get; set; } public string ColorCode { get; set; } public string ItemDim1Code { get; set; } public double Qty1 { get; set; } public double OrderAsnQty1 { get; set; } public double RemainingOrderQty1 { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; using TimeTracker.Infrastructure.Entities; namespace TimeTracker.Infrastructure.Mappings { public class TrackerMap : EntityTypeConfiguration<Tracker> { public TrackerMap() { this.ToTable("TimeTracker", "dbo"); this.Property(t => t.Id).HasColumnName("Id").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); this.Property(t => t.DateCreated).HasColumnName("Date"); this.Property(t => t.UserName).HasColumnName("UserName"); this.Property(t => t.MeetingMinutes).HasColumnName("MeetingMinutes"); this.Property(t => t.ActiveMinutes).HasColumnName("ActiveMinutes"); this.Property(t => t.IsWorkingDay).HasColumnName("IsWorkingDay"); this.Property(t => t.StartTime).HasColumnName("StartTime"); this.Property(t => t.DateModified).HasColumnName("LastUpdate"); this.Property(t => t.SyncRoot).HasColumnName("SyncRoot").IsConcurrencyToken(); } } }
using Microsoft.EntityFrameworkCore; using server.Models.Domain; namespace server.Models.Database { public class MySqlDbContext : DbContext { public MySqlDbContext(DbContextOptions<MySqlDbContext> options) : base(options) { Database.EnsureCreated(); } public DbSet<Product> Product { get; set; } public DbSet<Inventory> Inventory { get; set; } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Shipwreck.TypeScriptModels.Decompiler.Transformations.Members { [TestClass] public class FieldDeclarationTest { private class TestClass { #pragma warning disable CS0649 protected int _IntegerField; #pragma warning restore CS0649 } [TestMethod] public void FieldDeclaration_Test() { var f = new TypeTranslationContext<TestClass>().GetField("_IntegerField"); Assert.IsNotNull(f); } } }
// <author>Edson L. dela Torre</author> // <email>edsondt@yahoo.com</email> using IpswichWeather.Entities.WUnderground; using System; namespace IpswichWeather.Entities.Ipswitch { /// <summary> /// This takes in a CurrentObservation object and extracts the needed data to be displayed to the console. /// If additional weather data needs to be displayed, the client (Program class that displays to the console) /// is isolated from the change. /// </summary> class WeatherData { public string Location { get; private set; } public string Longitude { get; private set; } public string Latitude { get; private set; } public string CurrentDateTime { get; private set; } public string TemperatureInFahrenheit { get; private set; } public string TemperatureInCelsius { get; private set; } public string DewPoint { get; private set; } public WeatherData(CurrentObservation currentObservation) { Location = String.Format("{0}, {1}", currentObservation.DisplayLocation.City, currentObservation.DisplayLocation.State); Longitude = currentObservation.DisplayLocation.Longitude; Latitude = currentObservation.DisplayLocation.Latitude; DateTime dt = Convert.ToDateTime(currentObservation.LocalDateTime); CurrentDateTime = dt.ToString("MMM dd, yyyy hh:mm:ss tt"); TemperatureInFahrenheit = currentObservation.TemperatureInFahrenheit; TemperatureInCelsius = currentObservation.TemperatureInCelsius; DewPoint = currentObservation.DewPointString; } public override string ToString() { return String.Format( "Location: {0}\n" + "Longitude: {1}\n" + "Latitude: {2}\n" + "Current Date and Time: {3}\n" + "Temperature (F): {4}\n" + "Temperature (C): {5}\n" + "Dewpoint: {6}", Location, Longitude, Latitude, CurrentDateTime, TemperatureInFahrenheit, TemperatureInCelsius, DewPoint); } } }
using System; using Isop.Client.Transfer; namespace Isop.Gui.ViewModels { public interface IReceiveResult { string Result { get; set; } IErrorMessage[] Errors { get; set; } } }
using System.Web.Services.Protocols; namespace com.Sconit.WebService { public class Authentication : SoapHeader { public string UserName { get; set; } public string Password { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Tests.Data.Oberon { public enum DataFileType { CSV, Excel } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Kadastr.Data.Model { /// <summary> /// Пункт геодезической сети /// </summary> class GeodesicBase { public int Id { get; set; } /// <summary> /// Название пункта /// </summary> public string PName { get; set; } /// <summary> /// Тип знака (тип пункта геодезической сети) /// </summary> public string PKind { get; set; } /// <summary> /// Класс геодезической сети /// </summary> public string PKlass { get; set; } /// <summary> /// Координата Х /// </summary> public decimal OrdX { get; set; } /// <summary> /// Координата Y /// </summary> public decimal OrdY { get; set; } /// <summary> /// Наружный знак пункта /// </summary> public ConditionPoint OutdoorPoint { get; set; } /// <summary> /// Центр пункта /// </summary> public ConditionPoint CenterPoint { get; set; } /// <summary> /// Марка /// </summary> public ConditionPoint Mark { get; set; } /// <summary> /// Дата выполнения обследования при проведении кадастровых работ /// </summary> public DateTime AsOfDate { get; set; } } }
using System; using System.Threading.Tasks; namespace tellick_admin.Cli { class Program { static void Main(string[] args) { TpConfigReaderWriter tpConfigReader = new TpConfigReaderWriter(); TpConfig tpConfig = tpConfigReader.TpConfig; if (String.IsNullOrEmpty(tpConfig.Origin)) { Console.WriteLine("Please use 'tp connect' to connect to an origin."); return; } if (args.Length == 0) { Console.WriteLine("Please provide a command"); return; } Cli cli = new Cli(tpConfig); cli.ParseAndRun(args).Wait(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Web; using System.Web.Http; using System.Web.Mvc; using WebApiBluesea.Utils; namespace WebApiBluesea.Controllers { public class ReceiveMOController : ApiController { // POST api/receivemo //public string Post([FromBody]string value) //{ // Debug.WriteLine(value); // return "abc"; //} readonly log4net.ILog logAll = log4net.LogManager.GetLogger("request_response"); readonly log4net.ILog logError = log4net.LogManager.GetLogger("error"); public HttpResponseMessage Post(HttpRequestMessage request) { var requestText = request.Content.ReadAsStringAsync().Result; string ip = HttpRequestMessageHelper.GetClientIpAddress(request); logAll.Info("request|" + ip + "|" + requestText); string result = "0"; logAll.Info("response|" + requestText + "|" + result); return new HttpResponseMessage() { Content = new StringContent(result) }; } public HttpResponseMessage Get() { logAll.Info("request GET|" + HttpContext.Current.Request.UserHostAddress + "|" + HttpContext.Current.Request.Url.AbsoluteUri); string response = "0|Test ket noi"; return new HttpResponseMessage() { Content = new StringContent(response) }; } } }
using FluentAssertions; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GeneralResources.XUnitExample.CollectionTests { public class Tests { [Fact] public void AllNumberIsEven() { var numbers = new List<int> { 2, 4, 6 }; Action<int> allAreEvent = (a) => { Assert.True(a % 2 == 0); }; //Verifies that all items in the collection pass when executed against action. Assert.All(numbers, allAreEvent); Assert.All(numbers, item => Assert.True(item % 2 == 0)); } [Fact] public void AllNumberIsEvenUsingFluentAssertions() { var numbers = new List<int> { 2, 4, 6 }; numbers.Should().AllSatisfy(x => Assert.True(x % 2 == 0)); } [Fact] public void AllNumberAreEvenAndNotZero() { var numbers = new List<int> { 2, 4, 6 }; Assert.Collection(numbers, a => Assert.True(a == 2), a => Assert.True(a == 4), a => Assert.True(a == 6)); } [Fact] public void ShouldClearWithEvents() { // arrange var target = new ObservableStack<string>(); target.Push("1"); // act Assert.PropertyChanged(target, "Count", target.Clear); } } /// <summary> /// https://stackoverflow.com/questions/53889344/using-observablecollectiont-as-a-fifo-stack /// </summary> /// <typeparam name="T"></typeparam> public class ObservableStack<T> : Stack<T>, INotifyPropertyChanged { public event PropertyChangedEventHandler? PropertyChanged; public new void Clear() { base.Clear(); if(PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Count")); } } }
using System.Collections.Generic; using System.Linq; namespace Ejercicio { public class Raven : Titan { List<string> pensamientos; int cantidadDePorciones; int felicidad; public Raven(int tristeza) : base(tristeza) { this.pensamientos = new List<string>(); pensamientos.Add("Extraño a mi Papi"); pensamientos.Add("Me quedé sin MANTECA"); pensamientos.Add("Perdí a Pipo"); pensamientos.Add("Voy a comprar pilas para Robocop"); pensamientos.Add("¿Donde esta Pipo?"); cantidadDePorciones = 4; felicidad = tristeza; } public override void comerPizza() => felicidad += 2 * cantidadDePorciones; public override void llorarPorRobocop() => pensamientos.RemoveAt(0); public override bool estaTriste(){ int count = 0; foreach (var i in pensamientos){ if(i.Contains("Papi") || i.Contains("perrito") || i.Contains("Robocop") || i.Contains("Pipo") || i.Contains("MANTECA")) count++; } return count >= 5 && felicidad >= 10; } public override int poder(){ int count = 0; foreach (var i in pensamientos){ if(i.Contains("Papi") || i.Contains("perrito") || i.Contains("Robocop") || i.Contains("Pipo") || i.Contains("MANTECA")) count++; } return count; } } }
using System; using System.Collections.Generic; using System.Text; namespace ScriptKit { public class JsWeakReference { internal JsWeakReference(IntPtr value) { this.Value = value; } private IntPtr Value { get; set; } public JsObject Target { get { IntPtr targetValue = IntPtr.Zero; JsErrorCode jsErrorCode = NativeMethods.JsGetWeakReferenceValue(this.Value, out targetValue); JsRuntimeException.VerifyErrorCode(jsErrorCode); return new JsObject(targetValue); } } } }
using UnityEngine; using UnityEditor; using System; public class PhaseModule : Module { public float VelocityThreshold = 0.2f; public float PositionThreshold = 0.2f; public float Window = 0.5f; public bool ShowVelocities = true; public bool ShowPositions = true; public bool ShowKeys = true; public bool ShowCycle = true; public bool[] Bones = null; public bool Record = false; public LocalPhaseFunction[] Phases = new LocalPhaseFunction[3]; public override ID GetID() { return Module.ID.Phase; } public override Module Init(MotionData data) { Data = data; Bones = new bool[Data.Root.Bones.Length]; Record = Data.Mirrored; Phases[0] = new LocalPhaseFunction("Head", new int[2] { 4, 5 }, this); if(Data.Mirrored) { Phases[1] = new LocalPhaseFunction("Left Hand", new int[5] { 7, 8, 9, 10, 11 }, this); Phases[2] = new LocalPhaseFunction("Right Hand", new int[5] { 12, 13, 14, 15, 16 }, this); } else { Phases[1] = new LocalPhaseFunction("Left Hand", new int[5] { 12, 13, 14, 15, 16 }, this); Phases[2] = new LocalPhaseFunction("Right Hand", new int[5] { 7, 8, 9, 10, 11 }, this); } Compute(); return this; } public void ToggleBone(int[] index, PhaseFunction phase) { for (int i = 0; i < index.Length; i++) { Bones[index[i]] = !Bones[index[i]]; } } public void Compute() { for (int i = 0; i < Phases.Length; i++) { ToggleBone(Phases[i].Index, Phases[i].LocalPhase); Phases[i].LocalPhase.ComputeVelocity(); Phases[i].LocalPhase.ComputePosition(); Phases[i].LocalPhase.ComputeKey(); ToggleBone(Phases[i].Index, Phases[i].LocalPhase); } } public override void DerivedInspector(MotionEditor editor) { ShowVelocities = EditorGUILayout.Toggle("Show Velocities", ShowVelocities); ShowPositions = EditorGUILayout.Toggle("Show Positions", ShowPositions); ShowKeys = EditorGUILayout.Toggle("Show Keys", ShowKeys); Window = EditorGUILayout.FloatField("Window Time", Window); VelocityThreshold = EditorGUILayout.FloatField("Velocity Threshold", VelocityThreshold); PositionThreshold = EditorGUILayout.FloatField("Position Threshold", PositionThreshold); if(Phases[0] == null || Phases[0].LocalPhase == null || Record != Data.Mirrored) { Phases[0] = new LocalPhaseFunction("Head", new int[2] { 4, 5 }, this); if (Data.Mirrored) { Phases[1] = new LocalPhaseFunction("Left Hand", new int[5] { 7, 8, 9, 10, 11 }, this); Phases[2] = new LocalPhaseFunction("Right Hand", new int[5] { 12, 13, 14, 15, 16 }, this); } else { Phases[1] = new LocalPhaseFunction("Left Hand", new int[5] { 12, 13, 14, 15, 16 }, this); Phases[2] = new LocalPhaseFunction("Right Hand", new int[5] { 7, 8, 9, 10, 11 }, this); } Record = Data.Mirrored; Compute(); } if (GUILayout.Button("Compute")) Compute(); for (int i = 0; i < Phases.Length; i++) { EditorGUILayout.BeginHorizontal(); Phases[i].Visiable = EditorGUILayout.Toggle(Phases[i].Visiable, GUILayout.Width(20.0f)); EditorGUILayout.LabelField(Phases[i].Name); EditorGUILayout.EndHorizontal(); if (Phases[i].Visiable) Phases[i].LocalPhase.Inspector(editor); } } [Serializable] public class LocalPhaseFunction { public PhaseModule Module; public string Name; public int[] Index; public bool Visiable; public PhaseFunction LocalPhase; public LocalPhaseFunction(string name, int[] index, PhaseModule module) { Module = module; Name = name; Index = index; Visiable = true; LocalPhase = new PhaseFunction(module); } } public class PhaseFunction { public PhaseModule Module; public float[] Phase; public int[] Keys; public float[] Velocities; public float[] NVelocities; public float[] Positions; public float[] NPositions; public PhaseFunction(PhaseModule module) { Module = module; Phase = new float[module.Data.GetTotalFrames()]; Keys = new int[module.Data.GetTotalFrames()]; ComputeVelocity(); ComputePosition(); } public void ComputeVelocity() { float min, max; Velocities = new float[Module.Data.GetTotalFrames()]; NVelocities = new float[Module.Data.GetTotalFrames()]; min = float.MaxValue; max = float.MinValue; for (int i = 0; i < Velocities.Length; i++) { for (int j = 0; j < Module.Bones.Length; j++) { if (Module.Bones[j]) Velocities[i] = Mathf.Min(Module.Data.Frames[i].GetBoneVelocity(j, Module.Data.Mirrored, 1f / Module.Data.Framerate).magnitude, 1.0f); } if (Velocities[i] < Module.VelocityThreshold) { Velocities[i] = 0.0f; } if (Velocities[i] < min) { min = Velocities[i]; } if (Velocities[i] > max) { max = Velocities[i]; } } for (int i = 0; i < Velocities.Length; i++) { NVelocities[i] = Utility.Normalise(Velocities[i], min, max, 0f, 1f); } } public void ComputePosition() { float min, max; Positions = new float[Module.Data.GetTotalFrames()]; NPositions = new float[Module.Data.GetTotalFrames()]; Matrix4x4[] Posture = new Matrix4x4[Module.Bones.Length]; min = float.MaxValue; max = float.MinValue; Frame toFrame = Module.Data.GetFrame(5); Matrix4x4[] toPosture = toFrame.GetBoneTransformations(Module.Data.Mirrored); for (int i = 0; i < Positions.Length; i++) { Posture = Module.Data.Frames[i].GetBoneTransformations(Module.Data.Mirrored); for (int j = 0; j < Module.Bones.Length; j++) { if (Module.Bones[j]) { float bonePosition = Mathf.Min(Posture[j].GetPosition().GetRelativePositionTo(toPosture[j]).magnitude, 1.0f); Positions[i] += bonePosition; } } if (Positions[i] < Module.PositionThreshold) { Positions[i] = 0.0f; } if (Positions[i] < min) { min = Positions[i]; } if (Positions[i] > max) { max = Positions[i]; } float velocities = 0.0f; for (int k = i; k < Mathf.Min(i + Module.Data.Framerate * Module.Window, Module.Data.GetTotalFrames()); k++) { velocities += Velocities[k]; } if (velocities < Module.VelocityThreshold && Positions[i] != 0.0f) { toFrame = Module.Data.GetFrame(i); toPosture = toFrame.GetBoneTransformations(Module.Data.Mirrored); } } for (int i = 0; i < Positions.Length; i++) { NPositions[i] = Utility.Normalise(Positions[i], min, max, 0f, 1f); } } public void ComputeKey() { Keys = new int[Module.Data.GetTotalFrames()]; SetKey(Module.Data.GetFrame(1), 0); SetKey(Module.Data.GetFrame(Keys.Length), 0); for (int i = 1; i < Keys.Length - 1; i++) { if (Positions[i - 1] == 0.0f && Positions[i] != 0.0f) SetKey(Module.Data.GetFrame(i + 1), -1); else if(Positions[i - 1] != 0.0f && Positions[i] == 0.0f) SetKey(Module.Data.GetFrame(i + 1), 1); } } public void SetKey(Frame frame, int type) { if (IsKey(frame)) { Keys[frame.Index - 1] = 0; Phase[frame.Index - 1] = 0.0f; } if (type == -1) { Keys[frame.Index - 1] = -1; Phase[frame.Index - 1] = 0.0f; } else if (type == 1) { Keys[frame.Index - 1] = 1; Phase[frame.Index - 1] = 1.0f; } Interpolate(frame); } public bool IsKey(Frame frame) { return Keys[frame.Index - 1] != 0 ? true : false; } public bool IsInKey(Frame frame) { if (IsKey(frame)) return Keys[frame.Index - 1] == -1 ? true : false; else return false; } public bool IsOutKey(Frame frame) { if (IsKey(frame)) return Keys[frame.Index - 1] == 1 ? true : false; else return false; } public void Interpolate(Frame frame) { if (IsKey(frame)) { Interpolate(GetPreviousKey(frame), frame); Interpolate(frame, GetNextKey(frame)); } else { Interpolate(GetPreviousKey(frame), GetNextKey(frame)); } } public void Interpolate(Frame a, Frame b) { if (a == null || b == null) { Debug.Log("A given frame was null."); return; } if (a == b) { return; } if (Keys[a.Index - 1] == -1 && Keys[b.Index - 1] == 1) { int dist = b.Index - a.Index; for (int i = a.Index + 1; i < b.Index; i++) { float rateA = (float)((float)i - (float)a.Index) / (float)dist; float rateB = (float)((float)b.Index - (float)i) / (float)dist; Phase[i - 1] = rateB * Mathf.Repeat(Phase[a.Index - 1], 1f) + rateA * Phase[b.Index - 1]; } } else { for (int i = a.Index + 1; i < b.Index; i++) { Phase[i - 1] = 0.0f; } } } public void SetPhase(Frame frame, float value) { if (Phase[frame.Index - 1] != value) { Phase[frame.Index - 1] = value; Interpolate(frame); } } public float GetPhase(Frame frame) { return Phase[frame.Index - 1]; } public Frame GetPreviousKey(Frame frame) { if (frame != null) { for (int i = frame.Index - 1; i >= 1; i--) { if (Keys[i - 1] != 0) { return Module.Data.Frames[i - 1]; } } } return Module.Data.Frames.First(); } public Frame GetNextKey(Frame frame) { if (frame != null) { for (int i = frame.Index + 1; i <= Module.Data.GetTotalFrames(); i++) { if (Keys[i - 1] != 0) { return Module.Data.Frames[i - 1]; } } } return Module.Data.Frames.Last(); } public void Inspector(MotionEditor editor) { UltiDraw.Begin(); using (new EditorGUILayout.VerticalScope("Box")) { Frame frame = editor.GetCurrentFrame(); EditorGUILayout.BeginHorizontal(); if (IsKey(frame)) { if (IsInKey(frame)) { GUI.color = Color.red; if (GUILayout.Button("InKey")) SetKey(frame, 1); } else { GUI.color = Color.green; if (GUILayout.Button("OutKey")) SetKey(frame, 0); } } else { GUI.color = Color.white; if (GUILayout.Button("Key")) SetKey(frame, -1); } GUI.color = Color.white; if (IsKey(frame)) { SetPhase(frame, EditorGUILayout.Slider("Phase", GetPhase(frame), 0f, 1f)); } else { EditorGUI.BeginDisabledGroup(true); SetPhase(frame, EditorGUILayout.Slider("Phase", GetPhase(frame), 0f, 1f)); EditorGUI.EndDisabledGroup(); } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("<", GUILayout.Width(25.0f), GUILayout.Height(50.0f))) { editor.LoadFrame((GetPreviousKey(frame))); } EditorGUILayout.BeginVertical(GUILayout.Height(50f)); Rect ctrl = EditorGUILayout.GetControlRect(); Rect rect = new Rect(ctrl.x, ctrl.y, ctrl.width, 50f); EditorGUI.DrawRect(rect, UltiDraw.Black); float startTime = frame.Timestamp - editor.GetWindow() / 2f; float endTime = frame.Timestamp + editor.GetWindow() / 2f; if (startTime < 0f) { endTime -= startTime; startTime = 0f; } if (endTime > Module.Data.GetTotalTime()) { startTime -= endTime - Module.Data.GetTotalTime(); endTime = Module.Data.GetTotalTime(); } startTime = Mathf.Max(0f, startTime); endTime = Mathf.Min(Module.Data.GetTotalTime(), endTime); int start = Module.Data.GetFrame(startTime).Index; int end = Module.Data.GetFrame(endTime).Index; int elements = end - start; Vector3 prevPos = Vector3.zero; Vector3 newPos = Vector3.zero; Vector3 bottom = new Vector3(0f, rect.yMax, 0f); Vector3 top = new Vector3(0f, rect.yMax - rect.height, 0f); if (Module.ShowVelocities) { for (int i = 1; i < elements; i++) { prevPos.x = rect.xMin + (float)(i - 1) / (elements - 1) * rect.width; prevPos.y = rect.yMax - NVelocities[i + start - 1] * rect.height; newPos.x = rect.xMin + (float)(i) / (elements - 1) * rect.width; newPos.y = rect.yMax - NVelocities[i + start] * rect.height; UltiDraw.DrawLine(prevPos, newPos, Color.red); } } if (Module.ShowPositions) { for (int i = 1; i < elements; i++) { prevPos.x = rect.xMin + (float)(i - 1) / (elements - 1) * rect.width; prevPos.y = rect.yMax - NPositions[i + start - 1] * rect.height; newPos.x = rect.xMin + (float)(i) / (elements - 1) * rect.width; newPos.y = rect.yMax - NPositions[i + start] * rect.height; UltiDraw.DrawLine(prevPos, newPos, Color.green); } } if (Module.ShowKeys) { Frame A = Module.Data.GetFrame(start); if (A.Index == 1) { bottom.x = rect.xMin; top.x = rect.xMin; UltiDraw.DrawLine(bottom, top, UltiDraw.Magenta.Transparent(0.5f)); } Frame B = GetNextKey(A); while (A != B) { prevPos.x = rect.xMin + (float)(A.Index - start) / elements * rect.width; prevPos.y = rect.yMax - Mathf.Repeat(Phase[A.Index - 1], 1f) * rect.height; newPos.x = rect.xMin + (float)(B.Index - start) / elements * rect.width; newPos.y = rect.yMax - Phase[B.Index - 1] * rect.height; UltiDraw.DrawLine(prevPos, newPos, UltiDraw.White); bottom.x = rect.xMin + (float)(B.Index - start) / elements * rect.width; top.x = rect.xMin + (float)(B.Index - start) / elements * rect.width; UltiDraw.DrawLine(bottom, top, UltiDraw.Magenta.Transparent(0.5f)); A = B; B = GetNextKey(A); if (B.Index > end) { break; } } } float pStart = (float)(Module.Data.GetFrame(Mathf.Clamp(frame.Timestamp - 1f, 0f, Module.Data.GetTotalTime())).Index - start) / (float)elements; float pEnd = (float)(Module.Data.GetFrame(Mathf.Clamp(frame.Timestamp + 1f, 0f, Module.Data.GetTotalTime())).Index - start) / (float)elements; float pLeft = rect.x + pStart * rect.width; float pRight = rect.x + pEnd * rect.width; Vector3 pA = new Vector3(pLeft, rect.y, 0f); Vector3 pB = new Vector3(pRight, rect.y, 0f); Vector3 pC = new Vector3(pLeft, rect.y + rect.height, 0f); Vector3 pD = new Vector3(pRight, rect.y + rect.height, 0f); UltiDraw.DrawTriangle(pA, pC, pB, UltiDraw.White.Transparent(0.1f)); UltiDraw.DrawTriangle(pB, pC, pD, UltiDraw.White.Transparent(0.1f)); top.x = rect.xMin + (float)(frame.Index - start) / elements * rect.width; bottom.x = rect.xMin + (float)(frame.Index - start) / elements * rect.width; UltiDraw.DrawLine(top, bottom, UltiDraw.Yellow); Handles.DrawLine(Vector3.zero, Vector3.zero); EditorGUILayout.EndVertical(); if (GUILayout.Button(">", GUILayout.Width(25.0f), GUILayout.Height(50.0f))) { editor.LoadFrame(GetNextKey(frame)); } EditorGUILayout.EndHorizontal(); } UltiDraw.End(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SomeTechie.RoundRobinScheduler { using System.Windows.Forms; public class Paintable : Control { public Paintable() { this.DoubleBuffered = true; // or SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); UpdateStyles(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ShowMeDateBusiness { public class ShowMeDateBusiness { public string GetDate() { ShowMeDateDataLayer.ShowMeDateDataLayer date = new ShowMeDateDataLayer.ShowMeDateDataLayer(); return date.GetDate(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KartObjects; using System.ComponentModel; namespace KartSystem { public class AXLAccount_Movement : Entity { [DBIgnoreAutoGenerateParam] [DBIgnoreReadParam] public override string FriendlyName { get { return "Движение счета"; } } [DisplayName("Дата")] public DateTime DATETRAN { get; set; } [DisplayName("Тип транзакции")] public string TRANTYPE { get; set; } [DisplayName("Сумма")] public Decimal SUMTRAN { get; set; } [DisplayName("Баланс")] public Decimal ENDSUM { get; set; } } }
using System.Collections.Generic; using System.Data.Common; using Phenix.Core.Mapping; namespace Phenix.Business.Core { internal interface IRefinedlyObject : IRefinedly { #region 方法 void FillAggregateValues(FieldAggregateMapInfo fieldAggregateMapInfo); bool DeleteSelf(DbTransaction transaction, ref List<IRefinedlyObject> ignoreLinks); #endregion } }