text
stringlengths
13
6.01M
using System; namespace WinAppUpdater.Core { /// <summary> /// Different kind of URL type. /// </summary> public enum URLType { Local } }
using Microsoft.AppCenter.Crashes; using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Reflection; using System.Runtime.Serialization; using Xamarin.Forms; namespace TimeLogger.Helpers { [Serializable] public sealed class RestClientException : Exception, ISerializable { [NonSerialized] private readonly HttpStatusCode statusCode; [NonSerialized] private readonly string responseBody; public RestClientException(string message) : base(message) { Device.BeginInvokeOnMainThread(() => { Debug.WriteLine($"Serialization error {message}"); //DependencyService.Get<IToastService>().ShortAlert("Serialization error"); }); } public RestClientException(string message, Exception innerException) : base(message, innerException) { Device.BeginInvokeOnMainThread(() => { Debug.WriteLine($"RequestAsync Failed : {message}"); Crashes.TrackError(innerException, new Dictionary<string, string> { { "Class Name : ", GetType().Name }, { "Method Name : ", MethodBase.GetCurrentMethod().Name } }); //DependencyService.Get<IToastService>().ShortAlert($"API error : {innerException.Message}"); }); } public RestClientException(Exception innerException) : base(innerException.Message, innerException) { Debug.WriteLine($"API error {innerException.Message}"); } public RestClientException(HttpStatusCode statusCode, string responseBody) : base($"Request responded with status code={statusCode}, response={responseBody}") { this.statusCode = statusCode; this.responseBody = responseBody; if (statusCode == HttpStatusCode.Unauthorized || responseBody.Contains("Provided token is expired")) { // Force Logout Device.BeginInvokeOnMainThread(() => { //Settings.ClearAllData(); //Task.Delay(100); //App.Current.MainPage = new NavigationPage(new LoginPage()); //Task.Delay(1500); //DependencyService.Get<IToastService>().ShortAlert("Session Expires: Please login"); //SecureStorage.Remove("oauth_token"); }); } } private RestClientException(SerializationInfo info, StreamingContext context) : base(info, context) { Debug.WriteLine("Serialization error"); } } }
using System; using System.Linq; using System.Runtime.InteropServices; using Unity.Mathematics; using UnityEngine; using UnityTools; using UnityTools.Common; using UnityTools.ComputeShaderTool; using UnityTools.Debuging; using UnityTools.Rendering; namespace GPUTrail { [StructLayout(LayoutKind.Sequential)] public class TrailSource { public float3 pos; } public interface ITrailSource<T> where T : TrailSource { GPUBufferVariable<T> Buffer { get; } } public class GPUTrailController<T> : MonoBehaviour, IInitialize, IDataBuffer<TrailNode> where T : TrailSource { public enum Kernel { InitHeader, InitNode, EmitTrail, UpdateSourceBuffer, UpdateFromSourceBuffer, AppendDeadToNodePool, } [System.Serializable] public class GPUTrailData : GPUContainer { [Shader(Name = "_TrailHeaderBuffer")] public GPUBufferVariable<TrailHeader> trailHeaderBuffer = new GPUBufferVariable<TrailHeader>(); [Shader(Name = "_TrailHeaderIndexBufferAppend")] public GPUBufferAppendConsume<int> trailHeaderIndexBufferAppend = new GPUBufferAppendConsume<int>(); [Shader(Name = "_TrailHeaderIndexBufferConsume")] public GPUBufferAppendConsume<int> trailHeaderIndexBufferConsume = new GPUBufferAppendConsume<int>(); [Shader(Name = "_TrailNodeBuffer")] public GPUBufferVariable<TrailNode> trailNodeBuffer = new GPUBufferVariable<TrailNode>(); [Shader(Name = "_TrailNodeIndexBufferAppend")] public GPUBufferAppendConsume<int> trailNodeIndexBufferAppend = new GPUBufferAppendConsume<int>(); [Shader(Name = "_TrailNodeIndexBufferConsume")] public GPUBufferAppendConsume<int> trailNodeIndexBufferConsume = new GPUBufferAppendConsume<int>(); [Shader(Name = "_TrailNodeIndexDeadBufferAppend")] public GPUBufferAppendConsume<int> trailNodeIndexDeadBufferAppend = new GPUBufferAppendConsume<int>(); [Shader(Name = "_TrailNodeIndexDeadBufferConsume")] public GPUBufferAppendConsume<int> trailNodeIndexDeadBufferConsume = new GPUBufferAppendConsume<int>(); //optional local buffer: sometimes a local copy of source buffer is necessary [Shader(Name = "_SourceBuffer")] public GPUBufferVariable<T> sourceBuffer = new GPUBufferVariable<T>(); [Shader(Name = "_EmitTrailNum")] public int emitTrailNum = 2048; [Shader(Name = "_EmitTrailLen")] public int emitTrailLen = 128; } public bool Inited => this.inited; public GPUBufferVariable<TrailNode> Buffer => this.trailData.trailNodeBuffer; public ISpace Space => this.Configure.D.space; [SerializeField] protected ComputeShader trailCS; [SerializeField] protected GPUTrailData trailData = new GPUTrailData(); protected GPUTrailConfigure Configure => this.configure ??= this.gameObject.FindOrAddTypeInComponentsAndChildren<GPUTrailConfigure>(); protected GPUTrailConfigure configure; protected bool inited = false; protected ComputeShaderDispatcher<Kernel> dispatcher; protected ITrailSource<T> source; public void Init() { this.source = ObjectTool.FindAllObject<ITrailSource<T>>().FirstOrDefault(); LogTool.AssertNotNull(this.source); this.Configure.Initialize(); var headNum = this.Configure.D.trailHeaderNum; var nodeNum = this.Configure.D.trailNodeNum; this.trailData.trailHeaderBuffer.InitBuffer(headNum); this.trailData.trailHeaderIndexBufferAppend.InitAppendBuffer(headNum); this.trailData.trailHeaderIndexBufferConsume.InitAppendBuffer(this.trailData.trailHeaderIndexBufferAppend); this.trailData.trailNodeBuffer.InitBuffer(nodeNum); this.trailData.trailNodeIndexBufferAppend.InitAppendBuffer(nodeNum); this.trailData.trailNodeIndexBufferConsume.InitAppendBuffer(this.trailData.trailNodeIndexBufferAppend); this.trailData.trailNodeIndexDeadBufferAppend.InitAppendBuffer(nodeNum); this.trailData.trailNodeIndexDeadBufferConsume.InitAppendBuffer(this.trailData.trailNodeIndexDeadBufferAppend); this.dispatcher = new ComputeShaderDispatcher<Kernel>(this.trailCS); foreach (Kernel k in Enum.GetValues(typeof(Kernel))) { this.dispatcher.AddParameter(k, this.Configure.D); this.dispatcher.AddParameter(k, this.trailData); this.dispatcher.AddParameter(k, this.source.Buffer); } this.dispatcher.Dispatch(Kernel.InitHeader, headNum); this.dispatcher.Dispatch(Kernel.InitNode, nodeNum); LogTool.AssertIsTrue(this.trailData.emitTrailLen > 0); this.dispatcher.Dispatch(Kernel.EmitTrail, this.trailData.emitTrailNum); this.inited = true; } public void Deinit() { this.trailData?.Release(); } protected void Update() { if (this.trailData.sourceBuffer.Size != this.source.Buffer.Size) { //Update trail buffer after source buffer created this.trailData.sourceBuffer.InitBuffer(this.source.Buffer.Size); } var headerNum = this.Configure.D.trailHeaderNum; var pNum = this.source.Buffer.Size; this.dispatcher.Dispatch(Kernel.UpdateSourceBuffer, pNum); this.trailData.trailNodeIndexDeadBufferAppend.ResetCounter(); this.dispatcher.Dispatch(Kernel.UpdateFromSourceBuffer, headerNum); var counter = this.trailData.trailNodeIndexDeadBufferAppend.GetCounter(); if (counter > 0) { this.dispatcher.Dispatch(Kernel.AppendDeadToNodePool, counter); } } protected void OnEnable() { if (!this.Inited) this.Init(); } protected void OnDisable() { this.Deinit(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProyectoLP2 { public class Administrador : Persona { private double salario; public Administrador() { } public Administrador(double salario, string nombre, string apellido, int edad, char sexo, string dni, string direccion, int telefono, string email, int estado, DateTime fecha_ingreso, string IDUsuario, string password, string respuestaConfimacion,int tipo) : base(nombre, apellido, edad, sexo, dni, direccion, telefono, email, estado, fecha_ingreso, IDUsuario, password, respuestaConfimacion,tipo) { this.Salario = salario; } public double Salario { get => salario; set => salario = value; } public string getDatos() { return "Salario: " + Salario.ToString(); } } }
using UnityEngine; using System.Collections; public class GreenState : ISlutState { private readonly StatePatternSlut slut; public GreenState(StatePatternSlut statePatternSlut) { slut = statePatternSlut; } public void UpdateState () { WaitForInput(); } public void ToGreenState() { Debug.Log("cannot transition to same state"); } public void ToYellowState() { slut.currentState = slut.yellowState; } public void ToRedState() { slut.currentState = slut.redState; } private void WaitForInput() { Rest(); EventManager.TriggerEvent("greenIdle"); slut.slutStats.pain -= Time.deltaTime * slut.slutStats.painDecay; if(slut.slutStats.pain > slut.painThresholdYellow) { //play "owch" animation and sound ToYellowState(); } else if(slut.slutStats.pain > slut.painThresholdRed) { ToRedState(); } if (slut.slutStats.arousal > slut.slutStats.arousalThreshold && slut.slutStats.pain < slut.painThresholdYellow) { Orgasm(); } } void Orgasm() { Debug.Log("Orgasm"); EventManager.TriggerEvent("cumming"); } void Rest() { //slut.painCurCooldown += Time.deltaTime; if (slut.slutStats.exhaustion > 0) { slut.slutStats.exhaustion -= Time.deltaTime ; } if(slut.slutStats.exhaustion <= 0) { slut.slutStats.exhaustion = 0; } } void AddExhaustion() { slut.slutStats.exhaustion += 1; } }
using System; using Umbraco.Core.Dashboards; namespace Uintra.App_Plugins.Utils.Сache { public class CacheDashboard : IDashboard { public string Alias => "Cache"; public string[] Sections => new[] { "settings" }; public string View => "/App_Plugins/Utils/Сache/View/developer-cache.html"; public IAccessRule[] AccessRules => Array.Empty<IAccessRule>(); } }
using System; using System.Runtime.InteropServices; namespace Vlc.DotNet.Core.Interops.Signatures { /// <summary> /// Get current fullscreen status. /// </summary> [LibVlcFunction("libvlc_get_fullscreen")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int GetFullScreen(IntPtr mediaPlayerInstance); }
 using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace Ejercicio1 { /// <summary> /// Description of MainForm. /// </summary> public partial class MainForm : Form { public MainForm() { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); // // TODO: Add constructor code after the InitializeComponent() call. // } void SalirToolStripMenuItemClick(object sender, System.EventArgs e) { this.Close(); } void AbrirCarpetaToolStripMenuItemClick(object sender, EventArgs e) { if(folderBrowserDialog1.ShowDialog()==DialogResult.OK){ dir=new System.IO.DirectoryInfo(folderBrowserDialog1.SelectedPath); listBox1.Items.Clear(); listBox1.Items.AddRange(dir.GetFiles("*.ico")); listBox1.Items.AddRange(dir.GetFiles("*.jpeg")); listBox1.Items.AddRange(dir.GetFiles("*.jpg")); listBox1.Items.AddRange(dir.GetFiles("*.bmp")); listBox1.Items.AddRange(dir.GetFiles("*.bmp")); if(listBox1.Items.Count>0){ listBox1.SelectedIndex=0; } } } private System.IO.DirectoryInfo dir; void MainFormLoad(object sender, EventArgs e) { toolStripStatusLabel1.Text=System.IO.Directory.GetCurrentDirectory(); toolStripComboBox1.SelectedIndex=0; } void ListBox1SelectedIndexChanged(object sender, EventArgs e) { toolStripStatusLabel1.Text=dir.FullName+"\\"+listBox1.SelectedItem.ToString(); pictureBox1.Image=Image.FromFile(toolStripStatusLabel1.Text); if(!presentacionToolStripMenuItem.Enabled)presentacionToolStripMenuItem.Enabled=true; } void AjustarALaVentanaToolStripMenuItemCheckedChanged(object sender, EventArgs e) { if(ajustarALaVentanaToolStripMenuItem.Checked){ pictureBox1.Dock=DockStyle.Fill; pictureBox1.SizeMode=PictureBoxSizeMode.Zoom; }else{ pictureBox1.Dock=DockStyle.None; pictureBox1.SizeMode= PictureBoxSizeMode.AutoSize; } } void VerListaDeImagenesToolStripMenuItemCheckedChanged(object sender, EventArgs e) { if(verListaDeImagenesToolStripMenuItem.Checked){ splitContainer1.Panel1Collapsed=false; }else{ splitContainer1.Panel1Collapsed=true; } } void PresentacionToolStripMenuItemClick(object sender, EventArgs e) { Maximizado m=new Maximizado(); string[] lista=new string[listBox1.Items.Count]; int i=0; foreach(System.IO.FileInfo f in listBox1.Items){ lista[i]=f.FullName; i++; } m.LoadInfoPictures(lista,(toolStripComboBox1.SelectedIndex+1)*2000); m.ShowDialog(); } } }
using AW.Sca.Data.Domain; using Microsoft.EntityFrameworkCore; using System; using System.Linq; using System.Reflection; namespace Aw.Sca.Data.Extensions { public static class ModelBuilderExtensions { public static void SetSoftDeletableAllEntities(this ModelBuilder modelBuilder) { foreach (var type in modelBuilder.Model.GetEntityTypes() .Select(t => t.ClrType) .Where(t => typeof(ISoftDeletable).IsAssignableFrom(t))) { modelBuilder.SetSoftDeleteFilter(type); } } static void SetSoftDeleteFilter(this ModelBuilder modelBuilder, Type entityType) { SetSoftDeleteFilterMethod.MakeGenericMethod(entityType) .Invoke(null, new object[] { modelBuilder }); } static readonly MethodInfo SetSoftDeleteFilterMethod = typeof(ModelBuilderExtensions) .GetMethods(BindingFlags.Public | BindingFlags.Static) .Single(t => t.IsGenericMethod && t.Name == "SetSoftDeleteFilter"); public static void SetSoftDeleteFilter<TEntity>(this ModelBuilder modelBuilder) where TEntity : class, ISoftDeletable { modelBuilder.Entity<TEntity>().HasQueryFilter(x => !x.IsDeleted); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class WebCam : MonoBehaviour { public int redThreshold = 10000; public int greenThreshold = 20000; public int blueThreshold = 150000; public int reds = 0; public int greens = 0; public int blues = 0; public bool renderCam = true; private WebCamTexture webCamTexture; private PacketCollector packetCollector; public bool oldCountRedMethod = false; void Start() { webCamTexture = new WebCamTexture(); packetCollector = FindObjectOfType<PacketCollector>(); if (renderCam) GetComponent<Renderer>().material.mainTexture = webCamTexture; else Destroy(GetComponent<Renderer>()); webCamTexture.Play(); } void Update() { Color[] pixels = webCamTexture.GetPixels(); reds = 0; greens = 0; blues = 0; for (int i = 0; i < pixels.Length; ++i) { if (oldCountRedMethod) if (pixels[i].r > pixels[i].g + pixels[i].b) ++reds; if (!oldCountRedMethod) if (pixels[i].r > pixels[i].g && pixels[i].r > pixels[i].b) ++reds; if (pixels[i].g > pixels[i].r && pixels[i].g > pixels[i].b) ++greens; if (pixels[i].b > pixels[i].r && pixels[i].b > pixels[i].g) ++blues; } if (greens > greenThreshold) packetCollector.CollectMode(); else if (reds > redThreshold) packetCollector.DestroyMode(); //else if (blues > blueThreshold) //packetCollector.GoIntoBlue(); else packetCollector.TurnOff(); } }
using System; using Tomelt.Caching; using Tomelt.Events; namespace Tomelt.DisplayManagement.Descriptors { public interface IShapeTableManager : ISingletonDependency { ShapeTable GetShapeTable(string themeName); } public interface IShapeTableProvider : IDependency { void Discover(ShapeTableBuilder builder); } public interface IShapeTableEventHandler : IEventHandler { void ShapeTableCreated(ShapeTable shapeTable); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AbilityObject : MonoBehaviour { [SerializeField] private Ability ability; public Ability Ability { get { return ability; } set { ability = value; } } public void OnCollisionEnter(Collision other) { if (other.gameObject.layer == LayerMask.NameToLayer("Player")) Destroy(gameObject); } public void OnTriggerEnter(Collider other) { if (other.gameObject.layer == LayerMask.NameToLayer("Player")) Destroy(gameObject); } private void Update() { if (transform.position.y < 0.5) { transform.position = new Vector3(transform.position.x, 0.5f, transform.position.z); } } }
using System; using WorldPayDotNet.Common; namespace WorldPayDotNet.Hosted { public interface IHostedPaymentProcessor { void SubmitTransaction(HostedTransactionRequest request, string MD5secretKey); } }
using System.Collections; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine; public class PlayerSelection : MonoBehaviour { [SerializeField] private PlayerSelect _playerSelect; public PlayerSelect PlayerSelect { get { return _playerSelect; } set {_playerSelect = value;} } [SerializeField] private Text _SelectText; void Update () { _SelectText.text = PlayerSelect.ToString(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgorithmProblems.Dynamic_Programming { /// <summary> /// Also known as the typesetting problem used in text editors like ms word , latex, etc /// We are given a page with a length of one line as M /// and we will be given a list of words to fit on that line, we need to fit all the /// given words in the page with minimum space between the words and the margin. /// /// Note: for simplicity you dont have to worry about breaking the words and can assume that /// all the words are less than the length of line on the page. /// /// </summary> public class WordWrapping { /// <summary> /// We can solve this problem using dynamic programming /// Lets get the formulae for the dynamic programming approach /// /// Assuming kth word is the (first word of the last line) /// lowestSlack[n] - means the lowest slack when we have all words from 0 to n on the page /// slack[k,n] - means the extra spaces in line where the first word is words[k] and the last word is words[n]\ /// we will square the penalty so that no one line has a lot of spaces, we need to distribute the extra spaces /// /// lowestSlack[n] = min {lowestSlack[k-1] + (slack[k,n])^2} /// k = 1->n /// /// We will have to precompute slack matrix /// slack[i,j] = maxLengthOfLineOnPage - Sum(words[k].Length) + (j-i) only when this value is greater or equal to zero /// k:i->j /// INT_MAX , otherwise /// /// the above calculation of slack also has overlapping subproblems /// slack[i,j] = slack[i,j-1] - words[j].Length - 1; /// </summary> /// <param name="words">array of all the words that can be fitted on the line</param> /// <param name="maxLengthOfLineOnPage">length of the line on the page</param> /// <returns></returns> public List<string> GetTypeSettedLines(string[] words, int maxLengthOfLineOnPage) { List<string> lines = new List<string>(); int[,] slack = new int[words.Length, words.Length]; int[] lowestSlack = new int[words.Length]; int[] backtrack = new int[words.Length]; // Populate the slack matrix for (int i= 0; i<words.Length; i++) { for (int j = i; j < words.Length; j++) { if (i == j) { // we have only one word (words[j]) on the line and the assumption is // we dont have anywords greater than maxLengthOfLineOnPage slack[i, j] = maxLengthOfLineOnPage - words[j].Length; } else { if (slack[i, j - 1] != int.MaxValue) { int slackVal = slack[i, j - 1] - words[j].Length - 1; slack[i, j] = (slackVal < 0) ? int.MaxValue : slackVal; } else { slack[i, j] = int.MaxValue; } } } } lowestSlack[0] = slack[0,0]; for (int i =1; i<words.Length; i++) { lowestSlack[i] = int.MaxValue; int minSlack = int.MaxValue; for(int k=0; k<= i;k++) { if (slack[k,i] != int.MaxValue && k - 1 >= 0 && lowestSlack[k-1] != int.MaxValue ) { minSlack = lowestSlack[k-1] + (int)Math.Pow(slack[k,i], 2); } if(minSlack < lowestSlack[i]) { lowestSlack[i] = minSlack; backtrack[i] = k; } } } Console.WriteLine("The minimimum slack for printing the words is {0}", lowestSlack[words.Length - 1]); //Back track and get the listofStrings int index = words.Length - 1; while(index>=0) { lines.Add(GetStringOnLine(words, backtrack[index], index)); index = backtrack[index] - 1; } lines.Reverse(); return lines; } private string GetStringOnLine(string[] allWords, int firstWordIndex, int lastWordIndex) { StringBuilder sb = new StringBuilder(); for(int index = firstWordIndex; index<=lastWordIndex; index++) { sb.Append(allWords[index]); if (index !=lastWordIndex) { sb.Append(" "); } } return sb.ToString(); } public static void TestWordWrapping() { WordWrapping ww = new WordWrapping(); string[] words = new string[] { "it", "was", "the", "best", "of", "times", "and", "it", "was", "the", "worst", "of", "times." }; PrintAllLines(ww.GetTypeSettedLines(words, 10)); words = new string[] { "perseverence","it", "was", "the", "best", "of", "times", "and", "it", "was", "the", "worst", "of", "times.", "It", "was", "the", "time", "of", "great", "prosperity", "for", "some", "and", "crazy", "time", "for", "many", "others.", "Some", "people", "were", "persecuted", "and", "some", "were", "not."}; PrintAllLines(ww.GetTypeSettedLines(words, 15)); } private static void PrintAllLines(List<string> allLines) { foreach(string line in allLines) { Console.WriteLine(line); } } } }
using System; using System.Collections.Generic; using System.Text; namespace DomainModels.SharedModels { public class OrderView { public string Email { get; set; } public int ProdId { get; set; } public int Quantity { get; set; } public DateTime OrderDate { get; set; } public string Address { get; set; } public int PinCode { get; set; } public string State { get; set; } public string Landmark { get; set; } public string City { get; set; } public int Price { get; set; } public int TotalPrice { get; set; } } }
using jaytwo.Common.Http; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace jaytwo.Common.Test.Http.UrlHelperTests { public static class AddQueryStringParameterTests { private static IEnumerable<TestCaseData> UrlHelper_AddUriQueryStringParameter_TestCases() { yield return new TestCaseData(null, "", "").Throws(typeof(ArgumentNullException)); yield return new TestCaseData("http://www.google.com/", "", "value").Throws(typeof(ArgumentNullException)); yield return new TestCaseData("http://www.google.com/", null, "value").Throws(typeof(ArgumentNullException)); yield return new TestCaseData("http://www.google.com/", "hello", "world").Returns("http://www.google.com/?hello=world"); yield return new TestCaseData("http://www.google.com/?hello=john", "hello", "world").Returns("http://www.google.com/?hello=john&hello=world"); yield return new TestCaseData("../relative/path", "hello", "world").Returns("../relative/path?hello=world"); } [Test] [TestCaseSource("UrlHelper_AddUriQueryStringParameter_TestCases")] public static string UrlHelper_AddUriQueryStringParameter(string url, string key, string value) { var uri = TestUtility.GetUriFromString(url); return UrlHelper.AddUriQueryStringParameter(uri, key, value).ToString(); } [Test] [TestCaseSource("UrlHelper_AddUriQueryStringParameter_TestCases")] public static string UrlHelper_AddUriQueryStringParameter_generic(string url, string key, string value) { var uri = TestUtility.GetUriFromString(url); return UrlHelper.AddUriQueryStringParameter<string>(uri, key, value).ToString(); } [Test] [TestCaseSource("UrlHelper_AddUriQueryStringParameter_TestCases")] public static string UrlHelper_AddUriQueryStringParameter_object(string url, string key, object value) { var uri = TestUtility.GetUriFromString(url); return UrlHelper.AddUriQueryStringParameter(uri, key, value).ToString(); } [Test] [TestCaseSource("UrlHelper_AddUriQueryStringParameter_TestCases")] public static string UrlHelper_AddUrlQueryStringParameter(string url, string key, string value) { return UrlHelper.AddUrlQueryStringParameter(url, key, value); } [Test] [TestCaseSource("UrlHelper_AddUriQueryStringParameter_TestCases")] public static string UrlHelper_AddUrlQueryStringParameter_generic(string url, string key, string value) { return UrlHelper.AddUrlQueryStringParameter<string>(url, key, value); } [Test] [TestCaseSource("UrlHelper_AddUriQueryStringParameter_TestCases")] public static string UrlHelper_AddUrlQueryStringParameter_object(string url, string key, object value) { return UrlHelper.AddUrlQueryStringParameter(url, key, value); } } }
namespace HotelBookingSystem.Core { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using Controllers; using Data; using Endpoints; using Interfaces; using Utilities; using Views; public class Engine : IEngine { private readonly IInputReader reader; private readonly IOutputWriter writer; private readonly Dictionary<string, Type> controllersByName; private readonly Dictionary<string, MethodInfo> methodsByName; public Engine(IInputReader reader, IOutputWriter writer) { this.reader = reader; this.writer = writer; this.controllersByName = new Dictionary<string, Type>(); this.methodsByName = new Dictionary<string, MethodInfo>(); } public void StartOperation() { var database = new HotelBookingSystemData(); IUser currentUser = null; while (true) { string url = this.reader.ReadLine(); if (string.IsNullOrEmpty(url)) { break; } var executionEndpoint = new Endpoint(url); if (!this.controllersByName.ContainsKey(executionEndpoint.ControllerName)) { var controllerInDict = AssemblyUtilities.Types .FirstOrDefault(type => type.Name == executionEndpoint.ControllerName); if (controllerInDict != null) { this.controllersByName.Add( executionEndpoint.ControllerName, controllerInDict); } } var controllerType = this.controllersByName[executionEndpoint.ControllerName]; var controller = Activator.CreateInstance( controllerType, database, currentUser, executionEndpoint.ActionName) as Controller; var methodName = $"{executionEndpoint.ControllerName}{executionEndpoint.ActionName}"; if (!this.methodsByName.ContainsKey(methodName)) { this.methodsByName.Add( methodName, controllerType.GetMethod(executionEndpoint.ActionName)); } var action = this.methodsByName[methodName]; object[] parameters = MapParameters(executionEndpoint, action); string viewResult = string.Empty; try { var view = action.Invoke(controller, parameters) as IView; viewResult = view.Display(); currentUser = controller.CurrentUser; } catch (Exception ex) { viewResult = new ErrorView(ex.InnerException.Message).Display(); } this.writer.WriteLine(viewResult); } } private static object[] MapParameters(IEndpoint executionEndpoint, MethodInfo action) { var parameters = action .GetParameters() .Select<ParameterInfo, object>(p => { if (p.ParameterType == typeof(int)) { return int.Parse(executionEndpoint.Parameters[p.Name]); } if (p.ParameterType == typeof(decimal)) { return decimal.Parse(executionEndpoint.Parameters[p.Name]); } if (p.ParameterType == typeof(DateTime)) { return DateTime.ParseExact( executionEndpoint.Parameters[p.Name], Constants.DateFormat, CultureInfo.InvariantCulture); } return executionEndpoint.Parameters[p.Name]; }) .ToArray(); return parameters; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; /// <summary> /// Log 的摘要说明 /// </summary> public class Logs { public int Logid; public int Userid; public string Headline; public string Content; public string Time; public Logs(int logid) { this.Logid = logid; string sql = "select * from Log where logid='" + logid + "'"; DataTable dt = DataClass.DataT(sql); this.Userid = Convert.ToInt32(dt.Rows[0][1].ToString()); this.Headline = dt.Rows[0][2].ToString(); this.Content = dt.Rows[0][3].ToString(); this.Time = dt.Rows[0][4].ToString(); } }
using UnityEngine; using System.Collections; using UnityEngine.UI; /* The PreventGoThroughWalls script regulates what happens when the player goes through the wall and falls outside of the network. */ public class PreventGoThroughWalls : MonoBehaviour { public Image a; //The background UI Image to be shown when the player falls public Text b; //The UI Text to be shown when the player falls bool timerStarted; //boolean value starts after player falls float timer = 0.0f; //value of the timer /* The Update function counts the time after the player triggers the trigger on the safety net. After five seconds the text disappears and two seconds after the text disappears the level restarts. */ void Update() { if (timerStarted) { timer += Time.deltaTime; } if (timer >= 5.0f) { b.gameObject.SetActive(false); } if (timer >= 7.0f) { Application.LoadLevel(Application.loadedLevel); } } /* The OnTriggerEnter function defines what happens when the player falls out and triggers the trigger. It sets the UI Image a and UI Text b as active and starts the timer. */ void OnTriggerEnter(Collider other) { if(other.gameObject.tag == "Player") { a.gameObject.SetActive(true); b.gameObject.SetActive(true); timerStarted = true; } } }
using Anywhere2Go.DataAccess.Object; using System.IO; using System.ServiceModel; using System.ServiceModel.Activation; using System.ServiceModel.Web; namespace Claimdi.WCF.Public { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IPolicy" in both code and config file together. [ServiceContract] public interface IPolicy { [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/add", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] BaseResult<string> AddPolicy(APIPolicyRequest policy); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/edit", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] BaseResult<string> EditPolicy(APIPolicyRequest policy); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/upload_image", ResponseFormat = WebMessageFormat.Json)] BaseResult<APIUploadImageResponse> UploadImage(Stream data); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/details", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<APIPolicyDetailResponse> PolicyDetail(APIPolicyDetailRequest obj); [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/details_full_report_tracking?task_id={taskId}&acc_id={accId}&allow_unassign={allowUnAssign}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<APIPolicyDetailResponse> PolicyDetailFullReportTracking(string taskId, string accId,bool allowUnAssign = false); [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/generate_full_report_format_template?task_id={taskId}&acc_id={accId}&template_id={templateId}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<APIGenerateFullReportTemplateResponse> GenerateFullReportFormatTemplate(string taskId, string accId, string templateId); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/detail_by_tsoftid", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<APIPolicyDetailResponse> PolicyDetailByTSoftID(APIPolicyDetailByTSoftIdRequest obj); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/list", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<APIPolicyListResponse> PolicyList(APIPolicySearch policySearchModel); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/update_status", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<bool?> UpdateProcess(APITaskProcessLog taskProcess); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/update_status_reject", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<bool?> UpdateProcessReject(APITaskProcessLogReject taskProcess); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/update_infomation_bike", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<bool?> UpdateInformationBike(APIUpdateBikeRequest obj); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/update_infomation_claim", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<bool?> UpdateInformationClaim(APIUpdateClaimRequest obj); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/log_call", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<bool?> AddLogCall(APILogCall obj); [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/call_google_api/{url}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] string CallGoogleAPI(string url); [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/test_update_picture_approve/{taskId}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] string UpdatePictureApprove(string taskId); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/duplicate_task", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<APIDuplicateTaskResponse> DuplicateTask(APIDuplicateTaskRequest duplicateTask); [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/car_insurer?acc_id={accId}&task_id={taskId}", ResponseFormat = WebMessageFormat.Json)] BaseResult<APICarInsurer> CarInsurer(string accId, string taskId); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/update_car_insurer", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<bool?> UpdateCarInsurer(APICarInsurerRequest carInsurerRequest); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/delete_car_damage", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<bool?> DeleteCarDamage(APIDeleteCarDamageRequest deleteCarDamageRequest); [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/car_parties?acc_id={accId}&task_id={taskId}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<APICarParties> CarParties(string accId, string taskId); [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/car_party/{carPartyId}", ResponseFormat = WebMessageFormat.Json)] BaseResult<APICarParty> CarParty(string carPartyId); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/car_parties", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<APICarPartyResponse> SaveCarParty(APICarPartyRequest carPartyRequest); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/delete_car_party", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<bool?> DeleteCarParty(APIDeleteCarPartyRequest deleteCarPartyRequest); [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/summary_of_case?acc_id={accId}&task_id={taskId}", ResponseFormat = WebMessageFormat.Json)] BaseResult<APISummaryOfCaseResponse> SummaryOfCase(string accId, string taskId); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/summary_of_case", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<bool?> SaveSummaryOfCase(APISummaryOfCaseRequest summaryOfCaseRequest); [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/property_damages?acc_id={accId}&task_id={taskId}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<APIPropertyDamages> PropertyDamages(string accId, string taskId); [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/property_damage/{propertyDamageId}", ResponseFormat = WebMessageFormat.Json)] BaseResult<APIPropertyDamageResponse> PropertyDamage(string propertyDamageId); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/property_damages", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<bool?> SavePropertyDamage(APIPropertyDamageRequest propertyDamageRequest); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/delete_property_damage", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<bool?> DeletePropertyDamage(APIDeletePropertyDamageRequest deletePropertyDamageRequest); [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/woundeds?acc_id={accId}&task_id={taskId}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<APIWoundeds> Woundeds(string accId, string taskId); [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/wounded/{woundedId}", ResponseFormat = WebMessageFormat.Json)] BaseResult<APIWoundedResponse> Wounded(string woundedId); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/wounded", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<bool?> SaveWounded(APIWoundedRequest woundedRequest); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/delete_wounded", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<bool?> DeleteWounded(APIDeleteWoundedRequest deleteWoundedRequest); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/delete_image", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<bool?> DeleteImage(APIDeleteImageRequest deleteImageRequest); [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/surveyor_charges?acc_id={accId}&task_id={taskId}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<APISurveyorChargeResponse> SurveyorCharges(string accId, string taskId); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/surveyor_charge", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<APISurveyorChargeSaveResponse> SaveSurveyorCharge(APISurveyorChargeRequest surveyorChargeRequest); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/delete_surveyor_charge", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<bool?> DeleteSurveyorCharge(APIDeleteSurveyorChargeRequest deletSurveyorChargeRequest); [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/task_comments?acc_id={accId}&task_id={taskId}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<APITaskComments> TaskComments(string taskId, string accId); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/task_comment", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<APITaskComment> SaveTaskComment(APITaskComment taskComment); [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/task_token?acc_id={accId}&task_id={taskId}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<APITaskToken> GetTaskToken(string taskId, string accId); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/auto_assign", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] BaseResult<APIPolicyAutoAssignListResponse> PolicyAutoAssign(APIPolicyAutoAssignSearch policySearchModel); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Text.RegularExpressions; using System.Dynamic; using System.Web.Script.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace IRAPGeneralGateway { public static class JSONHelper { /// <summary> /// JSON 序列化 /// </summary> /// <param name="obj">源对象</param> /// <returns>以 JSON 序列化源对象后的内容</returns> public static string ToJSON(this object obj) { return JsonConvert.SerializeObject(obj); } /// <summary> /// 将字符串数组转换成 JSON 数据格式:["Value1", "Value2", ...] /// </summary> /// <param name="strs">字符串数组</param> /// <returns>JSON 数据格式的字符串</returns> public static string ToJSON(this string[] strs) { return ToJSON((object)strs); } /// <summary> /// 将 DataTable 数据源转换为 JSON 数据格式: /// [{"ColumnName":"ColumnValue",...},{"ColumnName":"ColumnValue",...},...] /// </summary> /// <param name="dt">DataTable 数据源</param> /// <returns>JSON 数据格式的字符串</returns> public static string ToJSON(this DataTable dt) { return JsonConvert.SerializeObject(dt, new DataTableConverter()); } /// <summary> /// 将 JSON 格式的日期时间("\/Date(673286400000)\/" 转换成 "YYYY-MM-dd HH:mm:ss" 格式 /// </summary> /// <param name="jsonDateTimeString">JSON 格式的日期时间</param> /// <returns></returns> public static string ConvertToDateTimeString(this string jsonDateTimeString) { string result = ""; string p = @"\\/Date\((d+\)\\/"; MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJSONDateToDateString); Regex reg = new Regex(p); result = reg.Replace(jsonDateTimeString, matchEvaluator); return result; } public static string ConvertJSONDateToDateString(Match match) { string result = ""; DateTime dt = new DateTime(1970, 1, 1); dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value)); dt = dt.ToLocalTime(); result = dt.ToString("yyyy-MM-dd HH:mm:ss"); return result; } /// <summary> /// 根据简单的 JSON 格式字符串返回动态类型 /// </summary> /// <param name="jsonString">JSON 格式字符串</param> /// <returns></returns> public static dynamic GetSimpleObjectFromJson(this string jsonString) { dynamic d = new ExpandoObject(); // 将JSON字符串反序列化 JavaScriptSerializer s = new JavaScriptSerializer(); object resobj = s.DeserializeObject(jsonString); // 拷贝数据 IDictionary<string, object> dic = (IDictionary<string, object>)resobj; IDictionary<string, object> dicdyn = (IDictionary<string, object>)d; foreach (var item in dic) { dicdyn.Add(item.Key, item.Value); } return d; } /// <summary> /// 把 JSON 格式字符串反序列化为 List&lt;T&gt; 对象 /// </summary> /// <typeparam name="T">反序列化对象类型</typeparam> /// <param name="jsonString">JSON 格式的字符串</param> /// <returns>List&lt;T&gt;]</typeparam></returns> public static List<T> GetListFromJSON<T>(this string jsonString) { JavaScriptSerializer s = new JavaScriptSerializer(); s.MaxJsonLength = 2147483647; IList<T> list = s.Deserialize<IList<T>>(jsonString); return list.ToList(); } //把Json字符串反序列化为T对象 /// <summary> /// 把 JSON 格式字符串反序列化为 T 对象 /// </summary> /// <typeparam name="T">反序列化对象类型</typeparam> /// <param name="jsonString">JSON 格式的字符串</param> /// <returns>T 对象</returns> public static T GetObjectFromJSON<T>(this string jsonString) { JavaScriptSerializer s = new JavaScriptSerializer(); T obj = s.Deserialize<T>(jsonString); return obj; } /// <summary> /// 把 Get 参数 Key1=Value1&Key2=Value2&Key3=Value3 用字典的形式返回 /// </summary> /// <param name="sourceString">参数字符串</param> /// <returns>参数字典</returns> public static Dictionary<string, string> ToDict(this string sourceString) { Dictionary<string, string> keys = new Dictionary<string, string>(); try { string[] inparam = sourceString.Split('&'); foreach (string item in inparam) { string[] keyvalue = item.Split('='); keys.Add(keyvalue[0], keyvalue[1]); }; return keys; } catch (Exception) { return keys; } } //把Json Array字符串转换为对象 /// <summary> /// 把 JSON Array 字符串转换为对象 /// </summary> /// <param name="jsonString"></param> /// <returns></returns> public static List<Dictionary<string, object>> ToRows(this string jsonString) { List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>(); JavaScriptSerializer s = new JavaScriptSerializer(); object[] resobj = (object[])s.DeserializeObject(jsonString); // 拷贝数据 foreach (Dictionary<string, object> item in resobj) { rows.Add(item); } return rows; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JDWinService.Model { /// <summary> /// 采购变更 日志 /// 编写人:ywk /// 编写日期:2018/8/8 星期三 /// </summary> public class JD_OrderListBG_Log { #region 类的属性定义 public int ItemID { get; set; } /// <summary> /// /// </summary> public int TaskID { get; set; } /// <summary> /// /// </summary> public int IsUpdate { get; set; } /// <summary> /// /// </summary> public DateTime CreateTime { get; set; } /// <summary> /// /// </summary> public DateTime UpdateTime { get; set; } /// <summary> /// /// </summary> public string Operater { get; set; } /// <summary> /// /// </summary> public DateTime OperateTime { get; set; } /// <summary> /// /// </summary> public string SupplierName { get; set; } /// <summary> /// /// </summary> public string SupplierCode { get; set; } /// <summary> /// /// </summary> public string BGType { get; set; } /// <summary> /// /// </summary> public decimal AllPrice { get; set; } /// <summary> /// /// </summary> public string BGName { get; set; } /// <summary> /// /// </summary> public string FBillNo { get; set; } /// <summary> /// /// </summary> public string SN { get; set; } /// <summary> /// /// </summary> public string Attachments { get; set; } /// <summary> /// /// </summary> public string WuLiaoNum { get; set; } /// <summary> /// /// </summary> public string GuiGe { get; set; } /// <summary> /// /// </summary> public decimal FAuxQty { get; set; } /// <summary> /// /// </summary> public decimal Count { get; set; } /// <summary> /// /// </summary> public string Unit { get; set; } /// <summary> /// /// </summary> public decimal FAuxPrice { get; set; } /// <summary> /// /// </summary> public decimal Price { get; set; } /// <summary> /// /// </summary> public decimal ActualPrice { get; set; } /// <summary> /// /// </summary> public DateTime SendDate { get; set; } /// <summary> /// /// </summary> public DateTime FDate { get; set; } /// <summary> /// /// </summary> public string BGMarks { get; set; } /// <summary> /// /// </summary> public string FInterID { get; set; } /// <summary> /// /// </summary> public string FEntryID { get; set; } /// <summary> /// /// </summary> public DateTime FEntrySelfP0267 { get; set; } /// <summary> /// /// </summary> public DateTime FirstConfirmDate { get; set; } /// <summary> /// /// </summary> public DateTime FEntrySelfP0268 { get; set; } /// <summary> /// /// </summary> public DateTime LastConfirmDate { get; set; } /// <summary> /// /// </summary> public decimal FPOHighPrice { get; set; } /// <summary> /// /// </summary> public decimal FPrice { get; set; } /// <summary> /// /// </summary> public decimal FCoefficient { get; set; } /// <summary> /// /// </summary> public decimal FLinkCount { get; set; } /// <summary> /// /// </summary> public string OrderListBGName { get; set; } public string BPMSourceNo { get; set; } public string BPMItemID { get; set; } #endregion } }
using System; using System.Collections.Generic; using System.IO; using Fingo.Auth.DbAccess.Repository.Interfaces; using Fingo.Auth.Domain.Infrastructure.EventBus.Events.Project; using Fingo.Auth.Domain.Infrastructure.EventBus.Interfaces; using Fingo.Auth.Domain.Models.UserModels; using Fingo.Auth.ManagementApp.Services.Interfaces; using Microsoft.AspNetCore.Http; namespace Fingo.Auth.ManagementApp.Services.Implementation { public class CsvService : ICsvService { private readonly IEventBus _eventBus; private readonly IProjectRepository _projectRepository; public CsvService(IProjectRepository projectRepository , IEventBus eventBus) { _projectRepository = projectRepository; _eventBus = eventBus; } public string ExportProject(int projectId) { var project = _projectRepository.GetById(projectId); if (project == null) throw new ArgumentNullException($"Could not find project with id: {projectId}."); var result = "Project name;Project GUID;Client name;Client contact data;Creation date UTC;Modification date UTC\r\n"; result += $"{ToCsvString(project.Name)};{ToCsvString(project.ProjectGuid.ToString())};{ToCsvString(project.Information.Name)};" + $"{ToCsvString(project.Information.ContactData)};{ToCsvString(project.CreationDate.ToString("dd.MM.yyyy HH:mm"))};" + $"{ToCsvString(project.ModificationDate.ToString("dd.MM.yyyy HH:mm"))}\n"; result += ";;;;;\r\n"; result += "User e-mail;First name;Last name;Last password change UTC;Creation date UTC;Modification date UTC\r\n"; var users = _projectRepository.GetAllUsersFromProject(projectId); if (users == null) throw new ArgumentNullException($"Could not find users of project with id: {projectId}."); foreach (var user in users) result += $"{ToCsvString(user.Login)};{ToCsvString(user.FirstName)};{ToCsvString(user.LastName)};" + $"{ToCsvString(user.LastPasswordChange.ToString("dd.MM.yyyy HH:mm"))};" + $"{ToCsvString(user.CreationDate.ToString("dd.MM.yyyy HH:mm"))};" + $"{ToCsvString(user.ModificationDate.ToString("dd.MM.yyyy HH:mm"))}\r\n"; _eventBus.Publish(new ProjectExported(projectId)); return result; } public List<UserModel> CsvToUsersList(IFormFile csvFile) { const char delimiter = '\t'; var users = new List<UserModel>(); using (var stream = csvFile.OpenReadStream()) { using (var reader = new StreamReader(stream)) { while (!reader.EndOfStream) { var line = reader.ReadLine(); var values = line.Split(delimiter); if (values.Length != 3) throw new FormatException(); users.Add(new UserModel { FirstName = values[0] , LastName = values[1] , Login = values[2] }); } } } return users; } private string ToCsvString(string entry) { return entry == null ? "N/A" : $"\"{entry.Replace("\"" , "\"\"")}\""; } } }
using ServiceQuotes.Domain.Entities; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace ServiceQuotes.Domain.Repositories { public interface IServiceRequestJobValuationRepository : IRepository<ServiceRequestJobValuation> { Task<ServiceRequestJobValuation> GetByServiceRequestId(Guid serviceRequestId); Task<ServiceRequestJobValuation> GetByEmployeeId(Guid employeeId); Task<ServiceRequestJobValuation> GetByJobValuationId(Guid jobValuationId); Task<IEnumerable<ServiceRequestJobValuation>> GetAllByServiceRequestId(Guid serviceRequestId); Task<IEnumerable<ServiceRequestJobValuation>> GetAllByEmployeeId(Guid employeeId); Task<IEnumerable<ServiceRequestJobValuation>> GetLastByEmployeeId(Guid employeeId, int amount); } }
using MyMovies.Domain.Enums; using System; using System.ComponentModel.DataAnnotations.Schema; namespace MyMovies.Domain.Entities { public class Item : Entity { public ItemType ItemType { get; set; } public SourceType SourceType { get; set; } public Guid? UserId { get; set; } [ForeignKey("UserId")] public virtual User User { get; set; } public Guid? MovieId { get; set; } [ForeignKey("MovieId")] public virtual Movie Movie { get; set; } public Guid? PersonId { get; set; } [ForeignKey("PersonId")] public virtual Person Person { get; set; } public string Value { get; set; } public string Width { get; set; } public string Height { get; set; } } }
using System.Collections.Immutable; namespace GraphQLDynamic.Model { public record TypeDefinition ( ImmutableList<AttributeDefinition> AttributeDefinitions, ImmutableList<Relationship> Relationships ); }
 using Android.App; using Android.OS; using Android.Widget; using Billetautomat.CustomAdapter; using Billetautomat.Services; using Xamarin.Essentials; namespace Billetautomat { [Activity(Label = "BookingsListActivity")] public class BookingsListActivity: Activity { private ListView lw; private TextView tw; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.Secondpage); tw = FindViewById<TextView>(Resource.Id.infotext); string name = Preferences.Get("name", "ok"); tw.Text = $"Hej {name}, her er en liste over dine bestillinger. \nKlik for yderligere Information"; lw = FindViewById<ListView>(Resource.Id.ListView); BookingAdapter b = new BookingAdapter(this, Resource.Layout.Listrow, HttpService.bookings,lw); lw.Adapter = b; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Verse; using RimWorld; namespace Replace_Stuff.CoolersOverWalls { //Designator_Build and _Dropdown both create their own dropdown list but only one shows //That'll be _build designators with things made from stuff //So let's remove any dropdown list if it holds things made from stuff //(if a mod makes coolers made from stuff, overwall coolers and their 2-wide version fit this description) public static class DesignatorBuildDropdownStuffFix { public static void SanityCheck() { //Either patch the method that created the dropdown designator, or just undo it here: foreach (var catDef in DefDatabase<DesignationCategoryDef>.AllDefsListForReading) for (int i = 0; i < catDef.AllResolvedDesignators.Count; i++) if (catDef.AllResolvedDesignators[i] is Designator_Dropdown des && des.Elements.Any(d => d is Designator_Build db && db.PlacingDef.MadeFromStuff)) { catDef.AllResolvedDesignators.RemoveAt(i); foreach (var dropDes in des.Elements) catDef.AllResolvedDesignators.Insert(i, dropDes); } } } }
using System.Data.Entity.ModelConfiguration; using Properties.Core.Objects; namespace Properties.Infrastructure.Data.Mapping { public class LandlordMap : EntityTypeConfiguration<Landlord> { public LandlordMap() { /*HasMany(p => p.SubmittedProperties) .WithOptional() .WillCascadeOnDelete(true);*/ HasMany(p => p.AlternateContactDetails) .WithOptional() .WillCascadeOnDelete(true); Property(p => p.LandlordReference) .HasMaxLength(25); Property(p => p.GivenName) .HasMaxLength(50); Property(p => p.FamilyName) .HasMaxLength(50); Property(p => p.KnownAs) .HasMaxLength(100); Property(p => p.AddressLine1) .HasMaxLength(100); Property(p => p.AddressLine2) .HasMaxLength(100); Property(p => p.AddressLine3) .HasMaxLength(100); Property(p => p.AddressLine4) .HasMaxLength(100); Property(p => p.Postcode) .HasMaxLength(25); Property(p => p.County) .HasMaxLength(50); Property(p => p.Mobile) .HasMaxLength(25); Property(p => p.Landline) .HasMaxLength(25); Property(e => e.Email) .HasMaxLength(50); HasOptional(p => p.User) .WithRequired(u => u.Landlord); HasOptional(p => p.Referrer) .WithRequired(u => u.Landlord); Ignore(p => p.IsDirty); } } }
using Microsoft.EntityFrameworkCore.Migrations; namespace Senparc.Web.Migrations { public partial class AddActivityScheduleStatusFiledDb : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<int>( name: "ScheduleStatus", table: "Activities", nullable: false, defaultValue: 0); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "ScheduleStatus", table: "Activities"); } } }
using EmberKernel.Plugins.Components; using System; using System.Collections.Generic; using System.Text; namespace EmberMemory.Listener { public static class ProcessListenerBuilderExtensions { public static void UseProcessListener(this IComponentBuilder builder, Func<ProcessListenerBuilder, ProcessListenerBuilder> build) { var processListenerBuilder = new ProcessListenerBuilder(builder); build(processListenerBuilder); processListenerBuilder.Build(); } } }
using System; using System.Globalization; namespace EXERCICIOENTRADA { class Program { static void Main(string[] args) { Console.WriteLine("Entre com seu nome completo:"); string nome = Console.ReadLine(); Console.WriteLine("Quantos quartos tem na sua casa?"); int quarto = int.Parse(Console.ReadLine()); Console.WriteLine("Entre com o preço do produto:"); double preco = double.Parse(Console.ReadLine()); Console.WriteLine("Entre com seu último nome, idade e altura na mesma linha:"); string[] vet = Console.ReadLine().Split(' '); string name = vet[0]; int old = int.Parse(vet[1]); double alt = double.Parse(vet[2], CultureInfo.InvariantCulture); Console.WriteLine(name); Console.WriteLine(old); Console.WriteLine(alt.ToString("F2",CultureInfo.InvariantCulture)); } } }
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using TryHardForum.Models; namespace TryHardForum.Data { public class AppUserDbContext : IdentityDbContext<AppUser> { public AppUserDbContext(DbContextOptions<AppUserDbContext> options) : base(options) { } public DbSet<AppUser> AppUsers { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<AppUser>() .HasMany(u => u.Forums) .WithOne(f => f.AppUser).HasForeignKey(f => f.AppUserId); modelBuilder.Entity<AppUser>() .HasMany(u => u.Topics) .WithOne(t => t.AppUser).HasForeignKey(t => t.AppUserId); modelBuilder.Entity<AppUser>() .HasMany(u => u.Posts) .WithOne(p => p.AppUser).HasForeignKey(p => p.AppUserId); modelBuilder.Entity<AppUser>() .HasMany(u => u.Replies) .WithOne(r => r.AppUser).HasForeignKey(r => r.AppUserId); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using UberCarAPI.Models; namespace UberCarAPI.Controllers { [Route("api/[controller]")] [ApiController] public class CarController : ControllerBase { public CarController() { } [HttpGet] public IEnumerable<Car> Get() { return Repository.CarRepository.Cars; } [HttpGet("{id}", Name = "Get")] public Car Get(int id) { return Repository.CarRepository.Cars.FirstOrDefault(x => x.Id == id); } [HttpPost] public IActionResult Post([FromBody] Car value) { if (value.FabricationYear < 2010) { return BadRequest( new { Message = "Fabrication Year must be greater than 2010", Error = true }); } if (value.HasAc == false) { return BadRequest( new { Message = "Car must have an A/C", Error = true }); } if (value.IsLuxe == true && (value.Color == "black" || value.Color == "Black")) { value.UberCategory = "black"; } else { value.UberCategory = "x"; } Repository.CarRepository.Cars.Add(value); return Ok( new { Message = "Car registered successfully. " + "Your car has been added to the category Uber " + value.UberCategory }); } [HttpPut("{id}")] public void Put(int id, [FromBody] Car value) { Car cr = Repository.CarRepository.Cars.FirstOrDefault(x => x.Id == id); if (cr != null) { cr.Model = value.Model; cr.Brand = value.Brand; cr.Color = value.Color; cr.Plate = value.Plate; cr.FabricationYear = value.FabricationYear; cr.IsLuxe = value.IsLuxe; cr.HasAc = value.HasAc; cr.UberCategory = value.UberCategory; } } [HttpDelete("{id}")] public void Delete(int id) { Car cr = Repository.CarRepository.Cars.FirstOrDefault(x => x.Id == id); if (cr != null) { Repository.CarRepository.Cars.Remove(cr); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mediator { class Program { static void Main(string[] args) { NotaDeCredito n = new NotaDeCredito(); n.Destinatario = "Lopez"; n.Numero = 11556; Factura f = new Factura(); f.Importe = 9997; f.Numero = 2; NotaDeCreditoMediator nM = new NotaDeCreditoMediator(n); nM.MostrarDestinatario(); nM.GuardarComprobante(); FacturaMediator fm = new FacturaMediator(f); fm.CalcularImpuestos(); fm.GuardarComprobante(); Console.ReadKey(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EmissionAudioReact : AudioReact { public override void react(float sumOfTotals, float maxLevel) { Color colour = new Color(); colour.r = sumOfTotals / maxLevel; colour.b = sumOfTotals / maxLevel; GetComponent<Renderer>().material.SetColor("_EmissionColor", colour); } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Upgrader.Infrastructure { internal static class Validate { public static void MaxLength(string argument, string argumentName, int maxLength) { if (argument != null && argument.Length >= maxLength) { throw new ArgumentException($"String cannot be longer than {maxLength} characters.", argumentName); } } public static void MaxLength(IEnumerable<string> argument, string argumentName, int maxLength) { foreach (var item in argument) { MaxLength(item, argumentName, maxLength); } } public static void IsTrue(bool argument, string argumentName, string message) { if (argument == false) { throw new ArgumentException(message, argumentName); } } public static void IsNotEmpty<T>(T argument, string argumentName) where T : IEnumerable { if (argument == null) { return; } if (argument.GetEnumerator().MoveNext() == false) { throw new ArgumentException("Value cannot be empty.", argumentName); } } public static void IsNotNullAndNotEmpty<T>(T argument, string argumentName) where T : class, IEnumerable { IsNotNull(argument, argumentName); IsNotEmpty(argument, argumentName); } public static void IsNotNullAndNotEmptyEnumerable<T>(IEnumerable<T> argument, string argumentName) where T : class, IEnumerable { var argumentShallowClone = argument.ToArray(); IsNotNull(argumentShallowClone, argumentName); IsNotEmpty(argumentShallowClone, argumentName); foreach (var item in argumentShallowClone) { IsNotNullAndNotEmpty(item, argumentName); } } public static void IsNotNull<T>(T argument, string argumentName) where T : class { if (argument == null) { throw new ArgumentNullException(argumentName); } } public static void IsNotNullable(Type argument, string argumentName) { IsNotNull(argument, argumentName); if (Nullable.GetUnderlyingType(argument) != null) { throw new ArgumentNullException(argumentName); } } public static void IsEqualOrGreaterThan(int argument, int value, string argumentName) { if (argument < value) { throw new ArgumentOutOfRangeException(argumentName); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Welic.Dominio.Patterns.Pattern.Ef6; namespace Welic.Dominio.Models.Marketplaces.Entityes { public partial class EmailTemplate : Entity { public int ID { get; set; } public string Slug { get; set; } public string Subject { get; set; } public string Body { get; set; } public bool SendCopy { get; set; } public System.DateTime Created { get; set; } public System.DateTime LastUpdated { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EffectBind : ExecuteBase { }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BusinessEntities { public class UsuarioBE { public int id { get; set; } public string usuario { get; set; } public string nombew { get; set; } public string apellidoPaterno { get; set; } public string apellidoMaterno { get; set; } public int perfil { get; set; } public string perfilCodigo { get; set; } public string perfilNombre { get; set; } public class Criterio { public string USUARIO { get; set; } public int ID { get; set; } } } }
using System; using System.IO; using System.Linq; using System.Text; namespace Even_Lines { class Program { static void Main(string[] args) { var file = new StreamReader("../../../Input.txt"); var text = new StringBuilder(); while (true) { var line = file.ReadLine(); if (line == null) { break; } for (int i = 0; i < line.Length; i++) { if (line[i] == '-' || line[i] == ',' || line[i] == '.' || line[i] == '!' || line[i] == '?') { var lineSt = new StringBuilder(line); lineSt[i] = '@'; line = lineSt.ToString(); } } text.AppendLine(line); } Console.WriteLine(text); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VerbiLib.ParserV1 { public class VerbiSyntax1 { public VerbiDeclaration[] Declarations { get; set; } public override bool Equals(object obj) { if (!(obj is VerbiSyntax1)) return false; var y = obj as VerbiSyntax1; if (!Declarations.SequenceEqualsNullCheck(y.Declarations)) return false; return true; } public override string ToString() { var sb = new StringBuilder(); foreach (var ddd in Declarations) sb.Append(ddd + "\n"); return sb.ToString(); } } public class VerbiDeclaration { public int Indentation { get; set; } public string Token { get; set; } public AttributeAssignment[] TokenFilters { get; set; } public string[] Conjugation { get; set; } public override bool Equals(object obj) { if (!(obj is VerbiDeclaration)) return false; var y = obj as VerbiDeclaration; if (Token != y.Token) return false; if (Indentation != y.Indentation) return false; if (!Conjugation.SequenceEqualsNullCheck(y.Conjugation)) return false; if (!TokenFilters.SequenceEqualsNullCheck(y.TokenFilters)) return false; return true; } public override string ToString() { var ttt = "noT"; if (Token != null) ttt = "T=" + Token; if (TokenFilters != null) ttt = "TF=" + string.Join(",", TokenFilters.Select(f => $"{f.Token}+{f.Value}")); var ccc = "noC"; if (Conjugation != null) ccc = "C=" + string.Join(",", Conjugation); return $"{Indentation}|{ttt}|{ccc}"; } } public class AttributeAssignment { public string Token { get; set; } public string Value { get; set; } public override bool Equals(object obj) { if (!(obj is AttributeAssignment)) return false; var y = obj as AttributeAssignment; if (Token != y.Token) return false; if (Value != y.Value) return false; return true; } public override string ToString() { return $"{Token}={Value}"; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.Text; namespace DotNetBridge { [ComVisible(true)] [ClassInterface(ClassInterfaceType.None)] [Guid("ddb71722-f7e5-4c45-817e-cc1b84bfab4e")] public class DotNetBridge : IDotNetBridge { delegate IntPtr JsonDelegate(IntPtr args); int _lastObjectId = 0; Dictionary<int, object> _objects = new Dictionary<int, object>(); public string CreateObject(string typeName, string args) { return NoThrowBoundary(() => DehydrateResult(Activator.CreateInstance(FindTypeByName(typeName), HydrateArguments(args)))); } public string ReleaseObject(string objRef) { return NoThrowBoundary(() => _objects.Remove(JsonToObject<OBJECT>(objRef).Id)); } public string DescribeObject(string typeName, string objRef) { return NoThrowBoundary(() => { Type type; object instance = null; if (string.IsNullOrWhiteSpace(objRef)) { type = FindTypeByName(typeName); } else { instance = ObjectRefToObject(JsonToObject<OBJECT>(objRef)); type = instance.GetType(); } return new TypeInfo { TypeName = type.FullName, IsEnum = type.GetTypeInfo().IsEnum, IsDelegate = typeof(MulticastDelegate).IsAssignableFrom(type.GetTypeInfo().BaseType), NestedTypes = type.GetNestedTypes(BindingFlags.Public).Select(t => t.FullName).ToArray(), Fields = type.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public).Select(f => f.Name).ToArray(), Methods = type.GetMethods().Select(m => new MethodInfo { Name = m.Name, Parameters = m.GetParameters().Select(p => p.Name).ToArray(), }).ToArray(), EnumValue = (type.GetTypeInfo().IsEnum && instance != null) ? Convert.ChangeType(instance, Enum.GetUnderlyingType(instance.GetType())) : 0, }; }); } public string CreateDelegate(string typeName, IntPtr callback) { return NoThrowBoundary(() => { return DehydrateResult(Delegate_Wrapper.Create((args) => { var jsonCallback = (JsonDelegate)Marshal.GetDelegateForFunctionPointer(callback, typeof(JsonDelegate)); var json_args = ObjectToJson(args.Select(a => DehydrateResult(a)).ToArray()); var ret = JsonToObject<object>(Marshal.PtrToStringUni(jsonCallback(Marshal.StringToHGlobalUni(json_args)))); if (ret != null && ret.GetType() == typeof(OBJECT)) { ret = ObjectRefToObject((OBJECT)ret); } return ret; }, FindTypeByName(typeName))); }); } public string InvokeMethod(string objRef, string typeName, string methodName, string args, string genericTypesRef, int box) { bool returnBoxed = box == 1; return NoThrowBoundary(() => { Type type; object instance = null; if (!string.IsNullOrWhiteSpace(objRef)) { instance = ObjectRefToObject(JsonToObject<OBJECT>(objRef)); type = instance.GetType(); } else { type = FindTypeByName(typeName); } var parameters = HydrateArguments(args); var method = type.GetMethod(methodName, parameters.Select(s => s.GetType()).ToArray()); if (method == null) // Fuzzy match for types that will cast. { method = type.GetMethods().FirstOrDefault(m => m.Name == methodName && m.GetParameters().Length == parameters.Length); } if (method != null) { if (!string.IsNullOrWhiteSpace(genericTypesRef)) { method = method.MakeGenericMethod((Type[])ObjectRefToObject(JsonToObject<OBJECT>(genericTypesRef))); } var resolvedArgs = HydrateArguments(args); var refMap = resolvedArgs.Select(o => ObjetToObjectRef(o)).ToArray(); var rawRet = method.Invoke(instance, resolvedArgs); // 'out' and 'ref' params must be picked up if they changed. for (var i = 0; i < refMap.Length; ++i) { if (refMap[i] > -1) { _objects[refMap[i]] = resolvedArgs[i]; } } return DehydrateResult(rawRet, returnBoxed); } else { var property = type.GetField(methodName, BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance); if (property != null) { if (parameters.Length == 0) { return DehydrateResult(property.GetValue(instance), returnBoxed); } else if (parameters.Length == 1) { property.SetValue(instance, parameters[0]); return null; } } throw new InvalidOperationException("DotNetBridge.Call: Didn't find method or field: m:" + methodName + " o:" + objRef + " i:" + instance + " a:" + args); } }); } public string DescribeNamespace(string nameSpace) { return NoThrowBoundary(() => { var ret = new List<NamespaceInfo>(); var matchNamespaces = new HashSet<string>(); foreach (var type in GetLoadedAssemblies().SelectMany(a => a.GetTypes())) { if (type.FullName.Contains("<") || type.FullName.Contains("+")) { continue; }; if (type.FullName.StartsWith(nameSpace + ".")) { if (type.FullName.LastIndexOf('.') == nameSpace.Length) { ret.Add(new NamespaceInfo { Name = type.Name, IsType = true }); } else { matchNamespaces.Add(type.FullName.Substring(nameSpace.Length + 1, type.FullName.Substring(nameSpace.Length + 1).IndexOf("."))); } } } ret.AddRange(matchNamespaces.Select(namespaceName => new NamespaceInfo { Name = namespaceName, IsType = false })); return ret; }); } int ObjetToObjectRef(object o) { return _objects.ContainsValue(o) ? _objects.FirstOrDefault(x => x.Value == o).Key : -1; } object ObjectRefToObject(OBJECT o) { return _objects[o.Id]; } string NoThrowBoundary(Func<object> invoke) { try { return ObjectToJson(invoke()); } catch (Exception ex) { ex = ex.InnerException != null ? ex.InnerException : ex; return ObjectToJson(new ERROR { Message = ex.Message, Stack = ex.StackTrace }); } } DataContractJsonSerializer GetBridgeSerializer(Type type) { return new DataContractJsonSerializer(type, new DataContractJsonSerializerSettings { EmitTypeInformation = EmitTypeInformation.Always, KnownTypes = new Type[] { typeof(OBJECT), typeof(ERROR), typeof(MethodInfo), typeof(TypeInfo), typeof(NamespaceInfo) }, }); } T JsonToObject<T>(string json) { if (string.IsNullOrWhiteSpace(json)) { return default(T); } using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) { return (T)GetBridgeSerializer(typeof(T)).ReadObject(ms); } } string ObjectToJson(object o) { if (o == null) { return "null"; } using (var ms = new MemoryStream()) { GetBridgeSerializer(o.GetType()).WriteObject(ms, o); ms.Position = 0; return new StreamReader(ms).ReadToEnd(); } } object[] HydrateArguments(string args) { var resolved = JsonToObject<object[]>(args); for (var i = 0; i < resolved.Length; ++i) { if (resolved[i].GetType() == typeof(OBJECT)) { resolved[i] = ObjectRefToObject((OBJECT)resolved[i]); } else if (resolved[i].GetType() == typeof(decimal)) { resolved[i] = double.Parse(resolved[i].ToString()); } } return resolved; } object DehydrateResult(object output, bool returnOnlyObjects = false) { if (output == null || (!returnOnlyObjects && !output.GetType().GetTypeInfo().IsEnum && (output.GetType().GetTypeInfo().IsPrimitive || output.GetType() == typeof(string)))) { return output; } else { lock (_objects) { var objId = ++_lastObjectId; _objects.Add(objId, output); return new OBJECT { Id = objId }; } } } IEnumerable<Assembly> GetLoadedAssemblies() { #if NETFX_CORE return new Assembly[] { typeof(System.String).GetTypeInfo().Assembly }; #else return AppDomain.CurrentDomain.GetAssemblies(); #endif } Type FindTypeByName(string typeName) { Type type = GetLoadedAssemblies().Select(a => a.GetType(typeName)).FirstOrDefault(t => t != null); if (type == null) { throw new ApplicationException("Can't resolve typeName: " + typeName); } return type; } } }
using UnityEngine; using System.Collections; public class ThirdPersonCamera : MonoBehaviour { public bool lockCursor; public float mouseSensitivity = 10; public Transform target; public Vector2 pitchMinMax = new Vector2(-40, 85); public float ScrollSensitvity = 2f; public float ScrollDampening = 6f; public float _CameraDistance = 5f; public float rotationSmoothTime = .12f; Vector3 rotationSmoothVelocity; Vector3 currentRotation; float yaw; float pitch; void Start() { if (lockCursor) { Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } } void LateUpdate() { yaw += Input.GetAxis("Mouse X") * mouseSensitivity; pitch -= Input.GetAxis("Mouse Y") * mouseSensitivity; pitch = Mathf.Clamp(pitch, pitchMinMax.x, pitchMinMax.y); currentRotation = Vector3.SmoothDamp(currentRotation, new Vector3(pitch, yaw), ref rotationSmoothVelocity, rotationSmoothTime); transform.eulerAngles = currentRotation; transform.position = target.position - transform.forward * _CameraDistance; if (Input.GetAxis("Mouse ScrollWheel") != 0f) { float ScrollAmount = Input.GetAxis("Mouse ScrollWheel") * ScrollSensitvity; ScrollAmount *= (this._CameraDistance * 0.3f); this._CameraDistance += ScrollAmount * -1f; this._CameraDistance = Mathf.Clamp(this._CameraDistance, 1.5f, 4f); } } }
using Puppeteer.Core.WorldState; namespace Puppeteer.Core { public class PuppeteerGoal : SortableGoal<string, object> { public System.Guid DescriptionGUID { get; set; } } }
using System; using System.Threading.Tasks; using UBaseline.Shared.Node; using Uintra.Core.Activity; using Uintra.Core.Activity.Entities; using Uintra.Features.Comments.Links; using Uintra.Features.Comments.Models; using Uintra.Features.Events.Entities; using Uintra.Features.Groups.Links; using Uintra.Features.Groups.Services; using Uintra.Features.Links; using Uintra.Features.Notification.Configuration; using Uintra.Features.Notification.Entities; using Uintra.Infrastructure.Extensions; namespace Uintra.Infrastructure.Helpers { public class NotifierDataHelper : INotifierDataHelper { private readonly IActivityLinkService _linkService; private readonly ICommentLinkHelper _commentLinkHelper; private readonly IGroupService _groupService; private readonly IGroupLinkProvider _groupLinkProvider; const int MaxTitleLength = 100; public NotifierDataHelper( IActivityLinkService linkService, ICommentLinkHelper commentLinkHelper, IGroupService groupService, IGroupLinkProvider groupLinkProvider ) { _linkService = linkService; _commentLinkHelper = commentLinkHelper; _groupService = groupService; _groupLinkProvider = groupLinkProvider; } public CommentNotifierDataModel GetCommentNotifierDataModel(IIntranetActivity activity, CommentModel comment, Enum notificationType, Guid notifierId) { return new CommentNotifierDataModel { CommentId = comment.Id, NotificationType = notificationType, NotifierId = notifierId, Title = GetNotifierDataTitle(activity).TrimByWordEnd(MaxTitleLength), Url = _commentLinkHelper.GetDetailsUrlWithComment(activity.Id, comment.Id), IsPinned = activity.IsPinned, IsPinActual = activity.IsPinActual }; } public CommentNotifierDataModel GetCommentNotifierDataModel(INodeModel content, CommentModel comment, Enum notificationType, Guid notifierId) { return new CommentNotifierDataModel { CommentId = comment.Id, NotificationType = notificationType, NotifierId = notifierId, Title = content.Name, Url = _commentLinkHelper.GetDetailsUrlWithComment(content, comment.Id), IsPinned = false, IsPinActual = false }; } public ActivityNotifierDataModel GetActivityNotifierDataModel(IIntranetActivity activity, Enum notificationType, Guid notifierId) { return new ActivityNotifierDataModel { NotificationType = notificationType, ActivityType = activity.Type, Title = GetNotifierDataTitle(activity).TrimByWordEnd(MaxTitleLength), Url = _linkService.GetLinks(activity.Id).Details, NotifierId = notifierId, IsPinned = activity.IsPinned, IsPinActual = activity.IsPinActual }; } public LikesNotifierDataModel GetLikesNotifierDataModel(IIntranetActivity activity, Enum notificationType, Guid notifierId) { return new LikesNotifierDataModel { Title = GetNotifierDataTitle(activity).TrimByWordEnd(MaxTitleLength), NotificationType = notificationType, ActivityType = activity.Type, NotifierId = notifierId, CreatedDate = DateTime.UtcNow, Url = _linkService.GetLinks(activity.Id).Details, IsPinned = activity.IsPinned, IsPinActual = activity.IsPinActual }; } public ActivityReminderDataModel GetActivityReminderDataModel(IIntranetActivity activity, Enum activityType) { var model = new ActivityReminderDataModel { Url = _linkService.GetLinks(activity.Id).Details, Title = activity.Title, NotificationType = activityType, ActivityType = activity.Type, IsPinned = activity.IsPinned, IsPinActual = activity.IsPinActual }; if (activity.Type is IntranetActivityTypeEnum.Events) { var @event = (Event)activity; model.StartDate = @event.StartDate; } return model; } public GroupInvitationDataModel GetGroupInvitationDataModel( NotificationTypeEnum notificationType, Guid groupId, Guid notifierId, Guid receiverId) { var group = _groupService.Get(groupId); var groupRoomLink = _groupLinkProvider.GetGroupRoomLink(groupId); var groupInvitationDataModel = new GroupInvitationDataModel { Url = groupRoomLink, Title = group.Title, NotificationType = notificationType, GroupId = groupId, NotifierId = notifierId, ReceiverId = receiverId }; return groupInvitationDataModel; } public async Task<ActivityNotifierDataModel> GetActivityNotifierDataModelAsync(IIntranetActivity activity, Enum notificationType, Guid notifierId) { return new ActivityNotifierDataModel { NotificationType = notificationType, ActivityType = activity.Type, Title = GetNotifierDataTitle(activity).TrimByWordEnd(MaxTitleLength), Url = (await _linkService.GetLinksAsync(activity.Id))?.Details, NotifierId = notifierId, IsPinned = activity.IsPinned, IsPinActual = activity.IsPinActual }; } public async Task<ActivityReminderDataModel> GetActivityReminderDataModelAsync(IIntranetActivity activity, Enum notificationType) { var model = new ActivityReminderDataModel { Url = (await _linkService.GetLinksAsync(activity.Id))?.Details, Title = activity.Title, NotificationType = notificationType, ActivityType = activity.Type, IsPinned = activity.IsPinned, IsPinActual = activity.IsPinActual }; if (activity.Type is IntranetActivityTypeEnum.Events) { var @event = (Event)activity; model.StartDate = @event.StartDate; } return model; } public async Task<CommentNotifierDataModel> GetCommentNotifierDataModelAsync(IIntranetActivity activity, CommentModel comment, Enum notificationType, Guid notifierId) { return new CommentNotifierDataModel { CommentId = comment.Id, NotificationType = notificationType, NotifierId = notifierId, Title = GetNotifierDataTitle(activity).TrimByWordEnd(MaxTitleLength), Url = await _commentLinkHelper.GetDetailsUrlWithCommentAsync(activity.Id, comment.Id), IsPinned = activity.IsPinned, IsPinActual = activity.IsPinActual }; } public async Task<LikesNotifierDataModel> GetLikesNotifierDataModelAsync(IIntranetActivity activity, Enum notificationType, Guid notifierId) { return new LikesNotifierDataModel { Title = GetNotifierDataTitle(activity).TrimByWordEnd(MaxTitleLength), NotificationType = notificationType, ActivityType = activity.Type, NotifierId = notifierId, CreatedDate = DateTime.UtcNow, Url = (await _linkService.GetLinksAsync(activity.Id))?.Details, IsPinned = activity.IsPinned, IsPinActual = activity.IsPinActual }; } public async Task<GroupInvitationDataModel> GetGroupInvitationDataModelAsync(NotificationTypeEnum notificationType, Guid groupId, Guid notifierId, Guid receiverId) { return new GroupInvitationDataModel { Url = $"/groups/room?groupId={groupId}".ToLinkModel(), Title = (await _groupService.GetAsync(groupId))?.Title, NotificationType = notificationType, GroupId = groupId, NotifierId = notifierId, ReceiverId = receiverId }; } private static string GetNotifierDataTitle(IIntranetActivity activity) => activity.Type is IntranetActivityTypeEnum.Social ? activity.Description.StripHtml() : activity.Title; } }
using System; using System.Web.Mvc; using DevExpress.Web.Mvc; namespace DevExpress.Web.Demos { public partial class GridViewController : DemoController { public ActionResult InlineEditing() { return DemoView("InlineEditing", NorthwindDataProvider.GetEditableProducts()); } [ValidateInput(false)] public ActionResult InlineEditingPartial() { return PartialView("InlineEditingPartial", NorthwindDataProvider.GetEditableProducts()); } [HttpPost, ValidateInput(false)] public ActionResult InlineEditingAddNewPartial(EditableProduct product) { if(ModelState.IsValid) { try { NorthwindDataProvider.InsertProduct(product); } catch(Exception e) { ViewData["EditError"] = e.Message; } } else ViewData["EditError"] = "Please, correct all errors."; return PartialView("InlineEditingPartial", NorthwindDataProvider.GetEditableProducts()); } [HttpPost, ValidateInput(false)] public ActionResult InlineEditingUpdatePartial(EditableProduct product) { if(ModelState.IsValid) { try { NorthwindDataProvider.UpdateProduct(product); } catch(Exception e) { ViewData["EditError"] = e.Message; } } else ViewData["EditError"] = "Please, correct all errors."; return PartialView("InlineEditingPartial", NorthwindDataProvider.GetEditableProducts()); } [HttpPost, ValidateInput(false)] public ActionResult InlineEditingDeletePartial(int productID) { if(productID >= 0) { try { NorthwindDataProvider.DeleteProduct(productID); } catch(Exception e) { ViewData["EditError"] = e.Message; } } return PartialView("InlineEditingPartial", NorthwindDataProvider.GetEditableProducts()); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Presentation.QLBSX_BUS_WebService; /** * Tên Đề Tài; Phần Mền Quản Lý Biển Số Xe và Vi Phạm Giao Thông(VLNM (Vehicle license number management)) * Ho tên sinh viên: * 1. Phan Nhật Tiến 0812515 * 2. Huỳnh Công Toàn 0812527 * * GVHD. Trần Minh Triết **/ namespace Presentation { public partial class F_XoaLoiVP : Form { private QLBSX_BUS_WebServiceSoapClient ws = new QLBSX_BUS_WebServiceSoapClient(); public F_XoaLoiVP() { InitializeComponent(); } private void bntXoa_Click(object sender, EventArgs e) { if (cbbChiTiet.Text != "") { if (MessageBox.Show("Bạn có thật sự muốn xóa lỗi \"" + cbbChiTiet.Text + "\"?", "Hỏi", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { HanhViViPhamDTO hv = new HanhViViPhamDTO(); hv = ws.TraCuuHanhViTheoTenHanhVi(cbbChiTiet.Text); if (ws.VoHieuHoaHanhVi(hv)) { MessageBox.Show("Xóa lỗi \"" + cbbChiTiet.Text + "\" thành công.", "Thông báo", MessageBoxButtons.OK); cbbChiTiet.Refresh(); cbbChiTiet.Items.Remove(cbbChiTiet.Text); } else MessageBox.Show("Xóa lỗi \"" + cbbChiTiet.Text + "\" thất bại!", "Thông báo", MessageBoxButtons.OK); } } else { MessageBox.Show("Bạn chưa chọn \"Lỗi\" cần xóa.","Lỗi",MessageBoxButtons.OK); } } private void F_XoaHanhVi_Load(object sender, EventArgs e) { NapDanhSachLoi(cbbChiTiet); } private void bntThoat_Click(object sender, EventArgs e) { this.Close(); } private void NapDanhSachLoi(ComboBox cbb) { cbb.Items.Clear(); List<HanhViViPhamDTO> chiTiet = new List<HanhViViPhamDTO>(); chiTiet = ws.LayDanhSachHanhVi().ToList(); var query = from n in chiTiet where n.VoHieuHoa == false orderby n.TenHanhVi select n; foreach (var ct in query) cbb.Items.Add(ct.TenHanhVi); } private void panel3_Paint(object sender, PaintEventArgs e) { } } }
using System; using System.Collections.Generic; using Pe.Stracon.SGC.Infraestructura.Core.Base; using Pe.Stracon.SGC.Infraestructura.QueryModel.Contractual; using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General; namespace Pe.Stracon.SGC.Infraestructura.Core.QueryContract.Contractual { public interface IRequerimientoLogicRepository : IQueryRepository<RequerimientoLogic> { /// <summary> /// Metodo para listar los contrato por usuario. /// </summary> /// <param name="CodigoResponsable">Codigo de trabajador que consulta</param> /// <param name="UnidadOperativa">Código de Unidad Operativa</param> /// <param name="NombreProveedor">Nombre del proveedor</param> /// <param name="NumdocPrv">Número de documento del proveedor</param> /// <param name="TipoServicio">Tipo de Servicio</param> /// <param name="TipoReq">Tipo de Requerimiento</param> /// <param name="nombreEstadio">Nombre de Estadio</param> /// <param name="indicadorFinalizarAprobacion">Indicador de Finalizar Aprobación</param> /// <returns>Lista de bandeja de contratos</returns> List<RequerimientoLogic> ListaBandejaRequerimientos( Guid CodigoResponsable, Guid? UnidadOperativa, string NombreProveedor, string NumdocPrv, string TipoServicio, string TipoReq, string nombreEstadio, string indicadorFinalizarAprobacion); /// <summary> /// Metodo para listar las Observaciones por Requerimiento por Estadio. /// </summary> /// <param name="CodigoRequerimientoEstadio">Código de Requerimiento Estadio</param> /// <returns>Lista de bandeja de contratos por observaciones</returns> List<RequerimientoEstadioObservacionLogic> ListaBandejaRequerimientosObservacion(Guid CodigoRequerimientoEstadio); /// <summary> /// Metodo para listar las Consultas por Requerimiento por Estadio. /// </summary> /// <param name="CodigoRequerimientoEstadio">Código de Requerimiento Estadio</param> /// <returns>Lista de consultas por contrato</returns> List<RequerimientoEstadioConsultaLogic> ListaBandejaRequerimientosConsultas(Guid CodigoRequerimientoEstadio); /// <summary> /// Metodo para aprobar cada contrato según su estadío. /// </summary> /// <param name="codigoRequerimientoEstadio">Código de Requerimiento Estadío</param> /// <param name="codigoIdentificacionUO">Código de Identificación UO</param> /// <param name="UserUpdate">Usuario que actualiza</param> /// <param name="TerminalUpdate">Terminal desde donde se ejecuta.</param> /// <param name="codigoUsuarioCreacionRequerimiento">Código de Usuario de creación de contrato</param> /// <param name="MotivoAprobacion"></param> /// <returns>Lista de estadios aprobados</returns> int ApruebaRequerimientoEstadio(Guid codigoRequerimientoEstadio, string codigoIdentificacionUO, string UserUpdate, string TerminalUpdate, string codigoUsuarioCreacionRequerimiento, string MotivoAprobacion); /// <summary> /// Método para retornar los párrafos por contrato /// </summary> /// <param name="CodigoRequerimiento">Código de Requerimiento</param> /// <returns>Parrafos por contrato</returns> List<RequerimientoParrafoLogic> RetornaParrafosPorRequerimiento(Guid CodigoRequerimiento); /// <summary> /// Método que retorna los estadio del contrato para su observación. /// </summary> /// <param name="CodigoRequerimientoEstadio">Código del Estadío del Requerimiento</param> /// <returns>Estadios de contrato</returns> List<FlujoAprobacionEstadioLogic> RetornaEstadioRequerimientoObservacion(Guid CodigoRequerimientoEstadio); /// <summary> /// Responder la Consulta que me han hecho /// </summary> /// <param name="codigoRequerimientoEstadioConsulta"></param> /// <param name="Respuesta"></param> /// <param name="UsuarioModificacion"></param> /// <param name="TerminalModificacion"></param> /// <returns></returns> int Responder_Consulta(Guid codigoRequerimientoEstadioConsulta, string Respuesta, string UsuarioModificacion,string TerminalModificacion); /// <summary> /// Método para generar un nuevo Estadio de contrato cada vez que es observado. /// </summary> /// <param name="codigoRequerimientoEstadioObservado">Código de Requerimiento Estadio Observado</param> /// <param name="codigoRequerimiento"> Código de Requerimiento </param> /// <param name="codigoFlujoEstadioRetorno">Código Flujo Estadio Retorno </param> /// <param name="codigoResponsable">Código de Responsable </param> /// <param name="UserUpdate">Usuario que actualiza</param> /// <param name="TerminalUpdate">Terminal desde donde de actualiza</param> /// <returns>Estadios de contrato segun observación</returns> int ObservaEstadioRequerimiento(Guid codigoRequerimientoEstadio, Guid codigoRequerimientoEstadioObservado, Guid codigoRequerimiento, Guid codigoFlujoEstadioRetorno, Guid codigoResponsable, string UserUpdate, string TerminalUpdate); /// <summary> /// Método que retorna los responsable por flujo de aprobación. /// </summary> /// <param name="codigoFlujoAprobacion">código del flujo de aprobación.</param> /// <param name="codigoRequerimiento"></param> /// <returns>Responsable del flujo del estadio</returns> List<TrabajadorResponse> RetornaResponsablesFlujoEstadio(Guid codigoFlujoAprobacion, Guid codigoRequerimiento); /// <summary> /// Método para listar los documentos de l bandeja de solicitud. /// </summary> /// <param name="NumeroRequerimiento">número del contrato</param> /// <param name="UnidadOperativa">unidad operativa</param> /// <param name="NombreProveedor">nombre del proveedor</param> /// <param name="NumdocPrv">numero documento del proveedor</param> /// <returns>Documentos de la bandeja de solicitud</returns> List<RequerimientoLogic> ListaBandejaSolicitudRequerimientos(string NumeroRequerimiento, Guid? UnidadOperativa, string NombreProveedor, string NumdocPrv); /// <summary> /// Método para retornar los documentos PDf por Requerimiento /// </summary> /// <param name="CodigoRequerimiento">Código de Requerimiento</param> /// <returns>Documentos pdf por contrato</returns> List<RequerimientoDocumentoLogic> DocumentosPorRequerimiento(Guid CodigoRequerimiento); /// <summary> /// Metodo para cargar un Archivo a un estadio de contrato. /// </summary> /// <param name="objLogic">Objeto Requerimiento Documento Logic</param> /// <param name="User">Usuario que ejecuta la transaccion</param> /// <param name="Terminal">Terminal desde donde se ejecuta la transaccion</param> /// <returns>Indicador con el resultado de la operación</returns> int RegistraRequerimientoDocumentoCargaArchivo(RequerimientoDocumentoLogic objLogic, string User, string Terminal); /// <summary> /// Método para retornar registros de Requerimiento Documento /// </summary> /// <param name="CodigoRequerimiento">Llave primaria código contrato</param> /// <returns>Lista de registros</returns> List<RequerimientoDocumentoLogic> ListarRequerimientoDocumento(Guid CodigoRequerimiento); /// <summary> /// Lista los Estadios de los Requerimientos /// </summary> /// <param name="codigoRequerimientoEstadio">Codigo de Requerimiento Estadio</param> /// <param name="codigoRequerimiento">Código de contrato</param> /// <param name="codigoFlujoAprobEsta">Código de flujo de aprobación</param> /// <param name="fechaIngreso">Fecha de ingreso</param> /// <param name="fechaFinaliz">Fecha de finalización</param> /// <param name="codigoResponsable">Código de responsable</param> /// <param name="codigoEstadoRequerimientoEst">Código de Estados de Requerimiento Estadio</param> /// <param name="fechaPrimera">Fecha de primera notificación</param> /// <param name="fechaUltima">Fecha de última notificación</param> /// <param name="PageNumero">número de página</param> /// <param name="PageSize">tamaño por página</param> /// <returns>Estadios de los contratos</returns> List<RequerimientoEstadioLogic> ListarRequerimientoEstadio(Guid? codigoRequerimientoEstadio = null, Guid? codigoRequerimiento = null, Guid? codigoFlujoAprobEsta = null, DateTime? fechaIngreso = null, DateTime? fechaFinaliz = null, Guid? codigoResponsable = null, string codigoEstadoRequerimientoEst = null, DateTime? fechaPrimera = null, DateTime? fechaUltima = null, int PageNumero = 1, int PageSize = -1); /// <summary> /// Método para retornar las unidades operativas del responsable. /// </summary> /// <param name="codigoTrabajador">Código del Trabjador</param> /// <returns>Lista de registros</returns> List<UnidadOperativaLogic> ListarUnidadOperativaResponsable(Guid codigoTrabajador); /// <summary> /// Retorna el participante y el codigo del flujo de aprobacion anterior del contrato estadio. /// </summary> /// <param name="codigoRequerimientoEstadio">Codigo de Requerimiento Estadio</param> /// <param name="codigoRequerimiento">Código de contrato</param> /// <returns>Participante y el código del flujo de aprobación</returns> List<FlujoAprobacionParticipanteLogic> EstadoAnteriorRequerimientoEstadio(Guid codigoRequerimientoEstadio, Guid codigoRequerimiento); /// <summary> /// Notifica las acciones de contratos. /// </summary> /// <param name="asunto">Asunto de la notificación</param> /// <param name="textoNotificar">contenido de la notificación</param> /// <param name="cuentaNotificar">cuentas destino a notificar</param> /// <param name="cuentaCopias">cuentas de copia del correo</param> /// <param name="profileCorreo">profile de la configuración de correo</param> /// <returns>Acciones del contrato</returns> int NotificaBandejaRequerimientos(string asunto, string textoNotificar, string cuentaNotificar, string cuentaCopias, string profileCorreo); /// <summary> /// Retorna los parámetros necesarios para enviar la notificación /// </summary> /// <param name="codigoRequerimientoEstadio">Código de Requerimiento estadio</param> /// <param name="TipoNotificacion">Tipo de notificación</param> /// <returns>Parametros necesarios para enviar la notifación</returns> List<RequerimientoEstadioLogic> InformacionNotificacionRequerimientoEstadio(Guid codigoRequerimientoEstadio, string TipoNotificacion); /// <summary> /// Listado de contratos por estadio responsable /// </summary> /// <param name="codigoRequerimiento">Código de contrato</param> /// <returns>Listado de contrato estadio</returns> List<RequerimientoEstadioLogic> ListadoRequerimientoEstadioResponsable(Guid codigoRequerimiento); /// <summary> /// Registrar adenda con contrato vencido /// </summary> /// <param name="unidadOperativa">Código Unidad Operativa</param> /// <param name="numeroRequerimiento">Número contrato</param> /// <param name="descripcion">Descripción</param> /// <param name="numeroAdenda">Número de adenda</param> /// <param name="numeroAdendaConcatenado">Número de adenda concatenado</param> /// <returns>Registro de adenda en tabla temporal</returns> int RegistraAdendaRequerimientoVencido(Guid unidadOperativa, string numeroRequerimiento, string descripcion, int numeroAdenda, string numeroAdendaConcatenado); /// <summary> /// Método para listar los contrato por usuario. /// </summary> /// <param name="CodigoResponsable">Codigo de trabajador que consulta</param> /// <param name="UnidadOperativa">Código de Unidad Operativa</param> /// <param name="NombreProveedor">Nombre del proveedor</param> /// <param name="NumdocPrv">Número de documento del proveedor</param> /// <param name="TipoServicio">Tipo de Servicio</param> /// <param name="TipoReq">Tipo de Requerimiento</param> /// <param name="nombreEstadio">Nombre de estadio</param> /// <param name="indicadorFinalizarAprobacion">Indicador de finalizar aprobación</param> /// <param name="columnaOrden">Columna para ordenar</param> /// <param name="tipoOrden">Tipo de ordenamiento</param> /// <param name="numeroPagina">Número de página</param> /// <param name="registroPagina">Número de registros por página</param> /// <returns>Lista de bandeja de contratos</returns> List<RequerimientoLogic> ListaBandejaRequerimientosOrdenado( Guid CodigoResponsable, Guid? UnidadOperativa, string NombreProveedor, string NumdocPrv, string TipoServicio, string TipoReq, string nombreEstadio, string indicadorFinalizarAprobacion, string columnaOrden, string tipoOrden, int numeroPagina, int registroPagina); /// <summary> /// Metodo para obtener el estadio de edición de un flujo de aprobación de un contrato /// </summary> /// <param name="codigoRequerimiento">Código contrato</param> /// <param name="codigoFlujoAprobacion">Código flujo de aprobación</param> /// <returns>Código de contrato estadio de edición</returns> Guid ObtenerRequerimientoEstadioEdicion(Guid codigoRequerimiento, Guid? codigoFlujoAprobacion); /// <summary> /// Metodo para obtener el responsable de edición de un estadio /// </summary> /// <param name="codigoRequerimientoEstadio">Código contrato estadio</param> /// <param name="codigoEstadioRetorno">Código estadio retorno</param> /// <param name="codigoResposable">Código responsale</param> /// <returns>Código responsable de estadio de edición</returns> Guid ObtenerResponsableRequerimientoEstadioEdicion(Guid codigoRequerimientoEstadio, Guid codigoEstadioRetorno, Guid codigoResposable); /// <summary> /// Método para obtener la empresa vinculada por proveedor /// </summary> /// <param name="codigoProveedor">Código de proveedor</param> /// <returns>Datos de empresa vinculada</returns> EmpresaVinculadaLogic ObtenerEmpresaVinculadaPorProveedor(Guid? codigoProveedor); /// <summary> /// Método para listar los contratos aprobados en la solicitud de modificación. /// </summary> /// <param name="NumeroRequerimiento">número del contrato</param> /// <param name="UnidadOperativa">unidad operativa</param> /// <param name="NombreProveedor">nombre del proveedor</param> /// <param name="NumdocPrv">numero documento del proveedor</param> /// <returns>Listado de contratos para revisión</returns> List<RequerimientoLogic> ListaBandejaRevisionRequerimientos(string NumeroRequerimiento, Guid? UnidadOperativa, string NombreProveedor, string NumdocPrv); /// <summary> /// AutoComplete Numero Requerimiento /// </summary> /// <param name="codigoUnidadOperativa"></param> /// <param name="numeroRequerimiento"></param> /// <param name="numeroPagina"></param> /// <param name="registroPagina"></param> /// <returns></returns> List<RequerimientoLogic> BuscarNumeroRequerimiento(Guid? codigoUnidadOperativa, string numeroRequerimiento, int numeroPagina, int registroPagina); /// <summary> /// Reporte Requerimiento Observado Aprobado /// </summary> /// <param name="codigoUnidadOperativa"></param> /// <param name="codigoRequerimiento"></param> /// <param name="tipoAccion"></param> /// <param name="fechaInicio"></param> /// <param name="fechaFin"></param> /// <param name="nombreBaseDatoPolitica"></param> /// <param name="numeroPagina"></param> /// <param name="registroPagina"></param> /// <returns></returns> List<RequerimientoObservadoAprobadoLogic> BuscarRequerimientoObservadoAprobado(Guid? codigoUnidadOperativa, Guid? codigoRequerimiento, string tipoAccion, DateTime? fechaInicio, DateTime? fechaFin, string nombreBaseDatoPolitica, int numeroPagina, int registroPagina); } }
using System.Collections.Generic; namespace TC.Internal { public interface ITracked { int Index { get; set; } } public abstract class Tracker<T> where T : class, ITracked { public static List<T> All = new List<T>(); public static void Register(T item) { item.Index = All.Count; All.Add(item); } public static void Deregister(T item) { if (item.Index == -1) { return; } //Update indices All[All.Count - 1].Index = item.Index; All[item.Index] = All[All.Count - 1]; All.RemoveAt(All.Count - 1); } } }
using EPI.Graphs.Algorithms; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace EPI.UnitTests.Graphs.Algorithms { [TestClass] public class TopologicalSortUnitTest { private AdjacencyListGraph graph; [TestInitialize] public void Setup() { graph = new AdjacencyListGraph(6); graph.AddEdge(5, 0, 1); graph.AddEdge(4, 0, 1); graph.AddEdge(4, 1, 1); graph.AddEdge(5, 2, 1); graph.AddEdge(2, 3, 1); graph.AddEdge(3, 1, 1); } [TestMethod] public void GetTopologicalSort() { TopologicalSort.GetTopologicalSortOrder(graph).ShouldBeEquivalentTo(new int[] {5,4,2,3,1,0}); } } }
using System; using System.Collections.Generic; namespace ITMakesSense.CSharp.Enumerations { public class Enumeration<TEnumeration, TValue> : IEquatable<Enumeration<TEnumeration, TValue>>, IComparable<Enumeration<TEnumeration, TValue>> where TEnumeration : Enumeration<TEnumeration, TValue> where TValue : IEquatable<TValue>, IComparable<TValue> { private static readonly Lazy<EnumerationCache<TEnumeration, TValue>> Cache; static Enumeration() { Cache = new Lazy<EnumerationCache<TEnumeration, TValue>>(EnumerationCache<TEnumeration, TValue>.Create); } public string Name { get; } public TValue Value { get; } public Enumeration(string name, TValue value) { Name = name; Value = value; } public static bool IsValueDefined(TValue value) => Cache.Value.Values.ContainsKey(value); public static bool IsNameDefined(string name) => Cache.Value.Names.ContainsKey(name); public static IEnumerable<TEnumeration> GetAll() => Cache.Value.All; public static IEnumerable<TValue> GetValues() => Cache.Value.Values.Keys; public static IEnumerable<string> GetNames() => Cache.Value.Names.Keys; public static TEnumeration FromName(string name) => Cache.Value.Names.ContainsKey(name) ? Cache.Value.Names[name] : default(TEnumeration); public static bool TryFromName(string name, out TEnumeration enumeration) { enumeration = FromName(name); return enumeration != null; } public static TEnumeration FromValue(TValue value) => Cache.Value.Values.ContainsKey(value) ? Cache.Value.Values[value] : default(TEnumeration); public static bool TryFromValue(TValue value, out TEnumeration enumeration) { enumeration = FromValue(value); return enumeration != null; } public static string GetName(TValue value) => Cache.Value.Values.ContainsKey(value) ? Cache.Value.Values[value].Name : default(string); public static bool TryGetName(TValue value, out string name) { name = GetName(value); return name != null; } public static Type GetUnderlyingType() => typeof(TValue); public override bool Equals(object obj) => obj is Enumeration<TEnumeration, TValue> other && Equals(other); public override int GetHashCode() => Value.GetHashCode(); public bool Equals(Enumeration<TEnumeration, TValue> other) => ReferenceEquals(this, other) || !(other is null) && Value.Equals(other.Value); public int CompareTo(Enumeration<TEnumeration, TValue> other) => Value.CompareTo(other.Value); public static bool operator ==(Enumeration<TEnumeration, TValue> left, Enumeration<TEnumeration, TValue> right) => left?.Equals(right) ?? right is null; public static bool operator !=(Enumeration<TEnumeration, TValue> left, Enumeration<TEnumeration, TValue> right) => !(left == right); public static bool operator <(Enumeration<TEnumeration, TValue> left, Enumeration<TEnumeration, TValue> right) => left.CompareTo(right) < 0; public static bool operator <=(Enumeration<TEnumeration, TValue> left, Enumeration<TEnumeration, TValue> right) => left.CompareTo(right) <= 0; public static bool operator >(Enumeration<TEnumeration, TValue> left, Enumeration<TEnumeration, TValue> right) => left.CompareTo(right) > 0; public static bool operator >=(Enumeration<TEnumeration, TValue> left, Enumeration<TEnumeration, TValue> right) => left.CompareTo(right) >= 0; public static implicit operator TValue(Enumeration<TEnumeration, TValue> enumeration) => enumeration.Value; public static explicit operator Enumeration<TEnumeration, TValue>(TValue value) => FromValue(value); } }
using UnityEngine; using System.Collections; using UnityEngine.UI; using System; public class LaserButtonClicker : MonoBehaviour { SteamVR_LaserPointer laserPointer; InteractiveObject targetObj; private int deviceIndex = -1; private SteamVR_Controller.Device controller; bool pointerOnButton = false; // Use this for initialization void Start() { laserPointer = GetComponent<SteamVR_LaserPointer>(); laserPointer.PointerIn += LaserPointer_PointerIn; laserPointer.PointerOut += LaserPointer_PointerOut; } private void SetDeviceIndex(int index) { deviceIndex = index; controller = SteamVR_Controller.Input(index); } private void LaserPointer_PointerOut(object sender, PointerEventArgs e) { if (targetObj != null) { Renderer[] renderers = targetObj.GetComponentsInChildren<Renderer>(); foreach (Renderer r in renderers) { r.material.shader = Shader.Find("Standard"); } pointerOnButton = false; targetObj = null; } } private void LaserPointer_PointerIn(object sender, PointerEventArgs e) { if (targetObj == null) { targetObj = e.target.gameObject.GetComponent<InteractiveObject>(); if (targetObj == null) { if (e.target.gameObject.transform.parent != null) { targetObj = e.target.gameObject.transform.parent.GetComponent<InteractiveObject>(); } } if (targetObj != null) { Renderer[] renderers = targetObj.GetComponentsInChildren<Renderer>(); foreach (Renderer r in renderers) { r.material.shader = Shader.Find("Self-Illumin/Outlined Diffuse"); } } pointerOnButton = true; } } void Update() { if (pointerOnButton) { if (controller.GetPressDown(Valve.VR.EVRButtonId.k_EButton_SteamVR_Trigger)) { targetObj.OnClicked(); } } } }
namespace GatewayEDI.Logging.Factories { /// <summary> A delegate that is used by the <see cref="DelegateFactory" /> in order to get a named log if its <see cref="DelegateFactory.GetLog(string)" /> method is being invoked. </summary> /// <returns> The log implementation that is being resolved based on the request. </returns> public delegate ILog LogRequestHandler(string logName); }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using Plus1.Models; namespace Plus1.Controllers { public class CategoriesController : Controller { private ApplicationDbContext db = new ApplicationDbContext(); // GET: Categories public ActionResult Index() { return View(db.Category.ToList()); } /*// GET: Categories/Details/5 public ActionResult Details(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Category category = db.Category.Find(id); if (category == null) { return HttpNotFound(); } return View(category); }*/ public ActionResult Details(string id) { Category category = db.Category.Find(id); if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } if (category == null) { return HttpNotFound(); } var viewModel = new CategoryViewModel(); List<Category> Cats = new List<Category>(); Cats.Add(category); viewModel.Products = new List<Product>(); foreach (Product p in db.Products.Where(c => c.Category == category.Name)) { p.Price = p.Price / 100; viewModel.Products.Add(p); } /* List<SubSubCategory> Dogs = new List<SubSubCategory>(); Dogs.Add(subsubcategory); viewModel.SubSubCategory = Dogs; viewModel.Products = new List<Product>(); foreach (Product p in db.Products.Where(c => c.SubSubcategory == SubSubcategory.Name).Take(100)) { p.Price = p.Price / 100; viewModel.Products.Add(p); }*/ //viewModel.Products = db.Products.Where(c => c.Category == category.Name).ToList(); viewModel.Category = Cats; viewModel.SubCategory = db.SubCategory.Where(c => c.ParentName == category.Name).Take(20).ToList(); return View(viewModel); } public ActionResult SubDetails(string id) { Category category = db.Category.Find(id); if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } if (category == null) { return HttpNotFound(); } var viewModel = new CategoryViewModel(); List<Category> Cats = new List<Category>(); Cats.Add(category); viewModel.Products = db.Products.Take(100).ToList(); viewModel.Category = Cats; viewModel.SubCategory = db.SubCategory.Where(c => c.ParentName == category.Name).Take(20).ToList(); return View(viewModel); } // GET: Categories/Create public ActionResult Create() { return View(); } // POST: Categories/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "Name")] Category category) { if (ModelState.IsValid) { db.Category.Add(category); db.SaveChanges(); return RedirectToAction("Index"); } return View(category); } // GET: Categories/Edit/5 public ActionResult Edit(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Category category = db.Category.Find(id); if (category == null) { return HttpNotFound(); } return View(category); } // POST: Categories/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "Name")] Category category) { if (ModelState.IsValid) { db.Entry(category).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(category); } // GET: Categories/Delete/5 public ActionResult Delete(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Category category = db.Category.Find(id); if (category == null) { return HttpNotFound(); } return View(category); } // POST: Categories/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(string id) { Category category = db.Category.Find(id); db.Category.Remove(category); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Welic.Dominio.Models.Marketplaces.Entityes { [MetadataType(typeof(ContentPageMetaData))] public partial class ContentPage { [NotMapped] public string Author { get; set; } } public class ContentPageMetaData { [DataType(DataType.MultilineText)] public string Html { get; set; } } }
using Shiftgram.Core.Models; using Shiftgram.Core.Strategy; using System.Collections.Generic; using System.Threading.Tasks; namespace Shiftgram.Core.Repository { public interface IAccountRepository: IRepository<Account>, IUpdatableAccount { Task<IEnumerable<Account>> GetAll(); Task<Account> GetByPhone(string phone); ShiftgramContext Context { get; } IUpdatableAccount Updatable { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EBS.Domain.ValueObject { public enum SaleOrderStatus { [Description("作废")] Cancel = -1, [Description("初始")] Create = 1, [Description("待支付")] WaitPaid = 2, [Description("已支付")] Paid = 3 } public enum PaidStatus { [Description("作废")] Cancel = -1, [Description("初始")] Create = 1, [Description("待支付")] WaitPaid = 2, [Description("已支付")] Paid = 3 } public enum PaymentWay { [Description("现金")] Cash = 1, [Description("支付宝")] AliPay = 2, [Description("微信支付")] WechatPay = 3, /// <summary> /// 支付宝扫码支付: 客户扫我的支付码 /// </summary> [Description("支付宝扫码")] AliPayScan = 4, /// <summary> /// 微信扫码支付: 客户扫我的支付码 /// </summary> [Description("微信扫码")] WechatScan = 5 } }
using SocialWorld.Entities.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SocialWorld.DataAccess.Interfaces { public interface IAppRoleDal : IGenericDal<AppRole> { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class OK_LaserMove : MonoBehaviour { public float fl_speed; public GameObject mGO_Ship; public Vector3 V3_ShipPos; // Use this for initialization void Start () { mGO_Ship = GameObject.FindGameObjectWithTag("ShipAll"); V3_ShipPos = mGO_Ship.transform.position; } // Update is called once per frame void Update () { float step = fl_speed * Time.deltaTime; transform.position = Vector3.MoveTowards(transform.position,V3_ShipPos, step); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.PlatformAbstractions; using Wee.UI.Core.Registers; using Wee.Common.Contracts; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Mvc; namespace Wee.UI.Core { /// <summary> /// /// </summary> public static class RegisterExtensions { /// <summary> /// /// </summary> /// <param name="app"></param> /// <param name="folderPath"></param> /// <returns></returns> public static IApplicationBuilder WeeRegisterPackages(this IApplicationBuilder app, string folderPath = "") { if (string.IsNullOrWhiteSpace(folderPath)) folderPath = PlatformServices.Default.Application.ApplicationBasePath; var instance = new StaticFilesRegister(app, folderPath); instance.Invoke<IWeePackage>(); var menuInstance = new MenuRegister(app, folderPath); menuInstance.Invoke<Controller>(); return app; } /// <summary> /// /// </summary> /// <param name="services"></param> /// <param name="folderPath"></param> /// <returns></returns> public static IServiceCollection WeeRegisterPackages(this IServiceCollection services, string folderPath = "") { if (string.IsNullOrWhiteSpace(folderPath)) folderPath = PlatformServices.Default.Application.ApplicationBasePath; var razorViewInstance = new RazorViewFileProvidersRegister(services, folderPath); razorViewInstance.Invoke<IWeePackage>(); var themeInstance = new ThemeRegister(services, folderPath); themeInstance.Invoke<IWeePackage>(); return services; } } }
using Autofac; using SSW.RulesSearchCore.ConsoleRunner.Commands; using SSW.RulesSearchCore.Data.SharePoint; using SSW.RulesSearchCore.Elastic; namespace SSW.RulesSearchCore.ConsoleRunner { public static class AutofacContainerFactory { public static IContainer CreateContainer() { var builder = new ContainerBuilder(); builder.RegisterModule(new SharePointModule(new SharePointClientConfig() { Url = ConfigSettings.SharePointUrl })); builder.RegisterModule(new ElasticSearchModule(new ElasticSearchSettings() { Url = ConfigSettings.ElasticSearchUrl })); builder.RegisterType<NestIndexer>() .Named<ICommand>(typeof(NestIndexer).Name) .As<ICommand>(); return builder.Build(); } } }
using System.Collections.Generic; using Newtonsoft.Json; namespace BieProduccion.Models { public class OrdersResponse { [JsonProperty("ordenProduccion")] public List<OrdenProduccion> OrdenProduccion { get; set; } } }
using gView.Framework.Carto; using gView.Framework.Geometry; using gView.Framework.IO; using gView.Framework.Symbology.UI; using gView.Framework.system; using gView.Framework.UI; using gView.GraphicsEngine; using gView.GraphicsEngine.Abstraction; using System.ComponentModel; using System.Reflection; namespace gView.Framework.Symbology { [gView.Framework.system.RegisterPlugIn("1496A1A8-8087-4eba-86A0-23FB91197B22")] public sealed class SimpleFillSymbol : LegendItem, IFillSymbol, IPropertyPage, IPenColor, IBrushColor, IPenWidth, IPenDashStyle { private IBrush _brush; private ArgbColor _color; private ISymbol _outlineSymbol = null; public SimpleFillSymbol() { _color = ArgbColor.Red; _brush = Current.Engine.CreateSolidBrush(_color); } private SimpleFillSymbol(ArgbColor color) { _color = color; _brush = Current.Engine.CreateSolidBrush(_color); } ~SimpleFillSymbol() { this.Release(); } [Browsable(true)] [Category("Fill Symbol")] [UseColorPicker()] public ArgbColor Color { get { return _color; } set { _brush.Color = value; _color = value; } } [Browsable(true)] [DisplayName("Symbol")] [Category("Outline Symbol")] [UseLineSymbolPicker()] public ISymbol OutlineSymbol { get { return _outlineSymbol; } set { _outlineSymbol = value; } } [Browsable(true)] [DisplayName("Smoothingmode")] [Category("Outline Symbol")] public SymbolSmoothing SmoothingMode { get { if (_outlineSymbol is Symbol) { return ((Symbol)_outlineSymbol).Smoothingmode; } return SymbolSmoothing.None; } set { if (_outlineSymbol is Symbol) { ((Symbol)_outlineSymbol).Smoothingmode = value; } } } [Browsable(true)] [DisplayName("Color")] [Category("Outline Symbol")] //[Editor(typeof(gView.Framework.UI.ColorTypeEditor), typeof(System.Drawing.Design.UITypeEditor))] [UseColorPicker()] public ArgbColor OutlineColor { get { return PenColor; } set { PenColor = value; } } [Browsable(true)] [DisplayName("DashStyle")] [Category("Outline Symbol")] //[Editor(typeof(gView.Framework.UI.DashStyleTypeEditor), typeof(System.Drawing.Design.UITypeEditor))] [UseDashStylePicker()] public LineDashStyle OutlineDashStyle { get { return PenDashStyle; } set { PenDashStyle = value; } } [Browsable(true)] [Category("Outline Symbol")] [DisplayName("Width")] //[Editor(typeof(gView.Framework.UI.PenWidthTypeEditor), typeof(System.Drawing.Design.UITypeEditor))] [UseWidthPicker()] public float OutlineWidth { get { return PenWidth; } set { PenWidth = value; } } public bool SupportsGeometryType(GeometryType geomType) => geomType == GeometryType.Polygon; #region IFillSymbol Member public void FillPath(IDisplay display, IGraphicsPath path) { if (_outlineSymbol == null || this.OutlineColor.IsTransparent) { display.Canvas.SmoothingMode = (SmoothingMode)this.SmoothingMode; } if (!_color.IsTransparent) { display.Canvas.FillPath(_brush, path); } display.Canvas.SmoothingMode = GraphicsEngine.SmoothingMode.None; //if (_outlineSymbol != null) //{ // if (_outlineSymbol is ILineSymbol) // { // ((ILineSymbol)_outlineSymbol).DrawPath(display, path); // } // else if (_outlineSymbol is SymbolCollection) // { // foreach (SymbolCollectionItem item in ((SymbolCollection)_outlineSymbol).Symbols) // { // if (!item.Visible) continue; // if (item.Symbol is ILineSymbol) // { // ((ILineSymbol)item.Symbol).DrawPath(display, path); // } // } // } //} } #endregion #region ISymbol Member public void Draw(IDisplay display, IGeometry geometry) { var gp = DisplayOperations.Geometry2GraphicsPath(display, geometry); if (gp != null) { this.FillPath(display, gp); if (!this.OutlineColor.IsTransparent) { SimpleFillSymbol.DrawOutlineSymbol(display, _outlineSymbol, geometry, gp); } gp.Dispose(); gp = null; } } public void Release() { if (_brush != null) { _brush.Dispose(); _brush = null; } if (_outlineSymbol != null) { _outlineSymbol.Release(); } } [Browsable(false)] public string Name { get { return "Fill Symbol"; } } #endregion #region IPropertyPage Member public object PropertyPageObject() { return null; } public object PropertyPage(object initObject) { string appPath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); Assembly uiAssembly = Assembly.LoadFrom(appPath + @"/gView.Win.Symbology.UI.dll"); IPropertyPanel p = uiAssembly.CreateInstance("gView.Framework.Symbology.UI.PropertyForm_SimpleFillSymbol") as IPropertyPanel; if (p != null) { return p.PropertyPanel(this); } return null; } #endregion #region IPersistable Member new public void Load(IPersistStream stream) { base.Load(stream); this.Color = ArgbColor.FromArgb((int)stream.Load("color", ArgbColor.Red.ToArgb())); _outlineSymbol = (ISymbol)stream.Load("outlinesymbol"); } new public void Save(IPersistStream stream) { base.Save(stream); stream.Save("color", this.Color.ToArgb()); if (_outlineSymbol != null) { stream.Save("outlinesymbol", _outlineSymbol); } } #endregion #region IClone2 public object Clone(CloneOptions options) { var display = options?.Display; if (display == null) { return Clone(); } SimpleFillSymbol fSym = new SimpleFillSymbol(_brush.Color); if (_outlineSymbol != null) { fSym._outlineSymbol = (ISymbol)_outlineSymbol.Clone(options); } fSym.LegendLabel = _legendLabel; //fSym.Smoothingmode = this.Smoothingmode; return fSym; } #endregion #region IPenColor Member [Browsable(false)] public ArgbColor PenColor { get { if (_outlineSymbol is IPenColor) { return ((IPenColor)_outlineSymbol).PenColor; } return ArgbColor.Transparent; } set { if (_outlineSymbol is IPenColor) { ((IPenColor)_outlineSymbol).PenColor = value; } } } #endregion #region IBrushColor Member [Browsable(false)] public ArgbColor FillColor { get { return this.Color; } set { this.Color = value; } } #endregion #region IPenWidth Member [Browsable(false)] public float PenWidth { get { if (_outlineSymbol is IPenWidth) { return ((IPenWidth)_outlineSymbol).PenWidth; } return 0; } set { if (_outlineSymbol is IPenWidth) { ((IPenWidth)_outlineSymbol).PenWidth = value; } } } [Browsable(false)] public DrawingUnit PenWidthUnit { get { if (_outlineSymbol is IPenWidth) { return ((IPenWidth)_outlineSymbol).PenWidthUnit; } return DrawingUnit.Pixel; } set { if (_outlineSymbol is IPenWidth) { ((IPenWidth)_outlineSymbol).PenWidthUnit = value; } } } [Browsable(true)] [Category("Reference Scaling")] [UseWidthPicker()] public float MaxPenWidth { get { if (_outlineSymbol is IPenWidth) { return ((IPenWidth)_outlineSymbol).MaxPenWidth; } return 0f; } set { if (_outlineSymbol is IPenWidth) { ((IPenWidth)_outlineSymbol).MaxPenWidth = value; } } } [Browsable(true)] [Category("Reference Scaling")] [UseWidthPicker()] public float MinPenWidth { get { if (_outlineSymbol is IPenWidth) { return ((IPenWidth)_outlineSymbol).MinPenWidth; } return 0f; } set { if (_outlineSymbol is IPenWidth) { ((IPenWidth)_outlineSymbol).MinPenWidth = value; } } } #endregion #region IPenDashStyle Member [Browsable(false)] public LineDashStyle PenDashStyle { get { if (_outlineSymbol is IPenDashStyle) { return ((IPenDashStyle)_outlineSymbol).PenDashStyle; } return LineDashStyle.Solid; } set { if (_outlineSymbol is IPenDashStyle) { ((IPenDashStyle)_outlineSymbol).PenDashStyle = value; } } } #endregion public static void DrawOutlineSymbol(IDisplay display, ISymbol outlineSymbol, IGeometry geometry, IGraphicsPath gp) { #region Überprüfen auf dash!!! if (outlineSymbol != null) { bool isDash = false; if (outlineSymbol is IPenDashStyle && ((IPenDashStyle)outlineSymbol).PenDashStyle != LineDashStyle.Solid) { isDash = true; } else if (outlineSymbol is SymbolCollection) { foreach (SymbolCollectionItem item in ((SymbolCollection)outlineSymbol).Symbols) { if (item.Symbol is IPenDashStyle && ((IPenDashStyle)item.Symbol).PenDashStyle != LineDashStyle.Solid) { isDash = true; } } } if (isDash) { if (geometry is IPolygon) { outlineSymbol.Draw(display, new Polyline((IPolygon)geometry)); } else { outlineSymbol.Draw(display, geometry); } } else { if (outlineSymbol is ILineSymbol) { ((ILineSymbol)outlineSymbol).DrawPath(display, gp); } else if (outlineSymbol is SymbolCollection) { foreach (SymbolCollectionItem item in ((SymbolCollection)outlineSymbol).Symbols) { if (!item.Visible) { continue; } if (item.Symbol is ILineSymbol) { ((ILineSymbol)item.Symbol).DrawPath(display, gp); } } } } } #endregion } #region ISymbol Member [Browsable(false)] public SymbolSmoothing SymbolSmothingMode { set { if (_outlineSymbol != null) { _outlineSymbol.SymbolSmothingMode = value; } } } public bool RequireClone() { return _outlineSymbol != null && _outlineSymbol.RequireClone(); } #endregion } }
using System; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using WindowsUpdateNotifier.Versioning; namespace WindowsUpdateNotifier { public class VersionHelper : IVersionHelper { public VersionHelper() { var info = FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location); CurrentVersion = info.ProductVersion; Copyright = info.LegalCopyright; } public void SearchForNewVersion(Action onFinishedCallback) { var scheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext(); Task.Factory.StartNew(() => { var rdr = new RssVersionReader(); var items = rdr.Execute(); LatestVersion = items.OrderByDescending(x => x.Version).FirstOrDefault(); IsNewVersionAvailable = LatestVersion != null && string.Compare(LatestVersion.Version, CurrentVersion, StringComparison.Ordinal) > 0; }) .ContinueWith(x => onFinishedCallback(), scheduler); } public string Copyright { get; private set; } public string CurrentVersion { get; private set; } public RssVersionItem LatestVersion { get; private set; } public bool IsNewVersionAvailable { get; private set; } } }
using NStandard.Caching; using NStandard.Diagnostics; using System; using System.Linq; using System.Threading; using Xunit; namespace NStandard.Test { public class CacheTests { [Fact] public void Test1() { var cache = new Cache<DateTime> { CacheMethod = () => DateTime.Now, UpdateExpirationMethod = cacheTime => cacheTime.Add(TimeSpan.FromSeconds(1)), }; var updateCount = 0; cache.OnCacheUpdated += (cacheTime, value) => updateCount += 1; var report = Concurrency.Run(id => { var value = cache.Value; Console.WriteLine($"{id}\t{cache}"); Thread.Sleep(500); return value; }, 20); var reportUpdate = report.Results.Select(x => x.Return).Distinct().Count(); Assert.Equal(updateCount, reportUpdate); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public static class CacheManager { public static void CachePrefabs(out Queue<GameObject> queue, int collectionSize, GameObject prefab) { queue = new Queue<GameObject>(collectionSize); for ( int i = 0; i < collectionSize; i++ ) { GameObject instantiantedPrefab = (GameObject) MonoBehaviour.Instantiate(prefab, Vector3.zero, new Quaternion()); instantiantedPrefab.SetActive(false); queue.Enqueue(instantiantedPrefab); } } public static GameObject SpawnNewGameObject(Queue<GameObject> queue, Vector3 position, Quaternion rotation) { GameObject gameObject = queue.Dequeue(); ResetGameObjectState(gameObject, position, rotation); gameObject.SetActive(true); queue.Enqueue(gameObject); return gameObject; } public static GameObject SpawnNewGameObject(Queue<GameObject> queue, Vector3 position, Quaternion rotation, int layer) { GameObject gameObject = SpawnNewGameObject(queue, position, rotation); ChangeLayers(gameObject, layer); return gameObject; } public static GameObject DeSpawnGameObject(GameObject gameObject) { gameObject.transform.position = Vector3.zero; Rigidbody rigidbody = gameObject.GetComponent<Rigidbody>(); if ( rigidbody != null ) { rigidbody.velocity = Vector3.zero; rigidbody.angularVelocity = Vector3.zero; rigidbody.useGravity = false; rigidbody.isKinematic = true; } Collider collider = gameObject.GetComponent<Collider>(); if ( collider != null ) { collider.enabled = false; } Renderer[] meshes = gameObject.GetComponentsInChildren<Renderer>(); for ( int i = 0; i < meshes.Length; i++ ) { meshes[i].enabled = false; } NavMeshAgent agent = gameObject.GetComponent<NavMeshAgent>(); if ( agent != null ) { agent.enabled = false; } Animator anim = gameObject.GetComponent<Animator>(); if ( anim != null ) { anim.Stop(); anim.enabled = false; } MonoBehaviour[] scripts = gameObject.GetComponentsInChildren<MonoBehaviour>(); for ( int i = 0; i < scripts.Length; i++ ) { scripts[i].enabled = false; } return gameObject; } public static GameObject DeSpawnGameObject(GameObject gameObject, int layer) { gameObject = DeSpawnGameObject(gameObject); ChangeLayers(gameObject, layer); return gameObject; } private static void ResetGameObjectState(GameObject gameObject, Vector3 position, Quaternion rotation) { gameObject.transform.position = position; gameObject.transform.rotation = rotation; Rigidbody rigidbody = gameObject.GetComponent<Rigidbody>(); if ( rigidbody != null ) { rigidbody.velocity = Vector3.zero; rigidbody.angularVelocity = Vector3.zero; rigidbody.Sleep(); rigidbody.useGravity = true; rigidbody.isKinematic = false; } Collider collider = gameObject.GetComponent<Collider>(); if ( collider != null ) { collider.enabled = true; } Renderer[] meshes = gameObject.GetComponentsInChildren<Renderer>(); for ( int i = 0; i < meshes.Length; i++ ) { meshes[i].enabled = true; } NavMeshAgent agent = gameObject.GetComponent<NavMeshAgent>(); if ( agent != null ) { agent.enabled = true; } Animator anim = gameObject.GetComponent<Animator>(); if ( anim != null ) { anim.enabled = true; } MonoBehaviour[] scripts = gameObject.GetComponentsInChildren<MonoBehaviour>(); for ( int i = 0; i < scripts.Length; i++ ) { scripts[i].enabled = true; } gameObject.SetActive(true); } private static void ChangeLayers(GameObject gameObject, int layer) { gameObject.layer = layer; foreach ( Transform child in gameObject.transform ) { ChangeLayers(child.gameObject, layer); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using MVCRoleTop.Models; using MVCRoleTop.Repositories; using MVCRoleTop.ViewModel; namespace MVCRoleTop.Controllers { public class ClienteController : AbstractController { EventoRepository eventorepository = new EventoRepository(); public IActionResult Index() { switch(ObterUsuarioNomeSession()) { case "Admin": return RedirectToAction("Dashboard","Administrador"); case "": return RedirectToAction("index","Home"); default: ClienteViewModel clienteviewmodel = new ClienteViewModel(ObterUsuarioNomeSession()); clienteviewmodel.Eventos = eventorepository.ObterEventosCliente(ObterUsuarioNomeSession()); return View(clienteviewmodel); } } public IActionResult CriarEvento() { switch(ObterUsuarioNomeSession()) { case "Admin": return RedirectToAction("Dashboard","Administrador"); case "": return RedirectToAction("index","Home"); default: ClienteViewModel clienteviewmodel = new ClienteViewModel(ObterUsuarioNomeSession()); return View(clienteviewmodel); } } public IActionResult Logoff() { HttpContext.Session.Remove(SESSION_CLIENTE_NOME); return RedirectToAction("index","Home"); } [HttpPost] public IActionResult CriarEvento(IFormCollection form) { try { Evento evento = new Evento( form["NomeDoEvento"], DateTime.Parse(form["DataDoEvento"]), form["Pacote"], int.Parse(form["QuantidadeDePessoas"]) ); evento.DonoDoEvento = ObterUsuarioNomeSession(); eventorepository.Inserir(evento); return RedirectToAction("index","Cliente"); }catch(Exception e) { return View("Erro"); } } } }
using Alabo.Data.People.Circles.Domain.Entities; using Alabo.Domains.Repositories; using MongoDB.Bson; namespace Alabo.Data.People.Circles.Domain.Repositories { public interface ICircleRepository : IRepository<Circle, ObjectId> { } }
using System.Collections.Generic; using OnlineClinic.Data.Entities; namespace OnlineClinic.Data.Repositories { public interface ISpecializationRepository: IRepository<Specialization> { Dictionary<int, string> GetSpecializationIdAndNames(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using IPTables.Net.Exceptions; using IPTables.Net.Iptables.IpSet.Adapter; using IPTables.Net.Supporting; namespace IPTables.Net.Iptables.IpSet { public class IpSetSets { private Dictionary<String, IpSetSet> _sets = new Dictionary<String, IpSetSet>(); private IpTablesSystem _system; public IpSetSets(IEnumerable<String> commands, IpTablesSystem system) { _system = system; foreach (var command in commands) { Accept(command, system); } } public IpSetSets(IpTablesSystem system) { _system = system; } public IEnumerable<IpSetSet> Sets { get { return _sets.Values; } } public IpTablesSystem System { get { return _system; } } /// <summary> /// Sync with an IPTables system /// </summary> /// <param name="canDeleteSet"></param> /// <param name="transactional"></param> public void Sync( Func<IpSetSet, bool> canDeleteSet = null, bool transactional = true) { if (transactional) { //Start transaction System.SetAdapter.StartTransaction(); } var systemSets = System.SetAdapter.SaveSets(System); foreach (var set in _sets.Values) { var systemSet = systemSets.GetSetByName(set.Name); if (systemSet == null) { //Add System.SetAdapter.CreateSet(set); systemSet = new IpSetSet(set.Type, set.Name, set.Timeout, "inet", System, set.SyncMode, set.BitmapRange, set.CreateOptions); } else { //Update if applicable if (!systemSet.SetEquals(set)) { System.SetAdapter.DestroySet(set.Name); System.SetAdapter.CreateSet(set); systemSet = new IpSetSet(set.Type, set.Name, set.Timeout, "inet", System, set.SyncMode, set.BitmapRange, set.CreateOptions, set.Entries); } } if (set.SyncMode == IpSetSyncMode.SetAndEntries) { HashSet<IpSetEntry> indexedEntries = new HashSet<IpSetEntry>(set.Entries, new IpSetEntryKeyComparer()); HashSet<IpSetEntry> systemEntries = new HashSet<IpSetEntry>(systemSet.Entries, new IpSetEntryKeyComparer()); try { foreach (var entry in indexedEntries) { if (!systemEntries.Remove(entry)) { System.SetAdapter.AddEntry(entry); } } foreach (var entry in systemEntries) { System.SetAdapter.DeleteEntry(entry); } } catch (Exception ex) { throw new IpTablesNetException(String.Format("An exception occured while adding or removing on entries of set {0} message:{1}",set.Name,ex.Message),ex); } } } if (canDeleteSet != null) { foreach (var set in systemSets.Sets) { if (!_sets.ContainsKey(set.Name) && canDeleteSet(set)) { System.SetAdapter.DestroySet(set.Name); } } } if (transactional) { //End Transaction: COMMIT if (!System.SetAdapter.EndTransactionCommit()) { throw new IpTablesNetException("Failed to commit IPSets"); } } } public IpSetSet GetSetByName(string name) { IpSetSet ret = null; _sets.TryGetValue(name, out ret); return ret; } public void AddSet(IpSetSet set) { _sets.Add(set.Name, set); } public void Accept(String line, IpTablesSystem iptables) { String[] split = ArgumentHelper.SplitArguments(line); if (split.Length == 0) return; var command = split[0]; switch (command) { case "create": var set = IpSetSet.Parse(split, iptables, 1); AddSet(set); break; case "add": IpSetEntry.Parse(split, this, 1); break; } } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using StarlightRiver.Codex; using System; using System.Linq; using Terraria; using Terraria.DataStructures; using Terraria.ID; using Terraria.ModLoader; using Terraria.ObjectData; namespace StarlightRiver { public static class Helper { /// <summary> /// Kills the NPC. /// </summary> /// <param name="npc"></param> public static Vector2 TileAdj { get => Lighting.lightMode > 1 ? Vector2.Zero : Vector2.One * 12; } public static void Kill(this NPC npc) { bool modNPCDontDie = npc.modNPC != null && !npc.modNPC.CheckDead(); if (modNPCDontDie) return; npc.life = 0; npc.checkDead(); npc.HitEffect(); npc.active = false; } public static void PlaceMultitile(Point16 position, int type, int style = 0) { TileObjectData data = TileObjectData.GetTileData(type, style); //magic numbers and uneccisary params begone! if (position.X + data.Width > Main.maxTilesX || position.X < 0) return; //make sure we dont spawn outside of the world! if (position.Y + data.Height > Main.maxTilesY || position.Y < 0) return; for (int x = 0; x < data.Width; x++) //generate each column { for (int y = 0; y < data.Height; y++) //generate each row { Tile tile = Framing.GetTileSafely(position.X + x, position.Y + y); //get the targeted tile tile.type = (ushort)type; //set the type of the tile to our multitile tile.frameX = (short)(x * (data.CoordinateWidth + data.CoordinatePadding)); //set the X frame appropriately tile.frameY = (short)(y * (data.CoordinateHeights[y] + data.CoordinatePadding)); //set the Y frame appropriately tile.active(true); //activate the tile } } } public static bool CheckAirRectangle(Point16 position, Point16 size) { if (position.X + size.X > Main.maxTilesX || position.X < 0) return false; //make sure we dont check outside of the world! if (position.Y + size.Y > Main.maxTilesY || position.Y < 0) return false; for (int x = position.X; x < position.X + size.X; x++) { for (int y = position.Y; y < position.Y + size.Y; y++) { if (Main.tile[x, y].active()) return false; //if any tiles there are active, return false! } } return true; } public static bool AirScanUp(Vector2 start, int MaxScan) { if (start.Y - MaxScan < 0) { return false; } bool clear = true; for (int k = 0; k <= MaxScan; k++) { if (Main.tile[(int)start.X, (int)start.Y - k].active()) { clear = false; } } return clear; } public static void UnlockEntry<type>(Player player) { player.GetModPlayer<CodexHandler>().Entries.FirstOrDefault(entry => entry is type).Locked = false; GUI.Codex.NewEntry = true; } public static void SpawnGem(int ID, Vector2 position) { int item = Item.NewItem(position, ModContent.ItemType<Items.StarlightGem>()); (Main.item[item].modItem as Items.StarlightGem).gemID = ID; } public static void DrawSymbol(SpriteBatch spriteBatch, Vector2 position, Color color) { Texture2D tex = ModContent.GetTexture("StarlightRiver/Symbol"); float scale = 0.9f + (float)Math.Sin(LegendWorld.rottime) * 0.1f; spriteBatch.Draw(tex, position, tex.Frame(), color * 0.8f * scale, 0, tex.Size() * 0.5f, scale * 0.8f, 0, 0); Texture2D tex2 = ModContent.GetTexture("StarlightRiver/Tiles/Interactive/WispSwitchGlow2"); float fade = LegendWorld.rottime / 6.28f; spriteBatch.Draw(tex2, position, tex2.Frame(), color * (1 - fade), 0, tex2.Size() / 2f, fade * 0.6f, 0, 0); } public static bool CheckCircularCollision(Vector2 center, int radius, Rectangle hitbox) { if (Vector2.Distance(center, hitbox.TopLeft()) <= radius) return true; if (Vector2.Distance(center, hitbox.TopRight()) <= radius) return true; if (Vector2.Distance(center, hitbox.BottomLeft()) <= radius) return true; if (Vector2.Distance(center, hitbox.BottomRight()) <= radius) return true; return false; } public static string TicksToTime(int ticks) { int sec = ticks / 60; return (sec / 60) + ":" + (sec % 60 < 10 ? "0" + sec % 60 : "" + sec % 60); } public static void DrawElectricity(Vector2 point1, Vector2 point2, int dusttype, float scale = 1) { int nodeCount = (int)Vector2.Distance(point1, point2) / 30; Vector2[] nodes = new Vector2[nodeCount + 1]; nodes[nodeCount] = point2; //adds the end as the last point for (int k = 1; k < nodes.Count(); k++) { //Sets all intermediate nodes to their appropriate randomized dot product positions nodes[k] = Vector2.Lerp(point1, point2, k / (float)nodeCount) + (k == nodes.Count() - 1 ? Vector2.Zero : Vector2.Normalize(point1 - point2).RotatedBy(1.58f) * Main.rand.NextFloat(-18, 18)); //Spawns the dust between each node Vector2 prevPos = k == 1 ? point1 : nodes[k - 1]; for (float i = 0; i < 1; i += 0.05f) { Dust.NewDustPerfect(Vector2.Lerp(prevPos, nodes[k], i), dusttype, Vector2.Zero, 0, default, scale); } } } private static int tiltTime; private static float tiltMax; public static void DoTilt(float intensity) { tiltMax = intensity; tiltTime = 0; } public static void UpdateTilt() { if (Math.Abs(tiltMax) > 0) { tiltTime++; if (tiltTime >= 1 && tiltTime < 40) { float tilt = tiltMax - tiltTime * tiltMax / 40f; StarlightRiver.Rotation = tilt * (float)Math.Sin(Math.Pow(tiltTime / 40f * 6.28f, 0.9f)); } if (tiltTime >= 40) { StarlightRiver.Rotation = 0; tiltMax = 0; } } } public static bool HasEquipped(Player player, int ItemID) { for (int k = 3; k < 7 + player.extraAccessorySlots; k++) if (player.armor[k].type == ItemID) return true; return false; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; namespace WhatNEXT { public static class Utility { public static int GetSizeOfObject(object obj) { //object v = null; //int size = 0; //Type type = obj.GetType(); //PropertyInfo[] info = type.GetProperties(); //foreach (PropertyInfo property in info) //{ // v = property.GetValue(obj, null); // unsafe // { // size += sizeof(v); // } //} //return size; return 100000; } public static byte[] GetByteArray(Stream input) { byte[] buffer = new byte[16 * 1024]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } } }
namespace Euler.Regions { public class ZTouchDevice : ITouchDevice { public int[][] GetScreenState() { return new int[][]{ new []{0, 0, 0, 0, 0}, new []{0, 0, 0, 0, 0}, new []{0, 0, 0, 0, 0}, new []{0, 0, 0, 0, 0}, new []{0, 0, 0, 0, 0}, }; } } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; using Aquamonix.Mobile.Lib.Extensions; using Aquamonix.Mobile.Lib.Utilities; namespace Aquamonix.Mobile.Lib.Domain { [DataContract] public class UserResponseObject { [DataMember(Name = PropertyNames.Name)] public string Name { get; set; } [DataMember(Name = PropertyNames.DevicesAccess)] public ItemsDictionary<DeviceAccess> DevicesAccess { get; set; } } }
using System; namespace Phenix.Business { /// <summary> /// 实体基类 /// </summary> [Serializable] public abstract class EntityBase<T> : Phenix.Core.Data.EntityBase<T> where T : EntityBase<T> { /// <summary> /// for CreateInstance /// </summary> protected EntityBase() { //禁止添加代码 } /// <summary> /// for Newtonsoft.Json.JsonConstructor /// </summary> protected EntityBase(bool? isNew, bool? isSelfDirty, bool? isSelfDeleted) : base(isNew, isSelfDirty, isSelfDeleted) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.ServiceModel.Description; using System.Text; using System.Threading.Tasks; namespace Nac.Wcf.Common { [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] public class NacWcfServer<TInterface, TImplementation> where TImplementation : class, TInterface { private static Uri _uri; private static ServiceHost _wcfHost; public static void Start(string url) { _uri = new Uri(url); Init(); } private static void Init() { NetTcpBinding netTcpBinding = new NetTcpBinding(); ServiceMetadataBehavior serviceMetadataBehavior = new ServiceMetadataBehavior(); _wcfHost = new ServiceHost(typeof(TImplementation), _uri); _wcfHost.Description.Behaviors.Add(serviceMetadataBehavior); _wcfHost.Description.Behaviors.Find<ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true; _wcfHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex"); _wcfHost.AddServiceEndpoint(typeof(TInterface), netTcpBinding, _uri); _wcfHost.Faulted += _wcfHost_Faulted; _wcfHost.Open(); } private static void _wcfHost_Faulted(object sender, EventArgs e) { _wcfHost?.Abort(); Init(); } public static void Stop() { _wcfHost?.Close(); _wcfHost = null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Midterm_BeerStorePOS { public enum Menu { OrderItems = 1, ViewCart, InventoryManager, Exit } }
using MasterDetail.Servicio; using MasterDetail; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.PlatformConfiguration; using System.Net.Http; using System.Text.RegularExpressions; namespace MasterDetail { public partial class MiPerfil : ContentPage { EmpaqueModel empa; List<Supermercado> listaSuperm; public MiPerfil(EmpaqueModel empaque) { this.empa = empaque; InitializeComponent(); Carga(empa); } private async void Carga(EmpaqueModel empaque) { await CargaPerfil(empaque); } private async Task CargaPerfil(EmpaqueModel emp) { string response = await Service.GetAllApi("api/supermarket"); List<Supermercado> supermercados2 = JsonConvert.DeserializeObject<List<Supermercado>>(response); lblSuperm.ItemsSource = supermercados2; listaSuperm = supermercados2; Supermercado super = new Supermercado(); foreach (var item in listaSuperm as List<Supermercado>) { if (item.Id == empa.Supermarket) { super = item; } } lblSuperm.SelectedItem = super; List<Genero> llenar = new List<Genero>(); Genero f = new Genero() { Id = 0, Sexo = "Femenino" }; llenar.Add(f); Genero m = new Genero() { Id = 1, Sexo = "Masculino" }; llenar.Add(m); Genero o = new Genero() { Id = 2, Sexo = "Otro" }; llenar.Add(o); PckGender.ItemsSource = llenar; PckGender.SelectedIndex = Convert.ToInt32(emp.Gender); lblRut.Text = emp.Rut.ToString(); lblEmail.Text = emp.Email; lblName.Text = emp.FirstName; lblLastname.Text = emp.LastName; lblPass.Text = emp.Password; dtpNacimiento.Date = emp.BirthDate; lblAdress.Text = emp.Address; lblPhone.Text = emp.PhoneNumber.ToString(); lblJobTitle.Text = emp.JobTitle; } public class Genero { public int Id { get; set; } public string Sexo { get; set; } } private void lblRut_Validated(object sender, EventArgs e) { if (lblRut.Text.Length > 1) { lblRut.Text = formatearRut(lblRut.Text); }else { return; } } public string formatearRut(string rut) { int cont = 0; string format; if (rut.Length == 0) { return ""; } else { rut = rut.Replace(".", ""); rut = rut.Replace("-", ""); format = "-" + rut.Substring(rut.Length - 1); for (int i = rut.Length - 2; i >= 0; i--) { format = rut.Substring(i, 1) + format; cont++; if (cont == 3 && i != 0) { format = "." + format; cont = 0; } } return format; } } public void ShowPass(object sender, EventArgs args) { lblPass.IsPassword = !lblPass.IsPassword; } private async void Btn_EditarPerfil_Clicked(object sender, EventArgs e) { Btn_EditarPerfil.IsEnabled = false; waitActivityIndicator.IsRunning = true; Supermercado super = new Supermercado(); foreach (var item in listaSuperm as List<Supermercado>) { if (item.Equals (lblSuperm.SelectedItem)) { super.Id = item.Id; } } EmpaqueModel empaque = new EmpaqueModel() { Id = empa.Id, Rut = Convert.ToInt32(lblRut.Text.Replace(".","").Replace("-","")), Email = lblEmail.Text, Password = lblPass.Text, FirstName = lblName.Text, LastName = lblLastname.Text, BirthDate = dtpNacimiento.Date, Gender = PckGender.SelectedIndex, Address = lblAdress.Text, PhoneNumber = Convert.ToInt32(lblPhone.Text), Supermarket = super.Id, JobTitle = lblJobTitle.Text }; try { HttpResponseMessage response = await Service.Put("api/user/" + empa.Id.ToString(), empaque); if (response.StatusCode != System.Net.HttpStatusCode.NotFound) { waitActivityIndicator.IsRunning = false; await DisplayAlert("Cambios Guardados", "Cambios realizados con éxito", "Ok"); Btn_EditarPerfil.IsEnabled = true; return; } else { waitActivityIndicator.IsRunning = false; await DisplayAlert("Error de conexión", "Error inesperado al editar sus datos", "Ok"); Btn_EditarPerfil.IsEnabled = true; return; } } catch (Exception ex) { Btn_EditarPerfil.IsEnabled = true; await DisplayAlert("Error de edición", "Error al editar empaque "+ ex, "Ok"); return; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Stratego { class Board { public int[,] GameBoard { get; set; } public Board(int n) { GameBoard = new int[n, n]; } public Board() { } public bool[,] GetAvaliableMoves() { bool[,] result = new bool[GameBoard.GetLength(0), GameBoard.GetLength(1)]; for (int i = 0; i < GameBoard.GetLength(0); i++) { for (int j = 0; j < GameBoard.GetLength(1); j++) { result[i, j] = GameBoard[i, j] == 0; } } return result; } } }
using jaytwo.Common.Extensions; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace jaytwo.Common.Test.Time { [TestFixture] public static class DateTimeExtensionsTests { [Test] public static void TruncateToSecondPrecision() { Assert.AreEqual( new DateTime(2014, 1, 1, 12, 23, 34, 0, DateTimeKind.Unspecified), new DateTime(2014, 1, 1, 12, 23, 34, 45, DateTimeKind.Unspecified).TruncateToSecondPrecision()); } [Test] public static void TruncateToMinutePrecision() { Assert.AreEqual( new DateTime(2014, 1, 1, 12, 23, 0, 0, DateTimeKind.Unspecified), new DateTime(2014, 1, 1, 12, 23, 34, 45, DateTimeKind.Unspecified).TruncateToMinutePrecision()); } [Test] public static void WithKind() { Assert.AreEqual( new DateTime(2014, 09, 17, 13, 46, 33, 756, DateTimeKind.Local), new DateTime(2014, 09, 17, 13, 46, 33, 756).WithKind(DateTimeKind.Local)); Assert.AreEqual( new DateTime(2014, 09, 17, 13, 46, 33, 756, DateTimeKind.Unspecified), new DateTime(2014, 09, 17, 13, 46, 33, 756).WithKind(DateTimeKind.Unspecified)); Assert.AreEqual( new DateTime(2014, 09, 17, 13, 46, 33, 756, DateTimeKind.Utc), new DateTime(2014, 09, 17, 13, 46, 33, 756).WithKind(DateTimeKind.Utc)); Assert.AreEqual( new DateTime(2014, 09, 17, 13, 46, 33, 756, DateTimeKind.Utc), ((DateTime?)new DateTime(2014, 09, 17, 13, 46, 33, 756)).WithKind(DateTimeKind.Utc)); Assert.IsNull(((DateTime?)null).WithKind(DateTimeKind.Utc)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using SimpleTaskListSPA.Data; using SimpleTaskListSPA.Data.DTO; namespace SimpleTaskListSPA.Models.Repo { public interface ITaskItemRepo : IBaseRepo<TaskItem> { Task<TaskItem> GetTaskAsync(long id); Task<TaskItemResponse> ReceiveTasksAsync(QueryOptions options); } }
using System; using System.Collections.Generic; using System.Text; namespace AnyTest.MobileClient { public interface IPopUp { void Long(string message); void Short(string message); } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text.RegularExpressions; class StringMatrixRotation { static void Main() { List<string> inputList = new List<string>(); string pattern = @"(?<=\()\d+(?=\))"; Regex rxRegex = new Regex(pattern); int degrees = (int.Parse(rxRegex.Match(Console.ReadLine()).Value)); string inputStr = Console.ReadLine(); while (inputStr != "END") { inputList.Add(inputStr); inputStr = Console.ReadLine(); } int maxL = int.MinValue; for (int i = 0; i < inputList.Count; i++) { int tmpVal = inputList[i].Length; if (tmpVal > maxL) { maxL = tmpVal; } } string[,] matrix = new string[inputList.Count, maxL]; for (int row = 0; row < inputList.Count; row++) { for (int col = 0; col < maxL; col++) { if (inputList[row].Length > col) { matrix[row, col] = inputList[row][col].ToString(); } else { matrix[row, col] = " "; } } } degrees = degrees % 360; if (degrees == 90) { matrix = Rotate90(matrix); } else if (degrees == 180) { matrix = Rotate180(matrix); } else if (degrees == 270) { matrix = Rotate270(matrix); } for (int row = 0; row < matrix.GetLength(0); row++) { for (int col = 0; col < matrix.GetLength(1); col++) { Console.Write(matrix[row, col]); } Console.WriteLine(); } } private static string[,] Rotate270(string[,] matrix) { string[,] newMat = new string[matrix.GetLength(1), matrix.GetLength(0)]; for (int row = 0; row < matrix.GetLength(0); row++) { for (int col = 0; col < matrix.GetLength(1); col++) { newMat[newMat.GetLength(0) - 1 - col, row] = matrix[row, col]; } } return newMat; } private static string[,] Rotate180(string[,] matrix) { string[,] newMat = new string[matrix.GetLength(0), matrix.GetLength(1)]; for (int row = 0; row < matrix.GetLength(0); row++) { for (int col = 0; col < matrix.GetLength(1); col++) { newMat[newMat.GetLength(0) - 1 - row, newMat.GetLength(1) - 1 - col] = matrix[row, col]; } } return newMat; } private static string[,] Rotate90(string[,] matrix) { string[,] newMat = new string[matrix.GetLength(1), matrix.GetLength(0)]; for (int row = 0; row < matrix.GetLength(0); row++) { for (int col = 0; col < matrix.GetLength(1); col++) { newMat[col, newMat.GetLength(1) - 1 - row] = matrix[row, col]; } } return newMat; } }
using System; namespace Travelling { class Program { static void Main(string[] args) { string destinationCommand = Console.ReadLine(); while (destinationCommand != "End") { double moneyNeeded = double.Parse(Console.ReadLine()); while (moneyNeeded > 0) { double savedMoney = double.Parse(Console.ReadLine()); moneyNeeded -= savedMoney; } Console.WriteLine($"Going to {destinationCommand}!"); destinationCommand = Console.ReadLine(); } } } }
using System; using System.Collections.Generic; using System.IO; using com.Sconit.Entity.MRP.ORD; using com.Sconit.Entity.MRP.TRANS; using com.Sconit.Entity.MRP.VIEW; using System.Text; using com.Sconit.Entity.SCM; using com.Sconit.Entity.PRD; //TODO: Add other using statements here. namespace com.Sconit.Service.MRP { public interface IPlanMgr { #region Customized Methods #region Import /// <summary> /// 导入MRP计划 /// </summary> void ReadDailyMrpPlanFromXls(Stream inputStream, DateTime? startDate, DateTime? endDate, string flowCode, bool isItemRef); void ReadWeeklyMrpPlanFromXls(Stream inputStream, string startWeek, string endWeek, string flowCode, bool isItemRef); /// <summary> /// 导入RCCP计划 /// </summary> void ReadRccpPlanFromXls(Stream inputStream, string startDateIndex, string endDateIndex, bool isItemRef, com.Sconit.CodeMaster.TimeUnit periodType); void ReadRccpPlanFromXls(Stream inputStream, DateTime startDate, DateTime endDate, bool isItemRef, com.Sconit.CodeMaster.TimeUnit periodType); /// <summary> /// 导入班产计划 /// </summary> List<MrpShiftPlan> ReadShiftPlanFromXls(Stream inputStream, DateTime startDate, DateTime endDate, string flow); void CreateMrpPlan(string flowCode, List<MrpPlanLog> mrpPlanLogList); void CreateRccpPlan(CodeMaster.TimeUnit dateType, List<RccpPlanLog> rccpPlanLogList); #endregion #region /// <summary> /// 后加工模具负荷 /// </summary> IList<RccpFiView> GetMachineRccpView(IList<RccpFiPlan> rccpFiPlanList); /// <summary> /// 后加工岛区负荷 /// </summary> IList<RccpFiView> GetIslandRccpView(IList<RccpFiPlan> rccpFiPlanList); void UpdateMrpPlan(MrpPlan mrpPlan); IEnumerable<RccpExGroupByProdLineView> GetExRccpViewGroupByProdLineLoad(IEnumerable<RccpTransGroup> rccpTransList); IEnumerable<RccpExGroupByProdLineView> GetExRccpViewGroupByProdLineQty(IEnumerable<RccpTransGroup> rccpTransList); IEnumerable<RccpExGroupByProdLineView> GetExRccpViewGroupByProdLineSpeed(IEnumerable<RccpTransGroup> rccpTransList); IEnumerable<RccpExGroupByProdLineView> GetExRccpViewGroupByProdLineScrapPercentage(IEnumerable<RccpTransGroup> rccpTransList); IEnumerable<RccpExGroupByItemView> GetExRccpViewGroupByItemTime(IEnumerable<RccpTransGroup> rccpTransList); IEnumerable<RccpExGroupByItemView> GetExRccpViewGroupByItemLoad(IEnumerable<RccpTransGroup> rccpTransList); IEnumerable<RccpExGroupByItemView> GetExRccpViewGroupByItemQty(IEnumerable<RccpTransGroup> rccpTransList); IEnumerable<RccpExGroupByClassifyView> GetExRccpViewGroupByClassifyLoad(IEnumerable<RccpTransGroup> rccpTransList); IEnumerable<RccpExGroupByClassifyView> GetExRccpViewGroupByClassifySpeed(IEnumerable<RccpTransGroup> rccpTransList); IEnumerable<RccpExGroupByClassifyView> GetExRccpViewGroupByClassifyScrapPercentage(IEnumerable<RccpTransGroup> rccpTransList); IEnumerable<RccpExGroupByClassifyView> GetExRccpViewGroupByClassifyQty(IEnumerable<RccpTransGroup> rccpTransList); IEnumerable<RccpExView> GetExRccpView(IEnumerable<RccpTransGroup> rccpTransList); #endregion StringBuilder GetPlanSimulation(DateTime planVersion, string flow); StringBuilder GetFiShiftPlanView(DateTime planVersion, string flow); StringBuilder GetMiDailyPlanView(DateTime planVersion, string flow); /// <summary> /// 计划跟踪 /// </summary> IList<MrpPlanTraceView> GetPlanTraceViewList(CodeMaster.ResourceGroup resourceGroup, string flow, string item, bool onlyShowUrgent = true); IList<ContainerView> GetContainerViewList(DateTime dateTime); string GetMrpInvIn(DateTime planVersion, CodeMaster.ResourceGroup resourceGroup, string flow, bool isShowDetail); string GetStringRccpPlanView(IList<RccpPlan> rccpPlanList, int planVersion, string timeType); string GetStringMrpPlanView(IList<MrpPlan> mrpPlanList, DateTime startDate, int planVersion, string reqUrl); #endregion Customized Methods } }
using UnityEngine; public class SoundManager : MonoBehaviour { [SerializeField] private AudioClip[] audioClips = null; [SerializeField] private AudioSource AudioSource = null; public void PlaySound(int num) { AudioSource.PlayOneShot(audioClips[num]); } }
using System.Windows.Controls; namespace MinecraftToolsBox.Commands { /// <summary> /// EntityFriend.xaml 的交互逻辑 /// </summary> public partial class EntityFriend : Grid { public EntityFriend() { InitializeComponent(); } public void Enable(string id) { E1.IsEnabled = false; E2.IsEnabled = false; E3.IsEnabled = false; E4.IsEnabled = false; E5.IsEnabled = false; E6.IsEnabled = false; E7.IsEnabled = false; E8.IsEnabled = false; switch (id) { default: break; case "SnowMan": E1.IsEnabled = true; break; case "Pig": E2.IsEnabled = true; break; case "Bat": E3.IsEnabled = true; break; case "VillagerGolem": E4.IsEnabled = true; break; case "Sheep": E5.IsEnabled = true; break; case "Chicken": E6.IsEnabled = true; break; case "Ozelot": E7.IsEnabled = true; break; case "Rabbit": E8.IsEnabled = true; break; } } public string getNBT() { string tag = ""; if (E1.IsEnabled) { if (pump.IsChecked == false) tag += "Pumpkin:false,"; } else if (E2.IsEnabled) { if (saddle.IsChecked == true) tag += "Saddle:true,"; } else if (E3.IsEnabled) { if (bat.IsChecked == true) tag += "BatFlags:true,"; } else if (E4.IsEnabled) { if (player.IsChecked == true) tag += "PlayerCreated:true,"; } else if (E5.IsEnabled) { if (shear.IsChecked == true) tag += "Sheared:true,"; if (color.Value != null) tag += "Color:" + color.Value + ","; } else if (E6.IsEnabled) { if (jokey.IsChecked == true) tag += "IsChickenJockey:true,"; if (lay.Value != null) tag += "EggLayTime:" + (lay.Value * 20) + ","; } else if (E7.IsEnabled) { if (cat.SelectedIndex != 4) tag += "CatType:" + cat.SelectedIndex + ","; } else if (E8.IsEnabled) { if (rabbit.SelectedIndex != 7) tag += "RabbitType:" + rabbit.SelectedIndex + ","; if (food.Value != null) tag += "MoreCarrotTicks:" + food.Value + ","; } return tag; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using ManageDomain; namespace ManageWeb.Controllers { public class ProjectController : ManageBaseController { // // GET: /Project/ public ActionResult Index(string keywords, int pno = 1) { //权限 ManageDomain.PermissionProvider.CheckExist(SystemPermissionKey.Project_Show); ViewBag.keywords = keywords; const int pagesize = 20; ManageDomain.BLL.ProjectBll cusbll = new ManageDomain.BLL.ProjectBll(); var model = cusbll.GetPage(keywords ?? "", pno, pagesize); return View(model); } [HttpGet] public ActionResult Edit(int projectid = 0) { ManageDomain.Models.Project model = null; if (projectid > 0) { //权限 ManageDomain.PermissionProvider.CheckExist(SystemPermissionKey.Project_Show); var bll = new ManageDomain.BLL.ProjectBll(); var mxmodel = bll.GetDetailWidthConfigs(projectid); if (mxmodel == null) { throw new MException("项目不存在!"); } model = mxmodel.Item1; ViewBag.configs = mxmodel.Item2; } else { //权限 ManageDomain.PermissionProvider.CheckExist(SystemPermissionKey.Project_Add); } return View(model); } [HttpPost] public ActionResult Edit(ManageDomain.Models.Project model, string[] configkey, string[] configvalue, string[] configremark) { if (model == null) { ViewBag.msg = "无效参数!"; return View(model); } if (model.ProjectId > 0) { //权限 ManageDomain.PermissionProvider.CheckExist(SystemPermissionKey.Project_Update); } else { //权限 ManageDomain.PermissionProvider.CheckExist(SystemPermissionKey.Project_Add); } if (string.IsNullOrWhiteSpace(model.CodeName)) { ViewBag.msg = "项目代码不能为空!"; return View(model); } if (string.IsNullOrWhiteSpace(model.Title)) { ViewBag.msg = "项目名称不能为空!"; return View(model); } var bll = new ManageDomain.BLL.ProjectBll(); List<ManageDomain.Models.ProjectConfig> configs = new List<ManageDomain.Models.ProjectConfig>(); if (configkey != null && configvalue != null && configremark != null) { if (configkey.Length == configvalue.Length && configvalue.Length == configremark.Length) { for (int i = 0; i < configkey.Length; i++) { string key = (configkey[i] ?? "").Trim(); if (string.IsNullOrEmpty(key)) continue; configs.Add(new ManageDomain.Models.ProjectConfig() { ProjectId = model.ProjectId, ConfigKey = key, ConfigValue = CCF.DB.LibConvert.NullToStr(configvalue[i]).Trim(), Remark = CCF.DB.LibConvert.NullToStr(configremark[i]).Trim(), }); } } } if (model.ProjectId > 0) { bll.Update(model, configs); ViewBag.msg = "修改成功"; } else { model = bll.Add(model, configs); ViewBag.msg = "新增成功"; } var mxmodel = bll.GetDetailWidthConfigs(model.ProjectId); model = mxmodel.Item1; ViewBag.configs = mxmodel.Item2; return View(model); } [HttpPost] public JsonResult Delete(int projectid) { //权限 ManageDomain.PermissionProvider.CheckExist(SystemPermissionKey.Project_Delete); var bll = new ManageDomain.BLL.ProjectBll(); int r = bll.Delete(projectid); if (r > 0) { return Json(new { code = 1 }); } else { return Json(new { code = -1, msg = "删除失败" }); } } public ActionResult Version(int projectid) { var bll = new ManageDomain.BLL.ProjectBll(); var projectversions = bll.GetProjectVersions(projectid); var projectmodel = bll.GetDetail(projectid); ViewBag.versions = projectversions; return View(projectmodel); } [HttpPost] public ActionResult Version(ManageDomain.Models.ProjectVersion model, HttpPostedFileBase downloadfile) { var bll = new ManageDomain.BLL.ProjectBll(); model.DownloadUrl = model.DownloadUrl ?? ""; if (downloadfile != null) { string filename = DateTime.Now.ToString("yyMMddHHmmss") + ".zip"; string pathname = Pub.GetConfig(SystemConst.Project_File_Config_Name, "ProjectFile"); string path = Server.MapPath(Pub.GetConfig(SystemConst.Project_File_Config_Name, "~/ProjectFile")); if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); string filefullname = System.IO.Path.Combine(path, filename); downloadfile.SaveAs(filefullname); model.DownloadUrl = System.IO.Path.Combine(pathname, filename); } if (model.VersionId > 0) { bll.UpdateProjectVersion(model); } else { model = bll.AddProjectVersion(model); } var projectversions = bll.GetProjectVersions(model.ProjectId); var projectmodel = bll.GetDetail(model.ProjectId); ViewBag.versions = projectversions; return View(projectmodel); } [HttpPost] public JsonResult SynConfig(string configkey) { var bll = new ManageDomain.BLL.ProjectBll(); int r = bll.SynConfigToCusProject(configkey); return Json(new { code = 1, data = r }); } } }
using System; using System.Collections; using System.Collections.Generic; using com.Sconit.Entity; using System.ComponentModel.DataAnnotations; //TODO: Add other using statements here namespace com.Sconit.Entity.FMS { [Serializable] public partial class FacilityCategory : EntityBase, IAuditable { #region O/R Mapping Properties [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))] [StringLength(50, ErrorMessageResourceName = "Errors_Common_FieldLengthExceed", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))] [Display(Name = "FacilityCategory_Code", ResourceType = typeof(Resources.FMS.FacilityCategory))] public string Code { get; set; } [Display(Name = "FacilityCategory_ChargeOrganization", ResourceType = typeof(Resources.FMS.FacilityCategory))] public string ChargeOrganization { get; set; } [Display(Name = "FacilityCategory_ChargeSite", ResourceType = typeof(Resources.FMS.FacilityCategory))] public string ChargeSite { get; set; } public Int32 ChargePersonId { get; set; } [Display(Name = "FacilityCategory_Description", ResourceType = typeof(Resources.FMS.FacilityCategory))] public string Description { get; set; } [Display(Name = "FacilityCategory_ChargePerson", ResourceType = typeof(Resources.FMS.FacilityCategory))] public string ChargePersonName { get; set; } [Display(Name = "FacilityCategory_ParentCategory", ResourceType = typeof(Resources.FMS.FacilityCategory))] public string ParentCategory { get; set; } public Int32 CreateUserId { get; set; } public string CreateUserName { get; set; } public DateTime CreateDate { get; set; } public Int32 LastModifyUserId { get; set; } public string LastModifyUserName { get; set; } public DateTime LastModifyDate { get; set; } #endregion public override int GetHashCode() { if (Code != null) { return Code.GetHashCode(); } else { return base.GetHashCode(); } } public override bool Equals(object obj) { FacilityCategory another = obj as FacilityCategory; if (another == null) { return false; } else { return (this.Code == another.Code); } } } }
// <copyright file="WebpackOptions.cs" company="Morten Larsen"> // Copyright (c) Morten Larsen. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. // </copyright> // ReSharper disable AutoPropertyCanBeMadeGetOnly.Global // ReSharper disable UnusedAutoPropertyAccessor.Global namespace AspNetWebpack.AssetHelpers { /// <summary> /// Webpack options configured in appsettings. /// </summary> public class WebpackOptions { /// <summary> /// Gets or sets the public url for the dev server. This needs to be accessible from the client. /// </summary> public string? PublicDevServer { get; set; } /// <summary> /// Gets or sets the internal url for the dev server. This needs to be accessible from the server. /// </summary> public string? InternalDevServer { get; set; } /// <summary> /// Gets or sets the public path set in Webpack. /// </summary> public string PublicPath { get; set; } = "/dist/"; /// <summary> /// Gets or sets name of the manifest file generated by Webpack. /// </summary> public string ManifestFile { get; set; } = "manifest.json"; } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or or http://www.opensource.org/licenses/mit-license.php. using FiiiChain.Data; using FiiiChain.DataAgent; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FiiiChain.Business.Extensions { internal enum TxType { UnPackge, RepeatedCost, NoFoundUtxo } internal static class BlackListExtension { public static void BlackTxPoolItems() { var items = TransactionPool.Instance.MainPool.ToList(); items.AddRange(TransactionPool.Instance.IsolateTransactionPool); List<string> hashes = new List<string>(); foreach (TransactionPoolItem item in items) { var type = Check(item); if (type != TxType.UnPackge) { hashes.Add(item.Transaction.Hash); TransactionPool.Instance.RemoveTransaction(item.Transaction.Hash); } } BlacklistTxs.Current.Add(hashes); } static TransactionDac txDac = TransactionDac.Default; public static TxType Check(TransactionPoolItem poolItem) { var inputs = poolItem.Transaction.Inputs; foreach (var input in inputs) { if (!txDac.HasTransaction(input.OutputTransactionHash)) return TxType.NoFoundUtxo; if (txDac.HasCost(input.OutputTransactionHash, input.OutputIndex)) return TxType.RepeatedCost; } return TxType.UnPackge; } static void CheckTxItem(List<TransactionPoolItem> items) { var sb = new StringBuilder(); int RepeatedCost = 0; int NoFoundUtxo = 0; foreach (var item in items) { var result = Check(item); if (result != TxType.UnPackge) { sb.AppendLine($"{result.ToString()}:{item.Transaction.Hash}"); if (result == TxType.NoFoundUtxo) NoFoundUtxo++; else RepeatedCost++; } } } } }
using System; namespace Miner { class Program { static void Main(string[] args) { var n = int.Parse(Console.ReadLine()); var commands = Console.ReadLine().Split(" ",StringSplitOptions.RemoveEmptyEntries); var matrix = new char[n, n]; var minerRow = -1; var minerCol = -1; var allCoals = 0; var collectedCoals = 0; for (int row = 0; row < n; row++) { var input = Console.ReadLine().Split(' '); for (int col = 0; col < n; col++) { matrix[row,col] = input[col].ToCharArray()[0]; if (matrix[row,col] == 's') { minerRow = row; minerCol = col; } if (matrix[row, col] == 'c') { allCoals++; } } } foreach (var command in commands) { if (command == "up") { if (minerRow - 1 >= 0) { minerRow--; if (CheckForEnd(matrix, minerRow, minerCol)) { Console.WriteLine($"Game over! ({minerRow}, {minerCol})"); return; } if (CheckForCoal(matrix, minerRow, minerCol)) { collectedCoals++; } if (CheckForCollectedCoals(allCoals, collectedCoals)) { Console.WriteLine($"You collected all coals! ({minerRow}, {minerCol})"); return; } MoveUp(matrix, minerRow + 1, minerCol); } } else if (command == "down") { if (minerRow + 1 < matrix.GetLength(0)) { minerRow++; if (CheckForEnd(matrix, minerRow, minerCol)) { Console.WriteLine($"Game over! ({minerRow}, {minerCol})"); return; } if (CheckForCoal(matrix, minerRow, minerCol)) { collectedCoals++; } if (CheckForCollectedCoals(allCoals, collectedCoals)) { Console.WriteLine($"You collected all coals! ({minerRow}, {minerCol})"); return; } MoveDown(matrix, minerRow - 1, minerCol); } } else if (command == "left") { if (minerCol - 1 >= 0) { minerCol--; if (CheckForEnd(matrix, minerRow, minerCol)) { Console.WriteLine($"Game over! ({minerRow}, {minerCol})"); return; } if (CheckForCoal(matrix, minerRow, minerCol)) { collectedCoals++; } if (CheckForCollectedCoals(allCoals, collectedCoals)) { Console.WriteLine($"You collected all coals! ({minerRow}, {minerCol})"); return; } MoveLeft(matrix, minerRow, minerCol + 1); } } else if (command == "right") { if (minerCol + 1 < matrix.GetLength(0)) { minerCol++; if (CheckForEnd(matrix, minerRow, minerCol)) { Console.WriteLine($"Game over! ({minerRow}, {minerCol})"); return; } if (CheckForCoal(matrix, minerRow, minerCol)) { collectedCoals++; } if (CheckForCollectedCoals(allCoals, collectedCoals)) { Console.WriteLine($"You collected all coals! ({minerRow}, {minerCol})"); return; } MoveRight(matrix, minerRow, minerCol - 1); } } } Console.WriteLine($"{allCoals - collectedCoals} coals left. ({minerRow}, {minerCol})"); } private static bool CheckForCollectedCoals(int allCoals, int collectedCoals) { return allCoals == collectedCoals; } private static bool CheckForCoal(char[,] matrix, int minerRow, int minerCol) { if (matrix[minerRow, minerCol] == 'c') { matrix[minerRow, minerCol] = 's'; return true; } return false; } private static bool CheckForEnd(char[,] matrix, int minerRow, int minerCol) { return matrix[minerRow, minerCol] == 'e'; } private static void MoveRight(char[,] matrix, int minerRow, int minerCol) { matrix[minerRow, minerCol] = '*'; matrix[minerRow, minerCol + 1] = 's'; } private static void MoveLeft(char[,] matrix, int minerRow, int minerCol) { matrix[minerRow, minerCol] = '*'; matrix[minerRow, minerCol - 1] = 's'; } private static void MoveDown(char[,] matrix, int minerRow, int minerCol) { matrix[minerRow, minerCol] = '*'; matrix[minerRow + 1, minerCol] = 's'; } private static void MoveUp(char[,] matrix, int minerRow, int minerCol) { matrix[minerRow, minerCol] = '*'; matrix[minerRow - 1,minerCol] = 's'; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using ApartmentApps.Api.ViewModels; using ApartmentApps.Data; using ApartmentApps.Forms; using ApartmentApps.Portal.Controllers; using ExpressiveAnnotations.Attributes; using Ninject; namespace ApartmentApps.Api.Modules { public class QuickAddRentBindingModel : BaseViewModel { [Required] [DisplayName("User that will be charged")] [SelectFrom(nameof(UserIdItems))] public string UserId { get; set; } [DisplayName("Date of the first charge")] [DataType(DataType.Date)] [AssertThat("NotBeforeToday(NextInvoiceDate)", ErrorMessage = "Invoice date must be future date")] public DateTime? NextInvoiceDate { get;set; } [Required] [DataType(DataType.Currency)] [DisplayName("Amount that will be charged in USD each month")] public decimal Amount { get; set; } public List<UserLookupBindingModel> UserIdItems { get; set; } public bool NotBeforeToday(DateTime? time) { if (!time.HasValue) return true; return CurrentUserDateTime.Now() < time.Value; } } public class EditUserLeaseInfoBindingModel : BaseViewModel { [Required] [DisplayName("Reasonable name for the payment request")] public string Title { get; set; } [Required] [DisplayName("User that will be charged")] [SelectFrom(nameof(UserIdItems))] public string UserId { get; set; } [Required] [DataType(DataType.Currency)] [DisplayName("Amount that will be charged in USD")] public decimal Amount { get; set; } [DisplayName("Create invoice due")] [RequiredIf("UseInterval == true || Id == null",ErrorMessage = "This field is required")] [DataType(DataType.Date)] [AssertThat("NotBeforeToday(NextInvoiceDate)",ErrorMessage = "Invoice date must be future date")] public DateTime? NextInvoiceDate { get;set; } [DisplayName("Create subscription ?")] [Description("Subscription allows to repeat invoices with a certain interval")] [ToggleCategory("IntervalSettings")] public bool UseInterval { get; set; } [DisplayName("Interval in months")] [WithCategory("IntervalSettings")] [RequiredIf("UseInterval == true")] public int? IntervalMonths { get; set; } [DisplayName("Set expiration date ?")] [WithCategory("IntervalSettings")] [ToggleCategory("ExpirationSettings")] public bool UseCompleteDate { get; set; } [DisplayName("Close subscription on")] [WithCategory("IntervalSettings ExpirationSettings")] [RequiredIf("UseInterval == true && UseCompleteDate == true")] [AssertThat("NotBefore(NextInvoiceDate,CompleteDate)",ErrorMessage = "Complete date must be after invoice date")] [DataType(DataType.Date)] public DateTime? CompleteDate { get; set; } public List<UserLookupBindingModel> UserIdItems { get; set; } public bool NotBeforeToday(DateTime? time) { if (!time.HasValue) return true; return CurrentUserDateTime.Now() < time.Value; } public bool NotBefore(DateTime? past, DateTime? future) { if (!past.HasValue || !future.HasValue) { return true; } return past.Value < future.Value; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Road : ReusableObject { public override void OnSpawn() { } public override void OnUnSpawn() { var itemChild = transform.Find("Item"); if (itemChild != null) { if (itemChild.childCount > 0) { for (int i = 0; i < itemChild.childCount; i++) { GameObject go = itemChild.GetChild(i).gameObject; if(go.activeSelf) Game.M_Instance.M_ObjectPool.UnSpawn(go); } } } } }
/*------------------------------------------------------------------------------------------- * Copyright (c) Fuyuno Mikazuki / Natsuneko. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *------------------------------------------------------------------------------------------*/ using Mochizuki.VariationPackager.Models.Interface; using Newtonsoft.Json; namespace Mochizuki.VariationPackager.Models.Json { public class PackageVariation : IPackageVariation { [JsonConstructor] public PackageVariation([JsonProperty("archive")] PackageConfiguration archive, [JsonProperty("unitypackage")] PackageConfiguration unityPackage) { Archive = archive; UnityPackage = unityPackage; } public IPackageConfiguration Archive { get; } public IPackageConfiguration UnityPackage { get; } [JsonProperty("name")] public string Name { get; set; } } }
using System; using System.Web.Http; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Web.Mvc; using Umbraco.Web.WebApi; using Umbraco.Web.WebApi.Filters; using Vendr.Checkout.Services; using Vendr.Core.Api; namespace Vendr.Checkout.Web.Controllers { [PluginController("VendrCheckout")] public class VendrCheckoutApiController : UmbracoAuthorizedApiController { private IVendrApi _vendrApi; public VendrCheckoutApiController(IVendrApi vendrApi) { _vendrApi = vendrApi; } [HttpGet] [UmbracoApplicationAuthorize(Constants.Applications.Settings)] public object InstallVendrCheckout(int siteRootNodeId) { // Validate the site root node var siteRootNode = Services.ContentService.GetById(siteRootNodeId); var storeId = GetStoreId(siteRootNode); if (!storeId.HasValue) return new { success = false, message = "Couldn't find a store connected to the site root node. Do you have a Vendr store picker configured?" }; var store = _vendrApi.GetStore(storeId.Value); if (store == null) return new { success = false, message = "Couldn't find a store connected to the site root node. Do you have a Vendr store picker configured?" }; // Perform the install new InstallService() .Install(siteRootNodeId, store); // Return success return new { success = true }; } private Guid? GetStoreId(IContent content) { if (content.HasProperty(Core.Constants.Properties.StorePropertyAlias)) return content.GetValue<Guid?>(Core.Constants.Properties.StorePropertyAlias); if (content.ParentId != -1) return GetStoreId(Services.ContentService.GetById(content.ParentId)); return null; } } }
namespace MonitoramentoBasesSql.Models { public class Alerta { public string baseDados { get; set; } public string alerta { get; set; } } }
using System; using System.Collections.Generic; namespace ProduceWithPandas.Models { public class DoubanPostCache { public DateTime LastUpdateDate { get; set; } public bool Initialized { get; set; } = false; public List<DoubanReply> Replies { get; set; } = new List<DoubanReply>(); } public class DoubanReply { public int Id { get; set; } public int UserId { get; set; } public string Name { get; set; } = string.Empty; public string Answer { get; set; } = string.Empty; public DateTime PublishTime { get; set; } public double Score { get; set; } } }