text
stringlengths
13
6.01M
/* Copyright (c) 2011-2012, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using Hl7.Fhir.Model; using System.Xml.Linq; using Hl7.Fhir.Parsers; using System.IO; using Hl7.Fhir.Serializers; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Hl7.Fhir.Support { public partial class Bundle { public const string JATOM_VERSION = "version"; public const string JATOM_DELETED = "deleted"; public static Bundle Load(JsonReader reader, ErrorList errors) { JObject feed; reader.DateParseHandling = DateParseHandling.DateTimeOffset; try { feed = JObject.Load(reader); } catch (Exception exc) { errors.Add("Exception while loading feed: " + exc.Message); return null; } Bundle result; try { result = new Bundle() { Title = feed.Value<string>(XATOM_TITLE), LastUpdated = feed.Value<DateTimeOffset?>(XATOM_UPDATED), Id = new Uri(feed.Value<string>(XATOM_ID), UriKind.Absolute), AuthorName = feed[XATOM_AUTHOR] as JArray != null ? feed[XATOM_AUTHOR] .Select(auth => auth.Value<string>(XATOM_AUTH_NAME)) .FirstOrDefault() : null, AuthorUri = feed[XATOM_AUTHOR] as JArray != null ? feed[XATOM_AUTHOR] .Select(auth => auth.Value<string>(XATOM_AUTH_URI)) .FirstOrDefault() : null }; result.Links = new UriLinkList(); result.Links.AddRange( getLinks(feed[XATOM_LINK]) ); } catch (Exception exc) { errors.Add("Exception while parsing feed attributes: " + exc.Message, String.Format("Feed '{0}'", feed.Value<string>(XATOM_ID))); return null; } if( feed[XATOM_ENTRY] != null ) result.Entries = result.loadItems(feed[XATOM_ENTRY], errors); errors.AddRange(result.Validate()); return result; } public static Bundle LoadFromJson(string json, ErrorList errors) { return Bundle.Load(Util.JsonReaderFromString(json), errors); } private ManagedEntryList loadItems( JToken token, ErrorList errors ) { var result = new ManagedEntryList(this); JArray items = (JArray)token; foreach (var item in items) { result.Add(loadItem(item, errors)); } return result; } private BundleEntry loadItem(JToken item, ErrorList errors) { BundleEntry result; errors.DefaultContext = "An atom entry"; string id = item.Value<string>(XATOM_ID); if (id != null) errors.DefaultContext = String.Format("Entry '{0}'", id); try { string category = getCategoryFromEntry(item); if (item.Value<DateTimeOffset?>(JATOM_DELETED) != null) result = new DeletedEntry(); else if (category == XATOM_CONTENT_BINARY) result = new BinaryEntry(); else result = new ResourceEntry(); result.SelfLink = getLinks(item[XATOM_LINK]).SelfLink; result.Id = new Uri(id, UriKind.Absolute); if (result is DeletedEntry) ((DeletedEntry)result).When = item.Value<DateTimeOffset>(JATOM_DELETED); else { ContentEntry ce = (ContentEntry)result; ce.Title = item.Value<string>(XATOM_TITLE); ce.LastUpdated = item.Value<DateTimeOffset?>(XATOM_UPDATED); ce.Published = item.Value<DateTimeOffset?>(XATOM_PUBLISHED); ce.EntryAuthorName = item[XATOM_AUTHOR] as JArray != null ? item[XATOM_AUTHOR] .Select(auth => auth.Value<string>(XATOM_AUTH_NAME)) .FirstOrDefault() : null; ce.EntryAuthorUri = item[XATOM_AUTHOR] as JArray != null ? item[XATOM_AUTHOR] .Select(auth => auth.Value<string>(XATOM_AUTH_URI)) .FirstOrDefault() : null; if (result is ResourceEntry) ((ResourceEntry)ce).Content = getContents(item[XATOM_CONTENT], errors); else getBinaryContentsFromEntry(item[XATOM_CONTENT], (BinaryEntry)ce, errors); }; } catch (Exception exc) { errors.Add("Exception while reading entry: " + exc.Message); return null; } finally { errors.DefaultContext = null; } return result; } private static string getCategoryFromEntry(JToken item) { return item[XATOM_CATEGORY] as JArray != null ? item[XATOM_CATEGORY] .Where(cat => cat.Value<string>(XATOM_CAT_SCHEME) == ATOM_CATEGORY_RESOURCETYPE_NS) .Select(scat => scat.Value<string>(XATOM_CAT_TERM)) .FirstOrDefault() : null; } private static Resource getContents(JToken token, ErrorList errors) { //TODO: This is quite inefficient. The Json parser has just parsed this //entry's Resource from json, now we are going to serialize it to as string //just to read from it again using a JsonTextReader. But that is what my //parser takes as input, so no choice for now... string contents = token.ToString(); JsonTextReader r = new JsonTextReader(new StringReader(contents)); return FhirParser.ParseResource( new JsonFhirReader(r), errors); } private static void getBinaryContentsFromEntry(JToken entryContent, BinaryEntry result, ErrorList errors) { JToken binaryObject = entryContent[XATOM_CONTENT_BINARY]; if (binaryObject != null) { result.MediaType = binaryObject.Value<string>(XATOM_CONTENT_BINARY_TYPE); JToken binaryContent = binaryObject[XATOM_CONTENT]; if (binaryContent != null) result.Content = Convert.FromBase64String(binaryContent.ToString()); } } public void Save(JsonWriter writer) { JObject result = new JObject(); if (!String.IsNullOrWhiteSpace(Title)) result.Add(new JProperty(XATOM_TITLE, Title)); if (LastUpdated != null) result.Add(new JProperty(XATOM_UPDATED, LastUpdated)); if (Util.UriHasValue(Id)) result.Add(new JProperty(XATOM_ID, Id)); if (Links.Count > 0) result.Add(new JProperty(XATOM_LINK, jsonCreateLinkArray(Links))); if (!String.IsNullOrWhiteSpace(AuthorName)) result.Add(jsonCreateAuthor(AuthorName, AuthorUri)); var entryArray = new JArray(); foreach( var entry in Entries ) { if( entry is ContentEntry ) entryArray.Add(jsonCreateContentEntry((ContentEntry)entry)); else if( entry is DeletedEntry ) entryArray.Add(jsonCreateDeletedEntry((DeletedEntry)entry)); } result.Add(new JProperty(XATOM_ENTRY, entryArray)); result.WriteTo(writer); } public string ToJson() { StringBuilder resultBuilder = new StringBuilder(); StringWriter sw = new StringWriter(resultBuilder); JsonWriter jw = new JsonTextWriter(sw); Save(jw); jw.Flush(); jw.Close(); return resultBuilder.ToString(); } public byte[] ToJsonBytes() { return Encoding.UTF8.GetBytes(ToJson()); } private JArray jsonCreateLinkArray(UriLinkList links) { var result = new JArray(); foreach(var l in links) result.Add(jsonCreateLink(l.Rel, l.Uri)); return result; } private JObject jsonCreateLink(string rel, Uri link) { return new JObject( new JProperty(XATOM_LINK_REL, rel), new JProperty(XATOM_LINK_HREF, link.ToString())); } private JObject jsonCreateDeletedEntry(DeletedEntry entry) { JObject newItem = new JObject(); newItem.Add(new JProperty(JATOM_DELETED, entry.When)); newItem.Add(new JProperty(XATOM_ID, entry.Id.ToString())); if (Util.UriHasValue(entry.SelfLink)) newItem.Add(new JProperty(XATOM_LINK, new JArray(jsonCreateLink(Util.ATOM_LINKREL_SELF, entry.SelfLink)))); return newItem; } private JObject jsonCreateContentEntry(ContentEntry ce) { JObject newItem = new JObject(); if (!String.IsNullOrWhiteSpace(ce.Title)) newItem.Add(new JProperty(XATOM_TITLE, ce.Title)); if (Util.UriHasValue(ce.SelfLink)) newItem.Add(new JProperty(XATOM_LINK, new JArray(jsonCreateLink(Util.ATOM_LINKREL_SELF, ce.SelfLink)))); if (Util.UriHasValue(ce.Id)) newItem.Add(new JProperty(XATOM_ID, ce.Id.ToString())); if (ce.LastUpdated != null) newItem.Add(new JProperty(XATOM_UPDATED, ce.LastUpdated)); if (ce.Published != null) newItem.Add(new JProperty(XATOM_PUBLISHED, ce.Published)); if (!String.IsNullOrWhiteSpace(ce.EntryAuthorName)) newItem.Add(jsonCreateAuthor(ce.EntryAuthorName, ce.EntryAuthorUri)); if (ce.Summary != null) newItem.Add(new JProperty(XATOM_SUMMARY, ce.Summary)); if(ce is ResourceEntry) { ResourceEntry re = (ResourceEntry)ce; if (!String.IsNullOrWhiteSpace(re.ResourceType)) newItem.Add(new JProperty(XATOM_CATEGORY, new JArray(jsonCreateCategory(re.ResourceType)))); if (re.Content != null) newItem.Add(new JProperty(XATOM_CONTENT, getContentsAsJObject(re.Content))); } else if(ce is BinaryEntry) { BinaryEntry be = (BinaryEntry)ce; newItem.Add(new JProperty(XATOM_CATEGORY, new JArray(jsonCreateCategory(XATOM_CONTENT_BINARY)))); if (be.Content != null) { newItem.Add(new JProperty(XATOM_CONTENT, new JObject( new JProperty( XATOM_CONTENT_BINARY, new JObject( new JProperty( XATOM_CONTENT_BINARY_TYPE, be.MediaType ), new JProperty( XATOM_CONTENT, Convert.ToBase64String(be.Content)) ) ) ) )); } } else throw new NotSupportedException("Cannot serialize unknown entry type " + ce.GetType().Name); return newItem; } private static JProperty jsonCreateAuthor(string name, string uri) { JObject author = new JObject(new JProperty(XATOM_AUTH_NAME, name)); if (!String.IsNullOrWhiteSpace(uri)) author.Add(new JProperty(XATOM_AUTH_URI, uri)); return new JProperty(XATOM_AUTHOR, new JArray(author)); } private static JObject jsonCreateCategory(string category) { return new JObject( new JProperty(XATOM_CAT_TERM, category), new JProperty(XATOM_CAT_SCHEME, ATOM_CATEGORY_RESOURCETYPE_NS)); } private JObject getContentsAsJObject(Resource resource) { StringWriter w = new StringWriter(); //TODO: This would be much more efficient if we could serialize //the resource to a JObject directly FhirSerializer.SerializeResource(resource, new JsonTextWriter(w)); JsonTextReader reader = new JsonTextReader(new StringReader(w.ToString())); reader.DateParseHandling = DateParseHandling.None; return JObject.Load(reader); } private static UriLinkList getLinks( JToken token ) { var result = new UriLinkList(); var links = token as JArray; if (links != null) { foreach (var link in links) { if (link.Value<string>(XATOM_LINK_HREF) != null) result.Add(new UriLinkEntry { Rel = link.Value<string>(XATOM_LINK_REL), Uri = new Uri(link.Value<string>(XATOM_LINK_HREF), UriKind.RelativeOrAbsolute) }); } } return result; } } }
using NUnit.Framework; using WorkLog.Controllers; using WorkLog.Models; using WorkLog.Repositories; namespace WorkLog.Test.UnitTests.ControllersTests { public class TimeClockControllerTest { [Test] public void GetTimeClock_CallRepositoryGetAll() { //arrange var mockTimeClockRepository = new Moq.Mock<ITimeClockRepository>(); mockTimeClockRepository.Setup(x => x.GetAll()); var timeClockController = new TimeClockController(mockTimeClockRepository.Object); //act timeClockController.GetTimeClock(); //assert mockTimeClockRepository.VerifyAll(); } [Test] public void GetTimeClock_PassingAnUserNameThatDoesntExistis_ReturnNull() { //arrange var userName = "Nobody"; var mockTimeClockRepository = new Moq.Mock<ITimeClockRepository>(); mockTimeClockRepository.Setup(x => x.GetByUserName(userName)).Returns<TimeClock>(null); var timeClockController = new TimeClockController(mockTimeClockRepository.Object); //act timeClockController.GetTimeClock(userName); //assert mockTimeClockRepository.VerifyAll(); } [Test] public void GetTimeClock_PassingAnUserNameThatExistis_ReturnATimeClock() { //arrange var userName = "Nobody"; var expectedTimeClock = new TimeClock(userName); var mockTimeClockRepository = new Moq.Mock<ITimeClockRepository>(); mockTimeClockRepository.Setup(x => x.GetByUserName(userName)).Returns(expectedTimeClock); var timeClockController = new TimeClockController(mockTimeClockRepository.Object); //act timeClockController.GetTimeClock(userName); //assert mockTimeClockRepository.VerifyAll(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace IPC2Proyecto { public partial class Registro : System.Web.UI.Page { //localhost.Usuario u = new IPC2Proyecto.localhost.Usuario(); protected void Page_Load(object sender, EventArgs e) { } protected void btt_registrar_Click(object sender, EventArgs e) { localhost.Usuario u = new localhost.Usuario(); u.AgregarUsuario(txt_nombre.Text, txt_email.Text, txt_nac.Text, txt_nick.Text, txt_pass.Text, txt_karma.Text); limpiarTXT(); } protected void limpiarTXT() { txt_nombre.Text = " "; txt_email.Text = " "; txt_nac.Text = " "; txt_nick.Text = " "; txt_pass.Text = " "; txt_karma.Text = " "; } } }
namespace ApartmentApps.Portal.Controllers { public interface IServiceQueryVariableProvider { object GetVariable(string name); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Web.Security; using Mvc3ToolsUpdateWeb_Default.Models; using MvcMusicStore.Models; namespace Mvc3ToolsUpdateWeb_Default.Controllers { public class AccountController : Controller { private void MigrateShoppingCart(string UserName) { var cart = ShoppingCart.GetCart(this.HttpContext); cart.MigrateCart(UserName); Session[ShoppingCart.CartSessionKey] = UserName; } public ActionResult LogOn() { return View(); } [HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl) { if (ModelState.IsValid) { if (Membership.ValidateUser(model.UserName, model.Password)) { MigrateShoppingCart(model.UserName); FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } else { ModelState.AddModelError("", "El nombre de usuario o contraseña es incorrecta."); } } return View(model); } public ActionResult LogOff() { FormsAuthentication.SignOut(); return RedirectToAction("Index", "Home"); } public ActionResult Register() { return View(); } [HttpPost] public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { MembershipCreateStatus createStatus; Membership.CreateUser(model.UserName, model.Password, model.Email, "question", "answer", true, null, out createStatus); if (createStatus == MembershipCreateStatus.Success) { MigrateShoppingCart(model.UserName); FormsAuthentication.SetAuthCookie(model.UserName, false); return RedirectToAction("Index", "Home"); } else { ModelState.AddModelError("", ErrorCodeToString(createStatus)); } } return View(model); } [Authorize] public ActionResult ChangePassword() { return View(); } [Authorize] [HttpPost] public ActionResult ChangePassword(ChangePasswordModel model) { if (ModelState.IsValid) { bool changePasswordSucceeded; try { MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true); changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword); } catch (Exception) { changePasswordSucceeded = false; } if (changePasswordSucceeded) { return RedirectToAction("ChangePasswordSuccess"); } else { ModelState.AddModelError("", "La contraseña actual es incorrecta o la nueva contraseña es invalida."); } } return View(model); } public ActionResult ChangePasswordSuccess() { return View(); } #region Status Codes private static string ErrorCodeToString(MembershipCreateStatus createStatus) { switch (createStatus) { case MembershipCreateStatus.DuplicateUserName: return "El usuario ya existe. Por favor ingrese un nombre de usuario diferente."; case MembershipCreateStatus.DuplicateEmail: return "Un nombre de usuario para ese correo ya existe. Por favor ingrese un correo electronico diferente."; case MembershipCreateStatus.InvalidPassword: return "La contraseña ingresada es invalida. Por favor ingrese una contraseña valida."; case MembershipCreateStatus.InvalidEmail: return "El correo electronico es invalido. Por favor verifique el valor e intentelo de nuevo."; case MembershipCreateStatus.InvalidAnswer: return "La respuesta a la pregunta de la recuperacion de contraseña es invalida. Por favor verifique el valor e intentelo de nuevo."; case MembershipCreateStatus.InvalidQuestion: return "La pregunta de la recuperacion de contraseña es invalida. Por favor verifique el valor e intentelo de nuevo."; case MembershipCreateStatus.InvalidUserName: return "El nombre de usuario provisto es invalido. Por favor verifique el valor e intentelo de nuevo."; case MembershipCreateStatus.ProviderError: return "La autenticacion provista ha retornado un error. Por favor verifique e intentelo de nuevo. Si el problema persiste, por favor contacte al administrador."; case MembershipCreateStatus.UserRejected: return "La creacion de usuario ha sido cancelada. Por favor verifique e intentelo de nuevo. Si el problema persiste, por favor contacte al administrador."; default: return "Un error desconocido ha ocurrido. Por favor verifique e intentelo de nuevo. Si el problema persiste, por favor contacte al administrador."; } } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using FairyGUI; public class ChessInfoUIPanel : GUIBase { private Dictionary<ChessEntity, GComponent> m_infos = new Dictionary<ChessEntity, GComponent>(); protected override void OnStart() { base.OnStart(); UIPackage.AddPackage("ChessInfo", (string name, string extension, System.Type type) => { return AssetLoadManager.LoadAsset("ui/chessinfo.bundle", name, type); }); } public void ShowChessInfo(ChessEntity chess) { GComponent info = (GComponent)UIPackage.CreateObject("ChessInfo", "ChessInfoItem"); if(info == null) { Debug.LogError("show chess info error."); return; } this.AddChild(info); GTextField name = info.GetChild("name").asTextField; name.text = chess.chessCfg.Name; m_infos.Add(chess, info); } public void RemoveChessInfo(ChessEntity chess) { if(m_infos.ContainsKey(chess)) { GComponent info = m_infos[chess]; m_infos.Remove(chess); info.RemoveFromParent(); info.Dispose(); } } protected override void OnUpdate() { base.OnUpdate(); foreach (var chess in m_infos.Keys) { Vector3 screenPos = Camera.main.WorldToScreenPoint(chess.transform.position); //原点位置转换 screenPos.y = Screen.height - screenPos.y; Vector2 pt = GRoot.inst.GlobalToLocal(screenPos); m_infos[chess].SetXY(pt.x, pt.y); GTextField hp = m_infos[chess].GetChild("hp").asTextField; hp.text = string.Format("{0}/{1}", chess.HP, chess.chessObj.max_hp); } } }
using System; using System.Collections.Generic; using System.Net; using System.Xml.Serialization; using System.Net.Http.Headers; using System.IO; using System.Net.Http; using ShutterflyStatusPost.mapi; namespace ShutterflyStatusPost { class StatusCommunication { public void PostData(LabStatus status, string uri) { Utils ut = new Utils(); HttpResponseMessage resp = new HttpResponseMessage(); string response; try { using (WebClient client = new WebClient()) { client.Headers.Add(HttpRequestHeader.Accept, "text/xml"); XmlSerializer serializer = new XmlSerializer(typeof(LabStatus)); using (StringWriter ms = new StringWriter()) { serializer.Serialize(ms, status); response = client.UploadString(uri, ms.ToString()); //var retStatus = (MessageResponseType)serializer.Deserialize(myStream); //} } SuccessType success = new SuccessType(); ErrorType error = new ErrorType(); //if (retStatus.Item.GetType() == typeof(SuccessType)) //{ // success = (SuccessType)retStatus.Item; // foreach (var prop in success.properties) // { // } //} //else //{ // error = (ErrorType)retStatus.Item; // foreach (var prop in error.properties) // { // } //} } } catch (Exception ex) { Console.WriteLine(ex.Message); } } public void PutData(string uri,string OrderNo) { OrderStatusType retStatus = new OrderStatusType(); Utils ut = new Utils(); using (WebClient client = new WebClient()) { client.Headers.Add(HttpRequestHeader.Accept, "text/xml"); client.QueryString.Add("order", OrderNo); var response = client.DownloadString(uri); XmlSerializer serializer = new XmlSerializer(typeof(OrderStatusType)); using (StringWriter sw = new StringWriter()) { using (MemoryStream myStream = new MemoryStream(ut.StringToUTF8ByteArray(response))) { retStatus = (OrderStatusType)serializer.Deserialize(myStream); } } } } public void SendTask(string uri, LabStatus status) { string retVal = "OK"; string dependencypath = @"\\ps1\dev\TaskQueueWorkers"; using (var client = new HttpClient()) { client.BaseAddress = new Uri(uri); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = client.PutAsJsonAsync<QueuedTask>("api/TaskQueue/task.sendstatus", new QueuedTask() { Method = "ShutterflyOrderStatus", Payload = Newtonsoft.Json.Linq.JObject.FromObject(status), Tags = new Dictionary<string, string>() { { "ShutterflyOrderNo", status.orderNo } }, MaxRetries = 3, RetryWait = TimeSpan.FromMinutes(2), OnFinalError = new QueuedTask() { Method = "Email", MaxRetries = 10, Tags = new Dictionary<string, string>() { { "ShutterflyOrderNo", status.orderNo} }, Payload = Newtonsoft.Json.Linq.JObject.FromObject(new { To = new string[] { "dougb@millerslab.com, marcusm@millerslab.com, luked@millerslab.com" }, From = "taskerror@millerslab.com", Subject = "ShutterflyOrderStatus errored", Body = "{{_erroredtask}}", DependencySources = new List<string>() { Path.Combine(dependencypath, "Standard"), Path.Combine(dependencypath, "Shutterfly") } }) }, DependencySources = new List<string>() { Path.Combine(dependencypath, "Standard"), Path.Combine(dependencypath, "Shutterfly") } } ); if (response.Result.IsSuccessStatusCode) { var resp = response.Result.Content.ReadAsAsync<Guid>(); resp.Wait(); } else { retVal = ((int)response.Result.StatusCode).ToString() + " " + response.Result.ReasonPhrase; } } } } }
using System.Collections.Generic; using UnityEngine; public class Localization : SingletonMonoBehaviour<Localization> { Dictionary<string, string> _localizedText = new Dictionary<string, string>(); protected override void Awake() { base.Awake(); DontDestroyOnLoad(this); LoadLocalizedText(); } private void LoadLocalizedText(string language = "en") { TextAsset textAsset = Resources.Load<TextAsset>("Localization/" + language); if (textAsset != null) { string[] textRows = textAsset.text.Split(new char[] { '\n' }); for (int loop = 0; loop < textRows.Length; loop++) { string[] textCols = textRows[loop].Split(new string[] { " ~ " }, System.StringSplitOptions.None); if (textCols.Length > 1) _localizedText.Add(textCols[0], textCols[1].Replace("\\n", "\n")); } Debug.Log("Data loaded, dictionary contains: " + _localizedText.Count + " entries"); } } public string Get(string key) { if (!_localizedText.ContainsKey(key)) return key; return _localizedText[key]; } }
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 FXB.DataManager; using FXB.Data; using FXB.Common; namespace FXB.Dialog { public partial class PayDataDlg : Form { public PayDataDlg() { InitializeComponent(); } private void InquireBtn_Click(object sender, EventArgs e) { if (-1 == monthSelectCb.SelectedIndex) { return; } string qtKey = monthSelectCb.SelectedItem as string; if (!PayDataMgr.Instance().AllQtPay.ContainsKey(qtKey)) { MessageBox.Show("工资没有生成"); return; } myDataGridView1.Rows.Clear(); SortedDictionary<string, PayData> allPayData = PayDataMgr.Instance().AllQtPay[qtKey]; QtTask qtTask = QtMgr.Instance().AllQtTask[qtKey]; foreach (var item in qtTask.AllQtEmployee) { QtEmployee data = item.Value; int lineIndex = myDataGridView1.Rows.Add(); DataGridViewRow row = myDataGridView1.Rows[lineIndex]; row.Cells["qtkey"].Value = qtKey; row.Cells["gonghao"].Value = item.Key; EmployeeData employeeData = EmployeeDataMgr.Instance().AllEmployeeData[item.Key]; row.Cells["name"].Value = employeeData.Name; row.Cells["bumen"].Value = DepartmentUtil.GetQtDepartmentShowText(qtTask, QtTaskUtil.GetJobDepartmentIdByQtTask(qtTask, item.Key)); if (allPayData.ContainsKey(item.Key)) { PayData patData = allPayData[item.Key]; row.Cells["qtpay"].Value = DoubleUtil.Show(patData.CurPay); } else { row.Cells["qtpay"].Value = DoubleUtil.Show(0); } } } private void GenerateBtn_Click(object sender, EventArgs e) { if (-1 == monthSelectCb.SelectedIndex) { return; } string qtKey = monthSelectCb.SelectedItem as string; if (PayDataMgr.Instance().AllQtPay.ContainsKey(qtKey)) { MessageBox.Show("工资已经生成"); return; } //查找qtkey标示月份所导入的回佣 SortedDictionary<string, SortedDictionary<Int64, List<PayItem>>> hyPay = new SortedDictionary<string, SortedDictionary<Int64, List<PayItem>>>(); try { PayUtil.GeneratePay(qtKey, ref hyPay); PayDataMgr.Instance().GeneratePay(qtKey, hyPay); } catch (ConditionCheckException ex1) { MessageBox.Show(ex1.Message); return; } catch (Exception ex2) { MessageBox.Show(ex2.Message); System.Environment.Exit(0); return; } } private void PayDataDlg_Load(object sender, EventArgs e) { WindowState = FormWindowState.Maximized; foreach (var item in QtMgr.Instance().AllQtTask) { monthSelectCb.Items.Add(item.Key); } SetDataGridViewColumn(); } private void SetDataGridViewColumn() { DataGridViewTextBoxColumn qtkey = new DataGridViewTextBoxColumn(); qtkey.Name = "qtkey"; qtkey.HeaderText = "月份"; qtkey.Width = 100; qtkey.Visible = false; myDataGridView1.Columns.Add(qtkey); //DataGridViewTextBoxColumn jobnumber = new DataGridViewTextBoxColumn(); //jobnumber.Name = "jobnumber"; //jobnumber.HeaderText = "工号"; //jobnumber.Width = 100; //jobnumber.Visible = false; //myDataGridView1.Columns.Add(jobnumber); DataGridViewTextBoxColumn gonghao = new DataGridViewTextBoxColumn(); gonghao.Name = "gonghao"; gonghao.HeaderText = "工号"; gonghao.Width = 100; myDataGridView1.Columns.Add(gonghao); DataGridViewTextBoxColumn name = new DataGridViewTextBoxColumn(); name.Name = "name"; name.HeaderText = "姓名"; name.Width = 100; myDataGridView1.Columns.Add(name); DataGridViewTextBoxColumn bumen = new DataGridViewTextBoxColumn(); bumen.Name = "bumen"; bumen.HeaderText = "部门"; bumen.Width = 200; myDataGridView1.Columns.Add(bumen); DataGridViewTextBoxColumn qtlevel = new DataGridViewTextBoxColumn(); qtlevel.Name = "qtlevel"; qtlevel.HeaderText = "QT级别"; qtlevel.Width = 100; myDataGridView1.Columns.Add(qtlevel); DataGridViewTextBoxColumn qtpay = new DataGridViewTextBoxColumn(); qtpay.Name = "qtpay"; qtpay.HeaderText = "QT工资"; qtpay.Width = 100; myDataGridView1.Columns.Add(qtpay); } } }
using Alabo.Data.People.Users.Domain.Services; using Alabo.Test.Base.Attribute; using Alabo.Test.Base.Core; using Alabo.Test.Base.Core.Model; using Xunit; namespace Alabo.Test.Core.User.Domain.Services { public class IUserDetailServiceTests : CoreTest { [Theory] [InlineData(2)] [InlineData(1)] [InlineData(-1)] [TestMethod("GetExtensions_Int64")] [TestIgnore] public void GetExtensions_Int64_test(long userId) { // var user = Service<IUserService>().GetRandom(userId); // var result = Service<IUserDetailService>().GetExtensions( user.Id); //Assert.NotNull(result); } [Theory] [InlineData(2)] [InlineData(1)] [InlineData(-1)] [TestMethod("QrCore_Int64")] [TestIgnore] public void QrCore_Int64_test(long userId) { //var user = Service<IUserService>().GetRandom(userId); // var result = Service<IUserDetailService>().QrCore(user.Id); // Assert.NotNull(result); } [Theory] [InlineData(1)] [InlineData(-1)] [TestMethod("CreateCode_User")] [TestIgnore] public void CreateCode_User_test(long userId) { //var user = Service<IUserService>().GetRandom(userId); //Service<IUserDetailService>().CreateCode(user); //var qrcodePath = FileHelper.QrcodePath+ $"/wwwroot/qrcode/{user.Id}.jpeg"; //Assert.True(File.Exists(qrcodePath)); } [Theory] [InlineData(1)] [InlineData(-1)] [TestMethod("GetUserOutput_Int64")] [TestIgnore] public void GetUserOutput_Int64_test(long userId) { // var user = Service<IUserService>().GetRandom(userId); // var result = Service<IUserDetailService>().GetUserOutput( user.Id); //Assert.NotNull(result); } /*end*/ [Fact] [TestMethod("ChangeMobile_ViewChangMobile")] [TestIgnore] public void ChangeMobile_ViewChangMobile_test() { //ViewChangMobile view = null; //var result = Service<IUserDetailService>().ChangeMobile( view); //Assert.NotNull(result); } [Fact] [TestMethod("ChangePassword_PasswordInput_Boolean")] [TestIgnore] public void ChangePassword_PasswordInput_Boolean_test() { //PasswordInput passwordInput = null; //var checkLastPassword = false; //var result = Service<IUserDetailService>().ChangePassword( passwordInput, checkLastPassword); //Assert.NotNull(result); } [Fact] [TestMethod("FindPassword_FindPasswordInput")] [TestIgnore] public void FindPassword_FindPasswordInput_test() { //FindPasswordInput findPassword = null; //var result = Service<IUserDetailService>().FindPassword( findPassword); //Assert.NotNull(result); } [Fact] [TestMethod("UpdateExtensions_Int64_UserExtensions")] public void UpdateExtensions_Int64_UserExtensions_test() { //var userId = 0; //UserExtensions userExtensions = null; //var result = Resolve<IUserDetailService>().UpdateExtensions(userId, userExtensions); //Assert.NotNull(result); } [Fact] [TestMethod("UpdateOpenId_String_Int64")] public void UpdateOpenId_String_Int64_test() { var openId = ""; var userId = 0; Resolve<IUserDetailService>().UpdateOpenId(openId, userId); } [Fact] [TestMethod("UpdateSingle_UserDetail")] [TestIgnore] public void UpdateSingle_UserDetail_test() { //UserDetail userDetail = null; //var result = Service<IUserDetailService>().UpdateSingle( userDetail); //Assert.True(result); } } }
using System; namespace Microsoft.UnifiedPlatform.Service.Common.Telemetry { public class MessageContext : LogContext { public string Message { get; set; } public MessageContext() : base() { } public MessageContext(string message, TraceLevel severityLevel, string correlationId, string transactionId, string source, string userId, string endToEndTrackingId) : base(severityLevel, correlationId, transactionId, source, userId, endToEndTrackingId) { Message = message; } public MessageContext(string message, TraceLevel severityLevel) : this(message, severityLevel, Guid.NewGuid().ToString(), transactionId: Guid.NewGuid().ToString(), source: null, userId: "System", endToEndTrackingId: null) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Text; using System.IO; using Spock.Davcna; using System.Threading; using mr.bBall_Lib; public partial class _Uporabniki : System.Web.UI.Page { protected string _sort; protected string msg = ""; protected string _persistence; protected void Page_Load(object sender, EventArgs e) { try { Master.SelectedBox = "Ostalo"; Master.Title = "Uporabniki"; if (!Master.Uporabnik.Pravice.Contains("uporabniki")) throw new Exception("Nimate pravice!"); msg = Request.QueryString["msg"] ?? ""; _sort = Request.QueryString["sort"] ?? "acLastName asc"; if (string.IsNullOrWhiteSpace(_sort)) { _sort = Convert.ToString(Session["sort_uporabniki"]); if (string.IsNullOrWhiteSpace(_sort)) _sort = "acLastName asc"; } else Session["sort_uporabniki"] = _sort; _persistence = Convert.ToString(Session["persistence_uporabniki"]) ?? ""; DataTable dt = Uporabniki.Get(); if (dt.Rows.Count > 0) { if (Request.QueryString["a"] == "csv") { Response.Clear(); byte[] csv = Encoding.Default.GetBytes(Splosno.Csv(dt, "uporabniki")); Response.ContentType = "application/csv; name=Uporabniki.csv"; Response.AddHeader("content-transfer-encoding", "binary"); Response.AddHeader("Content-Disposition", "attachment; filename=Uporabniki.csv"); Response.OutputStream.Write(csv, 0, csv.Length); Response.Flush(); Response.End(); } else { r_uporabniki.DataSource = dt.Select("", _sort).CopyToDataTable(); r_uporabniki.DataBind(); } } if (!string.IsNullOrWhiteSpace(msg)) Master.SetMessage(msg); } catch (Exception ee) { Master.SetMessage(ee); } } }
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General; using Pe.Stracon.SGC.Aplicacion.TransferObject.Response.Contractual; using Pe.Stracon.SGC.Presentacion.Core.ViewModel.Base; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Mvc; namespace Pe.Stracon.SGC.Presentacion.Core.ViewModel.Contractual.ReporteContratoPorFinalizar { /// <summary> /// Modelo de vista para el Reporte de Contrato Por Finalizar /// </summary> /// <remarks> /// Creación: GMD 20160623 </br> /// Modificación: </br> /// </remarks> public class ReporteContratoPorFinalizarBusqueda : GenericViewModel { /// <summary> /// Constructor usado para la búsqueda /// </summary> /// <param name="listaUnidadOperativa">Lista de Unidades Operativas</param> /// <param name="listaTipoContrato">Lista de Tipos de Contratos</param> /// <param name="listaTipoServicio">Lista de Tipos de Servicios</param> public ReporteContratoPorFinalizarBusqueda(List<UnidadOperativaResponse> listaUnidadOperativa, List<CodigoValorResponse> listaTipoContrato, List<CodigoValorResponse> listaTipoServicio, ReporteContratoPorFinalizarResponse reporteContratoPorFinalizar) { this.ListaUnidadOperativa = this.GenerarListadoOpcionUnidadOperativaFiltro(listaUnidadOperativa); this.ListaTipoContrato = this.GenerarListadoOpcioneGenericoFiltro(listaTipoContrato); this.ListaTipoServicio = this.GenerarListadoOpcioneGenericoFiltro(listaTipoServicio); this.ReporteContratoPorFinalizar = reporteContratoPorFinalizar; } #region Propiedades /// <summary> /// Lista de Unidades Operativas /// </summary> public List<SelectListItem> ListaUnidadOperativa { get; set; } /// <summary> /// Lista de Tipos de Contrato /// </summary> public List<SelectListItem> ListaTipoContrato { get; set; } /// <summary> /// Lista de Tipos de Servicios /// </summary> public List<SelectListItem> ListaTipoServicio { get; set; } /// <summary> /// Clase Response de Contrato Por Finalizar /// </summary> public ReporteContratoPorFinalizarResponse ReporteContratoPorFinalizar { get; set; } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Management; namespace Graphs.Utilities { public class PerformanceDataProvider { private static ManagementObject _processor; private List<PerformanceData> _peeks; private Stopwatch _watch; private static Process Process { get { return Process.GetCurrentProcess(); } } private static ManagementObject Processor { get { return _processor ?? (_processor = new ManagementObject("Win32_PerfFormattedData_PerfOS_Processor.Name='_Total'")); } } public void StartWatching() { _watch = Stopwatch.StartNew(); _peeks = new List<PerformanceData>(); } public void Peek() { _watch.Stop(); _peeks.Add(new PerformanceData { CpuUsage = GetCpuUsage(), RamUsage = GetRamUsage() }); _watch.Start(); } public PerformanceReport EndWatching() { _watch.Stop(); return new PerformanceReport(_peeks, _watch.Elapsed); } /// <summary> /// Current procesor usage in % /// </summary> /// <returns>Value in % (0-100)</returns> private static int GetCpuUsage() { Processor.Get(); var processorUsageProperty = Processor.Properties["PercentProcessorTime"]; return (int) double.Parse(processorUsageProperty.Value.ToString()); } /// <summary> /// Current RAM usage /// </summary> /// <returns>Memory currently allocated by a process (in MB)</returns> private static double GetRamUsage() { var ramInMb = Process.PrivateMemorySize64/(1024.0*1024.0); return Math.Round(ramInMb, 2); } } public class PerformanceReport { public PerformanceReport(IList<PerformanceData> performancePiecies, TimeSpan executionTime) { PerformancePiecies = performancePiecies; ExecutionTime = executionTime; } public TimeSpan ExecutionTime { get; private set; } public IList<PerformanceData> PerformancePiecies { get; set; } public int AverageCpuUsage { get { return (int) Math.Round(PerformancePiecies.Average(x => x.CpuUsage)); } } public double AverageRamUsage { get { return Math.Round(PerformancePiecies.Average(x => x.RamUsage), 2); } } public int PeakCpuUsage { get { return PerformancePiecies.Max(x => x.CpuUsage); } } public double PeakRamUsage { get { return PerformancePiecies.Max(x => x.RamUsage); } } } public class PerformanceData { public double RamUsage { get; set; } public int CpuUsage { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; class ABC124A{ public static void Main(){ var ab = Console.ReadLine().Split().Select(int.Parse); if(ab.ElementAt(0)+ab.ElementAt(1)>ab.Max()*2-1){ Console.WriteLine(ab.ElementAt(0)+ab.ElementAt(1)); return; } Console.WriteLine(ab.Max()*2-1); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using GrubTime.Middleware; using GrubTime.Models; using Microsoft.AspNetCore.Authorization; using System.Net.Http; using System.IO; using System.Text; using Newtonsoft.Json; using GrubTime.ViewModels; using Microsoft.AspNetCore.Http.Internal; using System.Net; using static GrubTime.Models.PlaceDetails; using Microsoft.Extensions.Options; namespace GrubTime.Controllers { /// <summary> /// Restaurants /// </summary> [Produces("application/json")] [Route("api/Places")] public class PlacesController : Controller { readonly private Google _google; /// <summary> /// Google API query /// </summary> /// <param name="optionsAccessor"></param> public PlacesController(IOptions<Google> optionsAccessor) { _google = optionsAccessor.Value; } /// <summary> /// Using the coordinates and a radius, a google search is conducted to locate open restaurants /// </summary> /// <param name="value"></param> /// <returns></returns> // POST: api/Places [HttpPost] public StatusCodeResult Post([FromBody]string value) { return Ok(); } /// <summary> /// Get more details on a restaurant by the place id from google /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpGet] public async Task<object> DetailsAsync(string id) { var detailApiUrl = string.Format(_google.Details, id); HttpWebRequest query = (HttpWebRequest)WebRequest.Create(detailApiUrl); WebResponse response = await query.GetResponseAsync(); var raw = String.Empty; using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8, true, 1024, true)) { raw = reader.ReadToEnd(); } var allresults = JsonConvert.DeserializeObject<RootObject>(raw); return allresults; } } }
using System.Collections.Generic; using System.Reflection; using UnityEngine; using BepInEx; using BepInEx.Configuration; using Newtonsoft.Json; using RadialUI; using Bounce.Unmanaged; using HarmonyLib; using LordAshes; using MoreSizesPlugin.Patches; using RadialUI.Extensions; namespace MoreSizesPlugin { public static class RadialExtensions { public static GameObject FindChild(this GameObject gameObject, string name, bool includeInactive = false) { Transform[] childTransforms = gameObject.GetComponentsInChildren<Transform>(includeInactive); RectTransform[] rectTransforms = gameObject.GetComponentsInChildren<RectTransform>(includeInactive); if (childTransforms != null) foreach (Transform transform in childTransforms) { GameObject child = transform.gameObject; if (child?.name == name) return child; } if (rectTransforms != null) foreach (Transform transform in rectTransforms) { GameObject child = transform.gameObject; if (child?.name == name) return child; } return null; } } [BepInPlugin(Guid, "More Sizes Plug-In", Version)] [BepInDependency(RadialUIPlugin.Guid)] [BepInDependency(StatMessaging.Guid)] [BepInDependency("org.generic.plugins.setinjectionflag")] public class MoreSizesPlugin : BaseUnityPlugin { // constants private const string Guid = "org.hollofox.plugins.MoreSizesPlugin"; private const string Version = "2.1.4.0"; private const string key = "org.lordashes.plugins.extraassetsregistration.Aura."; private static CreatureGuid _selectedCreature; // Dictionaries private readonly Dictionary<CreatureGuid, List<string>> _knownCreatureEffects = new Dictionary<CreatureGuid, List<string>>(); // Config private ConfigEntry<string> _customSizes; /// <summary> /// Awake plugin /// </summary> void Awake() { Logger.LogInfo("In Awake for More Sizes"); _customSizes = Config.Bind("Sizes", "List", JsonConvert.SerializeObject(new List<float> { 0.5f, 0.75f, 1f, 1.5f, 2f, 3f, 4f, 6, 8, 10, 15, 20, 25, 30, }),new ConfigDescription("", null, new ConfigurationManagerAttributes { IsJSON = true })); var harmony = new Harmony(Guid); harmony.PatchAll(); Debug.Log("MoreSizes Plug-in loaded"); ModdingTales.ModdingUtils.Initialize(this, Logger, "Hollofoxes'"); RadialUIPlugin.HideDefaultEmotesGMItem(Guid,"Set Size"); RadialUIPlugin.AddCustomButtonGMSubmenu("Set Size", new MapMenu.ItemArgs { Action = HandleSubmenus, Icon = Icons.GetIconSprite("creaturesize"), CloseMenuOnActivate = false, Title = "Set Size", } ,Reporter); // StatMessaging StatMessaging.Subscribe("*", HandleRequest); } private void HandleSubmenus(MapMenuItem arg1, object arg2) { CreaturePresenter.TryGetAsset(_selectedCreature, out CreatureBoardAsset asset); var c = asset; if (!_knownCreatureEffects.ContainsKey(c.CreatureId) || _knownCreatureEffects[c.CreatureId].Count == 0) OpenResizeMini(arg1, arg2); else OpenSelectAsset(arg1, arg2); } private void OpenSelectAsset(MapMenuItem arg1, object arg2) { CreaturePresenter.TryGetAsset(_selectedCreature, out CreatureBoardAsset asset); var c = asset; MapMenu mapMenu = MapMenuManager.OpenMenu(c.transform.position + Vector3.up * CreatureMenuBoardPatch._hitHeightDif, true); mapMenu.AddItem(new MapMenu.ItemArgs { Title = "Set creature size", Action = OpenResizeMini, CloseMenuOnActivate = false, Icon = Icons.GetIconSprite("creaturesize") }); foreach (var effect in _knownCreatureEffects[c.CreatureId]) { var x = effect.Replace(key, ""); mapMenu.AddItem(new MapMenu.ItemArgs { Title = $"Set {x.Replace("_", " ")} size", Action = OpenResizeEffect, Obj = effect, CloseMenuOnActivate = false, Icon = Icons.GetIconSprite("MagicMissile") }); } } private void OpenResizeEffect(MapMenuItem arg1, object arg2) { string effect = (string)arg2; CreaturePresenter.TryGetAsset(_selectedCreature, out CreatureBoardAsset asset); var c = asset; MapMenu mapMenu = MapMenuManager.OpenMenu(c.transform.position + Vector3.up * CreatureMenuBoardPatch._hitHeightDif, true); var sizes = JsonConvert.DeserializeObject<List<float>>(_customSizes.Value); foreach (var size in sizes) { if (size < 1) AddSizeEffect(mapMenu, size, effect, Icons.GetIconSprite("05x05")); else if (size < 2) AddSizeEffect(mapMenu, size, effect, Icons.GetIconSprite("1x1")); else if (size < 3) AddSizeEffect(mapMenu, size, effect, Icons.GetIconSprite("2x2")); else if (size < 4) AddSizeEffect(mapMenu, size, effect, Icons.GetIconSprite("3x3")); else AddSizeEffect(mapMenu, size, effect, Icons.GetIconSprite("4x4")); } } private void OpenResizeMini(MapMenuItem arg1, object arg2) { CreaturePresenter.TryGetAsset(_selectedCreature, out CreatureBoardAsset asset); var c = asset; MapMenu mapMenu = MapMenuManager.OpenMenu(c.transform.position + Vector3.up * CreatureMenuBoardPatch._hitHeightDif, true); var sizes = JsonConvert.DeserializeObject<List<float>>(_customSizes.Value); foreach (var size in sizes) { if (size < 1) AddSize(mapMenu, size, Icons.GetIconSprite("05x05")); else if (size < 2) AddSize(mapMenu, size, Icons.GetIconSprite("1x1")); else if (size < 3) AddSize(mapMenu, size, Icons.GetIconSprite("2x2")); else if (size < 4) AddSize(mapMenu, size, Icons.GetIconSprite("3x3")); else AddSize(mapMenu, size, Icons.GetIconSprite("4x4")); } } private void AddSize(MapMenu mapMenu, float x, Sprite icon = null) { mapMenu.AddItem(new MapMenu.ItemArgs { Title = $"{x}x{x}", Action = Menu_Scale, Obj = x, CloseMenuOnActivate = true, Icon = icon }); } private void AddSizeEffect(MapMenu mapMenu, float x, string effect, Sprite icon = null) { mapMenu.AddItem(new MapMenu.ItemArgs { Title = $"{x}x{x}", Action = Scale_Effect, Obj = new effectResize{key = effect, value = x}, CloseMenuOnActivate = true, Icon = icon }); } private void Scale_Effect(MapMenuItem arg1, object arg2) { var er = (effectResize) arg2; StatMessaging.SetInfo(_selectedCreature, $"size.{er.key}", JsonConvert.SerializeObject(er)); } private bool Reporter(NGuid arg1, NGuid arg2) { _selectedCreature = new CreatureGuid(arg2); return true; } private void Menu_Scale(MapMenuItem item, object obj) { var fetch = StatMessaging.ReadInfo(_selectedCreature, Guid); dto scale; if (!string.IsNullOrWhiteSpace(fetch)) { scale = JsonConvert.DeserializeObject<dto>(fetch); } else { CreaturePresenter.TryGetAsset(_selectedCreature, out var asset); scale = new dto { X = asset.transform.localScale.x, Y = asset.transform.localScale.y, Z = asset.transform.localScale.z }; } scale.value = (float) obj; CreatureManager.SetCreatureScale(_selectedCreature ,0, (float)obj); StatMessaging.SetInfo(_selectedCreature, Guid, JsonConvert.SerializeObject(scale)); } public static void SetValue(object o, string methodName, object value) { var mi = o.GetType().GetField(methodName, BindingFlags.NonPublic | BindingFlags.Instance); if (mi != null) mi.SetValue(o, value); } public void HandleRequest(StatMessaging.Change[] changes) { foreach (StatMessaging.Change change in changes) { if (change.key.Contains($"size.{key}")) { var previous = JsonConvert.DeserializeObject<effectResize>(change.previous); var er = JsonConvert.DeserializeObject<effectResize>(change.value); var goName = change.key.Replace($"size.{key}", ""); var AssetName = $"CustomAura:{change.cid}.{goName}"; var creatureId = change.cid; CreaturePresenter.TryGetAsset(creatureId, out CreatureBoardAsset asset); var me = asset.gameObject.FindChild(AssetName); me.gameObject.SetActive(false); me.gameObject.SetActive(true); var all = me.transform.GetComponentsInChildren<ParticleSystem>(); var allT = me.transform.GetComponentsInChildren<Transform>(); if (change.action == StatMessaging.ChangeType.modified) { foreach (var p in all) { p.transform.localScale /= previous.value; } foreach (var t in allT) { t.localScale = t.transform.localScale / previous.value; } } if (change.action != StatMessaging.ChangeType.removed) { foreach (var p in all) { p.transform.localScale *= er.value; } foreach (var t in allT) { t.localScale = t.transform.localScale * er.value; } } Debug.Log($"Change to size: ({change.value}, {er.value})"); } else if (change.key.Contains(key)) { var x = change.key.Replace(key,""); if (change.action == StatMessaging.ChangeType.added) { if (!_knownCreatureEffects.ContainsKey(change.cid)) _knownCreatureEffects[change.cid] = new List<string>(); _knownCreatureEffects[change.cid].Add(change.key); } else if (change.action == StatMessaging.ChangeType.removed) { if (_knownCreatureEffects.ContainsKey(change.cid)) _knownCreatureEffects[change.cid].Remove(change.key); } } if (change.key == Guid) { var creatureId = change.cid; var size = JsonConvert.DeserializeObject<dto>(change.value); CreaturePresenter.TryGetAsset(creatureId, out CreatureBoardAsset asset); SetValue(asset, "_scaleTransitionValue",0f); SetValue(asset, "_targetScale", size.value); } } } } }
using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle("Leprechaun.InputProviders.Sitecore")] [assembly: AssemblyDescription("")] [assembly: InternalsVisibleTo("Leprechaun.InputProviders.Sitecore.Tests")]
using AutoMapper; using XH.Commands.Hazards; using XH.Domain.Hazards; using XH.Infrastructure.Mapper; namespace XH.Command.Handlers.Configs { public class HazardsMapperRegistrar : IAutoMapperRegistrar { public void Register(IMapperConfigurationExpression cfg) { cfg.CreateMap<CreateHazardLevelCommand, HazardLevel>(); cfg.CreateMap<UpdateHazardLevelCommand, HazardLevel>(); } } }
using ApartmentApps.Data; namespace ApartmentApps.Api { public interface IMaintenanceRequestCheckinEvent { void MaintenanceRequestCheckin( MaintenanceRequestCheckin maitenanceRequest, MaitenanceRequest request); } public interface IMaintenanceRequestAssignedEvent { void MaintenanceRequestAssigned(MaitenanceRequest request); } }
using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Globalization; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; using Data; using Display; using IO; using SFB; namespace DesktopInterface { public class DesktopProfiler : IButtonScript { bool runUpdate = false; Vector3 initialMouseScreenPosition; Vector3 CurrentMouseScreenPosition; Vector3 CurrentMouseWorldPosition; Vector3 initialMouseWorldPosition; Vector3 FinalMousePosition; GameObject MeshObject; public GameObject UIWindow; CloudData data; GameObject cylinder = null; GameObject cylinderSide1; GameObject cylinderSide2; public InputField CylinderSide1_XField; public InputField CylinderSide1_YField; public InputField CylinderSide1_ZField; public InputField CylinderSide2_XField; public InputField CylinderSide2_YField; public InputField CylinderSide2_ZField; public InputField CylinderHeightField; public InputField BinsField; private int BinNumber; public Button ExportButton; public Button CloseButton; public Text DistanceText; private float Distance; public List<GameObject> sectionList = new List<GameObject>(); private void Awake() { button = GetComponent<Button>(); initializeClickEvent(); CylinderSide1_XField.onEndEdit.AddListener(delegate { ChangeCylinderPositions(); }); CylinderSide1_YField.onEndEdit.AddListener(delegate { ChangeCylinderPositions(); }); CylinderSide1_ZField.onEndEdit.AddListener(delegate { ChangeCylinderPositions(); }); CylinderSide2_XField.onEndEdit.AddListener(delegate { ChangeCylinderPositions(); }); CylinderSide2_YField.onEndEdit.AddListener(delegate { ChangeCylinderPositions(); }); CylinderSide2_ZField.onEndEdit.AddListener(delegate { ChangeCylinderPositions(); }); CylinderHeightField.onEndEdit.AddListener(delegate { ChangeCylinderHeight(); }); BinsField.onEndEdit.AddListener(delegate { ChangeBinNumber(); }); ExportButton.onClick.AddListener(delegate { ExportHistogram(); }); CloseButton.onClick.AddListener(delegate { CloseHistogram(); }); } public void ExportButtonClicked() { if (runUpdate) { Execute(); } CloudUpdater.instance.CreateCloudFromSelection(); } public override void Execute() { if (!CloudSelector.instance.noSelection) { data = CloudUpdater.instance.LoadCurrentStatus(); data.transform.parent.gameObject.GetComponent<CloudObjectRefference>().box.gameObject.GetComponent<DragMouse>().enabled = runUpdate; data.globalMetaData.FreeSelectionON = true; runUpdate = !runUpdate; if (runUpdate) { MeshObject = new GameObject("Selection Mesh Object"); MeshObject.AddComponent<MeshRenderer>(); MeshObject.AddComponent<MeshFilter>(); data.transform.parent.gameObject.GetComponent<CloudObjectRefference>().box.transform.position = Vector3.zero; data.transform.parent.gameObject.GetComponent<CloudObjectRefference>().box.transform.eulerAngles = Vector3.zero; UIManager.instance.DeactivateSelectionButtons(); GetComponent<Image>().color = Color.green; } else { Destroy(MeshObject); UIManager.instance.ActivateSelectionButtons(); GetComponent<Image>().color = Color.white; } } } private void LateUpdate() { if (runUpdate) { if (EventSystem.current.IsPointerOverGameObject()) { PointerEventData pointer = new PointerEventData(EventSystem.current); pointer.position = Input.mousePosition; List<RaycastResult> raycastResults = new List<RaycastResult>(); EventSystem.current.RaycastAll(pointer, raycastResults); if (raycastResults.Count > 0 && raycastResults[0].gameObject.layer == LayerMask.NameToLayer("UI")) { return; } } //Calculate Mouse World Position if (Input.GetMouseButtonDown(0)) { initialMouseScreenPosition = Input.mousePosition; RecordInitialPosition(); } else if (Input.GetMouseButton(0)) { RecordInitialPosition(); //Generate mesh wires CalculateCurrentPosition(); UpdateMesh(); } else if (Input.GetMouseButtonUp(0)) { RecordInitialPosition(); RecordFinalPosition(); //RECTANGLE CALCULUS //Vector3 Vertex1 = new Vector3(FinalMousePosition.x, initialMouseWorldPosition.y, FinalMousePosition.z); //Vector3 Vertex3 = new Vector3(initialMouseWorldPosition.x, FinalMousePosition.y, FinalMousePosition.z); ; Matrix4x4 world_to_local = data.gameObject.transform.worldToLocalMatrix; Vector3 LocalVertex0 = world_to_local.MultiplyPoint3x4(initialMouseWorldPosition); //Vector3 LocalVertex1 = world_to_local.MultiplyPoint3x4(Vertex1); Vector3 LocalVertex2 = world_to_local.MultiplyPoint3x4(FinalMousePosition); //Vector3 LocalVertex3 = world_to_local.MultiplyPoint3x4(Vertex3); float MaxX = Mathf.Max(LocalVertex2.x, LocalVertex0.x); float MinX = Mathf.Min(LocalVertex2.x, LocalVertex0.x); float MaxY = Mathf.Max(LocalVertex2.y, LocalVertex0.y); float MinY = Mathf.Min(LocalVertex2.y, LocalVertex0.y); if (cylinder) { Destroy(cylinder); } cylinder = CreateCylinder(LocalVertex0, LocalVertex2); ShowWindow(); //TODO //Make window with the 3 positions and number of bins //when a position is changed, move the two ends of the cylinder and make them face eachother //when the bins are set you can run the analysis and display the histogram } } } private void RecordInitialPosition() { initialMouseScreenPosition.z = Mathf.Abs(CameraManager.instance.desktop_camera.transform.position.z) + CameraManager.instance.desktop_camera.nearClipPlane; Vector3 newInWorldPosition = CameraManager.instance.desktop_camera.ScreenToWorldPoint(initialMouseScreenPosition); initialMouseWorldPosition = newInWorldPosition; //Find first mouse position } private void CalculateCurrentPosition() { CurrentMouseScreenPosition = Input.mousePosition; CurrentMouseScreenPosition.z = Mathf.Abs(CameraManager.instance.desktop_camera.transform.position.z) + CameraManager.instance.desktop_camera.nearClipPlane; Vector3 WorldPosition = CameraManager.instance.desktop_camera.ScreenToWorldPoint(CurrentMouseScreenPosition); UIManager.instance.ChangeStatusText(" Mouse Position : " + WorldPosition.ToString("F4")); CurrentMouseWorldPosition = WorldPosition; } private void RecordFinalPosition() { CurrentMouseScreenPosition = Input.mousePosition; CurrentMouseScreenPosition.z = Mathf.Abs(CameraManager.instance.desktop_camera.transform.position.z) + CameraManager.instance.desktop_camera.nearClipPlane; Vector3 WorldPosition = CameraManager.instance.desktop_camera.ScreenToWorldPoint(CurrentMouseScreenPosition); UIManager.instance.ChangeStatusText(" Mouse Position : " + WorldPosition.ToString("F4")); FinalMousePosition = WorldPosition; } private void UpdateMesh() { //RECTANGLE CALCULUS //Vector3 Vertex1 = new Vector3(CurrentMouseWorldPosition.x, initialMouseWorldPosition.y, CurrentMouseWorldPosition.z); //Vector3 Vertex3 = new Vector3(initialMouseWorldPosition.x, CurrentMouseWorldPosition.y, CurrentMouseWorldPosition.z); ; Mesh mesh = new Mesh(); mesh.vertices = new Vector3[2] { initialMouseWorldPosition, CurrentMouseWorldPosition}; mesh.SetIndices(new int[2] { 0, 1}, MeshTopology.Lines, 0); MeshObject.GetComponent<MeshFilter>().mesh = mesh; } private GameObject CreateCylinder(Vector3 Vertex1, Vector3 Vertex2) { Vertex1.z = 0f; Vertex2.z = 0f; GameObject go = CreateCircleMesh(Vertex1, Vertex2); GameObject go2 = CreateCircleMesh(Vertex2, Vertex1); GameObject obj = new GameObject(); //obj.transform.SetParent(baseCircle.transform, false); MeshRenderer mr = obj.AddComponent<MeshRenderer>(); MeshFilter mf = obj.AddComponent<MeshFilter>(); go.transform.SetParent(obj.transform, true); go2.transform.SetParent(obj.transform, true); List<Vector3> vertices = new List<Vector3>(); List<int> indices = new List<int>(); vertices.Add(go.transform.position); vertices.Add(go2.transform.position); indices.Add(0); indices.Add(1); mf.mesh.vertices = vertices.ToArray(); mf.mesh.SetIndices(indices.ToArray(), MeshTopology.Lines, 0); mr.material = new Material(Shader.Find("Standard")); cylinderSide1 = go; cylinderSide2 = go2; obj.transform.SetParent(data.transform, true); return obj; } public void ReshapeCylinder() { cylinderSide1.transform.LookAt(cylinderSide2.transform); cylinderSide2.transform.LookAt(cylinderSide1.transform); MeshFilter mf = cylinder.GetComponent<MeshFilter>(); Vector3[] newvertices = new Vector3[2] { cylinderSide1.transform.localPosition, cylinderSide2.transform.localPosition }; mf.mesh.vertices = newvertices; } public GameObject CreateCircleMesh(Vector3 position, Vector3 direction) { GameObject newpoint = new GameObject("Circle"); //Creates a circle MeshRenderer mr = newpoint.AddComponent<MeshRenderer>(); MeshFilter mf = newpoint.AddComponent<MeshFilter>(); List<Vector3> vertices = new List<Vector3>(); List<int> indices = new List<int>(); int counter = 0; int n = 50; float radius = 1f; float x, y, z; for (int i = 0; i < n; i++) // phi { x = radius * Mathf.Cos((2 * Mathf.PI * i) / n); y = radius * Mathf.Sin((2 * Mathf.PI * i) / n); z = 0; vertices.Add(new Vector3(x, y, z)); indices.Add(counter++); x = radius * Mathf.Cos((2 * Mathf.PI * (i + 1)) / n); y = radius * Mathf.Sin((2 * Mathf.PI * (i + 1)) / n); z = 0; vertices.Add(new Vector3(x, y, z)); indices.Add(counter++); } mf.mesh.vertices = vertices.ToArray(); mf.mesh.SetIndices(indices.ToArray(), MeshTopology.Lines, 0); mr.material = new Material(Shader.Find("Standard")); newpoint.transform.localScale = Vector3.one * 0.05f; newpoint.transform.position = position; newpoint.transform.LookAt(direction); return newpoint; } private void ShowWindow() { UIWindow.SetActive(true); CylinderSide1_XField.text = Math.Round(cylinderSide1.transform.localPosition.x * data.globalMetaData.maxRange, 2).ToString(CultureInfo.InvariantCulture); CylinderSide1_YField.text = Math.Round(cylinderSide1.transform.localPosition.y * data.globalMetaData.maxRange, 2).ToString(CultureInfo.InvariantCulture); CylinderSide1_ZField.text = Math.Round(cylinderSide1.transform.localPosition.z * data.globalMetaData.maxRange, 2).ToString(CultureInfo.InvariantCulture); CylinderSide2_XField.text = Math.Round(cylinderSide2.transform.localPosition.x * data.globalMetaData.maxRange, 2).ToString(CultureInfo.InvariantCulture); CylinderSide2_YField.text = Math.Round(cylinderSide2.transform.localPosition.y * data.globalMetaData.maxRange, 2).ToString(CultureInfo.InvariantCulture); CylinderSide2_ZField.text = Math.Round(cylinderSide2.transform.localPosition.z * data.globalMetaData.maxRange, 2).ToString(CultureInfo.InvariantCulture); DistanceText.text = "Cylinder distance : "+Vector3.Distance(cylinderSide1.transform.localPosition * data.globalMetaData.maxRange, cylinderSide2.transform.localPosition * data.globalMetaData.maxRange).ToString(CultureInfo.InvariantCulture); Distance = Vector3.Distance(cylinderSide1.transform.localPosition * data.globalMetaData.maxRange, cylinderSide2.transform.localPosition * data.globalMetaData.maxRange); ChangeBinNumber(); } private void ChangeCylinderHeight() { float newscale = (float)double.Parse(CylinderHeightField.text, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture); cylinderSide1.transform.localScale = Vector3.one * newscale; cylinderSide2.transform.localScale = Vector3.one * newscale; if (sectionList.Count != 0) { foreach(GameObject obj in sectionList) { obj.transform.localScale = Vector3.one * newscale; } } } private void ChangeCylinderPositions() { Vector3 PosSide1 = new Vector3((float)double.Parse(CylinderSide1_XField.text, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture) / data.globalMetaData.maxRange, (float)double.Parse(CylinderSide1_YField.text, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture) / data.globalMetaData.maxRange, (float)double.Parse(CylinderSide1_ZField.text, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture) / data.globalMetaData.maxRange); Vector3 PosSide2 = new Vector3((float)double.Parse(CylinderSide2_XField.text, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture) / data.globalMetaData.maxRange, (float)double.Parse(CylinderSide2_YField.text, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture) / data.globalMetaData.maxRange, (float)double.Parse(CylinderSide2_ZField.text, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture) / data.globalMetaData.maxRange); cylinderSide1.transform.localPosition = PosSide1; cylinderSide2.transform.localPosition = PosSide2; DistanceText.text = Vector3.Distance(cylinderSide1.transform.localPosition * data.globalMetaData.maxRange, cylinderSide2.transform.localPosition * data.globalMetaData.maxRange).ToString(CultureInfo.InvariantCulture); Distance = Vector3.Distance(cylinderSide1.transform.localPosition * data.globalMetaData.maxRange, cylinderSide2.transform.localPosition * data.globalMetaData.maxRange); ReshapeCylinder(); ChangeBinNumber(); } private void ChangeBinNumber() { BinNumber = int.Parse(BinsField.text, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture); if (BinNumber != 0) { Debug.Log("bin number : " + BinNumber); if (sectionList.Count != 0) { for (int j = 0; j < sectionList.Count; j++) { Destroy(sectionList[j]); } sectionList.Clear(); } float distance = Vector3.Distance(cylinderSide1.transform.localPosition, cylinderSide2.transform.localPosition); float sizeinterval = distance / BinNumber; for (int i = 1; i < BinNumber; i++) { GameObject newcircle = CreateCircleMesh(cylinderSide1.transform.localPosition, cylinderSide2.transform.localPosition); newcircle.transform.position = cylinderSide1.transform.position; newcircle.transform.localScale = cylinderSide1.transform.localScale; newcircle.transform.rotation = cylinderSide1.transform.rotation; Vector3 direction = cylinderSide2.transform.position - cylinderSide1.transform.position; newcircle.transform.position += (direction.normalized * (i * sizeinterval)); newcircle.transform.SetParent(cylinder.transform); sectionList.Add(newcircle); } VR_Interaction.HistogramPointSelector selector = GetComponent<VR_Interaction.HistogramPointSelector>(); List<GameObject> circleList = new List<GameObject>(); List<Vector3> circlePositionsList = new List<Vector3>(); circlePositionsList.Add(cylinderSide1.transform.position); circleList.Add(cylinderSide1); foreach (var go in sectionList) { circlePositionsList.Add(go.transform.position); circleList.Add(go); } circlePositionsList.Add(cylinderSide2.transform.position); circleList.Add(cylinderSide2); selector.radius = cylinderSide1.transform.localScale.x; selector.sectionsNumber = BinNumber; selector.FindPointsProto(circleList, circlePositionsList); } } private void ExportHistogram() { VR_Interaction.HistogramPointSelector selector = GetComponent<VR_Interaction.HistogramPointSelector>(); HistogramSaveable hsave = new HistogramSaveable(); hsave.HistogramXValues = selector.xValues; hsave.HistogramYValues = selector.yValues; hsave.Distance = Distance; hsave.Side1Position = cylinderSide1.transform.localPosition; hsave.Side2Position = cylinderSide1.transform.localPosition; var extensions = new[] { new ExtensionFilter("JSON", ".JSON")}; StandaloneFileBrowser.SaveFilePanelAsync("Save File", "", "", extensions, (string path) => { SaveJSON(path, hsave); }); } public void SaveJSON(string path, HistogramSaveable histogramData) { string JSON = JsonUtility.ToJson(histogramData); string directory = Path.GetDirectoryName(path); string filename = Path.GetFileNameWithoutExtension(path); using (System.IO.StreamWriter writer = new System.IO.StreamWriter(directory + Path.DirectorySeparatorChar + filename + ".JSON")) { writer.WriteLine(JSON); } } private void CloseHistogram() { GetComponent<VR_Interaction.HistogramPointSelector>().DestroyHistogramCanvas(); Destroy(cylinder); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GangOfFourDesignPatterns.Creational.FactoryMethod { /// <summary> /// Product interface /// </summary> public interface IProduct { void Drive(int miles); } }
using jaytwo.Common.Extensions; using jaytwo.Common.Parse; using NUnit.Framework; using System; using System.Collections.Generic; using System.Globalization; using System.Text; namespace jaytwo.Common.Test.Parse { [TestFixture] public partial class ParseUtilityTests { private static IEnumerable<TestCaseData> ParseUInt32AllTestValues() { yield return new TestCaseData("4294967295").Returns((uint)4294967295); yield return new TestCaseData("0").Returns(0); yield return new TestCaseData("4294967296").Throws(typeof(OverflowException)); yield return new TestCaseData("-1").Throws(typeof(OverflowException)); yield return new TestCaseData("0").Returns(0); yield return new TestCaseData("123").Returns(123); yield return new TestCaseData(null).Throws(typeof(ArgumentNullException)); yield return new TestCaseData("").Throws(typeof(FormatException)); yield return new TestCaseData("foo").Throws(typeof(FormatException)); yield return new TestCaseData("123.45").Throws(typeof(OverflowException)); yield return new TestCaseData("$123.00", NumberStyles.Currency).Returns(123); yield return new TestCaseData("123.00", NumberStyles.Number).Returns(123); yield return new TestCaseData("123,00", new CultureInfo("pt-BR")).Returns(123); yield return new TestCaseData("123.00", new CultureInfo("en-US")).Returns(123); yield return new TestCaseData("R$123,00", NumberStyles.Currency, new CultureInfo("pt-BR")).Returns(123); yield return new TestCaseData("$123.00", NumberStyles.Currency, new CultureInfo("en-US")).Returns(123); } private static IEnumerable<TestCaseData> ParseUInt32GoodTestValues() { foreach (var testCase in TestUtility.GetTestCasesWithArgumentTypes<string>(ParseUInt32AllTestValues())) if (testCase.HasExpectedResult) yield return testCase; } private static IEnumerable<TestCaseData> ParseUInt32BadTestValues() { foreach (var testCase in TestUtility.GetTestCasesWithArgumentTypes<string>(ParseUInt32AllTestValues())) if (testCase.ExpectedException != null) yield return testCase; } private static IEnumerable<TestCaseData> TryParseUInt32BadTestValues() { foreach (var testCase in ParseUInt32BadTestValues()) yield return new TestCaseData(testCase.Arguments).Returns(null); } private static IEnumerable<TestCaseData> ParseUInt32_With_styles_GoodTestValues() { return TestUtility.GetTestCasesWithArgumentTypes<string, NumberStyles>(ParseUInt32AllTestValues()); } private static IEnumerable<TestCaseData> ParseUInt32_With_formatProvider_GoodTestValues() { return TestUtility.GetTestCasesWithArgumentTypes<string, IFormatProvider>(ParseUInt32AllTestValues()); } private static IEnumerable<TestCaseData> ParseUInt32_With_styles_formatProvider_GoodTestValues() { return TestUtility.GetTestCasesWithArgumentTypes<string, NumberStyles, IFormatProvider>(ParseUInt32AllTestValues()); } [Test] [TestCaseSource("ParseUInt32GoodTestValues")] public uint ParseUtility_ParseUInt32(string stringValue) { return ParseUtility.ParseUInt32(stringValue); } [Test] [ExpectedException] [TestCaseSource("ParseUInt32BadTestValues")] public uint ParseUtility_ParseUInt32_Exceptions(string stringValue) { return ParseUtility.ParseUInt32(stringValue); } [Test] [TestCaseSource("ParseUInt32_With_styles_formatProvider_GoodTestValues")] public uint ParseUtility_ParseUInt32_With_styles_formatProvider(string stringValue, NumberStyles styles, IFormatProvider formatProvider) { return ParseUtility.ParseUInt32(stringValue, styles, formatProvider); } [Test] [TestCaseSource("ParseUInt32_With_styles_GoodTestValues")] public uint ParseUtility_ParseUInt32_With_styles(string stringValue, NumberStyles styles) { return ParseUtility.ParseUInt32(stringValue, styles); } [Test] [TestCaseSource("ParseUInt32_With_formatProvider_GoodTestValues")] public uint ParseUtility_ParseUInt32_With_formatProvider(string stringValue, IFormatProvider formatProvider) { return ParseUtility.ParseUInt32(stringValue, formatProvider); } [Test] [TestCaseSource("ParseUInt32GoodTestValues")] [TestCaseSource("TryParseUInt32BadTestValues")] public uint? ParseUtility_TryParseUInt32(string stringValue) { return ParseUtility.TryParseUInt32(stringValue); } [Test] [TestCaseSource("ParseUInt32_With_styles_formatProvider_GoodTestValues")] public uint? ParseUtility_TryParseUInt32_With_styles_formatProvider(string stringValue, NumberStyles styles, IFormatProvider formatProvider) { return ParseUtility.TryParseUInt32(stringValue, styles, formatProvider); } [Test] [TestCaseSource("ParseUInt32_With_styles_GoodTestValues")] public uint? ParseUtility_TryParseUInt32_With_styles(string stringValue, NumberStyles styles) { return ParseUtility.TryParseUInt32(stringValue, styles); } [Test] [TestCaseSource("ParseUInt32_With_formatProvider_GoodTestValues")] public uint? ParseUtility_TryParseUInt32_With_formatProvider(string stringValue, IFormatProvider formatProvider) { return ParseUtility.TryParseUInt32(stringValue, formatProvider); } [Test] [TestCaseSource("ParseUInt32GoodTestValues")] public uint StringExtensions_ParseUInt32(string stringValue) { return stringValue.ParseUInt32(); } [Test] [ExpectedException] [TestCaseSource("ParseUInt32BadTestValues")] public uint StringExtensions_ParseUInt32_Exceptions(string stringValue) { return stringValue.ParseUInt32(); } [Test] [TestCaseSource("ParseUInt32_With_styles_formatProvider_GoodTestValues")] public uint StringExtensions_ParseUInt32_With_styles_formatProvider(string stringValue, NumberStyles styles, IFormatProvider formatProvider) { return stringValue.ParseUInt32(styles, formatProvider); } [Test] [TestCaseSource("ParseUInt32_With_styles_GoodTestValues")] public uint StringExtensions_ParseUInt32_With_styles(string stringValue, NumberStyles styles) { return stringValue.ParseUInt32(styles); } [Test] [TestCaseSource("ParseUInt32_With_formatProvider_GoodTestValues")] public uint StringExtensions_ParseUInt32_With_formatProvider(string stringValue, IFormatProvider formatProvider) { return stringValue.ParseUInt32(formatProvider); } [Test] [TestCaseSource("ParseUInt32GoodTestValues")] [TestCaseSource("TryParseUInt32BadTestValues")] public uint? StringExtensions_TryParseUInt32(string stringValue) { return stringValue.TryParseUInt32(); } [Test] [TestCaseSource("ParseUInt32_With_styles_formatProvider_GoodTestValues")] public uint? StringExtensions_TryParseUInt32_With_styles_formatProvider(string stringValue, NumberStyles styles, IFormatProvider formatProvider) { return stringValue.TryParseUInt32(styles, formatProvider); } [Test] [TestCaseSource("ParseUInt32_With_styles_GoodTestValues")] public uint? StringExtensions_TryParseUInt32_With_styles(string stringValue, NumberStyles styles) { return stringValue.TryParseUInt32(styles); } [Test] [TestCaseSource("ParseUInt32_With_formatProvider_GoodTestValues")] public uint? StringExtensions_TryParseUInt32_With_formatProvider(string stringValue, IFormatProvider formatProvider) { return stringValue.TryParseUInt32(formatProvider); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace test1_task3.Test { [TestClass] public class ValidatorOfAutomobileParametersTests { [TestMethod] public void IsValidWithCorrectTypeSedanOfAutomobilePositive() { Assert.IsTrue(new ValidatorOfAutomobileParameters().IsValid("sedan", 200)); } [TestMethod] public void IsValidWithCorrectTypeEstateOfAutomobilePositive() { Assert.IsTrue(new ValidatorOfAutomobileParameters().IsValid("estate", 200)); } [TestMethod] public void IsValidWithCorrectTypeSUVOfAutomobilePositive() { Assert.IsTrue(new ValidatorOfAutomobileParameters().IsValid("SUV", 200)); } [TestMethod] public void IsValidWithInCorrectTypeOfAutomobileNegative() { Assert.IsFalse(new ValidatorOfAutomobileParameters().IsValid("type", 200)); } [TestMethod] public void IsValidWithDifferentRegisterOfAutomobileTypePositive() { Assert.IsTrue(new ValidatorOfAutomobileParameters().IsValid("sEdAn", 200)); } [TestMethod] public void IsValidWithCorrectPriceOfAutomobilePositive() { Assert.IsTrue(new ValidatorOfAutomobileParameters().IsValid("sedan", 200)); } [TestMethod] public void IsValidWithNegativePriceOfAutomobileNegative() { Assert.IsFalse(new ValidatorOfAutomobileParameters().IsValid("sedan", -5)); } [TestMethod] public void IsValidWithNullPriceOfAutomobileNegative() { Assert.IsFalse(new ValidatorOfAutomobileParameters().IsValid("sedan", 0)); } } }
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.Windows.Forms.DataVisualization.Charting; using System.Data.SqlClient; using System.Drawing.Drawing2D; namespace DeTaiQuanLyNhaTro { public partial class ThongKeDoanhThu : Form { //tạo kết nối SqlConnection connection; //tạo truy vấn SqlCommand command; //chuỗi kết nối string str = @"Data Source=DESKTOP-21LUHLN\SQLEXPRESS;Initial Catalog=QLNhaTro;Integrated Security=True"; //lọc data lên SqlDataAdapter adapter = new SqlDataAdapter(); DataTable table = new DataTable(); DataTable tableNam = new DataTable(); DataTable tableThang = new DataTable(); double[] tongThang = new double[12]; //hiển thị data void loadData(string query, DataTable table, DataGridView dataGridView) { command = connection.CreateCommand();//khởi tạo xử lí kết nối command.CommandText = query;//điền câu truy vấn adapter.SelectCommand = command;//thực thi câu truy vấn table.Clear(); adapter.Fill(table); dataGridView.DataSource = table; } public ThongKeDoanhThu() { InitializeComponent(); } private void ThongKeDoanhThu_Load(object sender, EventArgs e) { connection = new SqlConnection(str); connection.Open(); //dùng để nhập dữ liệu lên combobox loadData("SELECT YEAR(NgayLap) FROM HoaDon GROUP BY YEAR(NgayLap)", tableNam, dgvNam); dgvNam.Hide(); dgvThang.Hide(); //load nam for (int i = 0; i < dgvNam.Rows.Count - 1; i++) { cmbChonNam.Items.Add(dgvNam.Rows[i].Cells[0].Value.ToString()); } } private void panel1_Paint(object sender, PaintEventArgs e) { LinearGradientBrush brush = new LinearGradientBrush(panel1.ClientRectangle, Color.LightSkyBlue, Color.White, LinearGradientMode.Vertical); e.Graphics.FillRectangle(brush, panel1.ClientRectangle); } public string ChonNam() { if (cmbChonNam.Text != "") return "Đã chọn năm thống kê!"; return "Chưa chọn năm thống kê!"; } private void cmbChonNam_SelectedIndexChanged(object sender, EventArgs e) { if(ChonNam() == "Đã chọn năm thống kê!") { double[] tongThang = new double[12]; label1.Visible = true; loadData("SELECT YEAR(NgayLap), MONTH(NgayLap), TongTien FROM HOADON WHERE YEAR(NgayLap) = '" + cmbChonNam.Text + "'", tableThang, dgvThang); for (int i = 0; i < dgvThang.Rows.Count - 1; i++) { int thang = int.Parse(dgvThang.Rows[i].Cells[1].Value.ToString()); for (int j = 0; j < tongThang.Length; j++) { if (thang == j + 1) tongThang[j] += double.Parse(dgvThang.Rows[i].Cells[2].Value.ToString()); } } Axis XA = chartDoanhThu.ChartAreas[0].AxisX; Series S1 = chartDoanhThu.Series[0]; List<DateTime> dates = new List<DateTime>(); // ds tháng DateTime dt = DateTime.Now; for (int i = 1; i < 13; i++) dates.Add(new DateTime(dt.Year, i, 1)); int dem = 0; foreach (DateTime d in dates) // duyệt qua từng tháng trong ds dates = 12 tháng S1.Points.AddXY(d, tongThang[dem++]); // thiet lap gia trị Y ngau nhien cho 12 tháng //-> lấy giá trị từ dataGridVie Axis YA = chartDoanhThu.ChartAreas[0].AxisY; S1.XValueType = ChartValueType.Date; // set the type XA.MajorGrid.Enabled = false; // no gridlines XA.LabelStyle.Format = "MM"; // Jan = January XA.IntervalType = DateTimeIntervalType.Months; // show axis labels.. XA.Interval = 1; // ..moi 1 thang YA.LabelStyle.Format = "##0 vnd"; YA.MajorGrid.Enabled = false; chartDoanhThu.Series[0].IsValueShownAsLabel = true; cmbChonNam.Enabled = false; } } private void btnDongY_Click(object sender, EventArgs e) { btnXacNhan(); } public bool btnXacNhan() { if(ChonNam() == "Đã chọn năm thống kê!") { ThongKeDoanhThu thongKeDoanhThu = new ThongKeDoanhThu(); this.Dispose(); thongKeDoanhThu.Show(); return true; } return false; } } }
using BusinessLayer.Interfaces; using DALLayer.DataRepository; using DomainModels; using System; using System.Collections.Generic; using System.Text; namespace BusinessLayer { public class CategoryBL : ICategoryBL { private readonly ICategoryDAL categoryDAL; public CategoryBL(ICategoryDAL catDAL) { categoryDAL = catDAL; } public List<Categories> GetCategories() { return categoryDAL.GetCategoriesDAL(); } } }
using System; using System.Collections.Generic; namespace SpaceHosting.Index.Sparnn.Distances { internal interface IMatrixMetricSearchSpaceFactory { IMatrixMetricSearchSpace<TElement> Create<TElement>(IList<MathNet.Numerics.LinearAlgebra.Double.SparseVector> featureVectors, TElement[] elements, int searchBatchSize); } internal class MatrixMetricSearchSpaceFactory : IMatrixMetricSearchSpaceFactory { private readonly MatrixMetricSearchSpaceAlgorithm searchSpaceAlgorithm; public MatrixMetricSearchSpaceFactory(MatrixMetricSearchSpaceAlgorithm searchSpaceAlgorithm) { this.searchSpaceAlgorithm = searchSpaceAlgorithm; } public IMatrixMetricSearchSpace<TElement> Create<TElement>(IList<MathNet.Numerics.LinearAlgebra.Double.SparseVector> featureVectors, TElement[] elements, int searchBatchSize) { return searchSpaceAlgorithm switch { MatrixMetricSearchSpaceAlgorithm.Cosine => new CosineDistanceSpace<TElement>(featureVectors, elements, searchBatchSize), MatrixMetricSearchSpaceAlgorithm.JaccardBinary => new JaccardBinarySingleFeatureOrientedSpace<TElement>(featureVectors, elements), _ => throw new InvalidOperationException($"Invalid {nameof(searchSpaceAlgorithm)}: {searchSpaceAlgorithm}") }; } } }
using UnityEditor; using UnityAtoms.Editor; using UnityEngine; namespace UnityAtoms.BaseAtoms.Editor { /// <summary> /// Variable Inspector of type `GameObject`. Inherits from `AtomVariableEditor` /// </summary> [CustomEditor(typeof(GameObjectVariable))] public sealed class GameObjectVariableEditor : AtomVariableEditor<GameObject, GameObjectPair> { } }
using UnityEngine; using UnityEngine.Events; namespace Action { /// <summary> /// Action delay time. /// </summary> public class ActionDelay : ActionBase { ActionDelay( float duration, UnityAction callback ) : base(null, duration, callback) { } public static ActionDelay Create( float duration, UnityAction callback = null ) { return new ActionDelay(duration, callback); } /// <summary> /// Whether this action is finished /// </summary> /// <returns><c>true</c> if this instance is finished; otherwise, <c>false</c>.</returns> public override bool IsFinished() { return this._isFinished; } } }
using System; using System.Collections.Generic; using Embraer_Backend.Models; using Microsoft.Extensions.Configuration; namespace Embraer_Backend.Models { public class DateDiferenceModel { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(SecagensModel)); public bool Seconds(IConfiguration _configuration,DateTime dateColeta) { // Transformando a data recebida para uma data compativel com o SQL System.Globalization.CultureInfo brCulture = new System.Globalization.CultureInfo("pt-br"); log.Debug(brCulture.ThreeLetterISOLanguageName.ToString()); DateTime coleta = Convert.ToDateTime(dateColeta,brCulture); DateTime agora = Convert.ToDateTime(DateTime.Now,brCulture); TimeSpan difSec =agora.Subtract(coleta); long ultColetaSec = 30; if (difSec.Seconds<ultColetaSec && difSec.Minutes==0 && difSec.Hours==0) { log.Debug("true"); return true; } else log.Debug("false"); return false; } public bool Dias(IConfiguration _configuration,DateTime dateColeta,int Dias) { // Transformando a data recebida para uma data compativel com o SQL System.Globalization.CultureInfo brCulture = new System.Globalization.CultureInfo("pt-br"); log.Debug(brCulture.ThreeLetterISOLanguageName.ToString()); DateTime coleta = Convert.ToDateTime(dateColeta,brCulture); DateTime agora = Convert.ToDateTime(DateTime.Now,brCulture); TimeSpan dateNow = DateTime.Now.TimeOfDay; TimeSpan difMin =(agora - coleta); long diasDiff = difMin.Days; if (diasDiff<Dias) { log.Debug("true"); return true; } else log.Debug("false"); return false; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class GameManager : MonoBehaviour { public const int RESOULUTION_WIDTH = 1280; public const int RESOULUTION_HEIGHT = 720; public const float WAITING_TIME = 1.0f; public const float SUCCESS_ACCURACY = 60.0f; public readonly Vector3 VECTOR3_EMPTY = new Vector3(0.0f, 0.0f, -100.0f); //private delegate Vector3 GetPosition (Vector3 vector, float textureSize, float scale); //private List<GamePattern> _gamePatternList; //private GetPosition _startPositionType; //private GetPosition _endPositionType; private Vector3[] _wallType; private ScaleData _scaleData; private TimeData _timeData; private SpeedData _speedData; private Data _currentData; private int _currentStage; private bool _isWait; [SerializeField] private Circle _circle; // Use this for initialization void Start () { Screen.SetResolution(RESOULUTION_WIDTH, RESOULUTION_HEIGHT, false); _circle.Initialize(); _scaleData = new ScaleData(); _timeData = new TimeData(); _speedData = new SpeedData(); _wallType = new Vector3[4] { Vector3.up, Vector3.down, Vector3.left, Vector3.right }; _circle.SetColor(new Color(92/255.0f, 167/255.0f, 219/255.0f)); // 임시 색 _currentStage = 1; _isWait = false; SetStage(_currentStage); StartCoroutine(PlayGame(_currentStage, WAITING_TIME)); // 단계 설정 (임시) //_gamePatternList = new List<GamePattern>(); //_gamePatternList.Add(new GamePattern(_scaleData, _scaleData.Value, GetRandomPosition(RESOULUTION_WIDTH, RESOULUTION_HEIGHT, _circle.TextureSize, _circle.Scale), VECTOR3_EMPTY, Mathf.Infinity)); } // Update is called once per frame void Update () { if (Input.GetMouseButtonDown(0)) { if (_isWait) return; float accuracy = GetAccuracy(); if (accuracy >= SUCCESS_ACCURACY) Success(accuracy); else Fail(accuracy); //_circle.StartCoroutine("Wander"); } } public void Success(float accuracy) { _currentData.Success(accuracy); if (_currentData.IsFindBsetValue) _currentStage++; StartCoroutine(PlayGame(_currentStage, WAITING_TIME)); } public void Fail(float accuracy) { _currentData.Fail(accuracy); if (_currentData.IsFindBsetValue) _currentStage++; StartCoroutine(PlayGame(_currentStage, WAITING_TIME)); } public float GetAccuracy() // 정확도 { Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); mousePos.z = _circle.Position.z; // 카메라의 Z 값이 -10.0f이기 때문에 원과 맞춰준다. float dis = Vector3.Distance(_circle.Position, mousePos); float circleRadius = _circle.Scale * _circle.TextureSize * 0.5f; return (1.0f - dis / circleRadius) * 100.0f; } private void SetCircle(float scale, Vector3 startPos, Vector3 endPos, float limitTime) { _circle.Scale = scale; _circle.LimitTime = limitTime; if (startPos == VECTOR3_EMPTY || endPos == VECTOR3_EMPTY) { //Vector3 pos = (startPos != VECTOR3_EMPTY) ? startPos : endPos; //_circle.Position = pos; _circle.Position = GetRandomPosition(RESOULUTION_WIDTH, RESOULUTION_HEIGHT, _circle.TextureSize, _circle.Scale); // 임시 (버그때문에) } else if (startPos != VECTOR3_EMPTY && endPos != VECTOR3_EMPTY) { // 직선 _circle.SetLine(startPos, endPos); _circle.StartCoroutine("MoveInStraightLine"); } else { _circle.Position = GetRandomPosition(RESOULUTION_WIDTH, RESOULUTION_HEIGHT, _circle.TextureSize, _circle.Scale); _circle.StartCoroutine("Wander"); } } private void SetStage(int currentStage) { switch (currentStage) { case 1: // 크기 체크 (크기 서치, 스크린 랜덤 생성, Empty, Infinity ) _currentData = _scaleData; SetCircle(_scaleData.Value, GetRandomPosition(RESOULUTION_WIDTH, RESOULUTION_HEIGHT, _circle.TextureSize, _circle.Scale), VECTOR3_EMPTY, Mathf.Infinity); _circle.SetColor(92.0f, 167.0f, 219.0f); // 하늘 break; case 2: // 시간 체크 (적정 크기, 스크린 랜덤 생성, Empty, 시간 서치 ) _currentData = _timeData; SetCircle(_scaleData.Value, GetRandomPosition(RESOULUTION_WIDTH, RESOULUTION_HEIGHT, _circle.TextureSize, _circle.Scale), VECTOR3_EMPTY, _timeData.Value); _circle.SetColor(204.0f, 95.0f, 95.0f); // 빨강 break; case 3: // 속도 체크 (적정 크기, 왼쪽 벽, 오른쪽 벽, Infinity ) _currentData = _speedData; SetCircle(_scaleData.Value, GetWallPosition(Vector3.left, _circle.TextureSize, _circle.Scale), GetWallPosition(Vector3.right, _circle.TextureSize, _circle.Scale), Mathf.Infinity); _circle.Speed = _currentData.Value; // 이거 생각해보기 _circle.SetColor(117.0f, 173.0f, 107.0f); // 초록 break; case 4: // ?? 체크 (적정 크기, 랜덤 벽, 반대 벽, Infinity ) Vector3 wallType = _wallType[Random.Range(0, _wallType.Length)]; SetCircle(_scaleData.Value, GetWallPosition(wallType, _circle.TextureSize, _circle.Scale), GetWallPosition(wallType * -1.0f, _circle.TextureSize, _circle.Scale), Mathf.Infinity); _circle.SetColor(109.0f, 107.0f, 173.0f); // 보라 break; case 5: // ?? 체크, 조정 행동 SetCircle(_scaleData.Value, VECTOR3_EMPTY, VECTOR3_EMPTY, Mathf.Infinity); _circle.SetColor(109.0f, 107.0f, 173.0f); // 보라 break; default: break; } } private Vector3 GetRandomPosition(int width, int height, float textureSize, float scale = 1.0f) // 랜덤 위치 { float x = width * 0.01f * 0.5f; float y = height * 0.01f * 0.5f; float radius = textureSize * 0.5f * scale; return new Vector3(Random.Range(x * -1.0f + radius, x - radius), Random.Range(y * -1.0f + radius, y - radius)); } private Vector3 GetWallPosition(Vector3 wallPos, float textureSize, float scale = 1.0f) // 벽 위치 { float x = RESOULUTION_WIDTH * 0.01f * 0.5f; float y = RESOULUTION_HEIGHT * 0.01f * 0.5f; float radius = textureSize * 0.5f * scale + 0.1f; // 0.1f 나중에 수정 if (wallPos == Vector3.up) return new Vector3(Random.Range(x * -1.0f + radius, x - radius), y * wallPos.y - radius); else if (wallPos == Vector3.down) return new Vector3(Random.Range(x * -1.0f + radius, x - radius), y * wallPos.y + radius); else if (wallPos == Vector3.left) return new Vector3(x * wallPos.x + radius, Random.Range(y * -1.0f + radius, y - radius)); else if (wallPos == Vector3.right) return new Vector3(x * wallPos.x - radius, Random.Range(y * -1.0f + radius, y - radius)); else return Vector3.zero; } private IEnumerator PlayGame(int stage, float waitingTime) { _isWait = true; _circle.Hide(); yield return new WaitForSeconds(waitingTime); _isWait = false; _circle.Show(); // ~~~~ SetStage(stage); // ~~~~ _circle.StartCoroutine("Maintain", _circle.LimitTime); // 이부분 나중에 수정 } }
using System.Collections.Generic; using System.Linq; using System.Web.Http; using Uintra.Core.Member.Helpers; using Uintra.Core.Member.Models; using Umbraco.Core.Services; using Umbraco.Web.WebApi; namespace Uintra.Core.User.Web { public abstract class UserApiControllerBase : UmbracoAuthorizedApiController { private readonly IMemberService _memberService; private readonly IUserService _userService; private readonly IMemberServiceHelper _memberServiceHelper; protected UserApiControllerBase( IUserService userService, IMemberService memberService, IMemberServiceHelper memberServiceHelper) { _userService = userService; _memberService = memberService; _memberServiceHelper = memberServiceHelper; } [HttpGet] public virtual IEnumerable<UserPickerModel> NotAssignedToMemberUsers(int? selectedUserId) { var users = _userService.GetAll(0, int.MaxValue, out _).Where( i => i.Id != -1); var relatedUserIdsDictionary = _memberServiceHelper.GetRelatedUserIdsForMembers(_memberService.GetAllMembers()); var unassignedUsers = users.Where(u => !relatedUserIdsDictionary.Values.Contains(u.Id) || u.Id == selectedUserId); var mappedModels = unassignedUsers.Select(u => new UserPickerModel {Id = u.Id, Name = u.Name}); return mappedModels; } //[HttpGet] //public virtual IEnumerable<ProfileColumnModel> ProfileProperties() //{ // return UsersPresentationHelper.GetProfileColumns(); //} } }
using System.Linq; using UcenikShuffle.Common; using UcenikShuffle.Common.Exceptions; using Xunit; namespace UcenikShuffle.UnitTests.CommonTests { public class LvCombinationCountCalculatorTests { //TODO: check once again if expected variable for all cases is correct //TODO: test what happens to GetCombinationCount if unexpected variables are passed to it (negative group size, empty group sizes list etc.) //TODO: add unit tests where number of available students is higher than group sizes sum [Theory] [InlineData(new[] { 2, 2, 3 }, 105)] [InlineData(new[] { 6, 1 }, 7)] [InlineData(new[] { 1, 6 }, 7)] [InlineData(new[] { 1, 2, 3 }, 60)] [InlineData(new[] { 1, 3, 3 }, 70)] [InlineData(new[] { 1, 2, 2 }, 15)] [InlineData(new[] { 1, 2, 3, 4 }, 12600)] [InlineData(new[] { 5 }, 1)] [InlineData(new[] { 1, 1, 1 }, 1)] [InlineData(new[] { 5, 4 }, 126)] [InlineData(new[] { 1, 3, 3, 3, 3 }, 200200)] [InlineData(new[] { 1, 2, 1 }, 6)] //[InlineData(new[] { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 5 }, someAmmount)] [InlineData(new[] { 1, 1, 2, 3 }, 210)] [InlineData(new[] { 2, 2 }, 3)] [InlineData(null, 0)] [InlineData(new int[] { }, 0)] private static void GetLvCombinationCount_ShouldWork(int[] groupSizes, ulong expected) { ulong actual = new LvCombinationCountCalculator(groupSizes == null ? null : groupSizes.ToList(), groupSizes == null ? 0 : groupSizes.Sum()).GetLvCombinationCount(); Assert.Equal(expected.ToString(), actual.ToString()); } [Theory] [InlineData(new int[] { 0 })] [InlineData(new int[] { 1, 2, -1, 4 })] private static void GetLvCombinationCount_ShouldThrowGroupSizeException(int[] groupSizes) { Assert.Throws<GroupSizeException>(() => new LvCombinationCountCalculator(groupSizes.ToList(), groupSizes.Sum()).GetLvCombinationCount()); } } }
using Euler_Logic.Helpers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Euler_Logic.Problems.AdventOfCode.Y2019 { public class Problem20 : AdventOfCodeBase { private List<Dictionary<int, Dictionary<int, Node>>> _grid; private List<Node> _connected; private List<Node> _letters; private List<Node> _portals; private Node _start; private Node _end; private int _rimTop; private int _rimBottom; private int _rimLeft; private int _rimRight; private enum enumNodeType { Empty, Null, Wall, Letter } public override string ProblemName { get { return "Advent of Code 2019: 20"; } } public override string GetAnswer() { GetGrid(Input()); BuildNeighborsStandard(); BuildNeighborsPortals(); return Answer2().ToString(); } private int Answer1() { var heap = InitializeHeap(); for (int count = 1; count <= _connected.Count; count++) { var current = (Node)heap.Top; foreach (var neighbor in current.Neighbors) { if (neighbor.NextNode.Num > current.Num + 1) { neighbor.NextNode.Num = current.Num + 1; heap.Adjust(neighbor.NextNode.Index); } } heap.Remove(current.Index); } return _end.Num; } private int Answer2() { FindPortals(); var heap = InitializeHeap(); do { var current = (Node)heap.Top; if (current == _end) { return current.Num; } foreach (var neighbor in current.Neighbors) { if (neighbor.IsPortalInner && neighbor.NextNode.Stack == current.Stack) { AddNewStack(current, heap); } bool canConnect = true; if (current.Stack != 0) { if (neighbor.NextNode.X == _start.X && neighbor.NextNode.Y == _start.Y) { canConnect = false; } else if (neighbor.NextNode.X == _end.X && neighbor.NextNode.Y == _end.Y) { canConnect = false; } } else if (neighbor.IsPortalOuter) { canConnect = false; } if (canConnect && neighbor.NextNode.Num > current.Num + 1) { neighbor.NextNode.Num = current.Num + 1; heap.Adjust(neighbor.NextNode.Index); neighbor.NextNode.Prior = current; } } heap.Remove(current.Index); } while (true); } private void FindPortals() { _portals = new List<Node>(); foreach (var node in _connected) { foreach (var neighbor in node.Neighbors) { if (neighbor.IsPortalInner || neighbor.IsPortalOuter) { _portals.Add(node); break; } } } } private void AddNewStack(Node start, BinaryHeap_Min heap) { AddNewStackNodes(heap, start.Stack + 1); AddNewStackNeighbors(); ConnectNewStack(start.Stack + 1); } private void AddNewStackNodes(BinaryHeap_Min heap, int nextStack) { var newGrid = new Dictionary<int, Dictionary<int, Node>>(); foreach (var node in _connected) { var newNode = new Node() { Neighbors = new List<Edge>(), Num = int.MaxValue, Stack = nextStack, X = node.X, Y = node.Y }; heap.Add(newNode); if (!newGrid.ContainsKey(node.X)) { newGrid.Add(node.X, new Dictionary<int, Node>()); } newGrid[node.X].Add(node.Y, newNode); } _grid.Add(newGrid); } private void AddNewStackNeighbors() { var newGrid = _grid.Last(); foreach (var node in _connected) { var newNode = newGrid[node.X][node.Y]; foreach (var oldNeighbor in node.Neighbors) { newNode.Neighbors.Add(new Edge() { IsPortalInner = oldNeighbor.IsPortalInner, IsPortalOuter = oldNeighbor.IsPortalOuter, NextNode = newGrid[oldNeighbor.NextNode.X][oldNeighbor.NextNode.Y] }); } } } private void ConnectNewStack(int nextStack) { var newGrid = _grid[nextStack]; var priorGrid = _grid[nextStack - 1]; foreach (var node in _portals) { var newNode = newGrid[node.X][node.Y]; var priorNode = priorGrid[node.X][node.Y]; foreach (var neighbor in node.Neighbors) { if (neighbor.IsPortalInner) { var adjust = priorNode.Neighbors.Where(x => x.IsPortalInner).First(); adjust.NextNode = newGrid[adjust.NextNode.X][adjust.NextNode.Y]; } else if (neighbor.IsPortalOuter) { var adjust = newNode.Neighbors.Where(x => x.IsPortalOuter).First(); adjust.NextNode = priorGrid[adjust.NextNode.X][adjust.NextNode.Y]; } } } } private BinaryHeap_Min InitializeHeap() { var heap = new BinaryHeap_Min(); _connected.ForEach(x => { x.Num = int.MaxValue; heap.Add(x); }); _start.Num = 0; heap.Reset(); heap.Adjust(_start.Index); return heap; } private void BuildNeighborsPortals() { var hash = new Dictionary<string, Portal>(); foreach (var node in _letters) { // Portal on left of name if (_grid[0].ContainsKey(node.X - 2) && _grid[0][node.X - 2][node.Y].NodeType == enumNodeType.Empty && _grid[0][node.X - 1][node.Y].NodeType == enumNodeType.Letter) { var key = new string(new char[2] { _grid[0][node.X - 1][node.Y].Letter, _grid[0][node.X][node.Y].Letter }); AddToHash(hash, key, _grid[0][node.X - 2][node.Y]); } // Portal on right of name if (_grid[0].ContainsKey(node.X + 2) && _grid[0][node.X + 2][node.Y].NodeType == enumNodeType.Empty && _grid[0][node.X + 1][node.Y].NodeType == enumNodeType.Letter) { var key = new string(new char[2] { _grid[0][node.X][node.Y].Letter, _grid[0][node.X + 1][node.Y].Letter }); AddToHash(hash, key, _grid[0][node.X + 2][node.Y]); } // Portal on bottom of name if (_grid[0][node.X].ContainsKey(node.Y + 2) && _grid[0][node.X][node.Y + 2].NodeType == enumNodeType.Empty && _grid[0][node.X][node.Y + 1].NodeType == enumNodeType.Letter) { var key = new string(new char[2] { _grid[0][node.X][node.Y].Letter, _grid[0][node.X][node.Y + 1].Letter }); AddToHash(hash, key, _grid[0][node.X][node.Y + 2]); } // Portal on top of name if (_grid[0][node.X].ContainsKey(node.Y - 2) && _grid[0][node.X][node.Y - 2].NodeType == enumNodeType.Empty && _grid[0][node.X][node.Y - 1].NodeType == enumNodeType.Letter) { var key = new string(new char[2] { _grid[0][node.X][node.Y - 1].Letter, _grid[0][node.X][node.Y].Letter }); AddToHash(hash, key, _grid[0][node.X][node.Y - 2]); } } foreach (var portal in hash.Values) { if (portal.Node2 != null) { portal.Node1.Neighbors.Add(new Edge() { NextNode = portal.Node2 }); portal.Node2.Neighbors.Add(new Edge() { NextNode = portal.Node1 }); SetEdgePortal(portal.Node1, portal.Node1.Neighbors.Last()); SetEdgePortal(portal.Node2, portal.Node2.Neighbors.Last()); } else if (portal.Key == "AA") { _start = portal.Node1; } else if (portal.Key == "ZZ") { _end = portal.Node1; } } } private void SetEdgePortal(Node node, Edge edge) { edge.IsPortalInner = node.Y != _rimTop && node.Y != _rimBottom && node.X != _rimLeft && node.X != _rimRight; edge.IsPortalOuter = node.Y == _rimTop || node.Y == _rimBottom || node.X == _rimLeft || node.X == _rimRight; } private void AddToHash(Dictionary<string, Portal> hash, string key, Node node) { if (!hash.ContainsKey(key)) { hash.Add(key, new Portal() { Key = key }); } var portal = hash[key]; if (portal.Node1 == null) { portal.Node1 = node; } else { portal.Node2 = node; } } private void BuildNeighborsStandard() { foreach (var node in _connected) { var neighbor = _grid[0][node.X][node.Y - 1]; if (neighbor.NodeType == enumNodeType.Empty) { node.Neighbors.Add(new Edge() { NextNode = neighbor }); } neighbor = _grid[0][node.X][node.Y + 1]; if (neighbor.NodeType == enumNodeType.Empty) { node.Neighbors.Add(new Edge() { NextNode = neighbor }); } neighbor = _grid[0][node.X - 1][node.Y]; if (neighbor.NodeType == enumNodeType.Empty) { node.Neighbors.Add(new Edge() { NextNode = neighbor }); } neighbor = _grid[0][node.X + 1][node.Y]; if (neighbor.NodeType == enumNodeType.Empty) { node.Neighbors.Add(new Edge() { NextNode = neighbor }); } } } private void GetGrid(List<string> input) { _rimBottom = input.Count - 3; _rimTop = 2; _rimLeft = 2; _rimRight = input[0].Length - 3; _grid = new List<Dictionary<int, Dictionary<int, Node>>>(); _grid.Add(new Dictionary<int, Dictionary<int, Node>>()); _connected = new List<Node>(); _letters = new List<Node>(); for (int y = 0; y < input.Count; y++) { for (int x = 0; x < input[y].Length; x++) { var node = new Node() { X = x, Y = y, Neighbors = new List<Edge>() }; switch (input[y][x]) { case ' ': node.NodeType = enumNodeType.Null; break; case '#': node.NodeType = enumNodeType.Wall; break; case '.': node.NodeType = enumNodeType.Empty; _connected.Add(node); break; default: node.NodeType = enumNodeType.Letter; node.Letter = input[y][x]; _letters.Add(node); break; } if (!_grid[0].ContainsKey(x)) { _grid[0].Add(x, new Dictionary<int, Node>()); } _grid[0][x].Add(y, node); } } } private string PrintOutput(int index) { var grid = _grid[index]; var maxX = grid.Keys.Max(); var maxY = grid.First().Value.Keys.Max(); var text = new StringBuilder(); for (int y = 0; y <= maxY; y++) { for (int x = 0; x <= maxX; x++) { if (grid.ContainsKey(x) && grid[x].ContainsKey(y)) { var node = grid[x][y]; if (node.NodeType == enumNodeType.Empty) { if (node.IsTraversed) { text.Append("*"); } else { text.Append("."); } } else if (node.NodeType == enumNodeType.Wall) { text.Append("#"); } else { text.Append(" "); } } else { text.Append(" "); } } text.AppendLine(); } return text.ToString(); } private List<string> Input_Test1() { return new List<string>() { " A ", " A ", " #######.######### ", " #######.........# ", " #######.#######.# ", " #######.#######.# ", " #######.#######.# ", " ##### B ###.# ", "BC...## C ###.# ", " ##.## ###.# ", " ##...DE F ###.# ", " ##### G ###.# ", " #########.#####.# ", "DE..#######...###.# ", " #.#########.###.# ", "FG..#########.....# ", " ###########.##### ", " Z ", " Z " }; } private List<string> Input_Test2() { return new List<string>() { " A ", " A ", " #################.############# ", " #.#...#...................#.#.# ", " #.#.#.###.###.###.#########.#.# ", " #.#.#.......#...#.....#.#.#...# ", " #.#########.###.#####.#.#.###.# ", " #.............#.#.....#.......# ", " ###.###########.###.#####.#.#.# ", " #.....# A C #.#.#.# ", " ####### S P #####.# ", " #.#...# #......VT", " #.#.#.# #.##### ", " #...#.# YN....#.# ", " #.###.# #####.# ", "DI....#.# #.....# ", " #####.# #.###.# ", "ZZ......# QG....#..AS", " ###.### ####### ", "JO..#.#.# #.....# ", " #.#.#.# ###.#.# ", " #...#..DI BU....#..LF", " #####.# #.##### ", "YN......# VT..#....QG", " #.###.# #.###.# ", " #.#...# #.....# ", " ###.### J L J #.#.### ", " #.....# O F P #.#...# ", " #.###.#####.#.#####.#####.###.# ", " #...#.#.#...#.....#.....#.#...# ", " #.#####.###.###.#.#.#########.# ", " #...#.#.....#...#.#.#.#.....#.# ", " #.###.#####.###.###.#.#.####### ", " #.#.........#...#.............# ", " #########.###.###.############# ", " B J C ", " U P P " }; } private List<string> Input_Test3() { return new List<string>() { " Z L X W C ", " Z P Q B K ", " ###########.#.#.#.#######.############### ", " #...#.......#.#.......#.#.......#.#.#...# ", " ###.#.#.#.#.#.#.#.###.#.#.#######.#.#.### ", " #.#...#.#.#...#.#.#...#...#...#.#.......# ", " #.###.#######.###.###.#.###.###.#.####### ", " #...#.......#.#...#...#.............#...# ", " #.#########.#######.#.#######.#######.### ", " #...#.# F R I Z #.#.#.# ", " #.###.# D E C H #.#.#.# ", " #.#...# #...#.# ", " #.###.# #.###.# ", " #.#....OA WB..#.#..ZH", " #.###.# #.#.#.# ", "CJ......# #.....# ", " ####### ####### ", " #.#....CK #......IC", " #.###.# #.###.# ", " #.....# #...#.# ", " ###.### #.#.#.# ", "XF....#.# RF..#.#.# ", " #####.# ####### ", " #......CJ NM..#...# ", " ###.#.# #.###.# ", "RE....#.# #......RF", " ###.### X X L #.#.#.# ", " #.....# F Q P #.#.#.# ", " ###.###########.###.#######.#########.### ", " #.....#...#.....#.......#...#.....#.#...# ", " #####.#.###.#######.#######.###.###.#.#.# ", " #.......#.......#.#.#.#.#...#...#...#.#.# ", " #####.###.#####.#.#.#.#.###.###.#.###.### ", " #.......#.....#.#...#...............#...# ", " #############.#.#.###.################### ", " A O F N ", " A A D M " }; } private class Node : BinaryHeap_Min.Node { public int X { get; set; } public int Y { get; set; } public enumNodeType NodeType { get; set; } public List<Edge> Neighbors { get; set; } public char Letter { get; set; } public int Stack { get; set; } public Node Prior { get; set; } public bool IsTraversed { get; set; } } private class Portal { public Node Node1 { get; set; } public Node Node2 { get; set; } public string Key { get; set; } } private class Edge { public Node NextNode { get; set; } public bool IsPortalOuter { get; set; } public bool IsPortalInner { get; set; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AddServiceASP_core21.Models; namespace AddServiceASP_core21.Services.Scoped { public class ItemScopedService : IScoped { Product product; int count = 0; public ItemScopedService() { product = new Product { idProduct = 1, Title = "Test Scoped:" + Guid.NewGuid(), UrlImage = "Scoped.jpg", Price = 79000, Detail = "Singleto" }; } public Product getProduct() { count++; return product; } public int countService() { return count; } } }
using System.Collections.Generic; using CupcakePCL.BL; using CupcakePCL.DL.SQLiteBase; namespace CupcakePCL.DL { public class IdeaRepository { CupcakeDatabase db = null; protected static string dbLocation; public IdeaRepository(SQLiteConnection conn, string dbLocation) { db = new CupcakeDatabase(conn, dbLocation); } public Idea GetIdea(int id) { return db.GetItem<Idea>(id); } public IEnumerable<Idea> GetIdeas() { return db.GetItems<Idea>(); } public int SaveIdea(Idea item) { return db.SaveItem<Idea>(item); } public int DeleteIdea(int id) { return db.DeleteItem<Idea>(id); } } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using TweetApp.DAL.Interfaces; using TweetApp.DTOs; using TweetApp.Entities; namespace TweetApp.Controllers { [ApiController] [ApiVersion("1.0")] [Route("api/v{version}/[controller]")] public class UsersController : Controller { private readonly IUserRepository _userRepository; private readonly IConfiguration _config; public UsersController(IUserRepository userRepository,IConfiguration config) { _userRepository = userRepository; _config = config; } [HttpGet,Route("all")] public async Task<ActionResult<IEnumerable<AppUser>>> GetUsers() { try { var users =await _userRepository.GetUsersAsync(); return Ok(users); } catch(Exception ex) { return BadRequest("Error occurred while getting list of users"); } } [HttpGet, Route("search/{username}")] public async Task<ActionResult<AppUser>> GetUser(string username) { try { return await _userRepository.GetUserByUsernameAsync(username); } catch (Exception ex) { return BadRequest("Error occurred while getting user details by username"); } } [HttpPost, Route("{username}/forgot")] public async Task<JsonResult> ResetPassword(PasswordResetDto passwordResetDto, string username) { try { var user = await _userRepository.GetUserByUsernameAsync(username); if (user.Password == passwordResetDto.OldPassword) user.Password = passwordResetDto.NewPassword; _userRepository.Update(user); return new JsonResult("Successfully reset passowrd"); //return BadRequest("Failed to reset password"); } catch (Exception ex) { throw ex; } } [HttpGet,Route("getOtherUsers/{loginId}")] public async Task<ActionResult<IEnumerable<AppUser>>> GetOtherUsers(string loginId) { try { var otherUsers = await _userRepository.GetOtherUsers(loginId); return Ok(otherUsers); } catch(Exception ex) { return BadRequest("Failed to get other users"); } } [HttpGet, Route("getUserById/{userId}")] public async Task<ActionResult<AppUser>> GetUserById(string userId) { try { return await _userRepository.GetUserByIdAsync(userId); } catch (Exception ex) { return BadRequest("Error occurred while getting user details by username"); } } } }
using QuizApp.ViewModels; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace QuizApp.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ChooseDetailQuizPage : ContentPage { public ChooseDetailQuizPage() { InitializeComponent(); var triviaService = DependencyService.Resolve<ITriviaService>(); BindingContext = new ChooseDetailQuizPageVM(triviaService); } } }
using goPlayApi.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace goPlayApi { public class GoPlayDBContext:DbContext { public GoPlayDBContext(DbContextOptions<GoPlayDBContext> options):base(options) { } public DbSet<User> Users { get; set; } public DbSet<Venue> Venues { get; set; } public DbSet<Reservation> Reservation { get; set; } public DbSet<Promotion> Promotions { get; set; } public DbSet<Gamification> Gamification { get; set; } public DbSet<Review> Reviews { get; set; } public DbSet<VenuesImage> VenuesImages { get; set; } } }
using UnityEngine; using System.Collections; using DG.Tweening; public class Fire : MonoBehaviour { private Material _myMaterial; private int _times; private Vector2[] _offset_List = { new Vector2(0, 0) ,new Vector2(0.25f, 0), new Vector2(0.5f, 0),new Vector2(0.75f, 0) }; // Use this for initialization void Start () { _times = 0; _myMaterial = transform.GetComponent<Renderer>().material; InvokeRepeating("Play",0.05f,0.01f); } void Play() { _myMaterial.mainTextureOffset = _offset_List[_times]; _times++; _times = _times % 4; } }
using System; using System.Collections.Generic; using System.Linq; using MarkPad.Document; using MarkPad.Services.Interfaces; namespace MarkPad.MarkPadExtensions.SpellCheck { public class SpellCheckExtension : IDocumentViewExtension { public string Name { get { return "Spell check"; } } readonly ISpellingService _spellingService; IList<SpellCheckProvider> _providers = new List<SpellCheckProvider>(); public SpellCheckExtension(ISpellingService spellingService) { _spellingService = spellingService; } public void ConnectToDocumentView(DocumentView view) { if (_providers.Any(p => p.View == view)) throw new ArgumentException("View already has a spell check provider connected", "view"); var provider = new SpellCheckProvider(_spellingService, view); _providers.Add(provider); } public void DisconnectFromDocumentView(DocumentView view) { var provider = _providers.FirstOrDefault(p => p.View == view); if (provider == null) return; provider.Disconnect(); _providers.Remove(provider); } } }
using UnityEngine; public static class MethodExtensions { public static void ClampCoordinates(this Vector3 target, float minimumValue, float maximumValue) { target.x = Mathf.Clamp(target.x, minimumValue, maximumValue); target.y = Mathf.Clamp(target.y, minimumValue, maximumValue); target.z = Mathf.Clamp(target.z, minimumValue, maximumValue); } public static Vector3 ScreenToWorld(this Camera camera, Vector3 position) { position.z = camera.nearClipPlane; return camera.ScreenToWorldPoint(position); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IPTables.Net.NfTables.Modules.Nat { class NfSnatActionOp { } }
using System; using System.Runtime.InteropServices; namespace Vlc.DotNet.Core.Interops.Signatures { /// <summary> /// Get duration (in ms) of media descriptor object item. /// </summary> [LibVlcFunction("libvlc_media_get_duration")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate long GetMediaDuration(IntPtr mediaInstance); }
namespace gView.Framework.Symbology { public interface ISymbolRotation { float Rotation { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; using EBS.Infrastructure; using EBS.Infrastructure.Task; using Dapper.DBContext; using System.Reflection; using Autofac; using EBS.Infrastructure.Log; namespace EBS.AutoTask { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new TaskService() }; ServiceBase.Run(ServicesToRun); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using HHY.Models; using HHY.Models; using System.IO; using static Microsoft.AspNetCore.Http.StatusCodes; using HHY_NETCore.Attributes; using HHY.Models.ProductBanner; namespace HHY_NETCore.Controllers { [Authorize] public class ProductBannersController : Controller { private readonly HHYContext _context; public ProductBannersController(HHYContext context) { _context = context; } #region View public IActionResult Index() { return View(); } public IActionResult Edit() { return View(); } public IActionResult Create() { return View(); } #endregion [HttpGet("api/admin/getProductBanner")] public IActionResult Get(int? id) { if (id == null) { return Ok(_context.ProductBanners.ToList()); } else { var productbanner = _context.ProductBanners.Where(r => r.ID == id); if (productbanner.Any()) { return Ok(productbanner.FirstOrDefault()); } else { return StatusCode(Status400BadRequest, new ResponseMessage { Message = "查無資訊" }); } } } [HttpPost("api/admin/createProductBanner")] public async Task<IActionResult> Create(RequestProductBanner productBanner) { if (productBanner.file != null) { var savePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\Upload", productBanner.file.FileName); using (var stream = new FileStream(savePath, FileMode.Create)) { await productBanner.file.CopyToAsync(stream); } productBanner.ImgUrl = "/Upload/" + productBanner.file.FileName; } try { var targer = new ProductBanners() { ImgUrl = productBanner.ImgUrl, PublishDate = productBanner.PublishDate, Url = productBanner.Url, DownDate = productBanner.DownDate, Title = productBanner.Title }; _context.ProductBanners.Add(targer); await _context.SaveChangesAsync(); return Ok(); } catch (Exception ex) { return StatusCode(Status400BadRequest, new ResponseMessage { Message = "查無資訊" }); } } [HttpPut("api/admin/editProductBanner")] public async Task<IActionResult> Edit(RequestProductBanner productBanner) { var ProductBanner = _context.ProductBanners.Where(r => r.ID == productBanner.ID); if (ProductBanner.Any()) { try { var data = ProductBanner.FirstOrDefault(); if (productBanner.file != null) { var savePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\Upload", productBanner.file.FileName); using (var stream = new FileStream(savePath, FileMode.Create)) { await productBanner.file.CopyToAsync(stream); } data.ImgUrl = "/Upload/" + productBanner.file.FileName; } data.Title = productBanner.Title; data.Url = productBanner.Url; data.PublishDate = productBanner.PublishDate; data.DownDate = productBanner.DownDate; await _context.SaveChangesAsync(); return Ok(); } catch (Exception ex) { return StatusCode(Status400BadRequest, new ResponseMessage { Message = ex.Message }); } } else { return StatusCode(Status400BadRequest, new ResponseMessage { Message = "查無資訊" }); } } [HttpDelete("api/admin/delProductBanner")] public async Task<IActionResult> Delete(int? id) { if (id == null) { return StatusCode(Status400BadRequest, new ResponseMessage { Message = "查無資訊" }); } var productBanner = _context.ProductBanners.Where(r => r.ID == id); if (productBanner.Any()) { _context.ProductBanners.Remove(productBanner.FirstOrDefault()); await _context.SaveChangesAsync(); return Ok(); } else { return StatusCode(Status400BadRequest, new ResponseMessage { Message = "查無資訊" }); } } } }
using gView.Framework.IO; using gView.Framework.system; using gView.Framework.UI; using System; using System.Reflection; using System.Threading.Tasks; namespace gView.Framework.Metadata { [gView.Framework.system.RegisterPlugIn("32C9CDB8-5A2D-4fc1-87AD-2AE960D1E31A")] public class GeneralMetadata : IMetadataProvider, IPropertyPage { private string _abstract = "", _purpose = "", _language = "", _subl_info = ""; private string _access_constraints = "", _use_constraints = ""; private string _credits = "", _contact = ""; public GeneralMetadata() { _abstract = String.Empty; } #region Properties public string Abstract { get { return _abstract; } set { _abstract = value; } } public string Purpose { get { return _purpose; } set { _purpose = value; } } public string Language { get { return _language; } set { _language = value; } } public string Supplemental_Information { get { return _subl_info; } set { _subl_info = value; } } public string Access_Constraints { get { return _access_constraints; } set { _access_constraints = value; } } public string Use_Constraints { get { return _use_constraints; } set { _use_constraints = value; } } public string Contact { get { return _contact; } set { _contact = value; } } public string Credits { get { return _credits; } set { _credits = value; } } #endregion #region IMetadataProvider Member public Task<bool> ApplyTo(object Object) { return Task.FromResult(true); } public string Name { get { return "General"; } } #endregion #region IPersistable Member public void Load(IPersistStream stream) { _abstract = (string)stream.Load("Abstract", String.Empty); _purpose = (string)stream.Load("Purpose", String.Empty); _language = (string)stream.Load("Language", String.Empty); _subl_info = (string)stream.Load("Supplemental_Information", String.Empty); _access_constraints = (string)stream.Load("Access_Constraints", String.Empty); _use_constraints = (string)stream.Load("Use_Constraints", String.Empty); _contact = (string)stream.Load("Contact", String.Empty); _credits = (string)stream.Load("Credits", String.Empty); } public void Save(IPersistStream stream) { stream.Save("Abstract", _abstract); stream.Save("Purpose", _purpose); stream.Save("Language", _language); stream.Save("Supplemental_Information", _subl_info); stream.Save("Access_Constraints", _access_constraints); stream.Save("Use_Constraints", _use_constraints); stream.Save("Contact", _contact); stream.Save("Credits", _credits); } #endregion #region IPropertyPage Member public object PropertyPage(object initObject) { string appPath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); Assembly uiAssembly = Assembly.LoadFrom(appPath + @"/gView.Win.Metadata.UI.dll"); IPlugInParameter p = uiAssembly.CreateInstance("gView.Framework.Metadata.UI.GeneralMetadataControl") as IPlugInParameter; if (p != null) { p.Parameter = this; } return p; } public object PropertyPageObject() { return this; } #endregion } //[gView.Framework.system.RegisterPlugIn("2C1EA3BA-92E6-4B0D-B3C2-2802A1264683")] //public class AdvancedMetadata : IMetadataProvider //{ // static private List<Uri> _servers = new List<Uri>(); // #region IMetadataProvider Member // public bool ApplyTo(object Object) // { // return true; // } // public string Name // { // get { return "Advanced"; } // } // #endregion // #region IPersistable Member // public void Load(IPersistStream stream) // { // } // public void Save(IPersistStream stream) // { // } // #endregion //} }
using LineOperator2.Models; using LineOperator2.Services; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using SQLite; namespace LineOperator2.ViewModels { public class Job { [SQLite.PrimaryKey, SQLite.AutoIncrement] public int ID { get; set; } public string PartID { get; set; } public string Line { get; set; } public int TotalBoxes { get; set; } public string Material { get; set; } public int BoxesPerCrate { get; set; } [SQLite.Ignore] public ObservableCollection<Product> Parts { get; set; } private Pin pinpoint; [SQLite.Ignore] public Pin PinPoint { get { return pinpoint; } set { pinpoint = value; Database.AddUpdatePin(value); } } [SQLite.Ignore] public Product Part { get; set; } public Job() { Initialize(); } public Job(string lineID) { Initialize(lineID); } private void Initialize(string lineID = "Empty") { Line = lineID; PinPoint = new Pin(); Part = new Product(); Parts = Database.GetParts(); } public bool Write() { //write "this" to the database if (this.Part != null) { this.PartID = this.Part.PartName; } Database.AddUpdateJob(this); if (this.PinPoint != null) { this.PinPoint.JobID = this.ID; Database.AddUpdatePin(this.PinPoint); } //Write "pin" to the database with the key of "this" as a foriegn key //Write "product" to the database with the key of "this" as a foreign key return false; } public bool Read() { //Get the Part from the Part ID and put it in. this.Part = Database.GetProduct(this.PartID); //Get the PinPoint and assign it as well. this.PinPoint = Database.GetPinPoint(ID); return false; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.OleDb; namespace Proyecto { public partial class Auto : Form { public Auto() { InitializeComponent(); } private void btnAgregar_Click(object sender, EventArgs e) { string pla, mar, mod, col; pla = txtPlaca.Text; mar = txtMarca.Text; mod = txtModelo.Text; col = txtColor.Text; string query = "Insert into Auto(Placa, Marca, Modelo, Color) VALUES ('" + pla + "','" + mar + "','" + mod + "','" + col + "')"; OleDbConnection con = new OleDbConnection("Provider = SQLNCLI11; Data Source = IRIS\\SQLEXPRESS; Integrated Security = SSPI; Initial Catalog = Proyecto"); OleDbCommand cmd = new OleDbCommand(query, con); try { con.Open(); cmd.ExecuteNonQuery(); con.Close(); txtPlaca.Text = ""; txtModelo.Text = ""; txtMarca.Text = ""; txtColor.Text = ""; oleDbDataAdapter1.Fill(dAuto1); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnModificar_Click(object sender, EventArgs e) { string pla, mar, mod, col; pla = txtPlaca.Text; mar = txtMarca.Text; mod = txtModelo.Text; col = txtColor.Text; OleDbConnection con = new OleDbConnection("Provider = SQLNCLI11; Data Source = IRIS\\SQLEXPRESS; Integrated Security = SSPI; Initial Catalog = Proyecto"); con.Open(); string query = "Update Auto Set Marca = '" + txtMarca.Text + "'"; OleDbCommand cmd = new OleDbCommand(query, con); cmd.ExecuteNonQuery(); MessageBox.Show("Modificado"); con.Close(); } private void btnEliminar_Click(object sender, EventArgs e) { string pla, mar, mod, col; pla = txtPlaca.Text; mar = txtMarca.Text; mod = txtModelo.Text; col = txtColor.Text; OleDbConnection con = new OleDbConnection("Provider = SQLNCLI11; Data Source = IRIS\\SQLEXPRESS; Integrated Security = SSPI; Initial Catalog = Proyecto"); con.Open(); string query = "Delete from Auto where Placa = '" + txtPlaca.Text + "'"; OleDbCommand cmd = new OleDbCommand(query, con); cmd.ExecuteNonQuery(); MessageBox.Show("Eliminado"); con.Close(); } private void Auto_Load(object sender, EventArgs e) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace KartObjects { /// <summary> /// Перечень типов оплат /// </summary> public enum PayTypeInfo { [EnumDescription("Нет значения")] None = 0, [EnumDescription("ОПЛАТА НАЛ")] Cash = 1, [EnumDescription("ОПЛАТА БНАЛ")] Cashless = 2, [EnumDescription("БОНУС")] CLMBonus = 3, [EnumDescription("СЕРТИФИКАТ")] CLMCertificate = 4, [EnumDescription("КРЕДИТ")] Credit = 5, } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using MonoGame.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using System.Threading; using System.Timers; using Dev9.Xna.Performance; using RoboProv; namespace RoboBomber { /// <summary> /// This is the main type for your game /// </summary> public class RoboGame : Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; public Texture2D background, stone, player, player2, player3, player4, bomb, bomb2, fireh, firev, firem, pu_addbomb, pu_extendfire, pu_speedup, menu, roundend, ghost1, ghost2; int LastPlayerAlive = 0; SpriteFont GameFont, GameFont20pt; KeyboardState oldState; KeyboardState newState; FPSMonitor fps; bool ChangelogActive = false, GamesettingsActive = false, ShowDeathMessage, GameEnded = false; Random rand = new Random(); int MenuItem = 0, ActiveMenuValueItem = 0; string MenuParent = ""; SoundEffect bombexplosionsound2; //RoboBomber.Properties.Settings.Default.abc = "def"; Vector2 backgroundposition = Vector2.Zero; int MaxRows, MaxColumns, MaxRowsZr, MaxColumnsZr; generator Generator = new generator(); public RoboGame() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here graphics.PreferredBackBufferWidth = Properties.Settings.Default.ResolutionWidth; graphics.PreferredBackBufferHeight = Properties.Settings.Default.ResolutionHeight; graphics.PreferredBackBufferWidth = 600; graphics.PreferredBackBufferHeight = 600; Properties.Settings.Default.ResolutionWidth = graphics.PreferredBackBufferWidth; Properties.Settings.Default.ResolutionHeight = graphics.PreferredBackBufferHeight; //graphics.PreferredBackBufferHeight = 750; graphics.ApplyChanges(); MaxRows = (Properties.Settings.Default.ResolutionHeight / 50) + 1; MaxColumns = (Properties.Settings.Default.ResolutionWidth) / 50; MaxRowsZr = MaxRows-1; MaxColumnsZr = MaxColumns - 1; globals.MenuActive = false; generator.LoadMenuItems(); ShowDeathMessage = false; fps = new FPSMonitor(); //fps.Initialize(); base.Initialize(); GameEnded = false; // Die Listen erzeugen globals.Stonelist = new List<Rectangle>(); globals.Playerlist = new List<player>(); globals.Bomblist = new List<bomb>(); globals.FireList = new List<fire>(); globals.PowerupList = new List<powerup>(); //Steine erzeugen globals.Stonelist = Generator.GenerateStones(MaxRows, MaxColumns, 60, 80, stone); //Spieler erzeugen globals.Playerlist = Generator.GeneratePlayer(Properties.Settings.Default.HumanPlayer + Properties.Settings.Default.AIPlayer, MaxRowsZr, MaxColumnsZr, player, Properties.Settings.Default.AIPlayer); //Geister erzeugen globals.GhostList = Generator.GenerateGhosts(5); //this.ShowPlayerDeathNotice += new EventHandler( for (int tmpInt = 0; tmpInt <= ((Properties.Settings.Default.AIPlayer + Properties.Settings.Default.HumanPlayer) - 1); tmpInt++) globals.Playerlist[tmpInt].PlayerDied += new RoboProv.EventHandlerPlayerDied(this.NeedToShowDeathMessage); //Timer globals.GameTimer = new System.Timers.Timer(); globals.GameTimer.Elapsed += new ElapsedEventHandler(UpdateGameTimer); globals.GameTimer.Interval = 10; globals.GameTimer.Enabled = true; GC.KeepAlive(globals.GameTimer); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> /// protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); background = Content.Load<Texture2D>("ground"); stone = Content.Load<Texture2D>("stone"); player = Content.Load<Texture2D>("player"); player2 = Content.Load<Texture2D>("player2"); player3 = Content.Load<Texture2D>("player3"); player4 = Content.Load<Texture2D>("player4"); bomb = Content.Load<Texture2D>("bomb"); bomb2 = Content.Load<Texture2D>("bomb2"); fireh = Content.Load<Texture2D>("exp_h"); firev = Content.Load<Texture2D>("exp_v"); firem = Content.Load<Texture2D>("exp_m"); menu = Content.Load<Texture2D>("menu"); roundend = Content.Load<Texture2D>("roundend"); ghost1 = Content.Load<Texture2D>("ghost1"); ghost2 = Content.Load<Texture2D>("ghost2"); // bombexplosionsound = Content.Load<Song>("bombexplosion"); //TODO bombexplosionsound2 = Content.Load<SoundEffect>("bombexplosion2"); pu_addbomb = Content.Load<Texture2D>("pu_addbomb"); pu_extendfire = Content.Load<Texture2D>("pu_extendfire"); pu_speedup = Content.Load<Texture2D>("pu_speedup"); GameFont = Content.Load<SpriteFont>("Arial"); GameFont20pt = Content.Load<SpriteFont>("Arial20pt"); Properties.Settings.Default.PlayerHeight = player.Height; Properties.Settings.Default.PlayerWidth = player.Width; globals.StoneHeight = stone.Height; globals.StoneWidth = stone.Width; globals.BombWidth = bomb.Width; globals.BombHeight = bomb.Height; globals.FireWidth = firem.Width; globals.FireHeight = firem.Height; Properties.Settings.Default.MonsterWidth = ghost1.Width; Properties.Settings.Default.MonsterHeight = ghost1.Height; // TODO: use this.Content to load your game content here } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> /// protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> /// protected override void Update(GameTime gameTime) { // Allows the game to exit /* TODO if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); */ // TODO: Add your update logic here UpdateInput(); UpdateBombAnimations(); UpdateBombExplosions(); UpdateFire(); UpdatePlayer(); fps.Update(); base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> /// protected override void Draw(GameTime gameTime) { graphics.GraphicsDevice.Clear(Color.CornflowerBlue); //Hintergrund zeichnen spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); spriteBatch.Draw(background, backgroundposition, Color.White); spriteBatch.End(); #region Steine zeichnen //Alle Steine aus Stonelist zeichnen foreach (Rectangle CurrStone in globals.Stonelist) { spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); spriteBatch.Draw(stone, CurrStone, Color.White); spriteBatch.End(); } #endregion #region Figuren zeichnen //Figuren zeichnen foreach (player CurrPlayer in globals.Playerlist) { if (CurrPlayer.alive) { spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); switch (CurrPlayer.id) { case 0: spriteBatch.Draw(player, CurrPlayer.GetVector2(), Color.White); break; case 1: spriteBatch.Draw(player2, CurrPlayer.GetVector2(), Color.White); break; case 2: spriteBatch.Draw(player3, CurrPlayer.GetVector2(), Color.White); break; case 3: spriteBatch.Draw(player4, CurrPlayer.GetVector2(), Color.White); break; } spriteBatch.End(); } } #endregion #region Geister zeichnen //Figuren zeichnen foreach (ghost CurrGhost in globals.GhostList) { if (CurrGhost.alive) { spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); switch (CurrGhost.type) { case ghosttype.red: spriteBatch.Draw(ghost1, CurrGhost.position, Color.White); break; case ghosttype.purple: spriteBatch.Draw(ghost2, CurrGhost.position, Color.White); break; } spriteBatch.End(); } } #endregion #region Bomben zeichnen foreach (bomb CurrBomb in globals.Bomblist) { spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); if (CurrBomb.animationid == 0) spriteBatch.Draw(bomb, CurrBomb.GetRectangle(), Color.White); else spriteBatch.Draw(bomb2, CurrBomb.GetRectangle(), Color.White); spriteBatch.End(); } #endregion #region Feuer zeichnen foreach (fire CurrFire in globals.FireList) { spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); switch (CurrFire.direction) { case 'm': spriteBatch.Draw(firem, CurrFire.GetRectangle(), Color.White); break; case 'h': spriteBatch.Draw(fireh, CurrFire.GetRectangle(), Color.White); break; case 'v': spriteBatch.Draw(firev, CurrFire.GetRectangle(), Color.White); break; } spriteBatch.End(); } #endregion #region Powerups zeichnen foreach (powerup CurrPowerup in globals.PowerupList) { spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); switch (CurrPowerup.type) { case "pu_addbomb": spriteBatch.Draw(pu_addbomb, CurrPowerup.GetRectangle() , Color.White); break; case "pu_extendfire": spriteBatch.Draw(pu_extendfire, CurrPowerup.GetRectangle(), Color.White); break; case "pu_speedup": spriteBatch.Draw(pu_speedup, CurrPowerup.GetRectangle(), Color.White); break; } spriteBatch.End(); } #endregion DrawPlayerDeathMessage(); #region DebugInformationen zeichnen if (Properties.Settings.Default.debug) { spriteBatch.Begin(); fps.Draw(spriteBatch, GameFont, new Vector2(5, 700), Color.White); spriteBatch.DrawString(GameFont, "TimeElapsed: " + globals.GameTimeElapsed.ToString() + " FireSize: " + globals.Playerlist[0].GetFireSize().ToString() + " | StoneCount: " + globals.Stonelist.Count().ToString() + " | Alive: " + globals.Playerlist[0].alive.ToString() + " | ActivePUs: " + globals.Playerlist[0].ActivePowerups.Count().ToString() + " | ActiveBombs: " + globals.Playerlist[0].GetNumberOfActiveBombs().ToString(), new Vector2(5, 725), Color.White); spriteBatch.End(); } #endregion if (GameEnded) DrawGameEndMessage(); if (globals.MenuActive) ShowMenu(); base.Draw(gameTime); } private void UpdateInput() { newState = Keyboard.GetState(); if (ChangelogActive || GamesettingsActive) return; #region ESC für Menu if (newState.IsKeyDown(Keys.Escape) && !oldState.IsKeyDown(Keys.Escape)) { globals.MenuActive = !globals.MenuActive; if (globals.MenuActive) { MenuParent = ""; MenuItem = 0; } // ShowMenu(); } #endregion if (globals.MenuActive == false) { if (GameEnded) { if (newState.IsKeyDown(Keys.Enter) && !oldState.IsKeyDown(Keys.Enter)) { Initialize(); } } else { #region Computerspieler bewegen foreach (player CurrPlayer in globals.Playerlist) { if (CurrPlayer.AIplayer && CurrPlayer.alive) { switch (AIOperations.GetAction(CurrPlayer.id)) { case "MoveUp": globals.Playerlist[CurrPlayer.id].Move(MoveDirections.Up); break; case "MoveDown": globals.Playerlist[CurrPlayer.id].Move(MoveDirections.Down); break; case "MoveRight": globals.Playerlist[CurrPlayer.id].Move(MoveDirections.Right); break; case "MoveLeft": globals.Playerlist[CurrPlayer.id].Move(MoveDirections.Left); break; case "DropBomb": DropBomb(CurrPlayer.id); break; } } } #endregion #region Tasten Player 0 if (newState.IsKeyDown(Keys.W)) { if (globals.Playerlist[0].alive) globals.Playerlist[0].Move(MoveDirections.Up); } if (newState.IsKeyDown(Keys.S)) { if (globals.Playerlist[0].alive) globals.Playerlist[0].Move(MoveDirections.Down); } if (newState.IsKeyDown(Keys.A)) { if (globals.Playerlist[0].alive) globals.Playerlist[0].Move(MoveDirections.Left); } if (newState.IsKeyDown(Keys.D)) { if (globals.Playerlist[0].alive) globals.Playerlist[0].Move(MoveDirections.Right); } if (newState.IsKeyDown(Keys.Space)) { if (globals.Playerlist[0].alive) DropBomb(0); } #endregion #region Tasten Player 1 if (newState.IsKeyDown(Keys.Up)) { if (globals.Playerlist[1].alive) globals.Playerlist[1].Move(MoveDirections.Up); } if (newState.IsKeyDown(Keys.Down)) { if (globals.Playerlist[1].alive) globals.Playerlist[1].Move(MoveDirections.Down); } if (newState.IsKeyDown(Keys.Left)) { if (globals.Playerlist[1].alive) globals.Playerlist[1].Move(MoveDirections.Left); } if (newState.IsKeyDown(Keys.Right)) { if (globals.Playerlist[1].alive) globals.Playerlist[1].Move(MoveDirections.Right); } if (newState.IsKeyDown(Keys.RightShift)) { if (globals.Playerlist[1].alive) DropBomb(1); } #endregion #region Geister bewegen try { foreach (ghost CurrGhost in globals.GhostList) { if (CurrGhost.alive) { if (CurrGhost.position == CurrGhost.TargetPosition) CurrGhost.CalcNextMoveDirection(); if (CurrGhost.TargetPosition.X < CurrGhost.position.X) { CurrGhost.Move(MoveDirections.Left); } else if (CurrGhost.TargetPosition.X > CurrGhost.position.X) { CurrGhost.Move(MoveDirections.Right); } else if (CurrGhost.TargetPosition.Y < CurrGhost.position.Y) { CurrGhost.Move(MoveDirections.Up); } else if (CurrGhost.TargetPosition.Y > CurrGhost.position.Y) { CurrGhost.Move(MoveDirections.Down); } } } } catch { // throw new Exception("GHOST ALRDY DEAD EXCEPTION"); } #endregion } } else { // HIER SIND WIR IM MENÜ #region Menu hoch/runter if (newState.IsKeyDown(Keys.Up) && !oldState.IsKeyDown(Keys.Up)) { MenuItem--; if (MenuItem < 0) MenuItem = operations.CountEntrysFromMenuParent(MenuParent) - 1; } if (newState.IsKeyDown(Keys.Down) && !oldState.IsKeyDown(Keys.Down)) { MenuItem++; if (MenuItem > operations.CountEntrysFromMenuParent(MenuParent) - 1) MenuItem = 0; } #endregion #region Menu links/rechts if (newState.IsKeyDown(Keys.Left) && !oldState.IsKeyDown(Keys.Left)) { } if (newState.IsKeyDown(Keys.Right) && !oldState.IsKeyDown(Keys.Right)) { } #endregion #region ENTER (Menu wechseln) if (newState.IsKeyDown(Keys.Enter) && !oldState.IsKeyDown(Keys.Enter)) { menuitem MenuEntry = operations.GetEntryFromParentAndPosition(MenuParent, MenuItem); switch (MenuEntry.itemtype) { case menuitemtype.RestartGame: Initialize(); break; case menuitemtype.ExitApplication: Exit(); break; case menuitemtype.Parent: MenuParent = MenuEntry.name; MenuItem = 0; break; case menuitemtype.Back: MenuParent = operations.GetUpperParentNameFromParent(MenuParent); MenuItem = operations.CountEntrysFromMenuParent(MenuParent) - 1; break; case menuitemtype.ShowChangelog: ChangelogActive = true; changelog FChangelog = new changelog(); FChangelog.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; if (FChangelog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) ChangelogActive = false; break; case menuitemtype.ShowGamesettings: GamesettingsActive = true; Gamesettings FGamesettings = new Gamesettings(); FGamesettings.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; if (FGamesettings.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) GamesettingsActive = false; break; } } #endregion } // Update saved state. oldState = newState; } private void UpdateBombAnimations() { int tmpIdx = 0; foreach (bomb CurrBomb in globals.Bomblist) { if ((CurrBomb.LastAnimationChange + globals.BombAnimationChangeSeconds) < globals.GameTimeElapsed) { if (CurrBomb.animationid == 0) globals.Bomblist[tmpIdx].animationid = 1; else globals.Bomblist[tmpIdx].animationid = 0; globals.Bomblist[tmpIdx].LastAnimationChange = globals.GameTimeElapsed; } tmpIdx++; } } private void UpdateBombExplosions() { int BombFieldX, BombFieldY; bomb CurrBomb; for (int tmpBombIdx = 0; tmpBombIdx <= globals.Bomblist.Count()-1; tmpBombIdx++) { CurrBomb = globals.Bomblist[tmpBombIdx]; if ((CurrBomb.BombDeployed + Properties.Settings.Default.BombDelayTillExplosion) < globals.GameTimeElapsed) { BombFieldX = checks.GetFieldXFromX(CurrBomb.x); BombFieldY = checks.GetFieldYFromY(CurrBomb.y); // TODO bombexplosionsound2.Play(); // Die 4 Richtungen in die das Feuer geht for (int firedirection = 1; firedirection <= 4; firedirection++) { // Die länge der Feuerstrahlen for (int firelength = 1; firelength <= CurrBomb.firesize; firelength++) { switch (firedirection) { //Nach Rechts case 1: globals.FireList.Add(new fire((BombFieldX + firelength) * globals.StoneWidth, BombFieldY * globals.FireHeight, 'h')); //Falls ein Stein getroffen wurde, soll das Feuer nicht weiter verlängern: if (checks.CheckIfAStoneIsAtThisPosition(new Rectangle((BombFieldX + firelength) * globals.StoneWidth, BombFieldY * globals.FireHeight, globals.StoneWidth, globals.StoneHeight))) firelength = CurrBomb.firesize + 1; break; //Nach Links case 2: globals.FireList.Add(new fire(((BombFieldX - firelength)) * globals.StoneWidth, BombFieldY * globals.FireHeight, 'h')); if (checks.CheckIfAStoneIsAtThisPosition(new Rectangle(((BombFieldX - firelength)) * globals.StoneWidth, BombFieldY * globals.FireHeight, globals.StoneWidth, globals.StoneHeight))) firelength = CurrBomb.firesize + 1; break; //Nach Oben case 3: globals.FireList.Add(new fire(BombFieldX * globals.FireWidth, (BombFieldY - firelength) * globals.StoneHeight, 'v')); if (checks.CheckIfAStoneIsAtThisPosition(new Rectangle(BombFieldX * globals.FireWidth, (BombFieldY - firelength) * globals.StoneHeight, globals.StoneWidth, globals.StoneHeight))) firelength = CurrBomb.firesize + 1; break; //Nach Unten case 4: globals.FireList.Add(new fire(BombFieldX * globals.FireWidth, (BombFieldY + firelength) * globals.StoneHeight, 'v')); if (checks.CheckIfAStoneIsAtThisPosition(new Rectangle(BombFieldX * globals.FireWidth, (BombFieldY + firelength) * globals.StoneHeight, globals.StoneWidth, globals.StoneHeight))) firelength = CurrBomb.firesize + 1; break; } } } // Und das Feuer in der Mitte globals.FireList.Add(new fire(BombFieldX * globals.FireWidth, BombFieldY * globals.StoneHeight, 'm')); globals.Playerlist[globals.Bomblist[tmpBombIdx].playerid].BombsDropped--; for (int tmpPlayerID = 0; tmpPlayerID <= globals.Playerlist.Count() - 1; tmpPlayerID++) checks.CheckIfPlayerHitsFire(tmpPlayerID); foreach (fire CurrFire in globals.FireList) { checks.CheckIfFireHitsPowerup(CurrFire.GetRectangle()); checks.CheckIfFireHitsMonster(CurrFire.GetRectangle()); } globals.Bomblist.RemoveAt(tmpBombIdx); //FEHLER?: tmpBombIdx++; } } } private void UpdateFire() { //Feuer nach der Remain- Zeit löschen fire CurrFire; for (int tmpFireIdx = 0; tmpFireIdx <= globals.FireList.Count() - 1; tmpFireIdx++) { CurrFire = globals.FireList[tmpFireIdx]; if ((CurrFire.DropTime + Properties.Settings.Default.FireRemainSec) < globals.GameTimeElapsed) { globals.FireList.RemoveAt(tmpFireIdx); //Explodierte Steine löschen for (int tmpStoneIdx = 0; tmpStoneIdx <= globals.Stonelist.Count() - 1; tmpStoneIdx++) { if (globals.Stonelist[tmpStoneIdx].Intersects(CurrFire.GetRectangle())) { // Und ggf. ein PowerUp generieren if (rand.Next(100) < Properties.Settings.Default.powerupperc) globals.PowerupList.Add(new powerup(globals.Stonelist[tmpStoneIdx].X, globals.Stonelist[tmpStoneIdx].Y, pu_addbomb.Height,pu_addbomb.Width)); // Stein löschen globals.Stonelist.RemoveAt(tmpStoneIdx); } } } } } private void UpdatePlayer() { foreach (player CurrPlayer in globals.Playerlist) { for (int tmpPuIdx = 0; tmpPuIdx <= CurrPlayer.ActivePowerups.Count()-1;tmpPuIdx++) { //Prüfen ob Powerup abgelaufen ist switch (CurrPlayer.ActivePowerups[tmpPuIdx].type) { case "pu_addbomb": if ((CurrPlayer.ActivePowerups[tmpPuIdx].Activated + Properties.Settings.Default.pu_addbomb_remain) < globals.GameTimeElapsed) CurrPlayer.ActivePowerups.RemoveAt(tmpPuIdx); break; case "pu_extendfire": if ((CurrPlayer.ActivePowerups[tmpPuIdx].Activated + Properties.Settings.Default.pu_extendfire_remain) < globals.GameTimeElapsed) CurrPlayer.ActivePowerups.RemoveAt(tmpPuIdx); break; case "pu_speedup": if ((CurrPlayer.ActivePowerups[tmpPuIdx].Activated + Properties.Settings.Default.pu_speedup_remain) < globals.GameTimeElapsed) CurrPlayer.ActivePowerups.RemoveAt(tmpPuIdx); break; } } } } private void DropBomb(int PlayerID) { if (globals.Playerlist[PlayerID].CanDropBomb()) { globals.Playerlist[PlayerID].LastBombDroppedID = globals.AddBomb(PlayerID); globals.Playerlist[PlayerID].BombsDropped++; } } private void ShowMenu() { int tmpIdx = 0; //Hintergrund zeichnen spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); spriteBatch.Draw(menu, new Vector2((Properties.Settings.Default.ResolutionWidth-menu.Width) / 2, (Properties.Settings.Default.ResolutionHeight - menu.Height) /2),Color.White); //spriteBatch.DrawString(GameFont, System.Windows.Forms.Application.ProductVersion, new Vector2(((Properties.Settings.Default.ResolutionWidth - menu.Width) / 2) + menu.Width - 100, ((Properties.Settings.Default.ResolutionHeight - menu.Height) / 2)), Color.Black); spriteBatch.End(); foreach (menuitem CurrMenuItem in operations.GetEntrysFromMenuParent(MenuParent)) { if (CurrMenuItem.parent == MenuParent) { spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); if (MenuItem == tmpIdx) spriteBatch.DrawString(GameFont, "> " + CurrMenuItem.name, new Vector2((Properties.Settings.Default.ResolutionWidth - menu.Width) / 2, ((Properties.Settings.Default.ResolutionHeight - menu.Height) / 2) + 100 + (tmpIdx * 30)), Color.Red); else spriteBatch.DrawString(GameFont, CurrMenuItem.name, new Vector2((Properties.Settings.Default.ResolutionWidth - menu.Width) / 2, ((Properties.Settings.Default.ResolutionHeight - menu.Height) / 2) + 100 + (tmpIdx * 30)), Color.Black); //Auswahlwerte wenn notwendig anzeigen if (CurrMenuItem.itemtype == menuitemtype.SelectionList) { if (MenuItem == tmpIdx) spriteBatch.DrawString(GameFont, CurrMenuItem.name, new Vector2((Properties.Settings.Default.ResolutionWidth - menu.Width) , ((Properties.Settings.Default.ResolutionHeight - menu.Height) / 2) + 100 + (tmpIdx * 30)), Color.Red); else spriteBatch.DrawString(GameFont, CurrMenuItem.name, new Vector2((Properties.Settings.Default.ResolutionWidth - menu.Width), ((Properties.Settings.Default.ResolutionHeight - menu.Height) / 2) + 100 + (tmpIdx * 30)), Color.Black); } spriteBatch.End(); } tmpIdx++; } } private void NeedToShowDeathMessage(int PlayerID) { //Tritt ein wenn irgendein Spieler gestorben ist RoboSpeech.SpeekSentence("Bomberman " + PlayerID.ToString() + " died!"); ShowDeathMessage = true; //Und noch prüfen ob überhaupt noch jemand lebt, wenn nicht: Spielende anzeigen int tmpCountPlayerAlive = 0; foreach (player CurrPlayer in globals.Playerlist) { if (CurrPlayer.alive == true) { tmpCountPlayerAlive++; LastPlayerAlive = CurrPlayer.id; break; } } if (tmpCountPlayerAlive <= 1) GameEnded = true; } private void DrawPlayerDeathMessage() { List<int> DeadPlayers = new List<int>(); if (ShowDeathMessage) { foreach (player CurrPlayer in globals.Playerlist) if (CurrPlayer.PlayerDiedTimestamp.AddSeconds(Properties.Settings.Default.DeathNoticeRemain) > DateTime.Now) DeadPlayers.Add(CurrPlayer.id); if (DeadPlayers.Count() > 0) { for (int tmpIdx = 0; tmpIdx <= DeadPlayers.Count() - 1; tmpIdx++) { string tmpString = "BOMBERMAN " + DeadPlayers[tmpIdx].ToString() + " DIED!"; Vector2 tmpVec = operations.GetPositionForCenterString(GameFont20pt, tmpString); tmpVec.Y += (tmpIdx * GameFont20pt.MeasureString(tmpString).Y); spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); spriteBatch.DrawString(GameFont20pt, tmpString, tmpVec, Color.Red); spriteBatch.End(); } } else { ShowDeathMessage = false; } } } private void DrawGameEndMessage() { spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); spriteBatch.Draw(roundend, new Vector2((Properties.Settings.Default.ResolutionWidth - roundend.Width) / 2, (Properties.Settings.Default.ResolutionHeight - roundend.Height) / 2), Color.White); spriteBatch.End(); string tmpString = "BOMBERMAN " + LastPlayerAlive.ToString() + " WON!"; Vector2 tmpVec = operations.GetPositionForCenterString(GameFont20pt, tmpString); tmpVec.Y += (GameFont20pt.MeasureString(tmpString).Y); spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); spriteBatch.DrawString(GameFont20pt, tmpString, tmpVec, Color.Black); tmpString = "PRESS ENTER TO RESTART GAME"; tmpVec = operations.GetPositionForCenterString(GameFont20pt, tmpString); tmpVec.Y += Properties.Settings.Default.ResolutionHeight * (float) 0.2; spriteBatch.DrawString(GameFont20pt, tmpString, tmpVec, Color.Black); spriteBatch.End(); } private static void UpdateGameTimer(object source, ElapsedEventArgs e) { if (!globals.MenuActive) globals.GameTimeElapsed += globals.GameTimer.Interval; } } }
namespace EventFeed.Producer.Clicks { public interface IClickService { void RegisterClick(); } }
using System.Collections.Generic; using UserService.Model; using UserService.Repository; namespace UserService.Service { public class SpecialtyService : ISpecialtyService { private readonly ISpecialtyRepository _specialtyRepository; public SpecialtyService(ISpecialtyRepository specialtyRepository) { _specialtyRepository = specialtyRepository; } public IEnumerable<Specialty> GetAll() { return _specialtyRepository.GetAll(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using DChild.Gameplay.Player.Equipments; using DChild.Gameplay; public class WeaponPickUp : MonoBehaviour { private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.tag == "Player") { Debug.Log("Equiped"); //PrototypeLogic.playerEquiped(true); gameObject.SetActive(false); } } }
using System; using System.Collections.Generic; using Fingo.Auth.DbAccess.Models; namespace Fingo.Auth.DbAccess.Context { public class AuthServerContextSeeder { public static void Seed(AuthServerContext context) { SeedUsers(context); SeedProjects(context); } private static void SeedProjects(AuthServerContext context) { var data = new List<Project> { new Project { Information = new ClientInformation {ContactData = "contactData1"} , Name = "name1" , ProjectUsers = new List<ProjectUser> { new ProjectUser {UserId = 1} , new ProjectUser {UserId = 2} , new ProjectUser {UserId = 3} } } , new Project { Information = new ClientInformation {ContactData = "contactData2"} , Name = "name2" , ProjectUsers = new List<ProjectUser> {new ProjectUser {UserId = 2} , new ProjectUser {UserId = 4}} } , new Project { Information = new ClientInformation {ContactData = "contactData3"} , Name = "name3" } , new Project { Information = new ClientInformation {ContactData = "contactData4"} , Name = "name4" } }; var data1 = new List<Project> { new Project { Name = "ManagementAppProject" , ProjectGuid = new Guid("AC1A551CB011EDB100D1E55BEEF511CE") } }; context.Set<Project>().AddRange(data); context.Set<Project>().AddRange(data1); context.SaveChanges(); } private static void SeedUsers(AuthServerContext context) { var users = new List<User> { new User { FirstName = "pierwszy" , LastName = "pierwszy" , Login = "q@q" , Password = "8e35c2cd3bf6641bdb0e2050b76932cbb2e6034a0ddacc1d9bea82a6ba57f7cf" , Status = 0 } , new User {FirstName = "drugi" , LastName = "drugi" , Login = "drugi" , Password = "drugi" , Status = 0} , new User { FirstName = "trzeci" , LastName = "trzeci" , Login = "trzeci" , Password = "trzeci" , Status = 0 } , new User { FirstName = "czwarty" , LastName = "czwarty" , Login = "czwarty" , Password = "czwarty" , Status = 0 } }; context.Set<User>().AddRange(users); context.SaveChanges(); } } }
using UnityEngine; using System.Collections; public class Items : Scenario { private GameObject[] other; private int lay = 2; private bool isVisible = true; private bool clickOt = false; private float time2 = -10f; private int togo = 5; public int Lay { get { return this.lay; } set { lay = value; } } public bool IsVisible { get { return this.isVisible; } set { isVisible = value; } } public override void Put() { base.Put (); sc.sortingLayerName = "Game"; sc.sortingOrder = this.Lay; this.tag = "Item"; if (!this.IsVisible) sc.color = new Color (255f, 255f, 255f, 0f); else sc.color = new Color (255f, 255f, 255f, 1f); Instantiate (this, new Vector3 (this.posX, this.posY, 0f), Quaternion.identity); } void Start() { if (this.name == "Control_Blanco_IZQ(Clone)" || this.name == "Control_Blanco_DER(Clone)") this.gameObject.GetComponent<SpriteRenderer> ().color = new Color (255f, 255f, 255f, 0.1f); } void FixedUpdate() { clickOt = false; if (this.name == "Control_Blanco_IZQ(Clone)") this.gameObject.transform.position = new Vector3 (Camera.main.transform.position.x - Camara.delayCamX + 0.3f + gameObject.GetComponent<Renderer> ().bounds.size.x / 2f, Camera.main.transform.position.y - Camara.delayCamY + 1.4f); if (this.name == "Control_Blanco_DER(Clone)") gameObject.transform.position = new Vector3 (Camera.main.transform.position.x + Camara.delayCamX + 0.8f - gameObject.GetComponent<Renderer> ().bounds.size.x, Camera.main.transform.position.y - Camara.delayCamY + 1.5f); if (Input.GetMouseButtonDown (0)) { other = GameObject.FindGameObjectsWithTag("Other"); for (int i = 0, k = other.Length; i < k; i++) { if (other[i].gameObject.GetComponent<OtherChar>().ClickLimits(Input.mousePosition)) { clickOt = true; break; } } if (this.ClickLimits(Input.mousePosition) && !clickOt) { if (this.name == "Locker(Clone)") { if (GameObject.Find("Manzana(Clone)") != null) { if (!GameObject.Find("Manzana(Clone)").gameObject.GetComponent<Items>().ClickLimits(Input.mousePosition)) StartCoroutine(GameObject.FindGameObjectWithTag("GameController").gameObject.GetComponent<GameManager>().TopBall("Esto es un locker")); } else StartCoroutine(GameObject.FindGameObjectWithTag("GameController").gameObject.GetComponent<GameManager>().TopBall("Esto es un locker")); } else if (this.name == "LockerabiertoDer(Clone)" && this.gameObject.GetComponent<SpriteRenderer>().color.a == 0f) { this.gameObject.GetComponent<SpriteRenderer>().color = new Color(255f, 255f, 255f, 1f); if (GeneralGameManager.apple) GameObject.Find("Manzana(Clone)").gameObject.GetComponent<SpriteRenderer>().color = new Color(255f, 255f, 255f, 1f); } else if (this.name == "LockerabiertoIzq(Clone)" && this.gameObject.GetComponent<SpriteRenderer>().color.a == 0f) this.gameObject.GetComponent<SpriteRenderer>().color = new Color(255f, 255f, 255f, 1f); else if (this.name == "Manzana(Clone)" && this.gameObject.GetComponent<SpriteRenderer>().color.a == 1f) { StartCoroutine(GameObject.FindGameObjectWithTag("GameController").gameObject.GetComponent<GameManager>().TopBall("¡Has conseguido una manzana!")); GeneralGameManager.advance++; this.Active(false); } else if (this.name == "Tablones(Clone)") { if (GeneralGameManager.hammer) { StartCoroutine(GameObject.FindGameObjectWithTag("GameController").gameObject.GetComponent<GameManager>().TopBall("¡Pudiste desbloquear la puerta!")); GameObject.FindGameObjectWithTag("GameController").gameObject.GetComponent<GameManager>().PutNew("DoorPacman", "puertaPacman", false, 25.05f, 1.09f); this.Active(false); } else StartCoroutine(GameObject.FindGameObjectWithTag("GameController").gameObject.GetComponent<GameManager>().TopBall("Parece que la puerta esta bloqueada. Con la herramienta adecuada se puede abrir.")); } else if (this.name == "Personerocerrado(Clone)") StartCoroutine(GameObject.FindGameObjectWithTag("GameController").gameObject.GetComponent<GameManager>().TopBall("Parece que esta oficina esta bloqueada. Pero se escuchan ruidos.")); else if (this.name == "Organico(Clone)") StartCoroutine(GameObject.FindGameObjectWithTag("GameController").gameObject.GetComponent<GameManager>().TopBall("Orgánico")); else if (this.name == "Papel(Clone)") StartCoroutine(GameObject.FindGameObjectWithTag("GameController").gameObject.GetComponent<GameManager>().TopBall("Papel")); else if (this.name == "Plastico(Clone)") StartCoroutine(GameObject.FindGameObjectWithTag("GameController").gameObject.GetComponent<GameManager>().TopBall("Plástico")); else if (this.name == "Candado(Clone)") { if (GeneralGameManager.key) { if (GeneralGameManager.advance == 13) { GameObject.FindGameObjectWithTag("GameController").gameObject.GetComponent<GameManager>().PutNew("Personero", "PersoneroAbierto", true, 34f, 0f); this.gameObject.GetComponent<Items>().Active(false); GameObject.Find("Personerocerrado(Clone)").gameObject.GetComponent<Items>().Active(false); } else StartCoroutine(GameObject.FindGameObjectWithTag("GameController").gameObject.GetComponent<GameManager>().TopBall("Estoy ocupado,vuelve luego.")); } else StartCoroutine(GameObject.FindGameObjectWithTag("GameController").gameObject.GetComponent<GameManager>().TopBall("No tienes la llave para abrirlo.")); } else if (this.name == "CanecaAbierta(Clone)") { GameObject.FindGameObjectWithTag("GameController").gameObject.GetComponent<GameManager>().PutNew("CanecaAbierta2", "canecaAbierta", false, 20.9f, -0.63f); this.gameObject.GetComponent<Items>().Active(false); } else if (this.name == "CanecaAbierta2(Clone)") { GameObject.FindGameObjectWithTag("GameController").gameObject.GetComponent<GameManager>().PutNew("Encapuchado", "encapuchado_total", true, 20.8f, -1.39f, 0.5f); StartCoroutine(GameObject.Find("Encapuchado(Clone)").gameObject.GetComponent<OtherChar>().AnimEnc()); } else if (this.name == "Patio(Clone)" && GeneralGameManager.advance == 5) { GameObject.Find("Out").GetComponent<Inventory>().fadeoff(); time2 = Time.time; togo = 6;//1 } else if (this.name == "DoorPacman(Clone)" && GeneralGameManager.hammer && GeneralGameManager.advance == 8) { GameObject.Find("Out").GetComponent<Inventory>().fadeoff(); time2 = Time.time; togo = 7;//2 } else if (this.name == "ClassRoomClose(Clone)" && GeneralGameManager.advance == 18) { GameObject.FindGameObjectWithTag("GameController").gameObject.GetComponent<GameManager>().PutNew("ClassroomOpen", "PuertaColegioFinal", false, 50.4f, 1.09f); this.Active(false); } else if (this.name == "ClassroomOpen(Clone)" && GeneralGameManager.advance == 18) { GameObject.Find("Out").GetComponent<Inventory>().fadeoff(); time2 = Time.time; togo = 12;//7 } //---------------------------------------------------------------------------------------------------------- else if (this.name == "Cartel1(Clone)") { this.gameObject.transform.position = new Vector3(Camera.main.transform.position.x, Camera.main.transform.position.y); this.gameObject.GetComponent<SpriteRenderer>().sortingOrder = 9; this.gameObject.transform.localScale = new Vector3 (1.5f, 1.5f, 0f); } else if (this.name == "Cartel2(Clone)") { this.gameObject.transform.position = new Vector3(Camera.main.transform.position.x, Camera.main.transform.position.y); this.gameObject.GetComponent<SpriteRenderer>().sortingOrder = 9; this.gameObject.transform.localScale = new Vector3 (1.5f, 1.5f, 0f); } else if (this.name == "CartelSebusca(Clone)") { this.gameObject.transform.position = new Vector3(Camera.main.transform.position.x, Camera.main.transform.position.y); this.gameObject.GetComponent<SpriteRenderer>().sortingOrder = 9; this.gameObject.transform.localScale = new Vector3 (0.55f, 0.55f, 0f); } else if (this.name == "Skatepark(Clone)") { if (GeneralGameManager.advance == 29) { GameObject.Find("Out").GetComponent<Inventory>().fadeoff(); time2 = Time.time; togo = 14;//7 } else StartCoroutine(GameObject.FindGameObjectWithTag("GameController").gameObject.GetComponent<GameManager_City>().TopBall("¡Aún no ha abierto!")); } else if (this.name == "EncapuchadoBols(Clone)") { this.Active(false); GameObject.FindGameObjectWithTag("GameController").gameObject.GetComponent<GameManager_City>().PutNew("Encapuchado", "encapuchado_total", true, 50f, -2.6f, 0.5f); GameObject.Find("Encapuchado(Clone)").gameObject.GetComponent<OtherChar>().AnimEnc(); } else if (this.name == "Intercom(Clone)" && GeneralGameManager.advance == 35) { this.gameObject.transform.position = new Vector3(Camera.main.transform.position.x, Camera.main.transform.position.y); this.gameObject.GetComponent<SpriteRenderer>().sortingOrder = 9; this.gameObject.transform.localScale = new Vector3 (1.5f, 1.5f, 0f); } } else { if (this.name == "Cartel1(Clone)" && this.gameObject.transform.localScale.x >= 1f) { GameObject.Find("Cartel1(Clone)").gameObject.transform.position = new Vector3(-48.259f, 0.076f); GameObject.Find("Cartel1(Clone)").gameObject.GetComponent<SpriteRenderer>().sortingOrder = 2; GameObject.Find("Cartel1(Clone)").gameObject.transform.localScale = new Vector3(0.313f, 0.313f, 0f); } else if (this.name == "Cartel2(Clone)" && this.gameObject.transform.localScale.x >= 1f) { GameObject.Find("Cartel2(Clone)").gameObject.transform.position = new Vector3(-39.477f, -0.821f); GameObject.Find("Cartel2(Clone)").gameObject.GetComponent<SpriteRenderer>().sortingOrder = 2; GameObject.Find("Cartel2(Clone)").gameObject.transform.localScale = new Vector3(0.313f, 0.313f, 0f); } else if (this.name == "CartelSebusca(Clone)" && this.gameObject.transform.localScale.x >= 0.5f) { GameObject.Find("CartelSebusca(Clone)").gameObject.transform.position = new Vector3(-46.25f, -0.53f); GameObject.Find("CartelSebusca(Clone)").gameObject.GetComponent<SpriteRenderer>().sortingOrder = 2; GameObject.Find("CartelSebusca(Clone)").gameObject.transform.localScale = new Vector3(0.071f, 0.071f, 0f); } else if (this.name == "Intercom(Clone)" && this.gameObject.transform.localScale.x >= 1.3f) { GameObject.Find("Intercom(Clone)").gameObject.transform.position = new Vector3(65.93f, 0.87f); GameObject.Find("Intercom(Clone)").gameObject.GetComponent<SpriteRenderer>().sortingOrder = 2; GameObject.Find("Intercom(Clone)").gameObject.transform.localScale = new Vector3(0.366f, 0.366f, 0f); Application.LoadLevel(17); } } } } void LateUpdate() { if (Time.time >= time2 + 1.5f && Time.time <= time2 + 2f) Application.LoadLevel (togo); } }
using DataStructure.Abstractions; using System; using System.Collections.Generic; using System.Text; namespace DataStructure.Models { public class PlayList : BaseModel { public string PlayListName { get; set; } public User User { get; set; } public List<Song> Songs { get; set; } } }
[System.Serializable] public class CountryCodeModel { //public string as; public string city; public string country; public string countryCode; public string isp; public float lat; public float lon; public string org; public string query; public string region; public string regionName; public string status;//success public string timezone; }
using System; using System.Collections.Generic; using System.Text; namespace RoadSimLib { public interface IInstance { IMap Map { get; } IDeck Deck { get; } } }
using System; namespace Ricky.Infrastructure.Core { public interface ILog { void Error(object message, Exception exception = null, Type type = null); void Info(object message, Exception exception = null, Type type = null); } }
using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using SmartSchool.API.Models; using System.Collections.Generic; using System.Linq; namespace SmartSchool.API.Controllers { [Route("api/[controller]")] [ApiController] public class AlunoController : ControllerBase { public List<Aluno> Alunos = new List<Aluno>() { new Aluno(){Id=1, Nome="Marcos", Sobrenome="Cintra"}, new Aluno(){Id=2, Nome="Carlos", Sobrenome="Amaral"}, new Aluno(){Id=3, Nome="Luis", Sobrenome="Cintra"} }; [HttpGet] // Acessar todos All public ActionResult Get() { // acesso ======= http://localhost:5000/api/aluno return Ok(JsonConvert.SerializeObject(Alunos)); } [HttpGet("byId/{id}")] // Acessar por Id // acesso ======= http://localhost:5000/api/aluno/byid/1 public ActionResult GetById(int id) { var resultado = Alunos.FirstOrDefault(x => x.Id == id); if (resultado == null) return BadRequest("O Aluno não foi encontrado"); return Ok(JsonConvert.SerializeObject(resultado)); } //[HttpGet("nomeId/{nome}/sobrenomeId/{sobrenome}")] // acesso ======= http://localhost:5000/api/aluno/nomeid/Carlos/sobrenomeid/Amaral // ou [HttpGet("nomeId")] // Acessar por nome e Sobrenome ou somente nome // acesso ======= http://localhost:5000/api/aluno/nomeid?nome=carlos&sobrenome=amaral public ActionResult GetByName(string nome, string sobrenome) { //var resultado = Alunos.FirstOrDefault(x => x.Nome.ToUpper() == nome.ToUpper() && x.Sobrenome.ToUpper() == sobrenome.ToUpper()); // ou var resultado = Alunos.FirstOrDefault(x => x.Nome.ToUpper().Contains(nome.ToUpper()) && x.Sobrenome.ToUpper().Contains(sobrenome.ToUpper())); if (resultado == null) return BadRequest("O Aluno não foi encontrado"); return Ok(JsonConvert.SerializeObject(resultado)); } [HttpPost] // Incluir novo registro public ActionResult Post(Aluno aluno) { return Ok(aluno); } [HttpPut("{id}")] // Alterar todo registro public ActionResult Put(int id, Aluno aluno) { return Ok(aluno); } [HttpPatch("{id}")] // Alterar parcialmente public ActionResult Patch(int id, Aluno aluno) { return Ok(aluno); } [HttpDelete] // Deletar registro public ActionResult Delete(int id) { return Ok(); } } }
using HtmlAgilityPack; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MyKeibaDemo { class CHtmlResolver { public static RaceInfo GetRaceInfo(HtmlDocument htmldoc) { HtmlNode div = htmldoc.DocumentNode.SelectSingleNode("//html//div[@id='RCdata2']"); RaceInfo raceinfo = new RaceInfo(); raceinfo.race_date = DeleteCrlfTabNbsp(div.SelectSingleNode("//li[@class='RCdate']").InnerText); raceinfo.race_number = DeleteCrlfTabNbsp(div.SelectSingleNode("//li[@class='RCnum']").InnerText); raceinfo.race_distance = DeleteCrlfTabNbsp(div.SelectSingleNode("//li[@class='RCdst']").InnerText); raceinfo.race_starttime = DeleteCrlfTabNbsp(div.SelectSingleNode("//li[@class='RCstm']").InnerText); raceinfo.race_weather = DeleteCrlfTabNbsp(div.SelectSingleNode("//li[@class='RCwthr']").InnerText); raceinfo.race_condition = DeleteCrlfTabNbsp(div.SelectSingleNode("//li[@class='RCcnd']").InnerText); raceinfo.race_prize = DeleteCrlfTabNbsp(div.SelectSingleNode("//p").InnerText); return raceinfo; } public static List<string> GetWinOdds(HtmlDocument htmldoc) { HtmlNode table = htmldoc.DocumentNode.SelectSingleNode("//html//table[@summary='単勝・複勝']"); //HtmlNode table = htmldoc.DocumentNode.SelectSingleNode("/html[1]/body[1]/div[1]/div[3]/div[6]/div[1]/table[1]"); HtmlNodeCollection tds = table.SelectNodes("//td[@class='al-center']"); if (tds != null) { int count = tds.Count; // 単勝 List<string> win_odds = new List<string>(); for (int i = 0; i < count; i = i + 2) { string tdinnertext = DeleteCrlfTabNbsp(tds[i].InnerText); win_odds.Add(tdinnertext); } return win_odds; } else { List<string> win_odds = new List<string>(); win_odds.Add("null"); return win_odds; } } public static List<string> GetPlaceShowOdds(HtmlDocument htmldoc) { HtmlNode table = htmldoc.DocumentNode.SelectSingleNode("//html//table[@summary='単勝・複勝']"); //HtmlNode table = htmldoc.DocumentNode.SelectSingleNode("/html[1]/body[1]/div[1]/div[3]/div[6]/div[1]/table[1]"); HtmlNodeCollection tds = table.SelectNodes("//td[@class='al-center']"); if (tds != null) { int count = tds.Count; // 複勝 List<string> placeshow_odds = new List<string>(); for (int i = 1; i < count; i = i + 2) { string tdinnertext = DeleteCrlfTabNbsp(tds[i].InnerText); placeshow_odds.Add(tdinnertext); } return placeshow_odds; } else { List<string> placeshow_odds = new List<string>(); placeshow_odds.Add("null"); return placeshow_odds; } } public static List<string> GetBracketQuinellaOdds(HtmlDocument htmldoc) { HtmlNode table = htmldoc.DocumentNode.SelectSingleNode("//html//table[@summary='枠複']"); //HtmlNode table = htmldoc.DocumentNode.SelectSingleNode("/html[1]/body[1]/div[1]/div[3]/div[6]/div[1]/table[1]"); HtmlNodeCollection tdbqs = table.SelectNodes("//td[@class='w75px al-right' or @class='w75px al-right del']"); int count = tdbqs.Count; List<string> bracketquinella_odds = new List<string>(); // TODO: 枠連 for (int i = 0; i < count; i++) { string tdbqinnertext = DeleteCrlfTabNbsp(tdbqs[i].InnerText); bracketquinella_odds.Add(tdbqinnertext); } /* HtmlNodeCollection td77 = table.SelectNodes("//td[@class='w75px al-right del']"); if (td77 != null) { bracketquinella_odds.Insert(29, "null"); }*/ return bracketquinella_odds; } public static List<string> GetBracketExactaOdds(HtmlDocument htmldoc) { List<string> bracketexacta_odds = new List<string>(); // TODO: 枠単 return bracketexacta_odds; } public static List<string> GetQuinellaOdds(HtmlDocument htmldoc) { List<string> quinella_odds = new List<string>(); // TODO: 馬連 return quinella_odds; } public static List<string> GetExactaOdds(HtmlDocument htmldoc) { List<string> exacta_odds = new List<string>(); // TODO: 馬単 return exacta_odds; } public static List<string> GetQuinellaPlaceOdds(HtmlDocument htmldoc) { List<string> quinellaplace_odds = new List<string>(); // TODO: ワイド // http://en.wikipedia.org/wiki/Parimutuel_betting#Japan return quinellaplace_odds; } public static List<string> GetTrioOdds(HtmlDocument htmldoc) { List<string> trio_odds = new List<string>(); // TODO: 3連複 return trio_odds; } public static List<string> GetTrifectaOdds(HtmlDocument htmldoc) { List<string> trifecta_odds = new List<string>(); // TODO: 3連単 return trifecta_odds; } private static string DeleteCrlfTabNbsp(string innertxt) { return innertxt.Replace("\n", "").Replace("\t", "").Replace(" ", "").Replace("&nbsp;", ""); } } }
using CarManageSystem.helper; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.SessionState; namespace CarManageSystem.handler.DepartmentManage { /// <summary> /// View 的摘要说明 /// </summary> public class View : IHttpHandler,IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //是否有部门管理员权限 var currentUser = CheckHelper.RoleCheck(context, 2); if (currentUser == null) return; dynamic json = new JObject(); json.state = "success"; using(cmsdbEntities cms=new cmsdbEntities()) { var departments = cms.departmentmanage .ToList() .Select(item => new { id=item.Id, bmInf11 = item.Name, bmInf2 = item.CreateDate.Value.ToShortDateString(), driNum = cms.user.ToList().Count(u => Convert.ToInt16(u.Department) == item.Id&&u.UserType!=-1), carNum = cms.carinfo.ToList().Count(c => Convert.ToInt16(c.DepartmentId) == item.Id) }).ToList(); json.branchNum = departments.Count(); json.bmInf = JArray.FromObject(departments); context.Response.Write(json.ToString()); cms.Dispose(); } } public bool IsReusable { get { return false; } } } }
using System.Web.Mvc; using System.IO; using System.Drawing; using BarCode.Helpers; using BarcodeLib; using System.Drawing.Imaging; namespace BarCode.Controllers { public class BarCodeController : Controller { public ActionResult Index() { return View(); } public ActionResult Invalido() { return View(); } public ActionResult GerarCodigo(string texto, int? largura, int? altura) { texto = texto ?? "0000000000000000000000000000000000000000000000"; largura = largura ?? 800; altura = altura ?? 100; try { Barcode b = new Barcode(); Image img = b.Encode(TYPE.Interleaved2of5, texto, Color.Black, Color.White, (int)largura, (int)altura); using (var streak = new MemoryStream()) { img.Save(streak, ImageFormat.Png); return File(streak.ToArray(), "image/png"); } } catch (System.Exception) { return RedirectToAction("Invalido"); } } } }
using System.Collections.Generic; using NHibernate; using NHibernate.Transform; using Profiling2.Domain.Contracts.Queries.Procs; using Profiling2.Domain.Prf.Persons; using SharpArch.NHibernate; namespace Profiling2.Infrastructure.Queries.Procs { public class PersonChangeActivityQuery : NHibernateQuery, IPersonChangeActivityQuery { public IList<PersonChangeActivityDTO> GetRevisions(int personId) { return Session.GetNamedQuery("PRF_SP_Summaries_ProfileChangeActivity_NHibernate") .SetParameter("PersonID", personId, NHibernateUtil.Int32) .SetResultTransformer(Transformers.AliasToBean<PersonChangeActivityDTO>()) .List<PersonChangeActivityDTO>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RTreeCodeApproach { class Program { static void Main(string[] args) { var search = new Search(); search.SearchWithINN(); Console.ReadLine(); } } }
using Newtonsoft.Json; using ProjectGrace.Logic.Business; using ProjectGrace.Logic.Business.Business_Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; namespace ProjectGrace.Logic.API.Controllers { public class FilterByHotAptController : ApiController { private readonly BusinessHelper biz = new BusinessHelper(); public async Task<HttpResponseMessage> Get([FromBody]object o) { var TargetHotApt = JsonConvert.DeserializeObject<HotelApartmentDTO>(o.ToString()); return Request.CreateResponse(HttpStatusCode.OK, await biz.FilterRoomByHotApt(TargetHotApt)); } } }
using Puppeteer.Core; using Puppeteer.Core.Configuration; using Puppeteer.Core.Helper; using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UIElements; namespace Puppeteer.UI { internal class ArchetypeView : PuppeteerView { public ArchetypeView(VisualElement _rootElement, VisualElement _leftPanel, VisualElement _rightPanel, Action<Guid> _updateLastSelectedCallback) : base(_rootElement, _leftPanel, _rightPanel) { m_Label = "Archetypes"; tooltip = "Create and configure the archetypes that define sets of goals, actions, and sensors."; var visualTreeAsset = Resources.Load<VisualTreeAsset>("LayoutArchetypeConfigurator"); visualTreeAsset.CloneTree(m_ConfiguratorElement); m_ConfiguratorElement.name = "configuratorContent"; PuppeteerManager.Instance.LoadDescriptionsOfType<ArchetypeDescription>(); m_SerialisedArchetypes = PuppeteerManager.Instance.GetArchetypeDescriptions(); for (int i = 0; i < m_SerialisedArchetypes.Count; ++i) { CreateArchetypeListItem(m_SerialisedArchetypes[i]); } m_ContextMenuScrollView = new ContextualMenuManipulator(_menubuilder => { _menubuilder.menu.AppendAction("Create New Archetype", _dropDownMenuAction => { AddNewArchetypeListItem(); }, DropdownMenuAction.Status.Normal); }); m_ListItemInOtherTabDeleted = new Dictionary<Type, Action<ListItem>> { {typeof(GoalListItem), OtherTabGoalListItemDeleted}, {typeof(ActionListItem), OtherTabActionListItemDeleted}, {typeof(SensorListItem), OtherTabSensorListItemDeleted}, }; m_OnUpdateSerialisedLastSelected = _updateLastSelectedCallback; OnListItemSelectedOrRemoved = ListItemSelectedOrRemoved; } public override void ClearSelection() { if (m_SelectedContentListItem != null) { UpdateSelectedContentListItem(null); } else { base.ClearSelection(); } } public override void CloseView() { base.CloseView(); m_AddButton.clickable.clicked -= AddNewArchetypeListItem; m_SearchPopup?.RemoveFromHierarchy(); m_ListItemScrollView.RemoveManipulator(m_ContextMenuScrollView); } public override void DeleteSelection() { if (m_SelectedContentListItem != null) { DeleteContentListItem(m_SelectedContentListItem); } else { base.DeleteSelection(); } } public override void DuplicateSelection() { if (m_SelectedListItem != null) { AddNewArchetypeListItem((m_SelectedListItem as ArchetypeListItem).GetDescription()); } } public override void EnterSelection() { if (m_SearchPopup != null) { (m_SearchPopup as SearchPopup<GoalDescription>)?.ChooseSelected(); (m_SearchPopup as SearchPopup<ActionDescription>)?.ChooseSelected(); (m_SearchPopup as SearchPopup<SensorDescription>)?.ChooseSelected(); } else if (m_SelectedContentListItem != null) { OpenOtherTabEntryRelatedToListItem(m_SelectedContentListItem); } } public override void MoveSelection(MoveDirection _direction) { if (m_SearchPopup != null) { (m_SearchPopup as SearchPopup<GoalDescription>)?.MoveSelection(_direction); (m_SearchPopup as SearchPopup<ActionDescription>)?.MoveSelection(_direction); (m_SearchPopup as SearchPopup<SensorDescription>)?.MoveSelection(_direction); } else if (m_SelectedContentListItem != null) { int scrollViewIndex = m_ArchetypeConfigurator.ScrollViewsSortedByXPosition.IndexOf(m_SelectedContentListItem.parent as ScrollView); if (_direction == MoveDirection.Left && scrollViewIndex > 0) { var leftNeighbour = m_ArchetypeConfigurator.ScrollViewsSortedByXPosition[--scrollViewIndex]; if (leftNeighbour?.childCount > 0) { UpdateSelectedContentListItem(leftNeighbour[0] as ListItem); } } else if (_direction == MoveDirection.Right && scrollViewIndex < m_ArchetypeConfigurator.ScrollViewsSortedByXPosition.Count - 1) { var rightNeighbour = m_ArchetypeConfigurator.ScrollViewsSortedByXPosition[++scrollViewIndex]; if (rightNeighbour?.childCount > 0) { UpdateSelectedContentListItem(rightNeighbour[0] as ListItem); } } else { SelectNeighbourContentListItem(_direction); } } else { base.MoveSelection(_direction); } } public override void OpenView(SerialisedConfiguratorState _serialisedConfiguratorStates) { base.OpenView(_serialisedConfiguratorStates); m_ListItemScrollViewHeader.text = "Available Archetypes"; m_ListItemScrollViewHeaderIcon.image = PuppeteerEditorResourceLoader.ArchetypeIcon32.texture; m_AddButton.clickable.clicked += AddNewArchetypeListItem; m_AddButton.tooltip = "Create a new archetype."; m_ListItemScrollView.AddManipulator(m_ContextMenuScrollView); for (int i = 0; i < m_ListItems.Count; ++i) { m_ListItemScrollView.Add(m_ListItems[i]); } if (m_SelectedListItem != null) { UpdateConfigurator(); } else if (!_serialisedConfiguratorStates.LastOpenedArchetype.Equals(Guid.Empty)) { TryOpenEntry(_serialisedConfiguratorStates.LastOpenedArchetype.Value); } else { DisableRightPanelContent(); } } public override void RegisterTabViewCallbacks(TabView _tabView) { _tabView.OnTabListItemDeleted += OtherTabListItemDeleted; } public override void SaveAllChanges() { bool shouldSaveToFile = PuppeteerEditorHelper.RemoveDeletedItems<ArchetypeListItem, ArchetypeDescription>(m_SerialisedArchetypes, m_ListItems) > 0; for (int i = 0; i < m_ListItems.Count; ++i) { shouldSaveToFile |= PuppeteerEditorHelper.AddOrUpdateInList<ArchetypeListItem, ArchetypeDescription>(m_SerialisedArchetypes, m_ListItems[i]); } bool successful = !shouldSaveToFile || PuppeteerManager.Instance.SaveArchetypes(); if (successful) { for (int i = 0; i < m_ListItems.Count; ++i) { m_ListItems[i].MarkUnsavedChanges(false); TryClearUnsavedMarker(); } } } public override void SaveSelectedChange() { bool shouldSaveToFile = PuppeteerEditorHelper.AddOrUpdateInList<ArchetypeListItem, ArchetypeDescription>(m_SerialisedArchetypes, m_SelectedListItem); bool successful = !shouldSaveToFile || PuppeteerManager.Instance.SaveArchetypes(); if (successful) { m_SelectedListItem.MarkUnsavedChanges(false); TryClearUnsavedMarker(); } } public override bool TryOpenEntry(Guid _guid) { var matchingItem = m_ListItems.Find(_entry => (_entry as ArchetypeListItem).GetDescription().GUID == _guid); if (matchingItem != null) { UpdateSelectedListItem(matchingItem); return true; } else { return base.TryOpenEntry(_guid); } } protected override void LazyInitConfigurator() { if (m_ArchetypeConfigurator != null) { return; } m_ArchetypeConfigurator = new ArchetypeConfigurator { DisplayName = m_ConfiguratorElement.Q<TextField>(name: "displayName"), GoalAddButton = m_ConfiguratorElement.Q<Button>(name: "goalAddButton"), ActionAddButton = m_ConfiguratorElement.Q<Button>(name: "actionAddButton"), SensorAddButton = m_ConfiguratorElement.Q<Button>(name: "sensorAddButton"), GoalScrollView = m_ConfiguratorElement.Q<ScrollView>(name: "goalScrollView"), ActionScrollView = m_ConfiguratorElement.Q<ScrollView>(name: "actionScrollView"), SensorScrollView = m_ConfiguratorElement.Q<ScrollView>(name: "sensorScrollView"), GUIDLabel = m_RightPanelContent.Q<Label>(name: "GUIDLabel"), }; m_ArchetypeConfigurator.ScrollViewsSortedByXPosition = new List<ScrollView> { m_ArchetypeConfigurator.GoalScrollView, m_ArchetypeConfigurator.ActionScrollView, m_ArchetypeConfigurator.SensorScrollView, }; // just in case the scrollViews are reordered in the UXML file. m_ArchetypeConfigurator.ScrollViewsSortedByXPosition = m_ArchetypeConfigurator.ScrollViewsSortedByXPosition.OrderBy(_entry => _entry.layout.x).ToList(); RegisterConfiguratorCallbacks(); } protected override void UpdateConfigurator() { if (m_SelectedListItem is ArchetypeListItem selectedArchetypeListItem) { EnableRightPanelContent(); LazyInitConfigurator(); ArchetypeDescription selectedDescription = selectedArchetypeListItem.GetDescription(); m_ArchetypeConfigurator.GUIDLabel.text = selectedDescription.GUID.ToString(); m_ArchetypeConfigurator.DisplayName.value = selectedDescription.DisplayName; m_ArchetypeConfigurator.DisplayName.RegisterCallback<FocusOutEvent>(_eventTarget => { if (PuppeteerEditorHelper.UpdateDescriptionIfNecessary((_eventTarget.target as TextField), ref (m_SelectedListItem as ArchetypeListItem).GetDescription().DisplayName)) { m_SelectedListItem.ChangeText((_eventTarget.target as TextField).value); m_SelectedListItem.MarkUnsavedChanges(true); AddUnsavedMarker(); } }); m_SearchPopup?.RemoveFromHierarchy(); m_SearchPopup = null; FillBasicListToVisualElement<GoalDescription>(selectedDescription.GoalGUIDs, m_ArchetypeConfigurator.GoalScrollView); FillBasicListToVisualElement<ActionDescription>(selectedDescription.ActionGUIDs, m_ArchetypeConfigurator.ActionScrollView); FillBasicListToVisualElement<SensorDescription>(selectedDescription.SensorGUIDs, m_ArchetypeConfigurator.SensorScrollView); } } private void AddNewArchetypeListItem() { ArchetypeDescription archetypeDescription = new ArchetypeDescription { DisplayName = "New Archetype", GoalGUIDs = new Guid[0], ActionGUIDs = new Guid[0], SensorGUIDs = new Guid[0], }; AddNewArchetypeListItem(archetypeDescription); } private void AddNewArchetypeListItem(ArchetypeDescription _archetypeDescription) { ArchetypeDescription newArchetypeDescription = new ArchetypeDescription { GUID = Guid.NewGuid(), DisplayName = _archetypeDescription.DisplayName, GoalGUIDs = _archetypeDescription.GoalGUIDs, ActionGUIDs = _archetypeDescription.ActionGUIDs, SensorGUIDs = _archetypeDescription.SensorGUIDs, }; ArchetypeListItem item = CreateArchetypeListItem(newArchetypeDescription); m_ListItemScrollView.Add(item); item.MarkUnsavedChanges(true); AddUnsavedMarker(); UpdateSelectedListItem(item); } private void AddNewComponentListItem(ListItem _item) { m_SearchPopup?.RemoveFromHierarchy(); m_SearchPopup = null; if (m_SelectedListItem is ArchetypeListItem selectedArchetypeListItem) { ArchetypeDescription selectedDescription = selectedArchetypeListItem.GetDescription(); if (_item is BasicListItem<GoalDescription> goalItem) { var goalDescription = goalItem.GetDescription(); PuppeteerEditorHelper.Append(ref selectedDescription.GoalGUIDs, goalDescription.GUID); m_ArchetypeConfigurator.GoalScrollView.Add(CreateBasicListItemOfType<GoalDescription>(goalDescription.GUID)); } else if (_item is BasicListItem<ActionDescription> actionItem) { var actionDescription = actionItem.GetDescription(); PuppeteerEditorHelper.Append(ref selectedDescription.ActionGUIDs, actionDescription.GUID); m_ArchetypeConfigurator.ActionScrollView.Add(CreateBasicListItemOfType<ActionDescription>(actionDescription.GUID)); selectedDescription.ActionGUIDs.Append(actionItem.GetDescription().GUID); } else if (_item is BasicListItem<SensorDescription> sensorItem) { var sensorDescription = sensorItem.GetDescription(); PuppeteerEditorHelper.Append(ref selectedDescription.SensorGUIDs, sensorDescription.GUID); m_ArchetypeConfigurator.SensorScrollView.Add(CreateBasicListItemOfType<SensorDescription>(sensorDescription.GUID)); selectedDescription.SensorGUIDs.Append(sensorItem.GetDescription().GUID); } } m_SelectedListItem.MarkUnsavedChanges(true); AddUnsavedMarker(); } private ArchetypeListItem CreateArchetypeListItem(ArchetypeDescription _archetypeDescription) { ValidateAndFixDescription(ref _archetypeDescription); ArchetypeListItem item = new ArchetypeListItem(_archetypeDescription); item.OnMouseDown += UpdateSelectedListItem; item.OnDelete += DeleteListItem; item.OnDuplicate += _item => AddNewArchetypeListItem((_item as ArchetypeListItem).GetDescription()); m_ListItems.Add(item); return item; } private BasicListItem<T> CreateBasicListItemOfType<T>(Guid _guid) where T : BasicDescription, new() { T description = PuppeteerManager.Instance.GetDescriptionOfType<T>(_guid); if (description == null) { description = new T { GUID = _guid, DisplayName = "Invalid GUID" }; } var newBasicListItem = new BasicListItem<T>(_description: description, _useDuplicateManipulator: false); newBasicListItem.OnMouseDown += UpdateSelectedContentListItem; newBasicListItem.OnDelete += DeleteContentListItem; newBasicListItem.tooltip = m_BasicListItemTooltipText; return newBasicListItem; } private void DeleteContentListItem(ListItem _contentListItem) { if (m_SelectedListItem is ArchetypeListItem selectedArchetypeListItem) { if (_contentListItem == m_SelectedContentListItem) { SelectNeighbourContentListItemIfNeeded(_contentListItem); } _contentListItem.RemoveFromHierarchy(); if (_contentListItem is BasicListItem<GoalDescription> goalContentListItem) { PuppeteerEditorHelper.Remove(ref selectedArchetypeListItem.GetDescription().GoalGUIDs, goalContentListItem.GetDescription().GUID); } else if (_contentListItem is BasicListItem<ActionDescription> actionContentListItem) { PuppeteerEditorHelper.Remove(ref selectedArchetypeListItem.GetDescription().ActionGUIDs, actionContentListItem.GetDescription().GUID); } else if (_contentListItem is BasicListItem<SensorDescription> sensorContentListItem) { PuppeteerEditorHelper.Remove(ref selectedArchetypeListItem.GetDescription().SensorGUIDs, sensorContentListItem.GetDescription().GUID); } m_SelectedListItem.MarkUnsavedChanges(true); AddUnsavedMarker(); } } private void DeleteGuidFromContainerIfNeeded(ref ArchetypeListItem _archetypeListItem, ref Guid[] _container, Guid _deletedGuid) { if (_container.Contains(_deletedGuid)) { PuppeteerEditorHelper.Remove(ref _container, _deletedGuid); _archetypeListItem.MarkUnsavedChanges(true); AddUnsavedMarker(); } } private void FillBasicListToVisualElement<T>(Guid[] _content, VisualElement _targetList) where T : BasicDescription, new() { var sortedContent = _content.OrderBy(_entry => { return PuppeteerManager.Instance.GetDescriptionOfType<T>(_entry).DisplayName; }).ToArray(); _targetList.Clear(); for (int i = 0; i < sortedContent.Length; ++i) { _targetList.Add(CreateBasicListItemOfType<T>(sortedContent[i])); } } private List<string> GetRelevantWorldStatesForSelectedContentListItem() { List<string> relevantWorldStates = new List<string>(); foreach (var relatedListItem in m_RelatedContentListItems) { relatedListItem.RemoveFromClassList("related"); } m_RelatedContentListItems.Clear(); if (m_SelectedContentListItem is BasicListItem<GoalDescription> selectedGoalListItem) { foreach (var goalPart in selectedGoalListItem.GetDescription().GoalParts) { relevantWorldStates.Add(goalPart.Key); } } else if (m_SelectedContentListItem is BasicListItem<ActionDescription> selectedActionListItem) { foreach (var precondition in selectedActionListItem.GetDescription().Preconditions) { relevantWorldStates.Add(precondition.Key); } foreach (var effect in selectedActionListItem.GetDescription().Effects) { relevantWorldStates.Add(effect.Key); } } else if (m_SelectedContentListItem is BasicListItem<SensorDescription> selectedSensorListItem) { relevantWorldStates.Add(selectedSensorListItem.GetDescription().ManagedWorldState); } return relevantWorldStates; } private void ListItemSelectedOrRemoved(ListItem _listItem) { if (_listItem == null) { m_OnUpdateSerialisedLastSelected?.Invoke(Guid.Empty); } else { m_OnUpdateSerialisedLastSelected?.Invoke((_listItem as ArchetypeListItem).GetDescription().GUID); } } private void OpenOtherTabEntryRelatedToListItem(ListItem _listItem) { if (_listItem is BasicListItem<GoalDescription> selectedGoalListItem) { (parent as TabView).OpenEntryInTabOfType<GoalView>(selectedGoalListItem.GetDescription().GUID); } else if (_listItem is BasicListItem<ActionDescription> selectedActionListItem) { (parent as TabView).OpenEntryInTabOfType<ActionView>(selectedActionListItem.GetDescription().GUID); } else if (_listItem is BasicListItem<SensorDescription> selectedSensorListItem) { (parent as TabView).OpenEntryInTabOfType<SensorView>(selectedSensorListItem.GetDescription().GUID); } } private void OpenSelectorPopup<TDesc>(List<TDesc> _entries, Button _button) where TDesc : BasicDescription { if (m_SearchPopup != null) { m_SearchPopup.RemoveFromHierarchy(); } Vector2 popupPosition = _button.LocalToParent(_button.clickable.lastMousePosition, m_ConfiguratorElement); Vector2 minMaxX = new Vector2(m_ConfiguratorElement.layout.xMin, m_ConfiguratorElement.layout.xMax); m_SearchPopup = new SearchPopup<TDesc>(m_RootElement, _entries, popupPosition, minMaxX); m_ConfiguratorElement.Add(m_SearchPopup); if (m_SearchPopup is SearchPopup<TDesc> searchPopup) { searchPopup.OnListItemClicked += AddNewComponentListItem; } } private void OtherTabActionListItemDeleted(ListItem _deletedListItem) { if (_deletedListItem is ActionListItem deletedActionListItem) { for (int i = 0; i < m_ListItems.Count; ++i) { if (m_ListItems[i] is ArchetypeListItem archetypeListItem) { DeleteGuidFromContainerIfNeeded(ref archetypeListItem, ref archetypeListItem.GetDescription().ActionGUIDs, deletedActionListItem.GetDescription().GUID); } } } } private void OtherTabGoalListItemDeleted(ListItem _deletedListItem) { if (_deletedListItem is GoalListItem deletedGoalListItem) { for (int i = 0; i < m_ListItems.Count; ++i) { if (m_ListItems[i] is ArchetypeListItem archetypeListItem) { DeleteGuidFromContainerIfNeeded(ref archetypeListItem, ref archetypeListItem.GetDescription().GoalGUIDs, deletedGoalListItem.GetDescription().GUID); } } } } private void OtherTabListItemDeleted(ListItem _deletedListItem) { if (m_ListItemInOtherTabDeleted.TryGetValue(_deletedListItem.GetType(), out var deleteAction)) { deleteAction.Invoke(_deletedListItem); } } private void OtherTabSensorListItemDeleted(ListItem _deletedListItem) { if (_deletedListItem is SensorListItem deletedSensorListItem) { for (int i = 0; i < m_ListItems.Count; ++i) { if (m_ListItems[i] is ArchetypeListItem archetypeListItem) { DeleteGuidFromContainerIfNeeded(ref archetypeListItem, ref archetypeListItem.GetDescription().SensorGUIDs, deletedSensorListItem.GetDescription().GUID); } } } } private void RegisterConfiguratorCallbacks() { m_ArchetypeConfigurator.GoalAddButton.clickable.clicked += () => { var goals = PuppeteerManager.Instance.GetGoalDescriptions(); var filteredList = goals.Where(_entry => { var selectedDescription = (m_SelectedListItem as ArchetypeListItem).GetDescription(); return !selectedDescription.GoalGUIDs.Contains(_entry.GUID); }).ToList(); OpenSelectorPopup(filteredList, m_ArchetypeConfigurator.GoalAddButton); }; m_ArchetypeConfigurator.ActionAddButton.clickable.clicked += () => { var actions = PuppeteerManager.Instance.GetActionDescriptions(); var filteredList = actions.Where(_entry => { var selectedDescription = (m_SelectedListItem as ArchetypeListItem).GetDescription(); return !selectedDescription.ActionGUIDs.Contains(_entry.GUID); }).ToList(); OpenSelectorPopup(filteredList, m_ArchetypeConfigurator.ActionAddButton); }; m_ArchetypeConfigurator.SensorAddButton.clickable.clicked += () => { var sensors = PuppeteerManager.Instance.GetSensorDescriptions(); var filteredList = sensors.Where(_entry => { var selectedDescription = (m_SelectedListItem as ArchetypeListItem).GetDescription(); return !selectedDescription.SensorGUIDs.Contains(_entry.GUID); }).ToList(); OpenSelectorPopup(filteredList, m_ArchetypeConfigurator.SensorAddButton); }; } private bool SelectNeighbourContentListItem(MoveDirection _direction) { if (_direction != MoveDirection.Up && _direction != MoveDirection.Down) { return false; } VisualElement containingScrollView = m_SelectedContentListItem.parent; int index = containingScrollView.IndexOf(m_SelectedContentListItem); if (index > 0 && _direction == MoveDirection.Up) { UpdateSelectedContentListItem(containingScrollView[--index] as ListItem); return true; } else if (index < containingScrollView.childCount - 1 && _direction == MoveDirection.Down) { UpdateSelectedContentListItem(containingScrollView[++index] as ListItem); return true; } return false; } private void SelectNeighbourContentListItemIfNeeded(ListItem _contentListItem) { if (_contentListItem != m_SelectedContentListItem) { return; } bool neighbourSelected = SelectNeighbourContentListItem(MoveDirection.Up); if (!neighbourSelected) { neighbourSelected |= SelectNeighbourContentListItem(MoveDirection.Down); } if (!neighbourSelected) { m_SelectedContentListItem = null; } } private bool TryWeakSelectIfActionListItem(VisualElement _item, ref List<string> _relevantWorldStates) { if (_item is BasicListItem<ActionDescription> actionListItem) { foreach (var precondition in actionListItem.GetDescription().Preconditions) { if (_relevantWorldStates.Find(_entry => _entry.Equals(precondition.Key)) != null) { m_RelatedContentListItems.Add(actionListItem); actionListItem.AddToClassList("related"); return true; } } foreach (var effect in actionListItem.GetDescription().Effects) { if (_relevantWorldStates.Find(_entry => _entry.Equals(effect.Key)) != null) { m_RelatedContentListItems.Add(actionListItem); actionListItem.AddToClassList("related"); return true; } } } return false; } private bool TryWeakSelectIfGoalListItem(VisualElement _item, ref List<string> _relevantWorldStates) { if (_item is BasicListItem<GoalDescription> goalListItem) { foreach (var goalPart in goalListItem.GetDescription().GoalParts) { if (_relevantWorldStates.Find(_entry => _entry.Equals(goalPart.Key)) != null) { m_RelatedContentListItems.Add(goalListItem); goalListItem.AddToClassList("related"); return true; } } } return false; } private bool TryWeakSelectIfSensorListItem(VisualElement _item, ref List<string> _relevantWorldStates) { if (_item is BasicListItem<SensorDescription> sensorListItem) { string managedState = sensorListItem.GetDescription().ManagedWorldState; if (_relevantWorldStates.Find(_entry => _entry.Equals(managedState)) != null) { m_RelatedContentListItems.Add(sensorListItem); sensorListItem.AddToClassList("related"); return true; } } return false; } private void UpdateSelectedContentListItem(ListItem _listItem) { m_SearchPopup?.RemoveFromHierarchy(); if (m_SelectedContentListItem != null) { m_SelectedContentListItem.RemoveFromClassList("selected"); if (_listItem == m_SelectedContentListItem) { OpenOtherTabEntryRelatedToListItem(_listItem); return; } } m_SelectedContentListItem = _listItem; m_SelectedContentListItem?.AddToClassList("selected"); WeakSelectRelatedItemsInOtherLists(); } private void ValidateAndFixDescription(ref ArchetypeDescription _archetypeDescription) { if (_archetypeDescription.GoalGUIDs == null) { _archetypeDescription.GoalGUIDs = new Guid[0]; } if (_archetypeDescription.ActionGUIDs == null) { _archetypeDescription.ActionGUIDs = new Guid[0]; } if (_archetypeDescription.SensorGUIDs == null) { _archetypeDescription.SensorGUIDs = new Guid[0]; } } private void WeakSelectRelatedItemsInOtherLists() { var relevantWorldStates = GetRelevantWorldStatesForSelectedContentListItem(); foreach (ScrollView scrollView in m_ArchetypeConfigurator.ScrollViewsSortedByXPosition) { foreach (VisualElement item in scrollView.Children()) { if (item == m_SelectedContentListItem) { continue; } if (TryWeakSelectIfGoalListItem(item, ref relevantWorldStates)) { continue; } if (TryWeakSelectIfActionListItem(item, ref relevantWorldStates)) { continue; } TryWeakSelectIfSensorListItem(item, ref relevantWorldStates); } } } private const string m_BasicListItemTooltipText = "Select to see related goals, actions, and sensors. Click twice to open its configuration."; private readonly ContextualMenuManipulator m_ContextMenuScrollView; private readonly Dictionary<Type, Action<ListItem>> m_ListItemInOtherTabDeleted; private readonly Action<Guid> m_OnUpdateSerialisedLastSelected; private readonly List<ListItem> m_RelatedContentListItems = new List<ListItem>(); private readonly List<ArchetypeDescription> m_SerialisedArchetypes; private ArchetypeConfigurator m_ArchetypeConfigurator = null; private VisualElement m_SearchPopup; private ListItem m_SelectedContentListItem = null; private class ArchetypeConfigurator { public Button ActionAddButton; public ScrollView ActionScrollView; public TextField DisplayName; public Button GoalAddButton; public ScrollView GoalScrollView; public Label GUIDLabel; public List<ScrollView> ScrollViewsSortedByXPosition; public Button SensorAddButton; public ScrollView SensorScrollView; } } }
/**************************************************** 文件:Parallax.cs 作者:Sam 邮箱: 403117224@qq.com 日期:2020/02/04 0:26 功能:摄像机Y轴锁定 *****************************************************/ using UnityEngine; public class Parallax : MonoBehaviour { public Transform Cam; public float moveRate; private float startPointX, startPointY; public bool lockY;//默认false void Start() { startPointX = transform.position.x; startPointY = transform.position.y; } void Update() { if (lockY)//锁定Y轴,左右移动 { transform.position = new Vector2(startPointX + Cam.position.x * moveRate, transform.position.y); } else//可上下左右移动 { transform.position = new Vector2(startPointX + Cam.position.x * moveRate, startPointY+Cam.position.y*moveRate); } } }
using System; using FoodPricer.Core.Order.Beverage; using FoodPricer.Core.Order.Dessert; using FoodPricer.Core.Order.Meal; using FoodPricer.Core.Order.MealPlan; using FoodPricer.Core.Order.MealPlan.Service; using FoodPricer.Core.Order.Offer.Discount.Service; namespace FoodPricer.Core.Order { public class Order { public IMeal Meal { get; } public IBeverage Beverage { get; } public IDessert Dessert { get; } public bool WithCoffee { get; } public Order(IMeal meal, IBeverage beverage, IDessert dessert, bool withCoffee) { Meal = meal; Beverage = beverage; Dessert = dessert; WithCoffee = withCoffee; } public double GetPrice() { IMealPlan mealPlan = new MealPlanService().GetMealPlanOrDefault(this); double reduction = new DiscountService().GetOverallReduction(this); if (mealPlan != null) { return mealPlan.Price + (WithCoffee ? 1 : 0) - reduction; } return Meal.Price + Beverage.Price + Dessert.Price + (WithCoffee ? 1 : 0) - reduction; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace mvvm.Utils { class RelayCommand : ICommand { Action execute = ExecuteMethod; Func<bool> executable = CanExecuteMethod; static void ExecuteMethod() { } static bool CanExecuteMethod() { return true; } public RelayCommand(Action execute) : this(execute, null) { } public RelayCommand(Action execute, Func<bool> executable) { if (execute != null) this.execute = execute; if (executable != null) this.executable = executable; } public void Execute(object parameter) { execute(); } public bool CanExecute(object parameter) { return executable(); } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested += value; } } } }
using CPClient.Domain.Entities; using CPClient.Data.Interfaces; using CPClient.Infra.Data.Context; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CPClient.Infra.Data.Repository { public class EnderecoTipoRepository : BaseRepository<EnderecoTipo>, IEnderecoTipoRepository { public EnderecoTipoRepository(SqlContext repositoryContext) : base(repositoryContext) { } } }
namespace KRFTemplateApi.Domain.CQRS.Sample.Command { using KRFCommon.CQRS.Command; public class SampleCommandOutput : ICommandResponse { public string Result { get; set; } } }
using FirstFollowParser; using System; using System.Collections.Generic; using System.Text; namespace LL1Parser { class Parser { public static List<Derivations> output = new List<Derivations>(); public static List<Derivations> parser(GrammarParser grammar, List<String> input) { var table = new ParseTable(grammar).table; Stack<String> pda = new Stack<String>(); bool error = false; bool first = true; for (int a = 0; a < input.Count; a++) { bool done = false; while (!done) { if (error) break; for (int i = 0; i < table.Length; i++) { for (int j = 0; j < table[i].Length; j++) { String var = input[a]; if (table[0][j] == var) { if (!(table[i][0] == "")) { if (table[i][j] != null && first) { pda.Push(table[i][0]); first = false; } if (table[i][j] != null && pda.Count > 0 && !first && !(table[i][j] == var) && table[i][0] == pda.Peek()) { Derivations d = new Derivations(); d.input = var; d.topOfStack = pda.Pop(); d.output = table[i][j]; List<String> temp = new List<String>(); temp.Add(d.output); List<List<String>> productions = splitProduction(temp, grammar); for (int k = productions[0].Count - 1; k >= 0; k--) { if (productions[0][k] != "!") pda.Push(productions[0][k]); } output.Add(d); } if (table[i][j] != null && pda.Count > 0 && (!first && table[i][j] == var) && table[i][0] == pda.Peek()) { Derivations d = new Derivations(); d.input = var; d.output = table[i][j]; d.topOfStack = pda.Pop(); List<String> temp = new List<String>(); temp.Add(d.output); List<List<String>> productions = splitProduction(temp, grammar); for (int k = productions[0].Count - 1; k >= 0; k--) { if (productions[0][k] != "!") pda.Push(productions[0][k]); } output.Add(d); } if (table[i][j] != null && grammar.terminals.Contains(pda.Peek()) && pda.Peek() == var) { Derivations d = new Derivations(); d.input = ""; d.output = pda.Peek(); d.topOfStack = pda.Pop(); done = true; output.Add(d); } if (table[i][j] == null && table[0][j] == var && table[i][0] == pda.Peek() && !done) { error = true; } } } } } } } if (!error) dollarPrsing(pda, grammar,table); if (error) { output = null; } return output; } public static bool haveNonEpislon(String[][] table, String var) { for (int i = 0; i < table.Length; i++) { for (int j = 0; j < table[i].Length; j++) { if (table[0][j] == var) { if (table[i][j] != null && (table[i][j] != "!") && i > 0) { return true; } } } } return false; } public static void dollarPrsing(Stack<String> pda, GrammarParser grammar, string[][] table) { while (pda.Count > 0) { for (int i = 0; i < table.Length; i++) { for (int j = 0; j < table[i].Length; j++) { if (table[0][j] == "$") { if (table[i][j] != null && table[i][0] != "") { if (pda.Count > 0 && table[i][0] == pda.Peek()) { Derivations d = new Derivations(); d.input = "$"; d.topOfStack = pda.Pop(); d.output = table[i][j]; List<String> temp = new List<String>(); temp.Add(d.output); List<List<String>> productions = splitProduction(temp, grammar); for (int k = productions[0].Count - 1; k >= 0; k--) { if (productions[0][k] != "!") pda.Push(productions[0][k]); } output.Add(d); } } } } } } } public static List<List<String>> splitProduction(List<String> production, GrammarParser grammer) { List<List<String>> output = new List<List<String>>(); for (int i = 0; i < production.Count; i++) { String tempo = production[i]; List<String> aProduction = new List<String>(); String temp = ""; for (int j = 0; j < tempo.Length; j++) { temp += tempo[j]; if (j + 1 < tempo.Length && (tempo[j + 1] + "") == "'") { temp += "'"; j++; } if (grammer.nonTerminals.Contains(temp) || grammer.terminals.Contains(temp) || temp == "!") { aProduction.Add(temp); temp = ""; } } output.Add(aProduction); } return output; } public static void printOutput(List<Derivations> output) { if (output != null) for (int i = 0; i < output.Count; i++) { Console.Write(output[i].topOfStack); if (!string.IsNullOrEmpty(output[i].input)) Console.Write("[" + output[i].input + "]" + " --> " + output[i].output); else Console.Write(" --> " + output[i].output); Console.WriteLine(); } else Console.WriteLine("Parse error"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IdomOffice.Interface.BackOffice.MasterData { public class Country { public string Id { get; set; } public int CountryId { get; set; } public string CountryName { get; set; } public Dictionary<string, string> CountryNameTranslate { get; set; } public string ImageGalleryPath { get; set; } public string ImageThumbnailsPath { get; set; } } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using StardewModdingAPI; using StardewModdingAPI.Events; using StardewModdingAPI.Utilities; using StardewValley; namespace TimeNotifier { class ModEntry : Mod { private Models.TimeConfig Config { get; set; } private bool istriggered = false; private int lock_minute; private DateTime LastNotification { get; set; } private int OneTimeReminder; private HashSet<short> RepeatingReminder; public override void Entry(IModHelper helper) { this.Config = helper.ReadConfig<Models.TimeConfig>(); SetDateTime(); RepeatingReminder = new HashSet<short>(); helper.Events.GameLoop.OneSecondUpdateTicked += GameLoop_OneSecondUpdateTicked; helper.Events.GameLoop.TimeChanged += GameLoop_TimeChanged; // Übersetzen helper.ConsoleCommands.Add("reload_config", "Reloads changed config file without restarting game", ReloadConfig); helper.ConsoleCommands.Add("clear_all_reminders", "Clears both one-time and repeated-time in-game time reminders", ClearAllReminders); helper.ConsoleCommands.Add("set_reminder", "Usage: set_reminder [true=repeat|false=once] [timevalue]", SetReminder); helper.ConsoleCommands.Add("clear_reminder", "Usage: clear_reminder [true=repeat|false=once] [timevalue]", ClearReminder); helper.ConsoleCommands.Add("list_reminders","list all reminders",ListAllReminders); } private void SetReminder(string command, string[] args) { if(args.Length!=2) { Monitor.Log(Helper.Translation.Get("false_args"), LogLevel.Info); return; } // Check if should repeat is a valid bool and if time ist valid number if (bool.TryParse(args[0], out bool repeat) && short.TryParse(args[1], out short time)) { // Check if time between 6 a.m and 2 p.m. if (time <= 2600 || time >= 600) { time = time.RoundUp(); // check if should repeat in-game time if(repeat) { if(!RepeatingReminder.Contains(time)) { RepeatingReminder.Add(time); } else { Monitor.Log(Helper.Translation.Get("already_exists"), LogLevel.Info); return; } } else { OneTimeReminder = time; } Monitor.Log(Helper.Translation.Get("new_ingame") + $" ({time})", LogLevel.Info); } else { Monitor.Log(Helper.Translation.Get("false_args"), LogLevel.Info); } } else { Monitor.Log(Helper.Translation.Get("false_value"), LogLevel.Info); } } private void ClearReminder(string command, string[] args) { if (args.Length != 2) { Monitor.Log(Helper.Translation.Get("false_args"), LogLevel.Info); return; } // Check if should repeat is a valid bool and if time ist valid number if (bool.TryParse(args[0], out bool repeat) && short.TryParse(args[1], out short time)) { // Check if time between 6 a.m and 2 p.m. if (time <= 2600 || time >= 600) { // check if repeat bool set if (repeat) { RepeatingReminder.Remove(time); } else { OneTimeReminder = 0; } Monitor.Log(Helper.Translation.Get("removed_value"), LogLevel.Info); } else { Monitor.Log(Helper.Translation.Get("false_args"), LogLevel.Info); } } else { Monitor.Log(Helper.Translation.Get("false_args"), LogLevel.Info); } } private void ClearAllReminders(string command, string[] args) { OneTimeReminder = 0; RepeatingReminder.Clear(); Monitor.Log(Helper.Translation.Get("clear_success"), LogLevel.Info); } private void ListAllReminders(string command, string[] args) { var once = OneTimeReminder !=0 ? Helper.Translation.Get("once") + ": " + OneTimeReminder : ""; var repeat = RepeatingReminder.Count != 0 ? Helper.Translation.Get("repeatedly") + ": " + string.Join(", ", RepeatingReminder) : ""; if(once.Length == 0 && repeat.Length == 0) { Monitor.Log(Helper.Translation.Get("no_reminder"), LogLevel.Info); } if(!string.IsNullOrWhiteSpace(once)) { Monitor.Log(once, LogLevel.Info); } if (!string.IsNullOrWhiteSpace(repeat)) { Monitor.Log(repeat, LogLevel.Info); } } private void GameLoop_TimeChanged(object sender, TimeChangedEventArgs e) { var tmp = (short)e.NewTime; if(tmp != OneTimeReminder && !RepeatingReminder.Contains(tmp)) { return; } Game1.addHUDMessage(new HUDMessage(Helper.Translation.Get("in_game_reminder") + ": " + tmp)); OneTimeReminder = 0; } private void GameLoop_OneSecondUpdateTicked(object sender, OneSecondUpdateTickedEventArgs e) { var now = DateTime.Now; // Save check if new hour and reset without check if seconds==0 because of process change it could be already 1 // Event comes every ~ 1 second if (now.Minute==0 && lock_minute==0 || lock_minute <= now.Minute) { istriggered = false; lock_minute = 0; } if (this.istriggered == false && Config.AlertOnFullHour && now.Minute == 0) { Notify(nameof(Models.TimeConfig.AlertOnFullHour)); } else if (this.istriggered == false && Config.AlertSpecificMinute != 0 && DateTime.Now.Minute == Config.AlertSpecificMinute) { Notify(nameof(Models.TimeConfig.AlertSpecificMinute)); } else if (this.istriggered == false && Config.AlertEveryXMinute != 0 && LastNotification.Add(new TimeSpan(0, Config.AlertEveryXMinute, 0)) < now) { Notify(nameof(Models.TimeConfig.AlertEveryXMinute)); } } private void Notify(string caller) { var now_str = DateTime.Now.ToString("t", System.Globalization.CultureInfo.CurrentCulture); caller = Config.showCallerName ? caller + ": " : ""; Game1.addHUDMessage(new HUDMessage(caller + Helper.Translation.Get("notify_text") + " " + now_str + " " + Helper.Translation.Get("clock_suffix"))); istriggered =true; lock_minute = DateTime.Now.Minute+1; SetDateTime(); } private void SetDateTime() { var now = DateTime.Now; LastNotification = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0); } private void ReloadConfig(string command, string[] args) { try { this.Config = Helper.ReadConfig<Models.TimeConfig>(); SetDateTime(); this.istriggered = false; Monitor.Log(Helper.Translation.Get("config_reload_success"), LogLevel.Debug); } catch (Exception) { Monitor.Log(Helper.Translation.Get("config_reload_error"), LogLevel.Debug); } } } }
using Common.Attributes; using MODEL.ActionModel; using MODEL.ViewModel; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace ShengUI.Helper { public class SysAction { /// <summary> /// 获取所有的控制器信息 /// </summary> /// <returns></returns> public static IList<MVCController> GetAllControllerByAssembly() { var result = new List<MVCController>(); var types = Assembly.Load("ShengUI.Logic.Admin").GetTypes(); foreach (var type in types) { if (type.BaseType.Name == "Controller")//如果是Controller { var controller = new MVCController(); controller.ControllerName = type.Name.Replace("Controller", "");//去除Controller的后缀 object[] attrs = type.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true); if (attrs.Length > 0) controller.Description = (attrs[0] as System.ComponentModel.DescriptionAttribute).Description; controller.LinkUrl = "/Admin/" + controller.ControllerName + "/Index"; result.Add(controller); } } return result; } /// <summary> /// 获取所有的动作信息(out 控制器信息) /// </summary> /// <param name="controllers">控制器信息</param> /// <returns></returns> public static IList<MVCAction> GetAllActionByAssembly(out IList<MVCController> controllers) { controllers = new List<MVCController>(); var result = new List<MVCAction>(); var types = Assembly.Load("ShengUI.Logic.Admin").GetTypes(); foreach (var type in types) { if (type.BaseType.Name == "Controller")//如果是Controller { var controller = new MVCController(); controller.ControllerName = type.Name.Replace("Controller", "");//去除Controller的后缀 //设置Controller数组 object[] attrs = type.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true); if (attrs.Length > 0) controller.Description = (attrs[0] as System.ComponentModel.DescriptionAttribute).Description; string defaultPage = "";//默认首页的控制器 result.AddRange(GetActions(type, out defaultPage)); controller.LinkUrl = "/Admin/" + controller.ControllerName + "/" + defaultPage; controllers.Add(controller); } } return result; } /// <summary> /// 获取所有的动作(根据控制器的Type) /// </summary> /// <param name="type">类别</param> /// <param name="DefaultPage">默认的控制器首页(Action)</param> /// <returns></returns> public static IList<MVCAction> GetActions(Type type, out string DefaultPage) { //默认是Index页面 DefaultPage = "Index"; var members = type.GetMethods(); var result = new List<MVCAction>(); foreach (var member in members) { if (member.ReturnType.Name == "ActionResult")//如果是Action { var item = new MVCAction(); item.ActionName = member.Name; item.ControllerName = member.DeclaringType.Name.Substring(0, member.DeclaringType.Name.Length - 10); // 去掉“Controller”后缀 object[] Defaultpages = member.GetCustomAttributes(typeof(DefaultPageAttribute), true); if (Defaultpages.Length > 0) DefaultPage = item.ActionName; object[] attrs = member.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true); if (attrs.Length > 0) item.Description = (attrs[0] as System.ComponentModel.DescriptionAttribute).Description; item.LinkUrl = "/Admin/" + item.ControllerName + "/" + item.ActionName; item.Name = item.ActionName; item.IsButton = "N"; item.IsLink = "N"; object[] ActionParent = member.GetCustomAttributes(typeof(ActionParentAttribute), true); if (ActionParent.Length > 0) item.IsParent = true; object[] ActionDesc = member.GetCustomAttributes(typeof(ActionDescAttribute), true); if (ActionDesc.Length > 0) { item.Name = (ActionDesc[0] as Common.Attributes.ActionDescAttribute).Name; item.IsButton = (ActionDesc[0] as Common.Attributes.ActionDescAttribute).isButton; item.IsLink = (ActionDesc[0] as Common.Attributes.ActionDescAttribute).isLink; } item.CD = "A_" + item.ControllerName + "_" + item.ActionName; if (item.ActionName != DefaultPage) item.PCD = "A_" + item.ControllerName + "_" + DefaultPage; else item.PCD = ""; result.Add(item); } } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Framework.Data { partial class DbWrapperHelper { interface IWrappedDb { /* /// <summary>真正的實體</summary> object WrapInstance { get; } */ } interface IWrappedDb<T> : IWrappedDb { /// <summary>真正的實體</summary> T Instance { get; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task4 { class Program { static void Main(string[] args) { Console.CursorVisible = false; int n; Console.Write("Введите число элементов в массиве \n"); n = int.Parse(Console.ReadLine()); int[,] arr = new int[n, n]; Random r = new Random(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { arr[i, j] = r.Next(-100, 100); Console.Write("{0} \t", arr[i, j]); } Console.WriteLine(); } int sum = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if ((i + j) % 2 != 0) continue; sum += arr[i, j]; } } Console.WriteLine(); Console.Write("Сумма элементов в массиве, стоящих на четных позициях \n sum = {0} ", sum); Console.ReadKey(); } } }
using UnityEngine; using System.Collections; public class SpriteManager : MonoBehaviour { public enum Direction { Up, Down, Left, Right }; int spriteIndex = 0; public Sprite[] front; public Sprite[] back; public Sprite[] left; public Sprite[] right; Sprite[] currentArray; // Use this for initialization void Start () { currentArray = new Sprite[4]; } public void SetDirection(Direction newDirection) { switch(newDirection) { case Direction.Up: currentArray = front; break; case Direction.Down: currentArray = back; break; case Direction.Left: currentArray = left; break; case Direction.Right: currentArray = right; break; } UpdateSprite(); } void UpdateSprite() { spriteIndex++; if (spriteIndex == 4) { spriteIndex = 0; } GetComponent<SpriteRenderer>().sprite = currentArray[spriteIndex]; } }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace HTyoLippumestari { public partial class register : System.Web.UI.Page { private string hashedpasswd; protected void Page_Load(object sender, EventArgs e) { } protected void btnRegister_Click(object sender, EventArgs e) { if (txtPsswd.Text == txtPasswd2.Text) { hashedpasswd = SimpleHash.ComputeHash(txtPsswd.Text, "SHA512", ConfigurationManager.AppSettings["salt"]); MysliCustomConnector mysliconnector = new MysliCustomConnector(); mysliconnector.OpenConnection(); if (mysliconnector.VerifyUserNotDuplicate(txtUser1.Text)) { if(mysliconnector.CreateUser(txtUser1.Text, hashedpasswd, txtFirstname.Text, txtLastname.Text, txtAddress.Text, txtPostal.Text, txtCity.Text, txtNro.Text, txtEmail.Text)){ txtDebug.Text = "Onnistui!"; mysliconnector.CloseConnection(); } else txtDebug.Text = "FAILED TO CREATE"; } else txtDebug.Text = "USER EXIST"; } else txtDebug.Text = "PASSWORD DOESENT MATCH VERIFIED PASSWORD"; } protected static byte[] GetBytes(string str) { byte[] bytes = new byte[str.Length * sizeof(char)]; System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using IWorkFlow.DataBase; namespace IWorkFlow.ORM { [Serializable] [DataTableInfo("B_OA_Attachment", "id")] public class B_OA_Attachment : QueryInfo { [DataField("id", "B_OA_Attachment", false)] public int id { get; set; } [DataField("fileName", "B_OA_Attachment")] public string fileName { get; set; } [DataField("relativeID", "B_OA_Attachment")] public string relativeID { get; set; } [DataField("filePath", "B_OA_Attachment")] public string filePath { get; set; } [DataField("uploadDate", "B_OA_Attachment")] public DateTime uploadDate { get; set; } [DataField("userid", "B_OA_Attachment")] public string userid { get; set; } [DataField("size", "B_OA_Attachment")] public string size { get; set; } [DataField("tableName", "B_OA_Attachment")] public string tableName { get; set; } } }
using UnityEngine; using System.Collections; public class AutoScroll: MonoBehaviour { public enum ScrollDirection { Up = 0, Down, Left, Right } public ScrollDirection direction = ScrollDirection.Up; public float speed = 1; public float delay = 1; public bool loop = false; private Vector2 startPosition; private RectTransform rectTransform; private float elapsed = 0; private bool started = false; public void Restart() { elapsed = 0; ResetPosition(); } private void ResetPosition() { if (started) rectTransform.anchoredPosition = startPosition; } #region MonoBehaviour void Awake() { rectTransform = (RectTransform)transform; } void Start() { StartCoroutine(delayedStart()); } private IEnumerator delayedStart() { yield return new WaitForEndOfFrame(); startPosition = rectTransform.anchoredPosition; started = true; } void Update() { if (!started) return; if (elapsed < delay) { elapsed += Time.unscaledDeltaTime; } else { Vector2 velocity; switch (direction) { case ScrollDirection.Up: if (rectTransform.anchoredPosition.y > 0) goto Skip; velocity = Vector2.up; break; case ScrollDirection.Down: if (rectTransform.anchoredPosition.y < 0) goto Skip; velocity = Vector2.down; break; case ScrollDirection.Left: if (rectTransform.anchoredPosition.x < 0) goto Skip; velocity = Vector2.left; break; case ScrollDirection.Right: if (rectTransform.anchoredPosition.x > 0) goto Skip; velocity = Vector2.right; break; default: velocity = Vector2.zero; break; } rectTransform.anchoredPosition += velocity * speed * Time.unscaledDeltaTime; } return; Skip: if (loop) ResetPosition(); } #endregion }
using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; using Swashbuckle.Swagger.Annotations; using XH.APIs.WebAPI.Models.Assets; using XH.Infrastructure.Storage; using XH.Infrastructure.Web.Storage; namespace XH.APIs.WebAPI.Controllers { [RoutePrefix("assets")] public class AssetsController : ApiControllerBase { private readonly IBlobStorageProvider _blobProvider; private readonly IBlobUrlResolver _urlResolver; public AssetsController(IBlobStorageProvider blobProvider, IBlobUrlResolver urlResolver) { _blobProvider = blobProvider; _urlResolver = urlResolver; } /// <summary> /// Upload assets to the folder /// </summary> /// <remarks> /// Request body can contain multiple files. /// </remarks> /// <param name="folderUrl">Parent folder url (relative or absolute).</param> /// <param name="url">Url for uploaded remote resource (optional)</param> /// <returns></returns> [HttpPost] [Route("upload")] [SwaggerResponse(HttpStatusCode.OK, "update assets", typeof(BlobInfo[]))] public async Task<IHttpActionResult> UploadAsset([FromUri]string folderUrl) { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } var blobs = new List<BlobInfoReponseModel>(); var blobMultipartProvider = new BlobStorageMultipartProvider(_blobProvider, _urlResolver, folderUrl); await Request.Content.ReadAsMultipartAsync(blobMultipartProvider); foreach (var blobInfo in blobMultipartProvider.BlobInfos) { blobs.Add(new BlobInfoReponseModel { Name = blobInfo.FileName, Size = blobInfo.Size.ToString(), MimeType = blobInfo.ContentType, RelativeUrl = blobInfo.Key, Url = _urlResolver.GetAbsoluteUrl(blobInfo.Key), UtcModifiedDate = blobInfo.UtcModifiedDate }); } return Ok(blobs.ToArray()); } } }
namespace Entoarox.AdvancedLocationLoader.Configs { internal class Tile : TileInfo { /********* ** Accessors *********/ public int? Interval; public string LayerId; public string SheetId; public int? TileIndex; public int[] TileIndexes; /********* ** Public methods *********/ public override string ToString() { if (this.TileIndex != null) if (this.SheetId != null) return $"Tile({this.MapName}@[{this.TileX}{','}{this.TileY}]:{this.LayerId} = `{this.SheetId}:{this.TileIndex}`)"; else return $"Tile({this.MapName}@[{this.TileX}{','}{this.TileY}]:{this.LayerId} = `{this.TileIndex}`)"; if (this.SheetId != null) return $"Tile({this.MapName}@[{this.TileX}{','}{this.TileY}]:{this.LayerId} = `{this.SheetId}:{string.Join(",", this.TileIndexes)}`)"; return $"Tile({this.MapName}@[{this.TileX}{','}{this.TileY}]:{this.LayerId} = `{string.Join(",", this.TileIndexes)}`)"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace server.Controllers { [Route("api/[controller]")] public class HealthCheckController : Controller { [HttpGet("[action]")] public bool IsAlive() { return true; } } }
using Model.Manager; using System.Collections.Generic; namespace Backend.Repository.RenovationPeriodRepository { public interface IRenovationPeriodRepository { List<RenovationPeriod> GetAllRenovationPeriod(); RenovationPeriod GetRenovationPeriodByRoomNumber(int roomNumber); void UpdateRenovationPeriod(RenovationPeriod renovationPeriod); void DeleteRenovationPeriod(int roomNumber); void AddRenovationPeriod(RenovationPeriod renovationPeriod); } }
// File Prologue // Name: Darren Moody // Class: CS 1400 Section 005 // Project: Project 03 // Date: 9/29/2013 // // I declare that the following code was written by me or provided // by the instructor for this project. I understand that copying source // code from any other source constitutes cheating, and that I will receive // a zero on this project if I am found in violation of this policy. // --------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Project03 { public partial class Form1 : Form { // Declare constant variables: const double MILE_INCHES; const double MILE_INCHES = 63360; public Form1() { InitializeComponent(); } // The button1_Click method // Purpose: Calculate number of times a wheel must turn for the wagon to reach 1 mile // SEE COMMENTS INSIDE THE METHOD // Parameters: The object generating the event // and the event arguments // Returns: None private void button1_Click(object sender, EventArgs e) { // Declare variables to hold values: double wheelDiameter, wheelCircumference, numWheelTurns; // Parse diameter entered by user into double and store in wheelDiameter if (txtBoxDiam.Text != "") { wheelDiameter = double.Parse(txtBoxDiam.Text); // Calculate the circumference of the wheel and store it in wheelCircumference wheelCircumference = wheelDiameter * Math.PI; // Calculate the number of times the wheel must turn to reach 1 mile and store in numWheelTurns numWheelTurns = MILE_INCHES / wheelCircumference; // Output numWheelTurns to the answer text box string outStr = string.Format("{0:F2}", numWheelTurns); txtBoxTurns.Text = outStr; } } // The exitToolStripMenuItem_Click method // Purpose: To close the window and terminate the application // Parameters: The object generating the event // and the event arguments // Returns: None private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } // The aboutToolStripMenuItem_Click method // Purpose: To open a Message Box showing my information // Parameters: The object generating the event // and the event arguments // Returns: None private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("Darren Moody\nCS1400\nProject #3"); } // The btnClear_Click method // Purpose: To clear the text boxes of any information // Parameters: The object generating the event // and the event arguments // Returns: None private void btnClear_Click(object sender, EventArgs e) { txtBoxDiam.Text = ""; txtBoxTurns.Text = ""; txtBoxDiam.Focus(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class NPC : Actor { public NPCManager _statScreenManager; public Vector3 _target; [SerializeField] private GameObject _player; [SerializeField] private NavMeshAgent _agent; [SerializeField] private float _taskRange; public string _name; public Sprite _image; private int _trust; private int _fightingSkill; private int _farmingSkill; private int _gatheringSkill; private int _scavangingSkill; private int _maxSkill = 10; private int _minSkill = 0; private int _maxTrust = 100; private int _maxStartTrust = 50; private int _minTrust = 0; private bool _defending; private Interacteble _interacteble; void Start() { SetValues(); } void SetValues() { _fightingSkill = Random.Range(_minSkill, _maxSkill); _farmingSkill = Random.Range(_minSkill, _maxSkill); _gatheringSkill = Random.Range(_minSkill, _maxSkill); _scavangingSkill = Random.Range(_minSkill, _maxSkill); if (20 <= (_fightingSkill + _farmingSkill + _gatheringSkill + _scavangingSkill)) { _fightingSkill -= 3; _farmingSkill -= 3; _gatheringSkill -= 3; _scavangingSkill -= 3; } _fightingSkill = Mathf.Clamp(_fightingSkill, _minSkill, _maxSkill); _farmingSkill = Mathf.Clamp(_farmingSkill, _minSkill, _maxSkill); _gatheringSkill = Mathf.Clamp(_gatheringSkill, _minSkill, _maxSkill); _scavangingSkill = Mathf.Clamp(_scavangingSkill, _minSkill, _maxSkill); _trust = Random.Range(_minTrust, _maxStartTrust); ManagementMenu._managementMenu.NewNPC(this, _fightingSkill, _farmingSkill, _gatheringSkill, _scavangingSkill, _health, _trust); } void Update() { if (_agent == null) { return; } float distance = Vector3.Distance(transform.position, _target); if (_taskRange < distance) { _agent.SetDestination(_target); } else if (_interacteble != null && !_defending) { _interacteble.Action(this); } } public void SelectDefendPosition(Vector3 position) { _defending = true; _target = position; _agent.SetDestination(_target); } public void SelectJob(Interacteble interacteble) { _defending = false; _interacteble = interacteble; _target = interacteble.gameObject.transform.position; } }
using System; namespace _04._Baverage_labels { class Program { static void Main(string[] args) { string product = Console.ReadLine(); int volume = int.Parse(Console.ReadLine()); int energy = int.Parse(Console.ReadLine()); int sugar = int.Parse(Console.ReadLine()); double totalEnergy = (double)volume * energy / 100; double totalSugar = (double)volume * sugar / 100; Console.WriteLine($"{volume}ml {product}:"); Console.WriteLine($"{totalEnergy}kcal, {totalSugar}g sugars"); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using RestSharp; using service.Models; namespace service.Controllers.Interfacecore { public class InterfacecoreController : Controller { object result_function = ""; public IActionResult Index() { return View("~/Views/web001/Interfacecore/index.cshtml"); } //[Responsese(Location = ResponseCacheLocation.None, NoStore = true)] //[Proofpoint] public async Task<ActionResult> etl_swan_data(string v1, string v2,string token) { Logmodel log = new Logmodel(); log.swan_core_log("Debug_etl_swan", "data : " + v2.ToString()); try { var request_data = new Dictionary<string, string>(); request_data.Add("v1", v1); request_data.Add("v2", v2); Mysqlswan swandb = new Mysqlswan(); string Command = "swan_data"; Dictionary<object, object> param = new Dictionary<object, object>(); param.Add("@v1", v1); param.Add("@v2", v2); try { result_function = await swandb.data_with_col_procedures(Command, param); } catch(Exception e){ _ = log.interfacedata("Error data : " + e.ToString()); result_function = "nodata"; } return Content(JsonConvert.SerializeObject(result_function)); } catch(Exception e) { _ = log.interfacedata("Exception: " + e.ToString()); return Content("No Data"); } } //[Responsese(Location = ResponseCacheLocation.None, NoStore = true)] //[Proofpoint] public async Task<ActionResult> etl_swan_report(string v1, string v2, string token) { Logmodel log = new Logmodel(); var request_data = new Dictionary<string, string>(); request_data.Add("v1", v1); request_data.Add("v2", v2); Mysqlswan swandb = new Mysqlswan(); string Command = "swan_report"; Dictionary<object, object> param = new Dictionary<object, object>(); param.Add("@v1", v1); param.Add("@v2", v2); try { result_function = await swandb.data_with_col_procedures(Command, param); } catch (Exception e) { _ = log.interfacedata("Error data : " + e.ToString()); result_function = "nodata"; } return Content(JsonConvert.SerializeObject(result_function)); } //[Proofpoint] public async Task<ActionResult> etl_hawknet_data(string v1, string v2, string token) { Logmodel log = new Logmodel(); try { _ = log.swan_core_log("Debug_etl_hawk", "data : " + v2.ToString()); //var request_data = new Dictionary<string, string>(); //request_data.Add("v1", v1); //request_data.Add("v2", v2); Mysqlhawk hawkdb = new Mysqlhawk(); if (v1 == "list_customer_update") { string Command = "CALL Hawknet_data (@v1,@v2)"; Dictionary<object, object> param = new Dictionary<object, object>(); param.Add("v1", v1); param.Add("v2", v2); result_function = await hawkdb.data_with_col_api(Command, param); } else { string Command = "Hawknet_data"; Dictionary<object, object> param = new Dictionary<object, object>(); param.Add("@v1", v1); param.Add("@v2", v2); result_function = await hawkdb.data_with_col_procedures(Command, param); } _ = log.swan_core_log("Debug_etl_hawk", "return data : " + JsonConvert.SerializeObject(result_function)); } catch (Exception e) { _ = log.interfacedata("Error data : " + e.ToString()); result_function = "nodata"; } return Content(JsonConvert.SerializeObject(result_function)); } public async Task<ActionResult> etl_hawknet_data_maintenance(Customer_maintenance passdata) { Appconfig cfg = new Appconfig(); Logmodel log = new Logmodel(); var hawknet_data_maintenance = new Dictionary<object, object>(); try { _ = log.swan_core_log("Debug_etl_hawk", "data : " + passdata.v1.ToString()); var request_data = new Dictionary<string, string>(); request_data.Add("v1", passdata.v1); request_data.Add("v2", passdata.v2); request_data.Add("v3", passdata.v3); request_data.Add("v4", passdata.v4); request_data.Add("v5", passdata.v5); request_data.Add("v6", passdata.v6); request_data.Add("v7", passdata.v7); request_data.Add("v8", passdata.v8); request_data.Add("v9", passdata.v9); request_data.Add("v10", passdata.v10); request_data.Add("v11", passdata.v11); request_data.Add("v12", passdata.v12); request_data.Add("v13", passdata.v13); request_data.Add("v14", passdata.v14); request_data.Add("v15", passdata.v15); request_data.Add("v16", passdata.v16); request_data.Add("v17", passdata.v17); request_data.Add("v18", passdata.v18); request_data.Add("v19", passdata.v19); request_data.Add("v20", passdata.v20); request_data.Add("v21", passdata.v21); request_data.Add("v22", passdata.v22); request_data.Add("v23", passdata.v23); request_data.Add("v24", passdata.v24); request_data.Add("v25", passdata.v25); request_data.Add("v26", passdata.v26); request_data.Add("v27", passdata.v27); request_data.Add("v28", passdata.v28); request_data.Add("v29", passdata.v29); request_data.Add("v30", passdata.v30); request_data.Add("v31", passdata.v31); request_data.Add("v32", passdata.v32); request_data.Add("v33", passdata.v33); request_data.Add("v34", passdata.v34); request_data.Add("v35", passdata.v35); request_data.Add("v36", passdata.v36); request_data.Add("v37", passdata.v37); request_data.Add("v38", passdata.v38); request_data.Add("v39", passdata.v39); request_data.Add("v40", passdata.v40); hawknet_data_maintenance.Add("result", await HawknetData.Hawkdata_full_mysql(JsonConvert.SerializeObject(request_data))); _ = log.swan_core_log("Debug_etl_hawk", "result : " + JsonConvert.SerializeObject(hawknet_data_maintenance)); } catch (Exception e) { _ = log.swan_core_log("Debug_etl_hawk", "Error : " + e.ToString()); hawknet_data_maintenance.Add("result", "nodata"); } return Content(JsonConvert.SerializeObject(hawknet_data_maintenance)); } //[Proofpoint] public async Task<ActionResult> etl_hawknet_data_import(string v1, string v2, string token) { Logmodel log = new Logmodel(); var request_data = new Dictionary<string, string>(); request_data.Add("v1", v1); request_data.Add("v2", v2); Mysqlhawk hawkdb = new Mysqlhawk(); string Command = "Hawknet_data_import"; Dictionary<object, object> param = new Dictionary<object, object>(); param.Add("@v1", v1); param.Add("@v2", v2); try { result_function = await hawkdb.data_with_col_procedures(Command, param); } catch (Exception e) { _ = log.interfacedata("Error data : " + e.ToString()); result_function = "nodata"; } return Content(JsonConvert.SerializeObject(result_function)); } //[Proofpoint] public async Task<ActionResult> etl_hawknet_report(string v1, string v2, string token) { Logmodel log = new Logmodel(); var request_data = new Dictionary<string, string>(); request_data.Add("v1", v1); request_data.Add("v2", v2); // await Mysqlhawk hawkdb = new Mysqlhawk(); string Command = "Hawknet_report"; Dictionary<object, object> param = new Dictionary<object, object>(); param.Add("@v1", v1); param.Add("@v2", v2); try { result_function = await hawkdb.data_with_col_procedures(Command, param); } catch (Exception e) { _ = log.interfacedata("Error data : " + e.ToString()); result_function = "nodata"; } return Content(JsonConvert.SerializeObject(result_function)); } //[Proofpoint] public async Task<ActionResult> etl_tiger_data(string v1, string v2, string token) { Logmodel log = new Logmodel(); var request_data = new Dictionary<string, string>(); request_data.Add("v1", v1); request_data.Add("v2", v2); Mysqltiger tigerdb = new Mysqltiger(); string Command = "tiger_data"; Dictionary<object, object> param = new Dictionary<object, object>(); param.Add("@v1", v1); param.Add("@v2", v2); try { result_function = await tigerdb.data_with_col_procedures(Command, param); } catch (Exception e) { _ = log.interfacedata("Error data : " + e.ToString()); result_function = "nodata"; } return Content(JsonConvert.SerializeObject(result_function)); } // [Proofpoint] public async Task<ActionResult> etl_tiger_report(string v1, string v2, string token) { Logmodel log = new Logmodel(); var request_data = new Dictionary<string, string>(); request_data.Add("v1", v1); request_data.Add("v2", v2); Mysqltiger tigerdb = new Mysqltiger(); string Command = "tiger_data"; Dictionary<object, object> param = new Dictionary<object, object>(); param.Add("@v1", v1); param.Add("@v2", v2); try { result_function = await tigerdb.data_with_col_procedures(Command, param); } catch (Exception e) { _ = log.interfacedata("Error data : " + e.ToString()); result_function = "nodata"; } return Content(JsonConvert.SerializeObject(result_function)); } // [Proofpoint] public async Task<ActionResult> etl_wealth_data(string v1, string v2, string token) { Logmodel log = new Logmodel(); Mysqlwealth wealthdb = new Mysqlwealth(); string project_request = Appconfig.client_config("ite-000120190421", "wealth_project"); string Command = "EXEC wealth_data @1,@2"; Dictionary<string, string> param = new Dictionary<string, string>(); param.Add("1", v1); param.Add("2", v2); try { result_function = Core_mssql.data_with_col(project_request, Command, param); //result_function = await wealthdb.data_with_col_procedures(Command, param); } catch (Exception e) { _ = log.interfacedata("Error data : " + e.ToString()); result_function = "nodata"; } return Content(JsonConvert.SerializeObject(result_function)); } private static string projectsetting() { string path = Directory.GetCurrentDirectory(); string configtext = System.IO.File.ReadAllText(path + "/Data/Appsetting.json"); JObject config_parse = JObject.Parse(configtext); return config_parse["projectid"].ToString(); } private static string dbselect(string var_name) { string path = Directory.GetCurrentDirectory(); string configtext = System.IO.File.ReadAllText(path + "/Clients/Clients.json"); JObject config_parse = JObject.Parse(configtext); return config_parse[projectsetting()][var_name].ToString(); } //[Proofpoint] public async Task<ActionResult> etl_wealth_data_import(string v1, string v2, string token) { // for mssql Only EXEC Wealth_data_import 'sdddd' , ''; Logmodel log = new Logmodel(); //string project_request = Appconfig.client_config("ite-000120190421", "wealth_project"); //string Command = "EXEC Wealth_data_import @1,@2"; //Dictionary<string, string> param = new Dictionary<string, string>(); //param.Add("1", v1); //param.Add("2", v2); //try //{ // result_function = Core_mssql.data_with_col(project_request, Command, param); // //result_function = await wealthdb.data_with_col_procedures(Command, param); //} //catch (Exception e) //{ // _ = log.interfacedata("Error data : " + e.ToString()); // result_function = "nodata"; //} var db_select = dbselect("database"); if (db_select == "mssql") { string project_request = Appconfig.client_config("ite-000120190421", "wealth_project"); string Command = "EXEC Wealth_data_import @1,@2"; Dictionary<string, string> param = new Dictionary<string, string>(); param.Add("1", v1); param.Add("2", v2); try { result_function = Core_mssql.data_with_col(project_request, Command, param); //result_function = await wealthdb.data_with_col_procedures(Command, param); } catch (Exception e) { _ = log.swan_core_log("wealth_import","Error data : " + e.ToString()); result_function = "nodata"; } } else if (db_select == "mysql") { Mysqlwealth wealth = new Mysqlwealth(); string Command = "CALL Wealth_data_import (@1,@2)"; Dictionary<object, object> param = new Dictionary<object, object>(); param.Add("1", v1); param.Add("2", v2); _ = log.swan_core_log("wealth_import", "variable1 : " + v1); _ = log.swan_core_log("wealth_import", "variable2 : " + v2); result_function = await wealth.data_with_col_api(Command, param); _ = log.swan_core_log("wealth_import", "date _return : " + JsonConvert.SerializeObject(result_function)); } return Content(JsonConvert.SerializeObject(result_function)); } [Proofpoint] public async Task<ActionResult> etl_wealth_report(string v1, string v2, string token) { Logmodel log = new Logmodel(); string project_request = Appconfig.client_config("ite-000120190421", "wealth_project"); string Command = "EXEC wealth_data_report @1,@2"; Dictionary<string, string> param = new Dictionary<string, string>(); param.Add("@v1", v1); param.Add("@v2", v2); try { result_function = Core_mssql.data_with_col(project_request, Command, param); //result_function = await wealthdb.data_with_col_procedures(Command, param); } catch (Exception e) { _ = log.interfacedata("Error data : " + e.ToString()); result_function = "nodata"; } return Content(JsonConvert.SerializeObject(result_function)); } [Proofpoint] public async Task<ActionResult> etl_seal_data(string v1, string v2) { Logmodel log = new Logmodel(); var request_data = new Dictionary<string, string>(); request_data.Add("v1", v1); request_data.Add("v2", v2); Mysqlseal sealdb = new Mysqlseal(); string Command = "Seal_data"; Dictionary<object, object> param = new Dictionary<object, object>(); param.Add("@v1", v1); param.Add("@v2", v2); try { result_function = await sealdb.data_with_col_procedures(Command, param); } catch (Exception e) { _= log.interfacedata("Error data : " + e.ToString()); result_function = "nodata"; } return Json(result_function); } [Proofpoint] public async Task<ActionResult> etl_seal_report(string v1, string v2) { Logmodel log = new Logmodel(); var request_data = new Dictionary<string, string>(); request_data.Add("v1", v1); request_data.Add("v2", v2); Mysqlseal sealdb = new Mysqlseal(); string Command = "Seal_report"; Dictionary<object, object> param = new Dictionary<object, object>(); param.Add("@v1", v1); param.Add("@v2", v2); try { result_function = await sealdb.data_with_col_procedures(Command, param); } catch (Exception e) { _ = log.interfacedata("Error data : " + e.ToString()); result_function = "nodata"; } return Json(result_function); } [Proofpoint] public async Task<ActionResult> etl_bos_data(string v1, string v2) { Logmodel log = new Logmodel(); var request_data = new Dictionary<string, string>(); request_data.Add("v1", v1); request_data.Add("v2", v2); Mysqlbos bosdb = new Mysqlbos(); string Command = "Bos_data"; Dictionary<object, object> param = new Dictionary<object, object>(); param.Add("@v1", v1); param.Add("@v2", v2); try { result_function = await bosdb.data_with_col_procedures(Command, param); } catch (Exception e) { _ = log.interfacedata("Error data : " + e.ToString()); result_function = "nodata"; } return Json(result_function); } [Proofpoint] public async Task<ActionResult> etl_bos_report(string v1, string v2) { Logmodel log = new Logmodel(); var request_data = new Dictionary<string, string>(); request_data.Add("v1", v1); request_data.Add("v2", v2); Mysqlbos bosdb = new Mysqlbos(); string Command = "Bos_report"; Dictionary<object, object> param = new Dictionary<object, object>(); param.Add("@v1", v1); param.Add("@v2", v2); try { result_function = await bosdb.data_with_col_procedures(Command, param); } catch (Exception e) { _ = log.interfacedata("Error data : " + e.ToString()); result_function = "nodata"; } return Json(result_function); } } }
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("AzureFunctions.Contrib.SignalR.Test")]
using UnityEngine; using UnityEngine.EventSystems; public class Queue : MonoBehaviour { [SerializeField] private Tip tip; [SerializeField] private DragDetector dragDetector; /// <summary> /// dragに対してキューの移動速度を制御するための係数 /// </summary> readonly private float speedCofficient = 1f; private int shotBallLayer; private Vector3 startPosition; private bool active; private int pointerId; public Vector3 StartPosition { get { return startPosition; } } public SphereCollider Collider { get { return tip.TipCollider; } } public Vector3 QueueVelocity { get; private set; } /// <summary> /// tipとボールがぶつかったときに呼ばれるメソッド /// </summary> /// <param name="other"></param> public void OnContact(Collision other) { if (other.gameObject.layer == shotBallLayer) { tip.gameObject.SetActive(false); } } public void SetActive(bool isActive) { active = isActive; } void Awake() { // コンストラクタのタイミングでは使えないので、Startのタイミングで値を取る shotBallLayer = LayerMask.NameToLayer("ShotBall"); tip.OnContact += OnContact; dragDetector.OnInitializePotentialDragCallback += OnInitializePotentialDragCallback; dragDetector.OnBeginDragCallback += OnBeginDrag; dragDetector.OnDragCallback += OnDrag; dragDetector.OnEndDragCallback += OnEndDrag; startPosition = transform.position; } void OnInitializePotentialDragCallback(PointerEventData eventData) { if (!active) { return; } startPosition = transform.position; QueueVelocity = Vector3.zero; pointerId = eventData.pointerId; } void OnBeginDrag(PointerEventData eventData) { if (!ValidateInput(eventData)) { return; } } void OnDrag(PointerEventData eventData) { if (!ValidateInput(eventData)) { return; } // Dragにより次のキューの位置 var nextQueuePosition = tip.TipRigidbody.position + tip.transform.forward * eventData.delta.y * Time.deltaTime * speedCofficient; transform.position = nextQueuePosition; QueueVelocity = transform.forward * eventData.delta.magnitude * Time.deltaTime; } void OnEndDrag(PointerEventData eventData) { if (!ValidateInput(eventData)) { return; } tip.TipRigidbody.velocity = Vector3.zero; tip.TipRigidbody.angularVelocity = Vector3.zero; } bool ValidateInput(PointerEventData eventData) { if (active && pointerId == eventData.pointerId) { return true; } return false; } }
using NewsProject.Client.Helpers; using NewsProject.Shared.DataTransferObjects; using NewsProject.Shared.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NewsProject.Client.Repository { public class NewsRepository : INewsRepository { private readonly IHttpService _httpService; private string url = "api/news"; public NewsRepository(IHttpService httpService) { _httpService = httpService; } public async Task<int> Create(News item) { var response = await _httpService.Post<News, int>(url, item); if (!response.Success) { throw new ApplicationException(await response.GetBody()); } return response.Response; } public async Task<DetailsNewsDTO> GetDetailsNewsDTO(int id) //this action needing for gettind object details. { return await _httpService.GetHelper<DetailsNewsDTO>($"{url}/{id}", includeToken: false); } public async Task<List<News>> GetNewses() { var response = await _httpService.Get<List<News>>(url); if (!response.Success) { throw new ApplicationException(await response.GetBody()); } return response.Response; } public async Task<PaginatedResponse<List<News>>> GetNewsForPagination(PaginationDTO paginationDTO)//PaginatedResponse locating in BlazorProject.Shared/DataTransferObjects/PaginatedResponse { return await _httpService.GetHelper<List<News>>(url, paginationDTO, includeToken: false); } public async Task<PaginatedResponse<List<News>>> GetNewsesFiltered(FilterNewsDTO filterNewsDTO) { var responseHTTP = await _httpService.Post<FilterNewsDTO, List<News>>($"{url}/filter", filterNewsDTO, includeToken: false); var totalAmountPages = int.Parse(responseHTTP.HttpResponseMessage.Headers.GetValues("totalAmountPages").FirstOrDefault()); var paginatedResponse = new PaginatedResponse<List<News>>() { Response = responseHTTP.Response, TotalAmountPages = totalAmountPages }; return paginatedResponse; } //This method need for getting data and update theme in DB public async Task<NewsUpdateDTO> GetNewsForUpdate(int id) { return await _httpService.GetHelper<NewsUpdateDTO>($"{url}/update/{id}"); } public async Task UpdateNews(News model) { var response = await _httpService.Put(url, model); if (!response.Success) { throw new ApplicationException(await response.GetBody()); } } public async Task DeleteNews(int id) { var response = await _httpService.Delete($"{url}/{id}"); if (!response.Success) { throw new ApplicationException(await response.GetBody()); } } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using MultiUserBlock.Common.Enums; namespace MultiUserBlock.DB { public class Role { public int RoleId { get; set; } public UserRoleType UserRoleType { get; set; } public virtual ICollection<RoleToUser> RoleToUsers { get; set; } } }
using System.Collections.Generic; namespace SOLIDPrinciples.ISP.Example1.Good { public interface ITributavel { List<Item> ItensASeremTributados(); } }
using UnityEngine; using System.Collections; public class Fuel : MonoBehaviour { public float reactivateTime; PlayerStates playerState; void OnTriggerEnter2D(Collider2D col){ if (col.tag == "Player") { Refill(col.gameObject); } } void Refill(GameObject col) { playerState=col.GetComponent<PlayerStates>(); if (playerState.FuelInJetpack <= 0) { playerState.FuelInJetpack = playerState.FuelInJetpackMax; HideObject(); Invoke("UnhideObject", reactivateTime); } } //SWITCHING OBJECT OFF AND AFTER TIMEOUT ON AGAIN void HideObject(){ gameObject.GetComponent<Renderer> ().enabled=false; gameObject.GetComponent<Collider2D>().enabled=false; } void UnhideObject(){ gameObject.GetComponent<Renderer> ().enabled=true; gameObject.GetComponent<Collider2D>().enabled=true; } }
using System.Web.Mvc; using DevExpress.Web.Mvc; namespace DevExpress.Web.Demos { public partial class HtmlEditorController : DemoController { public ActionResult CustomCss() { return DemoView("CustomCss"); } public ActionResult CustomCssPartial() { return PartialView("CustomCssPartial"); } public ActionResult CustomCssImageUpload() { HtmlEditorExtension.SaveUploadedImage("heCustomCss", HtmlEditorDemosHelper.ImageUploadValidationSettings, HtmlEditorDemosHelper.UploadDirectory); return null; } } }
using System; using System.Linq; using Tomelt.ContentManagement.MetaData; using Tomelt.Core.Common.Models; using Tomelt.Core.Contents.Extensions; using Tomelt.Data; using Tomelt.Data.Migration; namespace Tomelt.Core.Common { public class Migrations : DataMigrationImpl { private readonly IRepository<IdentityPartRecord> _identityPartRepository; public Migrations(IRepository<IdentityPartRecord> identityPartRepository) { _identityPartRepository = identityPartRepository; } public int Create() { SchemaBuilder.CreateTable("BodyPartRecord", table => table .ContentPartVersionRecord() .Column<string>("Text", column => column.Unlimited()) .Column<string>("Format") ); SchemaBuilder.CreateTable("CommonPartRecord", table => table .ContentPartRecord() .Column<int>("OwnerId") .Column<DateTime>("CreatedUtc") .Column<DateTime>("PublishedUtc") .Column<DateTime>("ModifiedUtc") .Column<int>("Container_id") ); SchemaBuilder.CreateTable("CommonPartVersionRecord", table => table .ContentPartVersionRecord() .Column<DateTime>("CreatedUtc") .Column<DateTime>("PublishedUtc") .Column<DateTime>("ModifiedUtc") .Column<string>("ModifiedBy") ); SchemaBuilder.CreateTable("IdentityPartRecord", table => table .ContentPartRecord() .Column<string>("Identifier", column => column.WithLength(255)) ); ContentDefinitionManager.AlterPartDefinition("BodyPart", builder => builder .Attachable() .WithDescription("允许编辑器可用适用富文本编辑器(如:HTML,TEXT,MarkDown)")); ContentDefinitionManager.AlterPartDefinition("CommonPart", builder => builder .Attachable() .WithDescription("提供有关内容项的公共信息,如所有者、创建日期、发布日期和日期修改")); ContentDefinitionManager.AlterPartDefinition("IdentityPart", builder => builder .Attachable() .WithDescription("自动为内容项生成唯一标识,在导入/导出场景中,其中一个内容项引用另一个内容。")); return 5; } public int UpdateFrom1() { SchemaBuilder.CreateTable("IdentityPartRecord", table => table .ContentPartRecord() .Column<string>("Identifier", column => column.Unlimited()) ); ContentDefinitionManager.AlterPartDefinition("IdentityPart", builder => builder.Attachable()); return 2; } public int UpdateFrom2() { ContentDefinitionManager.AlterPartDefinition("BodyPart", builder => builder .WithDescription("允许编辑器可用适用富文本编辑器(如:HTML,TEXT,MarkDown)")); ContentDefinitionManager.AlterPartDefinition("CommonPart", builder => builder .WithDescription("提供有关内容项的公共信息,如所有者、创建日期、发布日期和日期修改")); ContentDefinitionManager.AlterPartDefinition("IdentityPart", builder => builder .WithDescription("自动为内容项生成唯一标识,在导入/导出场景中,其中一个内容项引用另一个内容。")); return 3; } public int UpdateFrom3() { var existingIdentityParts = _identityPartRepository.Table.ToArray(); foreach (var existingIdentityPart in existingIdentityParts) { if (existingIdentityPart.Identifier.Length > 255) { throw new ArgumentException("Identifier '" + existingIdentityPart + "' is over 255 characters"); } } SchemaBuilder.AlterTable("IdentityPartRecord", table => table.DropColumn("Identifier")); SchemaBuilder.AlterTable("IdentityPartRecord", table => table.AddColumn<string>("Identifier", command => command.WithLength(255))); foreach (var existingIdentityPart in existingIdentityParts) { var updateIdentityPartRecord = _identityPartRepository.Get(existingIdentityPart.Id); updateIdentityPartRecord.Identifier = existingIdentityPart.Identifier; _identityPartRepository.Update(updateIdentityPartRecord); } return 4; } public int UpdateFrom4() { SchemaBuilder.AlterTable("CommonPartVersionRecord", table => table.AddColumn<string>("ModifiedBy", command => command.Nullable())); return 5; } } }