private List<string> consultarMails(List<string> mails) { List<string> resulta = new List<string>(); //traigo todos los mails de la base de datos EJEMPLOEntities ctx = new EJEMPLOEntities(); var consulta = (from c in ctx.MAILS select c.mail).ToList(); //comparo componentes de cada lista IEnumerable<string> Diferencias = mails.Except(consulta); //guardo en nueva lista los componentes que no son iguales foreach (string f in Diferencias) { resulta.Add(f); } // //List<ListaMail> miLista = new List<ListaMail>(); //List<List<string>> listaMails = new List<List<string>>(); //// //if (resulta.Count > 0) { // for (int i = 0; i < resulta.Count; i++) { // listaMails.Add(new List<string> { miLista[i].idLista.ToString(), miLista[i].mailLista}); // } //} //valor de retorno->Lista de componentes diferentes a los traidos de la base PasarListaBD(resulta); return resulta; }
/// <summary> /// Inner calculation, don't call this directly /// </summary> private static string FindPermutationAt(List<string> alphabet, int currentIndex, int searchIndex) { // Factorial computation, does this exist in .NET framework already? Func<int, int> factorial = n => Enumerable.Range(1, n).Aggregate((acc, x) => acc * x); // Exit condition if (alphabet.Count == 1) { return alphabet.Single(); } // Number of combinations for each sybil in the alphabet int combinations = factorial(alphabet.Count - 1); // foreach sybil in alphabet for (int i = 0, lowIndex = currentIndex; i < alphabet.Count; i++, lowIndex += combinations) { int highIndex = lowIndex + combinations; // Search index should be between lowIndex and highIndex if (searchIndex >= lowIndex && searchIndex <= highIndex) { var found = alphabet[i]; // Remove found sybil from alphabet var newAlphabet = alphabet.Except(new[] { found }).ToList(); // Add and recurse return found + FindPermutationAt(newAlphabet, lowIndex, searchIndex); } } // Should only end up here if we ask for searchIndex more than max throw new IndexOutOfRangeException("No such index exist in permutation: " + searchIndex); }
public static List<Point> FalseObj(List<Point> obj, List<Point> foundObj, int R) { var eObj = ExactObj(obj, foundObj); List<Point> objects = new List<Point>(); var ieObj = InexactObj(obj, foundObj, R, out objects); return (foundObj.Except(eObj)).Except(ieObj).ToList(); }
private void FilterEntities() { List<object> list = new List<object>(); foreach(var entity in _game.Entities) { var tags = entity.Value.Tags.Select(GetTagKeyValue).Aggregate((c, n) => c + " | " + n); var card = GameV2.GetCardFromId(entity.Value.CardId); var cardName = card != null ? card.Name : ""; var name = string.IsNullOrEmpty(entity.Value.Name) ? cardName : entity.Value.Name; list.Add(new {Name = name, entity.Value.CardId, Tags = tags}); } var firstNotSecond = list.Except(_previous).ToList(); var secondNotFirst = _previous.Except(list).ToList(); if(firstNotSecond.Any() || secondNotFirst.Any()) { DataGridProperties.ItemsSource = list; DataGridProperties.UpdateLayout(); foreach(var item in firstNotSecond) { var row = DataGridProperties.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow; if(row != null) row.Background = new SolidColorBrush(Color.FromArgb(50, 0, 205, 0)); } _previous = list; } }
private void test_Load(object sender, EventArgs e) { List<int> a = new List<int> { 1, 2, 3, 4 }; List<int> b = new List<int> { 2, 3, 4, 5 }; List<int> c = new List<int> { 3, 4, 5, 6 }; List<int> res = a.Intersect(b).ToList<int>();//a.Except(b).Concat(b.Except(a)).ToList<int>(); res = res.Intersect(c).ToList<int>();//a.Except(c).Concat(c.Except(a)).ToList<int>(); a.Except(b).Concat(a.Except(b)).OrderBy(i => i).ToList().ForEach(i => Console.Write(i.ToString())); string abc = ""; for (int i = 0;i<res.Count ;i++ ) { abc += res[i]; } this.textBox1.Text = abc; }
private void CalculateBodyAndPivots() { var parentCfg = Scope.Parent.LocalCfg; var cflow = new List<ControlFlowBlock>(); var pivots = new List<ControlFlowBlock>(); var todo = new HashSet<ControlFlowBlock>{Head}; while (todo.IsNotEmpty()) { var v = todo.First(); cflow.Add(v); todo.Remove(v); var h_pivots = Scope.Hierarchy().SelectMany(s => s.Pivots); if (h_pivots.Contains(v)) { pivots.Add(v); } else { var inEdges = parentCfg.TreeVedges(null, v); var innerEdges = parentCfg.Edges(cflow, cflow); var rootEdge = parentCfg.Vedge(Root, v); inEdges.Except(innerEdges).Except(rootEdge).AssertEmpty(); var outEdges = parentCfg.Vedges(v, null); var pending = outEdges.Select(e => e.Target).Where(v1 => !cflow.Contains(v1)); pending.ForEach(v1 => todo.Add(v1)); } } Body = cflow.Except(pivots).ToReadOnly(); Pivots = pivots.ToReadOnly(); }
public static Dictionary<string, Image> ImagesFromFile(List<string> paths, Form form = null) { var pathsToLoad = paths.Except(imageDict.Keys).ToList(); var imagesPaths = pathsToLoad.AsParallel() .Select(p => new ImagePath{Path = p, Image = Image.FromFile(p)}) .ToList(); foreach (var image in imagesPaths) { imageDict.Add(image.Path, image.Image); } if (form != null) { form.Disposed -= form_Disposed; form.Disposed += form_Disposed; } var res = new Dictionary<string, Image>(); foreach (var path in paths) { var image = imageDict[path]; res.Add(path, image); if (form != null) formImageDict.GetOrAdd(form).Add(image); } return res; }
/// <summary> /// 修改商品属性 /// </summary> /// <param name="model"></param> private void EditDishGoodAttr(DishGood model) { List <DishGoodAttr> goodAttrList = DishGoodAttrBLL.SingleModel.GetList($"goods_id={model.id} and attr_type_id={model.goods_type}"); if (model.attr != null) { List <DishGoodAttr> tempGoodAttrList = model.attr.Where(w => w.id > 0).ToList(); //取差集,删除差集 List <DishGoodAttr> diffGoodAttr = goodAttrList?.Except(model.attr, new DishGoodAttrComparer2()).ToList(); diffGoodAttr?.ForEach(p => { if (p.id > 0) { DishGoodAttrBLL.SingleModel.Delete(p.id); } }); tempGoodAttrList?.ForEach(item => { DishGoodAttrBLL.SingleModel.Update(item, "price,value"); }); tempGoodAttrList = model.attr.Where(w => w.id == 0).ToList(); tempGoodAttrList?.ForEach(item => { item.id = Convert.ToInt32(DishGoodAttrBLL.SingleModel.Add(item)); }); } }
public void UpdateMovie(MovieEditViewModel model, MoviePart part) { part.IMDB_Id = model.IMDB_Id; part.YearReleased = model.YearReleased; part.Rating = model.Rating; var oldCast = _movieActorRepository.Fetch(ma => ma.MoviePartRecord.Id == part.Id); List<int> oldActors = new List<int>(); foreach (var actor in oldCast) { oldActors.Add(actor.ActorRecord.Id); } foreach (var oldActorId in oldActors.Except(model.Actors)) { var actor = _movieActorRepository.Get(r => r.ActorRecord.Id == oldActorId); _movieActorRepository.Delete(actor); } foreach (var newActorId in model.Actors.Except(oldActors)) { var actor = _actorRepository.Get(newActorId); var moviePart = _moviePartRepository.Get(part.Id); _movieActorRepository.Create(new MovieActorRecord { ActorRecord = actor, MoviePartRecord = moviePart }); } }
private static bool FillSubGrid(ref int[,] board, int subgrid, bool random=true) { try { int xStart = (subgrid / 3) * 3; int yStart = (subgrid % 3) * 3; int xend = xStart + 3; int yend = yStart + 3; Random rnd = new Random(); for (int i = xStart; i < xend; i++) for (int j = yStart; j < yend; j++) { int val = random ? rnd.Next(1, 10) : 1; Console.WriteLine("i={0}\t j={1}\t val={2}", i, j, val); List<int> existing = new List<int>(); //check row for (int k = i; k < i + 1; k++) for (int l = 0; l < 9; l++) if (k != i || l != j) { existing.Add(board[k, l]); } // check col for (int k = 0; k < 9; k++) for (int l = j; l < j + 1; l++) if (k != i || l != j) { existing.Add(board[k, l]); } var all = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; existing = existing.Distinct().ToList(); var candidates = all.Except(existing).ToList(); int count = 0; while (IsDuplicate(ref board, subgrid, i, j, val) == true || existing.Contains(val)) { if (candidates.Count == 0) throw new Exception("Solution not possible"); val = candidates[rnd.Next(0, candidates.Count)]; count++; if (count > 100) throw new Exception("Possibly infinite loop"); // while (IsDuplicate(ref board, x, x+3, y, y+3, val) == true || // IsDuplicate(ref board, 0, 1, 0, 9, val) == true || // IsDuplicate(ref board, 0, 9, 0, 1, val) == true) //val = random ? rnd.Next(1, 10) : (val + 1) % 10; //if (val == 0) val = val + 1; //if (!random) //{ // if (candidates.Count == 0) throw new Exception("Solution not possible"); // val = candidates[rnd.Next(0, candidates.Count)]; //} //count++; //if (!random && count > 40) { PrintBoard(ref board); Console.WriteLine("possible infinite loop at i={0}\t j={1}\t val={2}", i, j, val); Console.ReadLine(); } //Console.WriteLine("Subtituting val for i={0}\t j={1}\t val={2}", i, j, val); } board[i, j] = val; } //PrintBoard(ref board); return true; } catch (Exception e) { //ResetSubgrid(ref board, subgrid); return false; } }
/// <summary>Checks the list of given POC objects by given parents</summary> /// <returns>Modified and checked POC objects</returns> public static List<IdentityDocumentImage> Check( string folderName, List<IdentityDocument> identityDocuments, List<IdentityDocumentImage> identityDocumentImages) { var duplicates = identityDocumentImages .Where(first => identityDocumentImages.Any(second => first != second && first.IdentityDocumentId == second.IdentityDocumentId && first.SequenceNumber == second.SequenceNumber)).ToList(); foreach (var identityDocument in duplicates) { Console.WriteLine("Duplicated pair (Identity Document ID, Sequence Number) in the list of Identity Documents Images - " + identityDocument.IdentityDocumentId + ", " + identityDocument.SequenceNumber); } var orphans = identityDocumentImages .Where(image => identityDocuments.All(document => image.IdentityDocumentId != document.Id)).ToList(); foreach (var image in orphans) { Console.WriteLine("Absent Identity Document ID - " + image.IdentityDocumentId + " - for Image with No - " + image.SequenceNumber); } var absentOnDisk = identityDocumentImages.Where(image => !File.Exists(string.Format( Constants.Blobs.IdentityDocumentImageFormat, folderName, image.IdentityDocumentId, image.SequenceNumber))).ToList(); foreach (var image in absentOnDisk) { Console.WriteLine("Absent file on disk for Identity Document ID - " + image.IdentityDocumentId + ", for Image with No - " + image.SequenceNumber); } var validImages = identityDocumentImages.Except(duplicates).Except(orphans).Except(absentOnDisk).ToList(); foreach (var image in validImages) { image.IdentityDocument = identityDocuments.First(document => document.Id == image.IdentityDocumentId); } return validImages; }
public static SuggestedTournamentRound CreateRandomRound(List<Player> players) { players.Shuffle(); var round = new SuggestedTournamentRound(); var playersSittingOut = CalculatePlayersSittingOutNext(players); round.AddPlayersSittingOut(playersSittingOut); var playingPlayers = players.Except(playersSittingOut).ToList(); List<Player> remainingPlayers; var match = SuggestedMatch.CreateMatchFromFirstFirstFourPlayers(playingPlayers, out remainingPlayers); while (match != null) { round.AddMatch(match); playingPlayers = remainingPlayers; match = SuggestedMatch.CreateMatchFromFirstFirstFourPlayers(playingPlayers, out remainingPlayers); } if (remainingPlayers.Count != 0) { throw new Exception("Was not expecting any remainig players!"); } return round; }
public AssetComponents GetGlobComponentsForAsset(IEnumerable<string> assetPaths, string basePath) { var files = new List<string>(); var excludes = new List<string>(); var dependencies = new List<string>(); foreach (var path in assetPaths) { if (path.StartsWith("!")) { excludes.AddRange(Glob.Expand(Path.Combine(basePath, path.Substring(1))).Select(f => f.FullName)); } else if (path.StartsWith("+")) { dependencies.AddRange(Glob.Expand(Path.Combine(basePath, path.Substring(1))).Select(f => f.FullName)); } else { files.AddRange(Glob.Expand(Path.Combine(basePath, path)).Select(f => f.FullName)); } } excludes.AddRange(dependencies); var components = new AssetComponents(); dependencies.ForEach(o => components.Dependencies.Add(() => ReadFile(o))); files.Except(excludes).ForEach(o => components.Files.Add(() => ReadFile(o))); return components; }
public ActionResult Group_EditLocal(int id) { U_FunctionGroup _functionGroup; if (id == -1) { _functionGroup = new U_FunctionGroup { Id = -1 }; } else { _functionGroup = _inFlowDb.U_FunctionGroups.Find(id); } EditGroupViewModel model = new EditGroupViewModel() { GroupId = _functionGroup.Id, GroupName = _functionGroup.Name }; _functionGroup.Roles.ToList().ForEach(r => model.Roles.Add(new ListViewItemModel() { Id = r.Id, Name = r.Name, Selected = true })); _inFlowDb.U_Roles.ToList().Except(_functionGroup.Roles.ToList()).ToList().ForEach(r => model.Roles.Add(new ListViewItemModel() { Id = r.Id, Name = r.Name, Selected = false })); List<string> assignedUsers = new List<string>(); _functionGroup.Users.ToList().ForEach(u => assignedUsers.Add(u.Username)); assignedUsers.ForEach(u => model.Users.Add(new ListViewItemModel { Name = u, Selected = true })); List<string> allUsers = new List<string>(); _identityDb.Users.ToList().ForEach(u => allUsers.Add(u.UserName)); // _inFlowDb.U_User_FunctionGroups.ToList().ForEach(u => allUsers.Add(u.Username)); allUsers.Except(assignedUsers).ToList().ForEach(u => model.Users.Add(new ListViewItemModel { Name = u, Selected = false })); return View("Group_Edit",model); }
//Update the list of users who should have an authorization code public virtual void UpdateUserList(List<int> users) { lock(authLock) { //Start expiring any user codes that are no longer in the updated list foreach (int key in authCodes.Keys) if (!users.Contains(key)) authCodes[key].StartExpire(10); //Now remove any expired authcodes authCodes = authCodes.Where( x => !(x.Value.Expired && !users.Contains(x.Key))).ToDictionary( x => x.Key, x => x.Value); if (users.Except(authCodes.Keys).Count() > 0) Log("Someone attempted to add users to the authentication server", MyExtensions.Logging.LogLevel.Warning); //Next, add new users by simply adding those which were not already //in the dictionary. // foreach(int user in users.Except(authCodes.Keys)) // RequestAuth(user); //Remember this automatically adds users Log("Users with outstanding authentication codes: " + string.Join(", ", authCodes.Keys), MyExtensions.Logging.LogLevel.Debug); } }
/// <summary> /// Filters the list of <see cref="HttpModule"/> from those that have been added/removed from the system /// across all <see cref="IHttpModuleRegistry"/> with the system. /// </summary> /// <param name="moduleRegistries"></param> /// <returns></returns> protected virtual IList<HttpModule> GetFilteredList(IList<IHttpModuleRegistry> moduleRegistries) { var allInclude = new List<HttpModule>(); var allExclude = new List<HttpModule>(); foreach (var registry in moduleRegistries) { var moduleRegistration = registry.GetModuleRegistrations(); if (moduleRegistration == null || moduleRegistration.Count() == 0) continue; var includeList = moduleRegistration .Where(reg => !reg.IsRemoved) .ToList(); var excludeList = moduleRegistration .Where(reg => reg.IsRemoved) .ToList(); allInclude.AddRange(includeList); allExclude.AddRange(excludeList); } // Get the distinct modules based on the name allExclude = allExclude.Distinct().ToList(); allInclude = allInclude.Distinct().ToList(); return allInclude.Except(allExclude).ToList(); }
public IEnumerable<string> SubscribedLists(string emailAddress) { var result = new List<string>(); try { using (var model = WebServiceDataModel.NewContext()) { var email = (from emailAddressTable in model.EmailAddressTables where emailAddressTable.EmailAddress == emailAddress select emailAddressTable) .FirstOrDefault(); if (email != null) { result = (from emailAddressEmailList in model.EmailAddressEmailLists where emailAddressEmailList.EmailAddressId == email.Id select emailAddressEmailList.EmailList.ListName) .ToList(); result = result .Except(model.UnsubscribedEmails .Where(ue => ue.EmailAddress == emailAddress) .Select(ue => ue.ListName)) .ToList(); } } } catch (Exception exception) { Logger.TraceErr(exception); } return result; }
public Except() { IList<int> firstList = new List<int> { 1, 2, 3, 4, 5 }; IList<int> secondList = new List<int> { 1, 3, 5, 7 }; var exceptNumbers = firstList.Except(secondList); Console.WriteLine("Common numbers between two lists"); foreach (int exceptNumber in exceptNumbers) { Console.WriteLine(exceptNumber); } }
public Tuple<IEnumerable<Player>, IEnumerable<Player>> GenerateTeams(List<Player> selectedPlayers) { int halfCount = (int)Math.Ceiling((decimal)selectedPlayers.Count / 2); decimal totalSum = selectedPlayers.Sum(p => (decimal)p.PointsPerGame); decimal target = decimal.Divide(totalSum, 2); List<IEnumerable<Player>> team1combinations = selectedPlayers.Combinations(halfCount).ToList(); List<Tuple<IEnumerable<Player>, IEnumerable<Player>>> solutions = new List<Tuple<IEnumerable<Player>, IEnumerable<Player>>>(); decimal bestDifferential = -1; foreach (var team1 in team1combinations.Select(p => p.ToList())) { var team1Temp = team1; decimal team1Score = team1Temp.Sum(p => (decimal)p.PointsPerGame); var team2Temp = selectedPlayers.Except(team1Temp).ToList(); decimal team2Score = team2Temp.Sum(p => (decimal)p.PointsPerGame); decimal totalDifferential = Math.Abs(team1Score - target) + Math.Abs(team2Score - target); if (bestDifferential == -1 || totalDifferential <= bestDifferential) { if (totalDifferential < bestDifferential) // Everything found so far is not a solution, so wipe the list solutions = new List<Tuple<IEnumerable<Player>, IEnumerable<Player>>>(); solutions.Add(new Tuple<IEnumerable<Player>, IEnumerable<Player>>(team1Temp, team2Temp)); bestDifferential = totalDifferential; } } _shuffler.Shuffle(solutions); return solutions.First(); }
// disable initial readyness for trade and remove all but one muffalo, transferring all goods there public void ModifycaravanGroup(ref List<Pawn> pawns) { var muffaloChosen = false; var firstMuffalo = new Pawn(); var removeList = new List<Pawn>(); foreach (var pawn in pawns) { // disable initial readyness to trade pawn.mindState.wantsToTradeWithColony = false; // transfer all items from other muffaloes to the main one if (pawn.kindDef == PawnKindDef.Named("PackMuffalo")) { if (!muffaloChosen) { firstMuffalo = pawn; muffaloChosen = true; } else { for (var i = 0; i < pawn.inventory.container.Count; i++) { firstMuffalo.inventory.container.TryAdd(pawn.inventory.container[i]); } pawn.Destroy(); removeList.Add(pawn); } } } pawns = new List<Pawn>(pawns.Except(removeList)); }
public List<Tile> AccurateShotsHighlights(Vector2 originLocation, Vector2 mousePosition,int mouseArea, int minrange, int maxrange) { Color targetColor = new Color(ColorAdapter(0),ColorAdapter(255),ColorAdapter(0),1); Color AreaColor = new Color(ColorAdapter(153),ColorAdapter(153),ColorAdapter(0),1); List<Tile> MouseHighlightedTiles = new List<Tile>(); List<Tile> TotalArea = new List<Tile>(); List<Tile> IgnoreCloserTiles = new List<Tile>(); IgnoreCloserTiles = TileHighlight.FindHighlight(map[(int)originLocation.x][(int)originLocation.y], minrange, true,true); //Vector2[]_ignoreCloserTiles = IgnoreCloserTiles.Select(x=>x.gridPosition).ToArray(); TotalArea = TileHighlight.FindHighlight(map[(int)originLocation.x][(int)originLocation.y],maxrange,true,true); var _AreaHighlightedTiles = TotalArea.Except(IgnoreCloserTiles); List <Tile> AreaHighlighted = _AreaHighlightedTiles.ToList(); MouseHighlightedTiles = TileHighlight.FindHighlight(map[(int)mousePosition.x][(int)mousePosition.y], mouseArea, true,true); var _ActuallyMouse = AreaHighlighted.Intersect(MouseHighlightedTiles); List<Tile> IntesectionArea = _ActuallyMouse.ToList(); foreach (Tile t in AreaHighlighted) { t.visual.transform.GetComponent<Renderer>().materials[0].color = AreaColor; } foreach (Tile t in IntesectionArea) { t.visual.transform.GetComponent<Renderer>().materials[0].color = targetColor; } return IntesectionArea; }
public List<Widget> OrderManyParts(Warehouse wh, List<String> widgetsOrdered, List<SpecedWidget> specedWidgets) { var orderedWidgetsThatAreSpeced = specedWidgets.Where(w => widgetsOrdered.Contains(w.WidgetName)); //Widgets that we know we have the spec for. var orderedWidgetsThatAreNotSpeced = widgetsOrdered.Except(orderedWidgetsThatAreSpeced.Select(s => s.WidgetName)); //Widgets that we do not have the spec for. var widgetsAssembled = new List<Widget>(); foreach (var widgetThatWeCantOrder in orderedWidgetsThatAreNotSpeced)//Display messages to let users know that we cannot fulfill their order on these items { Trace.WriteLine(String.Format("We currently do not produce widget {0}. Please resubmit your request for this item at a later date.", widgetThatWeCantOrder)); } foreach (var widget in orderedWidgetsThatAreSpeced) { var w = new Widget(); var assembled = true; foreach (var part in widget.Parts) { try { for (var i = 0; i < part.NumberOfPart; i++) { w.Parts.Add(OrderOnePart(part.PartId, widget.WidgetName, wh)); } } catch (PartOrderException) { Trace.WriteLine(String.Format("Ordering failed for part {0}, for widget {1}. This part does not exist in our system at the moment.", part.PartId, widget.WidgetName)); assembled = false; } } if (assembled) widgetsAssembled.Add(w); } return widgetsAssembled; }
public static void Main () { List<int> first = new List<int> (); List<int> second = new List<int> (); IEnumerable<int> q = first.Except(second); }
// record any offline sites not already recorded public void RecordNewOfflineSites(List<string> sitesRecordedAsOffline, List<string> offlineSites) { // for all sites in sitesRecordedAsOffline but not in offlineSites, add details of site to table IEnumerable<string> newOfflineSites = offlineSites.Except(sitesRecordedAsOffline); foreach (string newOfflineSite in newOfflineSites) _repository.RecordNewOfflineSite(newOfflineSite); }
// remove sites that have come online from offline site table public void RemoveOnlineSites(List<string> sitesRecordedAsOffline, List<string> offlineSites) { // for all sites present in sitesRecordedAsOffline but not in offlineSites, remove those sites from table IEnumerable<string> onlineSites = sitesRecordedAsOffline.Except(offlineSites); foreach (string onlineSite in onlineSites) _repository.RemoveOnlineSite(onlineSite); }
/// <summary> /// Load logs from another textualizer to this. used to merge deserialized textualizer with an active one. /// </summary> public void LoadHistory(List<ProcessLog> logs) { var existing = logs.Where(nl => ActiveLogs.Any(ol => ol.Process.Equals(nl.Process))).ToArray(); var nonex = logs.Except(existing); ActiveLogs.AddRange(nonex); foreach (var nl in existing) { ActiveLogs.FirstOrDefault(ol=>ol.Process==nl.Process)?.Logs.AddRange(nl.Logs); } }
public Type[] GetAllReferencedHandleInterfaceTypes(Type handleInterfaceType) { List<Type> list = new List<Type>(); this.GetReferencedHandleInterfaceTypes(handleInterfaceType, list); return list .Except(new[] { handleInterfaceType }) .ToArray(); }
// Returns only the keys that were pressed keys since its last invocation. public List<Keys> keyPress(List<Keys> keys) { var newlyPressedKeys = keys.Except(lastKeys); lastKeys = keys; return newlyPressedKeys.ToList<Keys>(); }
private List<Link> filtraLinks(List<Link> aFiltrar) { List<Link> historico = histBLL.getHistorico(); //IEnumerable<Link> resultado = (IEnumerable<Link>) historico; List<Link> final = new List<Link>(aFiltrar.Except(historico)); //return aFiltrar.Except(historico).ToList().ConvertAll(new Converter<Link,Link>( Link => Link )); return final; }
public static void GenerateDataSets(List<double[]> data, out List<double[]> trainData, out List<double[]> testData, double ratio) { int trainDataLength = (int)Math.Floor(data.Count*ratio); var r = new Random(); trainData = data.OrderBy(x => r.Next()).Take(trainDataLength).ToList(); testData = data.Except(trainData).ToList(); }
private void ChangeLights(Colors light) { if (light == Colors.Unknown) throw new ArgumentException("setting unknown color not supported", "light"); // queue of commands List<CmdPart> cmds = new List<CmdPart>(); // turn on the desired color (if any) if (light != Colors.None && light != Colors.Unknown) cmds.Add(new CmdPart(GetUnitCode(light), true)); // turn off other lights // light = none last = ___ clear all starting with last // light = color last = none do nothing // light = color last = color do nothing // light = color last = other turn off last // light = color last = unknown turn off other colors var lights = new List<Colors> { Colors.Green, Colors.Yellow, Colors.Red }; var turnoff = new List<Colors>(); if (light == Colors.None) { if (lights.Contains(LastLight)) turnoff.Add(LastLight); turnoff.AddRange(lights.Except(turnoff)); } else if (LastLight == Colors.None) { } else if (LastLight == Colors.Unknown) { turnoff.AddRange(lights.Except(new[] { light })); } else if (light != LastLight) turnoff.Add(LastLight); turnoff.ForEach(a => cmds.Add(new CmdPart(GetUnitCode(a), false))); // make sure the specified port is on the computer var ports = SerialPort.GetPortNames(); if (!ports.Contains(settings.ComPort)) { var msg = String.Format("The ComPort name specified in settings ({0}) is not one of the ports on the machine ({1}). Please update your settings.", settings.ComPort, ports.Length == 0 ? "no ports detected" : String.Join(", ", ports)); MessageBox.Show(msg, "ComPort Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // queue up the list of commands to run QueueCommands(cmds); // remember the last set light LastLight = light; }
public bool UpdateUserRepositories(string userId, List <GithubRepository> repos) { var user = _context.Users.FirstOrDefault(x => x.UserId == userId); if (user == null) { user = new User { UserId = userId }; _context.Users.Add(user); _context.SaveChanges(); } var existingList = GetUserRepositories(userId); var deleted = existingList?.Except(repos, x => x.FullName)?.ToList() ?? new List <GithubRepository>(); var added = repos?.Except(existingList, x => x.FullName)?.ToList() ?? new List <GithubRepository>(); foreach (var add in added) { var existingRepo = _context.Repositories.FirstOrDefault(x => x.FullName == add.FullName); if (existingRepo != null) { add.Id = existingRepo.Id; } } var reposToAdd = added.Where(x => x.Id == 0).ToList(); if (reposToAdd.Any()) { _context.Repositories.AddRange(reposToAdd); _context.SaveChanges(); } _context.Set <UserRepository>().AddRange(added.Select(x => new UserRepository { User = user, Repository = x })); _context.Set <UserRepository>().RemoveRange(deleted.Select(x => new UserRepository { User = user, Repository = x })); _context.SaveChanges(); return(true); }
public IList <Route> Build(IList <Depot> deports, VehicleInfo venicleInfo, List <Request> requests) { BruteForceCounter.MaximumOption = 0; BruteForceCounter.CurrentOption = 0; BruteForceCounter.MinPathDistance = 0; BruteForceCounter.MinPath = null; while (true) { var routes = new List <Route>(); var unservicedRequests = requests; var venicles = CreateVenicles(deports); foreach (var venicle in venicles) { var route = BuildRoute(venicle, unservicedRequests); if (route == null) { continue; } unservicedRequests = unservicedRequests.Except(route.Requests).ToList(); routes.Add(route); } BruteForceCounter.PossibleRequests = BruteForceCounter.PossibleRequests.Concat(routes.SelectMany(r => r.Requests)).ToList(); if (unservicedRequests.Count() == requests.Count()) { if (BruteForceCounter.MinPath == null) { throw new ImpossibleRouteException("Can service all requests", requests.Except(BruteForceCounter.PossibleRequests).ToList()); } else { return(BruteForceCounter.MinPath); } } BruteForceCounter.MaximumOption++; BruteForceCounter.CurrentOption = 0; var totalDistance = routes.Sum(r => r.GetTotalDistance()); if (unservicedRequests.Any() || !(BruteForceCounter.MinPathDistance > totalDistance || BruteForceCounter.MinPath == null)) { continue; } BruteForceCounter.MinPathDistance = totalDistance; BruteForceCounter.MinPath = routes; } }
/// <summary> /// Downloads files required for updating according to <see cref="Type"/>. /// </summary> /// <param name="client"><see cref="WebClient"/> to be used for downloading.</param> /// <param name="updatePath">Path to store downloaded files.</param> public void Download(WebClient client, string updatePath) { var cancelArgs = new CancelEventArgs(false); DownloadProgressEventArgs downloadArgs = null; int fileDownloading = 0; void downloadComplete(object sender, AsyncCompletedEventArgs args) { lock (args.UserState) { Monitor.Pulse(args.UserState); } } void downloadProgressChanged(object sender, DownloadProgressChangedEventArgs args) { downloadArgs = new DownloadProgressEventArgs(args, fileDownloading, FilesToDownload); if (OnDownloadProgress(downloadArgs)) { ((WebClient)sender).CancelAsync(); } } switch (Type) { case ModDownloadType.Archive: { var uri = new Uri(Url); if (!uri.Host.EndsWith("github.com", StringComparison.OrdinalIgnoreCase)) { var request = (HttpWebRequest)WebRequest.Create(uri); request.Method = "HEAD"; var response = (HttpWebResponse)request.GetResponse(); uri = response.ResponseUri; response.Close(); } string filePath = Path.Combine(updatePath, uri.Segments.Last()); var info = new FileInfo(filePath); if (info.Exists && info.Length == Size) { if (OnDownloadCompleted(cancelArgs)) { return; } } else { if (OnDownloadStarted(cancelArgs)) { return; } client.DownloadFileCompleted += downloadComplete; client.DownloadProgressChanged += downloadProgressChanged; ++fileDownloading; var sync = new object(); lock (sync) { client.DownloadFileAsync(uri, filePath, sync); Monitor.Wait(sync); } client.DownloadProgressChanged -= downloadProgressChanged; client.DownloadFileCompleted -= downloadComplete; if (cancelArgs.Cancel || downloadArgs?.Cancel == true) { return; } if (OnDownloadCompleted(cancelArgs)) { return; } } string dataDir = Path.Combine(updatePath, Path.GetFileNameWithoutExtension(filePath)); if (!Directory.Exists(dataDir)) { Directory.CreateDirectory(dataDir); } if (OnExtracting(cancelArgs)) { return; } Process process = Process.Start( new ProcessStartInfo("7z.exe", $"x -aoa -o\"{dataDir}\" \"{filePath}\"") { UseShellExecute = false, CreateNoWindow = true }); if (process != null) { process.WaitForExit(); } else { throw new NullReferenceException("Failed to create 7z process"); } string workDir = Path.GetDirectoryName(ModInfo.GetModFiles(new DirectoryInfo(dataDir)).FirstOrDefault()); if (string.IsNullOrEmpty(workDir)) { throw new DirectoryNotFoundException($"Unable to locate mod.ini in \"{dataDir}\""); } string newManPath = Path.Combine(workDir, "mod.manifest"); string oldManPath = Path.Combine(Folder, "mod.manifest"); if (OnParsingManifest(cancelArgs)) { return; } if (!File.Exists(newManPath) || !File.Exists(oldManPath)) { CopyDirectory(new DirectoryInfo(workDir), Directory.CreateDirectory(Folder)); Directory.Delete(dataDir, true); if (File.Exists(filePath)) { File.Delete(filePath); } return; } if (OnParsingManifest(cancelArgs)) { return; } List <ModManifestEntry> newManifest = ModManifest.FromFile(newManPath); if (OnApplyingManifest(cancelArgs)) { return; } List <ModManifestEntry> oldManifest = ModManifest.FromFile(oldManPath); List <string> oldFiles = oldManifest.Except(newManifest) .Select(x => Path.Combine(Folder, x.FilePath)) .ToList(); foreach (string file in oldFiles) { if (File.Exists(file)) { File.Delete(file); } } RemoveEmptyDirectories(oldManifest, newManifest); foreach (ModManifestEntry file in newManifest) { string dir = Path.GetDirectoryName(file.FilePath); if (!string.IsNullOrEmpty(dir)) { string newDir = Path.Combine(Folder, dir); if (!Directory.Exists(newDir)) { Directory.CreateDirectory(newDir); } } var sourceFile = new FileInfo(Path.Combine(workDir, file.FilePath)); var destFile = new FileInfo(Path.Combine(Folder, file.FilePath)); if (destFile.Exists) { destFile.Delete(); } sourceFile.Attributes &= ~FileAttributes.ReadOnly; sourceFile.MoveTo(destFile.FullName); } File.Copy(newManPath, oldManPath, true); void removeReadOnly(DirectoryInfo dir) { foreach (DirectoryInfo d in dir.GetDirectories()) { removeReadOnly(d); d.Attributes &= ~FileAttributes.ReadOnly; } } removeReadOnly(new DirectoryInfo(dataDir)); Directory.Delete(dataDir, true); File.WriteAllText(Path.Combine(Folder, "mod.version"), Updated.ToString(DateTimeFormatInfo.InvariantInfo)); if (File.Exists(filePath)) { File.Delete(filePath); } break; } case ModDownloadType.Modular: { List <ModManifestDiff> newEntries = ChangedFiles .Where(x => x.State == ModManifestState.Added || x.State == ModManifestState.Changed) .ToList(); var uri = new Uri(Url); string tempDir = Path.Combine(updatePath, uri.Segments.Last()); if (!Directory.Exists(tempDir)) { Directory.CreateDirectory(tempDir); } var sync = new object(); foreach (ModManifestDiff i in newEntries) { string filePath = Path.Combine(tempDir, i.Current.FilePath); string dir = Path.GetDirectoryName(filePath); if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) { Directory.CreateDirectory(dir); } if (OnDownloadStarted(cancelArgs)) { return; } var info = new FileInfo(filePath); ++fileDownloading; if (!info.Exists || info.Length != i.Current.FileSize || !i.Current.Checksum.Equals(ModManifestGenerator.GetFileHash(filePath), StringComparison.OrdinalIgnoreCase)) { client.DownloadFileCompleted += downloadComplete; client.DownloadProgressChanged += downloadProgressChanged; lock (sync) { client.DownloadFileAsync(new Uri(uri, i.Current.FilePath), filePath, sync); Monitor.Wait(sync); } client.DownloadProgressChanged -= downloadProgressChanged; client.DownloadFileCompleted -= downloadComplete; info.Refresh(); if (info.Length != i.Current.FileSize) { throw new Exception(string.Format("Size of downloaded file \"{0}\" ({1}) differs from manifest ({2}).", i.Current.FilePath, SizeSuffix.GetSizeSuffix(info.Length), SizeSuffix.GetSizeSuffix(i.Current.FileSize))); } string hash = ModManifestGenerator.GetFileHash(filePath); if (!i.Current.Checksum.Equals(hash, StringComparison.OrdinalIgnoreCase)) { throw new Exception(string.Format("Checksum of downloaded file \"{0}\" ({1}) differs from manifest ({2}).", i.Current.FilePath, hash, i.Current.Checksum)); } } if (cancelArgs.Cancel || downloadArgs?.Cancel == true) { return; } if (OnDownloadCompleted(cancelArgs)) { return; } } client.DownloadFileCompleted += downloadComplete; lock (sync) { client.DownloadFileAsync(new Uri(uri, "mod.manifest"), Path.Combine(tempDir, "mod.manifest"), sync); Monitor.Wait(sync); } client.DownloadFileCompleted -= downloadComplete; // Handle all non-removal file operations (move, rename) List <ModManifestDiff> movedEntries = ChangedFiles.Except(newEntries) .Where(x => x.State == ModManifestState.Moved) .ToList(); if (OnApplyingManifest(cancelArgs)) { return; } // Handle existing entries marked as moved. foreach (ModManifestDiff i in movedEntries) { ModManifestEntry old = i.Last; // This would be considered an error... if (old == null) { continue; } string oldPath = Path.Combine(Folder, old.FilePath); string newPath = Path.Combine(tempDir, i.Current.FilePath); string dir = Path.GetDirectoryName(newPath); if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.Copy(oldPath, newPath, true); } // Now move the stuff from the temporary folder over to the working directory. foreach (ModManifestDiff i in newEntries.Concat(movedEntries)) { string tempPath = Path.Combine(tempDir, i.Current.FilePath); string workPath = Path.Combine(Folder, i.Current.FilePath); string dir = Path.GetDirectoryName(workPath); if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.Copy(tempPath, workPath, true); } // Once that has succeeded we can safely delete files that have been marked for removal. List <ModManifestDiff> removedEntries = ChangedFiles .Where(x => x.State == ModManifestState.Removed) .ToList(); foreach (string path in removedEntries.Select(i => Path.Combine(Folder, i.Current.FilePath)).Where(File.Exists)) { File.Delete(path); } // Same for files that have been moved. foreach (string path in movedEntries .Where(x => newEntries.All(y => y.Current.FilePath != x.Last.FilePath)) .Select(i => Path.Combine(Folder, i.Last.FilePath)).Where(File.Exists)) { File.Delete(path); } string oldManPath = Path.Combine(Folder, "mod.manifest"); string newManPath = Path.Combine(tempDir, "mod.manifest"); if (File.Exists(oldManPath)) { List <ModManifestEntry> oldManifest = ModManifest.FromFile(oldManPath); List <ModManifestEntry> newManifest = ModManifest.FromFile(newManPath); // Remove directories that are now empty. RemoveEmptyDirectories(oldManifest, newManifest); } // And last but not least, copy over the new manifest. File.Copy(newManPath, oldManPath, true); break; } default: throw new ArgumentOutOfRangeException(); } }
static void Main(string[] args) { List <Planet> planets = LoadData(); //Opgave 1 //Console.WriteLine("Opgave 1:"); //var queryall = from planet in planets // select planet; //foreach (Planet item in queryall) //{ // Console.WriteLine(item.Name); // Console.WriteLine(item.Diameter); //} //Opgave 1 Console.WriteLine("Opgave 1:"); var queryBeginM = from planet in planets where planet.Name.StartsWith("M") select planet; foreach (Planet item in queryBeginM) { Console.WriteLine(item.Name); } Console.WriteLine(); //Opgave 2 Console.WriteLine("Opgave 2:"); var queryContainsY = from planet in planets where planet.Name.Contains("y") || planet.Name.Contains("Y") select planet; foreach (Planet item in queryContainsY) { Console.WriteLine(item.Name); } Console.WriteLine(); //Opgave 3 Console.WriteLine("Opgave 3:"); var queryLength = from planet in planets where planet.Name.Length > 9 && planet.Name.Length < 15 select planet; foreach (Planet item in queryLength) { Console.WriteLine(item.Name); } Console.WriteLine(); //Opgave 4 Console.WriteLine("Opgave 4:"); var query = from planet in planets where planet.Name.IndexOf("a", 1, 1) > -1 && planet.Name.EndsWith("e") select planet; foreach (Planet item in query) { Console.WriteLine(item.Name); } Console.WriteLine(); //Opgave 5 Console.WriteLine("Opgave 5:"); var query5 = from planet in planets where planet.RotationPeriod > 40 orderby planet.RotationPeriod select planet; foreach (Planet item in query5) { Console.WriteLine(item.Name); } Console.WriteLine(); //Opgave 6 Console.WriteLine("Opgave 6:"); var query6 = from planet in planets where planet.RotationPeriod > 10 && planet.RotationPeriod < 20 orderby planet.Name select planet; foreach (Planet item in query6) { Console.WriteLine(item.Name); } Console.WriteLine(); //Opgave 7 Console.WriteLine("Opgave 7:"); var query7 = from planet in planets where planet.RotationPeriod > 30 orderby planet.Name, planet.RotationPeriod select planet; foreach (Planet item in query7) { Console.WriteLine(item.Name); } Console.WriteLine(); //Opgave 8 Console.WriteLine("Opgave 8:"); var query8 = from planet in planets where (planet.RotationPeriod < 30 || planet.SurfaceWater > 50) && planet.Name.Contains("ba") orderby planet.Name, planet.SurfaceWater, planet.RotationPeriod select planet; foreach (Planet item in query8) { Console.WriteLine(item.Name); } Console.WriteLine(); //Opgave 9 Console.WriteLine("Opgave 9:"); var query9 = from planet in planets where planet.SurfaceWater > 0 orderby planet.SurfaceWater descending select planet; foreach (Planet item in query9) { Console.WriteLine(item.Name); } Console.WriteLine(); //Opgave 10 Console.WriteLine("Opgave 10:"); var query10 = planets.Where(p => p.Population > 0 && p.Diameter > 0).OrderBy(p => (((4 * Math.PI) * Math.Pow((0.5 * p.Diameter), 2)) / p.Population)); //var query10 = planets.Where(p => p.Population != 0 || p.Diameter != 0).OrderBy(p => ((4 * Math.PI * Math.Pow((0.5 * p.Diameter), 2)) / p.Population)); foreach (Planet item in query10) { Console.WriteLine(item.Name); } Console.WriteLine(); //Opgave 11 Console.WriteLine("Opgave 11:"); List <Planet> norotation = (from planet in planets where planet.RotationPeriod > 0 select planet).ToList(); var query11 = planets.Except(norotation, new NameComparer()); //var query10 = planets.Where(p => p.Population != 0 || p.Diameter != 0).OrderBy(p => ((4 * Math.PI * Math.Pow((0.5 * p.Diameter), 2)) / p.Population)); foreach (Planet item in query11) { Console.WriteLine(item.Name); } Console.WriteLine(); //Opgave 12 Console.WriteLine("Opgave 12:"); var query12_1 = planets.Where(p => p.Name.StartsWith("A") || p.Name.EndsWith("s")); //var query12_2terrain = planets.Where(p => p.Name.StartsWith("A") && p.Name.EndsWith("s")); var query12_2 = planets.Where(p => p.Terrain != null && p.Terrain.Contains("rainforests")); var query12 = query12_1.Union(query12_2); //var query10 = planets.Where(p => p.Population != 0 || p.Diameter != 0).OrderBy(p => ((4 * Math.PI * Math.Pow((0.5 * p.Diameter), 2)) / p.Population)); foreach (Planet item in query12) { Console.WriteLine(item.Name); } Console.WriteLine(); //Opgave 13 Console.WriteLine("Opgave 13:"); var query13 = planets.Where(p => p.Terrain != null && (p.Terrain.Contains("deserts") || p.Terrain.Contains("desert"))); //var query10 = planets.Where(p => p.Population != 0 || p.Diameter != 0).OrderBy(p => ((4 * Math.PI * Math.Pow((0.5 * p.Diameter), 2)) / p.Population)); foreach (Planet item in query13) { Console.WriteLine(item.Name); } Console.WriteLine(); //Opgave 14 Console.WriteLine("Opgave 14:"); var query14 = planets.Where(p => p.Terrain != null && (p.Terrain.Contains("swamp") || p.Terrain.Contains("swamps"))).OrderBy(x => x.RotationPeriod).ThenBy(x => x.Name); //var query10 = planets.Where(p => p.Population != 0 || p.Diameter != 0).OrderBy(p => ((4 * Math.PI * Math.Pow((0.5 * p.Diameter), 2)) / p.Population)); foreach (Planet item in query14) { Console.WriteLine(item.Name); } Console.WriteLine(); //Opgave 15 Console.WriteLine("Opgave 15:"); Regex regularExpression = new Regex("a{2}|e{2}|i{2}|o{2}|y{2}$|u{2}"); var query15 = planets.Where(p => regularExpression.IsMatch(p.Name)); //var query10 = planets.Where(p => p.Population != 0 || p.Diameter != 0).OrderBy(p => ((4 * Math.PI * Math.Pow((0.5 * p.Diameter), 2)) / p.Population)); foreach (Planet item in query15) { Console.WriteLine(item.Name); } Console.WriteLine(); //Opgave 16 Console.WriteLine("Opgave 16:"); Regex regularExpression2 = new Regex("k{2}|l{2}|r{2}|n{2}"); var query16 = planets.Where(p => regularExpression2.IsMatch(p.Name)).OrderByDescending(x => x.Name); //var query10 = planets.Where(p => p.Population != 0 || p.Diameter != 0).OrderBy(p => ((4 * Math.PI * Math.Pow((0.5 * p.Diameter), 2)) / p.Population)); foreach (Planet item in query16) { Console.WriteLine(item.Name); } Console.ReadKey(); }
/// <summary> /// Generates polygons and nodegraphs using custom algorithm /// </summary> /// <param name="points"></param> /// <param name="pointWidth"></param> /// <param name="pointHeight"></param> private void GenerateVoronoi(List <Vector2> points, int pointWidth, int pointHeight) { var startTime = DateTime.Now; Polygons = new List <Polygon>(); _voronoiVertices = new List <VoronoiVertex>(); // assigns the max width and height of the "grid" of points used SetGraphLimits(pointWidth, pointHeight); List <Node <Polygon> > nodes = new List <Node <Polygon> >(); // generate an empty node for each polygon foreach (var point in points) { nodes.Add(new Node <Polygon>(new Polygon() { Centre = point })); } // go trough all "sites" for (int pointIndex = 0; pointIndex < points.Count; pointIndex++) { Polygon poly = nodes[pointIndex].Data; int mapX, mapY; // grid position of the polygon mapX = pointIndex % pointWidth; mapY = pointIndex / pointHeight; // the grid point surrounding the current point List <int> surroundingPoints = GetSurrouding(mapX, mapY); // check all the surrounding grid points in sets of 3 for (int point0i = 0; point0i < surroundingPoints.Count; point0i++) { for (int point1i = 0; point1i < surroundingPoints.Count; point1i++) { if (point0i == point1i) { continue; } // we skip polygons with more vertices than our limit if (poly.Vertices.Count > _maxPolyVertices) { // "double break" goto end; } Vector2 vertex; // does a circumcircle check if (CheckCircle(pointIndex, surroundingPoints[point0i], surroundingPoints[point1i], ref surroundingPoints, ref points, out vertex)) { // our vertex indicates a shared edge with two other sites, add them to the nodegraph connections float angle = Mathf.Atan2(vertex.y - poly.Centre.y, vertex.x - poly.Centre.x) * Mathf.Rad2Deg + 180f; if (!nodes[pointIndex].ConnectionAngles.ContainsKey(angle)) { if (!nodes[pointIndex].ConnectionAngles.ContainsValue(nodes[surroundingPoints[point0i]])) { nodes[pointIndex].ConnectionAngles.Add(angle, nodes[surroundingPoints[point0i]]); } else { nodes[pointIndex].ConnectionAngles.Add(angle, nodes[surroundingPoints[point1i]]); } } // our vertex is added to the polygon poly.AddVertex(vertex); } } } end: // orders the vertices of the polygon clockwise poly.Order(); poly.Node = nodes[pointIndex]; Polygons.Add(poly); } // ensures there are no double connections in the nodelist _polygons = _polygons.Distinct().ToList(); // sort node angles nodes.ForEach((node) => node.ConnectionAngles = node.ConnectionAngles.OrderBy(a => a.Key).ToDictionary(x => x.Key, x => x.Value)); // removes OOB polygons var oobPolies = _polygons.Where( (Polygon p) => !p.Vertices.TrueForAll((Vector2 vert) => _pointMap.InBound(vert)) ); oobPolies.ToList().ForEach((poly) => { poly.Node.ConnectionAngles.Values.ToList().ForEach( (connectedPoly) => { float key = connectedPoly.ConnectionAngles.FirstOrDefault(x => x.Value.Data.Centre == poly.Centre).Key; connectedPoly.ConnectionAngles.Remove(key); } ); }); _polygons = _polygons.Except(oobPolies).ToList(); // arbitrary start to our nodegraph _nodeGraph = nodes[0]; }
public void ApplyFeatureSelection_Step2() { // Process only the first topic from the sample var xmlClasses = ProcessingTopicsDictionary(); var globalEntropy = CalculateEntropy(xmlClasses); // Entropy DONE Console.WriteLine("\n[:::Calculated Entropy for attribute set : {0} :::]", globalEntropy); Console.WriteLine(">> Classes frequency after feature selection :"); foreach (KeyValuePair <string, int> pair in xmlClasses) { Console.WriteLine("{0}:{1} ", pair.Key, pair.Value); } // Needed because of first topic filtering AdjustVectorsAndTopicsDictionary(); // Compute GainRatio -> took only 10% most relevant attributes var GainRatioList = ComputeInfoGain(globalEntropy); var arffAttributes = CreateNewIndexDomainAfter10ProcFiltering(GetRelevantAttrFromGainRatio(GainRatioList, 10));/// GainRatioList.Clear(); //-------------------------------------------------------------------------------------------------------------------- // Generate .arff export file// Extract Target Classes string workingDirectory = Environment.CurrentDirectory; string projectTestDir = Directory.GetParent(workingDirectory).Parent.Parent.FullName + "\\Export-Test.arff"; string projectTrainingDir = Directory.GetParent(workingDirectory).Parent.Parent.FullName + "\\Export-Training.arff"; var rareIndexes = new List <int>(); var rareVectorsXML = GetRareVectors(arffAttributes, rareIndexes); var filteredVectorXML = new List <List <byte> >(VectorXMLs.Except(rareVectorsXML)); var targetClasses = GetFilteredTargetClasses(rareIndexes); var randomTestIndexes = new List <int>(); var VectorXMLTestSet = getRandom30ProcOfVectorXMLEntries(filteredVectorXML, randomTestIndexes); AttachAttributesInExport_arff(projectTestDir, arffAttributes, targetClasses); AttachAttributesInExport_arff(projectTrainingDir, arffAttributes, targetClasses); int lineCt = 0; // Writing the trainingSet file foreach (var list in filteredVectorXML.Except(VectorXMLTestSet)) { string vectLine = ""; for (int i = 0; i < list.Count; i++) { foreach (var itemAttr in arffAttributes) { if (i == itemAttr.index && list[i] != 0) { vectLine += itemAttr.newIndex + ":" + list[i] + ",";/// } } } using (FileStream fs = new FileStream(projectTrainingDir, FileMode.Append)) { if (vectLine != "") { var stringBuilder = new StringBuilder(vectLine); stringBuilder.Remove(vectLine.LastIndexOf(","), 1); stringBuilder.Insert(vectLine.LastIndexOf(","), " # "); while (randomTestIndexes.Contains(lineCt)) { lineCt++; } vectLine = stringBuilder.ToString() + targetClasses[lineCt]; StreamWriter sw = new StreamWriter(fs); sw.WriteLine(vectLine); sw.Flush(); } if (lineCt < targetClasses.Count) { lineCt++; } } } Console.WriteLine("\n>> 70% Training Set exported successfully!"); // Writing the testSET file lineCt = 0; foreach (var list in VectorXMLTestSet) { string vectLine = ""; for (int i = 0; i < list.Count; i++) { foreach (var itemAttr in arffAttributes) { if (i == itemAttr.index && list[i] != 0) { vectLine += itemAttr.newIndex + ":" + list[i] + ",";/// } } } using (FileStream fs = new FileStream(projectTestDir, FileMode.Append)) { if (vectLine != "") { var stringBuilder = new StringBuilder(vectLine); stringBuilder.Remove(vectLine.LastIndexOf(","), 1); stringBuilder.Insert(vectLine.LastIndexOf(","), " # "); vectLine = stringBuilder.ToString() + targetClasses[randomTestIndexes[lineCt]]; StreamWriter sw = new StreamWriter(fs); sw.WriteLine(vectLine); sw.Flush(); } if (lineCt < targetClasses.Count) { lineCt++; } } } Console.WriteLine(">> 30% Test Set exported successfully!\n"); }
private void RemoveElement(string eventId) { var items = _registeredEvents.Where(x => x.Equals(eventId)); _registeredEvents = _registeredEvents.Except(items).ToList(); }
public IEnumerable <Item> GetResults(Search <Item> search) { List <Item> results = (List <Item>)db.SPGetResults(search); List <Item> filteredResults = new List <Item>(); List <string> searchTags = new List <string>(); bool searchForTags = false; if (search.Tags != null) { if (search.Tags.Length > 0) { searchForTags = true; foreach (Tag tag in search.Tags) { searchTags.Add(tag.Tag_id); } } } for (int i = 0; i < results.Count; i++) { results[i].Tags = (List <Tag>)db.SPGetById(new Tag(), "SelectByItemId", results[i].Item_id);//Add tags for each item if (searchForTags) { if (results[i].Tags.Count >= searchTags.Count) { List <string> resultTags = new List <string>(); foreach (Tag tag in results[i].Tags) { resultTags.Add(tag.Tag_id); } if (!searchTags.Except(resultTags).Any())//This checks whether there are any elements in searchTags which aren't in resultTags - and then inverts the result. { filteredResults.Add(results[i]); } } } } List <string> searchWords = null; search.Title_Words = search.Title_Words ?? "";//turn null into "" //equals to (search.Title_Words = search.Title_Words == null ? "" : search.Title_Words;) searchWords = search.Title_Words.Trim(' ') != "" //check if search title has a real value ? search.Title_Words.Split(' ').ToList() //if this condition is true: searchWords= list of search words : null; //if this condition is true: title words =null; if (searchForTags) { if (searchWords != null) { //List<Item> filteredResultsWords = filteredResults.Where(item => item.ContainWords(searchWords)).ToList(); return(filteredResults.Where(item => item.ContainWords(searchWords)).ToList()); } return(filteredResults); } else { if (searchWords != null) { //List<Item> resultsWords = results.Where(item => item.ContainWords(searchWords)).ToList(); return(results.Where(item => item.ContainWords(searchWords)).ToList()); } return(results); } }
public Task SolveSelection() { try { if (mode == Enums.eEditMode.Solve) { SuspendLayout(); // Check if there are selected cells if (!selectedCells.Any()) { throw new MinificationException("Please select some cells to join."); } var selected_ones = ones.Except(zeros).Intersect(selectedCells); var selected_zeros = zeros.Except(ones).Intersect(selectedCells); var selected_dontcares = zeros.Intersect(ones).Intersect(selectedCells); // Find out the value of the loop bool value; if (selected_ones.Any()) { if (selected_zeros.Any()) { throw new MinificationException("Selected minterms must have the same value."); } else { value = true; } } else { if (selected_zeros.Any()) { value = false; } else { throw new MinificationException("Selected minterms cannot all be don't cares."); } } var result = QuineMcCluskey.QuineMcCluskeySolver.QMC_Solve(value ? selected_ones : selected_zeros, selected_dontcares).ToList(); // Check if selection resolves to one loop. if (result.Count != 1) { throw new MinificationException("Selected minterms cannot be simplified."); } if (value) { loops_ones.Add(result.First()); } else { loops_zeros.Add(result.First()); } selectedCells.Clear(); if (KarnaughLoopAdded != null) { KarnaughLoopAdded(this, new KarnaughLoopAddedEventArgs(result.First(), value)); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { ResumeLayout(true); Invalidate(); } return(Task.CompletedTask); }
private static CheckMoveResult[] ParseMoves(PKM pkm, int[] moves, int[] special, int[] lvlupegg, int[] egg, int[] NonTradebackLvlMoves, int[] eventegg, int[] initialmoves, LegalInfo info) { CheckMoveResult[] res = new CheckMoveResult[4]; var required = Legal.GetRequiredMoveCount(pkm, moves, info, initialmoves); // Check none moves and relearn moves before generation moves for (int m = 0; m < 4; m++) { if (moves[m] == 0) { res[m] = new CheckMoveResult(MoveSource.None, pkm.Format, m < required ? Severity.Fishy : Severity.Valid, V167, CheckIdentifier.Move); } else if (info.EncounterMoves.Relearn.Contains(moves[m])) { res[m] = new CheckMoveResult(MoveSource.Relearn, pkm.GenNumber, Severity.Valid, V172, CheckIdentifier.Move) { Flag = true } } ; } if (res.All(r => r != null)) { return(res); } bool MixedGen1NonTradebackGen2 = false; var Gen1MovesLearned = new List <int>(); var Gen2PreevoMovesLearned = new List <int>(); var EggMovesLearned = new List <int>(); var LvlupEggMovesLearned = new List <int>(); var EventEggMovesLearned = new List <int>(); var IsGen2Pkm = pkm.Format == 2 || pkm.VC2; var IncenseMovesLearned = new List <int>(); // Check moves going backwards, marking the move valid in the most current generation when it can be learned int[] generations = GetGenMovesCheckOrder(pkm); foreach (var gen in generations) { var HMLearned = new int[0]; // Check if pokemon knows HM moves from generation 3 and 4 but are not valid yet, that means it cant learn the HMs in future generations bool KnowDefogWhirlpool = false; if (gen == 4 && pkm.Format > 4) { // Copy to array the hm found or else the list will be emptied when the legal status of moves changes in the current generation HMLearned = moves.Where((m, i) => !(res[i]?.Valid ?? false) && Legal.HM_4_RemovePokeTransfer.Any(l => l == m)).Select((m, i) => i).ToArray(); // Defog and Whirlpool at the same time, also both can't be learned in future generations or else they will be valid KnowDefogWhirlpool = moves.Where((m, i) => (m == 250 || m == 432) && !(res[i]?.Valid ?? false)).Count() == 2; } else if (gen == 3 && pkm.Format > 3) { HMLearned = moves.Select((m, i) => i).Where(i => !(res[i]?.Valid ?? false) && Legal.HM_3.Any(l => l == moves[i])).ToArray(); } bool native = gen == pkm.Format; for (int m = 0; m < 4; m++) { if (res[m]?.Valid ?? false) { continue; } if (moves[m] == 0) { continue; } if (gen == 1 && initialmoves.Contains(moves[m])) { res[m] = new CheckMoveResult(MoveSource.Initial, gen, Severity.Valid, native ? V361 : string.Format(V362, gen), CheckIdentifier.Move); } else if (info.EncounterMoves.LevelUpMoves[gen].Contains(moves[m])) { res[m] = new CheckMoveResult(MoveSource.LevelUp, gen, Severity.Valid, native ? V177 : string.Format(V330, gen), CheckIdentifier.Move); } else if (info.EncounterMoves.TMHMMoves[gen].Contains(moves[m])) { res[m] = new CheckMoveResult(MoveSource.TMHM, gen, Severity.Valid, native ? V173 : string.Format(V331, gen), CheckIdentifier.Move); } else if (info.EncounterMoves.TutorMoves[gen].Contains(moves[m])) { res[m] = new CheckMoveResult(MoveSource.Tutor, gen, Severity.Valid, native ? V174 : string.Format(V332, gen), CheckIdentifier.Move); } else if (gen == pkm.GenNumber && special.Contains(moves[m])) { res[m] = new CheckMoveResult(MoveSource.Special, gen, Severity.Valid, V175, CheckIdentifier.Move); } if (res[m] == null || gen < 3) { continue; } if (res[m].Valid && gen == 2 && NonTradebackLvlMoves.Contains(m)) { Gen2PreevoMovesLearned.Add(m); } if (res[m].Valid && gen == 1) { Gen1MovesLearned.Add(m); if (Gen2PreevoMovesLearned.Any()) { MixedGen1NonTradebackGen2 = true; } } if (res[m].Valid && gen <= 2 && pkm.TradebackStatus == TradebackType.Any && pkm.GenNumber != gen) { pkm.TradebackStatus = TradebackType.WasTradeback; } } if (gen == generations.Last()) { // Check higher-level moves after all the moves but just before egg moves to differentiate it from normal level up moves // Also check if the base egg moves is a non tradeback move for (int m = 0; m < 4; m++) { if (res[m]?.Valid ?? false) // Skip valid move { continue; } if (moves[m] == 0) { continue; } if (!lvlupegg.Contains(moves[m])) // Check if contains level-up egg moves from parents { continue; } if (IsGen2Pkm && Gen1MovesLearned.Any() && moves[m] > Legal.MaxMoveID_1) { res[m] = new CheckMoveResult(MoveSource.InheritLevelUp, gen, Severity.Invalid, V334, CheckIdentifier.Move); MixedGen1NonTradebackGen2 = true; } else { res[m] = new CheckMoveResult(MoveSource.InheritLevelUp, gen, Severity.Valid, V345, CheckIdentifier.Move); } LvlupEggMovesLearned.Add(m); if (pkm.TradebackStatus == TradebackType.Any && pkm.GenNumber == 1) { pkm.TradebackStatus = TradebackType.WasTradeback; } } // Check egg moves after all the generations and all the moves, every move that can't be learned in another source should have preference // the moves that can only be learned from egg moves should in the future check if the move combinations can be breed in gens 2 to 5 for (int m = 0; m < 4; m++) { if (res[m]?.Valid ?? false) { continue; } if (moves[m] == 0) { continue; } if (egg.Contains(moves[m])) { if (IsGen2Pkm && Gen1MovesLearned.Any() && moves[m] > Legal.MaxMoveID_1) { // To learn exclusive generation 1 moves the pokemon was tradeback, but it can't be trade to generation 1 // without removing moves above MaxMoveID_1, egg moves above MaxMoveID_1 and gen 1 moves are incompatible res[m] = new CheckMoveResult(MoveSource.EggMove, gen, Severity.Invalid, V334, CheckIdentifier.Move) { Flag = true }; MixedGen1NonTradebackGen2 = true; } else { res[m] = new CheckMoveResult(MoveSource.EggMove, gen, Severity.Valid, V171, CheckIdentifier.Move) { Flag = true } }; EggMovesLearned.Add(m); if (pkm.TradebackStatus == TradebackType.Any && pkm.GenNumber == 1) { pkm.TradebackStatus = TradebackType.WasTradeback; } } if (!eventegg.Contains(moves[m])) { continue; } if (!egg.Contains(moves[m])) { if (IsGen2Pkm && Gen1MovesLearned.Any() && moves[m] > Legal.MaxMoveID_1) { res[m] = new CheckMoveResult(MoveSource.SpecialEgg, gen, Severity.Invalid, V334, CheckIdentifier.Move) { Flag = true }; MixedGen1NonTradebackGen2 = true; } else { res[m] = new CheckMoveResult(MoveSource.SpecialEgg, gen, Severity.Valid, V333, CheckIdentifier.Move) { Flag = true } }; } if (pkm.TradebackStatus == TradebackType.Any && pkm.GenNumber == 1) { pkm.TradebackStatus = TradebackType.WasTradeback; } EventEggMovesLearned.Add(m); } // A pokemon could have normal egg moves and regular egg moves // Only if all regular egg moves are event egg moves or all event egg moves are regular egg moves var RegularEggMovesLearned = EggMovesLearned.Union(LvlupEggMovesLearned).ToList(); if (RegularEggMovesLearned.Any() && EventEggMovesLearned.Any()) { // Moves that are egg moves or event egg moves but not both var IncompatibleEggMoves = RegularEggMovesLearned.Except(EventEggMovesLearned).Union(EventEggMovesLearned.Except(RegularEggMovesLearned)).ToList(); if (IncompatibleEggMoves.Any()) { foreach (int m in IncompatibleEggMoves) { if (EventEggMovesLearned.Contains(m) && !EggMovesLearned.Contains(m)) { res[m] = new CheckMoveResult(res[m], Severity.Invalid, V337, CheckIdentifier.Move); } else if (!EventEggMovesLearned.Contains(m) && EggMovesLearned.Contains(m)) { res[m] = new CheckMoveResult(res[m], Severity.Invalid, V336, CheckIdentifier.Move); } else if (!EventEggMovesLearned.Contains(m) && LvlupEggMovesLearned.Contains(m)) { res[m] = new CheckMoveResult(res[m], Severity.Invalid, V358, CheckIdentifier.Move); } } } } // If there is no incompatibility with event egg check that there is no inherited move in gift eggs and event eggs else if (RegularEggMovesLearned.Any() && (pkm.WasGiftEgg || pkm.WasEventEgg)) { foreach (int m in RegularEggMovesLearned) { if (EggMovesLearned.Contains(m)) { res[m] = new CheckMoveResult(res[m], Severity.Invalid, pkm.WasGiftEgg ? V377 : V341, CheckIdentifier.Move); } else if (LvlupEggMovesLearned.Contains(m)) { res[m] = new CheckMoveResult(res[m], Severity.Invalid, pkm.WasGiftEgg ? V378 : V347, CheckIdentifier.Move); } } } } if (3 <= gen && gen <= 4 && pkm.Format > gen) { // After all the moves from the generations 3 and 4, // including egg moves if is the origin generation because some hidden moves are also special egg moves in gen 3 // Check if the marked hidden moves that were invalid at the start are now marked as valid, that means // the hidden move was learned in gen 3 or 4 but was not removed when transfer to 4 or 5 if (KnowDefogWhirlpool) { int invalidCount = moves.Where((m, i) => (m == 250 || m == 432) && (res[i]?.Valid ?? false)).Count(); if (invalidCount == 2) // can't know both at the same time { for (int i = 0; i < 4; i++) // flag both moves { if (moves[i] == 250 || moves[i] == 432) { res[i] = new CheckMoveResult(res[i], Severity.Invalid, V338, CheckIdentifier.Move); } } } } for (int i = 0; i < HMLearned.Length; i++) { if (res[i]?.Valid ?? false) { res[i] = new CheckMoveResult(res[i], Severity.Invalid, string.Format(V339, gen, gen + 1), CheckIdentifier.Move); } } } // Mark the gen 1 exclusive moves as illegal because the pokemon also have Non tradeback egg moves. if (MixedGen1NonTradebackGen2) { foreach (int m in Gen1MovesLearned) { res[m] = new CheckMoveResult(res[m], Severity.Invalid, V335, CheckIdentifier.Move); } foreach (int m in Gen2PreevoMovesLearned) { res[m] = new CheckMoveResult(res[m], Severity.Invalid, V412, CheckIdentifier.Move); } } if (gen == 1 && pkm.Format == 1 && pkm.Gen1_NotTradeback) { // Check moves learned at the same level in red/blue and yellow, illegal because there is no move reminder // Only two incompatibilites and only there are no illegal combination if generation 2 or 7 are included in the analysis ParseRedYellowIncompatibleMoves(pkm, res, moves); ParseEvolutionsIncompatibleMoves(pkm, res, moves, info.EncounterMoves.TMHMMoves[1]); } if (Legal.SpeciesEvolutionWithMove.Contains(pkm.Species)) { // Pokemon that evolved by leveling up while learning a specific move // This pokemon could only have 3 moves from preevolutions that are not the move used to evolved // including special and eggs moves before realearn generations ParseEvolutionLevelupMove(pkm, res, moves, IncenseMovesLearned, info); } if (res.All(r => r != null)) { return(res); } } if (pkm.Species == 292 && info.EncounterMatch.Species != 292) { // Ignore Shedinja if the Encounter was also a Shedinja, assume null Encounter as a Nincada egg // Check Shedinja evolved moves from Ninjask after egg moves // Those moves could also be inherited egg moves ParseShedinjaEvolveMoves(pkm, res, moves); } for (int m = 0; m < 4; m++) { if (res[m] == null) { res[m] = new CheckMoveResult(MoveSource.Unknown, pkm.GenNumber, Severity.Invalid, V176, CheckIdentifier.Move); } } return(res); }
private string GetLanguagesToken(string mediaInfoLanguages, string filter, bool skipEnglishOnly, bool quoted) { List <string> tokens = new List <string>(); foreach (var item in mediaInfoLanguages.Split('/')) { if (!string.IsNullOrWhiteSpace(item)) { tokens.Add(item.Trim()); } } var cultures = CultureInfo.GetCultures(CultureTypes.NeutralCultures); for (int i = 0; i < tokens.Count; i++) { if (tokens[i] == "Swedis") { // Probably typo in mediainfo (should be 'Swedish') tokens[i] = "SV"; continue; } if (tokens[i] == "Chinese" && OsInfo.IsNotWindows) { // Mono only has 'Chinese (Simplified)' & 'Chinese (Traditional)' tokens[i] = "ZH"; continue; } try { var cultureInfo = cultures.FirstOrDefault(p => p.EnglishName.RemoveAccent() == tokens[i]); if (cultureInfo != null) { tokens[i] = cultureInfo.TwoLetterISOLanguageName.ToUpper(); } } catch { } } tokens = tokens.Distinct().ToList(); var filteredTokens = tokens; // Exclude or filter if (filter.IsNotNullOrWhiteSpace()) { if (filter.StartsWith("-")) { filteredTokens = tokens.Except(filter.Split('-')).ToList(); } else { filteredTokens = filter.Split('+').Intersect(tokens).ToList(); } } // Replace with wildcard (maybe too limited) if (filter.IsNotNullOrWhiteSpace() && filter.EndsWith("+") && filteredTokens.Count != tokens.Count) { filteredTokens.Add("--"); } if (skipEnglishOnly && filteredTokens.Count == 1 && filteredTokens.First() == "EN") { return(string.Empty); } var response = string.Join("+", filteredTokens); if (quoted && response.IsNotNullOrWhiteSpace()) { return($"[{response}]"); } else { return(response); } }
/// <summary> /// Perform spell check on the text from the element /// </summary> /// <param name="element">element to check</param> /// <param name="currentLanguage">language code to use spell check for</param> /// <param name="changedCallback">optional callback for text changes from dialog Elements</param> public static IEnumerable <Inline> CheckElement(IDialogElement element, string currentLanguage = "en_gb", Action <object, PropertyChangedEventArgs> changedCallback = null) { List <Inline> paragraphRuns = new List <Inline>(); if (GeneralPreference.Instance.EnableSpellCheck && m_dictionary.ContainsKey(currentLanguage)) { WordList dictionary = m_dictionary[currentLanguage]; string fullText = element.Text; string[] words = fullText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); string sentence = fullText.StartsWith(" ") ? " " : ""; for (int i = 0; i < words.Length; i++) { string word = words[i]; List <string> suggestions = dictionary.Suggest(word).ToList(); if (suggestions.Any() && !suggestions.Contains(word)) { if (i > 0) { sentence += " "; } paragraphRuns.Add(new Run(sentence)); sentence = ""; paragraphRuns.Add(new Bold(new SpellingOptions(word, element, suggestions.Except(new[] { word }), changedCallback))); } else { if (i > 0) { sentence += " "; } sentence += word; } } //add any remaining words if (fullText.EndsWith(" ")) { sentence += " "; } if (sentence.Length > 0) { paragraphRuns.Add(new EditBlock(sentence, element, changedCallback)); } } else { paragraphRuns.Add(new EditBlock(element.Text, element, changedCallback)); } return(paragraphRuns); }
/// <summary> /// compare objects /// </summary> /// <typeparam name="T">Type can Column , Index , ForeignKey</typeparam> /// <param name="doc">must be current XDocument</param> /// <param name="root">root xml element</param> /// <param name="targetData">Current Diff List Data</param> /// <param name="sourceData">must be compare data</param> /// <param name="navigatorAdd">refers to add element XML</param> /// <param name="navigatorRemove">refers to remove element XML</param> /// <param name="navigatorUpdate">refers to update element XML</param> public void GenerateDifference <T>(List <T> sourceData, List <T> targetData, XmlWriter navigatorAdd, XmlWriter navigatorRemove, XmlWriter navigatorUpdate) { // Detect new sql object like as INDEX , Column , REFERENTIAL_CONSTRAINTS var mustAdd = FindNewComponent <T>(sourceData, targetData); // Add new objects to xml if (mustAdd != null) { foreach (var sqlObject in mustAdd) { navigatorAdd.Serialize(sqlObject); } } var compareLogic = new CompareLogic { Config = { MaxDifferences = int.MaxValue, AttributesToIgnore = new List <Type> { typeof(CompareIgnoreAttribute) }, CaseSensitive = false, } }; if (typeof(T) == typeof(PrimaryKey)) { compareLogic.Config.MembersToIgnore.Add("Name"); compareLogic.Config.MembersToIgnore.Add("name"); } // Detect Sql Objects Changes if (targetData == null) { return; } { if (mustAdd != null) { sourceData = sourceData.Except(x => mustAdd.Contains(x)).ToList(); } foreach (var currentObject in sourceData) { var foundObject = FindRemoveOrUpdate <T>(currentObject, targetData); if (foundObject == null) { if (typeof(T) == typeof(PrimaryKey)) { navigatorUpdate.Serialize(currentObject); } else { navigatorRemove.Serialize(currentObject); } } else { var result = compareLogic.Compare(currentObject, foundObject); if (!result.AreEqual) { navigatorUpdate.Serialize(currentObject); } } } foreach (var currentObject in targetData) { var foundObject = FindRemoveOrUpdate <T>(currentObject, sourceData); if (foundObject == null) { navigatorRemove.Serialize(currentObject); } } } }
/// <summary> /// Fonction qui fait le paring des joueur qui ce strouve dans un même regroupement fait sur base du classement /// /// il peu y avoir des joueur d'un autre groupe /// </summary> /// <param name="Players">liste des joueur a pairé</param> /// <param name="PlayerOpponentList">dictonnaire des adversaire pour chaque joueur</param> /// <param name="OutReportedPlayer"> paramttre qui va listé les joueur qui sont reporté car impossible de pairé dans ce groupe</param> /// <param name="InReportedPlayer">liste de joueur qui sont rajouté a ce groupe car il n'ont pas pu être pairé dans celui d'avant</param> /// <returns>liste de pairing de joueur effectué pour ce groupe</returns> private static List <PairID> PairingInGroup(List <int> Players, Dictionary <int, List <int> > PlayerOpponentList, out List <int> OutReportedPlayer, List <int> InReportedPlayer = null) { List <PairID> retour = new(); // crée la variable qui se verra atrivué la liste de pairing qui doit être retourné. OutReportedPlayer = new List <int>(); //initilaization du paramtre out OutreportedPlayer OutReportedPlayer.Clear(); // on s'assure que le parametre out est bien vide List <int> AllRemainingPlayer = new(); AllRemainingPlayer.Clear(); AllRemainingPlayer.AddRange(Players); if (InReportedPlayer != null && InReportedPlayer.Count > 0) //on verfie si il y a des joueur reporté { AllRemainingPlayer.AddRange(InReportedPlayer); // on ajoute les joueur reporté a la liste des joueur restant a appareillé foreach (var Player in InReportedPlayer) //pour chaque joueur reporté a appareillé { if (AllRemainingPlayer.Contains(Player)) //on verifie que le joueur est toujours dans la liste des joueur a appareillé { if (PairAPlayer(Player, PlayerOpponentList, AllRemainingPlayer, out var pairPlayer) ) // on essaye de l'appareillé { // si on réussie on affect l'appareillement AllRemainingPlayer.Remove(pairPlayer.ID1); AllRemainingPlayer.Remove(pairPlayer.ID2); retour.Add(pairPlayer); } else //si on ne reussie pas on rajoute le joueur ala liste des joueur a reporté { OutReportedPlayer.Add(Player); } } } } foreach (var player in Players) //pour chaque joueur a appareillé { if (AllRemainingPlayer.Contains(player)) //on verifie que le joueur est toujours dans la liste des joueur a appareillé { if (PairAPlayer(player, PlayerOpponentList, AllRemainingPlayer, out var pairPlayer) ) // on essaye de l'appareillé { // si on réussie on affect l'appareillement et retrie les joueuer appareillé AllRemainingPlayer.Remove(pairPlayer.ID1); AllRemainingPlayer.Remove(pairPlayer.ID2); retour.Add(pairPlayer); } else //si on ne reussie pas on rajoute le joueur ala liste des joueur a reporté { OutReportedPlayer.Add(player); } } } if (OutReportedPlayer.Count > 1)// si il y a plus d'un joueur reporté on verifie que en faisant des permutation on ne peu pas les appareillé quand même { List <int> tempOutReportedPlayer = new(); tempOutReportedPlayer.AddRange(OutReportedPlayer); //crée un doublons de la list des joueur reporté foreach (var Player in tempOutReportedPlayer) //pour tout les joueur reporté { if (OutReportedPlayer.Contains(Player)) //on verifie que le joueur est encore dans les joueur reporté { foreach (var pair in retour) //pour chaque pairing dejà fait { if (!PlayerOpponentList[Player].Contains(pair.ID1)) //on regard si le playerone du pairing n'est pas dans la liste des adversaire déjà rencontré { var ListNewOpponent = OutReportedPlayer.Except(PlayerOpponentList[pair.ID2]).ToList(); //on crée une liste d'advaisaire potentielle sur base des joueur reporté qui serait ne serait pas dans la liste des adversaire du playertwo de la pair ListNewOpponent.Remove(Player); //on retire le joueur que l'on tente de pairé de la liste des potentille nouveau adversaire du playertwo (vu que le jouer va être apparaillé au playerone) if (ListNewOpponent.Any()) //on regard si il reste un adversaire potentielle { var rng = new Random(); var NewOpponent = ListNewOpponent.ElementAt(rng.Next(0, ListNewOpponent.Count)); //on choisie alléatoirement un adversaire parmi les adversaire potentielle var pairPlayer1 = new PairID //on crée une nouveelle pair { ID1 = pair.ID2, ID2 = NewOpponent //on pair le player 2 avec l'adversaire choisie aléatoirement }; retour.Add(pairPlayer1); //on joute la nouvelle pair var pairPlayer2 = new PairID //on crée une nouveelle pair { ID1 = pair.ID1, ID2 = Player //on pair le player1 avec le joueur que l'on tant de pairé }; retour.Add(pairPlayer2); //on joute la nouvelle pair retour.Remove(pair); //on supprime l'ancienne pair OutReportedPlayer.Remove(NewOpponent); //on retire l'adversaire choisie au hazard des joueur reporté OutReportedPlayer.Remove(Player); //on retire joueur des joueur reporté break; } } } } } } return(retour); }
/// <summary> /// Prepares generation by processing the result of code parsing. /// </summary> /// <remarks> /// Preparation includes figuring out from the existing code which models or properties should /// be ignored or renamed, etc. -- anything that comes from the attributes in the existing code. /// </remarks> private void Prepare() { var pureLive = UmbracoConfig.For.ModelsBuilder().ModelsMode == ModelsMode.PureLive; // mark IsContentIgnored models that we discovered should be ignored // then propagate / ignore children of ignored contents // ignore content = don't generate a class for it, don't generate children foreach (var typeModel in _typeModels.Where(x => ParseResult.IsIgnored(x.Alias))) { typeModel.IsContentIgnored = true; } foreach (var typeModel in _typeModels.Where(x => !x.IsContentIgnored && x.EnumerateBaseTypes().Any(xx => xx.IsContentIgnored))) { typeModel.IsContentIgnored = true; } // handle model renames foreach (var typeModel in _typeModels.Where(x => ParseResult.IsContentRenamed(x.Alias))) { typeModel.ClrName = ParseResult.ContentClrName(typeModel.Alias); typeModel.IsRenamed = true; ModelsMap[typeModel.Alias] = typeModel.ClrName; } // handle implement foreach (var typeModel in _typeModels.Where(x => ParseResult.HasContentImplement(x.Alias))) { typeModel.HasImplement = true; } // mark OmitBase models that we discovered already have a base class foreach (var typeModel in _typeModels.Where(x => ParseResult.HasContentBase(ParseResult.ContentClrName(x.Alias) ?? x.ClrName))) { typeModel.HasBase = true; } foreach (var typeModel in _typeModels) { // mark IsRemoved properties that we discovered should be ignored // ie is marked as ignored on type, or on any parent type var tm = typeModel; foreach (var property in typeModel.Properties .Where(property => tm.EnumerateBaseTypes(true).Any(x => ParseResult.IsPropertyIgnored(ParseResult.ContentClrName(x.Alias) ?? x.ClrName, property.Alias)))) { property.IsIgnored = true; } // handle property renames foreach (var property in typeModel.Properties) { property.ClrName = ParseResult.PropertyClrName(ParseResult.ContentClrName(typeModel.Alias) ?? typeModel.ClrName, property.Alias) ?? property.ClrName; } } // for the first two of these two tests, // always throw, even in purelive: cannot happen unless ppl start fidling with attributes to rename // things, and then they should pay attention to the generation error log - there's no magic here // for the last one, don't throw in purelive, see comment // ensure we have no duplicates type names foreach (var xx in _typeModels.Where(x => !x.IsContentIgnored).GroupBy(x => x.ClrName).Where(x => x.Count() > 1)) { throw new InvalidOperationException($"Type name \"{xx.Key}\" is used" + $" for types with alias {string.Join(", ", xx.Select(x => x.ItemType + ":\"" + x.Alias + "\""))}. Names have to be unique." + " Consider using an attribute to assign different names to conflicting types."); } // ensure we have no duplicates property names foreach (var typeModel in _typeModels.Where(x => !x.IsContentIgnored)) { foreach (var xx in typeModel.Properties.Where(x => !x.IsIgnored).GroupBy(x => x.ClrName).Where(x => x.Count() > 1)) { throw new InvalidOperationException($"Property name \"{xx.Key}\" in type {typeModel.ItemType}:\"{typeModel.Alias}\"" + $" is used for properties with alias {string.Join(", ", xx.Select(x => "\"" + x.Alias + "\""))}. Names have to be unique." + " Consider using an attribute to assign different names to conflicting properties."); } } // ensure content & property type don't have identical name (csharp hates it) foreach (var typeModel in _typeModels.Where(x => !x.IsContentIgnored)) { foreach (var xx in typeModel.Properties.Where(x => !x.IsIgnored && x.ClrName == typeModel.ClrName)) { if (!pureLive) { throw new InvalidOperationException($"The model class for content type with alias \"{typeModel.Alias}\" is named \"{xx.ClrName}\"." + $" CSharp does not support using the same name for the property with alias \"{xx.Alias}\"." + " Consider using an attribute to assign a different name to the property."); } // for purelive, will we generate a commented out properties with an error message, // instead of throwing, because then it kills the sites and ppl don't understand why xx.AddError($"The class {typeModel.ClrName} cannot implement this property, because" + $" CSharp does not support naming the property with alias \"{xx.Alias}\" with the same name as content type with alias \"{typeModel.Alias}\"." + " Consider using an attribute to assign a different name to the property."); // will not be implemented on interface nor class // note: we will still create the static getter, and implement the property on other classes... } } // ensure we have no collision between base types // NO: we may want to define a base class in a partial, on a model that has a parent // we are NOT checking that the defined base type does maintain the inheritance chain //foreach (var xx in _typeModels.Where(x => !x.IsContentIgnored).Where(x => x.BaseType != null && x.HasBase)) // throw new InvalidOperationException(string.Format("Type alias \"{0}\" has more than one parent class.", // xx.Alias)); // discover interfaces that need to be declared / implemented foreach (var typeModel in _typeModels) { // collect all the (non-removed) types implemented at parent level // ie the parent content types and the mixins content types, recursively var parentImplems = new List <TypeModel>(); if (typeModel.BaseType != null && !typeModel.BaseType.IsContentIgnored) { TypeModel.CollectImplems(parentImplems, typeModel.BaseType); } // interfaces we must declare we implement (initially empty) // ie this type's mixins, except those that have been removed, // and except those that are already declared at the parent level // in other words, DeclaringInterfaces is "local mixins" var declaring = typeModel.MixinTypes .Where(x => !x.IsContentIgnored) .Except(parentImplems); typeModel.DeclaringInterfaces.AddRange(declaring); // interfaces we must actually implement (initially empty) // if we declare we implement a mixin interface, we must actually implement // its properties, all recursively (ie if the mixin interface implements...) // so, starting with local mixins, we collect all the (non-removed) types above them var mixinImplems = new List <TypeModel>(); foreach (var i in typeModel.DeclaringInterfaces) { TypeModel.CollectImplems(mixinImplems, i); } // and then we remove from that list anything that is already declared at the parent level typeModel.ImplementingInterfaces.AddRange(mixinImplems.Except(parentImplems)); } // register using types foreach (var usingNamespace in ParseResult.UsingNamespaces) { if (!TypesUsing.Contains(usingNamespace)) { TypesUsing.Add(usingNamespace); } } // discover static mixin methods foreach (var typeModel in _typeModels) { typeModel.StaticMixinMethods.AddRange(ParseResult.StaticMixinMethods(typeModel.ClrName)); } // handle ctor foreach (var typeModel in _typeModels.Where(x => ParseResult.HasCtor(x.ClrName))) { typeModel.HasCtor = true; } }
private IEnumerator Play() { var myUnits = _cellGrid.Units.FindAll(u => u.PlayerNumber.Equals(PlayerNumber)).ToList(); foreach (var unit in myUnits.OrderByDescending(u => u.Cell.GetNeighbours(_cellGrid.Cells).FindAll(u.IsCellTraversable).Count)) { var enemyUnits = _cellGrid.Units.Except(myUnits).ToList(); var unitsInRange = new List <Unit>(); foreach (var enemyUnit in enemyUnits) { if (unit.IsUnitAttackable(enemyUnit, unit.Cell)) { unitsInRange.Add(enemyUnit); } }//Looking for enemies that are in attack range. if (unitsInRange.Count != 0) { var index = _rnd.Next(0, unitsInRange.Count); unit.DealDamage(unitsInRange[index]); yield return(new WaitForSeconds(0.5f)); continue; }//If there is an enemy in range, attack it. List <Cell> potentialDestinations = new List <Cell>(); foreach (var enemyUnit in enemyUnits) { potentialDestinations.AddRange(_cellGrid.Cells.FindAll(c => unit.IsCellMovableTo(c) && unit.IsUnitAttackable(enemyUnit, c))); }//Making a list of cells that the unit can attack from. var notInRange = potentialDestinations.FindAll(c => c.GetDistance(unit.Cell) > unit.Energy); potentialDestinations = potentialDestinations.Except(notInRange).ToList(); if (potentialDestinations.Count == 0 && notInRange.Count != 0) { potentialDestinations.Add(notInRange.ElementAt(_rnd.Next(0, notInRange.Count - 1))); } potentialDestinations = potentialDestinations.OrderBy(h => _rnd.Next()).ToList(); List <Cell> shortestPath = null; foreach (var potentialDestination in potentialDestinations) { var path = unit.FindPath(_cellGrid.Cells, potentialDestination); if ((shortestPath == null && path.Sum(h => h.EnergyCost) > 0) || shortestPath != null && (path.Sum(h => h.EnergyCost) < shortestPath.Sum(h => h.EnergyCost) && path.Sum(h => h.EnergyCost) > 0)) { shortestPath = path; } var pathCost = path.Sum(h => h.EnergyCost); if (pathCost > 0 && pathCost <= unit.Energy) { unit.Move(potentialDestination, path); while (unit.isMoving) { yield return(0); } shortestPath = null; break; } yield return(0); }//If there is a path to any cell that the unit can attack from, move there. if (shortestPath != null) { foreach (var potentialDestination in shortestPath.Intersect(unit.GetAvailableDestinations(_cellGrid.Cells)).OrderByDescending(h => h.GetDistance(unit.Cell))) { var path = unit.FindPath(_cellGrid.Cells, potentialDestination); var pathCost = path.Sum(h => h.EnergyCost); if (pathCost > 0 && pathCost <= unit.Energy) { unit.Move(potentialDestination, path); while (unit.isMoving) { yield return(0); } break; } yield return(0); } }//If the path cost is greater than unit movement points, move as far as possible. foreach (var enemyUnit in enemyUnits) { var enemyCell = enemyUnit.Cell; if (unit.IsUnitAttackable(enemyUnit, unit.Cell)) { unit.DealDamage(enemyUnit); yield return(new WaitForSeconds(0.5f)); break; } }//Look for enemies in range and attack. } _cellGrid.EndTurn(); }
private void ExportFile_Click(object sender, RoutedEventArgs e) { if (UIDCheck.IsChecked == true && PhoneCheck.IsChecked == true) { foreach (DataInfo item in dataListFolder) { string[] filePaths_HomeTruoc = Directory.GetFiles(item.Directory + "\\UID_Hom_Truoc", "*.csv", SearchOption.TopDirectoryOnly); // get UID_Hom_Truoc using (CsvFileReader csvReader = new CsvFileReader(filePaths_HomeTruoc[0])) { List <string> row = new List <string>(); List <string> dataId = new List <string>(); List <string> dataPhone = new List <string>(); while (csvReader.ReadRow(row)) { dataId.Add(row[1]); dataPhone.Add(row[4]); } dataIdYesterday = dataId.Distinct().ToList(); dataPhoneYesterday = dataPhone.Distinct().ToList(); } string[] filePaths_HomeNay = Directory.GetFiles(item.Directory + "\\UID_Hom_Nay", "*.csv", SearchOption.TopDirectoryOnly); // get UID_Hom_Nay using (CsvFileReader csvReader = new CsvFileReader(filePaths_HomeNay[0])) { List <string> row = new List <string>(); List <string> dataId = new List <string>(); List <string> dataPhone = new List <string>(); while (csvReader.ReadRow(row)) { dataId.Add(row[1]); dataPhone.Add(row[4]); } dataIdToday = dataId.Distinct().ToList(); dataPhoneToday = dataPhone.Distinct().ToList(); } string[] filePaths_DoiThu = Directory.GetFiles(item.Directory + "\\UID_Doi_Thu", "*.csv", SearchOption.TopDirectoryOnly); // get UID_Doi_Thu using (CsvFileReader csvReader = new CsvFileReader(filePaths_DoiThu[0])) { List <string> row = new List <string>(); List <string> dataId = new List <string>(); while (csvReader.ReadRow(row)) { dataId.Add(row[0]); } dataIdOpponent = dataId.Distinct().ToList(); } dataIdNoDuplicate = dataIdToday.Except(dataIdYesterday).ToList(); dataPhoneNoDuplicate = dataPhoneToday.Except(dataPhoneYesterday).ToList(); if (dataIdOpponent.Count() == 0) { string path = item.Directory + "/Ket_Qua/" + item.NameFile + "_UID" + ".txt"; if (dataIdNoDuplicate.Count() > 0 && dataIdNoDuplicate.ElementAt(0).ToString() == "Id") { dataIdNoDuplicate.RemoveAt(0); } using (StreamWriter sw = File.CreateText(path)) { foreach (string item1 in dataIdNoDuplicate) { sw.WriteLine(item1); } } string path2 = item.Directory + "/Ket_Qua/" + item.NameFile + "_Phone" + ".txt"; if (dataPhoneNoDuplicate.Count() > 0 && dataPhoneNoDuplicate.ElementAt(0).ToString() == "Điện thoại") { dataPhoneNoDuplicate.RemoveAt(0); } using (StreamWriter sw = File.CreateText(path2)) { foreach (string item2 in dataPhoneNoDuplicate) { sw.WriteLine(item2); } } } else { dataIdNoDuplicateFinal = dataIdNoDuplicate.Except(dataIdOpponent).ToList(); string path = item.Directory + "/Ket_Qua/" + item.NameFile + "_UID" + ".txt"; if (dataIdNoDuplicateFinal.Count() > 0 && dataIdNoDuplicateFinal.ElementAt(0).ToString() == "Id") { dataIdNoDuplicateFinal.RemoveAt(0); } using (StreamWriter sw = File.CreateText(path)) { foreach (string item2 in dataIdNoDuplicateFinal) { sw.WriteLine(item2); } } string path2 = item.Directory + "/Ket_Qua/" + item.NameFile + "_Phone" + ".txt"; if (dataPhoneNoDuplicate.Count() > 0 && dataPhoneNoDuplicate.ElementAt(0).ToString() == "Điện thoại") { dataPhoneNoDuplicate.RemoveAt(0); } using (StreamWriter sw = File.CreateText(path2)) { foreach (string item2 in dataPhoneNoDuplicate) { sw.WriteLine(item2); } } } } MessageBoxResult result = MessageBox.Show("Success"); return; } else if (UIDCheck.IsChecked == true && PhoneCheck.IsChecked == false) { foreach (var item in dataListFolder) { string[] filePaths_HomeTruoc = Directory.GetFiles(item.Directory + "\\UID_Hom_Truoc", "*.csv", SearchOption.TopDirectoryOnly); // get UID_Hom_Truoc using (CsvFileReader csvReader = new CsvFileReader(filePaths_HomeTruoc[0])) { List <string> row = new List <string>(); List <string> dataId = new List <string>(); List <string> dataPhone = new List <string>(); while (csvReader.ReadRow(row)) { dataId.Add(row[1]); dataPhone.Add(row[4]); } dataIdYesterday = dataId.Distinct().ToList(); dataPhoneYesterday = dataPhone.Distinct().ToList(); } string[] filePaths_HomeNay = Directory.GetFiles(item.Directory + "\\UID_Hom_Nay", "*.csv", SearchOption.TopDirectoryOnly); // get UID_Hom_Nay using (CsvFileReader csvReader = new CsvFileReader(filePaths_HomeNay[0])) { List <string> row = new List <string>(); List <string> dataId = new List <string>(); List <string> dataPhone = new List <string>(); while (csvReader.ReadRow(row)) { dataId.Add(row[1]); dataPhone.Add(row[4]); } dataIdToday = dataId.Distinct().ToList(); dataPhoneToday = dataPhone.Distinct().ToList(); } string[] filePaths_DoiThu = Directory.GetFiles(item.Directory + "\\UID_Doi_Thu", "*.csv", SearchOption.TopDirectoryOnly); // get UID_Doi_Thu using (CsvFileReader csvReader = new CsvFileReader(filePaths_DoiThu[0])) { List <string> row = new List <string>(); List <string> dataId = new List <string>(); while (csvReader.ReadRow(row)) { dataId.Add(row[0]); } dataIdOpponent = dataId.Distinct().ToList(); } dataIdNoDuplicate = dataIdToday.Except(dataIdYesterday).ToList(); dataPhoneNoDuplicate = dataPhoneToday.Except(dataPhoneYesterday).ToList(); if (dataIdOpponent.Count() == 0) { string path = item.Directory + "/Ket_Qua/" + item.NameFile + "_UID" + ".txt"; if (dataIdNoDuplicate.Count() > 0 && dataIdNoDuplicate.ElementAt(0).ToString() == "Id") { dataIdNoDuplicate.RemoveAt(0); } using (StreamWriter sw = File.CreateText(path)) { foreach (string item1 in dataIdNoDuplicate) { sw.WriteLine(item1); } } } else { dataIdNoDuplicateFinal = dataIdNoDuplicate.Except(dataIdOpponent).ToList(); string path = item.Directory + "/Ket_Qua/" + item.NameFile + "_UID" + ".txt"; if (dataIdNoDuplicateFinal.Count() > 0 && dataIdNoDuplicateFinal.ElementAt(0).ToString() == "Id") { dataIdNoDuplicateFinal.RemoveAt(0); } using (StreamWriter sw = File.CreateText(path)) { foreach (string item2 in dataIdNoDuplicateFinal) { sw.WriteLine(item2); } } } } MessageBoxResult result = MessageBox.Show("Success"); return; } else { MessageBoxResult result = MessageBox.Show("Bạn nên chọn UID"); return; } }
private static void CreateData(XmlDocument xmlResult, string AttachInfo2) { var zfbDA = new ZFBDA(); var entityList = new List <ZFBDataEntity>(); var now = DateTime.Now; XmlNodeList nodeList = xmlResult.GetElementsByTagName("csv_data"); if (nodeList.Count == 0) { throw new Exception("获取数据失败"); } string strResult = nodeList[0].InnerXml; XmlNodeList nodeList01 = xmlResult.GetElementsByTagName("is_success"); string flag = nodeList01[0].InnerXml; XmlNodeList nodeList02 = xmlResult.GetElementsByTagName("count"); int countList = int.Parse(nodeList02[0].InnerXml); if (flag == "F") { throw new Exception("获取失败,is_success标识为F"); } if (countList <= 0) { throw new Exception("当天没有交易记录"); } //去掉左右冗余符号 strResult = strResult.Replace("<![CDATA[", "").Replace("]]>", "").Replace("\n", "").Trim(); string[] resultArray = strResult.Split(','); const int coulmnCount = 14; int rowCount = resultArray.Count() / coulmnCount - 1; DataTable table = new DataTable(); DataColumn column; DataRow row; //加列头 for (int i = 0; i < coulmnCount; i++) { column = new DataColumn(); column.DataType = System.Type.GetType("System.String"); column.ColumnName = resultArray[i]; table.Columns.Add(column); } //加行 int index = coulmnCount; for (int j = 0; j < rowCount; j++) { row = table.NewRow(); for (int i = 0; i < coulmnCount; i++) { row[i] = resultArray[index++]; } table.Rows.Add(row); } foreach (DataRow rowData in table.Rows) { try { var soSysNo = Convert.ToInt32(rowData[0]); var getPayTypeResult = zfbDA.GetPayType(soSysNo); if (getPayTypeResult == null || getPayTypeResult.Count == 0) { throw new Exception("SO_Master中查找不到该订单信息"); } PayTypeEntity paytypeEntity = getPayTypeResult[0]; entityList.Add(new ZFBDataEntity { SoSysNo = soSysNo, PayTermsNo = paytypeEntity.PayTermsNo, PayTerms = paytypeEntity.PayTerms, PayedDate = Convert.ToDateTime(rowData[2]), PayedAmt = Convert.ToDecimal(rowData[8]), SerialNumber = rowData[3].ToString(), OutOrderNo = rowData[4].ToString(), PayedUserTag = rowData[5].ToString(), PayedUserName = rowData[6].ToString(), PayedUserNo = rowData[7].ToString(), PartnerName = "支付宝", TradeType = rowData[12].ToString(), AttachInfo = rowData[11].ToString(), AttachInfo2 = AttachInfo2, InUser = "******", InDate = now }); } catch (Exception ex) { string[] strArray = rowData.ItemArray.Select(x => { return(x == null ? string.Empty : x.ToString()); }).ToArray <string>(); string details = string.Format("异常订单信息 SoSysNo:{0},InDate:{1},Error:{2},ErrorInfoSource:{3}", rowData[0].ToString(), rowData[2].ToString(), ex.Message, string.Join(",", strArray)); OnShowInfo(details); SendMail("支付宝对账异常", details); if (rowData[0].ToString().Length >= 9) { var longInfo = string.Format("支付宝过长订单号信息提醒 SoSysNo:{0},InDate:{1},ErrorInfoSource:{2}", rowData[0].ToString(), rowData[2].ToString(), string.Join(",", strArray)); MailDA.SendEmail(Settings.LongOrderSysNoAlert, "支付宝过长订单号信息提醒", longInfo); } else if (ex.Message.Contains("SO_Master中查找不到该订单信息")) { var longInfo = string.Format("无法确认支付宝订单提醒 SoSysNo:{0},InDate:{1},ErrorInfoSource:{2}", rowData[0].ToString(), rowData[2].ToString(), string.Join(",", strArray)); MailDA.SendEmail(Settings.LongOrderSysNoAlert, "无法确认支付宝订单提醒", longInfo); } } } if (lastInfo != null && lastInfo.Count > 0) { entityList = entityList.Except(lastInfo, new ZFBEntityComparer()).ToList(); } if (entityList == null || entityList.Count == 0) { throw new Exception("不存在可导入记录"); } OnShowInfo("开始导入数据"); try { //每一百条数据导入一次 var entityMiddle = new List <ZFBDataEntity>(); for (int i = 0; i < entityList.Count; i++) { entityMiddle.Add(entityList[i]); if ((i != 0 && (i + 1) % 100 == 0) || (i + 1) == entityList.Count) { zfbDA.CreateData(entityMiddle); OnShowInfo(string.Format("导入了{0}条记录", (i + 1).ToString())); entityMiddle.Clear(); } } } catch (Exception ex) { OnShowInfo(string.Format("导入失败:{0}", ex.Message)); } OnShowInfo("导入完毕"); }
static void Main(string[] args) { Console.WriteLine("Проста вибірка елементів"); var q1 = from x in d1 select x; foreach (var x in q1) { Console.WriteLine(x); } Console.WriteLine("Вибірка окремого поля (проекція)"); var q2 = from x in d1 select x.value; foreach (var x in q2) { Console.WriteLine(x); } Console.WriteLine("Створення нового об'єкта анонімного типу"); var q3 = from x in d1 select new { IDENTIFIER = x.id, VALUE = x.value }; foreach (var x in q3) { Console.WriteLine(x); } Console.WriteLine("Умова"); var q4 = from x in d1 where x.id > 1 && (x.name == "Project1" || x.name == "Project2") select x; foreach (var x in q4) { Console.WriteLine(x); } Console.WriteLine("Вибірка по значенню типа"); object[] array = new object[] { 123, "строка 1", true, "строка 2" }; var qo = from x in array.OfType <string>() select x; foreach (var x in qo) { Console.WriteLine(x); } Console.WriteLine("Сортування"); var q5 = from x in d1 where x.id > 1 && (x.name == "Project1" || x.name == "Project2") orderby x.name descending, x.id descending select x; foreach (var x in q5) { Console.WriteLine(x); } Console.WriteLine("Сортування (з використанням методів)"); var q51 = d1.Where((x) => { return(x.id > 1 && (x.name == "Project1" || x.name == "Project2")); }).OrderByDescending(x => x.name).ThenByDescending(x => x.id); foreach (var x in q51) { Console.WriteLine(x); } Console.WriteLine("Partitioning Operators"); Console.WriteLine("Посторінкова вибірка даних"); var qp = GetPage(d1, 2, 2); foreach (var x in qp) { Console.WriteLine(x); } Console.WriteLine("Використання SkipWhile і TakeWhile"); int[] intArray = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 }; var qw = intArray.SkipWhile(x => (x < 4)).TakeWhile(x => x <= 7); foreach (var x in qw) { Console.WriteLine(x); } Console.WriteLine("Декартовий добуток"); var q6 = from x in d1 from y in d2 select new { v1 = x.value, v2 = y.value }; foreach (var x in q6) { Console.WriteLine(x); } Console.WriteLine("Inner Join з використанням Where"); var q7 = from x in d1 from y in d2 where x.id == y.id select new { v1 = x.value, v2 = y.value }; foreach (var x in q7) { Console.WriteLine(x); } Console.WriteLine("Cross Join (Inner Join) з використанням Join"); var q8 = from x in d1 join y in d2 on x.id equals y.id select new { v1 = x.value, v2 = y.value }; foreach (var x in q8) { Console.WriteLine(x); } Console.WriteLine("Cross Join (збереження об'єкта)"); var q9 = from x in d1 join y in d2 on x.id equals y.id select new { v1 = x.value, d2Group = y }; foreach (var x in q9) { Console.WriteLine(x); } //Вибираються всі елементи з d1 і якщо є звязані з d2 (outer join) //В temp поміщаєтся вся група, її елементи можна перебирати окремо Console.WriteLine("Group Join"); var q10 = from x in d1 join y in d2 on x.id equals y.id into temp select new { v1 = x.value, d2Group = temp }; foreach (var x in q10) { Console.WriteLine(x.v1); foreach (var y in x.d2Group) { Console.WriteLine(" " + y); } } Console.WriteLine("Cross Join і Group Join"); var q11 = from x in d1 join y in d2 on x.id equals y.id into temp from t in temp select new { v1 = x.value, v2 = t.value, cnt = temp.Count() }; foreach (var x in q11) { Console.WriteLine(x); } Console.WriteLine("Outer Join"); var q12 = from x in d1 join y in d2 on x.id equals y.id into temp from t in temp.DefaultIfEmpty() select new { v1 = x.value, v2 = ((t == null) ? "null" : t.value.ToString()) }; //-----------------------------? foreach (var x in q12) { Console.WriteLine(x); } Console.WriteLine("Використання Join для составних ключів"); var q12_1 = from x in d1 join y in d1_for_distinct on new { x.id, x.name } equals new { y.id, y.name } into details from d in details select d; foreach (var x in q12_1) { Console.WriteLine(x); } //Дії над множинами Console.WriteLine("Distinct - неповторні значення"); var q13 = (from x in d1 select x.name).Distinct(); foreach (var x in q13) { Console.WriteLine(x); } Console.WriteLine("Distinct - повторні значення для обєктів"); var q14 = (from x in d1_for_distinct select x).Distinct(); foreach (var x in q14) { Console.WriteLine(x); } Console.WriteLine("Distinct - неповторні значення для обєктів"); var q15 = (from x in d1_for_distinct select x).Distinct(new ProjectEqualityComparer()); foreach (var x in q15) { Console.WriteLine(x); } Console.WriteLine("Union - объединение с исключением дубликатов"); int[] i1 = new int[] { 1, 2, 3, 4 }; int[] i1_1 = new int[] { 2, 3, 4, 1 }; int[] i2 = new int[] { 2, 3, 4, 5 }; foreach (var x in i1.Union(i2)) { Console.WriteLine(x); } Console.WriteLine("Union - объединение для объектов"); foreach (var x in d1.Union(d1_for_distinct)) { Console.WriteLine(x); } Console.WriteLine("Union - объединение для объектов с исключением дубликатов 1"); foreach (var x in d1.Union(d1_for_distinct, new ProjectEqualityComparer())) { Console.WriteLine(x); } Console.WriteLine("Union - объединение для объектов с исключением дубликатов 2"); foreach (var x in d1.Union(d1_for_distinct).Union(d2).Distinct(new ProjectEqualityComparer())) { Console.WriteLine(x); } Console.WriteLine("Concat - объединение без исключения дубликатов"); foreach (var x in i1.Concat(i2)) { Console.WriteLine(x); } Console.WriteLine("SequenceEqual - проверка совпадения элементов и порядка их следования"); Console.WriteLine(i1.SequenceEqual(i1)); Console.WriteLine(i1.SequenceEqual(i2)); Console.WriteLine("Intersect - пересечение множеств"); foreach (var x in i1.Intersect(i2)) { Console.WriteLine(x); } Console.WriteLine("Intersect - пересечение множеств для объектов"); foreach (var x in d1.Intersect(d1_for_distinct, new ProjectEqualityComparer())) { Console.WriteLine(x); } Console.WriteLine("Except - вычитание множеств"); foreach (var x in i1.Except(i2)) { Console.WriteLine(x); } Console.WriteLine("Except - вычитание множеств для объектов"); foreach (var x in d1.Except(d1_for_distinct, new ProjectEqualityComparer())) { Console.WriteLine(x); } Console.WriteLine("Функции агрегирования"); Console.WriteLine("Count - количество элементов"); Console.WriteLine(d1.Count()); Console.WriteLine("Count с условием"); Console.WriteLine(d1.Count(x => x.id > 1)); //Sum - сумма элементов //Min - минимальный элемент //Max - максимальный элемент //Average - среднее значение Console.WriteLine("Aggregate - агрегирование значений"); //(1, "Project2", 111, new DateTime(2015, 7, 20), new DateTime(2015, 8, 30), new List<string>() { "Person1", "Person2" }) var qa1 = d1.Aggregate(new Project(0, "", 0, new DateTime(), new DateTime(), new List <string>()), (total, next) => { if (next.id > 1) { total.id += next.id; } return(total); }); Console.WriteLine(qa1); Console.WriteLine("Группировка"); var q16 = from x in d1.Union(d2) group x by x.name into g select new { Key = g.Key, Values = g }; foreach (var x in q16) { Console.WriteLine(x.Key); foreach (var y in x.Values) { Console.WriteLine(" " + y); } } Console.WriteLine("Группировка с функциями агрегирования"); var q17 = from x in d1.Union(d2) group x by x.name into g select new { Key = g.Key, Values = g, cnt = g.Count(), cnt1 = g.Count(x => x.id > 1), sum = g.Sum(x => x.id), min = g.Min(x => x.id) }; foreach (var x in q17) { Console.WriteLine(x); foreach (var y in x.Values) { Console.WriteLine(" " + y); } } Console.WriteLine("Группировка - Any"); var q18 = from x in d1.Union(d2) group x by x.name into g where g.Any(x => x.id > 3) select new { Key = g.Key, Values = g }; foreach (var x in q18) { Console.WriteLine(x.Key); foreach (var y in x.Values) { Console.WriteLine(" " + y); } } Console.WriteLine("Группировка - All"); var q19 = from x in d1.Union(d2) group x by x.name into g where g.All(x => x.id > 1) select new { Key = g.Key, Values = g }; foreach (var x in q19) { Console.WriteLine(x.Key); foreach (var y in x.Values) { Console.WriteLine(" " + y); } } Console.WriteLine("Имитация связи много-ко-многим"); var lnk1 = from x in d1 join l in lnk on x.id equals l.d1 into temp from t1 in temp join y in d2 on t1.d2 equals y.id into temp2 from t2 in temp2 select new { id1 = x.id, id2 = t2.id }; foreach (var x in lnk1) { Console.WriteLine(x); } Console.WriteLine("Имитация связи много-ко-многим, проверка условия"); var lnk2 = from x in d1 join l in lnk on x.id equals l.d1 into temp from t1 in temp join y in d2 on t1.d2 equals y.id into temp2 where temp2.Any(t => t.value == 24) select x; foreach (var x in lnk2) { Console.WriteLine(x); } Console.WriteLine("Имитация связи много-ко-многим, использование let, проверка условия"); var lnk3 = from x in d1 let temp1 = from l in lnk where l.d1 == x.id select l from t1 in temp1 let temp2 = from y in d2 where y.id == t1.d2 && y.value == 24 select y where temp2.Count() > 0 //let temp2 = from y in d2 where y.id == t1.d2 // select y //where temp2.Any(t=>t.value == "24") select x; foreach (var x in lnk3) { Console.WriteLine(x); } Console.WriteLine("Deferred Execution - відкладення виконання запроса"); var e1 = from x in d1 select x; Console.WriteLine(e1.GetType().Name); foreach (var x in e1) { Console.WriteLine(x); } Console.WriteLine("При зміні джерела данних запрос видає нові результати"); d1.Add(new Project(333, "", 0, new DateTime(), new DateTime(), new List <string>())); foreach (var x in e1) { Console.WriteLine(x); } Console.WriteLine("Immediate Execution - негайне виконання запроса, результат преобразуется в список "); var e2 = (from x in d1 select x).ToList(); Console.WriteLine(e2.GetType().Name); foreach (var x in e2) { Console.WriteLine(x); } Console.WriteLine("Результат преобразуется в масив"); var e3 = (from x in d1 select x).ToArray(); Console.WriteLine(e3.GetType().Name); foreach (var x in e3) { Console.WriteLine(x); } Console.WriteLine("Результат преобразуется в Dictionary"); var e4 = (from x in d1 select x).ToDictionary(x => x.id); Console.WriteLine(e4.GetType().Name); foreach (var x in e4) { Console.WriteLine(x); } Console.WriteLine("Результат преобразуется в Lookup"); var e5 = (from x in d1_for_distinct select x).ToLookup(x => x.id); Console.WriteLine(e5.GetType().Name); foreach (var x in e5) { Console.WriteLine(x.Key); foreach (var y in x) { Console.WriteLine(" " + y); } } Console.WriteLine("Отримання першого елемента з вибірки"); var f1 = (from x in d2 select x).First(x => x.id == 2); Console.WriteLine(f1); Console.WriteLine("Отримання першого елемента чи значення по умолчанию"); var f2 = (from x in d2 select x).FirstOrDefault(x => x.id == 22); Console.WriteLine(f2 == null ? "null" : f2.ToString()); Console.WriteLine("Отримання елементів в заданій позиції"); var f3 = (from x in d2 select x).ElementAt(2); Console.WriteLine(f3); Console.WriteLine("Генрація послідовності"); Console.WriteLine("Range"); foreach (var x in Enumerable.Range(1, 5)) { Console.WriteLine(x); } Console.WriteLine("Repeat"); foreach (var x in Enumerable.Repeat <int>(10, 3)) { Console.WriteLine(x); } Console.ReadLine(); }
private List <ApiMetadata> ComputeNewReleases(List <ApiMetadata> allApis, List <string> tags) { var noChange = allApis.Where(api => tags.Contains($"{api.Id}-{api.Version}") || api.Version.EndsWith("00")).ToList(); return(allApis.Except(noChange).ToList()); }
public static List <Peak> deisotope_scan(IEnumerable <Peak> scan) { List <Envelope> ActiveEnvelopes = new List <Envelope>(); List <Envelope> InactiveEnvelopes = new List <Envelope>(); //List<Tuple<int, Tuple<double, double>>> output = new List<Tuple<int, Tuple<double, double>>>(); List <Peak> output = new List <Peak>(); foreach (Peak cPt in scan) { bool assigned = false; foreach (Envelope envlp in ActiveEnvelopes) { if (!envlp.is_active) { continue; } if (envlp.try_add_peak(cPt)) { assigned = true; break; } } if (!assigned) { bool recovered_cPt = false; IEnumerable <Envelope> new_inactive = ActiveEnvelopes.Where(x => !x.is_active); ActiveEnvelopes = ActiveEnvelopes.Except(new_inactive).ToList(); foreach (Envelope envlp in new_inactive) { // For each envelope that's now past its prime, either add it to the output // list or release its peaks and try to re-assign them. if (envlp.peaks.Count >= minimum_required_peaks) { InactiveEnvelopes.Add(envlp); } else { // Throw out the root peak, though. foreach (Peak peak in envlp.peaks.Skip(1)) { Envelope rec_envlp = new Envelope(peak); if (!recovered_cPt) { recovered_cPt = rec_envlp.try_add_peak(cPt); } ActiveEnvelopes.Add(rec_envlp); } } } if (!recovered_cPt) { Envelope new_envlp = new Envelope(cPt); ActiveEnvelopes.Add(new_envlp); } } } InactiveEnvelopes.AddRange(ActiveEnvelopes.Where(e => e.peaks.Count >= minimum_required_peaks)); foreach (Envelope envlp in InactiveEnvelopes) { //output.Add(new Tuple<int, Tuple<double, double>>(envlp.charge, envlp.peaks[0])); Peak mono_pk = envlp.peaks[0]; Peak chg_pk = new Peak(mono_pk.Item1, mono_pk.Item2, envlp.charge); output.Add(chg_pk); } //Envelope foo = InactiveEnvelopes.Aggregate((e1, e2) => e1.peakcount > e2.peakcount ? e1 : e2); //Debug.Assert(output.Count() == 0); return(output); }
public List <object> FindPositions(HttpRequestBase Request, string zipcode, string attributes, string things, string gender, string programid) { bool demomode = Request["demo"] != null && Request["demo"] == "1"; LeadCounterClient leadcounterclient = new LeadCounterClient(); List <LeadCounter> leadcounters = null; LeadCapClient leadcapclient = new LeadCapClient(); List <LeadCap> leadcaps = null; List <object> results = new List <object>(); bool validprogramcategoryid = false; if (programid != "" && !programid.StartsWith("c")) { validprogramcategoryid = true; } //ZipCodeClient zipclient = new ZipCodeClient(); //ZipCode zipobject = zipclient.GetByRowKey(zipcode); BlobJsonResourceManager blobmgr = new BlobJsonResourceManager(); string zipjson = blobmgr.GetJsonResource("skillcow", "zipcodes", zipcode); JObject jzip = null; if (zipjson != "") { jzip = JObject.Parse(zipjson); } GeoIndexNationalClient nclient = new GeoIndexNationalClient(); GeoIndexAddStateClient addstateclient = new GeoIndexAddStateClient(); GeoIndexAddZipClient addzipclient = new GeoIndexAddZipClient(); GeoIndexSubtractStateClient subtractstateclient = new GeoIndexSubtractStateClient(); GeoIndexSubtractZipClient subtractzipclient = new GeoIndexSubtractZipClient(); List <IGeoIndex> allresults = new List <IGeoIndex>(); List <IGeoIndex> subtractions = new List <IGeoIndex>(); //By program id if (validprogramcategoryid) { allresults.AddRange(nclient.GetAllByPartition(programid)); if (jzip != null) { //allresults.AddRange(addstateclient.GetAllByPartition(zipobject.StateCode + "-" + programid)); allresults.AddRange(addstateclient.GetAllByPartition(jzip["statecode"].ToString() + "-" + programid)); allresults.AddRange(addzipclient.GetAllByPartition(zipcode + "-" + programid)); } if (jzip != null) { //subtractions.AddRange(subtractstateclient.GetAllByPartition(zipobject.StateCode + "-" + programid)); subtractions.AddRange(subtractstateclient.GetAllByPartition(jzip["statecode"].ToString() + "-" + programid)); subtractions.AddRange(subtractzipclient.GetAllByPartition(zipcode + "-" + programid)); } } else { allresults.AddRange(nclient.GetAllByPartition("attr")); if (jzip != null) { //allresults.AddRange(addstateclient.GetAllByPartition(zipobject.StateCode)); allresults.AddRange(addstateclient.GetAllByPartition(jzip["statecode"].ToString())); allresults.AddRange(addzipclient.GetAllByPartition(zipcode)); } if (jzip != null) { //subtractions.AddRange(subtractstateclient.GetAllByPartition(zipobject.StateCode)); subtractions.AddRange(subtractstateclient.GetAllByPartition(jzip["statecode"].ToString())); subtractions.AddRange(subtractzipclient.GetAllByPartition(zipcode)); } } IEnumerable <IGeoIndex> difference = allresults.Except(subtractions, new CompareGeoIndexResults()); DirectEmployerClientClient clientclient = new DirectEmployerClientClient(); DirectEmployerClientCampusClient campusclient = new DirectEmployerClientCampusClient(); DirectEmployerClientCampusProgramClient programclient = new DirectEmployerClientCampusProgramClient(); JObject oattributes = null; JObject othings = null; long attributemask = 0; long importantthingsmask = 0; if (attributes != null && attributes != "") { oattributes = JObject.Parse(attributes); AttributeMaskCalculator amc = new AttributeMaskCalculator(); attributemask = amc.GetMask(oattributes); } if (things != null && things != "") { othings = JObject.Parse(things); ImportantThingsMaskCalculator itmc = new ImportantThingsMaskCalculator(); importantthingsmask = itmc.GetMask(othings); } foreach (IGeoIndex geoindex in allresults) { if (geoindex.AttributeMask != null && (geoindex.AttributeMask & attributemask) == attributemask) { DirectEmployerClientCampusProgram job = programclient.GetByRowKey(geoindex.RowKey); if (job.Status == "Live" || (demomode == true && job.Status == "Demo")) { bool filtered = false; //Apply other filters if (gender != "" && job.Gender != null && job.Gender != "") { if (job.Gender != gender) { filtered = true; } } if (!filtered) { DirectEmployerClientCampus campus = campusclient.GetByRowKey(geoindex.CampusRowKey); DirectEmployerClient employer = clientclient.GetByRowKey(geoindex.ClientRowKey); bool acceptingleads = false; if (employer.Status == "Live" || (demomode == true && employer.Status == "Demo")) { if (campus.Status == "Live" || (demomode == true && campus.Status == "Demo")) { //List<DirectEmployerClientCampusProgram> campusprograms = new List<DirectEmployerClientCampusProgram>(programclient.GetAllByClientId(employer.RowKey).Where(x => x.CampusRowKey == campus.RowKey)); if (leadcounters == null) { leadcounters = new List <LeadCounter>(leadcounterclient.GetAll()); leadcaps = new List <LeadCap>(leadcapclient.GetAll()); } LeadCap schoolcap = leadcaps.Find(x => x.RowKey == employer.RowKey); LeadCap programcap = leadcaps.Find(x => x.RowKey == job.RowKey); LeadCounter schoolcounter = leadcounters.Find(x => x.RowKey == employer.RowKey); LeadCounter programcounter = leadcounters.Find(x => x.RowKey == job.RowKey); acceptingleads = AcceptingLeads(schoolcap, programcap, schoolcounter, programcounter); if (acceptingleads) { results.Add(new { clienttype = employer.ClientType, clientid = employer.ClientId, clientsetid = employer.ClientId, logoclientid = employer.ClientId, program = programid, formid = employer.FormId, distance = 0, campustype = campus.CampusType, campuskey = campus.CampusId, programkey = geoindex.RowKey, clientrowkey = employer.RowKey, jobkey = job.RowKey, jobtitle = job.JobTitle, company = employer.Name.ToJSONSafeString(), companylogo = "https://chaindate.blob.core.windows.net/resources/employerlogos/" + employer.ClientType + employer.RowKey, city = campus.City, state = campus.State, date = job.PostedDateTime.ToString("ddd, dd MMM yyyy HH:mm:ss") + " GMT", snippet = job.Description, attributescore = oattributes != null ? job.GetAttributeScore(oattributes) : 0, importantthingsscore = othings != null ? job.GetImportantThingsScore(othings) : 0 }); } } } } } } } return(results); }
private Exp WhereConditional( ICollection <int> exceptIDs, String searchText, Guid responsibleID, int milestoneID, IEnumerable <String> tags, int contactID, DealMilestoneStatus?stageType, bool?contactAlsoIsParticipant) { var conditions = new List <Exp>(); var ids = new List <int>(); if (!String.IsNullOrEmpty(searchText)) { searchText = searchText.Trim(); var keywords = searchText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .ToArray(); if (keywords.Length > 0) { if (FullTextSearch.SupportModule(FullTextSearch.CRMDealsModule)) { ids = FullTextSearch.Search(searchText, FullTextSearch.CRMDealsModule) .GetIdentifiers() .Select(item => Convert.ToInt32(item.Split('_')[1])).Distinct().ToList(); if (ids.Count == 0) { return(null); } } else { conditions.Add(BuildLike(new[] { "tblDeal.title", "tblDeal.description" }, keywords)); } } } if (tags != null && tags.Any()) { ids = SearchByTags(EntityType.Opportunity, ids.ToArray(), tags); if (ids.Count == 0) { return(null); } } if (contactID > 0) { if (contactAlsoIsParticipant.HasValue && contactAlsoIsParticipant.Value) { var relativeContactsID = GetRelativeToEntity(contactID, EntityType.Opportunity, null).ToList(); if (relativeContactsID.Count == 0) { conditions.Add(Exp.Eq("tblDeal.contact_id", contactID)); } else { if (ids.Count > 0) { ids = relativeContactsID.Intersect(ids).ToList(); if (ids.Count == 0) { return(null); } } else { ids = relativeContactsID; } } } else { conditions.Add(Exp.Eq("tblDeal.contact_id", contactID)); } } if (0 < milestoneID && milestoneID < int.MaxValue) { conditions.Add(Exp.Eq("tblDeal.deal_milestone_id", milestoneID)); } if (responsibleID != Guid.Empty) { conditions.Add(Exp.Eq("tblDeal.responsible_id", responsibleID)); } if (stageType != null) { conditions.Add(Exp.Eq("tblDM.status", (int)stageType.Value)); } if (ids.Count > 0) { if (exceptIDs.Count > 0) { ids = ids.Except(exceptIDs).ToList(); if (ids.Count == 0) { return(null); } } conditions.Add(Exp.In("tblDeal.id", ids)); } else if (exceptIDs.Count > 0) { conditions.Add(!Exp.In("tblDeal.id", exceptIDs.ToArray())); } if (conditions.Count == 0) { return(null); } if (conditions.Count == 1) { return(conditions[0]); } return(conditions.Aggregate((i, j) => i & j)); }
public virtual async Task EmitAsync(IOpenModComponent component, object?sender, IEvent @event, EventExecutedCallback?callback = null) { if (component == null) { throw new ArgumentNullException(nameof(component)); } if (@event == null) { throw new ArgumentNullException(nameof(@event)); } if (!component.IsComponentAlive) { return; } var eventTypes = new List <Type>(); var currentType = @event.GetType(); while (currentType != null && typeof(IEvent).IsAssignableFrom(currentType)) { eventTypes.Add(currentType); currentType = currentType.BaseType; } eventTypes.AddRange(@event.GetType().GetInterfaces().Where(d => typeof(IEvent).IsAssignableFrom(d))); foreach (var eventType in eventTypes.Except(s_OmittedTypes)) { string eventName = GetEventName(eventType); m_Logger.LogTrace($"Emitting event: {eventName}"); var eventSubscriptions = m_EventSubscriptions .Where(c => (c.EventType != null && c.EventType == eventType) || (eventName.Equals(c.EventName, StringComparison.OrdinalIgnoreCase) && c.Owner.IsAlive && ((IOpenModComponent)c.Owner.Target).IsComponentAlive)) .ToList(); if (eventSubscriptions.Count == 0) { continue; } var comparer = new PriorityComparer(PriortyComparisonMode.LowestFirst); eventSubscriptions.Sort((a, b) => comparer.Compare( (Priority)a.EventListenerAttribute.Priority, (Priority)b.EventListenerAttribute.Priority) ); foreach (var group in eventSubscriptions.GroupBy(e => e.Scope)) { // Creates a new scope for the event. This is needed for scoped services so they share the same service instance // on each events. AutofacWebRequest makes it emulate a request for proper scopes. This tag is hardcoded by AutoFac. // Without this tag, services with the "Scope" lifetime will cause "DependencyResolutionException: // No scope with a Tag matching 'AutofacWebRequest' (...)". // // If you are here because of the following error: "System.ObjectDisposedException: Instances cannot // be resolved and nested lifetimes cannot be created from this LifetimeScope as it (or one of its parent scopes) // has already been disposed." It means you injected a service to an IEventHandler // that used the service *after* the event has finished (e.g. in a Task or by storing it somewhere). await using var newScope = group.Key.BeginLifetimeScopeEx("AutofacWebRequest"); foreach (var subscription in group) { var cancellableEvent = @event as ICancellableEvent; if (cancellableEvent != null && cancellableEvent.IsCancelled && !subscription.EventListenerAttribute.IgnoreCancelled) { continue; } var wasCancelled = false; if (cancellableEvent != null) { wasCancelled = cancellableEvent.IsCancelled; } var serviceProvider = newScope.Resolve <IServiceProvider>(); try { await subscription.Callback.Invoke(serviceProvider, sender, @event); // Ensure monitor event listeners can't cancel or uncancel events if (cancellableEvent != null && subscription.EventListenerAttribute.Priority == EventListenerPriority.Monitor) { if (cancellableEvent.IsCancelled != wasCancelled) { cancellableEvent.IsCancelled = wasCancelled; m_Logger.LogWarning( $"{((IOpenModComponent)@subscription.Owner.Target).OpenModComponentId} changed {@eventName} cancellation status with Monitor priority which is not permitted."); } } } catch (Exception ex) { m_Logger.LogError(ex, $"Exception occured during event {@eventName}"); } } } m_Logger.LogTrace($"{eventName}: Finished."); } callback?.Invoke(@event); }
public IEnumerable <Transaction> ReadTransactions(string fileName) { var lines = GetFileLines(fileName); string japaneseCrazyEncoding = "�w��̂Ȃ��ꍇ�A�P�ʂ͉~"; //TODO solve using BOM? if (lines[1][0].Equals(japaneseCrazyEncoding)) { lines = GetFileLines(fileName, "Shift-JIS"); } var marketPlaceSetting = GetMarketPlaceSetting(lines); int linesToSkip; try { linesToSkip = lines.ToList() .FindIndex(s => s.Intersect(marketPlaceSetting.DateTimeColumnNames).Any()); } catch (Exception ex) { throw new Exception("Could not find start of the data columns", ex); } var validLines = lines.Skip(linesToSkip).ToList(); var transactionsDict = new Dictionary <string, string[]>(); for (int columnIndex = 0; columnIndex < validLines[0].Length; ++columnIndex) { string columnNameKey = validLines[0][columnIndex].Trim(); //tolower? transactionsDict.Add(columnNameKey, validLines.Skip(1).Select(l => l[columnIndex]).ToArray()); } var transactions = new List <Transaction>(); for (int index = 0; index < transactionsDict.First().Value.Count(); index++) { string orderId = transactionsDict[marketPlaceSetting.OrderIdColumnName][index]; if (string.IsNullOrEmpty(orderId)) { orderId = "0000000000000000000"; } // PRICE double transactionTotalValue = 0; foreach (var compColumnName in marketPlaceSetting.ValueComponentsColumnName) { transactionTotalValue += double.Parse(transactionsDict[compColumnName][index], marketPlaceSetting.DateCultureInfo); } var transactionType = ParseTransactionType(transactionsDict[marketPlaceSetting.TransactionTypeColumnName][index], marketPlaceSetting); if (transactionType == TransactionTypes.Transfer || transactionType == TransactionTypes.ServiceFee) { // V priprade Service Fee a Transferu product price je total price transactionTotalValue = double.Parse(transactionsDict[marketPlaceSetting.TotalPriceColumnName][index], marketPlaceSetting.DateCultureInfo); } // DATE string dateComplete = String.Empty; foreach (var columnName in marketPlaceSetting.DateTimeColumnNames) { dateComplete += transactionsDict[columnName][index] + " "; } var date = ParseDate(dateComplete, marketPlaceSetting); var transaction = new Transaction() { Date = date, OrderId = orderId, TransactionValue = transactionTotalValue, Type = transactionType, MarketplaceId = marketPlaceSetting.MarketPlaceId, }; transactions.Add(transaction); } var orders = transactions.Where(t => t.Type.Equals(TransactionTypes.Order)).ToList(); if (orders.Any()) { var averageMarketplace = (int)orders.Average(t => t.MarketplaceId); foreach (var transaction in transactions.Except(orders)) { transaction.MarketplaceId = averageMarketplace; } } return(transactions); }
public List <int> Search(string query) { var parser = new SimpleQueryParser(query); var parsedQuery = parser.Parse(); if (parsedQuery.Length == 1) { return(_index.Find(parsedQuery[0])); } var i = 0; var result = new List <int>(); while (i < parsedQuery.Length) { if (i == 0) { var invertedFirstArg = parsedQuery[i] == "NOT"; i = invertedFirstArg ? ++i : i; if (invertedFirstArg) { result = _dataSource.GetAllIds().Except(_index.Find(parsedQuery[i++])).ToList(); } else { result = _index.Find(parsedQuery[i++]); } } if (parsedQuery[i] == "AND") { i++; if (parsedQuery[i] == "NOT") { result = result.Except(_index.Find(parsedQuery[++i])).ToList(); } else { result = result.Intersect(_index.Find(parsedQuery[i])).ToList(); } } else if (parsedQuery[i] == "OR") { i++; if (parsedQuery[i] == "NOT") { result = result.Concat(_dataSource.GetAllIds().Except(_index.Find(parsedQuery[++i]))).ToList(); } else { result = result.Concat(_index.Find(parsedQuery[i])).ToList(); } } i++; } return(result); }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; if (Sys.ContestID == 0 || Sys.ProcessingProblems) // 未设置比赛 或 已经在处理 { context.Response.Write(JsonConvert.SerializeObject(new Ret() { error = false, newSolved = new List <Database.ProblemSolved>() })); return; } Sys.ProcessingProblems = true; // 表示正在处理 var json = GetUrltoHtml("http://oj.ocrosoft.com/JudgeOnline/contestsolved_ajax.php?cid=" + Sys.ContestID); json = json.Replace("[\"", "[\"team_id\":\"").Replace(",\"", ",\"num\":\"").Replace("[\"", "{\"").Replace("\"]", "\"}"); var tmp = JsonConvert.DeserializeObject <List <Tmp> >(json); List <Database.ProblemSolved> problems = new List <Database.ProblemSolved>(); var ret = new Ret() { error = false, newSolved = null }; try { foreach (var each in tmp) { problems.Add(new Database.ProblemSolved() { team_id = each.team_id, num = int.Parse(each.num) }); } var problemsSolved = Database.GetsProblemSolved(); var newSolved = problems.Except(problemsSolved, new Database.ProblemSolved()).ToList(); // 差集 ret.newSolved = newSolved; foreach (var solved in newSolved) { if (!Database.AddProblemSaved(solved.team_id, solved.num)) { ret.error = true; ret.newSolved = null; } } if (newSolved.Count > 0) { Sys.Log("获取到" + newSolved.Count + "道新过题"); } } catch (MySql.Data.MySqlClient.MySqlException ex) { Sys.Error("processProblems.ashx: SQL Error.[" + ex.Message + "]"); ret.error = true; ret.newSolved = null; } catch (Exception ex) { Sys.Error("processProblems.ashx: Unexpected error.[" + ex.Message + "]"); ret.error = true; ret.newSolved = null; } Sys.ProcessingProblems = false; // 表示处理完成 context.Response.Write(JsonConvert.SerializeObject(ret)); }
private static void UpdateContentType(Web web, Microsoft.SharePoint.Client.ContentType existingContentType, ContentType templateContentType, TokenParser parser, PnPMonitoredScope scope) { var isDirty = false; if (existingContentType.Hidden != templateContentType.Hidden) { scope.LogPropertyUpdate("Hidden"); existingContentType.Hidden = templateContentType.Hidden; isDirty = true; } if (existingContentType.ReadOnly != templateContentType.ReadOnly) { scope.LogPropertyUpdate("ReadOnly"); existingContentType.ReadOnly = templateContentType.ReadOnly; isDirty = true; } if (existingContentType.Sealed != templateContentType.Sealed) { scope.LogPropertyUpdate("Sealed"); existingContentType.Sealed = templateContentType.Sealed; isDirty = true; } if (templateContentType.Description != null && existingContentType.Description != parser.ParseString(templateContentType.Description)) { scope.LogPropertyUpdate("Description"); existingContentType.Description = parser.ParseString(templateContentType.Description); isDirty = true; } if (templateContentType.DocumentTemplate != null && existingContentType.DocumentTemplate != parser.ParseString(templateContentType.DocumentTemplate)) { scope.LogPropertyUpdate("DocumentTemplate"); existingContentType.DocumentTemplate = parser.ParseString(templateContentType.DocumentTemplate); isDirty = true; } if (existingContentType.Name != parser.ParseString(templateContentType.Name)) { scope.LogPropertyUpdate("Name"); existingContentType.Name = parser.ParseString(templateContentType.Name); isDirty = true; // CT is being renamed, add an extra token to the tokenparser parser.AddToken(new ContentTypeIdToken(web, existingContentType.Name, existingContentType.StringId)); } if (templateContentType.Group != null && existingContentType.Group != parser.ParseString(templateContentType.Group)) { scope.LogPropertyUpdate("Group"); existingContentType.Group = parser.ParseString(templateContentType.Group); isDirty = true; } if (templateContentType.DisplayFormUrl != null && existingContentType.DisplayFormUrl != parser.ParseString(templateContentType.DisplayFormUrl)) { scope.LogPropertyUpdate("DisplayFormUrl"); existingContentType.DisplayFormUrl = parser.ParseString(templateContentType.DisplayFormUrl); isDirty = true; } if (templateContentType.EditFormUrl != null && existingContentType.EditFormUrl != parser.ParseString(templateContentType.EditFormUrl)) { scope.LogPropertyUpdate("EditFormUrl"); existingContentType.EditFormUrl = parser.ParseString(templateContentType.EditFormUrl); isDirty = true; } if (templateContentType.NewFormUrl != null && existingContentType.NewFormUrl != parser.ParseString(templateContentType.NewFormUrl)) { scope.LogPropertyUpdate("NewFormUrl"); existingContentType.NewFormUrl = parser.ParseString(templateContentType.NewFormUrl); isDirty = true; } #if !ONPREMISES if (templateContentType.Name.ContainsResourceToken()) { existingContentType.NameResource.SetUserResourceValue(templateContentType.Name, parser); isDirty = true; } if (templateContentType.Description.ContainsResourceToken()) { existingContentType.DescriptionResource.SetUserResourceValue(templateContentType.Description, parser); isDirty = true; } #endif if (isDirty) { existingContentType.Update(true); web.Context.ExecuteQueryRetry(); } // Delta handling existingContentType.EnsureProperty(c => c.FieldLinks); List <Guid> targetIds = existingContentType.FieldLinks.AsEnumerable().Select(c1 => c1.Id).ToList(); List <Guid> sourceIds = templateContentType.FieldRefs.Select(c1 => c1.Id).ToList(); var fieldsNotPresentInTarget = sourceIds.Except(targetIds).ToArray(); if (fieldsNotPresentInTarget.Any()) { foreach (var fieldId in fieldsNotPresentInTarget) { var fieldRef = templateContentType.FieldRefs.Find(fr => fr.Id == fieldId); var field = web.Fields.GetById(fieldId); scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ContentTypes_Adding_field__0__to_content_type, fieldId); web.AddFieldToContentType(existingContentType, field, fieldRef.Required, fieldRef.Hidden); } } isDirty = false; foreach (var fieldId in targetIds.Intersect(sourceIds)) { var fieldLink = existingContentType.FieldLinks.FirstOrDefault(fl => fl.Id == fieldId); var fieldRef = templateContentType.FieldRefs.Find(fr => fr.Id == fieldId); if (fieldRef != null) { scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ContentTypes_Field__0__exists_in_content_type, fieldId); if (fieldLink.Required != fieldRef.Required) { scope.LogPropertyUpdate("Required"); fieldLink.Required = fieldRef.Required; isDirty = true; } if (fieldLink.Hidden != fieldRef.Hidden) { scope.LogPropertyUpdate("Hidden"); fieldLink.Hidden = fieldRef.Hidden; isDirty = true; } } } // The new CT is a DocumentSet, and the target should be, as well if (templateContentType.DocumentSetTemplate != null) { if (!Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate.IsChildOfDocumentSetContentType(web.Context, existingContentType).Value) { scope.LogError(CoreResources.Provisioning_ObjectHandlers_ContentTypes_InvalidDocumentSet_Update_Request, existingContentType.Id, existingContentType.Name); } else { Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate templateToUpdate = Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate.GetDocumentSetTemplate(web.Context, existingContentType); // TODO: Implement Delta Handling scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ContentTypes_DocumentSet_DeltaHandling_OnHold, existingContentType.Id, existingContentType.Name); } } if (isDirty) { existingContentType.Update(true); web.Context.ExecuteQueryRetry(); } }
static public void CornerRecordData() { var doc = Application.DocumentManager.MdiActiveDocument; var ed = doc.Editor; try { var acDB = doc.Database; using (var trans = acDB.TransactionManager.StartTransaction()) { DBDictionary layoutPages = (DBDictionary)trans.GetObject(acDB.LayoutDictionaryId, OpenMode.ForRead); // Handle Corner Record meta data dictionary extracted from Properties and Content Dictionary <String, object> cornerRecordForms = new Dictionary <string, object>(); CivilDB.CogoPointCollection cogoPointsColl = CivilDB.CogoPointCollection.GetCogoPoints(doc.Database); var cogoPointCollected = CogoPointJson.geolocationCapture(cogoPointsColl); List <string> layoutNamesList = new List <string>(); foreach (DBDictionaryEntry layoutPage in layoutPages) { var crFormItems = layoutPage.Value.GetObject(OpenMode.ForRead) as Layout; var isModelSpace = crFormItems.ModelType; ObjectIdCollection textObjCollection = new ObjectIdCollection(); // Formatted Dictionary to create JSON output Dictionary <string, object> textObjResults = new Dictionary <string, object>(); if (isModelSpace != true) { BlockTableRecord blkTblRec = trans.GetObject(crFormItems.BlockTableRecordId, OpenMode.ForRead) as BlockTableRecord; layoutNamesList.Add(crFormItems.LayoutName.Trim().ToString().ToLower().Replace(" ", "")); foreach (ObjectId btrId in blkTblRec) { if (btrId.ObjectClass.DxfName.Contains("TEXT") || btrId.ObjectClass.DxfName.Contains("MTEXT")) { textObjCollection.Add(btrId); } } // List of the Dictionary txtProps List <object> crFormElements = new List <object>(); List <object> crFormInputs = new List <object>(); List <ObjectId> crFormInputId = new List <ObjectId>(); foreach (ObjectId txtItem in textObjCollection) { // Dictionary to collect Contents of the Corner Records Sheet Dictionary <string, object> txtProps = new Dictionary <string, object>(); var txtItemName = trans.GetObject(txtItem, OpenMode.ForRead) as Entity; if (txtItemName.Layer == "-SHEET") { if (txtItem.ObjectClass.DxfName == "MTEXT") { var mtextValues = trans.GetObject(txtItem, OpenMode.ForRead) as MText; //txtProps.Add("Class Type", "MTEXT"); //txtProps.Add("Layer Name", mtextValues.Layer); txtProps.Add("Content", mtextValues.Text); //txtProps.Add("X", mtextValues.Location.X); //txtProps.Add("Y", mtextValues.Location.Y); crFormElements.Add(txtProps); } else if (txtItem.ObjectClass.DxfName == "TEXT") { //Capture Brief Legal Description here var textValues = trans.GetObject(txtItem, OpenMode.ForRead) as DBText; //txtProps.Add("Class Type", "TEXT"); //txtProps.Add("Layer Name", textValues.Layer); txtProps.Add("Content", textValues.TextString); //txtProps.Add("X", textValues.Position.X); //txtProps.Add("Y", textValues.Position.Y); crFormElements.Add(txtProps); } } else if (txtItemName.Layer == "$--SHT-ANNO") { if (txtItem.ObjectClass.DxfName == "MTEXT") { var mtextValues = trans.GetObject(txtItem, OpenMode.ForRead) as MText; //txtProps.Add("Class Type", "MTEXT"); //txtProps.Add("Layer Name", mtextValues.Layer); txtProps.Add("Content", mtextValues.Text); //txtProps.Add("X", mtextValues.Location.X); //txtProps.Add("Y", mtextValues.Location.Y); crFormInputs.Add(txtProps); crFormInputId.Add(txtItem); } else if (txtItem.ObjectClass.DxfName == "TEXT") { var textValues = trans.GetObject(txtItem, OpenMode.ForRead) as DBText; //txtProps.Add("Class Type", "TEXT"); //txtProps.Add("Layer Name", textValues.Layer); txtProps.Add("Content", textValues.TextString); //txtProps.Add("X", textValues.Position.X); //txtProps.Add("Y", textValues.Position.Y); crFormInputs.Add(txtProps); crFormInputId.Add(txtItem); } } } var briefLegalCollected = BriefLegalDescription.briefLegalCapture(textObjCollection, crFormInputId); textObjResults.Add("Legal_Description_c", briefLegalCollected); //textObjResults.Add("Form Inputs", crFormInputs); //textObjResults.Add("Form Elements", crFormElements); cornerRecordForms.Add(crFormItems.LayoutName.Trim().ToString().ToLower().Replace(" ", ""), textObjResults); } } // Checks to see whether the points from the cogo point collection exist within // the layout by searching for the correct collection key and layout name List <string> cogoPointCollectedCheck = cogoPointCollected.Keys.ToList(); List <bool> boolCheckResults = new List <bool>(); IEnumerable <string> cogoPointNameCheck = layoutNamesList.Except(cogoPointCollectedCheck); List <string> cogoPointNameCheckResults = cogoPointNameCheck.ToList(); var layoutNameChecker = new Regex("^(\\s*cr\\s*\\d\\d*)$"); if (!cogoPointNameCheckResults.Where(f => layoutNameChecker.IsMatch(f)).ToList().Any()) { boolCheckResults.Add(true); } else { foreach (string cogoPointNameResultItem in cogoPointNameCheckResults) { Match layoutNameMatch = Regex.Match(cogoPointNameResultItem, "^(\\s*cr\\s*\\d\\d*)$", RegexOptions.IgnoreCase); if (layoutNameMatch.Success) { string layoutNameX = layoutNameMatch.Value; ed.WriteMessage("\nLayout Named {0} does not have an associated cogo point", layoutNameX); } } boolCheckResults.Add(false); } IEnumerable <string> layoutNameCheck = cogoPointCollectedCheck.Except(layoutNamesList); List <string> layoutNameCheckResults = layoutNameCheck.ToList(); var cogoNameChecker = new Regex("^(\\s*cr\\s*\\d\\d*)$"); // If the layout name has any value other than CR == PASS // If CR point exists and does not match then throw an error for user to fix if (!layoutNameCheckResults.Where(f => cogoNameChecker.IsMatch(f)).ToList().Any()) { boolCheckResults.Add(true); } else // Found a CR point that DID NOT match a layout name { foreach (string layoutNameCheckResultItem in layoutNameCheckResults) { Match cogoNameMatch = Regex.Match(layoutNameCheckResultItem, "^(\\s*cr\\s*\\d\\d*)$", RegexOptions.IgnoreCase); if (cogoNameMatch.Success) { string cogoNameX = cogoNameMatch.Value; ed.WriteMessage("\nCorner Record point named {0} does not have an associated Layout", cogoNameX); } } boolCheckResults.Add(false); } // Output JSON file to BIN folder // IF there are two true booleans in the list then add the data to the corresponding keys (cr1 => cr1) if ((boolCheckResults.Count(v => v == true)) == 2) { foreach (string cornerRecordFormKey in cornerRecordForms.Keys) { if (cogoPointCollected.ContainsKey(cornerRecordFormKey)) { //ed.WriteMessage("THIS SHIT FINALLY WORKS FOR {0}", cornerRecordFormKey); var cogoFinal = (Dictionary <string, object>)cornerRecordForms[cornerRecordFormKey]; var cogoFinalType = ((Dictionary <string, object>)cogoPointCollected[cornerRecordFormKey]) ["Corner_Type_c"]; var cogoFinalLong = ((Dictionary <string, object>)cogoPointCollected[cornerRecordFormKey]) ["Geolocation_Longitude_s"]; var cogoFinalLat = ((Dictionary <string, object>)cogoPointCollected[cornerRecordFormKey]) ["Geolocation_Latitude_s"]; cogoFinal.Add("Corner_Type_c", cogoFinalType); cogoFinal.Add("Geolocation_Longitude_s", cogoFinalLong); cogoFinal.Add("Geolocation_Latitude_s", cogoFinalLat); } } using (var writer = File.CreateText("CornerRecordForms.json")) { string strResultJson = JsonConvert.SerializeObject(cornerRecordForms, Formatting.Indented); writer.WriteLine(strResultJson); } } trans.Commit(); } } catch (System.Exception ex) { ed.WriteMessage("Error: {0}", ex); } }