public static string FindPositionPart(IList<string> parts, int cursorPosition, out int foundPartsIndex, out int cursorInPartPosition) { cursorInPartPosition = 0; var partsComplete = parts.Aggregate(String.Empty, (aggr, s) => aggr + s); for (int i = 0; i < parts.Count(); i++) { var partsLower = parts.Take(i).Aggregate(String.Empty, (aggr, s) => aggr + s); var partsUpper = parts.Take(i + 1).Aggregate(String.Empty, (aggr, s) => aggr + s); var b = partsLower.Length; var t = partsUpper.Length; if ((cursorPosition >= b && cursorPosition < t) || partsUpper == partsComplete) { if (parts[i] == WorkDayParser.itemSeparator.ToString() || parts[i] == WorkDayParser.hourProjectInfoSeparator.ToString()) { // cursor left of separator foundPartsIndex = i - 1; var prevPart = parts.ElementAt(foundPartsIndex); // find out where in the found part the cursor is, need to use prevpart an its length cursorInPartPosition = prevPart.Length; return prevPart; } else { // find out where in the found part the cursor is cursorInPartPosition = cursorPosition - b; foundPartsIndex = i; return parts.ElementAt(i); } } } // not found foundPartsIndex = -1; return String.Empty; }
protected void BindQuestion() { queslist = CY.CSTS.Core.Business.Question.GetSqlWhere("[IsHomePage]=1"); unsolvequestion = new List<CY.CSTS.Core.Business.Question>(); for (int i = 0; i <= queslist.Count - 1; i++) { if (!isanswer(queslist.ElementAt(i).Id)) { unsolvequestion.Add(queslist.ElementAt(i)); } } for (int i = queslist.Count - 1; i >= 0; i--) { if (!isanswer(queslist.ElementAt(i).Id)) { queslist.RemoveAt(i); } } if (queslist.Count >= 4) { for (int i = queslist.Count - 1; i >= 4; i--) { queslist.RemoveAt(i); } } for (int i = 0, j = queslist.Count; i < j; i++) { //queslist[i].Title = CY.Utility.Common.StringUtility.CutString(queslist[i].Title, 80, "..."); } //Questionlist.DataSource = queslist; //Questionlist.DataBind(); if (unsolvequestion.Count >= 4) { for (int i = unsolvequestion.Count - 1; i >= 4; i--) { unsolvequestion.RemoveAt(i); } } for (int i = 0, j = unsolvequestion.Count; i < j; i++) { //unsolvequestion[i].Title = CY.Utility.Common.StringUtility.CutString(unsolvequestion[i].Title, 80, "..."); } }
public void bindunsolveques(IList<CY.CSTS.Core.Business.Question> list, int pagenum) { IList<CY.CSTS.Core.Business.Question> unsovlelist = new List<CY.CSTS.Core.Business.Question>(); for (int i = 0; i <= list.Count-1; i++) { bool isnum = getanswernum(list.ElementAt(i).Id); if (!isnum) { unsovlelist.Add(list.ElementAt(i)); } } PagedDataSource ps2 = new PagedDataSource(); ps2.DataSource = unsovlelist; ps2.AllowPaging = true; ps2.PageSize = 10; TotalPage2.Text = ps2.PageCount.ToString(); ShowPage2.Text = pagenum.ToString(); ps2.CurrentPageIndex = pagenum - 1; Pageup2.Enabled = true; Pagedown2.Enabled = true; if ((pagenum - 1) == 0) { this.Pageup2.Enabled = false; } if (pagenum == ps2.PageCount) { this.Pagedown2.Enabled = false; } Unsolvelist.DataSource = ps2; Unsolvelist.DataBind(); }
protected void bindbooklist() { booklist = CY.GFive.Core.Business.BookSchedule.GetAll(); if (booklist != null) { for (int i = booklist.Count-1; i>=0; i--) { if (booklist.ElementAt(i).Result == 2) { unarrivebook.Add(booklist.ElementAt(i)); if (booklist.ElementAt(i).Days <= 5) { warninglist.Add(booklist.ElementAt(i)); } booklist.RemoveAt(i); } } } WarnList.DataSource=warninglist; WarnList.DataBind(); UnarrivBookList.DataSource = unarrivebook; UnarrivBookList.DataBind(); ArrivBooklist.DataSource = booklist; ArrivBooklist.DataBind(); }
public void bindquestion(IList<CY.CSTS.Core.Business.Question> list ,int pagenum) { for (int i = list.Count - 1; i >= 0; i--) { bool isnum = getanswernum(list.ElementAt(i).Id); if (!isnum) { list.RemoveAt(i); } } PagedDataSource ps = new PagedDataSource(); ps.DataSource =list; ps.AllowPaging = true; ps.PageSize = 10; TotalPage.Text = ps.PageCount.ToString(); ShowPage.Text = pagenum.ToString(); ps.CurrentPageIndex = pagenum-1; Pageup.Enabled = true; Pagedown.Enabled = true; if ((pagenum-1) == 0) { this.Pageup.Enabled = false; } if (pagenum == ps.PageCount) { this.Pagedown.Enabled = false; } QuesList.DataSource = ps; QuesList.DataBind(); }
/// <summary> /// 删除一条食物 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void LinkButton1_Click(object sender, EventArgs e) { //获取要删除的食物的索引 LinkButton lbton = (LinkButton)sender; DataListItem gvr = (DataListItem)lbton.Parent; int foodindex = gvr.ItemIndex; OrderFoodControl ofc = new OrderFoodControl(); OrderControl oc = new OrderControl(); foodlist = oc.GetProductCarFoodList(userid); fooditemlist = oc.GetFoodItemByOrderFoodList(foodlist); int foodid = fooditemlist.ElementAt(foodindex).FoodId; int orderid = fooditemlist.ElementAt(foodindex).OrderId; Session["OrderId"] = orderid; //删除订单食物,如果订单里面没有食物了,就删除这个订单 ofc.DeleteOrderFood(orderid, foodid); if(1 == foodlist.Count) { OrderData _order = new OrderData(); _order.DeleteOrder(_order.GetOrderById(orderid)); } Response.Write("<script language=javascript>window.location.href=window.location.href;</script>"); }
/// <summary> /// Metodo que ejecuta la accion de Selección de tipo de Consulta /// </summary> public void BotonSeleccionTipo() { #region SolicitudServicios if (_vista.opcion.SelectedIndex == 0) // Seleccion Cedula { } if (_vista.opcion.SelectedIndex == 1)// Seleccion Nombre { } if (_vista.opcion.SelectedIndex == 2)// Seleccion Cargo { cargo = BuscarCargos(); for (int i = 0; i < cargo.Count; i++) { _vista.drowListaCargo.Items.Add(cargo.ElementAt(i)); } _vista.drowListaCargo.DataBind(); } #endregion }
public void BuscaRol() { try { string anio = _vista.SeleccionAnio.Text; string ConstFechaI = "01/01/" + anio; string ConstFechaF = "31/12/" + anio; DateTime FechaI = Convert.ToDateTime(ConstFechaI); DateTime FechaF = Convert.ToDateTime(ConstFechaF); empleado = BuscarRoles(FechaI, FechaF); int i = 0; for ( i = 0; i < empleado.Count; i++ ) { _vista.SeleccionRol.Items.Add( empleado.ElementAt(i) ); } _vista.SeleccionRol.DataBind(); _vista.SeleccionRol.Visible = true; } catch (WebException e) { //EXCECION WEB } }
public IBee GetRandomBee(IList<IBee> hive) { var random = new Random((int)DateTime.Now.Ticks & 0x0000FFFF); var randomBee = random.Next(0, hive.Count()); return hive.ElementAt(randomBee); }
private static PuzzleName FindPuzzleNameByKey(IList<PuzzleName> puzzleNames, int position) { // Lookup the correct PuzzleName by its position as calculated // in the BuildPuzzleNames(...) method. //TODO: remove this code and add your implementation here return puzzleNames.ElementAt(position); }
public DeckDealer(List<string>[] players, IList<string> deck, int handOut) { if (players == null || deck == null) throw new Exception("One of arguments is null"); if (handOut<1 || handOut> deck.Count/ players.GetLength(0)) throw new Exception("Wrong number of cards to handout"); foreach (var variable in players) { for (var i = 0; i < handOut; i++) { var tmpCard = deck.ElementAt(0); Console.WriteLine("Card taken form deck "+tmpCard); deck.RemoveAt(0); Console.WriteLine("Next card should be "+deck.ElementAt(0)); variable.Add(tmpCard); } } _tabLists = players; }
public void LlenarLista( bool o ) { List<string> ListaRecibida = new List<string>(); if ( o == true ) // SE SELECCIONO PROPUESTA SE PROCEDE A ELIMINAR { try { ListaRecibida.Add(_vista.ListaPropuesta.SelectedItem.Text); Core.LogicaNegocio.Comandos.ComandoPropuesta.Eliminar comando; comando = FabricaComandosPropuesta.CrearComandoEliminar(ListaPropuesta); ListaPropuesta = comando.Ejecutar(ListaRecibida); int i = 0; for (i = 0; i < ListaPropuesta.Count; i++) { _vista.ListaPropuesta.Items.Add(ListaPropuesta.ElementAt(i)); } _vista.ListaPropuesta.DataBind(); _vista.ListaPropuesta.Visible = false; _vista.LabelEliminarCompletado.Text = _vista.ListaPropuesta.SelectedItem.Text + " ELIMINADO"; _vista.LabelEliminarCompletado.Visible = true; } catch (WebException e) { //Excepcipon WEB } catch (NullReferenceException e) { } } else { try { Core.LogicaNegocio.Comandos.ComandoPropuesta.Eliminar comando; comando = FabricaComandosPropuesta.CrearComandoEliminar( ListaPropuesta ); ListaPropuesta = comando.Ejecutar( ListaRecibida ); int i = 0; for ( i = 0; i < ListaPropuesta.Count; i++ ) { _vista.ListaPropuesta.Items.Add( ListaPropuesta.ElementAt(i) ); } _vista.ListaPropuesta.DataBind(); _vista.ListaPropuesta.Visible = true; } catch { } } }
private void cargargrilla(IList<HorarioDetalle> listaDet) { dgDetalle.Rows.Clear(); for (int i = 0; i < listaDet.Count; i++) { HorarioDetalle horarioDet = listaDet.ElementAt<HorarioDetalle>(i); dgDetalle.Rows.Add(horarioDet.Dia.Descripcion, horarioDet.HoraDesde.ToShortTimeString(), horarioDet.HoraHasta.ToShortTimeString(), horarioDet.Frecuencia, horarioDet.Id); } dgDetalle.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; }
public DeckShuffler(IList<string> scards) { for (var i = 0; i < 52; i++) { if (scards == null) throw new Exception("Shuffled deck is null"); var index = _random.Next(0, scards.Count - 1); var tmpCard = scards.ElementAt(index); _tmpList.Add(tmpCard); scards.RemoveAt(index); } }
private static void MostrarAlumnos(IList <Alumno> alumnos) { Alumno al = null; Console.WriteLine("*******************"); Console.WriteLine("* Lista Alumnos *"); Console.WriteLine("*******************"); for (int i = 0; i < alumnos.Count; i++) { al=alumnos.ElementAt(i); Console.WriteLine(i+" "+al.Nombre+" "+al.Apellido); } }
/// <summary> /// Constructeur privé afin d'éviter la création de plusieurs objets (Singleton). /// </summary> private DalManager() { // Création artistes _artistes = new List<Artiste>(); _artistes.Add(new Artiste(0, new DateTime(1999, 12, 25), "Man", "Iron")); _artistes.Add(new Artiste(1, new DateTime(1998, 7, 6), "Zidane", "Zinedine")); _artistes.Add(new Artiste(2, new DateTime(1920, 2, 2), "Wayne", "Bruce")); _artistes.Add(new Artiste(3, new DateTime(1945, 6, 14), "Parker", "Peter")); _artistes.Add(new Artiste(4, new DateTime(1982, 3, 12), "Abar", "Ben")); _artistes.Add(new Artiste(5, new DateTime(1958, 11, 24), "Chabat", "Alain")); _artistes.Add(new Artiste(6, new DateTime(1957, 3, 23), "Lauby", "Chantal")); // Création evenements _events = new List<Evenement>(); IList<Artiste> artistesTmp = ((List<Artiste>)_artistes).GetRange(0, 4); _events.Add(new Exposition(artistesTmp, "La ligues des justiciers", 0, 8.50f, "The avengers", 50)); _events.Add(new Exposition(artistesTmp, "Le retour des supers héros", 1, 8.50f, "Le retour des supers héros", 50)); _events.Add(new Exposition(artistesTmp, "La suite du film \"Le retour des supers héros\"", 2, 8.50f, "Le re-retour des supers héros", 50)); artistesTmp = ((List<Artiste>)_artistes).GetRange(4, 1); _events.Add(new Concert(artistesTmp, "Concert de Benabar", 3, 1.5f, "Benabar", false, 200, 10)); artistesTmp = ((List<Artiste>)_artistes).GetRange(5, 2); _events.Add(new Exposition(artistesTmp, "La cité de la peur, le retour.", 4, 16f, "La cité de la peur 2", 20)); // Création des lieux _lieux = new List<Lieu>(); _lieux.Add(new Lieu(0, "Liberty Island", "53000", "Statue de liberté", 50, "USA", 22f, "06 06 06 06 06", "New York city")); _lieux.Add(new Lieu(1, "à droite du champs", "26823", "Prairie", 2, "France", 0f, "06 06 06 06 06", "Rochefourchat ")); _lieux.Add(new Lieu(2, "3 rue du capitole", "75005", "Boucherie", 200, "France", 12.5f, "06 06 06 06 06", "Paris")); // Création des PlanningElements _pe = new List<PlanningElement>(); _pe.Add(new PlanningElement(new DateTime(2012, 12, 21, 0, 0, 0), new DateTime(2012, 12, 21, 23, 59, 59), 0, _events.ElementAt(0),_lieux.ElementAt(0),0)); _pe.Add(new PlanningElement(new DateTime(2013, 1, 21, 0, 0, 0), new DateTime(2013, 1, 21, 23, 59, 59), 0, _events.ElementAt(1), _lieux.ElementAt(0), 0)); _pe.Add(new PlanningElement(new DateTime(2013, 2, 21, 0, 0, 0), new DateTime(2013, 2, 21, 23, 59, 59), 0, _events.ElementAt(2), _lieux.ElementAt(0), 0)); _pe.Add(new PlanningElement(new DateTime(2013, 1, 15, 21, 0, 0), new DateTime(2013, 1, 15, 23, 30, 0), 1, _events.ElementAt(3), _lieux.ElementAt(1), 0)); _pe.Add(new PlanningElement(new DateTime(2013, 2, 3, 21, 0, 0), new DateTime(2013, 2, 3, 23, 30, 0), 2, _events.ElementAt(4), _lieux.ElementAt(2), 0)); }
private CoreDataSet GetDataByOffset(IList<CoreDataSet> dataList) { int maximumIndex = dataList.Count() - 1; if (maximumIndex < dataPointOffset) { // Run out of data return null; } return dataList.ElementAt(maximumIndex - dataPointOffset); }
public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode) { var stream = _streams?.ElementAt((int)index); if (askExtractMode != AskMode.Extract || stream == null) { outStream = null; return(0); } outStream = new OutStreamWrapper(stream, true); return(0); }
public void BuscarPropuesta() { _presentadorPropuesta = new ConsultarPropuestaPresentador(); int i = 0; int estado = 1; propuestas = _presentadorPropuesta.BuscarPorTitulo(estado); for (i = 0; i < propuestas.Count; i++) { _vista.PropuestaAsociada.Items.Add(propuestas.ElementAt(i).Titulo); } }
public static IList<Car.Part> GetStorehouseParts(string xmlResource, IList<Car> cars) { XElement xml = XElement.Parse(xmlResource); IList<Car.Part> parts = ( from e in xml.Elements("Parts").Elements("Part") select new Car.Part ( cars.ElementAt(Int32.Parse(e.Attribute("car").Value) - 1). Parts.ElementAt(Int32.Parse(e.Attribute("part").Value) - 1) ) ).ToList(); return parts; }
public static bool ActionsAreEquals(this IList<DeploymentActionResource> dpar1, IList<DeploymentActionResource> dpar2) { if (dpar1 == null || dpar2 == null || dpar1.Count != dpar2.Count) { return false; } for (var i = 0; i < dpar1.Count; i++) { if (!dpar1.ElementAt(i).ActionsAreEquals(dpar2.ElementAt(i))) { return false; } } return true; }
public Quote AddQuote(Quote newQuote, IList<int> zanyIds, int userId, IList<byte[]> files) { Quote quote = context.Quotes.Create(); quote.AddedOn = newQuote.AddedOn; quote.Description = newQuote.Description; quote.GameId = newQuote.GameId; quote.QuoteText = newQuote.QuoteText; quote.UpdatedById = newQuote.UpdatedById; quote.UpdatedOn = newQuote.AddedOn; // updated and added dates are the same for creation quote.Zanies = zanyRepo.GetZanies(zanyIds); if (files != null && files.Count > 0) { Game quoteGame = gameRepo.GetGame(quote.GameId); if (quoteGame != null) { newQuote.MediaItems = new List<MediaItem>(); // add media items for(int i=0; i < files.Count; i++) { quote.MediaItems.Add( mediaRepo.AddMediaItem( files.ElementAt(i) , this.CreateQuoteMediaFileName( newQuote.Description , newQuote.GameId , ".png" , i.ToString()) , quoteGame.ShortName)); } } } context.Quotes.Add(quote); context.SaveChanges(); return quote; }
public void BuscaCargo() { try { cargo = BuscarCargos(); int i = 0; for (i = 0; i < cargo.Count; i++) { _vista.SeleccionCargo.Items.Add(cargo.ElementAt(i)); } _vista.SeleccionCargo.DataBind(); _vista.SeleccionCargo.Visible = true; } catch (WebException e) { //EXCECION WEB } }
protected void FoodNum_TextChanged(object sender, EventArgs e) { //获取修改了的TextBox的FoodItem项的索引 TextBox tb = (TextBox)sender; if (tb.Text == "0") { Page.Response.Write("<script>alert('食物数量不能为0!您可以选择删除该食物。')</script>"); Response.Write("<script language=javascript>window.location.href=window.location.href;</script>"); return; } DataListItem gvr = (DataListItem)tb.Parent; int foodindex = gvr.ItemIndex; //调用逻辑层修改食物数量 int userid = Convert.ToInt32(Session["UserId"]); OrderFoodControl ofc = new OrderFoodControl(); OrderControl oc = new OrderControl(); foodlist = oc.GetProductCarFoodList(userid); fooditemlist = oc.GetFoodItemByOrderFoodList(foodlist); int foodid = fooditemlist.ElementAt(foodindex).FoodId; int foodnum = Convert.ToInt32(tb.Text.ToString()); ofc.ModifyFoodNum(userid, foodid, foodnum); Response.Write("<script language=javascript>window.location.href=window.location.href;</script>"); }
public void BotonSeleccionTipo() { if (_vista.opcion.SelectedIndex == 0) { _vista.opcion.Visible = false; _vista.LabelTipoC.Visible = false; _vista.SeleccionOpcion.Visible = true; _vista.LabelSelec.Visible = true; } if (_vista.opcion.SelectedIndex == 1) { _vista.opcion.Visible = false; _vista.SeleccionOpcion.Visible = true; } #region SolicitudServicios if (_vista.opcion.SelectedIndex == 0) // PROPUESTAS EN ESPERA { int i = 0; propuesta = BuscarPropuestasEnEspera(); for (i = 0; i < propuesta.Count; i++) { _vista.SeleccionOpcion.Items.Add(propuesta.ElementAt(i).Titulo); } _vista.SeleccionOpcion.DataBind(); } }
private IList<State> Solve(IList<State> states) { var ic = IntegrationConstants(); var effectiveK = Inputs.K + ic[0] * Inputs.M + ic[1] * Inputs.C; for (double t = Inputs.T0; t < Inputs.Tk; t += Inputs.DeltaT) { var ancientState = states.ElementAt(states.Count - 2); var lastState = states.Last(); var effectiveR = Inputs.R.ToVector(t + Inputs.DeltaT) + Inputs.M * (ic[2] * lastState.NextStateMovementU + ic[4] * lastState.MovementU + ic[6] * ancientState.MovementU) + Inputs.C * (ic[3] * lastState.NextStateMovementU + ic[5] * lastState.MovementU + ic[1] * ancientState.MovementU); var nextMovementU = effectiveR * effectiveK.Inverse(); var nextSpeed = ic[1] * nextMovementU - ic[3] * lastState.NextStateMovementU - ic[5] * lastState.MovementU - ic[7] * ancientState.MovementU; var nextAcceleration = ic[0] * nextMovementU - ic[2] * lastState.NextStateMovementU - ic[4] * lastState.MovementU - ic[6] * ancientState.MovementU; states.Add(new State(t, effectiveR, lastState.NextStateMovementU, nextSpeed, nextAcceleration, nextMovementU)); } return states; }
private double getTeamPoints(IList<Game> homeTeamLatestGames, int teamId, int gamesCount) { double points = 0; for (int i = 0; i < gamesCount; i++) { Game game = homeTeamLatestGames.ElementAt(i); string result = game.result; string[] goals = result.Split(':'); int homeTeamGoals = int.Parse(goals[0]); int awayTeamGoals = int.Parse(goals[1]); if (game.homeTeam.Id == teamId) { if (homeTeamGoals > awayTeamGoals) { points += 3; } } else { if (awayTeamGoals > homeTeamGoals) { points += 3; } } if (homeTeamGoals == awayTeamGoals) { points += 1; } } return points; }
/// <summary> /// iterates a list of commercials and reorders commercials in /// such way that no commercials of the same type are placed next to each other within a brake /// </summary> /// <param name="commercials"></param> private void OrderCommercials(IList <Commercial> commercials) { var rep = commercials.FirstOrDefault(p => commercials.IndexOf(p) + 1 < commercials.Count && p.CommercialType == commercials.ElementAt(commercials.IndexOf(p) + 1).CommercialType); if (rep == null) { return; } var nonRep = commercials.FirstOrDefault(p => p.CommercialType != rep.CommercialType && commercials.IndexOf(p) + 1 == commercials.Count); if (nonRep != null) { var tmp = rep; commercials.Remove(rep); commercials.Add(tmp); OrderCommercials(commercials); return; } nonRep = commercials.FirstOrDefault(p => p.CommercialType != rep.CommercialType && commercials.IndexOf(p) + 1 < commercials.Count && rep.CommercialType != commercials.ElementAt(commercials.IndexOf(p) + 1).CommercialType); if (nonRep != null) { var tmp = rep; commercials.Remove(rep); commercials.Insert(commercials.IndexOf(nonRep) + 1, tmp); OrderCommercials(commercials); return; } nonRep = commercials.FirstOrDefault(p => p.CommercialType != rep.CommercialType && commercials.IndexOf(p) == 0); if (nonRep != null) { var tmp = rep; commercials.Remove(rep); commercials.Insert(0, tmp); OrderCommercials(commercials); return; } nonRep = commercials.FirstOrDefault(p => p.CommercialType != rep.CommercialType && commercials.IndexOf(p) - 1 >= 0 && rep.CommercialType != commercials.ElementAt(commercials.IndexOf(p) - 1).CommercialType); if (nonRep != null) { var tmp = rep; commercials.Remove(rep); commercials.Insert(commercials.IndexOf(nonRep), tmp); OrderCommercials(commercials); } }
private bool setProveedores(String email) { try { if (new EmailAddressAttribute().IsValid(email)) { var proveedorList = _objeto._proveedores.getTProveedores(email).ToList(); if (0 < proveedorList.Count) { inputModel = proveedorList.ElementAt(0); tProveedores = new TProveedores { ID = inputModel.ID, Proveedor = inputModel.Proveedor, Telefono = inputModel.Telefono, Email = inputModel.Email, Direccion = inputModel.Direccion, }; proveedoresReport = _objeto._context.TReportes_proveedores.Where(r => r.TProveedores.Equals(tProveedores)).ToList(); if (0 < proveedoresReport.Count) { proveedore_Report = proveedoresReport.ElementAt(0); Input = new InputModel { Proveedor = inputModel.Proveedor, Email = email, ProveedoresReport = proveedoresReport, }; } else { Input = new InputModel { Proveedor = inputModel.Proveedor, Email = idGet, ErrorMessage = "El proveedor " + inputModel.Proveedor + " no contiene repoprtes", ProveedoresReport = new List <TReportes_proveedores>() }; } return(true); } else { return(false); } } else { return(false); } } catch (Exception ex) { Input = new InputModel { Proveedor = inputModel.Proveedor, Email = idGet, ErrorMessage = ex.Message, ProveedoresReport = new List <TReportes_proveedores>() }; return(true); } }
public IList <User_Driving_Events> CheckAgressiveTurning_And_LaneChange(IList <User_Driving_Data> Datalist) { var frequency = Datalist.FirstOrDefault().Frequency; var listSize = Datalist.Count(); var RemainderOfList = listSize % frequency; var DatachuckSize = listSize - RemainderOfList; IList <User_Driving_Data> DataChunkList = new List <User_Driving_Data>(); IList <User_Driving_Events> AggressiveTurning_EventsList = new List <User_Driving_Events>(); IList <User_Driving_Events> LaneChange_EventsList = new List <User_Driving_Events>(); IList <User_Driving_Events> Events = new List <User_Driving_Events>(); double AgressiveTurningEventCount = 0; //double LaneChangeEventCount = 0; //LaneChange lanechange = new LaneChange(); for (int i = 0; i < DatachuckSize; i = i + frequency) { for (int j = i; j < i + frequency; j++) { DataChunkList.Add(Datalist.ElementAt(j)); } var FirstEntry = DataChunkList.First(); var LastEntry = DataChunkList.Last(); var Heading = TurningAngle(FirstEntry, LastEntry); if (Heading > 30) { //Create aggresive turning event AgressiveTurningEventCount++; User_Driving_Events events = new User_Driving_Events(); events.Session_Id = FirstEntry.Session_Id; events.Event_Type_Id = Convert.ToInt32(EventType.Agressive_Turning); events.Event_Time = FirstEntry.TimeStamp; Events.Add(events); } else if (Heading > 0 & Heading < 20) { var laneChangeAlgo = new LaneChange(); var laneChangeEvents = laneChangeAlgo.CheckLaneChange(DataChunkList); foreach (var e in laneChangeEvents) { Events.Add(e); } } FirstEntry = null; LastEntry = null; DataChunkList.Clear(); } if (RemainderOfList != 0) { for (var i = DatachuckSize; i < listSize; i++) { DataChunkList.Add(Datalist.ElementAt(i)); } var FirstEntry = DataChunkList.First(); var LastEntry = DataChunkList.Last(); var Heading = TurningAngle(FirstEntry, LastEntry); if (Heading >= 30) { //Create aggresive turning event AgressiveTurningEventCount++; AgressiveTurningEventCount++; User_Driving_Events events = new User_Driving_Events(); events.Session_Id = FirstEntry.Session_Id; events.Event_Type_Id = Convert.ToInt32(EventType.Agressive_Turning); events.Event_Time = FirstEntry.TimeStamp; Events.Add(events); } else if (Heading > 0 & Heading < 20) { var laneChangeAlgo = new LaneChange(); var laneChangeEvents = laneChangeAlgo.CheckLaneChange(DataChunkList); foreach (var e in laneChangeEvents) { Events.Add(e); } } FirstEntry = null; LastEntry = null; DataChunkList.Clear(); } return(Events); }
static void ElementAt(IList <int> intList) { Console.WriteLine("1.eleman: {0}", intList.ElementAt(0)); //intList.ElementAt(9) => index out of range hatası veir Console.WriteLine("10.eleman", intList.ElementAtOrDefault(9)); }
public override void draw(SpriteBatch b, int red = -1, int green = -1, int blue = -1) { for (int i = 0; i < inventory.Count; i++) { if (_iconShakeTimer.ContainsKey(i) && Game1.currentGameTime.TotalGameTime.TotalSeconds >= _iconShakeTimer[i]) { _iconShakeTimer.Remove(i); } } Color tint = ((red == -1) ? Color.White : new Color((int)Utility.Lerp(red, Math.Min(255, red + 150), 0.65f), (int)Utility.Lerp(green, Math.Min(255, green + 150), 0.65f), (int)Utility.Lerp(blue, Math.Min(255, blue + 150), 0.65f))); Texture2D texture = ((red == -1) ? Game1.menuTexture : Game1.uncoloredMenuTexture); if (drawSlots) { for (int l = 0; l < capacity; l++) { Vector2 toDraw2 = new Vector2(xPositionOnScreen + l % (capacity / rows) * 64 + horizontalGap * (l % (capacity / rows)), yPositionOnScreen + l / (capacity / rows) * (64 + verticalGap) + (l / (capacity / rows) - 1) * 4 - ((l < capacity / rows && playerInventory && verticalGap == 0) ? 12 : 0)); b.Draw(texture, toDraw2, Game1.getSourceRectForStandardTileSheet(Game1.menuTexture, 10), tint, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0.5f); if ((playerInventory || showGrayedOutSlots) && l >= (int)Game1.player.maxItems) { b.Draw(texture, toDraw2, Game1.getSourceRectForStandardTileSheet(Game1.menuTexture, 57), tint * 0.5f, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0.5f); } if (l < 12 && playerInventory) { string strToDraw = l switch { 11 => "=", 10 => "-", 9 => "0", _ => string.Concat(l + 1), }; Vector2 strSize = Game1.tinyFont.MeasureString(strToDraw); b.DrawString(Game1.tinyFont, strToDraw, toDraw2 + new Vector2(32f - strSize.X / 2f, 0f - strSize.Y), (l == Game1.player.CurrentToolIndex) ? Color.Red : Color.DimGray); } } for (int k = 0; k < capacity; k++) { Vector2 toDraw3 = new Vector2(xPositionOnScreen + k % (capacity / rows) * 64 + horizontalGap * (k % (capacity / rows)), yPositionOnScreen + k / (capacity / rows) * (64 + verticalGap) + (k / (capacity / rows) - 1) * 4 - ((k < capacity / rows && playerInventory && verticalGap == 0) ? 12 : 0)); if (actualInventory.Count > k && actualInventory.ElementAt(k) != null) { bool highlight2 = highlightMethod(actualInventory[k]); if (_iconShakeTimer.ContainsKey(k)) { toDraw3 += 1f * new Vector2(Game1.random.Next(-1, 2), Game1.random.Next(-1, 2)); } actualInventory[k].drawInMenu(b, toDraw3, (inventory.Count > k) ? inventory[k].scale : 1f, (!highlightMethod(actualInventory[k])) ? 0.25f : 1f, 0.865f, StackDrawType.Draw, Color.White, highlight2); } } return; } for (int j = 0; j < capacity; j++) { Vector2 toDraw = new Vector2(xPositionOnScreen + j % (capacity / rows) * 64 + horizontalGap * (j % (capacity / rows)), yPositionOnScreen + j / (capacity / rows) * (64 + verticalGap) + (j / (capacity / rows) - 1) * 4 - ((j < capacity / rows && playerInventory && verticalGap == 0) ? 12 : 0)); if (actualInventory.Count > j && actualInventory.ElementAt(j) != null) { bool highlight = highlightMethod(actualInventory[j]); if (_iconShakeTimer.ContainsKey(j)) { toDraw += 1f * new Vector2(Game1.random.Next(-1, 2), Game1.random.Next(-1, 2)); } actualInventory[j].drawInMenu(b, toDraw, (inventory.Count > j) ? inventory[j].scale : 1f, (!highlight) ? 0.25f : 1f, 0.865f, StackDrawType.Draw, Color.White, highlight); } } }
public static T GetRandom <T>(this IEnumerable <T> items) { IList <T> list = items.ToList(); return(list.ElementAt(_Random.Next(0, list.Count))); }
public void US_41888_PreventMaliciousFileUpload_StudentResults_InvalidFiles() { PropertiesCollection.test = PropertiesCollection.extent.CreateTest("US_41888_PreventMaliciousFileUpload_StudentResults_InvalidFiles"); var strTestCaseNo = "TC005"; var connection = new ConnectToMySQL_Fetch_TestData(); var testdataStudentResults = connection.Select(strtblname, strTestCaseNo, strTestType); var sidebarMenu = new FpSideMenus(); var studentResults = new FpStudentResultsPage(); var folderLocation = "Malicious Files\\"; sidebarMenu.lnkStudentResults.Click(); string strTDOrgnisationGroup = testdataStudentResults[4]; string strTDStudentName = testdataStudentResults[5]; string strTDInstructorName = testdataStudentResults[6]; string strTDCourseName = testdataStudentResults[7]; string strTDSyllabusName = testdataStudentResults[8]; string strTDEventName = testdataStudentResults[9]; string strTDScore = testdataStudentResults[10]; string strTDScoreAssesmentCriteria = testdataStudentResults[11]; string strTDStrength = testdataStudentResults[12]; string strTDWeakness = testdataStudentResults[13]; string strTDOverallComments = testdataStudentResults[14]; string strTDPrivateComments = testdataStudentResults[15]; string strTDServiceName = testdataStudentResults[16]; string strTDCountryName = testdataStudentResults[17]; string strTDStudentPosition = testdataStudentResults[18]; string strTDStudentSurname = testdataStudentResults[19]; string strTDResultAwarded = testdataStudentResults[20]; studentResults.SearchStudent(strTDStudentSurname); studentResults.SearchCourseEvent(strTDEventName); string style = studentResults.VerifyEventIcon(strTDEventName); if (style.Contains("background-color: rgb(70, 136, 71)") == false) { studentResults.DeleteWriteup(); } WebDriverWait wait = new WebDriverWait(PropertiesCollection.driver, TimeSpan.FromSeconds(10)); Console.WriteLine("The number of rows:" + PropertiesCollection.driver.FindElements(By.XPath("//*[@id=\"documentsGrid\"]/div/div[6]/div/div/div[1]/div/table/tbody/tr/td[1]")).Count); int Count = PropertiesCollection.driver.FindElements(By.XPath("//*[@id=\"documentsGrid\"]/div/div[6]/div/div/div[1]/div/table/tbody/tr/td[1]")).Count; for (int i = 0; i <= Count; i++) { System.Threading.Thread.Sleep(2000); if (PropertiesCollection.driver.FindElements(By.XPath("//*[@id=\"documentsGrid\"]/div/div[6]/div/div/div[1]/div/table/tbody/tr[1]/td[5]/div/dx-button")).Count != 0) { IWebElement btnRemove = PropertiesCollection.driver.FindElement(By.XPath("//*[@id=\"documentsGrid\"]/div/div[6]/div/div/div[1]/div/table/tbody/tr[1]/td[5]/div/dx-button")); btnRemove.Click(); System.Threading.Thread.Sleep(2000); IWebElement btnYesPopup = PropertiesCollection.driver.FindElement(By.XPath("/html/body/div[2]/div/div/div[3]/div/div[2]/div[1]/div/div")); btnYesPopup.Click(); System.Threading.Thread.Sleep(2000); } } int count = 0; foreach (var file in fileList_InvalidFiles) { IWebElement btnAddDocument = wait.Until(ExpectedConditions.ElementToBeClickable(PropertiesCollection.driver.FindElement(By.XPath("//*[@id=\"psr-file-uploader\"]/div/div/div/div[1]/div[1]/div/span")))); btnAddDocument.Click(); System.Threading.Thread.Sleep(2000); AutoIt.AutoItX.ControlFocus("Open", "", "Edit1"); AutoIt.AutoItX.ControlSetText("Open", "", "Edit1", System.Configuration.ConfigurationManager.AppSettings["MaliciousFileUploadLocation"] + folderLocation + file); AutoIt.AutoItX.ControlClick("Open", "", "Button1"); System.Threading.Thread.Sleep(3000); PropertiesCollection.driver.FindElement(By.XPath("//*[@id=\"psr-file-uploader\"]/div/div/div/div[3]/div/div[2]/div/div")).Click(); System.Threading.Thread.Sleep(2000); IList <IWebElement> fileNames = PropertiesCollection.driver.FindElements(By.XPath("//*[@id=\"documentsGrid\"]/div/div[6]/div/div/div[1]/div/table/tbody/tr/td[1]")); System.Threading.Thread.Sleep(3000); if (count <= fileNames.Count) { if (count == 0) { string filename = fileNames.First().Text; System.Threading.Thread.Sleep(2000); try { Assert.AreEqual(file, filename); PropertiesCollection.test.Log(Status.Pass, "File: " + filename + "is successfully uploaded"); } catch { PropertiesCollection.test.Log(Status.Fail, "File: " + filename + "is not successfully uploaded"); } } else { string filename = fileNames.ElementAt(count).Text; try { Assert.AreEqual(file, filename); PropertiesCollection.test.Log(Status.Pass, "File: " + filename + "is successfully uploaded"); } catch { PropertiesCollection.test.Log(Status.Fail, "File: " + filename + "is not successfully uploaded"); } } count = count + 1; } } Console.WriteLine("The number of rows:" + PropertiesCollection.driver.FindElements(By.XPath("//*[@id=\"documentsGrid\"]/div/div[6]/div/div/div[1]/div/table/tbody/tr/td[1]")).Count); Count = PropertiesCollection.driver.FindElements(By.XPath("//*[@id=\"documentsGrid\"]/div/div[6]/div/div/div[1]/div/table/tbody/tr/td[1]")).Count; for (int i = 0; i <= Count; i++) { System.Threading.Thread.Sleep(2000); if (PropertiesCollection.driver.FindElements(By.XPath("//*[@id=\"documentsGrid\"]/div/div[6]/div/div/div[1]/div/table/tbody/tr[1]/td[5]/div/dx-button")).Count != 0) { IWebElement btnRemove = PropertiesCollection.driver.FindElement(By.XPath("//*[@id=\"documentsGrid\"]/div/div[6]/div/div/div[1]/div/table/tbody/tr[1]/td[5]/div/dx-button")); btnRemove.Click(); System.Threading.Thread.Sleep(2000); IWebElement btnYesPopup = PropertiesCollection.driver.FindElement(By.XPath("/html/body/div[2]/div/div/div[3]/div/div[2]/div[1]/div/div")); btnYesPopup.Click(); System.Threading.Thread.Sleep(2000); } } }
public void TestBasicNRT() { Input[] keys = new Input[] { new Input("lend me your ear", 8, new BytesRef("foobar")), }; Analyzer a = new MockAnalyzer(Random(), MockTokenizer.WHITESPACE, false); AnalyzingInfixSuggester suggester = new AnalyzingInfixSuggester(TEST_VERSION_CURRENT, NewDirectory(), a, a, 3); suggester.Build(new InputArrayIterator(keys)); IList <Lookup.LookupResult> results = suggester.DoLookup(TestUtil.StringToCharSequence("ear", Random()).ToString(), 10, true, true); assertEquals(1, results.size()); assertEquals("lend me your <b>ear</b>", results.ElementAt(0).key); assertEquals(8, results.ElementAt(0).value); assertEquals(new BytesRef("foobar"), results.ElementAt(0).payload); // Add a new suggestion: suggester.Add(new BytesRef("a penny saved is a penny earned"), null, 10, new BytesRef("foobaz")); // Must refresh to see any newly added suggestions: suggester.Refresh(); results = suggester.DoLookup(TestUtil.StringToCharSequence("ear", Random()).ToString(), 10, true, true); assertEquals(2, results.size()); assertEquals("a penny saved is a penny <b>ear</b>ned", results.ElementAt(0).key); assertEquals(10, results.ElementAt(0).value); assertEquals(new BytesRef("foobaz"), results.ElementAt(0).payload); assertEquals("lend me your <b>ear</b>", results.ElementAt(1).key); assertEquals(8, results.ElementAt(1).value); assertEquals(new BytesRef("foobar"), results.ElementAt(1).payload); results = suggester.DoLookup(TestUtil.StringToCharSequence("ear ", Random()).ToString(), 10, true, true); assertEquals(1, results.size()); assertEquals("lend me your <b>ear</b>", results.ElementAt(0).key); assertEquals(8, results.ElementAt(0).value); assertEquals(new BytesRef("foobar"), results.ElementAt(0).payload); results = suggester.DoLookup(TestUtil.StringToCharSequence("pen", Random()).ToString(), 10, true, true); assertEquals(1, results.size()); assertEquals("a <b>pen</b>ny saved is a <b>pen</b>ny earned", results.ElementAt(0).key); assertEquals(10, results.ElementAt(0).value); assertEquals(new BytesRef("foobaz"), results.ElementAt(0).payload); results = suggester.DoLookup(TestUtil.StringToCharSequence("p", Random()).ToString(), 10, true, true); assertEquals(1, results.size()); assertEquals("a <b>p</b>enny saved is a <b>p</b>enny earned", results.ElementAt(0).key); assertEquals(10, results.ElementAt(0).value); assertEquals(new BytesRef("foobaz"), results.ElementAt(0).payload); // Change the weight: suggester.Update(new BytesRef("lend me your ear"), null, 12, new BytesRef("foobox")); // Must refresh to see any newly added suggestions: suggester.Refresh(); results = suggester.DoLookup(TestUtil.StringToCharSequence("ear", Random()).ToString(), 10, true, true); assertEquals(2, results.size()); assertEquals("lend me your <b>ear</b>", results.ElementAt(0).key); assertEquals(12, results.ElementAt(0).value); assertEquals(new BytesRef("foobox"), results.ElementAt(0).payload); assertEquals("a penny saved is a penny <b>ear</b>ned", results.ElementAt(1).key); assertEquals(10, results.ElementAt(1).value); assertEquals(new BytesRef("foobaz"), results.ElementAt(1).payload); suggester.Dispose(); }
public void TestRandomNRT() { DirectoryInfo tempDir = CreateTempDir("AnalyzingInfixSuggesterTest"); Analyzer a = new MockAnalyzer(Random(), MockTokenizer.WHITESPACE, false); int minPrefixChars = Random().nextInt(7); if (VERBOSE) { Console.WriteLine(" minPrefixChars=" + minPrefixChars); } AnalyzingInfixSuggester suggester = new AnalyzingInfixSuggester(TEST_VERSION_CURRENT, NewFSDirectory(tempDir), a, a, minPrefixChars); // Initial suggester built with nothing: suggester.Build(new InputArrayIterator(new Input[0])); var stop = new AtomicBoolean(false); Exception[] error = new Exception[] { null }; LookupThread lookupThread = new LookupThread(this, suggester, stop, error); lookupThread.Start(); int iters = AtLeast(1000); int visibleUpto = 0; ISet <long> usedWeights = new HashSet <long>(); ISet <string> usedKeys = new HashSet <string>(); List <Input> inputs = new List <Input>(); List <Update> pendingUpdates = new List <Update>(); for (int iter = 0; iter < iters; iter++) { string text; while (true) { text = RandomText(); if (usedKeys.contains(text) == false) { usedKeys.add(text); break; } } // Carefully pick a weight we never used, to sidestep // tie-break problems: long weight; while (true) { weight = Random().nextInt(10 * iters); if (usedWeights.contains(weight) == false) { usedWeights.add(weight); break; } } if (inputs.size() > 0 && Random().nextInt(4) == 1) { // Update an existing suggestion Update update = new Update(); update.index = Random().nextInt(inputs.size()); update.weight = weight; Input input = inputs.ElementAt(update.index); pendingUpdates.Add(update); if (VERBOSE) { Console.WriteLine("TEST: iter=" + iter + " update input=" + input.term.Utf8ToString() + "/" + weight); } suggester.Update(input.term, null, weight, input.term); } else { // Add a new suggestion inputs.Add(new Input(text, weight, new BytesRef(text))); if (VERBOSE) { Console.WriteLine("TEST: iter=" + iter + " add input=" + text + "/" + weight); } BytesRef br = new BytesRef(text); suggester.Add(br, null, weight, br); } if (Random().nextInt(15) == 7) { if (VERBOSE) { Console.WriteLine("TEST: now refresh suggester"); } suggester.Refresh(); visibleUpto = inputs.size(); foreach (Update update in pendingUpdates) { Input oldInput = inputs.ElementAt(update.index); Input newInput = new Input(oldInput.term, update.weight, oldInput.payload); inputs[update.index] = newInput; } pendingUpdates.Clear(); } if (Random().nextInt(50) == 7) { if (VERBOSE) { Console.WriteLine("TEST: now close/reopen suggester"); } //lookupThread.Finish(); stop.Set(true); lookupThread.Join(); Assert.Null(error[0], "Unexpcted exception at retry : \n" + stackTraceStr(error[0])); suggester.Dispose(); suggester = new AnalyzingInfixSuggester(TEST_VERSION_CURRENT, NewFSDirectory(tempDir), a, a, minPrefixChars); lookupThread = new LookupThread(this, suggester, stop, error); lookupThread.Start(); visibleUpto = inputs.size(); foreach (Update update in pendingUpdates) { Input oldInput = inputs.ElementAt(update.index); Input newInput = new Input(oldInput.term, update.weight, oldInput.payload); inputs[update.index] = newInput; } pendingUpdates.Clear(); } if (visibleUpto > 0) { string query = RandomText(); bool lastPrefix = Random().nextInt(5) != 1; if (lastPrefix == false) { query += " "; } string[] queryTerms = Regex.Split(query, "\\s", RegexOptions.Compiled); bool allTermsRequired = Random().nextInt(10) == 7; bool doHilite = Random().nextBoolean(); if (VERBOSE) { Console.WriteLine("TEST: lookup \"" + query + "\" allTermsRequired=" + allTermsRequired + " doHilite=" + doHilite); } // Stupid slow but hopefully correct matching: List <Input> expected = new List <Input>(); for (int i = 0; i < visibleUpto; i++) { Input input = inputs.ElementAt(i); string[] inputTerms = Regex.Split(input.term.Utf8ToString(), "\\s"); bool match = false; for (int j = 0; j < queryTerms.Length; j++) { if (j < queryTerms.Length - 1 || lastPrefix == false) { // Exact match for (int k = 0; k < inputTerms.Length; k++) { if (inputTerms[k].equals(queryTerms[j])) { match = true; break; } } } else { // Prefix match for (int k = 0; k < inputTerms.Length; k++) { if (inputTerms[k].StartsWith(queryTerms[j], StringComparison.InvariantCulture)) { match = true; break; } } } if (match) { if (allTermsRequired == false) { // At least one query term does match: break; } match = false; } else if (allTermsRequired) { // At least one query term does not match: break; } } if (match) { if (doHilite) { expected.Add(new Input(Hilite(lastPrefix, inputTerms, queryTerms), input.v, input.term)); } else { expected.Add(input); } } } expected.Sort(new TestRandomNRTComparator()); if (expected.Any()) { int topN = TestUtil.NextInt(Random(), 1, expected.size()); IList <Lookup.LookupResult> actual = suggester.DoLookup(TestUtil.StringToCharSequence(query, Random()).ToString(), topN, allTermsRequired, doHilite); int expectedCount = Math.Min(topN, expected.size()); if (VERBOSE) { Console.WriteLine(" expected:"); for (int i = 0; i < expectedCount; i++) { Input x = expected.ElementAt(i); Console.WriteLine(" " + x.term.Utf8ToString() + "/" + x.v); } Console.WriteLine(" actual:"); foreach (Lookup.LookupResult result in actual) { Console.WriteLine(" " + result); } } assertEquals(expectedCount, actual.size()); for (int i = 0; i < expectedCount; i++) { assertEquals(expected.ElementAt(i).term.Utf8ToString(), actual.ElementAt(i).key.toString()); assertEquals(expected.ElementAt(i).v, actual.ElementAt(i).value); assertEquals(expected.ElementAt(i).payload, actual.ElementAt(i).payload); } } else { if (VERBOSE) { Console.WriteLine(" no expected matches"); } } } } //lookupThread.finish(); stop.Set(true); lookupThread.Join(); Assert.Null(error[0], "Unexpcted exception at retry : \n" + stackTraceStr(error[0])); suggester.Dispose(); }
void ButtonSearch_Click(object sender, EventArgs e) { if ((string)LabelStatus.Content == "Status: Initialized") { if (t1 != null && t1.IsAlive) { t1.Abort(); } if (t2 != null && t2.IsAlive) { t2.Abort(); } t2 = new Thread(() => { for (int i = 0; i < co1.Count; i++) { if (Application.Current.Dispatcher.Invoke(() => { return(UserFilter(co1.ElementAt(i))); })) { co1[i].status = "loading"; co1[i].valid = "2"; Application.Current.Dispatcher.Invoke(() => { ListBoxDates.ItemsSource = co1; CollectionViewSource.GetDefaultView(ListBoxDates.ItemsSource).Refresh(); }); co1[i].valid = CheckDate(co1[i].date); Application.Current.Dispatcher.Invoke(() => { ListBoxDates.ItemsSource = co1; CollectionViewSource.GetDefaultView(ListBoxDates.ItemsSource).Refresh(); }); } } }); t2.Name = "SearchingThread"; t2.Start(); } else if ((string)LabelStatus.Content == "Status: Searching...") { MessageBox.Show($"If you want to search again, please reinitialize this route!"); } else { MessageBox.Show($"You have not initialized a route!"); } /* * * foreach (ValidDate item in ListBoxDates.Items) * { * CheckDate(item.date); * * }*/ }
public void ClickCell(int nCell) { _cells.ElementAt(nCell).Click(_markTurn); _markTurn = _markTurn == Mark.X ? Mark.O : Mark.X; _movementsCounter++; }
public static T Draw <T>(this IList <T> coll) => coll.ElementAt(Ordinal(coll.Count() - 1));
public View GetView(IList <View> layoutChildren, int currHighlightedViewId) => layoutChildren.ElementAt(currHighlightedViewId);
private SharedStringItem GetSharedStringItemById(IList <SharedStringItem> stringValues, int id) { return(stringValues.ElementAt(id)); }
public void SkillShare() { WebDriverWait wait = new WebDriverWait(Global.GlobalDefinitions.driver, TimeSpan.FromSeconds(100)); IWebElement element = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.XPath("//a[@class='ui basic green button']"))); //Populate data from Excel GlobalDefinitions.ExcelLib.PopulateInCollection(Base.ExcelPath, "SkillShare"); shareSkillBtn.Click(); //implict wait Global.GlobalDefinitions.driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(50); //add Title addTitle.SendKeys(GlobalDefinitions.ExcelLib.ReadData(2, "Title")); //add Description addDescription.SendKeys(GlobalDefinitions.ExcelLib.ReadData(2, "Description")); WebDriverWait wait1 = new WebDriverWait(Global.GlobalDefinitions.driver, TimeSpan.FromSeconds(100)); IWebElement element1 = wait1.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.Name("categoryId"))); //Select Category SelectElement categoryObj = new SelectElement(Global.GlobalDefinitions.driver.FindElement(By.Name("categoryId"))); categoryObj.SelectByValue("3"); //implict wait Global.GlobalDefinitions.driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(100); //Select Sub Category SelectElement subCategoryObj = new SelectElement(Global.GlobalDefinitions.driver.FindElement(By.Name("subcategoryId"))); subCategoryObj.SelectByIndex(2); //add Tags addTags.SendKeys(GlobalDefinitions.ExcelLib.ReadData(2, "Tags")); addTags.SendKeys(Keys.Enter); //Select Service type IList <IWebElement> serviceRadioBtnO = Global.GlobalDefinitions.driver.FindElements(By.Name("serviceType")); // Create a boolean variable which will hold the value (True/False) Boolean bValue = false; // This statement will return True, in case of first Radio button is selected bValue = serviceRadioBtnO.ElementAt(0).Selected; // This will check that if the bValue is True means if the first radio button is selected if (bValue == true) { // This will select Second radio button, if the first radio button is selected by default serviceRadioBtnO.ElementAt(1).Click(); } else { // If the first radio button is not selected by default, the first will be selected serviceRadioBtnO.ElementAt(0).Click(); } //Select Location Type IList <IWebElement> loacationRadioBtnO = Global.GlobalDefinitions.driver.FindElements(By.Name("locationType")); Boolean bVal = false; bVal = loacationRadioBtnO.ElementAt(0).Selected; if (bVal == true) { loacationRadioBtnO.ElementAt(1).Click(); } else { loacationRadioBtnO.ElementAt(0).Click(); } //implict wait Global.GlobalDefinitions.driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(60); //Enter date in startdate startDate.SendKeys("07252019"); //Press tab to shift focus to End date startDate.SendKeys(Keys.Tab); //Enter date in end date endDate.SendKeys("07302019"); //Press tab to shift focus to End date startDate.SendKeys(Keys.Tab); //implict wait Global.GlobalDefinitions.driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(100); //count number of days //IList<IWebElement> days = Global.GlobalDefinitions.driver.FindElements(By.Name("Available")); int noOfDays = Global.GlobalDefinitions.driver.FindElements(By.Name("Available")).Count(); for (var i = 1; i <= noOfDays; i++) { var daysObj = Global.GlobalDefinitions.driver.FindElement(By.XPath("//*[@id='service-listing-section']/div[2]/div/form/div[7]/div[2]/div/div[" + (i + 1) + "]/div[1]/div/label")).Text; var daysChekBox = Global.GlobalDefinitions.driver.FindElement(By.XPath("//*[@id='service-listing-section']/div[2]/div/form/div[7]/div[2]/div/div[" + (i + 1) + "]/div[1]/div/input")); var startTime = Global.GlobalDefinitions.driver.FindElement(By.XPath("//*[@id='service-listing-section']/div[2]/div/form/div[7]/div[2]/div/div[" + (i + 1) + "]/div[2]/input")); var endTime = Global.GlobalDefinitions.driver.FindElement(By.XPath("//*[@id='service-listing-section']/div[2]/div/form/div[7]/div[2]/div/div[" + (i + 1) + "]/div[3]/input")); if (daysObj == "Sun") { daysChekBox.Click(); daysChekBox.SendKeys(Keys.Tab); startTime.SendKeys("0940am"); daysChekBox.SendKeys(Keys.Tab); endTime.SendKeys("0500pm"); // Thread.Sleep(1000); } else { if (daysObj == "Tue") { daysChekBox.Click(); daysChekBox.SendKeys(Keys.Tab); startTime.SendKeys("0800am"); daysChekBox.SendKeys(Keys.Tab); endTime.SendKeys("0310pm"); } else { if (daysObj == "Sat") { daysChekBox.Click(); daysChekBox.SendKeys(Keys.Tab); startTime.SendKeys("0800am"); daysChekBox.SendKeys(Keys.Tab); endTime.SendKeys("0310pm"); break; } } } } //Select SkillTrade IList <IWebElement> skillTradeObj = Global.GlobalDefinitions.driver.FindElements(By.Name("skillTrades")); Boolean val = false; val = skillTradeObj.ElementAt(0).Selected; if (val == true) { skillTradeObj.ElementAt(1).Click(); Global.GlobalDefinitions.driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(100); credit.SendKeys(GlobalDefinitions.ExcelLib.ReadData(2, "Credit")); } else { skillTradeObj.ElementAt(0).Click(); Global.GlobalDefinitions.driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(100); skillExchange.SendKeys(GlobalDefinitions.ExcelLib.ReadData(2, "Skill-Exchange")); } //implict wait Global.GlobalDefinitions.driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(100); //select file for work sample uploadFile.Click(); //create a AutoIT class and object AutoItX3 autoIt = new AutoItX3(); autoIt.WinActivate("Open"); Thread.Sleep(1000); autoIt.Send(@"C:\Users\minty\OneDrive\Desktop\SampleImage"); Global.GlobalDefinitions.driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(100); autoIt.Send("{Enter}"); //implict wait Global.GlobalDefinitions.driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(100); // Select Active addActive.Click(); //implict wait Global.GlobalDefinitions.driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(100); //click Save saveBtn.Click(); //implict wait Global.GlobalDefinitions.driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(100); //Base.Test.Log(LogStatus.Info, "Added Skill"); }
/// <summary> /// Sends the asynchronous. /// </summary> /// <param name="emailMessage">The EmailMessage.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task SendMeetingInviteAsync(EmailMessage emailMessage) { if (emailMessage == null) { throw new ArgumentNullException(nameof(emailMessage)); } string recipients = string.Join(",", emailMessage.ToAddresses.Select(r => r.Address).ToList()); var traceProps = new Dictionary <string, string>(); traceProps["OperationName"] = this.GetType().FullName; traceProps["Recipients"] = recipients; var trimmedAddresses = emailMessage.ToAddresses.Where(a => !string.IsNullOrEmpty(a.Address)).ToArray(); emailMessage.ToAddresses = trimmedAddresses; if (!emailMessage.ToAddresses.Any()) { ArgumentNullException ex = new ArgumentNullException("ToAddresses", "Email message is missing 'To' addresses."); this.logger.WriteException(ex, traceProps); return; } var message = new MimeMessage(); message.To.AddRange(emailMessage.ToAddresses.Select(x => new MailboxAddress(x.Name, x.Address))); if (emailMessage.CcAddresses != null && emailMessage.CcAddresses.Any()) { message.Cc.AddRange(emailMessage.CcAddresses.Select(x => new MailboxAddress(x.Name, x.Address))); } message.From.AddRange(emailMessage.FromAddresses.Select(x => new MailboxAddress(this.mailConfiguration.DisplayName, x.Address))); message.Subject = emailMessage.Subject; var ical = new TextPart("calendar") { ContentTransferEncoding = ContentEncoding.Base64, Text = emailMessage.Content, }; ical.ContentType.Parameters.Add("method", "REQUEST"); Multipart multipart = new Multipart("mixed"); multipart.Add(ical); IList <string> fileNames = emailMessage.FileName?.ToList(); IList <string> fileContents = emailMessage.FileContent?.ToList(); int i = 0; if (fileNames != null && fileContents != null && fileNames.Any() && fileContents.Count == fileNames.Count) { foreach (var fileName in fileNames) { string content = fileContents.ElementAt(i++); if (!string.IsNullOrEmpty(content)) { Stream stream = new MemoryStream(Convert.FromBase64String(content)); var indx = fileName.LastIndexOf('.') + 1; var fileType = fileName.Substring(indx, fileName.Length - indx); MimePart attachment = new MimePart("mixed", fileType) { FileName = fileName, Content = new MimeContent(stream, ContentEncoding.Default), ContentDisposition = new ContentDisposition(ContentDisposition.Attachment), ContentTransferEncoding = ContentEncoding.Base64, }; multipart.Add(attachment); } } } message.Body = multipart; await this.SendItemAsync(message, traceProps).ConfigureAwait(false); }
private static T GetDividerAndMoveToFront<T>(this IList<T> inputs) { return inputs.ElementAt(0); }
public static T GetRandom <T>(this IList <T> items) { return(items.ElementAt(_Random.Next(0, items.Count))); }
public void GetWeekdayForecastFromXML() { StreamReader streamReader = Utils.readXML(Utils.GetXmlFileName(Navigation.ForecastCity, XML_WEEKDAY_POSTFIX)); if (streamReader == null) { return; } XDocument loadedData = XDocument.Load(streamReader); var timeData = from query in loadedData.Descendants("FcstTime") select(string) query; IList <string> timeDataList = timeData.ToList(); var forecastData = from c1 in loadedData.Descendants("Area") where c1.Attribute("AreaID").Value == Navigation.ForecastCity.ID from c2 in c1.Elements() select new ForecastData { Temperature = (string)c2.Element("Temperature"), Wx = (string)c2.Element("Wx"), WeatherDes = (string)c2.Element("WeatherDes"), WeatherIcon = (string)c2.Element("WeatherIcon"), RH = (string)c2.Element("RH"), Rain = ((string)c2.Element("PoP")).Length > 0 ? ((string)c2.Element("PoP")) : "", WindSpeed = (string)c2.Element("WindSpeed"), WindDir = (string)c2.Element("WindDir"), MinCI = (string)c2.Element("MinCI"), MaxCI = (string)c2.Element("MaxCI"), MinT = (string)c2.Element("MinT"), MaxT = (string)c2.Element("MaxT"), WindLevel = (string)c2.Element("WindLevel") }; IList <ForecastData> forecastDataList = forecastData.ToList(); for (int i = 0; i < forecastDataList.Count; i++) { forecastDataList[i].Time = timeDataList[i]; } DateTime prevDt = Convert.ToDateTime(forecastDataList[0].Time); int c = 1; while (c < forecastDataList.Count) { DateTime dt = Convert.ToDateTime(forecastDataList[c].Time); System.Diagnostics.Debug.WriteLine("dt: " + dt.Day); System.Diagnostics.Debug.WriteLine("prevDt: " + prevDt.Day); if (dt.Day == prevDt.Day) { forecastDataList.RemoveAt(c); } else { c++; } prevDt = dt; } //mWeekDayViewModel.WeekdayForecastItemsSource = forecastDataList; mWeekdayForecastDataList = forecastDataList; if (forecastDataList.ElementAt(0) != null) { mForecastViewModel.WeatherIcon = forecastDataList[0].WeatherIcon; mForecastViewModel.MaxT = forecastDataList[0].MaxT; mForecastViewModel.MinT = forecastDataList[0].MinT; SetBackgroundImage(forecastDataList[0].WeatherIcon); } streamReader.Close(); streamReader.Dispose(); }
public override MenuComponent getChild(int i) { return(menuComponents.ElementAt(i)); }
public Files fileUpload(HttpFileCollectionBase multipartFiles, String inputFileName, String allowType, long fileSize, int masterIdx, IList <int> fileIdxs) { IList <HttpPostedFileBase> files = multipartFiles.GetMultiple(inputFileName); Files fileItem = new Files(); IList <int> fileTmpIdxs = new List <int>(); int idx = 0; foreach (var file in files) { int fileIdx = -1; if (file.ContentLength != 0) { String fileName = file.FileName; if (fileName.IndexOf("\\") != -1) { fileName = fileName.Substring(fileName.LastIndexOf("\\") + 1); } int typeIndex = fileName.LastIndexOf(".") + 1; String fileType = fileName.Substring(typeIndex, fileName.Length - typeIndex); validationFileUpload(file, allowType, fileSize, fileType); //file type 및 size 체크 String replaceName = replaceFileName(); //파일 이름 변환 String path = Path.Combine(FILE_PATH, replaceName); //폴더가 없으면 생성 if (!Directory.Exists(FILE_PATH)) { Directory.CreateDirectory(FILE_PATH); } file.SaveAs(path); fileItem.originalFilename = fileName; fileItem.savedFilename = replaceName; fileItem.masterIdx = masterIdx; fileItem.type = inputFileName; if (fileIdxs == null || fileIdxs.Count == 0 || fileIdxs.Count <= idx || fileIdxs[idx] <= 0) { //새로 올리는 file인 경우, db에 file 정보 insert fileIdx = filesDao.insertFile(fileItem); fileTmpIdxs.Add(fileIdx); //리턴해줄 fileIdxs } else { //기존 file을 수정하는 경우, 해당 fileIdx로 update fileItem.fileIdx = fileIdxs.ElementAt(idx); fileTmpIdxs.Add(fileIdxs[idx]); //리턴해줄 fileIdxs filesDao.updateFile(fileItem); } } else//기존 file은 있지만, 업데이트 이루어지지 않은 경우. { if (fileIdxs != null && fileIdxs[idx] >= 0) { fileTmpIdxs.Add(fileIdxs[idx]);//리턴해줄 fileIdxs// exception } } if (fileIdxs != null) { if (fileIdx == -1) { if (fileIdxs[idx] >= 0) { idx++; } } } } fileItem.fileIdxs = fileTmpIdxs; return(fileItem); }
private IEnumerable <TItem> RowOrColumnValues(int i, IList <GridRowOrColumn <TStorage> > items) => ExtractItems(items.ElementAt(i).Elements);
private Tile readTile(FileStream fs, IList<Region> regions) { Tile tile = new Tile(); short regionId = readShort(fs); if (regionId >= 0) { tile.Region = regions.ElementAt(regionId); tile.Region.AddTile(tile); } return tile; }
public void RedirectToLogin() { uf.isJqueryActive(driver); iWait.Until(ExpectedConditions.ElementExists((OR.GetElement("NonIETMemberRegistration", "LoginLink", "TVWebPortalOR.xml")))); IWebElement loginLink = driver.FindElement((OR.GetElement("NonIETMemberRegistration", "LoginLink", "TVWebPortalOR.xml"))); executor.ExecuteScript("arguments[0].click();", loginLink); log.Info("username " + cf.readingXMLFile("WebPortal", "IndividualUser", "IndividualUserName", "Config.xml")); log.Info("Password " + cf.readingXMLFile("WebPortal", "IndividualUser", "IndividualPassword", "Config.xml")); string userName = cf.readingXMLFile("WebPortal", "IndividualUser", "IndividualUserName", "Config.xml"); string userPassword = cf.readingXMLFile("WebPortal", "IndividualUser", "IndividualPassword", "Config.xml"); log.Info("username " + userName); log.Info("Password " + userPassword); iWait.Until(ExpectedConditions.ElementIsVisible((OR.GetElement("VideoRequestByUser", "UserNameTB", "TVWebPortalOR.xml")))); driver.FindElement((OR.GetElement("VideoRequestByUser", "UserName", "TVWebPortalOR.xml"))).SendKeys(userName); Thread.Sleep(1000); driver.FindElement((OR.GetElement("VideoRequestByUser", "Password", "TVWebPortalOR.xml"))).SendKeys(userPassword); iWait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy((OR.GetElement("VideoRequestByUser", "Login", "TVWebPortalOR.xml")))); driver.FindElement((OR.GetElement("VideoRequestByUser", "Login", "TVWebPortalOR.xml"))).Click(); //need to comment below region to run at UAT #region region process Thread.Sleep(10000); iWait.Until(ExpectedConditions.ElementIsVisible((OR.GetElement("VideoRequestByUser", "UserNameTB", "TVWebPortalOR.xml")))); driver.FindElement((OR.GetElement("VideoRequestByUser", "UserName", "TVWebPortalOR.xml"))).SendKeys(userName); Thread.Sleep(1000); driver.FindElement((OR.GetElement("VideoRequestByUser", "Password", "TVWebPortalOR.xml"))).SendKeys(userPassword); iWait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy((OR.GetElement("VideoRequestByUser", "Login", "TVWebPortalOR.xml")))); driver.FindElement((OR.GetElement("VideoRequestByUser", "Login", "TVWebPortalOR.xml"))).Click(); uf.isJqueryActive(driver); #endregion Thread.Sleep(3000); log.Info("already logged in count : " + driver.FindElements((OR.GetElement("VideoRequestByUser", "YesButton", "TVWebPortalOR.xml"))).Count); //if user is already logged in if (driver.FindElements((OR.GetElement("VideoRequestByUser", "YesButton", "TVWebPortalOR.xml"))).Count > 0) { driver.FindElement((OR.GetElement("VideoRequestByUser", "YesButton", "TVWebPortalOR.xml"))).Click(); } //Handling pop up message iWait.Until(ExpectedConditions.ElementIsVisible(OR.GetElement("ReportAbuse", "PopupMessage", "TVWebPortalOR.xml"))); // Waiting for Popup window to appear after clicking on accept button IList <IWebElement> btnOK = driver.FindElements(OR.GetElement("ReportAbuse", "PopupMessage", "TVWebPortalOR.xml")); IWebElement element = btnOK.ElementAt(0); executor.ExecuteScript("arguments[0].click();", element); }
private void PrettyPrintSub(IList<object> node) { stringWriter.Write("("); for (int i = 0; i < node.Count; i++) { var printnode = node.ElementAt(i); PrettyPrintSub(printnode); if (i < node.Count - 1) { stringWriter.Write(" "); } } stringWriter.Write(")"); }
/// <summary>NewOrigin: /// This method find the relative vector for each Aggregate to be moved to its correct position in the assembly /// </summary> /// <param name="agg1"></param> /// <param name="agg2"></param> /// <param name="agg3"></param> /// <param name="orientation"></param> /// <returns></returns> public IList <Point3d> NewOrigin(IList <Aggregate> listagg, char orientation, int index) { Point3d agg1Origin = listagg.ElementAt(index).Origin; Point3d agg2Origin = listagg.ElementAt(listagg.Count - 2).Origin; Point3d agg3Origin = listagg.ElementAt(listagg.Count - 1).Origin; Point3d origin = new Point3d(0, 0, 0); Point3d agg1Freespot = new Point3d(); Point3d agg2Freespot = new Point3d(); Point3d agg3Freespot = new Point3d(); var pList = new List <Point3d>(); if (orientation == 'X') { agg1Freespot = listagg.ElementAt(index).XFsPos; agg2Freespot = listagg.ElementAt(listagg.Count - 2).YFsPos; agg3Freespot = listagg.ElementAt(listagg.Count - 1).ZFsPos; } else if (orientation == 'Y') { agg1Freespot = listagg.ElementAt(index).YFsPos; agg2Freespot = listagg.ElementAt(listagg.Count - 2).ZFsPos; agg3Freespot = listagg.ElementAt(listagg.Count - 1).XFsPos; } else { agg1Freespot = listagg.ElementAt(index).ZFsPos; agg2Freespot = listagg.ElementAt(listagg.Count - 2).XFsPos; agg3Freespot = listagg.ElementAt(listagg.Count - 1).YFsPos; } Vector3d v1 = new Vector3d(agg1Origin.X - origin.X, agg1Origin.Y - origin.Y, agg1Origin.Z - origin.Z); Vector3d v2 = new Vector3d(agg1Freespot.X - agg1Origin.X, agg1Freespot.Y - agg1Origin.Y, agg1Freespot.Z - agg1Origin.Z); Vector3d v3 = new Vector3d(agg2Freespot.X - agg2Origin.X, agg2Freespot.Y - agg2Origin.Y, agg2Freespot.Z - agg2Origin.Z); Vector3d v4 = new Vector3d(agg3Freespot.X - agg3Origin.X, agg3Freespot.Y - agg3Origin.Y, agg3Freespot.Z - agg3Origin.Z); Vector3d vA1 = v1 + v2 + v3; Vector3d vA2 = v1 + v2 + v4; agg1Origin = origin + vA1; agg2Origin = origin + vA2; pList.Add(agg1Origin); pList.Add(agg2Origin); return(pList); }
private void ChangeText(object sender, RoutedEventArgs e) { var selectedIndex = DataGridRow.GetRowContainingElement (sender as FrameworkElement).GetIndex(); if (mode == 1) { Bron obiekt = DataFromDatabase.ElementAt(selectedIndex); ModifyForm mForm = new ModifyForm(obiekt, mode, this); mForm.Show(); } else if (mode == 2) { Amunicja obiekt = DataFromDatabase.ElementAt(selectedIndex); ModifyForm mForm = new ModifyForm(obiekt, mode, this); mForm.Show(); } else if (mode == 3) { Hurtowe obiekt = DataFromDatabase.ElementAt(selectedIndex); ModifyForm mForm = new ModifyForm(obiekt, mode, this); mForm.Show(); } else if (mode == 4) { Detaliczne obiekt = DataFromDatabase.ElementAt(selectedIndex); ModifyForm mForm = new ModifyForm(obiekt, mode, this); mForm.Show(); } else if (mode == 5) { Dostawa obiekt = DataFromDatabase.ElementAt(selectedIndex); ModifyForm mForm = new ModifyForm(obiekt, mode, this); mForm.Show(); } else if (mode == 6) { Kategoria obiekt = DataFromDatabase.ElementAt(selectedIndex); ModifyForm mForm = new ModifyForm(obiekt, mode, this); mForm.Show(); } else if (mode == 7) { Material obiekt = DataFromDatabase.ElementAt(selectedIndex); ModifyForm mForm = new ModifyForm(obiekt, mode, this); mForm.Show(); } else if (mode == 8) { Pracownik obiekt = DataFromDatabase.ElementAt(selectedIndex); ModifyForm mForm = new ModifyForm(obiekt, mode, this); mForm.Show(); } else if (mode == 9) { Produkcja obiekt = DataFromDatabase.ElementAt(selectedIndex); ModifyForm mForm = new ModifyForm(obiekt, mode, this); mForm.Show(); } else { Zamowienie obiekt = DataFromDatabase.ElementAt(selectedIndex); ModifyForm mForm = new ModifyForm(obiekt, mode, this); mForm.Show(); } }
private void resetRegions(IList<Region> regions, Tile[][] tiles) { for (int i = 0; i < regions.Count; ++i) { Region region = regions.ElementAt(i); if (region.UpRegionId >= 0) { region.UpRegion = regions.ElementAt(region.UpRegionId); } if (region.LeftRegionId >= 0) { region.LeftRegion = regions.ElementAt(region.LeftRegionId); } if (region.DownRegionId >= 0) { region.DownRegion = regions.ElementAt(region.DownRegionId); } if (region.RightRegionId >= 0) { region.RightRegion = regions.ElementAt(region.RightRegionId); } region.CenterTile = tiles[region.CenterTileRow][region.CenterTileCol]; } }
public override Java.Lang.Object GetItem(int position) { return(BillList.ElementAt(position)); }
/// <summary> /// Clear data rows where the foreign key is missing. /// </summary> /// <param name="table">Table for which to manipulate data.</param> /// <param name="dataToManipulate">Data rows which should be manipulated.</param> /// <param name="keyValuesToClear">Key values for the rows, where the value should be cleared.</param> /// <param name="foreignKeyFields">Field in the foreign key.</param> /// <param name="keyValueComparer">Functionality to compare key values.</param> /// <returns>Data rows where value for the foreign key missing is cleaned.</returns> private IEnumerable <IEnumerable <IDataObjectBase> > ClearDataRows(INamedObject table, ICollection <IEnumerable <IDataObjectBase> > dataToManipulate, IList <string> keyValuesToClear, IList <IField> foreignKeyFields, IEqualityComparer <string> keyValueComparer) { if (table == null) { throw new ArgumentNullException("table"); } if (dataToManipulate == null) { throw new ArgumentNullException("dataToManipulate"); } if (keyValuesToClear == null) { throw new ArgumentNullException("keyValuesToClear"); } if (foreignKeyFields == null) { throw new ArgumentNullException("foreignKeyFields"); } if (keyValueComparer == null) { throw new ArgumentNullException("keyValueComparer"); } var dataRowsToClear = new List <IEnumerable <IDataObjectBase> >(); try { while (keyValuesToClear.Count > 0) { dataRowsToClear.AddRange(DataRepositoryHelper.GetDataRowsForKeyValue(foreignKeyFields, dataToManipulate, keyValuesToClear.ElementAt(0))); keyValuesToClear.RemoveAt(0); } dataRowsToClear.ForEach(dataRow => { var dataObject = dataRow.Single(m => m.Field != null && m.Field.Equals(foreignKeyFields.Last())); dataObject.UpdateSourceValue <object>(null); }); var foreignKeyInformationBuilder = new StringBuilder(); foreignKeyInformationBuilder.AppendFormat("{0}(", ForeignKeyTable.NameTarget); for (var i = 0; i < _foreignKeyFields.Count; i++) { if (i > 0) { foreignKeyInformationBuilder.AppendFormat(", {0}", _foreignKeyFields.ElementAt(i)); continue; } foreignKeyInformationBuilder.Append(_foreignKeyFields.ElementAt(i)); } foreignKeyInformationBuilder.Append(')'); InformationLogger.LogInformation(Resource.GetText(Text.ForeignKeyCleanerInformation, GetType().Name, dataRowsToClear.Count, table.NameTarget, foreignKeyInformationBuilder.ToString())); return(dataToManipulate); } finally { while (dataRowsToClear.Count > 0) { dataRowsToClear.Clear(); } } }
public void CreateTenantCharge() { //FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(@"C:\Users\FerozAshim\Desktop\geckodriver-v0.24.0-win64"); //service.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox\firefox.exe"; //IWebDriver driver = new FirefoxDriver(service); IWebDriver driver = new ChromeDriver(); driver.Url = "https://dev-manage.liveuptop.com"; driver.Manage().Window.Maximize(); var loginPagePO = new LoginPagePO(); PageFactory.InitElements(driver, loginPagePO); var topNavigationPO = new TopNavigationPO(); PageFactory.InitElements(driver, topNavigationPO); var portfolioPO = new PortfolioPagePO(); PageFactory.InitElements(driver, portfolioPO); var commonPageFunctions = new CommonPageFunctions(); PageFactory.InitElements(driver, commonPageFunctions); var tenantChargesPO = new TenantChargesPO(); PageFactory.InitElements(driver, tenantChargesPO); //------------------------------------------------------------------------------------------------------- //Enter Username loginPagePO.UserName.SendKeys("*****@*****.**"); //Enter Password loginPagePO.Password.SendKeys("Testing1!"); //Click on Submit Button loginPagePO.Submit.Click(); //------------------------------------------------------------------------------------------------------- System.Threading.Thread.Sleep(2000); // new Actions(driver).Click(topNavigationPO.GearIcon).Perform(); topNavigationPO.GearIcon.Click(); topNavigationPO.TenantCharges.Click(); System.Threading.Thread.Sleep(2000); tenantChargesPO.AddTenantCharges.Click(); System.Threading.Thread.Sleep(2000); String[] arr = { "Select Account", "1000 - BankAccountForEntity", "1001 - Escrow - LLCEntity", "1002 - EntityAccount2", "1003 - Escrow - Entity2", "1004 - TestAccount456", "1005 - Escrow - EntityCorp4", "1006 - Account332", "1007 - Escrow - EntityCorp444", "1008 - AccounttestFromEntity", "1009 - Escrow - CoopEntity", "1200 - Accounts Receivable", "1300 - Prepaid Expenses", "2000 - Accounts Payable", "2100 - Security Deposits", "2200 - Tenant Prepayments", "3200 - Opening Balance", "4000 - Rent", "4100 - Disputes", "4200 - Surcharges", "4300 - Late Fees", "4400 - Concessions", "6050 - Payment Processing Fees" }; var selectElement = new SelectElement(tenantChargesPO.ModalSelectAccount); IList <IWebElement> dropdownValues = selectElement.Options; int elementsSize = dropdownValues.Count; for (int i = 0; i < elementsSize; i++) { Console.WriteLine("Value at " + i + " is: " + dropdownValues.ElementAt(i).Text); if (dropdownValues.ElementAt(i).Text.Contains(arr[i])) { Console.WriteLine("Passed dropdown verification"); } else { Console.WriteLine("Failed dropdown verification"); } } String randomValues = commonPageFunctions.randomCharactersGenerator(); tenantChargesPO.ModalNameTextbox.SendKeys(randomValues); commonPageFunctions.selectFromDropdown(tenantChargesPO.ModalSelectAccount, 2); System.Threading.Thread.Sleep(2000); tenantChargesPO.ModalAddTenantCharge.Click(); System.Threading.Thread.Sleep(2000); commonPageFunctions.VerifyElementInTableExists(driver, tenantChargesPO.TenantChargesListTable, randomValues); System.Threading.Thread.Sleep(2000); tenantChargesPO.ModalNameTextbox.Clear(); String randomValueUpdate = commonPageFunctions.randomCharGenerator(); tenantChargesPO.ModalNameTextbox.SendKeys(randomValueUpdate); System.Threading.Thread.Sleep(2000); commonPageFunctions.selectFromDropdown(tenantChargesPO.ModalSelectAccount, 4); tenantChargesPO.ModalSaveChanges.Click(); System.Threading.Thread.Sleep(2000); commonPageFunctions.VerifyElementInTableExists(driver, tenantChargesPO.TenantChargesListTable, randomValueUpdate); System.Threading.Thread.Sleep(2000); tenantChargesPO.ModalDelete.Click(); System.Threading.Thread.Sleep(2000); tenantChargesPO.ModalDeleteConfirm.Click(); }
static Type ExtractNodeTypeAtPosition(IList<Type> messageTypesToDeserialize, int position) { Type nodeType = null; if (messageTypesToDeserialize != null && position < messageTypesToDeserialize.Count) { nodeType = messageTypesToDeserialize.ElementAt(position); } return nodeType; }
public void TestBasicContext() { Input[] keys = new Input[] { new Input("lend me your ear", 8, new BytesRef("foobar"), AsSet("foo", "bar")), new Input("a penny saved is a penny earned", 10, new BytesRef("foobaz"), AsSet("foo", "baz")) }; DirectoryInfo tempDir = CreateTempDir("analyzingInfixContext"); for (int iter = 0; iter < 2; iter++) { AnalyzingInfixSuggester suggester; Analyzer a = new MockAnalyzer(Random(), MockTokenizer.WHITESPACE, false); if (iter == 0) { suggester = new AnalyzingInfixSuggester(TEST_VERSION_CURRENT, NewFSDirectory(tempDir), a, a, 3); suggester.Build(new InputArrayIterator(keys)); } else { // Test again, after close/reopen: suggester = new AnalyzingInfixSuggester(TEST_VERSION_CURRENT, NewFSDirectory(tempDir), a, a, 3); } // No context provided, all results returned IList <Lookup.LookupResult> results = suggester.DoLookup(TestUtil.StringToCharSequence("ear", Random()).ToString(), 10, true, true); assertEquals(2, results.size()); Lookup.LookupResult result = results.ElementAt(0); assertEquals("a penny saved is a penny <b>ear</b>ned", result.key); assertEquals(10, result.value); assertEquals(new BytesRef("foobaz"), result.payload); assertNotNull(result.contexts); assertEquals(2, result.contexts.Count()); assertTrue(result.contexts.Contains(new BytesRef("foo"))); assertTrue(result.contexts.Contains(new BytesRef("baz"))); result = results.ElementAt(1); assertEquals("lend me your <b>ear</b>", result.key); assertEquals(8, result.value); assertEquals(new BytesRef("foobar"), result.payload); assertNotNull(result.contexts); assertEquals(2, result.contexts.Count()); assertTrue(result.contexts.Contains(new BytesRef("foo"))); assertTrue(result.contexts.Contains(new BytesRef("bar"))); // Both suggestions have "foo" context: results = suggester.DoLookup(TestUtil.StringToCharSequence("ear", Random()).ToString(), AsSet("foo"), 10, true, true); assertEquals(2, results.size()); result = results.ElementAt(0); assertEquals("a penny saved is a penny <b>ear</b>ned", result.key); assertEquals(10, result.value); assertEquals(new BytesRef("foobaz"), result.payload); assertNotNull(result.contexts); assertEquals(2, result.contexts.Count()); assertTrue(result.contexts.Contains(new BytesRef("foo"))); assertTrue(result.contexts.Contains(new BytesRef("baz"))); result = results.ElementAt(1); assertEquals("lend me your <b>ear</b>", result.key); assertEquals(8, result.value); assertEquals(new BytesRef("foobar"), result.payload); assertNotNull(result.contexts); assertEquals(2, result.contexts.Count()); assertTrue(result.contexts.Contains(new BytesRef("foo"))); assertTrue(result.contexts.Contains(new BytesRef("bar"))); // Only one has "bar" context: results = suggester.DoLookup(TestUtil.StringToCharSequence("ear", Random()).ToString(), AsSet("bar"), 10, true, true); assertEquals(1, results.size()); result = results.ElementAt(0); assertEquals("lend me your <b>ear</b>", result.key); assertEquals(8, result.value); assertEquals(new BytesRef("foobar"), result.payload); assertNotNull(result.contexts); assertEquals(2, result.contexts.Count()); assertTrue(result.contexts.Contains(new BytesRef("foo"))); assertTrue(result.contexts.Contains(new BytesRef("bar"))); // Only one has "baz" context: results = suggester.DoLookup(TestUtil.StringToCharSequence("ear", Random()).ToString(), AsSet("baz"), 10, true, true); assertEquals(1, results.size()); result = results.ElementAt(0); assertEquals("a penny saved is a penny <b>ear</b>ned", result.key); assertEquals(10, result.value); assertEquals(new BytesRef("foobaz"), result.payload); assertNotNull(result.contexts); assertEquals(2, result.contexts.Count()); assertTrue(result.contexts.Contains(new BytesRef("foo"))); assertTrue(result.contexts.Contains(new BytesRef("baz"))); // Both have foo or bar: results = suggester.DoLookup(TestUtil.StringToCharSequence("ear", Random()).ToString(), AsSet("foo", "bar"), 10, true, true); assertEquals(2, results.size()); result = results.ElementAt(0); assertEquals("a penny saved is a penny <b>ear</b>ned", result.key); assertEquals(10, result.value); assertEquals(new BytesRef("foobaz"), result.payload); assertNotNull(result.contexts); assertEquals(2, result.contexts.Count()); assertTrue(result.contexts.Contains(new BytesRef("foo"))); assertTrue(result.contexts.Contains(new BytesRef("baz"))); result = results.ElementAt(1); assertEquals("lend me your <b>ear</b>", result.key); assertEquals(8, result.value); assertEquals(new BytesRef("foobar"), result.payload); assertNotNull(result.contexts); assertEquals(2, result.contexts.Count()); assertTrue(result.contexts.Contains(new BytesRef("foo"))); assertTrue(result.contexts.Contains(new BytesRef("bar"))); suggester.Dispose(); } }