protected void ArmaPerfil(Modelo_Entidades.USUARIO oUsuarioActual, string nombre_formulario) { Controladora.CCURPF oCCURPF = new Controladora.CCURPF(); oForm = oCCURPF.obtenerFormulario(frmOperaciones.ObtenerInstancia().Name); collPerfilesObtenidos = oCCURPF.recuperarPerfilForm(oUsuarioActual, oForm); if (collPerfilesObtenidos.Find(delegate(Modelo_Entidades.PERFIL oPerfilBuscado) { return oPerfilBuscado.PER_CODIGO == "Z"; }) != null) { this.btnAutorizarOperacion.Enabled = true; this.btnAutCierre.Enabled = true; } else { this.btnAutorizarOperacion.Enabled = false; this.btnAutCierre.Enabled = false; } if (collPerfilesObtenidos.Find(delegate(Modelo_Entidades.PERFIL oPerfilBuscado) { return oPerfilBuscado.PER_CODIGO == "G"; }) != null) { this.btnRegistrarCargaDescarga.Enabled = true; } else { this.btnRegistrarCargaDescarga.Enabled = false; } }
// クラスリストでのFind挙動確認 public void findFromClass() { List<ParamClass> list = new List<ParamClass>(); list.Add(new ParamClass("abcde", 999)); list.Add(new ParamClass("hello", 12)); list.Add(new ParamClass("www", 23)); ParamClass p; Console.WriteLine("---- Find [hello] ----"); p = list.Find(param=> param.name == "hello"); Console.WriteLine("result={0}->{1}", p.name, p.val); Console.WriteLine("list count={0}", p.list.Count); // 見つからない場合は、型<T>の規定値が返る // class の場合は NULL が返る // UnityではSTRUCTでもNULLが返ってきたような気がするが… // まあ、見つからなかった場合の処理とかちゃんとしろよってところか Console.WriteLine("---- Find [Bad] ----"); p = list.Find(param=> param.name == "Bad"); if( null == p ) Console.WriteLine("NULL!"); else Console.WriteLine("result={0}->{1}", p.name, p.val); //Console.WriteLine("list count={0}", p.list.Count); // null参照で例外発生 }
public void CriarDummies(List<Produto> produtos) { var papelHigienico = produtos.Find(p => p.Id == 1); var arroz = produtos.Find(p => p.Id == 2); var feijao = produtos.Find(p => p.Id == 3); var batata = produtos.Find(p => p.Id == 4); var alface = produtos.Find(p => p.Id == 5); var papelHigienicoItem1 = new ItemDeProduto(papelHigienico, 1, new DateTime(2014, 09, 15)); var papelHigienicoItem2 = new ItemDeProduto(papelHigienico, 1, new DateTime(2014, 09, 28)); var arrozItem1 = new ItemDeProduto(arroz, 0, new DateTime(2014, 09, 28)); var feijaoItem1 = new ItemDeProduto(feijao, 0, null); var batataItem1 = new ItemDeProduto(batata, 1, new DateTime(2014, 09, 15)); var batataItem2 = new ItemDeProduto(batata, 2, new DateTime(2014, 09, 17)); var alfaceItem1 = new ItemDeProduto(alface, 0, new DateTime(2014, 09, 17)); Adicionar(papelHigienicoItem1); Adicionar(papelHigienicoItem2); Adicionar(arrozItem1); Adicionar(feijaoItem1); Adicionar(batataItem1); Adicionar(batataItem2); Adicionar(alfaceItem1); }
public Core(string path) { // Load Game from file path this.Game = ShootEmUpMaker.Serialization.ImportGame(path); // Inits this.Quit = false; this.CurrentSection = ShootEmUp.Enumrations.eSection.MAIN_MENU; // Window creation var ScreenSizes = new List<Tuple<eOrientation, uint, uint>>(); ScreenSizes.Add(new Tuple<eOrientation, uint, uint>(eOrientation.HORIZONTAL, 1024, 600)); ScreenSizes.Add(new Tuple<eOrientation, uint, uint>(eOrientation.VERTICAL, 700, 400)); uint w = ScreenSizes.Find(a => a.Item1 == this.Game._orientation).Item2; uint h = ScreenSizes.Find(a => a.Item1 == this.Game._orientation).Item3; this.VideoMode = new VideoMode(w, h, 32); this.Window = new RenderWindow(this.VideoMode, this.Game._name); // Init events this.Window.Closed += new EventHandler(OnClose); this.Window.KeyPressed += new EventHandler<KeyEventArgs>(OnKeyPressed); //_lastTouch = new Stopwatch(); //_lastTouch.Start(); //_lastShot = new Stopwatch(); //_lastShot.Start(); //_timer = new Stopwatch(); //_timer.Start(); //_background = new Sprite(); }
private void button_Ok_Click(object sender, EventArgs e) { if ((radioButton_tren.Checked == false && radioButton_aerob.Checked == false && radioButton_personal.Checked == false && radioButton_miniGr.Checked == false)) { MessageBox.Show(@"Выберите один из вариантов"); return; } switch (SelectedOptions.TypeWorkout) { case TypeWorkout.Аэробный_Зал: { SelectedOptions.GroupInfo.TrenerName = string.IsNullOrEmpty(_selectedTrenerName) ? "Имя неизвестно" : _selectedTrenerName; SelectedOptions.GroupInfo.ScheduleNote.SetTimeAndNameString(_selectedGroupTimeName); break; } case TypeWorkout.Тренажерный_Зал: break; case TypeWorkout.Персональная: SelectedOptions.PersonalTrener = _treners?.Find(x => x.Name == _selectedTrenerName); break; case TypeWorkout.МиниГруппа: SelectedOptions.PersonalTrener = _treners?.Find(x => x.Name == _selectedTrenerName); break; default: throw new ArgumentOutOfRangeException(); } DialogResult = DialogResult.OK; }
public ForwardBackward(List<HMM> HmmList, List<InputLine> Sequence) { m_HmmList = HmmList; m_Sequence = Sequence; m_WorkingStates = new List<HMM>(); m_WorkingStatesQty = 0; foreach (HMM Hmm in HmmList) if (!(Hmm.IsFirst || Hmm.IsFinal)) { m_WorkingStatesQty++; m_WorkingStates.Add(Hmm); } m_BeginingState = HmmList.Find(x => x.IsFirst == true); m_EndingState = HmmList.Find(x => x.IsFinal == true); m_FullSequenceCount = Sequence.Count + 2; // + 2 = for ending and beg BackwardValues = new double[m_FullSequenceCount,m_WorkingStatesQty]; ForwardValues = new double[m_FullSequenceCount,m_WorkingStatesQty]; for(int I = 0; I < m_FullSequenceCount; I++) for(int J = 0; J < m_WorkingStatesQty; J++) { BackwardValues[I,J] = 0; ForwardValues[I,J] = 0; } // backward L + 1; for (int I = 0; I < m_WorkingStatesQty; I++) BackwardValues[m_FullSequenceCount - 1, I] = 1; // Forward 0 for (int I = 0; I < m_WorkingStatesQty; I++) ForwardValues[0, I] = 1; }
// ################################################################################################################### // ############################################### 코사인 유사도 계산 ################################################ // ################################################################################################################### public static double CosSim(List<Tuple<string, string, double>> currentDoc, List<Tuple<string, string, double>> otherDoc) { double numerator = 0.0; double denominator_A = 0.0; double denominator_B = 0.0; double denominator = 0.0; if (currentDoc.Count != otherDoc.Count) { Console.WriteLine("not match feature Dictionary size"); return -1; } // 내적 계산 foreach (var item in currentDoc) { double otherVectorValue = otherDoc.Find(t => t.Item1 == item.Item1 || t.Item2 == item.Item1).Item3; numerator += otherVectorValue * item.Item3; } // 외적 계산 foreach (var item in currentDoc) { denominator_A += Math.Pow((double)currentDoc.Find(t => t.Item1 == item.Item1 || t.Item2 == item.Item1).Item3, 2.0); denominator_B += Math.Pow((double)otherDoc.Find(t => t.Item1 == item.Item1 || t.Item2 == item.Item1).Item3, 2.0); } denominator = Math.Sqrt(denominator_A) * Math.Sqrt(denominator_B); return numerator / denominator; }
/* * Health * Progress w/ abilities */ public RuntimeMoheData(IMohe Mohe, PlayerSeat seat, int idx) { baseMohe = Mohe; playerSeat = seat; baseExpType = BaseExpType.TranslateType(baseMohe.Data.ExperienceType); instanceID = baseMohe.Data.MoheID.ToString() + playerSeat + idx.ToString(); Health = (int)baseMohe.Stats.health; Exp = 0; abilities = new List <IRuntimeAbility>(); List <AbilityData> db = AbilityDatabase.Instance.GetFullList(); foreach (AbilityID abil in baseMohe.Abilities) { if (db?.Find(ability => ability.AbilityID == abil)) { abilities.Add(new RuntimeAbility(db?.Find(ability => ability.AbilityID == abil))); } } DamageMoheMechanic = new DamageMoheMechanic(this); DeathMoheMechanics = new DeathMoheMechanic(this); GainExpMoheMechanic = new GainExpMoheMechanic(this); GainLvlMoheMechanic = new GainLvlMoheMechanic(this); GainStatusMoheMehanic = new GainStatusMoheMehanic(this); HealMoheMechanic = new HealMoheMechanic(this); LoseStatusMoheMechanic = new LoseStatusMoheMechanic(this); }
public static void freshInitialize() { // check that the level is fresh GameObject[] gameObjects = GameObject.FindObjectsOfType<GameObject>(); if (gameObjects.Length != 2) return; List<GameObject> objectList = new List<GameObject>(gameObjects); if (objectList.Find(go => go.name == "Main Camera") == null || objectList.Find(go => go.name == "Directional Light") == null) return; // delete default objects foreach(GameObject ob in gameObjects) GameObject.DestroyImmediate(ob); // create player createPrefab("Assets/Prefabs/Player.prefab"); // create empty voxel object Vox.VoxelEditor.createEmpty(); // create sun createPrefab("Assets/Prefabs/Sun.prefab"); // create menu createPrefab("Assets/Prefabs/Main Menu.prefab"); // set lighting mode Lightmapping.giWorkflowMode = Lightmapping.GIWorkflowMode.OnDemand; }
public static List <Guid> AddDesignDays(this TBD.Building building, IEnumerable <DesignDay> coolingDesignDays, IEnumerable <DesignDay> heatingDesignDays, int repetitions = 30) { if (building == null) { return(null); } building.ClearDesignDays(); List <TBD.dayType> dayTypes = building.DayTypes(); List <Guid> result = new List <Guid>(); if (coolingDesignDays != null && coolingDesignDays.Count() != 0) { TBD.dayType dayType = dayTypes?.Find(x => x.name == "CDD"); List <TBD.CoolingDesignDay> coolingDesignDays_TBD = building.CoolingDesignDays(); foreach (DesignDay designDay in coolingDesignDays) { if (designDay == null) { continue; } TBD.CoolingDesignDay coolingDesignDay_TBD = coolingDesignDays_TBD?.Find(x => x.name == designDay.Name); if (coolingDesignDay_TBD == null) { coolingDesignDay_TBD = building.AddCoolingDesignDay(); } coolingDesignDay_TBD.Update(designDay, dayType, repetitions); result.Add(Guid.Parse(coolingDesignDay_TBD.GUID)); } } if (heatingDesignDays != null && heatingDesignDays.Count() != 0) { TBD.dayType dayType = dayTypes?.Find(x => x.name == "HDD"); List <TBD.HeatingDesignDay> heatingDesignDays_TBD = building.HeatingDesignDays(); foreach (DesignDay designDay in heatingDesignDays) { if (designDay == null) { continue; } TBD.HeatingDesignDay heatingDesignDay_TBD = heatingDesignDays_TBD?.Find(x => x.name == designDay.Name); if (heatingDesignDay_TBD == null) { heatingDesignDay_TBD = building.AddHeatingDesignDay(); } heatingDesignDay_TBD.Update(designDay, dayType, repetitions); result.Add(Guid.Parse(heatingDesignDay_TBD.GUID)); } } return(result); }
/* * What is an anonymous method? * In simple terms, anonymous method is a method without a name. Introduced in C#2. * They provide us a way of creating delegate instances without having to write a separate method. * * With anonymous Methods delegate parameters are optional. * Example : Adding dynamic button in windows form and in its event handler passing deligate without parameters (sender and e). * * This means the below code: Button1.Click += delegate(object obj, EventArgs eventArgs) { MessageBox.Show("Button Clicked"); }; can be rewritten as shown below Button1.Click += delegate { MessageBox.Show("Button Clicked"); }; */ static void Main(string[] args) { List<Employee> listEmployees = new List<Employee>() { new Employee() { ID = 101, Name = "Anand Dev" }, new Employee() { ID = 102, Name = "Uttam Kumar" }, new Employee() { ID = 103, Name = "Praveen" } }; #region 1. Using predicate // Using predicate - Step 2 Predicate<Employee> empPredicate = new Predicate<Employee>(FindEmployee); // Using predicate - Step 3 Employee employee = listEmployees.Find(empPredicate); Console.WriteLine("Using predicate - ID = {0}, Name = {1}", employee.ID, employee.Name); #endregion #region 2. Using anonynous mehtod. Employee employeeAnonymous = listEmployees.Find(delegate(Employee emp) { return emp.ID == 102; }); Console.WriteLine("\nUsing anonymous method - ID = {0}, Name = {1}", employeeAnonymous.ID, employeeAnonymous.Name); #endregion }
private void _processColon(SentenceElement colon, List<SentenceElement> elementList) { var mainEnumerationWord = elementList.Find(x => x.Order == colon.Order - 1); if (mainEnumerationWord != null) { log.InfoFormat("Enumeration main word is {0}", mainEnumerationWord.Text); var fisrtChildWord = elementList.Find(x => x.SyntacticParentWordId == mainEnumerationWord.Id); if (fisrtChildWord != null) { log.InfoFormat("First child in enumeration is {0}", fisrtChildWord.Text); if (_isCommaReplacementNeeded(mainEnumerationWord, fisrtChildWord, elementList)) { log.Info("Replacing colon..."); colon.Text = COLON_REPLACEMENT; } else { log.Info("Deleting colon..."); colon.Text = ""; } } else { log.Info("Child enumeration word not found. No action."); } } else { log.Info("Main Enumeration word not found. Replacing colon..."); colon.Text = COLON_REPLACEMENT; } }
public object GetDayInfo(List<smhiModel.Timesery> smhi, TimeSpan morningStart, TimeSpan morningEnd, TimeSpan eveningStart, TimeSpan eveningEnd) { if (DateTime.Now.TimeOfDay > morningEnd && DateTime.Now.TimeOfDay <= eveningEnd) { var evening = smhi.Find(x => x.date.TimeOfDay == eveningStart); string raining = (evening.pit == 0.0) ? "NEJ" : "JA"; var obj = new rainInformation { timeStart = eveningStart, timeEnd = eveningEnd, rain = raining }; return obj; } else { var morning = smhi.Find(x => x.date.TimeOfDay == morningStart); string raining = (morning.pit == 0.0) ? "NEJ" : "JA"; var obj = new rainInformation { timeStart = morningStart, timeEnd = morningEnd, rain = raining }; return obj; } }
public PredictionControl(IModel model, List<Property> properties, List<LoggedValue> loggedValues) { _logger = new LogIt("", loggedValues); // TODO Add Path // Variables from properties list M = (int) Convert.ToDouble(properties.Find(p => p.Name.Equals("M")).Value); _horizonSize = (int)Convert.ToDouble(properties.Find(p => p.Name.Equals("Horizon")).Value); _predictionHorizonSize = (int)Convert.ToDouble(properties.Find(p => p.Name.Equals("PredictionHorizon")).Value); // TODO _discount = Convert.ToDouble(properties.Find(p => p.Name.Equals("Discount")).Value); _startSigma = Convert.ToDouble(properties.Find(p => p.Name.Equals("StartSigma")).Value); _sigmaMin = Convert.ToDouble(properties.Find(p => p.Name.Equals("SigmaMin")).Value); var externalDiscretization = Convert.ToDouble(properties.Find(p => p.Name.Equals("ExternalDiscretization")).Value); var internalDiscretization = Convert.ToDouble(properties.Find(p => p.Name.Equals("InternalDiscretization")).Value); var TimeLimit = Convert.ToDouble(properties.Find(p => p.Name.Equals("TimeLimit")).Value); _iterationLimitOptimisation = (int)Convert.ToDouble(properties.Find(p => p.Name.Equals("OptimisationIterationLimit")).Value); _iterationsLimit = (int)(TimeLimit / externalDiscretization); _model = model; _model.SetDiscretizations(externalDiscretization, internalDiscretization); _state = new List<double>(_model.GetInitialState()); _minAction = _model.MinActionValues(); _maxAction = _model.MaxActionValues(); VestSum = 0; VestAv = 0; GenerateHorizon(); _iterationNumExternal = 0; _episodeNr = 0; }
/// <summary> /// Creates the local events and returns the creationEvents, the other Events are stored in the eventMap, handled objects are removed from storedObjects. /// </summary> /// <returns> /// The remote events. /// </returns> /// <param name='storedObjects'> /// Stored objects. /// </param> /// <param name='remoteTree'> /// Remote tree. /// </param> /// <param name='eventMap'> /// Event map. /// </param> public List<AbstractFolderEvent> CreateEvents( List<IMappedObject> storedObjects, IObjectTree<IFileableCmisObject> remoteTree, Dictionary<string, Tuple<AbstractFolderEvent, AbstractFolderEvent>> eventMap, ISet<IMappedObject> handledStoredObjects) { List<AbstractFolderEvent> createdEvents = new List<AbstractFolderEvent>(); var storedParent = storedObjects.Find(o => o.RemoteObjectId == remoteTree.Item.Id); foreach (var child in remoteTree.Children) { var storedMappedChild = storedObjects.Find(o => o.RemoteObjectId == child.Item.Id); if (storedMappedChild != null) { AbstractFolderEvent newEvent = this.CreateRemoteEventBasedOnStorage(child.Item, storedParent, storedMappedChild); eventMap[child.Item.Id] = new Tuple<AbstractFolderEvent, AbstractFolderEvent>(null, newEvent); } else { // Added AbstractFolderEvent addEvent = FileOrFolderEventFactory.CreateEvent(child.Item, null, MetaDataChangeType.CREATED, src: this); createdEvents.Add(addEvent); } createdEvents.AddRange(this.CreateEvents(storedObjects, child, eventMap, handledStoredObjects)); if (storedMappedChild != null) { handledStoredObjects.Add(storedMappedChild); } } return createdEvents; }
private DalEnDur() { listeDesAuteurs = new List<Auteur> { new Auteur {Id=1, Nom="Jules Verne"}, new Auteur {Id=2, Nom="Victor Hugo"}, new Auteur {Id=3, Nom="Albert Camus"} }; listeDesLivres = new List<Livre> { new Livre {Id=1, Auteur=listeDesAuteurs.Find(a => a.Id==1), Parution=new DateTime(1865,1,1), Titre="De la terre à la lune"}, new Livre {Id=2, Auteur=listeDesAuteurs.Find(a => a.Id==1), Parution=new DateTime(1864,1,1), Titre="Voyage au centre de la terre"}, new Livre {Id=3, Auteur=listeDesAuteurs.Find(a => a.Id==2), Parution=new DateTime(1862,1,1), Titre="Les misérables"}, new Livre {Id=4, Auteur=listeDesAuteurs.Find(a => a.Id==3), Parution=new DateTime(1942,1,1), Titre="L'étranger"}, new Livre {Id=5, Auteur=listeDesAuteurs.Find(a => a.Id==3), Parution=new DateTime(1947,1,1), Titre="La peste"} }; listeDesClients = new List<Client> { new Client {Email="*****@*****.**", Nom="M. Client1"}, new Client {Email="*****@*****.**", Nom="Mlle Client2"} }; listeLivresEmpruntes = new List<LivreEmprunt> { new LivreEmprunt {Emprunteur=listeDesClients.Find(c => c.Email=="*****@*****.**"), Livre=listeDesLivres.Find(l => l.Id==2)}, new LivreEmprunt {Emprunteur=listeDesClients.Find(c => c.Email=="*****@*****.**"), Livre=listeDesLivres.Find(l => l.Id==4)}, new LivreEmprunt {Emprunteur=listeDesClients.Find(c => c.Email=="*****@*****.**"), Livre=listeDesLivres.Find(l => l.Id==5)} }; }
public void execute() { sum s = delegate (int x, int y) { return x + y; }; for(int idx = 0; idx < 10; idx++) { s(idx, idx + 1); } //lambdas sum sd = (int x, int y) => { return x + y; }; sum sd1 = (x,y) => { return x + y; }; test sd2 = x => { return x ; }; test sd3 = x => x; List<string> li = new List<string>(); li.Find(person => person.Contains("a")); li.Find() pre = delegate (string x) { x.Contains("a");}; }
private static void AddActiveValue(string prefix, DataTable table, List<DataItem> dataItems) { // Add Value string valuePrefix = prefix + "/Value||00"; DeviceConfiguration.EditTable(table, valuePrefix, null, "id||00;"); // Add Triggers string triggerPrefix = valuePrefix + "/Triggers"; int i = 0; // Availability var item = dataItems.Find(x => x.Category == DataItemCategory.EVENT && x.Type == "AVAILABILITY"); if (item != null) { DeviceConfiguration.EditTable(table, triggerPrefix + "/Trigger||" + i.ToString("00"), null, "id||" + i.ToString("00") + ";link||" + item.Id + ";link_type||ID;value||AVAILABLE;"); i++; } // Emergency Stop item = dataItems.Find(x => x.Category == DataItemCategory.EVENT && x.Type == "EMERGENCY_STOP"); if (item != null) { DeviceConfiguration.EditTable(table, triggerPrefix + "/Trigger||" + i.ToString("00"), null, "id||" + i.ToString("00") + ";link||" + item.Id + ";link_type||ID;value||ARMED;"); i++; } // Add any Controller/Path Faults var items = dataItems.FindAll(x => x.Category == DataItemCategory.CONDITION && (x.Type == "SYSTEM" || x.Type == "LOGIC_PROGRAM" || x.Type == "MOTION_PROGRAM") && (x.FullAddress.ToLower().Contains("controller") || x.FullAddress.ToLower().Contains("path"))); if (items != null) { foreach (var item1 in items) { DeviceConfiguration.EditTable(table, triggerPrefix + "/Trigger||" + i.ToString("00"), null, "id||" + i.ToString("00") + ";link||" + item1.Id + ";link_type||ID;modifier||NOT;value||Fault;"); i++; } } // Controller Mode item = dataItems.Find(x => x.Category == DataItemCategory.EVENT && x.Type == "CONTROLLER_MODE"); if (item != null) { DeviceConfiguration.EditTable(table, triggerPrefix + "/Trigger||" + i.ToString("00"), null, "id||" + i.ToString("00") + ";link||" + item.Id + ";link_type||ID;value||AUTOMATIC;"); i++; } // Execution Mode item = dataItems.Find(x => x.Category == DataItemCategory.EVENT && x.Type == "EXECUTION"); if (item != null) { DeviceConfiguration.EditTable(table, triggerPrefix + "/Trigger||" + i.ToString("00"), null, "id||" + i.ToString("00") + ";link||" + item.Id + ";link_type||ID;value||ACTIVE;"); i++; } // Add Result DeviceConfiguration.EditTable(table, valuePrefix + "/Result", "Active", "numval||2;"); }
internal static void Main(string[] args) { List<string> names = new List<string>{ "Zhou Kai", "Liu Yaqiao", "Xiong Jie", "Wan Chenchen", "Zhao Yi"}; Console.WriteLine(names.Find(x => x.Equals("Zhou Kai"))); Console.WriteLine(names.Find(x => x.Equals("zhou kai"))); // returns null instead of String.Empty Console.ReadKey(); }
override public void recalcFlow(ref List<Component> compList, ref List<Pipe> pipeList) { Pipe p1 = pipeList.Find(x => x.EndComponentID == id); flowIn = p1.CurrentFlow; flowOut1 = (percentage * flowIn / 100); flowOut2 = ((100 - percentage) * flowIn / 100); Pipe p2 = null; p2 = pipeList.Find(x => x.ID == isOut1Available); if (p2 != null) { if (p2.MaxFlow > flowOut1 && p2.CurrentFlow != flowOut1) { p2.CurrentFlow = flowOut1; Component c = compList.Find(x => x.Id == p2.EndComponentID); c.recalcFlow(ref compList, ref pipeList); } else if (flowOut1 >= p2.MaxFlow && p2.CurrentFlow != p2.MaxFlow) { p2.CurrentFlow = p2.MaxFlow; Component c = compList.Find(x => x.Id == p2.EndComponentID); c.recalcFlow(ref compList, ref pipeList); } } Pipe p3 = null; p3 = pipeList.Find(x => x.ID == isOut2Available); if (p3 != null) { if (p3.MaxFlow > flowOut2 && p3.CurrentFlow != flowOut2) { p3.CurrentFlow = flowOut2; Component c = compList.Find(x => x.Id == p3.EndComponentID); c.recalcFlow(ref compList, ref pipeList); } else if (flowOut2 >= p3.MaxFlow && p3.CurrentFlow != p3.MaxFlow) { p3.CurrentFlow = p3.MaxFlow; Component c = compList.Find(x => x.Id == p3.EndComponentID); c.recalcFlow(ref compList, ref pipeList); } } if (p1.Removing == true) isInAvailable = -1; else if (p2.Removing == true) isOut1Available = -1; else if (p3.Removing == true) isOut2Available = -1; }
public CorpAduitOrderInfoModel GetAduitOrderInfoById(int aduitOrderId) { CorpAduitOrderEntity corpAduitOrderEntity = _corpAduitOrderDal.Find <CorpAduitOrderEntity>(aduitOrderId); CorpAduitOrderInfoModel corpAduitOrderInfoModel = Mapper.Map <CorpAduitOrderEntity, CorpAduitOrderInfoModel>(corpAduitOrderEntity); //审批单与订单关联信息 List <CorpAduitOrderDetailEntity> corpAduitOrderDetailEntities = _corpAduitOrderDetailDal.Query <CorpAduitOrderDetailEntity>( n => n.AduitOrderId == corpAduitOrderEntity.AduitOrderId, true).ToList(); corpAduitOrderInfoModel.OrderDetailList = Mapper.Map <List <CorpAduitOrderDetailEntity>, List <CorpAduitOrderDetailModel> >( corpAduitOrderDetailEntities); //审批环节信息 List <CorpAduitOrderFlowEntity> corpAduitOrderFlowEntities = _corpAduitOrderFlowDal.Query <CorpAduitOrderFlowEntity>( n => n.AduitOrderId == corpAduitOrderEntity.AduitOrderId, true).ToList(); corpAduitOrderInfoModel.FlowList = Mapper.Map <List <CorpAduitOrderFlowEntity>, List <CorpAduitOrderFlowModel> >( corpAduitOrderFlowEntities); //审批日志信息 List <CorpAduitOrderLogEntity> corpAduitOrderLogEntities = _corpAduitOrderLogDal.Query <CorpAduitOrderLogEntity>( n => n.AduitOrderId == corpAduitOrderEntity.AduitOrderId, true).ToList(); corpAduitOrderInfoModel.LogList = Mapper.Map <List <CorpAduitOrderLogEntity>, List <CorpAduitOrderLogModel> >( corpAduitOrderLogEntities); List <CustomerModel> customerModels = _getCustomerBll.GetCustomerByCidList(corpAduitOrderInfoModel.AduitCidList); if (corpAduitOrderInfoModel.FlowList != null && corpAduitOrderInfoModel.FlowList.Count > 0) { corpAduitOrderInfoModel.FlowList.ForEach(n => { n.FlowCustomerName = customerModels?.Find(x => x.Cid == n.FlowCid)?.RealName; }); } if (corpAduitOrderInfoModel.LogList != null && corpAduitOrderInfoModel.LogList.Count > 0) { corpAduitOrderInfoModel.LogList.ForEach(n => { if (n.DealCid.HasValue) { n.DealCustomerName = customerModels?.Find(x => x.Cid == n.DealCid.Value)?.RealName; } }); } return(corpAduitOrderInfoModel); }
private static void AddCaptureItems(string prefix, DataTable table, List<DataItem> dataItems) { string capturePrefix = prefix + "/Capture"; var item = dataItems.Find(x => x.Category == DataItemCategory.EVENT && x.Type == "PROGRAM"); if (item != null) DeviceConfiguration.EditTable(table, capturePrefix + "/Item||00", null, "id||00;name||program_name;link||" + item.Id + ";"); item = dataItems.Find(x => x.Category == DataItemCategory.EVENT && x.Type == "EXECUTION"); if (item != null) DeviceConfiguration.EditTable(table, capturePrefix + "/Item||01", null, "id||01;name||execution_mode;link||" + item.Id + ";"); }
public UserGroupsViewModel() { _users = new List<UserEntity>(); _users.Add(new UserEntity { Id = 1, Username = "******", Description = "Admin, user, developer" }); _users.Add(new UserEntity { Id = 2, Username = "******", Description = "Admin" }); _users.Add(new UserEntity { Id = 3, Username = "******", Description = "Admin, developer" }); _users.Add(new UserEntity { Id = 4, Username = "******", Description = "User, developer" }); _users.Add(new UserEntity { Id = 5, Username = "******", Description = "User" }); UserGroups = new ObservableCollection<UserGroupEntity>(); UserGroups.Add(new UserGroupEntity { Id = 1, Name = "Administrators", Description = "Administrators group", Users = new List<UserEntity>() }); UserGroups[0].Users.Add(_users.Find(u => u.Id == 1)); UserGroups[0].Users.Add(_users.Find(u => u.Id == 2)); UserGroups[0].Users.Add(_users.Find(u => u.Id == 3)); UserGroups.Add(new UserGroupEntity { Id = 2, Name = "Users", Description = "Users group", Users = new List<UserEntity>() }); UserGroups[1].Users.Add(_users.Find(u => u.Id == 1)); UserGroups[1].Users.Add(_users.Find(u => u.Id == 4)); UserGroups[1].Users.Add(_users.Find(u => u.Id == 5)); UserGroups.Add(new UserGroupEntity { Id = 3, Name = "Developers", Description = "Developers group", Users = new List<UserEntity>() }); UserGroups[2].Users.Add(_users.Find(u => u.Id == 1)); UserGroups[2].Users.Add(_users.Find(u => u.Id == 3)); UserGroups[2].Users.Add(_users.Find(u => u.Id == 4)); _cvs = new CollectionViewSource(); _cvs.Source = UserGroups; }
public void SetUserNameFromGUI() { List<Text> components = new List<Text>(this.gameObject.GetComponentsInChildren<Text>()); var text = components.Find(c => c.name == "Text"); var placeholder = components.Find(c => c.name == "UsernamePlaceholder"); _networkServices.SetUserName(text.text); placeholder.text = text.text; text.text = ""; }
public void ReturnsPublicAndPrivateStaticAndNonStaticMethods() { ITypeInfo typeInfo = Reflector.Wrap(typeof(TestClass)); List<IMethodInfo> methods = new List<IMethodInfo>(typeInfo.GetMethods()); foreach (string name in new string[] { "PrivateMethod", "PrivateStaticMethod", "PublicMethod", "PublicStaticMethod" }) Assert.NotNull(methods.Find(methodInfo => methodInfo.Name == name)); Assert.Null(methods.Find(methodInfo => methodInfo.Name == "Property")); }
public BaseReciever this[Guid index] { get { return(items?.Find(item => Guid.Equals(item.ID, index))); } private set { items?.Find(item => Guid.Equals(item.ID, index))?.Copy(value); } }
public static TreeNode<int> BuildTreeFromUserInput() { Console.Write("Please enter nodes number N: "); var nodesNumber = int.Parse(Console.ReadLine()); var nodes = new List<TreeNode<int>>(); for (int i = 0; i < nodesNumber - 1; i++) { var pair = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); var parentValue = int.Parse(pair[0]); var childValue = int.Parse(pair[1]); if (nodes.Any(n => n.Value == parentValue) && nodes.Any(n => n.Value == childValue)) { var parent = nodes.Find(p => p.Value == parentValue); var child = nodes.Find(c => c.Value == childValue); parent.Add(child); child.Parent = parent; } else if (nodes.Any(n => n.Value == parentValue)) { var parent = nodes.Find(p => p.Value == parentValue); var child = new TreeNode<int>(childValue); parent.Add(child); child.Parent = parent; nodes.Add(child); } else if (nodes.Any(n => n.Value == childValue)) { var parent = new TreeNode<int>(parentValue); var child = nodes.Find(p => p.Value == childValue); parent.Add(child); child.Parent = parent; nodes.Add(parent); } else { var parent = new TreeNode<int>(parentValue); var child = new TreeNode<int>(childValue); parent.Add(child); child.Parent = parent; nodes.Add(parent); nodes.Add(child); } } return nodes.FirstOrDefault(n => n.IsRoot); }
public Viterbi(List<HMM> HmmList, List<InputLine> Sequence) { m_WorkingStates = new List<HMM>(); m_Sequence = Sequence; foreach (HMM Hmm in HmmList) if (!(Hmm.IsFirst || Hmm.IsFinal)) m_WorkingStates.Add(Hmm); m_BeginingState = HmmList.Find(x => x.IsFirst == true); m_EndingState = HmmList.Find(x => x.IsFinal == true); //+2 for fist and last state Results = new ViterbiResult[Sequence.Count + 2, m_WorkingStates.Count]; }
/// <summary> /// Creates a map object layer from .tmx /// </summary> /// <param name="node"></param> public MapObjectLayer(XmlNode node, int TileWidth, int TileHeight) : base(node) { if (node.Attributes["color"] != null) { // get the color string, removing the leading # string color = node.Attributes["color"].Value.Substring(1); // get the RGB individually string r = color.Substring(0, 2); string g = color.Substring(2, 2); string b = color.Substring(4, 2); // convert to the color Color = new Color( (byte)int.Parse(r, NumberStyles.AllowHexSpecifier), (byte)int.Parse(g, NumberStyles.AllowHexSpecifier), (byte)int.Parse(b, NumberStyles.AllowHexSpecifier)); } Objects = new List<MapObject>(); foreach (XmlNode objectNode in node.SelectNodes("object")) { MapObject mapObjectContent = new MapObject(objectNode); mapObjectContent.ScaleObject(TileWidth, TileHeight); mapObjectContent.Name = this.Name + "_" + mapObjectContent.Name; // Object names need to be unique for our lookup system, but Tiled // doesn't require unique names. string objectName = mapObjectContent.Name; int duplicateCount = 2; // if a object already has the same name... if (Objects.Find(o => o.Name.Equals(objectName)) != null) { // figure out a object name that does work do { objectName = string.Format("{0}{1}", mapObjectContent.Name, duplicateCount); duplicateCount++; } while (Objects.Find(o => o.Name.Equals(objectName)) != null); // log a warning for the user to see Debug.Log("Renaming object \"" + mapObjectContent.Name + "\" to \"" + objectName + "\" in layer \"" + Name + "\" to make a unique name."); // save that name mapObjectContent.Name = objectName; } //Objects.Add(mapObjectContent); AddObject(mapObjectContent); } }
public ActionResult Index(int ID) { ViewBag.OpenDialog = true; List<Person> pr = new List<Person>(); for (int i = 0; i < 10; i++) { pr.Add(new Person { ID = i, LastName = "10" + i.ToString() }); } ViewBag.P = pr.Find(x => x.ID == ID); ViewBag.Model = pr; return View(pr.Find(x => x.ID == ID)); }
public static List<ColumnData> SetDefaultColumns(List<ColumnData> columns) { if (columns.Find(i => i.Name == DbCIC.DsStatus) == null) columns.Add(new ColumnData { Name = DbCIC.DsStatus, Type = DbDEF.VarchrNull(3), DefaultValue = "1" }); if (columns.Find(i => i.Name == DbCIC.InsertOn) == null) columns.Add(new ColumnData { Name = DbCIC.InsertOn, Type = DbDEF.VarchrNull(20), DefaultValue = "01.01.1900" }); if (columns.Find(i => i.Name == DbCIC.ModifyOn) == null) columns.Add(new ColumnData { Name = DbCIC.ModifyOn, Type = DbDEF.VarchrNull(20) }); return columns; }
override public void recalcFlow(ref List<Component> compList, ref List<Pipe> pipeList) { Pipe p1 = pipeList.Find(x => x.EndComponentID == id); flowIn = p1.CurrentFlow; flowOut1 = flowIn / 2; flowOut2 = flowIn / 2; Pipe p2 = null; p2 = pipeList.Find(x => x.ID == isOut1Available); if (p2 != null) { if (p2.MaxFlow > flowOut1 && p2.CurrentFlow != flowOut1) { p2.CurrentFlow = flowOut1; Component c = compList.Find(x => x.Id == p2.EndComponentID); c.recalcFlow(ref compList, ref pipeList); } else if (flowOut1 >= p2.MaxFlow && p2.CurrentFlow != p2.MaxFlow) { p2.CurrentFlow = p2.MaxFlow; Component c = compList.Find(x => x.Id == p2.EndComponentID); c.recalcFlow(ref compList, ref pipeList); } } Pipe p3 = null; p3 = pipeList.Find(x => x.ID == isOut2Available); if (p3 != null) { if (p3.MaxFlow > flowOut2 && p3.CurrentFlow != flowOut2) { p3.CurrentFlow = flowOut2; Component c = compList.Find(x => x.Id == p3.EndComponentID); c.recalcFlow(ref compList, ref pipeList); } else if (flowOut2 >= p3.MaxFlow && p3.CurrentFlow != p3.MaxFlow) { p3.CurrentFlow = p3.MaxFlow; Component c = compList.Find(x => x.Id == p3.EndComponentID); c.recalcFlow(ref compList, ref pipeList); } } }
public static void Main(string[] args) { List<string> par = new List<string>(args); bool inproc = par.Find(x => x == "-inproc") != null; bool wait = par.Find(x => x == "-wait") != null; RunTests( new HelloWorld(), new LatencyBenchmark(inproc), new ThroughputBenchmark()); Console.WriteLine("Finished running tests."); if (wait) Console.ReadLine(); }
public void GetResults() { errorLabel.Visible = false; choicesRadioButtonList.Visible = false; submitButton.Visible = false; int pollID = Convert.ToInt32(Request["poll_id"]); List<PollResult> rawResults = PollDAL.GetPollResults(pollID); Poll curPoll = PollDAL.GetPoll(pollID); List<PollResultItem> resultsList = new List<PollResultItem>(); foreach (Choice curChoice in curPoll.Choices) { PollResultItem newPollPollResultItem = new PollResultItem(); newPollPollResultItem.ChoiceName = curChoice.choice; newPollPollResultItem.VotesCount = 0; resultsList.Add(newPollPollResultItem); } foreach (PollResult pollResult in rawResults) { string curAnswer = PollDAL.GetChoice(pollResult.answerId); PollResultItem curPollResultItem = resultsList.Find(delegate(PollResultItem pollResultItem) { return pollResultItem.ChoiceName == curAnswer; }); if (curPollResultItem != null) { resultsList.Find(delegate(PollResultItem pollResultItem){return pollResultItem.ChoiceName == curAnswer;}).VotesCount++; } } foreach (PollResultItem pollResultItem in resultsList) { pollResultItem.Percentage = Convert.ToInt32((pollResultItem.VotesCount * 100) / rawResults.Count); } // Form chart string scoresDistribution = string.Empty; string answersDistribution = string.Empty; for (int i = 0, j = resultsList.Count - 1; i < resultsList.Count; i++, j--) { bool addSeparator = (j == 0) ? false : true; answersDistribution += resultsList[i].ChoiceName + "(" + resultsList[i].VotesCount + " votes)" + ((addSeparator) ? "|" : String.Empty); scoresDistribution += resultsList[j].Percentage.ToString() + ((addSeparator) ? "," : String.Empty); } int chartHeight = 40 + 20 * resultsList.Count; chart.ImageUrl = "http://chart.apis.google.com/chart?chbh=15,4,8&chco=A30313&chs=300x" + chartHeight.ToString() + "&chd=t:" + scoresDistribution + "&cht=bhs&chxt=y,x&chxl=0:|" + answersDistribution + "|1:|0%|20%|40%|60%|80%|100%"; }
private Passenger(XElement elemPassenger, List<Company> companies) { Name = elemPassenger.Attribute("name").Value; PointsDelivered = Convert.ToInt32(elemPassenger.Attribute("points-delivered").Value); XAttribute attr = elemPassenger.Attribute("lobby"); if (attr != null) Lobby = companies.Find(cpy => cpy.Name == attr.Value); attr = elemPassenger.Attribute("destination"); if (attr != null) Destination = companies.Find(cpy => cpy.Name == attr.Value); Route = new List<Company>(); foreach (XElement elemRoute in elemPassenger.Elements("route")) Route.Add(companies.Find(cpy => cpy.Name == elemRoute.Value)); Enemies = new List<Passenger>(); }
private static void _AdicionarConsulta() { Console.Clear(); if (_lstClientes.Count() == 0) { Console.WriteLine(Resources.MsgConsultasCadastroPaciente); } else { Consulta consulta = new Consulta(); consulta.Codigo = _lstConsultas.Count() > 0 ? _lstConsultas.Max(item => item.Codigo) + 1 : 1; Console.WriteLine(Resources.MsgConsultasPreenchaInform); Console.Write("[ 1 ] - " + Resources.ConsultaNomeCliente + " "); var codigoCliente = Console.ReadLine(); if (_ExisteCliente(codigoCliente) > 0) { var cliente = _lstClientes?.Find(item => item.Codigo == Convert.ToInt32(codigoCliente)); consulta.CodigoCliente = cliente.Codigo; consulta.NomeCliente = cliente.Nome; Console.Write("[ 2 ] - " + Resources.ConsultaData + " "); consulta.Data = Convert.ToDateTime(Console.ReadLine()); Console.Write("[ 3 ] - " + Resources.ConsultaHorario + " "); consulta.Horario = Console.ReadLine(); Console.Write("[ 4 ] - " + Resources.ConsultaPeso + " "); consulta.Peso = Convert.ToDouble(Console.ReadLine()); Console.Write("[ 5 ] - " + Resources.ConsultaPercentGordura + " "); consulta.PercentGorduraCorporal = Convert.ToDouble(Console.ReadLine()); Console.Write("[ 6 ] - " + Resources.ConsultaSensacaoFisica + " "); consulta.SensacaoFisica = Console.ReadLine(); Console.Write("[ 7 ] - " + Resources.ConsultaRestricoes + " "); consulta.Restricoes = Console.ReadLine(); _lstConsultas.Add(consulta); cliente.AdicionarConsulta(consulta); _ExibirConsulta(consulta); } else { Console.WriteLine(Resources.ConsultaPacienteNEncontrado); } } Console.WriteLine(Resources.MsgPressioneTeclaPVoltar); Console.ReadLine(); }
private void RefreshOrderItemList(List <singleItemOrder> theList) { try { if (localTshirtList == null) { return; } lvOrderedProducts.Items.Clear(); if (theList == null) { return; } ListViewItem item; tshirt currentTshirt; int reserved_amount; foreach (singleItemOrder o_item in theList) { currentTshirt = localTshirtList?.Find(t => t.id == o_item.tshirt_id); if (currentTshirt == null) { currentTshirt = new tshirt(); } decimal a = ((decimal)currentTshirt.default_loss_percentage / 100); reserved_amount = (int)Math.Ceiling((decimal)(a * o_item.amount) + o_item.amount); item = new ListViewItem(currentTshirt.company.name); item.Tag = o_item; item.SubItems.AddRange(new string[] { currentTshirt.style.name, currentTshirt.sex, currentTshirt.color.name, o_item.amount.ToString(), reserved_amount.ToString() }); item.ToolTipText = "Kliknij mnie dwukrotnie, by usunąć z listy"; lvOrderedProducts.Items.Add(item); } } catch { lvOrderedProducts.Items.Clear(); this.PushNotification("Nie udało się wyświetlić listy produktów", 2); } }
public void PlayUIMusic(MusicType type, bool useFadeOut = true) { var track = tracks?.Find(s => s.type == type); var clip = track?.clip; if (clip == null) { Debug.Log($"Can't find clip with type \"{type.ToString()}\" in UISoundManager"); return; } if (_currentMusic != null && _currentMusic == track) { return; } _currentMusic = track; if (useFadeOut && UIMusicPlayer.isPlaying) { _isFadingOut = true; return; } _isFadingOut = false; StartUIMusic(); }
public void DefineStorey(List <Storey> storeysNumbersTypeInAllFacades) { try { var storey = new Storey(BlRefName); if (storey.Type == EnumStorey.Number) { // поиск в общем списке этажей. Номерные этажи всех фасадов должны быть на одном уровне var storeyAllFacades = storeysNumbersTypeInAllFacades?.Find(s => s.Number == storey.Number); if (storeyAllFacades == null) { storeysNumbersTypeInAllFacades?.Add(storey); } else { storey = storeyAllFacades; } //Height = Settings.Default.FacadeFloorHeight; } Storey = storey; } catch (Exception ex) { // ошибка определения номера этажа монтажки - это не чердак (Ч), не парапет (П), и не // просто число Inspector.AddError(ex.Message + BlRefName, IdBlRefMounting, icon: System.Drawing.SystemIcons.Error); Logger.Log.Error(ex, "Floor - DefineStorey()"); } }
/// <summary> /// 计算影片结束时间 /// </summary> /// <param name="name">影片名称</param> /// <param name="startTime">开始时间</param> /// <returns></returns> private string UpdateTime(string name, string startTime) { //读取timejson中的数据 if (!File.Exists(SetPath.TimeJosnPath)) { //如果不存在,则创建 // File.Create("time.txt"); using (FileStream file = new FileStream(SetPath.TimeJosnPath, FileMode.Create)) { } } string timeJson = File.ReadAllText(SetPath.TimeJosnPath); List <SetTime> list = jss.Deserialize <List <SetTime> >(timeJson); SetTime se = list?.Find(x => { return(x.MovieName == name); }); if (se == null) { //如果找不到该影片的话 //则直接把一个空值传递回去 return(""); } else { string time = SetMovieTime(se.MovieTime, startTime); return(time); } }
// GET api/employee/5 //public EmployeeModel GetEmployee(int id) //{ // try // { // using (var empDbContext = new EmployeeDB()) // { // var employeeList = empDbContext.emps.ToList(); // List<EmployeeModel> employees = AdaptToEmployeeModel(employeeList); // if (employees != null) // { // return employees.Find(x => x.EmpId == id); // } // return null; // } // } // catch (Exception e) // { // Console.WriteLine(e); // throw; // } //} //public HttpResponseMessage GetEmployee(int id) //{ // try // { // using (var empDbContext = new EmployeeDB()) // { // var employeeList = empDbContext.emps.ToList(); // List<EmployeeModel> employees = AdaptToEmployeeModel(employeeList); // var employee = employees?.Find(x => x.EmpId == id); // if (employee != null) // { // return Request.CreateResponse(HttpStatusCode.OK, employee); // } // return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee with id = " + id + " not found"); ; // } // } // catch (Exception e) // { // Console.WriteLine(e); // return Request.CreateErrorResponse(HttpStatusCode.BadRequest, e); // } //} public IHttpActionResult GetEmployee(int id) { try { using (var empDbContext = new EmployeeDB()) { var employeeList = empDbContext.emps.ToList(); List <EmployeeModel> employees = AdaptToEmployeeModel(employeeList); var employee = employees?.Find(x => x.EmpId == id); if (employee != null) { return(Ok(employee)); } // return NotFound(); // For giving custom message use the below return return(Content(HttpStatusCode.NotFound, "Employee with id = " + id + " not found")); } } catch (Exception e) { Console.WriteLine(e); // return BadRequest(); return(Content(HttpStatusCode.BadRequest, e)); } }
/// <summary> /// Add the trasaction to the data source /// </summary> /// <param name="tranModel">transaction details to be added</param> /// <returns>throw exepction if application id already exist</returns> public List <TransactionModel> PostTransation(TransactionModel tranModel) { try { var allTransaction = allTransactions?.Find(x => x.ApplicationId == tranModel.ApplicationId); if (allTransaction == null) { allTransactions.Add(allTransaction); } } catch (Exception ex) { throw ex; } return(allTransactions); }
private Command tryGetNestedCommand(List <string> extra) { CommandSet nestedCommands = NestedCommandSets?.Find(c => c.Suite == extra[0]); if (nestedCommands == null) { return(null); } List <string> extraCopy = new List <string>(extra); extraCopy.RemoveAt(0); if (extraCopy.Count == 0) { return(null); } Command command = nestedCommands.GetCommand(extraCopy); if (command != null) { extra.Clear(); extra.AddRange(extraCopy); return(command); } return(null); }
/// <summary> /// Load the currency associated with the currency name /// </summary> /// <param name="currencyName">Name of the currency to load</param> /// <returns>The currenct currency, null if not found</returns> public static Currency LoadCurrency(string currencyName) { List <Currency> listCurrency = null; //List of all currency Currency currentCurrency = null; //The currency to use try { //Parse Json to get all currencies registered using (StreamReader r = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "\\Resources\\currencies.json")) { string json = r.ReadToEnd(); listCurrency = JsonConvert.DeserializeObject <List <Currency> >(json); } //Retrieve the currency associated to the currency name currentCurrency = listCurrency?.Find(item => String.Compare(item.Name, currencyName) == 0); if (currentCurrency == null) { throw new Exception("No currency was found associated with the currency name " + currencyName); } } catch (Exception e) { //Log some message } return(currentCurrency); }
private void PhoneCheck(string phone, List <PhoneBook> phoneBook) { while (true) { if (phoneBook?.Find(f => phone != null && f.PhoneNumber == int.Parse(phone)) != null) { Console.Clear(); ErrorMessage("Phone number is already exists !\nPlease, enter another phone number."); phone = Console.ReadLine(); } else if (phone == null || phone.Length != 9) { Console.Clear(); ErrorMessage("Phone must be 9 characters length !"); Console.Write("Enter phone number : "); phone = Console.ReadLine(); } else if (!int.TryParse(phone, out var result)) { Console.Clear(); ErrorMessage("Phone must contain only numbers !"); Console.Write("Enter phone number : "); phone = Console.ReadLine(); } else { PhoneNumber = result; return; } } }
public virtual BaseDistribution EvaluateExtended(List <CorrelatedPair> correlations) { if (IsUnary) { var left = Left.EvaluateExtended(correlations); var result = Evaluation.DistributionUnary(left, OperationType); return(result); } else { var left = Left.EvaluateExtended(correlations); var right = Right.EvaluateExtended(correlations); var corr = correlations?.Find(x => x.CheckDistributions(left, right)); if (corr != null) { return(Evaluation.DistributionBinaryCorrelated(corr.GetBivariate(left, right), OperationType)); } else { var result = Evaluation.DistributionBinary(left, right, OperationType); return(result); } } }
public void DeleteRedemptionOption(string rewardName) { EnsureFolderCreated(); var fullPath = FullFileName(RedemptionOptionsFileName); var existingOptions = new List <RedemptionOption>(); if (File.Exists(fullPath)) { var RedemptionOptionsJson = File.ReadAllText(fullPath); existingOptions = JsonConvert.DeserializeObject <List <RedemptionOption> >(RedemptionOptionsJson); } var result = existingOptions?.Find(x => x.RewardName == rewardName); if (result != null) { existingOptions.Remove(result); } var newJson = JsonConvert.SerializeObject(existingOptions); File.WriteAllText(fullPath, newJson); }
public Line(Block block, List <Block> blocks) { Block = block; Confidence = block.Confidence; Geometry = block.Geometry; Id = block.Id; Text = block == null ? string.Empty : block.Text; Words = new List <Word>(); var relationships = block?.Relationships; if (relationships != null && relationships.Count > 0) { foreach (var relationship in relationships) { if (relationship.Type == RelationshipType.CHILD) { foreach (var id in relationship.Ids) { Words.Add(new Word(blocks?.Find(b => b.BlockType == BlockType.WORD && b.Id == id) ?? new Block())); } } } } }
/// <summary> /// Create new sample data and into the list /// </summary> /// <param name="sampleData"></param> public void CreateSample(Sample sampleData) { try { var sampleInList = sampleList?.Find(x => x.Id == sampleData.Id); if (sampleInList == null) { sampleList.Add(sampleData); } } catch (Exception ex) { // Here we need log the error properly throw ex; } }
//public async static Task<string> ReadAllTextAsync(this string fileName, IFolder rootFolder = null) //{ //string content = ""; //IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage; ////bool exist = await file.IsFileExistAsync(folder); ////if(exist == true) //{ // IFile file = await folder.GetFileAsync(fileName); // content = await file.ReadAllTextAsync(); //} //return content; //} public async void OnMoveToMyLocation(Position userPosition) { //await _connection.CreateTableAsync<Location>(); await InitDB(); serializedLocations = await PCLHelper.ReadAllTextAsync(filename, null); savedLocations = JsonConvert.DeserializeObject <List <Location> >(serializedLocations); //var locations = await _connection.Table<Location>().ToListAsync(); //savedLocations = new List<Location>(locations); activeLocation = savedLocations?.Find(a => a.Name == "praha"); if (activeLocation == null) { System.Diagnostics.Debug.Write("@@@@@ creating praha"); activeLocation = new Location("praha", userPosition); //await _connection.InsertAsync(activeLocation); savedLocations = new List <Location> { activeLocation }; serializedLocations = JsonConvert.SerializeObject(savedLocations); await PCLHelper.WriteTextAllAsync(filename, serializedLocations); //customMap.GridCenter = userPosition; } DebugPosition = userPosition; LogPosition(userPosition); GridStepSize = MIN_GRID_STEP_SIZE; //set => it invokes DrawGrid }
/// <summary> /// This method checks if the role scopes for a specific role match the ones in the seed. If they don't they are added /// to a list and being returned. /// </summary> /// <param name="seededRoleScope"></param> /// <param name="roleScopeInDb"></param> /// <returns></returns> public static List <RoleScope> FindRoleScopesNotInDb(List <RoleScope> seededRoleScope, List <RoleScope> roleScopeInDb) { return(seededRoleScope .Where(entityInSeed => roleScopeInDb?.Find(e => e.Scope == entityInSeed.Scope) == null) .ToList()); }
/// <summary> /// 获取表名和字段 /// </summary> /// <returns></returns> public async Task <Dictionary <string, List <TABLES_COLUMNS> > > GetTableNameAndFields() { var _TableNames = (await this.GetAllTable()).ToList(); var dic = new Dictionary <string, List <TABLES_COLUMNS> >(); var _TableAll = DbTable.GetAll(); for (int i = 0; i < _TableNames.Count; i++) { var item = _TableNames[i]; var _Cols = (await this.GetColsByTableName(item)); List <FieldDescribe> _FieldDescribeList = new List <FieldDescribe>(); if (_TableAll.ContainsKey(item)) { _FieldDescribeList = _TableAll[item]; } foreach (var _Col in _Cols) { var _FieldDescribe = _FieldDescribeList?.Find(w => w.Name == _Col.COLUMN_NAME); if (_FieldDescribe != null) { _Col.Alias = _FieldDescribe.DisplayName; } } dic[item] = _Cols; } return(dic); }
/// <summary> /// <c>SetField</c> /// Sets the value associated with the tag with consideration for truncation /// </summary> /// <param name="fieldSet"></param> /// <param name="val"></param> /// <param name="tag"></param> /// <param name="overrideTruncate"></param> /// <returns></returns> protected bool SetField(List <Field> fieldSet, string val, string tag, bool overrideTruncate = false) { if (string.IsNullOrEmpty(val) || string.IsNullOrEmpty(tag)) { return(false); } var vlen = val.Length; var tlen = tag.Length; try { var logData = string.Empty; if (fieldSet == null || string.IsNullOrEmpty(val) || string.IsNullOrEmpty(tag)) { EventLogger.Warn($"Null value in SetField: tag = {tag ?? "tag"}"); return(false); } var f = fieldSet?.Find(x => x.TagName.ToLower().Contains(tag.ToLower())); if (f == null) { throw new Exception($"{tag} does not exist"); //fieldSet.Add(new Field(tag, val, -1, false, 'n', false, true)); //return false; // Field doesn't exist } if (!string.IsNullOrEmpty(val) && val.Length > f.MaxLen) { if (AutoTruncate && overrideTruncate) { logData = $"Field Overflow at: <{tag}>, Data: {val}. Maxlen = {f.MaxLen} but got: {val.Length}"; EventLogger.Error(logData); throw new Exception(logData); } logData = $"Autotruncated Overflowed Field at: <{tag}>, Data: {val}. Maxlen = {f.MaxLen} but got: {val.Length}"; EventLogger.Warn(logData); if (val.Length >= f.MaxLen) { val = val?.Substring(0, f.MaxLen); } } f.TagData = string.IsNullOrEmpty(val) ? string.Empty : val; IsEmpty = false; return(true); } catch (Exception ex) { EventLogger.Error($"SetField: {ex.Message}, vlen = {vlen} tlen = {tlen}"); return(false); } }
public static ServerConfigInfo Get(int ID) { if (ID == 0) { return(defaultServer); } return(m_servers?.Find(s => s.ID == ID)); }
/// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> protected override bool HasTables() { var count = _SHOWDATABASEs? .Find(db => db.name == _connection.DbConnection.Database) ?.ntables; return(count.HasValue && count != 0); }
private async Task <IResult> ParseArgument(SlashCommandParameterInfo parameterInfo, IInteractionContext context, List <IApplicationCommandInteractionDataOption> argList, IServiceProvider services) { if (parameterInfo.IsComplexParameter) { var ctorArgs = new object[parameterInfo.ComplexParameterFields.Count]; for (var i = 0; i < ctorArgs.Length; i++) { var result = await ParseArgument(parameterInfo.ComplexParameterFields.ElementAt(i), context, argList, services).ConfigureAwait(false); if (!result.IsSuccess) { return(result); } if (result is ParseResult parseResult) { ctorArgs[i] = parseResult.Value; } else { return(ExecuteResult.FromError(InteractionCommandError.BadArgs, "Complex command parsing failed for an unknown reason.")); } } return(ParseResult.FromSuccess(parameterInfo._complexParameterInitializer(ctorArgs))); } else { var arg = argList?.Find(x => string.Equals(x.Name, parameterInfo.Name, StringComparison.OrdinalIgnoreCase)); if (arg == default) { if (parameterInfo.IsRequired) { return(ExecuteResult.FromError(InteractionCommandError.BadArgs, "Command was invoked with too few parameters")); } else { return(ParseResult.FromSuccess(parameterInfo.DefaultValue)); } } else { var typeConverter = parameterInfo.TypeConverter; var readResult = await typeConverter.ReadAsync(context, arg, services).ConfigureAwait(false); if (!readResult.IsSuccess) { return(readResult); } return(ParseResult.FromSuccess(readResult.Value)); } } }
public string OpenAccount(string name, AccountType accountType, IAccountNumberCreator creator) { Account account = null; string accountNumber = creator.Create(); Account accountInList = accounts?.Find(a => a.AccountNumber == accountNumber); while (accountInList != null) { accountNumber = creator.Create(); accountInList = accounts?.Find(a => a.AccountNumber == accountNumber); } switch (accountType) { case AccountType.Base: account = new BaseAccount(accountNumber, name); break; case AccountType.Gold: account = new GoldAccount(accountNumber, name); break; case AccountType.Platinum: account = new PlatinumAccount(accountNumber, name); break; } if (accounts == null) { return(accountNumber); } accounts.Add(account); repository.Save(accounts); return(accountNumber); }
void AddListSand(ListSendData ls) { var ll = listSands?.Find(l => l?.CommandData.Str == ls.CommandData.Str); if (ll == null) { listSands.Add(ls); } }
private static void NullSafeSetTo(this List <NameValueElement> list, string name, Action <int> setter) { var value = list?.Find(c => c.Name.ToLower() == name.ToLower())?.Value; if (value != null) { setter(Convert.ToInt32(value)); } }
/// <summary> /// 获取配置信息 /// </summary> /// <param name="id">配置id</param> /// <returns></returns> public static ConnectionConfig GetConnectionConfig(string id) { AssertUtil.IsNullOrEmpty("指定的参数 {0} 为空或null。", id); List <ConnectionConfig> configs = GetAllConnectionConfig(); ConnectionConfig config = configs?.Find(p => p.Id.Equals(id)); return(config); }