text
stringlengths
13
6.01M
using System; namespace Binocle.AI.UtilityAI { /// <summary> /// wraps a Func for use as an Appraisal without having to create a subclass /// </summary> public class ActionAppraisal<T> : IAppraisal<T> { Func<T,float> _appraisalAction; public ActionAppraisal( Func<T,float> appraisalAction ) { _appraisalAction = appraisalAction; } float IAppraisal<T>.getScore( T context ) { return _appraisalAction( context ); } } }
using System; namespace Dominio { public class Usuario { public decimal SQ_USUARIO { get; set; } public string NM_USUARIO { get; set; } public string LOGIN { get; set; } public string SENHA { get; set; } public DateTime DT_INCLUSAO { get; set; } public string NM_USUARIO_INCLUSAO { get; set; } public DateTime DT_ALTERACAO { get; set; } public string NM_USUARIO_ALTERACAO { get; set; } public string ADMINISTRADOR { get; set; } public string EhAdministrador { get { return ADMINISTRADOR == "S" ? "Sim" : "Não"; } } } }
using CallCenter.Client.SqlStorage; using CallCenter.Client.SqlStorage.Entities; using CallCenter.Common; using CallCenter.Common.Entities; using CallCenterRepository.Controllers; using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; namespace CallCenter.Server.Helper { public static class Resolver { private static IWindsorContainer container; static Resolver() { container = new WindsorContainer(); container.Install(new WindsorInstaller()); } public static T Resolve<T>() { return container.Resolve<T>(); } } internal class WindsorInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register(Component.For<IControllerFactory>().ImplementedBy<ControllerFactory>()); container.Register(Component.For<IOperator>().ImplementedBy<Operator>()); container.Register(Component.For<ICustomer>().ImplementedBy<Customer>()); container.Register(Component.For<ICallCenter>().ImplementedBy<Client.SqlStorage.Entities.CallCenter>()); container.Register(Component.For<ICampaign>().ImplementedBy<Campaign>()); } } }
namespace Triton.Game.Mapping { using ns26; using System; using Triton.Game; using Triton.Game.Mono; [Attribute38("Error")] public class Error : MonoClass { public Error(IntPtr address) : this(address, "Error") { } public Error(IntPtr address, string className) : base(address, className) { } public static void AddFatal(string message) { Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.String }; object[] objArray1 = new object[] { message }; MonoClass.smethod_19(TritonHs.MainAssemblyPath, "", "Error", "AddFatal", enumArray1, objArray1); } public static void AddFatal(ErrorParams parms) { Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.Class }; object[] objArray1 = new object[] { parms }; MonoClass.smethod_19(TritonHs.MainAssemblyPath, "", "Error", "AddFatal", enumArray1, objArray1); } public static void AddWarning(ErrorParams parms) { Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.Class }; object[] objArray1 = new object[] { parms }; MonoClass.smethod_19(TritonHs.MainAssemblyPath, "", "Error", "AddWarning", enumArray1, objArray1); } public static void OnWarningPopupResponse(AlertPopup.Response response, object userData) { object[] objArray1 = new object[] { response, userData }; MonoClass.smethod_18(TritonHs.MainAssemblyPath, "", "Error", "OnWarningPopupResponse", objArray1); } public static bool ShouldUseWarningDialogForFatalError() { return MonoClass.smethod_14<bool>(TritonHs.MainAssemblyPath, "", "Error", "ShouldUseWarningDialogForFatalError", Array.Empty<object>()); } public static void ShowWarningDialog(ErrorParams parms) { object[] objArray1 = new object[] { parms }; MonoClass.smethod_18(TritonHs.MainAssemblyPath, "", "Error", "ShowWarningDialog", objArray1); } } }
using System; using Xunit; namespace PuzzleCore.Test { public class BoardValidMoves { [Theory] [ClassData(typeof(TD_ValidMoves))] public void ValidMoves_AreCorrect(string boardData, Directions moves) { var sut = BoardState.FromString(boardData); Assert.Equal(moves, sut.ValidMoves); } } }
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.Configuration; using System.IO; using System.Linq; using System.Management.Automation; using System.Threading; using biz.dfch.CS.LogShipper.Public; using System.Collections.Specialized; // Install-Package Microsoft.Net.Http // https://www.nuget.org/packages/Microsoft.Net.Http // Install-Package Newtonsoft.Json // https://www.nuget.org/packages/Newtonsoft.Json/6.0.1 // http://james.newtonking.com/json/help/index.html?topic=html/SelectToken.htm# namespace biz.dfch.CS.LogShipper.Core { public class LogShipperWorker { private bool _isInitialised = false; private volatile bool _isActive = false; private readonly FileSystemWatcher _fileSystemWatcher = new FileSystemWatcher(); private String _logFile; private String _logPath; private String _logFilter; private String _scriptFile; private Thread _thread; private readonly CompositionContainer _container; [ImportMany] private IEnumerable<Lazy<ILogShipperParser, ILogShipperParserData>> _parsers; private Lazy<ILogShipperParser, ILogShipperParserData> _parser; [ImportMany] private IEnumerable<Lazy<ILogShipperOutput, ILogShipperOutputData>> _outputs; private List<Lazy<ILogShipperOutput, ILogShipperOutputData>> _outputsActive = new List<Lazy<ILogShipperOutput, ILogShipperOutputData>>(); private void InitialiseExtensions(CompositionContainer container) { // An aggregate catalog that combines multiple catalogs var catalog = new AggregateCatalog(); // Adds all the parts found in the given directory var folder = ConfigurationManager.AppSettings["ExtensionsFolder"]; try { if (!Path.IsPathRooted(folder)) { folder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, folder); } catalog.Catalogs.Add(new DirectoryCatalog(folder)); } catch (Exception ex) { Trace.WriteLine(String.Format("AppSettings.ExtensionsFolder: Loading extensions from '{0}' FAILED.\n{1}", folder, ex.Message)); } finally { // Adds all the parts found in the same assembly as the Program class catalog.Catalogs.Add(new AssemblyCatalog(typeof(Program).Assembly)); } // Create the CompositionContainer with the parts in the catalog container = new CompositionContainer(catalog); try { // Fill the imports of this object container.ComposeParts(this); } catch (CompositionException compositionException) { Trace.WriteLine(compositionException.ToString()); throw; } // Get parser LoadParserExtension(ConfigurationManager.AppSettings["ParserName"]); // Get output LoadOutputExtension(ConfigurationManager.AppSettings["OutputName"]); } private void LoadParserExtension(String name) { if(String.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException("LoadParserExtension.name: Parameter validation FAILED. Parameter must not be null or empty."); } try { var parserNameNormalised = name.Trim(); _parser = _parsers .Where( p => p.Metadata.Name.Equals( parserNameNormalised, StringComparison.InvariantCultureIgnoreCase)) .Single(); var section = ConfigurationManager.GetSection(_parser.Metadata.Name) as NameValueCollection; _parser.Value.Configuration = section; Trace.WriteLine(String.Format("{0}: Loading parser extension SUCCEEDED.", parserNameNormalised)); } catch (InvalidOperationException ex) { Trace.WriteLine(String.Format("AppSettings.ParserName: Parameter validation FAILED. Parameter must not be null or empty and '{0}' has to be a valid parser extension.\n{1}", name, ex.Message)); throw; } catch(ConfigurationErrorsException ex) { Trace.WriteLine(String.Format("AppSettings.configSections: Section name '{0}' does not exist.\n{1}", name, ex.Message)); throw; } } private void LoadOutputExtension(String name) { if(String.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException("LoadOutputExtension.name: Parameter validation FAILED. Parameter must not be null or empty."); } var outputNames = name.Split(new char[] { ',', ';' }); foreach (var outputName in outputNames) { try { var outputNameNormalised = outputName.Trim(); var output = _outputs .Where( p => p.Metadata.Name.Equals( outputNameNormalised, StringComparison.InvariantCultureIgnoreCase)) .Single(); var section = ConfigurationManager.GetSection(outputNameNormalised) as NameValueCollection; output.Value.Configuration = section; _outputsActive.Add(output); Trace.WriteLine(String.Format("{0}: Loading output extension SUCCEEDED.", outputNameNormalised)); } catch (InvalidOperationException ex) { Trace.WriteLine(String.Format("AppSettings.OutputName: Parameter validation FAILED. Parameter must not be null or empty and '{0}' has to be a valid output extension.\n{1}", outputName, ex.Message)); throw; } catch (ConfigurationErrorsException ex) { Trace.WriteLine(String.Format("AppSettings.configSections: Section name '{0}' does not exist.\n{1}", outputName, ex.Message)); throw; } } } public bool IsActive { get { return _isActive; } set { lock (this) { if (!_isInitialised) { throw new InvalidOperationException(String.Format("LogShipperWorker not initialised. Cannot modify property 'IsActive'.")); } _isActive = value; _fileSystemWatcher.EnableRaisingEvents = value; } } } public LogShipperWorker() { Debug.WriteLine("{0}:{1}.{2}", this.GetType().Namespace, this.GetType().Name, System.Reflection.MethodBase.GetCurrentMethod().Name); InitialiseExtensions(_container); } public LogShipperWorker(String logFile, String scriptFile) { Debug.WriteLine("{0}:{1}.{2}", this.GetType().Namespace, this.GetType().Name, System.Reflection.MethodBase.GetCurrentMethod().Name); InitialiseExtensions(_container); var fReturn = false; fReturn = this.Initialise(logFile, scriptFile); } private bool Initialise(String logFile, String scriptFile) { var fReturn = false; try { // Parameter validation if (null == logFile || String.IsNullOrWhiteSpace(logFile)) throw new ArgumentNullException("logFile", String.Format("logFile: Parameter validation FAILED. Parameter cannot be null or empty.")); if (null == scriptFile || String.IsNullOrWhiteSpace(scriptFile)) throw new ArgumentNullException("scriptFile", String.Format("scriptFile: Parameter validation FAILED. Parameter cannot be null or empty.")); if (string.IsNullOrWhiteSpace(Path.GetDirectoryName(scriptFile))) { scriptFile = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(scriptFile)); } char[] achFileName = Path.GetFileName(scriptFile).ToCharArray(); char[] achFileInvalidChars = Path.GetInvalidFileNameChars(); if('\0' != achFileName.Intersect(achFileInvalidChars).FirstOrDefault()) { throw new ArgumentException("ScriptFile: Parameter validation FAILED. ScriptFile name contains invalid characters.", scriptFile); } if (!File.Exists(scriptFile)) throw new FileNotFoundException(String.Format("scriptFile: Parameter validation FAILED. File '{0}' does not exist.", scriptFile), scriptFile); _scriptFile = scriptFile; char[] achPathName = Path.GetDirectoryName(logFile).ToCharArray(); char[] achPathInvalidChars = Path.GetInvalidPathChars(); if('\0' != achPathName.Intersect(achPathInvalidChars).FirstOrDefault()) { throw new ArgumentException("logFile: Parameter validation FAILED. logFile path contains invalid characters.", scriptFile); } _logPath = Path.GetDirectoryName(logFile); if (!Directory.Exists(_logPath)) { throw new DirectoryNotFoundException(String.Format("logFile: Parameter validation FAILED. Path '{0}' does not exist.", _logPath)); } _logFile = logFile; _logFilter = String.Format("*{0}", Path.GetExtension(logFile)); if (_isInitialised) { Stop(); } _fileSystemWatcher.Path = _logPath; _fileSystemWatcher.Filter = _logFilter; _fileSystemWatcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.CreationTime; _fileSystemWatcher.Created += new FileSystemEventHandler(OnCreated); //_fileSystemWatcher.Changed += new FileSystemEventHandler(OnChanged); _fileSystemWatcher.Renamed += new RenamedEventHandler(OnRenamed); _fileSystemWatcher.Deleted += new FileSystemEventHandler(OnDeleted); _fileSystemWatcher.Error += new ErrorEventHandler(OnError); var ps = PowerShell .Create() .AddScript("return true;"); ps.Invoke(); ps.Commands.Clear(); _isInitialised = true; fReturn = _isInitialised; } catch (Exception ex) { Debug.WriteLine("{0}@{1}: {2}\r\n{3}", ex.GetType().Name, ex.Source, ex.Message, ex.StackTrace); throw ex; } return fReturn; } public bool Update() { Debug.WriteLine("{0}:{1}.{2}", this.GetType().Namespace, this.GetType().Name, System.Reflection.MethodBase.GetCurrentMethod().Name); var fReturn = this.IsActive; if (!fReturn) { return fReturn; } fReturn = Stop(); if (!fReturn) { return fReturn; } fReturn = Start(); return this.IsActive; } public bool Update(String logFile, String scriptFile) { Trace.WriteLine("{0}:{1}.{2}", this.GetType().Namespace, this.GetType().Name, System.Reflection.MethodBase.GetCurrentMethod().Name); var fReturn = false; // Parameter validation if (null == logFile || String.IsNullOrWhiteSpace(logFile)) throw new ArgumentNullException("logFile", String.Format("logFile: Parameter validation FAILED. Parameter cannot be null or empty.")); if (null == scriptFile || String.IsNullOrWhiteSpace(scriptFile)) throw new ArgumentNullException("scriptFile", String.Format("scriptFile: Parameter validation FAILED. Parameter cannot be null or empty.")); if (string.IsNullOrWhiteSpace(Path.GetDirectoryName(scriptFile))) { scriptFile = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(scriptFile)); } char[] achFileName = Path.GetFileName(scriptFile).ToCharArray(); char[] achFileInvalidChars = Path.GetInvalidFileNameChars(); if('\0' != achFileName.Intersect(achFileInvalidChars).FirstOrDefault()) { throw new ArgumentException("ScriptFile: Parameter validation FAILED. ScriptFile name contains invalid characters.", scriptFile); } if (!File.Exists(scriptFile)) throw new FileNotFoundException(String.Format("scriptFile: Parameter validation FAILED. File '{0}' does not exist.", scriptFile), scriptFile); _scriptFile = scriptFile; char[] achPathName = Path.GetDirectoryName(logFile).ToCharArray(); char[] achPathInvalidChars = Path.GetInvalidPathChars(); if('\0' != achPathName.Intersect(achPathInvalidChars).FirstOrDefault()) { throw new ArgumentException("logFile: Parameter validation FAILED. logFile path contains invalid characters.", scriptFile); } fReturn = this.IsActive; if (!fReturn) { return fReturn; } fReturn = Stop(); if (!fReturn) { return fReturn; } _logPath = Path.GetDirectoryName(logFile); if (!Directory.Exists(_logPath)) { throw new DirectoryNotFoundException(String.Format("logFile: Parameter validation FAILED. Path '{0}' does not exist.", _logPath)); } _logFile = logFile; _logFilter = String.Format("*.{0}", Path.GetExtension(logFile)); fReturn = Start(_logFile, _scriptFile); return fReturn; } private static void OnCreated(object source, FileSystemEventArgs e) { Trace.WriteLine("{0} - {1} : {2} [{3}]", e.FullPath, e.Name, e.ChangeType.ToString(), e.ToString()); } private static void OnChanged(object source, FileSystemEventArgs e) { Trace.WriteLine("{0} - {1} : {2} [{3}]", e.FullPath, e.Name, e.ChangeType.ToString(), e.ToString()); } private static void OnDeleted(object source, FileSystemEventArgs e) { Trace.WriteLine("{0} - {1} : {2} [{3}]", e.FullPath, e.Name, e.ChangeType.ToString(), e.ToString()); } private static void OnRenamed(object source, RenamedEventArgs e) { Trace.WriteLine("{0} - {1} : {2} [{3}]", e.FullPath, e.Name, e.ChangeType.ToString(), e.ToString()); } private static void OnError(object source, ErrorEventArgs e) { Trace.WriteLine("{0} : {1} : {2}", e.GetException().ToString(), e.GetType().ToString(), e.ToString()); } public bool Stop() { var fReturn = false; this.IsActive = fReturn; int nRetries = 10 * 30; int nWaitMs = 100; for(var c = 0; c < nRetries; c++) { if(!_thread.IsAlive) { break; } System.Threading.Thread.Sleep(nWaitMs); } fReturn = _thread.IsAlive; if(fReturn) { var msg = String.Format("Stopping thread FAILED. Operation timed out after '{0}' seconds.", (nRetries * nWaitMs) / 1000); System.Diagnostics.Trace.WriteLine(msg); _thread.Abort(); throw new TimeoutException(msg); } return !fReturn; } public bool Start() { var fReturn = false; if (!this._isInitialised) { throw new InvalidOperationException("Worker is not initialised and therefore cannot be started."); } if (this.IsActive) { return fReturn; } if(null != _thread && _thread.IsAlive) { return fReturn; } Trace.WriteLine("Creating worker thread ..."); _thread = new Thread(DoWork); Trace.WriteLine("Creating worker thread COMPLETED. _thread.ManagedThreadId '{0}'. _thread.IsAlive '{1}'", _thread.ManagedThreadId, _thread.IsAlive, ""); Trace.WriteLine("Starting worker thread ..."); _thread.Start(); Trace.WriteLine("Starting worker thread COMPLETED. _thread.IsAlive '{0}'", _thread.IsAlive, ""); fReturn = true; this.IsActive = fReturn; return this.IsActive; } public bool Start(String logFile, String scriptFile) { var fReturn = this.Initialise(logFile, scriptFile); if(fReturn) { fReturn = this.Start(); } return fReturn; } public void DoWork() { var fn = String.Format("{0}:{1}.{2}", this.GetType().Namespace, this.GetType().Name, System.Reflection.MethodBase.GetCurrentMethod().Name); Trace.WriteLine("{0} Do Work ...", fn, ""); bool fCreated = false; try { Trace.WriteLine("Do Work IsActive ..."); do { if (!File.Exists(_logFile)) { fCreated = true; Trace.WriteLine("File '{0}' does not exist. Waiting ...", _logFile, ""); System.Threading.Thread.Sleep(500); continue; } using (StreamReader streamReader = new StreamReader( new FileStream(_logFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) )) { long streamLength = 0; if (!fCreated) { streamLength = streamReader.BaseStream.Length; } do { //Trace.WriteLine("{0}:{1}.{2} streamReader. BaseStream.Length {3}. streamLength {4}", this.GetType().Namespace, this.GetType().Name, System.Reflection.MethodBase.GetCurrentMethod().Name, streamReader.BaseStream.Length, streamLength); if (streamReader.BaseStream.Length == streamLength) { continue; } // seek to the last read file pointer (always from the beginning) streamReader.BaseStream.Seek(streamLength, SeekOrigin.Begin); // read all lines var line = String.Empty; while (null != (line = streamReader.ReadLine())) { var list = _parser.Value.Parse(line); foreach(var output in _outputsActive) { list.ForEach(l => output.Value.Log(l)); } } // update to last read offset streamLength = streamReader.BaseStream.Position; System.Threading.Thread.Sleep(100); } while (this.IsActive); } } while (this.IsActive); } catch(ThreadAbortException ex) { System.Diagnostics.Trace.WriteLine(String.Format("{0}: {1} '{2}'", fn, ex.GetType().ToString(), ex.Message)); } } ~LogShipperWorker() { Debug.WriteLine("{0}:{1}.{2}", this.GetType().Namespace, this.GetType().Name, System.Reflection.MethodBase.GetCurrentMethod().Name); if(this.IsActive) { this.IsActive = false; } if (null != _fileSystemWatcher) { _fileSystemWatcher.Dispose(); } } } } /** * * * Copyright 2015 Ronald Rink, d-fens GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */
using KRF.Core.Entities.ValueList; using System.Collections.Generic; namespace KRF.Core.DTO.Employee { /// <summary> /// This class does not have database table. This class acts as a container for below products classes /// </summary> public class EmployeeDTO { public IList<KRF.Core.Entities.Employee.Employee> Employees { get; set; } /// <summary> /// Holds the Item List /// </summary> public IList<KRF.Core.Entities.AccessControl.Role> Roles { get; set; } /// <summary> /// Holds State List /// </summary> public IList<State> States { get; set; } /// <summary> /// Holds State List /// </summary> public IList<City> Cities { get; set; } /// <summary> /// Holds the Territory List /// </summary> public IList<tbl_EmpTerritory> Territories { get; set; } public IList<tbl_SkillLevel> SkillLevels { get; set; } public IList<KRF.Core.Entities.Employee.tbl_EmpSkillDetails> SkillItems { get; set; } } }
using SimpleBlogEngine.Repository.Models; using System.Collections.Generic; using System.Threading.Tasks; namespace SimpleBlogEngine.Services.Interfaces { public interface IBaseService<T> where T : BaseEntity { Task<ICollection<T>> GetAll(); Task<T> Get(long id); Task Insert(T entity); Task Update(T entity); Task Delete(long id); } }
using SDL2; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SharpDL.Events { public class TextEditingEventArgs : GameEventArgs { public int Length { get; set; } public int Start { get; set; } public String Text { get; set; } public UInt32 WindowID { get; set; } public TextEditingEventArgs(SDL.SDL_Event rawEvent) : base(rawEvent) { RawTimeStamp = rawEvent.edit.timestamp; } } }
using System; namespace ToDoApp.Models { public class ToDoItem { public Guid Id { get; set; } public bool IsDone { get; set; } public string Title { get; set; } public DateTimeOffset? StartedAt { get; set; } public string OwnerId { get; set; } } }
using UnityEngine; using System.Collections; public class ClickToShoot : MonoBehaviour { [HideInInspector] public BulletShooter BulletShooter; void Start () { BulletShooter = gameObject.GetComponent<BulletShooter> (); } void Update () { if (!BulletShooter) return; if(Input.GetKey(KeyCode.Mouse0)) { BulletShooter.Shoot(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using TwinkleStar.Common.Json; namespace TwinkleStar.Common { public static class HttpHelper { public static string GetPostBody(this HttpRequestBase requset) { using (StreamReader stream = new System.IO.StreamReader(requset.InputStream)) { return stream.ReadToEnd(); } } /// <summary> /// 获得请求对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="requset"></param> /// <returns></returns> public static T GetPostBody<T>(this HttpRequestBase requset) { using (StreamReader stream = new System.IO.StreamReader(requset.InputStream)) { string json = stream.ReadToEnd(); return JsonHelper.Deserialize<T>(json); } } } }
using UnityEngine; using System.Collections; public class TestLight : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { float newIntensity = HeartBeatAudioAnalyzer.smoothedVolume; newIntensity *= 0.015F; if ( newIntensity > 0.4F ) { newIntensity = 0.4F; } light.intensity = newIntensity; light.color = Metronome.getColorByBeat(); } }
using Domain.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Infrastructure.Persistence.Configurations { public class PostConfiguration : IEntityTypeConfiguration<Post> { public void Configure(EntityTypeBuilder<Post> builder) { builder.Property(t => t.Title) .HasMaxLength(200) .IsRequired(); builder.Property(t => t.Description) .HasMaxLength(2000) .IsUnicode(); builder.Property(t => t.Location) .HasMaxLength(200); builder.Property(t => t.Engine) .HasMaxLength(200); builder.Property(t => t.CreatedBy) .HasMaxLength(450); builder.Property(t => t.LastModifiedBy) .HasMaxLength(450); } } }
using System; namespace LubyClocker.CrossCuting.Shared.Exceptions { public class InvalidRequestException : Exception { public InvalidRequestException(string? message) : base(message) { } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // #region Usings using System; #endregion namespace DotNetNuke.Entities.Users.Social { /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Users /// Enum: RelationshipStatus /// ----------------------------------------------------------------------------- /// <summary> /// The RelationshipStatus enum describes various UserRelationship statuses. E.g. Accepted, Pending. /// </summary> /// ----------------------------------------------------------------------------- public enum RelationshipStatus { /// <summary> /// Relationship Request is not present (lack of any other status) /// </summary> None = 0, /// <summary> /// Relationship Request is Initiated. E.g. User 1 sent a friend request to User 2. /// </summary> Pending = 1, /// <summary> /// Relationship Request is Accepted. E.g. User 2 has accepted User 1's friend request. /// </summary> Accepted = 2, } }
using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc.RazorPages; using WagahighChoices.Ashe; using WagahighChoices.Kaoruko.Models; namespace WagahighChoices.Kaoruko.Pages { public class ResultsModel : PageModel { private readonly SearchStatusRepository _repository; public ResultsModel(SearchStatusRepository repository) { this._repository = repository; } public IReadOnlyDictionary<Heroine, int> RouteCount { get; set; } public IReadOnlyDictionary<(int, ChoiceAction), IReadOnlyDictionary<Heroine, double>> RouteProbabilities { get; set; } public IReadOnlyList<int> AvailableSelections { get; set; } public void OnGet() { this.RouteCount = this._repository.GetRouteCountByHeroine(); var results = this._repository.GetSearchResults(); this.RouteProbabilities = results .SelectMany(result => ModelUtils.ParseSelections(result.Selections) .Zip( ModelUtils.ParseChoices(result.Choices), (selection, choice) => new { Selection = selection, Choice = choice, result.Heroine } )) .GroupBy( x => (x.Selection, x.Choice), (key, values) => { var valuesArray = values.ToArray(); var dic = valuesArray.GroupBy(x => x.Heroine) .ToDictionary(x => x.Key, x => (double)x.Count() / valuesArray.Length * 100.0); return (key.Selection, key.Choice, dic); }) .ToDictionary(x => (x.Selection, x.Choice), x => (IReadOnlyDictionary<Heroine, double>)x.dic); this.AvailableSelections = this.RouteProbabilities .Select(x => x.Key.Item1) .Distinct() .OrderBy(x => x) .ToArray(); } public string GetProbability(int selectionId, ChoiceAction choice, Heroine heroine) { var p = this.RouteProbabilities .GetValueOrDefault((selectionId, choice)) ?.GetValueOrDefault(heroine); return $"{p:F1} %"; } } }
/* 01. Write a program that reads from the console a sequence of positive integer numbers. * The sequence ends when empty line is entered. Calculate and print the sum and average of the elements of the sequence. * Keep the sequence in List<int>. */ using System; using System.Collections.Generic; using System.Linq; class SequenceSumAndAverage { static void Main() { List<int> numbersList = new List<int>(); string intToParse = Console.ReadLine(); while (!string.IsNullOrWhiteSpace(intToParse)) { int toAdd = int.Parse(intToParse); numbersList.Add(toAdd); intToParse = Console.ReadLine(); } Console.WriteLine("Sequence sum: {0}", numbersList.Sum()); Console.WriteLine("Sequence average: {0}", numbersList.Average()); } }
using System; using UnityEngine; // Handles events that needs to be called ever second public class Clock : MonoBehaviour { #region -Events- // Event called every second public static event Action OnSecond; // Event called every tenth of a second public static event Action OnTenthSecond; #endregion #region -MonoBehaviour- private void Start() { InvokeRepeating("EventOnTenthSecond", 0.1f, 0.1f); InvokeRepeating("EventOnSecond", 1f, 1f); } #endregion #region -Methods- // Publishes the OnSecond event private void EventOnSecond() { if (OnSecond != null) { OnSecond(); } } // Publishes the OnTenthSecond event private void EventOnTenthSecond() { if (OnTenthSecond != null) { OnTenthSecond(); } } #endregion }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HelperLibrary.Models.Interfaces { public interface IPerson : ITable { string Email { get; } string Phone { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PDV.VIEW.Integração_Migrados.Model { public class VWContasReceber { public int ID { get; set; } public string Nome { get; set; } public DateTime DataEmissao { get; set; } public DateTime DataVencimento { get; set; } public decimal Valor { get; set; } public string Parcela { get; set; } public int NumeroPedido { get; set; } } }
using System; using End_to_End.Interface; using Microsoft.ProjectOxford.Face; using Microsoft.ProjectOxford.Emotion; using Microsoft.ProjectOxford.SpeakerRecognition; namespace End_to_End.ViewModel { public class MainViewModel : ObservableObject, IDisposable { private FaceServiceClient _faceServiceClient; private ISpeakerIdentificationServiceClient _speakerIdentificationClient; private AdministrationViewModel _administrationVm; public AdministrationViewModel AdministrationVm { get { return _administrationVm; } set { _administrationVm = value; RaisePropertyChangedEvent("AdministrationVm"); } } private HomeViewModel _homeVm; public HomeViewModel HomeVm { get { return _homeVm; } set { _homeVm = value; RaisePropertyChangedEvent("HomeVm"); } } private LuisViewModel _luisVm; public LuisViewModel LuisVm { get { return _luisVm; } set { _luisVm = value; RaisePropertyChangedEvent("LuisVm"); } } private BingSearchViewModel _bingSearchVm; public BingSearchViewModel BingSearchVm { get { return _bingSearchVm; } set { _bingSearchVm = value; RaisePropertyChangedEvent("BingSearchVm"); } } /// <summary> /// MainViewModel constructor /// Calls Initialize /// </summary> public MainViewModel() { Initialize(); } /// <summary> /// Initialize function to create all API client objects and ViewModels /// </summary> private void Initialize() { _faceServiceClient = new FaceServiceClient("FACE_API_KEY", "ROOT_URI"); _speakerIdentificationClient = new SpeakerIdentificationServiceClient("API_KEY_HERE"); AdministrationVm = new AdministrationViewModel(_faceServiceClient, _speakerIdentificationClient); HomeVm = new HomeViewModel(_faceServiceClient, _speakerIdentificationClient); LuisVm = new LuisViewModel(); BingSearchVm = new BingSearchViewModel(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if(disposing) { LuisVm.Dispose(); } } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Transactions; using Beamore.Contracts.DataTransferObjects.Event; using Beamore.Contracts.DataTransferObjects; using Beamore.API.Controllers; using Beamore.API.BusinessLogics.UnitOfWorks; namespace Beamore.Tests.Services { [TestClass] public class EventUnitTest { [TestMethod] public void AddNewEvent() { using (TransactionScope scope = new TransactionScope()) { NewEventDTO evnt = new NewEventDTO { EventName = "Deneme", EventEmail = "eventname@beamore.tech", StartDate = DateTime.UtcNow, FinishDate = DateTime.UtcNow, IsActive =true, Locaiton = new LocationDTO { Latitude = 12.5, Longitude = 15.6, Address = "Event Adress" }, LogoUrl = "url adres gelcek" }; //IEventService service = GenericProxy.GetService<IEventService>("eersinyildizz@gmail.com"); var service = new EventController(); var result = service.CreateNewEvent(evnt, "eersinyildizz@gmail.com"); Assert.AreEqual(true,result); scope.Complete(); } } } }
using Domain.Entities; using System.Threading.Tasks; namespace Application.Interfaces.Repositories { public interface IProductRepositoryAsync : IGenericRepositoryAsync<Product> { Task<bool> IsUniqueBarcodeAsync(string barcode); } }
namespace Triton.Game.Mapping { using ns26; using System; using Triton.Game; using Triton.Game.Mono; [Attribute38("TurnTimer")] public class TurnTimer : MonoBehaviour { public TurnTimer(IntPtr address) : this(address, "TurnTimer") { } public TurnTimer(IntPtr address, string className) : base(address, className) { } public void Awake() { base.method_8("Awake", Array.Empty<object>()); } public void ChangeSpellState(TurnTimerState timerState) { object[] objArray1 = new object[] { timerState }; base.method_8("ChangeSpellState", objArray1); } public void ChangeState(TurnTimerState state) { object[] objArray1 = new object[] { state }; base.method_8("ChangeState", objArray1); } public void ChangeState_Countdown() { base.method_8("ChangeState_Countdown", Array.Empty<object>()); } public void ChangeState_Kill() { base.method_8("ChangeState_Kill", Array.Empty<object>()); } public void ChangeState_Start() { base.method_8("ChangeState_Start", Array.Empty<object>()); } public void ChangeState_Timeout() { base.method_8("ChangeState_Timeout", Array.Empty<object>()); } public void ChangeStateImpl(TurnTimerState state) { object[] objArray1 = new object[] { state }; base.method_8("ChangeStateImpl", objArray1); } public float ComputeCountdownProgress(float countdownRemainingSec) { object[] objArray1 = new object[] { countdownRemainingSec }; return base.method_11<float>("ComputeCountdownProgress", objArray1); } public float ComputeCountdownRemainingSec() { return base.method_11<float>("ComputeCountdownRemainingSec", Array.Empty<object>()); } public string GenerateMatValAnimName() { return base.method_13("GenerateMatValAnimName", Array.Empty<object>()); } public string GenerateMoveAnimName() { return base.method_13("GenerateMoveAnimName", Array.Empty<object>()); } public static TurnTimer Get() { return MonoClass.smethod_15<TurnTimer>(TritonHs.MainAssemblyPath, "", "TurnTimer", "Get", Array.Empty<object>()); } public bool HasCountdownTimeout() { return base.method_11<bool>("HasCountdownTimeout", Array.Empty<object>()); } public void OnCurrentPlayerChanged(Player player, object userData) { object[] objArray1 = new object[] { player, userData }; base.method_8("OnCurrentPlayerChanged", objArray1); } public void OnDestroy() { base.method_8("OnDestroy", Array.Empty<object>()); } public void OnEndTurnRequested() { base.method_8("OnEndTurnRequested", Array.Empty<object>()); } public void OnGameOver(object userData) { object[] objArray1 = new object[] { userData }; base.method_8("OnGameOver", objArray1); } public void OnSpellStateStarted(Spell spell, SpellStateType prevStateType, object userData) { object[] objArray1 = new object[] { spell, prevStateType, userData }; base.method_8("OnSpellStateStarted", objArray1); } public void OnTurnStartManagerFinished() { base.method_8("OnTurnStartManagerFinished", Array.Empty<object>()); } public void OnTurnTimedOut() { base.method_8("OnTurnTimedOut", Array.Empty<object>()); } public void OnTurnTimerUpdate(TurnTimerUpdate update, object userData) { object[] objArray1 = new object[] { update, userData }; base.method_8("OnTurnTimerUpdate", objArray1); } public void OnUpdateFuseMatVal(float val) { object[] objArray1 = new object[] { val }; base.method_8("OnUpdateFuseMatVal", objArray1); } public void RestartCountdownAnims(float countdownRemainingSec) { object[] objArray1 = new object[] { countdownRemainingSec }; base.method_8("RestartCountdownAnims", objArray1); } public bool ShouldUpdateCountdownRemaining() { return base.method_11<bool>("ShouldUpdateCountdownRemaining", Array.Empty<object>()); } public void StartCountdownAnims(float startingMatVal, float countdownRemainingSec) { object[] objArray1 = new object[] { startingMatVal, countdownRemainingSec }; base.method_8("StartCountdownAnims", objArray1); } public void StopCountdownAnims() { base.method_8("StopCountdownAnims", Array.Empty<object>()); } public TurnTimerState TranslateSpellStateToTimerState(SpellStateType spellState) { object[] objArray1 = new object[] { spellState }; return base.method_11<TurnTimerState>("TranslateSpellStateToTimerState", objArray1); } public SpellStateType TranslateTimerStateToSpellState(TurnTimerState timerState) { object[] objArray1 = new object[] { timerState }; return base.method_11<SpellStateType>("TranslateTimerStateToSpellState", objArray1); } public float UpdateCountdownAnims(float countdownRemainingSec) { object[] objArray1 = new object[] { countdownRemainingSec }; return base.method_11<float>("UpdateCountdownAnims", objArray1); } public void UpdateCountdownTimeout() { base.method_8("UpdateCountdownTimeout", Array.Empty<object>()); } public static float BIRTH_ANIMATION_TIME { get { return MonoClass.smethod_6<float>(TritonHs.MainAssemblyPath, "", "TurnTimer", "BIRTH_ANIMATION_TIME"); } } public float m_countdownEndTimestamp { get { return base.method_2<float>("m_countdownEndTimestamp"); } } public float m_countdownTimeoutSec { get { return base.method_2<float>("m_countdownTimeoutSec"); } } public uint m_currentMatValAnimId { get { return base.method_2<uint>("m_currentMatValAnimId"); } } public uint m_currentMoveAnimId { get { return base.method_2<uint>("m_currentMoveAnimId"); } } public bool m_currentTimerBelongsToFriendlySidePlayer { get { return base.method_2<bool>("m_currentTimerBelongsToFriendlySidePlayer"); } } public float m_DebugTimeout { get { return base.method_2<float>("m_DebugTimeout"); } } public float m_DebugTimeoutStart { get { return base.method_2<float>("m_DebugTimeoutStart"); } } public float m_FuseMatValFinish { get { return base.method_2<float>("m_FuseMatValFinish"); } } public string m_FuseMatValName { get { return base.method_4("m_FuseMatValName"); } } public float m_FuseMatValStart { get { return base.method_2<float>("m_FuseMatValStart"); } } public GameObject m_FuseShadowObject { get { return base.method_3<GameObject>("m_FuseShadowObject"); } } public GameObject m_FuseWickObject { get { return base.method_3<GameObject>("m_FuseWickObject"); } } public float m_FuseXamountAnimation { get { return base.method_2<float>("m_FuseXamountAnimation"); } } public Transform m_SparksFinishBone { get { return base.method_3<Transform>("m_SparksFinishBone"); } } public GameObject m_SparksObject { get { return base.method_3<GameObject>("m_SparksObject"); } } public Transform m_SparksStartBone { get { return base.method_3<Transform>("m_SparksStartBone"); } } public Spell m_spell { get { return base.method_3<Spell>("m_spell"); } } public TurnTimerState m_state { get { return base.method_2<TurnTimerState>("m_state"); } } public bool m_waitingForTurnStartManagerFinish { get { return base.method_2<bool>("m_waitingForTurnStartManagerFinish"); } } } }
using System; namespace Buffers { public interface IErasableDevice : IBlockDevice { /// <summary> 该设备的块数 /// </summary> uint BlockCount { get; } /// <summary> 每个块的页面数 /// </summary> ushort PageCountPerBlock { get; } /// <summary> 执行擦除操作 /// </summary> void Erase(uint blockid); /// <summary> 擦除操作的次数 /// </summary> int EraseCount { get; } /// <summary> 返回某块被擦除的次数 /// </summary> int GetBlockEraseCount(uint blockid); BlockPageId ToBlockPageId(uint universalPageId); uint ToBlockId(uint universalPageId); ushort ToPageIdInBlock(uint universalPageId); uint ToUniversalPageId(uint blockid, ushort pageid); uint ToUniversalPageId(BlockPageId bpid); } public struct BlockPageId { public uint BlockId { get; private set; } public ushort PageId { get; private set; } public BlockPageId(uint blockid, ushort pageid) : this() { BlockId = blockid; PageId = pageid; } public bool IsInvalid { get { return BlockId == uint.MaxValue || PageId == uint.MinValue; } } public static BlockPageId Invalid { get { return new BlockPageId(uint.MaxValue, ushort.MaxValue); } } #region Equals 函数族 public bool Equals(BlockPageId other) { return BlockId == other.BlockId && PageId == other.PageId; } public override int GetHashCode() { return BlockId.GetHashCode() ^ PageId.GetHashCode(); } public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) return false; else return Equals((BlockPageId)obj); } public static bool operator ==(BlockPageId left, BlockPageId right) { return left.Equals(right); } public static bool operator !=(BlockPageId left, BlockPageId right) { return !left.Equals(right); } #endregion } }
using BLL.Dtos; using BLL.Exceptions; using BLL.Interfaces; using System; using System.Web.Http; namespace PL.Controllers.Api { public class ProvidersController : ApiController { private readonly IProviderService _providerService; public ProvidersController(IProviderService providerService) { _providerService = providerService; } // GET /api/providers [HttpGet] public IHttpActionResult GetProviders() { return Ok(_providerService.GetProviders()); } // GET /api/providers/1 [HttpGet] public IHttpActionResult GetProvider(int id) { var provider = _providerService.GetProvider(id); if (provider == null) return NotFound(); return Ok(provider); } // POST /api/providers [HttpPost] public IHttpActionResult CreateProvider(ProviderDto providerDto) { if (!ModelState.IsValid) return BadRequest(); try { providerDto.Id = _providerService.CreateProvider(providerDto); } catch (ProviderValidationException e) { return BadRequest(e.Message); } return Created(new Uri(Request.RequestUri + "/" + providerDto.Id), providerDto); } //PUT /api/providers/1 [HttpPut] public IHttpActionResult UpdateProvider(int id, ProviderDto providerDto) { if (!ModelState.IsValid) return BadRequest(); try { providerDto.Id = id; _providerService.UpdateProvider(providerDto); } catch (ProviderNotFoundException) { return NotFound(); } catch (ProviderValidationException e) { return BadRequest(e.Message); } return Ok(); } //DELETE /api/providers/1 [HttpDelete] public IHttpActionResult DeleteProvider(int id) { try { _providerService.DeleteProvider(id); } catch (ProviderNotFoundException) { return NotFound(); } return Ok(); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; public class ObjectsTransform : MonoBehaviour { private Vector2 _positionLast = Vector2.zero; public float rotateSpeedX = 2.0f; public float rotateSpeedY = 2.0f; public float rotateSpeedXios = 0.2f; public float rotateSpeedYios = 0.2f; public float moveSpeed = 0.5f; public float moveSpeedIOS = 0.05f; public float rotateOrMoveSensitive = 30.0f; public float rotateOrMoveSensitiveIOS = 30.0f; private Vector3 _positionDown = Vector3.zero; private bool _isTouchAnalyzed = false; private List<GameObject> _selectObjects = new List<GameObject> (); private GameObject _selectObject = null; private List<GameObject> _selectObjectsUp = new List<GameObject> (); private List<GameObject> _selectObjectsDown = new List<GameObject> (); public enum TouchType {none, rotate, move}; public TouchType touch = TouchType.none; private float moveYMinCurrent = 0.0f; void Update(){ if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer) { if (Input.touchCount > 0) { switch (Input.GetTouch (0).phase) { case TouchPhase.Began: checkTouch (Input.GetTouch(0).position); break; case TouchPhase.Moved: if(touch == TouchType.rotate) { touchAnalyze(Input.GetTouch(0).position, rotateOrMoveSensitiveIOS); } break; case TouchPhase.Ended: resetTouchSettings(); break; } } } else if (Application.platform == RuntimePlatform.WindowsEditor) { //по дабл клику эти строки пропускает и сразу вращает камеру, это не ошибка! if (Input.GetMouseButtonDown (0)) { checkTouch (Input.mousePosition); } if (Input.GetMouseButton(0)) { if(touch == TouchType.rotate) { touchAnalyze(Input.mousePosition, rotateOrMoveSensitive); } } if (Input.GetMouseButtonUp (0)) { resetTouchSettings(); } } } void touchAnalyze(Vector3 positionMove, float sensitive) { if(Vector3.Distance(_positionDown, positionMove) > sensitive && !_isTouchAnalyzed) { _isTouchAnalyzed = true; if(Mathf.Abs(_positionDown.x - positionMove.x) < Mathf.Abs(_positionDown.y - positionMove.y)) { List<GameObject> ballsColumn = new List<GameObject>(GameObject.FindGameObjectsWithTag("Ball")); float localAngle = Utils.ToAngleTwist(_selectObject.transform.localEulerAngles.y); for(int i = 0; i < ballsColumn.Count; i++) { if(Mathf.Abs(localAngle - Utils.ToAngleTwist(ballsColumn[i].transform.localEulerAngles.y)) > Model.angleSideHalf) { ballsColumn.RemoveAt(i); i--; } } int freeSpace = Model.rowCount - ballsColumn.Count; if(Mathf.Abs(localAngle - Utils.ToAngleTwist(GameObject.Find("SectionHole").transform.localEulerAngles.y - 180.0f)) < Model.angleSideHalf) { freeSpace++; moveYMinCurrent = Model.rowHoleY; } else { moveYMinCurrent = Model.rowZeroY; } if (freeSpace > 0) { unholdObjects (_selectObjects); _selectObjects.Clear(); touch = TouchType.move; _selectObjects.AddRange(ballsColumn); for(int i = 0; i < _selectObjects.Count; i++) { if(_selectObjects[i].transform.position.y - _selectObject.transform.position.y > Model.EPS) { _selectObjectsUp.Add(_selectObjects[i]); } else if(_selectObjects[i].transform.position.y - _selectObject.transform.position.y < -Model.EPS) { _selectObjectsDown.Add(_selectObjects[i]); } } _selectObjectsUp = _selectObjectsUp.OrderBy(p => p.transform.position.y).ToList(); _selectObjectsDown = _selectObjectsDown.OrderBy(p => -p.transform.position.y).ToList(); for(int i = 0; i < _selectObjects.Count; i++) { MagnetismRow magRow = _selectObjects[i].GetComponent<MagnetismRow>(); if(magRow) { List<GameObject> objectsCollision = new List<GameObject>(_selectObjects); objectsCollision.Remove(_selectObjects[i]); magRow.objectsCollision = objectsCollision; if(_selectObjects[i] == _selectObject) { continue; } magRow.isAlwaysCalculate = true; } } } } } } void LateUpdate() { //только в LateUpdate, потому что сначала магнетизм, потом толчок-поворот if(Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer) { if(Input.touchCount > 0) { switch(Input.GetTouch(0).phase) { case TouchPhase.Moved: if(touch == TouchType.rotate) { rotateObjects(-(Input.GetTouch(0).position.x - _positionLast.x) * rotateSpeedXios); } else if (touch == TouchType.move) { moveObjects((Input.GetTouch(0).position.y - _positionLast.y) * moveSpeedIOS); } _positionLast = Input.GetTouch(0).position; break; } } } else if(Application.platform == RuntimePlatform.WindowsEditor){ if ( Input.GetButton("Fire1") ) { if(touch == TouchType.rotate) { rotateObjects(-Input.GetAxis("Mouse X") * rotateSpeedX); } else if (touch == TouchType.move) { moveObjects(Input.GetAxis("Mouse Y") * moveSpeed); } } } } void checkTouch(Vector3 position){ Ray ray = Camera.main.ScreenPointToRay(position); RaycastHit hit; if(Physics.Raycast (ray, out hit)) { bool isSection = hit.transform.gameObject.tag.StartsWith("Section"); bool isBall = hit.transform.gameObject.tag.StartsWith("Ball"); if(!isSection && !isBall) { return; } if(Utils.IsCalculates(hit.transform.gameObject)) { return; } _selectObject = hit.transform.gameObject; _positionDown = position; if(isSection) { _isTouchAnalyzed = true; selectSectionAndBalls(_selectObject); } else if(isBall) { _isTouchAnalyzed = false; selectSectionAndBalls(GameObject.FindGameObjectsWithTag("Section").First(section => Mathf.Abs(section.transform.position.y + 0.5f - _selectObject.transform.position.y) < Model.rowDistanceHalf)); } } } void unholdObjects(List<GameObject> objects) { for(int i = 0; i < objects.Count; i++) { MagnetismColumn magCol = objects[i].GetComponent<MagnetismColumn>(); if(magCol) { magCol.isCalculates = true; } MagnetismRow magRow = objects[i].GetComponent<MagnetismRow>(); if(magRow) { magRow.isAlwaysCalculate = false; magRow.isCalculates = true; } } } void resetTouchSettings() { unholdObjects (_selectObjects); touch = TouchType.none; _selectObject = null; _selectObjects.Clear(); _selectObjectsUp.Clear(); _selectObjectsDown.Clear(); } void rotateObjects(float angle) { for (int i = 0; i < _selectObjects.Count; i++) { _selectObjects[i].transform.RotateAround(Vector3.zero, Vector3.up, angle); } } void moveObjects(float move) { if(Mathf.Abs(move) > Model.EPS) { List<GameObject> objectsToMove = new List<GameObject>(); objectsToMove.Add(_selectObject); List<float> spaceFree = new List<float>(); if(move > 0.0f) { objectsToMove.AddRange(_selectObjectsUp); } else { objectsToMove.AddRange(_selectObjectsDown); } for(int i = 0; i < objectsToMove.Count - 1; i++) { spaceFree.Add(Mathf.Clamp(move > 0.0f ? objectsToMove[i + 1].transform.position.y - objectsToMove[i].transform.position.y - Model.rowDistance : objectsToMove[i].transform.position.y - objectsToMove[i + 1].transform.position.y - Model.rowDistance , 0.0f, Model.rowDistance)); } spaceFree.Add(Mathf.Clamp(move > 0.0f ? Model.maxY - objectsToMove[objectsToMove.Count - 1].transform.position.y : objectsToMove[objectsToMove.Count - 1].transform.position.y - moveYMinCurrent , 0.0f, Model.rowDistance)); bool spaceFreeExist = spaceFree.Exists(p => Mathf.Abs(p) > Model.EPS); float moveAmount = move; while(Mathf.Abs(moveAmount) > Model.EPS && spaceFreeExist) { for(int i = 0; i < spaceFree.Count; i++) { if(Mathf.Abs(spaceFree[i]) > Model.EPS) { if(spaceFree[i] >= Mathf.Abs(moveAmount)) { for(int j = 0; j <= i; j++) { objectsToMove[j].transform.Translate(0.0f, moveAmount, 0.0f); } moveAmount = 0.0f; break; } else { float moveObject = spaceFree[i] * Mathf.Sign(moveAmount); objectsToMove[i].transform.Translate(0.0f, moveObject, 0.0f); moveAmount -= moveObject; spaceFree[i] = 0.0f; break; } } } spaceFreeExist = spaceFree.Exists(p => Mathf.Abs(p) > Model.EPS); } } } void selectSectionAndBalls(GameObject obj) { touch = TouchType.rotate; _selectObjects.AddRange(GameObject.FindGameObjectsWithTag("Ball")); for(int i = 0; i < _selectObjects.Count; i++) { if(Mathf.Abs(obj.transform.position.y + 0.5f - _selectObjects[i].transform.position.y) > Model.rowDistanceHalf) { _selectObjects.RemoveAt(i); i--; } } _selectObjects.Add(obj); } } //End class
using SistemaVentasWeb.Models; using Microsoft.EntityFrameworkCore; namespace SistemaVentasWeb.Data { public class ProductosContext : DbContext { public ProductosContext(DbContextOptions<ProductosContext> options) : base(options) { } public DbSet<Producto> Productos { get; set; } public DbSet<DetalleProducto> DetalledeProductos { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Producto>().ToTable("Productos"); modelBuilder.Entity<DetalleProducto>().ToTable("DetalleDeProductos"); } } }
using Caliburn.Micro; using Frontend.Core.Logging; namespace Frontend.Core.ViewModels.Interfaces { public interface ILogViewModel : IHandle<LogEntry> { } }
using Core.Repository.Library.UnitOfWork; namespace Asset.Core.Repository.Library.UnitOfWorks.AssetModelUnitOfWorks.AssetEntryUnitOfWorks { public interface IServicceAndRepairingUnitOfWork :IUnitOfWork { } }
using System; using System.Collections.Generic; using System.Text; namespace LV1 { class Note { private string mText; private string mAuthor; private int mPriority; public Note() { mText = "Ovo je bilješka"; mAuthor = "Mihovil Petrekovic"; mPriority = 3; } public Note(string text, string author, int priority) { mText = text; mAuthor = author; mPriority = priority; } public Note(string author) { mText = "biljeska tri"; mAuthor = author; mPriority = 3; } public void setText(string text) { mText = text; } public void setPriority(int priority) { mPriority = priority; } public string getText() { return mText; } public string getAuthor() { return mAuthor; } public string Text { get { return mText; } set { mText = value; } } public string Author { get { return mAuthor; } set { mAuthor = value; } } public int Priority { get { return mPriority; } set { mPriority = value; } } public override string ToString() { return mText + "\n autor:" + mAuthor; } } }
using ATSBackend.Domain.Entities; using ATSBackend.Infra.Data.Contexts; using ATSBackend.Domain.Interfaces.Repositories; using Microsoft.EntityFrameworkCore; using System.Linq; using System.Collections.Generic; namespace ATSBackend.Infra.Data.Repositories { public class CandidatoRepository : RepositoryBase<Candidato>, ICandidatoRepository { public CandidatoRepository(ATSContext db) : base(db) { } public void AlterarCandidato(Candidato candidato) { _db.Candidatos.Update(candidato); _db.Curriculos.Update(candidato.Curriculo); foreach (var experiencia in candidato.Curriculo.Experiencias) { if (experiencia.IdExperiencia == 0) _db.Experiencias.Add(experiencia); else _db.Experiencias.Update(experiencia); } _db.SaveChanges(); } public void ExcluirExperienciaCandidato(int idExperiencia) { var experienciaCandidato = _db.Experiencias.Find(idExperiencia); _db.Experiencias.Remove(experienciaCandidato); _db.SaveChanges(); } public IEnumerable<Candidato> ListarCandadatosAtivos() => _db.Candidatos.Where(x => x.Ativo).ToList(); public IEnumerable<Candidato> ListarCandadatosPorVaga(int idVaga) => _db.Candidatos.Where(x => x.IdVaga == idVaga && x.Ativo).ToList(); public Candidato ObterCantidado(int idCadidato) { var candidato = _db.Candidatos.Find(idCadidato); _db.Curriculos.Find(candidato.IdCurriculo); _db.Experiencias.ToList(); return candidato; } } }
/* * Bungie.Net API * * These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality. * * OpenAPI spec version: 2.1.1 * Contact: support@bungie.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter; namespace BungieNetPlatform.Model { /// <summary> /// An intrinsic perk on an item, and the requirements for it to be activated. /// </summary> [DataContract] public partial class DestinyDefinitionsDestinyItemPerkEntryDefinition : IEquatable<DestinyDefinitionsDestinyItemPerkEntryDefinition>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="DestinyDefinitionsDestinyItemPerkEntryDefinition" /> class. /// </summary> /// <param name="RequirementDisplayString">If this perk is not active, this is the string to show for why it&#39;s not providing its benefits..</param> /// <param name="PerkHash">A hash identifier for the DestinySandboxPerkDefinition being provided on the item..</param> public DestinyDefinitionsDestinyItemPerkEntryDefinition(string RequirementDisplayString = default(string), uint? PerkHash = default(uint?)) { this.RequirementDisplayString = RequirementDisplayString; this.PerkHash = PerkHash; } /// <summary> /// If this perk is not active, this is the string to show for why it&#39;s not providing its benefits. /// </summary> /// <value>If this perk is not active, this is the string to show for why it&#39;s not providing its benefits.</value> [DataMember(Name="requirementDisplayString", EmitDefaultValue=false)] public string RequirementDisplayString { get; set; } /// <summary> /// A hash identifier for the DestinySandboxPerkDefinition being provided on the item. /// </summary> /// <value>A hash identifier for the DestinySandboxPerkDefinition being provided on the item.</value> [DataMember(Name="perkHash", EmitDefaultValue=false)] public uint? PerkHash { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class DestinyDefinitionsDestinyItemPerkEntryDefinition {\n"); sb.Append(" RequirementDisplayString: ").Append(RequirementDisplayString).Append("\n"); sb.Append(" PerkHash: ").Append(PerkHash).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as DestinyDefinitionsDestinyItemPerkEntryDefinition); } /// <summary> /// Returns true if DestinyDefinitionsDestinyItemPerkEntryDefinition instances are equal /// </summary> /// <param name="input">Instance of DestinyDefinitionsDestinyItemPerkEntryDefinition to be compared</param> /// <returns>Boolean</returns> public bool Equals(DestinyDefinitionsDestinyItemPerkEntryDefinition input) { if (input == null) return false; return ( this.RequirementDisplayString == input.RequirementDisplayString || (this.RequirementDisplayString != null && this.RequirementDisplayString.Equals(input.RequirementDisplayString)) ) && ( this.PerkHash == input.PerkHash || (this.PerkHash != null && this.PerkHash.Equals(input.PerkHash)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.RequirementDisplayString != null) hashCode = hashCode * 59 + this.RequirementDisplayString.GetHashCode(); if (this.PerkHash != null) hashCode = hashCode * 59 + this.PerkHash.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
using System; using Logic.Resource; namespace Logic.Buildings { [Serializable] public class RingWorldBuilder : Builder { public RingWorldBuilder(string ringWorldName) : base(1200, new ReadOnlyResources(1E18, 1E19, 1E15), new Habitat(ringWorldName)) { } } }
using System; using UIKit; using CoreGraphics; using Ts.Core.Enums; using Ts.Core.iOS; using System.Collections.Generic; using Foundation; using System.Drawing; using Ts.Core.Translation; [assembly: Ts.Core.Dependency.Dependency(typeof(Ts.Core.UI.iOSDynamicContentDialog))] namespace Ts.Core.UI { public class iOSDynamicContentDialog : ViewWithKeyboard, IDynamicContentDialog { #region implemented abstract members of ViewWithKeyboard // protected override void KeyBoardUpNotification (NSNotification notification) // { // _isShown = true; // CGRect keyboardSize = UIKeyboard.BoundsFromNotification (notification); // } // // protected override void KeyBoardDownNotification (NSNotification notification) // { // throw new NotImplementedException (); // } // public ITranslator Translator {get {return DependencyService.Get<ITranslator>();}} #endregion protected readonly nfloat HEADER_HEIGHT = 40f; //36f; protected readonly nfloat FOOTER_HEIGHT = 40f; protected readonly nfloat MIN_CONTENT_HEIGHT = 60f; protected const float OVERLAY = 0.3f; private const float WIDTH_MULTIPLIER = 0.9f; private UIColor dialogColor = UIColor.FromRGB(255, 255, 255); protected UIView _parentView, _dialogView, _contentView; public object ContentView { get { return _contentView; } set { if(value != null) { try { var x = value as UIView; x.Frame = new CGRect (0, HeaderHeight, x.Frame.Width, x.Frame.Height); _contentView = x; } catch { throw new Exception ("Content View must be a UIView"); } } } } public UIView ParentView { get { if(_parentView == null) { // _parentView = UIApplication.SharedApplication.KeyWindow.Subviews [0]; _parentView = UIApplication.SharedApplication.KeyWindow.RootViewController.View; } return _parentView; } } public nfloat DialogHeight { get { return HeaderHeight + FOOTER_HEIGHT + (_contentView == null ? MIN_CONTENT_HEIGHT : _contentView.Frame.Height); } } public nfloat HeaderHeight { get { return ShowTitle ? HEADER_HEIGHT : 0f; } } public nfloat DialogWidth { get { return _contentView == null ? Frame.Width * WIDTH_MULTIPLIER : _contentView.Frame.Width; // TODO: Check null } } public PopupButtonsDirection Direction { get; set; } = PopupButtonsDirection.Horizontal; public iOSDynamicContentDialog() : base() { Frame = ParentView.Frame; } public void CreateViews() { BackgroundColor = UIColor.Clear; // Add Overlay view UIView overlayView = new UIView (this.Frame); overlayView.BackgroundColor = UIColor.Black; overlayView.Layer.Opacity = OVERLAY; if(TouchOutsideToClose) { overlayView.AddGestureRecognizer(new UITapGestureRecognizer (this.Hide)); } this.AddSubview(overlayView); // _dialogView = new UIView (); _dialogView.BackgroundColor = dialogColor; _dialogView.Layer.MasksToBounds = true; _dialogView.Layer.CornerRadius = 3f; _dialogView.Frame = new CGRect ((Frame.Width - DialogWidth) / 2, (Frame.Height - DialogHeight) / 2, DialogWidth, DialogHeight); // var blur = UIBlurEffect.FromStyle (UIBlurEffectStyle.Light); // var blurView = new UIVisualEffectView (blur) { // Frame = new CGRect (0, 0, _dialogView.Frame.Width, _dialogView.Frame.Height) // }; // // _dialogView.Add(blurView); // var header = GetHeader(); if(header != null) { _dialogView.AddSubview(header); } if(_contentView != null) { _dialogView.AddSubview(_contentView); } var footer = GetFooter(DialogButtons); _dialogView.AddSubview(footer); UpdateViewFrame(footer); // this.AddSubview(_dialogView); // _bottomSpace = UIScreen.MainScreen.ApplicationFrame.Height - _dialogView.Frame.Height - _dialogView.Frame.Y; KeyboardExtension.AddHideButtonToKeyboard(_contentView); } private void UpdateViewFrame(UIView footerView) { var frame = _dialogView.Frame; frame.Height += footerView.Frame.Height - FOOTER_HEIGHT; frame.Y = (Frame.Height - frame.Height) / 2; _dialogView.Frame = frame; } private UIView GetHeader() { if(!ShowTitle) { return null; } // UIView headerView = new UIView (); UILabel lblHeader = new UILabel (); lblHeader.TextAlignment = UITextAlignment.Center; lblHeader.TextColor = UIColor.Black; lblHeader.Font = UIFont.BoldSystemFontOfSize(18f); lblHeader.BackgroundColor = UIColor.Clear; lblHeader.Text = Title ?? string.Empty; lblHeader.Frame = new CGRect (0, 10, DialogWidth, HEADER_HEIGHT); // headerView.Frame = new CGRect (0, 0, DialogWidth, HEADER_HEIGHT); headerView.BackgroundColor = UIColor.Clear; headerView.AddSubview(lblHeader); // headerView.BackgroundColor = UIColor.Blue; // return headerView; } private UIView GetFooter(List<DialogButton> buttons) { if(buttons == null || buttons.Count == 0) { buttons = new List<DialogButton> () { new DialogButton () { Text = Translator.Translate("BUTTON_OK"), OnClicked = null } }; } UIView footerView; if (Direction == PopupButtonsDirection.Horizontal) footerView = AddFooterButtonsHorizontally(buttons); else footerView = AddFooterButtonsVertically(buttons); // return footerView; } private UIView AddFooterButtonsVertically(List<DialogButton> buttons) { UIView footerView = new UIView (); footerView.Frame = new CGRect (0, DialogHeight - FOOTER_HEIGHT, DialogWidth, FOOTER_HEIGHT * buttons.Count); footerView.BackgroundColor = UIColor.FromRGB(239, 239, 239); // Caculate size int count = buttons.Count; nfloat buttonWidth = footerView.Frame.Width; nfloat buttonHeight = FOOTER_HEIGHT - 1; for(int i = 0; i < buttons.Count; i++) { var p = buttons [i]; UIButton btn = new UIButton (UIButtonType.System); btn.BackgroundColor = dialogColor; btn.SetTitle(p.Text, UIControlState.Normal); btn.SetTitleColor(UIColor.FromRGB(11, 96, 255), UIControlState.Normal); btn.Font = UIFont.SystemFontOfSize(16f); btn.TouchUpInside += (sender, e) => { if(p.OnClicked != null) { p.OnClicked.Invoke(); } if(p.CloseAfterClick) { this.Hide(); } }; if(p.IsBold) { btn.Font = UIFont.BoldSystemFontOfSize(17); } btn.Frame = new CGRect (1, i * buttonHeight + i + 1, buttonWidth, buttonHeight); footerView.AddSubview(btn); } return footerView; } private UIView AddFooterButtonsHorizontally(List<DialogButton> buttons) { UIView footerView = new UIView (); footerView.Frame = new CGRect (0, DialogHeight - FOOTER_HEIGHT, DialogWidth, FOOTER_HEIGHT); footerView.BackgroundColor = UIColor.FromRGB(239, 239, 239); // Caculate size int count = buttons.Count; nfloat buttonWidth = (footerView.Frame.Width - count + 1) / count; nfloat buttonHeight = footerView.Frame.Height - 1; for(int i = 0; i < buttons.Count; i++) { var p = buttons [i]; UIButton btn = new UIButton (UIButtonType.System); btn.BackgroundColor = dialogColor; btn.SetTitle(p.Text, UIControlState.Normal); btn.SetTitleColor(UIColor.FromRGB(11, 96, 255), UIControlState.Normal); btn.Font = UIFont.SystemFontOfSize(16f); btn.TouchUpInside += (sender, e) => { if(p.OnClicked != null) { p.OnClicked.Invoke(); } if(p.CloseAfterClick) { this.Hide(); } }; if(p.IsBold) { btn.Font = UIFont.BoldSystemFontOfSize(17); } btn.Frame = new CGRect (i * buttonWidth + i, 1, buttonWidth, buttonHeight); footerView.AddSubview(btn); } return footerView; } #region Implements private readonly NSObject _owner = new NSObject (); public string Title { get; set; } public void Show() { _owner.BeginInvokeOnMainThread(()=> { CreateViews(); // _dialogView.Scale(true); // Animation ParentView.AddSubview(this); }); } public bool ShowTitle { get; set; } public void Hide() { _owner.BeginInvokeOnMainThread(this.RemoveFromSuperview); } public List<DialogButton> DialogButtons { get; set; } public bool TouchOutsideToClose { get; set; } #endregion } }
namespace _08._Custom_Comparator { using System; using System.Linq; class CustomComparator { static void Main(string[] args) { Action<int[]> Print = arr => Console.WriteLine(string.Join(" ", arr)); Func<int, int, int> SortArr = (a, b) => (a % 2 == 0 && b % 2 != 0) ? -1 : (a % 2 != 0 && b % 2 == 0) ? 1 : a.CompareTo(b); int[] inputNumbers = Console.ReadLine() .Split() .Select(int.Parse) .ToArray(); Array.Sort(inputNumbers, (x ,y) => sortArr(x, y)); Print(inputNumbers); } } }
using EvnTonThat.ResourceAccess.Contexts; using EvnTonThat.ResourceAccess.Entities; using EvnTonThat.ResourceAccess.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace EvnTonThat.ResourceAccess.EFEntities { public class EFMachVongRepository : IMaMachVong { private OracleDBContext context = new OracleDBContext(); public IQueryable<V_TT_MVONG> machVongData { get { return context.V_TT_MVONG; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Devices.Geolocation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Services.Maps; using Windows.Storage.Streams; using Windows.UI; using Windows.UI.Popups; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Maps; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace JoggingDating.Views { public sealed partial class CreatePage : Page { public CreatePage() { this.InitializeComponent(); } private void Map_MapTapped(MapControl sender, MapInputEventArgs args) { ViewModel.Map_MapTapped(sender, args); } } }
using System; using System.Collections.Generic; using System.Text; namespace OCP.Activity { /** * Interface IProvider * * @package OCP\Activity * @since 11.0.0 */ public interface IProvider { /** * @param string language The language which should be used for translating, e.g. "en" * @param IEvent event The current event which should be parsed * @param IEvent|null previousEvent A potential previous event which you can combine with the current one. * To do so, simply use setChildEvent(previousEvent) after setting the * combined subject on the current event. * @return IEvent * @throws \InvalidArgumentException Should be thrown if your provider does not know this event * @since 11.0.0 */ IEvent parse(string language, IEvent currentEvent, IEvent previousEvent = null); } }
using FictionFantasyServer.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; namespace FictionFantasyServer.NetCoreEntry { public class DesignTimeFFDbContextFactory : IDesignTimeDbContextFactory<FFDbContext> { public FFDbContext CreateDbContext(string[] args) { var optionsBuilder = new DbContextOptionsBuilder<FFDbContext>(); optionsBuilder.UseNpgsql("Host=localhost;Database=FictionFantasy;", b => b.MigrationsAssembly("FictionFantasyServer.NetCoreEntry")); return new FFDbContext(optionsBuilder.Options); } } }
using UnityEngine; using UnityEngine.UI; public class coins : MonoBehaviour { Text text; // Use this for initialization void Start () { text = GetComponent<Text> (); } // Update is called once per frame void Update () { printCoins (); } void printCoins(){ text.text=conf.coins+"$"; } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations.Schema; #nullable disable namespace dk.via.ftc.businesslayer.Models { public class VendorAdmin { [JsonPropertyName("username")] [Required] //[Display(Name = "Username")] public string Username { get; set; } [JsonPropertyName("vendor_id")] public string VendorId { get; set; } [JsonPropertyName("pass")] [Required] [DataType(DataType.Password)] [Display(Name = "Password")] [RegularExpression("^((?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])|(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[^a-zA-Z0-9])|(?=.*?[A-Z])(?=.*?[0-9])(?=.*?[^a-zA-Z0-9])|(?=.*?[a-z])(?=.*?[0-9])(?=.*?[^a-zA-Z0-9])).{8,}$", ErrorMessage = "Passwords must be at least 8 characters and contain at 3 of 4 of the following: upper case (A-Z), lower case (a-z), number (0-9) and special character (e.g. !@#$%^&*)")] public string Pass { get; set; } [Required] [JsonPropertyName("email")] [Display(Name = "Email")] [EmailAddress(ErrorMessage = "Invalid Email Address")] public string Email { get; set; } [JsonPropertyName("first_name")] [Required] public string FirstName { get; set; } [JsonPropertyName("last_name")] [Required] public string LastName { get; set; } [JsonPropertyName("phone")] public string Phone { get; set; } public virtual Vendor Vendor { get; set; } } }
using CHSystem.Models; using CHSystem.Repositories; using CHSystem.Services; using CHSystem.ViewModels.Groups; using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; namespace CHSystem.Controllers { public class GroupsController : BaseController { public ActionResult List() { GroupsListVM model = new GroupsListVM(); TryUpdateModel(model); GroupRepository groupRep = new GroupRepository(); model.Groups = groupRep.GetAll(); if (!String.IsNullOrEmpty(model.Search)) { model.Search = model.Search.ToLower(); model.Groups = model.Groups.Where(g => g.Name.ToLower().Contains(model.Search)).ToList(); } model.Props = new Dictionary<string, object>(); switch (model.SortOrder) { case "name_desc": model.Groups = model.Groups.OrderByDescending(g => g.Name).ToList(); break; case "name_asc": default: model.Groups = model.Groups.OrderBy(g => g.Name).ToList(); break; } PagingService.Prepare(model, ControllerContext, model.Groups); return View(model); } public ActionResult Edit(int? id) { Group group; GroupRepository groupRep = new GroupRepository(); if (!id.HasValue) { group = new Group(); } else { group = groupRep.GetByID(id.Value); if (group == null) { return RedirectToAction("List"); } } GroupsEditVM model = new GroupsEditVM(); model.ID = group.ID; model.Name = group.Name; return View(model); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit() { GroupsEditVM model = new GroupsEditVM(); TryUpdateModel(model); GroupRepository groupRep = new GroupRepository(); if (!ModelState.IsValid) { return View(model); } Group group; if (model.ID == 0) { group = new Group(); } else { group = groupRep.GetByID(model.ID); if (group == null) { return RedirectToAction("List"); } } group.Name = model.Name; groupRep.Save(group); return RedirectToAction("List"); } public ActionResult Delete(int id) { GroupRepository groupRep = new GroupRepository(); groupRep.Delete(id); return RedirectToAction("List"); } } }
using Service; using Service.Contract; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.ServiceModel; using System.ServiceModel.Description; using System.Text; using System.Threading.Tasks; namespace MKService { internal class ClientChannelProvider : IClientChannelProvider { /// <summary> /// The device service bootstrapper. /// </summary> private readonly IDeviceServiceBootstrapper deviceServiceBootstrapper; /// <summary> /// The service endpoint. /// </summary> private readonly IPEndPoint endpoint; /// <summary> /// Initializes a new instance of the <see cref="ClientChannelProvider" /> class. /// </summary> /// <param name="endpoint">The service endpoint.</param> /// <param name="deviceServiceBootstrapper">The device service bootstrapper.</param> public ClientChannelProvider(IPEndPoint endpoint, IDeviceServiceBootstrapper deviceServiceBootstrapper) { Console.WriteLine($"The service client will look for the WST service at {endpoint}."); this.endpoint = endpoint; this.deviceServiceBootstrapper = deviceServiceBootstrapper; } /// <summary> /// Gets the command channel. /// </summary> /// <param name="implementation">The client implementation.</param> /// <returns>The command channel.</returns> public ICommandContract GetCommandChannel(object implementation) { var binding = new NetTcpBinding { Name = "NetTcpBinding_ICommandContract", TransferMode = TransferMode.Buffered, ReceiveTimeout = TimeSpan.MaxValue, SendTimeout = TimeSpan.MaxValue, OpenTimeout = TimeSpan.MaxValue, MaxReceivedMessageSize = int.MaxValue, MaxBufferSize = int.MaxValue, MaxBufferPoolSize = int.MaxValue, }; binding.ReliableSession.InactivityTimeout = TimeSpan.MaxValue; var uriBuilder = new UriBuilder { Host = this.endpoint.Address.ToString(), Path = "/MageKnight2D/Service/Command", Port = this.endpoint.Port, Scheme = "net.tcp" }; var endpointAddress = new EndpointAddress(uriBuilder.Uri); var contractDescription = ContractDescription.GetContract(typeof(ICommandContract)); var serviceEndpoint = new ServiceEndpoint(contractDescription, binding, endpointAddress); var instanceContext = new InstanceContext(implementation); var factory = new DuplexChannelFactory<ICommandContract>(instanceContext, serviceEndpoint); foreach (var operation in factory.Endpoint.Contract.Operations) { var dataContractSerializerBehavior = operation.Behaviors.Find<DataContractSerializerOperationBehavior>(); if (dataContractSerializerBehavior != null) { dataContractSerializerBehavior.MaxItemsInObjectGraph = int.MaxValue; } } var assemblies = this.deviceServiceBootstrapper.KnownTypeAssemblies; factory.Endpoint.Contract.ContractBehaviors.Add(new KnownTypeContractBehavior(assemblies)); return factory.CreateChannel(); } /// <summary> /// Gets the query channel. /// </summary> /// <param name="implementation">The client implementation.</param> /// <returns>The query channel.</returns> public IQueryContract GetQueryChannel(object implementation) { var binding = new NetTcpBinding { TransferMode = TransferMode.Buffered, ReceiveTimeout = TimeSpan.MaxValue, SendTimeout = TimeSpan.MaxValue, OpenTimeout = TimeSpan.MaxValue, MaxReceivedMessageSize = int.MaxValue, MaxBufferSize = int.MaxValue, MaxBufferPoolSize = int.MaxValue, }; binding.ReliableSession.InactivityTimeout = TimeSpan.MaxValue; var uriBuilder = new UriBuilder { Host = this.endpoint.Address.ToString(), Path = "/MageKnight2D/Service/Query", Port = this.endpoint.Port, Scheme = "net.tcp" }; var endpointAddress = new EndpointAddress(uriBuilder.Uri); var contractDescription = ContractDescription.GetContract(typeof(IQueryContract)); var serviceEndpoint = new ServiceEndpoint(contractDescription, binding, endpointAddress); var factory = new DuplexChannelFactory<IQueryContract>( new InstanceContext(implementation), serviceEndpoint); foreach (var operation in factory.Endpoint.Contract.Operations) { var dataContractSerializerBehavior = operation.Behaviors.Find<DataContractSerializerOperationBehavior>(); if (dataContractSerializerBehavior != null) { dataContractSerializerBehavior.MaxItemsInObjectGraph = int.MaxValue; } } var assemblies = this.deviceServiceBootstrapper.KnownTypeAssemblies; factory.Endpoint.Contract.ContractBehaviors.Add(new KnownTypeContractBehavior(assemblies)); return factory.CreateChannel(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public static class Config { /// <summary> /// the blend value of new facial values with last values /// </summary> public static float motionBlendCoeffience = 2; }
using System; using System.Collections.Generic; using Master.Contract; using Master.DataFactory; namespace Master.BusinessFactory { public class PortBO { private PortDAL portDAL; public PortBO() { portDAL = new PortDAL(); } public List<Port> GetList() { return portDAL.GetList(); } public List<Port> GetListByPortType(int portType) { return portDAL.GetListByPortType(portType); } public List<Port> GetPageView(Int64 fetchRows) { return portDAL.GetPageView( fetchRows); } public Int64 GetRecordCount() { return portDAL.GetRecordCount(); } public List<Port> SearchPort(string portName) { return portDAL.SearchPort(portName); } public bool SavePort(Port newItem) { return portDAL.Save(newItem); } public bool DeletePort(Port item) { return portDAL.Delete(item); } public Port GetPort(Port item) { return (Port)portDAL.GetItem<Port>(item); } } }
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 Code_Hog { public partial class DeleteTicketMenu : Form { CodeHogEntities codeHogEntities; public DeleteTicketMenu(string ticketID) { InitializeComponent(); codeHogEntities = new CodeHogEntities(); ticketIDLabel.Text = ticketID; } private void CancelButton_Click(object sender, EventArgs e) { Close(); } private void DeleteTicketButton_Click(object sender, EventArgs e) { int TicketId = Convert.ToInt32(ticketIDLabel.Text); foreach (var ticket in codeHogEntities.Tickets) { if (ticket.TicketID == TicketId) { codeHogEntities.Tickets.Remove(ticket); } foreach (var dependency in codeHogEntities.Dependencies.Where(s => s.TicketID == TicketId)) { codeHogEntities.Dependencies.Remove(dependency); } } codeHogEntities.SaveChanges(); Close(); } } }
namespace TNBase.DataStorage { /// <summary> /// Options for ordering /// </summary> public enum OrderVar { WALLET, SURNAME } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using UnityEngine; namespace ProBuilder2.Common { [Serializable] public class pb_Face : ISerializable { [SerializeField] private int[] _indices; [SerializeField] private int[] _distinctIndices; [SerializeField] private pb_Edge[] _edges; [SerializeField] private int _smoothingGroup; [SerializeField] private pb_UV _uv; [SerializeField] private Material _mat; [SerializeField] public bool manualUV; [SerializeField] public int elementGroup; public int textureGroup = -1; public int[] indices { get { return this._indices; } } public int[] distinctIndices { get { return (this._distinctIndices != null) ? this._distinctIndices : this.CacheDistinctIndices(); } } public pb_Edge[] edges { get { return (this._edges != null) ? this._edges : this.CacheEdges(); } } public int smoothingGroup { get { return this._smoothingGroup; } } public pb_UV uv { get { return this._uv; } } public Material material { get { return this._mat; } } public pb_Face(SerializationInfo info, StreamingContext context) { this._indices = (int[])info.GetValue("indices", typeof(int[])); this._distinctIndices = (int[])info.GetValue("distinctIndices", typeof(int[])); this._edges = (pb_Edge[])info.GetValue("edges", typeof(pb_Edge[])); this._smoothingGroup = (int)info.GetValue("smoothingGroup", typeof(int)); this._uv = (pb_UV)info.GetValue("uv", typeof(pb_UV)); this.manualUV = (bool)info.GetValue("manualUV", typeof(bool)); this.elementGroup = (int)info.GetValue("elementGroup", typeof(int)); this._mat = pb_Constant.DefaultMaterial; string text = (string)info.GetValue("material", typeof(string)); Object[] array = Resources.FindObjectsOfTypeAll(typeof(Material)); for (int i = 0; i < array.Length; i++) { Material material = (Material)array[i]; if (material.get_name().Equals(text)) { this._mat = material; break; } } } public pb_Face() { } public pb_Face(int[] i) { this.SetIndices(i); this._uv = new pb_UV(); this._mat = pb_Constant.DefaultMaterial; this._smoothingGroup = 0; this.elementGroup = 0; this.RebuildCaches(); } public pb_Face(int[] i, Material m, pb_UV u, int smoothingGroup, int textureGroup, int elementGroup, bool manualUV) { this._indices = i; this._uv = u; this._mat = m; this._smoothingGroup = smoothingGroup; this.textureGroup = textureGroup; this.elementGroup = elementGroup; this.manualUV = manualUV; this.RebuildCaches(); } public pb_Face(pb_Face face) { this._indices = new int[face.indices.Length]; Array.Copy(face.indices, this._indices, face.indices.Length); this._uv = new pb_UV(face.uv); this._mat = face.material; this._smoothingGroup = face.smoothingGroup; this.textureGroup = face.textureGroup; this.elementGroup = face.elementGroup; this.manualUV = face.manualUV; this.RebuildCaches(); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("indices", this._indices, typeof(int[])); info.AddValue("distinctIndices", this._distinctIndices, typeof(int[])); info.AddValue("edges", this._edges, typeof(pb_Edge[])); info.AddValue("smoothingGroup", this._smoothingGroup, typeof(int)); info.AddValue("uv", this._uv, typeof(pb_UV)); info.AddValue("material", this._mat.get_name(), typeof(string)); info.AddValue("manualUV", this.manualUV, typeof(bool)); info.AddValue("elementGroup", this.elementGroup, typeof(int)); } public void SetUV(pb_UV u) { this._uv = u; } public void SetMaterial(Material m) { this._mat = m; } public void SetSmoothingGroup(int i) { this._smoothingGroup = i; } public bool IsValid() { return this.indices.Length > 2; } public Vector3[] GetDistinctVertices(Vector3[] verts) { int[] distinctIndices = this.distinctIndices; Vector3[] array = new Vector3[distinctIndices.Length]; for (int i = 0; i < distinctIndices.Length; i++) { array[i] = verts[distinctIndices[i]]; } return array; } public int[] GetTriangle(int index) { if (index * 3 + 3 > this.indices.Length) { return null; } return new int[] { this.indices[index * 3], this.indices[index * 3 + 1], this.indices[index * 3 + 2] }; } public pb_Edge[] GetEdges() { pb_Edge[] array = new pb_Edge[this.indices.Length]; for (int i = 0; i < this.indices.Length; i += 3) { array[i] = new pb_Edge(this.indices[i], this.indices[i + 1]); array[i + 1] = new pb_Edge(this.indices[i + 1], this.indices[i + 2]); array[i + 2] = new pb_Edge(this.indices[i + 2], this.indices[i]); } return array; } public void SetIndices(int[] i) { this._indices = i; this._distinctIndices = Enumerable.ToArray<int>(Enumerable.Distinct<int>(i)); } public void ShiftIndices(int offset) { for (int i = 0; i < this._indices.Length; i++) { this._indices[i] += offset; } } public int SmallestIndexValue() { int num = this._indices[0]; for (int i = 0; i < this._indices.Length; i++) { if (this._indices[i] < num) { num = this._indices[i]; } } return num; } public void ShiftIndicesToZero() { int num = this.SmallestIndexValue(); for (int i = 0; i < this.indices.Length; i++) { this._indices[i] -= num; } for (int j = 0; j < this._distinctIndices.Length; j++) { this._distinctIndices[j] -= num; } for (int k = 0; k < this._edges.Length; k++) { this._edges[k].x -= num; this._edges[k].y -= num; } } public void ReverseIndices() { Array.Reverse(this._indices); } public void RebuildCaches() { this.CacheDistinctIndices(); this.CacheEdges(); } private pb_Edge[] CacheEdges() { this._edges = pb_Edge.GetPerimeterEdges(this.GetEdges()); return this._edges; } private int[] CacheDistinctIndices() { this._distinctIndices = Enumerable.ToArray<int>(Enumerable.Distinct<int>(this._indices)); return this._distinctIndices; } public bool Contains(int[] triangle) { for (int i = 0; i < this.indices.Length; i += 3) { if (Enumerable.Contains<int>(triangle, this.indices[i]) && Enumerable.Contains<int>(triangle, this.indices[i + 1]) && Enumerable.Contains<int>(triangle, this.indices[i + 2])) { return true; } } return false; } public bool Equals(pb_Face face) { int num = face.indices.Length / 3; for (int i = 0; i < num; i++) { if (!this.Contains(face.GetTriangle(i))) { return false; } } return true; } public static int[] AllTriangles(pb_Face[] q) { List<int> list = new List<int>(); for (int i = 0; i < q.Length; i++) { pb_Face pb_Face = q[i]; list.AddRange(pb_Face.indices); } return list.ToArray(); } public static int[] AllTriangles(List<pb_Face> q) { List<int> list = new List<int>(); using (List<pb_Face>.Enumerator enumerator = q.GetEnumerator()) { while (enumerator.MoveNext()) { pb_Face current = enumerator.get_Current(); list.AddRange(current.indices); } } return list.ToArray(); } public static int[] AllTrianglesDistinct(pb_Face[] q) { List<int> list = new List<int>(); for (int i = 0; i < q.Length; i++) { pb_Face pb_Face = q[i]; list.AddRange(pb_Face.distinctIndices); } return list.ToArray(); } public static List<int> AllTrianglesDistinct(List<pb_Face> f) { List<int> list = new List<int>(); using (List<pb_Face>.Enumerator enumerator = f.GetEnumerator()) { while (enumerator.MoveNext()) { pb_Face current = enumerator.get_Current(); list.AddRange(current.distinctIndices); } } return list; } public static int MeshTriangles(pb_Face[] faces, out int[][] submeshes, out Material[] materials) { Dictionary<Material, List<pb_Face>> dictionary = new Dictionary<Material, List<pb_Face>>(); int i; for (i = 0; i < faces.Length; i++) { Material material = faces[i].material ?? pb_Constant.UnityDefaultDiffuse; if (dictionary.ContainsKey(material)) { dictionary.get_Item(material).Add(faces[i]); } else { Dictionary<Material, List<pb_Face>> arg_5A_0 = dictionary; Material arg_5A_1 = material; List<pb_Face> list = new List<pb_Face>(1); list.Add(faces[i]); arg_5A_0.Add(arg_5A_1, list); } } materials = new Material[dictionary.get_Count()]; submeshes = new int[materials.Length][]; i = 0; using (Dictionary<Material, List<pb_Face>>.Enumerator enumerator = dictionary.GetEnumerator()) { while (enumerator.MoveNext()) { KeyValuePair<Material, List<pb_Face>> current = enumerator.get_Current(); submeshes[i] = pb_Face.AllTriangles(current.get_Value()); materials[i] = current.get_Key(); i++; } } return submeshes.Length; } public override string ToString() { if (this.indices.Length % 3 != 0) { return "Index count is not a multiple of 3."; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("{ "); for (int i = 0; i < this.indices.Length; i += 3) { stringBuilder.Append("["); stringBuilder.Append(this.indices[i]); stringBuilder.Append(", "); stringBuilder.Append(this.indices[i + 1]); stringBuilder.Append(", "); stringBuilder.Append(this.indices[i + 2]); stringBuilder.Append("]"); if (i < this.indices.Length - 3) { stringBuilder.Append(", "); } } stringBuilder.Append(" }"); return stringBuilder.ToString(); } public string ToStringDetailed() { string text = string.Concat(new object[] { "index count: ", this._indices.Length, "\nmat name : ", this.material.get_name(), "\nisManual : ", this.manualUV, "\nsmoothing group: ", this.smoothingGroup, "\n" }); for (int i = 0; i < this.indices.Length; i += 3) { string text2 = text; text = string.Concat(new object[] { text2, "Tri ", i, ": ", this._indices[i], ", ", this._indices[i + 1], ", ", this._indices[i + 2], "\n" }); } text += "Distinct Indices:\n"; for (int j = 0; j < this.distinctIndices.Length; j++) { text = text + this.distinctIndices[j] + ", "; } return text; } public static explicit operator pb_EdgeConnection(pb_Face face) { return new pb_EdgeConnection(face, null); } public static explicit operator pb_VertexConnection(pb_Face face) { return new pb_VertexConnection(face, null); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Presenter.Operators { class Square //: IOperator { public void perform(double input, int Hpointer) { } } }
#if (UNITY_EDITOR) using UnityEngine; using System.Collections; using UnityEditor; [CustomEditor(typeof(HeightmapProceduralEditor))] public class HeightmapProceduralEditorButtons : Editor { public override void OnInspectorGUI() { DrawDefaultInspector(); HeightmapProceduralEditor myScript = (HeightmapProceduralEditor)target; if (GUILayout.Button("Add noise")) { myScript.AddNoise(); } if (GUILayout.Button("Smooth")) { myScript.Smooth(); } if (GUILayout.Button("ResetTerrain")) { myScript.ResetTerrain(); } if (GUILayout.Button ("AddStreams")) { myScript.AddStreams (); } if (GUILayout.Button("Save heightmap")) { myScript.SaveHeightmap(); } } } #endif
using static Weather.Safety; using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; namespace Weather { enum Status { OK, NotOK } public sealed class R<D> { readonly D data; readonly List<Log> log; readonly Status status; R(D data, List<Log> log, Status status) { this.data = data; this.log = log; this.status = status; } public bool IsOK() { return status == Status.OK; } public bool DidFail() { return status == Status.NotOK; } public D GetDataOrElse(D value) { return IsOK() ? data : value; } public D GetData() { return CheckNotNull(data); } public List<Log> GetLog() { return CheckNotNull(log); } public void Log(string message, Action<StackFrame[], string> function) { CheckNotNull(message); var ste = new StackTrace().GetFrames(); log.Add(new Log(ste, message, 1)); function(ste, message); } public void Log(string message) { CheckNotNull(message); log.Add(new Log(new StackTrace().GetFrames(), message, 1)); } public R<D2> ContinueWith<D2>(D2 data) { return new R<D2>(data, log, status); } public R<D2> StopWith<D2>(string message) { Log(CheckNotNull(message)); return new R<D2>(default(D2), log, Status.NotOK); } public R<D2> Stop<D2>() { return new R<D2>(default(D2), log, Status.NotOK); } public static R<T> StartWith<T>(T data) { return new R<T>(data, new List<Log>(), Status.OK); } public R<D2> Bind<D2>(Func<R<D>, R<D2>> function) { return function(this); } /** * + operator overloading to demonstrate feasibility of binding ith * operators. F# pipe forward operator |> would be ideal for this * * Current limitations are: * - No custom operator support * - both lhs & rhs operands cannot be generic, & therefore requires * fixed typing, hence we're forced to overload each io scenario */ public static R<string> operator +(R<D> arg, Func<R<D>, R<string>> function) { return function(arg); } public static R<HttpWebResponse> operator +(R<D> arg, Func<R<D>, R<HttpWebResponse>> function) { return function(arg); } public static R<WebRequest> operator +(R<D> arg, Func<R<D>, R<WebRequest>> function) { return function(arg); } public static R<Forecast> operator +(R<D> arg, Func<R<D>, R<Forecast>> function) { return function(arg); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using API.Dtos; using API.Models; namespace API.Services { public interface IAttachmentService { Task<IAsyncResult> AddAsync(AttachmentToAdd attachmentToAdd); Task<IAsyncResult> DeleteAsync(int attachmentId); Task<IEnumerable<AttachmentToReturn>> GetAllAsync(); Task<AttachmentToReturn> GetAsync(int attachmentId); } }
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 Foodieee { public partial class konfirmasi : Form { //Memanggil dari class bintangtabledriven static bintangtabledriven.id id = bintangtabledriven.id.binbin; public string pin = id.ToString(); public string Password = bintangtabledriven.getPassword(id); public konfirmasi() { InitializeComponent(); } private void textBox2_TextChanged(object sender, EventArgs e) { } private void konfirmasi_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { string id, password; id = textBoxpin.Text; password = textBoxpw.Text; Console.WriteLine(id.ToString()); Console.WriteLine(password.ToString()); if (textBoxpin.Text == id.ToString() && textBoxpw.Text == password.ToString()) { MessageBox.Show("Pembayaran Berhasil"); this.Hide(); Success Sc = new Success(); Sc.Show(); } // Menerapkan kondisi apabila username kosong else if (id == "") { MessageBox.Show("id tidak boleh kosong"); } // Menerapkan kondisi apabila password kosong else if (password == "") { MessageBox.Show("Password tidak boleh kosong"); } // Menerapkan kondisi apabila username dan password user TIDAK terdaftar else { MessageBox.Show("Username atau Password salah"); } } private void pictureBox1_Click(object sender, EventArgs e) { this.Hide(); Pembayaran Pm = new Pembayaran(); Pm.Show(); } private void label1_Click(object sender, EventArgs e) { } } }
namespace TNBase.External.DataImport { public class ImportResultError { public ImportResultError(string fieldName, string errorMessage, string rawRecord) { FieldName = fieldName; ErrorMessage = errorMessage; RawRecord = rawRecord; } public string FieldName { get; } public string ErrorMessage { get; } public string RawRecord { get; } } }
using System.IO; using Microsoft.Xna.Framework.Content.Pipeline; namespace MonoGame.Extended.Content.Pipeline.Json { [ContentImporter(".json", DefaultProcessor = nameof(JsonContentProcessor), DisplayName = "JSON Importer - MonoGame.Extended")] public class JsonContentImporter : ContentImporter<ContentImporterResult<string>> { public override ContentImporterResult<string> Import(string filename, ContentImporterContext context) { var json = File.ReadAllText(filename); return new ContentImporterResult<string>(filename, json); } } }
using System.Collections.Generic; using System.Threading.Tasks; using Business.Abstract; using Core.Utilities.Results; using DataAccess.Abstract; using Entities.Concrete; namespace Business.Concrete { public class OrderStatusManager:IOrderStatusService { private IOrderStatusDal _orderStatusDal; public OrderStatusManager(IOrderStatusDal orderStatusDal) { _orderStatusDal = orderStatusDal; } public async Task<IDataResult<List<OrderStatus>>> GetAll() { return new SuccessDataResult<List<OrderStatus>>(await _orderStatusDal.GetAllAsync()); } public async Task<IResult> Add(OrderStatus orderStatus) { await _orderStatusDal.AddAsync(orderStatus); return new SuccessResult(); } public async Task<IResult> Delete(OrderStatus orderStatus) { await _orderStatusDal.DeleteAsync(orderStatus); return new SuccessResult(); } public async Task<IResult> Update(OrderStatus orderStatus) { await _orderStatusDal.UpdateAsync(orderStatus); return new SuccessResult(); } } }
 using System; using System.Diagnostics; using System.Windows.Forms; using System.IO; using ClosedXML.Excel; namespace ForRocket_FrontEnd { public partial class Simulation : Form { RocketParamter rocket_parameter = new RocketParamter(); SimulationParameter simulation_parameter = new SimulationParameter(); public Simulation() { InitializeComponent(); } private void Simulation_Load(object sender, EventArgs e) { if (!Directory.GetCurrentDirectory().EndsWith("bin")) { Directory.SetCurrentDirectory("./bin"); } ActiveControl = this.LogoPic; } //Structureシート読み出し private void button_structure_file_Click(object sender, EventArgs e) { string file_path = null; openFileDialog_structure.InitialDirectory = System.IO.Path.GetFullPath("../"); openFileDialog_structure.Title = "Select Input Structure Sheet"; openFileDialog_structure.CheckFileExists = true; openFileDialog_structure.CheckPathExists = true; if (openFileDialog_structure.ShowDialog() == DialogResult.OK) file_path = System.IO.Path.GetFullPath(openFileDialog_structure.FileName); if (File.Exists(file_path)) { textBox_sturucture.Text = file_path; XLWorkbook workbook = new XLWorkbook(file_path, XLEventTracking.Disabled); IXLWorksheet worksheet = workbook.Worksheet(1); rocket_parameter.structure_read_v4(worksheet); workbook.Dispose(); } } //Engineシート読み出し private void button_engine_file_Click(object sender, EventArgs e) { string file_path = null; openFileDialog_Engine.InitialDirectory = System.IO.Path.GetFullPath("../"); openFileDialog_Engine.Title = "Select Input Engine Sheet"; openFileDialog_Engine.CheckFileExists = true; openFileDialog_Engine.CheckPathExists = true; if (openFileDialog_Engine.ShowDialog() == DialogResult.OK) file_path = System.IO.Path.GetFullPath(openFileDialog_Engine.FileName); if (File.Exists(file_path)) { textBox_Engine.Text = file_path; XLWorkbook workbook = new XLWorkbook(file_path, XLEventTracking.Disabled); IXLWorksheet worksheet = workbook.Worksheet(1); rocket_parameter.engine_read_v4(worksheet); workbook.Dispose(); } } //空力設計フォーム呼び出し private void Button_Aero_Click(object sender, EventArgs e) { AeroDesign.AeroDesignForm aerodesignform = new AeroDesign.AeroDesignForm(rocket_parameter); aerodesignform.ShowDialog(this); aerodesignform.Dispose(); } //Enviroment preset private void check_noshiro_land_Click(object sender, EventArgs e) { check_noshiro_land.Checked = true; check_noshiro_sea.Checked = false; check_taiki_land.Checked = false; preset_noshiro_land(); } private void check_noshiro_sea_Click(object sender, EventArgs e) { check_noshiro_land.Checked = false; check_noshiro_sea.Checked = true; check_taiki_land.Checked = false; preset_noshiro_sea(); } private void check_taiki_land_Click(object sender, EventArgs e) { check_noshiro_land.Checked = false; check_noshiro_sea.Checked = false; check_taiki_land.Checked = true; preset_taiki_land(); } private void preset_noshiro_land() { text_Pa.Text = "100.8"; text_Ta.Text = "25.0"; reset_rho(); text_g0.Text = "9.8"; text_Hw.Text = "5.0"; text_Wh.Text = "4.5"; text_Hsepa.Text = "0.0"; text_elevation.Text = "75.0"; text_azimuth.Text = "215.0"; text_LL.Text = "5.0"; } private void preset_noshiro_sea() { text_Pa.Text = "100.8"; text_Ta.Text = "20.0"; reset_rho(); text_g0.Text = "9.8"; text_Hw.Text = "5.0"; text_Wh.Text = "6.0"; text_Hsepa.Text = "150.0"; text_elevation.Text = "85.0"; text_azimuth.Text = "125.0"; ; text_LL.Text = "5.0"; } private void preset_taiki_land() { text_Pa.Text = "100.5"; text_Ta.Text = "0.0"; reset_rho(); text_g0.Text = "9.8"; text_Hw.Text = "5.0"; text_Wh.Text = "7.4"; text_Hsepa.Text = "150.0"; text_elevation.Text = "85.0"; text_azimuth.Text = "25.0"; ; text_LL.Text = "5.0"; } private void text_Pa_Leave(object sender, EventArgs e) { reset_rho(); } private void text_Ta_Leave(object sender, EventArgs e) { reset_rho(); } private void reset_rho() { text_rho.Text = (float.Parse(text_Pa.Text) * 1000.0 / (287.0 * (float.Parse(text_Ta.Text) + 273.15))).ToString("F3"); } //計算条件 private void check_log_Click(object sender, EventArgs e) { check_log.Checked = true; check_table.Checked = false; textBox_Vw_max.ReadOnly = true; textBox_Vw_delta.ReadOnly = true; textBox_anglew_max.ReadOnly = true; textBox_anglew_delta.ReadOnly = true; } private void check_table_Click(object sender, EventArgs e) { check_log.Checked = false; check_table.Checked = true; textBox_Vw_max.ReadOnly = false; textBox_Vw_delta.ReadOnly = false; textBox_anglew_max.ReadOnly = false; textBox_anglew_delta.ReadOnly = false; } //Call ForRocket private void Button_Simulation_Click(object sender, EventArgs e) { double[] array = new double[9]; double[] array_sim = new double[6]; //Rocket Parameter array[0] = double.Parse(text_Pa.Text); array[1] = double.Parse(text_Ta.Text); array[2] = double.Parse(text_g0.Text); array[3] = double.Parse(text_Hw.Text); array[4] = double.Parse(text_Wh.Text); array[5] = double.Parse(text_Hsepa.Text); array[6] = double.Parse(text_elevation.Text); array[7] = double.Parse(text_azimuth.Text); array[8] = double.Parse(text_LL.Text); rocket_parameter.Environment_Load(array); rocket_parameter.Output_v4(); //Simulation Parameter array_sim[0] = double.Parse(textBox_Vw_min.Text); array_sim[1] = double.Parse(textBox_Vw_max.Text); array_sim[2] = double.Parse(textBox_Vw_delta.Text); array_sim[3] = double.Parse(textBox_anglew_min.Text); array_sim[4] = double.Parse(textBox_anglew_max.Text); array_sim[5] = double.Parse(textBox_anglew_delta.Text); if (check_log.Checked == true) { simulation_parameter.Output(0, array_sim); } if (check_table.Checked == true) { simulation_parameter.Output(1, array_sim); } /****************************************************/ //solverフォルダへ移動 Directory.SetCurrentDirectory("./solver"); //計算終了まで待機 Process p_solve = Process.Start(Path.GetFullPath("./ForRocket_v4.exe")); p_solve.WaitForExit(); Process p_post = Process.Start(Path.GetFullPath("./ForRocketPost.exe")); p_post.WaitForExit(); Directory.SetCurrentDirectory("../"); // ./binへ移動 /****************************************************/ CopyDirectory("./solver/OutputLog", "../result"); CopyDirectory("./solver/OutputTable", "../result"); using (StreamWriter DataFile = new StreamWriter("../result/SimulationConfiguration.out")) { DataFile.WriteLine("!----------------------------------------------------------!"); DataFile.WriteLine("!----------------ForRocket-Simulation Result---------------!"); DataFile.WriteLine("!----------------------------------------------------------!"); DataFile.WriteLine("Launch Elevation " + text_elevation.Text + "[deg]"); DataFile.WriteLine("Launch Azimuth " + text_azimuth.Text + "[deg]"); DataFile.WriteLine("2nd Separation Altitude " + text_Hsepa.Text + "[deg]"); } } public static void CopyDirectory(string sourceDirName, string destDirName) { //コピー先のディレクトリがないときは作る if (!System.IO.Directory.Exists(destDirName)) { System.IO.Directory.CreateDirectory(destDirName); //属性もコピー System.IO.File.SetAttributes(destDirName, System.IO.File.GetAttributes(sourceDirName)); } //コピー先のディレクトリ名の末尾に"\"をつける if (destDirName[destDirName.Length - 1] != System.IO.Path.DirectorySeparatorChar) destDirName = destDirName + System.IO.Path.DirectorySeparatorChar; //コピー元のディレクトリにあるファイルをコピー string[] files = System.IO.Directory.GetFiles(sourceDirName); foreach (string file in files) System.IO.File.Copy(file, destDirName + System.IO.Path.GetFileName(file), true); //コピー元のディレクトリにあるディレクトリについて、再帰的に呼び出す string[] dirs = System.IO.Directory.GetDirectories(sourceDirName); foreach (string dir in dirs) CopyDirectory(dir, destDirName + System.IO.Path.GetFileName(dir)); } //落下分散プロット呼び出し private void Button_LandingRange_Click(object sender, EventArgs e) { LandingRangeViewer.LandingRangeViewer landingrangeform = new LandingRangeViewer.LandingRangeViewer(); landingrangeform.Show(); } private void LogoPic_Click(object sender, EventArgs e) { AboutForRocket info_form = new AboutForRocket(); info_form.ShowDialog(this); info_form.Dispose(); } } public class RocketParamter { public double l; public double d; public double me; public double me_withfin; public double lcge; public double lcge_withfin; public double lcgox; // v4.1 only public double lcgf; public double ltank; // v4.1 only public double Is; public double Ir; public double lcp; public double Clp; // Roll減衰モーメント係数 public double Cmq; // Pitch/Yaw減衰モーメント係数 public double CNa; public double CdS1; public double CdS2; public double freq; public double Isp; public double It; public double tb; public double mox; public double mfb; public double mfa; public double lf; public double df_out; public double df_port; public double mdotox; // v4.1 only public double mdotf; public double de; public double Pa; public double Ta; public double rho; public double g0; public double Hw; public double Wh; public double Hsepa; public double elevation; public double azimuth; public double LL; //空力用 public double lnose; public double dtail; public double ltail; public double ms, m, ma; public double lcgs, lcg, lcga; //Structureシート読み出し public void structure_read_v4(IXLWorksheet worksheet) { l = worksheet.Cell(1, 2).GetDouble(); d = worksheet.Cell(2, 2).GetDouble(); me = worksheet.Cell(3, 2).GetDouble(); lcge = worksheet.Cell(4, 2).GetDouble(); lcgox = worksheet.Cell(5, 2).GetDouble(); lcgf = worksheet.Cell(6, 2).GetDouble(); ltank = worksheet.Cell(7, 2).GetDouble(); Is = worksheet.Cell(8, 2).GetDouble(); Ir = worksheet.Cell(9, 2).GetDouble(); lnose = worksheet.Cell(10, 2).GetDouble(); dtail = worksheet.Cell(11, 2).GetDouble(); ltail = worksheet.Cell(12, 2).GetDouble(); CdS1 = worksheet.Cell(13, 2).GetDouble(); CdS2 = worksheet.Cell(14, 2).GetDouble(); } //Engineシート読み出し public void engine_read_v4(IXLWorksheet worksheet) { freq = worksheet.Cell(1, 2).GetDouble(); de = worksheet.Cell(2, 2).GetDouble(); Isp = worksheet.Cell(3, 2).GetDouble(); It = worksheet.Cell(4, 2).GetDouble(); mox = worksheet.Cell(5, 2).GetDouble(); mfb = worksheet.Cell(6, 2).GetDouble(); mfa = worksheet.Cell(7, 2).GetDouble(); lf = worksheet.Cell(8, 2).GetDouble(); df_out = worksheet.Cell(9, 2).GetDouble(); df_port = worksheet.Cell(10, 2).GetDouble(); mdotox = worksheet.Cell(11, 2).GetDouble(); mdotf = worksheet.Cell(12, 2).GetDouble(); tb = worksheet.Cell(13, 2).GetDouble(); } public void Environment_Load(double[] array) { Pa = array[0]; Ta = array[1]; rho = Pa * 1000.0 / (287.1 * (Ta * 273.15)); g0 = array[2]; Hw = array[3]; Wh = array[4]; Hsepa = array[5]; elevation = array[6]; azimuth = array[7]; LL = array[8]; } //ForRocket input書き出し public void Output_v4() { using (StreamWriter DataFile = new StreamWriter("./solver/rocket_param.inp")) { DataFile.WriteLine(l.ToString()); DataFile.WriteLine(d.ToString()); DataFile.WriteLine((me_withfin).ToString()); DataFile.WriteLine(lcge_withfin.ToString()); DataFile.WriteLine(lcgox.ToString()); DataFile.WriteLine(lcgf.ToString()); DataFile.WriteLine(ltank.ToString()); DataFile.WriteLine(Is.ToString()); DataFile.WriteLine(Ir.ToString()); DataFile.WriteLine(lcp.ToString()); DataFile.WriteLine(Clp.ToString()); DataFile.WriteLine(Cmq.ToString()); DataFile.WriteLine(CNa.ToString()); DataFile.WriteLine(0.0.ToString()); DataFile.WriteLine(CdS1.ToString()); DataFile.WriteLine(CdS2.ToString()); DataFile.WriteLine(freq.ToString()); DataFile.WriteLine(de.ToString()); DataFile.WriteLine(Isp.ToString()); DataFile.WriteLine(mox.ToString()); DataFile.WriteLine(mfb.ToString()); DataFile.WriteLine(mfa.ToString()); DataFile.WriteLine(lf.ToString()); DataFile.WriteLine(df_out.ToString()); DataFile.WriteLine(df_port.ToString()); DataFile.WriteLine(mdotf.ToString()); DataFile.WriteLine(Pa.ToString()); DataFile.WriteLine(Ta.ToString()); DataFile.WriteLine(g0.ToString()); DataFile.WriteLine(Hw.ToString()); DataFile.WriteLine(Wh.ToString()); DataFile.WriteLine(0.0.ToString()); DataFile.WriteLine(Hsepa.ToString()); DataFile.WriteLine(elevation.ToString()); DataFile.WriteLine(azimuth.ToString()); DataFile.WriteLine(LL.ToString()); } } } public class SimulationParameter { int switch_log_table; //0:Log / 1:Table double Vw_min; double Vw_max; double Vw_delta; double anglew_min; double anglew_max; double anglew_delta; public void Output(int sw, double[] array) { switch_log_table = sw; Vw_min = array[0]; Vw_max = array[1]; Vw_delta = array[2]; anglew_min = array[3]; anglew_max = array[4]; anglew_delta = array[5]; if (switch_log_table == 1) { if (((Vw_max - Vw_min) / Vw_delta) > 56 || ((anglew_max - anglew_min) / anglew_delta) > 56) { MessageBox.Show("Table出力はデータ数56(7x8)点までのみ対応です!"); } } using (StreamWriter DataFile = new StreamWriter("./solver/switch.inp")) { DataFile.WriteLine(switch_log_table.ToString()); DataFile.WriteLine(Vw_min.ToString()); DataFile.WriteLine(Vw_max.ToString()); DataFile.WriteLine(Vw_delta.ToString()); DataFile.WriteLine(anglew_min.ToString()); DataFile.WriteLine(anglew_max.ToString()); DataFile.WriteLine(anglew_delta.ToString()); } } } }
using System.Collections.Generic; using Escc.Umbraco.PropertyEditors; using Umbraco.Core.Models; namespace Escc.EastSussexGovUK.UmbracoDocumentTypes.DataTypes { /// <summary> /// A data type which validates and formats phone numbers /// </summary> public static class PhoneNumberDataType { public const string DataTypeName = "Phone number"; public const string PropertyEditorAlias = PropertyEditorAliases.PhonePropertyEditor; /// <summary> /// Creates the data type in Umbraco. /// </summary> public static void CreateDataType() { UmbracoDataTypeService.InsertDataType(DataTypeName, PropertyEditorAlias, DataTypeDatabaseType.Nvarchar, new Dictionary<string, PreValue>()); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UniRx; using UnityEngine; public class BuildingController : BuildingControllerBase { public override void InitializeBuilding(BuildingViewModel building) { } }
using System; using System.Data; using System.Data.OleDb; namespace exportXml { public static class BazaDeDate { public static string nume { get; set; } public static string connectionstring { get; set; } public static OleDbConnection conexiune { get; set; } public static bool conexiuneDeschisa { get; set; } public static bool conectare(string numebazadedate="2020.mdb"){ connectionstring="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "\\" + numebazadedate; conexiune=new OleDbConnection(connectionstring); conexiune.Open(); conexiuneDeschisa=true; return true; } public static bool deconectare(){ if(conexiuneDeschisa==true){ conexiune.Close(); conexiune.Dispose(); conexiuneDeschisa=false ; } return true; } } }
using System; using System.Collections.Generic; using UnityEngine; using UnityEditor; namespace AorFramework.NodeGraph { /// <summary> /// NodeGraph 样式定义 /// </summary> public class NodeGraphDefind { private static GUIStyle _ToolItemFoldoutStyle; public static GUIStyle GetToolItemFoldoutStyle() { if (_ToolItemFoldoutStyle == null) { _ToolItemFoldoutStyle = GUI.skin.GetStyle("IN Foldout").Clone(); _ToolItemFoldoutStyle.fontSize = 10; _ToolItemFoldoutStyle.alignment = TextAnchor.MiddleLeft; _ToolItemFoldoutStyle.wordWrap = true; _ToolItemFoldoutStyle.normal.textColor = Color.white; } return _ToolItemFoldoutStyle; } private static GUIStyle _toolBarBtnStyle; private static GUIStyle _toolBarBtnStyle_hidden; public static GUIStyle GetToolBarBtnStyle(bool isShow) { if (isShow) { if (_toolBarBtnStyle == null) { _toolBarBtnStyle = GUI.skin.GetStyle("TL tab right").Clone(); } return _toolBarBtnStyle; } else { if (_toolBarBtnStyle_hidden == null) { _toolBarBtnStyle_hidden = GUI.skin.GetStyle("Label").Clone(); } return _toolBarBtnStyle_hidden; } } private static GUIStyle _inspectorBtnStyle; private static GUIStyle _inspectorBtnStyle_hidden; public static GUIStyle GetInspectorBtnStyle(bool isShow) { if (isShow) { if (_inspectorBtnStyle == null) { _inspectorBtnStyle = GUI.skin.GetStyle("TL tab left").Clone(); } return _inspectorBtnStyle; } else { if (_inspectorBtnStyle_hidden == null) { _inspectorBtnStyle_hidden = GUI.skin.GetStyle("RightLabel").Clone(); } return _inspectorBtnStyle_hidden; } } private static GUIStyle _ConnectPointLabelStyle_input; private static GUIStyle _ConnectPointLabelStyle_output; /// <summary> /// /// </summary> public static GUIStyle GetConnectPointLabelStyle(bool isOutput) { if (isOutput) { if (_ConnectPointLabelStyle_output == null) { // _ConnectPointLabelStyle_output = GUI.skin.box.Clone _ConnectPointLabelStyle_output = new GUIStyle(); _ConnectPointLabelStyle_output.fontSize = 10; _ConnectPointLabelStyle_output.alignment = TextAnchor.MiddleRight; _ConnectPointLabelStyle_output.wordWrap = true; _ConnectPointLabelStyle_output.normal.textColor = Color.white; } return _ConnectPointLabelStyle_output; } else { if (_ConnectPointLabelStyle_input == null) { // _ConnectPointLabelStyle_input = GUI.skin.box.Clone(); _ConnectPointLabelStyle_input = new GUIStyle(); _ConnectPointLabelStyle_input.fontSize = 10; _ConnectPointLabelStyle_input.alignment = TextAnchor.MiddleLeft; _ConnectPointLabelStyle_input.wordWrap = true; _ConnectPointLabelStyle_input.normal.textColor = Color.white; } return _ConnectPointLabelStyle_input; } } private static GUIStyle _NodeGUIBaseMainStyle; private static GUIStyle _NodeGUIBaseMainStyle_Active; /// <summary> /// 获取MainNodeGUI的基础GUIStyle /// </summary> public static GUIStyle GetNodeGUIBaseMainStyle(bool isActive = false) { if (isActive) { if (_NodeGUIBaseMainStyle_Active == null) { _NodeGUIBaseMainStyle_Active = GUI.skin.GetStyle("flow node 6 on").Clone(); _NodeGUIBaseMainStyle_Active.fontSize = 14; } return _NodeGUIBaseMainStyle_Active; } else { if (_NodeGUIBaseMainStyle == null) { _NodeGUIBaseMainStyle = GUI.skin.GetStyle("flow node 6").Clone(); _NodeGUIBaseMainStyle.fontSize = 14; } return _NodeGUIBaseMainStyle; } } private static GUIStyle _NodeGUIBaseStyle; private static GUIStyle _NodeGUIBaseStyle_Active; /// <summary> /// 获取NodeGUI的基础GUIStyle /// </summary> public static GUIStyle GetNodeGUIBaseStyle(bool isActive = false) { if (isActive) { if (_NodeGUIBaseStyle_Active == null) { _NodeGUIBaseStyle_Active = GUI.skin.GetStyle("flow node 0 on").Clone(); _NodeGUIBaseStyle_Active.fontSize = 14; } return _NodeGUIBaseStyle_Active; } else { if (_NodeGUIBaseStyle == null) { _NodeGUIBaseStyle = GUI.skin.GetStyle("flow node 0").Clone(); _NodeGUIBaseStyle.fontSize = 14; } return _NodeGUIBaseStyle; } } private static GUIStyle _NodeToolItemStyle; /// <summary> /// 返回 NodeToolItemStyle /// </summary> public static GUIStyle GetNodeToolItemStyle() { if (_NodeToolItemStyle == null) { _NodeToolItemStyle = GUI.skin.GetStyle("box").Clone(); _NodeToolItemStyle.alignment = TextAnchor.MiddleCenter; _NodeToolItemStyle.fontSize = 12; _NodeToolItemStyle.wordWrap = true; _NodeToolItemStyle.normal.textColor = Color.white; } return _NodeToolItemStyle; } /// <summary> /// 根据 nodeData 的类型 返回 ConnectCenterTip的基础GUIStyle /// </summary> public static GUIStyle GetConnectCenterTipBaseStyle() { return GUI.skin.GetStyle("sv_label_0").Clone(); } public static Vector2 WindowMinSize { get { return new Vector2(960,600);} } public const float ConnectCenterTipMargin = 5f; public const float ConnectCenterTipLabelPreHeight = 26f; public const float ConnectCenterTipLabelPreWidth = 8f; //--------------------- 菜单 定义--------------- public const string MENU_ROOT = "Window"; public const string MENU_MAIN_DIR = MENU_ROOT + "/NodeGraph"; //--------------------- 菜单 定义----------- end //--------------------- 数据缓存 资源定义 ----- /// <summary> /// *** 定义NodeGraph 数据缓存所在路径 /// /// (** 注意: NodeGraph使用 Application.dataPath.Replace("/Assets", "") 作为根路径) /// /// </summary> public static string RESCACHE_ROOTPATH { get { return Application.dataPath.Replace("/Assets", "") + RESCACHE_ROOTDIR; } } /// <summary> /// 定义NodeGraph 数据缓存所在文件夹名 /// (** 注意因路径连接需求,保留前面的一反斜杠) /// </summary> public const string RESCACHE_ROOTDIR = "/NodeGraphRESCaches"; /// <summary> /// 定义动态生成的脚本存放地址 /// </summary> public const string RESCACHE_DYNAMICSCRIPTDIR = "/Editor/DynamicScripts"; //--------------------- 数据缓存 资源定义 --end //--------------------- NodeGraph 样式图片资源定义 ----- /// <summary> /// *** 定义NodeGraph界面使用的图形资源所在基本路径 /// </summary> public const string RESOURCE_BASEPATH = "Assets/NodeGraphAssets/Bitmaps"; public const string RESOURCE_REFRESH_ICON = RESOURCE_BASEPATH + "/AssetGraph_RefreshIcon.png"; public const string RESOURCE_ARROW = RESOURCE_BASEPATH + "/AssetGraph_Arrow.png"; public const string RESOURCE_CONNECTIONPOINT_ENABLE = RESOURCE_BASEPATH + "/AssetGraph_ConnectionPoint_EnableMark.png"; public const string RESOURCE_CONNECTIONPOINT_INPUT = RESOURCE_BASEPATH + "/AssetGraph_ConnectionPoint_InputMark.png"; public const string RESOURCE_CONNECTIONPOINT_OUTPUT = RESOURCE_BASEPATH + "/AssetGraph_ConnectionPoint_OutputMark.png"; public const string RESOURCE_CONNECTIONPOINT_OUTPUT_CONNECTED = RESOURCE_BASEPATH + "/AssetGraph_ConnectionPoint_OutputMark_Connected.png"; public const string RESOURCE_INPUT_BG = RESOURCE_BASEPATH + "/AssetGraph_InputBG.png"; public const string RESOURCE_OUTPUT_BG = RESOURCE_BASEPATH + "/AssetGraph_OutputBG.png"; public const string RESOURCE_SELECTION = RESOURCE_BASEPATH + "/AssetGraph_Selection.png"; //--------------------- NodeGraph 样式图片资源定义 -- end //判定NodeGUI.OnClick的偏移阈值 public const float MouseClickThresholdX = 5f; public const float MouseClickThresholdY = 5f; //菜单栏高度 public const float MenuLayoutHeight = 30f; //工具箱的宽度 public const float ToolAreaWidth = 135f; //工具箱物品高度 public const float ToolAreaItemHeight = 46f; public const float ToolAreaItemFoldoutHeight = 20f; //Inspector宽度 public const float InspectorWidth = 360f; //NodeGUI 最小Size public const float NodeGUIMinSizeX = 100f; public const float NodeGUIMinSizeY = 120f; //NodeGraphCanvas 最小Szie public const float NodeGraphMinSizeX = 1200f; public const float NodeGraphMinSizeY = 1600f; //NodeGraphCanvas 动态Size延展尺寸 public const float NodeGraphSizeExtX = 100f; public const float NodeGraphSizeExtY = 60f; //NodeGUI内容Margin public const float NodeGUIContentMarginX = 10f; public const float NodeGUIContentMarginY = 10f; public const float ModeGUIRefreshIconX = 16f; public const float ModeGUIRefreshIconY = 16f; //NodeGUI Resize图标size public const float NodeGUIResizeIconSizeX = 8f; public const float NodeGUIResizeIconSizeY = 8f; //NodeGraph框体基本颜色 private static Color m_NodeGraphBaseColor = Color.white; public static Color NodeGraphBaseColor { get { return m_NodeGraphBaseColor; } } //MutiSelection 框体颜色 private static Color m_MutiSelectionColor = Color.cyan; public static Color MutiSelectionColor { get { return m_MutiSelectionColor;} } public const float NODE_TITLE_HEIGHT = 30f; /// 输入点size(BG) public const float INPUT_POINT_WIDTH = 16f; public const float INPUT_POINT_HEIGHT = 26f; //输出点size(BG) public const float OUTPUT_POINT_WIDTH = 18f; public const float OUTPUT_POINT_HEIGHT = 32f; public const float CONNECTION_INPUT_POINT_MARK_SIZE = 20f; public const float CONNECTION_OUTPUT_POINT_MARK_SIZE = 16f; public const string NODE_INPUTPOINT_FIXED_LABEL = "FIXED_INPUTPOINT_ID"; //连线箭头size public const float CONNECTION_ARROW_WIDTH = 12f; public const float CONNECTION_ARROW_HEIGHT = 15f; //连线最小长度 public const float CONNECTION_CURVE_LENGTH = 10f; } }
using System; using System.Collections.Generic; using System.Text; namespace TrainingCS { interface ISolution { int Solution(int N); } }
namespace Library.Client.Core.Commands { using Data; using Models; using System; using System.Linq; using Utilities; public class RegisterUserCommand { public string Execute(string[] inputArgs) { Check.CheckLength(7, inputArgs); string username = inputArgs[0]; //Validate given username. if (username.Length > Constants.MaxUsernameLength || username.Length < Constants.MinUsernameLength) { throw new ArgumentException(string.Format(Constants.ErrorMessages.UsernameNotValid, username)); } string password = inputArgs[1]; //Validate password. if (!password.Any(char.IsDigit) || !password.Any(char.IsUpper)) { throw new ArgumentException(string.Format(Constants.ErrorMessages.PasswordNotValid, password)); } string repeatedPassword = inputArgs[2]; //Validate passwords if (password != repeatedPassword) { throw new InvalidOperationException(Constants.ErrorMessages.PasswordDoesNotMatch); } string firstName = inputArgs[3]; string lastName = inputArgs[4]; //Validate age int age; bool isNumber = int.TryParse(inputArgs[5], out age); if (!isNumber || age < 0) { throw new ArgumentException(Constants.ErrorMessages.AgeNotValid); } //Validate genre Gender gender; bool isGenderValid = Enum.TryParse(inputArgs[6], out gender); if (!isGenderValid) { throw new ArgumentException(Constants.ErrorMessages.GenderNotValid); } if (CommandHelper.IsUserExisting(username)) { throw new InvalidOperationException(string.Format(Constants.ErrorMessages.UsernameIsTaken, username)); } this.RegisterUser(username, password, firstName, lastName, age, gender); return $"User {username} was registered successfully!"; } private void RegisterUser(string username, string password, string firstName, string lastName, int age, Gender gender) { using (LibraryContext context = new LibraryContext()) { User u = new User() { Username = username, Password = password, FirstName = firstName, LastName = lastName, Age = age, Genre = gender, RegisteredOn = DateTime.Now, Role = Role.User }; context.Users.Add(u); context.SaveChanges(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SM.DAL; using SM.Entities.Model; namespace SM.BLL { public class AccountBLL { private readonly AccountDAL _accountDAL = new AccountDAL(); /// <summary> /// 获取账号信息 /// </summary> /// <param name="name"></param> /// <param name="psd"></param> /// <returns></returns> public Account GetAccount(string name, string psd) { return _accountDAL.GetAccount(name, psd); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SpSim.Util { /// <summary> /// Collection of Tags used in the game's .xml file /// </summary> public class Tags { //Clothes public const string CLOTHING = "clothing"; public const string CLOTHING_ID = "id"; public const string CLOTHING_NAME = "name"; public const string CLOTHING_DESCRIPTION = "description"; public const string CLOTHING_TYPE = "type"; public const string CLOTHING_UNDRESSTYPE = "und"; public const string CLOTHING_RESISTANCE = "resistance"; public const string CLOTHING_ARTICLE = "reqart"; //Girls public const string GIRL = "girl"; public const string GIRL_ID = "id"; public const string GIRL_NAME = "name"; public const string GIRL_DESCRIPTION = "description"; public const string GIRL_LORE = "lore"; public const string GIRL_RESISTANCE = "resistance"; public const string GIRL_AFFECTION = "affection"; public const string GIRL_SPANKABLE = "spankable"; public const string GIRL_CALL = "call"; public const string GIRL_OWN_ROOM = "own_room"; public const string GIRL_TOPCLOTH = "topcloth"; public const string GIRL_BOTCLOTH = "botcloth"; public const string GIRL_ONECLOTH = "onecloth"; public const string GIRL_BRACLOTH = "bracloth"; public const string GIRL_UNDCLOTH = "undcloth"; public const string GIRL_SOCCLOTH = "soccloth"; public const string GIRL_SHOCLOTH = "shocloth"; //Holdings public const string HOLDING = "holding"; public const string HOLDING_ID = "id"; public const string HOLDING_NAME = "name"; public const string HOLDING_REQUIREDCLOTHING = "requiredClothing"; //Implements public const string IMPLEMENT = "implement"; public const string IMPLEMENT_NAME = "name"; public const string IMPLEMENT_ID = "id"; public const string IMPLEMENT_STRENGTH = "strength"; public const string IMPLEMENT_SFX = "sfx"; //Messages public const string MESSAGE_FILTER_ID = "id"; public const string MESSAGE_FILTER_LIKE = "reqlike"; public const string MESSAGE_FILTER_PAIN = "reqpain"; public const string MESSAGE_FILTER_CONTRITEMENT = "reqrepnt"; public const string MESSAGE_FILTER_POSITION = "reqpos"; public const string MESSAGE_FILTER_HOLDING = "reqby"; public const string MESSAGE_LOOK_AT = "look"; public const string MESSAGE_PAIN_DOWN = "paindown"; public const string MESSAGE_PICKUP_IMPLEMENT = "reactpick"; public const string MESSAGE_ENTER_WITH_IMPLEMENT = "reactentercarrying"; public const string MESSAGE_SWAP_IMPLEMENT = "reactswap"; public const string MESSAGE_SWAP_WORSE = "reactworseswap"; public const string MESSAGE_DROP_IMPLEMENT = "reactdrop"; public const string MESSAGE_HOLDING_ANNOUNCE = "holdingannounce"; public const string MESSAGE_HOLDING_ANNOUNCE_REACT = "reactholdingannounce"; public const string MESSAGE_HOLDING_ANNOUNCE_WATCH = "watchholdingannounce"; public const string MESSAGE_HOLDING_START = "holdingstart"; public const string MESSAGE_HOLDING_START_REACT = "reactholdingstart"; public const string MESSAGE_HOLDING_START_WATCH = "holdingwatchstart"; public const string MESSAGE_HOLDING_DRAG = "drag"; public const string MESSAGE_HOLDING_DRAG_REACT = "reactdrag"; public const string MESSAGE_HOLDING_DRAG_WATCH = "watchdrag"; public const string MESSAGE_HOLDING_STOP = "holdingstop"; public const string MESSAGE_HOLDING_STOP_REACT = "reactholdingstop"; public const string MESSAGE_HOLDING_STOP_WITHOUTDRAG = "reactstopwithoutdrag"; //Protagonist public const string PROTAGONIST = "protagonist"; public const string PROTAGONIST_NAME = "name"; public const string PROTAGONIST_GENDER = "gender"; public const string PROTAGONIST_LORE = "lore"; public const string PROTAGONIST_OWNROOM = "own_room"; public const string PROTAGONIST_TEXTCOLOR = "textcolor"; //Rooms public const string ROOM = "room"; public const string ROOM_ID = "id"; public const string ROOM_NAME = "name"; public const string ROOM_DESCRIPTION = "description"; public const string ROOM_LINKS = "links"; public const string ROOM_PRE = "pre"; public const string ROOM_SITPLACE = "sitplace"; public const string ROOM_LIEPLACE = "lieplace"; public const string ROOM_BENDPLACE = "bendplace"; public const string ROOM_CLOTHES = "scatteredClothes"; public const string ROOM_CLOTHES_MAX = "max"; public const string ROOM_CLOTHES_DUMP = "dumpclothes"; } }
using Math = System.Math; namespace Uif { public enum EasingType { Linear = 0, Sine, Quad, Cubic, Quart, Quint, Expo, Circ, Back, Elastic, Bounce } public enum EasingPhase { In = 0, Out, InOut } /// <summary> /// b: beginning value, c: change in value, t: current time, d: duration. /// </summary> public delegate double EasingFunction(double begin, double change, double time, double duration); public static class Easing { /// <summary> /// Calculate the eased value from begin to begin + change. /// </summary> /// <param name="type">Easing type.</param> /// <param name="phase">Easing phase.</param> /// <param name="begin">Begin value.</param> /// <param name="change">Value change.</param> /// <param name="time">Current time.</param> /// <param name="duration">Total duration.</param> public static float Ease(EasingType type, EasingPhase phase, double begin, double change, double time, double duration = 1) { return (float)GetEasingFuction(type, phase)(begin, change, time, duration); } /// <summary> /// Calculate the eased value from 0 to 1. /// </summary> /// <param name="type">Easing type.</param> /// <param name="phase">Easing phase.</param> /// <param name="time">Current time.</param> /// <param name="duration">Total duration.</param> public static float Ease(EasingType type, EasingPhase phase, double time, double duration = 1) { return (float)GetEasingFuction(type, phase)(0, 1, time, duration); } /// <summary> /// Get the easing fuction. /// </summary> /// <returns>The easing fuction.</returns> /// <param name="type">Easing type.</param> /// <param name="phase">Easing phase.</param> public static EasingFunction GetEasingFuction(EasingType type, EasingPhase phase) { return EasingFunctions[(int)type * 3 + (int)phase]; } #region Easing Functions public static readonly EasingFunction[] EasingFunctions = { Linear, Linear, Linear, SineIn, SineOut, SineInOut, QuadIn, QuadOut, QuadInOut, CubicIn, CubicOut, CubicInOut, QuartIn, QuartOut, QuartInOut, QuintIn, QuintOut, QuintInOut, ExpoIn, ExpoOut, ExpoInOut, CircIn, CircOut, CircInOut, BackIn, BackOut, BackInOut, ElasticIn, ElasticOut, ElasticInOut, BounceIn, BounceOut, BounceInOut }; public static double Linear(double b, double c, double t, double d = 1) { return t / d * c + b; } public static double SineIn(double b, double c, double t, double d = 1) { return -c * Math.Cos(t / d * (Math.PI / 2)) + c + b; } public static double SineOut(double b, double c, double t, double d = 1) { return c * Math.Sin(t / d * (Math.PI / 2)) + b; } public static double SineInOut(double b, double c, double t, double d = 1) { return -c / 2 * (Math.Cos(Math.PI * t / d) - 1) + b; } public static double QuadIn(double b, double c, double t, double d = 1) { return c * (t /= d) * t + b; } public static double QuadOut(double b, double c, double t, double d = 1) { return -c * (t /= d) * (t - 2) + b; } public static double QuadInOut(double b, double c, double t, double d = 1) { if ((t /= d / 2) < 1) return c / 2 * t * t + b; return -c / 2 * ((--t) * (t - 2) - 1) + b; } public static double CubicIn(double b, double c, double t, double d = 1) { return c * (t /= d) * t * t + b; } public static double CubicOut(double b, double c, double t, double d = 1) { return c * ((t = t / d - 1) * t * t + 1) + b; } public static double CubicInOut(double b, double c, double t, double d = 1) { if ((t /= d / 2) < 1) return c / 2 * t * t * t + b; return c / 2 * ((t -= 2) * t * t + 2) + b; } public static double QuartIn(double b, double c, double t, double d = 1) { return c * (t /= d) * t * t * t + b; } public static double QuartOut(double b, double c, double t, double d = 1) { return -c * ((t = t / d - 1) * t * t * t - 1) + b; } public static double QuartInOut(double b, double c, double t, double d = 1) { if ((t /= d / 2) < 1) return c / 2 * t * t * t * t + b; return -c / 2 * ((t -= 2) * t * t * t - 2) + b; } public static double QuintIn(double b, double c, double t, double d = 1) { return c * (t /= d) * t * t * t * t + b; } public static double QuintOut(double b, double c, double t, double d = 1) { return c * ((t = t / d - 1) * t * t * t * t + 1) + b; } public static double QuintInOut(double b, double c, double t, double d = 1) { if ((t /= d / 2) < 1) return c / 2 * t * t * t * t * t + b; return c / 2 * ((t -= 2) * t * t * t * t + 2) + b; } public static double ExpoIn(double b, double c, double t, double d = 1) { return (t == 0) ? b : c * Math.Pow(2, 10 * (t / d - 1)) + b; } public static double ExpoOut(double b, double c, double t, double d = 1) { return (t == d) ? b + c : c * (-Math.Pow(2, -10 * t / d) + 1) + b; } public static double ExpoInOut(double b, double c, double t, double d = 1) { if (t == 0) return b; if (t == d) return b + c; if ((t /= d / 2) < 1) return c / 2 * Math.Pow(2, 10 * (t - 1)) + b; return c / 2 * (-Math.Pow(2, -10 * --t) + 2) + b; } public static double CircIn(double b, double c, double t, double d = 1) { return -c * (Math.Sqrt(1 - (t /= d) * t) - 1) + b; } public static double CircOut(double b, double c, double t, double d = 1) { return c * Math.Sqrt(1 - (t = t / d - 1) * t) + b; } public static double CircInOut(double b, double c, double t, double d = 1) { if ((t /= d / 2) < 1) return -c / 2 * (Math.Sqrt(1 - t * t) - 1) + b; return c / 2 * (Math.Sqrt(1 - (t -= 2) * t) + 1) + b; } public static double BackIn(double b, double c, double t, double d = 1) { double s = 1.70158; return c * (t /= d) * t * ((s + 1) * t - s) + b; } public static double BackOut(double b, double c, double t, double d = 1) { double s = 1.70158; return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b; } public static double BackInOut(double b, double c, double t, double d = 1) { double s = 1.70158; if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b; return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b; } public static double ElasticIn(double b, double c, double t, double d = 1) { if (t == 0) return b; if ((t /= d) == 1) return b + c; double s; double a = c; double p = d * .3; if (a < Math.Abs(c)) { a = c; s = p / 4; } else s = p / (2 * Math.PI) * Math.Asin(c / a); return -(a * Math.Pow(2, 10 * (t -= 1)) * Math.Sin((t * d - s) * (2 * Math.PI) / p)) + b; } public static double ElasticOut(double b, double c, double t, double d = 1) { if (t == 0) return b; if ((t /= d) == 1) return b + c; double s; double a = c; double p = d * .3; if (a < Math.Abs(c)) { a = c; s = p / 4; } else s = p / (2 * Math.PI) * Math.Asin(c / a); return a * Math.Pow(2, -10 * t) * Math.Sin((t * d - s) * (2 * Math.PI) / p) + c + b; } public static double ElasticInOut(double b, double c, double t, double d = 1) { if (t == 0) return b; if ((t /= d / 2) == 2) return b + c; double s; double a = c; double p = d * (.3 * 1.5); if (a < Math.Abs(c)) { a = c; s = p / 4; } else s = p / (2 * Math.PI) * Math.Asin(c / a); if (t < 1) return -.5 * (a * Math.Pow(2, 10 * (t -= 1)) * Math.Sin((t * d - s) * (2 * Math.PI) / p)) + b; return a * Math.Pow(2, -10 * (t -= 1)) * Math.Sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b; } public static double BounceIn(double b, double c, double t, double d = 1) { return c - BounceOut(0, c, d - t, d) + b; } public static double BounceOut(double b, double c, double t, double d = 1) { if ((t /= d) < (1 / 2.75)) { return c * (7.5625 * t * t) + b; } else if (t < (2 / 2.75)) { return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b; } else if (t < (2.5 / 2.75)) { return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b; } else { return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b; } } public static double BounceInOut(double b, double c, double t, double d = 1) { if (t < d / 2) return BounceIn(0, c, t * 2, d) * .5 + b; return BounceOut(0, c, t * 2 - d, d) * .5 + c * .5 + b; } #endregion } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // #region Usings using System; using System.Collections.Generic; using DotNetNuke.Common.Utilities; #endregion namespace DotNetNuke.Services.Search.Entities { /// <summary> /// Collection storing Search Results /// </summary> [Serializable] public class SearchResults { /// <summary> /// Total Hits found in Lucene /// </summary> /// <remarks>This number will generally be larger than count of Results object as Results usually holds 10 items, whereas TotalHits indicates TOTAL hits in entire Lucene for the query supplied.</remarks> public int TotalHits { get; set; } /// <summary> /// Collection of Results /// </summary> public IList<SearchResult> Results { get; set; } public SearchResults() { Results = new List<SearchResult>(); } } }
 using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Master.BusinessFactory; namespace LogiCon.Areas.Reports.Controllers { [RoutePrefix("api/reports/operational")] public class OperationalController : ApiController { [HttpGet] [Route("lookup")] public IHttpActionResult lookupData() { try { var lookupBO = new LookupBO(); var shipmentTypeList = lookupBO.GetListByCategory("ShipmentType").Select(x => new Select { Value = x.LookupID, Text = x.LookupDescription }).ToList(); var jobTypeList = lookupBO.GetListByCategory("JobType").Select(x => new Select { Value = x.LookupID, Text = x.LookupDescription }).ToList(); return Ok(new { shipmentTypeList = shipmentTypeList, jobTypeList = jobTypeList }); } catch (Exception ex) { return InternalServerError(ex); } } } }
using System.Web; using System.Web.Optimization; namespace amsdemo { public class BundleConfig { // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquerylogin").Include( "~/Scripts/jquery-3.2.1.min.js", "~/Scripts/animsition.min.js", "~/Scripts/popper.js", "~/Scripts/bootstrap.min.js", "~/Scripts/select2.min.js", "~/Scripts/moment.min.js", "~/Scripts/daterangepicker.js", "~/Scripts/countdowntime.js", "~/Scripts/main.js")); bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery.min.js", "~/Scripts/popper.min.js", "~/Scripts/metisMenu.min.js", "~/Scripts/jquery.slimscroll.min.js", "~/Scripts/app.min.js", "~/Scripts/dashboard_1_demo.js", "~/Scripts/datatables.min.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at https://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.min.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.min.css", "~/Content/font-awesome.min.css", "~/Content/themify-icons.css", "~/Content/main.min.css", "~/Content/datatables.min.css")); bundles.Add(new StyleBundle("~/Content/cssforlogin").Include( "~/Content/bootstrap.min1.css", "~/Content/font-awesome.min1.css", "~/Content/material-design-iconic-font.min.css", "~/Content/animate.css", "~/Content/hamburgers.min.css", "~/Content/animsition.min.css", "~/Content/select2.min.css", "~/Content/daterangepicker.css", "~/Content/util.css", "~/Content/main1.css")); } } }
using Godot; using System; using static Lib; public class Tower : StaticBody { public float power; public int type; public int effect; protected AnimationPlayer crystalAPlayer; protected MeshInstance model; protected MeshInstance crystal; protected Root root; public void RespawnSpell(Spell s, Vector3 normal, float angle, bool last = false) { if (s == null) { GD.Print("Respawn spell error."); return; } Spell a; if (last) { a = s; } else { if (s.copy >= MAX_SPELL_COPIES_NUM) { return; } a = (Spell)s.Duplicate(); /* a = root.CreateSpell(s.GlobalTransform.origin); if (a == null) { return; }*/ root.AddToGame(a); a.startTime = s.startTime; } a.copy = s.copy + 1; a.wizard = s.wizard; a.effect = effect; Vector3 v = normal.Rotated(new Vector3(0.0f, 1.0f, 0.0f), angle).Normalized(); Vector3 arrowPos = TOWER_GEN_SPELL_DIST * v + this.GlobalTransform.origin; arrowPos.y = s.GlobalTransform.origin.y; float arrowSpeed = s.speed.Length(); a.GlobalTransform = new Transform(s.GlobalTransform.basis, arrowPos); a.speed = arrowSpeed * v; a.damage *= power; } public void SpellCollision(Spell s, Vector3 normal) { if (type == SIDE_T_TYPE || type == ALL_T_TYPE) { RespawnSpell(s, normal, Mathf.Pi / 2.0f); RespawnSpell(s, normal, -Mathf.Pi / 2.0f, (type == SIDE_T_TYPE)); } if (type == FRONT_T_TYPE || type == ALL_T_TYPE) { if (s.copy <= 0) { RespawnSpell(s, normal, 0.0f); } RespawnSpell(s, normal, Mathf.Pi, true); } } public void Init() { if (type >= 0 && model != null) { model.Mesh = towerTModels[type]; } if (effect >= 0 && crystal != null) { crystal.MaterialOverride = eMaterials[effect]; } } public override void _Ready() { crystalAPlayer = (AnimationPlayer)GetNode("CrystalAPlayer"); model = (MeshInstance)GetNode("Model"); crystal = (MeshInstance)GetNode("Crystal"); root = (Root)GetNode("/root/root"); crystalAPlayer.Play("crystal"); type = -1; effect = -1; power = BASE_TOWER_POWER; } }
/* * Copyright (c) 2020 Samsung Electronics Co., Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using SquatCounter.Services; using System.Windows.Input; using Xamarin.Forms; namespace SquatCounter.ViewModels { /// <summary> /// Guide page view model which is parent to all guide page view models. /// </summary> public class GuidePageViewModel : ViewModelBase { /// <summary> /// Background image path. /// </summary> public string ImagePath { get; set; } /// <summary> /// Navigates to squat counter page. /// </summary> public ICommand GoToSquatCounterPageCommand { get; set; } /// <summary> /// Initializes GuidePageViewModel instance. /// </summary> public GuidePageViewModel() { GoToSquatCounterPageCommand = new Command(ExecuteGoToSquatCounterPageCommand); } /// <summary> /// Handles execution of GoToSquatCounterPageCommand. /// </summary> public void ExecuteGoToSquatCounterPageCommand() { PageNavigationService.Instance.GoToSquatCounterPage(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ArtCom.Logging { public static class HumanFriendlyRandomString { private static readonly string[] AnimalNames = new string[] { "Alligator", "Alpaca", "Ant", "Antelope", "Ape", "Armadillo", "Baboon", "Badger", "Bat", "Bear", "Beaver", "Bee", "Beetle", "Buffalo", "Butterfly", "Camel", "Cat", "Cheetah", "Chimpanzee", "Clam", "Crab", "Crow", "Deer", "Dinosaur", "Dog", "Dolphin", "Duck", "Eel", "Elephant", "Ferret", "Fish", "Fly", "Fox", "Frog", "Giraffe", "Goat", "Gorilla", "Hamster", "Horse", "Hyena", "Kangaroo", "Koala", "Leopard", "Lion", "Lizard", "Llama", "Mammoth", "Mink", "Mole", "Monkey", "Mouse", "Otter", "Ox", "Oyster", "Panda", "Pig", "Rabbit", "Raccoon", "Seal", "Shark", "Sheep", "Snake", "Spider", "Squirrel", "Tiger", "Turtle", "Wasp", "Weasel", "Whale", "Wolf", "Yak", "Zebra" }; private static readonly string[] Adjectives = new string[] { "Good", "New", "First", "Last", "Long", "Great", "Little", "Old", "Big", "High", "Different", "Small", "Large", "Young", "Important", "Bad", "Adorable", "Beautiful", "Clean", "Elegant", "Fancy", "Glamorous", "Magnificent", "Old-Fashioned", "Plain", "Wide-Eyed", "Red", "Orange", "Yellow", "Green", "Blue", "Purple", "Gray", "Black", "White", "Careful", "Clever", "Famous", "Gifted", "Helpful", "Important", "Odd", "Powerful", "Shy", "Vast", "Wrong", "Brave", "Calm", "Happy", "Kind", "Lively", "Nice", "Silly", "Angry", "Fierce", "Grumpy", "Lazy", "Nervous", "Scary", "Obnoxious", "Massive", "Short", "Small" }; public static string Create(Random rnd) { string result = ""; for (int i = rnd.Next(1, 3); i > 0; i--) { result = AnimalNames[rnd.Next(0, AnimalNames.Length)] + result; } for (int i = rnd.Next(1, 3); i > 0; i--) { result = Adjectives[rnd.Next(0, Adjectives.Length)] + result; } return result; } } }
using UnityEngine; using UnityEngine.UI; using VRTK; public class BatController : MonoBehaviour { public GameController gameController; public GameObject bat; public GameObject otherBat; public Canvas instructionCanvas; public Image radialProgress; private float _triggerHoldTime = -10f; private bool _inProgress; private AudioSource _audio; private VRTK_ControllerEvents _events; private const float TRIGGER_HOLD_TIME = 1; void Awake() { _audio = GetComponent<AudioSource>(); _events = GetComponent<VRTK_ControllerEvents>(); } void Update() { if (_inProgress && gameController.HasFinished) { instructionCanvas.gameObject.SetActive(true); _inProgress = false; } if (gameController.HasStarted || _triggerHoldTime <= 0) return; if (Time.time >= _triggerHoldTime) { gameController.OnStartGame(); _inProgress = true; instructionCanvas.gameObject.SetActive(false); _triggerHoldTime = -10f; radialProgress.gameObject.SetActive(false); radialProgress.fillAmount = 0f; } else { radialProgress.fillAmount = 1 - (_triggerHoldTime - Time.time) / TRIGGER_HOLD_TIME; } } void OnEnable() { _events.GripPressed += OnGripPressed; _events.TriggerPressed += OnTriggerPressed; _events.TriggerReleased += OnTriggerReleased; } void OnDisable() { _events.GripPressed -= OnGripPressed; _events.TriggerPressed -= OnTriggerPressed; _events.TriggerReleased -= OnTriggerReleased; } private void OnGripPressed(object sender, ControllerInteractionEventArgs e) { if (bat.activeSelf || gameController.HasStarted) return; bat.SetActive(!bat.activeSelf); otherBat.SetActive(!otherBat.activeSelf); } private void OnTriggerPressed(object sender, ControllerInteractionEventArgs e) { if (!bat.activeSelf || gameController.HasStarted) return; _triggerHoldTime = Time.time + TRIGGER_HOLD_TIME; radialProgress.gameObject.SetActive(true); radialProgress.fillAmount = 0f; _audio.Play(); } private void OnTriggerReleased(object sender, ControllerInteractionEventArgs e) { if (!bat.activeSelf || gameController.HasStarted) return; _triggerHoldTime = -10f; radialProgress.gameObject.SetActive(false); radialProgress.fillAmount = 0f; _audio.Stop(); } }
using DukcapilWS.ApiServices.Entity; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Text; namespace DukcapilWS.ApiServices { public class Services { public List<T> ConvertDataTable<T>(DataTable dt) { List<T> data = new List<T>(); foreach (DataRow row in dt.Rows) { T item = GetItem<T>(row); data.Add(item); } return data; } public T GetItem<T>(DataRow dr) { Type temp = typeof(T); T obj = Activator.CreateInstance<T>(); foreach (DataColumn column in dr.Table.Columns) { foreach (PropertyInfo pro in temp.GetProperties()) { if (pro.Name == column.ColumnName) pro.SetValue(obj, dr[column.ColumnName], null); else continue; } } return obj; } public KTP KtpPickup(string NIK, string UserID, string Pass, string Ip) { KTP data = new KTP(); try { var baseAddress = "http://172.16.160.128:8000/dukcapil/get_json/BATAVIA_FINANCE/call_nik"; var httpWebRequest = (HttpWebRequest)WebRequest.Create(baseAddress); httpWebRequest.ContentType = "application/json"; httpWebRequest.Accept = "application/json"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = "{\"NIK\":\"" + NIK + "\"," + "\"user_id\":\"" + UserID + "\"," + "\"password\":\"" + Pass + "\"," + "\"ip_user\":\"" + Ip + "\"}"; streamWriter.Write(json); streamWriter.Flush(); streamWriter.Close(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { string result = streamReader.ReadToEnd(); var items = JsonConvert.DeserializeObject<BaseEntity>(result); foreach (KTP item in items.content) { data.AGAMA = item.AGAMA; data.ALAMAT = item.ALAMAT; data.JENIS_KLMIN = item.JENIS_KLMIN; data.JENIS_PKRJN = item.JENIS_PKRJN; data.KAB_NAME = item.KAB_NAME; data.KEC_NAME = item.KEC_NAME; data.KEL_NAME = item.KEL_NAME; data.NAMA_LGKP = item.NAMA_LGKP; data.NAMA_LGKP_IBU = item.NAMA_LGKP_IBU; data.NIK = item.NIK; data.NO_KAB = item.NO_KAB; data.NO_KEC = item.NO_KEC; data.NO_KEL = item.NO_KEL; data.NO_KK = item.NO_KK; data.NO_PROP = item.NO_PROP; data.NO_RT = item.NO_RT; data.NO_RW = item.NO_RW; data.PROP_NAME = item.PROP_NAME; data.STATUS_KAWIN = item.STATUS_KAWIN; data.TGL_LHR = item.TGL_LHR; data.TMPT_LHR = item.TMPT_LHR; } } } catch (Exception ex) { data = null; } return data; } } }
using System; using System.Runtime.InteropServices; namespace Sample { partial class NativeMethods { partial class NCrypt { /// <summary> /// Struct NCryptBuffer /// </summary> /// <remarks> /// https://docs.microsoft.com/en-us/windows/desktop/api/bcrypt/ns-bcrypt-_bcryptbuffer /// </remarks> [StructLayout(LayoutKind.Sequential)] internal struct NCryptBuffer { /// <summary> /// The size, in bytes, of the buffer. /// </summary> public int cbBuffer; /// <summary> /// The buffer type /// </summary> public BufferType BufferType; /// <summary> /// The address of the buffer. The size of this buffer is contained in /// the cbBuffer member. /// The format and contents of this buffer are identified by the /// BufferType member. /// </summary> public IntPtr pvBuffer; } } } }
using System; using UnityEngine; namespace RO { public class DebugFake : MonoBehaviour { private void Awake() { Object.DestroyImmediate(base.get_gameObject()); } } }
using Application.Interfaces.Services; using Domain.Common; using Domain.Entities; using Microsoft.EntityFrameworkCore; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Infrastructure.Persistence.Contexts { public class ApplicationDbContext : DbContext { private readonly IDateTimeService dateTime; private readonly IAuthenticatedUserService authenticatedUser; public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IDateTimeService dateTime, IAuthenticatedUserService authenticatedUser) : base(options) { this.dateTime = dateTime; this.authenticatedUser = authenticatedUser; } public DbSet<Product> Products { get; set; } public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()) { foreach (var entry in ChangeTracker.Entries<AuditableBaseEntity>()) { switch (entry.State) { case EntityState.Added: entry.Entity.Created = dateTime.NowUtc; entry.Entity.CreatedBy = authenticatedUser.UserId; break; case EntityState.Modified: entry.Entity.LastModified = dateTime.NowUtc; entry.Entity.LastModifiedBy = authenticatedUser.UserId; break; } } return base.SaveChangesAsync(cancellationToken); } protected override void OnModelCreating(ModelBuilder builder) { // All Decimals will have 18,6 Range foreach (var property in builder.Model.GetEntityTypes() .SelectMany(t => t.GetProperties()) .Where(p => p.ClrType == typeof(decimal) || p.ClrType == typeof(decimal?))) { property.SetColumnType("decimal(18,6)"); } base.OnModelCreating(builder); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; //[CreateAssetMenu(menuName = "Game Data/CardContainer")] [Serializable] public class CardContainer { public List<CardData> Cards; }
using System.Collections.Generic; namespace test1.Models { public class Institute { public int Id { get; set; } public string Name { get; set; } public List<Trainer> Trainers { get; set; } public List<Branch> Branchs { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Microsoft.EntityFrameworkCore; using Zillow.Core.Constant; using Zillow.Core.Dto; using Zillow.Core.Dto.CreateDto; using Zillow.Core.Dto.UpdateDto; using Zillow.Core.Enum; using Zillow.Core.Exceptions; using Zillow.Core.ViewModel; using Zillow.Data.Data; using Zillow.Data.DbEntity; using Zillow.Service.Services.FileServices; namespace Zillow.Service.Services.ContractServices { public class ContractService : IContractService { private readonly ApplicationDbContext _dbContext; private readonly IMapper _mapper; private readonly EntityNotFoundException _notFoundException; public ContractService(ApplicationDbContext dbContext, IMapper mapper) { _dbContext = dbContext; _mapper = mapper; _notFoundException = new EntityNotFoundException("Contract"); } public async Task<PagingViewModel> GetAll(int page, int pageSize) { var pagesCount = (int)Math.Ceiling(await _dbContext.Contract.CountAsync() / (double)pageSize); if (page > pagesCount || page < 1) page = 1; var skipVal = (page - 1) * pageSize; var contracts = await _dbContext.Contract .Include(x => x.Customer) .Include(x => x.RealEstate) .Skip(skipVal).Take(pageSize) .ToListAsync(); var contractsViewModel = _mapper.Map<List<ContractViewModel>>(contracts); return new PagingViewModel() { CurrentPage = page, PagesCount = pagesCount, Data = contractsViewModel }; } public async Task<ContractViewModel> Get(int id) { var contract = await _dbContext.Contract .Include(x => x.Customer) .Include(x => x.RealEstate) .SingleOrDefaultAsync(x => x.Id == id); if (contract == null) throw _notFoundException; return _mapper.Map<ContractViewModel>(contract); } public async Task<int> Create(CreateContractDto dto, string userId) { var createdContract = _mapper.Map<ContractDbEntity>(dto); createdContract.CreatedBy = userId; await _dbContext.Contract.AddAsync(createdContract); await _dbContext.SaveChangesAsync(); return createdContract.Id; } public async Task<int> Update(int id ,UpdateContractDto dto, string userId) { var oldContract = await _dbContext.Contract.SingleOrDefaultAsync(x => x.Id == id); if (oldContract == null) throw _notFoundException; if (id != dto.Id) throw new UpdateEntityException(ExceptionMessage.UpdateEntityIdError); var updatedContract = _mapper.Map(dto, oldContract); updatedContract.UpdatedAt = DateTime.Now; updatedContract.UpdatedBy = userId; _dbContext.Contract.Update(updatedContract); await _dbContext.SaveChangesAsync(); return updatedContract.Id; } public async Task<int> Delete(int id, string userId) { var deletedContract = await _dbContext.Contract.SingleOrDefaultAsync(x => x.Id == id); if (deletedContract == null) throw _notFoundException; deletedContract.UpdatedAt = DateTime.Now; deletedContract.UpdatedBy = userId; deletedContract.IsDelete = true; _dbContext.Contract.Update(deletedContract); await _dbContext.SaveChangesAsync(); return deletedContract.Id; } } }
using System; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using ChoosePairs; namespace ChoosePairsUnitTest { [TestClass] public class CPairSelectorUnitTest { [TestMethod] public void Select_CheckValues() { const Int32 X = 7; ICollection<Int32> testArray = new[] { 1, -3, 9, 10, 11, 12 }; var pairs = CPairSelector.Select(testArray, X); Assert.AreEqual<Int32>(1, pairs.Count()); var pair = pairs.ToArray()[0]; Assert.IsTrue((pair.Item1 == -3 && pair.Item2 == 10) || (pair.Item1 == 10 && pair.Item2 == -3)); } [TestMethod] public void Select_CheckCount() { const Int32 X = 98; ICollection<Int32> testArrayY = new[] { -23, 17, 121, 6, 9, 95, 96, 7, 2, 5, 3, 108, -10, 578, 56, -480 }; var pairs = CPairSelector.Select(testArrayY, X); Assert.AreEqual<Int32>(pairs.Count(), 5); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Select_CollectionIsNullException() { CPairSelector.Select(null, 0).Any(); } } }
using System; using System.Collections.Generic; namespace OCP.FullTextSearch.Model { /** * Interface ISearchRequest * * When a search request is initiated, from a request from the front-end or using * the IFullTextSearchManager::search() method, FullTextSearch will create a * SearchRequest object, based on this interface. * * The object will be passed to the targeted Content Provider so it can convert * search options using available method. * * The object is then encapsulated in a SearchResult and send to the * Search Platform. * * @since 15.0.0 * * * @package OCP\FullTextSearch\Model */ interface ISearchRequest { /** * Get the maximum number of results to be returns by the Search Platform. * * @since 15.0.0 * * @return int */ int getSize(); /** * Get the current page. * Used by pagination. * * @since 15.0.0 * * @return int */ int getPage(); /** * Get the author of the request. * * @since 15.0.0 * * @return string */ string getAuthor(); /** * Get the searched string. * * @since 15.0.0 * * @return string */ string getSearch(); /** * Get the value of an option (as string). * * @since 15.0.0 * * @param string option * @param string default * * @return string */ string getOption(string option, string @default = ""); /** * Get the value of an option (as array). * * @since 15.0.0 * * @param string option * @param array default * * @return array */ IList<string> getOptionArray(string option, IList<string> @default); /** * Limit the search to a part of the document. * * @since 15.0.0 * * @param string part * * @return ISearchRequest */ ISearchRequest addPart(string part) ; /** * Limit the search to an array of parts of the document. * * @since 15.0.0 * * @param array parts * * @return ISearchRequest */ ISearchRequest setParts(IList<string> parts) ; /** * Get the parts the search is limited to. * * @since 15.0.0 * * @return array */ IList<string> getParts(); /** * Limit the search to a specific meta tag. * * @since 15.0.0 * * @param string tag * * @return ISearchRequest */ ISearchRequest addMetaTag(string tag); /** * Get the meta tags the search is limited to. * * @since 15.0.0 * * @return array */ IList<string> getMetaTags(); /** * Limit the search to an array of meta tags. * * @since 15.0.0 * * @param array tags * * @return ISearchRequest */ ISearchRequest setMetaTags(IList<string> tags) ; /** * Limit the search to a specific sub tag. * * @since 15.0.0 * * @param string source * @param string tag * * @return ISearchRequest */ ISearchRequest addSubTag(string source, string tag); /** * Get the sub tags the search is limited to. * * @since 15.0.0 * * @param bool formatted * * @return array */ IList<string> getSubTags(bool formatted); /** * Limit the search to an array of sub tags. * * @since 15.0.0 * * @param array tags * * @return ISearchRequest */ ISearchRequest setSubTags(IList<string> tags) ; /** * Limit the search to a specific field of the mapping, using a full string. * * @since 15.0.0 * * @param string field * * @return ISearchRequest */ ISearchRequest addLimitField(string field) ; /** * Get the fields the search is limited to. * * @since 15.0.0 * * @return array */ IList<string> getLimitFields(); /** * Limit the search to a specific field of the mapping, using a wildcard on * the search string. * * @since 15.0.0 * * @param string field * * @return ISearchRequest */ ISearchRequest addWildcardField(string field); /** * Get the limit to field of the mapping. * * @since 15.0.0 * * @return array */ IList<string> getWildcardFields(); /** * Filter the results, based on a group of field, using regex * * @since 15.0.0 * * @param array filters * * @return ISearchRequest */ ISearchRequest addRegexFilters(IList<string> filters) ; /** * Get the regex filters the search is limit to. * * @since 15.0.0 * * @return array */ IList<string> getRegexFilters(); /** * Filter the results, based on a group of field, using wildcard * * @since 15.0.0 * * @param array filter * * @return ISearchRequest */ ISearchRequest addWildcardFilter(IList<string> filter); /** * Get the wildcard filters the search is limit to. * * @since 15.0.0 * * @return array */ IList<string> getWildcardFilters(); /** * Add an extra field to the search. * * @since 15.0.0 * * @param string field * * @return ISearchRequest */ ISearchRequest addField(string field); /** * Get the list of extra field to search into. * * @since 15.0.0 * * @return array */ IList<string> getFields(); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace fes.Models { public class FileFieldValue { [Key] public int ID { get; set; } [Required] public int FileID { get; set; } [Required] public int FieldID { get; set; } [Required] public string value { get; set; } [Required] public DateTime ts { get; set; } [Required] public RecordType recordType { get; set; } [Required] public int recordSequence { get; set; } } }
using System.Collections.Generic; namespace Contoso.Forms.View.Common { public class ValidationMessageView { public string Field { get; set; } public Dictionary<string, string> Methods { get; set; } } }
using NuGet.Protocol.Core.Types; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Client.V2Test { public class SearchV2Tests { //[Fact] //public async Task SearchV2_1000() //{ // var repo = RepositoryFactory.Create("http://api.nuget.org/v2/"); // var resource = repo.GetResource<SearchLatestResource>(); // var results = await resource.Search("json", new SearchFilter(), 0, 1000, CancellationToken.None); // var list = results.ToList(); // Assert.True(list.Count > 50); //} } }
using System; using System.Collections.Generic; using Microsoft.Data.Entity.Migrations; namespace Socialease.Migrations { public partial class PingsChanges : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_SocialUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_SocialUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_SocialUser_UserId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_Note_Ping_PingId", table: "Note"); migrationBuilder.DropForeignKey(name: "FK_Person_Ping_PingId", table: "Person"); migrationBuilder.DropForeignKey(name: "FK_Ping_PingType_TypeId", table: "Ping"); migrationBuilder.DropColumn(name: "Date", table: "Ping"); migrationBuilder.DropColumn(name: "TypeId", table: "Ping"); migrationBuilder.DropColumn(name: "PingId", table: "Person"); migrationBuilder.DropColumn(name: "PingId", table: "Note"); migrationBuilder.AddColumn<string>( name: "Description", table: "Ping", nullable: true); migrationBuilder.AddColumn<DateTime>( name: "Occurred", table: "Ping", nullable: false, defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); migrationBuilder.AddColumn<int>( name: "PersonId", table: "Ping", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<int>( name: "PingTypeId", table: "Ping", nullable: false, defaultValue: 0); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_SocialUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_SocialUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_SocialUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_SocialUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_SocialUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_SocialUser_UserId", table: "AspNetUserRoles"); migrationBuilder.DropColumn(name: "Description", table: "Ping"); migrationBuilder.DropColumn(name: "Occurred", table: "Ping"); migrationBuilder.DropColumn(name: "PersonId", table: "Ping"); migrationBuilder.DropColumn(name: "PingTypeId", table: "Ping"); migrationBuilder.AddColumn<DateTime>( name: "Date", table: "Ping", nullable: false, defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); migrationBuilder.AddColumn<int>( name: "TypeId", table: "Ping", nullable: true); migrationBuilder.AddColumn<int>( name: "PingId", table: "Person", nullable: true); migrationBuilder.AddColumn<int>( name: "PingId", table: "Note", nullable: true); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_SocialUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_SocialUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_SocialUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Note_Ping_PingId", table: "Note", column: "PingId", principalTable: "Ping", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Person_Ping_PingId", table: "Person", column: "PingId", principalTable: "Ping", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Ping_PingType_TypeId", table: "Ping", column: "TypeId", principalTable: "PingType", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } } }
using NUnit.Framework; namespace RomanNumeralsTests { [TestFixture] public class RomanNumeralsTests { private RomanNumerals.RomanNumerals _romanNumerals; [SetUp] public void Initialize() { _romanNumerals = new RomanNumerals.RomanNumerals(); } [TestCase(1, "I")] [TestCase(4, "IV")] [TestCase(5, "V")] [TestCase(9, "IX")] [TestCase(10, "X")] [TestCase(40, "XL")] [TestCase(50, "L")] [TestCase(90, "XC")] [TestCase(100, "C")] [TestCase(400, "CD")] [TestCase(500, "D")] [TestCase(900, "CM")] [TestCase(1000, "M")] [TestCase(4000, "MV")] [TestCase(5000, "V")] public void ShouldConvertPivotalValuesCorrectly(int decimalNumber, string expectedRomanNumeral) { var result = _romanNumerals.Convert(decimalNumber); Assert.That(result, Is.EqualTo(expectedRomanNumeral)); } [TestCase(124, "CXXIV")] public void ShouldConverNonPivotalValuesCorrectlty(int decimalNumber, string expectedRomanNumeral) { var result = _romanNumerals.Convert(decimalNumber); Assert.That(result, Is.EqualTo(expectedRomanNumeral)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Diagnostics; using ICSharpCode.SharpZipLib.Zip; namespace SL.Util { public class ZipUtil { public static void Decompress(string GzipFile, string targetPath) { //string directoryName = Path.GetDirectoryName(targetPath + "\\") + "\\"; string directoryName = targetPath; if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);//生成解压目录 string CurrentDirectory = directoryName; byte[] data = new byte[2048]; int size = 2048; ZipEntry theEntry = null; using (ZipInputStream s = new ZipInputStream(File.OpenRead(GzipFile))) { while ((theEntry = s.GetNextEntry()) != null) { if (theEntry.IsDirectory) {// 该结点是目录 if (!Directory.Exists(CurrentDirectory + theEntry.Name)) Directory.CreateDirectory(CurrentDirectory + theEntry.Name); } else { if (theEntry.Name != String.Empty) { //解压文件到指定的目录 using (FileStream streamWriter = File.Create(CurrentDirectory + theEntry.Name)) { while (true) { size = s.Read(data, 0, data.Length); if (size <= 0) break; streamWriter.Write(data, 0, size); } streamWriter.Close(); } } } } s.Close(); } } } }
using Domain; using Microsoft.EntityFrameworkCore; using System; namespace DAL { public class UserContext : DbContext { public DbSet<User> Users { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseCosmos( Environment.GetEnvironmentVariable("ACCOUNT"), Environment.GetEnvironmentVariable("ACCOUNT_KEY"), databaseName: "Houses"); protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<User>(e => { e.ToContainer("UserContainer"); e.HasKey(u => u.id); e.HasNoDiscriminator(); e.HasPartitionKey(u => u.ZipCode); e.UseETagConcurrency(); } ); } } }
/* * Author: Jason D. Jimenez * Date : 5/30/2004 * Time : 9:10 AM */ using System; using System.Collections.Generic; using JasonJimenez.ClassicReport.Common; using JasonJimenez.ClassicReport.Common.Widgets; namespace JasonJimenez.ClassicReport { class ClassicReportPage : IPage { ClassicReportDocument _document; List<ClassicReportPageItem> _items; int _rowIndex; int _pageIndex; bool _hasFooter = false; public ClassicReportPage(ClassicReportDocument document) { _items = new List<ClassicReportPageItem>(); _document = document; _pageIndex = document.Count; _rowIndex = 0; } ~ClassicReportPage() { _items.Clear(); _items = null; } public bool hasFooter { get { return _hasFooter; } set { _hasFooter = value; } } public ClassicReportDocument Document { get { return _document; } } public ClassicReportPageItem this[int index] { get { return _items[index]; } } public int CurrentRow { get { return _rowIndex; } } public int PageNo { get { return _pageIndex+1; } } public void Write(BaseWidget widget,int col) { ClassicReportPageItem item = new ClassicReportPageItem(this); item.IsBold = widget.IsBold; item.IsItalic = widget.IsItalic; item.IsUnderline = widget.IsUnderline; item.Col= col; item.Text = widget.Value; _items.Add(item); } public void Write(BaseWidget widget, int col, AlignmentEnum align) { ClassicReportPageItem item = new ClassicReportPageItem(this); item.IsBold = widget.IsBold; item.IsItalic = widget.IsItalic; item.IsUnderline = widget.IsUnderline; item.Align = align; item.Col= col; item.Text = widget.Value; _items.Add(item); } public void Write(BaseWidget widget, JustifyEnum justify) { ClassicReportPageItem item = new ClassicReportPageItem(this); item.IsBold = widget.IsBold; item.IsItalic = widget.IsItalic; item.IsUnderline = widget.IsUnderline; item.Justify = justify; item.Text = widget.Value; _items.Add(item); } public void WriteLine() { _rowIndex++; } public IEnumerable<ClassicReportPageItem> GetItems(int row) { List<ClassicReportPageItem> items = _items.FindAll( delegate(ClassicReportPageItem pi) { return pi.Row == row; }); items.Sort( delegate(ClassicReportPageItem x, ClassicReportPageItem y) { return x.Offset - y.Offset; }); foreach (ClassicReportPageItem item in items) { item.Parse(this); yield return item; } } public string ToString(int row) { StringBuffer buffer = new StringBuffer(); foreach(ClassicReportPageItem item in GetItems(row)) { buffer.Insert(item); } return buffer.ToString(); } public override string ToString() { string sb = ""; StringBuffer buffer = new StringBuffer(); for (int i=0; i<_document.PageHeight; i++) { buffer.Clear(); foreach (ClassicReportPageItem item in GetItems(i)) { buffer.Insert(item); } sb += buffer.ToString(); //sb += string.Format("*** LINE {0:00}", i); if (i < _document.PageHeight - 1) sb += "\n"; } return sb; // return the page contents as a string } } class StringBuffer { char[] _buffer; int _size; public StringBuffer() { _size=512; _buffer=new char[_size]; this.Clear(); } public StringBuffer(int size) { _buffer = new char[size]; _size = size; this.Clear(); } public void Clear() { for (int i=0; i<_size; i++) _buffer[i] = ' '; } public void Insert(ClassicReportPageItem item) { CopyString(item.Value,item.Offset); } public override string ToString() { string s = ""; for (int i=0; i<_size; ++i) s += _buffer[i]; string sb = s.TrimEnd(' '); return sb; } private void CopyString(string src,int offset) { for(int i=0; i<src.Length; i++) _buffer[i+offset] = src[i]; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace Pointof { public partial class UserForm : Form { public UserForm() { InitializeComponent(); } private void btnclose_Click(object sender, EventArgs e) { this.Dispose(); } /* * Data Source=(LocalDB)\v11.0;AttachDbFilename="C:\Users\User\Documents\Visual Studio 2013\Projects\Pointofsale\Pointof\POS_db.mdf";Integrated Security=True * Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Temp.SFC\Documents\Visual Studio 2013\Projects\Pointofsale\Pointof\POS_db.mdf;Integrated Security=True * * private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { string sId; string fName; string gName; DataGridViewRow selectRow = dataGridView1.Rows[e.RowIndex]; sId = selectRow.Cells[0].Value.ToString(); fName = selectRow.Cells[1].Value.ToString(); gName = selectRow.Cells[2].Value.ToString(); } private void btnUpdate_click(object sender, EventArgs e) { int studentIdValue = int.Parse(txtID.Text); string fName = txtFamily.Text; string gName = txtGiven.Text; string conString; conString = Properties.Settings.Default.SDB; SqlConnection con = new SqlConnection(conString); con.Open(); SqlCommand cmd = new SqlCommand("UpdateStudentsTable", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@sID", studentIdValue)); cmd.Parameters.Add(new SqlParameter("@Fam", fName)); cmd.Parameters.Add(new SqlParameter("@Giv", gName)); cmd.ExecuteNonQuery(); MessageBox.Show("Updated:"); con.Close(); }*/ } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DiaxeirisiPoiotitas { class Pelatis: Synergatis { private String id; private String name; private String phoneNumber; private String fax; private String email; private String country; private String city; private String address; private String tk; private String inCharge; private string comments; public Pelatis(String id, String name) { this.id = id; this.name = name; } public string Id { get { return id; } set { id = value; } } public string Name1 { get { return name; } set { name = value; } } public string PhoneNumber { get { return phoneNumber; } set { phoneNumber = value; } } public string Fax { get { return fax; } set { fax = value; } } public string Email { get { return email; } set { email = value; } } public string Country { get { return country; } set { country = value; } } public string City { get { return city; } set { city = value; } } public string Address { get { return address; } set { address = value; } } public string Tk { get { return tk; } set { tk = value; } } public string InCharge { get { return inCharge; } set { inCharge = value; } } public string Comments { get { return comments; } set { comments = value; } } } }
using DataAccessLayer.Map; using Entity; using System.Data.Entity; namespace DataAccessLayer { public class DatabaseContext:DbContext { public DatabaseContext() : base("DefaultDb") { } internal DbSet<User> User { get; set; } internal DbSet<Exam> Exam { get; set; } internal DbSet<Question> Question { get; set; } internal DbSet<Answer> Answer { get; set; } internal DbSet<Article> Article { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new UserMap()); modelBuilder.Configurations.Add(new ExamMap()); modelBuilder.Configurations.Add(new ArticleMap()); modelBuilder.Configurations.Add(new AnswerMap()); modelBuilder.Configurations.Add(new QuestionMap()); base.OnModelCreating(modelBuilder); } } }
// Copyright 2019 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using NtApiDotNet; using System; using System.Management.Automation; namespace NtObjectManager.Cmdlets.Object { /// <summary> /// <para type="synopsis">Creates a new NT transaction object.</para> /// <para type="description">This cmdlet creates a new NT transaction object.</para> /// </summary> /// <example> /// <code>$obj = New-NtTransaction \BaseNamedObjects\ABC</code> /// <para>Create a transaction object with an absolute path.</para> /// </example> /// <example> /// <code>$obj = New-NtTransaction \BaseNamedObjects\ABC -PreferredNode 2</code> /// <para>Create a transaction object with an absolute path and preferred node 2.</para> /// </example> /// <example> /// <code>$root = Get-NtDirectory \BaseNamedObjects&#x0A;$obj = New-NtTransaction ABC -Root $root</code> /// <para>Create a transaction object with a relative path. /// </para> /// </example> /// <example> /// <code>cd NtObject:\BaseNamedObjects&#x0A;$obj = New-NtTransaction ABC</code> /// <para>Create a transaction object with a relative path based on the current location. /// </para> /// </example> /// <para type="link">about_ManagingNtObjectLifetime</para> [Cmdlet(VerbsCommon.New, "NtTransaction")] [OutputType(typeof(NtTransaction))] public sealed class NewNtTransactionCmdlet : NtObjectBaseCmdletWithAccess<TransactionAccessRights> { /// <summary> /// <para type="description">Specify an optional Unit of Work GUID.</para> /// </summary> [Parameter] public Guid? UnitOfWork { get; set; } /// <summary> /// <para type="description">Specify an optional Transaction Manager.</para> /// </summary> [Parameter] public NtTransactionManager TransactionManager { get; set; } /// <summary> /// <para type="description">Specify flags for transaction creation.</para> /// </summary> [Parameter] public TransactionCreateFlags CreateFlags { get; set; } /// <summary> /// <para type="description">Specify an optional isolation level.</para> /// </summary> [Parameter] public int IsolationLevel { get; set; } /// <summary> /// <para type="description">Specify isolation falgs.</para> /// </summary> [Parameter] public TransactionIsolationFlags IsolationFlags { get; set; } /// <summary> /// <para type="description">Specify timeout in milliseconds (0 is Infinite).</para> /// </summary> [Parameter] public NtWaitTimeout Timeout { get; set; } /// <summary> /// <para type="description">Specify an optional description.</para> /// </summary> [Parameter] public string Description { get; set; } /// <summary> /// Determine if the cmdlet can create objects. /// </summary> /// <returns>True if objects can be created.</returns> protected override bool CanCreateDirectories() { return true; } /// <summary> /// Method to create an object from a set of object attributes. /// </summary> /// <param name="obj_attributes">The object attributes to create/open from.</param> /// <returns>The newly created object.</returns> protected override object CreateObject(ObjectAttributes obj_attributes) { return NtTransaction.Create(obj_attributes, Access, UnitOfWork, TransactionManager, CreateFlags, IsolationLevel, IsolationFlags, Timeout, Description); } } }
using System; using System.Collections.Generic; namespace Sesi.WebsiteDaSaude.WebApi.Models { public partial class Bairros { public Bairros() { Locais = new HashSet<Locais>(); Usuarios = new HashSet<Usuarios>(); } public int IdBairro { get; set; } public string NomeBairro { get; set; } public virtual ICollection<Locais> Locais { get; set; } public virtual ICollection<Usuarios> Usuarios { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MusicBoxController : MonoBehaviour { AudioSource audioSrc; void Start() { audioSrc = GetComponent<AudioSource>(); } IEnumerator FadeOut(float delay) { audioSrc.volume = 1f; while (audioSrc.volume > 0) { audioSrc.volume -= Time.deltaTime / delay; yield return null; } } IEnumerator FadeIn(float delay) { audioSrc.volume = 0f; if (!audioSrc.isPlaying) { audioSrc.Play(); } while (audioSrc.volume < 1) { audioSrc.volume += Time.deltaTime / delay; yield return null; } } void OnTriggerEnter2D (Collider2D coll) { StartCoroutine(FadeIn(2f)); } void OnTriggerExit2D (Collider2D coll) { StartCoroutine(FadeOut(2f)); } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; namespace ProjectLauncher { public class BoolToEnumConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null && value.GetType().IsEnum) { return object.Equals(value, parameter); } return DependencyProperty.UnsetValue; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (value is bool && (bool)value) { return parameter; } return DependencyProperty.UnsetValue; } } }
using System; using System.Globalization; namespace ObjectPrinting { public static class PropertyPrintingConfigExtensions { public static string PrintToString<T>(this T obj, Func<PrintingConfig<T>, PrintingConfig<T>> config) => config(ObjectPrinter.For<T>()) .PrintToString(obj); public static PrintingConfig<TOwner> TrimmedToLength<TOwner>( this PropertyPrintingConfig<TOwner, string> config, int maxLen) => config.Using(s => s.Substring(0, Math.Min(maxLen, s.Length))); public static PrintingConfig<TOwner> Using<TOwner, T>( this PropertyPrintingConfig<TOwner, T> config, CultureInfo culture) where T : IFormattable => config.Using(i => i.ToString("", culture)); } }