text
stringlengths
13
6.01M
using System; using Yeasca.Metier; using Yeasca.Mongo; namespace Yeasca.Commande { public class AjouterFichierConstatCommande : Commande<IAjouterFichierConstatMessage> { public override ReponseCommande exécuter(IAjouterFichierConstatMessage message) { if (estUnHuissier()) return validerEtEnregistrer(message); return ReponseCommande.générerUnEchec(Ressource.Commandes.ERREUR_AUTH_HUISSIER); } private static ReponseCommande validerEtEnregistrer(IAjouterFichierConstatMessage message) { Guid idConstat; if (Guid.TryParse(message.IdConstat, out idConstat)) return procéderALenregistrement(message, idConstat); return ReponseCommande.générerUnEchec(Ressource.Commandes.REF_CONSTAT_INVALIDE); } private static ReponseCommande procéderALenregistrement(IAjouterFichierConstatMessage message, Guid idConstat) { IEntrepotConstat entrepot = EntrepotMongo.fabriquerEntrepot<IEntrepotConstat>(); Constat constat = entrepot.récupérerLeConstat(idConstat); if (constat != null) return enregistrerLeFichier(message, constat, entrepot); return ReponseCommande.générerUnEchec(Ressource.Commandes.REF_CONSTAT_INVALIDE); } private static ReponseCommande enregistrerLeFichier(IAjouterFichierConstatMessage message, Constat constat, IEntrepotConstat entrepot) { Fichier fichierAAjouter = Fichier.enregistrerLeFichierImageOuAudio(message.Fichier, message.Nom); if (fichierAAjouter != null) return modifierLeConstat(constat, fichierAAjouter, entrepot); return ReponseCommande.générerUnEchec(Ressource.Commandes.ERREUR_AJOUT_FICHIER); } private static ReponseCommande modifierLeConstat(Constat constat, Fichier fichierAAjouter, IEntrepotConstat entrepot) { constat.Fichiers.Add(fichierAAjouter); if (entrepot.modifier(constat)) return ReponseCommande.générerUnSuccès(); return ReponseCommande.générerUnEchec(Ressource.Commandes.ERREUR_ENREG_FICHIER); } } }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System.Linq; using System.Management.Automation.Language; namespace Microsoft.PowerShell.EditorServices.Services.Symbols { /// <summary> /// The vistior used to find the commandAst of a specific location in an AST /// </summary> internal class FindCommandVisitor : AstVisitor { private readonly int lineNumber; private readonly int columnNumber; public SymbolReference FoundCommandReference { get; private set; } public FindCommandVisitor(int lineNumber, int columnNumber) { this.lineNumber = lineNumber; this.columnNumber = columnNumber; } public override AstVisitAction VisitPipeline(PipelineAst pipelineAst) { if (this.lineNumber == pipelineAst.Extent.StartLineNumber) { // Which command is the cursor in? foreach (var commandAst in pipelineAst.PipelineElements.OfType<CommandAst>()) { int trueEndColumnNumber = commandAst.Extent.EndColumnNumber; string currentLine = commandAst.Extent.StartScriptPosition.Line; if (currentLine.Length >= trueEndColumnNumber) { // Get the text left in the line after the command's extent string remainingLine = currentLine.Substring( commandAst.Extent.EndColumnNumber); // Calculate the "true" end column number by finding out how many // whitespace characters are between this command and the next (or // the end of the line). // NOTE: +1 is added to trueEndColumnNumber to account for the position // just after the last character in the command string or script line. int preTrimLength = remainingLine.Length; int postTrimLength = remainingLine.TrimStart().Length; trueEndColumnNumber = commandAst.Extent.EndColumnNumber + (preTrimLength - postTrimLength) + 1; } if (commandAst.Extent.StartColumnNumber <= columnNumber && trueEndColumnNumber >= columnNumber) { this.FoundCommandReference = new SymbolReference( SymbolType.Function, commandAst.CommandElements[0].Extent); return AstVisitAction.StopVisit; } } } return base.VisitPipeline(pipelineAst); } /// <summary> /// Is the position of the given location is in the range of the start /// of the first element to the character before the second element /// </summary> /// <param name="firstExtent">The script extent of the first element of the command ast</param> /// <param name="secondExtent">The script extent of the second element of the command ast</param> /// <returns>True if the given position is in the range of the start of /// the first element to the character before the second element</returns> private bool IsPositionInExtent(IScriptExtent firstExtent, IScriptExtent secondExtent) { return (firstExtent.StartLineNumber == lineNumber && firstExtent.StartColumnNumber <= columnNumber && secondExtent.StartColumnNumber >= columnNumber - 1); } } }
using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using Vaccination.Services; using Vaccination.Models.DTO; using Vaccination.Services.Exceptions; using Vaccination.Models.ViewModel; using System.Diagnostics; using System; namespace Vaccination.Controllers { public class VaccineBatchController : Controller { private readonly VaccineBatchService _vaccineBatchService; private readonly VaccineService _vaccineService; public VaccineBatchController(VaccineBatchService vaccineBatchService, VaccineService vaccineService) { _vaccineBatchService = vaccineBatchService; _vaccineService = vaccineService; } public async Task<IActionResult> Index() { var list = await _vaccineBatchService.FindAllAsync(); ViewBag.Vaccine = await _vaccineService.FindAllAsync(); return View(list); } [Authorize] public async Task<IActionResult> Details(int id) { var dto = await _vaccineBatchService.FindByIdAsync(id); ViewBag.Vaccine = await _vaccineService.FindByIdAsync(dto.VaccineDTO); return View(dto); } [Authorize] public async Task<IActionResult> Create() { ViewBag.Vaccines = await _vaccineBatchService.TypeVaccines(); return View(); } public async Task<IActionResult> Delete(int id) { try { await _vaccineBatchService.RemoveAsync(id); return RedirectToAction(nameof(Index)); } catch (IntegrityException e) { return RedirectToAction(nameof(Error), new { message = e.Message }); } } [Authorize] public async Task<IActionResult> Edit(int? id) { if (id == null) return RedirectToAction(nameof(Error), new { message = "Id not provided"}); var obj = await _vaccineBatchService.FindByIdAsync(id.Value); if (obj == null) return RedirectToAction(nameof(Error), new { message = "Id not found"}); ViewBag.Vaccines = await _vaccineBatchService.TypeVaccines(); return View(obj); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, VaccineBatchDTO dto) { if (!ModelState.IsValid) return View(dto); if (id != dto.Id) return RedirectToAction(nameof(Error), new { message = "Id mismatch" }); try { await _vaccineBatchService.UpdateAsync(dto); return RedirectToAction(nameof(Index)); } catch (ApplicationException e) { return RedirectToAction(nameof(Error), new { message = e.Message}); } } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create(VaccineBatchDTO dto) { if(!ModelState.IsValid) return View(); await _vaccineBatchService.InsertAsync(dto); Response.StatusCode = 200; return RedirectToAction(nameof(Index)); } public IActionResult Error(string message) { var viewModel = new ErrorViewModel { Message = message, RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }; return View(viewModel); } } }
/* * Bungie.Net API * * These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality. * * OpenAPI spec version: 2.1.1 * Contact: support@bungie.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter; namespace BungieNetPlatform.Model { /// <summary> /// DestinyDefinitionsItemsDestinyItemTierTypeInfusionBlock /// </summary> [DataContract] public partial class DestinyDefinitionsItemsDestinyItemTierTypeInfusionBlock : IEquatable<DestinyDefinitionsItemsDestinyItemTierTypeInfusionBlock>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="DestinyDefinitionsItemsDestinyItemTierTypeInfusionBlock" /> class. /// </summary> /// <param name="BaseQualityTransferRatio">The default portion of quality that will transfer from the infuser to the infusee item. (InfuserQuality - InfuseeQuality) * baseQualityTransferRatio &#x3D; base quality transferred..</param> /// <param name="MinimumQualityIncrement">As long as InfuserQuality &gt; InfuseeQuality, the amount of quality bestowed is guaranteed to be at least this value, even if the transferRatio would dictate that it should be less. The total amount of quality that ends up in the Infusee cannot exceed the Infuser&#39;s quality however (for instance, if you infuse a 300 item with a 301 item and the minimum quality increment is 10, the infused item will not end up with 310 quality).</param> public DestinyDefinitionsItemsDestinyItemTierTypeInfusionBlock(float? BaseQualityTransferRatio = default(float?), int? MinimumQualityIncrement = default(int?)) { this.BaseQualityTransferRatio = BaseQualityTransferRatio; this.MinimumQualityIncrement = MinimumQualityIncrement; } /// <summary> /// The default portion of quality that will transfer from the infuser to the infusee item. (InfuserQuality - InfuseeQuality) * baseQualityTransferRatio &#x3D; base quality transferred. /// </summary> /// <value>The default portion of quality that will transfer from the infuser to the infusee item. (InfuserQuality - InfuseeQuality) * baseQualityTransferRatio &#x3D; base quality transferred.</value> [DataMember(Name="baseQualityTransferRatio", EmitDefaultValue=false)] public float? BaseQualityTransferRatio { get; set; } /// <summary> /// As long as InfuserQuality &gt; InfuseeQuality, the amount of quality bestowed is guaranteed to be at least this value, even if the transferRatio would dictate that it should be less. The total amount of quality that ends up in the Infusee cannot exceed the Infuser&#39;s quality however (for instance, if you infuse a 300 item with a 301 item and the minimum quality increment is 10, the infused item will not end up with 310 quality) /// </summary> /// <value>As long as InfuserQuality &gt; InfuseeQuality, the amount of quality bestowed is guaranteed to be at least this value, even if the transferRatio would dictate that it should be less. The total amount of quality that ends up in the Infusee cannot exceed the Infuser&#39;s quality however (for instance, if you infuse a 300 item with a 301 item and the minimum quality increment is 10, the infused item will not end up with 310 quality)</value> [DataMember(Name="minimumQualityIncrement", EmitDefaultValue=false)] public int? MinimumQualityIncrement { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class DestinyDefinitionsItemsDestinyItemTierTypeInfusionBlock {\n"); sb.Append(" BaseQualityTransferRatio: ").Append(BaseQualityTransferRatio).Append("\n"); sb.Append(" MinimumQualityIncrement: ").Append(MinimumQualityIncrement).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as DestinyDefinitionsItemsDestinyItemTierTypeInfusionBlock); } /// <summary> /// Returns true if DestinyDefinitionsItemsDestinyItemTierTypeInfusionBlock instances are equal /// </summary> /// <param name="input">Instance of DestinyDefinitionsItemsDestinyItemTierTypeInfusionBlock to be compared</param> /// <returns>Boolean</returns> public bool Equals(DestinyDefinitionsItemsDestinyItemTierTypeInfusionBlock input) { if (input == null) return false; return ( this.BaseQualityTransferRatio == input.BaseQualityTransferRatio || (this.BaseQualityTransferRatio != null && this.BaseQualityTransferRatio.Equals(input.BaseQualityTransferRatio)) ) && ( this.MinimumQualityIncrement == input.MinimumQualityIncrement || (this.MinimumQualityIncrement != null && this.MinimumQualityIncrement.Equals(input.MinimumQualityIncrement)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.BaseQualityTransferRatio != null) hashCode = hashCode * 59 + this.BaseQualityTransferRatio.GetHashCode(); if (this.MinimumQualityIncrement != null) hashCode = hashCode * 59 + this.MinimumQualityIncrement.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
/* * Megan Hong * Animal Class: creates a new animal with the needed information * holds their attacks, if they've evolved and their species * 1/24/2017 */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AnimalGame { class Animal { protected int _maxHealth; protected int _currentHealth; protected int _attack; protected int _defense; protected int _speed; protected int _level; protected Type _species; protected bool _hasEvolved; protected Attack[] _attackArray = new Attack[3]; public Animal(int maxHealth, int attack, int defense, int speed, Type species, int level,Attack attack1, Attack attack2, Attack attack3) { _maxHealth = maxHealth; _currentHealth = maxHealth; _attack = attack; _defense = defense; _speed = speed; _level = level; _species = species; _attackArray[0] = attack1; _attackArray[1] = attack2; _attackArray[2] = attack3; _hasEvolved = false; } public bool CanAnimalEvolve { get { if (Level == 3 && IsEvolved == false) { return true; } else { return false; } } } public bool IsEvolved { get { if (_level >= 3) { return true; } else { return false; } } } public Type Species { get { return _species; } } public int Level { set { _level = value; } get { return _level; } } public int Health { get { if (_currentHealth > MaxHealth) { _currentHealth = MaxHealth; } return _currentHealth; } set { _currentHealth = value; } } public int MaxHealth { get { return Level * _maxHealth; } } public int Attack { get { return _attack; } set { _attack = value; } } public int Defense { get { return _defense; } set { _defense = value; } } public int Speed { get { return _speed; } set { _speed = value; } } public Attack[] AttackArray { get { return _attackArray; } set { _attackArray = value; } } public bool HasFainted { get { if (Health <= 0) { return true; } else { return false; } } } } }
using GalaSoft.MvvmLight; using ReDefNet; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MKModel { public interface IUserModel : INotifyPropertyChanged { IReadOnlyObservableCollection<IMageKnightModel> Inventory { get; } IReadOnlyObservableCollection<IMageKnightModel> Army { get; } IMageKnightModel SelectedMage { get; set; } int RebellionBoosterPacks { get; set; } string UserName { get; set; } string Password { get; set; } Guid Id { get; set; } bool IsSignedIn { get; set; } void UpdateInventory(ObservableCollection<IMageKnightModel> inventory); void SignIn(string userName, string password); void AddMageToArmy(Guid id, Guid instantiatedId); void AddMageToInventory(Guid id); void OpenBooserPack(BoosterPack rebellion); } public class UserModel : ViewModelBase { UserData user; SerializableObservableCollection<IMageKnightModel> inventory = new SerializableObservableCollection<IMageKnightModel>(); SerializableObservableCollection<IMageKnightModel> army = new SerializableObservableCollection<IMageKnightModel>(); public UserModel(UserData user) { this.user = user; } public string UserName => this.user.UserName; public string Password => this.user.Password; public Guid Id => this.user.Id; public int RebellionBoosterPacks => this.user.RebellionBoosterPacks; //public int WhirlWindBoosterPacks => this.user.WhirlWindBoosterPacks; //public int LancersBoosterPacks => this.user.LancersBoosterPacks; //public int UnlimitedBoosterPacks => this.user.UnlimitedBoosterPacks; //public int SinisterBoosterPacks => this.user.SinisterBoosterPacks; //public int MinionsBoosterPacks => this.user.MinionsBoosterPacks; //public int UprisingBoosterPacks => this.user.UprisingBoosterPacks; } }
using System; namespace List { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } static int[] ZipWith(int[] a, int[] b, Func<int, int, int> zipper) { int[] comodin = new int[a.Length + b.Length]; for (int i = 0; i < a.Length; i++) { } return comodin; } } }
using System; using System.Collections.Generic; using NgTs.Entities; using NgTs.DataAccess; namespace NgTs.BusinessLogic { #region persistent manager public class NgTsUserManager : NgTsManager { public NgTsUserManager() { } //public NgTsUserManager(NgTsSession session) : base(session) //{ //} public NgTsUser CreateNgTsUser( NgTsUser ngtsuser) { if (null == ngtsuser) { throw new ArgumentNullException("NgTsUser"); } using (NgTsTransactionScope scope = new NgTsTransactionScope()) { _AddUpdate( ngtsuser); scope.Complete(); } return ngtsuser; } public void UpdateNgTsUser( NgTsUser ngtsuser) { if (null == ngtsuser) { throw new ArgumentNullException("NgTsUser"); } using (NgTsTransactionScope scope = new NgTsTransactionScope()) { _AddUpdate( ngtsuser); scope.Complete(); } } public NgTsUser GetNgTsUser(long userid) { return _GetNgTsUser(userid); } public List<NgTsUser> GetAll() { return _GetAll(); } private NgTsUserRepository _RepNgTsUser; protected NgTsUserRepository RepNgTsUser { get { return NgTsUtility.GetObject(ref _RepNgTsUser); } } private void _DefaultsForCreate(NgTsUser ngtsuser) { //ngtsuser.CreatedDate = DateTime.UtcNow; //ngtsuser.UpdatedDate = DateTime.UtcNow; //ngtsuser.CreatedById = this.Session.MemberEzkey; //ngtsuser.UpdatedById = this.Session.MemberEzkey; } private void _DefaultsForUpdate(NgTsUser ngtsuser) { //ngtsuser.UpdatedDate = DateTime.UtcNow; //ngtsuser.UpdatedById = this.Session.MemberEzkey; } private void _OverrideEdit(NgTsUser oldValue, NgTsUser newValue) { //newValue.UpdatedDate = oldValue.UpdatedDate; //newValue.UpdatedById = oldValueMemberEzkey; } private void _Validate(NgTsUser ngtsuser) { } private void _AddUpdate(NgTsUser ngtsuser) { if (0 == ngtsuser.UserId) { _DefaultsForCreate(ngtsuser); //ValidationUtility.Validate(ngtsuser); RepNgTsUser.Add(ngtsuser); } else { NgTsUser oldNgTsUser; oldNgTsUser = _GetNgTsUser(ngtsuser.UserId); _DefaultsForUpdate(ngtsuser); _OverrideEdit(oldNgTsUser, ngtsuser); //ValidationUtility.Validate(ngtsuser); RepNgTsUser.Save(ngtsuser); } } private NgTsUser _GetNgTsUser(long userid) { NgTsUser ngtsuser= this.RepNgTsUser.GetNgTsUserByuserid(userid); if (null == ngtsuser) { //throw new NgTsException(NgTsErrorCode.ErruseridInvalid, StringRes.ErruseridInvalid(UserId)); } return ngtsuser; } private List<NgTsUser> _GetAll() { List<NgTsUser> list = this.RepNgTsUser.GetAllFromNgTsUser(); if (null == list) { //throw new NgTsException(NgTsErrorCode.ErruseridInvalid, StringRes.ErruseridInvalid(UserId)); } return list; } } #endregion }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace LateOS.Models { public class cInventarioFisico { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; class ArrayVariableSymbol : VariableSymbol { private LinkedList<int> dimensions = new LinkedList<int>(); public ClassSymbol parameterizedType; public ArrayVariableSymbol(string name, ClassSymbol parameterizedType) : base(name, SymbolTable.arrayClassSymbol) { this.parameterizedType = parameterizedType; } public void addDimension(int size) { dimensions.AddLast(size); } public int getDimension(int dim) { return dimensions.ElementAt(dim); } public int getTotalNumberOfSlots() { int total = 1; foreach(int dim in dimensions) { total *= dim; } return total; } public override string ToString() { StringBuilder res = new StringBuilder(); res.Append(type.name); res.Append("<"); res.Append(parameterizedType.name); res.Append(">"); foreach (int dim in dimensions) { res.Append("["); res.Append(dim); res.Append("]"); } res.Append(" "); res.Append(name); res.Append(" address: "); res.Append(address); return res.ToString(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Http.Headers; using System.Net.Http; using System.Web; using System.Drawing; using System.IO; using Newtonsoft.Json.Linq; using Npgsql; namespace Projeto.Controller { class Identificador { private static String getPersonGroupID() { return "professores"; } private static String getChave() { return "0936a2a9e73c484ab54317c982e95697"; } private static String getURI() { return "https://brazilsouth.api.cognitive.microsoft.com/face/v1.0/identify"; } public static async Task<Boolean> reconhece(NpgsqlConnection conexao, string sResponse,object imagem, FormHistorico telaHistorico) { string sFaceId = ""; Boolean first = false; Boolean bInclui = false; var client = new HttpClient(); // Request headers client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", getChave()); var uri = getURI(); string json = sResponse; JArray aResponse = JArray.Parse(json); foreach (JObject oResponse in aResponse.Children<JObject>()) { foreach (JProperty propriedade in oResponse.Properties()) { string nome = propriedade.Name; if (nome == "faceId") { if (first) { sFaceId = sFaceId + ",\"" + (string)propriedade.Value + "\""; } else { sFaceId = sFaceId + "\"" + (string)propriedade.Value + "\""; } } first = true; } } HttpResponseMessage response; String body = "{\"PersonGroupId\": \"" + getPersonGroupID() + "\"," + "\"faceIds\" : [" + sFaceId + "]," + "\"maxNumOfCandidatesReturned\": 1," + "\"confidenceThreshold\": 0.55}"; byte[] byteData = Encoding.UTF8.GetBytes(body); using (var content = new ByteArrayContent(byteData)) { content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); response = await client.PostAsync(uri, content); Stream responseStream = await response.Content.ReadAsStreamAsync(); responseStream = await response.Content.ReadAsStreamAsync(); using (StreamReader responseReader = new StreamReader(responseStream)) { String sRetorno = responseReader.ReadToEnd(); if (sRetorno.Contains("error")) { return false; } JArray aRetorno = JArray.Parse(sRetorno); foreach (JObject oRetorno in aRetorno.Children<JObject>()) { Boolean inicial = true; string faceId = ""; string identificador = ""; foreach (JProperty propriedadeRetorno in oRetorno.Properties()) { string nome = propriedadeRetorno.Name; if (nome == "faceId") { faceId = (string)propriedadeRetorno.Value; } else if (nome == "candidates") { JArray aCandidatos = (JArray)propriedadeRetorno.Value; foreach (JObject oCandidato in aCandidatos.Children<JObject>()) { foreach (JProperty propriedadeCandidato in oCandidato.Properties()) { string nomeCandidato = propriedadeCandidato.Name; if (nomeCandidato == "personId") { identificador = (string)propriedadeCandidato.Value; bInclui = ControllerReconhecimento.setIncluiAsync(conexao, identificador); } } } } if (!inicial && telaHistorico != null) { adicionaRostoHistorico(conexao, faceId, identificador, sResponse, imagem, telaHistorico); } inicial = false; } } return bInclui; } } } private static void adicionaRostoHistorico(NpgsqlConnection conexao,string faceId, string identificador,string sResponse,object imagem, FormHistorico telaHistorico) { string nomePessoa = ControllerPessoaIdentificador.getNomePessoa(conexao, identificador); string json = sResponse; JArray aResponse = JArray.Parse(json); foreach (JObject oResponse in aResponse.Children<JObject>()) { foreach (JProperty propriedade in oResponse.Properties()) { string nome = propriedade.Name; if (nome == "faceId" && (string)propriedade.Value != faceId) { break; } else if (nome == "faceRectangle") { Retangulo retangulo = propriedade.Value.ToObject<Retangulo>(); Bitmap myBitmap = (Bitmap)imagem; Rectangle cloneRect = new Rectangle(retangulo.left,retangulo.top, (retangulo.width + 20),(retangulo.height+20)); Bitmap BitmapCortado = myBitmap.Clone(cloneRect, myBitmap.PixelFormat); Graphics grafico = Graphics.FromImage(BitmapCortado); grafico.DrawString(nomePessoa, new System.Drawing.Font("Tahoma", 10), Brushes.Purple, new PointF(0, 0)); telaHistorico.pictureBox4.Image = telaHistorico.pictureBox3.Image; telaHistorico.pictureBox3.Image = telaHistorico.pictureBox2.Image; telaHistorico.pictureBox2.Image = telaHistorico.pictureBox1.Image; telaHistorico.pictureBox1.Image = BitmapCortado; } } } } } }
// Copyright 2018 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // NOTE: This file is a modified version of SymbolResolver.cs from OleViewDotNet // https://github.com/tyranid/oleviewdotnet. It's been relicensed from GPLv3 by // the original author James Forshaw to be used under the Apache License for this // project. using System.Runtime.InteropServices; namespace NtApiDotNet.Win32.Debugger { internal sealed partial class DbgHelpSymbolResolver { [StructLayout(LayoutKind.Sequential)] internal struct IMAGEHLP_STACK_FRAME { public long InstructionOffset; public long ReturnOffset; public long FrameOffset; public long StackOffset; public long BackingStoreOffset; public long FuncTableEntry; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public long[] Params; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)] public long[] Reserved; public int Virtual; public int Reserved2; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace ClientesWebApi.Models { [Table("Gustos")] public class Gusto { public int ID { get; set; } public string Nombre { get; set; } public List<Cliente> Clientes { get; set; } // quesesho pibe toy reloco //este es un comentario pal shalooo, deja el hachis //holamundo } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Infra; namespace LeetCodeCSharp { public class _026_UniqueBinarySearchTree { /* * http://leetcode.com/onlinejudge#question_95 */ public List<TreeNode> CreateTree(int left, int right) { List<TreeNode> res = new List<TreeNode>(); if (left > right) return new List<TreeNode>(){null}; for (int i = left; i <= right; i++) { List<TreeNode> leftList = CreateTree(left, i - 1); List<TreeNode> rightList = CreateTree(i + 1, right); foreach (TreeNode l in leftList) { foreach (TreeNode r in rightList) { TreeNode currentRoot = new TreeNode(i); currentRoot.LeftChild = CloneTree(l); currentRoot.RightChild = CloneTree(r); res.Add(currentRoot); } } } return res; } private TreeNode CloneTree(TreeNode root) { if (root == null) return null; TreeNode newRoot = new TreeNode(root.Value); newRoot.LeftChild = CloneTree(root.LeftChild); newRoot.RightChild = CloneTree(root.RightChild); return newRoot; } public int FindCountOfTree(int left, int right) { if (left > right) return 1; int sum = 0; for (int i = left; i <= right; i++) { int m = FindCountOfTree(left, i - 1); int n = FindCountOfTree(i + 1, right); sum += m*n; } return sum; } } }
using System.Windows.Forms; namespace StopWatch { public partial class StopWatch { /// <summary> /// ⓘボタン押下または'I'キー押下時の動作 /// </summary> private void ShowInfoMsg() { MessageBox.Show( "Start/Stop     : ボタン押下 or Shiftキー" + "\n" + "Lap/Reset     : ボタン押下 or Ctrlキー" + "\n" + "StartTimeReset : ボタン押下 or 'R'キー" + "\n" + "\n" + "トグルスイッチ切り替え : F1キー" + "\n" + "\n" + "StopWatchクローズ : ×ボタン押下 or Deleteキー" , "操作方法"); } /// <summary> /// Tell Messaging Time /// 時間を知らせる。 /// </summary> private void TellMsgingTime() { // 時間になったらメッセージボックスを出す。 if ((TglSw.Checked && ts.Minutes == FinMinute.Value && ts.Seconds == FinSecond.Value && ts.Milliseconds < 20 && ts.Milliseconds > 0)) { System.Media.SystemSounds.Hand.Play(); using (NoticeMessage notice = new NoticeMessage()) { MessageBox.Show(notice, "時間です。", "このメッセージは2.5秒後に自動で終了します。", MessageBoxButtons.OK, MessageBoxIcon.Information); } // ここから超過カウントを始める。 nOverMin += 1; } // 超過時間にメッセージボックスを出す。 if ((TglSw.Checked && ts.Minutes == FinMinute.Value + nOverMin && ts.Seconds == FinSecond.Value && ts.Milliseconds < 20 && ts.Milliseconds > 0)) { System.Media.SystemSounds.Hand.Play(); using (NoticeMessage notice = new NoticeMessage()) { MessageBox.Show(notice, nOverMin.ToString() + "分超過です。", "このメッセージは2.5秒後に自動で終了します。", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } nOverMin += 1; } } private void TglChange(TglSwitch tgl) { if (tgl.Checked == true) tgl.Checked = false; else if (tgl.Checked == false) tgl.Checked = true; } /// <summary> /// トグルスイッチ切り替え時、このメソッドを走らせる。 /// </summary> private void TglChanged() { // 超過タイムリセット nOverMin = 0; // トグルスイッチがオンになった場合 if (TglSw.Checked) { // NumericUpDownを活性化する。 FinMinute.Enabled = true; FinSecond.Enabled = true; MessageBox.Show( "時間になったらお知らせします。" , "アラームモードに切り替えました。"); } // トグルスイッチがオフになった場合 if (!TglSw.Checked) { // NumericUpDownを非活性化する。 FinMinute.Enabled = false; FinSecond.Enabled = false; MessageBox.Show( "ひたすら時間計測だけします。" , "通常モードに切り替えました。"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace HOANGTUYENMILKTEE { public partial class Xem_session : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Session["Hoten"] == null) { lbl_Xem_session.Text = "Session đã hết hạn!"; } else { string Xem_session = Session["Hoten"].ToString(); lbl_Xem_session.Text = Xem_session; } } } }
using BookStore.Core.Calculator; using BookStore.Core.Domain; using System; using System.Collections.Generic; namespace BookStore.App { class Program { private const decimal GST = 0.1m; static void Main(string[] args) { var order = OrderService.GetOrder(); var calculator = new OrderCalculator(order); var crimeDiscount = new CategoryCrimeDiscount(); Console.WriteLine($"Order Total Cost Before Tax: {calculator.CalculateOrderTotal(discount: crimeDiscount).ToString("C")}"); Console.WriteLine($"Order Total Cost After Tax: {calculator.CalculateOrderTotal(GST, crimeDiscount).ToString("C")}"); } } }
using System; using MvvmCross.Binding.BindingContext; using MvvmCross.Binding.iOS.Views; using MvvmCross.iOS.Views; using UIKit; using VictimApplication.Core.ViewModels; namespace VictimApplication.iOS.Views { public partial class CasesView : MvxViewController<CasesViewModel> { public CasesView() : base("CasesView", null) { } public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view, typically from a nib. var source = new MvxSimpleTableViewSource(VCTableView, "CaseCell", CaseCell.Key); VCTableView.RowHeight = 142; var set = this.CreateBindingSet<CasesView, CasesViewModel>(); set.Bind(source).To(v => v.CasesObservable); set.Bind(source).For(s => s.SelectionChangedCommand).To(s => s.DisplayMessagesCommand); set.Apply(); VCTableView.Source = source; VCTableView.ReloadData(); } public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); // Release any cached data, images, etc that aren't in use. } } }
namespace AOC19 { using System; using System.Collections.Generic; class Aoc03 : AocBase { public Aoc03(string filepath) : base(filepath) { } public override string PartA(string[] inputs) { List<Point> intersectionPoints = GetIntersectionPoints(inputs); int minDistance = int.MaxValue; foreach(Point p in intersectionPoints) { int distance = Math.Abs(p.X) + Math.Abs(p.Y); if(distance < minDistance) { minDistance = distance; } } return minDistance.ToString(); } public override string PartB(string[] inputs) { List<Point> intersectionPoints = GetIntersectionPoints(inputs); int minDistance = int.MaxValue; foreach(var p in intersectionPoints) { int distance = GetStepsToPoint(p, inputs[0]) + GetStepsToPoint(p, inputs[1]); if (distance < minDistance) { minDistance = distance; } } return minDistance.ToString(); } private int GetStepsToPoint(Point p, string wire) { int distance = 0; var directions = wire.Split(','); Point pointA0 = new Point(0,0); foreach(var direction in directions) { Point pointA1= createPoint(pointA0, direction); if(pointA0.X == pointA1.X && p.X == pointA0.X && Math.Min(pointA0.Y,pointA1.Y) <= p.Y && p.Y <= Math.Max(pointA0.Y,pointA1.Y)) { distance += Math.Abs(p.Y - pointA0.Y); return distance; } else if(pointA0.Y == pointA1.Y && p.Y == pointA0.Y && Math.Min(pointA0.X,pointA1.X) <= p.X && p.X <= Math.Max(pointA0.X,pointA1.X)) { distance += Math.Abs(p.X - pointA0.X); return distance; } else { distance += int.Parse(direction.Substring(1)); } pointA0 = pointA1; } return 0; } private List<Point> GetIntersectionPoints(string [] inputs) { List<Point> intersectionPoints = new List<Point>(); Point pointA0 = new Point(0,0); foreach(var directionA in inputs[0].Split(',')) { Point pointA1 = createPoint(pointA0, directionA); Point pointB0 = new Point(0,0); foreach(var directionB in inputs[1].Split(',')) { Point pointB1 = createPoint(pointB0, directionB); //Check intersection if(pointA0.X == pointA1.X) { if( pointB0.Y == pointB1.Y && Math.Min(pointB0.X, pointB1.X) <= pointA0.X && Math.Max(pointB0.X, pointB1.X) >= pointA0.X && Math.Min(pointA0.Y, pointA1.Y) <= pointB0.Y && Math.Max(pointA0.Y, pointA1.Y) >= pointB0.Y ) { //intersection match intersectionPoints.Add(new Point(pointA0.X, pointB0.Y)); } } else { if( pointB0.Y != pointB1.Y && Math.Min(pointA0.X, pointA1.X) <= pointB0.X && Math.Max(pointA0.X, pointA1.X) >= pointB0.X && Math.Min(pointB0.Y, pointB1.Y) <= pointA0.Y && Math.Max(pointB0.Y, pointB1.Y) >= pointA0.Y ) { //intersection match intersectionPoints.Add(new Point(pointB0.X, pointA0.Y)); } } pointB0 = pointB1; } pointA0 = pointA1; } return intersectionPoints; } private Point createPoint(Point startpoint, string direction) { switch(direction[0]) { case 'R': startpoint.X += int.Parse(direction.Substring(1)); break; case 'L': startpoint.X -= int.Parse(direction.Substring(1)); break; case 'U': startpoint.Y += int.Parse(direction.Substring(1)); break; case 'D': startpoint.Y -= int.Parse(direction.Substring(1)); break; } return startpoint; } private struct Point { public int X; public int Y; public Point(int x, int y) { X= x; Y= y; } } } }
using Bogus; using Everest.Common.Enums; using Everest.ViewModels.Request; using Everest.ViewModels.Response; using System; using System.Collections.Generic; namespace Everest.ViewModels.Fakes { public static class AnuncioFake { public static List<AnuncioResponse> GetAnuncios() { var anuncioIds = 0; var fake = new Faker<AnuncioResponse>() .RuleFor(x => x.IdAnuncio, f => anuncioIds++) .RuleFor(x => x.Activo, f => f.PickRandom(new bool[] { true, false })) .RuleFor(x => x.AdmiteMascota, f => f.PickRandom(new bool[] { true, false })) .RuleFor(x => x.CantidadBaños, f => f.Random.Number(1, 20)) .RuleFor(x => x.CantidadHabitaciones, f => f.Random.Number(1, 20)) .RuleFor(x => x.CantidadParqueos, f => f.Random.Number(1, 20)) .RuleFor(x => x.MaximaCantidadPersonas, f => f.Random.Number(1, 20)) .RuleFor(x => x.Direccion, f => f.Address.StreetAddress()) .RuleFor(x => x.FechaCreacion, f => f.Date.Recent()) .RuleFor(x => x.Latitud, f => Convert.ToDecimal(f.Random.Number(-99, 99).ToString() + "." + f.Random.Number(10000000, 99999999).ToString())) .RuleFor(x => x.Longitud, f => Convert.ToDecimal(f.Random.Number(-99, 99).ToString() + "." + f.Random.Number(10000000, 99999999).ToString())) .RuleFor(x => x.Metros2, f => f.Random.Number(70, 500)) .RuleFor(x => x.Plantas, f => f.Random.Number(1, 5)) .RuleFor(x => x.Precio, f => Math.Round(f.Random.Decimal(100000, 1000000), 2)) .RuleFor(x => x.TieneSeguridadPrivada, f => f.PickRandom(new bool[] { true, false })) .RuleFor(x => x.Evaluaciones, EvaluacionFake.GetEvaluaciones) .RuleFor(x => x.Imagenes, ImagenFake.GetImagenes) .RuleFor(x => x.TipoPropiedad, TipoPropiedadFake.GetTipoPropiedad) .RuleFor(x => x.Usuario, UsuarioFake.GetUsuario(RolEnums.Propietario)) .Generate(10); return fake; } public static CreacionAnuncioRequest GetCreacionAnuncioRequest() { var fake = new Faker<CreacionAnuncioRequest>() .RuleFor(x => x.AdmiteMascota, f => f.PickRandom(new bool[] { true, false})) .RuleFor(x => x.CantidadBaños, f => f.Random.Number(1, 20)) .RuleFor(x => x.CantidadHabitaciones, f => f.Random.Number(1, 20)) .RuleFor(x => x.CantidadParqueos, f => f.Random.Number(1, 20)) .RuleFor(x => x.MaximaCantidadPersonas, f => f.Random.Number(1, 20)) .RuleFor(x => x.Direccion, f => f.Address.StreetAddress()) .RuleFor(x => x.Latitud, f => Convert.ToDecimal(f.Random.Number(-99, 99).ToString() + "." + f.Random.Number(10000000, 99999999).ToString())) .RuleFor(x => x.Longitud, f => Convert.ToDecimal(f.Random.Number(-99, 99).ToString() + "." + f.Random.Number(10000000, 99999999).ToString())) .RuleFor(x => x.Metros2, f => f.Random.Number(70, 500)) .RuleFor(x => x.Plantas, f => f.Random.Number(1, 5)) .RuleFor(x => x.Precio, f => Math.Round(f.Random.Decimal(100000, 1000000), 2)) .RuleFor(x => x.TieneSeguridadPrivada, f => f.PickRandom(new bool[] { true, false })) .RuleFor(x => x.IdTipoPropiedad, f => f.Random.Number(1, 6)) .Generate(); return fake; } public static EdicionAnuncioRequest GetEdicionAnuncioRequest() { var ids = 0; var fake = new Faker<EdicionAnuncioRequest>() .RuleFor(x => x.IdAnuncio, f => ids++) .RuleFor(x => x.AdmiteMascota, f => f.PickRandom(new bool[] { true, false })) .RuleFor(x => x.CantidadBaños, f => f.Random.Number(1, 20)) .RuleFor(x => x.CantidadHabitaciones, f => f.Random.Number(1, 20)) .RuleFor(x => x.CantidadParqueos, f => f.Random.Number(1, 20)) .RuleFor(x => x.MaximaCantidadPersonas, f => f.Random.Number(1, 20)) .RuleFor(x => x.Direccion, f => f.Address.StreetAddress()) .RuleFor(x => x.Latitud, f => Convert.ToDecimal(f.Random.Number(-99, 99).ToString() + "." + f.Random.Number(10000000, 99999999).ToString())) .RuleFor(x => x.Longitud, f => Convert.ToDecimal(f.Random.Number(-99, 99).ToString() + "." + f.Random.Number(10000000, 99999999).ToString())) .RuleFor(x => x.Metros2, f => f.Random.Number(70, 500)) .RuleFor(x => x.Plantas, f => f.Random.Number(1, 5)) .RuleFor(x => x.Precio, f => Math.Round(f.Random.Decimal(100000, 1000000), 2)) .RuleFor(x => x.TieneSeguridadPrivada, f => f.PickRandom(new bool[] { true, false })) .RuleFor(x => x.IdTipoPropiedad, f => f.Random.Number(1, 6)) .Generate(); return fake; } } }
// Accord Statistics Library // The Accord.NET Framework // http://accord-framework.net // // Copyright © César Souza, 2009-2015 // cesarsouza at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // namespace Accord.Statistics.Distributions.Univariate { using System; using Accord.Math; using Accord.Math.Optimization; using Accord.Statistics.Distributions.Fitting; using AForge; /// <summary> /// Cauchy-Lorentz distribution. /// </summary> /// /// <remarks> /// <para> /// The Cauchy distribution, named after Augustin Cauchy, is a continuous probability /// distribution. It is also known, especially among physicists, as the Lorentz /// distribution (after Hendrik Lorentz), Cauchy–Lorentz distribution, Lorentz(ian) /// function, or Breit–Wigner distribution. The simplest Cauchy distribution is called /// the standard Cauchy distribution. It has the distribution of a random variable that /// is the ratio of two independent standard normal random variables. </para> /// /// <para> /// References: /// <list type="bullet"> /// <item><description><a href="http://en.wikipedia.org/wiki/Cauchy_distribution"> /// Wikipedia, The Free Encyclopedia. Cauchy distribution. /// Available from: http://en.wikipedia.org/wiki/Cauchy_distribution </a></description></item> /// </list></para> /// </remarks> /// /// <example> /// <para> /// The following example demonstrates how to instantiate a Cauchy distribution /// with a given location parameter x0 and scale parameter γ (gamma), calculating /// its main properties and characteristics: </para> /// /// <code> /// double location = 0.42; /// double scale = 1.57; /// /// // Create a new Cauchy distribution with x0 = 0.42 and γ = 1.57 /// CauchyDistribution cauchy = new CauchyDistribution(location, scale); /// /// // Common measures /// double mean = cauchy.Mean; // NaN - Cauchy's mean is undefined. /// double var = cauchy.Variance; // NaN - Cauchy's variance is undefined. /// double median = cauchy.Median; // 0.42 /// /// // Cumulative distribution functions /// double cdf = cauchy.DistributionFunction(x: 0.27); // 0.46968025841608563 /// double ccdf = cauchy.ComplementaryDistributionFunction(x: 0.27); // 0.53031974158391437 /// double icdf = cauchy.InverseDistributionFunction(p: 0.69358638272337991); // 1.5130304686978195 /// /// // Probability density functions /// double pdf = cauchy.ProbabilityDensityFunction(x: 0.27); // 0.2009112009763413 /// double lpdf = cauchy.LogProbabilityDensityFunction(x: 0.27); // -1.6048922547266871 /// /// // Hazard (failure rate) functions /// double hf = cauchy.HazardFunction(x: 0.27); // 0.3788491832800277 /// double chf = cauchy.CumulativeHazardFunction(x: 0.27); // 0.63427516833243092 /// /// // String representation /// string str = cauchy.ToString(CultureInfo.InvariantCulture); // "Cauchy(x; x0 = 0.42, γ = 1.57) /// </code> /// /// <para> /// The following example shows how to fit a Cauchy distribution (estimate its /// location and shape parameters) given a set of observation values. </para> /// /// <code> /// // Create an initial distribution /// CauchyDistribution cauchy = new CauchyDistribution(); /// /// // Consider a vector of univariate observations /// double[] observations = { 0.25, 0.12, 0.72, 0.21, 0.62, 0.12, 0.62, 0.12 }; /// /// // Fit to the observations /// cauchy.Fit(observations); /// /// // Check estimated values /// double location = cauchy.Location; // 0.18383 /// double gamma = cauchy.Scale; // -0.10530 /// </code> /// /// <para> /// It is also possible to estimate only some of the Cauchy parameters at /// a time. For this, you can specify a <see cref="CauchyOptions"/> object /// and pass it alongside the observations:</para> /// /// <code> /// // Create options to estimate location only /// CauchyOptions options = new CauchyOptions() /// { /// EstimateLocation = true, /// EstimateScale = false /// }; /// /// // Create an initial distribution with a pre-defined scale /// CauchyDistribution cauchy = new CauchyDistribution(location: 0, scale: 4.2); /// /// // Fit to the observations /// cauchy.Fit(observations, options); /// /// // Check estimated values /// double location = cauchy.Location; // 0.3471218110202 /// double gamma = cauchy.Scale; // 4.2 (unchanged) /// </code> /// </example> /// /// <seealso cref="CauchyOptions"/> /// <seealso cref="WrappedCauchyDistribution"/> /// [Serializable] public class CauchyDistribution : UnivariateContinuousDistribution, IFittableDistribution<double, CauchyOptions>, ISampleableDistribution<double>, IFormattable { // Distribution parameters private double location; // x0 private double scale; // γ (gamma) // Derived measures private double lnconstant; private double constant; private bool immutable; /// <summary> /// Constructs a Cauchy-Lorentz distribution /// with location parameter 0 and scale 1. /// </summary> /// public CauchyDistribution() : this(0, 1) { } /// <summary> /// Constructs a Cauchy-Lorentz distribution /// with given location and scale parameters. /// </summary> /// /// <param name="location">The location parameter x0.</param> /// <param name="scale">The scale parameter gamma (γ).</param> /// public CauchyDistribution([Real] double location, [Positive] double scale) { if (scale <= 0) throw new ArgumentOutOfRangeException("scale", "Scale must be greater than zero."); init(location, scale); } private void init(double location, double scale) { this.location = location; this.scale = scale; this.constant = 1.0 / (Math.PI * scale); this.lnconstant = -Math.Log(Math.PI * scale); } /// <summary> /// Gets the distribution's /// location parameter x0. /// </summary> /// public double Location { get { return location; } } /// <summary> /// Gets the distribution's /// scale parameter gamma. /// </summary> /// public double Scale { get { return scale; } } /// <summary> /// Gets the median for this distribution. /// </summary> /// /// <value>The distribution's median value.</value> /// /// <remarks> /// The Cauchy's median is the location parameter x0. /// </remarks> /// public override double Median { get { System.Diagnostics.Debug.Assert(location.IsRelativelyEqual(base.Median, 1e-6)); return location; } } /// <summary> /// Gets the support interval for this distribution. /// </summary> /// /// <value> /// A <see cref="DoubleRange" /> containing /// the support interval for this distribution. /// </value> /// public override DoubleRange Support { get { return new DoubleRange(Double.NegativeInfinity, Double.PositiveInfinity); } } /// <summary> /// Gets the mode for this distribution. /// </summary> /// /// <value>The distribution's mode value.</value> /// /// <remarks> /// The Cauchy's median is the location parameter x0. /// </remarks> /// public override double Mode { get { return location; } } /// <summary> /// Cauchy's mean is undefined. /// </summary> /// /// <value>Undefined.</value> /// public override double Mean { get { return Double.NaN; } } /// <summary> /// Cauchy's variance is undefined. /// </summary> /// /// <value>Undefined.</value> /// public override double Variance { get { return Double.NaN; } } /// <summary> /// Gets the entropy for this distribution. /// </summary> /// /// <value>The distribution's entropy.</value> /// /// <remarks> /// The Cauchy's entropy is defined as log(scale) + log(4*π). /// </remarks> /// public override double Entropy { get { return Math.Log(scale) + Math.Log(4.0 * Math.PI); } } /// <summary> /// Gets the cumulative distribution function (cdf) for /// this distribution evaluated at point <c>x</c>. /// </summary> /// /// <param name="x">A single point in the distribution range.</param> /// /// <remarks> /// <para> /// The Cumulative Distribution Function (CDF) describes the cumulative /// probability that a given value or any value smaller than it will occur.</para> /// /// <para> /// The Cauchy's CDF is defined as CDF(x) = 1/π * atan2(x-location, scale) + 0.5. /// </para> /// </remarks> /// public override double DistributionFunction(double x) { return 1.0 / Math.PI * Math.Atan2(x - location, scale) + 0.5; } /// <summary> /// Gets the probability density function (pdf) for /// this distribution evaluated at point <c>x</c>. /// </summary> /// /// <param name="x">A single point in the distribution range.</param> /// /// <returns> /// The probability of <c>x</c> occurring /// in the current distribution. /// </returns> /// /// <remarks> /// <para> /// The Probability Density Function (PDF) describes the /// probability that a given value <c>x</c> will occur.</para> /// /// <para> /// The Cauchy's PDF is defined as PDF(x) = c / (1.0 + ((x-location)/scale)²) /// where the constant c is given by c = 1.0 / (π * scale); /// </para> /// </remarks> /// public override double ProbabilityDensityFunction(double x) { double z = (x - location) / scale; return constant / (1.0 + z * z); } /// <summary> /// Gets the log-probability density function (pdf) for /// this distribution evaluated at point <c>x</c>. /// </summary> /// /// <param name="x">A single point in the distribution range.</param> /// /// <returns> /// The logarithm of the probability of <c>x</c> /// occurring in the current distribution. /// </returns> /// /// <remarks> /// The Probability Density Function (PDF) describes the /// probability that a given value <c>x</c> will occur. /// </remarks> /// /// <seealso cref="ProbabilityDensityFunction"/> /// public override double LogProbabilityDensityFunction(double x) { double z = (x - location) / scale; return lnconstant - Math.Log(1.0 + z * z); } /// <summary> /// Fits the underlying distribution to a given set of observations. /// </summary> /// /// <param name="observations">The array of observations to fit the model against. The array /// elements can be either of type double (for univariate data) or /// type double[] (for multivariate data).</param> /// <param name="weights">The weight vector containing the weight for each of the samples.</param> /// <param name="options">Optional arguments which may be used during fitting, such /// as regularization constants and additional parameters.</param> /// /// <remarks> /// Although both double[] and double[][] arrays are supported, /// providing a double[] for a multivariate distribution or a /// double[][] for a univariate distribution may have a negative /// impact in performance. /// </remarks> /// /// <example> /// See <see cref="CauchyDistribution"/>. /// </example> /// public override void Fit(double[] observations, double[] weights, IFittingOptions options) { CauchyOptions cauchyOptions = options as CauchyOptions; if (options != null && cauchyOptions == null) throw new ArgumentException("The specified options' type is invalid.", "options"); Fit(observations, weights, cauchyOptions); } /// <summary> /// Fits the underlying distribution to a given set of observations. /// </summary> /// /// <param name="observations">The array of observations to fit the model against. The array /// elements can be either of type double (for univariate data) or /// type double[] (for multivariate data).</param> /// <param name="weights">The weight vector containing the weight for each of the samples.</param> /// <param name="options">Optional arguments which may be used during fitting, such /// as regularization constants and additional parameters.</param> /// /// <remarks> /// Although both double[] and double[][] arrays are supported, /// providing a double[] for a multivariate distribution or a /// double[][] for a univariate distribution may have a negative /// impact in performance. /// </remarks> /// /// <example> /// See <see cref="CauchyDistribution"/>. /// </example> /// public void Fit(double[] observations, double[] weights, CauchyOptions options) { if (immutable) throw new InvalidOperationException("This object can not be modified."); if (weights != null) throw new ArgumentException("This distribution does not support weighted samples."); bool useMLE = true; bool estimateT = true; bool estimateS = true; if (options != null) { useMLE = options.MaximumLikelihood; estimateT = options.EstimateLocation; estimateS = options.EstimateScale; } double t0 = location; double s0 = scale; int n = observations.Length; DoubleRange range; double median = Measures.Quartiles(observations, out range, alreadySorted: false); if (estimateT) t0 = median; if (estimateS) s0 = range.Length; if (useMLE) { // Minimize the log-likelihood through numerical optimization var lbfgs = new BoundedBroydenFletcherGoldfarbShanno(2); lbfgs.LowerBounds[1] = 0; // scale must be positive // Define the negative log-likelihood function, // which is the objective we want to minimize: lbfgs.Function = (parameters) => { // Assume location is the first // parameter, shape is the second double t = (estimateT) ? parameters[0] : t0; double s = (estimateS) ? parameters[1] : s0; if (s < 0) s = -s; double sum = 0; for (int i = 0; i < observations.Length; i++) { double y = (observations[i] - t); sum += Math.Log(s * s + y * y); } return -(n * Math.Log(s) - sum - n * Math.Log(Math.PI)); }; lbfgs.Gradient = (parameters) => { // Assume location is the first // parameter, shape is the second double t = (estimateT) ? parameters[0] : t0; double s = (estimateS) ? parameters[1] : s0; double sum1 = 0, sum2 = 0; for (int i = 0; i < observations.Length; i++) { double y = (observations[i] - t); sum1 += y / (s * s + y * y); sum2 += s / (s * s + y * y); } double dt = -2.0 * sum1; double ds = +2.0 * sum2 - n / s; double[] g = new double[2]; g[0] = estimateT ? dt : 0; g[1] = estimateS ? ds : 0; return g; }; // Initialize using the sample median as starting // value for location, and half interquartile range // for shape. double[] values = { t0, s0 }; // Minimize lbfgs.Minimize(values); // Check solution t0 = lbfgs.Solution[0]; s0 = lbfgs.Solution[1]; } init(t0, s0); // Become the new distribution } /// <summary> /// Gets the Standard Cauchy Distribution, /// with zero location and unitary shape. /// </summary> /// public static CauchyDistribution Standard { get { return standard; } } private static readonly CauchyDistribution standard = new CauchyDistribution() { immutable = true }; /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// /// <returns> /// A new object that is a copy of this instance. /// </returns> /// public override object Clone() { return new CauchyDistribution(location, scale); } #region ISamplableDistribution<double> Members /// <summary> /// Generates a random vector of observations from the current distribution. /// </summary> /// /// <param name="samples">The number of samples to generate.</param> /// <returns>A random vector of observations drawn from this distribution.</returns> /// public override double[] Generate(int samples) { return Random(location, scale, samples); } /// <summary> /// Generates a random observation from the current distribution. /// </summary> /// /// <returns>A random observations drawn from this distribution.</returns> /// public override double Generate() { return Random(location, scale); } /// <summary> /// Generates a random observation from the /// Cauchy distribution with the given parameters. /// </summary> /// /// <param name="location">The location parameter x0.</param> /// <param name="scale">The scale parameter gamma.</param> /// /// <returns>A random double value sampled from the specified Cauchy distribution.</returns> /// public static double Random(double location, double scale) { // Generate uniform U on [-PI/2, +PI/2] double x = UniformContinuousDistribution.Random(-Math.PI / 2.0, +Math.PI / 2.0); return Math.Tan(x) * scale + location; } /// <summary> /// Generates a random vector of observations from the /// Cauchy distribution with the given parameters. /// </summary> /// /// <param name="location">The location parameter x0.</param> /// <param name="scale">The scale parameter gamma.</param> /// <param name="samples">The number of samples to generate.</param> /// /// <returns>An array of double values sampled from the specified Cauchy distribution.</returns> /// public static double[] Random(double location, double scale, int samples) { // Generate uniform U on [-PI/2, +PI/2] double[] x = UniformContinuousDistribution.Random(-Math.PI / 2.0, +Math.PI / 2.0, samples); for (int i = 0; i < x.Length; i++) x[i] = Math.Tan(x[i]) * scale + location; return x; } #endregion /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> /// public override string ToString(string format, IFormatProvider formatProvider) { return String.Format(formatProvider, "Cauchy(x; x0 = {0}, γ = {1})", location.ToString(format, formatProvider), scale.ToString(format, formatProvider)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using consoleInverseKinematicsCalc; namespace consoleInverseKinematicsCalc { class Program { static void Main(string[] args) { InvKin iKin = new InvKin(); InKIN inki =new InKIN(); double [] Angles ; double a , b , c ; Console.WriteLine("Enter a = " ); a = double.Parse(Console.ReadLine()); Console.WriteLine("Enter b = " ); b = double.Parse(Console.ReadLine()); Console.WriteLine("Enter c = " ); c = double.Parse(Console.ReadLine()); Angles = inki.calcIK(a, b, c); // Angles = iKin.invKin(a, b, c); Console.WriteLine(" Angles are = {0} >> {1} >> {2} >> {3} >> {4} >> {5} ", Angles[0], Angles[1], Angles[2], Angles[3], Angles[4], Angles[5]); //Console.WriteLine(" Angles are = {0}", iKin.invKin(a, b, c)); Console.ReadKey(); } } }
using LuigiApp.Invoice.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace LuigiApp.Invoice.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class AddProductPage : ContentPage { AddProductViewModel viewModel; public AddProductPage() { InitializeComponent(); BindingContext = viewModel = new AddProductViewModel(); } protected override bool OnBackButtonPressed() { viewModel.Unsubscribe(); return false; } private void OnProductSelected(object sender, EventArgs e) { var elemnt = sender as Label; if (elemnt == null) { return; } viewModel.SelectProductCommand.Execute(elemnt.BindingContext as Product.Models.Product); } private void ValidateInt(object sender, TextChangedEventArgs e) { if (e.NewTextValue.Contains("-")) { var elemnt = sender as Entry; elemnt.Text = e.OldTextValue; } } } }
using ExamenSG_AJAXyJS_DAL.Connection; using ExamenSG_AJAXyJS_Entities; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExamenSG_AJAXyJS_DAL.Lists { public class clsListadoAlgo { public clsListadoAlgo() { } /// <summary> /// Esta funcion nos permite obtner el listado de heroes completo /// </summary> /// <returns>Un listado con todos los super Heroes</returns> public List<clsAlgo> obtnerListadoHeroes() { List<clsAlgo> listadoHeroes = new List<clsAlgo>(); try { clsMyConnection myConnection = new clsMyConnection(); SqlConnection connection = new SqlConnection(); SqlCommand command = new SqlCommand(); SqlDataReader reader; clsAlgo heroe; connection = myConnection.getConnection(); command.CommandText = "Select * from dbo.superheroes"; command.Connection = connection; reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { heroe = new clsAlgo(); heroe.idHeroe = (int)reader["idSuperheroe"]; if (!String.IsNullOrEmpty(reader["nombreSuperheroe"].ToString())) { heroe.nombreHeroe = (string)reader["nombreSuperheroe"]; } listadoHeroes.Add(heroe); } } reader.Close(); myConnection.closeConnection(ref connection); } catch (SqlException) { throw; } return listadoHeroes; } /// <summary> /// Esta funcion devuelve un heroe principalmente para conseguir el id /// </summary> /// <param name="heroe">El nombre del heroe que necesitamos</param> /// <returns>El heroe de la base de datos que tenga el mismo nombre</returns> public clsAlgo obtenerHeroe(int heroe) { clsAlgo superHeroe = new clsAlgo(); try { clsMyConnection myConnection = new clsMyConnection(); SqlConnection connection = new SqlConnection(); SqlCommand command = new SqlCommand(); SqlDataReader reader; connection = myConnection.getConnection(); command.CommandText = "Select * from dbo.superheroes where idSuperheroe = @id"; command.Parameters.Add("@id", System.Data.SqlDbType.Int).Value = heroe; command.Connection = connection; reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { superHeroe = new clsAlgo(); superHeroe.idHeroe = (int)reader["idSuperheroe"]; if (!String.IsNullOrEmpty(reader["nombreSuperheroe"].ToString())) { superHeroe.nombreHeroe = (string)reader["nombreSuperheroe"]; } } } reader.Close(); myConnection.closeConnection(ref connection); } catch (SqlException) { } return superHeroe; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace market_takip { public partial class Form16 : Form { public Form1 frm1; public Form16() { InitializeComponent(); } bool durum = false; void stokUrunAdetKontrol() { frm1.bag.Open(); frm1.kmt.Connection = frm1.bag; frm1.kmt.CommandText = "Select adet from stokbil Where urunAdi='" + comboBox2.Text + "'"; SqlDataReader oku; oku = frm1.kmt.ExecuteReader(); while (oku.Read()) { if (int.Parse(textBox7.Text) <= int.Parse(oku[0].ToString())) durum = true; } frm1.kmt.Dispose(); frm1.bag.Close(); } private void Form16_Load(object sender, EventArgs e) { frm1.musteriListele(); frm1.urunSatisComboEkle(); try { dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dataGridView1.Columns[0].HeaderText = "Müşteri Adı"; dataGridView1.Columns[1].HeaderText = "Müşteri Soyadı"; dataGridView1.Columns[2].HeaderText = "Tc Kimlik"; dataGridView1.Columns[3].HeaderText = "Cep Tel"; dataGridView1.Columns[4].HeaderText = "Ev Tel"; dataGridView1.Columns[5].HeaderText = "Adres"; } catch { ; } } private void btnAra_Click(object sender, EventArgs e) { SqlDataAdapter adtr = new SqlDataAdapter("select musteriAdi,musteriSoyadi,tcKimlik,cepTel,evTel,adres From musteribil", frm1.bag); string alan = ""; if (comboBox1.Text == "Müşteri Adı") alan = "musteriAdi"; else if (comboBox1.Text == "Müşteri Soyadı") alan = "musteriSoyadi"; else if (comboBox1.Text == "Tc Kimlik") alan = "tcKimlik"; else if (comboBox1.Text == "Cep Tel") alan = "cepTel"; else if (comboBox1.Text == "Ev Tel") alan = "evTel"; else if (comboBox1.Text == "Adres") alan = "adres"; if (comboBox1.Text == "Tümü") { frm1.bag.Open(); frm1.tabloMusteri.Clear(); frm1.kmt.Connection = frm1.bag; frm1.kmt.CommandText = "Select musteriAdi,musteriSoyadi,tcKimlik,cepTel,evTel,adres from musteribil"; adtr.SelectCommand = frm1.kmt; adtr.Fill(frm1.tabloMusteri); frm1.bag.Close(); } if (alan != "") { frm1.bag.Open(); adtr.SelectCommand.CommandText = " Select musteriAdi,musteriSoyadi,tcKimlik,cepTel,evTel,adres From musteribil" + " where(" + alan + " like '%" + textBox1.Text + "%' )"; frm1.tabloMusteri.Clear(); adtr.Fill(frm1.tabloMusteri); frm1.bag.Close(); } } private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) { textBox3.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString(); textBox4.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString(); textBox5.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString(); } private void btnSatisYap_Click(object sender, EventArgs e) { if (textBox2.Text.Trim() != "" && textBox3.Text.Trim() != "" && textBox4.Text.Trim() != "" && textBox7.Text.Trim() != "" && textBox6.Text.Trim() != "") { stokUrunAdetKontrol(); if (durum == true) { int adet; adet = int.Parse(textBox7.Text); frm1.bag.Open();// frm1.kmt.Connection = frm1.bag; frm1.kmt.CommandText = "INSERT INTO satisbil(faturaNo,musteriAdi,musteriSoyadi,tcKimlik,urunAdi,satisFiyat,adet,toplamTutar,kasaNo,tarih) VALUES ('" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + comboBox2.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "','" + textBox9.Text + "','" + dateTimePicker1.Text + "') "; frm1.kmt.ExecuteNonQuery(); frm1.kmt.CommandText = "UPDATE stokbil SET adet=adet-'" + adet + "' WHERE urunAdi='" + comboBox2.Text + "' "; frm1.kmt.ExecuteNonQuery(); frm1.kmt.Dispose(); frm1.bag.Close(); frm1.gununSatisListele(); frm1.urunSatisComboEkle(); MessageBox.Show("Kayıt işlemi tamamlandı ! "); for (int i = 0; i < this.Controls.Count; i++) { if (this.Controls[i] is TextBox) this.Controls[i].Text = ""; } comboBox2.Text = ""; } else MessageBox.Show("Stokta yeterli sayıda ürün yok"); } else { MessageBox.Show("Lütfen gerekli alanları doldurunuz"); } } private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) { frm1.urunSatisFiyatTextEkle(); } private void kapat_Click(object sender, EventArgs e) { Close(); } private void textBox7_TextChanged(object sender, EventArgs e) { try { textBox8.Text = (int.Parse(textBox6.Text) * int.Parse(textBox7.Text)).ToString(); } catch { ; } } private void comboBox2_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Restaurant_API.Models { public class Table { public int TableId { get; set; } public int? TableCategoryId { get; set; } public bool IsBooked { get; set; } = false; public TableCategory TableCategory { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using Unity.Entities; using Unity.Mathematics; using Unity.Transforms; public class ECSInterface : MonoBehaviour { private World world; public GameObject sheepPrefab; public GameObject tankPrefab; public GameObject palmPrefab; private const float range = 10; private void Start() { world = World.DefaultGameObjectInjectionWorld; Debug.Log("All Entities: "+ world.GetExistingSystem<MoveSystem>().EntityManager.GetAllEntities().Length); EntityManager entityManager = world.GetExistingSystem<MoveSystem>().EntityManager; EntityQuery entityQuery = entityManager.CreateEntityQuery(ComponentType.ReadOnly<SheepData>()); Debug.Log("Sheep Entities: "+ entityQuery.CalculateEntityCount()); } private void Update() { if (Input.GetKeyDown(KeyCode.Space)) { AddTank(); } if (Input.GetKeyDown(KeyCode.P)) { AddPalm(); } } private void AddTank() { Vector3 pos = new Vector3(UnityEngine.Random.Range(-10,10), 0, UnityEngine.Random.Range(-10,10)); Instantiate(tankPrefab, pos, Quaternion.identity); } private void AddPalm() { EntityManager manager = World.DefaultGameObjectInjectionWorld.EntityManager; var settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, null); var prefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(palmPrefab, settings); var instance = manager.Instantiate(prefab); var position = transform.TransformPoint(new float3(UnityEngine.Random.Range(-range, range), 0, UnityEngine.Random.Range(-range, range))); manager.SetComponentData(instance, new Translation {Value = position}); manager.SetComponentData(instance, new Rotation {Value = new quaternion(0,0,0,0)}); // EntityManager manager = World.DefaultGameObjectInjectionWorld.EntityManager; // var settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, null); // var prefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(palmPrefab, settings); // // // var instance = manager.Instantiate(prefab); // var position = transform.TransformPoint(new float3(UnityEngine.Random.Range(-range, range), UnityEngine.Random.Range(0, range*2), UnityEngine.Random.Range(-range, range))); // manager.SetComponentData(instance, new Translation {Value = position}); // manager.SetComponentData(instance, new Rotation {Value = new quaternion(0,0,0,0)}); } }
using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ValidationEngine.Test { class ValidationTest { [Test] public void TrueForValidAddress() { var sut = new EmailValidator(); var istrue = sut.ValidateEmailAddress("exe@mail.com"); Assert.IsTrue(istrue); } } }
using Microsoft.EntityFrameworkCore.Migrations; namespace E_Learning.Data.Migrations { public partial class init : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Korisnik", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Ime = table.Column<string>(nullable: true), Prezime = table.Column<string>(nullable: true), Email = table.Column<string>(nullable: true), Password = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Korisnik", x => x.Id); }); migrationBuilder.CreateTable( name: "Oblast", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Naziv = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Oblast", x => x.Id); }); migrationBuilder.CreateTable( name: "Kviz", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Rezultat = table.Column<int>(nullable: false), KorisnikId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Kviz", x => x.Id); table.ForeignKey( name: "FK_Kviz_Korisnik_KorisnikId", column: x => x.KorisnikId, principalTable: "Korisnik", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Kurs", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Naziv = table.Column<string>(nullable: true), OblastId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Kurs", x => x.Id); table.ForeignKey( name: "FK_Kurs_Oblast_OblastId", column: x => x.OblastId, principalTable: "Oblast", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Lekcija", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Ime = table.Column<string>(nullable: true), KursId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Lekcija", x => x.Id); table.ForeignKey( name: "FK_Lekcija_Kurs_KursId", column: x => x.KursId, principalTable: "Kurs", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Pitanje", columns: table => new { PitanjeId = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), PitanjeTekst = table.Column<string>(nullable: true), TacanOdg = table.Column<string>(nullable: true), NetacenOdg1 = table.Column<string>(nullable: true), NetacenOdg2 = table.Column<string>(nullable: true), NetacenOdg3 = table.Column<string>(nullable: true), KursId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Pitanje", x => x.PitanjeId); table.ForeignKey( name: "FK_Pitanje_Kurs_KursId", column: x => x.KursId, principalTable: "Kurs", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Upisivanje", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), KorisnikId = table.Column<int>(nullable: false), KursId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Upisivanje", x => x.Id); table.ForeignKey( name: "FK_Upisivanje_Korisnik_KorisnikId", column: x => x.KorisnikId, principalTable: "Korisnik", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Upisivanje_Kurs_KursId", column: x => x.KursId, principalTable: "Kurs", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Odgovor", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), JeLiTacno = table.Column<bool>(nullable: false), PitanjeId = table.Column<int>(nullable: false), KvizId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Odgovor", x => x.Id); table.ForeignKey( name: "FK_Odgovor_Kviz_KvizId", column: x => x.KvizId, principalTable: "Kviz", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Odgovor_Pitanje_PitanjeId", column: x => x.PitanjeId, principalTable: "Pitanje", principalColumn: "PitanjeId", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Kurs_OblastId", table: "Kurs", column: "OblastId"); migrationBuilder.CreateIndex( name: "IX_Kviz_KorisnikId", table: "Kviz", column: "KorisnikId"); migrationBuilder.CreateIndex( name: "IX_Lekcija_KursId", table: "Lekcija", column: "KursId"); migrationBuilder.CreateIndex( name: "IX_Odgovor_KvizId", table: "Odgovor", column: "KvizId"); migrationBuilder.CreateIndex( name: "IX_Odgovor_PitanjeId", table: "Odgovor", column: "PitanjeId"); migrationBuilder.CreateIndex( name: "IX_Pitanje_KursId", table: "Pitanje", column: "KursId"); migrationBuilder.CreateIndex( name: "IX_Upisivanje_KorisnikId", table: "Upisivanje", column: "KorisnikId"); migrationBuilder.CreateIndex( name: "IX_Upisivanje_KursId", table: "Upisivanje", column: "KursId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Lekcija"); migrationBuilder.DropTable( name: "Odgovor"); migrationBuilder.DropTable( name: "Upisivanje"); migrationBuilder.DropTable( name: "Kviz"); migrationBuilder.DropTable( name: "Pitanje"); migrationBuilder.DropTable( name: "Korisnik"); migrationBuilder.DropTable( name: "Kurs"); migrationBuilder.DropTable( name: "Oblast"); } } }
using Serializer; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Clases { public class Warehouse { private static Warehouse warehouse; private List<CarPart> availableParts; static Warehouse() { warehouse = new Warehouse(); warehouse.availableParts = new List<CarPart>(); } /// <summary> /// Returns the only instance of Warehouse. /// </summary> /// <returns></returns> public static Warehouse Get_Warehouse() { return Warehouse.warehouse; } /// <summary> /// Recieves a Parts list ass a request, it check whether it has enough stock of each part, if it has, it saves a the request as an XML file. /// if it doesn't, throws a new exception. /// </summary> /// <param name="newRequest"></param> public void ReceiveRequest(List<CarPart> newRequest) { if(newRequest.Count > 0) { foreach(CarPart item in newRequest) { if( !availableParts.Contains(item) || (availableParts.Contains(item) && availableParts[availableParts.IndexOf(item)].Stock < item.CheckStock()) ) { throw new Exception("Not enough stock"); } } /* * Here a message or request notification should be sent to the warehouse */ this.Save(Environment.CurrentDirectory + "\\Request_" + DateTime.Now.ToString("yyyy-MM-dd T HH-mm-ss") + ".xml", newRequest); foreach (CarPart item in newRequest) { availableParts[availableParts.IndexOf(item)].ReduceStock(item.CheckStock()); } } } /// <summary> /// Returns the List of CarParts. /// </summary> /// <returns></returns> public List<CarPart> GetParts() { return this.availableParts; } /// <summary> /// Recieves CarParts, if they are already on stock, it adds the new amount to it, if they are not, they are added to the Available Parts list. /// </summary> /// <param name="newParts"></param> public void AddParts(List<CarPart> newParts) { foreach(CarPart item in newParts) { if(availableParts.Contains(item)) { availableParts[availableParts.IndexOf(item)].AddStock(item.CheckStock()); } else { availableParts.Add(item); } } } /// <summary> /// Calls the Save method passing the available parts list. /// </summary> /// <param name="path"></param> public void Save(string path) { this.Save(path, this.availableParts); } /// <summary> /// Saves the recieved CarPart List to the recieved path as an XML document. /// </summary> /// <param name="path"></param> /// <param name="parts"></param> public void Save(string path, List<CarPart> parts) { List<Entry<string, int>> aux = new List<Entry<string, int>>(); foreach(CarPart item in parts) { aux.Add(new Entry<string, int>(item.Id, item.Stock)); } try { XML<List<Entry<string, int>>> serializer = new XML<List<Entry<string, int>>>(); serializer.Save(aux, path); } catch (Exception e) { throw e; } } /// <summary> /// Tries to load CarParts from the recieved path. /// </summary> /// <param name="path"></param> public void Load(string path) { XML<List<Entry<string, int>>> serializer = new XML<List<Entry<string, int>>>(); List<Entry<string, int>> aux = new List<Entry<string, int>>(); try { if(serializer.Read(path, out aux)) { this.LoadObjects( aux ); } } catch(Exception e) { throw new Exception("Problems when loading the Warehouse"); } } /// <summary> /// Translates the loaded file (strings and ints) to CarParts /// </summary> /// <param name="aux"></param> public void LoadObjects(List<Entry<string, int>> aux) { this.availableParts.Clear(); foreach (Entry<string, int> item in aux) { this.availableParts.Add(item.Key.LoadPartFromString()); this.availableParts.Last().Stock = item.Value; } } /// <summary> /// Loads the CarParts from a SQL database. /// </summary> public bool LoadFromDatabase() { this.availableParts.Clear(); this.availableParts = SQLConnection.LoadWarehouse(); if(availableParts.Count > 0) { return true; } else { return false; } } /// <summary> /// Saves the current car parts to the SQL database. /// </summary> public void SaveToDatabase() { SQLConnection.SaveWarehouse(this.availableParts); } } }
using CapstoneTravelApp.DatabaseTables; using CapstoneTravelApp.HelperFolders; using SQLite; using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace CapstoneTravelApp.EntertainmentFolder { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class AddEntertainmentPage : ContentPage { private SQLiteConnection conn; private Trips_Table currentTrip; public AddEntertainmentPage(Trips_Table _currentTrip) { InitializeComponent(); currentTrip = _currentTrip; Title = "Add Entertainment"; conn = DependencyService.Get<ITravelApp_db>().GetConnection(); } private async void SaveButton_Clicked(object sender, EventArgs e) { string cInDate = startDatePicker.Date.ToString("MM/dd/yyyy"); string cInTime = DateTime.Today.Add(startTimePicker.Time).ToString(startTimePicker.Format); DateTime cInDateFull = Convert.ToDateTime(cInDate + " " + cInTime); string cOutDate = endDatePicker.Date.ToString("MM/dd/yyyy"); string cOutTime = DateTime.Today.Add(endTimePicker.Time).ToString(endTimePicker.Format); DateTime cOutFull = Convert.ToDateTime(cOutDate + " " + cOutTime); conn.CreateTable<Entertainment_Table>(); var entertain = new Entertainment_Table(); entertain.TripId = currentTrip.TripId; entertain.EntertainName = entertainNameEntry.Text; entertain.EnterainAddress = entertainLocEntry.Text; entertain.EntertainPhone = entertainPhoneEntry.Text; entertain.EntertaninStart = cInDateFull; entertain.EntertainEnd = cOutFull; entertain.EntertainNotifications = notificationSwitch.IsToggled == true ? 1 : 0; if (UserHelper.IsNull(entertainNameEntry.Text)) { if (entertain.EntertaninStart <= entertain.EntertainEnd) { if (UserHelper.PhoneCheck(entertainPhoneEntry.Text)) { conn.Insert(entertain); await DisplayAlert("Notice", "Entertainment record created", "Ok"); await Navigation.PopModalAsync(); } else { await DisplayAlert("Warning", "Phone Number may only be 10 digits and only contain numbers", "Ok"); } } else { await DisplayAlert("Warning", "Check-in must be earlier than check-out", "Ok"); } } else await DisplayAlert("Warning", "Entertainment Name is required", "Ok"); } } }
namespace TeamBuilder.App.Core { using System; public class Engine { private CommandDispatcher commandDispacher; public Engine(CommandDispatcher commandDispacher) { this.commandDispacher = commandDispacher; } public void Run() { while(true) { try { string input = Console.ReadLine(); string output = this.commandDispacher.Dispatch(input); Console.WriteLine(output); } catch(Exception e) { Console.WriteLine(e.GetBaseException().Message); } } } } }
namespace Singleton { public class GlobalVariableBag { /// <summary> /// Global variable that anyone can modify. /// </summary> public static string GlobalVariable { get; set; } } }
using System; using System.Threading.Tasks; using GreenPipes; using MassTransit; namespace Sandbox.Blocks { public class TrackingPoller : IBlock { public string Name => "TrackingPoller"; public void Setup(IReceiveEndpointConfigurator x) { x.UseRateLimit(10); x.UseRetry(r => r.Immediate(3)); x.ConsumerWithDI<Consumer>(); } public class Consumer: IConsumer<JobBatch> { readonly IPoller _poller; public Consumer(IPoller poller) { _poller = poller; } public async Task Consume(ConsumeContext<JobBatch> x) { var raw = await _poller.Poll(); await x.Send(new Uri("TrackingMapper"), raw); } } } public class RawTracking {} public interface IPoller { Task<RawTracking> Poll(); } public static class Extensions { public static void ConsumerWithDI<TConsumer>(this IReceiveEndpointConfigurator x) where TConsumer : class, IConsumer { //... } } }
using System.Threading.Tasks; using Meziantou.Analyzer.Rules; using TestHelper; using Xunit; namespace Meziantou.Analyzer.Test.Rules; public sealed class OptionalParametersAttributeAnalyzerMA0088Tests { private static ProjectBuilder CreateProjectBuilder() { return new ProjectBuilder() .WithAnalyzer<OptionalParametersAttributeAnalyzer>(id: "MA0088"); } [Fact] public async Task DefaultParameterValue() { const string SourceCode = @" using System.ComponentModel; using System.Runtime.InteropServices; class Test { void A([Optional, DefaultParameterValue(10)]int a) { } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .ValidateAsync(); } [Fact] public async Task DefaultValue() { const string SourceCode = @" using System.ComponentModel; using System.Runtime.InteropServices; class Test { void A([DefaultValue(10)]int [|a|]) { } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .ValidateAsync(); } [Fact] public async Task BothAttributes() { const string SourceCode = @" using System.ComponentModel; using System.Runtime.InteropServices; class Test { void A([Optional, DefaultParameterValue(10), DefaultValue(10)]int a) { } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .ValidateAsync(); } }
using System.Collections.Generic; namespace NetDaemon.Common { /// <summary> /// Type of log to supress /// </summary> public enum SupressLogType { /// <summary> /// Supress Missing Execute Error in a method /// </summary> MissingExecute } /// <summary> /// Attribute to mark function as callback for state changes /// </summary> [System.AttributeUsage(System.AttributeTargets.Method, Inherited = false, AllowMultiple = true)] public sealed class DisableLogAttribute : System.Attribute { // See the attribute guidelines at // http://go.microsoft.com/fwlink/?LinkId=85236 private readonly SupressLogType[]? _logTypesToSupress; /// <summary> /// Default constructor /// </summary> /// <param name="logTypes">List of logtypes to supress</param> public DisableLogAttribute(params SupressLogType[] logTypes) => _logTypesToSupress = logTypes; /// <summary> /// Log types to supress /// </summary> public IEnumerable<SupressLogType>? LogTypesToSupress => _logTypesToSupress; /// <summary> /// Log tupes used /// </summary> public SupressLogType[]? LogTypes { get; } } /// <summary> /// Attribute to mark function as callback for service calls /// </summary> [System.AttributeUsage(System.AttributeTargets.Method, Inherited = false, AllowMultiple = false)] public sealed class HomeAssistantServiceCallAttribute : System.Attribute { } /// <summary> /// Attribute to mark function as callback for state changes /// </summary> [System.AttributeUsage(System.AttributeTargets.Method, Inherited = false, AllowMultiple = true)] public sealed class HomeAssistantStateChangedAttribute : System.Attribute { /// <summary> /// Default constructor /// </summary> /// <param name="entityId">Unique id of entity</param> /// <param name="to">To state filtered</param> /// <param name="from">From state filtered</param> /// <param name="allChanges">Get all changes, ie also attribute changes</param> public HomeAssistantStateChangedAttribute(string entityId, object? to = null, object? from = null, bool allChanges = false) { EntityId = entityId; To = to; From = from; AllChanges = allChanges; } /// <summary> /// Get all changes, even if only attribute changes /// </summary> public bool AllChanges { get; } /// <summary> /// Unique id of the entity /// </summary> public string EntityId { get; } /// <summary> /// From state filter /// </summary> public object? From { get; } /// <summary> /// To state filter /// </summary> public object? To { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using System.Data.SqlClient; namespace Combination { class Sql { DataTable dt; DataSet ds; SqlConnection con = new SqlConnection(@"Data Source=localhost;Initial Catalog=ChengyiYuntech;Integrated Security=True"); public string CYDB = "AIS20190520180820"; public string CKDB = "AIS20190520181425"; public DataTable getQuery(string Query) { SqlDataAdapter sda = new SqlDataAdapter(Query, con); dt = new DataTable(); dt.Clear(); sda.Fill(dt); return dt; } public DataSet SqlCmdDS(string tableCmd) { SqlDataAdapter da = new SqlDataAdapter(tableCmd, con); ds = new DataSet(); ds.Clear(); da.Fill(ds); return ds; } public void sqlCmd(string query) { con.Open(); SqlCommand cmd = new SqlCommand(query, con); cmd.ExecuteNonQuery(); con.Close(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace Login.settings { public partial class settings_uc : UserControl { public settings_uc() { InitializeComponent(); } private void bunifuFlatButton3_Click(object sender, EventArgs e) { invisible(); activepage.Text = "Reset"; reset.Visible = true; bunifuFlatButton3.Normalcolor = System.Drawing.Color.Black; } private void label2_Click(object sender, EventArgs e) { } private void materialFlatButton1_Click(object sender, EventArgs e) { } private void label4_Click(object sender, EventArgs e) { } private void bunifuFlatButton2_Click(object sender, EventArgs e) { invisible(); activepage.Text = "Add User"; adduser.Visible = true; bunifuFlatButton2.Normalcolor = System.Drawing.Color.Black; } private void invisible() { about.Visible = false; adduser.Visible = false; reset.Visible = false; changepassword.Visible = false; bunifuFlatButton1.Normalcolor = System.Drawing.Color.Transparent; bunifuFlatButton2.Normalcolor = System.Drawing.Color.Transparent; bunifuFlatButton3.Normalcolor = System.Drawing.Color.Transparent; bunifuFlatButton4.Normalcolor = System.Drawing.Color.Transparent; } private void bunifuFlatButton1_Click(object sender, EventArgs e) { invisible(); activepage.Text = "Change Password"; changepassword.Visible = true; bunifuFlatButton1.Normalcolor = System.Drawing.Color.Black; } private void bunifuFlatButton4_Click(object sender, EventArgs e) { invisible(); activepage.Text = "About"; about.Visible = true; bunifuFlatButton4.Normalcolor = System.Drawing.Color.Black; } private void adduser_Paint(object sender, PaintEventArgs e) { } private void materialFlatButton2_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection(DBHelper.connectionString); con.Open(); passvalid.Visible = false; if (addnewusername.Text!="" && addnewpass.Text!="" && addrepass.Text != "") { if (DBHelper.getID(con, addnewusername.Text) == -1) { if (addnewpass.Text == addrepass.Text) { if (DBHelper.addNewUser(con, addnewusername.Text, addnewpass.Text)) { MessageBox.Show("User added successfully"); } else { MessageBox.Show("Error adding user. Try again"); } } else { passvalid.Visible = true; } } else { MessageBox.Show("Username already exists."); } } else { MessageBox.Show("Fill all details"); } con.Close(); } private void label9_Click(object sender, EventArgs e) { } private void materialFlatButton1_Click_1(object sender, EventArgs e) { SqlConnection con = new SqlConnection(DBHelper.connectionString); con.Open(); change_pass_valid.Visible = false; if (old_pass.Text != "" && new_pass.Text != "" && re_pass.Text != "") { if (DBHelper.current_password == old_pass.Text) { if (new_pass.Text == re_pass.Text) { if (DBHelper.changePassword(con,new_pass.Text)) { MessageBox.Show("Password has been changed."); } else { MessageBox.Show("Error changing password. Try again"); } } else { change_pass_valid.Visible = true; } } else { MessageBox.Show("Current password does not match."); } } else { MessageBox.Show("Fill all details"); } con.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Manager.BLL; using Common.Function; namespace Manager.UI.Controllers { public class SystemController : Controller { // // GET: /System/ [UserAuthorization("user")] public ActionResult Index() { return View(); } [UserAuthorization("user")] public PartialViewResult SystemInfo() { ViewBag.vmSystem = new VMSystem().GetVMSystemInfo(Guid.Parse(Session["user"].ToString())); return PartialView(); } public JsonResult ActiveSystem(string names) { return Json(new VMSystem().ActiveSystem(names.Split(',').ToList())); } } }
using System; using System.Drawing; using System.Windows.Forms; using System.IO; using System.Diagnostics; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Collections; using System.Linq; using BrightIdeasSoftware; namespace Wc3Engine { public partial class Wc3Engine : Form { internal static Version GameVersionBridge = Version.Parse("1.27.1"); public static Version gameVersion; public static Wc3Engine This; internal AboutBox aboutBox = new AboutBox(); internal NameSuffixDialog nameSuffixDialog = new NameSuffixDialog(); public Settings configBox = new Settings(); public static TLVBase StandarAbilitiesTab; public static TLVBase CustomAbilitiesTab; public Wc3Engine() { This = this; InitializeComponent(); PrintWc3Version(); CreateAssetsListView(); AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit); JassScript.Load(); //GUIModule.Init(); StandarAbilitiesTab = new TLVBase(LTVStadarAbilities, name_olvColumn2, false); CustomAbilitiesTab = new TLVBase(LTVCustomAbilities, name_olvColumn, true); Ability.TLVStandard = StandarAbilitiesTab; Ability.TLVCustom = CustomAbilitiesTab; DataVisualizer.mainPanel = GUIHelper_tableLayout; /*DataVisualizer visualizer = new DataVisualizer("Test 1", 3); visualizer = new DataVisualizer("Test 2", 5); visualizer = new DataVisualizer("Test 3", 10); //visualizer.Visible = false;*/ List<string> test = new List<string> { "trigger edge", "wtf!", "test", }; string test2 = "trigger e2"; if (test.Exists(x => x.Contains(test2))) DebugMsg("funciona!"); mainTabControl.SelectedTab = mapInfoTab; abilities_tabControl.SelectedTab = custom_tabPage; if (Settings.LoadLastMap && Settings.LastMap != "") Map.Read(Settings.LastMap); else Map.SetPreview(Properties.Resources.Minimap_Unknown); } private void OnProcessExit(object sender, EventArgs e) { Map.Close(); } public void PrintWc3Version() { if (Settings.GamePath1 != "") wc3Version.Text = "Warcraft III " + FileVersionInfo.GetVersionInfo(Settings.GamePath1 + "Game.dll").ProductVersion; else wc3Version.Text = "Warcraft III not detected"; gameVersion = Version.Parse(string.Join("", Regex.Split(wc3Version.Text, @"[^0-9\.]+")).Substring(0, 6)); } private void CreateAssetsListView() { // Width of -2 indicates auto-size. assets_listView.Columns.Add("Id", -2, HorizontalAlignment.Left); assets_listView.Columns.Add("File name", -2, HorizontalAlignment.Left); assets_listView.Columns.Add("Type", -2, HorizontalAlignment.Left); assets_listView.Columns.Add("Size", -2, HorizontalAlignment.Left); } //Show custom message box warning public static void DebugMsg(string msg) { MessageBox.Show(msg, This.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning ); } private void About_Click(object sender, EventArgs e) { aboutBox.ShowDialog(); } private void MapTest_Click(object sender, EventArgs e) { Map.Save(); WindowState = FormWindowState.Minimized; string gameExe = "war3.exe"; string testPath = Settings.GamePath1 + @"Maps\Test\"; if (gameVersion > GameVersionBridge) { gameExe = "Warcraft III.exe"; testPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Warcraft III\Maps\Test\"; } string testMap = testPath + "Wc3EngineTestMap" + Path.GetExtension(Settings.LastMap); if (!Directory.Exists(testPath)) Directory.CreateDirectory(testPath); if (File.Exists(testMap)) File.Delete(testMap); File.Copy(Settings.LastMap, testMap); Process process = Process.Start(Settings.GamePath1 + gameExe, "-window -loadfile \"" + testMap + "\""); process.WaitForExit(); WindowState = FormWindowState.Normal; } /* Open Map */ private void OpenMap_button_Click(object sender, EventArgs e) { if (openFile_map.ShowDialog() == DialogResult.OK) { Map.Read(openFile_map.FileName); } } private void ConfigButton_OnClick(object sender, EventArgs e) { configBox.ShowDialog(); } private void EditMapInfo_OnClick(object sender, EventArgs e) { if (editMapInfo_button.Text == "Edit") { editMapInfo_button.Text = "Save"; W3I.ShowEditBox(true); } else { W3I.Write(W3I.mapName, mapName_textBox.Text); W3I.Write(W3I.mapPlayers, mapPlayers_textBox.Text); W3I.Write(W3I.mapAutor, mapAutor_textBox.Text); W3I.Write(W3I.mapDescription, mapDescription_richTextBox.Text); editMapInfo_button.Text = "Edit"; W3I.ShowEditBox(false); } } private void MapPreviewBox_Click(object sender, EventArgs e) { if (Map.opened && changeMapPreview_FileDialog.ShowDialog() == DialogResult.OK) { Image img = null; if (Path.GetExtension(changeMapPreview_FileDialog.FileName).ToLower() == ".tga") img = Paloma.TargaImage.LoadTargaImage(changeMapPreview_FileDialog.FileName); else img = Image.FromFile(changeMapPreview_FileDialog.FileName); if (img.Width != img.Height || (img.Width > Settings.MapPreviewWidth || img.Height > Settings.MapPreviewHeight)) { // } Map.SetPreview(img); img.Dispose(); } } private void MinimapTab_Selected(object sender, TabControlEventArgs e) { } private void OnNewAbilityClick(object sender, EventArgs e) { bool expand = false; string path = ""; string name = "New Ability " + CustomAbilitiesTab.AbilityMasterList. FindAll(x => x.Path.Contains("New Ability ")).Count.ToString(); if (null != LTVCustomAbilities.SelectedObject) { if (LTVCustomAbilities.SelectedObject is FolderModel) { expand = true; path = ((FolderModel)LTVCustomAbilities.SelectedObject).Path; } else if (LTVCustomAbilities.SelectedObject is AbilityModel && null != ((AbilityModel)LTVCustomAbilities.SelectedObject).Parent) path = ((AbilityModel)LTVCustomAbilities.SelectedObject).Parent.Path; } Ability.Create(path + name, name); if (expand) LTVCustomAbilities.Expand(LTVCustomAbilities.SelectedObject); } private void OnNewFolderClick(object sender, EventArgs e) { bool expand = false; string path = ""; if (null != LTVCustomAbilities.SelectedObject) { if (LTVCustomAbilities.SelectedObject is FolderModel) { expand = true; path = ((FolderModel)LTVCustomAbilities.SelectedObject).Path + @"\"; } else if (LTVCustomAbilities.SelectedObject is AbilityModel && null != ((AbilityModel)LTVCustomAbilities.SelectedObject).Parent) path = ((AbilityModel)LTVCustomAbilities.SelectedObject).Parent.Path + @"\"; } //CustomAbilitiesTab.CreateFolder(path + "New Folder " + CustomAbilitiesTab.FolderMasterList.FindAll(x => x.Path.Contains("New Folder ")).Count.ToString()); new FolderModel(CustomAbilitiesTab, path + "New Folder " + CustomAbilitiesTab.FolderMasterList.FindAll(x => x.Path.Contains("New Folder ")).Count.ToString()); if (expand) LTVCustomAbilities.Expand(LTVCustomAbilities.SelectedObject); } private void OnItemRemoveClick(object sender, EventArgs e) { if (LTVCustomAbilities.SelectedObject is FolderModel folder) CustomAbilitiesTab.DeleteObject(folder.Path); else if (LTVCustomAbilities.SelectedObject is AbilityModel _item) CustomAbilitiesTab.DeleteObject(_item.Path); LTVCustomAbilities.BuildList(); } private void LTVAbility_ModelCanDrop(object sender, ModelDropEventArgs e) { /*object item = e.TargetModel; if (item == null) e.Effect = DragDropEffects.None; else if (item is FolderModel targetFolder) e.Effect = DragDropEffects.Move; else if (item is Item) { if (e.DropTargetLocation == DropTargetLocation.AboveItem || e.DropTargetLocation == DropTargetLocation.BelowItem) e.Effect = DragDropEffects.Move; else { e.Effect = DragDropEffects.None; e.InfoMessage = "Can't drop this Ability here"; } }*/ } private void LTVAbility_ModelDropped(object sender, ModelDropEventArgs e) { /*// If they didn't drop on anything, then don't do anything if (e.TargetModel == null) return; if (e.TargetModel is FolderModel targetFolder) { foreach (object item in e.SourceModels) { if (item is FolderModel sourceFolder) CustomAbilitiesTab.Move(sourceFolder.Path, targetFolder.Path); else if (item is Item sourceItem) CustomAbilitiesTab.Move(sourceItem.Path, targetFolder.Path); } } e.RefreshObjects();*/ } public Ability SelectedAbility; private void LTV_OnSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e) { if (null != e.Item && e.Item.Text.StartsWith("(")) { string id = e.Item.Text.Remove(5, e.Item.Text.Length - 5).Substring(1); SelectedAbility = Ability.Find(id); SelectedAbility.UpdateOnSelect(); } } private void LTV_OnCellEdit_DoubleClick(object sender, EventArgs e) { nameSuffixDialog.ShowDialog(); } private void LTV_OnCellEdit_F2(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.F2) nameSuffixDialog.ShowDialog(); } private void OnMissileNumericChanged(object sender, EventArgs e) { //GUIModule.UpdateMissileHandle(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(HealthComponent))] public class Breakable : MonoBehaviour { HealthComponent hc; private void Awake() { hc = GetComponent<HealthComponent>(); } private void Update() { if (hc.isDead) Break(); } public void Break() { for (int i = 0; i < transform.childCount; i++) transform.GetChild(i).parent = null; Destroy(gameObject); } }
using System; public class Program { public static void Main() { var firstNum = int.Parse(Console.ReadLine()); var secNum = int.Parse(Console.ReadLine()); PrintNums(firstNum, secNum, "Before"); var tempNum = secNum; secNum = firstNum; firstNum = tempNum; PrintNums(firstNum, secNum, "After"); } public static void PrintNums(int a, int b, string str) { Console.WriteLine($"{str}:"); Console.WriteLine($"a = {a}"); Console.WriteLine($"b = {b}"); } }
using System; using System.Collections.Generic; using TiendeoAPI.Models; namespace TiendeoAPI.Core.Interfaces { public interface ICityCore { CityModel GetCityByName(string name); List<CityModel> GetCities(); } }
using PPKBuisnessLayer; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Net.WebSockets; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; namespace PPKConsole { class Program { static void Main(string[] args) { TcpClient myClient = new TcpClient(); myClient.Connect("127.0.0.1", 8080); var tcpStream = myClient.GetStream(); var myStreamWriter = new BinaryWriter(tcpStream); var myStreamReader = new BinaryReader(tcpStream); ThreadPool.QueueUserWorkItem(HandleWriting, myStreamWriter); ThreadPool.QueueUserWorkItem(HandleReading, myStreamReader); } private static void HandleReading(object state) { var myStreamReader = state as BinaryReader; do { try { // read the string sent to the server var theReply = myStreamReader.ReadString(); Console.WriteLine("\r\n" + theReply); } catch (Exception) { break; } } while (true); } private static void HandleWriting(object state) { try { var myStreamWriter = state as BinaryWriter; var stayAlive = true; while (stayAlive) { ThreadSafeConsole.WriteLine("Write commmand: "); var command = ThreadSafeConsole.ReadLine(); if (string.IsNullOrWhiteSpace(command)) { stayAlive = false; } else { myStreamWriter.Write(command); } } } catch(Exception ex) { throw ex; } } public static class ThreadSafeConsole { private static object _lockObject = new object(); public static void WriteLine(string str) { lock (_lockObject) { Console.WriteLine(str); } } public static string ReadLine() { lock (_lockObject) { return Console.ReadLine(); ; } } } } }
using UnityEngine; using System; using System.Collections; using live2d; using UnityEngine.UI; public class Live2dMain : MonoBehaviour { public TextAsset mocFile; public Texture2D[] textures; private Live2DModelUnity live2DModel; private Camera live2Dcam; public RawImage image; // Use this for initialization void Start () { Live2D.init(); live2DModel = Live2DModelUnity.loadModel(mocFile.bytes); live2DModel.setRenderMode(Live2D.L2D_RENDER_DRAW_MESH); for (int i = 0; i < textures.Length; i++) { live2DModel.setTexture(i, textures[i]); } setCamera(); setRenderTexture(); } void Update() { live2DModel.update(); if (live2DModel.getRenderMode() == Live2D.L2D_RENDER_DRAW_MESH) Render(); //live2DModel.update(); } void OnRenderObject() { if (live2DModel.getRenderMode() == Live2D.L2D_RENDER_DRAW_MESH_NOW) Render(); float modelWidth = live2DModel.getCanvasWidth(); Matrix4x4 m1 = Matrix4x4.Ortho( 0, modelWidth, modelWidth, 0, -50.0f, 50.0f); Matrix4x4 m2 = transform.localToWorldMatrix; Matrix4x4 m3 = m2 * m1; live2DModel.setMatrix(m3); live2DModel.draw(); } void Render() { live2DModel.draw(); } void setCamera() { live2Dcam = gameObject.AddComponent<Camera>(); live2Dcam.orthographic = true; live2Dcam.orthographicSize = 1f; live2Dcam.cullingMask = 0; live2Dcam.nearClipPlane = 0; } void setRenderTexture() { var w = live2DModel.getCanvasWidth(); var h = live2DModel.getCanvasHeight(); var target = new RenderTexture((int)w, (int)h, (int)Screen.dpi, RenderTextureFormat.ARGB32); live2Dcam.targetTexture = target; image.rectTransform.sizeDelta = new Vector2(w / 4f, h / 4f); } }
using System; namespace Entiry { public class Student { public string Name { set; get; } public int Age { set; get; } public double Height { set; get; } } }
namespace PluginStudy.EntityFramework.Migrations { using System; using System.Data.Entity.Migrations; public partial class AddStudentInfo : DbMigration { public override void Up() { CreateTable( "dbo.StudentInfo", c => new { Guid = c.String(nullable: false, maxLength: 128), Name = c.String(), ClassName = c.String(), Gender = c.String(maxLength: 3), Birthday = c.String(maxLength: 12), GraduationSchool = c.String(), NativePlace = c.String(), }) .PrimaryKey(t => t.Guid); } public override void Down() { DropTable("dbo.StudentInfo"); } } }
using GalaSoft.MvvmLight.Command; using Newtonsoft.Json; using nmct.ba.cashlessproject.crypto; using nmct.ba.cashlessproject.model.ASP.NET; using nmct.ba.cashlessproject.organisation.ViewModel.General; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace nmct.ba.cashlessproject.organisation.ViewModel.Administration { public class AccountManagementVM : ObservableObject, IPage { #region Properties public string Name { get { return "Accountbeheer"; } } private Organisation _myOrganisation; public Organisation MyOrganisation { get { return _myOrganisation; } set { _myOrganisation = value; OnPropertyChanged("MyOrganisation"); } } private String _firstPassword; public String FirstPassword { get { return _firstPassword; } set { _firstPassword = value; OnPropertyChanged(FirstPassword); } } private String _secondPassword; public String SecondPassword { get { return _secondPassword; } set { _secondPassword = value; OnPropertyChanged("SecondPassword"); } } private String _oldPassword; public String OldPassword { get { return _oldPassword; } set { _oldPassword = value; OnPropertyChanged("OldPassword"); } } private Boolean _showServerMessage; public Boolean ShowServerMessage { get { return _showServerMessage; } set { _showServerMessage = value; OnPropertyChanged("ShowServerMessage"); } } private String _serverMessage; public String ServerMessage { get { return _serverMessage; } set { _serverMessage = value; OnPropertyChanged("ServerMessage"); } } #endregion #region Constructor public AccountManagementVM() { GetOrganisation(); } #endregion #region Methods private async void GetOrganisation() { using(HttpClient client = new HttpClient()) { String url = String.Format("{0}{1}", "http://localhost:49534/api/organisation?id=", ApplicationVM.OrganisationID); HttpResponseMessage response = await client.GetAsync(url); if(response.IsSuccessStatusCode) { String json = await response.Content.ReadAsStringAsync(); MyOrganisation = JsonConvert.DeserializeObject<Organisation>(json); } } } #endregion #region Actions /* * Save new password to the database. */ public ICommand SaveOrganisationCommand { get { return new RelayCommand(SaveOrganisation); } } private async void SaveOrganisation() { if (Cryptography.Decrypt(MyOrganisation.Password) != OldPassword) { ShowServerMessage = true; ServerMessage = "Het huidige wachtwoord klopt niet."; return; } if (FirstPassword != SecondPassword) { ShowServerMessage = true; ServerMessage = "De ingegeven wachtwoorden komen niet met elkaar overeen."; return; } MyOrganisation.Password = Cryptography.Encrypt(FirstPassword); using(HttpClient client = new HttpClient()) { String organisation = JsonConvert.SerializeObject(MyOrganisation); HttpResponseMessage response = await client.PutAsync("http://localhost:49534/api/organisation", new StringContent(organisation, Encoding.UTF8, "application/json")); if(response.IsSuccessStatusCode) { ShowServerMessage = true; ServerMessage = "Het wachtwoord werd succesvol opgeslagen."; } } } #endregion } }
using CapaNegocio; using CapaNegocio.Mesas; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using static CapaNegocio.LogicaPedidos; namespace CapaUI { public partial class Programa : Form { MesaLogica logica = new MesaLogica(); LogicaPedidos logicaPedidos = new LogicaPedidos(); #region ControlesInicio //Seleccionar el numero de mesas ListBox lista = new ListBox(); Button[] boton = new Button[10]; int seleccion; #endregion #region ControlesMesa Label etiqueta = new Label(); TextBox txtMesaOrden = new TextBox(); Button btnSeleccionarMesa = new Button(); ListBox listaPersonas = new ListBox(); int numeroDePersonas; Button btn = new Button(); Button enviarOrdenes = new Button(); Button cancelarOrdenes = new Button(); Label cantidadMesa = new Label(); Label cantidadPersona = new Label(); Button Detalle = new Button(); #endregion #region pedidos Form pedidos = new Form(); int mesaEnUso; int contadorPedido=1; Button siguientePedido = new Button(); #endregion public Programa() { InitializeComponent(); // Boton para crear mas ordenes siguientePedido.Click += new EventHandler(continuar_Pedido); } private void SeleccionarMesa_Load(object sender, EventArgs e) { Label lb = new Label(); lb.Visible = true; lb.Text = "Seleccione una mesa"; lb.Font = new Font("Microsoft Sans serif", 20); lb.Location = new Point(43, 9); lb.Size = new Size(272, 31); this.Controls.Add(lb); Button atendido = new Button(); atendido.Visible = true; atendido.Text = ""; atendido.BackColor = Color.Green; atendido.Location = new Point(447,61); atendido.Size = new Size(33, 23); this.Controls.Add(atendido); Button proceso = new Button(); proceso.Visible = true; proceso.Text = ""; proceso.BackColor = Color.Yellow; proceso.Location = new Point(447, 90); proceso.Size = new Size(33, 23); this.Controls.Add(proceso); Label t1 = new Label(); t1.Visible = true; t1.Text = "Atendido"; t1.Location = new Point(500, 66); t1.Size = new Size(49,13); this.Controls.Add(t1); Label t2 = new Label(); t2.Visible = true; t2.Text = "Proceso de atencion"; t2.Location = new Point(500, 95); t2.Size = new Size(105, 13); this.Controls.Add(t2); //Numero De mesas lista.Items.Add(""); lista.Items.Add("1"); lista.Items.Add("2"); lista.Items.Add("3"); lista.Items.Add("4"); lista.Items.Add("5"); lista.Items.Add("6"); lista.Items.Add("7"); lista.Items.Add("8"); lista.Size = new Size(353,212); lista.Location = new Point(49,60); this.Controls.Add(lista); //Boton Para Seleccionar la cantidad de mesas btn.Text = "Seleccionar una mesa"; btn.Visible = true; btn.Location = new Point(171, 290); btn.Size = new Size(231,36); this.Controls.Add(btn); //Eventos botones btn.Click += new EventHandler(crear_FomularioMesa); this.Controls.Add(btn); btnSeleccionarMesa.Click += new EventHandler(crear_Pedido); enviarOrdenes.Click += new EventHandler(enviar_Pedido); txtMesaOrden.KeyPress += new KeyPressEventHandler(noTexto); cancelarOrdenes.Click += new EventHandler(cancelar_Pedido); } private void crear_FomularioMesa(object sender, System.EventArgs e) { Form mesas = new Form(); seleccion = lista.SelectedIndex+1; //Gerenrar mesa for (int i = 1; i < seleccion; i++) { boton[i] = new Button(); boton[i].Width = 75; boton[i].Height = 23; boton[i].Text = String.Format("{0}", i); boton[i].Top = i * 40; boton[i].Enabled = false; mesas.Controls.Add(boton[i]); } //Otro controles de la mesa if (seleccion >= 1 && seleccion <= 9) { mesas.Size = new Size(563,473); mesas.Text = "Mesas"; mesas.Controls.Add(txtMesaOrden); txtMesaOrden.Location = new System.Drawing.Point(270, 312); txtMesaOrden.Size = new Size(57,26); mesas.Controls.Add(btnSeleccionarMesa); btnSeleccionarMesa.Text = "Tomar orden"; btnSeleccionarMesa.Location = new System.Drawing.Point(252, 381); mesas.Visible = true; btnSeleccionarMesa.Size=new Size(75,23); logica.ListaPersona(listaPersonas); mesas.Controls.Add(listaPersonas); listaPersonas.Location = new System.Drawing.Point(97, 51); listaPersonas.Size = new Size(378,238); mesas.Controls.Add(enviarOrdenes); enviarOrdenes.Location = new System.Drawing.Point(116, 381); enviarOrdenes.Visible = true; enviarOrdenes.Text = "Enviar ordenes"; enviarOrdenes.Size = new Size(75,23); mesas.Controls.Add(cancelarOrdenes); cancelarOrdenes.Location = new System.Drawing.Point(400, 381); cancelarOrdenes.Visible = true; cancelarOrdenes.Text = "Cancelar"; cancelarOrdenes.Size = new Size(75,23); mesas.Controls.Add(cantidadPersona); cantidadPersona.Location = new Point(94,9); cantidadPersona.Visible = true; cantidadPersona.Text = "Cantidad de personas"; cantidadPersona.Font = new Font("Microsoft Sans serif",20); cantidadPersona.Size = new Size (279,31); mesas.Controls.Add(cantidadMesa); cantidadMesa.Location = new Point(93,312); cantidadMesa.Visible = true; cantidadMesa.Text = "Seleccionar mesa"; cantidadMesa.Font = new Font("Microsoft Sans serif", 12); cantidadMesa.Size = new Size(235,20); mesas.Controls.Add(Detalle); Detalle.Location = new Point(400, 320); Detalle.Visible = true; Detalle.Text = "Detalle"; Detalle.Size = new Size(75, 23); //siguientePedido.Text = "Siguiente Pedido"; //mesas.Controls.Add(siguientePedido); this.Hide(); } else { MessageBox.Show("Seleccionar un numero"); } } private void crear_Pedido(object sender, System.EventArgs e) { Form existe = Application.OpenForms.OfType<Form>().Where(pre => pre.Name == "logicaPedidos").SingleOrDefault<Form>(); if (String.IsNullOrEmpty(txtMesaOrden.Text) || String.IsNullOrEmpty(listaPersonas.Text)) { MessageBox.Show("Elija una mesa y la cantidad de personas"); } else { mesaEnUso = 0; mesaEnUso = int.Parse(txtMesaOrden.Text.ToString()); numeroDePersonas = int.Parse(listaPersonas.Text.ToString()); logica.EstadoMesa(boton[mesaEnUso]); continuar_Pedido(this,new EventArgs()); } } private void continuar_Pedido(object sender, System.EventArgs e) { //pedido p1 = new pedido(nombreClientePedido.Text.ToString(), // platoEntrada.SelectedIndex.ToString(), // platoFuerte.SelectedIndex.ToString(), // bebida.SelectedIndex.ToString(), // platoPostre.SelectedIndex.ToString()); //todosPedidos.Add(p1); if (contadorPedido < numeroDePersonas) { Button siguientePedido = new Button(); siguientePedido.Click += new EventHandler(continuar_Pedido); siguientePedido.Text = "Siguiente"; siguientePedido.Visible = true; siguientePedido.Location = new Point(723, 366); siguientePedido.Size = new Size(88,34); pedidos.Controls.Add(siguientePedido); logicaPedidos.nuevoPedido().Controls.Add(siguientePedido); } if (contadorPedido == numeroDePersonas) { Button finalizar = new Button(); finalizar.Click += new EventHandler(finalizar_Orden); finalizar.Text = "Finalizar"; finalizar.Visible = true; finalizar.Location = new Point(723, 366); finalizar.Size = new Size(88, 34); logicaPedidos.nuevoPedido().Controls.Add(finalizar); } contadorPedido++; } private void finalizar_Orden(object sender, System.EventArgs e) { btnSeleccionarMesa.Enabled = true; this.Close(); crear_FomularioMesa(this, new EventArgs()); } private void enviar_Pedido(object sender, System.EventArgs e) { MesaLogica mm = new MesaLogica(); Color cc = new Color(); cc = Color.Green; mm.Estados(boton,cc); contadorPedido = 1; } private void cancelar_Pedido(object sender, System.EventArgs e) { MesaLogica mm = new MesaLogica(); Color cc = new Color(); cc = Color.Green; mm.Estados(boton,cc); contadorPedido = 1; } private void noTexto(object sender, KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) { e.Handled = true; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BaiGiuaKy_PhanVanVuong.tagBitmap { public class TagBitmapFileInfo { public uint biSize; public long biWidth; public long biHeight; public int biPlanes; public int biBitCount; public uint biCompression; public uint biSizeImage; public long biXPelsPerMeter; public long biYPelsPerMeter; public uint biClrUsed; public uint biClrImportant; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class HoverMenu : MonoBehaviour { public Animator hoverAnim; public void PlayAnim() { hoverAnim.SetBool("Hovering", true); Debug.Log("ON"); } public void StopAnim() { hoverAnim.SetBool("Hovering", false); Debug.Log("OFF"); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace UCM.IAV.Practica2 { public class MinotauroMov : MonoBehaviour { [Header("Laberinto")] // Laberinto con casillas y direcciones public MazeLoader mazeLoader; [Header("Velocidad")] [Range(1.0f, 3.0f)] [Tooltip("Rango optimo de velocidad")] public float speed = 5.0f; private enum direction{ LEFT = 0, RIGHT = 1, UP = 2, DOWN = 3}; public struct Dir { public Vector3 vel; public int x, z; public Dir(Vector3 v, int ax, int az) { vel = v; x = ax; z = az; } }; public Dir dir; private float yRotation; private float tileSize; private int rand = 0; private DiffRandomGenerator rnd = new DiffRandomGenerator(0, 3); // Start is called before the first frame update void Start() { tileSize = mazeLoader.size; transform.position = SetStartPos(); transform.rotation = default(Quaternion); dir.x = dir.z = 0; yRotation = 0; //InvokeRepeating("GetNextPosition", 0, 3.0f); GetNextPosition(); } // Update is called once per frame void Update() { // Empieza el movimiento float time = Time.deltaTime; // Cambiar de casilla al avanzar if (transform.position.x > dir.x * tileSize + (tileSize / 2.0f)) dir.x++; if (transform.position.x < dir.x * tileSize - (tileSize / 2.0f)) dir.x--; if (transform.position.z > dir.z * tileSize + (tileSize / 2.0f)) dir.z++; if (transform.position.z < dir.z * tileSize - (tileSize / 2.0f)) dir.z--; // Movimiento por railes // ARRIBA Y ABAJO // Comprobar que este dentro del rail vertical if (transform.position.x % tileSize > tileSize * 0.85 && transform.position.x % tileSize <= tileSize || transform.position.x % tileSize < tileSize * 0.15 && transform.position.x % tileSize >= 0) { // Si esta pulsada la tecla up if (rand == (int)direction.UP) { // Ha pasado de la mitad y hay un muro en esa direccion, no moverse if (transform.position.z % tileSize < tileSize * 0.15 && !mazeLoader.mazeCells[dir.x, dir.z].walls[2]) { transform.position = new Vector3(transform.position.x, 0.0f, dir.z * tileSize); GetNextPosition(); } // Si no, moverse else dir.vel.z = speed; } // Si esta pulsada la tecla down else if (rand == (int)direction.DOWN) { // Ha pasado de la mitad y hay un muro en esa direccion, no moverse if ((transform.position.z % tileSize > tileSize * 0.85 && !mazeLoader.mazeCells[dir.x, dir.z].walls[3]) || transform.position.z < 0.0f) { transform.position = new Vector3(transform.position.x, 0.0f, dir.z * tileSize); GetNextPosition(); } if (this.transform.position.z == 0) { // rnd.Reset(0, 2); rand = rnd.Next(); } // Si no, moverse else dir.vel.z = -speed; } } // IZQUIERDA Y DERECHA // Comprobar que esta en el rail horizontal if (transform.position.z % tileSize > tileSize * 0.85 && transform.position.z % tileSize <= tileSize || transform.position.z % tileSize < tileSize * 0.15 && transform.position.z % tileSize >= 0) { if (rand == (int)direction.RIGHT) { // Ha pasado de la mitad y hay un muro en esa direccion, no moverse if (transform.position.x % tileSize < tileSize * 0.15 && !mazeLoader.mazeCells[dir.x, dir.z].walls[1]) { transform.position = new Vector3(dir.x * tileSize, 0.0f, transform.position.z); GetNextPosition(); } // Si no, moverse else dir.vel.x = speed; } else if (rand == (int)direction.LEFT) { // Ha pasado de la mitad y hay un muro en esa direccion, no moverse if (transform.position.x % tileSize > tileSize * 0.85 && !mazeLoader.mazeCells[dir.x, dir.z].walls[0]) { transform.position = new Vector3(dir.x * tileSize, 0.0f, transform.position.z); GetNextPosition(); } if (this.transform.position.x == 0) { // rnd.Reset(1, 3); rand = rnd.Next(); } // Si no, moverse else dir.vel.x = -speed; } } // Actualizar el movimiento transform.position += dir.vel * time; if (transform.position.z < 0) transform.position = new Vector3(transform.position.x, 0.0f, dir.z * tileSize); if (transform.position.x < 0) transform.position = new Vector3(dir.x * tileSize, 0.0f, transform.position.z); if (dir.vel.x > 0) yRotation = 1; else if (dir.vel.x < 0) yRotation = -1; if (dir.vel.z < 0) yRotation = 90; else if (dir.vel.z > 0) yRotation = 0; transform.rotation = Quaternion.Slerp(transform.rotation, new Quaternion(0, yRotation, 0, 1), 1); // Resetear la velocidad dir.vel = Vector3.zero; } void GetNextPosition() { // reset del generador de random rnd.Reset(0, 3); rand = rnd.Next(); // mientras haya una pared en la direccion elegida while(!mazeLoader.mazeCells[dir.x, dir.z].walls[rand]) { // cambia direccion rand = rnd.Next(); } } private Vector3 SetStartPos() { Vector2 vec; int i, j; i = mazeLoader.mazeRows / 2; j = mazeLoader.mazeColumns / 2; vec = mazeLoader.getPosInCell(j, i); Vector3 v = Vector3.zero; v.x = vec.x * tileSize; v.y = 0.0f; v.z = vec.y * tileSize; return v; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.IO; namespace ProyectoFinalParadigmas { [Serializable] public class Basededatos { public List<usuario_gral> usuarios; public List<Empresa> empresas; public List<ciudad> ciudades; public usuario_gral usuario_activo; public List<colectivo> colectivo; public List<viaje> viajes; //instancia todos los objetos public Basededatos() { usuarios = new List<usuario_gral>(); empresas = new List<Empresa>(); ciudades = new List<ciudad>(); colectivo = new List<colectivo>(); viajes = new List<viaje>(); } //guarda la base de datos en el archivo public void Save() { Archivo.Save(this); } } }
using UnityEngine; using System.Collections; public class IndoorNavigation : MonoBehaviour { GameObject player; GameObject cam; ScreenFader fader; public static IndoorNavigation instance = null; // Use this for initialization void Start() { player = GameObject.FindGameObjectWithTag("Player"); cam = Camera.main.gameObject; fader = GetComponentInChildren <ScreenFader>(); if (instance == null) instance = this; else if (instance != this) Destroy(gameObject); } public void ChangePosition (Vector3 playerPosition, Vector3 playerRotation, Vector3 camPosition, Vector3 camRotation) { StartCoroutine(ChangePositionRoutine(playerPosition, playerRotation, camPosition, camRotation)); } IEnumerator ChangePositionRoutine (Vector3 playerPosition, Vector3 playerRotation, Vector3 camPosition, Vector3 camRotation) { Debug.Log("fading out"); player.GetComponent<UnityStandardAssets.Characters.ThirdPerson.ThirdPersonCharacter>().enabled = false; player.GetComponent<UnityStandardAssets.Characters.ThirdPerson.ThirdPersonUserControl>().enabled = false; fader._fadeOut = true; while (fader._fadeOut) { yield return 0; } Debug.Log("Changing Position"); player.transform.position = playerPosition; player.transform.eulerAngles = playerRotation; cam.transform.position = camPosition; cam.transform.eulerAngles = camRotation; Debug.Log("Fading in"); fader._fadeIn = true; while (fader._fadeIn) { yield return 0; } player.GetComponent<UnityStandardAssets.Characters.ThirdPerson.ThirdPersonCharacter>().enabled = true; player.GetComponent<UnityStandardAssets.Characters.ThirdPerson.ThirdPersonUserControl>().enabled = true; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public partial class MyCylMesh : MonoBehaviour { public int N; //N = resolution public int M; // M = height public int[] t; public static bool meshChange; private float deg; private float degI; private int vertices; private int triangles; //y=height private float cylHeight; private float regRadius; private Vector3[] cylRadius; private float cylRotation; private Vector3[] v; private Vector3[] n; private Mesh theMesh; // Use this for initialization void Start() { N = 3; M = 4; vertices = (N + 1) * (M + 1); triangles = N * M * 2; v = new Vector3[vertices]; // 2x2 mesh needs 3x3 vertices t = new int[triangles * 3]; // Number of triangles: 2x2 mesh and 2x triangles on each mesh-unit n = new Vector3[vertices]; // MUST be the same as number of vertices cylRadius = new Vector3[M]; regRadius = 1; cylHeight = 5; cylRotation = 180; meshChange = false; if (!meshChange) setRegularRadius(); ReDrawMesh(N); } void makeMesh(float rot, float radius, float height) { theMesh = GetComponent<MeshFilter>().mesh; // get the mesh component theMesh.Clear(); // delete whatever is there!! vertices = (N + 1) * (M + 1); triangles = N * M * 2; v = new Vector3[vertices]; // 2x2 mesh needs 3x3 vertices t = new int[triangles * 3]; // Number of triangles: 2x2 mesh and 2x triangles on each mesh-unit n = new Vector3[vertices]; // MUST be the same as number of vertices if (!meshChange) setRegularRadius(); degI = rot / N; for (int i = 0; i <= M; i++) { for (int j = 0; j <= N; j++) { int index = j + (i * (N + 1)); v[index] = new Vector3(cylRadius[i].x * Mathf.Cos(CalcDeg(deg)), cylRadius[i].y, cylRadius[i].z * Mathf.Sin(CalcDeg(deg))); n[index] = new Vector3(0, 1, 0); deg += degI; } deg = 0; } //for loop for t for (int i = 0, ti = 0; i < M; i++) //ti = tIndex { for (int j = 0; j < N; j++) { int t1, t2, t3, t4, t5, t6; t1 = i * (N + 1) + j; t2 = j + ((i + 1) * (N + 1)); t3 = t2 + 1; t4 = t1; t5 = t3; t6 = t4 + 1; t[ti++] = t1; t[ti++] = t2; t[ti++] = t3; t[ti++] = t4; t[ti++] = t5; t[ti++] = t6; } } theMesh.vertices = v; // new Vector3[3]; theMesh.triangles = t; // new int[3]; theMesh.normals = n; InitControllers(v); InitNormals(v, n); } void setRegularRadius() //radius for regular M { if (cylRadius.Length != M + 1) cylRadius = new Vector3[M + 1]; float h = cylHeight / 2; float rowH = cylHeight / M; for (int i = 0; i < cylRadius.Length; i++) { cylRadius[i] = new Vector3(regRadius, h, regRadius); h -= rowH; } } public void radiusChange(Vector3 newPos, int index) { deg = degI; for (int j = index + 1; j <= index + N; j++) { mControllers[j].transform.localPosition = new Vector3(newPos.x * Mathf.Cos(CalcDeg(deg)), newPos.y, newPos.x * Mathf.Sin(CalcDeg(deg))); deg += degI; } cylRadius[index / (N + 1)] = new Vector3(newPos.x, newPos.y, newPos.x); } // Update is called once per frame void Update() { Mesh theMesh = GetComponent<MeshFilter>().mesh; Vector3[] v = theMesh.vertices; Vector3[] n = theMesh.normals; for (int i = 0; i < mControllers.Length; i++) { v[i] = mControllers[i].transform.localPosition; } ComputeNormals(v, n); theMesh.vertices = v; theMesh.normals = n; } //degree to radians float CalcDeg(float deg) { return deg * Mathf.PI / 180.0f; } public void ReDrawMesh() { foreach (Transform child in gameObject.transform) { DestroyObject(child.gameObject); } makeMesh(cylRotation, regRadius, cylHeight / 2); } public void ReDrawMesh(int newN) { N = newN; if (M < newN) M = newN; else M = (int)cylHeight; foreach (Transform child in gameObject.transform) { DestroyObject(child.gameObject); } meshChange = false; makeMesh(cylRotation, regRadius, cylHeight / 2); } public void incNMesh(int newN) { if (N != newN) N = newN; foreach (Transform child in gameObject.transform) { DestroyObject(child.gameObject); } makeMesh(cylRotation, regRadius, cylHeight / 2); } public void RotationChange(float newRot) { cylRotation = newRot; foreach (Transform child in gameObject.transform) { DestroyObject(child.gameObject); } makeMesh(cylRotation, regRadius, cylHeight / 2); } public void meshExtrude(int val) { cylHeight = val; M = (int)cylHeight *2; foreach (Transform child in gameObject.transform) { DestroyObject(child.gameObject); } meshChange = false; makeMesh(cylRotation, regRadius, cylHeight / 2); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using CaseReportal.Model.Entities; using NHibernate; using CaseReportal.Models; namespace CaseReportal.Controllers { public class SearchController : Controller { private readonly ISession _Session; public SearchController(ISession session) { _Session = session; } // // GET: /Search/ public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(SearchModels model, string returnUrl) { if(ModelState.IsValid == false) { return View(); } var srm = new SearchResultModel(); using (var itx = this._Session.BeginTransaction()) { var arts = _Session.QueryOver<Article>().List(); srm.articles = arts.Where(x => x.Title.Contains(model.Title)); itx.Commit(); } return View("SearchResult", srm); } } }
using System.Windows.Data; using Tai_Shi_Xuan_Ji_Yi.Classes; namespace Tai_Shi_Xuan_Ji_Yi.Converters { class CConverterCurebandStateToString : IValueConverter { public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { string ret = string.Empty; CCureBandClass.ENUM_STATE state = (CCureBandClass.ENUM_STATE)value; switch(state) { case CCureBandClass.ENUM_STATE.Disconnected: ret = "无治疗带"; break; case CCureBandClass.ENUM_STATE.Curing: ret = "正在治疗"; break; case CCureBandClass.ENUM_STATE.Overdue: ret = "治疗带过期"; break; case CCureBandClass.ENUM_STATE.Standby: ret = "准备好"; break; case CCureBandClass.ENUM_STATE.Heating: ret = "预加热"; break; } return ret; } public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new System.NotImplementedException(); } } }
using System; namespace PDV.VIEW.Forms.Util { public class FormaPagamentoAux { public int Identificador { get; set; } public int Sequencia { get; set; } public string Cod { get; set; } public string Nome { get; set; } public decimal Valor { get; set; } public DateTime Vencimento { get; set; } public int Pagamento { get; set; } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MonoGame.Extended.Animations; using MonoGame.Extended.Sprites; namespace Demo.SpaceGame.Entities { public class Explosion : Entity { private readonly SpriteSheetAnimator _animator; public Explosion(SpriteSheetAnimationGroup animations, Vector2 position, float radius) { _animator = new SpriteSheetAnimator(animations) { Sprite = { Position = position, Scale = Vector2.One * radius * 0.2f }, IsLooping = false }; _animator.PlayAnimation("explode", Destroy); } public override void Update(GameTime gameTime) { _animator.Update(gameTime); } public override void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(_animator); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Data.Entity; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using RestaurantApp.Core; using RestaurantApp.Infrastructure; namespace RestaurantApp.Test.InfrastructureTest { //Test with mock DBSet & mock DBContext to test action CRUD, query from database - with helper [TestClass] public class UnitRepositoryTest { [TestMethod] public void CreateItem_UpdateItem_Via_Context() { var mockSet = new Mock<DbSet<Unit>>(); var mockContext = new Mock<RestaurantApp.Infrastructure.VitualRestaurantContext>(); mockContext.Setup(m => m.Unit).Returns(mockSet.Object); var repo = new RestaurantApp.Infrastructure.Repositories.UnitRepository(mockContext.Object); var testObject = new Unit() { Name = "Piece" }; repo.Update(testObject); mockSet.Verify(m => m.Add(It.Is<RestaurantApp.Core.Unit>(u => u.Name == "Piece")), Times.Once); mockContext.Verify(m => m.SaveChanges(), Times.Once); } [TestMethod] public void UpdateItem_Via_Context() { var testObject = new Unit() { Id = 1, Name = "Piece" }; var mockSet = new Mock<DbSet<Unit>>(); var mockContext = new Mock<RestaurantApp.Infrastructure.VitualRestaurantContext>(); mockContext.Setup(m => m.Unit).Returns(mockSet.Object); mockContext.Setup(m => m.SetModified(It.IsAny<Unit>())); var repo = new RestaurantApp.Infrastructure.Repositories.UnitRepository(mockContext.Object); repo.Update(testObject); mockContext.Verify(m => m.SetModified(It.IsAny<Unit>()), Times.Once); mockContext.Verify(m => m.SaveChanges(), Times.Once); } [TestMethod] public void RemoteById() { var testObject = new Unit() { Id = 1, Name = "Piece" }; int idToDelete = 1; var mockSet = new Mock<DbSet<Unit>>(); var mockContext = new Mock<RestaurantApp.Infrastructure.VitualRestaurantContext>(); mockContext.Setup(m => m.Set<Unit>()).Returns(mockSet.Object); mockSet.Setup(m => m.Find(It.IsAny<int>())).Returns(testObject); mockSet.Setup(m => m.Remove(It.IsAny<Unit>())).Returns(testObject); var repo = new RestaurantApp.Infrastructure.Repositories.UnitRepository(mockContext.Object); var result = repo.Remove(idToDelete); //Assert Assert.AreEqual(true, result); mockContext.Verify(m => m.Set<Unit>()); mockSet.Verify(m => m.Find(It.IsAny<int>())); mockSet.Verify(m => m.Remove(It.IsAny<Unit>())); mockContext.Verify(m => m.SaveChanges(), Times.Once); } [TestMethod] public void GetUnits_WithPaging_OrderById() { var data = new List<Unit>() { new Unit { Id=1, Name = "Kg" }, new Unit { Id=2, Name = "Piece" }, new Unit { Id=3, Name = "bag" } }.AsQueryable(); var mockDbSet = Helper.CreateDbSetMock(data); var mockContext = new Mock<RestaurantApp.Infrastructure.VitualRestaurantContext>(); mockContext.Setup(m => m.Unit).Returns(mockDbSet.Object); var repo = new RestaurantApp.Infrastructure.Repositories.UnitRepository(mockContext.Object); List<Unit> result = repo.GetUnits(0, 2).ToList(); //assert Assert.AreEqual(2, result.Count()); Assert.AreEqual("bag", result[0].Name); Assert.AreEqual("Piece", result[1].Name); } [TestMethod] public void GetById() { var data = new List<Unit>() { new Unit { Id=1, Name = "Kg" }, new Unit { Id=2, Name = "Piece" } }.AsQueryable(); var mockSet = Helper.CreateDbSetMock<Unit>(data); var mockContext = new Mock<RestaurantApp.Infrastructure.VitualRestaurantContext>(); mockContext.Setup(m => m.Unit).Returns(mockSet.Object); var repo = new RestaurantApp.Infrastructure.Repositories.UnitRepository(mockContext.Object); var food = repo.GetById(2); Assert.AreEqual("Piece", food.Name); } } }
using System; using System.Drawing; using Kompas6API5; using Kompas6Constants3D; namespace KompasKeyboardPlugin { /// <summary> /// Класс, создающий тело клавиатуры. /// </summary> public class BodyCreator : KeyboardPartBase { /// <summary> /// Метод, создающий тело клавиатуры. /// </summary> /// <param name="document3D"></param> /// <param name="data"></param> public override void Build(ksDocument3D document3D, KeyboardParametersStorage data) { if (document3D == null || data == null) { throw new NullReferenceException("Метод ссылается на null объект."); } part = (ksPart)document3D.GetPart((short)Part_Type.pTop_Part); if (part != null) { // НИЖНЯЯ часть тела клавиатуры. // var entitySketch = (ksEntity)part.NewEntity((short)Obj3dType.o3d_sketch); if (entitySketch != null) { entitySketch.name = "Тело клавиатуры"; var sketchDef = (ksSketchDefinition)entitySketch.GetDefinition(); if (sketchDef != null) { var basePlane = (ksEntity)part.GetDefaultEntity((short)Obj3dType.o3d_planeXOY); sketchDef.SetPlane(basePlane); entitySketch.Create(); var sketchEdit = (ksDocument2D)sketchDef.BeginEdit(); sketchEdit.ksLineSeg(0, 0, 0, - data.BodyDepth, 1); sketchEdit.ksLineSeg(0, - data.BodyDepth, - data.BodyLength, - data.BodyDepth, 1); sketchEdit.ksLineSeg(- data.BodyLength, - data.BodyDepth, -data.BodyLength, 0, 1); sketchEdit.ksLineSeg(- data.BodyLength, 0, 0, 0, 1); sketchDef.EndEdit(); BodyExtruseBottom(data, entitySketch); } } // ВЕРХНЯЯ часть тела клавиатуры. // var entityOffsetPlane = (ksEntity)part.NewEntity((short)Obj3dType.o3d_planeOffset); entitySketch = (ksEntity)part.NewEntity((short)Obj3dType.o3d_sketch); if (entityOffsetPlane != null) { entitySketch.name = "Тело клавиатуры"; var offsetDef = (ksPlaneOffsetDefinition)entityOffsetPlane.GetDefinition(); if (offsetDef != null) { var basePlane = (ksEntity)part.GetDefaultEntity((short)Obj3dType.o3d_planeXOY); basePlane.name = "Начальная плоскость"; offsetDef.direction = true; offsetDef.offset = data.BodyHeight - 3.5; offsetDef.SetPlane(basePlane); entityOffsetPlane.name = "Смещенная плоскость"; entityOffsetPlane.hidden = true; entityOffsetPlane.Create(); var sketchDef = (ksSketchDefinition)entitySketch.GetDefinition(); if (sketchDef != null) { sketchDef.SetPlane(entityOffsetPlane); entitySketch.Create(); var sketchEdit = (ksDocument2D)sketchDef.BeginEdit(); sketchEdit.ksLineSeg(0, 0, 0, - data.BodyDepth, 1); sketchEdit.ksLineSeg(0, - data.BodyDepth, - data.BodyLength, - data.BodyDepth, 1); sketchEdit.ksLineSeg(- data.BodyLength, - data.BodyDepth, - data.BodyLength, 0, 1); sketchEdit.ksLineSeg(- data.BodyLength, 0, - (data.BodyLength / 2) - (data.BoardLength / 2), 0, 1); sketchEdit.ksLineSeg(- (data.BodyLength / 2) - (data.BoardLength / 2), 0, - (data.BodyLength / 2) - (data.BoardLength / 2), - 15.5, 1); sketchEdit.ksLineSeg(- (data.BodyLength / 2) - (data.BoardLength / 2), - 15.5, - (data.BodyLength / 2)+ (data.BoardLength / 2), -15.5, 1); sketchEdit.ksLineSeg(- (data.BodyLength / 2) + (data.BoardLength / 2), - 15.5, - (data.BodyLength / 2) + (data.BoardLength / 2), 0, 1); sketchEdit.ksLineSeg(- (data.BodyLength / 2) + (data.BoardLength / 2), 0, 0, 0, 1); sketchDef.EndEdit(); BodyExtruseTop(data, entitySketch); } } } } } /// <summary> /// Метод выдавливания нижней части тела клавиатуры. /// </summary> /// <param name="data"></param> /// <param name="entity"></param> private void BodyExtruseBottom(KeyboardParametersStorage data, ksEntity entity) { var entityExtrusion = (ksEntity)part.NewEntity((short)Obj3dType.o3d_baseExtrusion); if (entityExtrusion != null) { entityExtrusion.name = "Выдавливание тела"; var extrusionDefinition = (ksBaseExtrusionDefinition)entityExtrusion.GetDefinition(); if (extrusionDefinition != null) { extrusionDefinition.directionType = (short)Direction_Type.dtNormal; extrusionDefinition.SetSideParam(true, (short)End_Type.etBlind, data.BodyHeight - 3.5); extrusionDefinition.SetThinParam(false, 0, 0, 0); extrusionDefinition.SetSketch(entity); entityExtrusion.SetAdvancedColor(Color.FromArgb(120, 120, 120).ToArgb(), .0, .0, .0, .0, 100, 100); entityExtrusion.Create(); } } } /// <summary> /// Метод выдавливания верхней части тела клавиатуры. /// </summary> /// <param name="data"></param> /// <param name="entity"></param> private void BodyExtruseTop(KeyboardParametersStorage data, ksEntity entity) { var entityExtrusion = (ksEntity)part.NewEntity((short)Obj3dType.o3d_baseExtrusion); if (entityExtrusion != null) { entityExtrusion.name = "Выдавливание тела"; var extrusionDefinition = (ksBaseExtrusionDefinition)entityExtrusion.GetDefinition(); if (extrusionDefinition != null) { extrusionDefinition.directionType = (short)Direction_Type.dtNormal; extrusionDefinition.SetSideParam(true, (short)End_Type.etBlind, data.BodyHeight - (data.BodyHeight - 3.5)); extrusionDefinition.SetThinParam(false, 0, 0, 0); extrusionDefinition.SetSketch(entity); entityExtrusion.SetAdvancedColor(Color.FromArgb(120, 120, 120).ToArgb(), .0, .0, .0, .0, 100, 100); entityExtrusion.Create(); } } } } }
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using System.IO; namespace Reading_RSS_feed.Models { public partial class RssDbContext : DbContext { public RssDbContext() { Database.EnsureCreated(); } public virtual DbSet<ItemNews> News { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer("Data Source=WIN-AH0B86FQ7GQ\\MSSQLSERVER2019;Database=Rss;Trusted_Connection=True;"); } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<ItemNews>(entity => { entity.HasKey(e => e.Id); }); OnModelCreatingPartial(modelBuilder); } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); } }
using PlatformRacing3.Server.Game.Communication.Messages.Outgoing.Json; namespace PlatformRacing3.Server.Game.Communication.Messages.Outgoing; internal class MessageOutgoingMessage : JsonOutgoingMessage<JsonMessageOutgoingMessage> { internal MessageOutgoingMessage(string roomName, JsonMessageOutgoingMessage.RoomMessageData data) : base(new JsonMessageOutgoingMessage(roomName, data)) { } internal MessageOutgoingMessage(uint socketId, JsonMessageOutgoingMessage.RoomMessageData data) : base(new JsonMessageOutgoingMessage(socketId, data)) { } internal MessageOutgoingMessage(string roomName, uint socketId, JsonMessageOutgoingMessage.RoomMessageData data) : base(new JsonMessageOutgoingMessage(roomName, socketId, data)) { } }
using MediatR; using System.ServiceProcess; using System.Threading; using System.Threading.Tasks; using static System.ServiceProcess.ServiceControllerStatus; namespace ServerManagement.Core.Services.Commands.StopService { public class StopServiceRequest : MediatR.IRequest<ServiceControllerStatus> { public string ServiceName { get; set; } } public class StopServiceRequestHandler : IRequestHandler<StopServiceRequest, ServiceControllerStatus> { public Task<ServiceControllerStatus> Handle(StopServiceRequest request, CancellationToken cancellationToken) { // Note: When debugging in VS, remember to run VS as admin to not throw "Access Denied" message. var sc = new ServiceController(request.ServiceName); if (sc.Status != Stopped && sc.Status != StopPending) { sc.Stop(); } // Return current status return Task.FromResult(sc.Status); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AdapterPattern { public class Client { private readonly ITarget _target; public Client(ITarget target) { _target = target; } public void ProcessRequest() { _target.Request(); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using NuGet.Configuration; using NuGet.Protocol.Core.Types; using NuGet.Protocol.Core.v3; namespace NuGet.Protocol.PowerShellGet { public static class FactoryExtensionsPowerShell { public static SourceRepository GetPowerShell(this Repository.RepositoryFactory factory, string source) { return Repository.CreateSource(Repository.Provider.GetPowerShell(), source); } public static SourceRepository GetPowerShell(this Repository.RepositoryFactory factory, PackageSource source) { return Repository.CreateSource(Repository.Provider.GetPowerShell(), source); } /// <summary> /// Core V3 + PowerShell /// </summary> public static IEnumerable<Lazy<INuGetResourceProvider>> GetPowerShell(this Repository.ProviderFactory factory) { yield return new Lazy<INuGetResourceProvider>(() => new PowerShellSearchResourceProvider()); foreach (var provider in Repository.Provider.GetCoreV3()) { yield return provider; } yield break; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestPartA8 { class Aerobic : ChinOfResTraining { public override void Handle() { if (next != null) { Console.WriteLine("aerobic"); next.Handle(); } } } }
using UnityEngine; using System.Collections; using System.Xml; using UnityEngine.UI; using System; namespace BusinessTycoonSim { // TODO: This should be refactored to remove filling the UI // Once refactored LoadGameData would not (need to) inherit from MonoBehaviour // Ideally this class would have no concerns over how the UI is loaded // Because prefab initation is an extremely popular design pattern in Unity // This is not so much 'bad' design for smaller game projects. // In complex projects you should not rely at all on drag/drop components public class LoadGameData : MonoBehaviour { // Constants // TODO: We don't really want to hardcode this in our exe // perhaps a .dat or .config file to better implement //const string GameDataFile = "GameData_UnlimitedStores"; const string CurrencyDataFile = "BigNumbers"; const string resourcepath = "/FirstClassGameStudios/Resources/"; // Example of observer design pattern // Send out message to all subscribers when we are finished loading our game data // This technique is great when you need to have certain components loaded and in place before others public delegate void LoadDataComplete(); public static event LoadDataComplete OnLoadDataComplete; // Used to hold the XML data that defines the stores... // By editing the XML data you can change the balance of your stores, add new stores, and control the behavior of the game private TextAsset gameData; // We hold references here to our key interface objects and data stores // so we can easily load them with our gamedata // Holds a reference to our StorePanel private GameObject storePanel; // Holds a reference to our UpgradePanel and UpgradePrefab private GameObject upgradePanel; // Counts how many upgrades we have loaded... used to size the updatepanel // As transform.childcount returns 0. Probably because the panel is disabled. private int upgradeCount; // Holds a link to our UIManager private UIManager uiManagerObj; public string GameDataFile; #region Setters & Getters public TextAsset GameData { get { return gameData; } set { gameData = value; } } public GameObject StorePanel { get { return storePanel; } set { storePanel = value; } } public int UpgradeCount { get { return upgradeCount; } set { upgradeCount = value; } } public UIManager UIManagerObj { get { return uiManagerObj; } set { uiManagerObj = value; } } public GameObject UpgradePanel { get { return upgradePanel; } set { upgradePanel = value; } } #endregion public void Start() { // Load the references to the UI panels we will load the prefabs into // These were previously components that we used a drag and drop to wire them into the class // This method allows us to keep these private to the class... they must be public to drag and drop components gamemanager.CurrentState = gamemanager.State.Loading; storePanel = GameObject.Find("StorePanel"); UpgradePanel = (GameObject)utils.FindInactiveObjects("UpgradesListPanel", typeof(GameObject)); //GameObject Canvas = GameObject.Find("Canvas"); //upgradePanel = Canvas.transform.Find("UpgradesListPanel").gameObject; if (storePanel == null || UpgradePanel == null) { Debug.LogError("Could not find critical references to load game data: storePanel=" + storePanel.ToString() + ", UpgradePanel=" + UpgradePanel.ToString()); } // Loads the Game data... Changed name from LoadData to better describe the purpose LoadGameDataFromXML(); } public void LoadGameDataFromXML() { // Load our game data here... // TODO: Create a more elegant solution for loading in alternate game data string Filepath = Application.dataPath + resourcepath + GameDataFile; Debug.Log(Filepath); GameData = Resources.Load("GameData/" + GameDataFile) as TextAsset; Debug.Log(GameData); // Load Currency Data (ie million, billion, trillion, etc... up to 300+ descriptions) LoadCurrencyData(); // Create XML Document to hold game data XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(GameData.text); // Load Game Manager Data LoadGameManagerData(xmlDoc); // Load the Stores LoadStores(xmlDoc); // After we have loaded the stores we need to resize our update panel to hold all the children DynamicScrollFitter(upgradePanel, upgradeCount,1); DynamicScrollFitter(storePanel, gamemanager.StoreList.Count,2); if (OnLoadDataComplete != null) // Make sure we have at least one observer OnLoadDataComplete(); //new LoadPlayerDataPrefs().LoadSavedGame(); } public void LoadGameManagerData(XmlDocument xmlDoc) { // Load data items used within the gamemanager gamemanager.StartingBalance = double.Parse(utils.LoadGameDataElement("StartingBalance", xmlDoc)); gamemanager.CompanyName = utils.LoadGameDataElement("CompanyName", xmlDoc); gamemanager.GameName = utils.LoadGameDataElement("GameName", xmlDoc); gamemanager.FirstStoreCount = utils.LoadGameDataElementInt("FirstStoreCount", xmlDoc); gamemanager.ShareholderMultiplier = utils.LoadGameDataElementFloat("ShareHolderBonusPercent", xmlDoc); } // Loads the stores that are to be used in the game void LoadStores(XmlDocument xmlDoc) { // Look through our XML nodes to get a list of all the stores XmlNodeList StoreList = xmlDoc.GetElementsByTagName("store"); // loop through all the store notes foreach (XmlNode StoreInfo in StoreList) { //Load Store Nodes for each store LoadStoreNodes(StoreInfo); } } // Because our panel is disabled the dynamic content components do not work reliably // This method will dynamically resize our updatepanel to the right height // for our stores // // Depreciated: We no longer call this method once we figured out Unity's built in tools to dynamically resize the updatepanel // Leaving it in just in case at some point in the future we need to manually set the scroll view void DynamicScrollFitter(GameObject Panel, int NumberOfItems, int NumCols) { GridLayoutGroup layoutGroup = Panel.GetComponent<GridLayoutGroup>(); RectTransform myTransform = Panel.GetComponent<RectTransform>(); // Get the cellsize and padding Vector2 cellSize = layoutGroup.cellSize; RectOffset padding = layoutGroup.padding; // Get a reference to the size of our panel Vector2 newScale = myTransform.sizeDelta; // Calculate the size of the panel with the upgradelist newScale.y = ((cellSize.y + layoutGroup.spacing.y) * NumberOfItems / NumCols); newScale.y = newScale.y + padding.bottom; // Set the size of the panel myTransform.sizeDelta = newScale; } // Each store in XML has several nodes that describe the store // Loop through the nodes and load their values into the store prefab void LoadStoreNodes(XmlNode StoreInfo) { GameObject NewStore = (GameObject)Instantiate(Resources.Load("Prefabs/StorePrefab")); store storeobj = NewStore.GetComponent<store>(); XmlNodeList StoreNodes = StoreInfo.ChildNodes; foreach (XmlNode StoreNode in StoreNodes) { SetStoreObj(storeobj, StoreNode, NewStore); } // Connect our store to the parent panel NewStore.transform.SetParent(StorePanel.transform); // Add store to list in game manager... we could get them from the store panel // But that would be bad form //Debug.Log(storeobj.name + " should be adding into list"); gamemanager.AddStore(storeobj); } // Check each node name and store the value in the appropriate property of the store node void SetStoreObj(store storeobj, XmlNode StoreNode, GameObject NewStore) { // This will match the XML node 'name' for the store if (StoreNode.Name == "name") { // Locate the text object in the StoreNode Text StoreText = NewStore.transform.Find("StoreNameText").GetComponent<Text>(); // This sets the visual store node name in the UI for the store StoreText.text = StoreNode.InnerText; // This sets the storename as property in the store object // An alternative design would move this to the StoreUI and perhaps set it using the obersver pattern storeobj.StoreName = StoreNode.InnerText; } // We load the image out of our Resources and store it in the Storeimage.sprite property. This is how we // Load the correct image out of XML for each store // TODO: Create a utility function to wrap the calls to float.parse and other calls to StoreNode.InnerText in try blocks if (StoreNode.Name == "image") { storeobj.StoreImage = StoreNode.InnerText; string SpriteFile = "StoreIcons/" + storeobj.StoreImage; Sprite newSprite = Resources.Load<Sprite>(SpriteFile); Image StoreImage = NewStore.transform.Find("ImageButtonClick").GetComponent<Image>(); StoreImage.sprite = newSprite; } // Continue loading all the store properties from XML if (StoreNode.Name == "BaseStoreProfit") storeobj.BaseStoreProfit = float.Parse(StoreNode.InnerText); if (StoreNode.Name == "BaseStoreCost") storeobj.BaseStoreCost = float.Parse(StoreNode.InnerText); if (StoreNode.Name == "StoreTimer") { storeobj.StoreTimer = float.Parse(StoreNode.InnerText); storeobj.BaseTimer = storeobj.StoreTimer; } if (StoreNode.Name == "StoreMultiplier") storeobj.StoreMultiplier = float.Parse(StoreNode.InnerText); if (StoreNode.Name == "StoreTimerDivision") storeobj.StoreTimerDivision = int.Parse(StoreNode.InnerText); if (StoreNode.Name == "StoreCount") storeobj.StoreCount = int.Parse(StoreNode.InnerText); if (StoreNode.Name == "Manager") CreateManager(StoreNode, storeobj); if (StoreNode.Name == "Upgrades") CreateUpgrades(StoreNode, storeobj); if (StoreNode.Name == "id") storeobj.StoreID = int.Parse(StoreNode.InnerText); } // Loop through all the upgrade nodes void CreateUpgrades(XmlNode UpgradesNode, store Storeobj) { foreach (XmlNode UpgradeNode in UpgradesNode) { CreateUpgrade(UpgradeNode, Storeobj); } } // Creating a manager requires creating a new prefab, loading the items from XML and the storing the prefab in the managerpanel void CreateManager(XmlNode ManagerNode, store Storeobj) { float ManagerCost = 0f; string ManagerName = ""; foreach (XmlNode ManagerInfo in ManagerNode) { if (ManagerInfo.Name == "ManagerCost") ManagerCost = float.Parse(ManagerInfo.InnerText); if (ManagerInfo.Name == "ManagerName") ManagerName = ManagerInfo.InnerText; } // Create the Store Manager Object... In this design pattern we have left all this work to the store class Storeobj.CreateStoreManager(ManagerCost, ManagerName); } // Create each upgrade from the XML gamedata void CreateUpgrade(XmlNode UpgradeNode, store Storeobj) { // By default we will have a 1f multipler and 1f upgrade cost float UpgradeMultiplier = 1f; float UpgradeCost = 1f; string UpgradeName = ""; // Loop through the XML nodes for the upgrade and load the values into our variables // If we had more than a few we should refactor into another method foreach (XmlNode UpgradeInfo in UpgradeNode) { if (UpgradeInfo.Name == "UpgradeMultiplier") UpgradeMultiplier = float.Parse(UpgradeInfo.InnerText); if (UpgradeInfo.Name == "UpgradeCost") UpgradeCost = float.Parse(UpgradeInfo.InnerText); if (UpgradeInfo.Name == "UpgradeName") UpgradeName = UpgradeInfo.InnerText; } // We use a static method in storeupgrade class to create our store upgrade storeupgrade.CreateStoreUpgrade(UpgradeCost, UpgradeMultiplier, Storeobj, UpgradeName); // Increment upgrade count... used to set the height of our updatepanel afteer transform.childcount continued to return 0 UpgradeCount++; } // Loads the array of currency names // Sourced from a CSV file in data folder (bignumbers.csv) that // was drag and dropped into the CurrencyData propery on the LoadGameData object // Because we have over 300 currency names we have chosen not to hardcode them but // Instead to load them for a data file. This provices greater flexibility as you could // easily change how your processes without changing hundreds of lines of code. void LoadCurrencyData() { TextAsset CurrencyData = Resources.Load(CurrencyDataFile) as TextAsset; // Get the data from the csv file string FileData = CurrencyData.text; // Get all the rows of data... \n finds the hidden return that separates the lines string[] lines = FileData.Split("\n"[0]); // Create a new array list to hold our array ArrayList CurrencyArray = new ArrayList(); // We start at 6 because that is the millionth 'exponent'... this will be the first text description for an amount in the game int Counter = 6; // Load each row of the data foreach (string line in lines) { // This command breaks the comma delimited line of data into separate fields //string[] linedata = (line.Trim()).Split(","[0]); // Create a new Curreny item to hold our data CurrencyItem CreateItem = new CurrencyItem(); // Set the key value we will lookup to find the correct currency description CreateItem.KeyVal = Counter; try { // Format our exponent for this currency description. This is used to divide our currency amount so we can properly format the string CreateItem.ExpVal = double.Parse("1e" + (Counter).ToString()); } catch (OverflowException) { Debug.Log("Maximum Value reached, counter=" + Counter.ToString()); break; } // Get the currency name from the data file CreateItem.CurrencyName = line; // Keeping this debug commented inline in case we need it again for troubleshooting //Debug.Log("Key:" + CreateItem.KeyVal.ToString() + "-" + string.Format("{0:0.##E+00}", CreateItem.ExpVal) + " " + CreateItem.CurrencyName); // Add the currency item to the array CurrencyArray.Add(CreateItem); // We need to increment by 3 for each currency description as they will only change every 3 decimal places as the value grows // (ie 1.2 million, 12.3 million, 123.0 million ---- 2.1 Billion,21.0 Billion, 210.0 Billion, --- 3.2 Trillion, 33.2. 333.3 --- etc.) Counter = Counter + 3; } // Store the array we have created in our game manager for access during gameplay gamemanager.CurrencyArray = CurrencyArray; } } // Class to hold each currency level... These are every 3 exponents.... // e1 for 1,000, e3 for millions, e6 for billions, e9 for trillions, etc. // TODO: Refactor with simple arrays to gain some performance increase // As the game never really 'grows' in terms of new objects as the game progresses // it probably just isn't a priority public class CurrencyItem { // We look up this value by using the log10 of the amount. private int keyVal; // Thist stores the amount we need to divide by in order to properly format the results. (ie 3,403,000 / 1e6) = 3.403 private double expVal; // Currency label (ie million, billion, trillion, etc) private string currencyName; // Protect all our variables by keeping them private -- good practice to do throughout public int KeyVal { get { return keyVal; } set { keyVal = value; } } public double ExpVal { get { return expVal; } set { expVal = value; } } public string CurrencyName { get { return currencyName; } set { currencyName = value; } } } }
using Model.DataEntity; using Model.Locale; using Model.Helper; using ProcessorUnit.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using Utility; using Model.InvoiceManagement; using ClosedXML.Excel; using System.Xml; using Model.Schema.TXN; using Business.Helper.InvoiceProcessor; using ProcessorUnit.Helper; namespace ProcessorUnit.Execution { public class InvoiceXmlRequestForCBEProcessor : ExecutorForever { public InvoiceXmlRequestForCBEProcessor() { appliedProcessType = Naming.InvoiceProcessType.C0401_Xml_CBE; processRequest = (uploadData, requestItem) => { Root result = this.CreateMessageToken(); using (InvoiceManagerForCBE manager = new InvoiceManagerForCBE()) { manager.UploadInvoiceAutoTrackNo(uploadData, result, out OrganizationToken token); manager.BindProcessedItem(requestItem); } return result.ConvertToXml(); }; } protected virtual XmlDocument prepareDocument(String invoiceFile) { XmlDocument docInv = new XmlDocument(); docInv.Load(invoiceFile); ///去除"N/A"資料 /// var nodes = docInv.SelectNodes("//*[text()='N/A']"); for (int i = 0; i < nodes.Count; i++) { var node = nodes.Item(i); node.RemoveChild(node.SelectSingleNode("text()")); } /// return docInv; } protected Func<XmlDocument, ProcessRequest, XmlDocument> processRequest; protected override void ProcessRequestItem() { ProcessRequest requestItem = queueItem.ProcessRequest; String requestFile = requestItem.RequestPath.StoreTargetPath(); if(File.Exists(requestFile)) { Organization agent = requestItem.Organization; requestItem.ProcessStart = DateTime.Now; models.SubmitChanges(); XmlDocument uploadData = prepareDocument(requestFile); var result = processRequest(uploadData, requestItem); String responseName = $"{Path.GetFileNameWithoutExtension(requestFile)}_Response.xml"; String responsePath = Path.Combine(Path.GetDirectoryName(requestFile), responseName); if (SettingsHelper.Instance.ResponsePath != null) { responsePath = responsePath.Replace(Uxnet.Com.Properties.AppSettings.AppRoot, SettingsHelper.Instance.ResponsePath); } result.Save(responsePath); requestItem.ProcessComplete = DateTime.Now; requestItem.ResponsePath = responsePath; if (requestItem.ProcessCompletionNotification == null) requestItem.ProcessCompletionNotification = new ProcessCompletionNotification { }; models.DeleteAnyOnSubmit<ProcessRequestQueue>(d => d.TaskID == queueItem.TaskID); models.SubmitChanges(); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; namespace AchievementFramework { /* TODO List: * Rewrite the load and save acievement methods to use an XmlSerializer instead of hand coding everything */ public static class AchievementManager { //Achieveents are stored by their Id public static Dictionary<string, List<Achievement>> ActionListeners = new Dictionary<string, List<Achievement>>(); public static Dictionary<Guid, Achievement> AchievementList = new Dictionary<Guid, Achievement>(); public static int AchievementPoints { get { if(Initialized) { int result = 0; foreach(Achievement a in AchievementList.Values) { if(a.Earned) result += a.Points; } return result; } else { return 0; } } } public static int MaxAchievementPoints { get; private set; } private static Queue<Guid> QueuedCompletedAchievements = new Queue<Guid>(); private static bool Initialized = false; public static bool ProcessingAction { get; private set; } public delegate void AchievementComplete(Guid id); public static AchievementComplete NotifyOnAchievementComplete; public static string AchievementsMasterFilename{ get; set; } private static XmlDocument MasterFileDocument; public static void CreateNewMasterFile(string path) { //Process the filename first to check for .xml, add if doesnt exist if(Path.GetExtension(path) == string.Empty)//There is no extension { //add an extension on the end path += ".xml"; } AchievementsMasterFilename = path; //Create a new file using the path and filename File.Create(AchievementsMasterFilename); MasterFileDocument = new XmlDocument(); MasterFileDocument.Load(AchievementsMasterFilename); MasterFileDocument.CreateXmlDeclaration("1.0", null, null); MasterFileDocument.Save(AchievementsMasterFilename); } public static void LoadAchievements(string achievementsMasterFilename, string achievementProgress) { ProcessingAction = false; //Set the Master Achievement Database filename AchievementsMasterFilename = achievementsMasterFilename; //Create the XML object XmlDocument achievementDoc = new XmlDocument(); achievementDoc.Load(AchievementsMasterFilename); //get a list of achievements XmlNodeList achievements = achievementDoc.SelectNodes("/Achievements/Achievement"); foreach(XmlNode achievement in achievements) { RegisterAchievement(achievement); } foreach(Achievement a in AchievementList.Values) { MaxAchievementPoints += a.Points; } Initialized = true; LoadAchievementProgress(achievementProgress); } private static void LoadAchievementProgress(string achievementProgress) { if(Initialized) { //Build a list of Achievement ID's that already have progress if(achievementProgress != string.Empty) { ProcessAchievementProgress(achievementProgress.Split(':').ToList()); } } else { throw new InvalidOperationException("AchievemntManager is not Initialized!"); } //All Achievements progress has been loaded. Now fill the ActionListener container FillActionListeners(); } private static void FillActionListeners() { foreach(Achievement achievement in AchievementList.Values) { if(!achievement.Earned && IsAchievementEarned(achievement.RequiredAchievementId)) { foreach(string actionType in achievement.Progress.Keys) { //Check if the ActionType is already registered if(ActionListeners.ContainsKey(actionType)) { //ActionType is registered, add this achievement to its list ActionListeners[actionType].Add(achievement); } else { //Action type is not registered, register it and create a new list of achievements List<Achievement> tempList = new List<Achievement>(); tempList.Add(achievement); ActionListeners.Add(actionType, tempList); } } } } } /* Progress is encoded in the following manner: * AchievementID,ActionType,Value * Each achievements progress is seperated by a colon ':' * So the first split in the LoadAchievements method splits the achievements into a list * The second split takes each achievement and seperates its progress * The number of ActionTypes for each achievement can be different. to figure out how many types * a particular achievement has we first split the achievement using a comma ',' and count the members of the resulting string array * Then subtract 1 from that number, and divide by 2 * Example: 3,EnemyShipDestroyed,745:4,EnemyAFrigateDestroyed,3,EnemyBFrigateDestroyed,5,EnemyCFrigateDestroyed,2 * This translates to: * -Achievement ID 3 has an ActionType of EnemyShipDestroyed and the current progress is 745 * -Achievement ID 4 has 3 ActionTypes: EnemyAFrigateDestroyed with a progress of 3 * EnemyBFrigateDestroyed with a progress of 5 * EnemyCFrigateDestroyed with a progress of 2 */ private static void ProcessAchievementProgress(List<string> achievementsProgressData) { foreach(string progress in achievementsProgressData) { //Split each achievement into its raw data string[] data = progress.Split(','); Guid achievementId = new Guid(data[0]); //determine the number of actiontypes for this achievement if(data.Length > 1) //Length greater then 1 means there is progress { //loop through the action types for(int i = 1; i < data.Length; i += 2) { Action a = new Action(data[i], Convert.ToInt32(data[i + 1])); if(AchievementList.ContainsKey(achievementId)) { AchievementList[achievementId].OnAction(a); } } } else { //Data only has 1 element, this achievement has be unlocked already and progress does not need to be tracked if(AchievementList.ContainsKey(achievementId)) { AchievementList[achievementId].Earned = true; } } } } //This method Adds and Achievement to the master file public static void AddAchievment(Achievement achievement) { MasterFileDocument.Load(AchievementsMasterFilename); XmlNode achivementNode = MasterFileDocument.CreateNode(XmlNodeType.Element, "Achivement", "Achievements/"); MasterFileDocument.Save(AchievementsMasterFilename); } //This method registers a single achievment with the AchievmentManager private static void RegisterAchievement(XmlNode achievementNode) { //Pull the basics from the XML for each achievement string name = achievementNode["Name"].InnerText; Guid id = new Guid(achievementNode["ID"].InnerText); string description = achievementNode["Description"].InnerText; string category = achievementNode["Category"].InnerText; string subcategory = achievementNode["Subcategory"].InnerText; int iconId = Convert.ToInt32(achievementNode["IconID"].InnerText); int points = Convert.ToInt32(achievementNode["Points"].InnerText); Guid? requiredAchievement; if(achievementNode["RequiredAchievement"] != null) { requiredAchievement = new Guid(achievementNode["RequiredAchievement"].InnerText); } else { requiredAchievement = null; } XmlNodeList actionProgressList = achievementNode["Progression"].ChildNodes; Dictionary<string, ActionProgress> actionProgress = new Dictionary<string, ActionProgress>(); //Pull the progress information from the achievement XML foreach(XmlNode progress in actionProgressList) { //Create a blank ActionProgress to store the RequiredProgress ActionProgress ap = new ActionProgress(); //Verify that the node contains both the ActionType and RequiredProgress attributes if(progress.Attributes["ActionType"] != null && progress.Attributes["RequiredValue"] != null) { //Set the RequiredProgress ap.Required = Convert.ToInt32(progress.Attributes["RequiredValue"].Value); //Verify the action isnt registered with the actionProgress if(!actionProgress.ContainsKey(progress.Attributes["ActionType"].Value)) { actionProgress.Add(progress.Attributes["ActionType"].Value, ap); } else { //action type is registered twice, this is not allowed throw new IndexOutOfRangeException("ActionType: " + progress.Attributes["ActionType"].Value + " is already registered for AchievementID: " + id.ToString()); } } } Achievement achievement = new Achievement(name, id, description, category, subcategory, iconId, actionProgress, points, false, requiredAchievement); //Add the achievement to the AchievementList if it is not already there if(!AchievementList.ContainsKey(achievement.Id)) { AchievementList.Add(achievement.Id, achievement); } else { //Can not register an achievement twice with the same ID throw new IndexOutOfRangeException("AchievementList already contains Achievement ID: " + achievement.Id); } } public static string SaveAchievementProgress() { string achievementProgress = ""; foreach(Achievement achievement in AchievementList.Values) { //If the achievement is earned, just add its ID to the progress and move on if(achievement.Earned) { achievementProgress += achievement.Id.ToString() + ":"; continue; } //If the achievement is not earned, we need to add each actions progress to the list else { string actionList = ""; foreach(string actionType in achievement.Progress.Keys) { if(achievement.Progress[actionType].Current > 0) { actionList += "," + actionType + ","; actionList += achievement.Progress[actionType].Current.ToString(); } } //If the actionList contains actions whos values are not 0 add them to the progress record if(actionList != "") { achievementProgress += achievement.Id.ToString() + actionList + ":"; } else //If there are no actions and the achievement has not been earned, skip logging this achievement { continue; } } } return achievementProgress; } //Process Actions here public static LogActionResults LogAction(Action action) { LogActionResults result = new LogActionResults(); //Check that the actiontype is registered with the action listeners if(ActionListeners.ContainsKey(action.Type)) { foreach(Achievement achievement in ActionListeners[action.Type].ToList()) { if(AchievementList.ContainsKey(achievement.Id)) { AchievementList[achievement.Id].OnAction(action); } } result.Status = LogActionResultsEnum.Ok; result.Message = "ActionType: " + action.Type + " Handled without issue."; } else { //The action type in not registered //throw new IndexOutOfRangeException("ActionType: " + action.Type + " is not a registered type!"); result.Status = LogActionResultsEnum.ActionTypeNotRegistered; result.Message = "Error: ActionType - " + action.Type + " is not a registered ActionType."; } //Listeners are removed as they are earned, so we need to update the listener //container with any achievements that may have been opened while(QueuedCompletedAchievements.Count > 0) { Guid id = QueuedCompletedAchievements.Dequeue(); //First remove achievement from ActionListeners foreach(string actionType in AchievementList[id].Progress.Keys) { //Check that this actionType is registered if(ActionListeners.ContainsKey(actionType)) { ActionListeners[actionType].RemoveAll(a => a.Id == id); } } //Then check for achievements that required this acievement to be earned, and add them to the ActionListeners foreach(Achievement a in AchievementList.Values) { if(a.RequiredAchievementId != null) { if(id == a.RequiredAchievementId) { //Add a to actionlisteners foreach(string actionType in a.Progress.Keys) { //Check if the ActionType is already registered if(ActionListeners.ContainsKey(actionType)) { //ActionType is registered, add this achievement to its list ActionListeners[actionType].Add(a); } else { //Action type is not registered, register it and create a new list of achievements List<Achievement> tempList = new List<Achievement>(); tempList.Add(a); ActionListeners.Add(actionType, tempList); } } } } } } return result; } public static bool IsAchievementEarned(Guid? id) { bool result = false; if(id == null) { return true; } if(id.HasValue) { if(AchievementList.ContainsKey(id.Value)) { result = AchievementList[id.Value].Earned; } } return result; } //Used by Achievement's to notify theyre complete public static void OnAchievementComplete(Guid id) { //Add much more here to regenerate ActionListeners list QueuedCompletedAchievements.Enqueue(id); if(NotifyOnAchievementComplete != null) NotifyOnAchievementComplete(id); } } public enum LogActionResultsEnum { Ok, ActionTypeNotRegistered, } public struct LogActionResults { public LogActionResultsEnum Status; public string Message; } }
using PDV.DAO.Custom; using PDV.DAO.DB.Controller; using PDV.DAO.Entidades.Financeiro; using PDV.DAO.Enum; using System.Data; namespace PDV.CONTROLER.Funcoes { public class FuncoesChequesCtaReceber { public static bool Existe(decimal IDCHEQUECONTARECEBER) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = "SELECT 1 FROM CHEQUECONTARECEBER WHERE IDCHEQUECONTARECEBER = @IDCHEQUECONTARECEBER"; oSQL.ParamByName["IDCHEQUECONTARECEBER"] = IDCHEQUECONTARECEBER; oSQL.Open(); return !oSQL.IsEmpty; } } public static DataTable GetChequeContaReceber(decimal IDBaixaRecebimento) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"SELECT CHEQUECONTARECEBER.IDCHEQUECONTARECEBER, CHEQUECONTARECEBER.NUMERO, CHEQUECONTARECEBER.EMISSAO, CHEQUECONTARECEBER.VENCIMENTO, CHEQUECONTARECEBER.VALOR, CHEQUECONTARECEBER.CRUZADO, CHEQUECONTARECEBER.COMPENSADO, CHEQUECONTARECEBER.DATACOMPENSACAO, CHEQUECONTARECEBER.DEVOLVIDO, CHEQUECONTARECEBER.DATADEVOLUCAO, CHEQUECONTARECEBER.REPASSE, CHEQUECONTARECEBER.DATAREPASSE, CHEQUECONTARECEBER.OBSREPASSE, CHEQUECONTARECEBER.IDBAIXARECEBIMENTO FROM CHEQUECONTARECEBER WHERE CHEQUECONTARECEBER.IDBAIXARECEBIMENTO = @IDBAIXARECEBIMENTO"; oSQL.ParamByName["IDBAIXARECEBIMENTO"] = IDBaixaRecebimento; oSQL.Open(); return oSQL.dtDados; } } public static bool Salvar(ChequeContaReceber chequeContaReceber, TipoOperacao Op) { using (SQLQuery oSQL = new SQLQuery()) { switch (Op) { case TipoOperacao.INSERT: oSQL.SQL = @"INSERT INTO CHEQUECONTARECEBER(IDCHEQUECONTARECEBER, IDBAIXARECEBIMENTO, NUMERO, VALOR, EMISSAO, VENCIMENTO, CRUZADO, COMPENSADO, DATACOMPENSACAO, DEVOLVIDO, DATADEVOLUCAO, REPASSE, DATAREPASSE, OBSREPASSE) VALUES (@IDCHEQUECONTARECEBER, @IDBAIXARECEBIMENTO, @NUMERO, @VALOR, @EMISSAO, @VENCIMENTO, @CRUZADO, @COMPENSADO, @DATACOMPENSACAO, @DEVOLVIDO, @DATADEVOLUCAO, @REPASSE, @DATAREPASSE, @OBSREPASSE)"; break; case TipoOperacao.UPDATE: oSQL.SQL = @"UPDATE CHEQUECONTARECEBER SET IDCHEQUECONTARECEBER = @IDCHEQUECONTARECEBER, IDBAIXARECEBIMENTO = @IDBAIXARECEBIMENTO, NUMERO = @NUMERO, VALOR = @VALOR, EMISSAO = @EMISSAO, VENCIMENTO = @VENCIMENTO, CRUZADO = @CRUZADO, COMPENSADO = @COMPENSADO, DATACOMPENSACAO = @DATACOMPENSACAO, DEVOLVIDO = @DEVOLVIDO, DATADEVOLUCAO = @DATADEVOLUCAO, REPASSE = @REPASSE, DATAREPASSE = @DATAREPASSE, OBSREPASSE = @OBSREPASSE WHERE IDCHEQUECONTARECEBER = @IDCHEQUECONTARECEBER"; break; } oSQL.ParamByName["IDCHEQUECONTARECEBER"] = chequeContaReceber.IDChequeContaReceber; oSQL.ParamByName["IDBAIXARECEBIMENTO"] = chequeContaReceber.IDBaixaRecebimento; oSQL.ParamByName["NUMERO"] = chequeContaReceber.Numero; oSQL.ParamByName["VALOR"] = chequeContaReceber.Valor; oSQL.ParamByName["EMISSAO"] = chequeContaReceber.Emissao; oSQL.ParamByName["VENCIMENTO"] = chequeContaReceber.Vencimento; oSQL.ParamByName["CRUZADO"] = chequeContaReceber.Cruzado; oSQL.ParamByName["COMPENSADO"] = chequeContaReceber.Compensado; oSQL.ParamByName["DATACOMPENSACAO"] = chequeContaReceber.DataCompensacao; oSQL.ParamByName["DEVOLVIDO"] = chequeContaReceber.Devolvido; oSQL.ParamByName["DATADEVOLUCAO"] = chequeContaReceber.DataDevolucao; oSQL.ParamByName["REPASSE"] = chequeContaReceber.Repasse; oSQL.ParamByName["DATAREPASSE"] = chequeContaReceber.DataRepasse; oSQL.ParamByName["OBSREPASSE"] = chequeContaReceber.ObsRepasse; return oSQL.ExecSQL() == 1; } } public static bool Remover(decimal IDCHEQUECONTARECEBER) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = "DELETE FROM CHEQUECONTARECEBER WHERE IDCHEQUECONTARECEBER = @IDCHEQUECONTARECEBER"; oSQL.ParamByName["IDCHEQUECONTARECEBER"] = IDCHEQUECONTARECEBER; return oSQL.ExecSQL() == 1; } } } }
using Microsoft.Xna.Framework; using SprintFour.Collisions; using SprintFour.Player; using SprintFour.Utilities; using System; namespace SprintFour.Blocks.BlockStates { public class KillBlockState : BlockStateBase { public override Tuple<int, int>[] GetFrames() { return Utility.HiddenBlockFrames; } public override bool ActivateBlock(Vector2 direction, ICollidable ob) { Mario mario = ob as Mario; if(mario != null) mario.Kill(); return true; } } }
using System; using System.Collections.Generic; using DotNetty.Transport.Channels; using Plus.Communication.Packets.Outgoing; using Plus.Communication.Packets.Outgoing.BuildersClub; using Plus.Communication.Packets.Outgoing.Handshake; using Plus.Communication.Packets.Outgoing.Inventory.Achievements; using Plus.Communication.Packets.Outgoing.Inventory.AvatarEffects; using Plus.Communication.Packets.Outgoing.Moderation; using Plus.Communication.Packets.Outgoing.Navigator; using Plus.Communication.Packets.Outgoing.Notifications; using Plus.Communication.Packets.Outgoing.Rooms.Chat; using Plus.Communication.Packets.Outgoing.Sound; using Plus.Core; using Plus.Database.Interfaces; using Plus.HabboHotel.Permissions; using Plus.HabboHotel.Rooms; using Plus.HabboHotel.Subscriptions; using Plus.HabboHotel.Users; using Plus.HabboHotel.Users.Messenger.FriendBar; using Plus.HabboHotel.Users.UserData; using Plus.Network.Codec; namespace Plus.HabboHotel.GameClients { public class GameClient { private Habbo _habbo; public string MachineId; private bool _disconnected; private readonly IChannelHandlerContext _channel; public int PingCount { get; set; } public GameClient(IChannelHandlerContext context) { _channel = context; } public bool TryAuthenticate(string authTicket) { try { UserData userData = UserDataFactory.GetUserData(authTicket, out byte errorCode); if (errorCode == 1 || errorCode == 2) { Disconnect(); return false; } #region Ban Checking //Let's have a quick search for a ban before we successfully authenticate.. if (!string.IsNullOrEmpty(MachineId)) { if (PlusEnvironment.GetGame().GetModerationManager().IsBanned(MachineId, out _)) { if (PlusEnvironment.GetGame().GetModerationManager().MachineBanCheck(MachineId)) { Disconnect(); return false; } } } if (userData.User != null) { if (PlusEnvironment.GetGame().GetModerationManager().IsBanned(userData.User.Username, out _)) { if (PlusEnvironment.GetGame().GetModerationManager().UsernameBanCheck(userData.User.Username)) { Disconnect(); return false; } } } #endregion if (userData.User == null) //Possible NPE { return false; } PlusEnvironment.GetGame().GetClientManager().RegisterClient(this, userData.UserId, userData.User.Username); _habbo = userData.User; if (_habbo != null) { userData.User.Init(this, userData); SendPacket(new AuthenticationOkComposer()); SendPacket(new AvatarEffectsComposer(_habbo.Effects().GetAllEffects)); SendPacket(new NavigatorSettingsComposer(_habbo.HomeRoom)); SendPacket(new FavouritesComposer(userData.User.FavoriteRooms)); SendPacket(new FigureSetIdsComposer(_habbo.GetClothing().GetClothingParts)); SendPacket(new UserRightsComposer(_habbo.Rank)); SendPacket(new AvailabilityStatusComposer()); SendPacket(new AchievementScoreComposer(_habbo.GetStats().AchievementPoints)); SendPacket(new BuildersClubMembershipComposer()); SendPacket(new CfhTopicsInitComposer(PlusEnvironment.GetGame().GetModerationManager().UserActionPresets)); SendPacket(new BadgeDefinitionsComposer(PlusEnvironment.GetGame().GetAchievementManager().Achievements)); SendPacket(new SoundSettingsComposer(_habbo.ClientVolume, _habbo.ChatPreference, _habbo.AllowMessengerInvites, _habbo.FocusPreference, FriendBarStateUtility.GetInt(_habbo.FriendBarState))); //SendMessage(new TalentTrackLevelComposer()); if (GetHabbo().GetMessenger() != null) GetHabbo().GetMessenger().OnStatusChanged(true); if (!string.IsNullOrEmpty(MachineId)) { if (_habbo.MachineId != MachineId) { using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor()) { dbClient.SetQuery("UPDATE `users` SET `machine_id` = @MachineId WHERE `id` = @id LIMIT 1"); dbClient.AddParameter("MachineId", MachineId); dbClient.AddParameter("id", _habbo.Id); dbClient.RunQuery(); } } _habbo.MachineId = MachineId; } if (PlusEnvironment.GetGame().GetPermissionManager().TryGetGroup(_habbo.Rank, out PermissionGroup group)) { if (!string.IsNullOrEmpty(group.Badge)) if (!_habbo.GetBadgeComponent().HasBadge(group.Badge)) _habbo.GetBadgeComponent().GiveBadge(group.Badge, true, this); } if (PlusEnvironment.GetGame().GetSubscriptionManager().TryGetSubscriptionData(_habbo.VipRank, out SubscriptionData subData)) { if (!string.IsNullOrEmpty(subData.Badge)) { if (!_habbo.GetBadgeComponent().HasBadge(subData.Badge)) _habbo.GetBadgeComponent().GiveBadge(subData.Badge, true, this); } } if (!PlusEnvironment.GetGame().GetCacheManager().ContainsUser(_habbo.Id)) PlusEnvironment.GetGame().GetCacheManager().GenerateUser(_habbo.Id); _habbo.Look = PlusEnvironment.GetFigureManager().ProcessFigure(_habbo.Look, _habbo.Gender, _habbo.GetClothing().GetClothingParts, true); _habbo.InitProcess(); if (userData.User.GetPermissions().HasRight("mod_tickets")) { SendPacket(new ModeratorInitComposer( PlusEnvironment.GetGame().GetModerationManager().UserMessagePresets, PlusEnvironment.GetGame().GetModerationManager().RoomMessagePresets, PlusEnvironment.GetGame().GetModerationManager().GetTickets)); } if (PlusEnvironment.GetSettingsManager().TryGetValue("user.login.message.enabled") == "1") SendPacket(new MotdNotificationComposer(PlusEnvironment.GetLanguageManager().TryGetValue("user.login.message"))); PlusEnvironment.GetGame().GetRewardManager().CheckRewards(this); return true; } } catch (Exception e) { ExceptionLogger.LogException(e); } return false; } public void SendWhisper(string message, int colour = 0) { if (GetHabbo() == null || GetHabbo().CurrentRoom == null) return; RoomUser user = GetHabbo().CurrentRoom.GetRoomUserManager().GetRoomUserByHabbo(GetHabbo().Username); if (user == null) return; SendPacket(new WhisperComposer(user.VirtualId, message, 0, (colour == 0 ? user.LastBubble : colour))); } public void SendNotification(string message) { SendPacket(new BroadcastMessageAlertComposer(message)); } public void SendPacket(MessageComposer message) { _channel.WriteAndFlushAsync(message); } public async void SendPacketsAsync(List<MessageComposer> messages) { foreach (MessageComposer message in messages) { await _channel.WriteAsync(message); } _channel.Flush(); } public Habbo GetHabbo() { return _habbo; } public void Disconnect() { try { if (GetHabbo() != null) { using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor()) { dbClient.RunQuery(GetHabbo().GetQueryString); } GetHabbo().OnDisconnect(); } } catch (Exception e) { ExceptionLogger.LogException(e); } if (!_disconnected) { _channel?.CloseAsync(); _disconnected = true; } } public void Dispose() { if (GetHabbo() != null) GetHabbo().OnDisconnect(); MachineId = string.Empty; _disconnected = true; _habbo = null; _channel.DisconnectAsync(); } public void EnableEncryption(byte[] sharedKey) { _channel.Channel.Pipeline.AddFirst("gameCrypto", new EncryptionDecoder(sharedKey)); } } }
namespace SGDE.Domain.Supervisor { #region Using using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Converters; using Entities; using ViewModels; #endregion public partial class Supervisor { public List<RoleViewModel> GetAllRole() { return RoleConverter.ConvertList(_roleRepository.GetAll()); } public RoleViewModel GetRoleById(int id) { var roleViewModel = RoleConverter.Convert(_roleRepository.GetById(id)); return roleViewModel; } public RoleViewModel AddRole(RoleViewModel newRoleViewModel) { var role = new Role { AddedDate = DateTime.Now, ModifiedDate = null, IPAddress = newRoleViewModel.iPAddress, Name = newRoleViewModel.name }; _roleRepository.Add(role); return newRoleViewModel; } public bool UpdateRole(RoleViewModel roleViewModel) { if (roleViewModel.id == null) return false; var role = _roleRepository.GetById((int)roleViewModel.id); if (role == null) return false; role.ModifiedDate = DateTime.Now; role.IPAddress = roleViewModel.iPAddress; role.Name = roleViewModel.name; return _roleRepository.Update(role); } public bool DeleteRole(int id) { return _roleRepository.Delete(id); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace MilkBot.Points { public class PointUser { public string ID { get; set; } public int Points { get; set; } public DateTime LastMessageTime { get; set; } public XmlNode ToXml(XmlDocument document) { var user = document.CreateElement("User"); user.SetAttribute("ID", ID); user.SetAttribute("Points", Points.ToString()); user.SetAttribute("LastMessageTime", LastMessageTime.ToString()); return user; } public static PointUser FromXml(XmlNode node) => new PointUser() { ID = node.Attributes["ID"].InnerText, Points = Convert.ToInt32(node.Attributes["Points"].InnerText), LastMessageTime = DateTime.Parse(node.Attributes["LastMessageTime"].InnerText) }; } }
using CallCenter.Client.ViewModel.Helpers; using Moq; using NUnit.Framework; namespace CallCenter.Client.ViewModel.UnitTests.ViewModels { [TestFixture] public abstract class ViewModelBaseTest { protected abstract ViewModelBase ViewModelBase { get; set; } protected abstract Mock<IWindowService> WindowService { get; set; } [Test] public void AskUserTest() { this.ViewModelBase.AskUser(string.Empty, string.Empty); this.WindowService.Verify(service => service.AskUser(string.Empty, string.Empty), Times.Once); } [Test] public void CloseSuccesfulTest() { this.ViewModelBase.WindowId = 1; this.ViewModelBase.Close(); this.WindowService.Verify(service => service.Close(1), Times.Once); } [Test] public void CloseFailTest() { this.ViewModelBase.Close(); this.WindowService.Verify(service => service.Close(1), Times.Never); } [Test] public void InitTest() { this.ViewModelBase.Init(); } [Test] public void ShowTestWasNotCalled() { this.ViewModelBase.WindowId = 1; this.ViewModelBase.Show(); this.WindowService.Verify(service => service.ShowWindow(this.ViewModelBase.Type, this.ViewModelBase), Times.Never); } [Test] public void ShowTestWasCalled() { this.ViewModelBase.WindowId = 0; this.ViewModelBase.Show(); this.WindowService.Verify(service => service.ShowWindow(this.ViewModelBase.Type, this.ViewModelBase), Times.Once); } [Test] public void ShowDialogTestWasNotCalled() { this.ViewModelBase.WindowId = 1; this.ViewModelBase.ShowDialog(); this.WindowService.Verify(service => service.ShowDialogWindow(this.ViewModelBase.Type, this.ViewModelBase), Times.Never); } [Test] public void ShowDialogTestCalled() { this.ViewModelBase.WindowId = 0; this.ViewModelBase.ShowDialog(); this.WindowService.Verify(service => service.ShowDialogWindow(this.ViewModelBase.Type, this.ViewModelBase), Times.AtLeastOnce); } [Test] public void ShowMessageTest() { this.ViewModelBase.ShowMessage("", "", MessageType.Error); this.WindowService.Verify(service => service.ShowMessage("", "", MessageType.Error), Times.AtLeastOnce); } [Test] public void TestVisibFalse() { this.ViewModelBase.IsVisible = false; Assert.IsFalse(this.ViewModelBase.IsVisible); } [Test] public void TestVisibTrue() { this.ViewModelBase.IsVisible = true; Assert.IsTrue(this.ViewModelBase.IsVisible); } } }
/* * Bungie.Net API * * These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality. * * OpenAPI spec version: 2.1.1 * Contact: support@bungie.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter; namespace BungieNetPlatform.Model { /// <summary> /// This defines information that can only come from a talent grid on an item. Items mostly have negligible talent grid data these days, but instanced items still retain grids as a source for some of this common information. Builds/Subclasses are the only items left that still have talent grids with meaningful Nodes. /// </summary> [DataContract] public partial class DestinyDefinitionsDestinyItemTalentGridBlockDefinition : IEquatable<DestinyDefinitionsDestinyItemTalentGridBlockDefinition>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="DestinyDefinitionsDestinyItemTalentGridBlockDefinition" /> class. /// </summary> /// <param name="TalentGridHash">The hash identifier of the DestinyTalentGridDefinition attached to this item..</param> /// <param name="ItemDetailString">This is meant to be a subtitle for looking at the talent grid. In practice, somewhat frustratingly, this always merely says the localized word for \&quot;Details\&quot;. Great. Maybe it&#39;ll have more if talent grids ever get used for more than builds and subclasses again..</param> /// <param name="BuildName">A shortcut string identifier for the \&quot;build\&quot; in question, if this talent grid has an associated build. Doesn&#39;t map to anything we can expose at the moment..</param> /// <param name="HudDamageType">If the talent grid implies a damage type, this is the enum value for that damage type..</param> /// <param name="HudIcon">If the talent grid has a special icon that&#39;s shown in the game UI (like builds, funny that), this is the identifier for that icon. Sadly, we don&#39;t actually get that icon right now. I&#39;ll be looking to replace this with a path to the actual icon itself..</param> public DestinyDefinitionsDestinyItemTalentGridBlockDefinition(uint? TalentGridHash = default(uint?), string ItemDetailString = default(string), string BuildName = default(string), DestinyDamageType HudDamageType = default(DestinyDamageType), string HudIcon = default(string)) { this.TalentGridHash = TalentGridHash; this.ItemDetailString = ItemDetailString; this.BuildName = BuildName; this.HudDamageType = HudDamageType; this.HudIcon = HudIcon; } /// <summary> /// The hash identifier of the DestinyTalentGridDefinition attached to this item. /// </summary> /// <value>The hash identifier of the DestinyTalentGridDefinition attached to this item.</value> [DataMember(Name="talentGridHash", EmitDefaultValue=false)] public uint? TalentGridHash { get; set; } /// <summary> /// This is meant to be a subtitle for looking at the talent grid. In practice, somewhat frustratingly, this always merely says the localized word for \&quot;Details\&quot;. Great. Maybe it&#39;ll have more if talent grids ever get used for more than builds and subclasses again. /// </summary> /// <value>This is meant to be a subtitle for looking at the talent grid. In practice, somewhat frustratingly, this always merely says the localized word for \&quot;Details\&quot;. Great. Maybe it&#39;ll have more if talent grids ever get used for more than builds and subclasses again.</value> [DataMember(Name="itemDetailString", EmitDefaultValue=false)] public string ItemDetailString { get; set; } /// <summary> /// A shortcut string identifier for the \&quot;build\&quot; in question, if this talent grid has an associated build. Doesn&#39;t map to anything we can expose at the moment. /// </summary> /// <value>A shortcut string identifier for the \&quot;build\&quot; in question, if this talent grid has an associated build. Doesn&#39;t map to anything we can expose at the moment.</value> [DataMember(Name="buildName", EmitDefaultValue=false)] public string BuildName { get; set; } /// <summary> /// If the talent grid implies a damage type, this is the enum value for that damage type. /// </summary> /// <value>If the talent grid implies a damage type, this is the enum value for that damage type.</value> [DataMember(Name="hudDamageType", EmitDefaultValue=false)] public DestinyDamageType HudDamageType { get; set; } /// <summary> /// If the talent grid has a special icon that&#39;s shown in the game UI (like builds, funny that), this is the identifier for that icon. Sadly, we don&#39;t actually get that icon right now. I&#39;ll be looking to replace this with a path to the actual icon itself. /// </summary> /// <value>If the talent grid has a special icon that&#39;s shown in the game UI (like builds, funny that), this is the identifier for that icon. Sadly, we don&#39;t actually get that icon right now. I&#39;ll be looking to replace this with a path to the actual icon itself.</value> [DataMember(Name="hudIcon", EmitDefaultValue=false)] public string HudIcon { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class DestinyDefinitionsDestinyItemTalentGridBlockDefinition {\n"); sb.Append(" TalentGridHash: ").Append(TalentGridHash).Append("\n"); sb.Append(" ItemDetailString: ").Append(ItemDetailString).Append("\n"); sb.Append(" BuildName: ").Append(BuildName).Append("\n"); sb.Append(" HudDamageType: ").Append(HudDamageType).Append("\n"); sb.Append(" HudIcon: ").Append(HudIcon).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as DestinyDefinitionsDestinyItemTalentGridBlockDefinition); } /// <summary> /// Returns true if DestinyDefinitionsDestinyItemTalentGridBlockDefinition instances are equal /// </summary> /// <param name="input">Instance of DestinyDefinitionsDestinyItemTalentGridBlockDefinition to be compared</param> /// <returns>Boolean</returns> public bool Equals(DestinyDefinitionsDestinyItemTalentGridBlockDefinition input) { if (input == null) return false; return ( this.TalentGridHash == input.TalentGridHash || (this.TalentGridHash != null && this.TalentGridHash.Equals(input.TalentGridHash)) ) && ( this.ItemDetailString == input.ItemDetailString || (this.ItemDetailString != null && this.ItemDetailString.Equals(input.ItemDetailString)) ) && ( this.BuildName == input.BuildName || (this.BuildName != null && this.BuildName.Equals(input.BuildName)) ) && ( this.HudDamageType == input.HudDamageType || (this.HudDamageType != null && this.HudDamageType.Equals(input.HudDamageType)) ) && ( this.HudIcon == input.HudIcon || (this.HudIcon != null && this.HudIcon.Equals(input.HudIcon)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.TalentGridHash != null) hashCode = hashCode * 59 + this.TalentGridHash.GetHashCode(); if (this.ItemDetailString != null) hashCode = hashCode * 59 + this.ItemDetailString.GetHashCode(); if (this.BuildName != null) hashCode = hashCode * 59 + this.BuildName.GetHashCode(); if (this.HudDamageType != null) hashCode = hashCode * 59 + this.HudDamageType.GetHashCode(); if (this.HudIcon != null) hashCode = hashCode * 59 + this.HudIcon.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Calculator { class Controller { /// <summary> /// imprima un meniu /// </summary> public void PrintMenu() { Console.WriteLine("Selectati functia de rulat:"); Console.WriteLine("1.Plus1"); Console.WriteLine("2.Plus2"); Console.WriteLine("3.Plus3"); Console.WriteLine("4.Plus4"); Console.WriteLine("5.Plus5"); Console.WriteLine("Esc pentru a iesi"); } /// <summary> /// efectueaza lucrul principal cu utilizatorul /// </summary> /// <returns>returneaza false pentru a termina programul</returns> public bool Menu() { PrintMenu(); ConsoleKey ch = Console.ReadKey(true).Key; if (ch == ConsoleKey.Escape) return false; Console.Clear(); try { Console.WriteLine("Rezultatul: {0}\n\n", Switcher(ch)); } catch (ArgumentException exc) { if (exc.Message == "Intrare necorespunzatoare") Console.WriteLine("Metoda gresita de a introduce argumente\n\n"); else if (exc.Message == "Scadere") Console.WriteLine("Nu puteti introduce numere negative in aceasta functie\n\n"); else if (exc.Message == "Niciun element de meniu") Console.WriteLine("Puteti alege prin apasarea tastelor numerice\n\n"); } return true; } /// <summary> /// organizarea instructiunilor de comutare, functiile de apel Plus /// </summary> /// <param name="ch">cheie apasata de utilizator</param> /// <returns>returneaza rezultatul functiei plus</returns> public double Switcher(ConsoleKey ch) { Plus a = new Plus(); switch (ch) { case ConsoleKey.D1: case ConsoleKey.NumPad1: return a.Plus1(ReadArguments()); case ConsoleKey.D2: case ConsoleKey.NumPad2: return a.Plus2(ReadArguments()); case ConsoleKey.D3: case ConsoleKey.NumPad3: return a.Plus3(ReadArguments()); case ConsoleKey.D4: case ConsoleKey.NumPad4: return a.Plus4(ReadArguments()); case ConsoleKey.D5: case ConsoleKey.NumPad5: return a.Plus5(ReadArguments()); default: throw new ArgumentException("niciun element de meniu"); } } /// <summary> /// interogari si citeste sirul de argumente pentru functia Plus /// </summary> /// <returns></returns> public string ReadArguments() { Console.WriteLine("Introduceti un sir de argumente: "); return Console.ReadLine(); } } }
using System.Collections; using UnityEngine; using UnityEngine.Networking; public class Fire : NetworkBehaviour { void Start() { if (isServer) StartFire(); } [Server] void StartFire() { StopAllCoroutines(); StartCoroutine(Remove()); } [Server] void Remove(Collider2D entity) { NetworkServer.UnSpawn(entity.gameObject); Destroy(entity.gameObject); } [Server] public IEnumerator Remove() { yield return new WaitForSeconds(1f); Destroy(gameObject); NetworkServer.UnSpawn(gameObject); } public void OnTriggerEnter2D(Collider2D entity) { if (!isServer) return; if (entity.gameObject.GetComponent<Fire>()) return; var bomb = entity.gameObject.GetComponent<Bomb>(); if (bomb != null) bomb.Explode(); var box = entity.gameObject.GetComponent<PowerUpSpawner>(); if (box != null) { GetComponent<CircleCollider2D>().enabled = false; box.SpawnPowerUp(); } Remove(entity); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PrototypePattern { public class Prototype : IPrototype { public string Identifier { get; set; } public IPrototype Clone() { return (IPrototype)MemberwiseClone(); } } }
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace MonoGame.Extended.NuclexGui.Visuals.Flat { public partial class FlatGuiGraphics { /// <summary>Sets the clipping region for any future drawing commands</summary> /// <param name="clipRegion">Clipping region that will be set</param> /// <returns> /// An object that will unset the clipping region upon its destruction. /// </returns> /// <remarks> /// Clipping regions can be stacked, though this is not very typical for /// a game GUI and also not recommended practice due to performance constraints. /// Unless clipping is implemented in software, setting up a clip region /// on current hardware requires the drawing queue to be flushed, negatively /// impacting rendering performance (in technical terms, a clipping region /// change likely causes 2 more DrawPrimitive() calls from the painter). /// </remarks> public IDisposable SetClipRegion(RectangleF clipRegion) { // Cache the integer values of the clipping region's boundaries var clipX = (int) clipRegion.X; var clipY = (int) clipRegion.Y; var clipRight = clipX + (int) clipRegion.Width; var clipBottom = clipY + (int) clipRegion.Height; // Calculate the viewport's right and bottom coordinates var viewport = _spriteBatch.GraphicsDevice.Viewport; var viewportRight = viewport.X + viewport.Width; var viewportBottom = viewport.Y + viewport.Height; // Extract the part of the clipping region that lies within the viewport var scissorRegion = new Rectangle( Math.Max(clipX, viewport.X), Math.Max(clipY, viewport.Y), Math.Min(clipRight, viewportRight) - clipX, Math.Min(clipBottom, viewportBottom) - clipY ); scissorRegion.Width += clipX - scissorRegion.X; scissorRegion.Height += clipY - scissorRegion.Y; // If the clipping region was entirely outside of the viewport (meaning // the calculated width and/or height are negative), use an empty scissor // rectangle instead because XNA doesn't like scissor rectangles with // negative coordinates. if ((scissorRegion.Width <= 0) || (scissorRegion.Height <= 0)) scissorRegion = Rectangle.Empty; // All done, take over the new scissor rectangle _scissorManager.Assign(ref scissorRegion); return _scissorManager; } /// <summary>Draws a GUI element onto the drawing buffer</summary> /// <param name="frameName">Class of the element to draw</param> /// <param name="bounds">Region that will be covered by the drawn element</param> /// <remarks> /// <para> /// GUI elements are the basic building blocks of a GUI: /// </para> /// </remarks> public void DrawElement(string frameName, RectangleF bounds) { var frame = LookupFrame(frameName); // Draw all the regions defined for the element. Each region is a small bitmap // that needs to be blit somewhere into the element to form the element's // visual representation step by step. for (var index = 0; index < frame.Regions.Length; ++index) { var destinationRegion = CalculateDestinationRectangle(ref bounds, ref frame.Regions[index].DestinationRegion); _spriteBatch.Draw(frame.Regions[index].Texture, destinationRegion, frame.Regions[index].SourceRegion, Color.White); } } /// <summary>Draws text into the drawing buffer for the specified element</summary> /// <param name="frameName">Class of the element for which to draw text</param> /// <param name="bounds">Region that will be covered by the drawn element</param> /// <param name="text">Text that will be drawn</param> public void DrawString(string frameName, RectangleF bounds, string text) { var frame = LookupFrame(frameName); // Draw the text in all anchor locations defined by the skin for (var index = 0; index < frame.Texts.Length; ++index) { _spriteBatch.DrawString(frame.Texts[index].Font, text, PositionText(ref frame.Texts[index], bounds, text), frame.Texts[index].Color); } } public void DrawImage(RectangleF bounds, Texture2D texture, Rectangle sourceRectangle) { var destinationRectangle = new Rectangle(); if (bounds.Width > bounds.Height) { destinationRectangle.Height = Convert.ToInt32(Math.Round(bounds.Height * 0.8)); destinationRectangle.Width = Convert.ToInt32(Math.Round(bounds.Width * 0.8 * (bounds.Height / sourceRectangle.Height))); destinationRectangle.X = Convert.ToInt32(Math.Round(bounds.Center.X)) - destinationRectangle.Width / 2; destinationRectangle.Y = Convert.ToInt32(Math.Round(bounds.Center.Y)) - destinationRectangle.Height / 2; } else { destinationRectangle.Width = Convert.ToInt32(Math.Round(bounds.Width * 0.8)); destinationRectangle.Height = Convert.ToInt32(Math.Round(bounds.Height * 0.8 * (bounds.Width / sourceRectangle.Width))); destinationRectangle.X = Convert.ToInt32(Math.Round(bounds.Center.X)) - destinationRectangle.Width / 2; destinationRectangle.Y = Convert.ToInt32(Math.Round(bounds.Center.Y)) - destinationRectangle.Height / 2; } _spriteBatch.Draw(texture, destinationRectangle, sourceRectangle, Color.White); } /// <summary>Draws a caret for text input at the specified index</summary> /// <param name="frameName">Class of the element for which to draw a caret</param> /// <param name="bounds">Region that will be covered by the drawn element</param> /// <param name="text">Text for which a caret will be drawn</param> /// <param name="caretIndex">Index the caret will be drawn at</param> public void DrawCaret(string frameName, RectangleF bounds, string text, int caretIndex) { var frame = LookupFrame(frameName); _stringBuilder.Remove(0, _stringBuilder.Length); _stringBuilder.Append(text, 0, caretIndex); Vector2 caretPosition, textPosition; for (var index = 0; index < frame.Texts.Length; ++index) { textPosition = PositionText(ref frame.Texts[index], bounds, text); caretPosition = frame.Texts[index].Font.MeasureString(_stringBuilder); caretPosition.X -= _caretWidth; caretPosition.Y = 0.0f; _spriteBatch.DrawString(frame.Texts[index].Font, "|", textPosition + caretPosition, frame.Texts[index].Color); } } /// <summary>Measures the extents of a string in the frame's area</summary> /// <param name="frameName">Class of the element whose text will be measured</param> /// <param name="bounds">Region that will be covered by the drawn element</param> /// <param name="text">Text that will be measured</param> /// <returns> /// The size and extents of the specified string within the frame /// </returns> public RectangleF MeasureString(string frameName, RectangleF bounds, string text) { var frame = LookupFrame(frameName); Vector2 size; if (frame.Texts.Length > 0) size = frame.Texts[0].Font.MeasureString(text); else size = Vector2.Zero; return new RectangleF(0.0f, 0.0f, size.X, size.Y); } /// <summary> /// Locates the closest gap between two letters to the provided position /// </summary> /// <param name="frameName">Class of the element in which to find the gap</param> /// <param name="bounds">Region that will be covered by the drawn element</param> /// <param name="text">Text in which the closest gap will be found</param> /// <param name="position">Position of which to determien the closest gap</param> /// <returns>The index of the gap the position is closest to</returns> public int GetClosestOpening( string frameName, RectangleF bounds, string text, Vector2 position ) { var frame = LookupFrame(frameName); // Frames can repeat their text in several places. Though this is probably // not used very often (if at all), it should work here consistently. var closestGap = -1; for (var index = 0; index < frame.Texts.Length; ++index) { var textPosition = PositionText(ref frame.Texts[index], bounds, text); position.X -= textPosition.X; position.Y -= textPosition.Y; var openingX = position.X; var openingIndex = _openingLocator.FindClosestOpening( frame.Texts[index].Font, text, position.X + _caretWidth ); closestGap = openingIndex; } return closestGap; } /// <summary>Needs to be called before the GUI drawing process begins</summary> public void BeginDrawing() { var graphics = _spriteBatch.GraphicsDevice; var viewport = graphics.Viewport; graphics.ScissorRectangle = new Rectangle(0, 0, viewport.Width, viewport.Height); // On Windows Phone 7, if only the GUI is rendered (no other SpriteBatches) // and the initial spriteBatch.Begin() includes the scissor rectangle, // nothing will be drawn at all, so we don't use beginSpriteBatch() here // and instead call SpriteBatch.Begin() ourselves. Care has to be taken // if something ever gets added to the beginSpriteBatch() method. _spriteBatch.Begin(); } /// <summary>Needs to be called when the GUI drawing process has ended</summary> public void EndDrawing() { EndSpriteBatch(); } /// <summary>Starts drawing on the sprite batch</summary> private void BeginSpriteBatch() { _spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, _rasterizerState); } /// <summary>Stops drawing on the sprite batch</summary> private void EndSpriteBatch() { _spriteBatch.End(); } } }
using System.Collections.Generic; using System.ComponentModel; namespace Hsp.Mvvm { public static class Extensions { public static void AddRange<T>(this IList<T> coll, IEnumerable<T> items) { foreach (var item in items) coll.Add(item); } public static void AddRange<T>(this IList<T> coll, params T[] items) { foreach (var item in items) coll.Add(item); } public static object GetOldValue(this PropertyChangedEventArgs e) { return (e as ValuedPropertyChangedEventArgs)?.OldValue; } public static object GetNewValue(this PropertyChangedEventArgs e) { return (e as ValuedPropertyChangedEventArgs)?.NewValue; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; using System.Reflection; namespace transGraph { public partial class Routes : Form { dbFacade db = new dbFacade(); System.Windows.Forms.Timer time = new System.Windows.Forms.Timer(); Thread t; Global g; public int countRoutes = 0; bool loaded = false; public Routes(Global g) { this.g = g; InitializeComponent(); SetDoubleBuffered(dataG, true); loadit(); } void SetDoubleBuffered(Control c, bool value) { PropertyInfo pi = typeof(Control).GetProperty("DoubleBuffered", BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic); if (pi != null) { pi.SetValue(c, value, null); } } private void InitializeMyTimer() { time.Interval = 1; time.Tick += new EventHandler(IncreaseProgressBar); time.Start(); } private void IncreaseProgressBar(object sender, EventArgs e) { try { toolStripProgressBar1.Maximum = countRoutes; toolStripProgressBar1.Value = dataG.RowCount; if (loaded) { toolStripProgressBar1.Value = toolStripProgressBar1.Maximum; time.Stop(); } } catch (Exception) { } } public void loadThread() { loaded = false; try { dataG.Invoke(new MethodInvoker(delegate() { dataG.Rows.Clear(); })); } catch (Exception) { } DataTable data = db.FetchAllSql("SELECT id,ways,wayid,km,note FROM routes"); foreach (DataRow rr in data.Rows) { string ways = Convert.ToString(rr[1]); string waysT = ""; foreach (string id in ways.Split(';')) { try { DataTable dataB = db.FetchAllSql("SELECT title FROM citys WHERE id = '" + id + "'"); waysT += dataB.Rows[0][0].ToString() + " "; } catch (Exception) { } } string wayid = Convert.ToString(rr[2]); string wayidT = ""; try { DataTable dataB = db.FetchAllSql("SELECT title FROM ways WHERE id = '" + wayid + "'"); wayidT = dataB.Rows[0][0].ToString() + " "; } catch (Exception) { } try { dataG.Invoke(new MethodInvoker(delegate() { dataG.Rows.Add(rr[0], waysT, wayidT, rr[3], rr[4]); })); } catch (Exception) { } } loaded = true; } public void loadit() { DataTable data = db.FetchAllSql("SELECT COUNT(*) FROM routes"); countRoutes = Convert.ToInt32(data.Rows[0][0]); InitializeMyTimer(); t = new Thread(new ThreadStart(loadThread)); t.Start(); } private void toolStripButton1_Click(object sender, EventArgs e) { addRoute mt = new addRoute(); mt.ShowDialog(); loadit(); } private void toolStripButton2_Click(object sender, EventArgs e) { DialogResult dialogResult = MessageBox.Show("Вы действительно хотите удалить эту запись?", "Внимание!", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { string id = ""; try { id = dataG[0, dataG.SelectedRows[0].Index].Value.ToString(); } catch (Exception) { } if (id != "") { try { db.FetchAllSql("DELETE FROM routes WHERE id = '" + id + "'"); } catch (Exception) { } } loadit(); } } private void dataG_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) { string id = ""; try { id = dataG[0, dataG.SelectedRows[0].Index].Value.ToString(); } catch (Exception) { } if (id != "") { editRoute mt = new editRoute(id); mt.ShowDialog(); loadit(); } } private void Routes_FormClosing(object sender, FormClosingEventArgs e) { this.t.Abort(); this.time.Stop(); this.time.Dispose(); this.g.Routes = false; } void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.RowIndex == -1 && e.ColumnIndex >= 0) { e.PaintBackground(e.ClipBounds, true); Rectangle rect = this.dataG.GetColumnDisplayRectangle(e.ColumnIndex, true); Size titleSize = TextRenderer.MeasureText(e.Value.ToString(), e.CellStyle.Font); if (this.dataG.ColumnHeadersHeight < titleSize.Width) this.dataG.ColumnHeadersHeight = titleSize.Width; e.Graphics.TranslateTransform(0, titleSize.Width); e.Graphics.RotateTransform(-90.0F); e.Graphics.DrawString(e.Value.ToString(), this.Font, Brushes.Black, new PointF(rect.Y, rect.X)); e.Graphics.RotateTransform(90.0F); e.Graphics.TranslateTransform(0, -titleSize.Width); e.Handled = true; } } private void toolStripTextBox1_TextChanged(object sender, EventArgs e) { if (this.toolStripTextBox1.Text == "") { for (int i = 0; i < this.dataG.RowCount; i++) this.dataG.Rows[i].Visible = true; return; } for (int i = 0; i < this.dataG.RowCount; i++) this.dataG.Rows[i].Visible = false; string[] search = this.toolStripTextBox1.Text.Split(' '); foreach (string ss in search) { if (ss != "") for (int i = 0; i < this.dataG.RowCount; i++) { if (dataG[0, i].Value.ToString().IndexOf(ss) != -1) this.dataG.Rows[i].Visible = true; if (dataG[1, i].Value.ToString().IndexOf(ss) != -1) this.dataG.Rows[i].Visible = true; if (dataG[2, i].Value.ToString().IndexOf(ss) != -1) this.dataG.Rows[i].Visible = true; if (dataG[3, i].Value.ToString().IndexOf(ss) != -1) this.dataG.Rows[i].Visible = true; if (dataG[4, i].Value.ToString().IndexOf(ss) != -1) this.dataG.Rows[i].Visible = true; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Exam_Online.Models.IndexModel { public class QuestionModel { public int TotalQuestionInset { get; set; } public int QuestionNumber { get; set; } public int TestId { get; set; } public string TestName { get; set; } public string Question { get; set; } public string QuestionType { get; set; } public decimal Point { get; set; } public Guid Token { get; set; } public List<QXModel> Options { get; set; } } public class QXModel { public int ChoiceId { get; set; } public string Label { get; set; } public string Answer { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public class Card : NetworkBehaviour { [ContextMenuItem("Card Action","CardAction")] public string Name; [Range(1,3)] public int Age = 1; public int NumberOfPlayersInGame = 2; public enum CardStatus { InBox = 0, Draft = 1, NextDraft = 2, Consider = 3, Hand = 4, Played = 5, Discarded = 6 } [SyncVar] public CardStatus Status = 0; public ClanSheet CardOwner; public void SetCardStatus() { ClanSheet clanSheet = GetComponentInParent<ClanSheet>(); AgeTrack ageTrack = GetComponentInParent<AgeTrack>(); if (clanSheet != null) { CardOwner = clanSheet; if (clanSheet.Draft.Cards.Contains(this)) { Status = CardStatus.Draft; return; } if(clanSheet.NextDraft.Cards.Contains(this)) { Status = CardStatus.NextDraft; return; } if(clanSheet.ConsiderCards.Cards.Contains(this)) { Status = CardStatus.Consider; return; } if (clanSheet.Hand.Cards.Contains(this)) { Status = CardStatus.Hand; return; } foreach(UpgradeSlot leaderUpgradeslot in clanSheet.LeaderUpgrades ) { if(leaderUpgradeslot.Upgrade == this) { Status = CardStatus.Played; return; } } foreach (UpgradeSlot warriorUpgradeslot in clanSheet.WarriorUpgrades) { if (warriorUpgradeslot.Upgrade == this) { Status = CardStatus.Played; return; } } foreach (UpgradeSlot clanUpgradeslot in clanSheet.ClanUpgrades) { if (clanUpgradeslot.Upgrade == this) { Status = CardStatus.Played; return; } } foreach (UpgradeSlot monsterUpgradeslot in clanSheet.MonsterUpgrades) { if (monsterUpgradeslot.Upgrade == this) { Status = CardStatus.Played; return; } } foreach (UpgradeSlot shipUpgradeslot in clanSheet.ShipUpgrades) { if (shipUpgradeslot.Upgrade == this) { Status = CardStatus.Played; return; } } } else { CardOwner = null; if (ageTrack.Ages[Age-1].Cards.Contains(this)) { Status = CardStatus.Discarded; return; } } } public void MoveCard(List<Card> removeFrom, List<Card> addTo, Transform parent) { removeFrom.Remove(this); addTo.Add(this); transform.SetParent(parent); SetCardStatus(); } public void MoveCard(List<Card> removeFromList, CardsSlot addTo) { removeFromList.Remove(this); addTo.Cards.Add(this); transform.SetParent(addTo.CardsParent.transform); SetCardStatus(); } public void MoveCard(CardsSlot removeFrom, CardsSlot addTo) { removeFrom.Cards.Remove(this); addTo.Cards.Add(this); transform.SetParent(addTo.CardsParent.transform); SetCardStatus(); } //public void CardAction() //{ // if (CardOwner != null) // { // if (Status == CardStatus.Draft) // { // CardOwner.ConsiderCard(this); // return; // } // if(Status == CardStatus.Consider) // { // CardOwner.ReturnConsideredCard(this); // } // } //} [ClientRpc] public void RpcInstantiateCard() { Status = CardStatus.InBox; gameObject.name = (Age + "_" + Name); AgeTrack.instance.Ages[Age - 1].Cards.Add(this); transform.SetParent(AgeTrack.instance.Ages[Age-1].CardsParent.transform); } }
using System; using System.Collections.Generic; using System.Data; using oAuthTwitterWrapper; using TwitterManager.Models; namespace TwitterManager.Helper { public class DataContext { public static void InsertTwitterItems(List<TwitterItem> items) { DataHelper.InsertTwitterItems(items); } public static void InsertRowsUpdateLog(string hostName, int numofrowes, int oauth) { DataHelper.InsertRowsUpdateLog(hostName, numofrowes, oauth); } public static string GetMinMessageIdForUser(string screenName) { DataTable table = DataHelper.GetMinMessageIdForUser(screenName); string min = table.Rows.Count > 0 ? table.Rows[0].Field<string>("minId") : ""; return min; } public static string GetMaxMessageIdForUser(string screenName) { DataTable table = DataHelper.GetMaxMessageIdForUser(screenName); string max = table.Rows.Count > 0 ? table.Rows[0].Field<string>("maxId") : ""; return max; } public static int GetMaxRunID() { DataTable table = DataHelper.GetMaxRunID(); int max = table.Rows.Count > 0 ? table.Rows[0].Field<int>("RunId") : 0; return max; } public static void UpdateScreenNames_LastUpdated(string screenName) { DataHelper.UpdateScreenNames_LastUpdated(screenName); } public static void UpdateScreenNames_Deactivate(string screenName) { DataHelper.UpdateScreenNames_Deactivate(screenName); } public static void UpdateQueriesTracking(string screenName, string massage, int runId, int rowesCount) { DataHelper.UpdateQueriesTracking(screenName, massage, Environment.MachineName, runId, rowesCount); } public static OAuthData GetoAuthData() { DataTable table = DataHelper.GetoAuthData(Environment.MachineName); OAuthData data = new OAuthData(); foreach (DataRow row in table.Rows) { data.OAuthConsumerKey = row.Field<string>("ConsumerKey"); data.OAuthConsumerSecret = row.Field<string>("ConsumerSecret"); } return data; } public static List<ScreenNameToLoad> GetScreenNames() { DataTable table = DataHelper.GetScreenNames(); List<ScreenNameToLoad> names = new List<ScreenNameToLoad>(); foreach (DataRow row in table.Rows) { ScreenNameToLoad name = new ScreenNameToLoad { ScreenName = row.Field<string>("screenname"), IsFirstTime = row.Field<int>("count") > 0 ? false : true }; names.Add(name); } return names; } } }
using UnityEngine; using System; using System.Collections; public class PlayerFallState : PlayerState { public PlayerFallState( PlayerStateMachine stateMachine, PlayerCharacter character, PlayerController controller ) : base( stateMachine, character, controller ) { } public override void OnEnterState() { Debug.Log("Player Fall On Enter"); } public override void OnUpdate() { // Check for ground controller.ApplyGravity(); } public override void OnExitState() { Debug.Log("Player Fall On Exit"); } public override void HandleControllerEvent( string eventID ) { Debug.Log("EventID: " + eventID); if( eventID == PlayerControllerEvents.ENTER_GROUND ) stateMachine.CurrentState = PlayerStateType.IDLE; } }
using System; using System.Collections.Generic; using System.Text; namespace Eventual.EventStore.Core { public class EventStreamCommit { #region Attributes private Guid aggregateId; private Type aggregateType; private int workingCopyVersion; private string correlationId; private string causationId; private string metadataContentType; private string metadataContentEncoding; private byte[] metadata; private string changesContentType; private string changesContentEncoding; private byte[] changes; #endregion #region Constructors public EventStreamCommit(Guid aggregateId, Type aggregateType, int workingCopyVersion, string correlationId, string causationId, string metadataContentType, string metadataContentEncoding, byte[] metadata, string changesContentType, string changesContentEncoding, byte[] changes) { this.AggregateId = aggregateId; this.AggregateType = aggregateType; this.WorkingCopyVersion = workingCopyVersion; this.CorrelationId = correlationId; this.CausationId = causationId; this.MetadataContentType = metadataContentType; this.MetadataContentEncoding = metadataContentEncoding; this.Metadata = metadata; this.ChangesContentType = changesContentType; this.ChangesContentEncoding = changesContentEncoding; this.Changes = changes; } #endregion #region Properties public Guid AggregateId { get { return this.aggregateId; } private set { //TODO: Add validation code this.aggregateId = value; } } public Type AggregateType { get { return this.aggregateType; } private set { //TODO: Add validation code this.aggregateType = value; } } //TODO: Add here new property "AggregateState" for supporting snapshots (but maybe it should be treated from the upper layer -repository-, since it must be parsed and deserialized to the current aggregate specific schema). public int WorkingCopyVersion { get { return this.workingCopyVersion; } private set { //TODO: Add validation code this.workingCopyVersion = value; } } public string CorrelationId { get { return this.correlationId; } private set { //TODO: Add validation code this.correlationId = value; } } public string CausationId { get { return this.causationId; } private set { //TODO: Add validation code this.causationId = value; } } public string MetadataContentType { get { return this.metadataContentType; } private set { //TODO: Add validation code this.metadataContentType = value; } } public string MetadataContentEncoding { get { return this.metadataContentEncoding; } private set { //TODO: Add validation code this.metadataContentEncoding = value; } } public byte[] Metadata { get { return this.metadata; } private set { //TODO: Add validation code this.metadata = value; } } public string ChangesContentType { get { return this.changesContentType; } private set { //TODO: Add validation code this.changesContentType = value; } } public string ChangesContentEncoding { get { return this.changesContentEncoding; } private set { //TODO: Add validation code this.changesContentEncoding = value; } } public byte[] Changes { get { return this.changes; } private set { //TODO: Add validation code this.changes = value; } } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace practica_final { public partial class vProcCompra : Form { public vProcCompra(PictureBox pict,string sala, string precio, int disponibles, frmentrada frm) { InitializeComponent(); pictureBox9.Image = pict.Image; txtSala.Text = sala; txtprecio2.Text = precio; v = frm; } private void txtprecio_Click(object sender, EventArgs e) { } private void pictureBox10_Click(object sender, EventArgs e) { this.Close(); } private void textBox1_TextChanged(object sender, EventArgs e) { int cantidad = (string.IsNullOrWhiteSpace(textBox1.Text) ? 1 : int.Parse(textBox1.Text)); float precio = float.Parse(txtprecio2.Text); txttotal.Text = (cantidad * precio).ToString(); if (cantidad > 1 && cantidad < 3) txtdescuento.Text = (float.Parse(txttotal.Text) * 0.15).ToString(); } private void vProcCompra_Load(object sender, EventArgs e) { var valor = int.Parse(textBox1.Text) * int.Parse(txtprecio2.Text); txttotal.Text = valor.ToString(); } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (!(char.IsNumber(e.KeyChar)) && (e.KeyChar != (char)Keys.Back)) { MessageBox.Show("Solo se permiten numeros", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); e.Handled = true; return; } } private void button1_Click(object sender, EventArgs e) { DialogResult eleccion = MessageBox.Show("Quiere realizar el pago?", "Finalizando!", MessageBoxButtons.YesNo); if(eleccion == DialogResult.Yes) { this.Close(); v.nuevoDisponibles = int.Parse(textBox1.Text); } } frmentrada v; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; namespace qmaster { public partial class staff_reg : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=qus;User ID=sa;Password=admin123"); con.Open(); string com = "Select dept_name,dept_id from tbl_dept"; SqlDataAdapter adpt = new SqlDataAdapter(com, con); DataTable dt = new DataTable(); adpt.Fill(dt); ddldept.DataSource = dt; ddldept.DataBind(); ddldept.DataTextField = "dept_name"; ddldept.DataValueField = "dept_name"; ddldept.DataBind(); con.Close(); } } protected void Button1_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=qus;User ID=sa;Password=admin123"); con.Open(); string sql = "insert into tbl_staff (staff_id,staff_name,dept_id,username,password,type) values('" + txtid.Text.Trim() + "','" + txtname.Text.Trim() + "','" + ddldept.SelectedItem.Value + "','" + txtusername.Text.Trim() + "','" + txtpassword.Text.Trim() + "','" + ddlType.SelectedItem.Value + "')"; SqlCommand cmd = new SqlCommand(sql, con); cmd.ExecuteNonQuery(); txtid.Text = String.Empty; txtname.Text = String.Empty; txtusername.Text = String.Empty; txtpassword.Text = String.Empty; } protected void Button2_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=qus;User ID=sa;Password=admin123"); con.Open(); string com = "SELECT staff_id,staff_name,username,dept_id from tbl_staff where type = 'STAFF'"; SqlDataAdapter adpt = new SqlDataAdapter(com, con); DataTable dt = new DataTable(); adpt.Fill(dt); gvstaff.DataSource = dt; gvstaff.DataBind(); // this.Button2.Visible = true; con.Close(); } protected void Button3_Click(object sender, EventArgs e) { Session.Abandon(); Session.Clear(); Response.Redirect("admin_home.aspx"); } } }
using System.Xml.Linq; using PlatformRacing3.Common.User; using PlatformRacing3.Web.Extensions; using PlatformRacing3.Web.Responses; using PlatformRacing3.Web.Responses.Procedures; namespace PlatformRacing3.Web.Controllers.DataAccess2.Procedures; public class CountMyIgnoredProcedure : IProcedure { public async Task<IDataAccessDataResponse> GetResponseAsync(HttpContext httpContext, XDocument xml) { uint userId = httpContext.IsAuthenicatedPr3User(); if (userId > 0) { uint count = await UserManager.CountMyIgnoredAsync(userId); return new DataAccessCountMyIgnoredProcedureResponse(count); } else { return new DataAccessErrorResponse("You are not logged in!"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; namespace Infnet.EngSoft.SistemaBancario.Modelo.Repositorios { public class RepositorioDeClientes { SqlConnection connection = null; List<Cliente> clientes = null; public RepositorioDeClientes(SqlConnection connection) { this.connection = connection; } } }
using BasesDatos.Modulo_SQL; using System; using System.Runtime.InteropServices; using System.Windows.Forms; namespace BasesDatos { /// <summary> /// Clase para el form principal donde se cargara toda la informacion /// </summary> public partial class Form1 : Form { /// <summary> /// Nombre del archivo /// </summary> public string nombre_archivo; /// <summary> ///Archivo para poder guardar la informacion /// </summary> public Archivo arc; /// <summary> /// Base de datos en la que se esyta trabajando /// </summary> public BaseDatos BaseDatos; /// <summary> /// FOrmulario para hacer consultas sql /// </summary> private SQL_formulario sql; public Form1() { InitializeComponent(); arc = new Archivo(); } /// <summary> /// Importacion de elementos para poder serializar con JSON /// </summary> [DllImport("user32.DLL", EntryPoint = "ReleaseCapture")] private extern static void ReleaseCapture(); [DllImport("user32.DLL", EntryPoint = "SendMessage")] private extern static void SendMessage(System.IntPtr hwnd, int msg, int wparam, int lparam); /// <summary> /// Evento para cerrar la ventana principal y todos los forms /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void iconClose_Click(object sender, EventArgs e) { if (arc != null) { arc.CierraArchivo(); } arc = null; if (this.PanelCentral.Controls.Count > 0) this.PanelCentral.Controls.RemoveAt(0); Application.Exit(); } /// <summary> /// Evento para mover y hacer mas grade el campo de vision /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void iconButton2_Click(object sender, EventArgs e) { if (PanelMenuVertical.Width == 250) { PanelMenuVertical.Width = 90; } else { PanelMenuVertical.Width = 250; } } /// <summary> /// Evento del Icono para hacer mas chica la ventana /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void iconButton3_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Normal; iconMaximize.Visible = true; iconRestore.Visible = false; } /// <summary> /// Eveno del icono para hacer mas grande la ventana /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void iconButton1_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Maximized; iconMaximize.Visible = false; iconRestore.Visible = true; } /// <summary> /// Evento para minimizar la ventana /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void iconMinimize_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; } private void menuStrip1_MouseDown(object sender, MouseEventArgs e) { ReleaseCapture(); SendMessage(this.Handle, 0x112, 0xf012, 0); } /// <summary> /// Funcion para abrir un Form y que lo herede el Form principal /// </summary> /// <param name="FormHijo">Form a crear y heredar al Form1 </param> private void AbrirFormInPanel(object FormHijo) { if (this.PanelCentral.Controls.Count > 0) this.PanelCentral.Controls.RemoveAt(0); Form form = FormHijo as Form; form.TopLevel = false; form.Dock = DockStyle.Fill; this.PanelCentral.Controls.Add(form); this.PanelCentral.Tag = form; form.Show(); } /// <summary> /// Evento que abre una base de datos y crea su instancia correspondiente /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void abrirToolStripMenuItem_Click(object sender, EventArgs e) { arc = new Archivo(); // si se pudo abrir el archivo if (arc.AbrirBase()) { BaseDatos = arc.BaseD; FormEntidades formEntidades = new FormEntidades(); formEntidades.Archivo = arc; formEntidades.baseActual = arc.BaseD; AbrirFormInPanel(formEntidades); if (sql != null) sql.actualiza_bd(BaseDatos); } } /// <summary> /// Evento que crea una nueva instancia y captura el nombre de una base de datos /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void nuevoToolStripMenuItem_Click(object sender, EventArgs e) { if (arc.SaveD.ShowDialog() == DialogResult.OK) { nombre_archivo = arc.SaveD.FileName; arc.nombre_archivo = nombre_archivo; arc.CreaArchivo(nombre_archivo, 0); BaseDatos = arc.BaseD; FormEntidades formEntidades = new FormEntidades(); formEntidades.Archivo = arc; formEntidades.baseActual = BaseDatos; AbrirFormInPanel(formEntidades); } } private void guardarToolStripMenuItem_Click_1(object sender, EventArgs e) { } /// <summary> /// Evento que cierra un archivo de base de datos completamente /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void cerrarToolStripMenuItem1_Click(object sender, EventArgs e) { arc.CierraArchivo(); arc = new Archivo(); if (this.PanelCentral.Controls.Count > 0) this.PanelCentral.Controls.RemoveAt(0); MessageBox.Show("Cerrar ventana"); } /// <summary> /// Evento que abre el Form para realizar consultas con la base de datos actual /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Abre_modulo_sql(object sender, EventArgs e) { sql = new SQL_formulario(this.BaseDatos); sql.Show(); } /// <summary> /// Evento para llenar un textbox para cambiar el nombre de una base de datos /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void cambiarNombreToolStripMenuItem_Click(object sender, EventArgs e) { if (toolStripTextBox1.Text != "") { BaseDatos._NombreBD = toolStripTextBox1.Text; } } /// <summary> /// Evento que elimina la base de datos actual /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void eliminarToolStripMenuItem_Click(object sender, EventArgs e) { arc.EliminarBase(BaseDatos); arc.CierraArchivo(); arc = null; if (this.PanelCentral.Controls.Count > 0) this.PanelCentral.Controls.RemoveAt(0); MessageBox.Show("La base de datos actual ha sido eliminada"); } private void toolStripTextBox1_TextChanged(object sender, EventArgs e) { } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void toolStripTextBox1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) if (toolStripTextBox1.Text != "") { BaseDatos._NombreBD = toolStripTextBox1.Text; arc.CreaArchivo(BaseDatos._NombreBD, 0); MessageBox.Show(toolStripTextBox1.Text); //BaseDatos._NombreBD = toolStripTextBox1.Text; toolStripTextBox1.Text = ""; } } } }
using System; namespace CloneDeploy_Entities.DTOs { public class CustomApiCallDTO { public Uri BaseUrl { get; set; } public string Token { get; set; } } }
namespace Apresentacao { public enum AcaoNaTela //uma classe do tipo enum(enumerador), é usado amplamente para informações fixas(masculino, feminino) { Excluir = 0, Inserir = 1, Alterar = 2, Consultar = 3 } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using KT.DTOs.Objects; namespace KnowledgeTester.Models { public class AnswerModel { public bool IsCorrect { get; set; } public string Text { get; set; } public Guid Id { get; set; } public AnswerModel(AnswerDto ans) { IsCorrect = ans.IsCorrect; Text = ans.Text; Id = ans.Id; } public AnswerModel() { } } }
namespace UI.Templates { using System.Threading.Tasks; using Zebble; public class Blank : Page { public ScrollView BodyScroller = new ScrollView().Height(100.Percent()).Padding(20); public Stack Body; public override async Task OnInitializing() { this.Height.BindTo(View.Root.Height); await base.OnInitializing(); await Add(BodyScroller); await BodyScroller.Add(Body = new Stack()); } public string Title { get { return string.Empty; } set { } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace D_API.Enums { public static class AuthorizationRoles { public const string Root = "root"; public const string AppDataHost = "root,adh"; } public static class UserAccessRoles { public const string Root = "root"; public const string AppDataHost = "adh"; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RigidbodyTest : MonoBehaviour { private Rigidbody2D rb; // Use this for initialization void Start () { rb = GetComponent<Rigidbody2D>(); } // Update is called once per frame void Update () { } void FixedUpdate(){ /* //Solo para dinámicos... Vector2 force = new Vector2(2,-3); ForceMode2D mode = ForceMode2D.Force; rb.AddForce(force, mode); Vector2 pos = new Vector2(0,0); rb.AddForceAtPosition(force, pos, mode); rb.AddRelativeForce(force, mode); float torque = 5.0f; rb.AddTorque(torque, mode); //Solo para cinemáticos Vector2 finalPos = new Vector(50, 32); rb.MovePosition(finalPos); float angle = 30; rb.MoveRotation(angle); // S = V * t // x1 = x0 + V * t rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime); rb.IsAwake(); //true si el rigidbody está despierto, y falso si está dormido rb.IsSleeping(); //true si el rigidbody duerme y falso si está despierto rb.IsTouching(Collider2D otherCollider); //devuelve true si mi rigidbody está colisionando con el otro collider rb.OverlapPoint(Vector2 point); // devuelve true si el punto se encuentra dentro del rigidbody rb.Sleep();//pone el rigidbody a dormir rb.WakeUp();//despierta el rigidbody */ } }
using System.Collections.Generic; using System.Threading.Tasks; using Fluid; using Fluid.Filters; using Fluid.Values; namespace FlipLeaf.Core.Text.FluidLiquid { public static class FlipLeafFilters { public static async Task<FluidValue> RelativeUrl(FluidValue input, FilterArguments arguments, TemplateContext context) { var site = context.GetValue("site"); //var config = await site.GetValueAsync("configuration", context); var baseUrl = await site.GetValueAsync("baseUrl", context); if (baseUrl.IsNil()) { return input; } return StringFilters.Prepend(input, new FilterArguments(new StringValue(baseUrl.ToStringValue())), context); } } }