text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using Model.Models; using Data.Models; using Data.Infrastructure; using Service; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Presentation; namespace Web.Controllers { [Authorize] public class PersonAddressController : System.Web.Mvc.Controller { private ApplicationDbContext context = new ApplicationDbContext(); IPersonAddressService _personAddressService; IUnitOfWork _unitOfWork; public PersonAddressController(IPersonAddressService personAddress, IUnitOfWork unitOfWork) { _personAddressService = personAddress; _unitOfWork = unitOfWork; } [Authorize] public ActionResult Index() { //PrepareViewBag(); var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var supplierloginUserid = UserManager.FindByName(User.Identity.Name).Id; var supplier = new PersonService(_unitOfWork).GetSupplierByLoginId(supplierloginUserid); var personAddress = _personAddressService.GetPersonAddressList(supplier.PersonID); ViewBag.PersonId = supplier.PersonID; return View(personAddress); } private void PrepareViewBag(int id) { var person = context.Persons.Where(m => m.PersonID == id).FirstOrDefault(); ViewBag.personId = person.PersonID; ViewBag.personName = person.Name; var personList = new PersonService(_unitOfWork).GetPersonList().OfType<Employee>().ToList(); ViewBag.PersonList = personList; List<SelectListItem> AddressTypes = new List<SelectListItem>(); AddressTypes.Add(new SelectListItem { Text = "Office", Value = "O" }); AddressTypes.Add(new SelectListItem { Text = "Factory", Value = "F" }); AddressTypes.Add(new SelectListItem { Text = "Residence", Value = "R" }); AddressTypes.Add(new SelectListItem { Text = "Warehouse", Value = "W" }); ViewBag.AddressType = new SelectList(AddressTypes, "Value", "Text"); ViewBag.CountryList = new SelectList(new CountryService(_unitOfWork).GetCountryList().ToList(),"CountryId","CountryName"); ViewBag.StateList = new SelectList(new StateService(_unitOfWork).GetStateList().ToList(), "StateId", "StateName"); ViewBag.CityList = new SelectList(new CityService(_unitOfWork).GetCityList().ToList(), "CityId", "CityName"); } public JsonResult GetStatesJson(int CountryId) { return Json(new StateService(_unitOfWork).GetStateListForCountryType(CountryId).ToList()); } public JsonResult GetCityJson(int StateId) { return Json(new CityService(_unitOfWork).GetCityListForStateType(StateId)); } private void PrepareViewBag() { var personList = new PersonService(_unitOfWork).GetPersonList().OfType<Employee>().ToList(); ViewBag.PersonList = personList; } //public ActionResult Create() //{ // PrepareViewBag(); // return View(); //} public ActionResult Create(int personID) { PersonAddress pa = new PersonAddress(); pa.PersonId = personID; PrepareViewBag(personID); return View(pa); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(PersonAddress pa) { var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var loginid= UserManager.FindByName(User.Identity.Name).Id; var supplierByLoginId = new PersonService(_unitOfWork).GetSupplierByLoginId(loginid); if (ModelState.IsValid) { pa.Person = new PersonService(_unitOfWork).GetPerson(supplierByLoginId.PersonID); pa.CreatedDate = DateTime.Now; pa.ModifiedDate = DateTime.Now; pa.CreatedBy = User.Identity.Name; pa.ModifiedBy = User.Identity.Name; pa.ObjectState = Model.ObjectState.Added; _personAddressService.Create(pa); _unitOfWork.Save(); // return RedirectToAction("Index"); return RedirectToAction("Index", "ProductSample").Success("Data saved successfully"); } PrepareViewBag(pa.PersonId); return View(pa); } // GET: /BuyerDetail/Edit/5 public ActionResult Edit(int id) { PrepareViewBag(id); PersonAddress pa = _personAddressService.GetPersonAddress(id); if (pa == null) { return HttpNotFound(); } return View(pa); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(PersonAddress pa) { var persn = new PersonService(_unitOfWork).GetPerson(pa.PersonId); ; pa.Person = persn; if (ModelState.IsValid) { pa.CreatedDate = DateTime.Now; pa.ModifiedDate = DateTime.Now; pa.CreatedBy = User.Identity.Name; pa.ModifiedBy = User.Identity.Name; pa.ObjectState = Model.ObjectState.Modified; _personAddressService.Update(pa); _unitOfWork.Save(); return RedirectToAction("Index").Success("Data saved successfully"); } PrepareViewBag(); return View(pa); } /* */ protected override void Dispose(bool disposing) { if (disposing) { context.Dispose(); } base.Dispose(disposing); } } }
using PatientService.Model.Specification; using System; namespace PatientService.Model.TherapySpecification { public class TherapyStartDateSpecification : CompositeSpecification<Therapy> { private DateTime? _startDate; public TherapyStartDateSpecification(DateTime? startDate) { _startDate = startDate; } public override bool IsSatisfiedBy(Therapy o) { if (_startDate is null) return true; return DateTime.Compare(o.DateRange.StartDate, (DateTime)_startDate) >= 0; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Docller.Core.Common; using Docller.Core.Common.DataStructures; using Docller.Core.Models; using Docller.Core.Repository.Collections; using Docller.Core.Storage; using File = Docller.Core.Models.File; namespace Docller.Core.Services { public interface IStorageService { FolderCreationStatus CreateFolders(string userName, long projectId, List<Folder> folders); FolderCreationStatus CreateFolders(string userName, long projectId, long parentFolder, List<Folder> folders); Folders GetFolders(string userName, long projectId); StorageServiceStatus RenameFolder(Folder folder); IEnumerable<File> GetPreUploadInfo(long projectId, long folderId, string[] fileNames, bool attachCADFilesToPdfs, bool patternMatchForVersions); StorageServiceStatus AddFile(File file, bool addAsNewVersion, string versionPath); StorageServiceStatus AddAttachment(FileAttachment attachment, bool addAsNewVersion, string versionPath); StorageServiceStatus Upload<T>(T file,Stream data, int chunk, int totalChunks, bool addAsNewVersion) where T : BlobBase, new(); IEnumerable<File> GetFilesForEdit(List<File> filesToEdit); IEnumerable<File> GetFiles(List<Guid> fileInternNames); StorageServiceStatus TryUpdateFiles(List<File> filesToUpdate, out IEnumerable<File> filesNotUpdated); Files GetFiles(long projectId, long folderId, string userName, FileSortBy sortBy, SortDirection sortDirection, int pageNumber, int pageSize); StorageServiceStatus DownloadToStream(Stream target, BlobBase file, IClientConnection clientConnection); FileHistory GetFileHistory(long fileId); FileAttachment GetFileAttachment(long fileId); void DeleteAttachment(FileAttachment fileAttachment); FileAttachment DeleteAttachment(FileAttachmentVersion fileAttachmentVersion); bool DeleteFiles(long[] fileIds, long projectId); FileHistory DeleteFileVersion(long fileId, int revisionNumber); StorageServiceStatus UploadAttachment(FileAttachment fileAttachment, Stream data, int chunk, int totalChunks); StorageServiceStatus UploadVersion(long fileId, long folderId, long projectId, string fileName, decimal fileSize, Stream data, int chunk, int totalChunks); StorageServiceStatus UploadComment(long projectId, long folderId, long fileId, string fileName, decimal fileSize, Stream data, int chunk, int totalChunks, string comments, bool isFromApp, string appDetails); MarkUpFile GetMarkUpMetadataInfo(string markupFileName, long fileId, long folderId, long projectId); } }
 using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; public class APIController : MonoBehaviour { [SerializeField] string MAIN_URL = "https://games.kintoncloud.com/numbers"; public NumbersCollection NumbersCol { get; private set; } private void Awake() { StartCoroutine(GetRequest(MAIN_URL)); } private void Start() { } private void Update() { } IEnumerator GetRequest(string uri) { using (UnityWebRequest webRequest = UnityWebRequest.Get(uri)) { // Request and wait for the desired page. yield return webRequest.SendWebRequest(); string[] pages = uri.Split('/'); int page = pages.Length - 1; if (webRequest.isNetworkError) { Console.Log(pages[page] + ": Error: " + webRequest.error); } else { Console.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text); NumbersCol = JsonUtility.FromJson<NumbersCollection>(webRequest.downloadHandler.text); Console.Log("Length numbers received: "+ NumbersCol.numbers.Length); } } } public APINumbers GetRandomNumber() { int l = NumbersCol.numbers.Length; return NumbersCol.numbers[Random.Range(0, l)]; } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Security; using System.Text; using System.Threading.Tasks; namespace WAPWrapper { /// <summary> /// A class to instantiate WAP Admin context to perform WAP Admin functions /// </summary> public class WAPAdminService : WAPBaseService { private static string AdminUsername { get; set; } private static string AdminPassword { get; set; } private static string ADAuthEndpoint { get; set; } private static string ASPAuthEndpoint {get; set;} private static string ADFSAuthEndpoint { get; set; } private static string AdminEndpoint { get; set; } public string AdminHeaderValue { get; set; } /// <summary> /// Constructor for WAPAdminContext /// </summary> public WAPAdminService() : base() { } /// <summary> /// Sets WAP Admin Context for Endpoint and Admin user credentials /// </summary> /// <param name="adminEndpoint"></param> /// <param name="adminUserName"></param> /// <param name="adminHeaderValue"></param> public void SetWAPEndpoint(string adminEndpoint, string adminUserName, string adminHeaderValue) { AdminUsername = adminUserName; AdminEndpoint = adminEndpoint; AdminHeaderValue = adminHeaderValue; } /// <summary> /// Method to set the httpClient for WAP Admin operations /// </summary> public void WAPServiceHttpClient(bool acceptJSON = true) { httpClient = new HttpClient(); if (acceptJSON) { mediaType = JSONMediaType; } else { mediaType = XMLMediaType; } httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(mediaType)); string WAPURL = string.Format("{0}/", AdminEndpoint); httpClient.BaseAddress = new UriBuilder(WAPURL).Uri; httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AdminHeaderValue); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Epic.Training.Project.Inventory.Text; using Epic.Training.Project.Inventory.Text.Formatting; using Epic.Training.Project.Inventory.Text.UserInput; using Epic.Training.Project.Inventory.Text.Exceptions; using Epic.Training.Project.Inventory.Text.Persistence; namespace Epic.Training.Project.Inventory.Text.Menus { class TextMenu { #region MENU FUNCTIONS - MainMenu;InventoryMenu;CreateItem;EditItem;RemoveItem;DisplayInventory /// <summary> /// First Menu in the UI. Options - Load inventory from file; New inventory; Quit /// </summary> internal static void MainMenu() { while (true) { Console.Clear(); Format.Version(); Console.WriteLine("{0}\n", Resource1.MAIN_MENU_TITLE); Console.WriteLine("<<{0}>>", Resource1.SELECT_OPTIONS); Console.WriteLine("[1]Load inventory from file"); Console.WriteLine("[2]New Inventory"); Console.WriteLine("[3]Quit"); Format.Separator(); switch (Console.ReadKey(true).KeyChar) { case '1': Inventory inv; string filepath = null; try { inv = Persist.LoadInventory(out filepath); InventoryMenu(inv, filepath); } catch (Exception ex) { if (ex is EscapeKeyPressedException) { throw ex; //Mostly here for testing to make sure stray Escape exceptions arent bubbling up } Console.WriteLine("[! Problem loading inventory: {0} !]", ex.Message); wait(2000); } break; case '2': InventoryMenu(new Inventory()); break; case '3': return; default: Console.WriteLine("\n[! {0} !]", Resource1.INVALID_SEL); wait(2000); break; } } } /// <summary> /// Menu that contains options to manipulate the currently loaded inventory. /// </summary> /// <param name="inventory">Currently loaded inventory passed in from MainMenu()</param> private static void InventoryMenu(Inventory inventory, string filepath = null) { while (true) { Console.Clear(); Format.Version(); if (filepath != null) { Console.WriteLine("{0} - Loaded from {1}\n", Resource1.INV_MENU_TITLE, filepath); } else { Console.WriteLine("{0} - New Inventory\n", Resource1.INV_MENU_TITLE); } Console.WriteLine("<<{0}>>", Resource1.SELECT_OPTIONS); Console.WriteLine("[1]View Inventory State"); Console.WriteLine("[2]Create New Item(s)"); Console.WriteLine("[3]Edit Item(s)"); Console.WriteLine("[4]Save Inventory"); Console.WriteLine("[5]Return to Main Menu"); Format.Separator(); switch (Console.ReadKey(true).KeyChar) { case '1': InventoryState(inventory); break; case '2': CreateItem(inventory); break; case '3': EditItem(inventory); break; case '4': try { Persist.SaveInventory(inventory, ref filepath); } catch (Exception ex) { Console.WriteLine("[! Problem saving inventory: {0} !]", ex.Message); wait(2000); } break; case '5': return; default: Console.WriteLine("\n[! {0} !]", Resource1.INVALID_SEL); wait(2000); break; } } } /// <summary> /// Menu for creating Items to be stored in the currently loaded inventory. /// </summary> /// <param name="inv">Currently loaded inventory.</param> private static void CreateItem(Inventory inv) { while (true) { Console.Clear(); Format.Version(); Console.WriteLine("{0}\n", Resource1.CREATE_ITEM); Console.WriteLine("<<{0}>>\n", Resource1.ESC_PROMPT); bool repeat = true; int numOption = 0; //Keeps track of what the next prompt should be (0=Name, 1=Quantity, 2=Wholesale, 3=Weight) Item itemStage = new Item("", 1, 1, 1m); while (repeat) { switch (numOption) { case 0: //Name try { itemStage.Name = Input.GetNameFromUser(inv); numOption += 1; } catch (EscapeKeyPressedException ex) { return; } break; case 1: //Quantity try { itemStage.QuantityOnHand = Input.GetQuantityFromUser(itemStage); numOption += 1; } catch (EscapeKeyPressedException ex) { Console.WriteLine(); numOption -= 1; } break; case 2: //Wholesale try { itemStage.WholesalePrice = Input.GetWholesaleFromUser(itemStage); numOption += 1; } catch (EscapeKeyPressedException ex) { Console.WriteLine(); numOption -= 1; } break; case 3: //Weight try { itemStage.Weight = Input.GetWeightFromUser(itemStage); repeat = false; } catch (EscapeKeyPressedException ex) { Console.WriteLine(); numOption -= 1; } break; } } Console.WriteLine(); Format.TableHeader(); Format.DisplayRow(itemStage, 0); Console.WriteLine("\n<<[ENTER] to add Item '{0}' to the inventory - any other key to discard it>>\n", itemStage.Name); if (Console.ReadKey().Key == ConsoleKey.Enter) { inv.Add(itemStage); Console.WriteLine("\n['{0}' added to Inventory]", itemStage.Name); } else { Console.WriteLine("\n[Discarding staged Item]"); } wait(2000); } } /// <summary> /// Menu for editing pre-existing Items in the currently loaded inventory. /// </summary> /// <param name="inv">Currently loaded inventory.</param> private static void EditItem(Inventory inv) { bool continueEditingCurrent = false; //Whether or not to continue editing currently selected Item while (true) { Console.Clear(); Format.Version(); Console.WriteLine("{0}\n", Resource1.EDIT_ITEM); #region CHECK INVENTORY IS NOT EMPTY; DISPLAY ITEMS if (inv.TotalProducts < 1) { Console.WriteLine("[! There are no items in this Inventory yet. Returning to Inventory Menu !]"); wait(2000); return; } Format.DisplayInventory(inv, SortOption.ByName); Console.WriteLine("\n<<{0}>>\n", Resource1.ESC_PROMPT); #endregion #region CHECK IF USER CHOSEN ITEM EXISTS; INSTANTIATE ITEMSTAGE Item itemStage = null; string itemName; do { try { itemName = Input.betterInput("\n<<Enter the name of the Item you wish to edit>> "); if (inv.Contains(itemName)) { itemStage = inv[itemName]; continueEditingCurrent = true; } else { Console.WriteLine("\n[! No Item with name '{0}' exists in this inventory !]", itemName); } } catch (EscapeKeyPressedException ex) { return; } } while (itemStage == null); #endregion while (continueEditingCurrent) { Console.Clear(); Console.WriteLine("\n<<{0}>>\n", Resource1.ESC_PROMPT); Format.TableHeader(); Format.DisplayRow(itemStage, 0); Console.WriteLine("\n<<Item '{0}' found. Select which property to edit>>", itemStage.Name); Console.WriteLine("[1]Name"); Console.WriteLine("[2]Quantity On Hand"); Console.WriteLine("[3]Wholesale Price (USD)"); Console.WriteLine("[4]Weight (LBS)"); Console.WriteLine("[5]Remove Item from Inventory"); Console.WriteLine("[6]Select another Item"); Console.WriteLine("[7]Return to Inventory Menu"); Format.Separator(); switch (Console.ReadKey(true).KeyChar) { case '1': try { itemStage.Name = Input.GetNameFromUser(inv); } catch (EscapeKeyPressedException ex) { Console.WriteLine(); } break; case '2': try { itemStage.QuantityOnHand = Input.GetQuantityFromUser(itemStage); } catch (Exception) { Console.WriteLine(); } break; case '3': try { itemStage.WholesalePrice = Input.GetWholesaleFromUser(itemStage); } catch (Exception) { Console.WriteLine(); } break; case '4': try { itemStage.Weight = Input.GetWeightFromUser(itemStage); } catch (Exception) { Console.WriteLine(); } break; case '5': Console.WriteLine("<<[ENTER] to confirm Item removal or any other key to abort>>"); if (Console.ReadKey().Key == ConsoleKey.Enter) { inv.Remove(itemStage); Console.WriteLine("\n[Item '{0}' has been removed from Inventory]\n", itemStage.Name); continueEditingCurrent = false; } break; case '6': continueEditingCurrent = false; break; case '7': return; default: Console.WriteLine("[! {0} !]\n", Resource1.INVALID_SEL); wait(2000); continue; } } } } /// <summary> /// Menu for displaying inventory statistics of the currently loaded inventory, including its Item members. /// </summary> /// <param name="inv">Currently loaded inventory.</param> private static void InventoryState(Inventory inv) { Console.Clear(); Format.InventoryStatistics(inv); while (true) { Console.WriteLine("\n<<Select a sorted view for the Inventory>>\n"); Console.WriteLine("[1]Sort Items alphabetically by name"); Console.WriteLine("[2]Sort Items by order entered into Inventory"); //Console.WriteLine("[3]Display Inventory Statistics"); Console.WriteLine("[3]Return to Inventory Menu"); Format.Separator(); switch (Console.ReadKey(true).KeyChar) { case '1': Console.Clear(); Format.InventoryStatistics(inv); Format.DisplayInventory(inv, SortOption.ByName); break; case '2': Console.Clear(); Format.InventoryStatistics(inv); Format.DisplayInventory(inv, SortOption.ByAdded); break; case '3': return; default: Console.WriteLine("\n[! {0} !]", Resource1.INVALID_SEL); wait(2000); Console.Clear(); Format.InventoryStatistics(inv); break; } } } private static void wait(int milliseconds) { System.Threading.Thread.Sleep(milliseconds); } #endregion } }
using System; using System.Collections.Generic; namespace Generic.Data.Models { public partial class TblPurchaseOrderDetails { public int PodetId { get; set; } public int PoId { get; set; } public string Decsription { get; set; } public int Quantity { get; set; } public decimal Rate { get; set; } public decimal Amount { get; set; } public decimal Total { get; set; } public string PaymentTerms { get; set; } public string DeliveryTerms { get; set; } public string DeliveryAddress { get; set; } public virtual TblPurchaseOrder Po { get; set; } } }
using System.Data; using Visitors.entity; namespace Visitors.DAO { interface RoleMasterDAO { void insertRole(RoleMaster roleMasterRef); void updaterole(RoleMaster roleMasterRef); void deleteRole(RoleMaster roleMasterRef); RoleMaster findbyprimaryKey(string roleName); // List<ArrayList> getRoleList(); DataTable selectAll(); } }
using FBS.Domain.Booking.Aggregates; using FBS.Domain.Core; using System; using System.Collections.Generic; using System.Text; namespace FBS.Domain.Booking.Events { public class FlightReleasedEvent : DomainEventBase<FlightAggregate> { public FlightReleasedEvent() { } public FlightReleasedEvent(Guid aggregateId) : base(aggregateId) { } public Seat[] Seats { get; set; } public Location From { get; set; } public Location To { get; set; } public DateTime Date { get; set; } public TimeSpan Duration { get; set; } public string Gate { get; set; } public string Number { get; set; } public string PlaneModel { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.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; namespace AndroidAirHockey { /// <summary> /// This is a game component that implements IUpdateable. /// </summary> public class MainMenuScreen : Microsoft.Xna.Framework.GameComponent { Rectangle singlePlayerButton = new Rectangle(0, 200, 420, 55); Rectangle exitButton = new Rectangle(345, 460, 130, 55); SpriteBatch spriteBatch; Texture2D textureMainMenu; Vector2 mainMenuPosition = Vector2.Zero; public MainMenuScreen(Game game) : base(game) { // TODO: Construct any child components here Initialize(); } /// <summary> /// Allows the game component to perform any initialization it needs to before starting /// to run. This is where it can query for any required services and load content. /// </summary> public override void Initialize() { // TODO: Add your initialization code here spriteBatch = new SpriteBatch(Game.GraphicsDevice); textureMainMenu = Game.Content.Load<Texture2D>("MainMenuMed"); base.Initialize(); } /// <summary> /// Allows the game component to update itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Update(GameTime gameTime) { // TODO: Add your update code here base.Update(gameTime); } public void DrawMainMenu() { spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend); spriteBatch.Draw(textureMainMenu, mainMenuPosition, Color.White); spriteBatch.End(); } public Rectangle SinglePlayerButton { get { return singlePlayerButton; } } public Rectangle ExitButton { get { return exitButton; } } } }
using System; using System.Collections.Generic; using System.Text; using Xunit; using ZKCloud.App.Core.Reports.Domain.Dtos; using ZKCloud.App.Core.Reports.Domain.Services; using ZKCloud.Domains.Dtos; using ZKCloud.Extensions; using ZKCloud.Helpers; using ZKCloud.Test.Base.Core.Model; namespace ZKCloud.Test.Reports { public class AutoReportService_Ltest : CoreTest { /// <summary> /// 指定同步网址,数据服务中心 /// </summary> private readonly string _serviceHostUrl = "http://localhost:9018"; /// <summary> /// 分布统计图,支持漏斗图、环图、饼状图 /// </summary> [Fact] public void LT001() { //CountReportInput var sqlwhereWhere = new CountReportInput { EntityType="order", }; var proList = Ioc.Resolve<IAutoReportService>().GetPieReport(sqlwhereWhere);// (x => x.Id > 700); var result = ""; } [Fact] public void CreateRouterT000est() { var type = "Status".GetTypeByName(); foreach (Enum item in Enum.GetValues(type)) { var value = item.GetDisplayName(); var key = System.Convert.ToInt16(item); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MergeSortedArrays { class Program { static void Main(string[] args) { Console.Write("Enter array size: "); int size1 = int.Parse(Console.ReadLine()); int[] arr1 = new int[size1]; Console.WriteLine($"Enter {size1} element in array1:"); for (int i = 0; i < size1; i++) { arr1[i] = int.Parse(Console.ReadLine()); } Console.Write("Enter array size: "); int size2 = int.Parse(Console.ReadLine()); int[] arr2 = new int[size2]; Console.WriteLine($"Enter {size2} element in array2:"); for (int i = 0; i < size2; i++) { arr2[i] = int.Parse(Console.ReadLine()); } int mergeSize = size1 + size2; int[] mergeArray = new int[mergeSize]; int index1 = 0; int index2 = 0; int merdgeIndex; for (merdgeIndex = 0; merdgeIndex < mergeSize; merdgeIndex++) { if (index1 >= size1 || index2 >= size2) { break; } if (arr1[index1] < arr2[index2]) { mergeArray[merdgeIndex] = arr1[index1]; index1++; } else { mergeArray[merdgeIndex] = arr2[index2]; index2++; } } while (index1 < size1) { mergeArray[merdgeIndex] = arr1[index1]; merdgeIndex++; index1++; } while (index2 < size2) { mergeArray[merdgeIndex] = arr2[index2]; merdgeIndex++; index2++; } Console.Write("\nArray merged in ascending order : "); for (int i = 0; i < mergeSize; i++) { Console.Write("{0}\t", mergeArray[i]); } Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArkSavegameToolkitNet.Data { public interface IExtraData { //int calculateSize(bool nameTable); } }
using System; namespace FactoryMethod { public class Dog : IAnimal { public void GetName() { Console.WriteLine("Jestem psem"); } public void MakeSound() { Console.WriteLine("Hauuuu!"); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using Microsoft.AspNet.Identity; using myFinPort.Extensions; using myFinPort.Helpers; using myFinPort.Models; using myFinPort.ViewModels; namespace myFinPort.Controllers { public class HouseholdsController : Controller { private ApplicationDbContext db = new ApplicationDbContext(); UserRolesHelper rolesHelper = new UserRolesHelper(); HouseholdHelper hhHelper = new HouseholdHelper(); // GET: Households public ActionResult Index() { return View(db.Households.ToList()); } // GET: Members public ActionResult Members() { return View(hhHelper.ListHouseholdMembers()); } // GET: Households/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Household household = db.Households.Find(id); if (household == null) { return HttpNotFound(); } return View(household); } // GET: Households/BuildHouse public ActionResult BuildHouse() { var model = new BuildHouseWizardVM(); return View(model); } // POST: Households/BuildHouse [HttpPost] [ValidateAntiForgeryToken] //[Authorize(Roles = "New User")] public async Task<ActionResult> BuildHouse(BuildHouseWizardVM model, bool isPersonalAccount = false) { if (ModelState.IsValid) { // success path db.Households.Add(model.Household); db.SaveChanges(); var user = db.Users.Find(User.Identity.GetUserId()); user.HouseholdId = model.Household.Id; rolesHelper.UpdateUserRole(user.Id, "Head"); db.SaveChanges(); await AuthorizeExtensions.RefreshAuthentication(HttpContext, user); // add bank account info var bankAccount = new BankAccount ( model.StartingBalance, model.BankAccount.WarningBalance, model.BankAccount.AccountName ); bankAccount.HouseholdId = (int)user.HouseholdId; bankAccount.AccountType = model.BankAccount.AccountType; if (isPersonalAccount) { bankAccount.OwnerId = user.Id; } else { bankAccount.OwnerId = null; } db.BankAccounts.Add(bankAccount); // add budget info var budget = new Budget(); budget.HouseholdId = (int)model.Household.Id; budget.BudgetName = model.Budget.BudgetName; db.Budgets.Add(budget); db.SaveChanges(); // add budget item info var budgetItem = new BudgetItem(); budgetItem.BudgetId = budget.Id; budgetItem.TargetAmount = model.BudgetItem.TargetAmount; budgetItem.ItemName = model.BudgetItem.ItemName; db.BudgetItems.Add(budgetItem); db.SaveChanges(); // now that the household has been established, refresh their login and send them to the dashboard. return RedirectToAction("Dashboard", "Home"); } // error return View(model); } // GET: Households/Create public ActionResult Create() { return View(); } // POST: Households/Create // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] //[Authorize(Roles = "New User")] public async Task<ActionResult> Create([Bind(Include = "Id,HouseholdName,Greeting")] Household household) { if (ModelState.IsValid) { household.Created = DateTime.Now; // this may come out later db.Households.Add(household); db.SaveChanges(); var user = db.Users.Find(User.Identity.GetUserId()); user.HouseholdId = household.Id; rolesHelper.UpdateUserRole(user.Id, "Head"); db.SaveChanges(); await AuthorizeExtensions.RefreshAuthentication(HttpContext, user); return RedirectToAction("ConfigureHouse"); } return View(household); } [HttpGet] //[Authorize(Roles = "Head")] public ActionResult ConfigureHouse() { var model = new ConfigureHouseVM(); model.HouseholdId = User.Identity.GetHouseholdId(); if(model.HouseholdId == null) { // this is the fail case return RedirectToAction("Create"); } return View(model); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult ConfigureHouse(ConfigureHouseVM model) { // Create the bank account(s) var bankAccount = new BankAccount ( model.StartingBalance, model.BankAccount.WarningBalance, model.BankAccount.AccountName ); bankAccount.AccountType = model.BankAccount.AccountType; db.BankAccounts.Add(bankAccount); var budget = new Budget(); budget.HouseholdId = (int)model.HouseholdId; budget.BudgetName = model.Budget.BudgetName; db.Budgets.Add(budget); db.SaveChanges(); var budgetItem = new BudgetItem(); budgetItem.BudgetId = budget.Id; budgetItem.TargetAmount = model.BudgetItem.TargetAmount; budgetItem.ItemName = model.BudgetItem.ItemName; db.BudgetItems.Add(budgetItem); db.SaveChanges(); return RedirectToAction("Index", "Home"); } // GET: Households/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Household household = db.Households.Find(id); if (household == null) { return HttpNotFound(); } return View(household); } // POST: Households/Edit/5 // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "Id,HouseholdName,Greeting,Created,IsDeleted")] Household household) { if (ModelState.IsValid) { db.Entry(household).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(household); } // what do we need to do to leave a household? // user leaving the house has HHId set to null // if the user is in the Head role someone must take over // if the user is in the Member role they can just leave // anyone leaving needs role reset to New User // if the user is the last person in the household the household can be deleted. // async Task == void return type [HttpPost] [ValidateAntiForgeryToken] [Authorize(Roles = "Head, Member")] public async Task<ActionResult> LeaveAsync() { var userId = User.Identity.GetUserId(); var user = db.Users.Find(userId); var role = rolesHelper.ListUserRoles(userId).FirstOrDefault(); switch (role) { case "Head": // -1 because I don't count the user doing this var memberCount = db.Users.Where(u => u.HouseholdId == user.HouseholdId).Count() - 1; if(memberCount >= 1) { // if I get here, I am not the last person in the household. var members = db.Users.Where(u => u.HouseholdId == user.HouseholdId).ToList(); ViewBag.NewHoH = new SelectList(members, "Id", "FullName"); return View("ExitDenied"); } // this user is the last person in the household, so it's safe to "soft" delete the household. // this is a "soft" delete. record stays in the database, but you can limit access on the front end user.Household.IsDeleted = true; // uncomment the next two lines for a hard delete, the record is removed from the database and anything with the // household foreign key will be cascade deleted //var household = db.Households.Find(user.HouseholdId); //db.Households.Remove(household); user.HouseholdId = null; // Drew had this code because he wants the accounts to stay with the user, not be "household" acocunts // but I want the accounts to belong to the household (like for joint accounts). // so I will have to do something different here. // I'll need to think through it. // // remove the HouseholdId from all BankAccounts associated with this user. //foreach(var account in user.Accounts) //{ // account.HouseholdId = null; //} db.SaveChanges(); rolesHelper.UpdateUserRole(userId, "New User"); await AuthorizeExtensions.RefreshAuthentication(HttpContext, user); return RedirectToAction("Dashboard", "Home"); case "Member": user.HouseholdId = null; db.SaveChanges(); rolesHelper.UpdateUserRole(userId, "New User"); await AuthorizeExtensions.RefreshAuthentication(HttpContext, user); return RedirectToAction("Dashboard", "Home"); default: return RedirectToAction("Dashboard", "Home"); } } [Authorize(Roles = "Head")] public ActionResult ExitDenied() { return View(); } [Authorize(Roles = "Head")] public ActionResult ChangeHead() { // TODO: look up null coelessing operator var myHouseId = User.Identity.GetHouseholdId(); if (myHouseId == 0) { return RedirectToAction("Dashboard", "Home"); } var members = db.Users.Where(u => u.HouseholdId == myHouseId).ToList(); ViewBag.NewHoH = new SelectList(members, "Id", "FullName"); return View(); } // this is the post that catches the submit from the ChangeHead.cshtml view. [HttpPost, ActionName("ChangeHead")] [ValidateAntiForgeryToken] public async Task<ActionResult> ChangeHeadAsync(string newHoH, bool leave) { if (string.IsNullOrEmpty(newHoH) || newHoH == User.Identity.GetUserId()) { return RedirectToAction("Dashboard", "Home"); } var user = db.Users.Find(User.Identity.GetUserId()); var newHoHuser = db.Users.Find(newHoH); if (user.HouseholdId != newHoHuser.HouseholdId) { user.HouseholdId = newHoHuser.HouseholdId; } rolesHelper.UpdateUserRole(newHoH, "Head"); if (leave) { user.HouseholdId = null; // Drew had this code because he wants the accounts to stay with the user, not be "household" acocunts // but I want the accounts to belong to the household (like for joint accounts). // so I will have to do something different here. // I'll need to think through it. // // remove the HouseholdId from all BankAccounts associated with this user. //foreach(var account in user.Accounts) //{ // account.HouseholdId = null; //} db.SaveChanges(); rolesHelper.UpdateUserRole(user.Id, "New User"); await AuthorizeExtensions.RefreshAuthentication(HttpContext, user); } else { rolesHelper.UpdateUserRole(user.Id, "Member"); await AuthorizeExtensions.RefreshAuthentication(HttpContext, user); } return RedirectToAction("Dashboard", "Home"); } // GET: Households/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Household household = db.Households.Find(id); if (household == null) { return HttpNotFound(); } return View(household); } // POST: Households/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Household household = db.Households.Find(id); db.Households.Remove(household); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; using BS; namespace partAssembler { class ItemPartInfo : MonoBehaviour { public List<Renderer> bladeRenderes = new List<Renderer>(); public List<ColliderGroup> bladeColliders = new List<ColliderGroup>(); } }
using System; using System.Collections.Generic; namespace TablesReady.Data.Domain { public partial class Restaurant { public Restaurant() { AddressDetails = new HashSet<AddressDetails>(); Email = new HashSet<Email>(); Employee = new HashSet<Employee>(); Phonebook = new HashSet<Phonebook>(); } public int RestaurantId { get; set; } public string RestaurantName { get; set; } public string RestaurantBusinessNum { get; set; } public DateTime RestaurantSignUpDate { get; set; } public virtual ICollection<AddressDetails> AddressDetails { get; set; } public virtual ICollection<Email> Email { get; set; } public virtual ICollection<Employee> Employee { get; set; } public virtual ICollection<Phonebook> Phonebook { get; set; } } }
using fNbt; using System.Collections.Generic; using UnityEngine; public class HireCandidates : MonoBehaviour, ISaveableState { [SerializeField] private World world = null; [SerializeField] private int startingCandidateCount = 2; [SerializeField] private WorkerType[] startingUnlockedTypes = null; [SerializeField] private float _workerTrainTime = 15f; [SerializeField] private int _hireCost = 100; [SerializeField, MinMaxSlider(1, 60), Tooltip("Time is in minutes")] private Vector2 candidateAvailabilityTimeRange = new Vector2(2, 8); private List<Candidate> candidates; private float traineeTrainingTime; private Trainee trainee; public float workerTrainTime => this._workerTrainTime; public int hireCost => this._hireCost; public int candaditeCount => this.candidates.Count; public string tagName => "hireCandidates"; private void Awake() { this.candidates = new List<Candidate>(); } private void Update() { if(this.isTraining()) { this.traineeTrainingTime += Time.deltaTime; if(this.traineeTrainingTime >= this.workerTrainTime || CameraController.instance.inCreativeMode) { // Create a new Worker Main.instance.workerFactory.spawnWorker( this.world, this.world.storage.workerSpawnPoint, trainee.info, trainee.type); this.trainee = null; } } } /// <summary> /// Removes all candidates from the list. /// </summary> public void clearAllCandidates() { this.candidates.Clear(); } public Candidate getCandidate(int index) { if(index < 0 || index >= this.candidates.Count) { return null; } return this.candidates[index]; } /// <summary> /// Returns true if you are in the process of hiring someone new. /// </summary> public bool isTraining() { return this.trainee != null; } public float remainingTrainingTime() { return this.traineeTrainingTime; } public void hireAndTrain(int candidateIndex) { Candidate candidate = this.getCandidate(candidateIndex); this.trainee = new Trainee(candidate.info, candidate.type); this.traineeTrainingTime = 0; // Remove the Candidate from the list this.candidates.RemoveAt(candidateIndex); } public void refreshCanidates() { // Remove candidates that aren't available anymore for(int i = 0; i < this.candidates.Count; i++) { Candidate c = this.candidates[i]; if(c != null) { if(this.world.time.time > c.endAvailabilityTime) { // Worker is not longer available to be hired this.candidates.RemoveAt(0); } } } // Find the number of candadites that should be shown. int candaditeCount = this.startingCandidateCount; foreach(MilestoneData milestone in this.world.milestones.milestones) { if(milestone == null) { continue; } if(CameraController.instance.inCreativeMode || milestone.isUnlocked) { candaditeCount += milestone.hireCandaditeIncrease; } } // Add new candidates int stop = candaditeCount - this.candidates.Count; for(int i = 0; i < stop; i++) { WorkerType type = this.getNewCandatiteType(); if(type == null) { Debug.LogWarning("Error finding a type for a new candadite"); continue; } this.candidates.Add(new Candidate( Main.instance.workerFactory.generateWorkerInfo(type), type, this.world.time.time + Random.Range( this.candidateAvailabilityTimeRange.x * 60, this.candidateAvailabilityTimeRange.y * 60))); } } public void writeToNbt(NbtCompound tag) { NbtList list = new NbtList(NbtTagType.Compound); foreach(Candidate c in this.candidates) { if(c != null) { list.Add(c.writeToNbt()); } } tag.setTag("candidates", list); if(this.trainee != null) { tag.setTag("trainee", this.trainee.writeToNbt()); tag.setTag("trainingTime", this.traineeTrainingTime); } } public void readFromNbt(NbtCompound tag) { NbtList list = tag.getList("candidates"); for(int i = 0; i < list.Count; i ++) { this.candidates.Add(new Candidate(list.Get<NbtCompound>(i))); } if(tag.hasKey("trainee")) { this.trainee = new Trainee(tag.getCompound("trainee")); this.traineeTrainingTime = tag.getFloat("trainingTime"); } } /// <summary> /// Returns the WorkerType that a new candadite should have. /// Null is returned if there are no unlocked candadites. /// </summary> /// <returns></returns> private WorkerType getNewCandatiteType() { WorkerTypeRegistry reg = Main.instance.workerTypeRegistry; bool inCreative = CameraController.instance.inCreativeMode; // Get totals of all of the currently shown worker types. int[] counts = new int[reg.getRegistrySize()]; foreach(Candidate c in this.candidates) { if(c != null) { int index = reg.getIdOfElement(c.type); counts[index]++; } } // Get a list of all of the unlocked worker types. This may // contain duplicates, but that's fine. List<WorkerType> allUnlockedTypes = new List<WorkerType>(); allUnlockedTypes.AddRange(this.startingUnlockedTypes); foreach(MilestoneData milestone in this.world.milestones.milestones) { if(milestone.isUnlocked) { allUnlockedTypes.AddRange(milestone.unlockedWorkerTypes); } } // Break early if nothing is unlocked. if(allUnlockedTypes.Count == 0) { return null; } // If there are none of a certain type, add them for(int i = 0; i < reg.getRegistrySize(); i++) { WorkerType t = reg.getElement(i); if(t != null && counts[i] == 0 && (allUnlockedTypes.Contains(t) || inCreative)) { return t; // There is none of this time currently hired. } } // There is at least one of every type, add the type that is // the least common (if there are multiple, pick a random). int lowestCount = int.MaxValue; for(int i = 0; i < counts.Length; i++) { if(reg.getElement(i) != null) { if(counts[i] < lowestCount) { lowestCount = counts[i]; } } } // Get a list of the Types that are the least shown. List<WorkerType> possibilites = new List<WorkerType>(); for(int i = 0; i < reg.getRegistrySize(); i++) { WorkerType type = reg.getElement(i); if(type != null && counts[i] <= lowestCount && (allUnlockedTypes.Contains(type) || inCreative)) { possibilites.Add(type); } } if(possibilites.Count == 0) { // There is an equal number of all worker types, pick one at random return allUnlockedTypes[Random.Range(0, allUnlockedTypes.Count)]; } else { return possibilites[Random.Range(0, possibilites.Count)]; } } }
using gView.GraphicsEngine; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Text; namespace gView.Drawing.Pro.Filters { public interface IFilter { Bitmap Apply(Bitmap bitmap); Bitmap Apply(BitmapData bmData); } }
using PedidosAPI.Controllers; using PedidosAPI.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace PedidosAPI.Test.UnitTest { [TestClass] public class PedidoControllerTest : TestBase { [TestMethod] public async Task ObtenerTodosLosPedidos() { var nombreDB = Guid.NewGuid().ToString(); var contexto = ConstruirContext(nombreDB); await contexto.Pedidos.AddAsync(new Pedido { Cliente = "ClientePrueba1", FechaPedido = null, MontoPedido = 111}); await contexto.Pedidos.AddAsync(new Pedido { Cliente = "ClientePrueba2", FechaPedido = null, MontoPedido = 333}); await contexto.SaveChangesAsync(); var contexto2 = ConstruirContext(nombreDB); var controller = new PedidoController(contexto2); var respuesta = await controller.GetPedidos(); var resultado = respuesta.Count; Assert.AreEqual(2, resultado); } [TestMethod] public async Task ObtenerPedidosPorID() { var nombreDB = Guid.NewGuid().ToString(); var contexto = ConstruirContext(nombreDB); await contexto.Pedidos.AddAsync(new Pedido { Cliente = "ClientePrueba3", FechaPedido = null, MontoPedido = 1152}); await contexto.SaveChangesAsync(); var pedido = new Pedido(); var contexto2 = ConstruirContext(nombreDB); var controller = new PedidoController(contexto2); var id = 1; //var respuesta = controller.GetPedidoByID(id); pedido = await controller.GetPedidoByID(id); var resultado = pedido.ID; Assert.AreEqual(id, resultado); } [TestMethod] public async Task AgregarPedido() { var nombreDB = Guid.NewGuid().ToString(); var contexto = ConstruirContext(nombreDB); var nuevoPedido = new Pedido() { Cliente = "ClientePrueba4", FechaPedido = DateTime.Now, MontoPedido = 9000 }; var controller = new PedidoController(contexto); var respuesta = await controller.SavePedido(nuevoPedido); var resultado = respuesta as CreatedAtRouteResult; Assert.IsNotNull(resultado); } [TestMethod] public async Task EditarPedido() { var nombreDB = Guid.NewGuid().ToString(); var contexto = ConstruirContext(nombreDB); await contexto.Pedidos.AddAsync(new Pedido { Cliente = "Test_A", FechaPedido = DateTime.Now, MontoPedido = 1321 }); await contexto.SaveChangesAsync(); var contexto2 = ConstruirContext(nombreDB); var controller = new PedidoController(contexto2); var id = 1; var pedidoAct = new Pedido() { ID= id, Cliente = "Test_B", FechaPedido = DateTime.Now, MontoPedido = 1320 }; var respuesta = await controller.EditPedido(id, pedidoAct); var context3 = ConstruirContext(nombreDB); var existe = await context3.Pedidos.AnyAsync(x => x.Cliente == "Test_B"); Assert.IsTrue(existe); } [TestMethod] public async Task BorrarPedidoOK() { var nombreDB = Guid.NewGuid().ToString(); var contexto = ConstruirContext(nombreDB); await contexto.Pedidos.AddAsync(new Pedido { Cliente = "ClientePrueba6", FechaPedido = null, MontoPedido = 9999 }); await contexto.SaveChangesAsync(); var controller = new PedidoController(contexto); var id = 1; var respuesta = await controller.DeletePedido(id); var resultado = respuesta as StatusCodeResult; Assert.AreEqual(200, resultado.StatusCode); } [TestMethod] public async Task BorrarPedidoNoExistente() { var nombreDB = Guid.NewGuid().ToString(); var contexto = ConstruirContext(nombreDB); var controller = new PedidoController(contexto); var id = 1; var respuesta = await controller.DeletePedido(id); var resultado = respuesta as StatusCodeResult; Assert.AreEqual(400, resultado.StatusCode); } } }
using Shiftgram.Core.Enums; using System.Threading.Tasks; namespace Shiftgram.Core.Strategy { public interface IUpdatableAccount { Task<DbAnswerCode> Update(AccountUpdateViewModel model); } }
using System.Linq; using System.Web.Mvc; using CAPCO.Infrastructure.Domain; using CAPCO.Infrastructure.Data; namespace CAPCO.Areas.Admin.Controllers { public class ProductCategoriesController : BaseAdminController { private readonly IRepository<ProductCategory> _ProductcategoryRepository; public ProductCategoriesController(IRepository<ProductCategory> productcategoryRepository) { _ProductcategoryRepository = productcategoryRepository; } public ViewResult Index() { return View(_ProductcategoryRepository.All.ToList()); } public ActionResult New() { return View(); } [HttpPost, ValidateAntiForgeryToken, ValidateInput(false)] public ActionResult Create(ProductCategory productcategory) { if (ModelState.IsValid) { _ProductcategoryRepository.InsertOrUpdate(productcategory); _ProductcategoryRepository.Save(); this.FlashInfo("The product category was successfully created."); return RedirectToAction("Index"); } this.FlashError("There was a problem creating the product category."); return View("New", productcategory); } public ActionResult Edit(int id) { return View(_ProductcategoryRepository.Find(id)); } [HttpPut, ValidateAntiForgeryToken, ValidateInput(false)] public ActionResult Update(ProductCategory productcategory) { if (ModelState.IsValid) { var prop = _ProductcategoryRepository.Find(productcategory.Id); prop.Name = productcategory.Name; prop.Code = productcategory.Code; _ProductcategoryRepository.InsertOrUpdate(prop); _ProductcategoryRepository.Save(); this.FlashInfo("The product category was successfully saved."); return RedirectToAction("Index"); } this.FlashError("There was a problem saving the product category."); return View("Edit", productcategory); } public ActionResult Delete(int id) { _ProductcategoryRepository.Delete(id); _ProductcategoryRepository.Save(); this.FlashInfo("The product category was successfully deleted."); return RedirectToAction("Index"); } } }
using System; using System.Collections.Generic; using System.Text; namespace AiBridge { public class StepNeuron : Neuron { public double Threshold { get; private set; } public StepNeuron(double threshold = 1) { Threshold = threshold; } public StepNeuron(int dendriteCount, double initialWeight, double threshold = 1) : base(dendriteCount, initialWeight) { Threshold = threshold; } public override double Activation(double value) { return (value >= Threshold) ? Threshold : 0; //return value >= Threshold ? 0 : Threshold; } } }
using University.Data; using University.Data.CustomEntities; using University.Service.Interface; using University.UI.Areas.Admin.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using University.UI.Controllers; namespace IPSU.Web.Controllers { public class UserGuideController : BaseController { // GET: UserGuide private IProductUserGuideService _productUserGuideService; public UserGuideController(IProductUserGuideService productUserGuideService, IProductService productService) : base(productService) { _productUserGuideService = productUserGuideService; } public ActionResult Index() { return View(); } public ActionResult UserGuide(string SearchString) { //var userGuides = _productUserGuideService.GetProductUserGuideList().ToList(); //var viewModel = AutoMapper.Mapper.Map<List<ProductUserGuide>, List<ProductUserGuideViewModel>>(userGuides); //if (!String.IsNullOrEmpty(SearchString)) //{ // viewModel = viewModel.Where(x => x.Title.ToLower().Contains(SearchString.ToLower())).ToList(); //} //return View(viewModel); List<ProductUserGuideViewModel> productUserGuideViewModels = new List<ProductUserGuideViewModel>(); var res = _productUserGuideService.GetUserGuideList().ToList(); if (!String.IsNullOrEmpty(SearchString)) { res = res.Where(x => x.Title.ToLower().Contains(SearchString.ToLower())).ToList(); } foreach (var pGuide in res) { productUserGuideViewModels.Add(new ProductUserGuideViewModel { Id = pGuide.Id, Title = pGuide.Title, Description = pGuide.Description, ImageURL = pGuide.ImageURL }); } if (!String.IsNullOrEmpty(SearchString)) { productUserGuideViewModels = productUserGuideViewModels.Where(x => x.Title.ToLower().Contains(SearchString.ToLower())).ToList(); } return View(productUserGuideViewModels); } } }
/* * 监听标志位,单例模式,不用挂物体上 */ using System; public class DetectionManage { private static DetectionManage _instance; public static DetectionManage Instance { get { if (_instance == null) { _instance = new DetectionManage(); } return _instance; } } //连接标志位 private bool _Connected; //急停标志位 private bool _EMstopBit; //0点丢失标志位 private bool _SysCalPass; //痉挛标志位 private bool _Caution; //机器故障标志位 private bool _Fault; //机器断开连接事件 public Action<bool> ActionReConnect; //急停事件 public Action<bool> ActionEmrgencyStop; //0点丢失事件 public Action<bool> ActionHomeCalibrate; //痉挛事件 public Action<bool> ActionCaution; //机器故障事件 public Action<bool> ActionFault; //当标志位改变值的时候会触发断开或者重新连接的事件 public bool Connected { get { return _Connected; } set { if (_Connected != value) { _Connected = value; if (ActionReConnect != null) { ActionReConnect(value); } } } } //当标志位改变值的时候会触发急停或者恢复正常的事件 public bool EMstopBit { get { return _EMstopBit; } set { if (_EMstopBit != value) { _EMstopBit = value; if (ActionEmrgencyStop != null) ActionEmrgencyStop(value); } } } //当标志位改变值的时候会0点丢失或者校准完毕的事件 public bool SysCalPass { get { return _SysCalPass; } set { if (_SysCalPass != value)//CommandFunctions.resettingState == CommandFunctions.ResettingState.NoGaming&& { _SysCalPass = value; if (ActionHomeCalibrate != null) { ActionHomeCalibrate(value); } } } } //当标志位改变值的时候会发生痉挛或者恢复正常的事件 public bool Caution { get { return _Caution; } set { if (_Caution != value) { _Caution = value; if (ActionCaution != null) { ActionCaution(value); } } } } ////当标志位改变值的时候会触发机器故障事件 public bool Fault { get { return _Fault; } set { if (_Fault != value) { _Fault = value; if (ActionFault != null) { ActionFault(value); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LightingBook.Tests.Api.Product.CarBooking { public class TripIdentifier { public TripIdentifier(string passengerIdentifier, string passengerItinIdentifier, string passengerSearchIdentifier, string searchCarIdentifer) { PassengerIdentifier = passengerIdentifier; PassengerItinIdentifier = passengerItinIdentifier; PassengerSearchIdentifier = passengerSearchIdentifier; SearchCarIdentifer = searchCarIdentifer; } public string PassengerIdentifier { get; } public string PassengerItinIdentifier { get; } public string PassengerSearchIdentifier { get; } public string SearchCarIdentifer { get; } } }
using Microsoft.EntityFrameworkCore.Migrations; namespace Draft_FF.Frontend.Migrations { public partial class updated_owner_entity2 : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.UpdateData( table: "Owners", keyColumn: "Id", keyValue: 5, columns: new[] { "DraftRank", "TeamName" }, values: new object[] { 2, "Affligem Brewers" }); migrationBuilder.UpdateData( table: "Owners", keyColumn: "Id", keyValue: 6, columns: new[] { "DraftRank", "TeamName" }, values: new object[] { 6, "Alvin and the KareemHunts" }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.UpdateData( table: "Owners", keyColumn: "Id", keyValue: 5, columns: new[] { "DraftRank", "TeamName" }, values: new object[] { 6, "Alvin and the KareemHunts" }); migrationBuilder.UpdateData( table: "Owners", keyColumn: "Id", keyValue: 6, columns: new[] { "DraftRank", "TeamName" }, values: new object[] { 10, "Team Willi" }); } } }
using System; using System.Collections.Generic; using Welic.Dominio.Eventos.Contratos; namespace Welic.Dominio.Eventos { public interface IManipulador<T> : IDisposable where T : IEventoDominio { void Manipular(T args); IEnumerable<T> Notificar(); bool PossuiNotificacoes(); } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using POSServices.Data; using POSServices.Models; using POSServices.WebAPIModel; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace POSServices.Controllers { [Route("api/[controller]")] public class ReportMutasiBarangController : Controller { private readonly DB_BIENSI_POSContext _context; public ReportMutasiBarangController(DB_BIENSI_POSContext context) { _context = context; } // GET: api/<controller> [HttpGet] public IActionResult Get([FromQuery]string transactionId) { MutasiAPIModel model = new MutasiAPIModel(); string noReturn = ""; List<MutasiAPIModel> listModel = new List<MutasiAPIModel>(); List<MutasiLineAPIModel> listModelLine = new List<MutasiLineAPIModel>(); List<ObjectAPIModel> listParam = new List<ObjectAPIModel>(); DBSQLConnect connect = new DBSQLConnect(); try { connect.sqlCon().Open(); string cmd = "select* from vInventoryTransaction where TransactionId = @TransactionId"; var inputDate = new ObjectAPIModel(); inputDate.param = "@TransactionId"; inputDate.typeValue = DbType.String; inputDate.value = transactionId; listParam.Add(inputDate); connect.sqlDataRd = connect.ExecuteDataReaderWithParams(cmd, connect.sqlCon(), listParam); if (connect.sqlDataRd.HasRows) { while (connect.sqlDataRd.Read()) { if (noReturn == "" || noReturn != connect.sqlDataRd["Id"].ToString()) { if (model.lines != null) listModel.Add(model); model = new MutasiAPIModel(); noReturn = connect.sqlDataRd["Id"].ToString(); model.noReturn = noReturn; DateTime transDate; if (DateTime.TryParse(connect.sqlDataRd["TransactionDate"].ToString(), out transDate)) { model.tanggalRetur = transDate; } model.showroom = connect.sqlDataRd["Warehouse Original Name"].ToString(); model.showroomTujuan = connect.sqlDataRd["Warehouse Destination Name"].ToString(); model.keterangan = connect.sqlDataRd["Remarks"].ToString(); model.status = connect.sqlDataRd["Status"].ToString(); model.lines = new List<MutasiLineAPIModel>(); var line = new MutasiLineAPIModel(); line.articleId = connect.sqlDataRd["ArticleId"].ToString(); line.articleName = connect.sqlDataRd["ArticleName"].ToString(); line.color = connect.sqlDataRd["Color"].ToString(); line.size = connect.sqlDataRd["Size"].ToString(); Decimal qtyResult = 0; if (Decimal.TryParse(connect.sqlDataRd["Qty"].ToString(), out qtyResult)) { line.qty = qtyResult; } Decimal totalResult = 0; if (Decimal.TryParse(connect.sqlDataRd["Total"].ToString(), out totalResult)) { line.total = totalResult; } if (line.qty > 0 && line.total > 0) line.price = line.total / line.qty; model.lines.Add(line); } else { var line = new MutasiLineAPIModel(); line.articleId = connect.sqlDataRd["ArticleId"].ToString(); line.articleName = connect.sqlDataRd["ArticleName"].ToString(); line.color = connect.sqlDataRd["Color"].ToString(); line.size = connect.sqlDataRd["Size"].ToString(); Decimal qtyResult = 0; if (Decimal.TryParse(connect.sqlDataRd["Qty"].ToString(), out qtyResult)) { line.qty = qtyResult; } Decimal totalResult = 0; if (Decimal.TryParse(connect.sqlDataRd["Total"].ToString(), out totalResult)) { line.total = totalResult; } if (line.qty > 0 && line.total > 0) line.price = line.total / line.qty; model.lines.Add(line); } } if (model.lines != null) listModel.Add(model); } } catch (Exception e) { return Ok(e.Message); } finally { if (connect.sqlDataRd != null) connect.sqlDataRd.Close(); if (connect.sqlCon().State == ConnectionState.Open) connect.sqlCon().Close(); } return Ok(listModel); } } }
using System; using System.Collections.Generic; using System.Linq; using Uintra.Core.Controls.LightboxGallery; namespace Uintra.Features.Groups.Models { public class GroupInfoViewModel : IHaveLightboxPreview { public Guid Id { get; set; } public string Title { get; set; } public string Description { get; set; } public IEnumerable<string> Media { get; set; } = Enumerable.Empty<string>(); public LightboxPreviewModel MediaPreview { get; set; } public bool CanHide { get; set; } public bool IsHidden { get; set; } } }
using System; using System.Configuration; using System.IO; using System.Linq; using System.Reflection; using Ninject.Modules; using Podemski.Musicorum.Dao.Factories; using Podemski.Musicorum.Dao.Repositories; using Podemski.Musicorum.Interfaces.Entities; using Podemski.Musicorum.Interfaces.Factories; using Podemski.Musicorum.Interfaces.Repositories; namespace Podemski.Musicorum.Dao { public sealed class DaoModule : NinjectModule { public override void Load() { Bind<IRepository<IAlbum>>().To<AlbumRepository>(); Bind<IRepository<IArtist>>().To<ArtistRepository>(); Bind<IRepository<ITrack>>().To<TrackRepository>(); Bind<IArtistFactory>().To<ArtistFactory>(); Bind<IAlbumFactory>().To<AlbumFactory>(); Bind<ITrackFactory>().To<TrackFactory>(); Bind<Context>().ToMethod(_ => GetContext()).InSingletonScope(); } private static Context GetContext() { var context = CreateContext(); context.LoadContext(); return context; } private static Context CreateContext() { string exeLocation = Assembly.GetEntryAssembly().Location; var config = ConfigurationManager.OpenExeConfiguration(exeLocation); string contextSource = config.AppSettings.Settings["Context"].Value; string contextData = config.AppSettings.Settings["ContextData"].Value; if(!Path.IsPathRooted(contextSource)) { contextSource = Path.Combine(Path.GetDirectoryName(exeLocation), contextSource); } var assembly = Assembly.LoadFile(contextSource); var contextType = assembly.GetTypes().Single(t => t.IsSubclassOf(typeof(Context))); var context = (Context)Activator.CreateInstance(contextType); context.Initialize(contextData); return context; } } }
using NonogramProject; using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using System.Threading; namespace WindowsFormsApplication1 { public partial class NonogramGUI : Form { private NonogramSolver solver; private int row; private int column; private PictureBox[,] picBox; UpdatedEventArgs last; ManualResetEvent reset = new ManualResetEvent(false); public NonogramGUI(NonogramSolver solver) { InitializeComponent(); this.solver = solver; this.AutoSize = true; this.AutoSizeMode = AutoSizeMode.GrowAndShrink; this.Padding = new Padding(100); row = solver.GetRows(); column = solver.GetColumns(); picBox = new PictureBox[row, column]; Console.WriteLine("column = " + column); Console.WriteLine("row = " + row); tableLayoutPanel1.AutoSize = true; tableLayoutPanel1.AutoSizeMode = AutoSizeMode.GrowAndShrink; tableLayoutPanel1.Padding = new Padding(0, 0, 0, 0); tableLayoutPanel1.Margin = new Padding(0, 0, 0, 0); tableLayoutPanel1.ColumnCount = column + 1; tableLayoutPanel1.RowCount = row + 1; string textClues; tableLayoutPanel1.Controls.Add(new Label()); for (int i = 1; i <= column; i++) { textClues = ""; foreach (Clue clue in solver.GetColumn(i).Clues) { textClues += "\n" + clue.Value; } tableLayoutPanel1.Controls.Add(new Label { Text = textClues, AutoSize = true, Font = new Font("Arial", 18) }); } for (int i = 0; i < row; i++) { textClues = ""; foreach (Clue clue in solver.GetRow(i + 1).Clues) { textClues += clue.Value + " "; } tableLayoutPanel1.Controls.Add(new Label { Text = textClues, AutoSize = true, Font = new Font("Arial", 18) }); ; for (int j = 0; j < column; j++) { Image image; PictureBox tempBox; if (row >= 12 || column >= 12) { Image imager = Properties.Resources.Blank; image = new Bitmap(imager, new Size(25, 25)); tempBox = new PictureBox() { Image = image }; } else image = Properties.Resources.Blank; tempBox = new PictureBox() { Image = image }; tempBox.Size = image.Size; tableLayoutPanel1.Controls.Add(tempBox); picBox[i, j] = tempBox; solver.Updater += Updated; } } solver.Updater += Updated; this.Show(); Application.DoEvents(); Thread.Sleep(5000); solver.Run(); if (solver.IsFinished()) label1.Visible = true; } private void Form2_Load(object sender, EventArgs e) { } private void Form2_FormClosing(object sender, FormClosingEventArgs e) { System.Windows.Forms.Application.Exit(); } public void Updated(object sender, UpdatedEventArgs e) { if (last != null) { foreach (Tuple<int, int, int> tuple in last.Changes) { if (tuple != null) { if (tuple.Item3.Equals(1)) picBox[tuple.Item1 - 1, tuple.Item2 - 1].Image = Properties.Resources.Filled; else if (tuple.Item3.Equals(2)) picBox[tuple.Item1 - 1, tuple.Item2 - 1].Image = Properties.Resources.Cross; } } } //System.Timers.Timer timer = new System.Timers.Timer(1000); //timer.Elapsed += OnTimer; //timer.AutoReset = false; //timer.Start(); foreach (Tuple<int, int, int> tuple in e.Changes) { if (tuple != null) { if (tuple.Item3.Equals(1)) picBox[tuple.Item1 - 1, tuple.Item2 - 1].Image = Properties.Resources.New_Filled; else if (tuple.Item3.Equals(2)) picBox[tuple.Item1 - 1, tuple.Item2 - 1].Image = Properties.Resources.New_Cross; } } last = e; Application.DoEvents(); } private void OnTimer(Object sender, EventArgs e) { reset.Set(); reset.Reset(); Console.WriteLine("I made it"); } private void Button1_Click(object sender, EventArgs e) { } } }
using Microsoft.AspNetCore.Mvc; using Service.Contracts; using SiemensCommunity.Adapters; using SiemensCommunity.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; namespace SiemensCommunity.Controllers { [ApiController] [Route("api/[controller]")] public class ProductController : ControllerBase { private readonly IProductService _productService; private readonly IAccountService _accountService; private readonly ProductAdapter _productAdapter = new ProductAdapter(); private readonly UserAdapter _userAdapter = new UserAdapter(); public ProductController(IProductService productService) { _productService = productService; } [HttpPost] public async Task<IActionResult> Add([FromBody]Product product) { if (!(ModelState.IsValid)) { return BadRequest(ModelState); } else { var returnedProduct = await _productService.AddAsync(_productAdapter.Adapt(product)); if (returnedProduct != null) { return Ok(_productAdapter.Adapt(returnedProduct)); } else { return StatusCode((int) HttpStatusCode.InternalServerError); } } } [HttpDelete] public async Task<IActionResult> Delete(int id) { var success = await _productService.DeleteByIdAsync(id); if (success) { return Ok(id); } else { return NotFound(id); } } [HttpGet("get")] public async Task<IActionResult> Get() { var productList = await _productService.GetAsync(); return Ok(productList); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DA.Empresa { public interface IDAOFactory { IempresaDAO getempresaDAO(); } }
using System.Collections.Generic; namespace DelftTools.Utils { public interface ITimeNavigatableProvider { IEnumerable<ITimeNavigatable> Navigatables { get; } } }
using Microsoft.AspNetCore.Http; namespace Sentry.AspNetCore; /// <summary> /// Sentry User Factory /// </summary> public interface IUserFactory { /// <summary> /// Creates a <see cref="User"/> from the <see cref="HttpContext"/> /// </summary> /// <param name="context">The HttpContext where the user resides</param> /// <returns>The protocol user</returns> User? Create(HttpContext context); }
namespace _09.UserLogs { using System; using System.Collections.Generic; using System.Text; public class UserLogs { public static void Main() { Dictionary<string, Dictionary<string, int>> usersLogsDictionary = new Dictionary<string, Dictionary<string, int>>(); while (true) { string[] inputStr = Console.ReadLine().Split(); if (inputStr[0] == "end") { break; } string ip = inputStr[0].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries)[1]; string user = inputStr[2].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries)[1]; if (!usersLogsDictionary.ContainsKey(user)) { usersLogsDictionary.Add(user,new Dictionary<string, int>()); } if (!usersLogsDictionary[user].ContainsKey(ip)) { usersLogsDictionary[user].Add(ip,0); } usersLogsDictionary[user][ip]++; } List<string> usersList = new List<string>(usersLogsDictionary.Keys); usersList.Sort(); for (int i = 0; i < usersList.Count; i++) { Console.WriteLine($"{usersList[i]}:"); StringBuilder ipsStr = new StringBuilder(); foreach (KeyValuePair<string, int> ips in usersLogsDictionary[usersList[i]]) { ipsStr.Append($"{ips.Key} => {ips.Value}, "); } ipsStr.Remove(ipsStr.Length - 2, 2); ipsStr.Append("."); Console.WriteLine(ipsStr); } } } }
using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; namespace HospitalSystem.Models.Mapping { public class patientMap : EntityTypeConfiguration<patient> { public patientMap() { // Primary Key this.HasKey(t => t.PatientID); // Properties this.Property(t => t.Name) .HasMaxLength(50); this.Property(t => t.Gender) .HasMaxLength(5); this.Property(t => t.Telephone) .HasMaxLength(50); // Table & Column Mappings this.ToTable("patient", "teamwork"); this.Property(t => t.PatientID).HasColumnName("PatientID"); this.Property(t => t.Name).HasColumnName("Name"); this.Property(t => t.Birthday).HasColumnName("Birthday"); this.Property(t => t.Gender).HasColumnName("Gender"); this.Property(t => t.Telephone).HasColumnName("Telephone"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using static MoneyWeb.Models.ContaModel; namespace MoneyWeb.ViewModels { public class ContaFilterModel { public string Nome { get; set; } public int[] ListTipo { get; set; } = new int[] { }; public SortingViewModel Sorting { get; set; } } public class ContaPostModel { public int? Id { get; set; } public string Nome { get; set; } public TipoEnum Tipo { get; set; } public int Ordem { get; set; } } public class ContaDeleteModel { public int? Id { get; set; } } }
using System; using System.Data.Entity; using System.Linq; using DAL.Models; namespace DAL { public class AllDbContext: DbContext { public AllDbContext():base("ParkingFine") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { } public DbSet<Parking> Parkings { get; set; } public DbSet<Fine> Fines { get; set; } public DbSet<Auto> Autos { get; set; } public DbSet<Evacuation> Evacuations { get; set; } public DbSet<Declaration> Declarations { get; set; } public DbSet<Profile> Profiles { get; set; } } }
using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; using CefSharp; using CefSharp.Enums; using CefSharp.OffScreen; using CefSharp.Structs; namespace Browser.OffScreen.CefHandler { public class RenderHandler : IRenderHandler { public delegate void BrowserPaintHandler(Bitmap bitmap); public event BrowserPaintHandler BrowserPaint; public bool Render { get; set; } private ChromiumWebBrowser _browser; private byte[] _buffer; private int _lastWidth; private int _lastHeight; protected virtual void OnBrowserPaint(Bitmap bitmap) { BrowserPaint?.Invoke(bitmap); } public RenderHandler(ChromiumWebBrowser browser) { _browser = browser; Render = true; } public void Dispose() { _browser = null; } public virtual ScreenInfo? GetScreenInfo() { var screenInfo = new ScreenInfo { DeviceScaleFactor = 1.0F }; return screenInfo; } public virtual Rect GetViewRect() { var size = _browser.Size; var viewRect = new Rect(0, 0, size.Width, size.Height); return viewRect; } public virtual bool GetScreenPoint(int viewX, int viewY, out int screenX, out int screenY) { screenX = viewX; screenY = viewY; return false; } public virtual void OnAcceleratedPaint(PaintElementType type, Rect dirtyRect, IntPtr sharedHandle) { } private void ResizeBuffer(int width, int height) { if (_buffer == null || width != _lastWidth || height != _lastHeight) { var nob = width * height * 4; _buffer = new byte[nob]; _lastWidth = width; _lastHeight = height; } } public virtual void OnPaint(PaintElementType type, Rect dirtyRect, IntPtr buffer, int width, int height) { if (Render && _browser.IsBrowserInitialized) { ResizeBuffer(width, height); Marshal.Copy(buffer, _buffer, 0, _buffer.Length); var bitmap = new Bitmap(width, height, PixelFormat.Format32bppPArgb); var bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppPArgb); Marshal.Copy(_buffer, 0, bitmapData.Scan0, _buffer.Length); bitmap.UnlockBits(bitmapData); OnBrowserPaint(bitmap); } } public virtual void OnCursorChange(IntPtr cursor, CursorType type, CursorInfo customCursorInfo) { } public virtual bool StartDragging(IDragData dragData, DragOperationsMask mask, int x, int y) { return false; } public virtual void UpdateDragCursor(DragOperationsMask operation) { } public virtual void OnPopupShow(bool show) { } public virtual void OnPopupSize(Rect rect) { } public virtual void OnImeCompositionRangeChanged(Range selectedRange, Rect[] characterBounds) { } public virtual void OnVirtualKeyboardRequested(IBrowser browser, TextInputMode inputMode) { } } }
namespace ModelTransformationComponent { /// <summary> /// Класс конструкции /// </summary> public abstract class Rule{ } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ConfigHelper.cs"> // Copyright (c) 2021 Johannes Deml. All rights reserved. // </copyright> // <author> // Johannes Deml // public@deml.io // </author> // -------------------------------------------------------------------------------------------------------------------- using System.Globalization; using BenchmarkDotNet.Columns; using BenchmarkDotNet.Configs; using BenchmarkDotNet.Exporters; using BenchmarkDotNet.Exporters.Csv; using BenchmarkDotNet.Reports; using Perfolizer.Horology; namespace NetworkBenchmark { public static class ConfigHelper { /// <summary> /// A summary style that makes processing of data more accessible. /// * Long column width to avoid names being truncated /// * units stay the same /// * No units in cell data (Always numbers) /// </summary> private static readonly SummaryStyle CsvStyle = new SummaryStyle(CultureInfo.InvariantCulture, false, SizeUnit.KB, TimeUnit.Millisecond, false, true, 100); public static void AddDefaultColumns(ManualConfig config) { config.AddColumn(FixedColumn.VersionColumn); config.AddColumn(FixedColumn.OperatingSystemColumn); config.AddColumn(FixedColumn.DateTimeColumn); config.AddColumn(new EnvironmentVariableColumn("SystemTag", "SYSTEM_TAG")); config.AddExporter(MarkdownExporter.GitHub); config.AddExporter(new CsvExporter(CsvSeparator.Comma, ConfigHelper.CsvStyle)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Threading; using TypeInThai.Models; using TypeInThai.ViewModels; using System.Web.UI; namespace TypeInThai.Controllers { public class ChallengeController : BaseController { public ActionResult Index() { var vm = new ChallengeViewModel(); var thisChallenge = new Challenge(); vm.HighestLevelPassed = thisChallenge.GetHighestLevelPassed(thisUser.Id); return View(vm); } public ActionResult Level(int Id) { var vm = new LevelViewModel(); vm.Id = Id; return View(vm); } } }
using BugTracker.Entities; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BugTracker.DataAccessLayer { class StockDao { public IList<Stock> GetAll() { List<Stock> listadoBugs = new List<Stock>(); var strSql = "SELECT codProducto, cantActual, cantMin from Categorias"; var resultadoConsulta = DBHelper.GetDBHelper().ConsultaSQL(strSql); foreach (DataRow row in resultadoConsulta.Rows) { listadoBugs.Add(MappingBug(row)); } return listadoBugs; } private Stock MappingBug(DataRow row) { Stock oStock = new Stock { CodProducto = Convert.ToInt32(row["codProducto"].ToString()), CantActual = Convert.ToInt32(row["cantactual"].ToString()), CantMin = Convert.ToInt32(row["cantMin"].ToString()) }; return oStock; } } }
 using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace VR_Interaction { public class VideoCaptureUIMenu : MonoBehaviour { public Button CloseButton; public Toggle ManualTimingToggle; public Toggle AutomaticTimingToggle; public Text DurationText; //WAYPÖINT TIMING BUTTONS public GameObject WaypointsTimingButtonsContainer; public GameObject TimingButtonPrefab; public Button ApplyTimingChangesButton; public Dictionary<int, VideoCaptureTimeButton> WaypointTimingButtonList; //CLOUDSTATE TIMING BUTTONS public GameObject CloudStatesTimingButtonsContainer; public Dictionary<int, VideoCaptureTimeButton> CloudStatesTimingButtonList; public Button NewCloudStateButton; public Button RecordButton; public bool AutomaticModeOn = true; public int defaultTransitionTime = 5; public Button SaveTextButton; private void Awake() { WaypointTimingButtonList = new Dictionary<int, VideoCaptureTimeButton>(); CloudStatesTimingButtonList = new Dictionary<int, VideoCaptureTimeButton>(); AutomaticTimingToggle.onValueChanged.AddListener(CheckToggle); ApplyTimingChangesButton.onClick.AddListener(TimingEditFinished); SetTimingButtonsActive(false); ApplyTimingChangesButton.interactable = false; RecordButton.onClick.AddListener(LaunchRecordingEvent); NewCloudStateButton.onClick.AddListener(LaunchAddCloudStateEvent); if (SaveTextButton) { SaveTextButton.onClick.AddListener(SaveTextFile); } if (CloseButton) { CloseButton.onClick.AddListener(DeleteSelf); } //DEBUG /** CreateTimeButton(0, 0); CreateTimeButton(1, 0); CreateTimeButton(2, 0); CreateTimeButton(3, 0); **/ } public delegate void OnDeleteEvent(); public event OnDeleteEvent OnDelete; private void DeleteSelf() { if (OnDelete != null) { OnDelete(); } Destroy(this.gameObject); } //Toggle Auto and Manual Modes public delegate void OnRecordStartEvent(); public event OnRecordStartEvent OnRecordStart; private void LaunchRecordingEvent() { if(OnRecordStart != null) { OnRecordStart(); } } public delegate void OnSaveTextFileEvent(); public event OnSaveTextFileEvent OnSaveTextFile; private void SaveTextFile() { if (OnSaveTextFile != null) { OnSaveTextFile(); } } private void CheckToggle(bool value) { if(value == true) { //SWITCH TO AUTOMATIC MODE SetTimingButtonsActive(false); int index = 0; foreach (KeyValuePair<int, VideoCaptureTimeButton> kvp in WaypointTimingButtonList) { kvp.Value.SetTime(index * defaultTransitionTime); index++; } ApplyTimingChangesButton.interactable = false; TimingEditFinished(); AutomaticModeOn = true; } else { //SWITCH TO MANUAL MODE SetTimingButtonsActive(true); ApplyTimingChangesButton.interactable = true; AutomaticModeOn = true; } } public void ChangeDurationText(int newDuration) { DurationText.text = "Duration : " + newDuration + " s"; } //TimingButtons public void CreateTimeButton(int id, int Time) { GameObject go = Instantiate(TimingButtonPrefab) as GameObject; go.transform.SetParent(WaypointsTimingButtonsContainer.transform, false); VideoCaptureTimeButton t = go.GetComponent<VideoCaptureTimeButton>(); WaypointTimingButtonList.Add(id,t); t.SetID(id); t.SetTime(Time); t.OnDelete += DeleteWaypointTiming; UpdateDuration(); if (AutomaticModeOn) { t.DeactivateButtons(); } } private void UpdateDuration() { int durationmax = 0; foreach (KeyValuePair <int,VideoCaptureTimeButton> t in WaypointTimingButtonList) { if(durationmax < t.Value.Time) { durationmax = t.Value.Time; } } ChangeDurationText(durationmax); } public delegate void OnTimingEditEvent(); public event OnTimingEditEvent OnTimingEdit; private void TimingEditFinished() { UpdateDuration(); if(OnTimingEdit != null) { OnTimingEdit(); } } private void SetTimingButtonsActive(bool value) { if (value == true) { foreach(KeyValuePair<int, VideoCaptureTimeButton> kvp in WaypointTimingButtonList) { kvp.Value.ActivateButtons(); } foreach (KeyValuePair<int, VideoCaptureTimeButton> kvp in CloudStatesTimingButtonList) { kvp.Value.ActivateButtons(); } } else { foreach (KeyValuePair<int, VideoCaptureTimeButton> kvp in CloudStatesTimingButtonList) { kvp.Value.DeactivateButtons(); } foreach (KeyValuePair<int, VideoCaptureTimeButton> kvp in CloudStatesTimingButtonList) { kvp.Value.DeactivateButtons(); } } } public List<CameraWaypoint> GetWaypointTimingInfo() { List<CameraWaypoint> list = new List<CameraWaypoint>(); foreach (KeyValuePair<int, VideoCaptureTimeButton> t in WaypointTimingButtonList) { list.Add(new CameraWaypoint(t.Value.ID, t.Value.Time)); } return list; } public List<CloudStateInTime> GetCloudStateTimingInfo() { List<CloudStateInTime> list = new List<CloudStateInTime>(); foreach (KeyValuePair<int, VideoCaptureTimeButton> t in CloudStatesTimingButtonList) { list.Add(new CloudStateInTime(t.Value.ID, t.Value.Time, null, 0f, Vector3.zero, Vector3.zero, null)); } return list; } public delegate void OnAddCloudStateEvent(); public event OnAddCloudStateEvent OnAddCloudState; private void LaunchAddCloudStateEvent() { if (OnAddCloudState != null) { OnAddCloudState(); } } public void CreateCloudStateTimingButton(int id, int Time) { GameObject go = Instantiate(TimingButtonPrefab) as GameObject; go.transform.SetParent(CloudStatesTimingButtonsContainer.transform, false); VideoCaptureTimeButton t = go.GetComponent<VideoCaptureTimeButton>(); CloudStatesTimingButtonList.Add(id, t); t.SetID(id); t.SetTime(Time); t.OnDelete += DeleteCloudStateTiming; UpdateDuration(); if (AutomaticModeOn) { t.DeactivateButtons(); } } public delegate void OnWaypointDeletedEvent(int id); public event OnWaypointDeletedEvent OnWaypointDeleted; private void DeleteWaypointTiming(int id) { //WaypointTimingButtonList[id].OnDelete -= DeleteWaypointTiming; Destroy(WaypointTimingButtonList[id].gameObject); WaypointTimingButtonList.Remove(id); if (OnWaypointDeleted != null) { OnWaypointDeleted(id); } } public delegate void OnCloudStateDeletedEvent(int id); public event OnCloudStateDeletedEvent OnCloudStateDeleted; private void DeleteCloudStateTiming(int id) { CloudStatesTimingButtonList[id].OnDelete -= DeleteCloudStateTiming; Destroy(CloudStatesTimingButtonList[id].gameObject); CloudStatesTimingButtonList.Remove(id); if (OnCloudStateDeleted != null) { OnCloudStateDeleted(id); } } } }
namespace Framework.Core.Helpers.Data { public enum Browser { Firefox, Chrome, InternetExplorer, Default, } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IPCrawler { public class IPData { public string status { get; set; } public string country { get; set; } public string regionName { get; set; } public string city { get; set; } public string zip { get; set; } public float lat { get; set; } public float lon { get; set; } public string isp { get; set; } public string query { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StardewValley; using StardewModdingAPI; using StardewModdingAPI.Events; using StardewModdingAPI.Framework; using StardewModdingAPI.Utilities; namespace AnomalyTracker { class ModEntry : Mod { public override void Entry(IModHelper helper) { helper.Events.GameLoop.UpdateTicked += this.GameLoopUpdateTicked; helper.Events.GameLoop.DayStarted += this.GameLoopDayStarted; } private void GameLoopDayStarted(object sender, DayStartedEventArgs) { this.Monitor.Log("Day started"); } private void GameLoopUpdateTicked(object sender, UpdateTickedEventArgs e) { } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; #if UNITY_EDITOR using UnityEditor; #endif namespace BanSupport { /// <summary> /// 这个东西定义了基本的排列方式 /// </summary> [ExecuteAlways] public class ScrollLayout : MonoBehaviour { public NewLine newLine = NewLine.None; public enum NewLine { None,//不启用新行 Center,//居中 LeftOrUp,//贴着左边或者下边 RightOrDown,//贴着右边或者上边 }; private void Awake() { Init(); } protected virtual void Init() { } public virtual float GetHeightByStr(string str) { return 0; } #if UNITY_EDITOR private NewLine oldNewLine = NewLine.None; private float oldWidth; private float oldHeight; private void Start() { if (Application.isPlaying) { return; } var rectTransform = this.transform as RectTransform; oldWidth = rectTransform.sizeDelta.x; oldHeight = rectTransform.sizeDelta.y; } private void Update() { if (Application.isPlaying) { return; } var changed = false; if (oldNewLine != newLine) { oldNewLine = newLine; changed = true; } var rectTransform = this.transform as RectTransform; if (oldWidth != rectTransform.sizeDelta.x) { oldWidth = rectTransform.sizeDelta.x; changed = true; } if (oldHeight != rectTransform.sizeDelta.y) { oldHeight = rectTransform.sizeDelta.y; changed = true; } if (changed) { ResetScrollSystem(); } } private void OnDrawGizmos() { if (Application.isPlaying) { return; } if (Selection.transforms.Contains(this.transform) || Selection.transforms.Contains(temp => temp.IsChildOf(this.transform))) { var rectTransform = this.transform as RectTransform; var size = new Vector3(this.transform.lossyScale.x * rectTransform.sizeDelta.x, this.transform.lossyScale.y * rectTransform.sizeDelta.y, 0); Gizmos.color = new Color(0, 1, 0, 0.2f); Gizmos.DrawCube(this.transform.position, size); } } private void ResetScrollSystem() { var scrollSystem = this.gameObject.GetComponentInParent<ScrollSystem>(); if (scrollSystem != null) { scrollSystem.SetContent(); } } #endif } }
using System; namespace ContestsPortal.Domain.Models { public class Feedback { public int FeedbackId { get; set; } public string FeedbackContent { get; set; } public DateTime PublicationDate { get; set; } public string ReferredEmail { get; set; } public int IdFeedbackType { get; set; } public int? IdUserProfile { get; set; } public virtual UserProfile UserProfile { get; set; } public virtual FeedbackType FeedbackType { get; set; } } }
using System; using System.Collections.ObjectModel; using System.Globalization; using System.Threading.Tasks; using System.Windows; using Microsoft.Practices.ServiceLocation; using SpatialEye.Framework.Client; using SpatialEye.Framework.Geometry; using SpatialEye.Framework.Geometry.Services; using SpatialEye.Framework.Redlining; using Lite.Resources.Localization; namespace Lite { /// <summary> /// THe map popup menu view model /// </summary> public class LiteMapPopupMenuViewModel : ViewModelBase { #region Event Tracker /// <summary> /// The event tracker /// </summary> internal class MapPopupMenuEventTracker : MapEventTracker { /// <summary> /// Constructor for the event tracker /// </summary> internal MapPopupMenuEventTracker(LiteMapPopupMenuViewModel owner) { Owner = owner; } /// <summary> /// The owner /// </summary> private LiteMapPopupMenuViewModel Owner { get; set; } /// <summary> /// Is this element active /// </summary> internal bool IsActive { get; set; } /// <summary> /// On mouse move handler /// </summary> protected override void OnMouseMove(MapViewModel sender, MapMouseEventArgs args) { if (IsActive) { Owner.ClosePopupMenu(); } } /// <summary> /// On mouse rmc handler /// </summary> protected override void OnMouseRightButtonDown(MapViewModel sender, MapMouseEventArgs args) { Owner.OpenPopupMenu(args); } } #endregion #region Property Names /// <summary> /// The popup menu visibility /// </summary> public const string PopupMenuVisibilityPropertyName = "PopupMenuVisibility"; /// <summary> /// The popup x indent /// </summary> public const string PopupMenuIndentXPropertyName = "PopupMenuIndentX"; /// <summary> /// The popup y indent /// </summary> public const string PopupMenuIndentYPropertyName = "PopupMenuIndentY"; #endregion #region Fields /// <summary> /// The active event tracker /// </summary> private MapPopupMenuEventTracker _activeEventTracker; /// <summary> /// The active map view model /// </summary> private LiteMapViewModel _currentMapViewModel; /// <summary> /// The popup menu visibility /// </summary> private Visibility _popupMenuVisibility = Visibility.Collapsed; /// <summary> /// The indentation of the popup /// </summary> private GridLength _popupMenuIndentX; /// <summary> /// The indentation of the popup /// </summary> private GridLength _popupMenuIndentY; /// <summary> /// Menu items holder /// </summary> private ObservableCollection<LiteMenuCategoryViewModel> _menuItems; /// <summary> /// Is editability enabled (authorized) /// </summary> private Boolean _editabilityEnabled; #endregion #region Constructor /// <summary> /// Constructs the popup menu view model /// </summary> public LiteMapPopupMenuViewModel(Messenger messenger = null) : base(messenger) { AttachToMessenger(); SetupMenuCommands(); Resources = new Lite.Resources.Localization.ApplicationResources(); } /// <summary> /// Attach to the messenger /// </summary> private void AttachToMessenger() { Messenger.Register<PropertyChangedMessage<LiteMapViewModel>>(this, (m) => this.MapViewModel = m.NewValue); } #endregion #region Menu & Commands /// <summary> /// Set up the menu commands /// </summary> private void SetupMenuCommands() { // Setup the menu items var items = new ObservableCollection<LiteMenuCategoryViewModel>(); // Setup the clipboard actions { var cat = new LiteMenuCategoryViewModel { Title = "Clipboard", BorderVisibility = Visibility.Collapsed }; cat.Items.Add(new LiteMenuItemViewModel(ApplicationResources.MapPopupCopyCoordinateToClipboard, "MetroIcon.Content.Clipboard") { Command = new RelayCommand(CopyMouseCoordinateToClipboard) }); items.Add(cat); } // Setup the selection actions { var cat = new LiteMenuCategoryViewModel { Title = "Selection", BorderVisibility = Visibility.Visible }; cat.Items.Add(new LiteMenuItemViewModel(ApplicationResources.MapPopupGotoSelection, "MetroIcon.Content.GotoSelection") { Command = new RelayCommand(GoToSelection, HasSelection) }); cat.Items.Add(new LiteMenuItemViewModel(ApplicationResources.MapPopupClearSelection, "MetroIcon.Content.ClearSelection") { Command = new RelayCommand(ClearSelection, HasSelection) }); cat.Items.Add(new LiteMenuItemViewModel(ApplicationResources.MapPopupEditGeometrySelection, "MetroIcon.Content.EditSelection") { Command = new RelayCommand(EditSelectedGeometry), VisibilityPredicate = HasEditableGeometrySelection }); items.Add(cat); } // Setup the trail actions { var cat = new LiteMenuCategoryViewModel { Title = "Trail", BorderVisibility = Visibility.Visible }; cat.Items.Add(new LiteMenuItemViewModel(ApplicationResources.MapPopupCreateTrailFromSelection, "MetroIcon.Content.Trail") { Command = new RelayCommand(CreateTrailFromSelection, HasSelectionForTrailCreation) }); cat.Items.Add(new LiteMenuItemViewModel(ApplicationResources.MapPopupRemoveTrail, "MetroIcon.Content.TrailClear") { Command = new RelayCommand(RemoveSelectedTrail, HasTrailSelection) }); items.Add(cat); } // Setup the object properties actions { var cat = new LiteMenuCategoryViewModel { Title = "Properties", BorderVisibility = Visibility.Visible }; cat.Items.Add(new LiteMenuItemViewModel(ApplicationResources.MapPopupObjectProperties, "MetroIcon.Content.Details") { Command = new RelayCommand(DisplayObjectProperties, HasSelection) }); items.Add(cat); } // Set the new menu MenuItems = items; } /// <summary> /// Check the commands /// </summary> private void CheckMenuItemStates() { // Have the menu items check their states foreach (var item in MenuItems) { item.CheckStates(); } } /// <summary> /// Copy the mouse coordinate to clipboard /// </summary> private void CopyMouseCoordinateToClipboard() { // Close the popup menu ClosePopupMenu(); // Close the popup menu Clipboard.SetText(this.MouseClipboardText); } /// <summary> /// Go To selection /// </summary> private void GoToSelection() { var mapView = MapViewModel; ClosePopupMenu(); if (mapView != null && mapView.SelectedFeatures.Count > 0) { // There is a feature var feature = mapView.SelectedFeatures[0]; // Pick up the feature's envelope var envelope = feature.GetEnvelope(); if (envelope != null) { // Request a go-to envelope and put it on the messenger Messenger.Send(new LiteGoToGeometryRequestMessage(mapView, envelope, feature)); } } } /// <summary> /// Clear the selection /// </summary> private void ClearSelection() { var mapView = MapViewModel; ClosePopupMenu(); if (mapView != null) { mapView.ClearSelection(); } } /// <summary> /// Edit the selected geometry /// </summary> private void EditSelectedGeometry() { var mapView = MapViewModel; ClosePopupMenu(); if (mapView != null && mapView.SelectedFeatureGeometry.Count > 0) { // There is a feature var featureGeometry = mapView.SelectedFeatureGeometry[0]; // Request to display the feature Messenger.Send(new LiteDisplayFeatureDetailsRequestMessage(this, featureGeometry.Feature, featureGeometry.TargetGeometryFieldDescriptor, makeViewActive: true, startEditing: true)); } } /// <summary> /// Display the object properties for the selected element /// </summary> private void DisplayObjectProperties() { var mapView = MapViewModel; ClosePopupMenu(); if (mapView != null && mapView.SelectedFeatureGeometry.Count > 0) { // There is a feature var featureGeometry = mapView.SelectedFeatureGeometry[0]; // Request to display the feature Messenger.Send(new LiteDisplayFeatureDetailsRequestMessage(this, featureGeometry.Feature, featureGeometry.TargetGeometryFieldDescriptor, makeViewActive: true)); } } /// <summary> /// Create a trail from the selection /// </summary> private void CreateTrailFromSelection() { var mapView = MapViewModel; ClosePopupMenu(); if (mapView != null) { var trailLayer = mapView.TrailLayer; var selectedElement = mapView.SelectedFeatureGeometry.Count > 0 ? mapView.SelectedFeatureGeometry[0] : null; if (selectedElement != null && selectedElement.Feature.TableDescriptor.Name != SpatialEye.Framework.Client.MapViewModel.TrailTableDescriptorName) { var redliningElement = RedliningElement.ElementFor(selectedElement.TargetGeometry); if (redliningElement != null) { trailLayer.Drawing.Add(redliningElement); trailLayer.DrawingSelection.Set(redliningElement); } } } } /// <summary> /// Clear the trail /// </summary> private void RemoveSelectedTrail() { var mapView = MapViewModel; ClosePopupMenu(); if (mapView != null) { mapView.TrailLayer.Drawing.Remove(mapView.TrailLayer.DrawingSelection, true); mapView.TrailLayer.DrawingSelection.Clear(); ClearSelection(); } } /// <summary> /// Do we have a selection /// </summary> private bool HasSelection() { return MapViewModel != null && MapViewModel.SelectedFeatureGeometry != null && MapViewModel.SelectedFeatureGeometry.Count > 0; } /// <summary> /// Returns a flag indicating whether there is editable geometry selected /// </summary> private bool HasEditableGeometrySelection() { var hasEditableGeometrySelection = false; if (MapViewModel != null && EditabilityEnabled) { var selection = MapViewModel.SelectedFeatureGeometry; // Check whether the selected geometry field is editable hasEditableGeometrySelection = selection != null && selection.Count == 1 && selection[0].TargetGeometryFieldDescriptor.EditabilityProperties.AllowUpdate; } return hasEditableGeometrySelection; } /// <summary> /// Do we have a selection /// </summary> private bool HasSelectionForTrailCreation() { var hasSelection = false; if (MapViewModel != null && MapViewModel.SelectedFeatureGeometry != null && MapViewModel.SelectedFeatureGeometry.Count > 0) { var feature = MapViewModel.SelectedFeatureGeometry[0].Feature; if (feature != null && feature.TableDescriptor.Name != SpatialEye.Framework.Client.MapViewModel.TrailTableDescriptorName) { hasSelection = true; } } return hasSelection; } /// <summary> /// Do we have a trail /// </summary> /// <returns></returns> private bool HasTrailSelection() { var hasSelection = false; if (MapViewModel != null && MapViewModel.SelectedFeatureGeometry != null && MapViewModel.SelectedFeatureGeometry.Count > 0) { var feature = MapViewModel.SelectedFeatureGeometry[0].Feature; if (feature != null && feature.TableDescriptor.Name == SpatialEye.Framework.Client.MapViewModel.TrailTableDescriptorName) { hasSelection = true; } } return hasSelection; } #endregion #region Overrides /// <summary> /// Callback when the culture changes /// </summary> /// <param name="currentCultureInfo">the current culture info</param> protected override void OnCurrentCultureChanged(System.Globalization.CultureInfo currentCultureInfo) { SetupMenuCommands(); } /// <summary> /// Authentication changed callback /// </summary> protected override void OnAuthenticationChanged(SpatialEye.Framework.Authentication.AuthenticationContext context, bool isAuthenticated) { base.OnAuthenticationChanged(context, isAuthenticated); if (isAuthenticated) { // Set the authorized options EditabilityEnabled = LiteClientSettingsViewModel.Instance.AllowGeoNoteEdits; } } #endregion #region Event Tracker /// <summary> /// Attach an event tracker to the current map view model /// </summary> private void AttachMap() { var mapViewModel = MapViewModel; if (mapViewModel != null) { _activeEventTracker = new MapPopupMenuEventTracker(this); mapViewModel.InteractionHandler.EventTrackers.Add(_activeEventTracker); mapViewModel.PropertyChanged += MapViewModelPropertyChanged; mapViewModel.TrailLayer.Drawing.ContentsChanged += TrailLayerContentChanged; } } /// <summary> /// Detach the active map event tracker /// </summary> private void DetachMap() { var tracker = _activeEventTracker; var mapViewModel = MapViewModel; _activeEventTracker = null; if (tracker != null && mapViewModel != null) { mapViewModel.InteractionHandler.EventTrackers.Remove(tracker); mapViewModel.PropertyChanged -= MapViewModelPropertyChanged; mapViewModel.TrailLayer.Drawing.ContentsChanged -= TrailLayerContentChanged; } } /// <summary> /// Check the commands whenever appropriate properties change /// </summary> void MapViewModelPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (e.PropertyName == SpatialEye.Framework.Client.MapViewModel.SelectedFeatureGeometryPropertyName) { CheckMenuItemStates(); } } /// <summary> /// The trail content has changed /// </summary> /// <param name="model"></param> /// <param name="args"></param> void TrailLayerContentChanged(GeometryModel<RedliningElement> model, GeometryModel<RedliningElement>.ContentsChangedEventArgs args) { CheckMenuItemStates(); } #endregion #region Properties /// <summary> /// The current map view model /// </summary> public LiteMapViewModel MapViewModel { get { return _currentMapViewModel; } private set { if (_currentMapViewModel != value) { DetachMap(); _currentMapViewModel = value; AttachMap(); } } } /// <summary> /// Is editability enabled (authorized) /// </summary> public Boolean EditabilityEnabled { get { return _editabilityEnabled; } set { if (value != _editabilityEnabled) { _editabilityEnabled = value; RaisePropertyChanged(); CheckMenuItemStates(); } } } /// <summary> /// The clipboard text /// </summary> private string MouseClipboardText { get; set; } /// <summary> /// The visibility of the popup menu /// </summary> public Visibility PopupMenuVisibility { get { return _popupMenuVisibility; } set { if (_popupMenuVisibility != value) { _popupMenuVisibility = value; RaisePropertyChanged(PopupMenuVisibilityPropertyName); if (_activeEventTracker != null) { _activeEventTracker.IsActive = _popupMenuVisibility == Visibility.Visible; } } } } /// <summary> /// The X ident of the popup /// </summary> public GridLength PopupMenuIndentX { get { return _popupMenuIndentX; } set { if (_popupMenuIndentX != value) { _popupMenuIndentX = value; RaisePropertyChanged(PopupMenuIndentXPropertyName); } } } /// <summary> /// The Y ident of the popup /// </summary> public GridLength PopupMenuIndentY { get { return _popupMenuIndentY; } set { if (_popupMenuIndentY != value) { _popupMenuIndentY = value; RaisePropertyChanged(PopupMenuIndentYPropertyName); } } } /// <summary> /// Gets or sets the menu items /// </summary> public ObservableCollection<LiteMenuCategoryViewModel> MenuItems { get { return _menuItems; } private set { _menuItems = value; RaisePropertyChanged(); } } #endregion #region Popup Menu handling /// <summary> /// Indicates a Right Mouse click at the specified position /// </summary> public async Task SetupMouseDescription(MapMouseEventArgs args) { // Set up coordinates in pixel and world space // Transform to WGS84 var geomService = ServiceLocator.Current.GetInstance<IGeometryService>(); // Get the epsg-code to transform the selected coordinate to var clipboardCS = MapViewModel.SelectedEpsgCoordinateSystem ?? LiteMapViewModel.DefaultEpsgCoordinateSystem; // Transform the coordinate to the selected display cs var clipboardCoordinate = await geomService.TransformAsync(args.Location.Coordinate, 3785, clipboardCS.SRId); var mouseClipboardText = string.Empty; var clipboardX = clipboardCoordinate.X.ToString(NumberFormatInfo.InvariantInfo); var clipboardY = clipboardCoordinate.Y.ToString(NumberFormatInfo.InvariantInfo); if (clipboardCS.SRId == 4326) { // Do something special for WGS84 mouseClipboardText = string.Format("{0} ({1}, {2})", CoordinateSystem.CoordinateToDmsString(clipboardCoordinate), clipboardY, clipboardX); } else { // Default clipboard text mouseClipboardText = string.Format("{0}, {1}", clipboardX, clipboardY); } // Set the clipboard text MouseClipboardText = mouseClipboardText; } /// <summary> /// Open the popup menu /// </summary> internal async void OpenPopupMenu(MapMouseEventArgs args) { // Setup the mouse description await SetupMouseDescription(args); PopupMenuIndentX = new GridLength(args.X - 10); PopupMenuIndentY = new GridLength(args.Y - 10); PopupMenuVisibility = Visibility.Visible; } /// <summary> /// Close the popup menu /// </summary> internal void ClosePopupMenu() { PopupMenuVisibility = Visibility.Collapsed; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; namespace Problem_3._Periodic_Table { class Program { static void Main(string[] args) { var rows = int.Parse(Console.ReadLine()); var elements = new HashSet<string>(); for (int i = 0; i < rows; i++) { var inputEle = Console.ReadLine().Split(); foreach (var item in inputEle) { elements.Add(item); } } Console.WriteLine(String.Join(" ",elements.OrderBy(x => x))); } } }
using StardewValley; using StardewModdingAPI; using TwilightShards.Stardew.Common; using TwilightShards.Common; using System; using System.Collections.Generic; using System.Linq; using StardewValley.Locations; using StardewValley.Objects; namespace TwilightShards.WeatherIllnesses { internal enum IllCauses { None, TooColdOutside, TooHotOutside, TooColdInside, InclementWeather, BlizzardsOutside, TheWampaWillGetYou, NonspecificSevereWeather } internal class StaminaDrain { private IllnessConfig IllOptions; private ITranslationHelper Helper; private bool FarmerSick; private bool turnTheHeatOn; private IllCauses ReasonSick ; public bool FarmerHasBeenSick; public bool IssuedInHouseWarning; private IMonitor Monitor; public static readonly int MedicineClear = 1; public static readonly int BathHouseClear = 2; public StaminaDrain(IllnessConfig Options, ITranslationHelper SHelper, IMonitor mon) { IllOptions = Options; Helper = SHelper; Monitor = mon; IssuedInHouseWarning = false; } public bool IsSick() { return this.FarmerSick; } public void MakeSick() { FarmerSick = true; FarmerHasBeenSick = true; switch (ReasonSick) { case IllCauses.InclementWeather: SDVUtilities.ShowMessage(Helper.Get("hud-text.desc_inclement"),4); break; case IllCauses.BlizzardsOutside: SDVUtilities.ShowMessage(Helper.Get("hud-text.desc_blizzard"),4); break; case IllCauses.NonspecificSevereWeather: SDVUtilities.ShowMessage(Helper.Get("hud-text.desc_flu"),4); break; case IllCauses.TheWampaWillGetYou: SDVUtilities.ShowMessage(Helper.Get("hud-text.desc_wampa"),4); break; case IllCauses.TooColdInside: SDVUtilities.ShowMessage(Helper.Get("hud-text.desc_turntheheaton"), 4); break; case IllCauses.TooColdOutside: SDVUtilities.ShowMessage(Helper.Get("hud-text.desc_cold"), 4); break; case IllCauses.TooHotOutside: SDVUtilities.ShowMessage(Helper.Get("hud-text.desc_hot"), 4); break; default: SDVUtilities.ShowMessage(Helper.Get("hud-text.desc_sick"),4); break; } } public void OnNewDay() { FarmerSick = false; ReasonSick = IllCauses.None; IssuedInHouseWarning = false; turnTheHeatOn = false; } public void ClearDrain(int reason = 1) { FarmerSick = false; if (reason == StaminaDrain.MedicineClear) { SDVUtilities.ShowMessage(Helper.Get("hud-text.desc_cold_removed"), 4); } else if (reason == StaminaDrain.BathHouseClear) { SDVUtilities.ShowMessage(Helper.Get("hud-text.desc_bathHouse"),4); } } public void Reset() { FarmerSick = false; IssuedInHouseWarning = false; turnTheHeatOn = false; } public bool FarmerCanGetSick() { if (FarmerSick && !IllOptions.SickMoreThanOnce) return false; if (!IllOptions.SickMoreThanOnce && FarmerHasBeenSick) return false; return true; } public int TenMinuteTick(int? hatID, double temp, string conditions,int ticksInHouse, int ticksOutside, int ticksTotal, MersenneTwister Dice) { double amtOutside = ticksOutside / (double)ticksTotal, totalMulti = 0; double amtInHouse = ticksInHouse / (double)ticksTotal; int staminaAffect = 0; var condList = new List<string>(); if (IllOptions.Verbose) { Monitor.Log($"Ticks: {ticksOutside}/{ticksTotal} with percentage {amtOutside}:N3 against target {IllOptions.PercentageOutside}"); Monitor.Log($"Ticks in house is {amtInHouse}:N3 against target {IllOptions.PercentageOutside}"); Monitor.Log($"Current Condition: {conditions}"); } //First, update the sick status bool farmerCaughtCold = false; double sickOdds = IllOptions.ChanceOfGettingSick - Game1.dailyLuck; //weee. if (hatID == 28 && (conditions.Contains("lightning") || conditions.Contains("stormy") || conditions.Contains("thundersnow"))) sickOdds -= (Dice.NextDoublePositive() / 5.0) - .1; if (hatID == 25 && conditions.Contains("blizzard") || conditions.Contains("whiteout")) sickOdds -= .22; if (hatID == 4 && conditions.Contains("heatwave") && !SDVTime.IsNight) sickOdds -= .11; farmerCaughtCold = (Dice.NextDoublePositive() <= sickOdds) && (IllOptions.StaminaDrain > 0); FarmHouse fh = Game1.getLocationFromName("FarmHouse") as FarmHouse; bool isHeaterHere = false; foreach (var v in fh.objects.Pairs) { if (v.Value.Name.Contains("Heater")) { if (IllOptions.Verbose) Monitor.Log("Heater detected"); isHeaterHere = true; } } foreach (var v in fh.furniture) { if (v.furniture_type.Value == Furniture.fireplace && v.IsOn) { if (IllOptions.Verbose) Monitor.Log("fireplace detected"); isHeaterHere = true; } } turnTheHeatOn = (turnTheHeatOn || (amtInHouse >= IllOptions.PercentageOutside && farmerCaughtCold && temp < IllOptions.TooColdInside && !isHeaterHere && IssuedInHouseWarning && (Game1.timeOfDay < 1000 || Game1.timeOfDay > 1650))); if (!IssuedInHouseWarning && amtInHouse >= IllOptions.PercentageOutside && temp < IllOptions.TooColdInside && (Game1.timeOfDay < 1000 || Game1.timeOfDay > 1650) && !Game1.currentLocation.IsOutdoors && !isHeaterHere) { SDVUtilities.ShowMessage(Helper.Get("hud-text.desc_HeatOn"),4); IssuedInHouseWarning = true; } if (amtOutside >= IllOptions.PercentageOutside && farmerCaughtCold || this.FarmerSick || turnTheHeatOn) { //check if it's a valid condition if (FarmerCanGetSick()) { //rewrite time.. if (conditions.Contains("blizzard") || conditions.Contains("whiteout") || (conditions.Contains("lightning") || conditions.Contains("stormy") || conditions.Contains("thundersnow")) && !(Game1.currentLocation is Desert) || (conditions.Contains("frost") && SDVTime.IsNight) || (conditions.Contains("heatwave") && !SDVTime.IsNight) || turnTheHeatOn) { if (turnTheHeatOn) ReasonSick = IllCauses.TooColdInside; else if ((conditions.Contains("heatwave") && !SDVTime.IsNight)) ReasonSick = IllCauses.TooHotOutside; else if (conditions.Contains("frost") && SDVTime.IsNight) ReasonSick = IllCauses.TooColdOutside; else if (condList.Contains("blizzard")) ReasonSick = IllCauses.BlizzardsOutside; else if (condList.Contains("whiteout")) ReasonSick = IllCauses.TheWampaWillGetYou; else if (conditions.Contains("lightning") || conditions.Contains("stormy")) ReasonSick = IllCauses.InclementWeather; else ReasonSick = IllCauses.NonspecificSevereWeather; this.MakeSick(); } } //now that we've done that, go through the various conditions if (this.FarmerSick && (conditions.Contains("lightning") || conditions.Contains("stormy") || conditions.Contains("thundersnow"))) { totalMulti += 1; condList.Add("Lightning or Thundersnow"); } if (this.FarmerSick && conditions.Contains("fog")) { totalMulti += .5; condList.Add("Fog"); } if (this.FarmerSick && conditions.Contains("fog") && SDVTime.IsNight) { totalMulti += .25; condList.Add("Night Fog"); } if (this.FarmerSick && conditions.Contains("blizzard") && !conditions.Contains("whiteout")) { totalMulti += 1.25; condList.Add("Blizzard"); } if (this.FarmerSick && conditions.Contains("blizzard") && conditions.Contains("whiteout")) { totalMulti += 2.45; condList.Add("White Out"); } if (this.FarmerSick && conditions.Contains("thunderfrenzy")) { totalMulti += 1.85; condList.Add("Thunder Frenzy"); } if (this.FarmerSick && conditions.Contains("frost") && SDVTime.IsNight) { totalMulti += 1.25; condList.Add("Night Frost"); } if (this.FarmerSick && turnTheHeatOn) { totalMulti += 1; condList.Add("Cold House"); } if (this.FarmerSick && conditions.Contains("thundersnow") && SDVTime.IsNight) { totalMulti += .5; condList.Add("Night Thundersnow"); } if (this.FarmerSick && conditions.Contains("blizzard") && SDVTime.IsNight) { totalMulti += .5; condList.Add("Night Blizzard"); } if (this.FarmerSick && conditions.Contains("heatwave") && !SDVTime.IsNight) { totalMulti += 1.25; condList.Add("Day Heatwave"); } } staminaAffect -= (int)Math.Floor(IllOptions.StaminaDrain * totalMulti); if (IllOptions.Verbose && this.FarmerSick) { string condString = "[ "; for (int i = 0; i < condList.Count; i++) { if (i != condList.Count - 1) { condString += condList[i] + ", "; } else { condString += condList[i]; } } condString += " ]"; Monitor.Log($"[{Game1.timeOfDay}] Conditions for the drain are {condString} for a total multipler of {totalMulti} for a total drain of {staminaAffect}"); } return staminaAffect; } } }
using System; namespace ApartmentApps.Api.Modules { public static class DateTimeExtensions { public static DateTime Offset(this DateTime source, int days, int months, int years) { return source.AddYears(years).AddMonths(months).AddDays(days); } public static DateTime ToCorrectedDateTime(this DateTime source) { var lastDay = DateTime.DaysInMonth(source.Year, source.Month); var dif = source.Day - lastDay; if (dif > 0) { return source.Subtract(TimeSpan.FromDays(dif)); } return source; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ManageDomain { public enum COMMANDTYPE { /// <summary> /// 发布项目 /// </summary> [Description("publishapp")] PUBLISHAPP, /// <summary> /// 备份项目 /// </summary> [Description("backupapp")] BACKUPAPP, /// <summary> /// 回退项目 /// </summary> [Description("rollbackapp")] ROLLBACKAPP, /// <summary> /// 更新配置 /// </summary> [Description("updateconfig")] UPDATECONFIG, /// <summary> /// CMD /// </summary> [Description("cmd")] CMD, /// <summary> /// 运行任务 /// </summary> [Description("starttask")] STARTTASK, /// <summary> /// 停止任务 /// </summary> [Description("stoptask")] STOPTASK, /// <summary> /// 卸载任务 /// </summary> [Description("deletetask")] DELETETASK, } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Teste.Application.Service; using Teste.Application.ViewModel; namespace Teste.Api.Controllers { [ApiController] [Route("[controller]")] public class CadastroTesteController : ControllerBase { private readonly ILogger<CadastroTesteController> _logger; private readonly ICadastroTesteService _cadastroTesteService; public CadastroTesteController(ILogger<CadastroTesteController> logger, ICadastroTesteService cadastroTesteService) { _logger = logger; _cadastroTesteService = cadastroTesteService; } [HttpGet] public async Task<IEnumerable<CadastroTesteVM>> GetAll() { return await _cadastroTesteService.GetAll(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GSVM.Constructs.DataTypes; using GSVM.Components.Coprocessors; namespace GSVM.Constructs.FastDataTypes { public class int8_t : Integral<sbyte> { public int8_t() : this(0) { } public int8_t(sbyte value, uint address) { this.value = value; ptr = new SmartPointer(address, 1); } public int8_t(sbyte value) : this(value, 0) { } public int8_t(byte[] value) : this() { FromBinary(value); } public override byte[] ToBinary() { unchecked { return new byte[] { (byte)value }; } } public override void FromBinary(byte[] value) { if (value.Length > Pointer.Length) throw new IndexOutOfRangeException(); unchecked { Value = (sbyte)value[0]; } } public static implicit operator sbyte(int8_t value) { return value.Value; } public static implicit operator int8_t(sbyte value) { return new int8_t(value); } } public class uint8_t : Integral<byte> { public uint8_t() : this(0) { } public uint8_t(byte value, uint address) { this.value = value; ptr = new SmartPointer(address, 1); } public uint8_t(byte value) : this(value, 0) { } public uint8_t(byte[] value) : this() { FromBinary(value); } public override byte[] ToBinary() { return new byte[] { value }; } public override void FromBinary(byte[] value) { if (value.Length > Pointer.Length) throw new IndexOutOfRangeException(); this.value = value[0]; } public static implicit operator byte(uint8_t value) { return value.Value; } public static implicit operator uint8_t(byte value) { return new uint8_t(value); } } public class int16_t : Integral<Int16> { public int16_t() : this(0) { } public int16_t(Int16 value, uint address) { this.value = value; ptr = new SmartPointer(address, 2); } public int16_t(Int16 value) : this(value, 0) { } public int16_t(byte[] value) : this() { FromBinary(value); } public override byte[] ToBinary() { return BitConverter.GetBytes(value); } public override void FromBinary(byte[] value) { if (value.Length > Pointer.Length) throw new IndexOutOfRangeException(); byte[] val = new byte[Pointer.Length]; Array.Copy(value, val, value.Length); this.value = FastBitConverter.ToInt16(val, 0); } public static implicit operator Int16(int16_t value) { return value.Value; } public static implicit operator int16_t(Int16 value) { return new int16_t(value); } } public class uint16_t : Integral<UInt16> { public uint16_t() : this(0) { } public uint16_t(UInt16 value, uint address) { this.value = value; ptr = new SmartPointer(address, 2); } public uint16_t(UInt16 value) : this(value, 0) { } public uint16_t(uint address) : this(0, address) { } public uint16_t(byte[] value) : this() { FromBinary(value); } public override byte[] ToBinary() { return BitConverter.GetBytes(value); } public override void FromBinary(byte[] value) { if (value.Length > Pointer.Length) throw new IndexOutOfRangeException(); byte[] val = new byte[Pointer.Length]; Array.Copy(value, val, value.Length); this.value = FastBitConverter.ToUInt16(val, 0); } public static implicit operator UInt16(uint16_t value) { return value.Value; } public static implicit operator uint16_t(UInt16 value) { return new uint16_t(value); } } public class int32_t : Integral<Int32> { public int32_t() : this(0) { } public int32_t(Int32 value, uint address) { this.value = value; ptr = new SmartPointer(address, 4); } public int32_t(Int32 value) : this(value, 0) { } public int32_t(uint address) : this(0, address) { } public int32_t(byte[] value) : this() { FromBinary(value); } public override byte[] ToBinary() { return BitConverter.GetBytes(value); } public override void FromBinary(byte[] value) { if (value.Length > Pointer.Length) throw new IndexOutOfRangeException(); byte[] val = new byte[Pointer.Length]; Array.Copy(value, val, value.Length); this.value = FastBitConverter.ToInt32(val, 0); } public static implicit operator Int32(int32_t value) { return value.Value; } public static implicit operator int32_t(Int32 value) { return new int32_t(value); } } public class uint32_t : Integral<UInt32> { public uint32_t() : this(0) { } public uint32_t(UInt32 value, uint address) { this.value = value; ptr = new SmartPointer(address, 4); } public uint32_t(UInt32 value) : this(value, 0) { } public uint32_t(byte[] value) : this() { FromBinary(value); } public override byte[] ToBinary() { return BitConverter.GetBytes(value); } public override void FromBinary(byte[] value) { if (value.Length > Pointer.Length) throw new IndexOutOfRangeException(); byte[] val = new byte[Pointer.Length]; Array.Copy(value, val, value.Length); this.value = FastBitConverter.ToUInt32(val, 0); } public static implicit operator UInt32(uint32_t value) { return value.Value; } public static implicit operator uint32_t(UInt32 value) { return new uint32_t(value); } } public class int64_t : Integral<Int64> { public int64_t() : this(0) { } public int64_t(Int64 value, uint address) { this.value = value; ptr = new SmartPointer(address, 8); } public int64_t(Int64 value) : this(value, 0) { } public int64_t(uint address) : this(0, address) { } public int64_t(byte[] value) : this() { FromBinary(value); } public override byte[] ToBinary() { return BitConverter.GetBytes(value); } public override void FromBinary(byte[] value) { if (value.Length > Pointer.Length) throw new IndexOutOfRangeException(); byte[] val = new byte[Pointer.Length]; Array.Copy(value, val, value.Length); this.value = FastBitConverter.ToInt64(val, 0); } public static implicit operator Int64(int64_t value) { return value.Value; } public static implicit operator int64_t(Int64 value) { return new int64_t(value); } } public class uint64_t : Integral<UInt64> { public uint64_t() : this(0) { } public uint64_t(UInt64 value, uint address) { this.value = value; ptr = new SmartPointer(address, 8); } public uint64_t(UInt64 value) : this(value, 0) { } public uint64_t(uint address) : this(0, address) { } public uint64_t(byte[] value) : this() { FromBinary(value); } public override byte[] ToBinary() { return BitConverter.GetBytes(value); } public override void FromBinary(byte[] value) { if (value.Length > Pointer.Length) throw new IndexOutOfRangeException(); byte[] val = new byte[Pointer.Length]; Array.Copy(value, val, value.Length); this.value = FastBitConverter.ToUInt64(val, 0); } public static implicit operator UInt64(uint64_t value) { return value.Value; } public static implicit operator uint64_t(UInt64 value) { return new uint64_t(value); } } }
namespace WinAppDriver { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Security.Cryptography; internal interface IUtils { string ExpandEnvironmentVariables(string input); bool DirectoryExists(string path); void CopyDirectoryAndSecurity(string src, string dir); void CopyFileAndSecurity(string src, string dir); bool CreateDirectoryIfNotExists(string path); bool DeleteDirectoryIfExists(string path); string GetFileMD5(string filePath); string GetAppFileFromWeb(string webResource, string checksum); Process Execute(string command, IDictionary<string, string> envs); } internal class Utils : IUtils { private static ILogger logger = Logger.GetLogger("WinAppDriver"); public string ExpandEnvironmentVariables(string input) { return Environment.ExpandEnvironmentVariables(input); } public bool DirectoryExists(string path) { return Directory.Exists(path); } public void CopyDirectoryAndSecurity(string src, string dir) { var dest = Path.Combine(dir, Path.GetFileName(src)); logger.Debug("Copy directory (and security) from \"{0}\" to \"{1}\".", src, dest); this.DeleteDirectoryIfExists(dest); this.CreateDirectoryIfNotExists(dest); { var security = Directory.GetAccessControl(src); security.SetAccessRuleProtection(true, true); Directory.SetAccessControl(dest, security); } foreach (var file in Directory.GetFiles(src)) { this.CopyFileAndSecurity(file, dir); } foreach (var subdir in Directory.GetDirectories(src)) { this.CopyDirectoryAndSecurity(subdir, dest); } } public void CopyFileAndSecurity(string src, string dir) { var dest = Path.Combine(dir, Path.GetFileName(src)); logger.Debug("Copy file (and security) from \"{0}\" to \"{1}\".", src, dest); File.Copy(src, dest, true); var security = File.GetAccessControl(src); security.SetAccessRuleProtection(true, true); File.SetAccessControl(dest, security); } public bool CreateDirectoryIfNotExists(string path) { if (this.DirectoryExists(path)) { return false; } else { Directory.CreateDirectory(path); return true; } } public bool DeleteDirectoryIfExists(string path) { if (this.DirectoryExists(path)) { foreach (var subdir in Directory.GetDirectories(path)) { this.DeleteDirectoryIfExists(subdir); } foreach (var file in Directory.GetFiles(path)) { logger.Debug("Delete file: {0}", file); File.Delete(file); } logger.Debug("Delete directory: {0}", path); try { Directory.Delete(path); } catch (IOException e) { // Seems like a timing issue that the built-in Directory.Delete(path, true) // did not take into account. logger.Warn("IOException raised while deleting the directory: {0} ({1})", path, e.Message); logger.Debug("Sleep for a while (5s), and try again..."); System.Threading.Thread.Sleep(5000); Directory.Delete(path); } return true; } else { return false; } } public string GetFileMD5(string filePath) { MD5 md5 = new MD5CryptoServiceProvider(); FileStream zipFile = new FileStream(filePath, FileMode.Open); byte[] bytes = md5.ComputeHash(zipFile); zipFile.Close(); return BitConverter.ToString(bytes).Replace("-", string.Empty).ToLower(); } public string GetAppFileFromWeb(string webResource, string checksum) { string storeFileName = Environment.GetEnvironmentVariable("TEMP") + @"\StoreApp_" + DateTime.Now.ToString("yyyyMMddHHmmss") + webResource.Substring(webResource.LastIndexOf(".")); // Create a new WebClient instance. WebClient myWebClient = new WebClient(); logger.Info("Downloading file \"{0}\" .......", webResource); int retryCounter = 3; while (retryCounter > 0) { retryCounter--; // Download the Web resource and save it into temp folder. myWebClient.DownloadFile(webResource, storeFileName); string checksumActual = this.GetFileMD5(storeFileName); if (checksum != null && checksum != this.GetFileMD5(storeFileName)) { if (retryCounter == 0) { string msg = "You got a wrong file. Expected checksum is \"" + checksum + "\", but downloaded file checksum is \"" + checksumActual + "\"."; throw new WinAppDriverException(msg); } else { logger.Debug("Expected checksum is \"{0}\", but downloaded file checksum is \"{1}\".", checksum, checksumActual); logger.Debug("Retry downloading file \"{0}\" .......", webResource); } } else { logger.Debug("Successfully downloaded file from \"{0}\"", webResource); logger.Debug("Downloaded file saved in the following file system folder: \"{0}\"", storeFileName); break; } } return storeFileName; } public Process Execute(string command, IDictionary<string, string> variables) { string executable, arguments; this.ParseCommand(command, out executable, out arguments); // TODO not exited, or non-zero exit status var startInfo = new ProcessStartInfo(executable, arguments); startInfo.UseShellExecute = false; // mandatory for setting environment variables if (variables != null) { var envs = startInfo.EnvironmentVariables; foreach (var item in variables) { envs[item.Key] = item.Value; } } return Process.Start(startInfo); } private void ParseCommand(string command, out string executable, out string arguments) { // TODO quoted executable int index = command.IndexOf(' '); // the first space as the separator if (index == -1) { executable = command; arguments = null; } else { executable = command.Substring(0, index); arguments = command.Substring(index); } // TODO PowerShell scripts -> use PowerShell.exe and append '-ExecutionPolicy Bypass' (if not provided) logger.Debug( "Parse command; [{0}] ==> executable = [{1}], arguments = [{2}]", command, executable, arguments); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace App.Web.AsyncApi { internal static class AsyncApiJsonPropertyExtensions { internal static bool IsRequired(this JsonProperty jsonProperty) { return jsonProperty.Required == Required.AllowNull || jsonProperty.Required == Required.Always || jsonProperty.HasAttribute<RequiredAttribute>(); } internal static bool IsObsolete(this JsonProperty jsonProperty) { return jsonProperty.HasAttribute<ObsoleteAttribute>(); } internal static bool HasAttribute<T>(this JsonProperty jsonProperty) where T : Attribute { MemberInfo memberInfo; if (!jsonProperty.TryGetMemberInfo(out memberInfo)) return false; return (object) memberInfo.GetCustomAttribute<T>() != null; } internal static bool TryGetMemberInfo(this JsonProperty jsonProperty, out MemberInfo memberInfo) { if (jsonProperty.UnderlyingName == null) { memberInfo = (MemberInfo) null; return false; } object obj = ((IEnumerable<object>) jsonProperty.DeclaringType.GetTypeInfo() .GetCustomAttributes(typeof(ModelMetadataTypeAttribute), true)).FirstOrDefault<object>(); Type type = obj != null ? ((ModelMetadataTypeAttribute) obj).MetadataType : jsonProperty.DeclaringType; memberInfo = ((IEnumerable<MemberInfo>) type.GetMember(jsonProperty.UnderlyingName)) .FirstOrDefault<MemberInfo>(); return memberInfo != (MemberInfo) null; } } }
namespace E4 { public class Administrativo : Empleado { public Administrativo(int cajaBancaria) : base(cajaBancaria) { } public override void depositan() { cajaBancaria += 35000; } } }
using System; using System.Threading.Tasks; using CC.Mobile.Routing; using System.Linq; using UIKit; using Foundation; using System.Collections.Generic; using CC.Utilities; namespace CC.Mobile.MonoTouch { public class StackNavigationController:UINavigationController, IRouter { public NavItem HomeNav { get { return Router.HomeNav; } } public NavItem CurrentNonModal { get { return Router.CurrentNonModal; } } public IViewControllerFactory ControllerFactory {get;set;} public override void ViewDidLoad () { base.ViewDidLoad (); CC.Mobile.Routing.Router.ResetInstance (); var root = this.ViewControllers.First (); var nav = (root as INavigationEnabledPage); if (nav!=null) { Router.Push (new NavItem(nav.ScreenId, nav.NavModel)); } } public override void ViewWillAppear (bool animated) { this.ToolbarHidden = true; base.ViewWillAppear (animated); } IRouter router; public IRouter Router { get { if (router == null) { router = CC.Mobile.Routing.Router.Instance; } return router; } set { router = value; } } public StackNavigationController ():base(){} public StackNavigationController (IntPtr handle) : base (handle){} public StackNavigationController (NSCoder coder) : base (coder){} public StackNavigationController(UIViewController rootController):base(rootController){} public override void PresentViewController (UIViewController viewControllerToPresent, bool animated, Action completionHandler) { base.PresentViewController (viewControllerToPresent, animated, completionHandler); } public override Task PresentViewControllerAsync (UIViewController viewControllerToPresent, bool animated) { return base.PresentViewControllerAsync (viewControllerToPresent, animated); } public override void PushViewController(UIViewController viewController, bool animated) { if (viewController is INavigationEnabledPage) { var navPage = viewController as INavigationEnabledPage; NavItem navItem = navPage.GetNavItem(); if (Router.Contains(navItem)) { foreach (var vc in this.ViewControllers) { if (vc is INavigationEnabledPage) { var n = vc as INavigationEnabledPage; if (n.ScreenId == navItem.Screen) { var poppedItems = PopToViewController(vc, animated); CleanupPoppedViewControllers(poppedItems); break; } } } } else { Router.Push(navItem); base.PushViewController(viewController, animated); } } else { base.PushViewController(viewController, animated); } } public override UIViewController[] PopToRootViewController(bool animated) { GoHome(animated); return null; } public override UIViewController PopViewController(bool animated) { if (Router.Handles(ViewControllers.Last())) { Router.Pop(); } return base.PopViewController(animated); } public override UIViewController[] ViewControllers { get { return base.ViewControllers; } set { base.ViewControllers = value; } } public List<NavItem> PopAllModals(object context = null, bool animated = true) { var result = Router.PopAllModals (); var vc = ViewControllerForItem (Router.Current); if (result.Count > 0) { if (vc != null) { if (vc is IEmbedsControllerForModal) { (vc as IEmbedsControllerForModal).DismissEmbededController (); } else { vc.DismissModalViewController (animated); } } } return result; } public NavItem GetItemForScreen (int screenId)=>Router.GetItemForScreen (screenId); public bool ContainsScreen (int screenId)=>Router.ContainsScreen (screenId); public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations() { return TopViewController.GetSupportedInterfaceOrientations(); } #region IRouter implementation public bool Handles(object page) { return Router.Handles(page); } public bool Contains(NavItem navItem) { return Router.Contains(navItem); } public void SetHandle(Action<NavigationType, NavItem> handle) { Router.SetHandle(handle); } private UIViewController ViewControllerForItem(NavItem navItem){ foreach (var item in ViewControllers.Reverse()) { if (item is INavigationEnabledPage) { var navPage = item as INavigationEnabledPage; if (navPage.ScreenId == navItem.Screen) { return item; } } } return null; } public override UIViewController[] PopToViewController(UIViewController viewController, bool animated) { if (Router.Handles(viewController)) { var vc = viewController as INavigationEnabledPage; Router.GoTo(vc.GetNavItem()); } return base.PopToViewController(viewController, animated); } static void CleanupPoppedViewControllers(UIViewController[] poppedVcs) { if (poppedVcs.IsNotNull ()) { foreach (var item in poppedVcs) { item.Dispose(); } } } static void CleanupPoppedViewController(UIViewController poppedVc) { if (poppedVc != null) { poppedVc.Dispose(); } } public NavItem[] GoTo(NavItem navItem, bool animated=true, object context = null, Action<bool> completionHandler=null) { UIViewController vc = null; var poppedItems = Router.GoTo (navItem, animated, context); bool isScreenless = navItem.PresentationStyle == PresentationStyle.Screenless; bool isBack = poppedItems.Length > 0 && navItem.PresentationStyle != PresentationStyle.Replace || poppedItems.Length > 1; if (isScreenless) { // if (completionHandler != null) { completionHandler (true); } } else if (isBack) { vc = ViewControllerForItem (navItem); if (navItem.ForceViewModelOnPop && vc is IModelEnabledElement) { (vc as IModelEnabledElement).SetModel (navItem.ViewModel); } if (poppedItems.Length == 1 && poppedItems.Last ().PresentationStyle == PresentationStyle.Modal) { if (vc is IEmbedsControllerForModal) { (vc as IEmbedsControllerForModal).DismissEmbededController (); } else { vc.DismissViewController (animated, () => {}); } } else if (poppedItems.Last ().PresentationStyle == PresentationStyle.Modal) { if (vc is IEmbedsControllerForModal) { (vc as IEmbedsControllerForModal).DismissEmbededController (); } else { vc.DismissViewController (false, () => {}); } var poppedVcs = base.PopToViewController (vc, animated); CleanupPoppedViewControllers (poppedVcs); } else { var poppedVcs = base.PopToViewController (vc, animated); CleanupPoppedViewControllers (poppedVcs); } if (completionHandler != null) { completionHandler (true); } } else { vc = ControllerFactory.ForScreen (navItem.Screen, navItem.ViewModel); if (navItem.PresentationStyle == PresentationStyle.Push || navItem.PresentationStyle == PresentationStyle.Replace) { if (navItem.PresentationStyle == PresentationStyle.Replace) { var r = base.PopViewController (false); CleanupPoppedViewController (r); navItem.PresentationStyle = PresentationStyle.Push; } base.PushViewController (vc, animated); } else if (navItem.PresentationStyle == PresentationStyle.Modal) { var baseController = ViewControllerForItem (CurrentNonModal); if (vc is IRouterEnabledElement) { (vc as IRouterEnabledElement).Router = this; } if (baseController is IEmbedsControllerForModal) { (baseController as IEmbedsControllerForModal).ShowEmbededController (vc, animated, () => { }); } else { base.PresentViewController (vc, animated, () => { }); } } else if (navItem.PresentationStyle == PresentationStyle.ThruSegue) { VisibleViewController.PerformSegue (context as string, VisibleViewController); } if (completionHandler != null) { completionHandler (true); } } return poppedItems.ToArray (); } public void Push(NavItem item, bool animated=true) { var vc = ViewControllerForItem(item); PushViewController(vc, animated); } public NavItem Pop(object context, bool animated = true) { return GoTo (Router.Previous).LastOrDefault (); } public NavItem[] GoHome(bool animated=true) { return GoTo(HomeNav, animated); } public void Clear () { Router.Clear (); } public NavItem Current { get { return Router.Current; } } public NavItem Previous { get { return Router.Previous; } } public bool CanGoBack { get { return Router.CanGoBack; } } #endregion public Task RefreshViewModelsInBackstackAsync() { return Router.RefreshViewModelsInBackstackAsync(); } public Task RefreshViewModelForScreens(params int[] screens) { return Router.RefreshViewModelForScreens(screens); } public Task RefreshCurrentViewModelAsync () { return Router.RefreshCurrentViewModelAsync (); } public void AttachTranstion(UIViewController fromVC, UIViewController toVC) { } public NavItem this [int s] { get { return null; } } } }
using CaveGeneration.Content_Generation.Map_Cleanup; using CaveGeneration.Content_Generation.Parameter_Settings; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CaveGeneration.Content_Generation.Map_Generation { class RandomPlacement : MapGenerator { public int randomFillPercent; public RandomPlacement(int width, int height, Settings settings) : base(width, height, settings) { this.randomFillPercent = settings.RandomFillPercent; } public override void Start(string seed) { if (seed.Equals("")) UseRandomSeed = true; Seed = seed; GenerateMap(); } private void GenerateMap() { map = new int[Width, Height]; RandomFillMap(); } private void FillMap() { for (int x = 0; x < Width; x++) { for (int y = 0; y < Height; y++) { map[x, y] = 1; } } } private void RandomFillMap() { if (UseRandomSeed) { Seed = DateTime.Now.TimeOfDay.TotalSeconds.ToString(); } Random pseudoRandom = new Random(Seed.GetHashCode()); for (int x = 0; x < Width; x++) { for (int y = 0; y < Height; y++) { if (x == 0 || x == Width - 1 || y == 0 || y == Height - 1) { map[x, y] = 1; } else { map[x, y] = (pseudoRandom.Next(0, 100) < randomFillPercent) ? 1 : 0; } } } } } }
using System; using System.Security.Cryptography; using System.Text; namespace TAiMStore.Classes { public static class Hash { /// <summary> /// Метод кодирующий пароль md5 /// </summary> /// <param name="pass">пароль</param> /// <returns>хэш пароля </returns> public static string HashPassword(string pass) { // Преобразуем битовое значение пароля var passTextBytes = Encoding.UTF8.GetBytes(pass); // хешируем пароль и соль в MD5 var hash = new SHA1Managed(); var hashBytes = hash.ComputeHash(passTextBytes); // хешируем смешанный пароь с помощью SHA512 var hashSha1 = new SHA512Managed(); var hashWithSaltCode = hashSha1.ComputeHash(hashBytes); var hashValue = Convert.ToBase64String(hashBytes); return hashValue; } } }
using SuperMario.Entities; using SuperMario.Entities.Mario; using SuperMario.Sound; namespace SuperMario.HUDAndSoundSystemControl.SoundSystemControl { public sealed class MusicController { bool starState; bool inUnderground; bool deadPlayer; bool endGameSequence; readonly int hurryTimeInTicks = 1000000000; static readonly MusicController instance = new MusicController(); public static MusicController Instance { get { return instance; } } MusicController() { starState = false; inUnderground = false; deadPlayer = false; endGameSequence = false; } public void UpdateMusic() { if (!Music.IsMusicStopped()) return; UpdateConditions(); if (endGameSequence) Music.Instance.PlayLevelComplete(); else if (deadPlayer) Music.Instance.PlayDead(); else if (!IsTimeRunningOut()) { if (starState) Music.Instance.PlayStarman(); else if (inUnderground) Music.Instance.PlayUnderworld(); else Music.Instance.PlayMainTheme(); } else { if (starState) Music.Instance.PlayStarManHurry(); else if (inUnderground) Music.Instance.PlayUnderworldHurry(); else Music.Instance.PlayMainThemeHurry(); } } void UpdateConditions() { starState = AreAnyPlayersStarState(); inUnderground = AreAnyPlayersUnderground(); deadPlayer = AreAnyPlayersDead(); endGameSequence = HaveAnyPlayerReachedFlag(); } bool IsTimeRunningOut() { return HUDController.Instance.TimeInTicks <= hurryTimeInTicks; } static bool AreAnyPlayersStarState() { foreach (Entity player in EntityStorage.Instance.PlayerEntityList) { MarioEntity playerLookingAt = (MarioEntity) player; if (playerLookingAt.CurrentConditionIsStarCondition()) return true; } return false; } static bool AreAnyPlayersUnderground() { foreach (Entity player in EntityStorage.Instance.PlayerEntityList) { MarioEntity playerLookingAt = (MarioEntity)player; if (playerLookingAt.IsMarioUnderGround()) return true; } return false; } static bool AreAnyPlayersDead() { foreach (Entity player in EntityStorage.Instance.PlayerEntityList) { MarioEntity playerLookingAt = (MarioEntity)player; if (playerLookingAt.MarioDead) return true; } return false; } static bool HaveAnyPlayerReachedFlag() { foreach (Entity player in EntityStorage.Instance.PlayerEntityList) { MarioEntity playerLookingAt = (MarioEntity)player; if (playerLookingAt.IsMarioEndGame()) return true; } return false; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; /// <summary> /// Base class for paddles /// </summary> public class PaddleBase : NetworkBehaviour { private float thrust = 10.0f; private Vector3 up = new Vector3(1, 0, 0); private Rigidbody rigidBody; protected Animator animator; protected List<SuperPowerBase> myPowers = new List<SuperPowerBase>(); protected string currentPowerName=""; public virtual void Start() { rigidBody = GetComponent<Rigidbody>(); animator = GetComponent<Animator>(); } private void OnEnable() { currentPowerName = ""; } protected void SetThrust(float thrust) { this.thrust = thrust; } // +ve for "up" protected void MovePaddles(float dir) { Debug.Assert(Time.inFixedTimeStep, "Paddle movement should only happen inside physics code"); if (rigidBody) { // Invert for one side if (transform.position.x < 0) dir *= -1; // Clamp between [-1,1] dir = Mathf.Clamp(dir, -1.0f, 1.0f); //rigidBody.AddForce(dir * up * Thrust); transform.Translate(dir * up * thrust * Time.fixedDeltaTime); } } internal void FixedUpdate() { // Clamp Z if we're outside an arbitrary value if(transform.position.z < 4.0f || transform.position.z > 4.0f) { transform.position = new Vector3( transform.position.x, transform.position.y, Mathf.Clamp(transform.position.z, -4.0f, 4.0f) ); } } internal void Update() { //Try to cleanup oldest power if (myPowers.Count > 0) { SuperPowerBase p = myPowers[0]; if(!p.isActive && !p.isReady) { myPowers.RemoveAt(0); Destroy(p); Debug.Log("Cleaning"); } } } internal void TryActivate() {} public void AddPower(string powerName) { if (myPowers.Count > 0) { myPowers[myPowers.Count - 1].isReady = false; } Debug.Log(powerName); SuperPowerBase spb = gameObject.AddComponent(Type.GetType(powerName)) as SuperPowerBase; spb.isReady = true; myPowers.Add(spb); } public void SetPower(string powerName) { Debug.Log("Set Power: " + powerName); currentPowerName = powerName; } }
using System; namespace AssemblyTimeStamp { public static class TimeStampUtil { public static DateTime GetAssemblyTimeStamp() { throw new NotImplementedException(); } } }
using BELCORP.GestorDocumental.BE.Comun; using BELCORP.GestorDocumental.BE.DDP; using BELCORP.GestorDocumental.BL; using BELCORP.GestorDocumental.BL.DDP; using BELCORP.GestorDocumental.Common; using BELCORP.GestorDocumental.Common.Excepcion; using BELCORP.GestorDocumental.Common.Util; using BELCORP.GestorDocumental.DA.Sharepoint; using Microsoft.Office.Server.UserProfiles; using Microsoft.SharePoint; using Microsoft.SharePoint.Administration; using Microsoft.SharePoint.WorkflowServices; using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PruebasDDPFormulario { public class Program { static void Main(string[] args) { try { SPSecurity.RunWithElevatedPrivileges(delegate() { string URL_SitioDDP = (ConfigurationManager.AppSettings["URL_SitioDDP"] != null) ? ConfigurationManager.AppSettings["URL_SitioDDP"].ToString() : string.Empty; if (string.IsNullOrEmpty(URL_SitioDDP)) throw new ErrorPersonalizado("URL de Sitio DDP no está configurado"); using (SPSite oSPSite = new SPSite(URL_SitioDDP)) { using (SPWeb oSPWeb = oSPSite.OpenWeb()) { //Obtener el listado total de perfiles de usuario //#region Cargar los perfiles de usuario //SPServiceContext serviceContext = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, SPSiteSubscriptionIdentifier.Default); //UserProfileManager upMananger1ro = new UserProfileManager(serviceContext); //List<PerfilesBE> lstPerfiles = new List<PerfilesBE>(); ////Obtenemos las propiedades de usuario del WebConfig (OWS Timer) //string PROP_WorkEmail = (ConfigurationManager.AppSettings["PROP_WorkEmail"] != null) ? ConfigurationManager.AppSettings["PROP_WorkEmail"].ToString() : string.Empty; //string PROP_CentroDeCostos = (ConfigurationManager.AppSettings["PROP_CentroDeCostos"] != null) ? ConfigurationManager.AppSettings["PROP_CentroDeCostos"].ToString() : string.Empty; ////Validar si las propiedades deseadas existen //if (PROP_WorkEmail != string.Empty && PROP_CentroDeCostos != string.Empty) //{ // //Recorremos los perfiles de usuario // foreach (UserProfile profile1ro in upMananger1ro) // { // //Validamos la existencia de los atributos necesarios // if ( // profile1ro.Properties.GetPropertyByName(PROP_WorkEmail) != null && // profile1ro.Properties.GetPropertyByName(PROP_CentroDeCostos) != null // ) // { // string email_ = string.Empty; // if (profile1ro["WorkEmail"].Value != null) // { // email_ = profile1ro["WorkEmail"].Value.ToString(); // } // string centroCostos = string.Empty; // if (profile1ro["CentroDeCostos"].Value != null) // { // centroCostos = profile1ro["CentroDeCostos"].Value.ToString(); // } // PerfilesBE objPerfil = new PerfilesBE(); // objPerfil.Correo = email_; // objPerfil.CentroCostos = centroCostos; // lstPerfiles.Add(objPerfil); // } // } //} //#endregion SPListItemCollection spliTiposDocumentales = SharePointHelper.ObtenerInformacionLista(oSPWeb, ListasGestorDocumental.TiposDocumentales); foreach (SPListItem TipoDocumental in spliTiposDocumentales) { string spQuery = "<Where>" + "<Eq>" + "<FieldRef Name='EstadoPasoFlujo'/>" + "<Value Type='Text'>" + EstadosDDP.Publicado + "</Value>" + "</Eq>" + "</Where>"; SPListItemCollection spliDocumentos = SharePointHelper.ObtenerInformacionLista(oSPWeb.Site.Url, TipoDocumental["Biblioteca"].ToString(), spQuery); foreach (SPListItem DocumentoDDP in spliDocumentos) { DocumentoDDPBE oDocumentoDDPBE = null; if (DocumentoDDP != null) oDocumentoDDPBE = DocumentoDDPBL.Instance.LeerSPListItem(DocumentoDDP); // *** MOVER ARCHIVO String SitioPublicado = URL_SitioDDP + Constantes.URL_SUBSITIO_PUBLICADO; //string NombreBiblioteca = hdfCodigoTipoDocumento.Value + " " + txtTipoDocumento.Text; //DocumentoDDPBL.Instance.MoverAPublicado(Convert.ToInt32(hdfIdDocumentoDDP.Value), SitioPublicado, NombreBiblioteca); SPFile Archivo = DocumentoDDPBL.Instance.ObtenerArchivoXId(URL_SitioDDP, TipoDocumental["Biblioteca"].ToString(), DocumentoDDP.ID); oDocumentoDDPBE.TipoDocumental.Codigo = TipoDocumental.Title; oDocumentoDDPBE.TipoDocumental.Biblioteca = TipoDocumental["Biblioteca"].ToString(); //oDocumentoDDPBE.CodigoDocumento = txtCodigoDocumentoCabecera.Text; oDocumentoDDPBE.Estado = EstadosDDP.Publicado ; oDocumentoDDPBE.FechaPublicacion = DateTime.Today; // DocumentoDDPBL.Instance.CopiarAPublicado(Convert.ToInt32(hdfIdDocumentoDDP.Value), SitioPublicado, NombreBiblioteca, Archivo); //string mensaje = Mensajes.ExitoGestorDocumental.EnvioCorrectamente; //Archivo. //RegistrarOActualizarMetadatos(ref oDocumentoDDPBE, mensaje); int idPublicado = 0; DocumentoDDPBE oDocumentoPublicado = DocumentoDDPBL.Instance.RegistrarPublicado(SitioPublicado, oDocumentoDDPBE, Archivo); if (oDocumentoPublicado != null) { idPublicado = oDocumentoPublicado.ID; } //DocumentoDDPBL.Instance.CrearNuevoRegistroDocumento(oDocumentoDDPBE); DocumentoDDPBL.Instance.AsignarPermisosDocumentoPublicado(oDocumentoPublicado, SitioPublicado); if (TipoDocumental["ListaDocVigente"] != null) { ElementoBE oElemento = new ElementoBE(); oElemento.Codigo = oDocumentoDDPBE.CodigoDocumento; oElemento.EstadoDocVigente = EstadosDDP.Publicado ; ElementoBL.Instance.Actualizar(oSPWeb.Site.Url, TipoDocumental["ListaDocVigente"].ToString(), oElemento); } HistorialFlujoBE oHistorialFlujo = new HistorialFlujoBE(); //oHistorialFlujo.IDVersion = 4; oHistorialFlujo.Accion = Mensajes.ExitoGestorDocumental.PublicoCorrectamente; oHistorialFlujo.CodigoDocumento = oDocumentoDDPBE.CodigoDocumento; oHistorialFlujo.Version = oDocumentoDDPBE.Version; oHistorialFlujo.FechaAccion = DateTime.Now; oHistorialFlujo.Estado = oDocumentoDDPBE.Estado; oHistorialFlujo.Usuario = Constantes.TIMER_PUBLICACION_DDP; oHistorialFlujo.Comentario = Mensajes.HistorialGestorDocumental.Publicacion; HistorialFlujoDDPBL.Instance.CrearNuevoRegistroHistorialFlujo(oHistorialFlujo); // *** ACTUALIZAR ESTADO DE ARCHIVO VERSION ANTERIOR A OBSOLETO oDocumentoDDPBE.UrlDocumento = Constantes.URL_SUBSITIO_PUBLICADO + @"/" + oDocumentoDDPBE.TipoDocumental.Codigo + Constantes.URL_PAGINA_FORMULARIO + idPublicado.ToString(); //VersionBL.Instance.ActualizarEstadoAPublicado(oDocumentoDDPBE.CodigoDocumento, oDocumentoDDPBE.Version, EstadosDDP.Publicado , Constantes.OBSOLETO_ESTADO, oDocumentoDDPBE.UrlDocumento); // *** ACTUALIZAR ESTADO DE ARCHIVO VERSION ANTERIOR A OBSOLETO if (oDocumentoDDPBE.Version > 1) { DocumentoDDPBL.Instance.ActualizarAObsoleto(SitioPublicado, oDocumentoDDPBE.TipoDocumental.Biblioteca, oDocumentoDDPBE.CodigoDocumento, oDocumentoDDPBE.Version); } // *** ELIMINA ARCHIVO EN FLUJO DocumentoDDPBL.Instance.EliminarDocumentoFlujoXId(URL_SitioDDP, oDocumentoDDPBE.TipoDocumental.Biblioteca, DocumentoDDP.ID); // *** ENVIAR CORREO String UrlArchivoPublicado = SitioPublicado + "/" + oDocumentoDDPBE.TipoDocumental.Biblioteca + "/Dispform.aspx?ID=" + idPublicado.ToString(); } } } } }); } catch (ErrorPersonalizado ep) { //Se escribe en el log de sharepoint //Logging.RegistrarMensajeLogSharePoint( // Constantes.CATEGORIA_LOG_TJ_PUBLICAR_DDP, // JobName, // TraceSeverity.High, // EventSeverity.Error, // ep); //Se lanza el error para que se registre en el historial del timer job throw; } catch (Exception ex) { //Se escribe en el log de sharepoint //Logging.RegistrarMensajeLogSharePoint(Constantes.CATEGORIA_LOG_TJ_PUBLICAR_DDP, 'Job', ex); //Se lanza el error para que se registre en el historial del timer job throw; } } //static void AsignarPermisosDocumentoPublicado( // DocumentoDDPBE oDocumentoDDPBE, // string pe_strUrlSitio) //{ // //Se ejecuta el codigo con privilegios elevados // SPSecurity.RunWithElevatedPrivileges(delegate() // { // using (SPSite objSPSite = new SPSite(pe_strUrlSitio)) // { // using (SPWeb objSPWeb = objSPSite.OpenWeb()) // { // //Se consulta la informacion de sharepoint // SPList ListDocumental = objSPWeb.Lists[oDocumentoDDPBE.TipoDocumental.Biblioteca]; // SPListItem pe_objSPListItem = ListDocumental.GetItemById(oDocumentoDDPBE.ID); // if (pe_objSPListItem != null) // { // DocumentoDDPBE objDocumentoDDPBE = new DocumentoDDPBE();//DocumentoDDPBL.Instance.LeerPropiedadesSPListItemDocumentoGD(pe_objSPListItem); // //Se remueven los permisos sobre el documento heredando nuevamente de la lista // pe_objSPListItem.ResetRoleInheritance(); // SharePointHelper.RemoverTodosPermisosSPListItem(pe_objSPListItem, true, true); // if (pe_objSPListItem["Elaborador"] != null) // { // SPFieldUserValue objSPFieldElaborador = new SPFieldUserValue(pe_objSPListItem.Web, pe_objSPListItem["Elaborador"].ToString()); // objDocumentoDDPBE.Elaborador = ComunBL.Instance.ObtenerUsuarioDeSPFieldUserValue(objSPFieldElaborador, pe_objSPListItem.Web.Site.Url); // } // SPFieldUserValue objSPFieldContribuidor = new SPFieldUserValue(pe_objSPListItem.Web, pe_objSPListItem["Author"].ToString()); // objDocumentoDDPBE.Contribuidor = ComunBL.Instance.ObtenerUsuarioDeSPFieldUserValue(objSPFieldContribuidor, pe_objSPListItem.Web.Site.Url); // if (pe_objSPListItem["Revisor"] != null) // { // SPFieldUserValue objSPFieldRevisor = new SPFieldUserValue(pe_objSPListItem.Web, pe_objSPListItem["Revisor"].ToString()); // objDocumentoDDPBE.Revisor = ComunBL.Instance.ObtenerUsuarioDeSPFieldUserValue(objSPFieldRevisor, pe_objSPListItem.Web.Site.Url); // } // if (pe_objSPListItem["Aprobador"] != null) // { // SPFieldUserValue objSPFieldAprobador = new SPFieldUserValue(pe_objSPListItem.Web, pe_objSPListItem["Aprobador"].ToString()); // objDocumentoDDPBE.Aprobador = ComunBL.Instance.ObtenerUsuarioDeSPFieldUserValue(objSPFieldAprobador, pe_objSPListItem.Web.Site.Url); // } // if (pe_objSPListItem["SubAdministrador"] != null) // { // SPFieldUserValueCollection objSPFieldSubAdministrador = new SPFieldUserValueCollection(pe_objSPListItem.Web, pe_objSPListItem["SubAdministrador"].ToString()); // foreach (var itemSubAdministrador in objSPFieldSubAdministrador) // { // objDocumentoDDPBE.SubAdministradores.Add(ComunBL.Instance.ObtenerUsuarioDeSPFieldUserValue(itemSubAdministrador, pe_objSPListItem.Web.Site.Url)); // } // } // objSPWeb.AllowUnsafeUpdates = true; // SPPrincipal SPElaborador = null; // SPPrincipal SPAprobador = null; // SPPrincipal SPRevisor = null; // //Se asigna los permisos // if (objDocumentoDDPBE.GrupoSeguridad.Title != GruposSeguridad.Confidencial // && objDocumentoDDPBE.GrupoSeguridad.Title != GruposSeguridad.Secreto) // { // SharePointHelper.AgregarPermisosSPListItem(pe_objSPListItem, SPRoleType.Reader, objSPWeb.Groups[Constantes.NOMBRE_GRUPO_LECTORES], false); // } // else // { // SPGroup grupoAdministradores = SharePointHelper.ObtenerGruposPorNombre(objSPWeb.Url, Constantes.IDENTIFICADOR_GRUPO_ADMINISTRADOR); // SharePointHelper.AgregarPermisosSPListItem(pe_objSPListItem, SPRoleType.Administrator, grupoAdministradores, false); // List<SPPrincipal> lisSPPrincipalSubAdministradores = new List<SPPrincipal>(); // foreach (UsuarioBE itemSubadministrador in objDocumentoDDPBE.SubAdministradores) // lisSPPrincipalSubAdministradores.Add(ComunBL.Instance.ObtenerSPPrincipalDeUsuario(itemSubadministrador, objSPWeb)); // foreach (SPPrincipal SPSubAdministrador in lisSPPrincipalSubAdministradores) // SharePointHelper.AgregarPermisosSPListItem(pe_objSPListItem, SPRoleType.Contributor, SPSubAdministrador, false); // SPPrincipal SPContribuidor = ComunBL.Instance.ObtenerSPPrincipalDeUsuario(objDocumentoDDPBE.Contribuidor, objSPWeb); // if (objDocumentoDDPBE.Elaborador.ID != 0) // SPElaborador = ComunBL.Instance.ObtenerSPPrincipalDeUsuario(objDocumentoDDPBE.Elaborador, objSPWeb); // if (objDocumentoDDPBE.Aprobador.ID != 0) // SPAprobador = ComunBL.Instance.ObtenerSPPrincipalDeUsuario(objDocumentoDDPBE.Aprobador, objSPWeb); // if (objDocumentoDDPBE.Revisor.ID != 0) // SPRevisor = ComunBL.Instance.ObtenerSPPrincipalDeUsuario(objDocumentoDDPBE.Revisor, objSPWeb); // if (SPContribuidor != null) // SharePointHelper.AgregarPermisosSPListItem(pe_objSPListItem, SPRoleType.Reader, SPContribuidor, false); // if (SPRevisor != null) // SharePointHelper.AgregarPermisosSPListItem(pe_objSPListItem, SPRoleType.Reader, SPRevisor, false); // if (SPAprobador != null) // SharePointHelper.AgregarPermisosSPListItem(pe_objSPListItem, SPRoleType.Reader, SPAprobador, false); // foreach (UsuarioBE oUsuarioLector in objDocumentoDDPBE.LectoresNoPublicos) // { // oUsuarioLector.EsGrupo = false; // SPPrincipal oLector = ComunBL.Instance.ObtenerSPPrincipalDeUsuario(oUsuarioLector, objSPWeb); // SharePointHelper.AgregarPermisosSPListItem(pe_objSPListItem, SPRoleType.Reader, oLector, false); // } // } // } // } // } // }); //} } }
namespace RockPapperScissors { public interface IStrategy { string Letter { get; } bool Wins(IStrategy strategy); } }
using System; using System.Linq; using System.Management; using System.Text; namespace MacAddressReader { internal class Program { private static void Main(string[] args) { Console.WriteLine(GetMacAddress()); } public static string GetMacAddress() { var managementClass = new ManagementClass("Win32_NetworkAdapterConfiguration"); var instances = managementClass.GetInstances(); var managementObjects = instances .Cast<ManagementObject>() .First(x => HasMacAddress(x) && IsIpEnabled(x)); return GetMacAddress(managementObjects); } private static bool IsIpEnabled(ManagementBaseObject x) { return Convert.ToBoolean(x["IPEnabled"]); } private static bool HasMacAddress(ManagementBaseObject x) { return GetMacAddress(x) != null; } private static string GetMacAddress(ManagementBaseObject x) { return (string) x["MACAddress"]; } } }
using System; using System.Windows.Forms; using ExamOnline.BaseClass; namespace ExamOnline.Admin { public partial class ChangeStudentInfo : System.Web.UI.Page { private static int id; protected void Page_Load(object sender, EventArgs e) { if (Session["AdminName"] == null) { Response.Redirect("../Login.aspx"); } if (!IsPostBack) { id = Convert.ToInt32(Request.QueryString["stuid"]); BaseClass.DalTeacher dal = new DalTeacher(); var sdr = dal.GetSdrInfo(id); sdr.Read(); txtStuName.Text = sdr["StudentName"].ToString(); txtStuNum.Text = sdr["StudentNum"].ToString(); txtStuPwd.Text = sdr["StudentPwd"].ToString(); rblSex.SelectedValue = sdr["StudentSex"].ToString(); sdr.Close(); } } protected void btnSava_Click(object sender, EventArgs e) { if (txtStuName.Text.Trim() == "" || txtStuPwd.Text.Trim() == "") { MessageBox.Show("请将信息填写完整"); return; } else { string str = "update F_Student set StudentName='" + txtStuName.Text.Trim() + "',StudentPwd='" + txtStuPwd.Text.Trim() + "',StudentSex='" + rblSex.SelectedItem.Text + "' where StudentNum=" + id; BaseClass.BaseClass.OperateData(str); Response.Redirect("StudentInfo.aspx"); } } protected void btnConcel_Click(object sender, EventArgs e) { Response.Redirect("StudentInfo.aspx"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SeaFight.Infrastructure { public enum Cell { Empty, Ship, Stricken, Halo, Unknown, Shot } }
using System; using System.Collections.Generic; using System.Text; using System.Linq; namespace ChessDotNetBackend { public class Board { IList<IPiece> m_pieces = new List<IPiece>(); public Board( Board board ) { this.WhitesTurn = board.WhitesTurn; foreach( var piece in board.Pieces ) { this.m_pieces.Add( piece.Copy() ); } } internal void DebugOutput() { /* Console.WriteLine("Board:"); for ( int y = 0; y < 8; y++ ) { for ( int x = 0; x < 8; x++ ) { IPiece piece = GetPieceOnSquare( new Square( x, y ) ); if ( piece != null ) { PieceCode code = new PieceCode(); piece.Accept( code, null ); Console.Write( code.Code ); } else { Console.Write( "•" ); } } Console.WriteLine(); } */ } public double CalcSidesScore( bool whitesTurn, TranspositionTable transpositionTable) { if( whitesTurn ) { return CalcWhitesScore(transpositionTable); } else { return -CalcWhitesScore(transpositionTable); } } public double CalcWhitesScore(TranspositionTable transpositionTable) { ZobristHash hash = new ZobristHash(this); if(transpositionTable.ContainsLeafScore(hash)) { return transpositionTable.LeafScore(hash); } double whitesScore = 0; foreach( var piece in m_pieces ) { if( piece.White ) { whitesScore += piece.Value; } else { whitesScore -= piece.Value; } if( piece.IsPawn ) { int spacesAdvanced = 0; if( piece.White ) { spacesAdvanced = 6 - piece.CurrentPosition.y; } else { spacesAdvanced = piece.CurrentPosition.y - 1; } whitesScore += 0.1 * spacesAdvanced * ( piece.White ? 1 : -1 ); } } transpositionTable.UpdateLeafScore(hash, whitesScore); return whitesScore; } public Board() { } public IList<IPiece> Pieces => m_pieces; public bool WhitesTurn { get; set; } public static Board InitNewGame() { int pieceNumber = 0; Board b = new Board(); for( int i = 0; i < 8; i++ ) { b.m_pieces.Add( new Pawn( new Square( i, 1 ), false ) ); b.m_pieces.Add( new Pawn( new Square( i, 6 ), true ) ); } b.m_pieces.Add( new Rook( new Square( 0, 0 ), false ) ); b.m_pieces.Add( new Rook( new Square( 7, 0 ), false ) ); b.m_pieces.Add( new Knight( new Square( 1, 0 ), false ) ); b.m_pieces.Add( new Knight( new Square( 6, 0 ), false ) ); b.m_pieces.Add( new Bishop( new Square( 2, 0 ), false ) ); b.m_pieces.Add( new Bishop( new Square( 5, 0 ), false ) ); b.m_pieces.Add( new Queen( new Square( 3, 0 ), false ) ); b.m_pieces.Add( new King( new Square( 4, 0 ), false ) ); b.m_pieces.Add( new Rook( new Square( 0, 7 ), true ) ); b.m_pieces.Add( new Rook( new Square( 7, 7 ), true ) ); b.m_pieces.Add( new Knight( new Square( 1, 7 ), true ) ); b.m_pieces.Add( new Knight( new Square( 6, 7 ), true ) ); b.m_pieces.Add( new Bishop( new Square( 2, 7 ), true ) ); b.m_pieces.Add( new Bishop( new Square( 5, 7 ), true ) ); b.m_pieces.Add( new Queen( new Square( 3, 7 ), true ) ); b.m_pieces.Add( new King( new Square( 4, 7 ), true ) ); b.WhitesTurn = true; return b; } public IPiece GetPieceOnSquare( Square square ) { foreach( var piece in m_pieces ) { if( square == piece.CurrentPosition ) { return piece; } } return null; } /// <summary> /// Walk the piece up to the given square and see if anyone gets in the way /// </summary> /// <param name="piece"></param> /// <param name="square"></param> /// <returns></returns> public bool IsNothingInTheWay( IPiece piece, Square square ) { int dx = piece.CurrentPosition.x - square.x; int dy = piece.CurrentPosition.y - square.y; int xinc = ( dx == 0 ) ? 0 : ( ( dx < 0 ) ? 1 : -1 ); // ie. either no horizontal move or left / right int yinc = ( dy == 0 ) ? 0 : ( ( dy < 0 ) ? 1 : -1 ); // ie. either no vertical move or up / down if( xinc == 0 && yinc == 0 ) { throw new InvalidOperationException(); // if this happens, we're stuffed - it shouldn't ever happen } Square s = piece.CurrentPosition; for(; ; ) { s = s.Offset( xinc, yinc ); if( square == s ) { return true; } if( GetPieceOnSquare( s ) != null ) { return false; } } } public Board MovePiece( IPiece piece, Square destinationSquare ) { Board board = new Board( this ); var capturedPiece = GetPieceOnSquare( destinationSquare ); if( capturedPiece != null ) { if( capturedPiece.White != piece.White ) { board.RemovePiece( capturedPiece ); } else { throw new InvalidOperationException( "tried to move to a square occupied by a piece on our own side" ); } } var pieceCopy = board.GetPieceOnSquare( piece.CurrentPosition ); pieceCopy.CurrentPosition = destinationSquare; board.WhitesTurn = !WhitesTurn; return board; } private void RemovePiece( IPiece capturedPiece ) { for( int i = 0; i < m_pieces.Count; i++ ) { if( m_pieces[ i ].CurrentPosition == capturedPiece.CurrentPosition ) { m_pieces.RemoveAt( i ); break; } } } public override bool Equals( object obj ) { if( obj == null || GetType() != obj.GetType() ) { return false; } Board b = ( Board ) obj; if( WhitesTurn != b.WhitesTurn ) { return false; } if( Pieces.Count != b.Pieces.Count ) { return false; } for( int x = 0; x < 8; x++ ) { for( int y = 0; y < 8; y++ ) { Square s = new Square( x, y ); IPiece piece1 = GetPieceOnSquare( s ); IPiece piece2 = b.GetPieceOnSquare( s ); if( piece1 == null && piece2 != null ) { return false; } if( piece1 != null && piece2 == null ) { return false; } if( piece1 != null && piece2 != null ) { if( !piece1.Equals( piece2 ) ) { return false; } } } } return true; } private List<Board> GetAllNextBoards() { var boards = new List<Board>(); foreach( var piece in m_pieces ) { if( WhitesTurn == piece.White ) { var moves = piece.GetAllMoves( this ); foreach( var move in moves ) { Board newBoard = MovePiece( piece, move ); newBoard.DebugOutput(); boards.Add( newBoard ); } } } return boards; } double Minimax( int depth, double alpha, double beta, bool maximizing, bool whitesTurn, ref long boardsConsidered, TranspositionTable transpositionTable) { bool sortOrder = ( maximizing && !whitesTurn ) || ( !maximizing && whitesTurn ); if( depth == 0 ) { boardsConsidered++; return CalcSidesScore( whitesTurn, transpositionTable ); } List<Board> boards = GetAllNextBoards(); foreach(var board in boards) { board.CalcSidesScore( sortOrder, transpositionTable ); } boards.Sort( ( a, b ) => a.CalcSidesScore( sortOrder, transpositionTable ).CompareTo( b.CalcSidesScore( sortOrder, transpositionTable) ) ); if( maximizing ) { double max = double.MinValue; foreach( var board in boards ) { max = Math.Max( max, board.Minimax( depth - 1, alpha, beta, !maximizing, whitesTurn, ref boardsConsidered, transpositionTable) ); alpha = Math.Max( alpha, max ); if( alpha >= beta ) { break; } } return max; } else { double min = double.MaxValue; foreach( var board in boards ) { min = Math.Min( min, board.Minimax( depth - 1, alpha, beta, !maximizing, whitesTurn, ref boardsConsidered, transpositionTable) ); beta = Math.Min( beta, min ); if( alpha >= beta ) { break; } } return min; } } public Board ThinkAndMove(TranspositionTable transpositionTable) { DateTime t0 = DateTime.UtcNow; IEnumerable<Board> boards = GetAllNextBoards(); double bestScore = double.MinValue; Board bestBoard = null; long boardsConsidered = 0; foreach( var board in boards ) { var score = board.Evaluate( WhitesTurn, ref boardsConsidered, transpositionTable ); if( score > bestScore ) { bestScore = score; bestBoard = board; } } TimeSpan dt = DateTime.UtcNow - t0; Console.WriteLine( "Considered {0} outcomes in {1}s, choosing move with score of {2}", boardsConsidered, dt.TotalSeconds, bestScore ); return bestBoard; } public double Evaluate( bool whitesTurn, ref long boardsConsidered, TranspositionTable transpositionTable) { return Minimax( 2, double.MinValue, double.MaxValue, false, whitesTurn, ref boardsConsidered, transpositionTable ); } public override int GetHashCode() { int hashCode = 0.GetHashCode(); foreach( var piece in m_pieces ) { hashCode = hashCode ^ piece.GetHashCode(); hashCode = hashCode ^ piece.CurrentPosition.GetHashCode(); } return hashCode; } } }
namespace LiveModels { public class Mouse { public int Id { get; set; } public decimal Price { get; set; } public int Dpi { get; set; } public int NumberOfButtons { get; set; } } }
using Microsoft.Xna.Framework; using ProjectMini.src.entitys; using ProjectMini.src.terrain; using System; using System.Collections.Generic; using System.Text; namespace ProjectMini.src.world { public class GreenWorld : World { public static GreenWorld instance; private Dictionary<Vector2, Chunk> v_chunkDictionary = new Dictionary<Vector2, Chunk>(); private List<Chunk> v_chunkList = new List<Chunk>(); private EntityPlayer v_playerentity; private int RenderDistance = 20; public GreenWorld() { instance = this; print("Hello from GreenWorld!"); v_playerentity = (EntityPlayer)Entity.SpawnEntity(new EntityPlayer()); } Vector2 PlayerP; int minX; int maxX; int minY; int maxY; protected override void OnTick() { PlayerP = new Vector2((int)(MathF.Round(EntityPlayer.v_playerPosition.X / Chunk.v_chunkSize) * Chunk.v_chunkSize), (int)(MathF.Round(EntityPlayer.v_playerPosition.Y / Chunk.v_chunkSize) * Chunk.v_chunkSize)); minX = (int)PlayerP.X - RenderDistance; maxX = (int)PlayerP.X + RenderDistance; minY = (int)PlayerP.Y - RenderDistance; maxY = (int)PlayerP.Y + RenderDistance; foreach (var item in v_chunkDictionary) { if (item.Value.v_position.X > maxX || item.Value.v_position.X < minX || item.Value.v_position.Y > maxY || item.Value.v_position.Y < minY) { if (v_chunkDictionary.ContainsKey(item.Value.v_position)) { Chunk chunk = v_chunkDictionary[item.Value.v_position]; v_chunkList.Remove(chunk); v_chunkDictionary.Remove(item.Value.v_position); chunk.Dispose(); } } } for (int x = minX; x < maxX; x += Chunk.v_chunkSize) { for (int y = minY; y < maxY; y += Chunk.v_chunkSize) { Vector2 pos = new Vector2(x, y); if (!v_chunkDictionary.ContainsKey(pos)) { Chunk chunk = new Chunk(pos); v_chunkDictionary.Add(pos, chunk); v_chunkList.Add(chunk); } } } base.OnTick(); } protected override void OnDraw() { for (int i = 0; i < v_chunkList.Count; i++) { v_chunkList[i].Draw(); } base.OnDraw(); } protected override void OnDispose() { Entity.DestroyEntity(v_playerentity); v_playerentity = null; base.OnDispose(); } public TileVoxel GetTileAt(int x, int y) { Chunk chunk = GetChunkAt(x, y); if (chunk != null) { return chunk.v_voxelArray[x - (int)chunk.v_position.X, y - (int)chunk.v_position.Y]; } return TileVoxel.Empty; } public TileVoxel GetTileAt(Vector2 pos) { Chunk chunk = GetChunkAt((int)pos.X, (int)pos.Y); if (chunk != null) { return chunk.v_voxelArray[(int)pos.X - (int)chunk.v_position.X, (int)pos.Y - (int)chunk.v_position.Y]; } return TileVoxel.Empty; } public TileVoxel GetTileAt(float x, float y) { int mx = MathUtils.FloorToInt(x); int my = MathUtils.FloorToInt(y); Chunk chunk = GetChunkAt(mx, my); if (chunk != null) { return chunk.v_voxelArray[mx - (int)chunk.v_position.X, my - (int)chunk.v_position.Y]; } return TileVoxel.Empty; } public Chunk GetChunkAt(int xx, int yy) { Vector2 chunkpos = new Vector2(MathUtils.FloorToInt(xx / (float)Chunk.v_chunkSize) * Chunk.v_chunkSize, MathUtils.FloorToInt(yy / (float)Chunk.v_chunkSize) * Chunk.v_chunkSize); if (v_chunkDictionary.ContainsKey(chunkpos)) { return v_chunkDictionary[chunkpos]; } else { return null; } } } }
using System; using System.Reflection; namespace iSukces.Code.FeatureImplementers { public struct GetHashCodeExpressionDataWithMemberInfo : IComparable<GetHashCodeExpressionDataWithMemberInfo>, IComparable { public GetHashCodeExpressionDataWithMemberInfo(MemberInfo member, GetHashCodeExpressionData code) { Member = member; Code = code; } public static bool operator >(GetHashCodeExpressionDataWithMemberInfo left, GetHashCodeExpressionDataWithMemberInfo right) => left.CompareTo(right) > 0; public static bool operator >=(GetHashCodeExpressionDataWithMemberInfo left, GetHashCodeExpressionDataWithMemberInfo right) => left.CompareTo(right) >= 0; public static bool operator <(GetHashCodeExpressionDataWithMemberInfo left, GetHashCodeExpressionDataWithMemberInfo right) => left.CompareTo(right) < 0; public static bool operator <=(GetHashCodeExpressionDataWithMemberInfo left, GetHashCodeExpressionDataWithMemberInfo right) => left.CompareTo(right) <= 0; public int CompareTo(GetHashCodeExpressionDataWithMemberInfo other) { int GetGroup(GetHashCodeExpressionDataWithMemberInfo x) { var type = x.GetMemberType().StripNullable(); if (type == typeof(bool)) return 3; #if COREFX if (type.GetTypeInfo().IsEnum) return 2; #else if (type.IsEnum) return 2; #endif return 1; } var g1 = GetGroup(this); var g2 = GetGroup(other); return g1.CompareTo(g2); } public int CompareTo(object obj) { if (ReferenceEquals(null, obj)) return 1; return obj is GetHashCodeExpressionDataWithMemberInfo other ? CompareTo(other) : throw new ArgumentException( $"Object must be of type {nameof(GetHashCodeExpressionDataWithMemberInfo)}"); } private Type GetMemberType() { if (Member is PropertyInfo pi) return pi.PropertyType; if (Member is FieldInfo fi) return fi.FieldType; throw new NotImplementedException(); } public MemberInfo Member { get; } public GetHashCodeExpressionData Code { get; } public override string ToString() => Code.ToString(); } }
using System.Collections.Generic; using System.Linq; using KartLib; namespace KartSystem.Presenters { public class AssortmentBuilder { public List<List<SelectableAttribute>> ResultList; public AssortmentBuilder(IList<long> selectedIdAttrTypes, List<SelectableAttribute> attributes) { ResultList = new List<List<SelectableAttribute>>(); if (selectedIdAttrTypes.Count == 1) { var v = from a in attributes where a.IdAttributeType == selectedIdAttrTypes[0] select new {a}; foreach (var list in v.Select(item => new List<SelectableAttribute> {item.a})) { ResultList.Add(list); } } if (selectedIdAttrTypes.Count == 2) { var v = from a in attributes from b in attributes where a.IdAttributeType == selectedIdAttrTypes[0] && b.IdAttributeType == selectedIdAttrTypes[1] select new {a, b}; foreach (var list in v.Select(item => new List<SelectableAttribute> {item.a, item.b})) { ResultList.Add(list); } } if (selectedIdAttrTypes.Count == 3) { var v = from a in attributes from b in attributes from c in attributes where a.IdAttributeType == selectedIdAttrTypes[0] && b.IdAttributeType == selectedIdAttrTypes[1] && c.IdAttributeType == selectedIdAttrTypes[2] select new {a, b, c}; foreach (var list in v.Select(item => new List<SelectableAttribute> {item.a, item.b, item.c})) { ResultList.Add(list); } } if (selectedIdAttrTypes.Count == 4) { var v = from a in attributes from b in attributes from c in attributes from d in attributes where a.IdAttributeType == selectedIdAttrTypes[0] && b.IdAttributeType == selectedIdAttrTypes[1] && c.IdAttributeType == selectedIdAttrTypes[2] && d.IdAttributeType == selectedIdAttrTypes[3] select new {a, b, c, d}; foreach (var list in v.Select(item => new List<SelectableAttribute> {item.a, item.b, item.c, item.d})) { ResultList.Add(list); } } if (selectedIdAttrTypes.Count == 5) { var v = from a in attributes from b in attributes from c in attributes from d in attributes from e in attributes where a.IdAttributeType == selectedIdAttrTypes[0] && b.IdAttributeType == selectedIdAttrTypes[1] && c.IdAttributeType == selectedIdAttrTypes[2] && d.IdAttributeType == selectedIdAttrTypes[3] && e.IdAttributeType == selectedIdAttrTypes[4] select new {a, b, c, d, e}; foreach (var item in v) { var list = new List<SelectableAttribute> {item.a, item.b, item.c, item.d, item.e}; ResultList.Add(list); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ZY.OA.Model.SearchModel { public class BaseParms { public int pageIndex { get; set; } public int pageSize { get; set; } public int total { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Blog.Core.Helper; using Blog.Core.Model; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace Blog.Core.Controllers { /// <summary> /// 测试控制器 /// </summary> [Route("api/[controller]")] [ApiController] [ApiExplorerSettings(IgnoreApi =true)] public class ValuesController : ControllerBase { /// <summary> /// 获取测试数据列表 /// </summary> /// <returns></returns> // GET api/values [HttpGet] //[Authorize(Roles = "Admin")] [Authorize(Policy = "SystemOrAdmin")] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public ActionResult<string> Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody] string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } // DELETE api/values/5 [HttpDelete("{id}")] // 文档隐藏接口 [ApiExplorerSettings(IgnoreApi = true)] public void Delete(int id) { } /// <summary> /// 登录接口:随便输入字符,获取token,然后添加 Authoritarian /// </summary> /// <param name="name"></param> /// <param name="pass"></param> /// <returns></returns> [HttpGet("GetJWTToken")] public async Task<object> GetJWTToken(string name, string pass) { string jwtStr = string.Empty; bool suc = false; //这里就是用户登陆以后,通过数据库去调取数据,分配权限的操作 //这里直接写死了 if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(pass)) { return new JsonResult(new { Status = false, message = "用户名或密码不能为空" }); } TokenModelJWT tokenModel = new TokenModelJWT(); tokenModel.Uid = 1; tokenModel.Role = "Admin"; jwtStr = JwtHelper.IssueJWT(tokenModel); suc = true; return Ok(new { success = suc, token = jwtStr }); } } }
using Common; using Microsoft.DX.Controls; using Newtonsoft.Json; using SignalrData.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using TDC_Union.Model; using TDC_Union.ModelsPush; using TDC_Union.ViewModels; using Windows.Data.Json; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Networking.PushNotifications; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556 namespace TDC_Union.View { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class ClassListPage : Page { private List<ProfileEventArgs> lProfileEventArgs; private List<ClassStudents> lClassStudents; public ClassListPage() { this.InitializeComponent(); Start(); } private async void Start() { lProfileEventArgs = new List<ProfileEventArgs>(); App.Channel.PushNotificationReceived += PushNotificationReceived; CommonVar.PopupCommon.ShowLoading(App.rmap.GetValue("txbLoaddingClassList", App.ctx).ValueAsString); hamburger.LeftPaneWidth = CommonConstant.x_Device * 5 / 6; await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => await CommonVar.SignalRData.SendGetCurrenupdate(App.currenModel.St, App.currenModel.Up, App.currenModel.Ac, App.currenModel.As)); } private async void PushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { if (CommonVar.Page != "ClassListPage") return; if (!string.IsNullOrEmpty(args.TileNotification.Content.InnerText)) { JsonObject root = Windows.Data.Json.JsonValue.Parse(args.TileNotification.Content.InnerText).GetObject(); switch (root["FName"].GetString()) { case CommonConstant.PUpdateCurrentModel: UpdateCurrentModel evUp = JsonConvert.DeserializeObject<UpdateCurrentModel>(args.TileNotification.Content.InnerText); try { if (CommonVar.DateNowSt == "1") { App.currenModel.StClass = evUp.DateNowSt; App.db.Update<CurrenModel>(App.currenModel); } } catch (Exception) { } break; case CommonConstant.PUpdateCurrentModelExist: UpdateCurrentModel ev = JsonConvert.DeserializeObject<UpdateCurrentModel>(args.TileNotification.Content.InnerText); Common.CommonVar.DateNowSt = ev.DateNowSt; if (Common.CommonVar.DateNowSt == "1") { await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => await CommonVar.SignalRData.SendClassList()); await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => await CommonVar.SignalRData.SendGetCurrenupdate()); } else { lClassStudents = App.db.SelectList<ClassStudents>(); if (lClassStudents.Count != 0) { ClassListListSelector.ItemsSource = lClassStudents; CommonVar.PopupCommon.CloseLoading(); } else { await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => await CommonVar.SignalRData.SendClassList()); } } break; case CommonConstant.PProfileClassEventArgs: ProfileEventArgs _ProfileEventArgs = JsonConvert.DeserializeObject<ProfileEventArgs>(args.TileNotification.Content.InnerText); if (_ProfileEventArgs.StudentID != "-1") { if (string.IsNullOrEmpty(txbClassListName.Text)) { txbClassListName.Text = _ProfileEventArgs.ClassName; } ClassStudents classStudents = new ClassStudents(_ProfileEventArgs); App.db.InsertOrReplace<ClassStudents>(classStudents); lProfileEventArgs.Add(_ProfileEventArgs); ClassListListSelector.ItemsSource = null; ClassListListSelector.ItemsSource = lProfileEventArgs; } else { CommonVar.PopupCommon.CloseLoading(); } break; } } }); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. /// This parameter is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { } private void txbClassList_Tapped(object sender, TappedRoutedEventArgs e) { if (hamburger.IsLeftPaneOpen) hamburger.IsLeftPaneOpen = false; else { hamburger.IsLeftPaneOpen = true; } } private async void SetProfile(dynamic student) { try { student = (ProfileEventArgs)student; student = lProfileEventArgs.Find(i => i.StudentID == student.StudentID); await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { txbClass.Text = student.ClassName; txbDOB.Text = student.DOB; txbEmail.Text = student.Email; txbEthnic.Text = student.Ethnic; txbFaculaty.Text = student.FacultyName; txbFullName.Text = student.FirstName + " " + student.LastName; txbGender.Text = student.Gender; if (student.Nationality != "Việt Nam" && !string.IsNullOrEmpty(student.Nationality)) { txbNation.Text = student.Nationality; } txbPhone.Text = student.Tel; txbPOB.Text = student.POB; txbReligious.Text = student.Religion; txbPOU.Text = student.POU; txbPOU.Text = student.POU; }); } catch (Exception) { student = (ClassStudents)student; student = lClassStudents.Find(i => i.StudentID == student.StudentID); await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { txbClass.Text = student.ClassName; txbDOB.Text = student.DOB; txbEmail.Text = student.Email; txbEthnic.Text = student.Ethnic; txbFaculaty.Text = student.FacultyName; txbFullName.Text = student.FirstName + " " + student.LastName; txbGender.Text = student.Gender; if (student.Nationality != "Việt Nam" && !string.IsNullOrEmpty(student.Nationality)) { txbNation.Text = student.Nationality; } txbPhone.Text = student.Tel; txbPOB.Text = student.POB; txbReligious.Text = student.Religion; txbPOU.Text = student.POU; txbPOU.Text = student.POU; }); } hamburger.IsLeftPaneOpen = false; } private void ClassListListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e) { dynamic ac; ac = ClassListListSelector.SelectedItem; SetProfile(ac); } private void Page_Loaded(object sender, RoutedEventArgs e) { hamburger.IsLeftPaneOpen = true; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bullet : MonoBehaviour { public float speed = 20f; public Rigidbody2D rb; public GameObject particle; public AudioClip hitSound; // Use this for initialization void Start () { rb.velocity = transform.right * speed; } private void OnTriggerEnter2D(Collider2D other) { if (other.tag == "Wall") { AudioManager.instance.playClip(hitSound); Instantiate(particle, transform.position, transform.rotation); Destroy(gameObject); GameManager.instance.playersTurn = false; } else if (other.tag == "Enemy") { Enemy enemy = other.GetComponent<Enemy>(); if (enemy != null) { enemy.loseHp(); } GameManager.instance.CheckEnemy(); Destroy(gameObject); GameManager.instance.playersTurn = false; } } }
#region << 版 本 注 释 - v1 >> /* * ======================================================================== * * 作者:lith * 时间:2019-05-10 * 邮箱:sersms@163.com * * ======================================================================== */ #endregion using Newtonsoft.Json; namespace SAAS.FrameWork.Mail { public class MailSenderAccount { [JsonIgnore] private string _From; /// <summary> /// 发件人邮件地址,例:123456789@qq.com /// </summary> [JsonProperty] public string address { set { _From = value; try { _UserName = value.Remove(value.LastIndexOf('@')); } catch { _UserName = value; } } get { return _From; } } /// <summary> /// 用户名,注意如果发件人地址是abc@def.com ,则用户名是abc 而不是abc@def.com /// </summary> private string _UserName; [JsonIgnore] public string UserName { get { return _UserName; } } /// <summary> /// 密码(发件人的邮箱登陆密码或授权码) /// </summary> [JsonProperty] public string password{ get; set; } /// <summary> /// 发送邮件的服务器地址或IP,例:"smtp.qq.com" /// </summary> [JsonProperty] public string host { get; set; } public MailSenderAccount(string address, string password, string host) { this.address = address; this.password = password; this.host = host; } public MailSenderAccount() { } } }
using System; using System.Threading.Tasks; namespace MySql.Data.Protocol.Serialization { internal sealed class BufferedByteReader { public BufferedByteReader() { m_buffer = new byte[16384]; } public ValueTask<ArraySegment<byte>> ReadBytesAsync(IByteHandler byteHandler, int count, IOBehavior ioBehavior) { // check if read can be satisfied from the buffer if (m_remainingData.Count >= count) { var readBytes = m_remainingData.Slice(0, count); m_remainingData = m_remainingData.Slice(count); return new ValueTask<ArraySegment<byte>>(readBytes); } // get a buffer big enough to hold all the data, and move any buffered data to the beginning var buffer = count > m_buffer.Length ? new byte[count] : m_buffer; if (m_remainingData.Count > 0) { Buffer.BlockCopy(m_remainingData.Array, m_remainingData.Offset, buffer, 0, m_remainingData.Count); m_remainingData = new ArraySegment<byte>(buffer, 0, m_remainingData.Count); } return ReadBytesAsync(byteHandler, new ArraySegment<byte>(buffer, m_remainingData.Count, buffer.Length - m_remainingData.Count), count, ioBehavior); } private ValueTask<ArraySegment<byte>> ReadBytesAsync(IByteHandler byteHandler, ArraySegment<byte> buffer, int totalBytesToRead, IOBehavior ioBehavior) { // keep reading data synchronously while it is available var readBytesTask = byteHandler.ReadBytesAsync(buffer, ioBehavior); while (readBytesTask.IsCompleted) { ValueTask<ArraySegment<byte>> result; if (HasReadAllData(readBytesTask.Result, ref buffer, totalBytesToRead, out result)) return result; readBytesTask = byteHandler.ReadBytesAsync(buffer, ioBehavior); } // call .ContinueWith (as a separate method, so that the temporary class for the lambda is only allocated if necessary) return AddContinuation(readBytesTask, byteHandler, buffer, totalBytesToRead, ioBehavior); ValueTask<ArraySegment<byte>> AddContinuation(ValueTask<int> readBytesTask_, IByteHandler byteHandler_, ArraySegment<byte> buffer_, int totalBytesToRead_, IOBehavior ioBehavior_) => readBytesTask_.ContinueWith(x => HasReadAllData(x, ref buffer_, totalBytesToRead_, out var result_) ? result_ : ReadBytesAsync(byteHandler_, buffer_, totalBytesToRead_, ioBehavior_)); } /// <summary> /// Returns <c>true</c> if all the required data has been read, then sets <paramref name="result"/> to a <see cref="ValueTask{ArraySegment{byte}}"/> representing that data. /// Otherwise, returns <c>false</c> and updates <paramref name="buffer"/> to where more data should be placed when it's read. /// </summary> /// <param name="readBytesCount">The number of bytes that have just been read into <paramref name="buffer"/>.</param> /// <param name="buffer">The <see cref="ArraySegment{byte}"/> that contains all the data read so far, and that will receive more data read in the future. It is assumed that data is stored /// at the beginning of the array owned by <paramref name="buffer"/> and that <code>Offset</code> indicates where to place future data.</param> /// <param name="totalBytesToRead">The total number of bytes that need to be read.</param> /// <param name="result">On success, a <see cref="ValueTask{ArraySegment{byte}}"/> representing all the data that was read.</param> /// <returns><c>true</c> if all data has been read; otherwise, <c>false</c>.</returns> private bool HasReadAllData(int readBytesCount, ref ArraySegment<byte> buffer, int totalBytesToRead, out ValueTask<ArraySegment<byte>> result) { if (readBytesCount == 0) { var data = m_remainingData; m_remainingData = default(ArraySegment<byte>); result = new ValueTask<ArraySegment<byte>>(data); return true; } var bufferSize = buffer.Offset + readBytesCount; if (bufferSize >= totalBytesToRead) { var bufferBytes = new ArraySegment<byte>(buffer.Array, 0, bufferSize); var requestedBytes = bufferBytes.Slice(0, totalBytesToRead); m_remainingData = bufferBytes.Slice(totalBytesToRead); result = new ValueTask<ArraySegment<byte>>(requestedBytes); return true; } buffer = new ArraySegment<byte>(buffer.Array, bufferSize, buffer.Array.Length - bufferSize); result = default(ValueTask<ArraySegment<byte>>); return false; } ArraySegment<byte> m_remainingData; readonly byte[] m_buffer; } }
using System; using System.Collections.Generic; using UserService.Model; using UserService.Model.Memento; namespace UserServiceTests.UnitTests.Data { public class PatientBuilder { private PatientAccountMemento _patientAccountMemento; public PatientBuilder() { _patientAccountMemento = new PatientAccountMemento() { Jmbg = "2506998524102", Name = "Pera", Surname = "Peric", Gender = Gender.Male, City = new CityMemento() { Id = 1, Name = "Novi Sad", Country = new CountryMemento() { Id = 1, Name = "Srbija" } }, DateOfBirth = new DateTime(1998, 6, 25), Email = "pera.peric@gmail.com", HomeAddress = "Tolstojeva 12", ImageName = "1.jpg", IsActivated = false, IsBlocked = false, MaliciousActions = new List<MaliciousActionMemento>(), Password = "perapera123", Phone = "065895452", UserType = UserType.Patient }; } public PatientAccount GetUnactivated() { _patientAccountMemento.IsActivated = false; _patientAccountMemento.IsBlocked = false; _patientAccountMemento.MaliciousActions = new List<MaliciousActionMemento>(); return new PatientAccount(_patientAccountMemento); } public PatientAccount GetActivated(int numberOfMaliciousActions) { List<MaliciousActionMemento> maliciousActions = new List<MaliciousActionMemento>(); _patientAccountMemento.IsActivated = true; _patientAccountMemento.IsBlocked = false; for (int i = 1; i <= numberOfMaliciousActions; i++) { maliciousActions.Add(new MaliciousActionMemento() { Id = i, TimeStamp = DateTime.Now, Type = MaliciousActionType.AppointmentCancellation }); } _patientAccountMemento.MaliciousActions = maliciousActions; return new PatientAccount(_patientAccountMemento); } public PatientAccount GetBlocked() { _patientAccountMemento.IsActivated = true; _patientAccountMemento.IsBlocked = true; _patientAccountMemento.MaliciousActions = new List<MaliciousActionMemento>() { new MaliciousActionMemento() { Id = 1, TimeStamp = DateTime.Now, Type = MaliciousActionType.AppointmentCancellation }, new MaliciousActionMemento() { Id = 2, TimeStamp = DateTime.Now, Type = MaliciousActionType.AppointmentCancellation }, new MaliciousActionMemento() { Id = 3, TimeStamp = DateTime.Now, Type = MaliciousActionType.AppointmentCancellation }, new MaliciousActionMemento() { Id = 4, TimeStamp = DateTime.Now, Type = MaliciousActionType.AppointmentCancellation } }; return new PatientAccount(_patientAccountMemento); } } }
namespace Mashup.Data.Mapping { using System; using System.Data.Entity; using System.Data.Entity.ModelConfiguration; using System.Data.Entity.ModelConfiguration.Configuration; using System.Linq; using System.Reflection; /// <summary> /// Klasa inicjalizująca mappingi /// </summary> public static class MapInitializer { /// <summary> /// Metoda inicjalizująca mappingi /// </summary> /// <param name="modelBuilder"></param> public static void InitMapping(DbModelBuilder modelBuilder) { var classMaps = Assembly.GetExecutingAssembly().GetTypes().Where(type => type.BaseType != null && type.BaseType.Name == typeof(EntityTypeConfiguration<>).Name); var addMethod = typeof(ConfigurationRegistrar).GetMethods(BindingFlags.Instance | BindingFlags.Public).FirstOrDefault(method => method.Name == "Add" && method.GetGenericArguments()[0].Name == "TEntityType"); if (addMethod == null) { return; } foreach (var classMap in classMaps.Where(x => x.BaseType != null)) { var instance = Activator.CreateInstance(classMap); if (classMap.BaseType != null) { var addClassMap = addMethod.MakeGenericMethod(classMap.BaseType.GetGenericArguments()[0]); addClassMap.Invoke(modelBuilder.Configurations, new[] { instance }); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Dominio.EntidadesNegocio; namespace Dominio.EntidadesNegocio { public class ProductoImportado : Producto { public string Pais{ get; set; } public static decimal ImpuestoImportacion{ get; set; } public override decimal RetornarPrecio() { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace EpisodeGrabber.Library.Entities { public class RottenTomatoesData { public int ID { get; set; } public string Url { get; set; } public string IMDBId { get; set; } public string Name { get; set; } public string MPAARating { get; set; } public string Studio { get; set; } public int Runtime { get; set; } public string Description { get; set; } public DateTime Created { get; set; } public List<string> Genres { get; set; } public List<Image> Images { get; set; } public Rating CriticsRating { get; set; } public Rating AudienceRating { get; set; } public RottenTomatoesData() { this.Genres = new List<string>(); this.Images = new List<Image>(); } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Text; namespace PingoSnake { class Animation { public string Name; private int[] Frames; private double TimePerFrame; private bool Loop; public bool Locked; public bool Forced; private int CurrentFrame; private double TimePassed; public Animation(string name, int[] frames, double timePerFrame, bool loop=true, bool locked=false) { this.Name = name; this.Frames = frames; this.TimePerFrame= timePerFrame; this.Loop = loop; this.Locked = locked; this.Forced = false; this.CurrentFrame = 0; this.TimePassed = 0.0f; } public void Update(GameTime gameTime) { this.TimePassed += gameTime.ElapsedGameTime.TotalSeconds; if (this.TimePassed > this.TimePerFrame) { this.TimePassed = this.TimePassed % this.TimePerFrame; if (this.CurrentFrame < this.Frames.Length-1) { this.CurrentFrame += 1; } else if (this.Loop) { this.CurrentFrame = 0; } } } public int GetCurrentFrame() { return this.Frames[this.CurrentFrame]; } public bool isFinished() { return this.CurrentFrame == this.Frames.Length - 1; } public void Reset() { this.CurrentFrame = 0; this.TimePassed = 0.0f; this.Forced = false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using System.Data; using System.Data.SqlClient; using WindowsFormsApplication2; using System.IO; public partial class zjdlright3 : System.Web.UI.Page { SqlConnection mycn; string zjID; string IDs; string mycns = ConfigurationSettings.AppSettings["connString"]; protected void Page_Load(object sender, EventArgs e) { if (Session["zjuser"] == null) { Response.Write("<script>alert('账号已失效,请重新登录!');top.location.href = 'login.aspx';</script>"); return; } if (!Page.IsPostBack) { using (SqlConnection mycn = new SqlConnection(mycns)) { using (SqlCommand sqlcmm = mycn.CreateCommand()) { //专家ID mycn.Open(); string users = Session["zjuser"].ToString(); string mycm1 = "select userID from User_Reg where username='" + users + "'"; SqlCommand mycmd1 = new SqlCommand(mycm1, mycn); SqlDataReader myrd1; myrd1 = mycmd1.ExecuteReader(); myrd1.Read(); IDs = myrd1[0].ToString(); Session["ids"] = IDs; myrd1.Close(); zjID = IDs; sqlcmm.CommandText = "select * from xmk where spzt != '在园' and spzt != '毕业' and tj = 1 and (spzjID = '" + IDs + "' or spzjID2 = '" + IDs + "' or spzjID3 = '" + IDs + "')"; DataTable dt = new DataTable(); SqlDataAdapter adapter = new SqlDataAdapter(sqlcmm); adapter.Fill(dt); if (dt.Rows.Count > 0) //当数据库有数据的时候绑定数据 { this.GridView1.DataSource = dt; this.GridView1.DataBind(); bindgrid(); } else { img_nodigit.Visible = true; } mycn.Close(); } } } IDs = Session["ids"].ToString(); } void bindgrid() { //专家ID SqlConnection mycn = new SqlConnection(mycns); mycn.Open(); //查询数据库 DataSet ds = new DataSet(); using (SqlConnection sqlconn = new SqlConnection(mycns)) { SqlDataAdapter sqld = new SqlDataAdapter("select xmID,xmmc,fzr,lxfs,xmqx,xmlb,zjshzt,zjshzt2,zjshzt3,spzjID,spzjID2,spzjID3 from xmk where spzt != '在园' and spzt != '毕业' and tj = 1 and (spzjID = '" + IDs + "' or spzjID2 = '" + IDs + "' or spzjID3 = '" + IDs + "') order by spzt", sqlconn); sqld.Fill(ds, "tabenterprise"); } //ds.Tables[0].Rows[0]["字段"] foreach (DataRow row in ds.Tables[0].Rows) { //判断与那个专家几与此专家账号ID相同 if (row[10].ToString() == zjID) { row[6] = row[7]; } if (row[11].ToString() == zjID) { row[6] = row[8]; } } if (ds.Tables[0].Rows.Count > 0) //当数据库有数据的时候绑定数据 { for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { string temp = ds.Tables[0].Rows[i]["xmlb"].ToString().Trim(), s1, s2; s1 = temp.Replace("a", "企业技术服务类"); s2 = s1.Replace("b", " 双创人才项目"); ds.Tables[0].Rows[i]["xmlb"] = s2; } this.GridView1.DataSource = ds.Tables[0]; this.GridView1.DataBind(); } else { img_nodigit.Visible = true; } //排序,将未审核的放在上面 ds.Tables[0].DefaultView.Sort = "zjshzt DESC"; //为控件绑定数据 GridView1.DataSource = ds.Tables["tabenterprise"].DefaultView; GridView1.DataBind(); mycn.Close(); //countDropDownList(); } protected void gridList_RowDataBound(object sender, GridViewRowEventArgs e) { string gridViewHeight = ConfigurationSettings.AppSettings["gridViewHeight"]; GridView1.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; //如果是绑定数据行 if (e.Row.RowType == DataControlRowType.DataRow) { //鼠标经过时,行背景色变 e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#e5ebee'"); //鼠标移出时,行背景色变 e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c"); // 控制每一行的高度 e.Row.Attributes.Add("style", gridViewHeight); // 点击一行是复选框选中 CheckBox chk = (CheckBox)e.Row.FindControl("CheckBox1"); //e.Row.Attributes["onclick"] = "if(" + chk.ClientID + ".checked) " + chk.ClientID + ".checked = false ; else " + chk.ClientID + ".checked = true ;"; // 双击弹出新页面,并传递id值 int row_index = e.Row.RowIndex; string ID = GridView1.DataKeys[row_index].Value.ToString(); e.Row.Attributes.Add("ondblclick", "newwin=window.open('zjdlxmsp.aspx?xmID=" + ID + "','newwin')"); // 未审核的行为红色 var drv = (DataRowView)e.Row.DataItem; string status = drv["zjshzt"].ToString().Trim(); if (status.Trim() == "未审核") { e.Row.Cells[6].ForeColor = System.Drawing.Color.Red; } } } protected void sshs(object sender, EventArgs e) { //专家ID SqlConnection mycn = new SqlConnection(mycns); mycn.Open(); //查询数据库 //string sqlconnstr = ConfigurationManager.ConnectionStrings["server=LAPTOP-JFN4NKUE;database=teaching;User ID=zl;pwd=123456;Trusted_Connection=no"].ConnectionString; // Label1.Text = "查找成功"; DataSet ds = new DataSet(); //mycn.Open(); string userss = ss_text.Text.Trim().ToString(); String cxtj = DropDownList1.SelectedItem.Text; if (cxtj == "项目名称") { cxtj = "xmmc"; } else if (cxtj == "负责人") { cxtj = "fzr"; } using (SqlConnection sqlconn = new SqlConnection(mycns)) { mycn.Open(); SqlDataAdapter sqld = new SqlDataAdapter("select * from xmk where " + cxtj + " like '%" + userss + "%' and spzt != '在园' and spzt != '毕业' and tj = 1 and (spzjID = '" + IDs + "' or spzjID2 = '" + IDs + "' or spzjID3 = '" + IDs + "')", sqlconn); sqld.Fill(ds, "tabenterprise"); mycn.Close(); } if (ds.Tables[0].Rows.Count > 0) //当数据库有数据的时候绑定数据 { for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { string temp = ds.Tables[0].Rows[i]["xmlb"].ToString().Trim(), s1, s2; s1 = temp.Replace("a", "企业技术服务类"); s2 = s1.Replace("b", " 双创人才项目"); ds.Tables[0].Rows[i]["xmlb"] = s2; } this.GridView1.DataSource = ds.Tables[0]; this.GridView1.DataBind(); } else { img_nodigit.Visible = true; } mycn.Close(); //为控件绑定数据 GridView1.DataSource = ds.Tables["tabenterprise"].DefaultView; GridView1.DataBind(); } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { if (DropDownList1.SelectedItem.Text.Trim() == "项目类别") { ss_text.Visible = false; ss_droplist.Visible = false; DropDownList2.Visible = true; btss.Visible = false; } else if (DropDownList1.SelectedItem.Text.Trim() == "审核状态") { ss_text.Visible = false; DropDownList2.Visible = false; ss_droplist.Visible = true; btss.Visible = false; } else { ss_text.Visible = true; ss_droplist.Visible = false; DropDownList2.Visible = false; btss.Visible = true; } } protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e) { //专家ID SqlConnection mycn = new SqlConnection(mycns); mycn.Open(); DataSet ds = new DataSet(); //mycn.Open(); string userss; if (DropDownList2.SelectedValue == "ss") { userss = ""; } else { userss = DropDownList2.SelectedValue.Trim(); } String cxtj = DropDownList1.SelectedValue.Trim(); using (SqlConnection sqlconn = new SqlConnection(mycns)) { SqlDataAdapter sqld = new SqlDataAdapter("select * from xmk where " + cxtj + " like '%" + userss + "%' and spzt != '在园' and spzt != '毕业' and tj = 1 and (spzjID = '" + IDs + "' or spzjID2 = '" + IDs + "' or spzjID3 = '" + IDs + "')", sqlconn); sqld.Fill(ds, "tabenterprise"); mycn.Close(); } //为控件绑定数据 GridView1.DataSource = ds.Tables["tabenterprise"].DefaultView; GridView1.DataBind(); DataSet ds1 = new DataSet(); SqlConnection mycn1 = new SqlConnection(mycns); using (SqlConnection sqlconn = new SqlConnection(mycns)) { if (userss == "") { mycn1.Open(); SqlDataAdapter sqld = new SqlDataAdapter("select * from xmk ", sqlconn); sqld.Fill(ds1, "tabenterprise"); mycn1.Close(); } else { mycn1.Open(); SqlDataAdapter sqld = new SqlDataAdapter("select * from xmk where " + cxtj + " like '%" + userss + "%' and spzt != '在园' and spzt != '毕业' and tj = 1 and (spzjID = '" + IDs + "' or spzjID2 = '" + IDs + "' or spzjID3 = '" + IDs + "')", sqlconn); sqld.Fill(ds1, "tabenterprise"); mycn1.Close(); } } if (ds1.Tables[0].Rows.Count > 0) //当数据库有数据的时候绑定数据 { for (int i = 0; i < ds1.Tables[0].Rows.Count; i++) { string temp = ds1.Tables[0].Rows[i]["xmlb"].ToString().Trim(), s1, s2; s1 = temp.Replace("a", "企业技术服务类"); s2 = s1.Replace("b", " 双创人才项目"); ds1.Tables[0].Rows[i]["xmlb"] = s2; } this.GridView1.DataSource = ds1.Tables[0]; this.GridView1.DataBind(); } else { img_nodigit.Visible = true; } //为控件绑定数据 GridView1.DataSource = ds1.Tables["tabenterprise"].DefaultView; GridView1.DataBind(); } protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridView1.PageIndex = e.NewPageIndex; bindgrid(); //数据绑定 } protected void PageDropDownList_SelectedIndexChanged(Object sender, EventArgs e) { // Retrieve the pager row. GridViewRow pagerRow = GridView1.BottomPagerRow; // Retrieve the PageDropDownList DropDownList from the bottom pager row. DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList"); // Set the PageIndex property to display that page selected by the user. GridView1.PageIndex = pageList.SelectedIndex; bindgrid(); //数据绑定 } protected void GridView1_DataBound(Object sender, EventArgs e) { GridView1.BottomPagerRow.Visible = true;//只有一页数据的时候也再下面显示pagerrow,需要top的再加Top // Retrieve the pager row. GridViewRow pagerRow = GridView1.BottomPagerRow; // Retrieve the DropDownList and Label controls from the row. DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList"); Label pageLabel = (Label)pagerRow.Cells[0].FindControl("CurrentPageLabel"); if (pageList != null) { // Create the values for the DropDownList control based on // the total number of pages required to display the data // source. for (int i = 0; i < GridView1.PageCount; i++) { // Create a ListItem object to represent a page. int pageNumber = i + 1; ListItem item = new ListItem(pageNumber.ToString()); // If the ListItem object matches the currently selected // page, flag the ListItem object as being selected. Because // the DropDownList control is recreated each time the pager // row gets created, this will persist the selected item in // the DropDownList control. if (i == GridView1.PageIndex) { item.Selected = true; } // Add the ListItem object to the Items collection of the // DropDownList. pageList.Items.Add(item); } } if (pageLabel != null) { // Calculate the current page number. int currentPage = GridView1.PageIndex + 1; // Update the Label control with the current page information. pageLabel.Text = "Page " + currentPage.ToString() + " of " + GridView1.PageCount.ToString(); } } protected void CountDropDownList_SelectedIndexChanged(Object sender, EventArgs e) { GridViewRow pagerRow = GridView1.BottomPagerRow; DropDownList countList = (DropDownList)pagerRow.Cells[0].FindControl("CountDropDownList"); string selectText = countList.SelectedItem.Text; switch (selectText) { case "默认": { GridView1.PageSize = 7; } break; case "10": { GridView1.PageSize = 10; } break; case "20": { GridView1.PageSize = 20; } break; case "全部": { mycn = new SqlConnection(mycns); SqlCommand mycmm = new SqlCommand("select count(*) from xmk", mycn); mycn.Open(); int count = (int)mycmm.ExecuteScalar(); mycn.Close(); GridView1.PageSize = count; } break; default: break; } bindgrid(); } protected void ss_droplist_SelectedIndexChanged(object sender, EventArgs e) { DataSet ds = new DataSet(); SqlConnection mycn = new SqlConnection(mycns); //mycn.Open(); string userss; if (ss_droplist.SelectedValue == "ss1") { userss = ""; } else { userss = ss_droplist.SelectedItem.Text.Trim(); } String cxtj = DropDownList1.SelectedValue.Trim(); using (SqlConnection sqlconn = new SqlConnection(mycns)) { mycn.Open(); SqlDataAdapter sqld = new SqlDataAdapter("select * from xmk where " + cxtj + " like '%" + userss + "%' and spzt != '在园' and spzt != '毕业' and tj = 1 and (spzjID = '" + IDs + "' or spzjID2 = '" + IDs + "' or spzjID3 = '" + IDs + "')", sqlconn); sqld.Fill(ds, "tabenterprise"); mycn.Close(); } //为控件绑定数据 GridView1.DataSource = ds.Tables["tabenterprise"].DefaultView; GridView1.DataBind(); DataSet ds1 = new DataSet(); SqlConnection mycn1 = new SqlConnection(mycns); using (SqlConnection sqlconn = new SqlConnection(mycns)) { mycn1.Open(); SqlDataAdapter sqld = new SqlDataAdapter("select * from xmk where " + cxtj + " like '%" + userss + "%' and spzt != '在园' and spzt != '毕业' and tj = 1 and (spzjID = '" + IDs + "' or spzjID2 = '" + IDs + "' or spzjID3 = '" + IDs + "')", sqlconn); sqld.Fill(ds1, "tabenterprise"); mycn1.Close(); } if (ds1.Tables[0].Rows.Count > 0) //当数据库有数据的时候绑定数据 { for (int i = 0; i < ds1.Tables[0].Rows.Count; i++) { string temp = ds1.Tables[0].Rows[i]["xmlb"].ToString().Trim(), s1, s2; s1 = temp.Replace("a", "企业技术服务类"); s2 = s1.Replace("b", " 双创人才项目"); ds1.Tables[0].Rows[i]["xmlb"] = s2; } img_nodigit.Visible = false ; } else { img_nodigit.Visible = true; } //为控件绑定数据 GridView1.DataSource = ds1.Tables["tabenterprise"].DefaultView; GridView1.DataBind(); } }
namespace MySurveys.Web.Areas.Administration.ViewModels { using System.ComponentModel.DataAnnotations; using System.Web.Mvc; using AutoMapper; using Base; using Models; using MvcTemplate.Web.Infrastructure.Mapping; public class UserViewModel : AdministrationViewModel, IMapFrom<User>, IHaveCustomMappings { [HiddenInput(DisplayValue = false)] public string Id { get; set; } [UIHint("CustomString")] public string UserName { get; set; } [UIHint("CustomString")] public string Email { get; set; } [HiddenInput(DisplayValue = false)] public int TotalSurveys { get; set; } [HiddenInput(DisplayValue = false)] public int TotalResponses { get; set; } public void CreateMappings(IMapperConfiguration configuration) { configuration.CreateMap<User, UserViewModel>() .ForMember(m => m.TotalSurveys, opt => opt.MapFrom(r => r.Surveys.Count)) .ForMember(m => m.TotalResponses, opt => opt.MapFrom(r => r.Responses.Count)) .ReverseMap(); } } }
using System; using System.IO; using Microsoft.EntityFrameworkCore.Migrations; namespace Zovi_Fashion.Data.Migrations { public partial class Init : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Studios", columns: table => new { StudioID = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Title = table.Column<string>(maxLength: 100, nullable: false), StudioDesc = table.Column<string>(maxLength: 1000, nullable: false), PostDate = table.Column<DateTime>(nullable: false), Extension = table.Column<string>(maxLength: 20, nullable: false) }, constraints: table => { table.PrimaryKey("PK_Studios", x => x.StudioID); }); migrationBuilder.CreateTable( name: "Brands", columns: table => new { BrandID = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), BrandName = table.Column<string>(maxLength: 100, nullable: false) }, constraints: table => { table.PrimaryKey("PK_Brands", x => x.BrandID); }); migrationBuilder.CreateTable( name: "Products", columns: table => new { ProductID = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), ProductName = table.Column<string>(maxLength: 200, nullable: false), Fabric = table.Column<string>(maxLength: 400, nullable: true), ManufacturingYear = table.Column<string>(maxLength: 400, nullable: true), Description = table.Column<string>(maxLength: 400, nullable: true), Color = table.Column<string>(maxLength: 400, nullable: true), Fit = table.Column<string>(maxLength: 400, nullable: true), SleveLength = table.Column<string>(maxLength: 400, nullable: true), Occasion = table.Column<string>(maxLength: 400, nullable: true), PatternType = table.Column<string>(maxLength: 400, nullable: true), Size = table.Column<string>(maxLength: 400, nullable: true), Neck = table.Column<string>(maxLength: 400, nullable: true), WashCare = table.Column<string>(maxLength: 400, nullable: true), SoldBy = table.Column<string>(maxLength: 400, nullable: true), Price = table.Column<string>(maxLength: 400, nullable: true), Extension = table.Column<string>(maxLength: 20, nullable: false), BrandID = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Products", x => x.ProductID); table.ForeignKey( name: "FK_Products_Brands_BrandID", column: x => x.BrandID, principalTable: "Brands", principalColumn: "BrandID", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "ProductReviews", columns: table => new { ReviewID = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Name = table.Column<string>(maxLength: 100, nullable: false), Rating = table.Column<int>(nullable: false), ReviewText = table.Column<string>(maxLength: 1000, nullable: false), ProductID = table.Column<int>(nullable: false), ReviewDate = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_ProductReviews", x => x.ReviewID); table.ForeignKey( name: "FK_ProductReviews_Products_ProductID", column: x => x.ProductID, principalTable: "Products", principalColumn: "ProductID", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_ProductReviews_ProductID", table: "ProductReviews", column: "ProductID"); migrationBuilder.CreateIndex( name: "IX_Products_BrandID", table: "Products", column: "BrandID"); var sqlFile = Path.Combine(".\\Scripts", @"records.sql"); migrationBuilder.Sql(File.ReadAllText(sqlFile)); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Studios"); migrationBuilder.DropTable( name: "ProductReviews"); migrationBuilder.DropTable( name: "Products"); migrationBuilder.DropTable( name: "Brands"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HVCheck.Models { public class DanhSachDaiLy { private static DanhSachDaiLy _instance = null; public static DanhSachDaiLy Instance() { if (_instance == null) _instance = new DanhSachDaiLy(); return _instance; } public int ID { get; set; } public string MaDL { get; set; } public string TenDL { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FrbaOfertas.Model { public class Usuario { public List<String> atributesModify = new List<string>(); private Int32 _id_usuario; private String _usu_username; private String _usu_contrasenia; private Int32 _usu_cant_intentos_fallidos; private List<Rol> _roles = new List<Rol>() ; private Boolean _usu_activo; public Int32 id_usuario { get { return this._id_usuario; } set { this._id_usuario = value; atributesModify.Add("id_usuario"); } } [System.ComponentModel.DisplayName("Username")] public String usu_username { get { return this._usu_username; } set { this._usu_username = value; atributesModify.Add("usu_username"); } } [System.ComponentModel.DisplayName("Contraseña")] public String usu_contrasenia { get { return this._usu_contrasenia; } set { this._usu_contrasenia = value; atributesModify.Add("usu_contrasenia"); } } [System.ComponentModel.DisplayName("Intentos Fallidos")] public Int32 usu_cant_intentos_fallidos { get { return this._usu_cant_intentos_fallidos; } set { this._usu_cant_intentos_fallidos = value; atributesModify.Add("usu_cant_intentos_fallidos"); } } [System.ComponentModel.DisplayName("Activo")] public Boolean usu_activo { get { return this._usu_activo; } set { this._usu_activo = value; atributesModify.Add("usu_activo"); } } public List<Rol> roles { get { return this._roles; } set { this._roles = value; } } public Usuario(string user, String p2, bool p3) { // TODO: Complete member initialization this.usu_username = (String)user; this.usu_contrasenia = (String)p2; this.usu_activo = (Boolean)p3; } public Usuario() { // TODO: Complete member initialization } public Usuario(string p,string pass) { // TODO: Complete member initialization this.usu_username = p; this.usu_contrasenia = pass; } public List<String> getAtributeMList() { return atributesModify.Distinct().ToList(); } public dynamic getMethodString(String methodName) { return this.GetType().GetProperty(methodName).GetValue(this, null); ; } public void restartMList() { this.atributesModify.Clear(); } public void setMethodString(String methodName, object value) { this.GetType().GetProperty(methodName).SetValue(this, value); } } }
namespace NomNom { #region Using Directives using System.Collections.Generic; using System.Configuration; using System.IO; using System.Xml.Serialization; using Contracts; using Domain.Models; #endregion public class ReadMonitorSettings : IReadMonitorSettings { public IEnumerable<Monitor> Read() { IEnumerable<Monitor> monitors; var monitorPath = ConfigurationManager.AppSettings["monitorFilePath"]; var xmlReader = new StreamReader(monitorPath); var xmlSerializer = new XmlSerializer(typeof(List<Monitor>)); using (xmlReader) { monitors = xmlSerializer.Deserialize(xmlReader) as IEnumerable<Monitor>; } return monitors; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public enum GameState { wait, move } public class Board : MonoBehaviour { #region Private Attributes private float score; private GameObject[] dots; private FindMatches finder; #endregion #region Public Attributes public Slider slider; public Text scoreTag; public GameObject[] dotsSet1; public GameObject[] dotsSet2; public int width, height; [HideInInspector] public int offset; [HideInInspector] public GameState currentState; [HideInInspector] public GameObject[,] allDots; #endregion #region Start Settings void Start() { finder = FindObjectOfType<FindMatches>(); finder.board = this; currentState = GameState.move; allDots = new GameObject[width, height]; /* ###################### PROVISIONAL ##############################*/ /* ## */ dots = Random.Range(0, 2) == 0 ? dotsSet1 : dotsSet2;/* ## */ /* ################################################################ */ score = 0f; slider.value = score; slider.maxValue = 600f; SetUp(); } private void SetUp() { for(int i = 0; i<width; i++) { for(int j = 0; j<height; j++) { Vector2 tempPosition = new Vector2(i, j + offset); int dotToUse = Random.Range(0, dots.Length); int maxIterations = 0; while(finder.MatchesAt(i,j, dots[dotToUse]) && maxIterations<100) { dotToUse = Random.Range(0, dots.Length); maxIterations++; }maxIterations = 0; GameObject dot = Instantiate(dots[dotToUse], tempPosition, Quaternion.identity); dot.GetComponent<Dot>().column = i; dot.GetComponent<Dot>().row = j; dot.transform.parent = this.transform; dot.name = "Dot(" + i + "," + j + ")"; allDots[i, j] = dot; } } } #endregion #region Destroy Matches Logic public void CheckMatches() { finder.FindAllMatches(); } private void DestroyMatchAt(int column, int row){ if(allDots[column, row].GetComponent<Dot>().isMatched) { Destroy(allDots[column, row]); allDots[column, row] = null; if (score < slider.maxValue) { score += 10f; } else { score = slider.maxValue; } } } public void DestroyAllMatches() { for(int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { if(allDots[i,j] != null) { DestroyMatchAt(i, j); } } } StartCoroutine(DecreaseRowCoroutine()); } private IEnumerator DecreaseRowCoroutine() { int nullCount = 0; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { if (allDots[i, j] == null) { nullCount++; }else if(nullCount > 0) { allDots[i, j].GetComponent<Dot>().row -= nullCount; allDots[i, j] = null; } } nullCount = 0; } yield return new WaitForSeconds(.2f); StartCoroutine(FillBoardCoroutine()); } #endregion #region Refill Board Logic private void RefillBoard() { for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { if (allDots[i, j] == null) { Vector2 tempPosition = new Vector2(i, j + offset); int dotToUse = Random.Range(0, dots.Length); GameObject piece = Instantiate(dots[dotToUse], tempPosition, Quaternion.identity); piece.GetComponent<Dot>().row = j; piece.GetComponent<Dot>().column = i; piece.transform.parent = this.transform; piece.name = "Dot(" + i + "," + j + ")"; allDots[i, j] = piece; } } } } private IEnumerator FillBoardCoroutine() { RefillBoard(); yield return new WaitForSeconds(.1f); while (finder.MatchesOnBoard()) { yield return new WaitForSeconds(.5f); DestroyAllMatches(); } yield return new WaitForSeconds(.5f); slider.value = score; scoreTag.text = "Puntaje: "+ score.ToString(); currentState = GameState.move; } #endregion #region Deadlock Solver public void shuffle() { for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { Destroy(allDots[i, j]); } } SetUp(); if (score >= 60f) { score = score - 60f; } else { score = 00f; } slider.value = score; scoreTag.text = "Puntaje: " + score.ToString(); } #endregion }
using System;using Alabo.Domains.Repositories.EFCore;using Alabo.Domains.Repositories.Model; using System.Linq; using MongoDB.Bson; using Alabo.Domains.Repositories; using Alabo.Data.Targets.Reports.Domain.Entities; namespace Alabo.Data.Targets.Reports.Domain.Repositories { public interface ITargetReportRepository : IRepository<TargetReport, long> { } }
using Assets.Scripts.Models; using Assets.Scripts.Ui; namespace Assets.Scripts.UI { public class UiDraggableSlot : View { public UISprite Icon; public void Init(HolderObject itemModel) { Icon.spriteName = itemModel.Item.IconName; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CompiledValidators.Core { internal enum MemberType { Scalar, Collection } internal class MemberGraph { public static readonly string RootMemberName = "root"; private readonly List<Member> _members; private readonly List<Validator> _validators; private bool _isSealed; public MemberGraph() { _members = new List<Member> { null }; // [0] = root _validators = new List<Validator>(); } public int RootId { get { return 0; } } public IEnumerable<MemberValidationErrorMessage> GetErrorMessages(int validatorId, object memberValue) { var validator = _validators[validatorId]; if (validator.ErrorMessages != null) return validator.ErrorMessages; var errorMessageValidatorInfo = validator.Info as ErrorMessageValidatorInfo; if (errorMessageValidatorInfo != null) return validator.ErrorMessages = new[] { new MemberValidationErrorMessage(GetMemberAccessString(validator.MemberId), errorMessageValidatorInfo.GetErrorMessage()) }; var memberErrorValidatorInfo = validator.Info as MemberErrorValidatorInfo; if (memberErrorValidatorInfo != null) return memberErrorValidatorInfo .GetErrorMessages(memberValue) .Select(x => new MemberValidationErrorMessage(GetMemberAccessString(validator.MemberId, x.MemberName), x.ErrorMessage)) .ToArray(); return validator.ErrorMessages = new[] { new MemberValidationErrorMessage(GetMemberAccessString(validator.MemberId), "Unspecified error") }; } private string GetMemberAccessString(int id, string additional = null) { if (id == RootId) return additional != null ? string.Format("{0}.{1}", RootMemberName, additional) : RootMemberName; var member = _members[id]; if (member.AccessString != null) return member.AccessString; var chain = new Stack<Member>(); while (member != null) { chain.Push(member); member = member.Parent; } var builder = new StringBuilder(RootMemberName); while (chain.Count > 0) { member = chain.Pop(); switch (member.MemberType) { case MemberType.Scalar: builder.AppendFormat(".{0}", member.Name); break; case MemberType.Collection: builder.AppendFormat(".{0}[]", member.Name); break; default: throw new NotSupportedException(); } } if (!string.IsNullOrEmpty(additional)) builder.AppendFormat(".{0}", additional); return member.AccessString = builder.ToString(); } public int NewMemberId(int parentId, string memberName, MemberType memberType = MemberType.Scalar) { if (_isSealed) throw new InvalidOperationException(); _members.Add(new Member(_members[parentId], memberName, memberType)); return _members.Count - 1; } public int NewValidatorId(int memberId, ValidatorInfo validatorInfo) { if (_isSealed) throw new InvalidOperationException(); _validators.Add(new Validator(memberId, validatorInfo)); return _validators.Count - 1; } public void Seal() { _isSealed = true; _members.TrimExcess(); _validators.TrimExcess(); } private class Validator { public Validator(int memberId, ValidatorInfo info) { MemberId = memberId; Info = info; } public int MemberId { get; private set; } public ValidatorInfo Info { get; private set; } public IEnumerable<MemberValidationErrorMessage> ErrorMessages { get; set; } } private class Member { public Member(Member parent, string name, MemberType memberType) { Parent = parent; Name = name; MemberType = memberType; } public Member Parent { get; private set; } public string Name { get; private set; } public MemberType MemberType { get; private set; } public string AccessString { get; set; } } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using System; using RestaurantList.Models; namespace RestaurantList.Tests { [TestClass] public class RestaurantTests : IDisposable { public RestaurantTests() { DBConfiguration.ConnectionString = "server=localhost;user id=root;password=root;port=3306;database=restaurantlist_test;"; } public void Dispose() { Restaurant.DeleteAll(); Cuisine.DeleteAll(); } [TestMethod] public void Equals_OverrideTrueForName_Restaurant() { //Arrange, Act Restaurant firstRestaurant = new Restaurant("Reedville Cafe", 0, "1234 Reedville Street", 5, "burgers", 1); Restaurant secondRestaurant = new Restaurant("Reedville Cafe", 0, "1234 Reedville Street", 5, "burgers", 1); //Assert Assert.AreEqual(firstRestaurant.GetName(), secondRestaurant.GetName()); } [TestMethod] public void Equals_OverrideTrueForEntireRestaurant() { //Arrange, Act Restaurant firstRestaurant = new Restaurant("Reedville Cafe", 0, "1234 Reedville Street", 5, "burgers", 1); Restaurant secondRestaurant = new Restaurant("Reedville Cafe", 0, "1234 Reedville Street", 5, "burgers", 1); //Assert Assert.AreEqual(firstRestaurant, secondRestaurant); } [TestMethod] public void Save_SavesRestaurantToDatabase_RestaurantList() { //Arrange Restaurant testRestaurant = new Restaurant("Reedville Cafe", 0, "1234 Reedville Street", 5, "burgers", 1); testRestaurant.Save(); //Act List<Restaurant> resultList = Restaurant.GetAll(); List<Restaurant> testList = new List<Restaurant>{testRestaurant}; //Assert CollectionAssert.AreEqual(testList, resultList); } [TestMethod] public void Save_DatabaseAssignsIdToObject_Id() { //Arrange Restaurant testRestaurant = new Restaurant("Reedville Cafe", 0, "1234 Reedville Street", 5, "burgers", 1); testRestaurant.Save(); //Act Restaurant savedRestaurant = Restaurant.GetAll()[0]; int resultId = savedRestaurant.GetId(); int testId = testRestaurant.GetId(); //Assert Assert.AreEqual(testId, resultId); } [TestMethod] public void Find_FindsRestaurantInDatabase_Restaurant() { //Arrange Restaurant testRestaurant = new Restaurant("Reedville Cafe", 0, "1234 Reedville Street", 5, "burgers", 1); testRestaurant.Save(); //Act Restaurant foundRestaurant = Restaurant.FindId(testRestaurant.GetId()); //Assert Assert.AreEqual(testRestaurant, foundRestaurant); } [TestMethod] public void Find_FindsCuisineInDatabase_Restaurant() { //Arrange Restaurant firstRestaurant = new Restaurant("Reedville Cafe", 0, "1234 Reedville Street", 5, "burgers", 1); firstRestaurant.Save(); Restaurant secondRestaurant = new Restaurant("Panera", 0, "567 185th Street", 4, "veggie options", 2); secondRestaurant.Save(); //Act List<Restaurant> foundList = Restaurant.FindCuisine(0); List<Restaurant> testList = new List<Restaurant> {firstRestaurant, secondRestaurant}; //Assert CollectionAssert.AreEqual(testList, foundList); } [TestMethod] public void UpdateRestaurant_RestaurantCorrectlyUpdates_Restaurant() { //Arrange Restaurant testRestaurant = new Restaurant("Reedville Cafe", 0, "1234 Reedville Street", 5, "burgers", 1); testRestaurant.Save(); //Act string newName = "Panera"; int newCuisineId = 0; string newAddress = "567 185th Street"; int newRating = 4; string newSpecialty = "veggie options"; testRestaurant.UpdateRestaurant(newName, newCuisineId, newAddress, newRating, newSpecialty); string resultName = Restaurant.FindId(testRestaurant.GetId()).GetName(); //Assert Assert.AreEqual(newName, resultName); } } }
namespace Cogito.Web.Configuration { public interface IWebSectionConfigurator : IWebElementConfigurator { } }