text
stringlengths
13
6.01M
using System; using OpenTK; namespace AndroidUI.Scene { class Objects { static public void InitSpotLight(ref Light light) { light.color = new Vector4(0.0f, 0.0f, 0.0f, 1.0f); light.pos = new Vector3(0.0f, 0.0f, 0.0f); light.attenuation = new Vector3(0.0f, 0.0f, 0.0f); light.direction = new Vector3(0.0f, 0.0f, 0.0f); light.ambient = 0.3f; light.diffuse = 0.6f; light.specular = 0.9f; light.exp = 1.0f; light.cosCutOff = (float)(Math.Cos(90.0 * Math.PI / 180.0)); light.type = LightType.SPOT; } static public void InitPointLight(ref Light light) { light.color = new Vector4(0.0f, 0.0f, 0.0f, 1.0f); light.pos = new Vector3(0.0f, 0.0f, 0.0f); light.attenuation = new Vector3(0.0f, 0.0f, 0.0f); light.direction = new Vector3(0.0f, 0.0f, 0.0f); light.ambient = 0.1f; light.diffuse = 0.2f; light.specular = 0.5f; light.exp = 0.0f; light.cosCutOff = 0.0f; light.type = LightType.POINT; } } public enum LightType { POINT = 1, SPOT = 2 } public struct Light { public Vector4 color; public Vector3 pos; public Vector3 attenuation; public Vector3 direction; public float exp; public float cosCutOff; public float ambient; public float diffuse; public float specular; public LightType type; } }
using Entities.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Domain.Interfaces.InterfaceServices { public interface IServiceUsuario { Task<List<ApplicationUser>> ListarUsuariosSomenteParaAdministradores(string userID); } }
using System; using System.Collections.Generic; using System.Text; namespace JabberPoint.Domain.Content.Behaviours { /// <summary> /// composite pattern interface for leaves and composites that can be added to a List composite /// </summary> public interface IListableBehaviour : IContentBehaviour { } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace RipplerES.CommandHandler { public abstract class AggregateBase<T> { public IAggregateCommandResult<T> Success(IAggregateEvent<T> @event) { return new AggregateCommandSuccessResult<T>(@event); } public IAggregateCommandResult<T> Error(IAggregateError<T> error) { return new AggregateCommandErrorResult<T>(error); } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Rendering; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace online_knjizara.ViewModels { public class KnjigaUrediVM { public int ID { get; set; } [Required(ErrorMessage = "Unesite autora knjige.")] public int Autor_ID { get; set; } public List<SelectListItem> Autor { get; set; } [Required(ErrorMessage = "Unesite izdavaca knjige.")] public int Izdavac_ID { get; set; } public List<SelectListItem> Izdavac { get; set; } [Required(ErrorMessage = "Unesite skladiste knjige.")] public int Skladiste_ID { get; set; } public List<SelectListItem> Skladiste { get; set; } [Required(ErrorMessage = "Unesite zanr knjige.")] public int Zanr_ID { get; set; } public List<SelectListItem> Zanr { get; set; } [Required(ErrorMessage = "Unesite stanje knjige.")] public int Stanje_ID { get; set; } public List<SelectListItem> Stanje { get; set; } [Required(ErrorMessage = "Unesite odlomak knjige.")] public int Odlomak_ID { get; set; } public List<SelectListItem> Odlomak { get; set; } [Required(ErrorMessage = "Unesite naziv knjige.")] public string Naziv { get; set; } [Required(ErrorMessage = "Unesite cijenu knjige.")] public float Cijena { get; set; } [Required(ErrorMessage = "Unesite datum izdavanja knjige.")] public DateTime DatumIzdavanja { get; set; } public IFormFile Slika { get; set; } } }
using System; using System.Collections.Generic; using CommandLine; using CommandLine.Text; namespace Example { public class FileOptions { [Option('i', "Input", Required = false, HelpText = "Path to file input")] public string InputFile { get; set; } [Option('o', "Output", Required = false, HelpText = "Path to file output")] public string OutputFile { get; set; } [Usage(ApplicationAlias = "Building Calculator")] public static IEnumerable<CommandLine.Text.Example> Examples { get { yield return new CommandLine.Text.Example("Normal scenario", new FileOptions { InputFile = "in.json", OutputFile = "out.json" }); } } } public class JsonOptions { [Option('i', "Input", Required = true, HelpText = "Array of site inputs")] public string Input { get; set; } [Usage(ApplicationAlias = "Building Calculator")] public static IEnumerable<CommandLine.Text.Example> Examples { get { yield return new CommandLine.Text.Example("JSON input with array of site configurations", new JsonOptions { Input = "[]" }); } } } }
using System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace ThousandUpload.Controllers { [Route("api/[controller]/[action]")] public class UploadCController : ControllerBase { private static readonly string tempPath = TempFile.GetTempPath(); [HttpPost] public async Task<dynamic> Upload() { var files = this.Request.Form.Files; foreach (var file in files) { var dest = Path.Combine(tempPath, Guid.NewGuid().ToString("N") + "-class.pdf"); using (var stream = new FileStream(dest, FileMode.Create, FileAccess.Write)) { await file.CopyToAsync(stream); } } return new { }; } } }
using System.Collections.Generic; using Asset.Models.Library.EntityModels.OrganizationModels; using Core.Repository.Library.Core; namespace Asset.Core.Repository.Library.Repositorys.Organizations { public interface IDepartmentRepository : IRepository<Department> { Department GetDepartmentByShortName(string shortName); Department GetDepartmentByName(string name); Department GetDepartmentByCode(string code); IEnumerable<Department> DepartmentWithOrganization(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Voronov.Nsudotnet.BuildingCompanyIS.Entities; using Voronov.Nsudotnet.BuildingCompanyIS.Logic.DataStructures; namespace Voronov.Nsudotnet.BuildingCompanyIS.Logic.DbInterfaces { public interface IOrganizationUnitsService : ICrudService<OrganizationUnit> { IQueryable<OrganizationUnit> GetOrganizationUnitsWithManager(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AutoInsuranceMVC.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult GetQuote(string FirstName, string LastName, string EmailAddress, DateTime Dob, int CarYear, string CarMake, string CarModel, int Duis, int SpeedingTickets, string Coverage) { // Base Fee double Quote = 50; // Get Age and Calculate Age Rates int Age = 0; DateTime now = DateTime.Now; if(now.Month > Dob.Month) { Age = now.Year - Dob.Year; } else if(now.Month < Dob.Month) { Age = now.Year - Dob.Year - 1; } else if (now.Month == Dob.Month) { if (now.Day > Dob.Day) { Age = now.Year - Dob.Year; } else if (now.Day < Dob.Day) { Age = now.Year - Dob.Year - 1; } else { Age = now.Year - Dob.Year; } } if (Age < 25) { Quote += 25; } if (Age < 18) { Quote += 75; } if (Age > 100) { Quote += 25; } // Car Attributes if (CarYear < 2000) { Quote += 25; } if (CarYear > 2015) { Quote += 25; } if (CarMake=="Porsche") { if(CarModel == "911 Carrera") { Quote += 50; } else { Quote += 25; } } // Driving History Quote += 10 * SpeedingTickets; if(Duis > 0) { Quote += Quote * 0.25; } // Coverage Type if (Coverage == "Full") { Quote += Quote * 0.50; } // Database Insert of all Data using (AutoQuoteEntities1 db = new AutoQuoteEntities1()) { var quote = new Quote(); quote.FirstName = FirstName; quote.LastName = LastName; quote.EmailAddress = EmailAddress; quote.Dob = Dob; quote.CarYear = CarYear; quote.CarMake = CarMake; quote.CarModel = CarModel; quote.QuoteValue = Convert.ToInt32(Quote); db.Quotes.Add(quote); db.SaveChanges(); ViewBag.Message = quote; } return View("TheQuote"); } public ActionResult Admin() { using (AutoQuoteEntities1 db = new AutoQuoteEntities1()) { var dbQuotes = db.Quotes; var quotes = new List<Quote>(); foreach(var quote in dbQuotes) { var aQuote = new Quote(); aQuote.FirstName = quote.FirstName; aQuote.LastName = quote.LastName; aQuote.EmailAddress = quote.EmailAddress; aQuote.Dob = quote.Dob; aQuote.CarYear = quote.CarYear; aQuote.CarMake = quote.CarMake; aQuote.CarModel = quote.CarModel; aQuote.QuoteValue = quote.QuoteValue; quotes.Add(aQuote); } ViewBag.Message = quotes; return View(); } } } }
using System.Globalization; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Bogus; using Bogus.DataSets; using Bogus.Extensions.Brazil; using Eventos.IO.Infra.CrossCutting.Identity.Models.AccountViewModels; using Eventos.IO.Tests.API.Integration_Tests.DTO; using Newtonsoft.Json; using Xunit; namespace Eventos.IO.Tests.API.Integration_Tests { public class AccountControllerIntegrationTests { public AccountControllerIntegrationTests() { Environment.CriarServidor(); } [Fact(DisplayName = "Registrar organizador com sucesso")] [Trait("Category","Testes de integração API")] public async Task AccountController_RegistrarNovoOrganizador_RetornarComSucesso() { // Arrange var userFaker = new Faker<RegisterViewModel>("pt_BR") .RuleFor(r => r.Nome, c => c.Name.FullName(Name.Gender.Male)) .RuleFor(r => r.CPF, c => c.Person.Cpf().Replace(".","").Replace("-","")) // remoção de acento no email .RuleFor(r => r.Email, (c, r) => RemoverAcentos(c.Internet.Email(r.Nome).ToLower())); var user = userFaker.Generate(); user.Senha = "Teste@123"; user.SenhaConfirmacao = "Teste@123"; var postContent = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json"); // Act var response = await Environment.Client.PostAsync("api/v1/nova-conta", postContent); var userResult = JsonConvert.DeserializeObject<UserReturnJson>(await response.Content.ReadAsStringAsync()); var token = userResult.data.result.access_token; // Assert response.EnsureSuccessStatusCode(); Assert.NotEmpty(token); } private static string RemoverAcentos(string text) { var normalizedString = text.Normalize(NormalizationForm.FormD); var stringBuilder = new StringBuilder(); foreach (var c in normalizedString) { var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c); if (unicodeCategory != UnicodeCategory.NonSpacingMark) { stringBuilder.Append(c); } } return stringBuilder.ToString().Normalize(NormalizationForm.FormC); } } }
using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace ALM.Reclutamiento.Entidades { [Serializable] public class ECiudad { public int IdCiudad { get; set; } [Required(ErrorMessage = "Dato requerido")] [StringLength(100)] [DisplayName("Nombre Ciudad")] public string Nombre { get; set; } [Required(ErrorMessage = "Dato requerido")] [StringLength(100)] [DisplayName("Nombre Ciudad")] public string Clave_Ciudad { get; set; } public string Clave_Estado { get; set; } public int Estatus { get; set; } public int IdEstado { get; set; } public int IdUsuarioCreacion { get; set; } public DateTime FechaCreacion { get; set; } public int IdUsuarioModificacion { get; set; } public DateTime FechaModificacion { get; set; } public int IdNacionalidad { get; set; } } }
//Using blizzy78's Toolbar API using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; using Toolbar; namespace CactEyeTelescope { [KSPAddon(KSPAddon.Startup.Flight, false)] public class ResetTelescopeGuidance : MonoBehaviour { public void Awake() { TelescopeGuidance.numInit = 0; } } public class TelescopeGuidance : PartModule { protected Rect windowPos = new Rect(Screen.width / 2, Screen.height / 2, 10f, 10f); Part bayPart = null; Part mountPart = null; Part procPart = null; TelescopeProcessor procModule = null; [KSPField(isPersistant = false)] public bool checkBuild = true; [KSPField(isPersistant = false)] public string requiredBay = "tele.bay"; [KSPField(isPersistant = false)] public string requiredMount = "tele.mount"; [KSPField(isPersistant = false, guiActive = false, guiName = "Deactivated", guiActiveEditor = false)] public string warningMessage = "Other Guidance Module Detected"; private string status = ""; private double targetDist = 0; private double targetAngleTo = 0; private double targetSize = 0; private double targetProximity = 0; private bool activated = false; private bool addDist = false; private IButton buttonGuidance; public static int numInit = 0; private void mainGUI(int windowID) { GUILayout.BeginVertical(); if (checkBuild) { if (probe()) { status = getStatus(); } } else { status = getStatus(); } GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.Label("1.000 = Pointing directly at target"); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.Label("" + status); GUILayout.EndHorizontal(); if(addDist) { GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.Label("Distance: " + string.Format("{0:0.0}", targetDist) + "m"); GUILayout.EndHorizontal(); } GUILayout.EndVertical(); GUI.DragWindow(); } protected void drawGUI() { if (activated && HighLogic.LoadedSceneIsFlight) windowPos = GUILayout.Window(-5234628, windowPos, mainGUI, "Fine Guidance Sensor", GUILayout.Width(250), GUILayout.Height(50)); } public override void OnStart(PartModule.StartState state) { base.OnStart(state); if (state == StartState.Editor) { return; } //print("tg numInit: " + numInit + " => " + (numInit + 1)); numInit += 1; if (numInit == 1) { RenderingManager.AddToPostDrawQueue(3, new Callback(drawGUI)); toolbarButton(); Events["toggleEvent"].active = true; } else { Events["toggleEvent"].active = false; Fields["warningMessage"].guiActive = true; } } private string getStatus() { var target = FlightGlobals.fetch.VesselTarget; if (target == null) { addDist = false; return "You must select a target!"; } if (target.GetType().Name == "CelestialBody") { addDist = false; CelestialBody targetBody = FlightGlobals.Bodies.Find(index => index.GetName() == target.GetName()); Vector3d targetLocation = targetBody.position; targetDist = Vector3d.Distance(targetLocation, FlightGlobals.ship_position); Vector3d targetAngle = FlightGlobals.fetch.vesselTargetDirection; Vector3d vesselAngle = part.transform.up; if (checkBuild) vesselAngle = procPart.transform.up; targetAngleTo = Vector3d.Angle(targetAngle, vesselAngle); //relative angle between where processor is pointing and angle to target - 0 degrees ideal targetSize = Math.Atan2(targetBody.Radius, targetDist); //angular size of planet targetSize *= (180 / Math.PI); targetProximity = Math.Sqrt(Math.Max(0, targetAngleTo - targetSize) / 5); if (targetProximity > 1) return "Point within 5° of target to begin proximity reading!"; else return "Proximity: " + string.Format("{0:0.000}", 1 - targetProximity); } else if (target.GetType().Name == "Vessel") { addDist = true; Vessel targetShip = FlightGlobals.Vessels.Find(index => index.GetName() == target.GetName()); targetDist = (Vector3d.Distance(FlightGlobals.ship_position, targetShip.GetWorldPos3D())); Vector3d targetAngle = FlightGlobals.fetch.vesselTargetDirection; Vector3d vesselAngle = part.transform.up; if (checkBuild) vesselAngle = procPart.transform.up; targetAngleTo = Vector3d.Angle(targetAngle, vesselAngle); targetProximity = Math.Sqrt(Math.Max(0, targetAngleTo) / 5); if (targetProximity > 1) return "Point within 5° of target to begin proximity reading!"; else return "Proximity: " + string.Format("{0:0.000}", 1 - targetProximity); } else { addDist = false; return "You must target a celestial body or vessel!"; //can you even target anything else? whatever } } [KSPEvent(guiActive = true, guiName = "Toggle Display", active = true)] public void toggleEvent() { activated = !activated; if(activated) buttonGuidance.TexturePath = "CactEye/Icons/toolbar"; else buttonGuidance.TexturePath = "CactEye/Icons/toolbar_disabled"; } [KSPAction("Toggle Display")] public void toggleAction(KSPActionParam param) { toggleEvent(); } private void toolbarButton() { buttonGuidance = ToolbarManager.Instance.add("test", "buttonGuidance"); buttonGuidance.Visibility = new GameScenesVisibility(GameScenes.FLIGHT); buttonGuidance.TexturePath = "CactEye/Icons/toolbar_disabled"; buttonGuidance.ToolTip = "CactEye Fine Guidance Sensor"; buttonGuidance.OnClick += (e) => toggleEvent(); } private void OnDestroy() { buttonGuidance.Destroy(); } private bool probe() { bayPart = part.parent; if (!bayPart.name.Contains(requiredBay)) { status = "Guidance sensor needs to be placed on bay!"; return false; } mountPart = bayPart.parent; if (bayPart.FindChildPart(requiredMount) != null) mountPart = bayPart.FindChildPart(requiredMount); else if (mountPart == null) { status = "Could not find processor!"; return false; } else if (!mountPart.name.Contains(requiredMount)) { status = "Could not find processor!"; return false; } procPart = mountPart.children.Last(); if (procPart == null) { status = "Could not find processor!"; return false; } procModule = procPart.GetComponent<TelescopeProcessor>(); if (procModule == null) { status = "Could not find processor!"; return false; } if (!procModule.partFunctional) { status = "Processor not functional!"; return false; } if (!procModule.partActive) { status = "Processor not activated!"; return false; } return true; } } }
using LuaInterface; using SLua; using System; public class Lua_RO_ScreenShot_AntiAliasing : LuaObject { public static void reg(IntPtr l) { LuaObject.getEnumTable(l, "RO.ScreenShot.AntiAliasing"); LuaObject.addMember(l, 0, "None"); LuaObject.addMember(l, 2, "Samples2"); LuaObject.addMember(l, 4, "Samples4"); LuaObject.addMember(l, 8, "Samples8"); LuaDLL.lua_pop(l, 1); } }
using System; using System.ComponentModel.DataAnnotations; namespace DIYTracker.Models { public class Material : IItem { [Key] public int Id { get; set; } public string Name { get; set; } public double Price { get; set; } public string SingleUnits { get; set; } public string PluralUnits { get; set; } } }
using System.Collections.Generic; using System.Diagnostics; using ClearSight.RendererAbstract.Memory; namespace ClearSight.RendererAbstract.Binding { public abstract class DescriptorHeap : DeviceChild<DescriptorHeap.Descriptor> { public struct Descriptor { public enum ResourceDescriptorType { /// <summary> /// Textures, constant buffers and unordered access views. /// </summary> ShaderResource, Sampler, RenderTarget, DepthStencil } public ResourceDescriptorType Type; public uint NumResourceDescriptors; } protected Resource[] associatedResources; protected DescriptorHeap(ref Descriptor desc, Device device, string label) : base(ref desc, device, label) { associatedResources = new Resource[desc.NumResourceDescriptors]; Create(); } internal void SetAssociatedResource(uint slot, Resource resource) { // todo: Check if this slot is in use? associatedResources[slot] = resource; } } }
namespace CalcItCore.Operands { public abstract class Operand { public string[] characters { get; } public bool reversed { get; } public int priority { get; } public Operand(string[] characters, int priority, bool reversed = false) { this.characters = characters; this.reversed = reversed; this.priority = priority; } public abstract double calculate(double val1, double val2, CalculatorEngine engine); } public class Plus: Operand { public Plus(): base(new string[] { "+" }, 1) {} public override double calculate(double val1, double val2, CalculatorEngine engine) { return val1 + val2; } } public class Minus: Operand { public Minus(): base(new string[] { "-", "–" }, 1) {} public override double calculate(double val1, double val2, CalculatorEngine engine) { return val1 - val2; } } public class Multiply: Operand { public Multiply(): base(new string[] { ".", "*", "·", "×" }, 2) {} public override double calculate(double val1, double val2, CalculatorEngine engine) { return val1 * val2; } } public class Divide: Operand { public Divide(): base(new string[] { ":", "/", "÷" }, 2) { } public override double calculate(double val1, double val2, CalculatorEngine engine) { if (val2 == 0) throw new ExpressionInvalidException("divisionByZero"); return val1 / val2; } } public class Exponentiation: Operand { public Exponentiation(): base(new string[] { "^" }, 4, true) { } public override double calculate(double val1, double val2, CalculatorEngine engine) { return CoreUtils.power(val1, val2, engine); } } public class Root: Operand { public Root(): base(new string[] { "#" }, 4) { } public override double calculate(double val1, double val2, CalculatorEngine engine) { if (val1 == 0) throw new ExpressionInvalidException("level0Root"); return CoreUtils.power(val2, 1 / val1, engine); } } public class OpeningBrace: Operand { public OpeningBrace(): base(new string[] { "(", "[", "{", "<" }, -2) { } public override double calculate(double val1, double val2, CalculatorEngine engine) { throw new ExpressionInvalidException("braceInvolved"); } } public class ClosingBrace: Operand { public ClosingBrace(): base(new string[] { ")", "]", "}", ">" }, -2) { } public override double calculate(double val1, double val2, CalculatorEngine engine) { throw new ExpressionInvalidException("braceInvolved"); } } public class DotlessMultiplication: Operand { public DotlessMultiplication(): base(new string[] { "." }, 3) { } public override double calculate(double val1, double val2, CalculatorEngine engine) { return val1 * val2; } } }
 public interface IDamagable { void TakeDamage(float dmg); }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Anima2D; using UnityEngine.UI; public class ChangeColor : MonoBehaviour { public bool ui; public bool hasHoverText; public SpriteMeshInstance[] suit; public Image[] overlays; public SpriteRenderer[] spriteRenderers; public Text hoverText; [Header("Colors")] public Color yellow; public Color red; public Color blue; public Color green; [Space(5)] [Range(1,4)] public int color; void OnValidate(){ if (ui){ foreach(Image s in overlays){ if (color == 1) s.color = yellow; else if (color == 2) s.color = red; else if (color == 3) s.color = blue; else if (color == 4) s.color = green; } }else{ foreach(SpriteMeshInstance s in suit){ if (color == 1) s.color = yellow; else if (color == 2) s.color = red; else if (color == 3) s.color = blue; else if (color == 4) s.color = green; } } if(hasHoverText){ if (color == 1) hoverText.color = yellow; else if (color == 2) hoverText.color = red; else if (color == 3) hoverText.color = blue; else if (color == 4) hoverText.color = green; } if (spriteRenderers != null) foreach (SpriteRenderer s in spriteRenderers) { if (color == 1) s.color = yellow; else if (color == 2) s.color = red; else if (color == 3) s.color = blue; else if (color == 4) s.color = green; } } public void ManualValidate(){ if (ui){ foreach(Image s in overlays){ if (color == 1) s.color = yellow; else if (color == 2) s.color = red; else if (color == 3) s.color = blue; else if (color == 4) s.color = green; } }else{ foreach(SpriteMeshInstance s in suit){ if (color == 1) s.color = yellow; else if (color == 2) s.color = red; else if (color == 3) s.color = blue; else if (color == 4) s.color = green; } } if(hasHoverText){ if (color == 1) hoverText.color = yellow; else if (color == 2) hoverText.color = red; else if (color == 3) hoverText.color = blue; else if (color == 4) hoverText.color = green; } if (spriteRenderers != null) foreach (SpriteRenderer s in spriteRenderers) { if (color == 1) s.color = yellow; else if (color == 2) s.color = red; else if (color == 3) s.color = blue; else if (color == 4) s.color = green; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; using Accounting.Entity; using Accounting.Utility; namespace Accounting.DataAccess { public class DaCountry { public DaCountry() { } public static DataTable GetCountries(string pWhere, string OrderBy) { DataTable dt = new DataTable(); try { using (SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Country WHERE " + pWhere + " ORDER BY " + OrderBy, ConnectionHelper.getConnection())) { da.Fill(dt); da.Dispose(); } } catch (Exception ex) { throw ex; } return dt; } public DataTable getCountry(SqlConnection con) { try { SqlDataAdapter da = new SqlDataAdapter("select * from Country WHERE CompanyID = " + LogInInfo.CompanyID.ToString(), con); DataTable ds = new DataTable(); da.Fill(ds); da.Dispose(); return ds; } catch (Exception ex) { throw ex; } } public void saveUpdateCountry(Country obCountry, SqlConnection con) { SqlCommand com = null; SqlTransaction trans = null; try { com = new SqlCommand(); trans = con.BeginTransaction(); com.Transaction = trans; com.Connection = con; com.CommandText = "spSaveUpdateCountry"; com.CommandType = CommandType.StoredProcedure; com.Parameters.Add("@CountryID", SqlDbType.Int).Value = obCountry.CountryID; com.Parameters.Add("@CountryName", SqlDbType.VarChar, 100).Value = obCountry.CountryName; com.Parameters.Add("@CompanyID", SqlDbType.Int).Value = LogInInfo.CompanyID; com.Parameters.Add("@UserID", SqlDbType.Int).Value = LogInInfo.UserID; //com.Parameters.Add("@ModifiedDate", SqlDbType.DateTime).Value = obCountry.ModifiedDate; com.ExecuteNonQuery(); trans.Commit(); } catch (Exception ex) { trans.Rollback(); throw ex; } } public void deleteCountry(SqlConnection con, int CountryID) { SqlCommand com = null; SqlTransaction trans = null; try { com = new SqlCommand(); trans = con.BeginTransaction(); com.Transaction = trans; com.Connection = con; com.CommandText = "Delete from Country where CountryID = @CountryID"; com.CommandType = CommandType.Text; com.Parameters.Add("@CountryID", SqlDbType.Int).Value = CountryID; com.ExecuteNonQuery(); trans.Commit(); } catch (Exception ex) { trans.Rollback(); throw ex; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class Controller : Singleton<Controller> { protected Controller() { } public status state = status.none; status previousState; public enum status { none, carryingNode, linkingStart, linkingNodes, linkOnTarget, linked } public Link currentLink; GameObject linkVisual; public GameObject linkBeginning; public GameObject linkTarget; GameObject carriedNode; List<SpellNode> nodesPlaced; int NodeLayer; int DefaultLayer = 0; bool showError = false; string errorText; float errorTiming = 0; Vector3 mouseWorldPos; void Start() { //GameObject controller = this.gameObject; //Debug.Log(controller); //controller.AddComponent<EventCatcher>(); state = status.none; previousState = status.none; NodeLayer = LayerMask.NameToLayer("Nodes"); nodesPlaced = new List<SpellNode>(); } void OnGUI() { if (showError) { //GUI.Label(new Rect(Screen.width / 2, Screen.height / 2, Screen.width / 6, Screen.height / 6), errorText);\ GUILayout.Label("<size=30><color=red>" + errorText + "</color></size>"); } } // Update is called once per frame void LateUpdate() { mouseWorldPos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane * 5)); if (state != previousState) { Debug.Log(state); previousState = state; } switch (state) { case status.carryingNode: nodeDragUpdate(); break; case status.linkingStart: linkingStart(); break; case status.linkingNodes: linkingUpdate(); break; case status.linkOnTarget: attachLink(); break; case status.linked: finalizeLink(); break; } if (showError) { if (errorTiming < 5f) errorTiming += Time.deltaTime; else { errorTiming = 0; showError = false; } } } private void linkingStart() { if (!hittingUI()) { linkVisual = new GameObject("Link"); linkVisual.transform.parent = linkBeginning.transform; //LineRenderer link = linkVisual.GetComponent<LineRenderer>(); LineRenderer link; if (true) { link = linkVisual.AddComponent<LineRenderer>(); link.useWorldSpace = true; link.positionCount = 2; link.widthMultiplier = 0.2f; link.material = new Material(Shader.Find("Particles/Additive")); //link.startColor = Color.gray; //link.endColor = Color.gray; // A simple 2 color gradient with a fixed alpha of 1.0f. float alpha = 1.0f; Color c1 = Color.blue; Color c2 = Color.cyan; Gradient gradient = new Gradient(); gradient.SetKeys( new GradientColorKey[] { new GradientColorKey(c1, 0.0f), new GradientColorKey(c2, 1.0f) }, new GradientAlphaKey[] { new GradientAlphaKey(alpha, 0.0f), new GradientAlphaKey(alpha, 1.0f) } ); link.colorGradient = gradient; } currentLink.start = linkBeginning.transform.position; linkingUpdate(); state = status.linkingNodes; } } void linkingUpdate() { currentLink.end = mouseWorldPos; LineRenderer link = linkVisual.GetComponent<LineRenderer>(); //Debug.Log("StartWidth = " + link.startWidth); //Debug.Log("EndWidth = " + link.endWidth); //Debug.Log("StartColor= " + link.startColor); //Debug.Log("EndColor= " + link.endColor); link.SetPosition(link.positionCount - 2, currentLink.start); link.SetPosition(link.positionCount - 1, currentLink.end); if (Input.GetMouseButtonDown(2)) { state = status.none; Destroy(linkVisual); } } private void attachLink() { var link = linkVisual.GetComponent<LineRenderer>(); link.SetPosition(link.positionCount - 1, linkTarget.transform.position); } private void finalizeLink() { var currentLink = new Link(linkBeginning.transform.position, linkTarget.transform.position); var startNode = linkBeginning.GetComponent<NodeBehaviour>(); var endNode = linkTarget.GetComponent<NodeBehaviour>(); if (!startNode.node.links.Contains(currentLink) && !endNode.node.links.Contains(currentLink)) { Debug.Log("Link added"); foreach (Link link in startNode.node.links) { Debug.Log("Link" + ":" + link.start + " " + link.end); Debug.Log("Link is " + link.Equals(currentLink) + " to current"); } currentLink.endId = endNode.node.id; currentLink.startId = startNode.node.id; startNode.node.links.Add(currentLink); endNode.node.links.Add(currentLink.reverse()); } else { Debug.Log("Link terminated as obsolete"); //LineRenderer link = linkVisual.GetComponent<LineRenderer>(); Destroy(linkVisual); //link.positionCount -= 2; } state = status.none; } public bool carryNode<T> (GameObject node) where T : SpellNode, new() { var nodeBehaviour = node.GetComponent<NodeBehaviour>(); if (nodeBehaviour) { if (state == status.carryingNode) { Destroy(carriedNode); } carriedNode = Instantiate(node, Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane)), Quaternion.identity); nodeBehaviour = carriedNode.GetComponent<NodeBehaviour>(); nodeBehaviour.node = new T(); nodeBehaviour.node.id = (uint)nodesPlaced.Count; carriedNode.layer = DefaultLayer; state = status.carryingNode; return true; } else return false; } void nodeDragUpdate() { carriedNode.transform.position = mouseWorldPos; if (Input.GetMouseButtonDown(0)) { placeNode(); } if (Input.GetMouseButtonDown(2)) { state = status.none; Destroy(carriedNode); } } void placeNode() { if (!hittingUI()) { RaycastHit hit; float distance = 3f; //how far the ray shoots int layerMask = 1 << NodeLayer; //layerMask = ~layerMask; //invert layerMask Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); float rayRadius = NodeBehaviour.nodeRadius; if (!Physics.SphereCast(ray, rayRadius, out hit, distance, layerMask)) { //node is placed correctly var currentNode = carriedNode.GetComponent<NodeBehaviour>(); Debug.Log(currentNode.node.GetType().ToString()); //Debug.Log(currentNode.node.Type()); currentNode.node.position = carriedNode.transform.position; nodesPlaced.Add(currentNode.node); state = status.none; carriedNode.layer = NodeLayer; } else { showError = true; errorText = "You are placing this node too close to an another node"; }//GUI.Label(new Rect(Screen.width/2, Screen.height / 2, Screen.width / 6, Screen.height / 6), "You are placing this node too close to an another node");//Debug.Log("You are placing this node too close to an another node"); } else { Debug.Log("You are hitting a UI element"); } } public bool hittingUI () { PointerEventData cursor = new PointerEventData(EventSystem.current); cursor.position = Input.mousePosition; List<RaycastResult> objectsHit = new List<RaycastResult>(); // This section prepares a list for all objects hit with the raycast EventSystem.current.RaycastAll(cursor, objectsHit); int hitsToUi = objectsHit.Count; return hitsToUi != 0; } public List<SpellNode> getSpellNodes () { return nodesPlaced; } public bool initiate() { return true; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.SolverFoundation.Common; using Microsoft.SolverFoundation.Services; using Xamarin.Forms; using Microsoft.SolverFoundation.Solvers; namespace OMIKAS { public partial class ProcessChooseForm : ContentPage { /// <summary> /// Solver rozwiązujący układ równań /// </summary> private SimplexSolver solver; /// <summary> /// Konstruktor okna /// </summary> public ProcessChooseForm() { InitializeComponent(); selectedAlloys = new List<Alloy>(); selectedSmelts = new List<Smelt>(); } /// <summary> /// strona do wyboru stopow /// </summary> private SelectMultipleBasePage<Alloy> multiPageAlloys; /// <summary> /// strona do wyboru wytopow /// </summary> private SelectMultipleBasePage<Smelt> multiPageSmelts; /// <summary> /// Lista wybranych stopów do procesu /// </summary> private List<Alloy> selectedAlloys; /// <summary> /// Jednoelementowa lista z wybranym wytopem /// </summary> private List<Smelt> selectedSmelts; /// <summary> /// Funkcja ładuje stronę z wszystkimi stopami /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void btn_chooseAlloy_Clicked(object sender, EventArgs e) { //Wczytaj do strony liste stopów i ją wyświetl if(multiPageAlloys == null) multiPageAlloys = new SelectMultipleBasePage<Alloy>(App.DAUtil.GetAllAlloys()) { Title = "Wybór składników" }; await Navigation.PushAsync(multiPageAlloys); } /// <summary> /// Funkcja ładuje stronę z wszystkimi wytopami /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void btn_chooseSmelt_Clicked(object sender, EventArgs e) { //Wczytaj do strony liste wytopów i ją wyświetl if(multiPageSmelts == null) multiPageSmelts = new SelectMultipleBasePage<Smelt>(App.DAUtil.GetAllSmelts()) { Title = "Wybór wytopu" }; await Navigation.PushAsync(multiPageSmelts); } /// <summary> /// Wyświetla nazwy wszystkich wybranych stopów na etykiecie /// </summary> /// <param name="page">Strona z której zostały wybrane stopy</param> /// <param name="lbl">Etykieta na której ma się pojawić tekst</param> /// <returns>lista stopów</returns> private List<Alloy> WhatisSelected(SelectMultipleBasePage<Alloy> page, Label lbl) { if(page != null) { lbl.Text = "Wybrano: "; List<Alloy> selected = page.GetSelection(); foreach(Alloy item in selected) { lbl.Text += item.name + ", "; } return selected; } else { lbl.Text = "Wybrano: "; List<Alloy> tmp = new List<Alloy>(); return tmp; } } /// <summary> /// Wyświetla nazwy wszystkich wybranych wytopów na etykiecie /// </summary> /// <param name="page">Strona z której zostały wybrane wytopy</param> /// <param name="lbl">Etykieta na której ma się pojawić tekst</param> /// <returns>lista wytopów</returns> private List<Smelt> WhatisSelected(SelectMultipleBasePage<Smelt> page, Label lbl) { if(page != null) { lbl.Text = "Wybrano: "; List<Smelt> selected = page.GetSelection(); foreach(Smelt item in selected) { lbl.Text += item.name + ", "; } return selected; } else { lbl.Text = "Wybrano: "; List<Smelt> tmp = new List<Smelt>(); return tmp; } } /// <summary> /// Za każdym razem gdy pokaze się okno wczytaj wybrane stopy i wytopy aby przejsc dalej muszą być wybrane conajmniej 1 stop i conajmniej 1 wytop /// </summary> protected override void OnAppearing() { //Jezeli cos jest wybrane w obu listach odblokuj przycisk obliczeń base.OnAppearing(); selectedAlloys = WhatisSelected(multiPageAlloys, lbl_selectedAlloys); selectedSmelts = WhatisSelected(multiPageSmelts, lbl_selectedSmelts); if(!selectedAlloys.Any() || !selectedSmelts.Any()) { btn_count.IsEnabled = false; } else btn_count.IsEnabled = true; } /// <summary> /// Akcja wykonywana po wcisnieciu przycisku. Sprawdzenie poprawnosci danych i uruchomienie solvera /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void btn_count_Clicked(object sender, EventArgs e) { if(!(selectedSmelts.Count > 1)) { double num = 0; //Spróbuj przeparsować dane if(Double.TryParse(entWeight.Text, out num)) { //Inicjalizuj solver i do wytopu wprowadź masę this.solver = new SimplexSolver(); selectedSmelts.ElementAt(0).Weight = double.Parse(entWeight.Text); //Do uruchomienia solera potrzebnne są tablice z pierwiastkami (zmniejszenie ilości kodu i poprawienie czytelności) foreach(Alloy xd in selectedAlloys) { xd.createTabOfElements(xd); } foreach(Smelt xd in selectedSmelts) { xd.createTabofEvoporation(xd); xd.createTabofMaxNorm(xd); xd.createTabofMinNorm(xd); } //Wybór otymalizacji kosztowej lub masowej if(SwitchPriceWeight.IsToggled) { //optymalizuj mase calculate_weight(selectedAlloys, selectedSmelts); } else { //optymalizuj koszt calculate_price(selectedAlloys, selectedSmelts); } } //Pokaż errory jak coś źle else await DisplayAlert("Error", "Popraw masę wytopu", "OK"); } else await DisplayAlert("Error", "Ilość wybranych wytopów musi wynosić 1", "OK"); } /// <summary> /// Powrót do poprzedniego ekranu (menu główne) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void btntool_Clicked(object sender, EventArgs e) { await Navigation.PopModalAsync(); } /// <summary> /// Funkcja z pomocą której następuje uruchomienie solvera i wykonanie obliczeń optymalizujących cenę /// </summary> /// <param name="alloys">Lista stopów biorących udział w procesie wytapiania</param> /// <param name="smelt">Wytop który chcemy uzyskać</param> private async void calculate_price(List<Alloy> alloys, List<Smelt> smelt) { int[] tabVar = new int[alloys.Count]; //il stopow w wytopie int[] tabEq = new int[31]; //il pierwiastkow + war + f. celu try { //warunek nieujemnosci zmiennych for(int i = 0; i < tabVar.Count(); i++) { solver.AddVariable(alloys.ElementAt(i).name, out tabVar[i]); solver.SetBounds(tabVar[i], 0, Rational.PositiveInfinity); } //E(Aij*Xij>bi) i=1,2,..,n for(int i = 0; i < tabEq.Count() - 2; i++) { solver.AddRow("r" + i.ToString(), out tabEq[i]); for(int j = 0; j < selectedAlloys.Count; j++) { //zmienna, kazda zawartosc pierwiastka x jego wsp. parowania solver.SetCoefficient(tabEq[i], tabVar[j], selectedAlloys.ElementAt(j).tabOfElements[i] * (1 - smelt.ElementAt(0).evoporation[i] / 100)); } solver.SetBounds(tabEq[i], smelt.ElementAt(0).min_Norm[i] * smelt.ElementAt(0).Weight, smelt.ElementAt(0).max_Norm[i] * smelt.ElementAt(0).Weight); } solver.AddRow("weightCond", out tabEq[29]); //war masowy solver.AddRow("cost", out tabEq[30]); //f celu for(int i = 0; i < alloys.Count; i++) { solver.SetCoefficient(tabEq[29], tabVar[i], 1); if(alloys.ElementAt(i).Price == 0) { solver.SetCoefficient(tabEq[30], tabVar[i], 1); } else solver.SetCoefficient(tabEq[30], tabVar[i], alloys.ElementAt(i).Price); } solver.SetBounds(tabEq[29], smelt.ElementAt(0).Weight, smelt.ElementAt(0).Weight); solver.AddGoal(tabEq[30], 1, true); //po obliczeniach pokaż ekran z wynikami await Navigation.PushAsync(new ProcessResults(solver, alloys, smelt, SwitchPriceWeight.IsToggled)); } catch(Exception ex) { await DisplayAlert("Error", "Cos w solverze nie tak:\n" + ex.ToString(), "OK"); } } /// <summary> /// Funkcja z pomocą której następuje uruchomienie solvera i wykonanie obliczeń optymalizujących mase /// </summary> /// <param name="alloys">Lista stopów biorących udział w procesie wytapiania</param> /// <param name="smelt">Wytop który chcemy uzyskać</param> private async void calculate_weight(List<Alloy> alloys, List<Smelt> smelt) { int[] tabVar = new int[alloys.Count]; //il stopow w wytopie int[] tabEq = new int[31]; //il pierwiastkow + war + f. celu try { //warunek nieujemnosci zmiennych for(int i = 0; i < tabVar.Count(); i++) { solver.AddVariable(alloys.ElementAt(i).name, out tabVar[i]); solver.SetBounds(tabVar[i], 0, Rational.PositiveInfinity); } //E(Aij*Xij>bi) i=1,2,..,n for(int i = 0; i < tabEq.Count() - 2; i++) { solver.AddRow("r" + i.ToString(), out tabEq[i]); for(int j = 0; j < selectedAlloys.Count; j++) { //zmienna, kazda zawartosc pierwiastka x jego wsp. parowania solver.SetCoefficient(tabEq[i], tabVar[j], selectedAlloys.ElementAt(j).tabOfElements[i] * (1 - smelt.ElementAt(0).evoporation[i] / 100)); } solver.SetBounds(tabEq[i], smelt.ElementAt(0).min_Norm[i] * smelt.ElementAt(0).Weight, smelt.ElementAt(0).max_Norm[i] * smelt.ElementAt(0).Weight); } solver.AddRow("weightCond", out tabEq[29]); //war masowy solver.AddRow("Weight", out tabEq[30]); //f celu for(int i = 0; i < alloys.Count; i++) { solver.SetCoefficient(tabEq[29], tabVar[i], 1); solver.SetCoefficient(tabEq[30], tabVar[i], 1); } //double tmpW = -1 * smelt.ElementAt(0).Weight; //int m; //solver.AddVariable("m", out m); //solver.SetBounds(m, smelt.ElementAt(0).Weight, smelt.ElementAt(0).Weight); //solver.SetCoefficient(tabEq[30], m , tmpW); solver.SetBounds(tabEq[29], smelt.ElementAt(0).Weight, smelt.ElementAt(0).Weight); solver.AddGoal(tabEq[30], 1, true); //po obliczeniach pokaż ekran z wynikami await Navigation.PushAsync(new ProcessResults(solver, alloys, smelt, SwitchPriceWeight.IsToggled)); } catch(Exception ex) { await DisplayAlert("ERROR", ex.ToString(), "Ok"); } } } }
using LuaInterface; using RenderHeads.Media.AVProVideo; using SLua; using System; public class Lua_RenderHeads_Media_AVProVideo_Helper : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int GetName_s(IntPtr l) { int result; try { Platform platform; LuaObject.checkEnum<Platform>(l, 1, out platform); string name = RenderHeads.Media.AVProVideo.Helper.GetName(platform); LuaObject.pushValue(l, true); LuaObject.pushValue(l, name); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int GetPlatformNames_s(IntPtr l) { int result; try { string[] platformNames = RenderHeads.Media.AVProVideo.Helper.GetPlatformNames(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, platformNames); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int GetTimeString_s(IntPtr l) { int result; try { float totalSeconds; LuaObject.checkType(l, 1, out totalSeconds); string timeString = RenderHeads.Media.AVProVideo.Helper.GetTimeString(totalSeconds); LuaObject.pushValue(l, true); LuaObject.pushValue(l, timeString); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_ScriptVersion(IntPtr l) { int result; try { LuaObject.pushValue(l, true); LuaObject.pushValue(l, "1.5.22"); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "RenderHeads.Media.AVProVideo.Helper"); LuaObject.addMember(l, new LuaCSFunction(Lua_RenderHeads_Media_AVProVideo_Helper.GetName_s)); LuaObject.addMember(l, new LuaCSFunction(Lua_RenderHeads_Media_AVProVideo_Helper.GetPlatformNames_s)); LuaObject.addMember(l, new LuaCSFunction(Lua_RenderHeads_Media_AVProVideo_Helper.GetTimeString_s)); LuaObject.addMember(l, "ScriptVersion", new LuaCSFunction(Lua_RenderHeads_Media_AVProVideo_Helper.get_ScriptVersion), null, false); LuaObject.createTypeMetatable(l, null, typeof(RenderHeads.Media.AVProVideo.Helper)); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Accounting.Entity { public class Sizes { public Sizes() { } #region Fields private int intSizesID = 0; private string strSizesName = ""; #endregion #region Properties public int SizesID { get { return intSizesID; } set { intSizesID = value; } } public string SizesName { get { return strSizesName; } set { strSizesName = value; } } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CandyCane { public class BuildScript { private string _path; private string _name; public BuildScript(string path, string name) { this._name = name; this._path = path; } public List<string> folders() { var folders = new List<string>(); foreach (string folder in Directory.GetDirectories(_path + "\\src")) folders.Add(Path.GetFileName(folder)); return folders; } public void CreateBuildScript() { List<string> buildScript = new List<string>(); buildScript.Add("#I @\"tools\\FAKE\\tools\\\"\r\n"); buildScript.Add("#r @\"tools\\FAKE\\tools\\FakeLib.dll\"\r\n"); buildScript.Add("\r\n"); buildScript.Add("open Fake\r\n"); buildScript.Add("open Fake.AssemblyInfoFile\r\n"); buildScript.Add("open Fake.Git\r\n"); buildScript.Add("open System.IO\r\n"); buildScript.Add("\r\n"); buildScript.Add("let projectName = " + "\"" + _name + "\"\r\n"); buildScript.Add("\r\n"); buildScript.Add("//Directories\r\n"); buildScript.Add("let buildDir = @\".\\build\"\r\n"); buildScript.Add("\r\n"); foreach (var folder in folders()) { if (folder == "js") { continue; } if (folder.ToLower() == "test") { buildScript.Add("let testDir = buildDir + @\".\\test\"\r\n"); } else { buildScript.Add("let " + folder + "BuildDir = buildDir + @\"\\" + folder + "\"\r\n"); } } buildScript.Add("\r\n"); buildScript.Add("let deployDir = @\".\\Publish\"\r\n"); buildScript.Add("\r\n"); buildScript.Add("let packagesDir = @\".\\packages\\\"\r\n"); buildScript.Add("\r\n"); buildScript.Add("let mutable version = \"1.0\"\r\n"); buildScript.Add("let mutable build = buildVersion\r\n"); buildScript.Add("let mutable nugetVersion = \"\"\r\n"); buildScript.Add("let mutable asmVersion = \"\"\r\n"); buildScript.Add("let mutable asmInfoVersion = \"\"\r\n"); buildScript.Add("let mutable setupVersion = \"\"\r\n"); buildScript.Add("\r\n"); buildScript.Add("let gitbranch = Git.Information.getBranchName \".\"\r\n"); buildScript.Add("let sha = Git.Information.getCurrentHash()\r\n"); buildScript.Add("\r\n"); buildScript.Add("Target \"Clean\" (fun _ ->\r\n"); if (folders().Contains("test")) { buildScript.Add(" CleanDirs [buildDir; deployDir; testDir]\r\n"); } else { buildScript.Add(" CleanDirs [buildDir; deployDir]\r\n"); } buildScript.Add(")\r\n"); buildScript.Add("\r\n"); buildScript.Add("Target \"RestorePackages\" (fun _ ->\r\n"); buildScript.Add(" RestorePackages()\r\n"); buildScript.Add(")\r\n"); buildScript.Add("\r\n"); buildScript.Add("Target \"BuildVersions\" (fun _ ->\r\n"); buildScript.Add("\r\n"); buildScript.Add(" let safeBuildNumber = if not isLocalBuild then build else \"0\"\r\n"); buildScript.Add("\r\n"); buildScript.Add(" asmVersion <- version + \".\" + safeBuildNumber\r\n"); buildScript.Add(" asmInfoVersion <- asmVersion + \" - \" + gitbranch + \" - \" + sha\r\n"); buildScript.Add("\r\n"); buildScript.Add(" nugetVersion <- version + \".\" + safeBuildNumber\r\n"); buildScript.Add(" setupVersion <- version + \".\" + safeBuildNumber\r\n"); buildScript.Add("\r\n"); buildScript.Add(" match gitbranch with\r\n"); buildScript.Add(" | \"master\" -> ()\r\n"); buildScript.Add(" | \"develop\" -> (nugetVersion <- nugetVersion + \" - \" + \"beta\")\r\n"); buildScript.Add(" | _ -> (nugetVersion <- nugetVersion + \" - \" + gitbranch)\r\n"); buildScript.Add("\r\n"); buildScript.Add(" SetBuildNumber nugetVersion\r\n"); buildScript.Add(")"); buildScript.Add("\r\n"); buildScript.Add("Target \"AssemblyInfo\" (fun _ ->\r\n"); buildScript.Add(" BulkReplaceAssemblyInfoVersions \"src/\" (fun f ->\r\n"); buildScript.Add(" {f with\r\n"); buildScript.Add(" AssemblyVersion = asmVersion\r\n"); buildScript.Add(" AssemblyInformationalVersion = asmInfoVersion})\r\n"); buildScript.Add(")\r\n"); buildScript.Add("\r\n"); foreach (var folder in folders()) { if (folder == "js") { continue; } if (folder.ToLower() == "test") { buildScript.Add("Target \"BuildTest\" (fun _->\r\n"); buildScript.Add(" !! @\"src\\" + folder + "\\*.csproj\"\r\n"); buildScript.Add(" |> MSBuildRelease " + folder + "Dir \"Build\"\r\n"); buildScript.Add(" |> Log \"Build - Output: \"\r\n"); buildScript.Add(")\r\n"); buildScript.Add("\r\n"); } else { buildScript.Add("Target \"Build" + folder + "\" (fun _->\r\n"); buildScript.Add(" !! @\"src\\" + folder + "\\*.csproj\"\r\n"); buildScript.Add(" |> MSBuildRelease " + folder + "BuildDir \"Build\"\r\n"); buildScript.Add(" |> Log \"Build - Output: \"\r\n"); buildScript.Add(")\r\n"); buildScript.Add("\r\n"); } } if (folders().Contains("test")) { buildScript.Add("Target \"NUnitTest\" (fun _ ->\r\n"); buildScript.Add(" if (Directory.GetFiles(testDir).Length <> 0) then\r\n"); buildScript.Add(" !! (testDir + @\"\\*.Tests.dll\")\r\n"); buildScript.Add(" |> NUnit (fun p ->\r\n"); buildScript.Add(" {p with\r\n"); buildScript.Add(" ToolPath = @\".\\tools\\NUnit.Runners\\tools\\\";\r\n"); buildScript.Add(" Framework = \"net - 4.0\";\r\n"); buildScript.Add(" DisableShadowCopy = true;\r\n"); buildScript.Add(" OutputFile = testDir + @\"\\TestResults.xml\"})\r\n"); buildScript.Add(")\r\n"); buildScript.Add("\r\n"); } buildScript.Add("Target \"Zip\" (fun _ ->\r\n"); buildScript.Add(" !! (buildDir @@ @\"\\**\\*.* \")\r\n"); buildScript.Add(" -- \" *.zip\"\r\n"); buildScript.Add(" |> Zip buildDir (buildDir + projectName + version + \".zip\")\r\n"); buildScript.Add(")\r\n"); buildScript.Add("\r\n"); buildScript.Add("Target \"Publish\" (fun _ ->\r\n"); buildScript.Add(" CreateDir deployDir\r\n"); buildScript.Add("\r\n"); buildScript.Add(" !! (buildDir @@ @\"/**/*.* \")\r\n"); buildScript.Add(" -- \" *.pdb\"\r\n"); buildScript.Add(" |> CopyTo deployDir\r\n"); buildScript.Add(")\r\n"); buildScript.Add("\r\n"); buildScript.Add("\"Clean\"\r\n"); buildScript.Add(" ==> \"RestorePackages\"\r\n"); buildScript.Add(" ==> \"BuildVersions\"\r\n"); buildScript.Add(" =?> (\"AssemblyInfo\", not isLocalBuild )\r\n"); foreach (var folder in folders()) { if (folder == "js") { continue; } buildScript.Add(" ==> \"Build" + folder + "\"\r\n"); } if (folders().Contains("test")) { buildScript.Add(" ==> \"NUnitTest\"\r\n"); } buildScript.Add(" ==> \"Zip\"\r\n"); buildScript.Add(" ==> \"Publish\"\r\n"); buildScript.Add("\r\n"); buildScript.Add("\r\n"); buildScript.Add("RunTargetOrDefault \"Publish\""); string tempBuildScript = ""; for (int i = 0; i < buildScript.Count; i++) { tempBuildScript += buildScript[i]; } if (!File.Exists(_path + @"\build.fsx")) { File.WriteAllText(_path + @"\build.fsx", tempBuildScript); } else { Console.WriteLine("Datei existiert bereits, wenn die Datei überschrieben werden soll, antworten Sie bitte mit \"Ja\""); var input = Console.ReadLine().ToLower(); if (input == "ja") { File.Delete(_path + @"\build.fsx"); File.WriteAllText(_path + @"\build.fsx", tempBuildScript); } else { Console.WriteLine("Programm wird beendet"); } } } } }
 namespace Escc.EastSussexGovUK.UmbracoDocumentTypes.RichTextPropertyEditor { /// <summary> /// A customised rich text editor data type with ESCC formatters and validators /// </summary> public static class RichTextEsccStandardDataType { /// <summary> /// The display name of the data type /// </summary> public const string DataTypeName = "Rich text: ESCC standard"; /// <summary> /// Creates the data type. /// </summary> public static void CreateDataType() { var editorSettings = RichTextPropertyEditorEsccWebsiteSettings.CreateDefaultPreValues(); RichTextDataTypeService.InsertDataType(DataTypeName, editorSettings); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Valve.VR.InteractionSystem; public class WardrobeDoorsAnimationController : MonoBehaviour { public Animator anim; // Start is called before the first frame update void Start() { if(!anim) anim = GetComponentInParent<Animator>(); } // Update is called once per frame void Update() { } private void OnTriggerEnter(Collider other) { if (other.GetComponentInParent<HandCollider>()) { if (!anim.GetBool("isOpening")) { anim.SetBool("isOpening", true); StartCoroutine(ChangeAnimationBoolToFalse()); } } } IEnumerator ChangeAnimationBoolToFalse() { yield return new WaitForSeconds(.7f); anim.SetBool("isOpening", false); } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using UnitTestProject1.Entities; namespace UnitTestProject1 { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { ManagerConfiguracionPrueba manager = new ManagerConfiguracionPrueba(); Configuracion config = manager.ObtenerConfiguracion(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class WeaponSpawner : MonoBehaviour { public GameObject[] weaponList; public float weaponDensity; private PlanetMeshGenerator planetMeshGenerator; private List<GameObject> spawnedWeaponList = new List<GameObject>(); private void Start() { planetMeshGenerator = GameManager.GetInstance().GetPlanet().GetComponent<PlanetMeshGenerator>(); } // Update is called once per frame void Update() { if(spawnedWeaponList.Count < weaponDensity) { spawnedWeaponList.Add(this.spawnSingleWeapon()); } for(int i=0; i<spawnedWeaponList.Count; i++) { if(spawnedWeaponList[i] == null) { Debug.Log("spawn new weapon"); spawnedWeaponList[i] = this.spawnSingleWeapon(); } } } GameObject spawnSingleWeapon() { // Rand weapon int weaponIndex = Random.Range(0, this.weaponList.Length); // Rand position Vector3 newPos = Random.insideUnitCircle.normalized * (planetMeshGenerator.radius + planetMeshGenerator.terrainFluctuationMagnitude); // spawn obj GameObject spawned = Instantiate(weaponList[weaponIndex], newPos, Quaternion.identity); return spawned; } }
using UnityEngine; using System.Collections; public class WinState : MonoBehaviour { void onTriggerEnter (Collider other) { Debug.Log ("You have completed this level."); } void onTriggerStay (Collider other) { Debug.Log ("You have beaten this level."); } void onTriggerExit (Collider other) { Debug.Log ("You have conquered this level."); } }
using System; using System.Collections.Generic; namespace Core.Caching.Interface { public interface ICache { /// <summary> /// Загрузка данных из БД для полного обновления кэша /// </summary> /// <returns></returns> IDictionary<string, object> LoadAll(); } public interface ICache<in TKey, TValue> : ICache where TKey : IEquatable<TKey> where TValue : class, new() { /// <summary> /// Метод инвалидации элемента данных /// </summary> /// <param name="key">Ключ.</param> /// <param name="value"></param> /// <returns> Значение </returns> void Set(TKey key, TValue value); /// <summary> /// Получение значения из кеша /// </summary> /// <param name="key"> Ключ </param> /// <returns> Значение </returns> TValue Get(TKey key); /// <summary> /// Удаление всех данных из кеша /// </summary> void Clear(); /// <summary> /// Удаление значения из кеша. /// </summary> /// <param name="key">Ключ.</param> void Remove(TKey key); /// <summary> /// Метод инвалидации элемента данных /// </summary> /// <param name="key">Ключ.</param> /// <returns> Значение </returns> TValue Invalidate(TKey key); ICacheProvider Provider { get; } /// <summary> /// Метод запускает механизм регулярного автоматического полного обновления кэша. /// </summary> /// <param name="timeSpan">Временной интервал, задающий промежуток времени между соседними обновлениями</param> /// <param name="runImmediately"></param> void SetIntervalUpdate(TimeSpan timeSpan, bool runImmediately = true); } }
using System; using System.Collections.Generic; using System.Text; namespace DTO.Results { public class CompanyRules { public double EmployeeCost { get; set; } public double DependentCost { get; set; } public string NameDiscount { get; set; } public double NameDiscountPercentage { get; set; } public double PayCheck { get; set; } public int TotalPayCheck { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChanceToDraw { class Program { static void Main(string[] args) { double numCards = double.Parse(args[0]); double turnNum = (double.Parse(args[1]) == 0) ? 1 : double.Parse(args[1]); double numCardsMulliganed = (args[2] == "y") ? 3 : 4; // First : Second double deckSize = 30; double numCopiesWanted = 2; // Describes the higher amount wanted. Amount wanted: 1 - numCopiesWanted double chanceToDraw = 0; double chanceBeforeMulligan; double chanceMulligan; double chanceByTurn; Console.WriteLine("Number of copies in deck: {0}", numCards); Console.WriteLine("Number of turns to get 1 or more copies: {0}", turnNum); Console.WriteLine("Number of cards mulliganed: {0}\n", numCardsMulliganed); chanceBeforeMulligan = getHypergeometricDistribution(deckSize, numCards, numCardsMulliganed, numCopiesWanted); Console.WriteLine("Chance by initial draw: {0:f2}%", chanceBeforeMulligan * 100); chanceToDraw += (1 - chanceBeforeMulligan); deckSize = 30 - numCardsMulliganed; chanceMulligan = getHypergeometricDistribution(deckSize, numCards, numCardsMulliganed, numCopiesWanted); Console.WriteLine("Chance by mulliganning {1} cards: {0:f2}%", chanceMulligan * 100, numCardsMulliganed); chanceToDraw *= (1 - chanceMulligan); chanceByTurn = getHypergeometricDistribution(deckSize, numCards, turnNum, numCopiesWanted); Console.WriteLine("Chance to draw by turn {1}: {0:f2}%", chanceByTurn * 100, turnNum); chanceToDraw *= (1 - chanceByTurn); chanceToDraw = 100 * (1 - chanceToDraw); // Convert to percentage Console.WriteLine("Overall chance to draw by turn {1} and after mulliganing: {0:f2}%", chanceToDraw, turnNum); } static double getCombination(double numItems, double numSuccessItems) { double combinationValue = calcPreCombinationValue(numItems) / (calcPreCombinationValue(numSuccessItems) * calcPreCombinationValue(numItems - numSuccessItems)); return combinationValue; } static double calcPreCombinationValue(double input) { double result = 1; for (double i = 0; i < input; i++) { double workingValue = i + 1; result *= workingValue; } return (double)result; } static double getHypergeometricDistribution(double numPopulation, double numPopulationSuccesses, double numSample, double numSampleSuccessesHighest) { double firstExp; double secondExp; double thirdExp; double hyperGeometricDistribution; double cumulativeHyperGeometricDistribution = 0; for (double numSampleSuccesses = 1; numSampleSuccesses <= numSampleSuccessesHighest; numSampleSuccesses++) { firstExp = getCombination(numPopulationSuccesses, numSampleSuccesses); secondExp = getCombination(numPopulation - numPopulationSuccesses, numSample - numSampleSuccesses); thirdExp = getCombination(numPopulation, numSample); hyperGeometricDistribution = firstExp * secondExp / thirdExp; cumulativeHyperGeometricDistribution += hyperGeometricDistribution; } return cumulativeHyperGeometricDistribution; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace WinForm.UI.WinUserControl { public partial class FormUserControl : UserControl { public FormUserControl() { InitializeComponent(); } private void FormUserControl_Load(object sender, EventArgs e) { List<KeyValuePair<string, string>> lstCom = new List<KeyValuePair<string, string>>(); lstCom.Add(new KeyValuePair<string, string>("在职", "在职")); lstCom.Add(new KeyValuePair<string, string>("离职", "离职")); this.ComUseState.Source = lstCom; ComUseState.SelectedIndex = 0; } } }
using MooshakPP.Models.Entities; using System.Collections.Generic; namespace MooshakPP.Models.ViewModels { public class DetailsViewModel { public List<ComparisonViewModel> tests { get; set; } public Submission submission { get; set; } } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("CardBurstCommon")] public class CardBurstCommon : Spell { public CardBurstCommon(IntPtr address) : this(address, "CardBurstCommon") { } public CardBurstCommon(IntPtr address, string className) : base(address, className) { } public void OnBirth(SpellStateType prevStateType) { object[] objArray1 = new object[] { prevStateType }; base.method_8("OnBirth", objArray1); } public GameObject m_EdgeGlow { get { return base.method_3<GameObject>("m_EdgeGlow"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AccountApi.Core.Services; using AccountApi.Core.Services.Responses; using AccountApi.DataAccess; using Moq; using NUnit.Framework; namespace AccountApi.Core.Tests { public class AccountCoreTests { [Test] public async Task GetUserInfo() { var accountDataAccessMoq = new Mock<IAccountDataAccess>(); var customerClientMoq = new Mock<ICustomerClient>(); var transactionClientMoq = new Mock<ITransactionClient>(); var accountCore = new AccountCore(accountDataAccessMoq.Object, customerClientMoq.Object, transactionClientMoq.Object); var expectedCustomer = new CustomerResponse { Name = "John", Surname = "Doe" }; var customerId = Guid.NewGuid(); var expectedAccount1 = new Account { Id = Guid.NewGuid(), CustomerId = customerId, Name = "Account01" }; var expectedAccount2 = new Account { Id = Guid.NewGuid(), CustomerId = customerId, Name = "Account02" }; var expectedAccount3 = new Account { Id = Guid.NewGuid(), CustomerId = customerId, Name = "Account03" }; var accountsList = new List<Account> { expectedAccount1, expectedAccount2, expectedAccount3 }; customerClientMoq.Setup(x => x.GetById(customerId.ToString())).Returns(async () => await Task.FromResult(expectedCustomer) ); accountDataAccessMoq.Setup(x => x.GetByCustomerId(customerId)).Returns(async () => await Task.FromResult(accountsList)); var expectedTransactions1 = new List<TransactionResponse> {new TransactionResponse { AccountId = expectedAccount1.Id, Amount = 50, Timestamp = DateTime.Now }, new TransactionResponse { AccountId = expectedAccount1.Id, Amount = 500, Timestamp = DateTime.Now }, new TransactionResponse { AccountId = expectedAccount1.Id, Amount = 500, Timestamp = DateTime.Now }}; transactionClientMoq.Setup(x => x.GetByAccountId(expectedAccount1.Id)).Returns(async () => await Task.FromResult(expectedTransactions1)); var expectedTransactions2 = new List<TransactionResponse> { new TransactionResponse { AccountId = expectedAccount2.Id, Amount = 25, Timestamp = DateTime.Now }, new TransactionResponse { AccountId = expectedAccount2.Id, Amount = 250, Timestamp = DateTime.Now }}; transactionClientMoq.Setup(x => x.GetByAccountId(expectedAccount2.Id)).Returns(async () => await Task.FromResult(expectedTransactions2)); var resultUserInfo = await accountCore.GetUserInfo(customerId); Assert.NotNull(resultUserInfo); var expectedTransactionsCount = expectedTransactions1.Count + expectedTransactions2.Count; Assert.AreEqual(expectedTransactionsCount, resultUserInfo.Accounts.SelectMany(x => x.Transactions).Count()); } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using System.IO; using System.Linq; using Gurock.TestRail; using Newtonsoft.Json.Linq; using System.Collections.Generic; namespace Inflectra.SpiraTest.AddOns.TestRailImporter { /// <summary> /// This is the code behind class for the utility that imports projects from /// HP Mercury Quality Center / TestDirector into Inflectra SpiraTest /// </summary> public class MainForm : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label5; private System.Windows.Forms.ComboBox cboProject; private System.Windows.Forms.TextBox txtPassword; private System.Windows.Forms.TextBox txtLogin; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnAuthenticate; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox txtServer; private System.Windows.Forms.Button btnNext; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; protected ImportForm importForm; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.GroupBox groupBox2; public System.Windows.Forms.CheckBox chkImportRequirements; public System.Windows.Forms.CheckBox chkImportTestCases; public System.Windows.Forms.CheckBox chkImportTestRuns; public System.Windows.Forms.CheckBox chkImportUsers; private CheckBox chkPassword; protected ProgressForm progressForm; /// <summary> /// The id of the selected test rail project /// </summary> public int TestRailProjectId { get; set; } public MainForm() { // // Required for Windows Form Designer support // InitializeComponent(); // Add any event handlers this.Closing += new CancelEventHandler(MainForm_Closing); //Set the initial state of any buttons this.btnNext.Enabled = false; //Create the other forms and set a handle to this form and the import form this.importForm = new ImportForm(); this.progressForm = new ProgressForm(); this.importForm.MainFormHandle = this; this.importForm.ProgressFormHandle = this.progressForm; this.progressForm.MainFormHandle = this; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.btnNext = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.chkPassword = new System.Windows.Forms.CheckBox(); this.label6 = new System.Windows.Forms.Label(); this.txtServer = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.btnAuthenticate = new System.Windows.Forms.Button(); this.cboProject = new System.Windows.Forms.ComboBox(); this.txtPassword = new System.Windows.Forms.TextBox(); this.txtLogin = new System.Windows.Forms.TextBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.chkImportUsers = new System.Windows.Forms.CheckBox(); this.chkImportTestRuns = new System.Windows.Forms.CheckBox(); this.chkImportTestCases = new System.Windows.Forms.CheckBox(); this.chkImportRequirements = new System.Windows.Forms.CheckBox(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // btnNext // this.btnNext.Location = new System.Drawing.Point(451, 74); this.btnNext.Name = "btnNext"; this.btnNext.Size = new System.Drawing.Size(115, 26); this.btnNext.TabIndex = 0; this.btnNext.Text = "Next >"; this.btnNext.Click += new System.EventHandler(this.btnNext_Click); // // btnCancel // this.btnCancel.Location = new System.Drawing.Point(326, 74); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(106, 26); this.btnCancel.TabIndex = 1; this.btnCancel.Text = "Cancel"; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // label1 // this.label1.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(19, 18); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(528, 27); this.label1.TabIndex = 6; this.label1.Text = "1. Connect to TestRail"; // // groupBox1 // this.groupBox1.Controls.Add(this.chkPassword); this.groupBox1.Controls.Add(this.label6); this.groupBox1.Controls.Add(this.txtServer); this.groupBox1.Controls.Add(this.label5); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.btnAuthenticate); this.groupBox1.Controls.Add(this.cboProject); this.groupBox1.Controls.Add(this.txtPassword); this.groupBox1.Controls.Add(this.txtLogin); this.groupBox1.ForeColor = System.Drawing.Color.Black; this.groupBox1.Location = new System.Drawing.Point(29, 55); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(576, 240); this.groupBox1.TabIndex = 10; this.groupBox1.TabStop = false; this.groupBox1.Text = "TestRail Configuration"; // // chkPassword // this.chkPassword.AutoSize = true; this.chkPassword.Location = new System.Drawing.Point(115, 128); this.chkPassword.Name = "chkPassword"; this.chkPassword.Size = new System.Drawing.Size(164, 21); this.chkPassword.TabIndex = 22; this.chkPassword.Text = "Remember Password"; this.chkPassword.UseVisualStyleBackColor = true; // // label6 // this.label6.Location = new System.Drawing.Point(29, 28); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(77, 18); this.label6.TabIndex = 21; this.label6.Text = "Server:"; this.label6.TextAlign = System.Drawing.ContentAlignment.TopRight; // // txtServer // this.txtServer.Location = new System.Drawing.Point(115, 28); this.txtServer.Name = "txtServer"; this.txtServer.Size = new System.Drawing.Size(403, 22); this.txtServer.TabIndex = 20; this.txtServer.Text = "http://myserver/qcbin"; // // label5 // this.label5.Location = new System.Drawing.Point(19, 175); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(154, 19); this.label5.TabIndex = 19; this.label5.Text = "Project:"; this.label5.TextAlign = System.Drawing.ContentAlignment.TopRight; // // label3 // this.label3.Location = new System.Drawing.Point(28, 103); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(77, 18); this.label3.TabIndex = 17; this.label3.Text = "Password:"; this.label3.TextAlign = System.Drawing.ContentAlignment.TopRight; // // label2 // this.label2.Location = new System.Drawing.Point(10, 65); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(96, 18); this.label2.TabIndex = 16; this.label2.Text = "User Name:"; this.label2.TextAlign = System.Drawing.ContentAlignment.TopRight; // // btnAuthenticate // this.btnAuthenticate.Location = new System.Drawing.Point(413, 128); this.btnAuthenticate.Name = "btnAuthenticate"; this.btnAuthenticate.Size = new System.Drawing.Size(105, 27); this.btnAuthenticate.TabIndex = 14; this.btnAuthenticate.Text = "Authenticate"; this.btnAuthenticate.Click += new System.EventHandler(this.btnAuthenticate_Click); // // cboProject // this.cboProject.Location = new System.Drawing.Point(182, 175); this.cboProject.Name = "cboProject"; this.cboProject.Size = new System.Drawing.Size(336, 24); this.cboProject.TabIndex = 13; // // txtPassword // this.txtPassword.Location = new System.Drawing.Point(115, 100); this.txtPassword.Name = "txtPassword"; this.txtPassword.PasswordChar = '*'; this.txtPassword.Size = new System.Drawing.Size(402, 22); this.txtPassword.TabIndex = 11; // // txtLogin // this.txtLogin.Location = new System.Drawing.Point(115, 65); this.txtLogin.Name = "txtLogin"; this.txtLogin.Size = new System.Drawing.Size(403, 22); this.txtLogin.TabIndex = 10; this.txtLogin.Text = "alex_alm"; // // groupBox2 // this.groupBox2.Controls.Add(this.chkImportUsers); this.groupBox2.Controls.Add(this.btnCancel); this.groupBox2.Controls.Add(this.chkImportTestRuns); this.groupBox2.Controls.Add(this.chkImportTestCases); this.groupBox2.Controls.Add(this.chkImportRequirements); this.groupBox2.Controls.Add(this.btnNext); this.groupBox2.ForeColor = System.Drawing.Color.Black; this.groupBox2.Location = new System.Drawing.Point(29, 314); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(576, 111); this.groupBox2.TabIndex = 12; this.groupBox2.TabStop = false; this.groupBox2.Text = "Import Options"; // // chkImportUsers // this.chkImportUsers.Checked = true; this.chkImportUsers.CheckState = System.Windows.Forms.CheckState.Checked; this.chkImportUsers.Location = new System.Drawing.Point(202, 55); this.chkImportUsers.Name = "chkImportUsers"; this.chkImportUsers.Size = new System.Drawing.Size(105, 28); this.chkImportUsers.TabIndex = 6; this.chkImportUsers.Text = "Users"; // // chkImportTestRuns // this.chkImportTestRuns.Location = new System.Drawing.Point(202, 28); this.chkImportTestRuns.Name = "chkImportTestRuns"; this.chkImportTestRuns.Size = new System.Drawing.Size(220, 27); this.chkImportTestRuns.TabIndex = 4; this.chkImportTestRuns.Text = "Test Runs"; // // chkImportTestCases // this.chkImportTestCases.Checked = true; this.chkImportTestCases.CheckState = System.Windows.Forms.CheckState.Checked; this.chkImportTestCases.Location = new System.Drawing.Point(19, 55); this.chkImportTestCases.Name = "chkImportTestCases"; this.chkImportTestCases.Size = new System.Drawing.Size(221, 28); this.chkImportTestCases.TabIndex = 3; this.chkImportTestCases.Text = "Test Cases"; this.chkImportTestCases.CheckedChanged += new System.EventHandler(this.chkImportTestCases_CheckedChanged); // // chkImportRequirements // this.chkImportRequirements.Checked = true; this.chkImportRequirements.CheckState = System.Windows.Forms.CheckState.Checked; this.chkImportRequirements.Location = new System.Drawing.Point(19, 28); this.chkImportRequirements.Name = "chkImportRequirements"; this.chkImportRequirements.Size = new System.Drawing.Size(221, 27); this.chkImportRequirements.TabIndex = 2; this.chkImportRequirements.Text = "Milestones"; // // pictureBox1 // this.pictureBox1.Image = global::Inflectra.SpiraTest.AddOns.TestRailImporter.Properties.Resources.TestRail_Icon; this.pictureBox1.Location = new System.Drawing.Point(566, 9); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(48, 46); this.pictureBox1.TabIndex = 11; this.pictureBox1.TabStop = false; // // MainForm // this.AutoScaleBaseSize = new System.Drawing.Size(6, 15); this.ClientSize = new System.Drawing.Size(619, 437); this.Controls.Add(this.groupBox2); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.groupBox1); this.Controls.Add(this.label1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.Name = "MainForm"; this.Text = "SpiraTest Importer for TestRail"; this.Load += new System.EventHandler(this.MainForm_Load); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { MiniDump.CreateMiniDump(); } /// <summary> /// Authenticates the user from the providing server/login/password information /// </summary> /// <param name="sender">The sending object</param> /// <param name="e">The event arguments</param> private void btnAuthenticate_Click(object sender, System.EventArgs e) { //Disable the next button this.btnNext.Enabled = false; //Make sure that a login was entered if (this.txtLogin.Text.Trim() == "") { MessageBox.Show ("You need to enter a login", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } //Make sure that a server was entered if (this.txtServer.Text.Trim() == "") { MessageBox.Show ("You need to enter the URL to your TestRail instance", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } try { //Instantiate the connection to TestRail (by getting a list of projects) APIClient testRailApi = new APIClient(this.txtServer.Text.Trim()); testRailApi.User = this.txtLogin.Text.Trim(); testRailApi.Password = this.txtPassword.Text.Trim(); JArray projects = (JArray)testRailApi.SendGet("get_projects"); if (projects.Count > 0) { MessageBox.Show("You have logged into TestRail Successfully", "Authentication", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("You have logged into TestRail successfully, but you don't have any projects to import!", "No Projects Found", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } //Now we need to populate the list of projects List<NameIdObject> projectsList = new List<NameIdObject>(); //Convert into a standard bindable list source for (int i = 0; i < projects.Count; i++) { NameIdObject project = new NameIdObject(); project.Id = projects[i]["id"].Value<string>(); project.Name = projects[i]["name"].Value<string>(); projectsList.Add(project); } //Sort by name projectsList = projectsList.OrderBy(p => p.Name).ToList(); this.cboProject.DisplayMember = "Name"; this.cboProject.DataSource = projectsList; //Enable the Next button this.btnNext.Enabled = true; } catch (APIException exception) { MessageBox.Show("Unable to access the TestRail API. The error message is: " + exception.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } catch (Exception exception) { MessageBox.Show("General error accessing the TestRail API. The error message is: " + exception.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } } /// <summary> /// Closes the application /// </summary> /// <param name="sender">The sending object</param> /// <param name="e">The event arguments</param> private void btnCancel_Click(object sender, System.EventArgs e) { //Close the application this.Close(); } /// <summary> /// Called if the form is closed /// </summary> /// <param name="sender">The sending object</param> /// <param name="e">The event arguments</param> private void MainForm_Closing(object sender, CancelEventArgs e) { //Nothing needs to be done } /// <summary> /// Called when the Next button is clicked. Switches to the second form /// </summary> /// <param name="sender">The sending object</param> /// <param name="e">The event arguments</param> private void btnNext_Click(object sender, System.EventArgs e) { //Store the info in settings for later Properties.Settings.Default.TestRailUrl = this.txtServer.Text.Trim(); Properties.Settings.Default.TestRailUserName = this.txtLogin.Text.Trim(); if (chkPassword.Checked) { Properties.Settings.Default.TestRailPassword = this.txtPassword.Text; //Don't trip in case it contains a space } else { Properties.Settings.Default.TestRailPassword = ""; } Properties.Settings.Default.Releases = this.chkImportRequirements.Checked; Properties.Settings.Default.TestCases = this.chkImportTestCases.Checked; Properties.Settings.Default.TestRuns = this.chkImportTestRuns.Checked; //Properties.Settings.Default.Attachments = this.chkImportAttachments.Checked; Properties.Settings.Default.Users = this.chkImportUsers.Checked; Properties.Settings.Default.Save(); //Always put the current password in settings after save, for use in current run Properties.Settings.Default.TestRailPassword = this.txtPassword.Text; //Don't trip in case it contains a space //Store the current test rail project id for use by the import thread this.TestRailProjectId = Int32.Parse(((NameIdObject)cboProject.SelectedItem).Id); //Hide the current form this.Hide(); //Show the second page in the import wizard this.importForm.Show(); } /// <summary> /// Change the active status of the test run import checkbox depending on this selection /// </summary> /// <param name="sender">The sending object</param> /// <param name="e">The event arguments</param> private void chkImportTestCases_CheckedChanged(object sender, System.EventArgs e) { this.chkImportTestRuns.Enabled = this.chkImportTestCases.Checked; this.chkImportTestRuns.Checked = false; } /// <summary> /// Populates the fields when the form is loaded /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainForm_Load(object sender, EventArgs e) { this.txtServer.Text = Properties.Settings.Default.TestRailUrl; this.txtLogin.Text = Properties.Settings.Default.TestRailUserName; if (String.IsNullOrEmpty(Properties.Settings.Default.TestRailPassword)) { this.chkPassword.Checked = false; this.txtPassword.Text = ""; } else { this.chkPassword.Checked = true; this.txtPassword.Text = Properties.Settings.Default.TestRailPassword; } this.chkImportRequirements.Checked = Properties.Settings.Default.Releases; this.chkImportTestCases.Checked = Properties.Settings.Default.TestCases; this.chkImportTestRuns.Checked = Properties.Settings.Default.TestRuns; //this.chkImportAttachments.Checked = Properties.Settings.Default.Attachments; this.chkImportUsers.Checked = Properties.Settings.Default.Users; } } }
using ImmedisHCM.Data.Entities; using ImmedisHCM.Data.Identity.Entities; using ImmedisHCM.Data.Infrastructure; using Microsoft.AspNetCore.Identity; using NHibernate.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography.X509Certificates; namespace ImmedisHCM.Services.Core { public class DatabaseSeeder : IDatabaseSeeder { private readonly IUnitOfWork _unitOfWork; private readonly UserManager<WebUser> _userManager; public DatabaseSeeder(IUnitOfWork unitOfWork, UserManager<WebUser> userManager) { _unitOfWork = unitOfWork; _userManager = userManager; } public void Seed() { //WARNING: DO NOT CHANGE CALL ORDER int locationStartIndex = 0; SeedCountries(); SeedCities(); SeedCurrency(); SeedScheduleType(); SeedSalaryType(); SeedCompanies(); SeedJobs(); SeedSalaries(); SeedLocation(); SeedEmergencyContacts(ref locationStartIndex); SeedDepartments(ref locationStartIndex); SeedEmployee(ref locationStartIndex); UpdateManagers(); } private void SeedCountries() { try { _unitOfWork.BeginTransaction(); var countryRepo = _unitOfWork.GetRepository<Country>(); var countryList = new List<Country>(); if (!countryRepo.Entity.Any()) { countryList.Add(new Country { Name = "Bulgaria", ShortName = "BG" }); countryList.Add(new Country { Name = "Ireland", ShortName = "IR" }); countryList.Add(new Country { Name = "England", ShortName = "EN" }); countryRepo.AddRange(countryList); } _unitOfWork.Commit(); } catch (Exception ex) { _unitOfWork.Rollback(); throw ex; } } private void SeedCities() { try { _unitOfWork.BeginTransaction(); var cityRepo = _unitOfWork.GetRepository<City>(); var countryRepo = _unitOfWork.GetRepository<Country>(); var countryList = countryRepo.Get(); var cityList = new List<City>(); if (!cityRepo.Entity.Any()) { var countryBulgaria = countryList.Single(x => x.Name == "Bulgaria"); cityList.Add(new City { Name = "Sofia", Country = countryBulgaria }); cityList.Add(new City { Name = "Varna", Country = countryBulgaria }); cityList.Add(new City { Name = "Burgas", Country = countryBulgaria }); var countryIreland = countryList.Single(x => x.Name == "Ireland"); cityList.Add(new City { Name = "Dublin", Country = countryIreland }); cityList.Add(new City { Name = "Cork", Country = countryIreland }); cityList.Add(new City { Name = "Galway", Country = countryIreland }); var countryEngland = countryList.Single(x => x.Name == "England"); cityList.Add(new City { Name = "London", Country = countryEngland }); cityList.Add(new City { Name = "Liverpool", Country = countryEngland }); cityList.Add(new City { Name = "Norwich", Country = countryEngland }); cityRepo.AddRange(cityList); } _unitOfWork.Commit(); } catch (Exception ex) { _unitOfWork.Rollback(); throw ex; } } private void SeedCurrency() { try { _unitOfWork.BeginTransaction(); var currencyRepo = _unitOfWork.GetRepository<Currency>(); if (!currencyRepo.Entity.Any()) { var currencyList = new List<Currency> { new Currency { Name = "BGN" }, new Currency { Name = "GBP" }, new Currency { Name = "EUR" } }; currencyRepo.AddRange(currencyList); } _unitOfWork.Commit(); } catch (Exception ex) { _unitOfWork.Rollback(); throw ex; } } private void SeedScheduleType() { try { _unitOfWork.BeginTransaction(); var scheduleTypeRepo = _unitOfWork.GetRepository<ScheduleType>(); if (!scheduleTypeRepo.Entity.Any()) { var scheduleTypeList = new List<ScheduleType>(); var date = DateTime.UtcNow; scheduleTypeList.Add(new ScheduleType { Name = "Morning Shift", Hours = 8, StartTime = new DateTime(date.Year, date.Month, date.Day, 9, 0, 0) }); scheduleTypeList.Add(new ScheduleType { Name = "Evening Shift", Hours = 8, StartTime = new DateTime(date.Year, date.Month, date.Day, 17, 0, 0) }); scheduleTypeList.Add(new ScheduleType { Name = "Night Shift", Hours = 8, StartTime = new DateTime(date.Year, date.Month, date.Day, 2, 0, 0) }); scheduleTypeRepo.AddRange(scheduleTypeList); } _unitOfWork.Commit(); } catch (Exception ex) { _unitOfWork.Rollback(); throw ex; } } private void SeedSalaryType() { try { _unitOfWork.BeginTransaction(); var salaryTypeRepo = _unitOfWork.GetRepository<SalaryType>(); if (!salaryTypeRepo.Entity.Any()) { var salaryTypeList = new List<SalaryType> { new SalaryType { Name = "Weekly" }, new SalaryType { Name = "Hourly" }, new SalaryType { Name = "Monthly" } }; salaryTypeRepo.AddRange(salaryTypeList); } _unitOfWork.Commit(); } catch (Exception ex) { _unitOfWork.Rollback(); throw ex; } } private void SeedCompanies() { try { _unitOfWork.BeginTransaction(); var companyRepo = _unitOfWork.GetRepository<Company>(); if (!companyRepo.Entity.Any()) { var companyList = new List<Company> { new Company { Name = "Ubisoft", LegalName = "Ubisoft LLC" }, new Company { Name = "Activision", LegalName = "Activision LLC" }, new Company { Name = "Bullfrog", LegalName = "Bullfrog LLC" } }; companyRepo.AddRange(companyList); } _unitOfWork.Commit(); } catch (Exception ex) { _unitOfWork.Rollback(); throw ex; } } private void SeedJobs() { try { _unitOfWork.BeginTransaction(); var jobsRepo = _unitOfWork.GetRepository<Job>(); var scheduleList = _unitOfWork.GetRepository<ScheduleType>().Get(); if (!jobsRepo.Entity.Any() && scheduleList.Any()) { var jobsList = new List<Job>(); var dayShift = scheduleList.Single(x => x.Name == "Morning Shift"); jobsList.Add(new Job { Name = "Programmer", MinimalSalary = 900M, MaximumSalary = 1500M, ScheduleType = dayShift }); jobsList.Add(new Job { Name = "IT Specialist", MinimalSalary = 800M, MaximumSalary = 1600M, ScheduleType = dayShift }); jobsList.Add(new Job { Name = "Security", MinimalSalary = 900M, MaximumSalary = 1500M, ScheduleType = dayShift }); jobsRepo.AddRange(jobsList); } _unitOfWork.Commit(); } catch (Exception ex) { _unitOfWork.Rollback(); throw ex; } } private void SeedLocation() { try { _unitOfWork.BeginTransaction(); var locationRepo = _unitOfWork.GetRepository<Location>(); var cityList = _unitOfWork.GetRepository<City>().Get(); if (!locationRepo.Entity.Any()) { string[] lines = ReadLinesFromFile("Addresses.txt"); if (lines.Length != 63) throw new Exception("Number of addresses should be 63"); var postalCodes = new List<string>(64); var addressLines = new List<string>(64); for (int i = 0; i < lines.Length; i++) { int postalCodeIndex = lines[i].IndexOf(" "); postalCodes.Add(lines[i].Substring(0, postalCodeIndex)); addressLines.Add(lines[i][postalCodeIndex..]); } Random rnd = new Random(); var locationList = new List<Location>(); int cityCount = cityList.Count; for (int i = 0; i < lines.Length; i++) locationList.Add(new Location { AddressLine1 = addressLines[i], PostalCode = postalCodes[i], City = cityList[rnd.Next(0, cityCount)], }); locationRepo.AddRange(locationList); } _unitOfWork.Commit(); } catch (Exception ex) { _unitOfWork.Rollback(); throw ex; } } private void SeedEmergencyContacts(ref int locationStartIndex) { try { _unitOfWork.BeginTransaction(); var emergencyContactRepo = _unitOfWork.GetRepository<EmergencyContact>(); var locationList = _unitOfWork.GetRepository<Location>().Get(); if (!emergencyContactRepo.Entity.Any()) { string[] randomNames = ReadLinesFromFile("RandomNames.txt"); string[] randomPhoneNumbers = ReadLinesFromFile("RandomECPhoneNumbers.txt"); var firstNames = new List<string>(); var lastName = new List<string>(); for (int i = 0; i < randomNames.Length; i++) { int whitespaceIndex = randomNames[i].IndexOf(" "); firstNames.Add(randomNames[i].Substring(0, whitespaceIndex)); lastName.Add(randomNames[i][whitespaceIndex..]); } var emergencyContactList = new List<EmergencyContact>(); for (int i = 0; i < 27; i++) { emergencyContactList.Add(new EmergencyContact { FirstName = firstNames[i], LastName = lastName[i], PhoneNumber = randomPhoneNumbers[i], Location = locationList[locationStartIndex] }); locationStartIndex++; } emergencyContactRepo.AddRange(emergencyContactList); } _unitOfWork.Commit(); } catch (Exception ex) { _unitOfWork.Rollback(); throw ex; } } private void SeedDepartments(ref int locationStartIndex) { try { _unitOfWork.BeginTransaction(); var departmentRepo = _unitOfWork.GetRepository<Department>(); var companyList = _unitOfWork.GetRepository<Company>().Get(); var locationList = _unitOfWork.GetRepository<Location>().Get(); if (!departmentRepo.Entity.Any()) { var departmentList = new List<Department> { new Department { Name = "IT", Location = locationList[locationStartIndex++], Company = companyList[0] }, new Department { Name = "Financial", Location = locationList[locationStartIndex++], Company = companyList[0] }, new Department { Name = "Software", Location = locationList[locationStartIndex++], Company = companyList[0] }, new Department { Name = "IT", Location = locationList[locationStartIndex++], Company = companyList[1] }, new Department { Name = "Security", Location = locationList[locationStartIndex++], Company = companyList[1] }, new Department { Name = "HR", Location = locationList[locationStartIndex++], Company = companyList[1] }, new Department { Name = "IDK", Location = locationList[locationStartIndex++], Company = companyList[2] }, new Department { Name = "Management", Location = locationList[locationStartIndex++], Company = companyList[2] }, new Department { Name = "IT", Location = locationList[locationStartIndex++], Company = companyList[2] } }; departmentRepo.AddRange(departmentList); } _unitOfWork.Commit(); } catch (Exception ex) { _unitOfWork.Rollback(); throw ex; } } private void SeedSalaries() { try { _unitOfWork.BeginTransaction(); var salaryRepo = _unitOfWork.GetRepository<Salary>(); var salaryTypeList = _unitOfWork.GetRepository<SalaryType>().Get(); var currencyList = _unitOfWork.GetRepository<Currency>().Get(); if (!salaryRepo.Entity.Any()) { var salaryList = new List<Salary>(); Random rnd = new Random(); int min = 800; int max = 1600; int typeCount = salaryTypeList.Count; int currencyCount = currencyList.Count; for (int i = 0; i < 27; i++) { salaryList.Add(new Salary { Amount = rnd.Next(min, max), SalaryType = salaryTypeList[rnd.Next(0, typeCount)], Currency = currencyList[rnd.Next(0, currencyCount)] }); } salaryRepo.AddRange(salaryList); } _unitOfWork.Commit(); } catch (Exception ex) { _unitOfWork.Rollback(); throw ex; } } private void SeedEmployee(ref int locationStartIndex) { try { _unitOfWork.BeginTransaction(); var employeeRepo = _unitOfWork.GetRepository<Employee>(); var jobList = _unitOfWork.GetRepository<Job>().Get(); var departmentList = _unitOfWork.GetRepository<Department>().Get(); var salaryList = _unitOfWork.GetRepository<Salary>().Get(); var locationList = _unitOfWork.GetRepository<Location>().Get(); var emergencyContactList = _unitOfWork.GetRepository<EmergencyContact>().Get(); if (!employeeRepo.Entity.Any()) { string[] emails = ReadLinesFromFile("RandomEmails.txt"); string[] randomNames = ReadLinesFromFile("RandomNames.txt"); string[] randomEmpPhoneNumbers = ReadLinesFromFile("RandomEmpPhoneNumbers.txt"); string password = "P@ssw0rd"; var employeeList = new List<Employee>(); var firstNames = new List<string>(); var lastName = new List<string>(); for (int i = 0; i < randomNames.Length; i++) { int whitespaceIndex = randomNames[i].IndexOf(" "); firstNames.Add(randomNames[i].Substring(0, whitespaceIndex)); lastName.Add(randomNames[i][whitespaceIndex..]); } int departmentIndex = 0; Random rnd = new Random(); for (int i = 0; i < 27; i += 3) { //3 per department -> 9 per company var manager = new WebUser { Email = emails[i], UserName = emails[i] }; _userManager.CreateAsync(manager, password).Wait(); _userManager.AddToRoleAsync(manager, "Manager").Wait(); _userManager.CreateAsync(new WebUser { Email = emails[i + 1], UserName = emails[i + 1] }, password).Wait(); _userManager.CreateAsync(new WebUser { Email = emails[i + 2], UserName = emails[i + 2] }, password).Wait(); var department = departmentList[departmentIndex]; int randomNameIndex = rnd.Next(0, randomNames.Length); employeeList.Add(new Employee { Email = emails[i], PhoneNumber = randomEmpPhoneNumbers[i], FirstName = firstNames[randomNameIndex], LastName = lastName[randomNameIndex], Department = department, EmergencyContact = emergencyContactList[i], HrId = Guid.NewGuid(), Job = jobList[rnd.Next(0, jobList.Count)], Location = locationList[locationStartIndex++], Salary = salaryList[i], HiredDate = DateTime.UtcNow }); randomNameIndex = rnd.Next(0, randomNames.Length); employeeList.Add(new Employee { Email = emails[i + 1], PhoneNumber = randomEmpPhoneNumbers[i + 1], FirstName = firstNames[randomNameIndex], LastName = lastName[randomNameIndex], Department = department, EmergencyContact = emergencyContactList[i + 1], HrId = Guid.NewGuid(), Job = jobList[rnd.Next(0, jobList.Count)], Location = locationList[locationStartIndex++], Salary = salaryList[i + 1], HiredDate = DateTime.UtcNow }); randomNameIndex = rnd.Next(0, randomNames.Length); employeeList.Add(new Employee { Email = emails[i + 2], PhoneNumber = randomEmpPhoneNumbers[i + 2], FirstName = firstNames[randomNameIndex], LastName = lastName[randomNameIndex], Department = department, EmergencyContact = emergencyContactList[i + 2], HrId = Guid.NewGuid(), Job = jobList[rnd.Next(0, jobList.Count)], Location = locationList[locationStartIndex++], Salary = salaryList[i + 2], HiredDate = DateTime.UtcNow }); departmentIndex++; } employeeRepo.AddRange(employeeList); } _unitOfWork.Commit(); } catch (Exception ex) { _unitOfWork.Rollback(); throw ex; } } private void UpdateManagers() { try { _unitOfWork.BeginTransaction(); var departmentRepo = _unitOfWork.GetRepository<Department>(); var employeeRepo = _unitOfWork.GetRepository<Employee>(); var managerUsers = _userManager.GetUsersInRoleAsync("Manager").Result .Select(x => x.Email) .ToList(); if (managerUsers.Count > 0 && !employeeRepo.Entity.Any(x => x.Manager != null)) { var employees = employeeRepo.Get(fetch: x => x.Fetch(y => y.Department)); var managers = employees.Where(x => managerUsers.Any(y => x.Email.Contains(y))).ToList(); var departments = departmentRepo.Get(); for (int i = 0; i < departments.Count; i++) { departments[i].Manager = managers[i]; departmentRepo.Update(departments[i]); } int managerIndex = 0; for (int i = 0; i < employees.Count; i += 3) { employees[i + 1].Manager = managers[managerIndex]; employeeRepo.Update(employees[i + 1]); employees[i + 2].Manager = managers[managerIndex]; employeeRepo.Update(employees[i + 2]); managerIndex++; } } _unitOfWork.Commit(); } catch (Exception ex) { _unitOfWork.Rollback(); throw ex; } } private string[] ReadLinesFromFile(string filename) { return File.ReadAllLines(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Core\SeedResources", filename)); } } }
using Psub.DataAccess.Abstract; using Psub.DataService.Abstract; using Psub.DataService.CommonViewModels; using Psub.DataService.HandlerPerQuery.PublicationProcess.Entities; using Psub.Domain.Entities; using UESPDataManager.DataService.HandlerPerQuery.Abstract; using System.Linq; using AutoMapper; namespace Psub.DataService.HandlerPerQuery.PublicationProcess.Handlers { public class PublicationEditGetHandler : IQueryHandler<PublicationEditGetQuery, PublicationEditViewModel> { private readonly IRepository<Publication> _publicationRepository; private readonly IUserService _userService; private readonly IRepository<Section> _sectionRepository; public PublicationEditGetHandler(IRepository<Publication> publicationRepository, IUserService userService, IRepository<Section> sectionRepository) { _publicationRepository = publicationRepository; _userService = userService; _sectionRepository = sectionRepository; } public PublicationEditViewModel Handle(PublicationEditGetQuery catalog) { var currentDocument = _publicationRepository.Get(catalog.Id); if (currentDocument == null || !_userService.IsAdmin()) return null; var result = Mapper.Map<Publication, PublicationEditViewModel>(currentDocument); result.Section = new DropDownSelectorViewModel { Items = _sectionRepository.Query().Select(m => new DropDownItem() { Id = m.Id, Name = m.Name }).ToList(), Id = result.Section.Id }; return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RGiesecke.DllExport; using System.Runtime.InteropServices; using System.Text.RegularExpressions; namespace re { public static partial class re { // ********************************************************** // Matches str /// <summary> /// /// </summary> /// <param name="matchesOut"></param> /// <param name="re"></param> /// <param name="input"></param> [DllExport("Regex.Matches")] public static void RegexMatches( out wrap matchesOut, Regex re, [MarshalAs(UnmanagedType.LPWStr)] string input ) { wrap w = new wrap() { o = re.Matches(input) }; GC.SuppressFinalize(w); matchesOut = w; } /// <summary> /// /// </summary> /// <param name="matchesOut"></param> /// <param name="re"></param> /// <param name="input"></param> [DllExport("Regex.MatchesT")] public static void RegexMatchesT( out wrap matchesOut, Regex re, [MarshalAs(UnmanagedType.LPTStr)] string input ) { wrap w = new wrap() { o = re.Matches(input) }; GC.SuppressFinalize(w); matchesOut = w; } /// <summary> /// /// </summary> /// <param name="matchesOut"></param> /// <param name="re"></param> /// <param name="input"></param> [DllExport("Regex.MatchesA")] public static void RegexMatchesA( out wrap matchesOut, Regex re, [MarshalAs(UnmanagedType.LPStr)] string input ) { wrap w = new wrap() { o = re.Matches(input) }; GC.SuppressFinalize(w); matchesOut = w; } // ********************************************************** // Matches str, startat /// <summary> /// /// </summary> /// <param name="matchesOut"></param> /// <param name="re"></param> /// <param name="input"></param> /// <param name="startat"></param> [DllExport("Regex.Matches_startat")] public static void RegexMatches_startat( out wrap matchesOut, Regex re, [MarshalAs(UnmanagedType.LPWStr)] string input, [MarshalAs(UnmanagedType.I4)] int startat ) { wrap w = new wrap() { o = re.Matches(input, startat) }; GC.SuppressFinalize(w); matchesOut = w; } /// <summary> /// /// </summary> /// <param name="matchesOut"></param> /// <param name="re"></param> /// <param name="input"></param> /// <param name="startat"></param> [DllExport("Regex.Matches_startatT")] public static void RegexMatches_startatT( out wrap matchesOut, Regex re, [MarshalAs(UnmanagedType.LPTStr)] string input, [MarshalAs(UnmanagedType.I4)] int startat ) { wrap w = new wrap() { o = re.Matches(input, startat) }; GC.SuppressFinalize(w); matchesOut = w; } /// <summary> /// /// </summary> /// <param name="matchesOut"></param> /// <param name="re"></param> /// <param name="input"></param> /// <param name="startat"></param> [DllExport("Regex.Matches_startatA")] public static void RegexMatches_startatA( out wrap matchesOut, Regex re, [MarshalAs(UnmanagedType.LPStr)] string input, [MarshalAs(UnmanagedType.I4)] int startat ) { wrap w = new wrap() { o = re.Matches(input, startat) }; GC.SuppressFinalize(w); matchesOut = w; } // ********************************************************** // Matches str, str /// <summary> /// /// </summary> /// <param name="matchesOut"></param> /// <param name="input"></param> /// <param name="pattern"></param> [DllExport("Matches")] public static void reMatches( out wrap matchesOut, [MarshalAs(UnmanagedType.LPWStr)] string input, [MarshalAs(UnmanagedType.LPWStr)] string pattern ) { wrap w = new wrap() { o = Regex.Matches(input, pattern) }; GC.SuppressFinalize(w); matchesOut = w; } /// <summary> /// /// </summary> /// <param name="matchesOut"></param> /// <param name="input"></param> /// <param name="pattern"></param> [DllExport("MatchesT")] public static void reMatchesT( out wrap matchesOut, [MarshalAs(UnmanagedType.LPTStr)] string input, [MarshalAs(UnmanagedType.LPTStr)] string pattern ) { wrap w = new wrap() { o = Regex.Matches(input, pattern) }; GC.SuppressFinalize(w); matchesOut = w; } /// <summary> /// /// </summary> /// <param name="matchesOut"></param> /// <param name="input"></param> /// <param name="pattern"></param> [DllExport("MatchesA")] public static void reMatchesA( out wrap matchesOut, [MarshalAs(UnmanagedType.LPStr)] string input, [MarshalAs(UnmanagedType.LPStr)] string pattern ) { wrap w = new wrap() { o = Regex.Matches(input, pattern) }; GC.SuppressFinalize(w); matchesOut = w; } // ********************************************************** // Matches str, str, options /// <summary> /// /// </summary> /// <param name="matchesOut"></param> /// <param name="input"></param> /// <param name="pattern"></param> /// <param name="options"></param> [DllExport("Matches_opt")] public static void reMatches_opt( out wrap matchesOut, [MarshalAs(UnmanagedType.LPWStr)] string input, [MarshalAs(UnmanagedType.LPWStr)] string pattern, [MarshalAs(UnmanagedType.I4)] RegexOptions options ) { wrap w = new wrap() { o = Regex.Matches(input, pattern, options) }; GC.SuppressFinalize(w); matchesOut = w; } /// <summary> /// /// </summary> /// <param name="matchesOut"></param> /// <param name="input"></param> /// <param name="pattern"></param> /// <param name="options"></param> [DllExport("Matches_optT")] public static void reMatches_optT( out wrap matchesOut, [MarshalAs(UnmanagedType.LPTStr)] string input, [MarshalAs(UnmanagedType.LPTStr)] string pattern, [MarshalAs(UnmanagedType.I4)] RegexOptions options ) { wrap w = new wrap() { o = Regex.Matches(input, pattern, options) }; GC.SuppressFinalize(w); matchesOut = w; } /// <summary> /// /// </summary> /// <param name="matchesOut"></param> /// <param name="input"></param> /// <param name="pattern"></param> /// <param name="options"></param> [DllExport("Matches_optA")] public static void reMatches_optA( out wrap matchesOut, [MarshalAs(UnmanagedType.LPStr)] string input, [MarshalAs(UnmanagedType.LPStr)] string pattern, [MarshalAs(UnmanagedType.I4)] RegexOptions options ) { wrap w = new wrap() { o = Regex.Matches(input, pattern, options) }; GC.SuppressFinalize(w); matchesOut = w; } // ********************************************************** // Matches str, str, options, time /// <summary> /// /// </summary> /// <param name="matchesOut"></param> /// <param name="input"></param> /// <param name="pattern"></param> /// <param name="options"></param> /// <param name="timeSpan"></param> [DllExport("Matches_opt_time")] public static void reMatches_opt_time( out wrap matchesOut, [MarshalAs(UnmanagedType.LPWStr)] string input, [MarshalAs(UnmanagedType.LPWStr)] string pattern, [MarshalAs(UnmanagedType.I4)] RegexOptions options, [MarshalAs(UnmanagedType.I4)] TimeSpan timeSpan ) { wrap w = new wrap() { o = Regex.Matches(input, pattern, options, timeSpan) }; GC.SuppressFinalize(w); matchesOut = w; } /// <summary> /// /// </summary> /// <param name="matchesOut"></param> /// <param name="input"></param> /// <param name="pattern"></param> /// <param name="options"></param> /// <param name="timeSpan"></param> [DllExport("Matches_opt_timeT")] public static void reMatches_opt_timeT( out wrap matchesOut, [MarshalAs(UnmanagedType.LPTStr)] string input, [MarshalAs(UnmanagedType.LPTStr)] string pattern, [MarshalAs(UnmanagedType.I4)] RegexOptions options, [MarshalAs(UnmanagedType.I4)] TimeSpan timeSpan ) { wrap w = new wrap() { o = Regex.Matches(input, pattern, options, timeSpan) }; GC.SuppressFinalize(w); matchesOut = w; } /// <summary> /// /// </summary> /// <param name="matchesOut"></param> /// <param name="input"></param> /// <param name="pattern"></param> /// <param name="options"></param> /// <param name="timeSpan"></param> [DllExport("Matches_opt_timeA")] public static void reMatches_opt_timeA( out wrap matchesOut, [MarshalAs(UnmanagedType.LPStr)] string input, [MarshalAs(UnmanagedType.LPStr)] string pattern, [MarshalAs(UnmanagedType.I4)] RegexOptions options, [MarshalAs(UnmanagedType.I4)] TimeSpan timeSpan ) { wrap w = new wrap() { o = Regex.Matches(input, pattern, options, timeSpan) }; GC.SuppressFinalize(w); matchesOut = w; } // ********************************************************** // Matches for /// <summary> /// /// </summary> /// <param name="wMatch"></param> public delegate void matchesForCb(wrap wMatch); /// <summary> /// /// </summary> /// <param name="wMatches"></param> /// <param name="cb"></param> [DllExport("Matches.For")] public static void matchesFor(wrap wMatches, matchesForCb cb) { MatchCollection matches = (MatchCollection)wMatches.o; wrap wMatch = new wrap(); int len = matches.Count; int i = 0; for (i = 0; i < len; i++) { wMatch.o = matches[i]; cb(wMatch); } } /// <summary> /// /// </summary> /// <param name="w"></param> [DllExport("Matches.Free")] public static void matchesFree(wrap w) { w.o = null; GC.ReRegisterForFinalize(w); } } }
using System; using System.Collections.Generic; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.ID; using Terraria.ModLoader; using TheMinepack.Items; namespace TheMinepack.Items.Weapons { public class SwordOfMeteors : ModItem { public override bool Autoload(ref string name, ref string texture, IList<EquipType> equips) { texture = "TheMinepack/Items/Weapons/SwordOfMeteors"; return true; } public override void SetDefaults() { // Item Details item.name = "Sword of Meteors"; AddTooltip("Fires meteor waves at foes"); item.width = 50; item.height = 50; item.rare = 4; item.value = Item.sellPrice(0, 5, 0, 0); // Item Animations & Sounds item.UseSound = SoundID.Item15; item.useTime = 20; item.useAnimation = 20; item.useStyle = 1; // Item Stats item.melee = true; item.damage = 30; item.knockBack = 2; // Item Functionality item.useTurn = true; item.autoReuse = true; item.shoot = mod.ProjectileType("MeteorSlash"); item.shootSpeed = 10; } public override void OnHitNPC(Player player, NPC target, int damage, float knockback, bool crit) { target.AddBuff(BuffID.OnFire, 300); // Inflicts On Fire! Debuff for 5 seconds } public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(ItemID.MeteoriteBar, 20); // 20 Meteorite Bars recipe.AddIngredient(ItemID.Obsidian, 10); // 10 Obsidian recipe.AddIngredient(ItemID.FallenStar, 5); // 5 Fallen Stars recipe.AddIngredient(ItemID.MagmaStone, 1); // 1 Magma Stone recipe.AddTile(TileID.Anvils); // Anvils recipe.SetResult(this); recipe.AddRecipe(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BossController : AttachableObject { public List<BossWeakpoint> weakpoints; private List<ActionBased> actionList; public GameObject popupSpawner; private AutoQueue _BossMainQueue = new AutoQueue(); // Start is called before the first frame update void Start() { actionList = GenerateActionList(); UpdateBossRotation(); //_BossMainQueue.AddAction(new GroupAction(new IAction[] { new BossWalkAction(gameObject) })); } // Update is called once per frame void Update() { if (_BossMainQueue.GetQueue().Count.Equals(0)) { actionList = GenerateActionList(); _BossMainQueue.AddAction(actionList[Random.Range(0, actionList.Count)]); } } List<ActionBased> GenerateActionList() { return new List<ActionBased>() { new BossWalkAction(gameObject), new BossJumpAction(gameObject, true), new BossJumpAction(gameObject), new BossShootPopup(popupSpawner), new BossSummonerCactus(Random.insideUnitCircle.normalized * 65, 10f, 180f), new BossSummonerBird(Random.insideUnitCircle.normalized * 80), new BossSummonerEnemy(Random.insideUnitCircle.normalized * 80, 50) }; } void UpdateBossRotation() { GameObject planet = GameManager.GetInstance().GetPlanet(); Vector2 between = transform.position - planet.transform.position; Vector2 ninetyDegrees = Vector2.Perpendicular(between) * -1; float angle = Mathf.Atan2(ninetyDegrees.y, ninetyDegrees.x) * Mathf.Rad2Deg; transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward); } public void RemoveWeakpoint(BossWeakpoint weakpoint) { weakpoints.Remove(weakpoint); if (weakpoints.Count == 0) { this.Dead(); } } private void Dead() { GameManager.GetInstance().DoBossDead(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model { class Cart : MovableObject { private char _toChar; public Cart(Tile initialTile) { this.Spot = initialTile; _toChar = 'F'; } public override Direction WayToMove() { if (Spot.GetType().Equals(typeof(Start))) { return Direction.Right; } if (Spot.GetType().Equals(typeof(Warehouse))) { if (Spot.TileToLeft.GetType().Equals(typeof(EmptyTile))) return Direction.Still; if (Spot.TileToLeft.IsEmpty()) return Direction.Left; } if (Spot.GetType().Equals(typeof(Track))) { if (Spot.TileToLeft == null) { return Direction.Remove; } if (Spot.TileToLeft.GetType().Equals(typeof(Warehouse)) && Spot.TileToLeft.Content != null) return Direction.Still; if (Spot.TileAbove.GetType().Equals(typeof(Water)) || Spot.TileAbove.GetType().Equals(typeof(Dock))) return Direction.Left; if (Spot.TileAbove.GetType().Equals(typeof(Track)) && Spot.TileToLeft.TileToLeft.TileToLeft.GetType().Equals(typeof(Warehouse))) return Direction.Left; if (Spot.TileAbove.GetType().Equals(typeof(Track)) && Spot.TileBelow.GetType().Equals(typeof(Switch)) && Spot.TileToRight.GetType().Equals(typeof(EmptyTile)) && Spot.TileToRight.TileToRight.GetType().Equals(typeof(EmptyTile))) return Direction.Up; if (Spot.TileToRight.GetType().Equals(typeof(Track))) { Tile targetTile = Spot.NeighbourInDirection(Direction.Right); if (!targetTile.IsEmpty()) { return Direction.Still; } if (targetTile.IsEmpty() && !targetTile.GetType().Equals(typeof(EmptyTile))) { return Direction.Right; } else return Direction.Still; } if (Spot.TileAbove.GetType().Equals(typeof(Switch))) { Tile targetTile = Spot.NeighbourInDirection(Direction.Up); if (targetTile.ToChar().Equals('\\')) return Direction.Still; ; if (targetTile.ToChar().Equals('/')) { return Direction.Up; } else return Direction.Still; } if (Spot.TileBelow.GetType().Equals(typeof(Switch))) { Tile targetTile = Spot.NeighbourInDirection(Direction.Down); if (targetTile.ToChar().Equals('\\')) { return Direction.Down; } if (targetTile.ToChar().Equals('/')) return Direction.Still; else return Direction.Still; } if (Spot.TileToRight.GetType().Equals(typeof(Switch))) { Tile targetTile = Spot.NeighbourInDirection(Direction.Right); if (targetTile.ToChar().Equals('S')) { return Direction.Still; } else return Direction.Right; } if (Spot.TileToRight.GetType().Equals(typeof(EmptyTile)) && Spot.TileBelow.GetType().Equals(typeof(EmptyTile)) && !Spot.TileToLeft.TileToLeft.TileToLeft.GetType().Equals(typeof(Warehouse))) return Direction.Up; if (Spot.TileToRight.GetType().Equals(typeof(EmptyTile)) && Spot.TileToLeft.GetType().Equals(typeof(EmptyTile))) return Direction.Up; if (Spot.TileBelow.GetType().Equals(typeof(Track)) && Spot.TileAbove.GetType().Equals(typeof(EmptyTile))) return Direction.Down; } if (Spot.GetType().Equals(typeof(Switch))) { Tile targetTile = Spot.NeighbourInDirection(Direction.Down); if (Spot.TileToRight.GetType().Equals(typeof(Track))) { return Direction.Right; } Switch Tile = (Switch)Spot; if (Tile.ToDirection().Equals(SwitchDirection.UP)) return Direction.Up; if (Tile.ToDirection().Equals(SwitchDirection.DOWN)) return Direction.Down; } return Direction.Still; } public bool checkGameOver() { if (Spot.GetType().Equals(typeof(Start))) { if (Spot.TileToRight.Content != null) { if (Spot.TileToRight.Content.ToChar().Equals('W')) return true; } } else if (!Spot.GetType().Equals(typeof(Warehouse))) { if (Spot.TileToLeft == null) return false; if (Spot.TileToRight.Content != null) { if (Spot.TileToRight.Content.ToChar().Equals('W')) return true; } if (Spot.TileToLeft.Content != null) { if (Spot.TileToLeft.Content.ToChar().Equals('W')) return true; } } return false; } public override void MakeMove(Direction richting) { Tile targetTile = Spot.NeighbourInDirection(richting); var Tile = (Tile)targetTile; Tile.Place(this); Spot.Remove(); Spot = Tile; } public bool checkScore() { if (Spot.TileAbove.GetType().Equals(typeof(Dock)) && Spot.TileAbove.TileAbove.Content != null) { _toChar = 'E'; return true; } return false; } public override char ToChar() { return _toChar; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Model.DataEntity; namespace Model.InvoiceManagement.Validator { public static partial class ExtensionMethods { public const String __InvoiceNoPattern = "([A-Za-z]{2})([0-9]{8})"; public static Exception OrganizationValueCheck(this Organization dataItem) { if (String.IsNullOrEmpty(dataItem.CompanyName)) { //檢查名稱 return new Exception("請輸入公司名稱!!"); } if (String.IsNullOrEmpty(dataItem.ReceiptNo)) { //檢查名稱 return new Exception("請輸入公司統編!!"); } if (String.IsNullOrEmpty(dataItem.Addr)) { //檢查名稱 return new Exception("請輸入公司地址!!"); } if (String.IsNullOrEmpty(dataItem.Phone)) { //檢查名稱 return new Exception("請輸入公司電話!!"); } Regex reg = new Regex("\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"); if (String.IsNullOrEmpty(dataItem.ContactEmail) || !reg.IsMatch(dataItem.ContactEmail)) { //檢查email return new Exception("電子信箱尚未輸入或輸入錯誤!!"); } return null; } public static Match ParseInvoiceNo(this String invoiceNo) { return Regex.Match(invoiceNo ?? "", __InvoiceNoPattern); } } }
using HelperLibrary.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HelperLibrary.Models.Interfaces; namespace HelperLibrary.Models { public class StudentModel : IPerson, ITable { public StudentModel(string firstname, string lastname, string email, string phone, int groupId) { St_First_Name = firstname; St_Last_Name = lastname; Email = email; Phone = phone; GroupNumberId = groupId; } public StudentModel() {} public int Id { get; set; } public string St_First_Name { get; set; } public string St_Last_Name { get; set; } public string Email { get; set; } public string Phone { get; set; } public int GroupNumberId { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using TachyHealth.Models; namespace TachyHealth.ViewModel { public class UsersViewModel { public IList<ApplicationUser> Users; public UsersViewModel() { Users = new List<ApplicationUser>(); } } }
using System; using System.Collections.Generic; using System.Text; namespace Football.DAL.Entities { public enum TrainingType { Interval, Game, Speed, RepeatedSprint } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using TestFramework; namespace SeleniumTests { [TestClass] public class AddMessagePageTests { [TestInitialize] public void SetUp() { Browser.Open(); } [TestMethod] public void Can_Go_To_AddMessage_Page() { Pages.AddMessagePage.Goto(); Assert.IsTrue(Pages.AddMessagePage.IsAt()); } [TestMethod] public void Can_Add_Message() { Pages.AddMessagePage.Goto(); Assert.IsTrue(Pages.AddMessagePage.IsMessageAdded()); } [TestCleanup] public void CleanUp() { Browser.Close(); } } }
using Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataAccess.Interfaces { /// <summary> /// Interface usada como contrato para resolver /// la logica de negocio para los clientes newshore /// </summary> public interface IClientDao { /// <summary> /// Metodo encargado de obtener tdos los clientes /// </summary> /// <param name="path">ruta donde se encuentra el archivo de cleintes</param> /// <returns></returns> IEnumerable<Client> GetClients(String path, char separator); /// <summary> /// Metodo encargado de grabar una colleccion de cleintes en el archivo /// correspodniente /// </summary> /// <param name="ClientsSave">colleccion de clientes a grabar</param> /// <param name="separator">archivo a grabar</param> /// <returns></returns> Boolean SaveClients(IEnumerable<Client> clients,String fullName, char separator); /// <summary> /// Lee las clientes desde un arreglo bytes que contiene la inforamcion /// </summary> /// <param name="bytes">arreglo de bytes</param> /// <param name="separator">separador</param> /// <returns></returns> IEnumerable<Client> ReadClientBytes(byte[] bytes, char separator); } }
using System.Linq; using System.Threading.Tasks; using AutoMapper; using IMDB.Api.Services.Interfaces; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using ResponseDto = IMDB.Api.Models.ResponseDto; using ViewModel = IMDB.Api.Models.ViewModel; namespace IMDB.Api.Controllers { //[Authorize] [Route("api/users")] public class UserController : GenericController<ResponseDto.User, Entities.User> { readonly IMapper _mapper; readonly ICacheService _cacheService; readonly IUserService _service; public UserController(IMapper mapper, ICacheService cacheService, IUserService service) : base(mapper, cacheService, service) { _mapper = mapper; _cacheService = cacheService; _service = service; } [HttpPut("{id}")] public async Task<IActionResult> Update(long id, [FromBody] ViewModel.User viewModel) { return await base.Update(id, viewModel); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ChangeJavaToC : AndroidJavaProxy { public ChangeJavaToC() : base("com.amap.api.location.AMapLocationListener"){ } public delegate void DelegateOnLocationChanged(AndroidJavaObject amap); public event DelegateOnLocationChanged locationChanged; void onLocationChanged(AndroidJavaObject amapLocation) { if (locationChanged != null) { locationChanged(amapLocation); } } }
/* Copyright 2018 | 2153735 ONTARIO LTD | https://Stru.ca 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. */ #region Namespaces using System; using System.Diagnostics; using System.IO; #endregion namespace StruCa.Structureˉui.BuildˉandˉDeploy { public static class Processes { public static void Execute(string Processˉname, string Arguments = null, string Workingˉdirectory = null, bool Waitˉforˉexit = true) { ProcessStartInfo Processˉinfo = new ProcessStartInfo(Processˉname, Arguments); Processˉinfo.UseShellExecute = false; Processˉinfo.RedirectStandardOutput = true; Processˉinfo.RedirectStandardError = true; Processˉinfo.CreateNoWindow = true; if (Workingˉdirectory != null) { Processˉinfo.WorkingDirectory = new DirectoryInfo(Workingˉdirectory).FullName; } var Processˉreference = new Process(); Processˉreference.StartInfo = Processˉinfo; Processˉreference.ErrorDataReceived += Writeˉtoˉconsoleˉwindow; Processˉreference.OutputDataReceived += Writeˉtoˉconsoleˉwindow; Processˉreference.EnableRaisingEvents = true; Processˉreference.Start(); Processˉreference.BeginOutputReadLine(); Processˉreference.BeginErrorReadLine(); if (Waitˉforˉexit) { Processˉreference.WaitForExit(); } } // write out info to the display window static void Writeˉtoˉconsoleˉwindow(object sender, DataReceivedEventArgs e) { Console.WriteLine(e.Data); } } }
using DependencyInjectionSample.Data; using DependencyInjectionSample.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; namespace APIChallenge { public class ClienteDados : IClienteDados { IDataBase dataBase; public ClienteDados(IDataBase dataBaseClient) { this.dataBase = dataBaseClient; } public void inserirCliente(Cliente clienteTemp) { try { dataBase.inserirCliente(clienteTemp); } catch(DbUpdateException) { throw new Exception(); } } public Cliente obterClientePorId(long id) { return dataBase.obterClientePorId(id); } public List<Cliente> obterListaClientes() { return dataBase.obterListaClientes(); } } }
using GameStore.Domain.Infrastructure; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GameStore.Domain.Identity { public class AppUserStore : UserStore<AppUser> { public AppUserStore(GameStoreDBContext context) : base(context) { } } }
using System; using System.Linq; using TreeDataStructure.Helper; namespace TreeDataStructure { class Program { static void Main(string[] args) { TreeUsingLinkedList tree = new TreeUsingLinkedList(); while (true) { Console.WriteLine ("Please select an option" + Environment.NewLine + "1. Create Tree" + Environment.NewLine + "2. In-order Traversal" + Environment.NewLine + "3. Level-order Traversal" + Environment.NewLine + "4. Generate tree from traversal" + Environment.NewLine + "0. Exit" ); if (!int.TryParse(Console.ReadLine(), out int i)) { Console.WriteLine(Environment.NewLine + "Input format is not valid. Please try again." + Environment.NewLine); } if (i == 0) { Environment.Exit(0); } else if (i == 1) { tree.CreateTree(); } else if (i == 2) { tree.RInOrderTraversal(tree.RootNode); Console.WriteLine(); } else if (i == 3) { tree.LevelOrderTrversal(tree.RootNode); Console.WriteLine(); } else if (i == 4) { Console.WriteLine("Enter the tree pre-order traversal form(comma separated)"); int[] preOrder = Console.ReadLine().Split(',').Select(x => Convert.ToInt32(x.Trim())).ToArray(); // 4,7,9,6,3,2,5,8,1 Console.WriteLine("Enter the tree in-order traversal form(comma separated)"); int[] inOrder = Console.ReadLine().Split(',').Select(x => Convert.ToInt32(x.Trim())).ToArray(); // 7,6,9,3,4,5,8,2,1 tree.RootNode = tree.GenerateTreeFromTraversal(preOrder, inOrder, 0, inOrder.Length - 1); } else { Console.WriteLine("Please select a valid option."); } } } } }
using System; using System.Net; namespace Microsoft.DataStudio.WebExtensions { public static class HttpWebResponseExtensions { public static Guid GetCorrelationId(this HttpWebResponse response) { string clientRequestId = response.GetResponseHeader("x-ms-client-request-id"); // studioapi requests seem to set this if (!string.IsNullOrEmpty(clientRequestId)) return Guid.Parse(clientRequestId); string requestId = response.GetResponseHeader("x-ms-request-id"); // For management.azureml.net if (!string.IsNullOrEmpty(requestId)) return Guid.Parse(requestId); return Guid.Empty; } } }
using System; using SLua; using System.Collections.Generic; [UnityEngine.Scripting.Preserve] public class Lua_EffectController : LuaObject { [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int Play(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif EffectController self=(EffectController)checkSelf(l); self.Play(); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int Stop(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif EffectController self=(EffectController)checkSelf(l); System.Boolean a1; checkType(l,2,out a1); self.Stop(a1); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int Remove(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif EffectController self=(EffectController)checkSelf(l); self.Remove(); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_playAutomatically(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif EffectController self=(EffectController)checkSelf(l); pushValue(l,true); pushValue(l,self.playAutomatically); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_playAutomatically(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif EffectController self=(EffectController)checkSelf(l); System.Boolean v; checkType(l,2,out v); self.playAutomatically=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_autoRemove(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif EffectController self=(EffectController)checkSelf(l); pushValue(l,true); pushValue(l,self.autoRemove); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_autoRemove(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif EffectController self=(EffectController)checkSelf(l); System.Boolean v; checkType(l,2,out v); self.autoRemove=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_isFlip(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif EffectController self=(EffectController)checkSelf(l); pushValue(l,true); pushValue(l,self.isFlip); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_isFlip(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif EffectController self=(EffectController)checkSelf(l); System.Boolean v; checkType(l,2,out v); self.isFlip=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_onEffectEnd(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif EffectController self=(EffectController)checkSelf(l); System.Action v; int op=checkDelegate(l,2,out v); if(op==0) self.onEffectEnd=v; else if(op==1) self.onEffectEnd+=v; else if(op==2) self.onEffectEnd-=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_EffectTime(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif EffectController self=(EffectController)checkSelf(l); pushValue(l,true); pushValue(l,self.EffectTime); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_TimeScale(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif EffectController self=(EffectController)checkSelf(l); pushValue(l,true); pushValue(l,self.TimeScale); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_TimeScale(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif EffectController self=(EffectController)checkSelf(l); float v; checkType(l,2,out v); self.TimeScale=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_isAlive(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif EffectController self=(EffectController)checkSelf(l); pushValue(l,true); pushValue(l,self.isAlive); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_isPlaying(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif EffectController self=(EffectController)checkSelf(l); pushValue(l,true); pushValue(l,self.isPlaying); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [UnityEngine.Scripting.Preserve] static public void reg(IntPtr l) { getTypeTable(l,"EffectController"); addMember(l,Play); addMember(l,Stop); addMember(l,Remove); addMember(l,"playAutomatically",get_playAutomatically,set_playAutomatically,true); addMember(l,"autoRemove",get_autoRemove,set_autoRemove,true); addMember(l,"isFlip",get_isFlip,set_isFlip,true); addMember(l,"onEffectEnd",null,set_onEffectEnd,true); addMember(l,"EffectTime",get_EffectTime,null,true); addMember(l,"TimeScale",get_TimeScale,set_TimeScale,true); addMember(l,"isAlive",get_isAlive,null,true); addMember(l,"isPlaying",get_isPlaying,null,true); createTypeMetatable(l,null, typeof(EffectController),typeof(UnityEngine.MonoBehaviour)); } }
using Koek; using Microsoft.Extensions.Logging; using System; namespace Tests { public abstract class KoekTests : BaseTestClass, IDisposable { public KoekTests() { _loggerFactory = Microsoft.Extensions.Logging.LoggerFactory.Create(builder => { builder.AddConsole(); builder.SetMinimumLevel(LogLevel.Trace); }); _logger = _loggerFactory.CreateLogger(""); } protected readonly ILoggerFactory _loggerFactory; protected readonly ILogger _logger; public virtual void Dispose() { _loggerFactory.Dispose(); } } }
using System; using System.Collections.Generic; public class Program { public static void Main() { var resourceDict = new Dictionary<string, int>(); while (true) { var input = Console.ReadLine(); if (input == "stop") { break; } var currResource = input; var currQuantity = int.Parse(Console.ReadLine()); if (!resourceDict.ContainsKey(currResource)) { resourceDict[currResource] = 0; } resourceDict[currResource] += currQuantity; } foreach (var kvp in resourceDict) { var currResource = kvp.Key; var currResourceQuantity = kvp.Value; Console.WriteLine($"{currResource} -> {currResourceQuantity}"); } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Xml; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace Uxnet.Web.Module.Common { public partial class WebPageTreeView : System.Web.UI.UserControl { private Regex _reg; protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { initializeData(); } } public TreeView PageTree { get { return pageTree; } } public string SearchPattern { get { return (string)this.ViewState["sp"]; } set { this.ViewState["sp"] = value; } } private void initializeData() { if (!String.IsNullOrEmpty(SearchPattern)) { _reg = new Regex(SearchPattern); } StringBuilder webDoc = new StringBuilder(); webDoc.Append("<web>\r\n"); buildWebPageTree(webDoc, HttpRuntime.AppDomainAppPath); webDoc.Append("</web>"); dsPageTree.DataFile = String.Empty; dsPageTree.Data = webDoc.ToString(); } private bool buildWebPageTree(StringBuilder root, string path) { bool hasFiles = false; int length; foreach (string dir in Directory.GetDirectories(path)) { length = root.Length; root.Append(String.Format("\t<directory name=\"{0}\">\r\n",Path.GetFileName(dir))); hasFiles = buildWebPageTree(root, dir); root.Append("</directory>"); if (!hasFiles) { root.Remove(length, root.Length - length); } } length = root.Length; foreach (string fileName in Directory.GetFiles(path)) { if (_reg == null || _reg.IsMatch(fileName)) { root.Append(String.Format("\t<file name=\"{0}\"/>\r\n", Path.GetFileName(fileName))); } } return root.Length>length; } } }
using LogicBuilder.Attributes; using System; using System.Collections.Generic; using System.Text; namespace Contoso.Forms.Parameters.Common { public class CommandColumnParameters { public CommandColumnParameters() { } public CommandColumnParameters ( [Comments("Column title.")] string title, [Comments("Column width")] int? width ) { Title = title; Width = width; } public string Title { get; set; } public int? Width { get; set; } } }
using GraphQL.Types; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebAPI_GraphQL_DotNetCore.InputTypes { public class ArtistInputType : InputObjectGraphType { public ArtistInputType() { Name = "createArtistInput"; Field<StringGraphType>("Name"); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleApp.Samples { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class GetSetCookieSample : ContentPage { public GetSetCookieSample() { InitializeComponent(); } private async void SetCookieClicked(object sender, EventArgs e) { var expiresDate = DateTime.Now; expiresDate = expiresDate.AddDays(10); // This cookie will expire after 10 days Cookie cookie = new Cookie(); cookie.Name = "testCookie"; cookie.Value = "testCookieValue"; cookie.Domain = (new Uri(localContent.Source)).Host; cookie.Expired = false; cookie.Expires = expiresDate; cookie.Path = "/"; // This cookie will expire 30 seconds after it is set Cookie cookie2 = new Cookie(); cookie2.Name = "testCookie1"; cookie2.Value = "testCookieValue1"; cookie2.Domain = (new Uri(localContent.Source)).Host; cookie2.Expired = false; cookie2.Expires = DateTime.Now.AddSeconds(30); var str = await localContent.SetCookieAsync(cookie); var str2 = await localContent.SetCookieAsync(cookie2); } private async void GetCookieClicked(object sender, EventArgs e) { var str = await localContent.GetCookieAsync("testCookie"); var str2 = await localContent.GetCookieAsync("testCookie1"); } private async void GetAllCookiesClicked(object sender, EventArgs e) { var str = await localContent.GetAllCookiesAsync(); } void OnRefreshPageClicked(object sender, EventArgs e) { localContent.Refresh(); } } }
namespace testcs { #region CDoclet generated code /** * <summary> * Generated by CDoclet from test.TestInterfaceGeneric. Do not edit. * </summary> */ public interface TestInterfaceGeneric<A, B> where A : System.DateTime? { void Foo(A bar, B baz); } #endregion }
namespace LuaInterface { using System; using System.Runtime.InteropServices; using System.Reflection; using System.Collections; using System.Text; using System.Security; using LuaLu; [AttributeUsage(AttributeTargets.Method)] public sealed class MonoPInvokeCallbackAttribute : Attribute { public MonoPInvokeCallbackAttribute(Type t) { } } /// <summary> /// lua value type constant /// </summary> public enum LuaTypes { LUA_TNONE = -1, LUA_TNIL = 0, LUA_TBOOLEAN = 1, LUA_TLIGHTUSERDATA = 2, LUA_TNUMBER = 3, LUA_TSTRING = 4, LUA_TTABLE = 5, LUA_TFUNCTION = 6, LUA_TUSERDATA = 7, LUA_TTHREAD = 8 } /// <summary> /// lua garbage collection option /// </summary> public enum LuaGCOptions { LUA_GCSTOP = 0, LUA_GCRESTART = 1, LUA_GCCOLLECT = 2, LUA_GCCOUNT = 3, LUA_GCCOUNTB = 4, LUA_GCSTEP = 5, LUA_GCSETPAUSE = 6, LUA_GCSETSTEPMUL = 7, } /// <summary> /// lua thread status /// </summary> public enum LuaThreadStatus { LUA_YIELD = 1, LUA_ERRRUN = 2, LUA_ERRSYNTAX = 3, LUA_ERRMEM = 4, LUA_ERRERR = 5 } /// <summary> /// special lua index /// </summary> public enum LuaIndex { LUA_REGISTRYINDEX = -10000, LUA_ENVIRONINDEX = -10001, LUA_GLOBALSINDEX = -10002 } // lua side function #if !UNITY_IPHONE [UnmanagedFunctionPointer(CallingConvention.Cdecl)] #endif public delegate int LuaFunction(IntPtr L); /// <summary> /// struct for lua side registeration /// </summary> [StructLayout(LayoutKind.Sequential)] public struct luaL_Reg { [MarshalAs(UnmanagedType.LPStr)] public string name; // in il2cpp enabled platform, here is a marshalling bug for reference type, // so we have to use IntPtr directly // issue tracker: https://issuetracker.unity3d.com/issues/il2cpp-marshaldirectiveexception-marshaling-of-delegates-as-fields-of-a-struct-is-not-working public IntPtr func; public luaL_Reg(string n, LuaFunction f) { name = n; func = f == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(f); } } [StructLayout(LayoutKind.Sequential)] public struct tolua_Error { public int index; public int array; public IntPtr type; } /// <summary> /// lua native lib wrapper /// </summary> #if !UNITY_IPHONE [SuppressUnmanagedCodeSecurity] #endif [NoLuaBinding] public class LuaLib { // option for multiple returns in `lua_pcall' and `lua_call' public const int LUA_MULTRET = -1; // tolua no peer public const int tolua_NOPEER = (int)LuaIndex.LUA_REGISTRYINDEX; // lua lib name #if UNITY_IPHONE const string LUALIB = "__Internal"; #else const string LUALIB = "lualu"; #endif // get lib name public static string GetLibName() { return LUALIB; } public static string Ptr2String(IntPtr ptr, int len) { if(ptr != IntPtr.Zero) { string ss = Marshal.PtrToStringAnsi(ptr, len); // when lua return non-ansi string, conversion fails if(ss == null) { return Marshal.PtrToStringUni(ptr, len); } return ss; } else { return null; } } ///////////////////////////////////////////// // lua.h ///////////////////////////////////////////// // pending api // LUA_API IntPtr (lua_newstate) (lua_Alloc f, void *ud); // LUA_API const char *(lua_pushvfstring) (IntPtr L, const char *fmt, va_list argp); // LUA_API const char *(lua_pushfstring) (IntPtr L, const char *fmt, ...); // LUA_API int (lua_load) (IntPtr L, lua_Reader reader, void *dt, const char *chunkname); // LUA_API int (lua_dump) (IntPtr L, lua_Writer writer, void *data); // LUA_API lua_Alloc (lua_getallocf) (IntPtr L, void **ud); // LUA_API void lua_setallocf (IntPtr L, lua_Alloc f, void *ud); // LUA_API int lua_getstack (IntPtr L, int level, lua_Debug *ar); // LUA_API int lua_getinfo (IntPtr L, const char *what, lua_Debug *ar); // LUA_API const char *lua_getlocal (IntPtr L, const lua_Debug *ar, int n); // LUA_API const char *lua_setlocal (IntPtr L, const lua_Debug *ar, int n); // LUA_API int lua_sethook (IntPtr L, lua_Hook func, int mask, int count); // LUA_API lua_Hook lua_gethook (IntPtr L); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_close(IntPtr L); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_newthread(IntPtr L); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_atpanic(IntPtr L, LuaFunction panicf); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool lua_isnumber(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool lua_isstring(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool lua_iscfunction(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool lua_isuserdata(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_type(IntPtr L, int index); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_typelname(IntPtr L, int tp, out int len); public static string lua_typename(IntPtr L, int tp) { int len; IntPtr str = lua_typelname(L, tp, out len); return Ptr2String(str, len); } [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool lua_equal(IntPtr L, int idx1, int idx2); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool lua_rawequal(IntPtr L, int idx1, int idx2); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool lua_lessthan(IntPtr L, int idx1, int idx2); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_gettop(IntPtr L); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_settop(IntPtr L, int newTop); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushvalue(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_remove(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_insert(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_replace(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_checkstack(IntPtr L, int sz); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_xmove(IntPtr from, IntPtr to, int n); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern double lua_tonumber(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_tointeger(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_toboolean(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_tolstring(IntPtr L, int idx, out int len); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_objlen(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_tocfunction(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_touserdata(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_tothread(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_topointer(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushnil(IntPtr L); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushnumber(IntPtr L, double n); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushinteger(IntPtr L, int n); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushlstring(IntPtr L, byte[] s, int l); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushstring(IntPtr L, string s); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushcclosure(IntPtr L, IntPtr fn, int n); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushboolean(IntPtr L, bool b); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushlightuserdata(IntPtr L, IntPtr p); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_pushthread(IntPtr L); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_gettable(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_getfield(IntPtr L, int stackPos, string meta); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawget(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawgeti(IntPtr L, int idx, int n); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_createtable(IntPtr L, int narr, int nrec); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_newuserdata(IntPtr L, int sz); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_getmetatable(IntPtr L, int objindex); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_getfenv(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_settable(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_setfield(IntPtr L, int idx, string k); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawset(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawseti(IntPtr L, int idx, int n); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_setmetatable(IntPtr L, int objindex); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_setfenv(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_call(IntPtr L, int nArgs, int nResults); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_pcall(IntPtr L, int nArgs, int nResults, int errfunc); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_cpcall(IntPtr L, LuaFunction func, IntPtr ud); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_yield(IntPtr L, int nresults); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_resume(IntPtr L, int narg); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_status(IntPtr L); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_gc(IntPtr L, int what, int data); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_error(IntPtr L); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_next(IntPtr L, int idx); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_concat(IntPtr L, int n); public static void lua_pop(IntPtr L, int amount) { lua_settop(L, -(amount) - 1); } public static void lua_newtable(IntPtr L) { lua_createtable(L, 0, 0); } public static void lua_register(IntPtr L, string n, IntPtr f) { lua_pushcfunction(L, f); lua_setglobal(L, n); } public static void lua_pushcfunction(IntPtr L, IntPtr f) { lua_pushcclosure(L, f, 0); } public static int lua_strlen(IntPtr L, int i) { return lua_objlen(L, i); } public static bool lua_isfunction(IntPtr L, int stackPos) { return lua_type(L, stackPos) == (int)LuaTypes.LUA_TFUNCTION; } public static bool lua_istable(IntPtr L, int n) { return lua_type(L, (n)) == (int)LuaTypes.LUA_TTABLE; } public static bool lua_islightuserdata(IntPtr L, int n) { return lua_type(L, (n)) == (int)LuaTypes.LUA_TLIGHTUSERDATA; } public static bool lua_isnil(IntPtr L, int n) { return lua_type(L, (n)) == (int)LuaTypes.LUA_TNIL; } public static bool lua_isboolean(IntPtr L, int n) { return lua_type(L, (n)) == (int)LuaTypes.LUA_TBOOLEAN; } public static bool lua_isthread(IntPtr L, int n) { return lua_type(L, (n)) == (int)LuaTypes.LUA_TTHREAD; } public static bool lua_isnone(IntPtr L, int n) { return lua_type(L, (n)) == (int)LuaTypes.LUA_TNONE; } public static bool lua_isnoneornil(IntPtr L, int n) { return lua_type(L, (n)) <= 0; } public static void lua_pushliteral(IntPtr L, byte[] s) { lua_pushlstring(L, s, s.Length); } public static void lua_setglobal(IntPtr L, string s) { lua_setfield(L, (int)LuaIndex.LUA_GLOBALSINDEX, s); } public static void lua_getglobal(IntPtr L, string n) { lua_getfield(L, (int)LuaIndex.LUA_GLOBALSINDEX, n); } public static string lua_tostring(IntPtr L, int idx) { int len; IntPtr str = lua_tolstring(L, idx, out len); return Ptr2String(str, len); } public static IntPtr lua_open() { return luaL_newstate(); } public static void lua_getregistry(IntPtr L) { lua_pushvalue(L, (int)LuaIndex.LUA_REGISTRYINDEX); } public static int lua_getgccount(IntPtr L) { return lua_gc(L, (int)LuaGCOptions.LUA_GCCOUNT, 0); } [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern string lua_getupvalue(IntPtr L, int funcindex, int n); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern string lua_setupvalue(IntPtr L, int funcindex, int n); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_gethookmask(IntPtr L); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_gethookcount(IntPtr L); ///////////////////////////////////////////// // lualib.h ///////////////////////////////////////////// [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_openlibs(IntPtr L); ///////////////////////////////////////////// // luaxlib.h ///////////////////////////////////////////// // pending api // LUALIB_API void (luaL_buffinit) (IntPtr L, luaL_Buffer *B); // LUALIB_API char *(luaL_prepbuffer) (luaL_Buffer *B); // LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l); // LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s); // LUALIB_API void (luaL_addvalue) (luaL_Buffer *B); // LUALIB_API void (luaL_pushresult) (luaL_Buffer *B); // LUALIB_API void (luaI_openlib) (IntPtr L, const char *libname, const luaL_Reg *l, int nup); // LUALIB_API int (luaL_checkoption) (IntPtr L, int narg, const char *def, const char *const lst[]); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_register(IntPtr L, string libname, luaL_Reg[] l); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_getmetafield(IntPtr L, int obj, string e); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_callmeta(IntPtr L, int obj, string e); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_typerror(IntPtr L, int narg, string tname); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_argerror(IntPtr L, int numarg, string extramsg); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr luaL_checklstring(IntPtr L, int numArg, out int l); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr luaL_optlstring(IntPtr L, int numArg, byte[] def, out int l); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern double luaL_checknumber(IntPtr L, int numArg); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern double luaL_optnumber(IntPtr L, int nArg, double def); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_checkinteger(IntPtr L, int numArg); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_optinteger(IntPtr L, int nArg, int def); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_checkstack(IntPtr L, int sz, string msg); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_checktype(IntPtr L, int narg, int t); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_checkany(IntPtr L, int narg); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_newmetatable(IntPtr L, string tname); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr luaL_checkudata(IntPtr L, int ud, string tname); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_where(IntPtr L, int lvl); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_error(IntPtr L, string fmt); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_ref(IntPtr L, int t); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_unref(IntPtr L, int t, int _ref); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_loadfile(IntPtr L, string filename); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_loadbuffer(IntPtr L, byte[] buff, int sz, string name); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_loadstring(IntPtr L, string chunk); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr luaL_newstate(); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern string luaL_gsub(IntPtr L, string s, string p, string r); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern string luaL_findtable(IntPtr L, int idx, string fname, int szhint); public static string luaL_checkstring(IntPtr L, int n) { int len; IntPtr str = luaL_checklstring(L, n, out len); return Ptr2String(str, len); } public static string luaL_optstring(IntPtr L, int n, string d) { int len; IntPtr str = luaL_optlstring(L, n, Encoding.UTF8.GetBytes(d), out len); return Ptr2String(str, len); } public static int luaL_checkint(IntPtr L, int n) { return luaL_checkinteger(L, n); } public static int luaL_optint(IntPtr L, int n, int d) { return luaL_optinteger(L, n, d); } public static long luaL_checklong(IntPtr L, int n) { return (long)luaL_checkinteger(L, n); } public static long luaL_optlong(IntPtr L, int n, int d) { return (long)luaL_optinteger(L, n, d); } public static string luaL_typename(IntPtr L, int i) { return lua_typename(L, lua_type(L, i)); } public static int luaL_dofile(IntPtr L, string fn) { int result = luaL_loadfile(L, fn); if(result != 0) { return result; } return lua_pcall(L, 0, LUA_MULTRET, 0); } public static int luaL_dostring(IntPtr L, string chunk) { int result = luaL_loadstring(L, chunk); if(result != 0) { return result; } return lua_pcall(L, 0, -1, 0); } public static void luaL_getmetatable(IntPtr L, string meta) { lua_getfield(L, (int)LuaIndex.LUA_REGISTRYINDEX, meta); } public static int lua_ref(IntPtr L, int lockRef) { if(lockRef != 0) { return luaL_ref(L, (int)LuaIndex.LUA_REGISTRYINDEX); } else { lua_pushstring(L, "unlocked references are obsolete"); lua_error(L); return 0; } } public static void lua_unref(IntPtr L, int _ref) { luaL_unref(L, (int)LuaIndex.LUA_REGISTRYINDEX, _ref); } public static void lua_getref(IntPtr L, int _ref) { lua_rawgeti(L, (int)LuaIndex.LUA_REGISTRYINDEX, _ref); } ///////////////////////////////////////////// // other module ///////////////////////////////////////////// [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void luaopen_lfs(IntPtr L); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void luaopen_cjson(IntPtr L); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void luaopen_socket_core(IntPtr L); ///////////////////////////////////////////// // log support ///////////////////////////////////////////// [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void set_unity_log_func(IntPtr fp); ///////////////////////////////////////////// // tolua ///////////////////////////////////////////// [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_stack_dump(IntPtr L, string label); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool lua_isusertype(IntPtr L, int lo, string type); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr tolua_typelname(IntPtr L, int lo, out int len); public static string tolua_typename(IntPtr L, int lo) { int len; IntPtr str = tolua_typelname(L, lo, out len); return Ptr2String(str, len); } [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_error(IntPtr L, string msg, ref tolua_Error err); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool tolua_isnoobj(IntPtr L, int lo, ref tolua_Error err); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool tolua_isfunction(IntPtr L, int lo, ref tolua_Error err); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool tolua_isvalue(IntPtr L, int lo, ref tolua_Error err); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool tolua_isvaluenil(IntPtr L, int lo, ref tolua_Error err); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool tolua_isboolean(IntPtr L, int lo, ref tolua_Error err); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool tolua_isnumber(IntPtr L, int lo, ref tolua_Error err); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool tolua_isstring(IntPtr L, int lo, ref tolua_Error err); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool tolua_istable(IntPtr L, int lo, ref tolua_Error err); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool tolua_isusertable(IntPtr L, int lo, string type, ref tolua_Error err); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool tolua_isuserdata(IntPtr L, int lo, ref tolua_Error err); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool tolua_isusertype(IntPtr L, int lo, string type, ref tolua_Error err); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool tolua_checkusertype(IntPtr L, int lo, string type); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool tolua_isvaluearray(IntPtr L, int lo, int dim, ref tolua_Error err); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool tolua_isbooleanarray(IntPtr L, int lo, int dim, ref tolua_Error err); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool tolua_isnumberarray(IntPtr L, int lo, int dim, ref tolua_Error err); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool tolua_isstringarray(IntPtr L, int lo, int dim, ref tolua_Error err); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool tolua_istablearray(IntPtr L, int lo, int dim, ref tolua_Error err); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool tolua_isuserdataarray(IntPtr L, int lo, int dim, ref tolua_Error err); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool tolua_isusertypearray(IntPtr L, int lo, string type, int dim, ref tolua_Error err); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_open(IntPtr L); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr tolua_copy(IntPtr L, IntPtr value, uint size); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int tolua_register_gc(IntPtr L, int lo); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int tolua_unregister_gc(IntPtr L, int lo); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int tolua_default_collect(IntPtr L); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_usertype(IntPtr L, string type); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_beginmodule(IntPtr L, string name); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_endmodule(IntPtr L); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_module(IntPtr L, string name, int hasvar); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_class(IntPtr L, string name, string _base, LuaFunction col); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_function(IntPtr L, string name, LuaFunction func); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_constant(IntPtr L, string name, double value); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_constant_string(IntPtr L, string name, string value); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_variable(IntPtr L, string name, LuaFunction get, LuaFunction set); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_array(IntPtr L, string name, LuaFunction get, LuaFunction set); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_addbase(IntPtr L, string name, string _base); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_pushvalue(IntPtr L, int lo); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_pushboolean(IntPtr L, bool value); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_pushnumber(IntPtr L, double value); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_pushstring(IntPtr L, string value); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_pushuserdata(IntPtr L, IntPtr value); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_replaceref(IntPtr L, int oldRefId, int newRefId); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_pushusertype(IntPtr L, int refid, string type, bool addToRoot); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_add_value_to_root(IntPtr L, int refid); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_remove_value_from_root(IntPtr L, int refid); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern double tolua_tonumber(IntPtr L, int narg, double def); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int tolua_tointeger(IntPtr L, int narg, int def); public static string tolua_tostring(IntPtr L, int narg, string def) { return lua_gettop(L) < Math.Abs(narg) ? def : lua_tostring(L, narg); } [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int tolua_tousertype(IntPtr L, int narg); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int tolua_tovalue(IntPtr L, int narg, int def); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern bool tolua_toboolean(IntPtr L, int narg, int def); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void tolua_dobuffer(IntPtr L, byte[] B, uint size, string name); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int tolua_fast_isa(IntPtr L, int mt_indexa, int mt_indexb, int super_index); //////////////////////////////////////////// // tolua fix //////////////////////////////////////////// [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void toluafix_open(IntPtr L); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int toluafix_ref_function(IntPtr L, int lo, int def); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void toluafix_get_function_by_refid(IntPtr L, int refid); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void toluafix_remove_function_by_refid(IntPtr L, int refid); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern int toluafix_ref_table(IntPtr L, int lo, int def); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void toluafix_get_table_by_refid(IntPtr L, int refid); [DllImport(LUALIB, CallingConvention = CallingConvention.Cdecl)] public static extern void toluafix_remove_table_by_refid(IntPtr L, int refid); } }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.Rendering; using SimpleBlogEngine.Services.Interfaces; using SimpleBlogEngine.Web.Models.PostViewModels; namespace SimpleBlogEngine.Web.Pages.Post { [Authorize] public class CreateEditPostModel : PageModel { IPostService postService; ICategoryService categoryService; [BindProperty] public CreateEditPostViewModel createEditPostViewModel { get; set; } = new CreateEditPostViewModel(); public CreateEditPostModel(IPostService postService, ICategoryService categoryService) { this.postService = postService; this.categoryService = categoryService; } public async Task OnGet(long? id) { var categoryCollection = await categoryService.GetAll(); createEditPostViewModel.Categories = categoryCollection.ToList().Select(a => new SelectListItem { Text = a.Name, Value = a.Id.ToString() }).ToList(); if (id.HasValue) { var post = await postService.Get(id.Value); if (post != null) { createEditPostViewModel.Id = post.Id; createEditPostViewModel.Title = post.Title; createEditPostViewModel.Content = post.Content; createEditPostViewModel.CategoryId = post.CategoryId; } } } public async Task<IActionResult> OnPost(long? id) { try { if (ModelState.IsValid) { bool isNew = !id.HasValue; Repository.Models.Post post = isNew ? new Repository.Models.Post { AddedDate = DateTime.UtcNow } : await postService.Get(id.Value); post.Title = createEditPostViewModel.Title; post.Content = createEditPostViewModel.Content; post.CategoryId = createEditPostViewModel.CategoryId; post.IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString(); post.ModifiedDate = DateTime.UtcNow; if (isNew) { await postService.Insert(post); } else { await postService.Update(post); } } } catch (Exception) { throw; } return RedirectToPage("Index"); } } }
using System.Runtime.Serialization; namespace MediComponents.ViewModel { [DataContract] public class ABCompViewModel : ViewModel { public string Title { get { return string.Format(Strings.FormulaTitleFormatString, Strings.AppTitle, Strings.ABCompTitle); } } private int _ph; [DataMember] public int Ph { get { return _ph; } set { if (SetProperty(ref _ph, value)) State = 0; } } private int _hco3; [DataMember] public int Hco3 { get { return _hco3; } set { if (SetProperty(ref _hco3, value)) State = 0; } } private int _pco2; [DataMember] public int Pco2 { get { return _pco2; } set { if (SetProperty(ref _pco2, value)) State = 0; } } private AbState _state; public AbState State { get { return _state; } set { if (Ph == 0 && Pco2 == 0 && Hco3 == 0) _state = AbState.MetaAcid; else if (Ph == 1 && Pco2 == 1 && Hco3 == 1) _state = AbState.MetaAlka; else if (Ph == 0 && Pco2 == 1 && Hco3 == 1) _state = AbState.RespAcid; else if (Ph == 1 && Pco2 == 0 && Hco3 == 0) _state = AbState.RespAlka; else _state = AbState.Unknown; OnPropertyChanged(() => IndicationString); } } public string IndicationString { get { switch (_state) { case AbState.MetaAcid: return string.Format(Strings.IndicativeOfFormat, Strings.MetaAcid); case AbState.MetaAlka: return string.Format(Strings.IndicativeOfFormat, Strings.MetaAlka); case AbState.RespAcid: return string.Format(Strings.IndicativeOfFormat, Strings.RespAcid); case AbState.RespAlka: return string.Format(Strings.IndicativeOfFormat, Strings.RespAlka); default: return string.Format(Strings.IndicativeOfFormat, Strings.AnionGapExplanation); } } } public ABCompViewModel() : base() { } public ABCompViewModel(bool isDesign) : base(isDesign) { } protected override void InitializeDesignTime() { InitializeRunTime(); } protected override void InitializeRunTime() { Ph = 0; Pco2 = 0; Hco3 = 0; } public override bool Rehydrate(object vm) { var other = vm as ABCompViewModel; if (other == null) return false; Ph = other.Ph; Pco2 = other.Pco2; Hco3 = other.Hco3; return base.Rehydrate(vm); } } public enum AbState { Unknown = 0, MetaAcid = 1, MetaAlka = 2, RespAcid = 3, RespAlka = 4 } }
using MCC.Core.Manager; using MCC.Utility.IO; using Reactive.Bindings; using System; using System.IO; namespace MultiCommentCollectorCLI { public class Setting { #region Singleton private static Setting instance; public static Setting Instance => instance ??= XmlSerializer.FileDeserialize<Setting>($"{Path.GetDirectoryName(Environment.GetCommandLineArgs()[0])}\\setting.xml"); #endregion /// <summary> /// Servers /// </summary> public Server Servers { get; set; } = new(); /// <summary> /// ConnectionList /// </summary> public ReactiveCollection<ConnectionData> ConnectionList { get; set; } = new(); } }
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace BasesDatos.Modulo_SQL { /// <summary> /// Formulario para la parte de las consultas /// </summary> public partial class SQL_formulario : System.Windows.Forms.Form { private TabPage nueva_tab; //private Gramatica mysql; private BaseDatos BD; private Select select; private bool ejecuta; /// <summary> /// Constructor /// </summary> /// <param name="bd"> /// Base de datos con la cual trabajar /// </param> public SQL_formulario(BaseDatos bd) { ejecuta = false; this.BD = bd; select = new Select(BD); InitializeComponent(); //mysql = new Gramatica(); //clona_tab(); tab_ctrl.TabPages[0].Text += " 1"; } /// <summary> /// Cambia la referencia de nuestra base de datos por una nueva /// </summary> /// <param name="nueva_bd"> /// Nueva base de datos a referenciar /// </param> public void actualiza_bd(BaseDatos nueva_bd) { select.BD = nueva_bd; } /// <summary> /// Añade una nueva pestaña a la forma /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Agrega_nueva_pestaña_sql(object sender, EventArgs e) { TextBox entrada = new TextBox() { Font = new Font("Consolas", 12), Multiline = true, //Dock = DockStyle.Top, }; TextBox salida = new TextBox() { Multiline = true, //Dock = DockStyle.Fill, }; TextBox compilacion = new TextBox() { Multiline = true, //Dock = DockStyle.Bottom, }; nueva_tab = new TabPage(); nueva_tab.Controls.Add(entrada); nueva_tab.Controls.Add(salida); nueva_tab.Controls.Add(compilacion); nueva_tab.Controls[nueva_tab.Controls.Count - 3].Dock = DockStyle.Top; nueva_tab.Controls[nueva_tab.Controls.Count - 1].Dock = DockStyle.Bottom; nueva_tab.Controls[nueva_tab.Controls.Count - 2].Dock = DockStyle.Fill; nueva_tab.Text = "SQL " + tab_ctrl.TabPages.Count + 1; tab_ctrl.TabPages.Add(nueva_tab); } /// <summary> /// Evento que existe al presionarse una tecla /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void tab_ctrl_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.F5) { txt_compilacion.Text = ejecuta_sentencia(); muestra_resultados_grid(); //MessageBox.Show("f5 pressed!"); } } /// <summary> /// Trata de ejecutar una sentencia sql /// </summary> /// <returns> /// Una cadena que contiene informacion acerca de la ejecución /// </returns> public string ejecuta_sentencia() { ejecuta = true; select.resultado = "Error de sintaxis!."; // si no hay tablas, amonos if (!select.hay_tablas()) { ejecuta = false; return "Abre una base de datos primero!."; } string entrada = txtb_entrada.Text; if (select.coincide_select_all(entrada) && select.ejecuta_select_all()) { return select.resultado; } else if (select.coincide_select_columns(entrada) && select.ejecuta_select_columns(false)) { return select.resultado; } else if (select.coincide_select_where(entrada) && select.ejecuta_select_columns(true)) { return select.resultado; } else if (select.coincide_inner_join(entrada) && select.ejecuta_inner_join()) { return select.resultado; } ejecuta = false; limpia_grid(); return select.resultado; } /// <summary> /// Ejecuta una sentencia al presionar la tecla F5 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ejecutarSentenciaF5ToolStripMenuItem_Click(object sender, EventArgs e) { txt_compilacion.Text = ejecuta_sentencia(); muestra_resultados_grid(); } /// <summary> /// Limpia los renglones y columas del datagridview /// </summary> public void limpia_grid() { if (select.atributos != null) { dgv_resultados.Columns.Clear(); dgv_resultados.Rows.Clear(); } } /// <summary> /// Muestra los resultados en el grid de la ultima consulta ejecutada /// </summary> private void muestra_resultados_grid() { if (!ejecuta) return; limpia_grid(); try { agrega_cabecera_datos(); elimina_columnas_sobrantes(); organiza_columnas(); } catch(Exception e) { MessageBox.Show(e.Message); limpia_grid(); } } /// <summary> /// Agrega los headers al grid /// </summary> private void agrega_cabecera_datos() { // agregando el encabezado del grid for (int i = 0; i < select.atributos_tablaA.Count; i++) { dgv_resultados.Columns.Add(select.tablaA + "." + select.atributos_tablaA[i], select.atributos_tablaA[i]); } for (int i = 0; i < select.atributos_tablaB.Count; i++) { dgv_resultados.Columns.Add(select.tablaB + "." + select.atributos_tablaB[i], select.atributos_tablaB[i]); } // agregando los datos for (int i = 0; i < select.datos.Count; i++) { dgv_resultados.Rows.Add(select.datos[i].ToArray()); } } /// <summary> /// Elimina las columnas que no deseamos observar como parte del resultado /// </summary> private void elimina_columnas_sobrantes() { // borrando las columnas que no nos interesan for (int i = 0; i < select.ansA.Count; i++) dgv_resultados.Columns.Remove(dgv_resultados.Columns[select.tablaA + "." + select.ansA[i]]); int desplazamiento = select.ansA.Count + 1; for (int i = 0; i < select.ansB.Count; i++) dgv_resultados.Columns.Remove(dgv_resultados.Columns[select.tablaB + "." + select.ansB[i]]); } /// <summary> /// Reorganiza las columnas mostradas para que coincida con la secuencia pedida por la consulta SQL /// </summary> private void organiza_columnas() { // reorganizando las columnas for (int i = 0; i < select.atributos.Count; i++) { // probando atributos de la tabla a if (dgv_resultados.Columns.Contains(select.tablaA + "." + select.atributos[i])) { dgv_resultados.Columns[select.tablaA + "." + select.atributos[i]].DisplayIndex = i; } else if(dgv_resultados.Columns.Contains(select.atributos[i])) { dgv_resultados.Columns[select.atributos[i]].DisplayIndex = i; } // probando atributos de la tabla b else if(dgv_resultados.Columns.Contains(select.tablaB + "." + select.atributos[i])) { dgv_resultados.Columns[select.tablaB + "." + select.atributos[i]].DisplayIndex = i; } else if (dgv_resultados.Columns.Contains(select.atributos[i])) { dgv_resultados.Columns[select.atributos[i]].DisplayIndex = i; } if (select.atributos[i].Contains(".")) dgv_resultados.Columns[select.atributos[i]].HeaderText = select.atributos[i]; } } /// <summary> /// Evento que se produce al dar click al botón de limpiar el grid /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void limpiaGridToolStripMenuItem_Click(object sender, EventArgs e) { limpia_grid(); } } }
using Padeg; namespace HouseCostCalculation { public class Owner { private string ownerAddress; private string ownerOVD; private string initials; private string firstName; private string lastName; private string passSerial; private string passRegDate; private string passNumber; private string ownerPhone; public string ownerFullName; public string ownerFullNameR; public string ownerFullNameD; public string ownerFullNameV; public string ownerFullNameT; public string ownerFullNameP; public Owner(string address1, string OVD1, string ownerInit1, string ownerName1, string ownerSurname1, string passDate1, string passNum1, string passportSerial1, string phone1) { address = address1; OVD = OVD1; ownerInit = ownerInit1; ownerName = ownerName1; ownerSurname = ownerSurname1; passportSerial = passportSerial1; passNum = passNum1; passDate = passDate1; phone = phone1; ownerPadeg(); ownerFullName = ownerSurname + " " + ownerName + " " + ownerInit; } public string ownerName { get { return firstName; } set { firstName = value; } } public string ownerSurname { get { return lastName; } set { lastName = value; } } public string ownerInit { get { return initials; } set { initials = value; } } public string phone { get { return ownerPhone; } set { ownerPhone = value; } } public string address { get { return ownerAddress; } set { ownerAddress = value; } } public string passNum { get { return passNumber; } set { passNumber = value; } } public string passDate { get { return passRegDate; } set { passRegDate = value; } } public string passportSerial { get { return passSerial; } set { passSerial = value; } } public string OVD { get { return ownerOVD; } set { ownerOVD = value; } } public void ownerPadeg() { Declension padeg = new Declension(); int sex = padeg.GetSex(ownerInit); string cSex; if (sex == 1) { cSex = "м"; } else { cSex = "ж"; } ownerFullNameR = padeg.GetFIOPadeg(ownerSurname, ownerName, ownerInit, cSex, 2); ownerFullNameD = padeg.GetFIOPadeg(ownerSurname, ownerName, ownerInit, cSex, 3); ownerFullNameV = padeg.GetFIOPadeg(ownerSurname, ownerName, ownerInit, cSex, 4); ownerFullNameT = padeg.GetFIOPadeg(ownerSurname, ownerName, ownerInit, cSex, 5); ownerFullNameP = padeg.GetFIOPadeg(ownerSurname, ownerName, ownerInit, cSex, 6); } } }
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/. // VisualNovelToolkit /_/_/_/_/_/_/_/_/_/. // Copyright ©2013 - Sol-tribe. /_/_/_/_/_/_/_/_/_/. //_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/. using UnityEngine; using System.Collections.Generic; /// <summary> /// PlayTransition Node. /// </summary> //[ AddComponentMenu("ViNo/Nodes/PlayTransition") ] public class PlayTransitionNode : ViNode { [ Range( 0.1f , 10f )] public float waitSec = 1f; public bool _BEGIN; public bool _END; void Start(){ } public void BeginPreview(){ if( ITransition.Instance != null ){ ITransition.Instance.BeginTransition(); } } public void EndPreview(){ if( ITransition.Instance != null ){ ITransition.Instance.EndTransition(); } } public override void ToByteCode( ByteCodes code ){ List<byte> byteList = new List<byte>(); // AddNodeCodeWithTag( byteList , name ); AddNodeCode( byteList ); if( _BEGIN ){ byteList.Add( Opcode.BEGIN_TRANSITION ); } CodeGenerator.GenerateWaitCode( byteList , waitSec ); if( _END ){ byteList.Add( Opcode.END_TRANSITION ); } code.Add( byteList.ToArray() ); // ToByteCode this Children. ToByteCodeInternal( code ); } }
using Serilog; public class Runner { private readonly ILogger _log; public Runner(ILogger log) { _log = log; } public void DoAction(string name) { _log.Debug("Doing hard work! {Action}", name); } }
using AutoMapper.QueryableExtensions; using Microsoft.EntityFrameworkCore; using MutationMode.UI.Models.Entities; using MutationMode.UI.Models.ViewModels; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace MutationMode.UI.Models { public class DataConnector { public static readonly string ProgramFolder = Path.GetDirectoryName(typeof(DataConnector).Assembly.Location); AppOptions options = AppOptions.Instance; IDictionary<string, string> gameTexts; public void CompressTextData(List<LeaderWithTraitsViewModel> leaders, List<CivWithTraitsViewModel> civs) { var fullTexts = new Dictionary<string, string>(); var texts = JsonConvert.DeserializeObject<Dictionary<string, string>>( File.ReadAllText(@"D:\Temp\texts1.json")); foreach (var text in texts) { fullTexts[text.Key] = text.Value; } texts = JsonConvert.DeserializeObject<Dictionary<string, string>>( File.ReadAllText(@"D:\Temp\texts2.json")); foreach (var text in texts) { fullTexts[text.Key] = text.Value; } var neededValues = new Dictionary<string, string>(); Action<string> tryAdd = key => { if (string.IsNullOrWhiteSpace(key)) { return; } if (!fullTexts.TryGetValue(key, out var result)) { Debug.WriteLine("Missing: " + key); return; } neededValues[key] = result; }; foreach (var leader in leaders) { tryAdd(leader.Name); foreach (var trait in leader.LeaderTraits) { tryAdd(trait.Name); tryAdd(trait.Description); } } foreach (var civ in civs) { tryAdd(civ.Name); tryAdd(civ.Description); foreach (var trait in civ.CivilizationTraits) { tryAdd(trait.Name); tryAdd(trait.Description); } } File.WriteAllText(@"D:\Temp\texts-cache.json", JsonConvert.SerializeObject(neededValues)); } public void LoadGameTexts() { var textFile = Path.Combine(ProgramFolder, "texts-cache.json"); this.gameTexts = JsonConvert.DeserializeObject<Dictionary<string, string>>( File.ReadAllText(textFile)); } public async Task LoadGameText1Async() { using (var dc = new LocalizationContext( this.GetConnectionStringFromFile(this.options.CacheDebugLocalization))) { this.gameTexts = (await dc.BaseGameText .ToListAsync()) .ToDictionary(q => q.Tag, q => q.Text); } File.WriteAllText(@"D:\Temp\texts1.json", JsonConvert.SerializeObject(this.gameTexts)); } public void LoadGameText2() { this.gameTexts = new Dictionary<string, string>(); const string Folder = @"F:\Game\SteamLibrary\steamapps\common\Sid Meier's Civilization VI\"; var counter = 0; var files = Directory.GetFiles(Folder, "*.xml", SearchOption.AllDirectories); foreach (var file in files) { try { Debug.WriteLine($"{++counter}/{files.Length}: {file}"); var xmlDoc = new XmlDocument(); xmlDoc.Load(file); Action<string> scanTag = tagName => { var englishTexts = xmlDoc.DocumentElement.GetElementsByTagName(tagName); foreach (XmlElement englishText in englishTexts) { var rows = englishText.GetElementsByTagName("Row"); foreach (XmlElement row in rows) { this.gameTexts[row.GetAttribute("Tag")] = row.GetElementsByTagName("Text")[0].InnerText; } } }; scanTag("BaseGameText"); scanTag("EnglishText"); scanTag("LocalizedText"); } catch (Exception ex) { Debug.WriteLine(ex); } } File.WriteAllText(@"D:\Temp\texts2.json", JsonConvert.SerializeObject(this.gameTexts)); } public async Task<List<TraitViewModel>> GetAllTraitsAsync() { using (var dc = this.GetGameplayContext()) { return this.LookupTraitTexts(await dc.Traits .AsNoTracking() .OrderBy(q => q.TraitType) .ProjectTo<TraitViewModel>() .ToListAsync()); } } public async Task<List<LeaderWithTraitsViewModel>> GetLeadersWithTraitsAsync(bool getValidOnly) { using (var dc = this.GetGameplayContext()) { IQueryable<Leader> query = dc.Leaders .AsNoTracking() .Include(q => q.LeaderTraits); if (getValidOnly) { query = query.Where(q => q.InheritFrom == "LEADER_DEFAULT"); } var result = await query .OrderBy(q => q.LeaderType) .ProjectTo<LeaderWithTraitsViewModel>() .ToListAsync(); if (await this.IsTableExist("OriginalLeaderTraits", dc)) { var traits = await dc.Set<LeaderTrait>() .FromSql("SELECT * FROM OriginalLeaderTraits") .AsNoTracking() .ToListAsync(); var allTraits = (await this.GetAllTraitsAsync()) .ToDictionary(q => q.TraitType); foreach (var leader in result) { leader.LeaderTraits.Clear(); foreach (var trait in traits) { if (trait.LeaderType == leader.LeaderType) { leader.LeaderTraits.Add(allTraits[trait.TraitType]); } } } } this.LookupLeaderTexts(result); this.LookupTraitTexts(result.SelectMany(q => q.LeaderTraits).ToList()); return result; } } public async Task<List<CivWithTraitsViewModel>> GetCivsWithTraitsAsync(bool getValidOnly) { using (var dc = this.GetGameplayContext()) { IQueryable<Civilization> query = dc.Civilizations .AsNoTracking() .Include(q => q.CivilizationTraits); if (getValidOnly) { query = query.Where(q => q.StartingCivilizationLevelType == "CIVILIZATION_LEVEL_FULL_CIV"); } var result = await query .OrderBy(q => q.CivilizationType) .ProjectTo<CivWithTraitsViewModel>() .ToListAsync(); if (await this.IsTableExist("OriginalCivilizationTraits", dc)) { var traits = await dc.Set<CivilizationTrait>() .FromSql("SELECT * FROM OriginalCivilizationTraits") .AsNoTracking() .ToListAsync(); var allTraits = (await this.GetAllTraitsAsync()) .ToDictionary(q => q.TraitType); foreach (var civ in result) { civ.CivilizationTraits.Clear(); foreach (var trait in traits) { if (civ.CivilizationType == trait.CivilizationType) { civ.CivilizationTraits.Add(allTraits[trait.TraitType]); } } } } this.LookupCivTexts(result); this.LookupTraitTexts(result.SelectMany(q => q.CivilizationTraits).ToList()); return result; } } public string LookupText(string tag) { if (string.IsNullOrEmpty(tag)) { return ""; } if (this.gameTexts == null) { throw new InvalidOperationException("Game Text not loaded"); } return this.gameTexts.TryGetValue(tag, out var result) ? result : tag; } public List<T> LookupCivTexts<T>(List<T> civs) where T : CivilizationViewModel { foreach (var civ in civs) { civ.NameLookup = this.LookupText(civ.Name); civ.DescriptionLookup = this.LookupText(civ.Description); } return civs; } public List<T> LookupLeaderTexts<T>(List<T> leaders) where T : LeaderViewModel { foreach (var leader in leaders) { leader.NameLookup = this.LookupText(leader.Name); } return leaders; } public List<T> LookupTraitTexts<T>(List<T> traits) where T : TraitViewModel { foreach (var trait in traits) { trait.NameLookup = this.LookupText(trait.Name); trait.DescriptionLookup = this.LookupText(trait.Description); } return traits; } private string GetConnectionStringFromFile(string filePath) { return "Data Source=" + filePath; } private async Task<bool> IsTableExist(string tableName, DbContext dc) { var connection = dc.Database.GetDbConnection(); using (var command = connection.CreateCommand()) { command.CommandText = $"SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='{tableName}';"; if (connection.State == System.Data.ConnectionState.Closed) { connection.Open(); } var scalar = await command.ExecuteScalarAsync(); var result = int.Parse(scalar.ToString()); if (connection.State == System.Data.ConnectionState.Open) { connection.Close(); } return result > 0; } } private GameplayContext GetGameplayContext() { return new GameplayContext( this.GetConnectionStringFromFile(this.options.CacheDebugGameplay)); } } }
using Everest.Entities; using System.Threading.Tasks; namespace Everest.Repository.Interfaces { public interface IPromocionAnuncioRepository { Task<PromocionAnuncioEntity> ConsultarPromocionAsync(); Task<int> CrearPromocionAnuncioAsync(int idAnuncio); Task<bool> AgendarPromocionAnuncioAsync(PromocionAnuncioEntity entity); } }
using LuaInterface; using SLua; using System; using UnityEngine; public class Lua_FMPosSimulation : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Initialize(IntPtr l) { int result; try { FMPosSimulation fMPosSimulation = (FMPosSimulation)LuaObject.checkSelf(l); Vector3 pos_center; LuaObject.checkType(l, 2, out pos_center); fMPosSimulation.Initialize(pos_center); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Register(IntPtr l) { int result; try { FMPosSimulation fMPosSimulation = (FMPosSimulation)LuaObject.checkSelf(l); Vector3 pos_born; LuaObject.checkType(l, 2, out pos_born); float speed; LuaObject.checkType(l, 3, out speed); bool is_clockwise; LuaObject.checkType(l, 4, out is_clockwise); Action<Vector3, float> callback; LuaDelegation.checkDelegate(l, 5, out callback); int i = fMPosSimulation.Register(pos_born, speed, is_clockwise, callback); LuaObject.pushValue(l, true); LuaObject.pushValue(l, i); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int InitializeFI(IntPtr l) { int result; try { FMPosSimulation fMPosSimulation = (FMPosSimulation)LuaObject.checkSelf(l); int id; LuaObject.checkType(l, 2, out id); fMPosSimulation.InitializeFI(id); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int GetFI(IntPtr l) { int result; try { FMPosSimulation fMPosSimulation = (FMPosSimulation)LuaObject.checkSelf(l); int id; LuaObject.checkType(l, 2, out id); FlyingInfo fI = fMPosSimulation.GetFI(id); LuaObject.pushValue(l, true); LuaObject.pushValue(l, fI); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int GetPos(IntPtr l) { int result; try { FMPosSimulation fMPosSimulation = (FMPosSimulation)LuaObject.checkSelf(l); int id; LuaObject.checkType(l, 2, out id); Vector3 pos = fMPosSimulation.GetPos(id); LuaObject.pushValue(l, true); LuaObject.pushValue(l, pos); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int ResetFI(IntPtr l) { int result; try { FMPosSimulation fMPosSimulation = (FMPosSimulation)LuaObject.checkSelf(l); int id; LuaObject.checkType(l, 2, out id); Vector3 pos_born; LuaObject.checkType(l, 3, out pos_born); float speed; LuaObject.checkType(l, 4, out speed); fMPosSimulation.ResetFI(id, pos_born, speed); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int StartFI(IntPtr l) { int result; try { FMPosSimulation fMPosSimulation = (FMPosSimulation)LuaObject.checkSelf(l); int id; LuaObject.checkType(l, 2, out id); fMPosSimulation.StartFI(id); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int StopFI(IntPtr l) { int result; try { FMPosSimulation fMPosSimulation = (FMPosSimulation)LuaObject.checkSelf(l); int id; LuaObject.checkType(l, 2, out id); fMPosSimulation.StopFI(id); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int TranslatePoint(IntPtr l) { int result; try { FMPosSimulation fMPosSimulation = (FMPosSimulation)LuaObject.checkSelf(l); Vector3 p; LuaObject.checkType(l, 2, out p); Vector3 o = fMPosSimulation.TranslatePoint(p); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "FMPosSimulation"); LuaObject.addMember(l, new LuaCSFunction(Lua_FMPosSimulation.Initialize)); LuaObject.addMember(l, new LuaCSFunction(Lua_FMPosSimulation.Register)); LuaObject.addMember(l, new LuaCSFunction(Lua_FMPosSimulation.InitializeFI)); LuaObject.addMember(l, new LuaCSFunction(Lua_FMPosSimulation.GetFI)); LuaObject.addMember(l, new LuaCSFunction(Lua_FMPosSimulation.GetPos)); LuaObject.addMember(l, new LuaCSFunction(Lua_FMPosSimulation.ResetFI)); LuaObject.addMember(l, new LuaCSFunction(Lua_FMPosSimulation.StartFI)); LuaObject.addMember(l, new LuaCSFunction(Lua_FMPosSimulation.StopFI)); LuaObject.addMember(l, new LuaCSFunction(Lua_FMPosSimulation.TranslatePoint)); LuaObject.createTypeMetatable(l, null, typeof(FMPosSimulation), typeof(MonoBehaviour)); } }
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.Reflection; namespace scaner { public partial class ViewTicketMeta : Form { string data1; string data2; string data3; Globals global; public string[,] D = new string[1000, 30]; public ViewTicketMeta(string data1,string data2,string data3) { InitializeComponent(); this.data1 = data1; this.data2 = data2; this.data3 = data3; label4.Text = data1; label5.Text = data2; label6.Text = data3; global = new Globals(); } private void ViewTicketMeta_Load(object sender, EventArgs e) { dataGrid.Columns.Clear(); dataGrid.RowHeadersWidth = 4; dataGrid.Columns.Add("i", "№"); dataGrid.Columns.Add("id", "uid"); dataGrid.Columns.Add("code1", "Штрихкод"); dataGrid.Columns.Add("title", "Товар"); dataGrid.Columns.Add("count", "Кол-во"); dataGrid.Columns.Add("prize", "Цена"); dataGrid.Columns.Add("sum", "Сумма"); dataGrid.Columns[0].Width = 32; dataGrid.Columns[1].Width = 80; dataGrid.Columns[2].Width = 120; dataGrid.Columns[3].Width = 230; dataGrid.Columns[4].Width = 80; dataGrid.Columns[5].Width = 60; dataGrid.Columns[6].Width = 80; SetDoubleBuffered(dataGrid); } public static void SetDoubleBuffered(Control control) { typeof(Control).InvokeMember("DoubleBuffered", BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic, null, control, new object[] { true }); } /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// private void ViewTicketMeta_Shown(object sender, EventArgs e) { My db = new My(); db.Connect(); string query = "SELECT * FROM ticket_meta WHERE `26` = '" + data1 + "'"; db.Query(query); int i = 0; while (db.Read()) { for (int j = 0; j < 30; j++) { D[i, j] = db.GetString(j); } i++; } db.Close(); PaintGrid(); } /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// public void PaintGrid() { int increment = 1; string[] datarow = { "", "", "", "", "", "", "" }; for (int i = 0; i < 1000; i++) { if (D[i, 0] != "" && D[i, 0] != null) { datarow[0] = Convert.ToString(increment); datarow[1] = D[i, 25]; datarow[2] = D[i, 3]; datarow[3] = D[i, 4]; datarow[4] = D[i, 19]; datarow[5] = D[i, 9]; datarow[6] = D[i, 10]; if (D[i, 18] == "1") dataGrid.RowTemplate.DefaultCellStyle.BackColor = Color.LightGreen; else dataGrid.RowTemplate.DefaultCellStyle.BackColor = Color.OrangeRed; increment++; dataGrid.Rows.Add(datarow); } } } /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// private void dataGrid_KeyDown(object sender, KeyEventArgs e) { if (global.KeysCodes(e,"Close")) { this.Close(); } } /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// } }
using Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace Repository.Interface { public interface ICallLogRepository { /// <summary> /// Send Call-log /// </summary> /// <param name="call_Log"></param> /// <returns></returns> bool Send(call_log call_Log); /// <summary> /// Insert object to database /// </summary> /// <param name="call_Log"></param> /// <returns></returns> int Insert(call_log call_Log); /// <summary> /// Delete object from database /// </summary> /// <param name="id"></param> /// <returns></returns> bool Delete(int id); /// <summary> /// Update the object /// </summary> /// <param name="call_Log"></param> /// <returns></returns> bool Update(call_log call_Log, HttpPostedFileBase file, string s); //ngoctq bool Update(call_log call_Log); //end List<call_log> GetAll(); List<call_log> GetByAssinee(string assigneeAccount); List<call_log> GetByCategory(int categoryID); List<call_log> GetByAssiner(string assignerAccount); List<call_log> GetByWeek(DateTime dateTime); List<call_log> GetByMonth(DateTime dateTime); call_log GetById(int id); List<clmanager> GetClMangerById(int id); bool UpdateClMan(int id, string flow); bool SearchClMan(int id); //string GetStt_CEO(int id); List<string> GetListManagerByDepartment(string dep); //ngoctq0810 string GetStt(int id, string dep); string Validate_NewAccount(string acc); bool UpdateDeleteStatus(int id); } }
using Project_CelineGardier_2NMCT2.model; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Project.view { /// <summary> /// Interaction logic for Stages.xaml /// </summary> public partial class Stages : UserControl { public Stages() { InitializeComponent(); } private void SearchList(object sender, TextChangedEventArgs e) { ObservableCollection<Stage> stageSearch = new ObservableCollection<Stage>(Stage.GetStages().Where(x => x.Name.IndexOf(search.Text, StringComparison.OrdinalIgnoreCase) >= 0)); stages.ItemsSource = stageSearch; } private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = EnableDisableControls(); } private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) { string txt = ""; Stage item = (Stage)stages.SelectedItem; // edit stage if (item == null || !Stage.Edit(item)) { // something went wrong int id = (item == null) ? 0 : item.stageID; txt += "Error: editing stage #" + id; } if (txt == "") { txt = "Stage has been edited successfully"; } //Message.Text = txt;*/ MessageBox.Show(txt); } public bool EnableDisableControls() { return true; } } }
using System; namespace Timelogger.Api { public class ProjectOverviewModel { public int Id { get; set; } public string Name { get; set; } public double TimeLogged { get; set; } public DateTime Deadline { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace Minesweeper { public partial class EditorForm : Form { public int mapX, mapY; public Map map { get; set; } public Button[,] buttons; public Coordinate check; public EditorForm(int x, int y) { //Test values, grab real values some other way mapX = x; mapY = y; InitializeComponent(); } public void Form3_Load(object sender, EventArgs e) { buttons = new Button[mapX, mapY]; map = new Map(mapX, mapY, 0); int gridSizeInPixels = 400; //Change this at some point int offset = 50; int buttonSize = Math.Min(gridSizeInPixels / mapX, gridSizeInPixels / mapY); for (int x = 0; x < buttons.GetLength(0); x++) { for (int y = 0; y < buttons.GetLength(1); y++) { buttons[x, y] = new Button(); buttons[x, y].Top = offset + x * buttonSize; buttons[x, y].Left = offset + y * buttonSize; buttons[x, y].Width = buttonSize; buttons[x, y].Height = buttonSize; buttons[x, y].Click += new EventHandler(MapClicked); this.Controls.Add(buttons[x, y]); } } } public void MapClicked(object sender, EventArgs e) { Button button = sender as Button; bool keepLooping = true; for (int x = 0; x < buttons.GetLength(0) && keepLooping; x++) { for (int y = 0; y < buttons.GetLength(1) && keepLooping; y++) { if (buttons[x, y].Equals(button)) { Coordinate c = new Coordinate(x, y); check = c; map.squares[c].isBomb = !map.squares[c].isBomb; updateAdj(); keepLooping = false; } } } } public void ColorText(int numAdj, Button button) { switch (numAdj) { case 1: button.ForeColor = Color.Blue; break; case 2: button.ForeColor = Color.ForestGreen; break; case 3: button.ForeColor = Color.DarkRed; break; case 4: button.ForeColor = Color.Purple; break; case 5: button.ForeColor = Color.Orange; break; case 6: button.ForeColor = Color.DarkBlue; break; case 7: button.ForeColor = Color.Goldenrod; break; case 8: button.ForeColor = Color.Brown; break; default: button.ForeColor = Color.Black; break; } } [ExcludeFromCodeCoverage] private void mainMenuToolStripMenuItem_Click(object sender, EventArgs e) { MainForm menu = new MainForm(); menu.Show(); this.Hide(); } [ExcludeFromCodeCoverage] private void resetMapToolStripMenuItem_Click(object sender, EventArgs e) { EditorForm editor = new EditorForm(mapX, mapY); editor.Show(); this.Hide(); } [ExcludeFromCodeCoverage] private void saveMapToolStripMenuItem_Click(object sender, EventArgs e) { String filename = Microsoft.VisualBasic.Interaction.InputBox("Save Map", "Enter name", "", 0, 0); if (filename.Length > 0) { map.CreateMapFile(filename + ".map"); SaveOutcomeLabel.Text = "Map successfully saved!"; } else { SaveOutcomeLabel.Text = "Map could not be saved. Enter a valid filename."; } } public void updateAdj() { map.SetAdjBombVals(); for (int x = 0; x < buttons.GetLength(0); x++) { for (int y = 0; y < buttons.GetLength(1); y++) { Coordinate c = new Coordinate(x, y); Square square = map.squares[c]; if (!square.isBomb) { buttons[x, y].BackgroundImage = null; int adj = square.numAdjBombs; if (adj != 0) { buttons[x, y].Text = square.numAdjBombs.ToString(); ColorText(square.numAdjBombs, buttons[x, y]); } else { buttons[x, y].Text = ""; } } else { buttons[x, y].BackgroundImage = Properties.Resources.bomb; buttons[x, y].Text = ""; buttons[x, y].BackgroundImageLayout = ImageLayout.Stretch; } } } } } }
using UnityEngine; public struct HittingColor { public KeyCode KeyCode; public Color Color; public HittingColor(KeyCode keyCode, Color color) { KeyCode = keyCode; Color = color; } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using System.Runtime.Serialization; using Dnn.PersonaBar.Users.Components.Dto; namespace Dnn.PersonaBar.Users.Components.Contracts { [DataContract] public class GetUsersContract { public GetUsersContract() { SortColumn = "Joined"; SortAscending = false; } public int PortalId { get; set; } public string SearchText { get; set; } public int PageIndex { get; set; } public int PageSize { get; set; } public string SortColumn { get; set; } public bool SortAscending { get; set; } public UserFilters Filter { get; set; } } }
// Decompiled with JetBrains decompiler // Type: PingMonitor.HelpForm // Assembly: PingMonitor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null // MVID: C7F21AE2-E822-440B-97D1-7ECAE911FD7D // Assembly location: G:\Projects\PingMonitor\PingMonitor\bin\Debug\PingMonitor.exe using System; using System.ComponentModel; using System.Drawing; using System.Threading; using System.Windows.Forms; namespace PingMonitor { public class HelpForm : Form { private IContainer components = (IContainer) null; private Label label1; private Button closeButton; private Label helptextLabel; public HelpForm() { this.InitializeComponent(); } private void onClose(object sender, EventArgs e) { for (int index = 0; index < 10; ++index) { this.Opacity = this.Opacity - 0.1; Thread.Sleep(10); } this.Close(); } private void onLoad(object sender, EventArgs e) { this.Opacity = 0.0; } private void onShow(object sender, EventArgs e) { for (int index = 0; index < 10; ++index) { this.Opacity = this.Opacity + 0.1; Thread.Sleep(10); } } protected override void Dispose(bool disposing) { if (disposing && this.components != null) this.components.Dispose(); base.Dispose(disposing); } private void InitializeComponent() { ComponentResourceManager componentResourceManager = new ComponentResourceManager(typeof (HelpForm)); this.label1 = new Label(); this.closeButton = new Button(); this.helptextLabel = new Label(); this.SuspendLayout(); this.label1.AutoSize = true; this.label1.Font = new Font("Microsoft Sans Serif", 12f, FontStyle.Bold, GraphicsUnit.Point, (byte) 0); this.label1.Location = new Point(12, 9); this.label1.Name = "label1"; this.label1.Size = new Size(162, 20); this.label1.TabIndex = 0; this.label1.Text = "Ping Monitor - Help"; this.closeButton.FlatStyle = FlatStyle.Flat; this.closeButton.Font = new Font("Microsoft Sans Serif", 8.25f, FontStyle.Bold, GraphicsUnit.Point, (byte) 0); this.closeButton.Location = new Point(603, 12); this.closeButton.Name = "closeButton"; this.closeButton.Size = new Size(25, 25); this.closeButton.TabIndex = 3; this.closeButton.Text = "X"; this.closeButton.UseVisualStyleBackColor = true; this.closeButton.Click += new EventHandler(this.onClose); this.helptextLabel.AutoSize = true; this.helptextLabel.Location = new Point(13, 51); this.helptextLabel.Name = "helptextLabel"; this.helptextLabel.Size = new Size(562, 143); this.helptextLabel.TabIndex = 4; this.helptextLabel.Text = componentResourceManager.GetString("helptextLabel.Text"); this.AutoScaleDimensions = new SizeF(6f, 13f); this.AutoScaleMode = AutoScaleMode.Font; this.BackColor = Color.FromArgb(30, 30, 30); this.ClientSize = new Size(640, 480); this.Controls.Add((Control) this.helptextLabel); this.Controls.Add((Control) this.closeButton); this.Controls.Add((Control) this.label1); this.ForeColor = Color.White; this.FormBorderStyle = FormBorderStyle.None; this.Icon = (Icon) componentResourceManager.GetObject("$this.Icon"); this.Name = "HelpForm"; this.StartPosition = FormStartPosition.CenterScreen; this.Text = "Ping Monitor Help"; this.Load += new EventHandler(this.onLoad); this.Shown += new EventHandler(this.onShow); this.ResumeLayout(false); this.PerformLayout(); } } }
using System; using System.Collections.Generic; using System.Text; namespace Soduku { class Sudoku { int[,] board; public Sudoku() { board = new int[9, 9]; } public void SetSodukuBoard(int[,] board) { this.board = board; } public int[,] GetSodukuBoard() { return board; } public void Solve() { board = GetSodukuInput(); if (_FillMissingNumbers(board)) { Console.WriteLine("Sudoku is solved!"); Console.WriteLine(); PrintSudokuBoard(board); } else { Console.WriteLine("Sudoku cannot be solved!"); } } public int[,] GetSodukuInput() { Console.WriteLine("Enter the elements of each row" + " separated by space, colon or semi-colon"); try { for (int index = 0; index < 9; index++) { Console.WriteLine("Enter the elements of row " + index + " separated by space"); String[] elements = Console.ReadLine().Split(' ', ',', ';'); for (int elementIndex = 0; elementIndex < elements.Length; elementIndex++) { board[index, elementIndex] = int.Parse(elements[elementIndex]); } } } catch (Exception exception) { Console.WriteLine("Thrown exception is " + "" + exception.Message); } return board; } public void PrintSudokuBoard(int[,] matrix) { for (int rowIndex = 0; rowIndex < 9; rowIndex++) { for (int colIndex = 0; colIndex < 9; colIndex++) { Console.Write(matrix[rowIndex, colIndex] + " "); } Console.WriteLine(); } } private bool IndeedMissing(UnfilledPosition unfilledPosition) { return unfilledPosition.GetRowPosition() != -1 && unfilledPosition.GetColumnPosition() != -1; } private bool _FillMissingNumbers(int[,] board) { UnfilledPosition position = new UnfilledPosition(-1, -1); position = _GetMissingPosition(board); //If there is no missing number, the problem is solved! if (!IndeedMissing(position)) { return true; } for (int numberToBeFilled = 1; numberToBeFilled < 10; numberToBeFilled++) { if (CanThisNumberFilled(board, position.GetRowPosition(), position.GetColumnPosition(), numberToBeFilled)) { board[position.GetRowPosition(), position.GetColumnPosition()] = numberToBeFilled; //Recurse for other missing numbers if (_FillMissingNumbers(board)) { return true; } else { //Backtrack -> Reset the filled number board[position.GetRowPosition(), position.GetColumnPosition()] = 0; } } } return false; } private UnfilledPosition _GetMissingPosition(int[,] board) { UnfilledPosition unfilledPosition = new UnfilledPosition(-1, -1); for (int index = 0; index < 9; index++){ for (int secIndex = 0; secIndex < 9; secIndex++) { if (board[index, secIndex] == 0) { unfilledPosition.SetRowPosition(index); unfilledPosition.SetColumnPosition(secIndex); break; } } //Break out of outer for if missing position is found if (IndeedMissing(unfilledPosition)) { break; } } return unfilledPosition; } private bool CanThisNumberFilled(int[,] board, int rowPosition, int columnPosition, int number) { /* Check whether the number that we are going to fill * is already present in the same row. * If yes, we should return false */ for (int colIndex = 0; colIndex < 9; colIndex++) { if (board[rowPosition, colIndex] == number) { return false; } } /* Similarly, we should return false, if we find * the number that we are going to place is already * present in the column */ for (int rowIndex = 0; rowIndex < 9; rowIndex++) { if (board[rowIndex, columnPosition] == number) { return false; } } /* We know that as per Sudoku rules, we cannot have the * same number that we are going to fill in the same * box. That is every (3*3) box in Sudoku board * should have unique numbers from 1 to 9. */ int rowPositionStart = rowPosition - (rowPosition%3); int colPositionStart = columnPosition - (columnPosition % 3); int rowPositionEnd = rowPositionStart + 3; int colPositionEnd = colPositionStart + 3; for (int rowIndex = rowPositionStart; rowIndex < rowPositionEnd; rowIndex++) { for (int colIndex = colPositionStart; colIndex < colPositionEnd; colIndex++) { if (board[rowIndex, colIndex] == number) { return false; } } } return true; } } }
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Infrastructure.Migrations { public partial class InitialCreate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Categoria", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Categoria", x => x.Id); }); migrationBuilder.CreateTable( name: "Cliente", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Cpf = table.Column<string>(type: "nvarchar(max)", nullable: true), Email = table.Column<string>(type: "nvarchar(max)", nullable: true), Senha = table.Column<string>(type: "nvarchar(max)", nullable: true), Nome = table.Column<string>(type: "nvarchar(max)", nullable: true), Data_nascimento = table.Column<DateTime>(type: "datetime2", nullable: false), Tipo_perfil = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Cliente", x => x.Id); }); migrationBuilder.CreateTable( name: "Vendedores", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Cnpj = table.Column<string>(type: "nvarchar(max)", nullable: true), Razao_social = table.Column<string>(type: "nvarchar(max)", nullable: true), Chave_pix = table.Column<string>(type: "nvarchar(max)", nullable: true), Email = table.Column<string>(type: "nvarchar(max)", nullable: true), Senha = table.Column<string>(type: "nvarchar(max)", nullable: true), Nome = table.Column<string>(type: "nvarchar(max)", nullable: true), Data_nascimento = table.Column<DateTime>(type: "datetime2", nullable: false), Tipo_perfil = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Vendedores", x => x.Id); }); migrationBuilder.CreateTable( name: "Produtos", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Preco_desconto = table.Column<float>(type: "real", nullable: false), Preco = table.Column<float>(type: "real", nullable: false), Nome = table.Column<string>(type: "nvarchar(max)", nullable: true), Descricao = table.Column<string>(type: "nvarchar(max)", nullable: true), Url_imagem = table.Column<string>(type: "nvarchar(max)", nullable: true), Vendedor_id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Quantidade = table.Column<int>(type: "int", nullable: false), Desconto_aplicado = table.Column<bool>(type: "bit", nullable: false), Oferta_inicio = table.Column<DateTime>(type: "datetime2", nullable: false), Oferta_fim = table.Column<DateTime>(type: "datetime2", nullable: false), Desconto_porcentagem = table.Column<int>(type: "int", nullable: false), Categoria_id = table.Column<Guid>(type: "uniqueidentifier", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Produtos", x => x.Id); table.ForeignKey( name: "FK_Produtos_Categoria_Categoria_id", column: x => x.Categoria_id, principalTable: "Categoria", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Produtos_Vendedores_Vendedor_id", column: x => x.Vendedor_id, principalTable: "Vendedores", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "ProdutoCliente", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Cliente_id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Produto_id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Vendedor_id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Estrelas = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_ProdutoCliente", x => x.Id); table.ForeignKey( name: "FK_ProdutoCliente_Cliente_Cliente_id", column: x => x.Cliente_id, principalTable: "Cliente", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_ProdutoCliente_Produtos_Produto_id", column: x => x.Produto_id, principalTable: "Produtos", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_ProdutoCliente_Vendedores_Vendedor_id", column: x => x.Vendedor_id, principalTable: "Vendedores", principalColumn: "Id", onDelete: ReferentialAction.NoAction); }); migrationBuilder.CreateIndex( name: "IX_ProdutoCliente_Cliente_id", table: "ProdutoCliente", column: "Cliente_id"); migrationBuilder.CreateIndex( name: "IX_ProdutoCliente_Produto_id", table: "ProdutoCliente", column: "Produto_id"); migrationBuilder.CreateIndex( name: "IX_ProdutoCliente_Vendedor_id", table: "ProdutoCliente", column: "Vendedor_id"); migrationBuilder.CreateIndex( name: "IX_Produtos_Categoria_id", table: "Produtos", column: "Categoria_id"); migrationBuilder.CreateIndex( name: "IX_Produtos_Vendedor_id", table: "Produtos", column: "Vendedor_id"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "ProdutoCliente"); migrationBuilder.DropTable( name: "Cliente"); migrationBuilder.DropTable( name: "Produtos"); migrationBuilder.DropTable( name: "Categoria"); migrationBuilder.DropTable( name: "Vendedores"); } } }
using Microsoft.AspNet.Http.Extensions; using Microsoft.AspNet.Mvc; namespace HaloHistory.Web.Controllers { public class HomeController : Controller { public IActionResult Index() { if (Request.Path.HasValue && !Request.Path.Value.EndsWith("/")) { return Redirect(Request.Path.Value + "/"); } if (!Request.GetDisplayUrl().EndsWith("/")) { return Redirect(Request.GetDisplayUrl() + "/"); } ViewBag.BaseHref = Request.PathBase + "/"; return View(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Kers.Models.Entities.KERScore { public partial class LadderStageRole : IEntityBase { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public LadderStage LadderStage { get; set; } public int LadderStageId { get; set; } public zEmpRoleType zEmpRoleType { get; set; } public int zEmpRoleTypeId { get; set; } } }
using System; namespace Tff.Panzer.Models.Army { public enum EmbarkTypeEnum { Air = 0, Sea = 1, None = 2 } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Linq; namespace HaloOnlineVersionBrowser { public partial class Form1 : Form { List<Build> _list = new List<Build>(); List<string> _VersionList = new List<string>(); string _downloaddir = AppDomain.CurrentDomain.BaseDirectory + "DownLoads\\"; string _downloadurl = string.Empty; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { AnalysisJson(); this.gbContent.Text = "Welcome"; this.DownLoadbtn.Text = "开始"; this.lbVersion.Enabled = this.Versionlb.Visible = this.VersionTitlelb.Visible = this.Authorlb.Visible = this.AuthorTitlelb.Visible = this.FileSizelb.Visible = this.FileSizeTilelb.Visible = this.commitIdlb.Visible = this.commitMessagelb.Visible = this.commitTitlelb.Visible = this.DownLoadStatespb.Visible = this.CommitTimeTilelab.Visible = this.commitTimelb.Visible = false; } private void lbVersion_Click(object sender, EventArgs e) { var index = this.lbVersion.SelectedIndex; if (index > -1) { this.DownLoadbtn.Text = "下载"; this.DownLoadbtn.Visible = this.Versionlb.Visible = this.VersionTitlelb.Visible = this.Authorlb.Visible = this.AuthorTitlelb.Visible = this.FileSizelb.Visible = this.FileSizeTilelb.Visible = this.commitIdlb.Visible = this.commitMessagelb.Visible = this.commitTitlelb.Visible = this.CommitTimeTilelab.Visible = this.DownLoadStatespb.Visible = this.commitTimelb.Visible = true; this.Versionlb.Text = _list[index].BuildVersion; this.Authorlb.Text = _list[index].CommitAuthor; this.FileSizelb.Text = (Convert.ToInt32(_list[index].size) / 1000000).ToString("0MB"); this.commitIdlb.Text = _list[index].CommitId; this.commitMessagelb.Text = _list[index].CommitMessage; _downloadurl = _list[index].downloadUrl; this.branchlb.Text = _list[index].Branch; this.commitTimelb.Text = _list[index].CommitDate.ToString(); this.commitIdlb.Links[0].LinkData = "https://github.com/ElDewrito/ElDorito/commit/" + _list[index].CommitId; } } bool FindDir() { if (Directory.Exists(_downloaddir)) { return true; } else { Directory.CreateDirectory(_downloaddir); return FindDir(); } } void AnalysisJson() { var BuildString = (new WebClient()).DownloadString("https://dewrito.halo.click/api/builds"); _list = JsonConvert.DeserializeObject<List<JObject>>(BuildString).Select((t) => { JArray jar = JArray.Parse(t["artifacts"].ToString()); Build b = new Build() { Branch = t["branch"].ToString(), BuildVersion = t["buildVersion"].ToString(), CommitAuthor = t["commitAuthor"].ToString(), CommitId = t["commitId"].ToString(), CommitMessage = t["commitMessage"].ToString(), downloadUrl = t["downloadUrl"].ToString(), CommitDate = Convert.ToDateTime(t["commitDate"]) }; for (var i = 0; i < jar.Count; i++) { JObject j = JObject.Parse(jar[i].ToString()); b.size = j["size"].ToString(); b.url = j["url"].ToString(); } return b; }).ToList() as List<Build>; _list.Reverse(); } private void DownLoadbtn_Click(object sender, EventArgs e) { if (DownLoadbtn.Text == "开始") { if (_list.Count > 0) { this.gbContent.Text = "版本信息"; this.DownLoadbtn.Visible = this.Devlab.Visible = false; lbVersion.DataSource = new List<string>(_list.Select((t) => { return t.BuildVersion; })); this.lbVersion.Enabled = true; } } else if (DownLoadbtn.Text == "下载") { if (!string.IsNullOrEmpty(_downloadurl)&&FindDir()) { this.DownLoadbtn.Enabled = false; this.lbVersion.Enabled = false; WebClient downloader = new WebClient(); downloader.DownloadFileCompleted += DownLoadCompleted; downloader.DownloadProgressChanged += DownLoadProgressChanged; downloader.DownloadFileAsync(new System.Uri(_downloadurl), _downloaddir + _downloadurl.Substring(_downloadurl.LastIndexOf("/") + 1)); } else { MessageBox.Show("请先选择版本", "Halo Online Version Browser"); } } } private void DownLoadCompleted(object sender, AsyncCompletedEventArgs e) { MessageBox.Show("下载完毕!", "Halo Online Version Browser"); this.lbVersion.Enabled = this.DownLoadbtn.Enabled = true; DownLoadStatespb.Value = 0; Process.Start(_downloaddir); } void DownLoadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { DownLoadStatespb.Value = e.ProgressPercentage; } private void commitIdlb_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start(e.Link.LinkData.ToString()); } } }
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using System; using System.Collections.Generic; using System.Text; namespace HangoutsDbLibrary.Data { public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<HangoutsContext> { public HangoutsContext CreateDbContext(string[] args) { var builder = new DbContextOptionsBuilder<HangoutsContext>(); builder.UseSqlServer(Configuration.ConnectionString); return new HangoutsContext(builder.Options); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Pitstop { public class HHRelai : MonoBehaviour { [SerializeField] bool isFinalRelay = false; [SerializeField] GameObject nextPoint = default; GorillaBehaviour gorillaBehaviour; private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.name == "Hammerhead(Clone)") { if (isFinalRelay) { Destroy(collision.gameObject); } gorillaBehaviour = collision.gameObject.GetComponent<GorillaBehaviour>(); if (!isFinalRelay) { gorillaBehaviour.target = nextPoint; gorillaBehaviour.targetPos = nextPoint.transform.position; } gorillaBehaviour.isFleeing = true; } } } }
using System; using System.Collections.Generic; using System.Linq; using ALTechTest.DataTransferObjects; namespace ALTechTest.ViewModels { public class RecordingViewModel { public RecordingViewModel(RecordingDto recording) { Id = recording.Id; Title = recording.Title; Length = recording.Length; Disambiguation = recording.Disambiguation; Relationships = recording.Relationships.Select(x => new RelationshipViewModel(x)); } public string Disambiguation { get; set; } public Guid Id { get; set; } public int? Length { get; set; } public IEnumerable<RelationshipViewModel> Relationships { get; set; } public string Title { get; set; } } }
using UnityEngine; using System.Collections; namespace AntColony { public class PheromoneGland : MonoBehaviour { [Tooltip("The radius of the produced pheromone trail")] public float Diameter = 1; [Tooltip("The delay in seconds between each pheromone production step")] public float ProductionRate = 0.25f; [Tooltip("The pheromone trail prefab that this gland will instantiate")] public PheromoneTrail trailPrefab; public GameObject trailContainer; /// <summary> /// Checks whether or not this trail is currently producing pheromones /// </summary> public bool Producing { get { return activeTrail != null; } } private PheromoneTrail activeTrail; /// <summary> /// Begins production of a pheromone trail. The trail will be extended until the StopProduction method is called /// </summary> public void BeginProduction() { // Instantiate new trail, set diameter activeTrail = Instantiate(trailPrefab, Vector3.zero, Quaternion.identity) as PheromoneTrail; activeTrail.transform.parent = trailContainer.transform; activeTrail.Diameter = Diameter; // Continuously add to trail, until StopProduction is called InvokeRepeating("AppendToTrail", 0, ProductionRate); } /// <summary> /// Stops production of the pheromone trail and returns it. /// </summary> /// <returns></returns> public PheromoneTrail StopProduction() { // Stop appending to trail CancelInvoke("AppendToTrail"); // Return finished trail PheromoneTrail finishedTrail = activeTrail; activeTrail = null; return finishedTrail; } /// <summary> /// Appends the glands current position to the active trail /// </summary> void AppendToTrail() { activeTrail.Append(transform.position); } } }
using PropertyChanged; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PuddingWolfLoader.Framework.ViewModel { [AddINotifyPropertyChangedInterface] public class DashboardViewModel { public int ModuleCount { get; set; } public string SystemStatus { get; set; } = "运行中"; public string IMStatus { get; set; } = "IM运行中"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; namespace PricingService { public interface IProductRepository { Product GetProduct(int productId); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MusicManager : MonoBehaviour { public AudioSource music; public AudioSource explosion; public AudioSource keyboard; public AudioClip[] keyPresses; public AudioClip[] musicLoops; public AudioClip[] explosions; public AudioClip bigExplosion; private int loopIndex = 0; private bool nextLoop = false; public void PlayMusic() { music.clip = musicLoops[loopIndex]; music.Play(); } public void StopMusic() { music.Stop(); } public void SetIndex(int index) { if(index != loopIndex && index < musicLoops.Length && index > 0) { loopIndex = index; music.loop = false; nextLoop = true; } } public void PlayKeyboardClick() { keyboard.clip = keyPresses[Random.Range(0, keyPresses.Length - 1)]; keyboard.pitch = Random.Range(0.9f, 1f); keyboard.Play(); } public void PlayExplosion() { explosion.clip = explosions[Random.Range(0, explosions.Length - 1)]; explosion.pitch = Random.Range(0.95f, 1f); explosion.Play(); } public void PlayBigExplosion() { explosion.clip = bigExplosion; explosion.Play(); } private void Start() { } private void Update() { if (nextLoop && !music.isPlaying) { nextLoop = false; music.loop = true; PlayMusic(); } if (Input.anyKeyDown) { PlayKeyboardClick(); } } }
using OpenTK; namespace Calcifer.Engine.Particles { public class Particle { private readonly ParticlePool owner; internal readonly int ID; internal bool Destroyed; public Vector3 Position, Velocity, Force; public float Rotation, AngularVelocity, TTL; public bool IsActive { get { return TTL > 0; } } public IBehavior Behavior { get; internal set; } internal Particle(ParticlePool owner, int id) { Destroyed = true; this.owner = owner; ID = id; } public void Update(float time) { if (Destroyed) return; if (IsActive) { TTL -= time; Behavior.Update(this, time); Vector3 temp; Vector3.Multiply(ref Force, time, out temp); Vector3.Add(ref Velocity, ref temp, out Velocity); Vector3.Multiply(ref Velocity, time, out temp); Vector3.Add(ref Position, ref temp, out Position); Rotation += time * AngularVelocity; } else Destroy(); } public void Destroy() { owner.Destroy(this); } } }
using System; using Share; using UnityEngine; namespace Viewer { public sealed class PointDataSupplierUdp : MonoBehaviour, IPointDataSupplier { [SerializeField] private PackedMessageSupplier packedMessageSupplier; public IObservable<PackedMessage.IdentifiedPointArray> OnReceivePointData() { return packedMessageSupplier.ObservablePointArray; } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // #region Usings using System; using DotNetNuke.Security; #endregion namespace DotNetNuke.Services.EventQueue.Config { [Serializable] public class SubscriberInfo { public SubscriberInfo() { ID = Guid.NewGuid().ToString(); Name = ""; Description = ""; Address = ""; var oPortalSecurity = PortalSecurity.Instance; PrivateKey = oPortalSecurity.CreateKey(16); } public SubscriberInfo(string subscriberName) : this() { Name = subscriberName; } public string ID { get; set; } public string Name { get; set; } public string Description { get; set; } public string Address { get; set; } public string PrivateKey { get; set; } } }