public PersonsContext() { Persons = new Persons(); List<Customer> customers = new List<Customer>(); List<Manager> managers = new List<Manager>(); List<Programmer> programmers = new List<Programmer>(); for (int i = 0; i < 3; i++) { customers.Add(new Customer("ACustomer", i.ToString(), new DateTime((1975 + i), 1, 1), "my a customer address")); customers.Add(new Customer("BCustomer", i.ToString(), new DateTime((2000 + i), 1, 1), "my b customer address")); } managers.Add(new Manager("Manager", "0", new DateTime((1990), 1, 1), 2000)); for (int i = 0; i < 5; i++) { programmers.Add(new Programmer("Programmer", i.ToString(), new DateTime((1990), 1, 1), 1000)); } programmers.ForEach(p => managers.First().AddProgrammer(p)); customers.OrderBy(c => c.Fullname).ToList().ForEach(p => Persons.AddPerson(p)); managers.OrderBy(c => c.Fullname).ToList().ForEach(p => Persons.AddPerson(p)); programmers.OrderBy(c => c.Fullname).ToList().ForEach(p => Persons.AddPerson(p)); }
//------------------------------------------------------------------------------------- /// protected override void AsyncTaskDoneBody(AsyncTask task) { #region Persons if(task.TaskName == "Persons") { _pers = (Persons)task.Result; ListBinder b = new ListBinder(_list = new PList<ISubject>(_pers)); b.CacheSort = false; b.Sort(Sort); fdgvList.DataSource = b; } #endregion Persons #region Save if(task.TaskName == "Save") { ISubject s = (ISubject)task.Tag; if(_pers.Contains(s) == false) _pers.Add((Person)s); else Pulsar.Serialization.PulsarSerializer.Deserialize(Pulsar.Serialization.PulsarSerializer.Backup(s), _pers[s.OID]); Modify = false; } #endregion Save #region Remove if(task.TaskName == "Remove") { _pers.Remove((Person)task.Tag); _list.Remove((ISubject)task.Tag); } #endregion Remove }
static void Main(string[] args) { List<Customer> customers = new List<Customer>(); List<Manager> managers = new List<Manager>(); List<Programmer> programmers = new List<Programmer>(); for (int i = 0; i < 3; i++) { customers.Add(new Customer("ACustomer", i.ToString(), new DateTime((1975 + i), 1, 1), "my a customer address")); customers.Add(new Customer("BCustomer", i.ToString(), new DateTime((2000 + i), 1, 1), "my b customer address")); } managers.Add(new Manager("Manager", "0", new DateTime((1990), 1, 1), 2000)); for (int i = 0; i < 5; i++) { programmers.Add(new Programmer("Programmer", i.ToString(), new DateTime((1990), 1, 1), 1000)); } programmers.ForEach(p => managers.First().AddProgrammer(p)); Console.WriteLine("# Costummers:"); customers.ForEach(c => Console.WriteLine(c.Print())); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("# Managers:"); managers.ForEach(c => Console.WriteLine(c.Print())); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("# Programmers:"); programmers.ForEach(c => Console.WriteLine(c.Print())); var costumersA = customers.Where(c => c.Fullname.StartsWith("A")); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("# Costummers, Name starts with 'A':"); costumersA.OrderBy(c => c.Fullname).ToList(). ForEach(c => Console.WriteLine(c.Print())); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("# How many Costummers, Name starts with 'A': " + costumersA.Count()); var costumersA40 = costumersA.Where(c => c.Age > 40); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("# How many Costummers, Name starts with 'A' and age > 40: " + costumersA40.Count()); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("# All Persons:"); Persons persons = new Persons(); customers.OrderBy(c => c.Fullname).ToList().ForEach(p => persons.AddPerson(p)); managers.OrderBy(c => c.Fullname).ToList().ForEach(p => persons.AddPerson(p)); programmers.OrderBy(c => c.Fullname).ToList().ForEach(p => persons.AddPerson(p)); persons.ToList().ForEach(p => Console.WriteLine(p.Print())); }
void before_each() { seed = new Seed(); seed.PurgeDb(); persons = new Persons(); }
void before_each() { seed = new Seed(); seed.PurgeDb(); person = new Person(); persons = new Persons(); person.Email = "*****@*****.**"; person.EmailConfirmation = "*****@*****.**"; }
/// <summary> /// 指定された条件に合致する<see cref="Person"/>を取得します。 /// </summary> /// <param name="self">自分自身</param> /// <param name="predicate">抽出条件</param> /// <returns>絞込結果</returns> public static Persons Where(this Persons self, Func<Person, bool> predicate) { var result = new Persons(); Output.WriteLine("========= WHERE ========"); foreach (var aPerson in self) { if (predicate(aPerson)) { result.Add(aPerson); } } return result; }
public void Execute() { var persons = new Persons { new Person {Id = 1, Name = "gsf_zero1"}, new Person {Id = 2, Name = "gsf_zero2"}, new Person {Id = 3, Name = "gsf_zero3"} }; // // PersonExtensionが定義されているので // そのまま実行すると、Whereの部分にてPersonExtension.Whereが // 呼ばれる. // Output.WriteLine("===== 拡張メソッドを定義した状態でそのままクエリ実行 ====="); var query = from aPerson in persons where aPerson.Id == 2 select aPerson; foreach (var aPerson in query) { Output.WriteLine(aPerson); } // // AsEnumerableメソッドを利用して、PersonsをIEnumerable<Person>に // 変換すると、カスタムWhere拡張メソッドは呼ばれない。 // Output.WriteLine("===== AsEnumerableメソッドを利用してから、クエリ実行 ====="); var query2 = from aPerson in persons.AsEnumerable() where aPerson.Id == 2 select aPerson; foreach (var aPerson in query2) { Output.WriteLine(aPerson); } }
public SubordinateViewModel(IScreen screen) { UrlPathSegment = nameof(SubordinateViewModel); HostScreen = screen; SearchText = string.Empty; _networkServiceOfPersons ??= Locator.Current.GetService <INetworkService <Person> >(); #region Init Chat service _clientService ??= Locator.Current.GetService <IClientService>(); _clientService.MessageReceived += MessageReceived; #endregion #region Init SelectPersonCommand SelectPersonCommand = ReactiveCommand.Create <Person, bool>(FillVisitorBySelected); this.WhenAnyValue(x => x.SelectedPerson) .InvokeCommand(SelectPersonCommand); #endregion #region Init SearchPersonCommand var canSearch = this.WhenAnyValue(x => x.SearchText, query => !string.IsNullOrWhiteSpace(query)); SearchPersonCommand = ReactiveCommand.CreateFromTask <string, IEnumerable <Person> >( async query => await SearchPersons(query), canSearch); SearchPersonCommand.ThrownExceptions.Subscribe(error => ShowError(error)); _searchedPersons = SearchPersonCommand.ToProperty(this, x => x.Persons); this.WhenAnyValue(x => x.SearchText) .Throttle(TimeSpan.FromSeconds(1), RxApp.MainThreadScheduler) .InvokeCommand(SearchPersonCommand); #endregion #region Init ClearSearchPersonCommand var canClearSearch = this.WhenAnyValue(x => x.SearchText, query => !string.IsNullOrWhiteSpace(query) || Persons.Any()); ClearSearchPersonCommand = ReactiveCommand.CreateFromTask <Unit, bool>(ClearSearchPersons, canClearSearch); #endregion #region Init SendPersonCommand var canSendPerson = this.WhenAnyValue( x => x.Visitor, x => x.Visitor.Comment, x => x.Visitor.FirstName, x => x.Visitor.Message, x => x.Visitor.MiddleName, x => x.Visitor.Post, x => x.Visitor.SecondName, (person, _, __, ___, ____, _____, ______) => !person.IsNullOrEmpty()); SendVisitorCommand = ReactiveCommand.CreateFromTask <Visitor, bool>(SendVisitor, canSendPerson); #endregion Initialized = SubordinateViewModel_Initialized; Initialized.Invoke(); }
public void ClearPersons() { Persons.RemoveRange(Persons.ToList()); }
public async Task <JsonResult> OnPostVerificarDoc([FromBody] Persons comprobarDoc) { Prospecto regsitro = null; Persons PeopleRegisted = new Persons(); HttpContext.Session.SetString("registroDesemascarado", ""); HttpContext.Session.SetString("registroDesemascaradoError", ""); var respuesta = await _peopleService.RegisterByDocument(new ParamProspecto { Document = new DocumentIdentification { Country = Int32.Parse(Request.Cookies["Country"]), Identification = comprobarDoc.Document.Identification, Prefix = comprobarDoc.Document.Prefix, Number = comprobarDoc.Document.Number, } }); try { filterInvoice PeopleId = new filterInvoice(); PeopleId.Id = respuesta.Person; regsitro = await _peopleService.RegisterById(new ParamProspecto { Filter = PeopleId, Country = Int32.Parse(Request.Cookies["Country"]) }); if (regsitro.Documents != null && regsitro.Documents.Count > 0) { PeopleRegisted.Document = regsitro.Documents[0]; } if (regsitro.Addresses != null && regsitro.Addresses.Count > 0) { PeopleRegisted.Address = regsitro.Addresses[0]; } if (regsitro.Phones != null && regsitro.Phones.Count > 0) { PeopleRegisted.Phone = regsitro.Phones[0]; } if (regsitro.Emails != null && regsitro.Emails.Count > 0) { PeopleRegisted.Email = regsitro.Emails[0]; } ; PeopleRegisted.Discriminator = regsitro.Discriminator; PeopleRegisted.Company = regsitro.Company; PeopleRegisted.FirstName = regsitro.FirstName; PeopleRegisted.LastName = regsitro.LastName; PeopleRegisted.Category = regsitro.Category; PeopleRegisted.Country = regsitro.Country; PeopleRegisted.Contacts = regsitro.Contacts; if (regsitro.Entities != null) { PeopleRegisted.Routing_number = regsitro.Entities[0].Routing_number; } if (regsitro.Accounts == null) { PeopleRegisted.Accounts = new List <TuFactoringModels.nuevaVersion.Account>(); } else { foreach (var cuenta in regsitro.Accounts) { TuFactoringModels.nuevaVersion.Account newAccount = new TuFactoringModels.nuevaVersion.Account(); newAccount.Entity = cuenta.Entity.Id; newAccount.AccountNumber = cuenta.AccountNumber; newAccount.AccountType = cuenta.AccountType; newAccount.Currency = cuenta.Currency; PeopleRegisted.Accounts.Add(newAccount); } } HttpContext.Session.SetString("People", JsonConvert.SerializeObject(regsitro)); HttpContext.Session.SetString("registroDesemascarado", JsonConvert.SerializeObject(PeopleRegisted)); HttpContext.Session.SetString("registroDesemascaradoError", JsonConvert.SerializeObject(PeopleRegisted)); PeopleRegisted.Contacts = new List <TuFactoringModels.nuevaVersion.Contact>(); //HttpContext.Session.SetString("registroDesemascarado", JsonConvert.SerializeObject(PeopleRegisted)); return(new JsonResult(new { registro = PeopleRegisted, contacts = regsitro.Contacts, contratos = regsitro.Agreements })); } catch { return(null); } }
//------------------------------------------------------------------------------------- /// <summary> /// /// </summary> /// <param name="task"></param> protected override void AsyncTaskDoneBody(AsyncTask task) { #region Persons if(task.TaskName == "Persons") { users = (Persons)task.Result; comboBoxUsers.Items.Add(new ComboBoxItem<Person>(null, " (Bсе)")); foreach(Person u in users) comboBoxUsers.Items.Add(new ComboBoxItem<Person>(u)); } #endregion Persons #region Security if(task.TaskName == "Security") { pSec = (PulsarSecurity)task.Result; } #endregion Security #region MainMenu if(task.TaskName == "MainMenu") { mMenu = (PulsarMainMenu)task.Result; } #endregion MainMenu #region SetACEsForSD if(task.TaskName == "SetACEsForSD") { ValuesPair<OID, PList<ACE>> i = (ValuesPair<OID, PList<ACE>>)task.Tag; pSec.SetACEsForSD(i.Value1, i.Value2); btnCancel_Click(btnCancel, EventArgs.Empty); RecheckUserAccess(); } #endregion SetACEsForSD }
/// <summary> /// Pick the root person database folder, to minimum the data preparation logic, the folder should be under following construction /// Each person's image should be put into one folder named as the person's name /// All person's image folder should be put directly under the root person database folder /// </summary> /// <param name="sender">Event sender</param> /// <param name="e">Event argument</param> private async void FolderPicker_Click(object sender, RoutedEventArgs e) { bool groupExists = false; MainWindow mainWindow = Window.GetWindow(this) as MainWindow; string subscriptionKey = mainWindow._scenariosControl.SubscriptionKey; var faceServiceClient = new FaceServiceClient(subscriptionKey); // Test whether the group already exists try { MainWindow.Log("Request: Group {0} will be used for build person database. Checking whether group exists.", GroupName); await faceServiceClient.GetPersonGroupAsync(GroupName); groupExists = true; MainWindow.Log("Response: Group {0} exists.", GroupName); } catch (FaceAPIException ex) { if (ex.ErrorCode != "PersonGroupNotFound") { MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage); return; } else { MainWindow.Log("Response: Group {0} does not exist before.", GroupName); } } if (groupExists) { var cleanGroup = System.Windows.MessageBox.Show(string.Format("Requires a clean up for group \"{0}\" before setup new person database. Click OK to proceed, group \"{0}\" will be fully cleaned up.", GroupName), "Warning", MessageBoxButton.OKCancel); if (cleanGroup == MessageBoxResult.OK) { await faceServiceClient.DeletePersonGroupAsync(GroupName); } else { return; } } // Show folder picker System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog(); var result = dlg.ShowDialog(); // Set the suggestion count is intent to minimum the data preparation step only, // it's not corresponding to service side constraint const int SuggestionCount = 15; if (result == System.Windows.Forms.DialogResult.OK) { // User picked a root person database folder // Clear person database Persons.Clear(); TargetFaces.Clear(); SelectedFile = null; // Call create person group REST API // Create person group API call will failed if group with the same name already exists MainWindow.Log("Request: Creating group \"{0}\"", GroupName); try { await faceServiceClient.CreatePersonGroupAsync(GroupName, GroupName); MainWindow.Log("Response: Success. Group \"{0}\" created", GroupName); } catch (FaceAPIException ex) { MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage); return; } int processCount = 0; bool forceContinue = false; MainWindow.Log("Request: Preparing faces for identification, detecting faces in chosen folder."); // Enumerate top level directories, each directory contains one person's images foreach (var dir in System.IO.Directory.EnumerateDirectories(dlg.SelectedPath)) { var tasks = new List <Task>(); var tag = System.IO.Path.GetFileName(dir); Person p = new Person(); p.PersonName = tag; var faces = new ObservableCollection <Face>(); p.Faces = faces; // Call create person REST API, the new create person id will be returned MainWindow.Log("Request: Creating person \"{0}\"", p.PersonName); p.PersonId = (await faceServiceClient.CreatePersonAsync(GroupName, p.PersonName)).PersonId.ToString(); MainWindow.Log("Response: Success. Person \"{0}\" (PersonID:{1}) created", p.PersonName, p.PersonId); // Enumerate images under the person folder, call detection foreach (var img in System.IO.Directory.EnumerateFiles(dir, "*.jpg", System.IO.SearchOption.AllDirectories)) { tasks.Add(Task.Factory.StartNew( async(obj) => { var imgPath = obj as string; using (var fStream = File.OpenRead(imgPath)) { try { // Update person faces on server side var persistFace = await faceServiceClient.AddPersonFaceAsync(GroupName, Guid.Parse(p.PersonId), fStream, imgPath); return(new Tuple <string, ClientContract.AddPersistedFaceResult>(imgPath, persistFace)); } catch (FaceAPIException) { // Here we simply ignore all detection failure in this sample // You may handle these exceptions by check the Error.Error.Code and Error.Message property for ClientException object return(new Tuple <string, ClientContract.AddPersistedFaceResult>(imgPath, null)); } } }, img).Unwrap().ContinueWith((detectTask) => { // Update detected faces for rendering var detectionResult = detectTask.Result; if (detectionResult == null || detectionResult.Item2 == null) { return; } this.Dispatcher.Invoke( new Action <ObservableCollection <Face>, string, ClientContract.AddPersistedFaceResult>(UIHelper.UpdateFace), faces, detectionResult.Item1, detectionResult.Item2); })); if (processCount >= SuggestionCount && !forceContinue) { var continueProcess = System.Windows.Forms.MessageBox.Show("The images loaded have reached the recommended count, may take long time if proceed. Would you like to continue to load images?", "Warning", System.Windows.Forms.MessageBoxButtons.YesNo); if (continueProcess == System.Windows.Forms.DialogResult.Yes) { forceContinue = true; } else { break; } } } Persons.Add(p); await Task.WhenAll(tasks); } MainWindow.Log("Response: Success. Total {0} faces are detected.", Persons.Sum(p => p.Faces.Count)); try { // Start train person group MainWindow.Log("Request: Training group \"{0}\"", GroupName); await faceServiceClient.TrainPersonGroupAsync(GroupName); // Wait until train completed while (true) { await Task.Delay(1000); var status = await faceServiceClient.GetPersonGroupTrainingStatusAsync(GroupName); MainWindow.Log("Response: {0}. Group \"{1}\" training process is {2}", "Success", GroupName, status.Status); if (status.Status != Contract.Status.Running) { break; } } } catch (FaceAPIException ex) { MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage); } } }
private void Load() { Persons = personsService.Get(); SelectedPerson = Persons.FirstOrDefault(); }
private async void FolderPicker() { if (Properties.Settings.Default.FacePath == "path here") { return; } _faceClient = new FaceAPI.FaceServiceClient(Properties.Settings.Default.FaceAPIKey, Properties.Settings.Default.FaceAPIHost); bool groupExists = false; MainWindow mainWindow = System.Windows.Window.GetWindow(this) as MainWindow; var faceServiceClient = _faceClient; // Test whether the group already exists try { Log("Request: Group {0} will be used to build a person database. Checking whether the group exists.", this.GroupId); await faceServiceClient.GetLargePersonGroupAsync(this.GroupId); groupExists = true; Log("Response: Group {0} exists.", this.GroupId); } catch (FaceAPIException ex) { if (ex.ErrorCode != "LargePersonGroupNotFound") { Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage); return; } else { Log("Response: Group {0} did not exist previously.", this.GroupId); } } // Show folder picker //System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog(); //var result = dlg.ShowDialog(); // Set the suggestion count is intent to minimum the data preparation step only, // it's not corresponding to service side constraint const int SuggestionCount = 15; if (Properties.Settings.Default.FacePath != "path here") { // User picked a root person database folder // Clear person database Persons.Clear(); TargetFaces.Clear(); SelectedFile = null; //IdentifyButton.IsEnabled = false; // Call create large person group REST API // Create large person group API call will failed if group with the same name already exists if (groupExists) { Log("Request: Loading group \"{0}\"", this.GroupId); load_Persons = await faceServiceClient.ListPersonsInLargePersonGroupAsync(this.GroupId); } else { Log("Request: Creating group \"{0}\"", this.GroupId); try { await faceServiceClient.CreateLargePersonGroupAsync(this.GroupId, this.GroupId); Log("Response: Success. Group \"{0}\" created.", this.GroupId); } catch (FaceAPIException ex) { Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage); return; } } int processCount = 0; bool forceContinue = false; Log("Request: Preparing faces for identification, detecting faces in chosen folder."); // Enumerate top level directories, each directory contains one person's images int invalidImageCount = 0; personData.Clear(); int i = 0; foreach (var dir in System.IO.Directory.EnumerateDirectories(Properties.Settings.Default.FacePath)) { i++; } imageWall.Init(i); i = 0; foreach (var dir in System.IO.Directory.EnumerateDirectories(Properties.Settings.Default.FacePath)) { var tasks = new List <Task>(); var tag = System.IO.Path.GetFileName(dir); Person p = new Person(); p.PersonName = tag; var faces = new ObservableCollection <Face>(); p.Faces = faces; // Call create person REST API, the new create person id will be returned Log("Request: Creating person \"{0}\"", p.PersonName); Guid personid = Guid.NewGuid(); bool isFound = false; if (groupExists) { isFound = FindPersonByName(load_Persons, p.PersonName, out personid); } if (groupExists && isFound) { p.PersonId = (await faceServiceClient.GetPersonInLargePersonGroupAsync(this.GroupId, personid)).PersonId.ToString(); } else { p.PersonId = (await faceServiceClient.CreatePersonInLargePersonGroupAsync(this.GroupId, p.PersonName)).PersonId.ToString(); } Log("Response: Success. Person \"{0}\" (PersonID:{1}) created. Please wait for training.", p.PersonName, p.PersonId); personData.Add(new PersonData(p.PersonId, p.PersonName)); string img; // Enumerate images under the person folder, call detection var imageList = new ConcurrentBag <string>( Directory.EnumerateFiles(dir, "*.*", SearchOption.AllDirectories) .Where(s => s.ToLower().EndsWith(".jpg") || s.ToLower().EndsWith(".png") || s.ToLower().EndsWith(".bmp") || s.ToLower().EndsWith(".gif"))); int j = 0; while (imageList.TryTake(out img)) { if (j == 0 && i < ImageWall.num) { imageWall.faceBitmaps[i] = new BitmapImage(new Uri(img)); imageWall.id.Add(p.PersonId); } j++; tasks.Add(Task.Factory.StartNew( async(obj) => { var imgPath = obj as string; using (var fStream = File.OpenRead(imgPath)) { try { // Update person faces on server side var persistFace = await faceServiceClient.AddPersonFaceInLargePersonGroupAsync(this.GroupId, Guid.Parse(p.PersonId), fStream, imgPath); return(new Tuple <string, ClientContract.AddPersistedFaceResult>(imgPath, persistFace)); } catch (FaceAPIException ex) { // if operation conflict, retry. if (ex.ErrorCode.Equals("ConcurrentOperationConflict")) { imageList.Add(imgPath); return(null); } // if operation cause rate limit exceed, retry. else if (ex.ErrorCode.Equals("RateLimitExceeded")) { imageList.Add(imgPath); return(null); } else if (ex.ErrorMessage.Contains("more than 1 face in the image.")) { Interlocked.Increment(ref invalidImageCount); } // Here we simply ignore all detection failure in this sample // You may handle these exceptions by check the Error.Error.Code and Error.Message property for ClientException object return(new Tuple <string, ClientContract.AddPersistedFaceResult>(imgPath, null)); } } }, img).Unwrap().ContinueWith((detectTask) => { // Update detected faces for rendering var detectionResult = detectTask?.Result; if (detectionResult == null || detectionResult.Item2 == null) { return; } this.Dispatcher.Invoke( new Action <ObservableCollection <Face>, string, ClientContract.AddPersistedFaceResult>(UIHelper.UpdateFace), faces, detectionResult.Item1, detectionResult.Item2); })); if (processCount >= SuggestionCount && !forceContinue) { var continueProcess = System.Windows.Forms.MessageBox.Show("The images loaded have reached the recommended count, may take long time if proceed. Would you like to continue to load images?", "Warning", System.Windows.Forms.MessageBoxButtons.YesNo); if (continueProcess == System.Windows.Forms.DialogResult.Yes) { forceContinue = true; } else { break; } } if (tasks.Count >= _maxConcurrentProcesses || imageList.IsEmpty) { await Task.WhenAll(tasks); tasks.Clear(); } } Persons.Add(p); i++; } PersonDataUpdate(); imageWall.UpdateCanvas(); if (invalidImageCount > 0) { Log("Warning: more or less than one face is detected in {0} images, can not add to face list.", invalidImageCount); } Log("Response: Success. Total {0} faces are detected.", Persons.Sum(p => p.Faces.Count)); try { // Start train large person group Log("Request: Training group \"{0}\"", this.GroupId); await faceServiceClient.TrainLargePersonGroupAsync(this.GroupId); // Wait until train completed while (true) { await Task.Delay(1000); var status = await faceServiceClient.GetLargePersonGroupTrainingStatusAsync(this.GroupId); Log("Response: {0}. Group \"{1}\" training process is {2}", "Success", this.GroupId, status.Status); if (status.Status != ClientContract.Status.Running) { break; } } //IdentifyButton.IsEnabled = true; } catch (FaceAPIException ex) { Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage); } } GC.Collect(); }
private void SubmitExecute(object parameter) { Persons.Add(Person); }
public void WhenIUpdateFirstNameForEachPersonTo(string newFirstName) { Persons.ToList().ForEach(x => x.FirstName = newFirstName); }
// Creates person void CreatePerson() { Persons.Insert(0, new Person()); Current = Persons[0]; _deleteCommand.RaiseCanExecuteChanged(); }
public JsonResult List2([DataSourceRequest] DataSourceRequest request) { return(Json(Persons.GetListAll2().ToDataSourceResult(request), JsonRequestBehavior.AllowGet)); }
internal bool Load(HomeData.Home home) { if (home.Cameras.Count == 0 && home.SmokeDetectors.Count == 0) { return(false); } Id = home.Id; Name = home.Name; Place = new Location() { City = home.Place.City, Country = home.Place.Country, TimeZone = home.Place.Timezone }; foreach (HomeData.Person person in home.Persons) { Person newPerson = new Person { Id = person.Id, Pseudo = person.Pseudo, Face = new Snapshot() { Id = person.Face.Id, Version = person.Face.Version, Key = person.Face.Key, Url = person.Face.Url }, LastSeen = person.LastSeen.ToLocalDateTime(), OutOfSight = person.OutOfSight }; Persons.Add(newPerson); } AddEvents(home.Events); if (home.Modules != null) { foreach (HomeData.Module module in home.Modules) { SecurityModule securityModule = new SecurityModule() { BatteryPercent = module.BatteryPercent, Id = module.Id, LastActivity = module.LastActivity.ToLocalDateTime(), Name = module.Name, RadioStatus = module.RadioFrequecy.ToRadioFrequencyStatus(), Status = module.Status.ToStatusSecurityModule(), Type = module.Type.ToSecurityModuleType() }; Modules.Add(securityModule); } } if (home.Cameras != null) { foreach (HomeData.Camera camera in home.Cameras) { Camera newCamera = new Camera() { AlimStatus = camera.AlimStatus.ToAlimStatus(), Id = camera.Id, IsLocal = camera.IsLocal, LastSetup = camera.LastSetup.ToLocalDateTime(), Name = camera.Name, SDCardStatus = camera.SdStatus.ToSDCardStatus(), Status = camera.Status.ToCameraStatus(), Type = camera.Type.ToCameraType(), UsePinCode = camera.UsePinCode, VpnUrl = camera.VpnUrl }; Cameras.Add(newCamera); } } return(true); }
private static Persons instantiate(DataSet ds) { Persons p = new Persons(); p.Id = Convert.ToInt16(ds.Tables[0].Rows[0]["id"]); p.Name = ds.Tables[0].Rows[0]["name"].ToString(); p.Surname = ds.Tables[0].Rows[0]["surname"].ToString(); p.Age = Convert.ToInt16(ds.Tables[0].Rows[0]["age"]); p.UserId = Convert.ToInt16(ds.Tables[0].Rows[0]["user_id"]); p.Description = ds.Tables[0].Rows[0]["description"].ToString(); return p; }
/// <summary> /// Pick image, detect and identify all faces detected /// </summary> /// <param name="sender">Event sender</param> /// <param name="e">Event arguments</param> private async void Identify_Click(object sender, RoutedEventArgs e) { // Show file picker Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.DefaultExt = ".jpg"; dlg.Filter = "Image files(*.jpg, *.png, *.bmp, *.gif) | *.jpg; *.png; *.bmp; *.gif"; var result = dlg.ShowDialog(); if (result.HasValue && result.Value) { // User picked one image // Clear previous detection and identification results TargetFaces.Clear(); var pickedImagePath = dlg.FileName; var renderingImage = UIHelper.LoadImageAppliedOrientation(pickedImagePath); var imageInfo = UIHelper.GetImageInfoForRendering(renderingImage); SelectedFile = renderingImage; var sw = Stopwatch.StartNew(); var faceServiceClient = FaceServiceClientHelper.GetInstance(this); // Call detection REST API using (var fStream = File.OpenRead(pickedImagePath)) { try { var faces = await faceServiceClient.Face.DetectWithStreamAsync(fStream, recognitionModel : recognitionModel); // Convert detection result into UI binding object for rendering foreach (var face in UIHelper.CalculateFaceRectangleForRendering(faces, MaxImageSize, imageInfo)) { TargetFaces.Add(face); } MainWindow.Log("Request: Identifying {0} face(s) in group \"{1}\"", faces.Count, GroupName); // Identify each face // Call identify REST API, the result contains identified person information var identifyResult = await faceServiceClient.Face.IdentifyAsync((from face in faces where face.FaceId != null select face.FaceId.Value).ToList(), null, GroupName); for (int idx = 0; idx < faces.Count; idx++) { // Update identification result for rendering var face = TargetFaces[idx]; var res = identifyResult[idx]; if (res.Candidates.Count > 0 && Persons.Any(p => p.PersonId == res.Candidates[0].PersonId.ToString())) { face.PersonName = Persons.Where(p => p.PersonId == res.Candidates[0].PersonId.ToString()).First().PersonName; } else { face.PersonName = "Unknown"; } } var outString = new StringBuilder(); foreach (var face in TargetFaces) { outString.AppendFormat("Face {0} is identified as {1}. ", face.FaceId, face.PersonName); } MainWindow.Log("Response: Success. {0}", outString); } catch (APIErrorException ex) { MainWindow.Log("Response: {0}. {1}", ex.Body.Error.Code, ex.Body.Error.Message); } } } GC.Collect(); }
static void Main() { Persons max = new Persons("Max", 20); }
/// <summary> /// ToDos onay / ret /// </summary> public JsonResult ToDosOnay(int Id, bool Onay, int Sure) { var tbl = db.GorevlerToDoLists.Where(m => m.ID == Id).FirstOrDefault(); // getir tbl.DegisTarih = DateTime.Now; tbl.Degistiren = vUser.UserName; if (Onay == true) { // onaylamalar if (tbl.Onay == false) { tbl.Onay = true; tbl.Onaylayan = vUser.UserName; // messages if (tbl.Gorevler.KontrolSorumlusu != null) { var mesaj = new Message() { MesajTipi = ComboItems.DuyuruMesajı.ToInt32(), Kimden = vUser.UserName, Kime = tbl.Gorevler.KontrolSorumlusu, Tarih = DateTime.Now, Mesaj = "Onay listenize bir maddde eklendi: " + tbl.Aciklama, URL = "/ToDo/DutyWork/Todos" }; db.Messages.Add(mesaj); } } else if (tbl.Onay == true && vUser.RoleName == "Destek") { tbl.KontrolOnay = true; tbl.KontrolEden = vUser.UserName; // messages var kullList = Persons.GetList("Admin"); foreach (var item in kullList) { db.Messages.Add(new Message() { MesajTipi = ComboItems.DuyuruMesajı.ToInt32(), Kimden = vUser.UserName, Kime = item.Kod, Tarih = DateTime.Now, Mesaj = "Onay listenize bir maddde eklendi: " + tbl.Aciklama, URL = "/ToDo/DutyWork/Todos" }); } } else if (tbl.Onay == true && CheckPerm(Perms.TodoÇalışma, PermTypes.Deleting) == true) { tbl.KontrolOnay = true; tbl.KontrolEden = vUser.UserName; tbl.AdminOnay = true; } else if (tbl.Onay == true && tbl.KontrolOnay == true && CheckPerm(Perms.TodoÇalışma, PermTypes.Deleting) == true) { tbl.AdminOnay = true; } // çalışma gir if (Sure > 0) { var calisma = new GorevlerCalisma() { GorevID = tbl.GorevID, Tarih = DateTime.Now, Sure = Sure, Calisma = tbl.Aciklama, KayitTarih = DateTime.Now, Kaydeden = vUser.UserName, Degistiren = vUser.UserName, DegisTarih = DateTime.Now, }; db.GorevlerCalismas.Add(calisma); } // eğer if (vUser.RoleName == "Developer") { var c = db.GorevlerToDoLists.Where(m => m.GorevID == tbl.GorevID && m.Onay == false && m.ID != Id).FirstOrDefault(); if (c == null) { tbl.Gorevler.DurumID = ComboItems.gydKaliteKontrol.ToInt32(); } else { tbl.Gorevler.DurumID = ComboItems.gydBaşlandı.ToInt32(); } } else if (CheckPerm(Perms.TodoÇalışma, PermTypes.Deleting) == true) { var c = db.GorevlerToDoLists.Where(m => m.GorevID == tbl.GorevID && m.AdminOnay == false && m.ID != Id).FirstOrDefault(); if (c == null) { tbl.Gorevler.DurumID = ComboItems.gydOnaylandı.ToInt32(); } } } else { if ((tbl.Onay == true && tbl.KontrolOnay == true && CheckPerm(Perms.TodoÇalışma, PermTypes.Deleting) == true) || (tbl.Onay == true && (tbl.Gorevler.KontrolSorumlusu == vUser.UserName || tbl.Gorevler.KontrolSorumlusu == null))) { tbl.AdminOnay = false; tbl.KontrolOnay = false; tbl.KontrolEden = null; tbl.Onay = false; tbl.Onaylayan = null; tbl.Gorevler.DurumID = ComboItems.gydBaşlandı.ToInt32(); // messages var mesaj = new Message() { MesajTipi = ComboItems.DuyuruMesajı.ToInt32(), Kimden = vUser.UserName, Kime = tbl.Gorevler.Sorumlu, Tarih = DateTime.Now, Mesaj = vUser.FullName + " onay listenizdeki bir maddeyi reddetti: " + tbl.Aciklama, URL = "/ToDo/DutyWork/Todos" }; db.Messages.Add(mesaj); if (tbl.Gorevler.Sorumlu2 != null) { var mesaj2 = new Message() { MesajTipi = ComboItems.DuyuruMesajı.ToInt32(), Kimden = vUser.UserName, Kime = tbl.Gorevler.Sorumlu2, Tarih = DateTime.Now, Mesaj = vUser.FullName + " onay listenizdeki bir maddeyi reddetti: " + tbl.Aciklama, URL = "/ToDo/DutyWork/Todos" }; db.Messages.Add(mesaj2); } if (tbl.Gorevler.Sorumlu3 != null) { var mesaj3 = new Message() { MesajTipi = ComboItems.DuyuruMesajı.ToInt32(), Kimden = vUser.UserName, Kime = tbl.Gorevler.Sorumlu3, Tarih = DateTime.Now, Mesaj = vUser.FullName + " onay listenizdeki bir maddeyi reddetti: " + tbl.Aciklama, URL = "/ToDo/DutyWork/Todos" }; db.Messages.Add(mesaj3); } } } // kaydet try { db.SaveChanges(); return(Json(new Result(true, Id), JsonRequestBehavior.AllowGet)); } catch (Exception ex) { Logger(ex, "ToDo/DutyWork/ToDosOnay"); return(Json(new Result(false, "Kayıt hatası"), JsonRequestBehavior.AllowGet)); } }
static void TakeNewProfile(string name, int age, string email) { Persons user = new Persons(name, age, email); Console.WriteLine(user.ToString()); }
public void DeletePerson(Person person) { Persons.DeletePersonFromList(person); Relations.DeleteRelationOfPerson(person); }
public void AddData(IEntity data, EntityType entityType) { switch (entityType) { case EntityType.Person: { Persons.Add((Person)data); break; } case EntityType.Death: { Deaths.Add((Death)data); break; } case EntityType.PayerPlanPeriod: { PayerPlanPeriods.Add((PayerPlanPeriod)data); break; } case EntityType.ConditionOccurrence: { ConditionOccurrences.Add((ConditionOccurrence)data); break; } case EntityType.DrugExposure: { DrugExposures.Add((DrugExposure)data); break; } case EntityType.ProcedureOccurrence: { ProcedureOccurrences.Add((ProcedureOccurrence)data); break; } case EntityType.Observation: { Observations.Add((Observation)data); break; } case EntityType.VisitOccurrence: { VisitOccurrences.Add((VisitOccurrence)data); break; } case EntityType.VisitDetail: { VisitDetails.Add((VisitDetail)data); break; } case EntityType.Cohort: { Cohort.Add((Cohort)data); break; } case EntityType.Measurement: { Measurements.Add((Measurement)data); break; } case EntityType.DeviceExposure: { DeviceExposure.Add((DeviceExposure)data); break; } case EntityType.ObservationPeriod: { ObservationPeriods.Add((ObservationPeriod)data); break; } case EntityType.DrugEra: { DrugEra.Add((EraEntity)data); break; } case EntityType.ConditionEra: { ConditionEra.Add((EraEntity)data); break; } case EntityType.Note: { Note.Add((Note)data); break; } } }
public IActionResult PersoCreate([Bind("LastName,FirstName,Address,City")] Persons persons) { _db.Insert(persons); return(RedirectToAction(nameof(Index))); }
// GET api/values/5 public async Task<string> Get(int id) { bool groupExists = false; string returnStatus = "Success"; string subscriptionKey = ""; string endpoint = ""; var faceServiceClient = new FaceServiceClient(subscriptionKey, endpoint); System.Diagnostics.Debug.WriteLine("---------Hiiiii--------"); try { System.Diagnostics.Debug.WriteLine("Request: Group {0} will be used to build a person database. Checking whether the group exists.", this.GroupId); await faceServiceClient.GetLargePersonGroupAsync(this.GroupId); count++; groupExists = true; System.Diagnostics.Debug.WriteLine("Response: Group {0} exists.", this.GroupId); } catch (FaceAPIException ex) { if (ex.ErrorCode != "LargePersonGroupNotFound") { System.Diagnostics.Debug.WriteLine("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage); return ""; } else { System.Diagnostics.Debug.WriteLine("Response: Group {0} did not exist previously.", this.GroupId); } } if (groupExists) { await faceServiceClient.DeleteLargePersonGroupAsync(this.GroupId); count++; this.GroupId = Guid.NewGuid().ToString(); } const int SuggestionCount = 15; Persons.Clear(); TargetFaces.Clear(); SelectedFile = null; // IdentifyButton.IsEnabled = false; System.Diagnostics.Debug.WriteLine("Request: Creating group \"{0}\"", this.GroupId); try { await faceServiceClient.CreateLargePersonGroupAsync(this.GroupId, this.GroupId); count++; System.Diagnostics.Debug.WriteLine("Response: Success. Group \"{0}\" created", this.GroupId); } catch (FaceAPIException ex) { System.Diagnostics.Debug.WriteLine("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage); return ""; } int processCount = 0; bool forceContinue = false; System.Diagnostics.Debug.WriteLine("Request: Preparing faces for identification, detecting faces in chosen folder."); // Enumerate top level directories, each directory contains one person's images int invalidImageCount = 0; foreach (var dir in System.IO.Directory.EnumerateDirectories("")) { var tasks = new List<Task>(); var tag = System.IO.Path.GetFileName(dir); Person p = new Person(); p.PersonName = tag; var faces = new ObservableCollection<Face>(); p.Faces = faces; // Call create person REST API, the new create person id will be returned System.Diagnostics.Debug.WriteLine("Request: Creating person \"{0}\"", p.PersonName); p.PersonId = (await faceServiceClient.CreatePersonInLargePersonGroupAsync(this.GroupId, p.PersonName)).PersonId.ToString(); System.Diagnostics.Debug.WriteLine("Response: Success. Person \"{0}\" (PersonID:{1}) created", p.PersonName, p.PersonId); string img; // Enumerate images under the person folder, call detection var imageList = new ConcurrentBag<string>( Directory.EnumerateFiles(dir, "*.*", SearchOption.AllDirectories) .Where(s => s.ToLower().EndsWith(".jpg") || s.ToLower().EndsWith(".png") || s.ToLower().EndsWith(".bmp") || s.ToLower().EndsWith(".gif"))); while (imageList.TryTake(out img)) { tasks.Add(Task.Factory.StartNew( async (obj) => { var imgPath = obj as string; using (var fStream = File.OpenRead(imgPath)) { try { // Update person faces on server side var persistFace = await faceServiceClient.AddPersonFaceInLargePersonGroupAsync(this.GroupId, Guid.Parse(p.PersonId), fStream, imgPath); return new Tuple<string, ClientContract.AddPersistedFaceResult>(imgPath, persistFace); } catch (FaceAPIException ex) { // if operation conflict, retry. if (ex.ErrorCode.Equals("ConcurrentOperationConflict")) { imageList.Add(imgPath); return null; } // if operation cause rate limit exceed, retry. else if (ex.ErrorCode.Equals("RateLimitExceeded")) { imageList.Add(imgPath); return null; } else if (ex.ErrorMessage.Contains("more than 1 face in the image.")) { Interlocked.Increment(ref invalidImageCount); } // Here we simply ignore all detection failure in this sample // You may handle these exceptions by check the Error.Error.Code and Error.Message property for ClientException object return new Tuple<string, ClientContract.AddPersistedFaceResult>(imgPath, null); } } }, img).Unwrap().ContinueWith((detectTask) => { // Update detected faces for rendering var detectionResult = detectTask?.Result; if (detectionResult == null || detectionResult.Item2 == null) { return; } } Persons.Add(p); } if (invalidImageCount > 0) { System.Diagnostics.Debug.WriteLine("Warning: more or less than one face is detected in {0} images, can not add to face list.", invalidImageCount); } System.Diagnostics.Debug.WriteLine("Response: Success. Total {0} faces are detected.", Persons.Sum(p => p.Faces.Count)); try { // Start train large person group System.Diagnostics.Debug.WriteLine("Request: Training group \"{0}\"", this.GroupId); await faceServiceClient.TrainLargePersonGroupAsync(this.GroupId); count++; // Wait until train completed while (true) { await Task.Delay(1000); var status = await faceServiceClient.GetLargePersonGroupTrainingStatusAsync(this.GroupId); count++; System.Diagnostics.Debug.WriteLine("Response: {0}. Group \"{1}\" training process is {2}", "Success", this.GroupId, status.Status); if (status.Status != Microsoft.ProjectOxford.Face.Contract.Status.Running) { break; } } //IdentifyButton.IsEnabled = true; } catch (FaceAPIException ex) { System.Diagnostics.Debug.WriteLine("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage); } GC.Collect(); CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(""); // Create a blob client for interacting with the blob service. CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("samplecontainer"); foreach (IListBlobItem blob in container.ListBlobs()) { // Blob type will be CloudBlockBlob, CloudPageBlob or CloudBlobDirectory // Use blob.GetType() and cast to appropriate type to gain access to properties specific to each type try { await Identify_Click(blob); } catch (Exception e) { returnStatus = e.ToString(); break; } } //Identify_Click(); return returnStatus; }
public IActionResult Edited([Bind("LastName,FirstName,Address,City,PersonID")] Persons persons) { _db.Update(persons, persons.PersonID); return(RedirectToAction(nameof(Index))); }
public PersonsViewModel(Persons persons) : this(persons, null) { }
protected override async Task InitializeAsync() { await base.InitializeAsync(); SelectedPerson = Persons.FirstOrDefault(); }
/// <summary> /// Pick image, detect and identify all faces detected /// </summary> /// <param name="sender">Event sender</param> /// <param name="e">Event arguments</param> private async void Identify_Click(object sender, RoutedEventArgs e) { // Show file picker Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.DefaultExt = ".jpg"; dlg.Filter = "Image files(*.jpg) | *.jpg"; var result = dlg.ShowDialog(); if (result.HasValue && result.Value) { // User picked one image // Clear previous detection and identification results TargetFaces.Clear(); SelectedFile = dlg.FileName; var sw = Stopwatch.StartNew(); var imageInfo = UIHelper.GetImageInfoForRendering(dlg.FileName); MainWindow mainWindow = Window.GetWindow(this) as MainWindow; string subscriptionKey = mainWindow._scenariosControl.SubscriptionKey; var faceServiceClient = new FaceServiceClient(subscriptionKey); // Call detection REST API using (var fileStream = File.OpenRead(dlg.FileName)) { try { var faces = await faceServiceClient.DetectAsync(fileStream); // Convert detection result into UI binding object for rendering foreach (var face in UIHelper.CalculateFaceRectangleForRendering(faces, MaxImageSize, imageInfo)) { TargetFaces.Add(face); } MainWindow.Log("Request: Identifying {0} face(s) in group \"{1}\"", faces.Length, GroupName); // Identify each face // Call identify REST API, the result contains identified person information var identifyResult = await faceServiceClient.IdentifyAsync(GroupName, faces.Select(ff => ff.FaceId).ToArray()); for (int idx = 0; idx < faces.Length; idx++) { // Update identification result for rendering var face = TargetFaces[idx]; var res = identifyResult[idx]; if (res.Candidates.Length > 0 && Persons.Any(p => p.PersonId == res.Candidates[0].PersonId.ToString())) { face.PersonName = Persons.Where(p => p.PersonId == res.Candidates[0].PersonId.ToString()).First().PersonName; } else { face.PersonName = "Unknown"; } } var outString = new StringBuilder(); foreach (var face in TargetFaces) { outString.AppendFormat("Face {0} is identified as {1}. ", face.FaceId, face.PersonName); } MainWindow.Log("Response: Success. {0}", outString); } catch (FaceAPIException ex) { MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage); } } } }
//------------------------------------------------------------------------------------- /// <summary> /// /// </summary> /// <param name="task"></param> protected override void AsyncTaskDoneBody(AsyncTask task) { #region Persons if(task.TaskName == "Persons") { users = (Persons)task.Result; } #endregion Persons #region Security if(task.TaskName == "Security") { psec = (PulsarSecurity)task.Result; fdgvGroups.DataSource = new DictionaryBinder(psec.SecurityGroups); } #endregion Security #region AddGroup if(task.TaskName == "AddGroup") { SecurityGroup gr = (SecurityGroup)task.Tag; psec.SecurityGroups.Add(gr.SID, gr); } #endregion AddGroup #region UpdNameGroup if(task.TaskName == "UpdNameGroup") { SecurityGroup gr = (SecurityGroup)task.Tag; psec.SecurityGroups[gr.SID].Name = gr.Name; } #endregion UpdNameGroup #region UpdDescGroup if(task.TaskName == "UpdDescGroup") { SecurityGroup gr = (SecurityGroup)task.Tag; psec.SecurityGroups[gr.SID].Description = gr.Description; } #endregion UpdDescGroup #region DelGroup if(task.TaskName == "DelGroup") { SecurityGroup gr = (SecurityGroup)task.Tag; psec.SecurityGroups.Remove(gr.SID); } #endregion DelGroup #region SetParents if(task.TaskName == "SetParents") { ValuesPair<OID,List<OID>> i = (ValuesPair<OID,List<OID>>)task.Tag; psec.SetParentsSidLinks(i.Value1, i.Value2); fdgvGroups_SelectionChanged(null, null); } #endregion SetParents #region SetChilds if(task.TaskName == "SetChilds") { ValuesPair<OID,List<OID>> i = (ValuesPair<OID,List<OID>>)task.Tag; psec.SetChildSidLinks(i.Value1, i.Value2); fdgvGroups_SelectionChanged(null, null); } #endregion SetChilds }
public string GetPersonIdFieldName() { if (Persons != null && Persons.Any()) { return(Persons[0].PersonId); } if (PayerPlanPeriods != null && PayerPlanPeriods.Any()) { return(PayerPlanPeriods[0].PersonId); } if (ConditionOccurrence != null && ConditionOccurrence.Any()) { return(ConditionOccurrence[0].PersonId); } if (Death != null && Death.Any()) { return(Death[0].PersonId); } if (DrugExposure != null && DrugExposure.Any()) { return(DrugExposure[0].PersonId); } if (ProcedureOccurrence != null && ProcedureOccurrence.Any()) { return(ProcedureOccurrence[0].PersonId); } if (Observation != null && Observation.Any()) { return(Observation[0].PersonId); } if (Measurement != null && Measurement.Any()) { return(Measurement[0].PersonId); } if (VisitOccurrence != null && VisitOccurrence.Any()) { return(VisitOccurrence[0].PersonId); } if (Cohort != null && Cohort.Any()) { return(Cohort[0].PersonId); } if (DeviceExposure != null && DeviceExposure.Any()) { return(DeviceExposure[0].PersonId); } if (Note != null && Note.Any()) { return(Note[0].PersonId); } throw new Exception("Cant find PersonId FieldName " + this.FileName); }
// Augmentation public bool AddPerson(string inPerson) { return(Persons.Add(inPerson)); }
private async Task Identify_Click(IListBlobItem blob) { if (true) { // User picked one image // Clear previous detection and identification results TargetFaces.Clear(); using (var client = new WebClient()) { client.DownloadFile(blob.Uri.AbsoluteUri, @"C:\Users\Thinksysuser\Pictures\Saved Pictures\"+blob.Uri.Segments.Last()); } var pickedImagePath = @"C:\Users\Thinksysuser\Pictures\Saved Pictures\" + blob.Uri.Segments.Last(); var renderingImage = UIHelper.LoadImageAppliedOrientation(pickedImagePath); var imageInfo = UIHelper.GetImageInfoForRendering(renderingImage); SelectedFile = renderingImage; var sw = Stopwatch.StartNew(); string subscriptionKey = ""; string subscriptionEndpoint = ""; var faceServiceClient = new FaceServiceClient(subscriptionKey, subscriptionEndpoint); // Call detection REST API using (var fStream = File.OpenRead(pickedImagePath)) { try { var faces = await faceServiceClient.DetectAsync(fStream); count++; System.Diagnostics.Debug.WriteLine("-----after detect----"+count); // Convert detection result into UI binding object for rendering foreach (var face in UIHelper.CalculateFaceRectangleForRendering(faces, MaxImageSize, imageInfo)) { TargetFaces.Add(face); } System.Diagnostics.Debug.WriteLine("Request: Identifying {0} face(s) in group \"{1}\"", faces.Length, this.GroupId); // Identify each face // Call identify REST API, the result contains identified person information var identifyResult = await faceServiceClient.IdentifyAsync(faces.Select(ff => ff.FaceId).ToArray(), largePersonGroupId: this.GroupId); count++; System.Diagnostics.Debug.WriteLine("-----after identify----" + count); for (int idx = 0; idx < faces.Length; idx++) { // Update identification result for rendering var face = TargetFaces[idx]; var res = identifyResult[idx]; if (res.Candidates.Length > 0 && Persons.Any(p => p.PersonId == res.Candidates[0].PersonId.ToString())) { face.PersonName = Persons.Where(p => p.PersonId == res.Candidates[0].PersonId.ToString()).First().PersonName; } else { face.PersonName = "Unknown"; } } var outString = new StringBuilder(); foreach (var face in TargetFaces) { outString.AppendFormat("Face {0} is identified as {1}. ", face.FaceId, face.PersonName); } System.Diagnostics.Debug.WriteLine("Response: Success. {0}", outString); } catch (FaceAPIException ex) { System.Diagnostics.Debug.WriteLine("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage); } } } GC.Collect(); }
public void TruncateAllData() { CDCatalogEntities.DeleteAllOnSubmit <CDCatalogEntity>(CDCatalogEntities); Persons.DeleteAllOnSubmit <Person>(Persons); SubmitChanges(); }
static void Main() { Console.Write("*Please enter your name: "); string name = Console.ReadLine(); // reading the console input for name. Mandatory! Console.Write("*Please enter your age: "); int age = int.Parse(Console.ReadLine()); //reading the console input for age. Mandatory! Console.Write("Please enter your email: "); string email = Console.ReadLine(); //reading the console input for email. Optional! Persons Person = new Persons(name, age, email); // creating a object from Persons class Console.WriteLine(Person); // Print the object on the console }
public IActionResult Edit(Persons model) { _personsService.Update(model); return(RedirectToAction("List")); }
static void Main() { Persons ivan = new Persons("Ivan", 18); Console.WriteLine(ivan); Console.WriteLine("Example 1"); try { TakeNewProfile("niki", 18); Console.WriteLine("-> OK"); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("Example 2"); try { TakeNewProfile("Niki", 18, "*****@*****.**"); Console.WriteLine("-> OK"); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Console.WriteLine("Example 3"); try { TakeNewProfile("niki", 101); Console.WriteLine("-> OK"); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("Example 4"); try { TakeNewProfile("Niki", 18, "*****@*****.**"); Console.WriteLine("-> OK"); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("Example 5"); try { TakeNewProfile("Niki", 18, "abv.bg"); Console.WriteLine("-> OK"); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
/// <summary> /// Pick the root person database folder, to minimum the data preparation logic, the folder should be under following construction /// Each person's image should be put into one folder named as the person's name /// All person's image folder should be put directly under the root person database folder /// </summary> /// <param name="sender">Event sender</param> /// <param name="e">Event argument</param> private async void FolderPicker_Click(object sender, RoutedEventArgs e) { bool groupExists = false; MainWindow mainWindow = Window.GetWindow(this) as MainWindow; string subscriptionKey = mainWindow._scenariosControl.SubscriptionKey; string endpoint = mainWindow._scenariosControl.SubscriptionEndpoint; var faceServiceClient = new FaceServiceClient(subscriptionKey, endpoint); // Test whether the group already exists try { MainWindow.Log("Request: Group {0} will be used to build a person database. Checking whether the group exists.", this.GroupId); await faceServiceClient.GetLargePersonGroupAsync(this.GroupId); groupExists = true; MainWindow.Log("Response: Group {0} exists.", this.GroupId); } catch (FaceAPIException ex) { if (ex.ErrorCode != "LargePersonGroupNotFound") { MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage); return; } else { MainWindow.Log("Response: Group {0} did not exist previously.", this.GroupId); } } if (groupExists) { var cleanGroup = System.Windows.MessageBox.Show(string.Format("Requires a clean up for group \"{0}\" before setting up a new person database. Click OK to proceed, group \"{0}\" will be cleared.", this.GroupId), "Warning", MessageBoxButton.OKCancel); if (cleanGroup == MessageBoxResult.OK) { await faceServiceClient.DeleteLargePersonGroupAsync(this.GroupId); this.GroupId = Guid.NewGuid().ToString(); } else { return; } } // Show folder picker System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog(); var result = dlg.ShowDialog(); // Set the suggestion count is intent to minimum the data preparation step only, // it's not corresponding to service side constraint const int SuggestionCount = 15; if (result == System.Windows.Forms.DialogResult.OK) { // User picked a root person database folder // Clear person database Persons.Clear(); TargetFaces.Clear(); SelectedFile = null; IdentifyButton.IsEnabled = false; // Call create large person group REST API // Create large person group API call will failed if group with the same name already exists MainWindow.Log("Request: Creating group \"{0}\"", this.GroupId); try { await faceServiceClient.CreateLargePersonGroupAsync(this.GroupId, this.GroupId, dlg.SelectedPath); MainWindow.Log("Response: Success. Group \"{0}\" created", this.GroupId); } catch (FaceAPIException ex) { MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage); return; } int processCount = 0; bool forceContinue = false; MainWindow.Log("Request: Preparing faces for identification, detecting faces in chosen folder."); // Enumerate top level directories, each directory contains one person's images int invalidImageCount = 0; foreach (var dir in System.IO.Directory.EnumerateDirectories(dlg.SelectedPath)) { var tasks = new List <Task>(); var tag = System.IO.Path.GetFileName(dir); Person p = new Person(); p.PersonName = tag; var faces = new ObservableCollection <Controls.Face>(); p.Faces = faces; // Call create person REST API, the new create person id will be returned MainWindow.Log("Request: Creating person \"{0}\"", p.PersonName); p.PersonId = (await RetryHelper.OperationWithBasicRetryAsync(async() => await faceServiceClient.CreatePersonInLargePersonGroupAsync(this.GroupId, p.PersonName, dir), new[] { typeof(FaceAPIException) }, traceWriter: _mainWindowLogTraceWriter )).PersonId.ToString(); MainWindow.Log("Response: Success. Person \"{0}\" (PersonID:{1}) created", p.PersonName, p.PersonId); string img; // Enumerate images under the person folder, call detection var imageList = new ConcurrentBag <string>( Directory.EnumerateFiles(dir, "*.*", SearchOption.AllDirectories) .Where(s => s.ToLower().EndsWith(".jpg") || s.ToLower().EndsWith(".png") || s.ToLower().EndsWith(".bmp") || s.ToLower().EndsWith(".gif"))); while (imageList.TryTake(out img)) { tasks.Add(Task.Factory.StartNew( async(obj) => { var imgPath = obj as string; using (var fStream = File.OpenRead(imgPath)) { try { // Update person faces on server side var persistFace = await faceServiceClient.AddPersonFaceInLargePersonGroupAsync(this.GroupId, Guid.Parse(p.PersonId), fStream, imgPath); return(new Tuple <string, ClientContract.AddPersistedFaceResult>(imgPath, persistFace)); } catch (FaceAPIException ex) { // if operation conflict, retry. if (ex.ErrorCode.Equals("ConcurrentOperationConflict")) { imageList.Add(imgPath); return(null); } // if operation cause rate limit exceed, retry. else if (ex.ErrorCode.Equals("RateLimitExceeded")) { imageList.Add(imgPath); return(null); } else if (ex.ErrorMessage.Contains("more than 1 face in the image.")) { Interlocked.Increment(ref invalidImageCount); } // Here we simply ignore all detection failure in this sample // You may handle these exceptions by check the Error.Error.Code and Error.Message property for ClientException object return(new Tuple <string, ClientContract.AddPersistedFaceResult>(imgPath, null)); } } }, img).Unwrap().ContinueWith((detectTask) => { // Update detected faces for rendering var detectionResult = detectTask?.Result; if (detectionResult == null || detectionResult.Item2 == null) { return; } this.Dispatcher.Invoke( new Action <ObservableCollection <Controls.Face>, string, ClientContract.AddPersistedFaceResult>(UIHelper.UpdateFace), faces, detectionResult.Item1, detectionResult.Item2); })); if (processCount >= SuggestionCount && !forceContinue) { var continueProcess = System.Windows.Forms.MessageBox.Show("The images loaded have reached the recommended count, may take long time if proceed. Would you like to continue to load images?", "Warning", System.Windows.Forms.MessageBoxButtons.YesNo); if (continueProcess == System.Windows.Forms.DialogResult.Yes) { forceContinue = true; } else { break; } } if (tasks.Count >= _maxConcurrentProcesses || imageList.IsEmpty) { await Task.WhenAll(tasks); tasks.Clear(); } } Persons.Add(p); } if (invalidImageCount > 0) { MainWindow.Log("Warning: more or less than one face is detected in {0} images, can not add to face list.", invalidImageCount); } MainWindow.Log("Response: Success. Total {0} faces are detected.", Persons.Sum(p => p.Faces.Count)); try { // Start train large person group MainWindow.Log("Request: Training group \"{0}\"", this.GroupId); await RetryHelper.VoidOperationWithBasicRetryAsync(() => faceServiceClient.TrainLargePersonGroupAsync(this.GroupId), new[] { typeof(FaceAPIException) }, traceWriter : _mainWindowLogTraceWriter); //await faceServiceClient.TrainLargePersonGroupAsync(this.GroupId); // Wait until train completed while (true) { await Task.Delay(1000); var status = await faceServiceClient.GetLargePersonGroupTrainingStatusAsync(this.GroupId); MainWindow.Log("Response: {0}. Group \"{1}\" training process is {2}", "Success", this.GroupId, status.Status); if (status.Status != Status.Running) { break; } } IdentifyButton.IsEnabled = true; } catch (FaceAPIException ex) { MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage); } } GC.Collect(); }
public void clear() { Persons.Clear(); }
public CommonViewModel() { _persons = new Persons(); this.People = _persons.PersonList; }